//Object to manage custom jewelry items 
var jewelry = new CustomJewelry();
//model number
var model = "";
// base url for image rendering
var baseUrl = "http://s7d4.scene7.com/ir/render/BogarzRender/";
//selected custom jewelry obj
var currentCustomJwl = null;

function CustomJewelry(){
	this.jewelryObjHash = {};
	this.getJewelryObj = getJewelryObj;
	this.loadJewelryObj = loadJewelryObj;
	
}//END : customJewelry object

function customJewelryObj(iid,si,pi,s,c,sc,p,t,e,mt,cp) {
	this.itemId = iid;
	this.sivId = si;
	this.prodId = pi;
	this.style = s;
	this.color = c;
	this.stoneCount = sc;
	this.price = p;
	this.title = t;
	this.engraving =e;
	this.metalType = mt;
	this.textLimit = lookupTableValue(modelTable,s,4);
	this.comparePrice = cp;
	var tempImageNum = s;
	tempImageNum = tempImageNum.replace("MR00","");
	tempImageNum = tempImageNum.replace("MR0","");
	tempImageNum = tempImageNum.replace("MR","");
	this.imageNumber = tempImageNum;
	
} //END: listingObject constructor

function loadJewelryObj(key,iid,si,pi,s,c,sc,p,t,e,mt,cp)
{
	var obj = new customJewelryObj(iid,si,pi,s,c,sc,p,t,e,mt,cp);
	jewelry.jewelryObjHash[""+key] = obj;
}

function getJewelryObj(key)
{
	alert("getJewelryObj " + key);
	return jewelry.jewelryObjHash[""+key];
}

function createJewelryKey(model,selectedMetal,selectedStones)
{
	return  model+":"+selectedMetal+":"+selectedStones;
}

function searchTable(value, table, index) {
	for (i = 0; i < table.length; i++)
		if (table[i][index] == value)
			return true;
	return false;
}

function lookupTableValue(table, key, index) {
	//   alert("lookupTableValue - " + key + "<< key index >>" + index);
	for (i = 0; i < table.length; i++)
	{
		if (table[i][0] == key)
			return table[i][index];
	}
	return "";
}

function populateOptions(selector, colorTable) {
	for (var i = 0; i < colorTable.length; i++) {
		selector.options[i] = new Option(colorTable[i][0]);
		selector.options[i].value = colorTable[i][0];
	}
}

 function getSelectedItem(selector) {
	if (selector.selectedIndex < 0)
		pid="";
	else
		pid = selector.options[selector.selectedIndex].text;
	return pid;
}
 
function selectRingSize(selectRingSize) {
	//first get ringsize sdropdown
	//locate where size to select is
	//alert("selectRingSize - size passed: " + selectRingSize);
	$('#ringSize').val(selectRingSize);
}
function updateDivs(keyString)
{
	//alert("updateDivs - key: " + keyString);
	var customJwl = jewelry.jewelryObjHash[keyString];
	currentCustomJwl = customJwl;
	$('#title').html(customJwl.title);
	
	$('#itemId').html(customJwl.itemId);
	$('#engraving').html(customJwl.engraving);
	$('#sivId').html(customJwl.sivId);
	$('#metalType').html(customJwl.metalType);
	$('#textLimit').html(customJwl.textLimit);
	//set engraving message if engraving is enabled. else, hide message
	if (customJwl.engraving=="Y")
		$('#textLimitMessage').html("* Engraving limit: up to " + customJwl.textLimit + " characters");
	else
		$('#textLimitMessage').html("");
	
	
	var roundedComparePrice = Math.round(customJwl.comparePrice);
	var roundedBuysPrice = Math.round(customJwl.price);
	$('#product_retail_price').html("$" + roundedComparePrice);
	$('#comparePrice').html("$" + roundedComparePrice);
	$('#product_buyz_price').html("$" + roundedBuysPrice);
	$('#price').html("$" + roundedBuysPrice);
    var percentage = Math.round(Math.round( (1 - customJwl.price/customJwl.comparePrice)*100)/100 *100);
    $('#product_discount').html(percentage + "%");
    $('#prodId').html(customJwl.prodId);
    //alert("hidden field attr value before " + document.jeweleryForm.elements['attr'].value)
    var attributeString = buildAttributeString();
    //alert("updateDivs - attribute string : " + attributeString);
    document.jeweleryForm.elements['attr'].value =attributeString;
    document.jeweleryForm.elements['sivId'].value =customJwl.sivId;
    document.jeweleryForm.elements['productId'].value =customJwl.prodId;
    
    //alert("hidden field attr value after " + document.jeweleryForm.elements['attr'].value)
}

function updateStoneSummary(selectedStone)
{
	//update selected stones to summary div
	
	//get element by id and update
	var selectedStoneEle = ("#" + selectedStone.id+"Summary");
	var selectedStoneIdNumberOnly = selectedStone.id.replace("cbStone","");
	var selectedStoneValue = selectedStone.options[selectedStone.selectedIndex].value;
	//alert("index " + selectedStone.selectedIndex + " : " + selectedStone.options[selectedStone.selectedIndex].value + ":" + selectedStone);
	//alert("value of index 1 " + selectedStone.options[0]);
	var selectedStoneValueWithNumId =  selectedStoneIdNumberOnly + " " + selectedStone.options[selectedStone.selectedIndex].value;
	//if it's not cubic, insert the word "simulated" in summary
	if (selectedStoneValue!="April - Cubic Zirconia")
	{
		//parse the value by - and insert the word simulated
		var splitSelectedStoneValue = selectedStoneValueWithNumId.split("-");
		var finalSelectedStoneValue = splitSelectedStoneValue[0];
		if (!splitSelectedStoneValue[1])
		{
		}
		else
		{
			finalSelectedStoneValue += "- Simulated " + splitSelectedStoneValue[1];
		}
		                                                                                                    	

		//alert("updateStoneSummary - selected element name: " + selectedStoneEle + " selectedStone.value: " + selectedStone.options[selectedStone.selectedIndex].value);
	    $(selectedStoneEle).html(finalSelectedStoneValue);
	}
	else
	{
		 $(selectedStoneEle).html(selectedStoneValueWithNumId);
	}
	
}

/*
 * TODO: update engraving summary to be done later
 * */
function updateEngravingSummary()
{
	//update selected engraving message to summary div
}

function updateCustomSummary()
{
	updateStoneSummary();
	updateEngravingSummary();
}

// enable controls based on whether stones are available for design
function enableControlsNoEngraving()
{
	var maxNumStones = 6;
	var temp = new Array(maxNumStones);

	var selectedStones = getSelectedItem(document.jeweleryForm.numStoneSelector);
	var selectedMetal = getSelectedItem(document.jeweleryForm.metalSelector);
	$('#metalColor').html(selectedMetal);	
	$('#stoneCount').html(selectedStones);
	var keyString = createJewelryKey(model,selectedMetal,selectedStones);
	
	updateDivs(keyString);
	
	// enable/disable stones
	for (var i=1; i <= maxNumStones; i++ ) {
		var x = "document.jeweleryForm.cbStone" + i;
		var tempObj=eval(x);


		if ( i <= selectedStones )
			tempObj.style.visibility = 'visible';
		else
			tempObj.style.visibility = 'hidden';
	}


	// enable/disable labels
	for (var i=1; i <= maxNumStones; i++ ) {
		var x = "label" + i;
		var tempObj=eval(x);

		if ( i <= selectedStones )
			tempObj.innerHTML = i; 
		else
			tempObj.innerHTML = ''; 
	}	

}

function enableControlsEngraving(){
	var maxNumStones = 6;
	var temp = new Array(maxNumStones);
	var selectedStones = getSelectedItem(document.jeweleryForm.numStoneSelector);
	
	$('#stoneCount').html(selectedStones);
	// enable/disable stones
	for (var i=1; i <= maxNumStones; i++ ) {
		var x = "document.jeweleryForm.cbStone" + i;
		var tempObj = eval(x);

		if ( i <= selectedStones )
			tempObj.style.visibility = 'visible';
		else
			tempObj.style.visibility = 'hidden';
	}

	//enable disable stone summary
	for (var i=1; i <= maxNumStones; i++ ) {
		var x = "#cbStone" + i + "Summary";
		var tempObj = $(x);

		if ( i <= selectedStones )
		{
			tempObj.show();
			//alert("visible i " + i + " selected stone count " + selectedStones);
		}
		else
		{
			tempObj.hide();
			//alert("hidden i " + i + " selected stone count " + selectedStones);
		}
	}
	
	if (currentCustomJwl.engraving=="Y" && "$engraving" =="Y"){
		// enable/disable text
		$('#namediv').show();
		for (var i=1; i <= maxNumStones; i++ ) {
			var x = "document.jeweleryForm.text" + i;
			var tempObj=eval(x);

			if ( i <= selectedStones ) {
				tempObj.style.display = '';
			} else {
				tempObj.style.display = 'none';
			}
		}
	}
	else
	{
		// disable all text
		$('#namediv').hide();
		for (var i=1; i <= maxNumStones; i++ ) {
			var x = "document.jeweleryForm.text" + i;
			var tempObj=eval(x);
				tempObj.style.display = 'none';
		}
	}
	
	
	// enable/disable labels
	for (var i=1; i <= maxNumStones; i++ ) {
		var x = "#label" + i;
		var tempObj = x;

		if ( i <= selectedStones )
			$(tempObj).show();
		else
			$(tempObj).hide();
	}

	var tempObj = $('#note');
	var tempObj2 = $('#disclaimer');
	
	if (model == "MR159") {
		if (selectedStones >= 4) {
			tempObj.html('**');
			tempObj2.html('** engraving is not visible in this picture');
		} else {
			tempObj.html(''); 
			tempObj2.html('');
		}
	}
}


// lookup ring color
function getRingColor() {

	var selectedMetal = getSelectedItem(document.jeweleryForm.metalSelector);
	var selectedStones = getSelectedItem(document.jeweleryForm.numStoneSelector);
	var viewMode = "";
	if (currentCustomJwl.engraving=="Y")
	{
		viewMode="/ft";
	}
	for (var i=0; i < metalTable.length; i++ ) {
		
		// handle special gold cases
		/*
		if (selectedMetal == metalTable[0][0] && 
			( model == "MR012" ||  model == "MR050" ||  model == "MR059" || model == "MP171" ))
		{	
			return "&obj=g" + selectedStones + viewMode + "/metal_gold&show";
		}
		*/
		if ( selectedMetal == metalTable[i][0]) {
			return "&obj=g" + selectedStones + viewMode + metalTable[i][1];
		}
	}
    return "undefined";
}

// lookup stone color
function getStoneColor(stoneColor) {

	for (var i=0; i < gemSimulatedTable.length; i++ ) {

		if ( stoneColor == gemSimulatedTable[i][0]) {
			return gemSimulatedTable[i][1];
		}
	}
    return "undefined";
}

// lookup stones
function getStones() {

	var numStones = getSelectedItem(document.jeweleryForm.numStoneSelector);
	var stoneURL = "";
	var viewMode = "";
	if (currentCustomJwl.engraving=="Y")
	{
		viewMode="/ft";
	}
	// only set stone colors for stones available in vignette
	if ( numStones >= 1)
		stoneURL += "&obj=g" + numStones + viewMode + "/gems/1&show&color=" + getStoneColor(getSelectedItem(document.jeweleryForm.cbStone1));

	if ( numStones >= 2)
		stoneURL += "&obj=g" + numStones + viewMode + "/gems/2&show&color=" + getStoneColor(getSelectedItem(document.jeweleryForm.cbStone2));

	if ( numStones >= 3)
		stoneURL += "&obj=g" + numStones + viewMode + "/gems/3&show&color=" + getStoneColor(getSelectedItem(document.jeweleryForm.cbStone3));

	if ( numStones >= 4)
		stoneURL += "&obj=g" + numStones + viewMode + "/gems/4&show&color=" + getStoneColor(getSelectedItem(document.jeweleryForm.cbStone4));

	if ( numStones >= 5)
		stoneURL += "&obj=g" + numStones + viewMode + "/gems/5&show&color=" + getStoneColor(getSelectedItem(document.jeweleryForm.cbStone5));

	if ( numStones >= 6)
		stoneURL += "&obj=g" + numStones + viewMode + "/gems/6&show&color=" + getStoneColor(getSelectedItem(document.jeweleryForm.cbStone6));

	if ( numStones >= 7)
		stoneURL += "&obj=g" + numStones + viewMode + "/gems/7&show&color=" + getStoneColor(getSelectedItem(document.jeweleryForm.cbStone7));

	if ( numStones >= 8)
		stoneURL += "&obj=g" + numStones + viewMode + "/gems/8&show&color=" + getStoneColor(getSelectedItem(document.jeweleryForm.cbStone8));

	if ( numStones >= 9)
		stoneURL += "&obj=g" + numStones + viewMode + "/gems/9&show&color=" + getStoneColor(getSelectedItem(document.jeweleryForm.cbStone9));

	return stoneURL;
}

// get engravings by looking up text tables
function getEngraving(selectedRing) {

	var numStones = getSelectedItem(document.jeweleryForm.numStoneSelector);
	var lookup = selectedRing + "_" + numStones;
	var engravingURL = lookupTableValue(engravingTable,lookup, 1);
	
	// only set stone colors for stones available in vignette
	if ( numStones >= 1)
		engravingURL = engravingURL.replace("$Name1$", document.jeweleryForm.text1.value);
	if ( numStones >= 2)
		engravingURL = engravingURL.replace("$Name2$", document.jeweleryForm.text2.value);

	if ( numStones >= 3)
		engravingURL = engravingURL.replace("$Name3$", document.jeweleryForm.text3.value);

	if ( numStones >= 4)
		engravingURL = engravingURL.replace("$Name4$", document.jeweleryForm.text4.value);

	if ( numStones >= 5)
		engravingURL = engravingURL.replace("$Name5$", document.jeweleryForm.text5.value);

	if ( numStones >= 6)
		engravingURL = engravingURL.replace("$Name6$", document.jeweleryForm.text6.value);
	
	return engravingURL;
}

function limitText(evt,field) {

	if (evt.which && evt.which == 8) 
		return true; // allow Netscape backspace
	else 
		return (field.value.length < lookupTableValue(modelTable,model,4));

}

// preview images
function previewImage() {
	
	var selectedMetal = getSelectedItem(document.jeweleryForm.metalSelector);
	$('#metalColor').html(selectedMetal);	
	
	var selectedStones = getSelectedItem(document.jeweleryForm.numStoneSelector);
	$('#stoneCount').html(selectedStones);
	
	var keyString = createJewelryKey(model,selectedMetal,selectedStones);
	
	updateDivs(keyString);
	
	var url = baseUrl + currentCustomJwl.imageNumber;
	
	url += "-600?wid=430&sharpen=1&qlt=95&resmode=sharp";
	url += getRingColor();
	url += getStones();

    document.jeweleryForm.imgRing.src = url;
}

function selectStyleRefreshView(styleValue, color) {
	//first set style 
	if( model != styleValue)
	{
		model = styleValue;
		populateNumStones(document.jeweleryForm.numStoneSelector);
	}
	//alert("resetting style " +  styleValue + " !") ;
	$('#modelTitle').html("Style Number " + model);
	$('#style').html(model);

	// Added by Minh & Andrei to implement yellow gold thumbnails
	for( i = 0; i < document.jeweleryForm.metalSelector.length+1; i++ )
	{
		if( document.jeweleryForm.metalSelector.options[i].value == color )
		{
			document.jeweleryForm.metalSelector.selectedIndex = i;
			break;
		}
		
	}
	
	previewImageWithEngraving();
	//previewImage();
	enableControlsEngraving();
}

function getSelectedStyle() {
	var selectedStyleName  = "";
	
	return selectedStyleName;
}

function previewImageWithEngraving() {
	
	//setSelectedIndex(document.jeweleryForm.cbStone1,"February - Amethyst");
	
	var selectedMetal = getSelectedItem(document.jeweleryForm.metalSelector);
	$('#metalColor').html(selectedMetal);	
	
	var selectedStones = getSelectedItem(document.jeweleryForm.numStoneSelector);
	$('#stoneCount').html(selectedStones);
	
	var keyString = createJewelryKey(model,selectedMetal,selectedStones);
	
	updateDivs(keyString);
	
	var url = baseUrl + currentCustomJwl.imageNumber;
	url += "-600?wid=360&sharpen=1&qlt=95&resmode=sharp";
	url += getRingColor();
	url += getStones();
	url += getEngraving(model);

    document.jeweleryForm.imgRing.src = createImageURL(360);
}

function createImageURL(imageWidth)
{	
	var url = baseUrl + currentCustomJwl.imageNumber;
	url += "-600?wid="+imageWidth+"&sharpen=1&qlt=95&resmode=sharp";
	url += getRingColor();
	url += getStones();
	url += getEngraving(model);

	return url;
}

function enlargeWithEngraving() {

	var url = baseUrl + model;
	
	url += "-600?wid=600&resmode=sharp";
	url += getRingColor();
	url += getStones();
	url += getEngraving(model);

   window.open (url,"mywindow");
}

function enlargeNoEngraving() {

	var url = baseUrl + model;
	
	url += "-600?wid=600&resmode=sharp";
	url += getRingColor();
	url += getStones();

   window.open (url,"mywindow");
}

function getQueryVariable(variable) { 
	var query = window.location.search.substring(1); 
	var vars = query.split("&"); 
	for (var i=0;i<vars.length;i++) { 
		var pair = vars[i].split("="); 
		if (pair[0] == variable) { 
			return pair[1]; 
		} 
	}
}

function init() {

	// get model
	model = getQueryVariable("model");
	//var selectedStyleDiv = document.getElementById("selectedStyle");
	//model = selectedStyleDiv.innerHTML;
	$('#modelTitle').html("Style Number " + model);
	
	// disable ring size if pendent
//	var tempRingObj2=eval(ringSize);	
	
	if (model.indexOf("MP") == 0) {
		$('#ringsizelabel').html(''); 
		ShowLayer('ringSize','hidden');
		
	} else {
		$('#ringsizelabel').html('Ring Size'); 
		ShowLayer('ringSize','visible');
	}
}


function ShowLayer(id, action){

  if (navigator.userAgent.indexOf("Opera")!=-1
    && document.getElementById) type="OP";

if (document.all) type="IE";

if (document.layers) type="NN";

if (!document.all && document.getElementById) type="MO";

  if (type=="IE") eval("document.all." + id + ".style.visibility='" + action + "'");
  if (type=="NN") eval("document." + id + ".visibility='" + action + "'");
  if (type=="MO" || type=="OP") 
    eval("document.getElementById('" + id + "').style.visibility='" + action + "'");
}

function populateNumStones(selector) {
	//first clear all existing options
	
	// andristo:09-03-2010: was error here, should be "selector.length" not "selector.options.length"
	//var selectorLength = selector.options.length;
	var selectorLength = selector.length;
	if (selectorLength>0)
	{
		for (counter = 0; counter<selectorLength;counter++)
		{
			//selector.remove(0);
			selector.remove(counter);
		}
	}
	
	//populate options
	var startNum = lookupTableValue(modelTable,model,1);
	var endNum = lookupTableValue(modelTable,model,2);
	
	k = 0;
	for (var i = startNum; i <= endNum; i++) {
		// andristo:09-03-2010: was error here, should be Option(i,i) not Option(i)
		// first argument "text" (required), second argument "value" (optional)
		//selector.options[k++] = new Option(i);
		selector.options[k++] = new Option(i,i);
		//alert("populateNumStones start number " +startNum + " end number " + endNum + " k " + k + " i " + i);
	}

	// @added by andristo on 08/20/2010
	// In the selector, select the option that corresponds to the currentNumberOfStones
	// unless the maximum number of stones for this ring style is lower. 
	var newCurrentNumberOfStones = Math.min(currentNumberOfStones,endNum);
	setSelectedIndex(selector,newCurrentNumberOfStones);
}

function updateRingsizeDiv(ringSizeSelector)
{
	var selectedSize = getSelectedItem(ringSizeSelector);
	$('#ringSizeTxt').html(selectedSize);
}

function addCustomJewelryToNewCart(url)
{
	if (!checkStoneSelection())
	{
		alert("Please select stones for all available stone slots.");
	}
	else
	{
		//alert("url " + url);
		var attr = buildAttributeString();
	    document.jeweleryForm.elements['attr'].value =attr;
		//alert("addCustomJewelryToNewCart - storeitemvar " + currentCustomJwl.sivId + " prodid " + currentCustomJwl.prodId + " attr " + attr + " url " + url);
		var urlToSend = url + "&sivId=" +currentCustomJwl.sivId + "&productId="+currentCustomJwl.prodId //+ "&attr="+attr;
		//alert("addToCart - send url: " + urlToSend);
		//alert("addCustomJewelryToNewCart - attr: " + attr);
		document.jeweleryForm.submit();
		//location.href=urlToSend;
	}
}

function buildAttributeString()
{
	var returnStr = 
		   'style*' + $('#style').html() + '|' +
		   'size*' + $('#ringSizeTxt').html() + '|' +
		   'metalColor*' + $('#metalColor').html() + '|' + 
		   'metalType*' + $('#metalType').html() + '|' +
		   'numOfStones*' + $('#stoneCount').html() + '|' +
		   'thumb*'+ createImageURL(100);;
	
    //get number of stones
	var numberOfStones = $('#stoneCount').html();
	
		   
	//add stones
	if ($('#cbStone1Summary').html()!="" && numberOfStones>=1)
	{
		returnStr = returnStr + "|"+"stone1*"+$('#cbStone1Summary').html();
		//alert("stone1");
	}
	if ($('#cbStone2Summary').html()!="" && numberOfStones>=2)
	{
		returnStr = returnStr + "|"+"stone2*"+$('#cbStone2Summary').html();
		//alert("stone2");
	}
	if ($('#cbStone3Summary').html()!="" && numberOfStones>=3)
	{
		returnStr = returnStr + "|"+"stone3*"+$('#cbStone3Summary').html();
		//alert("stone3");
	}
	if ($('#cbStone4Summary').html()!="" && numberOfStones>=4)
	{
		returnStr = returnStr + "|"+"stone4*"+$('#cbStone4Summary').html();
		//alert("stone4");
	}
	if ($('#cbStone5Summary').html()!="" && numberOfStones>=5)
	{
		returnStr = returnStr + "|"+"stone5*"+$('#cbStone5Summary').html();
		//alert("stone5");
	}
	if ($('#cbStone6Summary').html()!="" && numberOfStones>=6)
	{
		returnStr = returnStr + "|"+"stone6*"+$('#cbStone6Summary').html();
		//alert("stone6 ");
	}
	
	//alert("buildAttributeString - " + returnStr);
	return returnStr;
}

function checkStoneSelection()
{
	var result = true;
	//get number of stones
	var numberOfStones = getSelectedItem(document.jeweleryForm.numStoneSelector);
	//check if each stone slot is selected (customized)
	var selectedStoneDropDownBaseName = "cbStone";
	for (i = 1; i <= numberOfStones; i++)
	{
		var selectedStoneDropDownActual = selectedStoneDropDownBaseName + i;
		var selectedStpmeDropDownObject = document.getElementById(selectedStoneDropDownActual);
		var selectedStone = getSelectedItem(selectedStpmeDropDownObject);
		if (selectedStone=="Select Stone")
		{
			result = false;
		}
	}
	return result;
}


/*******************************************************************************
@author: andristo
@date: 08/04/2010
	
The variables and functions below were added to implement birthstone selections
by clicking on birthstones in the lineup. The main idea is to hold the state
of the selected stones in the array currentStones, which stores the names of the
currently selected stones. The state of the select objects in the stone selection 
form is updated based on the array content.
*******************************************************************************/

var defaultNumberOfStones = 3; // Global variable holding the default number of stones  

var currentStoneNumber = 0; // Number of the last selected birthstone;
							// starts from 0 because we use preincrement in the
							// selectStoneRefreshView(stoneName) function
var currentNumberOfStones = 3; // Global variable holding current number of stones

var currentStones = new Array();	// global array holding a list of selectable
									// stone names

// Initialization of the stone array. Called only from the .vm page upon load.
function initStoneArray(){
	//currentNumberOfStones = getSelectedItem(document.jeweleryForm.numStoneSelector);
	currentNumberOfStones = defaultNumberOfStones;
	for(var i=0; i<currentNumberOfStones; i++){
		currentStones[i] = "Select Stone";
	}
	//alert("currentStones = " + currentStones);
}

// The main function that is called when one clicks on a stone in the lineup.
// The parameter stoneName is passed from the HTML form.
function selectStoneRefreshView(stoneName) {
	//alert("array=" + currentStones);
	// pre-increment the current stone number
	if(currentStoneNumber <= currentNumberOfStones-1){
		currentStoneNumber++;
	} else {
		currentStoneNumber=1;
	}
	// update the stones array
	currentStones[currentStoneNumber-1] = stoneName; 
	updateStoneSelectBasedOnArray();
	updateStoneSummaryByStoneNumber(currentStoneNumber);
	previewImageWithEngraving();
	enableControlsEngraving();
}


// This function is currently not used, but may be used in the future to have
// different stone selection/clearing behavior. It is supposed to be called 
// from HTML form instead of updateNumStones(). It updates currentStones() array 
// by either adding/initializing new or removing redundant elements.
function updateStoneArray(){
	var numberOfStones = getSelectedItem(document.jeweleryForm.numStoneSelector);
	//alert("updateStoneArray: num= " + numberOfStones + " curNum=" + currentNumberOfStones + " length =" + currentStones.length);
	if(numberOfStones > currentNumberOfStones){	
		for(var i=currentNumberOfStones; i<numberOfStones; i++){
			//currentStones[i] = "Select Stone";
		}
		currentNumberOfStones = numberOfStones;
	} else if(numberOfStones < currentNumberOfStones){
		for(var i=numberOfStones; i<currentNumberOfStones; i++){
			//currentStones.splice(i,i);
			//alert("spliced " + i + "," + i);
		}
		currentNumberOfStones = numberOfStones;
	}
	//alert("updateStoneArray: num= " + numberOfStones + " curNum=" + currentNumberOfStones + " now length =" + currentStones.length);
}
// This function just updates the currentNumberOfStones. It is called from HTML
// select form upon change in the number of stones.
function updateNumStones(){
	currentNumberOfStones = getSelectedItem(document.jeweleryForm.numStoneSelector);
}

// Updates the current stone number and the corresponding array element.
// Called from HTML from each of the 6 stone selects upon change.
function updateClickableInfo(stoneNumber,stoneName){
	//alert("stoneNumber=" + stoneNumber + " stoneName=" + stoneName);
	currentStoneNumber = stoneNumber;
	currentStones[stoneNumber-1] = stoneName;
}

// Updates values of the select element object according to current state of stoneArray.
function updateStoneSelectBasedOnArray(){
	var num = currentNumberOfStones; //currentStones.length;
	//alert("array=" + currentStones);
	if(num >= 1) {
		setSelectedIndex(document.jeweleryForm.cbStone1,currentStones[0]);
	}
	if(num >= 2) {
		setSelectedIndex(document.jeweleryForm.cbStone2,currentStones[1]);
	}
	if(num >= 3) {
		setSelectedIndex(document.jeweleryForm.cbStone3,currentStones[2]);
	}
	if(num >= 4) {
		setSelectedIndex(document.jeweleryForm.cbStone4,currentStones[3]);
	}
	if(num >= 5) {
		setSelectedIndex(document.jeweleryForm.cbStone5,currentStones[4]);
	}
	if(num >= 6) {
		setSelectedIndex(document.jeweleryForm.cbStone6,currentStones[5]);
	}
}

// This function sets the "Select Stone" option in select objects for all stones.
// Called by resetStoneSelections() upon pressing "Clear" button.
function clearStoneSelect(){
	setSelectedIndex(document.jeweleryForm.cbStone1,"Select Stone");
	setSelectedIndex(document.jeweleryForm.cbStone2,"Select Stone");
	setSelectedIndex(document.jeweleryForm.cbStone3,"Select Stone");
	setSelectedIndex(document.jeweleryForm.cbStone4,"Select Stone");
	setSelectedIndex(document.jeweleryForm.cbStone5,"Select Stone");
	setSelectedIndex(document.jeweleryForm.cbStone6,"Select Stone");
}

// This function is called when the "Clear" button is pressed
function resetStoneSelections(){
	for(var i=0; i<currentStones.length; i++){
		currentStones[i] = "Select Stone";
	}
	currentStoneNumber = 0;
	clearStoneSelect();
	previewImageWithEngraving();
	clearStoneSummary();
}

// This function sets the given element in a select statement as "selected"
function setSelectedIndex(sel, val) {
	for ( var i = 0; i < sel.options.length; i++ ) {
       	if ( sel.options[i].value == val ) {
           	sel.options[i].selected = true;
           	return;
       	}
   	}
}

// This function updates stone summary for a given stone number
function updateStoneSummaryByStoneNumber(stoneNumber){
	if(stoneNumber == 1){
		updateStoneSummary(document.jeweleryForm.cbStone1);
	}
	if(stoneNumber == 2){
		updateStoneSummary(document.jeweleryForm.cbStone2);
	}
	if(stoneNumber == 3){
		updateStoneSummary(document.jeweleryForm.cbStone3);
	}
	if(stoneNumber == 4){
		updateStoneSummary(document.jeweleryForm.cbStone4);
	}
	if(stoneNumber == 5){
		updateStoneSummary(document.jeweleryForm.cbStone5);
	}
	if(stoneNumber == 6){
		updateStoneSummary(document.jeweleryForm.cbStone6);
	}
}

// This function hides the stone summary - currently not used
function hideStoneSummary(){
	// hide stone summary
	for (var i=1; i<=6; i++ ) {
	//for (var i=1; i<=currentNumberOfStones; i++ ) {
		var x = "#cbStone" + i + "Summary";
		var tempObj = $(x);
		tempObj.hide();
	}
}

// This function clears the stone summary. It is called by  
// resetStoneSelections() upon pressing the "Clear" button.
function clearStoneSummary(){
	// clear stone summary
	for (var i=1; i<=6; i++ ) {
		var x = "#cbStone" + i + "Summary";
		$(x).html("");
	}
}

// Sets the setDefaultNumberOfStones to the value passed from the
// http get parameter
function setDefaultNumberOfStones(numStones){
	defaultNumberOfStones = numStones;
	//alert("defaultNumberOfStones=" + defaultNumberOfStones);
}

