/*
ADOBE CONFIDENTIAL
Copyright 2010 Adobe Systems Incorporated
All Rights Reserved.

NOTICE:  All information contained herein is, and remains the property of Adobe Systems Incorporated and its suppliers,
if any.  The intellectual and technical concepts contained herein are proprietary to Adobe Systems Incorporated and its
suppliers and may be covered by U.S. and Foreign Patents, patents in process, and are protected by trade secret or 
copyright law. Dissemination of this information or reproduction of this material is strictly forbidden unless prior 
written permission is obtained from Adobe Systems Incorporated.
*/

//json==============================================================================
function sjLoadImageSet(inImage,inVar,inCallback) {
 sjGetResponse(
  'req=imageset,json',
  inImage,
  function(inArg) {
   if (inArg != null) {
    var imageList = inArg.IMAGE_SET.split(',');
    for (var i = 0; i < imageList.length; i ++) {
         inVar[i] = new Object();
		 var delim = imageList[i].indexOf(";");
		 if (delim > 0){
			inVar[i] = encodeURI(imageList[i].substring(0,delim));
		 }else{
			inVar[i] = encodeURI(imageList[i]);
		 }
    }
     if (inCallback !=null ){
    inCallback();
     }
   }
  },
  function(inArg) {
   //alert('failed loading map for image [' + inImage + ']: ' + inArg.message);
  }
 );
}

function sjLoadConfig(inURL,inParams,inCallback) {
 sjGetResponse(
  'req=userdata,json',
  inURL,
  function(inArg) {
   if (inArg != null) {
		for (var i in inArg) {
		  inParams[i] = inArg[i];
		}
     if (inCallback !=null ){
	inCallback(inArg);
     }
   }
  },
  function(inArg) {
   //alert('failed loading config [' + inImageSet + ']: ' + inArg.message);
  }
 );
}

function sjLoadSet(inServerURL,inImageSet,inModifier,inList,inCallback) {
	var serverURL = inServerURL;
	var companyName = inImageSet;
	var imgSetName = inImageSet;
	var modifier = inModifier;
	var useMod = false; 
	var aIdx = companyName.indexOf('?');
	if (aIdx != -1) {
		if (modifier == null) {
			modifier = "&"+companyName.substring(aIdx+1);
		}else{
			modifier += "&"+companyName.substring(aIdx+1);
		}
		companyName = companyName.substring(0, aIdx);
		imgSetName = companyName;
	}
	var cIdx = companyName.indexOf(':');
	if (cIdx != -1) {
		companyName = companyName.substring(0, cIdx);
		useMod = true;
	}
	var scIdx = companyName.indexOf(';');
	if (scIdx != -1) {
		companyName = companyName.substring(0, scIdx);
		useMod = true;
	}
	var cmIdx = companyName.indexOf(',');
	if (cmIdx != -1) {
		companyName = companyName.substring(0, cmIdx);
		useMod = true;
	}
	var comIdx = companyName.indexOf('/');
	if (comIdx == -1) {
		companyName = companyName;
	} else {
		companyName = companyName.substring(0, comIdx);
	}
	companyName = encodeURI(companyName);
	modifier = encodeURI(modifier);
	imgSetName = encodeURI(imgSetName);
	var req = "";	
	var name = "";
	var modStr = (modifier == "") ? "" : "&layer=comp&"+modifier;

	  if (useMod == true){
		req = 'req=set,json,UTF-8'+"&imageSet="+imgSetName+modStr;
		name = companyName;
	  }else{
		req = 'req=set,json,UTF-8'+modStr;
		name = imgSetName;
	  }

	  sjGetResponse(
		  req,
		  serverURL+name,
		  function(inArg) {
		   if (inArg != null) {
			 parseSetResponse(inArg,null,inList);
			 if (inCallback !=null ){
				inCallback(inArg);
			 }
		   }
		  },
		  function(inArg) {
		   //alert('failed loading image set [' + inImageSet + ']: ' + inArg.message);
		   return false;
		  }
	 );
}

function parseSetResponse(o,parent,imglist) {
	var ret = null;
	if (typeof(o)=="string") {
		switch(parent){
			case "rect":
				var tempAr = o.split(","); 
				ret = {x:parseInt(tempAr[0]),y:parseInt(tempAr[1]),width:parseInt(tempAr[2]),height:parseInt(tempAr[3])};
				break;
			case "number":
				ret = parseInt(o); break;
			case "dx":
				ret = parseInt(o); break;
			case "dy":
				ret = parseInt(o); break;
			default:
				ret = o;
		}
		return ret;
	} 
	if (typeof(o)=="number") {
		ret = o;
		return ret;
	}
	if (typeof(o)=="object") {
		if (typeof(o.length)=="number" ) {
			ret = new Array();
			for (var i=0; i<o.length;i++) {
				ret[i] = parseSetResponse(o[i],parent,imglist);
				if ((parent == "item") && (typeof(ret[i].image) != "undefined")){
					imglist.push(ret[i]);
				}
			}
			return ret;
		} else {
			ret = new Object();
			var syn = null;
			for (elm in o) {
				switch(elm){
					case "set":
						syn = "set"; break;
					case "item":
						syn = "item"; break;
					case "targets":
						syn = "targetList"; break;
					case "s":
						syn = "swatch"; break;
					case "i":
						syn = "image"; break;
					case "v":
						syn = "video"; break;
					case "map":
						syn = "map"; break;
					default:
						syn = elm;
				}
				ret[syn] = parseSetResponse(o[elm],elm,imglist);
				if ((syn == "item") && (typeof(ret[syn].image) != "undefined")){
					imglist.push(ret[syn]);
				}
			}
			return ret;
		}
	}
}

function getCombinedImageName(inImageList,inOrder) {
     var combinedImageName;
     if (inOrder) {
         combinedImageName = inImageList[0] + '?layer=0&extendN=' +(inImageList.length - 1) + ',0,0,0&originN=' + (1 / inImageList.length - 0.5) + ',-0.5';
         for (var i = 1; i < inImageList.length; i ++) {
             combinedImageName += '&layer=' + i + '&src=' + inImageList[i] + '&originN=' + (i - inImageList.length + 1.5) + ',-0.5&sizeN=' + 1 / inImageList.length + ',1';
         }
     } else {
         combinedImageName = inImageList[0] + '?layer=0&extendN=0,0,' + (inImageList.length - 1) + ',0&originN=' + (1 / inImageList.length - 0.5) + ',-0.5';
         for (var i = 1; i < inImageList.length; i ++) {
             combinedImageName += '&layer=' + i + '&src=' + inImageList[i] + '&originN=' + (0.5 - i) + ',-0.5&sizeN=' + 1 / inImageList.length + ',1';
         }
     }
     return combinedImageName;
};
//end json==========================================================================

Number.prototype.NaN0=function() { return (isNaN(this) || !isFinite(this)) ? 0 : this; }

function sjScreenSize() {
   var w = (window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth));
   var h = (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight));
   return {w:w, h:h};
}

function sjFindPos(obj){
var x = 0;
var y = 0;
var dx = 0;
var dy = 0; 
	while( obj != null ){
		if( window.getComputedStyle ) {
		  dx = window.getComputedStyle(obj,null).borderLeftWidth;
		  dy = window.getComputedStyle(obj,null).borderTopWidth;
		} else if( obj.currentStyle ) {
		  dx = obj.currentStyle.borderLeftWidth;
		  dy = obj.currentStyle.borderTopWidth;
		}
		x += obj.offsetLeft + parseInt(dx).NaN0();
		y += obj.offsetTop +parseInt(dy).NaN0();
		obj = obj.offsetParent ;
	}
	return [x,y];
}

function sjGetDim(obj){
var w = 0;
var h = 0;
	if( window.getComputedStyle ) {
	  w = window.getComputedStyle(obj,null).width;
	  h = window.getComputedStyle(obj,null).height;
	} else if( obj.currentStyle ) {
	  w = obj.currentStyle.width;
	  h = obj.currentStyle.height;
	}
	return [w,h];
}

function sjGetStyle(obj){
var style = null;
	if( window.getComputedStyle ) {
	  style = window.getComputedStyle(obj,null);
	} else if( obj.currentStyle ) {
	  style = obj.currentStyle;
	}
	return style;
}

function sjSetOpacity(inObj,inOpacity) {
    if(inOpacity < 0) inOpacity = 0; 
	if(inOpacity > 99) inOpacity = 99.999999;
	inObj.style.opacity = (inOpacity / 100);
	inObj.style.MozOpacity = (inOpacity / 100);
	inObj.style.KhtmlOpacity = (inOpacity / 100);
	var arVersion = navigator.appVersion.split("MSIE")
	var version = parseFloat(arVersion[1])
    if ((version >= 5.5) && (version <=8) && (document.body.filters)){
		if(inOpacity > 99){
			inOpacity = 100;
			inObj.style.opacity = (inOpacity / 100);
		}
		if (inObj.filters){
			if (inObj.filters.length>0){
				if (inObj.filters["DXImageTransform.Microsoft.Alpha"]){
					inObj.filters.item("DXImageTransform.Microsoft.Alpha").Opacity = inOpacity;
				}else{
					inObj.style.filter += " progid:DXImageTransform.Microsoft.Alpha(opacity="+inOpacity+")"; 
				}	
			}else{
				inObj.style.filter = " progid:DXImageTransform.Microsoft.Alpha(opacity="+inOpacity+")"; 
			}
		}
	}
	inObj.opacity = inObj.style.opacity;
	return inObj.opacity;
}

function sjAnimation(inObj,properties,begin,finish,duration,timeFunction,callback){
	inObj.animationStartTime = new Date().getTime();
	if(typeof inObj._animationId != 'undefined'){
		clearTimeout(inObj._animationId);
		inObj._animationId = null;
	}
	animationStep(inObj,properties,begin,finish,duration,timeFunction,callback);
}

function animationStep(inObj,properties,begin,finish,duration,timeFunction,callback){
	var dt = new Date().getTime() - inObj.animationStartTime;
	var currentStatus = dt / (duration+1);
	var suff = "";
	var diff = (finish - begin) * timeFunction(currentStatus) + begin;
	if (currentStatus < 1){
		diff = (finish - begin) * timeFunction(currentStatus) + begin;
	}else{
		diff = finish;
	}
	switch(properties){
		case "left":
			suff = "px";
			break;
		case "top":
			suff = "px";
			break;
		case "height":
			suff = "px";
			break;
		case "width":
			suff = "px";
			break;
		default:
			suff = "";
	}
	inObj.style[properties] = diff + suff;
	if (properties == "opacity"){
		sjSetOpacity(inObj,diff + suff);
	}
	if (currentStatus < 1){
			inObj._animationId = setTimeout(function(){
										animationStep(inObj,properties,begin,finish,duration,timeFunction,callback);
									}, 20);
	}else{
		if (callback){
			callback();
		}
	}
}

function linear(p) {
	return p;
}
function quad(p) {
	return Math.pow(p, 2);
}

function root(p) {
	return Math.pow(p, 0.5);
}

function sine(currentStatus) {  
    return 1 - Math.sin((1 - currentStatus) * Math.PI/2);  
} 

function fixEvent(e){
	if (!e) var e = window.event;
	var target = null;
	if (e.target) {
		target = (e.target.nodeType == 3) ? e.target.parentNode : e.target;
	} else {
		target = e.srcElement;
	}
	//e.target = target;
	if (e.touches && e.touches.length) { 	// iPhone
		e.posx = e.touches[0].clientX;
		e.posy = e.touches[0].clientY;
	} else if(window.event){
		e.posx=e.clientX;
		e.posy=e.clientY;
		if(document.body&&(document.body.scrollLeft||document.body.scrollTop)){
			e.posx=e.clientX+document.body.scrollLeft
			e.posy=e.clientY+document.body.scrollTop;
		}else if(document.documentElement&&(document.documentElement.scrollLeft||document.documentElement.scrollTop)){
				e.posx=e.clientX+document.documentElement.scrollLeft
				e.posy=e.clientY+document.documentElement.scrollTop;
		}
	}else{
		e.posx=e.clientX;
		e.posy=e.clientY;
		e.posx+=window.pageXOffset
		e.posy+=window.pageYOffset;
	}
	return e;
}

//////////////////////////////////////////////////////////////////
/*
Xc = (L1*X'1 + L2*X'2 + ... + LN*X'N) / P 
Yc = (L1*Y'1 + L2*Y'2 + ... + LN*Y'N) / P
(X'i, Y'i) - center of i-segment.
Li - length of i-segment
P - perimetr of poly (P = L1 + ... + LN)
*/

// return length of segment (x1,y1)-(x2,y2)
function sjSegmentLength(x1,y1,x2,y2){
	return Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
}

function coordsToPoints(inCoords){
    var points = new Array(); 
	for (var p = 0; p < inCoords.length; p += 2) {
      var point = new Object();
	  point.x = parseInt(inCoords[p]);
	  point.y = parseInt(inCoords[p + 1]);
	  points.push(point);
	}
	return points;
}

function sjPolyArea(inPointArray) {
   var p1 = null; 
   var p2 = null;
   var area = 0;
   var j = inPointArray.length-1;

   for (var i=0; i < inPointArray.length; j=i++) {
      p1 = inPointArray[i]; 
	  p2 = inPointArray[j];
      area += p1.x*p2.y;
      area -= p1.y*p2.x;
   }
   area /= 2;
   return area;
};

function sjPolyCentroid(inPointArray) {
   var x=0, y=0, f, j=inPointArray.length-1;
   var p1 = null; 
   var p2 = null;

   for (var i=0; i < inPointArray.length; j=i++) {
      p1 = inPointArray[i]; 
	  p2 = inPointArray[j];
      f = p1.x*p2.y - p2.x*p1.y;
      x += (p1.x+p2.x)*f;
      y += (p1.y+p2.y)*f;
   }

   f = sjPolyArea(inPointArray)*6;
   return {x: x/f,y:y/f};
};

function sjGetMapCentroidList(inMapName){
var centroidList = [];	
	if(inMapName){
	  if (document.all) {
		var map = document.all[inMapName];
		if (map){
			var areas = map.all.tags('AREA');
		}
	  } else if (document.getElementsByName) {
		var map = document.getElementsByName(inMapName)[0];
		if (map){
			var areas = map.getElementsByTagName('AREA');
		}
	  }

	  if (areas) {
		for (var a = 0; a < areas.length; a++) {
		  var coords = areas[a].getAttribute('coords').split(/\s*,\s*/);
		  if (areas[a].getAttribute('shape').toLowerCase() == 'rect'){
			centroidList[a] = {
								xc:Math.round(parseInt(coords[0])+parseInt(coords[2])/2),
								yc:Math.round(parseInt(coords[1])+parseInt(coords[3])/2),
								href:(areas[a].getAttribute('href'))?areas[a].getAttribute('href'):null,
								target:(areas[a].getAttribute('target'))?areas[a].getAttribute('target'):null,
								alt:(areas[a].getAttribute('alt'))?areas[a].getAttribute('alt'):null,
								rollover_key:(areas[a].getAttribute('rollover_key'))?areas[a].getAttribute('rollover_key'):null
							};
		  } else if (areas[a].getAttribute('shape').toLowerCase() == 'circle') {
			centroidList[a] = {
								xc:parseInt(coords[0]),
								yc:parseInt(coords[1]),
								href:(areas[a].getAttribute('href'))?areas[a].getAttribute('href'):null,
								target:(areas[a].getAttribute('target'))?areas[a].getAttribute('target'):null,
								alt:(areas[a].getAttribute('alt'))?areas[a].getAttribute('alt'):null,
								rollover_key:(areas[a].getAttribute('rollover_key'))?areas[a].getAttribute('rollover_key'):null
							};
		  } else if (areas[a].getAttribute('shape').toLowerCase() == 'poly') {
			var pts = coordsToPoints(coords);
			var cc = sjPolyCentroid(pts);
			centroidList[a] = {
								xc:Math.round(cc.x),
								yc:Math.round(cc.y),
								href:(areas[a].getAttribute('href'))?areas[a].getAttribute('href'):null,
								target:(areas[a].getAttribute('target'))?areas[a].getAttribute('target'):null,
								alt:(areas[a].getAttribute('alt'))?areas[a].getAttribute('alt'):null,
								rollover_key:(areas[a].getAttribute('rollover_key'))?areas[a].getAttribute('rollover_key'):null
							};
		  }
		}
	  }
	}
  return centroidList;
}

///////////////////////////////////////////////////////////
SjZoom.prototype.initTouchHandlers = function(inWithMap){
	var obj = this;
	var tapCounerTimer = null; 
	var moving = {};
	var touches = [];
	var currGScl = 1;
//////////////////////////
	this.withMap = inWithMap;
	this.createIconsPlate();
	if (this.withMap == true){
		this.mapIconsVisible = true;
	}else{
		this.mapIconsVisible = false;
	}

function initMouse(o,evt){
	if (evt.preventDefault) evt.preventDefault();
	obj.storeImagesXY();
	obj.ex = evt.posx;
	obj.ey = evt.posy;
	obj.startDrag=false;
	if (evt.touches.length == 1) {	
		obj.startDrag=true;
	}else{
		touches = evt.touches;
	}
	obj.moving=false;
//	sjSetCursor('hand');
	obj.mapImage.addEventHandler('touchmove',moveMouse);
	obj.mapImage.addEventHandler('touchend',finishMouse);
	obj.mapImage.addEventHandler('touchcancel',finishMouse);
	return false;
}

function moveMouse(o,evt){
	if (evt.preventDefault) evt.preventDefault();
	if (evt.touches.length == 1) {
		if (obj.startDrag){
			if (obj._animeid){
				clearTimeout(obj._animeid);
				obj._animeid = null;
			}
			obj.moving=true;
			var diffX = evt.posx - obj.ex;
			var diffY = evt.posy - obj.ey;
			obj.setPosition(obj.backImage,obj.bx + diffX,obj.by + diffY,obj.currentScl);
			var x=obj.currentX-obj.bx+obj.fx;
			var y=obj.currentY-obj.by+obj.fy;
			obj.foreImage.toXY(x,y);
			obj.iconsPlate.style.visibility = "hidden";
		}
	}else{
		touches = evt.touches;
	}
	return false;
}

function finishMouse(o,evt){
	if (evt.preventDefault) evt.preventDefault();
	if ((evt.touches.length == 0) && (obj.startDrag)) {
		var x =sjGetPageCoords (sjGetElement(obj._elementId)).x;
		var y =sjGetPageCoords (sjGetElement(obj._elementId)).y;
		var newx=evt.posx-obj.currentX-x;
		var newy=evt.posy-obj.currentY-y;
		if(!obj.moving){
			if(tapCounerTimer){
				clearTimeout(tapCounerTimer);
				tapCounerTimer = null;
				// double tap code
				obj.fireEvent('doubleTap','x',newx,'y',newy);
				obj.iconsPlate.style.visibility = "hidden";
			} else {
				obj.evt = evt;
				tapCounerTimer = setTimeout(function(){
					tapCounerTimer = null;
					// single tap code
					if (obj.evt.touches.length == 0) {
						if ((obj.startDrag) && (!obj.moving)){
							if ((obj.clickToZoom) && (obj.enableZoom)){
								obj.fireEvent('singleTap');
							}
						}
					}
					obj.startDrag=false;
				},300);
			}
		}else if(obj.moving){
			obj.moving=false;
			clearTimeout(tapCounerTimer);
			tapCounerTimer = null;
			obj.state = "endPan";
			obj.fireEvent('endZoom');
			obj.fireEvent('zoomPan');
			if (obj.defaultScl != obj.currentScl){
				obj.updateForeImage();
			}
			if (obj.mapIconsVisible){
				obj.iconsPlate.style.visibility = "inherit";
			}
			obj.startDrag=false;
		}
	}
//	sjSetCursor('default');
	obj.mapImage.removeEventHandler('touchmove',moveMouse);
	obj.mapImage.removeEventHandler('touchend',finishMouse);
	obj.mapImage.removeEventHandler('touchcancel',finishMouse);
	return false;
}
/////////////iPhone
	this.mapImage.addEventHandler('touchstart',initMouse);
	this.mapImage.addEventHandler('touchmove',moveMouse);
	this.mapImage.addEventHandler('touchend',finishMouse);
	this.mapImage.addEventHandler('touchcancel',finishMouse);
//////////////////////////
	var sz = false;
	function gesture(o,evt){
		if (evt.preventDefault) evt.preventDefault();
		clearTimeout(tapCounerTimer);
		tapCounerTimer = null;
		obj.moving=true;
		obj.startDrag=false;
		sz = [	obj.backImage.width(), obj.backImage.height(),obj.backImage.left(), obj.backImage.top(),
				obj.foreImage.width(), obj.foreImage.height(),obj.foreImage.left(), obj.foreImage.top()];
		currGScl = 1;
		return false;
	}

	function gesturechange(o,evt){
        var diff = evt.scale - currGScl;
		if(sz){
			if (evt.preventDefault) evt.preventDefault();
		    if ((touches[0]) && (touches[1])){
				var poi = [(touches[0].clientX + touches[1].clientX)/2,(touches[0].clientY + touches[1].clientY)/2];
				var x =sjGetPageCoords (sjGetElement(obj._elementId)).x;
				var y =sjGetPageCoords (sjGetElement(obj._elementId)).y;
				var newx=poi[0]-obj.currentX-x;
				var newy=poi[1]-obj.currentY-y;
				var factor = Math.pow(obj.zoom_factor,1/3);
				if (Math.abs(diff) > 0.1){
					newx = obj.viewSize.width/2-obj.currentX;
					newy = obj.viewSize.height/2-obj.currentY;
					if (typeof zoomLimit != 'undefined'){
						factor = Math.pow(2,1/evt.scale/zoomLimit);
					}
					if (diff > 0) {//Math.pow(2,1/inZoomStep)
							obj.PinchZoomAt(obj.backImage,newx,newy,1/factor);
					}
					else {
							obj.PinchZoomAt(obj.backImage,newx,newy,factor);
					}
					//var dx = (obj.viewSize.width/2-poi[0])/evt.scale/zoomLimit;
					//var dy = (obj.viewSize.height/2-poi[1])/evt.scale/zoomLimit;
					//obj.setPosition(obj.backImage,obj.currentX+dx,obj.currentY+dy,obj.currentScl);
					//obj.updateForeImage();
					currGScl = evt.scale;
				}
			}	
		}
		return false;
	}

	function gestureend(o,evt){
		if (evt.preventDefault) evt.preventDefault();
		sz = false;
		touches = [];
		clearTimeout(tapCounerTimer);
		tapCounerTimer = null;
		return false;
	}
///////
	this.mapImage.addEventHandler('gesturestart',gesture);
	this.mapImage.addEventHandler('gesturechange',gesturechange);
	this.mapImage.addEventHandler('gestureend',gestureend);
//////////////////////////
	this.closeButton.addEventHandler('touchend',
		function (o,evt){
				window.close();
			return false;
		}
	);
	this.closeButton.addEventHandler('click',
		function (o,evt){
				window.close();
			return false;
		}
	);
}

//////////////////////////////////////////////////////////////////////////
function touchHandler(evt){
	if (evt.preventDefault) evt.preventDefault();
}

/*if (window.addEventListener) { 
	document.addEventListener("touchstart", touchHandler, false);
	document.addEventListener("touchmove", touchHandler, false);
	document.addEventListener("touchend", touchHandler, false);
	document.addEventListener("touchcancel", touchHandler, false);    
	document.addEventListener("zoom", touchHandler, false);    
	document.addEventListener("scroll", touchHandler, false);    
}else if (window.attachEvent) { 
	document.attachEvent("ontouchstart", touchHandler);
	document.attachEvent("ontouchmove", touchHandler);
	document.attachEvent("ontouchend", touchHandler);
	document.attachEvent("ontouchcancel", touchHandler);    
	document.attachEvent("onzoom", touchHandler);    
	document.attachEvent("onscroll", touchHandler);    
}*/
//////////////////////////////////////////////////////////////////////////

SjZoom.prototype.resizing = function(w,h){
	var oldW = this.viewSize.width;
	var oldH = this.viewSize.height;
	if ((oldW == w) && (oldH == h)) {
		return;
	}
	this.clearIconsPlates();
	this.viewSize = {width:w, height:h};
	this.setSize(this.viewSize.width,this.viewSize.height);
	this.clip(0,0,this.viewSize.width+2,this.viewSize.height+2);
	this.defaultScl = Math.max(Math.max(this.imgServerWidth / this.viewSize.width, this.imgServerHeight / this.viewSize.height), 1.0);//ss
	var dW = (this.viewSize.width - oldW)/2;
	var dH = (this.viewSize.height - oldH)/2;
	var oldTime = this.transitionTime;
	var oldFTime = this.fadeTime;
	this.transitionTime = 0;
	this.fadeTime = 0;
	if (this.defaultScl <= this.currentScl){
		this.ResetView(this.backImage);
	}else{
		var xy = this.checkPosition(this.currentX+dW,this.currentY+dH,this.currentScl);
		this.setPosition(this.backImage,xy.nx,xy.ny,this.currentScl);
		this.updateForeImage();
	}
	this.transitionTime = oldTime;
	this.fadeTime = oldFTime;
	this.fireEvent('endZoom');
	this.fireEvent('setPosition');
}

SjZoom.prototype.setZoomLimit = function (inZoomStep,inZoomLimit,inMaxZoom){
  	if (inZoomStep <= 0) inZoomStep = 0.0001;
  	if (inZoomLimit < 1) inZoomLimit = 1;
	this.max_zoom = Math.ceil(Math.log(inZoomLimit)/Math.log(Math.pow(2,1/inZoomStep)));
	this.setMaxZoom(this.max_zoom, Math.pow(2,1/inZoomStep),inMaxZoom/100);
}

SjZViewer.prototype.resizing = function(w,h){
	this.elem.style.width = w+"px";
	this.elem.style.height = h+"px";
	this.elem_base.style.width = w+"px";
	this.elem_base.style.height = h+"px";
	document.getElementById(this._elementId+'_tbl_base').style.width = w+"px";
	document.getElementById(this._elementId+'_tbl_base').style.height = h+"px";
	this.zviewer.resizing(w,h);
}

SjZViewer.prototype.setZoomLimit = function(inZoomStep,inZoomLimit,inMaxZoom) {	
	this.zviewer.setZoomLimit(inZoomStep,inZoomLimit,inMaxZoom); 
};

SjZoom.prototype.PinchZoomAt = function (img,x,y,factor) {
	var nothing = false;
	var newScl = this.currentScl*factor;
	if (this.zoom_factor_limit != 0) {
		newScl = Math.max(newScl, 1 / this.zoom_factor_limit);
	}
	newScl = Math.min(this.defaultScl,newScl);
	var newx = this.viewSize.width/2-x/(newScl/this.currentScl);
	var newy = this.viewSize.height/2-y/(newScl/this.currentScl);
	var nx = this.checkPosition(newx,newy,newScl).nx;
	var ny = this.checkPosition(newx,newy,newScl).ny;
	if (!nothing){ 
			if ((newScl != this.currentScl) || (Math.round(nx) != Math.round(this.currentX)) || (Math.round(ny) != Math.round(this.currentY))){
				if (newScl < this.currentScl){
					if (this.zoomScl){
						if (this.zoomIdx < this.zoomSclArray.length){
							this.zoomIdx++;
						}
					}else{
						this.zoomIdx++;
					}
				}else if (newScl > this.currentScl){
					if (this.zoomIdx > 0){
						this.zoomIdx--;
					}
				}
				if ((factor != 1) && (newScl != this.currentScl)){
					if ((newScl < this.currentScl) && (this._animeid == null)){//?? open
						this.fireEvent('zoom','factor',1/newScl*100);
					}
				}else if ((Math.round(nx) != Math.round(this.currentX)) || (Math.round(ny) != Math.round(this.currentY))){
					this.fireEvent('zoomPan');//?? open
				}
				if (this._animeid){
					clearTimeout(this._animeid);
					this._animeid = null;
				}
				if (this.foreImage._fadeid) {
					clearTimeout(this.foreImage._fadeid);
					this.foreImage._fadeid = null;
					//this.checkPendingChangeContext();//?? open 
				}
				this.foreImage.visible(false);
				this.currentScl = newScl;
				img.setSize(this.imgServerWidth / this.currentScl,this.imgServerHeight / this.currentScl);
				this.setPosition(img,nx,ny,this.currentScl);
				this.fireEvent('endZoom');
				this.fireEvent('setPosition');
				//sjSetCursor('wait');
				this.requestShowWaitIcon();
				this.updateForeImage();
				//sjSetCursor('default');
				this.requestHideWaitIcon();
		}else{
			//sjSetCursor('default');
		}
	}
}
/////////////////////////////
SjZoom.prototype.createIconsPlate = function(){
	var cvs = document.createElement("div");
	cvs.style.width = this.mapImage.width(); 
	cvs.style.height = this.mapImage.height();  
	cvs.style.position = "absolute";  
	cvs.id = "iconsPlate_"+this.id;
	this.mapImage._content.appendChild(cvs);
	this.iconsPlate = cvs;
	var obj = this;
	obj.iconsPlate.style.visibility = "hidden";
	this.backImage.addEventListener("load", 
		function (){
			if (obj.withMap == true){
				var metaStr = "";
				if (obj.metaVersion){
					metaStr = '&.mv='+obj.metaVersion;
				}
				obj.mapImage.visible(false);
				sjLoadMap(obj.mainURL,metaStr,1/obj.currentScl, 1/obj.currentScl,obj._elementId,
						function (){
							obj.mapImage.visible(true);
							obj.clearIconsPlates();
							obj.drawIcons("s7map_"+obj._elementId);
							if (obj.mapIconsVisible){
								obj.iconsPlate.style.visibility = "inherit";
							}
							return false;
						}
					);
			}
			return false;
		}
	);
}

SjZoom.prototype.clearIconsPlates = function(){
	this.iconsPlate.style.visibility = "hidden";
	this.iconsPlate.innerHTML = "";
}

SjZoom.prototype.drawIcons = function (inMap) {
	var cList = new Array();	
	var icons = new Array();
	var obj = this;
	obj.clearIconsPlates();
	cList = sjGetMapCentroidList(inMap);
	for (var i=0; i < cList.length; i++){
		icons[i] = document.createElement("div");
		icons[i].style.position = "absolute";
		icons[i].id = "link_"+i
		icons[i].className = "s7mapIcon";
		icons[i].href = cList[i].href;
		//target: "_blank" - new window,"_self" - current window,"_parent" - parent window,"_top" - top frame	
		icons[i].target = ((cList[i].target == "undefined") || (cList[i].target == null)) ? "_self":cList[i].target; 
		icons[i].xc = cList[i].xc;
		icons[i].yc = cList[i].yc;
		icons[i].alt = cList[i].alt;
		icons[i].rollover_key = cList[i].rollover_key;
		if ((icons[i].href == null) && (icons[i].rollover_key == null)){
			icons[i].style.display = "none";
		}

		icons[i].ontouchstart = icons[i].onmousedown = function(e){
								e = fixEvent(e);
								this.startPosX = e.posx;
								this.startPosY = e.posy;
								this.endPosX = e.posx;
								this.endPosY = e.posy;
								obj.enableZoom = false;
								this.setAttribute('state','down');
								obj.enableZoom = true;
								this.touchStart = new Date().getTime(); 
								return false;
							};
		icons[i].ontouchmove = icons[i].onmousemove = function(e){
								e = fixEvent(e);
								this.moving = true;
								this.endPosX = e.posx;
								this.endPosY = e.posy;
								this.setAttribute('state','');
								return false;
							};
		icons[i].ontouchend = icons[i].onmouseup = function(e){
								e = fixEvent(e);
								this.touchEnd = new Date().getTime(); 
								var dt = this.touchEnd - this.touchStart;
								var dx = Math.abs(this.endPosX - this.startPosX);
								var dy = Math.abs(this.endPosY - this.startPosY);
								//if ((dt < 200) && (dx < 10) && (dy < 10)){//??
								if ((dx < 10) && (dy < 10)){
									e.cancelBubble = true;
									if (e.stopPropagation) e.stopPropagation();
									if (e.preventDefault) e.preventDefault();
									if (window.event) window.event.cancelBubble=true;
									obj.fireEvent('mapIconSelect','icon',this);
								}
								this.setAttribute('state','');
								this.moving = false;
								return false;
							};
		obj.iconsPlate.appendChild(icons[i]);
		icons[i].style.left = cList[i].xc -icons[i].offsetWidth/2 + "px";  
		icons[i].style.top = cList[i].yc -icons[i].offsetHeight/2 + "px";  
	}
}

SjZoom.prototype.mapUpdate = function (x,y,w,h,scale){
	this.mapImage.toXY(x,y);
	this.mapImage.setSize(w,h);
	sjResetMap("s7map_"+this._elementId);//map
	sjZoomMap ("s7map_"+this._elementId, scale, scale);
	this.clearIconsPlates();
	this.iconsPlate.width = this.mapImage.width(); 
	this.iconsPlate.height = this.mapImage.height();  
	this.drawIcons("s7map_"+this._elementId);
}
///////////////////////////////////////////SwatchBar/////////////////////////////////////////////
//calculate swatchBar parameters
function sjGetMaxSwatchCount(inSize,inInnerSpacing, inOuterSpacing, inSwatchSize, inButtonSize) {
	return Math.floor((inSize - 2 * inOuterSpacing + inInnerSpacing - 2 * inButtonSize) / (inSwatchSize + inInnerSpacing));
}

function sjGetSwatchBarSize(inInnerSpacing, inSwatchSize, inSwatchCount, inButtonSize) {
	return inSwatchCount * inSwatchSize + (inSwatchCount - 1) * inInnerSpacing + 2 * inButtonSize;
}

function sjCalcSwatchBar(inSize,inButtonSize, inUserInnerSpacing, inAutoInnerSpacing, inOuterSpacing, inSwatchSize, inUserSwatchCount, inImageListLength) {
	var maxSwatchCount = sjGetMaxSwatchCount(inSize,inUserInnerSpacing, inOuterSpacing, inSwatchSize, 0);
	if (maxSwatchCount < inImageListLength){
		maxSwatchCount = sjGetMaxSwatchCount(inSize,inUserInnerSpacing, inOuterSpacing, inSwatchSize, inButtonSize);
	}
	//var	maxSwatchCount = sjGetMaxSwatchCount(inSize,inUserInnerSpacing, inOuterSpacing, inSwatchSize, inButtonSize);

	var swatchCount = Math.min(maxSwatchCount, inUserSwatchCount);
	if (maxSwatchCount < inUserSwatchCount) {
		swatchCount = maxSwatchCount;
	} else {
		swatchCount = inUserSwatchCount;
	}
	if (swatchCount > inImageListLength) {
		swatchCount = inImageListLength;
	}

	if (swatchCount < 1) {
		swatchCount = 1;
		inUserInnerSpacing = 0;
		var defaultSize = (inSize - inOuterSpacing * 2) / 3;
		if (inButtonSize > defaultSize) {
			inButtonSize = defaultSize;
		}
		if (inSwatchSize > defaultSize) {
			inSwatchSize = defaultSize;
		}
	}

	var useButtons = (swatchCount < inImageListLength);
	var stretchLayout = (
		inAutoInnerSpacing && 
		(swatchCount > 1) &&
		(sjGetSwatchBarSize(inUserInnerSpacing, inSwatchSize, swatchCount, (useButtons ? inButtonSize : 0)) < inSize - 2 * inOuterSpacing) && 
		(sjGetSwatchBarSize(inUserInnerSpacing, inSwatchSize, swatchCount + 1, (useButtons ? inButtonSize : 0)) > inSize - 2 * inOuterSpacing)
	);

	var innerSpacing;
	if (stretchLayout) {
		innerSpacing = inUserInnerSpacing + (inSize - 2 * inOuterSpacing - sjGetSwatchBarSize(inUserInnerSpacing, inSwatchSize, swatchCount, (useButtons ? inButtonSize : 0))) / (swatchCount - 1);
	} else {
		innerSpacing = inUserInnerSpacing;
	}

	return ({
				buttonSize:(useButtons ? inButtonSize : 0),
				innerSpacing:innerSpacing,
				outerSpacing:inOuterSpacing,
				swatchSize:inSwatchSize,
				swatchCount:swatchCount
			}
	);
}

///swatchBar////////////////////////////
function SjSwatchBar(inElem,inImageList,inParams){
	this.doc = window.parent.document;
	this.imgList = inImageList || [];
	this.params = inParams || new Object();
	this.dir = this.params.dir || "horiz"; //"vertical" || "horiz"
	//this.dir = "vertical";
	this.serverURL = this.params.serverURL || "/is/image/"; 
	this.callback = this.params.swatchBarCallback || null; 
	this.autoInnerSpacing = this.params.autoInnerSpacing || false; 
	//this.autoInnerSpacing = true; 
	this.userSwatchCount = this.params.userSwatchCount || 3;
	this.animationTime = this.params.animationTime || 500;
	this.itemsImg = [];
	this.prevButton = null;
	this.nextButton = null;
	this.selectedItem = null;
	this.counter = 0;
	this.index = 0;
	var obj = this;

	this.swBar = this.doc.createElement("div");
	this.swBar.style.padding = "0";
	this.swBar.style.position = "absolute";
	this.swBar.style.zIndex = 100;
	this.swBar.style.visibility = "inherit";
	this.swBar.style.borderStyle = "solid";
	this.swBar.style.borderColor = "transparent";
	this.swBar.id = "s7swatchBar";
	this.swBar.className = "s7swatchBar";
	this.swBar.style.overflow = "hidden";

	this.swMask = this.doc.createElement("div");
	this.swMask.style.position = "absolute";
	this.swMask.id = "swMask";
	this.swMask.className = "s7swatchItemsArea";
	this.swMask.style.left = 0+"px";
	this.swMask.style.top = 0+"px";
	this.swMask.style.overflow = "hidden";
	this.swMask.style.webkitTransform = "none";

	this.swCont = this.doc.createElement("div");
	this.swCont.style.position = "absolute";
	this.swCont.id = "swCont";
	this.swCont.className = "s7swatchCont";
	this.swCont.style.left = 0+"px";
	this.swCont.style.top = 0+"px";

	this.itemMask = this.doc.createElement("div");
	this.itemMask.style.position = "absolute";
	this.itemMask.style.zIndex = 100;
	this.itemMask.id = "itemMask";
	this.itemMask.className = "s7swatchHighlight";
	this.itemMask.style.visibility = "hidden";
	this.swCont.appendChild(this.itemMask);

	for(var i=0; i<this.imgList.length; i++){
		this.itemsImg[i] = this.doc.createElement("img");
		this.itemsImg[i].style.position = "absolute";
		this.itemsImg[i].img = this.imgList[i];
		this.itemsImg[i].id = "swItem_"+i;
		this.itemsImg[i].idx = i;
		this.itemsImg[i].className = "s7swatchItem";
		this.itemsImg[i].selected = false;
		this.itemSpacer = this.doc.createElement("div");
		this.itemSpacer.style.position = "absolute";
		this.itemSpacer.id = "swSpacer";
		this.itemSpacer.className = "s7swatchSpacer";
		this.itemSpacer.style.left = 0+"px";
		this.itemSpacer.style.top = 0+"px";

		this.swCont.appendChild(this.itemsImg[i]);
		this.swCont.appendChild(this.itemSpacer);
	}
	this.swMask.appendChild(this.swCont);
	this.swBar.appendChild(this.swMask);

	this.prevButton = this.doc.createElement("div");
	this.nextButton = this.doc.createElement("div");
	this.prevButton.style.position = "absolute";
	this.prevButton.id = "swLButton";
	this.prevButton.className = "s7swatchPrevButton";
	this.prevButton.setAttribute("state","enabled");
	this.prevButton.onmouseup = this.prevButton.ontouchend = function(e){
								e = fixEvent(e);
								if (obj.prevButton.getAttribute("state") == "down"){
									obj.prevButton.setAttribute("state","");
									obj.prev();
								}
							};
	this.prevButton.onmousedown = this.prevButton.ontouchstart = function(e){
								e = fixEvent(e);
								if (obj.prevButton.getAttribute("state") == "enabled"){
									obj.prevButton.setAttribute("state","down");
								}
							};
	this.nextButton.style.position = "absolute";
	this.nextButton.id = "swRButton";
	this.nextButton.className = "s7swatchNextButton";
	this.nextButton.setAttribute("state","enabled");
	this.nextButton.onmouseup = this.nextButton.ontouchend = function(e){
								e = fixEvent(e);
								if (obj.nextButton.getAttribute("state") == "down"){
									obj.nextButton.setAttribute("state","");
									obj.next();
								}
							};
	this.nextButton.onmousedown = this.nextButton.ontouchstart = function(e){
								e = fixEvent(e);
								if (obj.nextButton.getAttribute("state") == "enabled"){
									obj.nextButton.setAttribute("state","down");
								}
							};
	this.swBar.appendChild(this.prevButton);
	this.swBar.appendChild(this.nextButton);
	//this.doc.body.appendChild(this.swBar);	
	//document.getElementById("cont").appendChild(this.swBar);
	//document.getElementById("izView").parentNode.appendChild(this.swBar);
	document.getElementById(inElem).parentNode.appendChild(this.swBar);
	
	this.moving = false;

	this.dw = parseInt(sjGetStyle(this.itemsImg[0]).marginLeft).NaN0()+parseInt(sjGetStyle(this.itemsImg[0]).marginRight).NaN0();
	this.dh = parseInt(sjGetStyle(this.itemsImg[0]).marginTop).NaN0()+parseInt(sjGetStyle(this.itemsImg[0]).marginBottom).NaN0();
	this.swatchWidth = parseInt(sjGetStyle(this.itemsImg[0]).width).NaN0()+this.dw || 50;
	this.swatchHeight = parseInt(sjGetStyle(this.itemsImg[0]).height).NaN0()+this.dh || this.swatchWidth;
	this.buttonPresent = 0;
	if (this.dir == "horiz"){
		this.buttonSize = parseInt(sjGetStyle(this.prevButton).width).NaN0() || 50;
		this.outerSpacing = (parseInt(sjGetStyle(this.swBar).left).NaN0() != 0) ? parseInt(sjGetStyle(this.swBar).left).NaN0():parseInt(sjGetStyle(this.swBar).right).NaN0();
		this.outerSpacing += parseInt(sjGetStyle(this.swBar).borderLeftWidth).NaN0();
		this.userInnerSpacing = parseInt(sjGetStyle(this.itemSpacer).width).NaN0() || 5;
	}else{
		this.buttonSize = parseInt(sjGetStyle(this.prevButton).height).NaN0() || 50;
		this.outerSpacing = (parseInt(sjGetStyle(this.swBar).top).NaN0() != 0) ? parseInt(sjGetStyle(this.swBar).top).NaN0():parseInt(sjGetStyle(this.swBar).bottom).NaN0();
		this.outerSpacing += parseInt(sjGetStyle(this.swBar).borderTopWidth).NaN0();
		this.userInnerSpacing = parseInt(sjGetStyle(this.itemSpacer).height).NaN0() || 5;
	}
	this.resize();
	this.redraw();
	return this;
}

SjSwatchBar.prototype.resize = function (){
	var obj = this;
	this.swBar.style.width = "";
	this.swBar.style.height = "";
	this.swBar.style.left = "";
	this.swBar.style.top = "";
	with(this){
		var calcSW = sjCalcSwatchBar((dir == "horiz")?  sjScreenSize().w:sjScreenSize().h,
														buttonSize, 
														userInnerSpacing, 
														autoInnerSpacing, 
														outerSpacing, 
									 (dir == "horiz")?	swatchWidth:swatchHeight, 
														userSwatchCount, 
														imgList.length);
	}
	this.buttonPresent = calcSW.buttonSize;
	this.actualSpacing = calcSW.innerSpacing;
	this.swatchCount = calcSW.swatchCount;
	if (this.dir == "horiz"){
		this.swatchWidth = calcSW.swatchSize;
	}else{
		this.swatchHeight = calcSW.swatchSize;
	}
	this.outerSpacing = calcSW.outerSpacing;  
	if (this.dir == "horiz"){
		this.swBar.style.width = sjGetSwatchBarSize(calcSW.innerSpacing, calcSW.swatchSize, calcSW.swatchCount, calcSW.buttonSize)+"px";
		this.swBar.style.height = this.swatchHeight +"px";
		this.swBar.style.left = this.swBar.offsetLeft + "px";
		this.swBar.style.top = this.swBar.offsetTop + "px";
	}else{
		this.swBar.style.height = sjGetSwatchBarSize(calcSW.innerSpacing, calcSW.swatchSize, calcSW.swatchCount, calcSW.buttonSize)+"px";
		this.swBar.style.width = this.swatchWidth+"px";
		this.swBar.style.left = this.swBar.offsetLeft + "px";
		this.swBar.style.top = this.swBar.offsetTop + "px";
	}
	this.swMask.style.height = this.swBar.style.height;
	this.swMask.style.width = this.swBar.style.width;
	this.swMask.style.clip = "rect(auto,auto,auto,auto)";
	this.swCont.style.left = 0+"px";
	this.swCont.style.top = 0+"px";
	for(var i=0; i<this.imgList.length; i++){
		this.itemsImg[i].style.width = this.swatchWidth-this.dw + "px";
		this.itemsImg[i].style.height = this.swatchHeight-this.dh + "px";
		this.itemsImg[i].src = this.serverURL+this.imgList[i]+sjPBreak(this.imgList[i])+"wid="+(this.swatchWidth-this.dw)+"&hei="+(this.swatchHeight-this.dh);
		if (this.dir == "horiz"){
			if (calcSW.buttonSize){
				this.itemsImg[i].style.left = calcSW.buttonSize+i*(this.swatchWidth+this.actualSpacing) +"px";
			}else{
				this.itemsImg[i].style.left = i*(this.swatchWidth+this.actualSpacing) +"px";
			}
		}else{
			if (calcSW.buttonSize){
				this.itemsImg[i].style.top = calcSW.buttonSize+i*(this.swatchHeight+this.actualSpacing) +"px";
			}else{
				this.itemsImg[i].style.top = i*(this.swatchHeight+this.actualSpacing) +"px";
			}
		}

		function itemsHandler(e){
			if (!obj.moving){
				e = fixEvent(e);
				for (var i=0;i<obj.itemsImg.length;i++){
					obj.itemsImg[i].selected = false;
				}
				this.selected = true;
				obj.selectedItem = this;
				obj.redraw();
				if (obj.callback != null){
					obj.callback(this.idx);
				}
			}	
		};
		if("ontouchstart" in window){
			this.itemsImg[i].ontouchend = itemsHandler;
		}else{
			this.itemsImg[i].onclick = itemsHandler;
		}
	}

	if (calcSW.buttonSize > 0){
		if (this.dir == "horiz"){
			/*rect(<top>, <right>, <bottom>, <left>)*/
			this.swMask.style.clip = 'rect(0px, '+(parseInt(this.swBar.style.width).NaN0()-calcSW.buttonSize)+'px,'+parseInt(this.swBar.style.height).NaN0()+'px, '+calcSW.buttonSize+'px)';
		}else{
			this.swMask.style.clip = 'rect('+calcSW.buttonSize+'px, '+parseInt(this.swBar.style.width).NaN0()+'px,'+(parseInt(this.swBar.style.height).NaN0()-calcSW.buttonSize)+'px, '+0+'px)';
		}
		this.prevButton.style.left = 0 +"px";
		if (this.dir == "horiz"){
			this.prevButton.style.width = calcSW.buttonSize +"px";
			this.prevButton.style.height = this.swatchHeight +"px";
			this.nextButton.style.width= calcSW.buttonSize +"px";
			this.nextButton.style.height = this.swatchHeight +"px";
			this.nextButton.style.left = sjGetSwatchBarSize(calcSW.innerSpacing, calcSW.swatchSize, calcSW.swatchCount, calcSW.buttonSize) - calcSW.buttonSize +"px";
		}else{
			this.prevButton.style.height = calcSW.buttonSize +"px";
			this.prevButton.style.width = this.swatchWidth +"px";
			this.nextButton.style.height= calcSW.buttonSize +"px";
			this.nextButton.style.width = this.swatchWidth +"px";
			this.nextButton.style.top = sjGetSwatchBarSize(calcSW.innerSpacing, calcSW.swatchSize, calcSW.swatchCount, calcSW.buttonSize) - calcSW.buttonSize +"px";
		}
	}else{
		this.prevButton.style.width = this.prevButton.style.height = this.nextButton.style.width = this.nextButton.style.height = 0 +"px";
		this.swMask.style.clip = 'rect(auto,auto,auto,auto)';
	}
	if (this.selectedItem != null){
		this.scrollTo(this.selectedItem.idx);
	}
}

SjSwatchBar.prototype.setImageList = function (inImageList){
	this.imgList = inImageList || [];
}

SjSwatchBar.prototype.next = function (inStep){
	var oldCounter = this.counter;
	var step = inStep || this.swatchCount;
	if (this.counter < this.imgList.length-1) {
		this.counter += step;
	}
	if (this.counter > this.imgList.length-step) {
		this.counter = this.imgList.length-step;
	}
		if (this.dir == "horiz"){
			var b = parseInt(this.swCont.style.left).NaN0(); 
			var f = (this.swatchWidth+this.actualSpacing)*this.counter;
			var obj = this;
				sjAnimation(this.swCont,"left",b,-f,this.animationTime,sine,function(){
																obj.redraw();
															}
														);
		}else{
			var b = parseInt(this.swCont.style.top).NaN0();
			var f = (this.swatchWidth+this.actualSpacing)*this.counter;
			var obj = this;
				sjAnimation(this.swCont,"top",b,-f,this.animationTime,sine,function(){
																obj.redraw();
															}
														);
		}
}

SjSwatchBar.prototype.prev = function (inStep){
	var oldCounter = this.counter;
	var step = inStep || this.swatchCount;
	if (this.counter > 0) {
		this.counter -= step;
	}
	if (this.counter < 0) {
		this.counter = 0;
	}
		if (this.dir == "horiz"){
			var b = parseInt(this.swCont.style.left).NaN0();
			var f = (this.swatchWidth+this.actualSpacing)*this.counter;
			var obj = this;
				sjAnimation(this.swCont,"left",b,-f,this.animationTime,sine,function(){
															   obj.redraw();
															}
														);
		}else{
			var b = parseInt(this.swCont.style.top).NaN0();
			var f = (this.swatchWidth+this.actualSpacing)*this.counter;
			var obj = this;
				sjAnimation(this.swCont,"top",b,-f,this.animationTime,sine,function(){
															   obj.redraw();
															}
														);
		}
}

SjSwatchBar.prototype.scrollTo = function (idx){
	if (typeof idx == "undefined"){
		return;
	}
	var obj = this;
	var oldCounter = this.counter;
	var a = Math.abs(this.swCont.offsetLeft/(this.swatchWidth+this.actualSpacing));
	var b = Math.abs(this.swCont.offsetLeft/(this.swatchWidth+this.actualSpacing))+(this.swatchCount-1);
	var oldSelectedIdx = this.selectedItem.idx;
	var selectedIdx = idx;
	if (idx < 0){
		selectedIdx = 0; 
	}
	if(idx > obj.imgList.length-1){
		selectedIdx = obj.imgList.length-1; 
	} 
	this.counter = Math.floor(selectedIdx/this.swatchCount)*this.swatchCount;
	if (this.counter < 0){
		this.counter = 0;
	}
	if(this.counter > obj.imgList.length-this.swatchCount){
		this.counter = obj.imgList.length-this.swatchCount;
	}

	if (selectedIdx>=a && selectedIdx<=b){
		this.counter = oldCounter;
	}else if (selectedIdx > b){
		if (this.dir == "horiz"){
			this.swCont.style.left = parseInt(this.swCont.style.left) - (this.swatchWidth+this.actualSpacing)*(selectedIdx-b)+"px"; 
		}else{
			this.swCont.style.top = parseInt(this.swCont.style.top) - (this.swatchWidth+this.actualSpacing)*(selectedIdx-b)+"px"; 
		}
	}else if (selectedIdx < a){
		if (this.dir == "horiz"){
			this.swCont.style.left = parseInt(this.swCont.style.left) - (this.swatchWidth+this.actualSpacing)*(selectedIdx-a)+"px"; 
		}else{
			this.swCont.style.top = parseInt(this.swCont.style.top) - (this.swatchWidth+this.actualSpacing)*(selectedIdx-a)+"px"; 
		}
	}

	for (var i=0;i<this.itemsImg.length;i++){
		this.itemsImg[i].selected = false;
	}
	this.itemsImg[selectedIdx].selected = true;
	this.selectedItem = this.itemsImg[selectedIdx];
	this.redraw();
}

SjSwatchBar.prototype.redraw = function (){
	if (this.buttonPresent > 0){
		this.prevButton.setAttribute("state","enabled");
		this.nextButton.setAttribute("state","enabled");

		if (this.counter == 0){
			this.prevButton.setAttribute("state","disabled");
		}else if (this.counter == this.imgList.length-this.swatchCount){
			this.nextButton.setAttribute("state","disabled");
		}
	}
	this.itemMask.style.visibility = "hidden";
	/* corect width&height by margin:border:padding*/
	var maskStyle = sjGetStyle(this.itemMask);
	var dW = 0;
	var dH = 0;
	var corr = ["borderLeftWidth","borderTopWidth","borderRightWidth","borderBottomWidth",
				"marginLeft","marginTop","marginRight","marginBottom",
				"paddingLeft","paddingTop","paddingRight","paddingBottom"];
	for (var i=0; i<corr.length;i++){
		if (corr[i] in maskStyle){
			if ((corr[i].indexOf("Left") != -1) || (corr[i].indexOf("Right") != -1)){
				dW += parseInt(maskStyle[corr[i]]).NaN0();
			}
			if ((corr[i].indexOf("Top") != -1) || (corr[i].indexOf("Bottom") != -1)){
				dH += parseInt(maskStyle[corr[i]]).NaN0();
			}
		}
	}
	this.itemMask.style.width = this.swatchWidth - dW +"px";
	this.itemMask.style.height = this.swatchHeight - dH + "px";
	for (var i=0;i<this.itemsImg.length;i++){
		if (this.itemsImg[i].selected){
			this.itemMask.style.left = this.itemsImg[i].style.left;
			this.itemMask.style.top = this.itemsImg[i].style.top;
			this.itemMask.style.visibility = "inherit";
		}
	}
}

SjSwatchBar.prototype.visibility = function (inVisibility){
	if (inVisibility){
		this.swBar.style.visibility = inVisibility
	}
	return this.swBar.style.visibility;
}

SjSwatchBar.prototype.setSelectedItem = function (idx){
	for (var i=0;i<this.itemsImg.length;i++){
		this.itemsImg[i].selected = false;
	}
	this.itemsImg[idx].selected = true;
	this.selectedItem = this.itemsImg[idx];
	this.redraw();
}

