var DLN = DLN || {};

DLN.utils = new function() {
	this.isNumeric = function(n) {
		return !isNaN(parseFloat(n)) && isFinite(n);
	};
	
	this.randRange = function(to,from) {
		return Math.floor(Math.random() * (to - from + 1) + from);
	};
	
	this.thumbSpinner = function(containerID,spinSetName) {
		var qvs2 = new QuickViewSpin();
		qvs2.setContainerId(containerID);
		qvs2.setServerUrl('//lining.scene7.com/is/image/');
		qvs2.setImageSet('LiNing/' + spinSetName);
		qvs2.setSize(188, 188);
		qvs2.setAttributes('$DLN_Thumb$');
		qvs2.draw();
	};
};



$(document).ready(function(){
	$('.thumb[data-imageset]').each(function(){
		var id = $(this).attr('id');
		var imgSet = $(this).attr('data-imageset');
		if (!id.length) {
			id = imgSet + '_' + DLN.utils.randRange(10000000,99999999);
			$(this).attr('id',id)
		}
		DLN.utils.thumbSpinner(id,imgSet);
	});
});

function QuickViewSpin() {
	this.containerId;
	this.image;
	this.serverUrl;
	this.viewerWidth;
	this.viewerHeight;
	this.autoRotateTick;
	this.direction = 1;
	this.frameHash = new Array();
	this.touchTick;
	this.attributes = ''; /* Added Rob O'Brien 11/8/12 */
	this.autoRotateInterval = 500; /* Added Rob O'Brien 11/8/12 */
	this.instanceCount = QuickViewSpin.CNT;
	QuickViewSpin.INSTANCES[QuickViewSpin.CNT] = this;
	QuickViewSpin.CNT++;
};
QuickViewSpin.CNT = 0;
QuickViewSpin.INSTANCES = new Object();
QuickViewSpin.prototype.setContainerId = function (inId) {
	this.containerId = inId;
};
QuickViewSpin.prototype.setImageSet = function (inImage) {
	this.image = inImage;
};
QuickViewSpin.prototype.setServerUrl = function (inUrl) {
	this.serverUrl = inUrl;
};
QuickViewSpin.prototype.setSize = function (inWid, inHei) {
	this.viewerWidth = inWid;
	this.viewerHeight = inHei;
};
QuickViewSpin.prototype.setAttributes = function (str) {
	this.attributes = str;
};
QuickViewSpin.prototype.createLayout = function () {
	this.imageHolder = document.createElement('div');
	this.imageHolder.id = 'qvsImageHolder_' + this.instanceCount;
	this.imageHolder.style.position = 'relative';
	this.imageHolder.style.width = this.viewerWidth + 'px';
	this.imageHolder.style.height = this.viewerHeight + 'px';
	this.imageHolder.style.overflow = 'hidden';
	document.getElementById(this.containerId).appendChild(this.imageHolder);
	this.containerCoords = this.getObjectCoords(this.containerId);
	this.setMouseEvents();
};
QuickViewSpin.prototype.setMouseEvents = function () {
	var classRef = this;
	this.imageHolder.onmouseover = function (e) {
		var evt = e;
		if (!e) {
			var evt = window.event;
		}
		classRef.onMouseOver(evt);
	};
	this.imageHolder.onmouseout = function (e) {
		var evt = e;
		if (!e) {
			var evt = window.event;
			evt.cancelBubble = true;
		}
		classRef.onMouseOut(evt);
	};
	this.imageHolder.ontouchstart = function (e) {
		if (classRef.touchTick != null) {
			clearInterval(classRef.touchTick);
			classRef.touchTick = null;
		}

		function touchDealy() {
			classRef.onMouseOver(e);
		};
		classRef.touchTick = setInterval(touchDealy, 250);
	};
	this.imageHolder.ontouchend = function (e) {
		if (classRef.touchTick != null) {
			clearInterval(classRef.touchTick);
			classRef.touchTick = null;
		}
		classRef.onMouseOut(e);
	};
};
QuickViewSpin.prototype.onMouseOver = function (evt) {
	if (evt.touches && evt.touches.length) {
		evt.posx = evt.touches[0].clientX;
		evt.posy = evt.touches[0].clientY;
	} else {
		evt.posx = evt.clientX;
		evt.posy = evt.clientY;
	}
	if (window.event) {
		if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
			evt.posx = event.clientX + document.body.scrollLeft
			evt.posy = event.clientY + document.body.scrollTop;
		} else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
			evt.posx = event.clientX + document.documentElement.scrollLeft
			evt.posy = event.clientY + document.documentElement.scrollTop;
		}
	}
	this.direction = 1;
	if ((evt.posx - this.containerCoords.objectX) < (this.viewerWidth / 2)) {
		this.direction = -1;
	}
	this.startAutoRotate();
};
QuickViewSpin.prototype.onMouseOut = function (evt) {
	this.stopAutoRotate();
	evt.posx = evt.clientX;
	evt.posy = evt.clientY;
	if (window.event) {
		if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
			evt.posx = event.clientX + document.body.scrollLeft
			evt.posy = event.clientY + document.body.scrollTop;
		} else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
			evt.posx = event.clientX + document.documentElement.scrollLeft
			evt.posy = event.clientY + document.documentElement.scrollTop;
		}
	}
	var mX = evt.posx - this.containerCoords.objectX;
	var mY = evt.posy - this.containerCoords.objectY;
	if ((mX >= 0) && (mX <= this.viewerWidth) && (mY >= 0) && (mY <= this.viewerHeight)) {
		return;
	} else {
		this.setCurrentImageIdx(0);
	}
};
QuickViewSpin.prototype.startAutoRotate = function () {
	var classRef = this;

	function autoRotate() {
		classRef.doAutoRotate();
	};
	this.stopAutoRotate();
	this.autoRotateTick = setInterval(autoRotate, this.autoRotateInterval);
};
QuickViewSpin.prototype.stopAutoRotate = function () {
	if (this.autoRotateTick != null) {
		clearInterval(this.autoRotateTick);
		this.autoRotateTick = null;
	}
};
QuickViewSpin.prototype.doAutoRotate = function () {
	var idx = this.currentImageIdx + this.direction;
	if ((this.currentImageIdx + this.direction) >= this.rootImageSet.length) {
		idx = 0;
	} else if ((this.currentImageIdx + this.direction) < 0) {
		idx = (this.rootImageSet.length - 1);
	}
	this.setCurrentImageIdx(idx);
};
QuickViewSpin.prototype.createRootImageset = function () {
	var url = this.serverUrl + '/' + this.image + '?req=imageset,json&' + this.attributes;
	var classRef = this;
	sjGetResponse('', url, function (inData) {
		classRef.processImageSetResponse(inData);
	}, function (inData) {
		//fail quietly
	});
};
QuickViewSpin.prototype.processImageSetResponse = function (inData) {
	var imageSet = inData['IMAGE_SET'];
	var imageSetList = new Array();
	if (imageSet.indexOf(',') != -1) {
		imageSetList = imageSet.split(',');
	} else {
		imageSetList.push(imageSet);
	}
	this.rootImageSet = new Array();
	for (var i = 0; i < imageSetList.length; i++) {
		var obj = new Object();
		if (imageSetList[i].indexOf(';') != -1) {
			obj.image = imageSetList[i].split(';')[0];
			obj.swatch = imageSetList[i].split(';')[1];
		} else {
			obj.image = imageSetList[i];
			obj.swatch = imageSetList[i];
		}
		this.rootImageSet.push(obj);
	}
	this.setCurrentImageIdx(0);
};
QuickViewSpin.prototype.setCurrentImageIdx = function (inIdx) {
	if (((this.currentImageIdx != null) && (this.currentImageIdx == inIdx)) || ((inIdx < 0) || (inIdx >= this.rootImageSet.length))) {
		return;
	} else {
		this.currentImageIdx = inIdx;
	}
	if (this.frameHash[this.currentImageIdx] == null) {
		this.loadFrame(this.currentImageIdx);
	} else if (this.frameHash[this.currentImageIdx].loaded) {
		this.showFrame(this.currentImageIdx);
	}
};
QuickViewSpin.prototype.showFrame = function (inIdx) {
	if (!this.frameHash[inIdx].loaded || (inIdx != this.currentImageIdx)) {
		return;
	}
	for (var i in this.frameHash) {
		if (parseInt(i) == inIdx) {
			this.frameHash[i].frame.style.visibility = 'visible';
		} else {
			this.frameHash[i].frame.style.visibility = 'hidden';
		}
	}
};
QuickViewSpin.prototype.loadFrame = function (inIdx) {
	var frame = document.createElement('img');
	frame.id = 'frameContainer_' + this.instanceCount + '_' + inIdx;
	frame.style.position = 'absolute';
	frame.style.left = '0px';
	frame.style.top = '0px';
	frame.style.visibility = 'hidden';
	var frameObj = new Object();
	frameObj.frame = frame;
	frameObj.loaded = false;
	this.frameHash[inIdx] = frameObj;
	var classRef = this;
	frame.onload = function () {
		classRef.frameHash[inIdx].loaded = true;
		classRef.showFrame(inIdx);
	};
	var url = this.serverUrl + '/' + this.rootImageSet[inIdx].image + '?wid=' + this.viewerWidth + '&hei=' + this.viewerHeight + '&' + this.attributes;
	frame.src = url;
	this.imageHolder.appendChild(frame);
};
QuickViewSpin.prototype.getObjectCoords = function (inName) {
	var isObj = document.getElementById(inName);
	var objectCoordsY = 0;
	var objectCoordsX = 0;
	while (isObj) {
		objectCoordsX += isObj.offsetLeft;
		objectCoordsY += isObj.offsetTop;
		isObj = isObj.offsetParent;
	}
	coordHolder = new Object();
	coordHolder.objectX = objectCoordsX;
	coordHolder.objectY = objectCoordsY;
	return coordHolder;
}
QuickViewSpin.prototype.draw = function () {
	this.createLayout();
	this.createRootImageset();
};
var sjCallbacks = []; //!global variable MUST be created !
var sjErrCallbacks = []; //!global variable MUST be created !

function sjGetResponse(inReq, inImg, inCallback, inErrCallback) {
	var urljson = "";
	var tempi = inImg.indexOf("?");
	if (tempi >= 0) {
		urljson = inImg + '&' + inReq;
	} else {
		urljson = inImg + '?' + inReq;
	}
	var id = sjHashCode(urljson);
	urljson += '&id=' + id;
	if (typeof inCallback != 'undefined') {
		sjCallbacks.push({
			callback: inCallback,
			id: id
		});
	}
	if (typeof inErrCallback != 'undefined') {
		sjErrCallbacks.push({
			callback: inErrCallback,
			id: id
		});
	}
	var oScript = document.getElementById('sjScript_' + id);
	if (oScript) {
		document.getElementsByTagName("head")[0].removeChild(oScript);
		oScript = null;
	}
	oScript = document.createElement('script');
	oScript.type = 'text/javascript';
	oScript.id = 'sjScript_' + id;
	oScript.src = urljson;
	if (typeof oScript != "undefined") {
		document.getElementsByTagName("head")[0].appendChild(oScript);
	}
}

function s7jsonResponse(inArg, inId) {
	for (var i = 0; i < sjCallbacks.length; i++) {
		if (sjCallbacks[i] != null) {
			if (sjCallbacks[i].id == parseInt(inId)) {
				if (sjCallbacks[i].callback) {
					sjCallbacks[i].callback(inArg);
				}
				delete sjCallbacks[i];
			}
		}
	}
}

function s7jsonError(inArg, inId) {
	var alertErr = true;
	for (var i = 0; i < sjErrCallbacks.length; i++) {
		if (sjErrCallbacks[i] != null) {
			if (sjErrCallbacks[i].id == parseInt(inId)) {
				if (sjErrCallbacks[i].callback) {
					sjErrCallbacks[i].callback(inArg);
				}
				delete sjErrCallbacks[i];
				alertErr = false;
			}
		}
	}
	if (alertErr) {
		//alert(inArg.message);
		//console.log(inArg.message);
		if (typeof window.console != "undefined") {
			window.console.log(inArg.message);
		} else {
			//window.status = inArg.message;
		}
	}
}

function sjDebug(inPsResponse, inJsonResponse, inPsResponseParserName, inPsRequest) {}

function sjHashCode(d) { //unix style
	if (!d || d == "") return 1;
	var h = 0,
		g = 0;
	for (var i = d.length - 1; i >= 0; i--) {
		var c = parseInt(d.charCodeAt(i));
		h = ((h << 6) & 0xfffffff) + c + (c << 14);
		if ((g = h & 0xfe00000) != 0) h = (h ^ (g >> 21));
	}
	return h;
}

function sjLoadCtx(tl, inURL) {
	sjGetResponse('req=ctx,json&scl=1', inURL.replace(/req=ctx,json/gi, ""), //check doubling req

	function (inArg) {
		tl.text = dumpProps(inArg, "");
		if (tl.onLoadText) {
			tl.onLoadText();
		}
	}, function (inArg) {
		//alert('failed loading ctx for image [' + inURL + ']: ' + inArg.message);
		if (typeof window.console != "undefined") {
			window.console.log('failed loading ctx for image [' + inURL + ']: ' + inArg.message);
		} else {
			//window.status = 'failed loading ctx for image [' + inURL + ']: ' + inArg.message;
		}
		if (tl.onError) {
			tl.onError(inArg);
		}
	});
}
