/* Javascript for showroom page */

/* Load-time stuff */
$(document).ready(function() {
	//Compose thumbnails
	rebuildThumbnails(eval($('#codeList').val()),$('#designStart').val());
});

//These are the fields to check in the form, and to send
var fieldlist=new Array('Category','Type','Gender','Code','Material','Carat','Clarity','Colour','Width');

//Keep a track of hilighting
var myHiLite;
var myPrevious=1;
var myNext=1;
var myPage=1;
var myPageLength;
var ajaxResult="";

/**
 * Rebuild thumbnails
 *
 * @param string The list of product codes
 * @param int The start number
 */
function rebuildThumbnails(codeList,start) {
	//Make sure start is parsed as an integer, not a string as may happen first time when called from DIV
	start=parseInt(start);

	//Calculate the number of items in the page
	var pageLength=thumbRows*thumbCols;
	myPageLength=pageLength;
	
	//Work out end
	var end=(start+pageLength)-1;
	var actualEnd=end;
	if (codeList.length<end) {
		end=codeList.length;
	}

	//Keep a track of the start
	myPrevious=start-pageLength;
	myNext=start+pageLength;
	myPage=parseInt(start/pageLength)+1;

	//Go through the images, setting the thumbnails and selecting the selected one
	var objCode=document.getElementById('code');
	var objFullImage=document.getElementById('fullImage');

	//Remember the start of the list index
	var lStart=start;
	if (lStart<1) lStart=1; //Avoid silly javascript error
	for (i=1; i<=end && lStart<=codeList.length; i++) {
		//Set the image
		var fn=thumbPrefix+codeList[lStart-1].replace(/[^\w\d-]/g,"").toLowerCase()+thumbImageCode+thumbSuffix;
		var objImg=document.getElementById('thumb'+i);
		if (objImg) {
			objImg.src=fn;
			objImg.style.visibility='visible';
			
			//Select this?
			if (objCode.options[objCode.selectedIndex].value.toLowerCase()==codeList[lStart-1].toLowerCase()) {
				//Yes
				objImg.style.border=thumbBorderHilite;
	
				//Set the full image?
				if (objFullImage) {
					//Yes!
					var fn=imagePrefix+codeList[lStart-1].replace(/[^\w\d-]/g,"").toLowerCase()+imageImageCode+imageSuffix;
					objFullImage.src=fn;
				}
				
				//Keep a track of the hilighting
				myHiLite=i;
			} else {
				//No
				objImg.style.border=thumbNoBorderHilite;
			}
		}		
		
		//Set the mousepointer to the default and make it clickable
		var objLink=document.getElementById('tlink'+i);
		
		if (objLink) {
			objLink.style.cursor='';
			objLink.onclick='';
		}		
		
		//Increment the array index counter
		lStart++;
	}

	//Fill in any blanks?
	if (i<=pageLength) {
		//We need to fill in blanks

		for (var k=i; k<=actualEnd; k++) {
			//Blank the image
			var objImg=document.getElementById('thumb'+k);

			if (objImg) {
				objImg.style.visibility='hidden';
			}
			
			//Set the mousepointer to nothing and disable the link
			var objLink=document.getElementById('tlink'+k);
			
			if (objLink) {
				objLink.style.cursor='default';
				
				objLink.onclick=function () {
					return false;	
				}
			}
		}
	}
	
	//Show any links? Get the objects first
	objBackLinkContainer=document.getElementById('backLinkContainer');
	objNextLinkContainer=document.getElementById('nextLinkContainer');
	
	if (objBackLinkContainer && objNextLinkContainer) {
		/* Previous Link */
		if (start>1) {
			//Show back link
			
			//Set it
			objBackLinkContainer.style.display='';
		} else {
			//Hide back link

			objBackLinkContainer.style.display='none';
		}

		/* Next Link */
		if (codeList.length>end) {
			//More than one page
			//Show next link
	
			objNextLinkContainer.style.display='';
		} else {
			//Hide next link
			objNextLinkContainer.style.display='none';			
		}
	}

}

/**
 * Select a thumbnail to be the full size image
 *
 * @param string The ID of the thumbnail
 */
function selectThumb(id) {
	//Process click for a thumbnail, and change the code dropdown and the preview image

	//Have we got a code object to select?
 	var objThumb=document.getElementById('thumb'+id);
	var objCode=document.getElementById('code');
	
	if (objThumb && objCode) {
		//We have a valid thumb - get it's filename

		//Blank the hiliting on the old option
		objOldThumb=document.getElementById('thumb'+myHiLite);
		if (objOldThumb) {
			objOldThumb.style.border=thumbNoBorderHilite;
		}
		myHiLite=id;

		//Hilite the current one
		objThumb.style.border=thumbBorderHilite;

		//Select it in the list
		objCode.selectedIndex=myHiLite+((myPage-1)*myPageLength)-1;
		
		//Change the full size image
		objFullImage=document.getElementById('fullImage');
		if (objFullImage) {
			var fn=objThumb.src.replace(/^.*\//,'');

			var re=new RegExp(thumbImageCode+thumbSuffix);
			objFullImage.src=imagePrefix+fn.replace(re,imageImageCode+imageSuffix);
		}
		
		//Run the dropdown change function
		dropdownChange(objCode,1);
	}
		
}

/**
 * Move to next set of thumbnails
 *
 * @var string The list of codes to use
 */
function thumbNext(codeList) {
	//Next has been clicked
	var Codes=eval($('#codeList').val());

	//Rebuild thumbnails	
	rebuildThumbnails(Codes,myNext);	

}

/**
 * Move to previous set of thumbnails
 *
 * @var string The list of codes to use
 */
function thumbBack(codeList) {
	//Back has been clicked
	var Codes=eval($('#codeList').val());

	//Rebuild thumbnails	
	rebuildThumbnails(Codes,myPrevious);	
}

/**
 * Process a dropdown change
 *
 * @var object The dropdown object
 * @var bool True=don't process thumbnails
 */
function dropdownChange(ddObj,noThumbs) {
	//A dropdown has changed. Reload all the dropdowns via ajax

	//Special case for design code - don't do it for that.
	if (ddObj.id=='code') {
		/* Do the necessary for a code change */
		
		//First of all, work out the position in the array
		var Codes=eval($('#codeList').val());
		var Descriptions=eval($('#descriptionList').val());

		//Work out what page we will be on
		var thePage=parseInt(ddObj.selectedIndex/myPageLength)+1;
		var PageStart=((thePage-1)*myPageLength)+1;

		//Change the code and description
		$('#codeText').html(Codes[ddObj.selectedIndex]);
		$('#descriptionText').html(Descriptions[ddObj.selectedIndex]);
		
		//Call the function to rebuild the thumbnails - if not running from a thumb click
		if (!noThumbs) {
			rebuildThumbnails(Codes,PageStart)
		}
	}
	//Everything else is fetched on the fly by Ajax
	//Compose the URL to send to ajax
	var theURL="/ajax/Showroom/section/"+escape(section)+"/";
	
	//Go through fields
	for (i=0;i<fieldlist.length;i++) {
		//Only include the fields that are present in the form - get the object
		var objField=document.getElementById(fieldlist[i].toLowerCase());
		
		if (objField) {
			//The field exists, add it to the query string
			theURL+=fieldlist[i].toLowerCase()+"/"+urlencode(objField.options[objField.selectedIndex].value)+"/";
		}
	}

	//We now have a nicely composed URL - fetch it
	$.ajax({
		type: "GET",
		url: theURL,
		cache: false,
		success: function(data) {
			ajaxResult=data;
			displayCategories(1,noThumbs);
		}
	});

}

/**
 * Display the category dropdowns
 *
 * @var bool From code
 * @var bool No thumbs
 */
function displayCategories(fromCode,noThumbs) {
	//Convert the ajax result into actual dropdowns
	//Ajax result now in ajaxResult.innerHTML
	
	// 
	// 	//What browser are we using?
	// 	var myBrowser=browserDetect();
	var myBrowser="";
	
	var fieldArray=ajaxResult.split("****")
	//Go through the fields and update the HTML
	for(i=0;i<fieldArray.length;i++) {
		//In turn, split that into a field and content
		var objArray=fieldArray[i].split("^^^^");
		
		//Get the object
		var objField=document.getElementById(objArray[0]);
		
		//A product ID or a field?
		if (objArray[0]=='productId') {
			//The productId variable
			productId=objArray[1];
		} else if (objArray[0]=='priceText') {
			//Set the price text
			$('#priceText').html(objArray[1]);			
		} else if (objArray[0]=='hideButton') {
			//Hide the basket button?

			if (objArray[1]==1) {
				//yes
				$('#basketButtonContainer').hide();
			} else {
				//No, show it
				$('#basketButtonContainer').show();
			}
		} else 	if (objField) {
			//A form field
			if (objField.type=='select-one') {
				//Get an array of all the new options
				var optArray=objArray[1].split("!!!!");

				//Remove all the select's options
				objField.options.length=0;

				//Store new selected index
				var newSelection=null;
									
				//Add the new ones
				for (j=0;j<optArray.length;j++) {
					var objSelCheck=optArray[j].split("####");

					if (objSelCheck[0]) {
						var optn = document.createElement("OPTION");
						optn.text = objSelCheck[0];
						optn.value = objSelCheck[0];
						objField.options.add(optn);
						
						//Select it?
						if (objSelCheck.length>1) {
							newSelection=j;
							if (myBrowser!='Opera') {
								//Not opera - we can select it now without error
								objField.selectedIndex=newSelection;
							}
						}
					}
				}
				
				//Actually select the new option
				if (newSelection) {
					//Work round annoying Opera bug
					if (myBrowser=='Opera') {
						//Do this a millisecond later so it doesn't cock up
						setTimeout("document.getElementById('"+objField.id+"').selectedIndex="+newSelection,1);
					}
				}
			} else if (!noThumbs || objField.id=='price') {
				//This is another field - set the innerHTML. Do correct function:
				if (objField.id=='fullImage') {
 					//Image
 					objField.src=objArray[1];
				} else if (objField.type=='hidden') {
					//Hidden text field
 					$(objField).val(objArray[1]);
					
				} else {
 					//Other random text field
 					if (objArray[0]=="price") {
	 					//Do some nice displaying
	 					$(objField).html(numberFormat(objArray[1],2,".",""));
 					} else {
						//Normal field 					
	 					$(objField).html(objArray[1]);
 					}
				}
			}
		}
	}	

	if (fromCode) {
		//Work out what thumbnail page we will be on
		//Get CODE object
		var objCode=document.getElementById('code');
		if (objCode) {
			var thePage=parseInt(objCode.selectedIndex/myPageLength)+1;
			var PageStart=((thePage-1)*myPageLength)+1;
			
			if (!noThumbs) {
				rebuildThumbnails(eval($('#codeList').val()),PageStart);
			}
		}
	} else {
		if (!noThumbs) {
			rebuildThumbnails(eval($('#codeList').val()),1);
		}
	}
}

/**
 * Add the current product to the shopping basket
 */
function addToBasket() {
	//Check we have a valid ring size
	
	//Get the ring size object
	var objRingSize=$('#ringSize');
	var doBasket=true;
	var size="";
	if (objRingSize.length>0 ) {
	
		if ($('#ringSize').val()) {
			//Set size
			size="size/"+$('#ringSize').val()+"/";
		} else {
			//No size!
	 		alert("You must choose a size for your ring in order to add it to the basket!");
	 		doBasket=false;
	 	}

 	}
 	
 	//Only add if we have all the bits filled in
 	if (doBasket) {
		//Compose the basket URL
		var basketUrl="/Basket/basketAdd/productId/"+productId+"/uniqueId/"+uniqueId+"/"+size;
		
		//Redirect to it
		document.location.href=basketUrl;
	}	
}

function urlencode(str) {
	return escape(str).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '--SLASH--').replace(/@/g, '%40');
}