//consts:
var d=document;
var loadingPoolSize=3;	// how many image loading can be statred simultaneously
var rollStep=15;	// max step (speed) of catalog rolling
var rollSpeedUp=3;	// roll step multiplier when mouse reaches either screen side
var rollSpeedUpWidth=64;	// width of area where roll speed up occurs
var rollPadding=0.3;	// width of part of screenWidth where rolling starts (0.5 = rollig starts everywhere)
var loopBorderWidth=400;	// width of loopBorder
var paddingWidth=64;
var screensForLoop=2;	// how many screen width catalogWidth should be to activate catalog looping

//variables:
var catalog=null;	// html TABLE element which holds the catalog items as colums
var catalogX=0;
var catalogY=0;
var catalogWidth=0;
var catalogHeight=0;
var countItems=0;	// inited with number of items on the page
var realPartWidth=0;
var clonePartWidthLeft=0;
var clonePartWidthRight=0;
var countClonesRight=0;
var countClonesLeft=0;
var isCatalogLooped=false;
var isAllLoaded=false;	// is true when all item images are loaded
var imageLoaders=new Array();	// pool of image loaders
var intervalRollCatalog=null;
var intervalLoadItemImages=null;
var isWindowLoaded=false;

function ImageLoader(lim){
	this.lim=lim;
	this.targetIndex=-1;
	this.isDone=true;
}
function updateLeftRight(){
	var l=d.getElementById("btnLeftActive");
	var r=d.getElementById("btnRightActive");
	if(catalogWidth<screenWidth){
		l.className="";
		r.className="";
	}
	else{
		if(catalogX<0)l.className="on";
		else l.className="";
		if(catalogX+catalogWidth>screenWidth)r.className="on";
		else r.className="";
	}
}
function loadItemImages(){
	if(!isWindowLoaded)return;
	if(isAllLoaded)return;

	// clear this interval:
	clearInterval(intervalLoadItemImages);
	intervalLoadItemImages=null;

	// find item with unloaded image:
	var tFrame=d.getElementById("frameLoader");
	var doc=tFrame.contentDocument;
	if (doc==undefined||doc==null){
		// IE:
		doc=tFrame.contentWindow.document;
		doc.open();
		doc.write("<div id='imageLoaders'></div>");
		doc.close();
		debug("IE, using IFRAME frameLoader.");
	}
	else {
		doc=d;
		debug("Non IE, using document.");
	}
	var imageLoaders=doc.getElementById("imageLoaders");
	debug("Starting loading images into "+imageLoaders);
	for(i=1;i<=countItems;i++){
		var id="im"+i;
		var im=d.getElementById(id);
		//im.src=im.getAttribute("rsrc");//+"?r="+Math.random();	// start loading
		debug(i+". src: "+im.getAttribute("rsrc"));
		
		var lim=doc.createElement("img");
		lim.setAttribute("id","_im"+i);
		lim.setAttribute("width",100);
		lim.setAttribute("height",100);
		lim.setAttribute("src",im.getAttribute("rsrc"));//+"?r="+Math.random());
		imageLoaders.appendChild(lim);
		if(isImageLoaded(lim)){
			debug("Image is already loaded:"+lim);
			setImageLoaded(im.getAttribute("rsrc"));
		}
		else onEvent(lim,"load",onImageLoad);
	}
}
function onImageLoad(e){
	var lim=eventTarget(e);
	var id=lim.getAttribute("id").substring(1);
	debug("Image "+id+" is loaded.");
	setImageLoaded(lim.src);
}
function setImageLoaded(src){
	for(var i=1;i<=countItems+countClonesRight+countClonesLeft;i++){
		var id="im"+i;
		var im=d.getElementById(id);
		var rsrc=im.getAttribute("rsrc");
		if(rsrc==src.substring(src.length-rsrc.length)){
			debug(rsrc+"=="+src);
			im.src=rsrc;
			d.getElementById(id+"_progress").style.display="none";
		}
	}

}
function isImageLoaded(img) {
	// During the onload event, IE correctly identifies
	// any images that
	// weren’t downloaded as not complete. Others should too. Gecko-based
	// browsers act like NS4 in that they report this incorrectly.
	if(!img.complete)return false;

	// However, they do have two very useful properties:
	//naturalWidth and
	// naturalHeight. These give the true size of the image. If it failed
	// to load, either of these should be zero.
	if(typeof img.naturalWidth!="undefined"&&img.naturalWidth==0)return false;

	// No other way of checking: assume it’s ok.
	return true;
}
function updateCatalogX(){
	if(screenWidth>catalogWidth) catalogX=(screenWidth-catalogWidth)/2;
	else {
		if(catalogX<(screenWidth-catalogWidth)){
			if(isCatalogLooped){
				var d=(screenWidth-catalogWidth)-catalogX;
				catalogX=(screenWidth-clonePartWidthRight-clonePartWidthLeft-loopBorderWidth)-d;
			}
			else catalogX=screenWidth-catalogWidth;
		}
		else if(catalogX>0){
			if(isCatalogLooped){
				catalogX+=clonePartWidthLeft+clonePartWidthRight+loopBorderWidth-catalogWidth;
			}
			else catalogX=0;
		}
	}
	catalog.style.left=catalogX+"px";
	cookieSet("catalogX"+brandName,catalogX);
	updateLeftRight();
	catalog.style.visibility="visible";
}
function rollCatalog(){
	if(mouseY<catalogY||mouseY>(catalogY+catalogHeight))return;
	if(mouseX<screenWidth*(1-rollPadding)&&mouseX>screenWidth*rollPadding)return;
	//debug("mouseX:"+mouseX+", "+screenWidth*(1-rollPadding)+", "+screenWidth);
	if(screenWidth>catalogWidth)return;

	var p=rollPadding;
	if(mouseX>screenWidth/2)p=(1-rollPadding);
	//var o=Math.round(((screenWidth*p-mouseX)/(screenWidth*rollPadding))*rollStep);
	var f=((screenWidth*p-mouseX)/(screenWidth*rollPadding))*1.57;
	if(f>1.57)f=1.57;
	if(f<-1.57)f=-1.57;
	//debug("f: "+f+", "+Math.round(Math.cos(f)*100)/100);
	if(mouseX>screenWidth/2)f=Math.cos(f)-1;
	else if(mouseX<screenWidth/2) f=1-Math.cos(f);
	else f=0;
	var o=Math.round(f*rollStep);
	if(mouseX<=rollSpeedUpWidth)o=rollStep*rollSpeedUp;
	else if(mouseX>=screenWidth-rollSpeedUpWidth)o=rollStep*-rollSpeedUp;
	//if(sitesLeft+o*10<(screenWidth-divSites.offsetWidth))o=o*.8;
	//else if(sitesLeft+o*10>0)o=o*.8;
	catalogX+=o;
	updateCatalogX();
}
function recreateClonesAndLoopBorders(){
	// take parent TR and first TD:
	var cloneParent=d.getElementById("catalogTR");
	var firstTD=d.getElementById("td1");
	var lastTD=d.getElementById("td"+countItems);

	// delete previous clones and loopBorders:
	while(firstTD.previousSibling){
		cloneParent.removeChild(firstTD.previousSibling);
	}
	while(lastTD.nextSibling){
		cloneParent.removeChild(lastTD.nextSibling);
	}

	// init values:
	isCatalogLooped=false;
	countClonesRight=0;
	countClonesLeft=0;
	clonePartWidthRight=0;
	clonePartWidthLeft=0;

	// if catalogWidth is too small - skip creating clones:
	if(realPartWidth<screenWidth*screensForLoop){
		// just create paddings:
		p1=d.createElement("td");
		cloneParent.insertBefore(p1,firstTD);
		p1.className="padding";
		firstTD=p1;
		//var pe1=d.createElement("img");
		//pe1.setAttribute("src","/i/e.gif");
		//pe1.setAttribute("width",loopBorderWidth);
		//pe1.setAttribute("height",1);
		p1.appendChild(d.createElement("img"));
		p2=p1.cloneNode(true);
		cloneParent.appendChild(p2);

		// calc full catalogWidth:
		catalogWidth=realPartWidth+paddingWidth*2;
		debug("Catalog is NOT looped");
		debug("Catalog width: "+catalogWidth+"px");
		return;
	}
	isCatalogLooped=true;

	// measure clone part widths:
	while(clonePartWidthRight<screenWidth&&countClonesRight<countItems){
		countClonesRight++;
		var m=d.getElementById("td"+countClonesRight);
		clonePartWidthRight+=m.offsetWidth;
	}
	while(clonePartWidthLeft<screenWidth&&countClonesLeft<countItems){
		countClonesLeft++;
		var m=d.getElementById("td"+(countItems-countClonesLeft+1));
		clonePartWidthLeft+=m.offsetWidth;
	}

	// we will use this func to rename IDs:
	var renameIds=function(c,j){
		if(c.childNodes){
			for(var k=0;k<c.childNodes.length;k++){
				renameIds(c.childNodes[k],j);
			}
		}
		if(!c.getAttribute||!c.getAttribute("id"))return;;
		var newId=c.getAttribute("id").replace(/\d+/,j);
		c.setAttribute("id",newId);
	}

	// create loopBorders:
	p1=d.createElement("td");
	cloneParent.insertBefore(p1,firstTD);
	p1.className="loopBorder";
	firstTD=p1;
	//var pe1=d.createElement("img");
	//pe1.setAttribute("src","/i/e.gif");
	//pe1.setAttribute("width",loopBorderWidth);
	//pe1.setAttribute("height",1);
	p1.appendChild(d.createElement("img"));
	p1.appendChild(d.createElement("div"));
	p2=p1.cloneNode(true);
	cloneParent.appendChild(p2);

	// append clone items to the right end of catalog to make illusion of a loop:
	for(var i=1;i<=countClonesRight;i++){
		// take original:
		var m=d.getElementById("td"+i);
		// create clone:
		var c=m.cloneNode(true);//d.createElement("td");
		// rename IDs in clone:
		renameIds(c,countItems+i);
		// append clone to catalog:
		cloneParent.appendChild(c);

		// create border:
		if(i==countClonesRight)continue;
		var b=d.createElement("td");
		b.className="b";
		b.innerHTML="&nbsp;";
		// append node to catalog:
		cloneParent.appendChild(b);
		clonePartWidthRight+=b.offsetWidth;
	}
	//alert("Right clone 1 td: "+d.getElementById("td"+(countItems+1)));
	//alert("Right clone 1 img: "+d.getElementById("im"+(countItems+1)));

	// prepend clone items to the left of catalog to make illusion of a loop:
	for(var i=1;i<=countClonesLeft;i++){
		// take original:
		var m=d.getElementById("td"+(countItems-i+1));
		// create clone:
		var c=m.cloneNode(true);//d.createElement("td");
		// rename IDs in clone:
		renameIds(c,countItems+countClonesRight+i);
		// prepend clone to catalog:
		cloneParent.insertBefore(c,firstTD);
		firstTD=c;

		// create border:
		if(i==countClonesLeft)continue;
		var b=d.createElement("td");
		b.className="b";
		b.innerHTML="&nbsp;";
		// append node to catalog:
		cloneParent.appendChild(b);
		cloneParent.insertBefore(b,firstTD);
		clonePartWidthLeft+=b.offsetWidth;
		//debug("b.offsetWidth:"+b.offsetWidth);
		firstTD=b;
	}
	//alert("1st td width: "+d.getElementById("td"+1).offsetWidth);
	//alert("3 td width: "+d.getElementById("td"+(countItems+countClonesRight+1)).offsetWidth);

	// calc full catalogWidth:
	catalogWidth=realPartWidth+clonePartWidthRight+clonePartWidthLeft+loopBorderWidth*2;
	debug("countClonesRight:"+countClonesRight+", clonePartWidthRight:"+clonePartWidthRight);
	debug("countClonesLeft:"+countClonesLeft+", clonePartWidthLeft:"+clonePartWidthLeft);
	debug("realPartWidth:"+realPartWidth);
	debug("Catalog width: "+catalogWidth+"px");
}
function onWindowLoad(){
	isWindowLoaded=true;
}
function onWindowResize(){
	getScreenSize();
	recreateClonesAndLoopBorders();
	debug("screenWidth:"+screenWidth);
}
function initPage(){
	debugInit();
	onEvent(window,"resize",onWindowResize);

	// show catalogBG:
	//d.getElementById("catalogFrameBG").style.display="block";

	// init screen size:
	getScreenSize();

	// take some constants and objects:
	catalog=d.getElementById("catalog");
	catalogY=d.getElementById("catalogFrame").offsetTop;
	catalogHeight=catalog.offsetHeight;
	realPartWidth=catalog.offsetWidth;

	//count items:
	countItems=0;
	do{
		var m=d.getElementById("td"+(countItems+1));
		if(m==undefined)break;
		countItems++;
	}while(true);
	debug("Items count: "+countItems);

	// in order to make illusion of a loop - count how many clones of items we need on right and left to cover screenWidth:
	recreateClonesAndLoopBorders();

	// get or init catalogX:
	var s=cookieGet("catalogX"+brandName);
	if(s!=null&&!isNaN(s))catalogX=parseInt(s);
	else {
		if(isCatalogLooped)catalogX=-(clonePartWidthLeft+loopBorderWidth-paddingWidth);
		else catalogX=0;
	}

	// create image loading progress:
	for(var i=1;i<=countItems+countClonesRight+countClonesLeft;i++){
		// create loading progress image:
		var p=d.createElement("img");
		p.setAttribute("id","im"+i+"_progress");
		if(brandName=="search")p.setAttribute("src","/i/item-progress2.gif");
		else p.setAttribute("src","/i/item-progress2b.gif");
		p.className="imProgress";
		var di=d.getElementById("di"+i);
		di.appendChild(p);
		p.style.left=(di.offsetWidth/2-32)+"px";
		p.style.top=136+"px";//di.offsetHeight/2-32
	}

	updateCatalogX();

	// start catalog rolling
	intervalRollCatalog=setInterval("rollCatalog()",10);

	// start loading items' images:
	intervalLoadItemImages=setInterval("loadItemImages()",50);
	debug("Page inited.");
}
onEvent(window,"load",onWindowLoad);
onReadys.push(initPage);
