// bag_designer.js
// JS for bag designer
var ImageURLCounter = 1;
var incomingData = "";

window.addEvent('domready', function(){
  //alert('the dom is ready');
  	var sQuery = window.location.search;
	
  
  	// test pre-load images
	preLoadImages( imagearray, loadedImages, ChosenStyle );
  
  	ajaxloaderon(); //turn loading icon ON
	
	//simpleAjax( 'http://oneybags.axceltest.com/bag_designer_styles.htm', 'BagAttributeArea');
	centerAnElement('CoordinatingFabricDiv');

  
});


function simpleAjax( url, update_id, method, complete ) {
	if(method==null) method = 'post';
	if(complete==null) ajaxoptions = {method: method, update: $(update_id)};
	else {
		ajaxoptions = {
			method: method, 
			update: $(update_id), 
			onComplete: function() {
							//errorMsg("onCompleted called: " + complete);
							complete();
						}
		};
	}
	
	new Ajax(url, ajaxoptions).request();
}//end function

function simpleChange( update_id, update_data ) {
	if($(update_id)) $(update_id).innerHTML = update_data;
}//end function


// Testing image pre-loading (assets)
function preLoadImages( imagearray, loadedImages, ChosenStyle ) {
			if(ChosenStyle!=null) {
				selectBagStyle( ChosenStyle, "name" );
				confirmBagStyle();
			} else {
				simpleAjax( 'http://www.oneybags.com/bag_designer_styles.htm', 'BagAttributeArea', 'post', ajaxloaderoff);
			}
			//ajaxloaderoff(); //turn loading icon OFF
			preLoadFabrics( fabricarray, loadedFabricImages ); //start pre-loading the bag fabrics
			simpleChange( 'StepInstructionsTitleArea', 'SELECT YOUR BAG STYLE' );
//		}
//	});
}//end function
function preLoadFabrics( fabricsarray, loadedFabricImages ) {
	new Asset.images(fabricsarray, {
		onProgress: function(i) {
			loadedFabricImages[i] = this;
			errorMsg('Finished preloading '+this.src+'.');
		},
		onComplete: function(){
			//alert('all images loaded!');
			//simpleAjax( 'http://oneybags.axceltest.com/bag_designer_styles.htm', 'BagAttributeArea');
			errorMsg('Finished preloading fabrics.');
		}
	});
}//end function

function CallAjaxImage( url, image, staticURL, method, xmlData ) {
	if(method==null) method = 'post';
	ajaxoptions = {
		method: method, 
		onComplete: function() {

						var responseImg = (this.response.text != "") ? staticURL + this.response.text : "http://www.oneybags.com/images/preview_not_available.jpg";
						var thisIsMainImage = false;

						//errorMsg("onCompleted called: " + complete);
						if(typeof image == "object") {
							for(var i=0; i<image.length; i++) {
								$(image[i]).src = responseImg;

								if(image[i]=="MainImage") thisIsMainImage = true;
							}							
						} else {
							$(image).src = responseImg;
							
							if(image=="MainImage") thisIsMainImage = true;
						}
						
						if(thisIsMainImage) incomingData = this.response.text;
						
						centerImage( $('MainImage') );
						
					},
		data: xmlData
//		onFailure: function() {
//						alert("Couldn't find the image!");
//			
//					}
//		onSuccess:	function() {
//						alert("hey now!!!: " + this.response);
//					}
	};
	
	var ImageAjax = new Ajax(url, ajaxoptions);
	//ImageAjax.data = xmlData;
	
	ImageAjax.request();
}//end function

function selectBagStyle( styleID, styleName ) {
	//store our bag style id
	CurrentBag = styleID;

	//selectStyleInfo(styleName);
	simpleChange( 'BagStyleNameArea', styleName );
	
	simpleAjax( 'http://www.oneybags.com/bag_designer_baginfo.htm?BagID='+CurrentBag+'&InfoType=long_description', 'StyleInfoTextDiv');

//alert("blah, blah");

	if($('MainStyleImg')) CallAjaxImage( 'http://www.oneybags.com/bag_designer_baginfo.htm?BagID='+styleID +'&ImageType=main', 'MainStyleImg', 'http://www.oneybags.com/dbImages/medium/' );

	$('MainImage').src = 'http://www.oneybags.com/dbImages/bagstyleimages/' + ChosenStyleName + '_canvas.jpg';
	
	//CallAjaxImage( 'http://oneybags.axceltest.com/bag_designer_baginfo.htm?BagID='+styleID +'&ImageType=none', 'MainImage', 'http://oneybags.axceltest.com/dbImages/bagstyleimages/' + ChosenStyleName + '_canvas.jpg' );
	
	//centerImage( $('MainImage') );

	//simpleAjax( 'http://oneybags.axceltest.com/bag_designer_baginfo.htm?BagID='+CurrentBag+'&ImageType=main', 'SetMainImageBagStyle');

	//changeMainImage( src );
}//end function

// Testing "select bag style" proceedure
function confirmBagStyle() {
	//increment our step
	CurrentStep = 1;

	//we might be starting over.  In that case, reset highest step
	HighestStep = 1;
	
	//current price back to zero
	$('CurrentPrice').innerHTML = 0;
	
	//updateCurrentPrice( CurrentStep );
	
	//store our bag style id
	//CurrentBag = styleID;
	
	ajaxloaderon(); //set ajax loader to ON
	
	//reload Step 1 with new bag style
	//simpleAjax( 'http://oneybags.axceltest.com/bag_designer_steps.htm?BagID='+styleID+'&Step=1', 'BagStepsArea1');

	
	loadAllSteps( CurrentBag );
	

}//end function

// Testing populate all steps
function loadAllSteps( styleID ) {
	simpleAjax( 'http://www.oneybags.com/bag_designer_steps.htm?BagID='+styleID+'&Step=1&CurrentStep=2', 'BagStepsArea1', 'post', onFirstStepLoaded );
	simpleAjax( 'http://www.oneybags.com/bag_designer_steps.htm?BagID='+styleID+'&Step=2&CurrentStep=2', 'BagStepsArea2', 'post', gotoStep);
	simpleAjax( 'http://www.oneybags.com/bag_designer_steps.htm?BagID='+styleID+'&Step=3', 'BagStepsArea3');
	simpleAjax( 'http://www.oneybags.com/bag_designer_steps.htm?BagID='+styleID+'&Step=4', 'BagStepsArea4');
	simpleAjax( 'http://www.oneybags.com/bag_designer_steps.htm?BagID='+styleID+'&Step=5', 'BagStepsArea5');
	simpleAjax( 'http://www.oneybags.com/bag_designer_steps.htm?BagID='+styleID+'&Step=6', 'BagStepsArea6');
	simpleAjax( 'http://www.oneybags.com/bag_designer_steps.htm?BagID='+styleID+'&Step=7', 'BagStepsArea7');
	simpleAjax( 'http://www.oneybags.com/bag_designer_steps.htm?BagID='+styleID+'&Step=8', 'BagStepsArea8');
	simpleAjax( 'http://www.oneybags.com/bag_designer_steps.htm?BagID='+styleID+'&Step=9', 'BagStepsArea9');
}//end function 

function onFirstStepLoaded() {
	// once the first step has been loaded we can:
	
	//use the title information to populate the additional bag style title area
	simpleChange( 'BagStyleNameArea', $('BagStyleName').innerHTML );
	//use the price information to update the total price
	updateCurrentPrice( 1 );
	
	OriginalPrice = $('BagStepPrice' + CurrentStep).value.toFloat().round(2);
}//end function


function gotoStep( stepNum ) {
	
	errorMsg('gotoStep('+stepNum+') called');
	errorMsg('CurrentStep: ' + CurrentStep + ", gotoStep: " + stepNum + ', HighestStep: ' + HighestStep);
	if((stepNum-1) > HighestStep ) errorMsg('(stepNum-1) > HighestStep   IS TRUE');
	if(stepNum == CurrentStep) errorMsg('stepNum == CurrentStep   IS TRUE');
	if(isLastStep(stepNum-1)) errorMsg('isLastStep(stepNum-1)   IS TRUE');
	
	if(stepNum==null) stepNum = CurrentStep+1;


	//if we've selected current step or greater than highest step (excluding the very next step), do nothing
	if((stepNum-1) > HighestStep || stepNum == CurrentStep || isLastStep(stepNum-1)) return;
	//if prompted for a fabric, don't go forward until we pick one
	if( $('BagStepImage'+CurrentStep) && $('BagStepImage'+CurrentStep).src=="" && stepNum!=1 ) {
		alert("Please select a fabric before moving to the next step.");
		return;
	}
	
	//handle loader image	
	if($('BagStepSelect' + stepNum)) $('BagAttributeLoadingImg').style.display = 'none'; //turn off the loader image for select steps
	ajaxloaderon(); //set ajax loader to ON


	// make sure description area is off
	$('DescriptionTitleArea').style.display = 'none';
	$('DescriptionTextArea').style.display = 'none';
	$('BagStepFabricLink').style.display = 'none';


	// Update the total price from prev. step. (unless this was the first step.  That's already been taken care of)
	if(CurrentStep>1) updateCurrentPrice( CurrentStep );
    
	if(isLastStep(stepNum+1) && stepNum!=2) {
		$('nextLink').innerHTML = "ADD TO CART";
		if( $('addToCartLink').innerHTML == "" ) 
			$('addToCartLink').innerHTML = '<table width="160" border="0" cellspacing="3" cellpadding="0" class="maintext"><tr><td width="15" align="left"><img width="15" height="15" src="http://oneybags.axceltest.com/images/no_before0' + (HighestStep+2) + '.gif" id="BagStepIcon' + (HighestStep+2) + '" onclick="goNext();" /></td><td width="145" align="left"><a href="javascript:goNext();" class="ds">MY BAG IS COMPLETE</a></td></tr></table>'; //<a href="javascript:goNext();" class="ds">MY BAG IS COMPLETE</a>';
	} else if( isLastStep(stepNum) ) {
		$('nextLink').innerHTML = "";
	} else {
		if($('nextLink')) $('nextLink').innerHTML = "NEXT"; 
		$('addToCartLink').innerHTML = '';
	}


	//change step instructions/title
	if(!isLastStep(stepNum)) { 
		nextStepTitle = 'SELECT YOUR ' + $('BagStepTitle'+stepNum).innerHTML;
		simpleChange( 'StepInstructionsTitleArea', nextStepTitle );
	}
	
	// turn prev step icon OFF, turn this step ON
	if($('BagStepIcon' + CurrentStep)) $('BagStepIcon' + CurrentStep).src = '/images/no_before0'+CurrentStep+'.gif';
	if(!isLastStep(stepNum)) $('BagStepIcon' + stepNum).src = '/images/no_after0'+stepNum+'.gif';

	//if($('AltBagRecipe' + stepNum) && $('AltBagRecipe' + stepNum).value!="") $('AltViewLink').style.display = '';

	
	if (stepNum == 1) { //if this is step one, load all bag styles
		window.location = 'http://www.oneybags.com/bag_designer_tool_firststep.htm';
		//simpleAjax( 'http://oneybags.axceltest.com/bag_designer_styles.htm', 'BagAttributeArea', 'post', ajaxloaderoff);	
	} else if( isLastStep(stepNum) ) { //the final step
		simpleAjax( 'http://www.oneybags.com/bag_designer_final.htm?BagStyle='+CurrentBag, 'BagAttributeArea', 'post', prepareCartVars);
		//if($('AltBagRecipe' + CurrentStep) && $('AltBagRecipe' + CurrentStep).value!="") $('AltViewLink').style.display = '';
	} else if( $('BagStepSwatch'+stepNum) ) { // else, load all fabrics based on this step
		simpleAjax( 'http://www.oneybags.com/bag_designer_fabrics.htm?SwatchSet='+$('BagStepSwatch'+stepNum).value+'&NoFabric='+$('BagStepNone'+stepNum).value, 'BagAttributeArea', 'post', ajaxloaderoff);
	} else if($('BagStepSelect' + stepNum)) { // else , load select attributes
		simpleAjax( 'http://www.oneybags.com/bag_designer_attribs.htm?ID='+$('BagStepAttribID'+stepNum).value, 'BagAttributeArea', 'post', ajaxloaderoff);
	}


	//changeMainImage();

	// change the current step number to this one
	CurrentStep = stepNum;
	if(CurrentStep>HighestStep) HighestStep = CurrentStep;

}//end function

function changeAllStepIcons( position ) {
	for(var i=1; i<10; i++) {
		$('BagStepIcon' + i).src = (position=="on") ? '/images/no_after0'+i+'.gif' : '/images/no_before0'+i+'.gif';
	}//end for
}//end function

function errorMsg( msg ) {
	$('debugdiv').innerHTML = msg + "<br>" + $('debugdiv').innerHTML;
}

function ajaxloaderon() { 
	$('AjaxLoadTable').style.display = ''; 
}
function ajaxloaderoff() { 
	$('BagAttributeLoadingImg').style.display = ''; $('AjaxLoadTable').style.display = 'none'; 
}


function selectSwatch( swatchID, swatchName, swatchImg, overridePrice ) {
	// change step details	
	if($('BagStepImage' + CurrentStep)) { 
		$('BagStepImage' + CurrentStep).src = swatchImg;
		$('BagStepImage' + CurrentStep).style.display = '';
	} 
	if(swatchName) $('BagStepText' + CurrentStep).innerHTML = swatchName;
	
	// change description text
	if( $('BagStepSwatch'+CurrentStep).value == "FABRICS" ) { 
		$('DescriptionTitleArea').style.display = '';
		$('DescriptionTextArea').style.display = '';
		$('BagStepFabricLink').style.display = '';
		simpleChange( 'DescriptionTitleArea', swatchName + ' description:' );
		simpleAjax( 'http://www.oneybags.com/bag_designer_fabricinfo.htm?FabricID='+swatchID+'&InfoType=description', 'DescriptionTextArea');
	}
	
	$('BagStepFabricLink').innerHTML = '<img width="8" height="8" src="/images/arrow.jpg"> suggested coordinates';
	$('BagStepFabricLink').onclick = function() {
														ajaxloaderon();
														displayFloatingLayer('CoordinatingFabricDiv');
														simpleAjax( 'http://www.oneybags.com/bag_designer_fabrics.htm?SwatchColors='+swatchID+'&Columns=4', 'CoordinatingFabricArea', 'post', ajaxloaderoff);
														$('CoordinatingParentImg').src = swatchImg;
													};
													
	//override the price for this fabric
	if(overridePrice!=null) {
		$('BagStepPrice'+CurrentStep).value = overridePrice;	
	}
		
	//for "none" option, kill the AltLink
	if(swatchID==-1) { 
		if( $('AltLink' + CurrentStep) ) $('AltLink' + CurrentStep).style.display = 'none';
	} else {
		if( $('AltLink' + CurrentStep) ) $('AltLink' + CurrentStep).style.display = '';
	}
	
	$('BagStepFabricID' + CurrentStep).value = swatchID;											

	changeMainImage();
}//end function

function selectStyleInfo( styleName ) {
	if(CurrentBag!=-1) {
		
		CurrentBagName = (styleName==null) ? $('BagStyleName').innerHTML : styleName;
		
		$('DescriptionTitleArea').style.display = '';
		simpleChange( 'DescriptionTitleArea', CurrentBagName + ' Style Info:' );
		simpleAjax( 'http://www.oneybags.com/bag_designer_baginfo.htm?BagID='+CurrentBag+'&InfoType=long_description', 'StyleInfoDiv');
		//$('StyleInfoDiv').style.display = 'block';
		
		//update the main image body with this bag style image
		
		new Ajax('http://www.oneybags.com/bag_designer_baginfo.htm?BagID='+CurrentBag+'&ImageType=main', {
		method: 'get',
		evalResponse: $('log')
	}).request();
	}
}//end function
	
	
function displayFloatingLayer( layerName ) {
	//first, hide all functions
	$$('.floatinglayers','.floatinglayers_large').setStyle('display','none');
	
	//then, show this one
	$(layerName).style.display = 'block';
}//end function

function isLastStep( teststep ) {
	//if step == 10 OR if prev step contains a table, but this step does not
	return (teststep==10 || ( $('BagStepTable'+(teststep-1)) && $('BagStepTable'+teststep)==null )) ? true : false;
}//end function

function prepareCartVars() {
	ajaxloaderoff();
	
	//start with name for this bag style
	finalName = $('BagStyleName').innerHTML;
	finalPrice = 0.00;
	
	//spacingStr = "<br>&nbsp;&nbsp;&nbsp;&bull;&nbsp;";
	spacingStr = "; ";
	
	//foreach attribute...
	$$('.bag_step_table').each(function(el){
		//obtain step number
		s = el.getAttribute('id');
		s = s.substr( (s.length-1),1);
										
		//concat name: value to finalName
		finalName += spacingStr + $('BagStepTitle'+s).innerHTML.toLowerCase() + ": " + $('BagStepText'+s).innerHTML.toLowerCase();
		
		//add price to finalPrice
		finalPrice += parseFloat($('BagStepPrice'+s).value);
	});

	
	//update cart vars
	//$('_item_desc').value = "<span style=\"text-decoration:none;\">" + finalName + "</span>";
	$('_item_desc').value = finalName;
	$('_item_unitPrice').value = $('CurrentPrice').innerHTML.toFloat();
	//$('prodPrice').innerHTML = finalPrice.toFixed(0);
		
		errorMsg("_item_desc = " + $('_item_desc').value);
		errorMsg("_item_unitPrice = "  + $('_item_unitPrice').value);
		
}//end function

function changeFromSelect( selectedObj ) {
	simpleChange( 'BagStepText'+CurrentStep, selectedObj.text );
	$('BagStepPrice'+CurrentStep).value = selectedObj.value;
}//end function

function updateCurrentPrice( stepOfPrice ) {
	//if((stepOfPrice==1 || stepOfPrice==HighestStep) && $('BagStepPrice' + stepOfPrice)) {
		
	//currentPrice = $('CurrentPrice').innerHTML.toFloat();	
	//alert(currentPrice);
	tempPrice = 0.00; //currentPrice; //(currentPrice!=null) ? currentPrice : 0.00;	
		
	// get first step, too
	tempPriceObj = $('BagStepPrice1');
	if(tempPriceObj.value != "") tempPrice += tempPriceObj.value.toFloat().round(2);

	//foreach step...grab fabric id's
	$$('.bag_step_table').each(function(el){

		//obtain step number
		s = el.getAttribute('id');
		s = s.substr( (s.length-1),1);
		
		tempPriceObj = $('BagStepPrice' + s);
		//alert( "$('BagStepPrice" + s + "')" + tempPriceObj.value );								
		//concat name: value to finalName
		if(tempPriceObj.value != "") tempPrice += tempPriceObj.value.toFloat().round(2);
	}); //end loop through each step
		
	$('CurrentPrice').innerHTML = tempPrice;	
	
	if(tempPrice==0) $('CurrentPriceSpan').style.display = 'none';
	else $('CurrentPriceSpan').style.display = '';

		
//	if( $('BagStepPrice' + stepOfPrice) ) {
//		var newPrice = $('CurrentPrice').innerHTML.toFloat() + $('BagStepPrice' + stepOfPrice).value.toFloat().round(2);
//		$('CurrentPrice').innerHTML = newPrice;
//		
//		if(newPrice==0) $('CurrentPriceSpan').style.display = 'none';
//		else $('CurrentPriceSpan').style.display = '';
//	}//end function
}//end function

function goNext() {
	if(CurrentStep==1) confirmBagStyle();
	else gotoStep();
}//end function 

function goPrev() {
	if(CurrentStep>1) gotoStep(CurrentStep-1);
}//end function 


function changeMainImage() {

	var sendXML = generateIMGenXML();
	if(sendXML===false) return false;
	
	XMLdata = Object.toQueryString({SiteID: "1", ImageXML: sendXML});
	
	errorMsg(XMLdata);

	$('MainImage').src = '/images/ajax-loader-medium.gif';

	var changeArray = new Array("MainImage","EnlargedViewImage");
	CallAjaxImage( "http://www.oneybags.com/IGpassthru.php", changeArray, "http://www.serverapp.net/imagegen/IGtestRetrieve.php?SiteID=1&ImageHash=", 'post', XMLdata );
	//CallAjaxImage( "http://www.oneybags.com/IGControl.php", changeArray, "http://oneyimage"+returnNextImageURLCount()+".com/IGtestRetrieve.php?SiteID=1&ImageHash=", 'post', XMLdata );
	

}//end function

function changeToModelImage() {
	displayFloatingLayer('ModelImageViewDiv');
	$('ModelImage').src = '/images/ajax-loader-medium.gif';
	
	CallAjaxImage( 'http://www.oneybags.com/bag_designer_baginfo.htm?BagID='+CurrentBag+'&ImageType=main', 'ModelImage', 'http://www.oneybags.com/dbImages/medium/' );

}//end function

function returnNextImageURLCount() {
	ImageURLCounter++;
	if(ImageURLCounter > 4) {
		ImageURLCounter = 1;
	} 

	return ImageURLCounter;
}

function updateAltImage() {
		var sendXML = generateIMGenXML("alt");
		if(sendXML===false) return false;
		
		XMLdata = Object.toQueryString({SiteID: "1", ImageXML: sendXML});
		
		errorMsg(XMLdata);
		
		displayFloatingLayer('AlternateViewDiv');
		$('AlternateViewImage').src = '/images/ajax-loader-medium.gif';
		
		//var changeArray = new Array("MainImage","EnlargedViewImage");
		
		CallAjaxImage( "http://www.oneybags.com/IGpassthru.php", "AlternateViewImage", "http://www.serverapp.net/imagegen/IGtestRetrieve.php?SiteID=1&ImageHash=", 'post', XMLdata );
}//end function 

function centerAnElement( ID ) {

	var myObj = $(ID);
	
	var thisObjWidth = myObj.getStyle('width');
	var thisObjHeight = myObj.getStyle('height');
	var thisWindowHeight = window.getScrollHeight();
	var thisWindowWidth = window.getScrollWidth();


	var newTop = (thisWindowHeight/2) - (thisObjHeight.substr(0,thisObjHeight.length-2)/2);
	var newLeft = (thisWindowWidth/2) - (thisObjWidth.substr(0,thisObjWidth.length-2)/2);
	
	myObj.setStyle('top', newTop+'px');
	myObj.setStyle('left', newLeft+'px');	

//alert("w: " + newLeft+'px' + ", h: " + newTop+'px');
	
}//end function


function customChangeStepRecipe( customRecipe, recipeStep ) {
	if( $('BagStepRecipes'+recipeStep) ) {
		$('BagStepRecipes'+recipeStep).value = customRecipe;
	}//end if
} //end function

function centerImage( imgObj ) {
	
	var thisObjWidth = imgObj.getStyle('width');
	var thisObjHeight = imgObj.getStyle('height');
	thisObjParent = imgObj.getParent();
	var thisObjParentHeight = thisObjParent.getStyle('width');
	var thisObjParentWidth = thisObjParent.getStyle('height');

//errorMsg("w: " + thisObjWidth + ", h: " + thisObjHeight);
//errorMsg("w: " + thisObjParentWidth + ", h: " + thisObjParentHeight);

	var newTop = ( thisObjParentHeight.substr(0,thisObjParentHeight.length-2) /2) - (thisObjHeight.substr(0,thisObjHeight.length-2)/2);
	var newLeft = ( thisObjParentWidth.substr(0,thisObjParentWidth.length-2) /2) - (thisObjWidth.substr(0,thisObjWidth.length-2)/2);
	
	imgObj.setStyle('padding-top', newTop+'px');
	imgObj.setStyle('padding-left', newLeft+'px');	

errorMsg("w: " + newLeft+'px' + ", h: " + newTop+'px');
	
}//end function
