//Initialize global variables
var FABRIC_ID = null; //stores id of selected fabric
measureRowArray = new Array(1,0,0,0,0,0,0,0,0,0); //keeps track of curtains without tracks
var validationErrors;
var NUMBER_OF_STYLES = 6;
var SETUP_TYPE = 1;

/***********************************************************************************************
* GENERAL PAGE DISPLAY FUNCTIONS
***********************************************************************************************/

// selectSetup()
// Selects the type of set up for the cubicle and shower curtain page
// Changes the color of the selected set up and hides/shows the track measurement block
// args: num - the type of set up that is selected 1-curtains and tracks, 2-just curtains, 3-just tracks (redirects to track page)
function selectSetup(num){	
	var genButtons = new Array();

	if( num == 1 ){
		//track and curtains
		$('setupType1').className = "setupSelected";
		$('setupType2').className = "setupUnselected";
		$('setupLink1').innerHTML = "<b>Selected</b>";
		$('setupLink2').innerHTML = "<b>Click Here</b>";
		
		// Swap next step button
		$('showStep3').style.display = "inline";
		$('showStep4').style.display = "none";
		
		// Show the generate buttons
		$$('.trackSetup').setStyle("display","inline");
		$$('.trackSetupAlt').setStyle("display","none");
		
		// Change next button color
		$('firstNextBtn').src = "/images/graphics/next-button-red.gif";
		
		this.innerHTML = "Selected";
		
		SETUP_TYPE = 1;
	}else if( num == 2){
		//only curtains
		$('setupType1').className = "setupUnselected";
		$('setupType2').className = "setupSelected";
		$('setupLink1').innerHTML = "<b>Click Here</b>";
		$('setupLink2').innerHTML = "<b>Selected</b>";
		
		// Swap next step button
		$('showStep3').style.display = "none";
		$('showStep4').style.display = "inline";
		
		// Hide the generate measurement buttons
		$$('.trackSetup').setStyle("display","none");
		$$('.trackSetupAlt').setStyle("display","inline");
		
		// Change next button color
		$('firstNextBtn').src = "/images/graphics/next-button-red.gif";
		
		this.innerHTML = "Selected";
		
		SETUP_TYPE = 2;
	}else{
		var tracks = confirm("Are you sure you only want tracks? You will lose all the information you have entered on this page.");
		if( tracks ){ document.write("<script>window.location='/s/curtain-track-hardware'</script>"); }
	}
}


// showHideSteps()
// Shows or hides the step that is clicked
// args: num - the number of the step
//       text - a reference to the link that was clicked to call this function
function showHideSteps(num){
	if( $("stepsContainer1") ){ $("stepsContainer1").style.display = "none"; }
	if( $("stepsContainer2") ){ $("stepsContainer2").style.display = "none"; }
	if( $("stepsContainer3") ){ $("stepsContainer3").style.display = "none"; }
	if( $("stepsContainer4") ){ $("stepsContainer4").style.display = "none"; }
	if( $("stepsContainer5") ){ $("stepsContainer5").style.display = "none"; }
	if( $("stepsContainer"+num) ){ 
		$("stepsContainer"+num).style.display = "inline"; 
	}
}

// showStep()
// Shows the given step
// args: num - the number of the step
function showStep(num){
	if( $("stepsHeader"+num) ){
		$("stepsHeader"+num).innerHTML = $("stepsHeader"+num).innerHTML.replace("u.gif","d.gif");
		showDivs("stepsContainer"+num);
	}
}

// hideStep()
// Hides the given step
// args: num - the number of the step
function hideStep(num){
	if( $("stepsHeader"+num) ){
		$("stepsHeader"+num).innerHTML =$("stepsHeader"+num).innerHTML.replace("d.gif","u.gif");
		hideDivs("stepsContainer"+num);
	}
}

// selectTrackKits
// Redirect to the track kits page
function selectTrackKits(){
	var tracks = confirm("Are you sure you want a track kit? You will lose all the information you have entered on this page.");
	if( tracks ){ document.write("<script>window.location='/IFC-98-Track---IFC-100-Carrier/41960'</script>"); }	
}

/***********************************************************************************************
* END GENERAL PAGE DISPLAY FUNCTIONS
***********************************************************************************************/

/**************************************************************************************
* VALIDATION & SUBMISSION FUNCTIONS
**************************************************************************************/

// processCurtainsForm() - used for custom curtains page
// Processess order form data.  Retreives all info, validates it then
// either prints an message about validation or runs a AJAX call to add 
// the order to the cart
function processCurtainsForm(type){
	var counter = 0;
	var trackFlag = false;
	var curtainData = null; 
	var trackData = null; 
	var errorBlock = "";
	validationErrors = new Array();
	
	//Validate Fabric Selection
	if( FABRIC_ID == null && type != 'blackout' ){
		alert("ALERT: You must select a fabric!");
		if($('stepsContainer2').style.display == 'none'){ showHideSteps(2); }
	} else {
		
		//Get all active Rows
		activeCurtainIDs = getActiveRows();
		
		////////////////////////////////////////////////////////////
		// RETRIEVE AND VALIDATE TRACK AND CURTAIN DATA
		////////////////////////////////////////////////////////////
		if( SETUP_TYPE == 2 ){ //Get curtains data and validate
			curtainData = getCurtainData(activeCurtainIDs);
			validateCurtains(curtainData,type);
		} else {//Get curtains and track data and validate 
			trackData = getTrackData(activeCurtainIDs);
			validateTracks(trackData,type);
			curtainData = getCurtainData(activeCurtainIDs);	
			validateCurtains(curtainData,type);
		}
		///////////////////////////////////////////////////////////
		// END RETRIEVE AND VALIDATE TRACK AND CURTAIN DATA
		///////////////////////////////////////////////////////////
		
		
		///////////////////////////////////////////////////////////
		// SET UP VALIDATION ERRORS BLOCK OR ADD ITEMS TO CART
		///////////////////////////////////////////////////////////
		if( validationErrors.length > 0 ){
			for(var i=0;i<validationErrors.length;i++){ errorBlock += "<li>"+validationErrors[i]+"</li>"; }
			showDivs('validationErrors');
			$('validationErrors').innerHTML = "<h4 id='errorHeader'>Alert! You Must Correct the Following Errors:</h4><ol>" + errorBlock + "</ol>";
		} else { // No validation errors submit to cart
			if( type == 'blackout' ){
				addBlackoutToCart(curtainData,trackData); 
			} else {
				addCurtainsToCart(curtainData,trackData); 	
				
				//Switch Setup Type to Curtain and Track
				selectSetup(1);
			}
			
			//Reset page and display curtains added message
			//resetPage();
			
			//Redirect to shopping cart
			document.write("<script>window.location='/cart.php'</script>");
		}
		///////////////////////////////////////////////////////////
		// END SET UP VALIDATION ERRORS BLOCK OR ADD ITEMS TO CART
		///////////////////////////////////////////////////////////
	}
}


// processTracksForm() - used for custom tracks page
// Processess order form data.  Retreives all info, validates it then
// either prints an message about validation or runs a AJAX call to add 
// the order to the cart
function processTracksForm(){
	validationErrors = new Array();
	var counter = 0;
	var errorBlock = "";
	
	//Get all active Rows
	activeTrackIDs = getActiveRows();
	
	//Retrieve and validate track information
	trackData = getTrackData(activeTrackIDs);
	validateTracks(trackData,"track");
	
	//set up validation errors or submit tracks to cart 
	if( validationErrors.length > 0 ){
		for(var i=0;i<validationErrors.length;i++){ errorBlock += "<li>"+validationErrors[i]+"</li>"; }
		showDivs('validationErrors');
		$('validationErrors').innerHTML = "<h4 id='errorHeader'>Alert! You Must Correct the Following Errors:</h4><ol>" + errorBlock + "</ol>";
	} else {
		//show the loading screen
		showDivs('validationErrors');
		$("validationErrors").innerHTML = "<br /><center><img src='/images/graphics/page-loading.gif' alt='Loading...' /><br />Building Estimate...</center><br />";
		$("loadingText").innerHTML = "Building Estimate";
		$("loading").style.top = getScrollY() + "px";
		//$("loading").className = "loading-visible";
		$("loading").setStyle("display","block");
	
		//Add the tracks to the cart
		addTracksToCart(trackData);
		
		//Reset the track form
		//resetTracks();
		
		//Redirect to shopping cart
		document.write("<script>window.location='/cart.php'</script>");
		
		//Hide the loading screen
		//$('validationErrors').innerHTML = "<h4 id='itemsAdded'>Your estimate was submitted. <a href='/cart.php' title='view cart'>View Cart <img border='0' src='/images/graphics/cart.gif' /></a></h4>";
		//$("loading").className = "loading-invisible";
		//$("loading").setStyle("display","none");
	}
}

function processFabricForm(){
	var fabricArgs = new2DArray(3,2);
	var length = itemAdded = errorBlock = "";
	validationErrors = new Array();
	
	//Validate Fabric Selection
	if( FABRIC_ID == null ){
		alert("ALERT: You must select a fabric!");
		showStep(1); 
	} else {
		//Get and validate fabric length
		length = $('lengthYrds').value;
		if( !isNumeric(length) ){ validationErrors[validationErrors.length] = "<b class='required'>Invalid Length.</b> Must be greater than zero and contain only numerical characters 0-9.";  }
		if( length < 3 ){ validationErrors[validationErrors.length] = "<b class='required'>Invalid Length.</b> Length must be at least 3 yards."; }
	
		//Print validation errors or add fabric to cart
		if( validationErrors.length > 0 ){
			for(var i=0;i<validationErrors.length;i++){ errorBlock += "<li>"+validationErrors[i]+"</li>"; }
			showDivs('validationErrors');
			$('validationErrors').innerHTML = "<h4 id='errorHeader'>Alert! You Must Correct the Following Errors:</h4><ol>" + errorBlock + "</ol>";
		} else {
			//show the loading screen
			showDivs('validationErrors');
			$("validationErrors").innerHTML = "<br /><center><img src='/images/graphics/page-loading.gif' alt='Loading...' /><br />Building Estimate...</center><br />";
			$("loadingText").innerHTML = "Building Estimate";
			$("loading").style.top = getScrollY() + "px";
			//$("loading").className = "loading-visible";
			$("loading").setStyle("display","block");
			
			//Set up arguments for add to cart
			fabricArgs[0][0] = "item_id";
			fabricArgs[0][1] = $('itemID').value;
			fabricArgs[1][0] = "fabric_id";
			fabricArgs[1][1] = FABRIC_ID;
			fabricArgs[2][0] = "length";
			fabricArgs[2][1] = length;
			
			//run ajax to add item to cart
			itemAdded = runAJAXsync('curtains_ajax',fabricArgs);
			
			if( itemAdded != "Item Added to Cart" ){
				$('validationErrors').innerHTML = "<center><h4 id='itemsAdded'>ERROR: Unable to add your fabric to the cart.</h4> Refresh the page and try again if the problem persists call 800-791-2946.</center>";
			} else {
				/*
				//Reset page
				FABRIC_ID = null;
				$('lengthYrds').value = "";
				showStep(1);
				hideStep(2);
				showDivs('selectStyle');
				hideDivs('patternBlock');
				hideDivs('colorBlock');
				
				//Hide the loading screen
				$('validationErrors').innerHTML = "<h4 id='itemsAdded'>Your estimate was submitted. <a href='/cart.php' title='view cart'>View Cart <img border='0' src='/images/graphics/cart.gif' /></a></h4>";
				//$("loading").className = "loading-invisible";
				$("loading").setStyle("display","none");
				*/
				//Redirect to shopping cart
				document.write("<script>window.location='/cart.php'</script>");
			}
		}
	}
}


// getCurtainData()
// Retrieves all curtain data
// args: activeIDs - an array of all active curtain ids, flag - a boolean true if there is tracks false otherwise
// returns: a 2d array off all the curtain data
function getCurtainData(activeIDs){
	var returnArray = new Array(activeIDs.length);
	var ctfHeight, hoFloor, width, qty, banding, tiebacks, mesh, itemID, curtainPrice;
	var counter = 0;
	
	//loop through elements and get values
	for(var i=0;i<activeIDs.length;i++){
		id = activeIDs[i];
		ctfHeight = $('height'+(id)).value; 
		hoFloor = $('offFloor'+(id)).value;
		width = $('width'+(id)).value;
		qty = $('qty'+(id)).value;
		
		if( $('stdCurtainCheck') ){
			curtainPrice = $('curtainPrice'+(id)).value;
		} else {
			curtainPrice = 0.00;	
		}
		
		//add values to an array
		returnArray[i] = new Array(id,ctfHeight,hoFloor,width,qty,curtainPrice);
	}
	
	return returnArray;
}

// getTrackData()
// Retrieves all track data
// args: activeIDs - an array of all active curtain ids
// returns: a 2d array off all the track data
function getTrackData(activeIDs){
	var returnArray = new Array(activeIDs.length);
	var trackType,A,B,C,qty,trackPrice,onePiece,id,carriers = "";
	var trackStyle = "";
	var finish = "";
	
	var itemID = $('trackItemID').value;
	
	// get carrier type if track is IFC-98 or track type
	if( document.orderForm.trackType ){
		for (var i=0; i<document.orderForm.trackType.length; i++){
			if( document.orderForm.trackType[i].checked == true ){ carriers = document.orderForm.trackType[i].value; }
		}
	} else { //Custom IFC-50 page
		carriers = "IFC-400";	
	}
	
	/*
	if( carriers == "IFC-100" || carriers == "IFC-600" ){
		//get finish color if it exists
		if( document.orderForm.trackColor ){
			for(var i=0; i<document.orderForm.trackColor.length; i++){
				if( document.orderForm.trackColor[i].checked == true ){ finish = document.orderForm.trackColor[i].value;}
			}
		} else {
			finish = "Aluminum";	
		}
	}*/
	
	for(var i=0;i<activeIDs.length;i++){
		trackStyle = $('trackStyle'+activeIDs[i]).value;
		
		id = activeIDs[i];
		A = B = C = null;
		
		//Retrieve values from track length inputs 
		A = $('trackA'+id).value;
		if( trackStyle != 1 ){ B = $('trackB'+id).value; } 
		if( trackStyle == 4 ){ C = $('trackC'+id).value; }
		
		qty = $('trackQty'+id).value;
		trackPrice = $('trackPrice'+id).value;
		
		if( $('onePiece'+id).checked == true ){ onePiece = 'Yes'; } else { onePiece = 'No'; }
		
		returnArray[i] = new Array(itemID,carriers,trackStyle,qty,onePiece,trackPrice,A,B,C);
	}
	
	return returnArray;
}

// validateCurtains()
// Validates all curtain data and adds error messages to the validationErrors array
// args: curtainData - an array of all curtain data
function validateCurtains(curtainData,type){
	var id;
	
	// Set up the step number for the validation link
	if( type == "blackout" ){
		stepNum = 2;	
	} else {
		stepNum = 4	
	}
	
	//Loop through curtain info and vaidate text fields
	for(var i=0;i<curtainData.length;i++){
		id = curtainData[i][0];
		
		//Validate Height
		if( curtainData[i][1] == "" ){ validationErrors[validationErrors.length] = "<a onclick=\"showHideSteps("+stepNum+")\" href='#line"+id+"'>Curtain "+id+": You must enter a curtain height.</a><br />"; }
		if( !isNumericDecimal(curtainData[i][1]) ){ validationErrors[validationErrors.length] = "<a onclick=\"showHideSteps("+stepNum+")\" href='#line"+id+"'>Curtain "+id+": Invalid Curtain Height.</a>  Your curtain height must be <u>in inches</u> and only contain numerical characters 0-9 and a decimal.<br />"; }
		
		//Validate Width
		if( curtainData[i][3] == "" ){ validationErrors[validationErrors.length] = "<a onclick=\"showHideSteps("+stepNum+")\" href='#line"+id+"'>Curtain "+id+": You must enter a curtain width.</a><br />"; }
		if( !isNumericDecimal(curtainData[i][3]) ){ validationErrors[validationErrors.length] = "<a onclick=\"showHideSteps("+stepNum+")\" href='#line"+id+"'>Curtain "+id+": Invalid Curtain Width.</a>  Your curtain width must be <u>in inches</u> and only contain numerical characters 0-9 and a decimal.<br />"; }
		
		//Validate Quantitiy
		if( !isNumeric(curtainData[i][4]) || curtainData[i][4] < 1  ){ validationErrors[validationErrors.length] = "<a onclick=\"showHideSteps("+stepNum+")\" href='#line"+id+"'>Curtain "+id+": Invalid Quantity.</a> Must be greater than zero and contain only numerical characters 0-9.<br />"; }
	
		//Validate price
		/*
		if( $('stdCurtainCheck') ){
			if( $('error'+id).innerHTML != "" ){ validationErrors[validationErrors.length] = "<a onclick=\"showDivs('stepsContainer4')\" href='#line"+id+"'>Curtain "+id+": "+ $('error'+id).innerHTML +"</a>"; }
		}
		*/
	}
}

// validateTracks()
// Validates all track data and adds error messages to the validationErrors array
// args: trackData - an array of all track data
function validateTracks(trackData,type){
	// Set up step id number for validation links
	if( type == "blackout" || type == "track" ){
		stepNum = 1;	
	} else if( type == "stdCurtain" ){
		stepNum = 	3;
	}
	
	//loop through tracks and validate
	for(var i=0;i<trackData.length;i++){
		style = trackData[i][2];
			
		if( trackData[i][1] == "IFC-69" || trackData[i][1] == "IFC-79" ){
			//Validate type for IFC-69 and IFC-79
			if( trackData[i][1] == "" ){ validationErrors[validationErrors.length] = "<a onclick=\"showHideSteps("+stepNum+")\" href='#trackType'>Select a track type.</a>"; }
		} else {
			//Validate Finish
			if( trackData[i][1] != "IFC-400" && trackData[i][5] == "" ){ validationErrors[validationErrors.length] = "<a onclick=\"showHideSteps("+stepNum+")\" href='#trackType'>Select a track finish.</a>"; }
			//Validate Carriers
			if( trackData[i][1] == "" ){ validationErrors[validationErrors.length] = "<a onclick=\"showHideSteps("+stepNum+")\" href='#trackType'>Select a carrier.</a>"; }
		}
		//Validate track style
		if( trackData[i][2] == "" ){ validationErrors[validationErrors.length] = "<a onclick=\"showHideSteps("+stepNum+")\" href='#trackLine"+(i+1)+"'>Track Setup "+(i+1)+": You must select a track style.</a>"; }
		//Validate quantity
		if( !isNumeric(trackData[i][3]) || trackData[i][3] < 1 ){ validationErrors[validationErrors.length] = "<a onclick=\"showHideSteps("+stepNum+")\" href='#trackLine"+(i+1)+"'>Track Setup "+(i+1)+" - Invalid Quantity.</a> Must be greater than zero and contain only numerical characters 0-9.<br />";	}
		
		//Validate side A
		if( trackData[i][1] == "IFC-69" || trackData[i][1] == "IFC-79" ){
			if( trackData[i][6] == "" ){ validationErrors[validationErrors.length] = "<a onclick=\"showHideSteps("+stepNum+")\" href='#trackLine"+(i+1)+"'>Track Setup "+(i+1)+" - You must enter a track length.</a><br />"; }
			if( !isNumericDecimal(trackData[i][6]) ){ validationErrors[validationErrors.length] = "<a onclick=\"showHideSteps("+stepNum+")\" href='#trackLine"+(i+1)+"'>Track Setup "+(i+1)+": Invalid Side A Length.</a>  Your 'Side A' length must be <u>in inches</u> and only contain numerical characters 0-9 and a decimal.<br />"; }
		} else {
			if( trackData[i][6] == "" ){ validationErrors[validationErrors.length] = "<a onclick=\"showHideSteps("+stepNum+")\" href='#trackLine"+(i+1)+"'>Track Setup "+(i+1)+" - You must enter a length for Side A.</a><br />"; }
			if( !isNumericDecimal(trackData[i][6]) ){ validationErrors[validationErrors.length] = "<a onclick=\"showHideSteps("+stepNum+")\" href='#trackLine"+(i+1)+"'>Track Setup "+(i+1)+": Invalid Side A Length.</a>  Your 'Side A' length must be <u>in inches</u> and only contain numerical characters 0-9 and a decimal.<br />"; }
		}
		
		//Validate side B lengths
		if( style != 1 && style != "" && trackData[i][7] == "" ){ validationErrors[validationErrors.length] = "<a onclick=\"showHideSteps("+stepNum+")\" href='#trackLine"+(i+1)+"'>Track Setup "+(i+1)+" - You must enter a length for Side B.</a><br />"; }
		if( style != 1 && style != "" && !isNumericDecimal(trackData[i][7]) ){ validationErrors[validationErrors.length] = "<a onclick=\"showHideSteps("+stepNum+")\" href='#trackLine"+(i+1)+"'>Track Setup "+(i+1)+": Invalid Side B Length.</a>  Your 'Side B' length must be <u>in inches</u> and only contain numerical characters 0-9 and a decimal.<br />"; }
		
		//Validate side C lengths
		if( style == 4 && trackData[i][8] == "" ){ validationErrors[validationErrors.length] = "<a onclick=\"showHideSteps("+stepNum+")\" href='#trackLine"+(i+1)+"'>Track Setup "+(i+1)+" - You must enter a length for Side C.</a><br />";	}
		if( style == 4 && !isNumericDecimal(trackData[i][8]) ){ validationErrors[validationErrors.length] = "<a onclick=\"showHideSteps("+stepNum+")\" href='#trackLine"+(i+1)+"'>Track Setup "+(i+1)+": Invalid Side C Length.</a>  Your 'Side C' length must be <u>in inches</u> and only contain numerical characters 0-9 and a decimal.<br />"; }
		
	}
}


// addCurtainsToCart()
// Adds the curtains in the measureRowArray and the track setups in trackArray to the cart
// args: curtainArray - array with all the curtain data, trackArray - array with track data
function addCurtainsToCart(curtainArray,trackArray){
	//Set up 2D arrays for track arguments, if you add/remove arguments you must alter the length of the corrisponding array
	var curtainArgs = new2DArray(10,2);
	var tempArray = new Array();
	
	//Show loading screen
	showDivs('validationErrors');
	$("validationErrors").innerHTML = "<br /><center><img src='/images/graphics/page-loading.gif' alt='Loading...' /><br />Building Estimate...</center><br />";
	$("loadingText").innerHTML = "Building Estimate";
	$("loading").style.top = getScrollY() + "px";
	$("loading").setStyle("display","block");
	
	//Get curtain options
	if( $('banding').checked == true){ banding = "Yes"; } else { banding = "No"; }
	if( $('tiebacks').checked == true){ tiebacks = $('tiebackDrop').value; } else { tiebacks = "None"; }
	if( $('meshChk').checked == true){ mesh = $('meshHeight').value; } else { mesh = 0; }
	
	for(var i=0;i<curtainArray.length;i++){
		//Set up curtain arguments array
		curtainArgs[0][0] = "item_id";
		curtainArgs[0][1] = $("itemID").value;
		curtainArgs[1][0] = "fabric_id";
		curtainArgs[1][1] = FABRIC_ID;
		curtainArgs[2][0] = "ctfHeight";
		curtainArgs[2][1] = curtainArray[i][1];
		curtainArgs[3][0] = "hoFloor";
		curtainArgs[3][1] = curtainArray[i][2];
		curtainArgs[4][0] = "width";
		curtainArgs[4][1] = curtainArray[i][3];
		curtainArgs[5][0] = "qty";
		curtainArgs[5][1] = curtainArray[i][4];
		curtainArgs[6][0] = "banding";
		curtainArgs[6][1] = banding;
		curtainArgs[7][0] = "tiebacks";
		curtainArgs[7][1] = tiebacks;
		curtainArgs[8][0] = "mesh";
		curtainArgs[8][1] = mesh;
		curtainArgs[9][0] = "curtainPrice";
		curtainArgs[9][1] = curtainArray[i][5];
		
		//run ajax to add item to cart
		runAJAXsync('curtains_ajax',curtainArgs);
		
		//If there are track setups add them to the cart
		if( trackArray != null ){
			tempArray[0] = trackArray[i];
			addTracksToCart(tempArray);
		}
	}
	//Display success message and hide loading screen
	$('validationErrors').innerHTML = "<h4 id='itemsAdded'>Your estimate was submitted. <a href='/cart.php' title='view cart'>View Cart <img border='0' src='/images/graphics/cart.gif' /></a></h4>";
	//$("loading").className = "loading-invisible";
	$("loading").setStyle("display","none");
}

// addBlackoutToCart()
// Adds the blackout curtains in the measureRowArray and the track setups in trackArray to the cart
// args: curtainArray - array with all the curtain data, trackArray - array with track data
function addBlackoutToCart(curtainArray,trackArray){
	//Set up 2D arrays for track arguments, if you add/remove arguments you must alter the length of the corrisponding array
	var curtainArgs = new2DArray(6,2);
	var tempArray = new Array();
	
	//Show loading screen
	showDivs('validationErrors');
	$("validationErrors").innerHTML = "<br /><center><img src='/images/graphics/page-loading.gif' alt='Loading...' /><br />Building Estimate...</center><br />";
	$("loadingText").innerHTML = "Building Estimate";
	$("loading").style.top = getScrollY() + "px";
	$("loading").setStyle("display","block");
	
	//Get curtain options
	if( $('valChk').checked == true){ valance = $('valHeight').value; } else { valance = 0; }
	
	for(var i=0;i<curtainArray.length;i++){
		//Set up curtain arguments array
		curtainArgs[0][0] = "item_id";
		curtainArgs[0][1] = $("itemID").value;
		curtainArgs[1][0] = "ctfHeight";
		curtainArgs[1][1] = curtainArray[i][1];
		curtainArgs[2][0] = "hoFloor";
		curtainArgs[2][1] = curtainArray[i][2];
		curtainArgs[3][0] = "width";
		curtainArgs[3][1] = curtainArray[i][3];
		curtainArgs[4][0] = "qty";
		curtainArgs[4][1] = curtainArray[i][4];
		curtainArgs[5][0] = "valance";
		curtainArgs[5][1] = valance;
		
		//run ajax to add item to cart
		runAJAXsync('curtains_ajax',curtainArgs);
		
		//If there are track setups add them to the cart
		if( trackArray != null ){
			tempArray[0] = trackArray[i];
			addTracksToCart(tempArray);
		}
	}
	
	//Display success message and hide loading screen
	$('validationErrors').innerHTML = "<h4 id='itemsAdded'>Your estimate was submitted. <a href='/cart.php' title='view cart'>View Cart <img border='0' src='/images/graphics/cart.gif' /></a></h4>";
	//$("loading").className = "loading-invisible";
	$("loading").setStyle("display","none");
}

// addTracksToCart()
// Adds the track setups in trackArray to the cart
// args: trackArray - array with track data
function addTracksToCart(trackArray){
	//Set up 2D arrays for track arguments, if you add/remove arguments you must alter the length of the corrisponding array
	var trackArgs = new2DArray(9,2);
	
	for(var i=0;i<trackArray.length;i++){
		//Set up track arguments array
		trackArgs[0][0] = "item_id";
		trackArgs[0][1] = trackArray[i][0];
		trackArgs[1][0] = "carriers";
		trackArgs[1][1] = trackArray[i][1];
		trackArgs[2][0] = "trackStyle";
		trackArgs[2][1] = trackArray[i][2];
		trackArgs[3][0] = "qty";
		trackArgs[3][1] = trackArray[i][3];
		trackArgs[4][0] = "onePiece";
		trackArgs[4][1] = trackArray[i][4];
		trackArgs[5][0] = "trackPrice";
		trackArgs[5][1] = trackArray[i][5];
		trackArgs[6][0] = "A";
		trackArgs[6][1] = trackArray[i][6];
		
		//Check track style and add B and C lengths if appropriate
		if( trackArray[i][2] != 1 ){
			trackArgs[7][0] = "B";
			trackArgs[7][1] = trackArray[i][7];
			
			if( trackArray[i][2] == 4 ){
				trackArgs[8][0] = "C";
				trackArgs[8][1] = trackArray[i][8];
			}
		}
			
		//run ajax to add item to cart
		runAJAXsync('curtains_ajax',trackArgs);
	}
}

/**************************************************************************************
* END VALIDATION & SUBMISSION FUNCTIONS
**************************************************************************************/

/**************************************************************************************
* UPDATE CART ITEM FUNCTIONS
**************************************************************************************/
// updateCurtain()
// Used in the update curtain page. Retrieves all curtain data validates it then
// either prints the validation errors or updates the cart with an AJAX call
function updateCurtain(){
	var height, hofloor, width, qty, banding, tieback, mesh, errorBlock = "";
	var curtainUpdateArray = new2DArray(10,2);
	validationErrors = new Array();
	
	//Get the input field values
	height = $('height1').value;
	width = $('width1').value;
	qty = $('qty1').value;
	
	if( $('curtainPrice1') ){
		curtainPrice = $('curtainPrice1').value;
	} else {
		curtainPrice = 0.00;	
	}
		
	//Validate the input fields 
	if( height == "" ){ validationErrors[validationErrors.length] = "<b class='required'>You must enter a curtain height.</b><br />"; }
	if( width == "" ){ validationErrors[validationErrors.length] = "<b class='required'>You must enter a curtain width.</b><br />"; }
	if( !isNumericDecimal(height) ){ validationErrors[validationErrors.length] = "<b class='required'>Your curtain height must be <u>in inches</u> and only contain numerical characters 0-9 and a decimal.</b><br />"; }
	if( !isNumericDecimal(width) ){ validationErrors[validationErrors.length] = "<b class='required'>Your curtain width must be <u>in inches</u> and only contain numerical characters 0-9 and a decimal.</b><br />"; }
	if( !isNumeric(qty) || qty < 1 ){ validationErrors[validationErrors.length] = "<b class='required'>Invalid Quantity.</b> Must be greater than zero and contain only numerical characters 0-9.<br />"; }

	//Get curtain options
	if( $('banding').checked == true){ banding = "Yes"; } else { banding = "No"; }
	if( $('tiebacks').checked == true){ tiebacks = $('tiebackDrop').value; } else { tiebacks = "None"; }
	if( $('meshChk').checked == true){ mesh = $('meshHeight').value; } else { mesh = 0; }

	//If there were errors display error messages or send AJAX call to update the item
	if( validationErrors.length > 0 ){
		for(var i=0;i<validationErrors.length;i++){ errorBlock += "<li>"+validationErrors[i]+"</li>"; }
		showDivs('validationErrors');
		$('validationErrors').innerHTML = "<h3 id='errorHeader'>Alert! You Must Correct the Following Errors:</h3><ol>" + errorBlock + "</ol>";
	} else { // No validation errors submit to cart
		hideDivs('validationErrors');
		
		//Display loading screen
		$("loadingText").innerHTML = "Updating Curtain";
		$("loading").style.top = getScrollY() + "px";
		//$("loading").className = "loading-visible";
		$("loading").setStyle("display","block");
		
		//Set up arguments array
		curtainUpdateArray[0][0] = "cart_id";
		curtainUpdateArray[0][1] = $('cartID').value;
		curtainUpdateArray[1][0] = "fabric_id";
		curtainUpdateArray[1][1] = $('fabricID').value;
		curtainUpdateArray[2][0] = "ctfHeight";
		curtainUpdateArray[2][1] = height;
		curtainUpdateArray[3][0] = "hoFloor";
		curtainUpdateArray[3][1] = $('offFloor1').value;
		curtainUpdateArray[4][0] = "width";
		curtainUpdateArray[4][1] = width;
		curtainUpdateArray[5][0] = "qty";
		curtainUpdateArray[5][1] = qty;
		curtainUpdateArray[6][0] = "banding";
		curtainUpdateArray[6][1] = banding;
		curtainUpdateArray[7][0] = "tiebacks";
		curtainUpdateArray[7][1] = tiebacks;
		curtainUpdateArray[8][0] = "mesh";
		curtainUpdateArray[8][1] = mesh;
		curtainUpdateArray[9][0] = "curtainPrice";
		curtainUpdateArray[9][1] = curtainPrice;
		
		//Send AJAX Call
		runAJAXsync('curtains_ajax',curtainUpdateArray);
		
		//Redirect to shopping cart
		document.write("<script>window.location='/cart.php'</script>");
	}
}


// updateBlackoutCurtain()
// Used in the update blackout curtain page. Retrieves all curtain data validates it then
// either prints the validation errors or updates the cart with an AJAX call
function updateBlackoutCurtain(){
	var height, heightF, hofloor, width, widthF, qty, banding, tieback, mesh, errorBlock = "";
	var curtainUpdateArray = new2DArray(6,2);
	validationErrors = new Array();
	
	//Get the input field values
	height = $('height').value;
	width = $('width').value;
	qty = $('qty').value;
	
	//Validate the input fields 
	if( height == "" ){ validationErrors[validationErrors.length] = "<b class='required'>You must enter a curtain height.</b><br />"; }
	if( width == "" ){ validationErrors[validationErrors.length] = "<b class='required'>You must enter a curtain width.</b><br />"; }
	if( !isNumericDecimal(height) ){ validationErrors[validationErrors.length] = "<b class='required'>Your curtain height must be <u>in inches</u> and only contain numerical characters 0-9 and a decimal.</b><br />"; }
	if( !isNumericDecimal(width) ){ validationErrors[validationErrors.length] = "<b class='required'>Your curtain width must be <u>in inches</u> and only contain numerical characters 0-9 and a decimal.</b><br />"; }
	if( !isNumeric(qty) || qty < 1 ){ validationErrors[validationErrors.length] = "<b class='required'>Invalid Quantity.</b> Must be greater than zero and contain only numerical characters 0-9.<br />"; }

	//Get curtain options
	if( $('valChk').checked == true){ valance = $('valHeight').value; } else { valance = 0; }

	//If there were errors display error messages or send AJAX call to update the item
	if( validationErrors.length > 0 ){
		for(var i=0;i<validationErrors.length;i++){ errorBlock += "<li>"+validationErrors[i]+"</li>"; }
		showDivs('validationErrors');
		$('validationErrors').innerHTML = "<h3 id='errorHeader'>Alert! You Must Correct the Following Errors:</h3><ol>" + errorBlock + "</ol>";
	} else { // No validation errors submit to cart
		hideDivs('validationErrors');
		
		//Display loading screen
		$("loadingText").innerHTML = "Updating Curtain";
		$("loading").style.top = getScrollY() + "px";
		//$("loading").className = "loading-visible";
		$("loading").setStyle("display","block");
		
		//Set up arguments array
		curtainUpdateArray[0][0] = "cart_id";
		curtainUpdateArray[0][1] = $('cartID').value;
		curtainUpdateArray[1][0] = "ctfHeight";
		curtainUpdateArray[1][1] = height;
		curtainUpdateArray[2][0] = "hoFloor";
		curtainUpdateArray[2][1] = $('offFloor').value;
		curtainUpdateArray[3][0] = "width";
		curtainUpdateArray[3][1] = width;
		curtainUpdateArray[4][0] = "qty";
		curtainUpdateArray[4][1] = $('qty').value;
		curtainUpdateArray[5][0] = "valance";
		curtainUpdateArray[5][1] = valance;
		
		//Send AJAX Call
		runAJAXsync('curtains_ajax',curtainUpdateArray);
		
		//Redirect to shopping cart
		document.write("<script>window.location='/cart.php'</script>");
	}
}



// updateTrack()
// Used in the update track page. Retrieves all track data validates it then
// either prints the validation errors or updates the cart with an AJAX call
function updateTrack(){
	validationErrors = new Array();
	var trackUpdateArray = new2DArray(10,2);
	var carriers, trackStyle, trackType, onePiece, errorBlock = "";
	var finish = "";
	A = null;
	B = null;
	C = null;
	carriers = $('trackType1').value;
	
	//get track type
	for (var i=0; i<document.orderForm.trackType.length; i++){
		if( document.orderForm.trackType[i].checked == true ){ carriers = document.orderForm.trackType[i].value; }
	}
	
	//Get track style
	if( $('trackStyle1') ) {
		trackStyle = $('trackStyle1').value;	
	} else {
		//IFC-79 or IFC-69 is selected
		trackStyle = 1;	
	}
	
	//Retrieve and validate values from track length inputs 
	A = $('trackA1').value;
	if( A == "" || !isNumericDecimal(A) ){ validationErrors[validationErrors.length] = "<b class='required'>You must enter a track length for Side A <u>in inches</u> that only contain numerical characters 0-9 and a decimal.</b><br />"; }
	
	if( trackStyle != 1 ){ 
		B = $('trackB1').value; 
		if( B == "" || !isNumericDecimal(B) ){ validationErrors[validationErrors.length] = "<b class='required'>You must enter a track length for Side B <u>in inches</u> that only contain numerical characters 0-9 and a decimal.</b><br />"; }
	} 
	if( trackStyle == 4 ){ 
		C = $('trackC1').value;
		if( C == "" || !isNumericDecimal(C) ){ validationErrors[validationErrors.length] = "<b class='required'>You must enter a track length for Side C <u>in inches</u> that only contain numerical characters 0-9 and a decimal.</b><br />"; }
	}
	qty = $('trackQty1').value;
	
	if( !isNumeric(qty) || qty < 1 ){ validationErrors[validationErrors.length] = "<b class='required'>Invalid Quantity.</b> Must be greater than zero and contain only numerical characters 0-9.<br />"; }
	if( $('onePiece1').checked == true ){ onePiece = 'Yes'; } else { onePiece = 'No'; }
	
	//If there were errors display error messages or send AJAX call to update the item
	if( validationErrors.length > 0 ){
		for(var i=0;i<validationErrors.length;i++){ errorBlock += "<li>"+validationErrors[i]+"</li>"; }
		showDivs('validationErrors');
		$('validationErrors').innerHTML = "<h4 id='errorHeader'>Alert! You Must Correct the Following Errors:</h4><ol>" + errorBlock + "</ol>";
	} else { // No validation errors submit to cart
		hideDivs('validationErrors');
		
		//Display loading screen
		$("loadingText").innerHTML = "Updating Curtain";
		$("loading").style.top = getScrollY() + "px";
		//$("loading").className = "loading-visible";
		$("loading").setStyle("display","block");
	
		trackUpdateArray[0][0] = "item_id";
		trackUpdateArray[0][1] = $('trackItemID').value;
		trackUpdateArray[1][0] = "cart_id";
		trackUpdateArray[1][1] = $('cartID').value;
		trackUpdateArray[2][0] = "carriers";
		trackUpdateArray[2][1] = carriers;
		trackUpdateArray[3][0] = "trackStyle";
		trackUpdateArray[3][1] = trackStyle;
		trackUpdateArray[4][0] = "qty";
		trackUpdateArray[4][1] = qty;
		trackUpdateArray[5][0] = "onePiece";
		trackUpdateArray[5][1] = onePiece;
		trackUpdateArray[6][0] = "trackPrice";
		trackUpdateArray[6][1] = $('trackPrice1').value;
		trackUpdateArray[7][0] = "A";
		trackUpdateArray[7][1] = A;
		
		//Check track style and add B and C lengths if appropriate
		if( trackStyle != 1 ){
			trackUpdateArray[8][0] = "B";
			trackUpdateArray[8][1] = B;
			
			if( trackStyle == 4 ){
				trackUpdateArray[9][0] = "C";
				trackUpdateArray[9][1] = C;
			}
		}
	
		//Send AJAX Call
		runAJAXsync('curtains_ajax',trackUpdateArray);
		
		//Redirect to shopping cart
		document.write("<script>window.location='/cart.php'</script>");

	}
}
/**************************************************************************************
* END UPDATE CART ITEM FUNCTIONS
**************************************************************************************/

/**************************************************************************************
* FABRIC SELECTOR FUNCTIONS 
**************************************************************************************/

// hideFabricSteps()
// Shows/Hides fabric selecton steps
function hideFabricSteps(step){
	if( step == "A" ){ showDivs('selectStyle'); hideDivs('patternSelect'); hideDivs('colorSelect'); } 
	else if( step == "B" ) { hideDivs('selectStyle'); showDivs('patternSelect'); hideDivs('colorSelect'); } 
	else if( step == "C" ) { hideDivs('selectStyle'); hideDivs('patternSelect'); showDivs('colorSelect'); }
}

// hideFabricSteps()
// Shows/Hides shower fabric selecton steps
function hideFabricStepsShower(step){
	if( step == "A" ){ showDivs('patternSelectShower'); hideDivs('colorSelect'); } 
	else if( step == "B" ) { hideDivs('patternSelectShower'); showDivs('colorSelect'); } 
}


// hideFabricSteps()
// Selects a fabric. Changes fabric styles and sets FABRIC_ID 
// to the currently selected fabrice id
function selectFabric(id,span_id,name){
	var activeRows = getActiveRows();
	FABRIC_ID = id;
	
	//Set fabricID input only used in edit curtains page
	$('fabricID').value = id;
	$('selectedFabric').innerHTML = " - " + name;

	// Change colors of selected swatch
	var selectLink = $$('.fabricSelect');
	var fabricDivs = $$('.fabrics');

	for(var i=0;i<selectLink.length;i++){
		// Change back color of previously selected swatch
		if( selectLink[i].innerHTML == "Selected" ){
			$('fabric'+i).setStyles({background: "#ffffff",border: "1px solid #828488",color: "#666666"});
			selectLink[i].innerHTML = "Select +";
			selectLink[i].setStyles({background: "#cadce9",border: "1px solid #657db9",color: "#304b8d"});
		}
		
		// Set up fade effect
		var myFx = new Fx.Tween(fabricDivs[i]);
		myFx.set('tween', {duration: '1000'});
		
		// Change color of currently selected swatch
		if( i == span_id ){ 
			//Change color of currently selected swatch and fade in
			$('fabric'+i).setStyles({background: "#ffd8d8",border: "1px solid #800000",color: "#800000"});
			$('fabricLink'+i).innerHTML = "Selected";
			$('fabricLink'+i).setStyles({background: "#ffd8d8",border: "1px solid #800000",color: "#800000"});
			//fade in selected fabric
			myFx.start('opacity','0.5','1.0');
		} else {
			//fade out all other swatches
			myFx.start('opacity',fabricDivs[i].opacity,'0.5');
		}
	}
	
	//change text of link in slimbox
	if( $('slimLink'+span_id) ){ $('slimLink'+span_id).innerHTML = "Fabric selected. <br /> Click the 'close' link to close."; }
	
	/*
	// Recalculate curtain prices
	for(var i=0; i<activeRows.length; i++){
		calculateCurtainPrice(activeRows[i]);
	}
	
	// Recalculate curtain subtotal
	if( $('curtainSubtotal') ){ getCurtainSubtotal(); }
	*/
}


// getPatterns()
// Executes an ajax call that retrieves all the fabric patterns 
// for the selected style and Loads them into the patternSelect Div
// Args: style - the fabric type that is currently selected, type - the type of curtain
function getPatterns(style,type){
	//Set up arguments array
	var styleType;
	var args = new2DArray(2,2);
	args[0][0] = 'style';
	args[0][1] = style;
	args[1][0] = 'type';
	args[1][1] = type;
	
	if( style == "SOLID" ){
		styleType = "Solid";
	}else if( style == "GEO" ){
		styleType = "Geometric/Stripes";
	}else if( style == "ALT" ){
		styleType = "Alternative";
	}else if( style == "TOT" ){
		styleType = "Tone on Tone";
	}else if( style == "FLO" ){
		styleType = "Floral";
	}
	
	//Hide/Show Divs
	hideDivs('selectStyle');
	$('patternSelect').innerHTML = "<br /><center><img src='/images/graphics/page-loading.gif' alt='Loading...' /><br />Loading...</center><br />";
	$('selectedStyle').innerHTML = " - " + styleType;
	showDivs('patternBlock');
	showDivs('patternSelect');
	
	//Execute Ajax
	runAJAXasync('curtains_ajax','patternSelect',args);
}

// getColors()
// Executes an ajax call that retrieves all the fabric color variations 
// for the selected pattern and Loads them into the colorSelect Div
// Args: pattern - the fabric pattern that is currently selected
function getColors(style,pattern){
	//Set up arguments array
	var args = new2DArray(2,2);
	args[0][0] = 'pattern';
	args[0][1] = pattern;
	args[1][0] = 'style';
	args[1][1] = style;
	
	//Hide/Show Divs
	hideDivs('patternSelect');
	hideDivs('patternSelectShower');
	$('colorSelect').innerHTML = "<br /><center><img src='/images/graphics/page-loading.gif' alt='Loading...' /><br />Loading...</center><br />";
	$('selectedPattern').innerHTML = " - " + pattern;
	showDivs('colorBlock');
	showDivs('colorSelect');
	
	//Execute Ajax
	runAJAXasync('curtains_ajax','colorSelect',args);
}

// getColors()
// Executes an ajax call that add the given fabric to the sample request cart
// Args: id - the id of the fabric that is requested, handle - the id of the link that was clicked
function requestSample(id,handle){
	args = new2DArray(2,2);
	args[0][0] = 'sample';
	args[0][1] = 'add';
	args[1][0] = 'fabric_id';
	args[1][1] = id;
	
	//Change link text
	$(handle).innerHTML = "Requested";
	//$(handle).setStyles({color: "#8d8d8d",border: "1px solid #8d8d8d", background: "#e9e9e9"});
	$(handle).className = "fabricSampleReq";
	
	var temp = runAJAXsync('fabrics_ajax',args);
	alert(temp);
}

/**************************************************************************************
* END FABRIC SELECTOR FUNCTIONS FUNCTIONS
**************************************************************************************/


/**************************************************************************************
* TRACK AND CURTAIN MEASUREMENT FUNCTIONS FUNCTIONS FUNCTIONS
**************************************************************************************/


// setupTrackBlock()
// Displays the track block according to what type of curtain / track is selected
// args: type - the type of curtain that is selected
function setupTrackBlock(type){
	if( type == "IFC-100" || type == "IFC-600" || type == "IFC-400" ){
		showDivs("trackMeasurements");
		showDivs("trackStyleDivs");
		
		if( type == "IFC-100" || type == "IFC-600" ){
			switchTrackFinish();	
		} else {
			var activeRows = getActiveRows();
			$('trackItemID').value = $('ifc50_ID').value;
			$('trackPrice').value = $('ifc50_price').value;
			
			/*
			// Recalculate Track Setup Pricing
			for(var i=0; i<activeRows.length; i++){
				calculateTrackPrice(activeRows[i]);
			}
			
			// Recalculate Subtotal
			if( $('trackSubtotal') ){ getTrackSubtotal(); }
			*/
		}
		
		//show the style selector
		for(var i=0;i<measureRowArray.length;i++){ showDivs('styleDrop'+(i+1)); }
	}else if( type == "IFC-79" || type == "IFC-69" ){
		showDivs("trackMeasurements");
		hideDivs("trackStyleDivs");
		
		//Set item id for ifc-69
		if( type == "IFC-69" ){ 
			$('trackItemID').value = $('ifc69_ID').value; 
			$('trackPrice').value = $('ifc69_price').value;
			
		//Set item id for ifc-79
		} else { 
			$('trackItemID').value = $('ifc79_ID').value;
			$('trackPrice').value = $('ifc79_price').value;
		}
		
		//Hide the style selector
		for(var i=0;i<measureRowArray.length;i++){
			$('trackStyle'+(i+1)).value = 1;
			hideDivs('styleDrop'+(i+1));
			showDivs('inputA'+(i+1));
			hideDivs('inputB'+(i+1));
			hideDivs('inputC'+(i+1));
		}
	}
}

// setTrackInputs()
// shows or hides the track inputs base on what style is selected
// args: num - the track style that is selected
function setTrackInputs(num){
	var value = $('trackStyle'+num).value;	

	//Show or hide track inputs	
	if( value == 1 ){ showDivs('inputA'+num); hideDivs('inputB'+num); hideDivs('inputC'+num);}
	else if( value == 4 ){  showDivs('inputA'+num); showDivs('inputB'+num); showDivs('inputC'+num); }
	else if( value == "" ){ hideDivs('inputA'+num); hideDivs('inputB'+num); hideDivs('inputC'+num); }
	else{ showDivs('inputA'+num); showDivs('inputB'+num); hideDivs('inputC'+num); }
	
	/*
	//Recalculate track price
	calculateTrackPrice(num);
	*/
}

// changeQty()
// Changes the quantity of curtains to correspond with the quantity of track
function changeQty(num){
	//if the corrisponding text field exists set the value
	if( $('qty'+num) ){ $('qty'+num).value = $('trackQty'+num).value; }
	
	/*
	//recalculate track subtotal
	if( $('trackSubtotal') ){ getTrackSubtotal(); }
	
	//recalculate curtains subtotal
	if( $('curtainSubtotal') ){ getCurtainSubtotal(); }
	*/
}

// trackMeasureEdit()
// Displays/Hides the track Measurements inputs depending on what one is checked
// Used in the 'edit track' page
function trackMeasureEdit(){
	var trackChecked;
	
	//Get the track that is currently checked
	for (var i=0; i<document.orderForm.trackCheckEdit.length; i++){
		if( document.orderForm.trackCheckEdit[i].checked == true ){ 
			trackChecked = document.orderForm.trackCheckEdit[i].value; 
		}
	}
	
	//Hide/show measurement inputs that do not apply
	if( trackChecked == 1 ){
		hideDivs('editB');
		hideDivs('editC');
	}else if( trackChecked != 4 ){
		showDivs('editB');
		hideDivs('editC');
	}else if( trackChecked == 4 ){
		showDivs('editB');
		showDivs('editC');
	}
}

// generateMeasurements()
// Generates curtains measurement by adding 10% to track size it then adjusts
// the curtain width drop downs to the apropriate sizes
// Args: num - the number of the field 1-6 for each track style
function generateMeasurements(num){
	var length, feet, inches, A, B, C, validator = 0;
	var style = $('trackStyle'+num).value;

	//Get and validate track lengths
	if( style == 1 ){
		A = $('trackA'+num).value;
		if( A == 0 || A == null || A == "" ){ validator = 1; }
		else if( !isNumericDecimal(A) ){ validator = 2; }
		else { length = eval(A); }
	} else if( style == 4 ){
		A = $('trackA'+num).value;
		B = $('trackB'+num).value;
		C = $('trackC'+num).value;
		if( A == 0 || A == null || A == "" || B == 0 || B == null || B == "" || C == 0 || C == null || C == ""){ validator = 1; }
		else if( !isNumericDecimal(A) || !isNumericDecimal(B) || !isNumericDecimal(C) ){ validator = 2; }
		else {length = eval(A)+eval(B)+eval(C);}
	} else {
		A = $('trackA'+num).value;
		B = $('trackB'+num).value;
		if( A == 0 || A == null || A == "" || B == 0 || B == null || B == "" ){ validator = 1; }
		else if( !isNumericDecimal(A) || !isNumericDecimal(B) ){ validator = 2; }
		else {length = eval(A)+eval(B);}
	}
	
	//calculate new size
	if( validator == 0 ){
		//Add 10% to size
		length = Math.round(length * 1.10);
		
		//Set values in drop downs
		$('width'+num).value = length;
		
		//Recalculate curtain subtotal
		calculateCurtainPrice(num);
	} else if( validator == 1 ) {
		alert("ALERT: You did not enter all required track measurements.");
	} else {
		alert("AlERT: Track measurements must only contain numerical characters 0-9."); 	
	}
}

/**************************************************************************************
* END TRACK AND CURTAIN MEASUREMENT FUNCTIONS 
**************************************************************************************/

/**************************************************************************************
* FUNCTIONS  THAT DEAL WITH ADDING AND REMOVING MEASUREMENT ROWS
**************************************************************************************/
// getInactiveRows()
// Searches the measureRowArray and returns a new array containing 
// the id numbers of all currently inactive measurement rows 
function getInactiveRows(){
	inactiveRows = new Array();
	var counter = 0;
	
	//populate array with id numbers of active curtains
	for(var i=0;i<measureRowArray.length;i++){
		if( measureRowArray[i] == 0 ){
			inactiveRows[counter] = i+1;
			counter++;
		}
	}
	return inactiveRows;
}

// getActiveRows()
// Searches the measureRowArray and returns a new array containing 
// the id numbers of all currently active measurement rows 
function getActiveRows(){
	var counter = 0;
	activeTrackIDs = new Array();
	//Find all active rows
	for (var i=0; i<measureRowArray.length; i++){
		if( measureRowArray[i] == 1 ){ 
			activeTrackIDs[counter] = (i+1);
			counter++;
		}
	}
	
	return activeTrackIDs;
}


// addRow()
// Adds another measurement row
function addRow(){
	curtainID = getInactiveRows();
	if( curtainID[0] != null ){
		measureRowArray[curtainID[0]-1] = 1;
		showDivs('measureRow'+curtainID[0]);
		showDivs('setup'+curtainID[0]);
		
		if( curtainID[1] == null ){
			hideDivs('addRow');
			showDivs('moreRows');
			hideDivs('addRowTrack');
			showDivs('moreRowsTrack');
		}
	}	
	
	/*
	// Recalculate track subtotal
	if( $('trackSubtotal') ){  getTrackSubtotal(); }
	// Recalculate curtain subtotal
	if( $('curtainSubtotal') ){  getCurtainSubtotal(); }
	*/
}

// removeRow()
// Removes a measurement row
function removeRow(num){
	//This ensures that the first curtain always remains active
	if( num > 1 ){
		//set curtain as in active in curtains array
		measureRowArray[num-1] = 0;
		hideDivs('measureRow'+num);
		hideDivs('setup'+num);
		
		//if there is now at least one inactive curtain show the
		//add curtain button and hide the text block
		curtainID = getInactiveRows();
		if( curtainID[0] != null ){
			hideDivs('moreRows');
			showDivs('addRow');
			hideDivs('moreRowsTrack');
			showDivs('addRowTrack');
		}
	}
	
	/*
	// Recalculate track subtotal
	if( $('trackSubtotal') ){  getTrackSubtotal(); }
	// Recalculate curtain subtotal
	if( $('curtainSubtotal') ){  getCurtainSubtotal(); }
	*/
}

/**************************************************************************************
* END FUNCTIONS  THAT DEAL WITH ADDING AND REMOVING MEASUREMENT ROWS
**************************************************************************************/


/**************************************************************************************
* RESET PAGE FUNCTIONS
**************************************************************************************/

// noTracks()
// Resets the track info boxes and curtain boxes
function resetTracks(){
	var trackFlag = "";
	
	//Hide main track selection div
	hideStep(3);
		
	//Reset select track type bullets
	for(var i=0; i<document.orderForm.trackType.length; i++){
		document.orderForm.trackType[i].checked = false;
		trackFlag = document.orderForm.trackType[i].value;
	}
		
	//get finish color if it exists
	if( document.orderForm.trackColor ){		
		for(var i=0; i<document.orderForm.trackColor.length; i++){ document.orderForm.trackColor[i].checked = false; } 
	}
	
	//Hide track style and measurement divs
	hideDivs('trackStyle');
	hideDivs('trackMeasurements');
	
	//Uncheck all track style check boxes and hide all track and curtain measurements
	//reset all track and curtain measurements
	for(var i=0; i<measureRowArray.length; i++){
		//Reset track measurements and options
		$('trackStyle'+(i+1)).value = "";
		$('trackA'+(i+1)).value = "";
		$('trackB'+(i+1)).value = ""; 
		$('trackC'+(i+1)).value = "";
		$('trackQty'+(i+1)).value = 1;
		$('onePiece'+(i+1)).checked = false;
		
		//Hide A, B and C length inputs if track is IFC-98
		if( trackFlag == "IFC-100" || trackFlag == "IFC-600" ){
			hideDivs('inputA'+(i+1));
			hideDivs('inputB'+(i+1));
			hideDivs('inputC'+(i+1));
		}
		
		//Reset row display
		removeRow((i+1));
	}
}

// resetCurtains()
// Resets curtains 
function resetCurtains(){
	//Hide curtain measurement div
	hideStep(4);
	
	//Reset no track curtain measurement rows
	for(var i=0;i<measureRowArray.length;i++){
		//Reset curtain measurements
		$('height'+(i+1)).value = "";
		$('width'+(i+1)).value = "";
		$('qty'+(i+1)).value = 1;
		$('offFloor'+(i+1)).value = 0;
	}
	
	//Resent custom curtain options
	if( $('banding') ){
		//Reset options
		$('banding').checked = false;
		$('tiebacks').checked = false;
		$('meshChk').checked = false;
		$('meshHeight').value = 10;
		
		//Hide mesh drop down
		hideDivs('meshDisplay');
		hideDivs('tieBackDisplay');
		
	}else{ //Reset blackout curtain options
		$('valChk').checked = false;
		$('valHeight').value = 12;
		
		//Hide mesh drop down
		hideDivs('valDisplay');
	}
	
	//Show add extra curtain button
	hideDivs('moreRows');
	showDivs('addRow');
}

// resetPage()
// Resets page 
function resetPage(){
	//Reset Fabric
	FABRIC_ID = null;
	
	//Reset the fabric selector
	showStep(1);
	hideStep(2);
	showDivs('trackSetup');
	showDivs('selectStyle');
	showDivs('patternSelectShower');
	hideDivs('patternBlock');
	hideDivs('colorBlock');
	
	//Reset tracks and curtains
	resetTracks();
	resetCurtains();
}

/**************************************************************************************
* END RESET PAGE FUNCTIONS
**************************************************************************************/

/**************************************************************************************
* CALCULATE PRICE FUNCTIONS
**************************************************************************************/
// calculateTrackPrice()
// Calculates the track price of a given set up
function calculateTrackPrice(num){
	var trackStyle = $('trackStyle'+num).value;
	var sideA = $('trackA'+num).value;
	var trackPrice = $('trackPrice').value;
	var trackQty = $('trackQty'+num).value;
	var totalLength = 0;
	var trackTotal = "0.00";
	
	// Validate Quantity
	if( !isNumeric(trackQty) || trackQty == 0 ){
		alert("INVALID QUANTITY: Setup "+num+": Your quantity must be greater than zero and only contain numerical characters 0-9.");
		return false;	
	}
	
	// Initalize siteA
	if( sideA == "" ){ sideA = 0.00; }
	
	// Calculate cost of Style 1
	if( trackStyle == 1 ){
		if( !isNumericDecimal(sideA) ){
			alert("INVALID LENGTH: Setup "+num+" Side A: Your length must be in inches and only contain numerical characters 0-9 and a decimal.");
		}else{
			sideA =  Math.ceil(eval(sideA));
			totalLength = sideA;
			
			trackTotal = roundUp( (totalLength / 12) * trackPrice );
			
			$("trackPrice"+num).value = trackTotal;
		}
		
	// Calculate cost of Styles 2, 3, 5, 6	
	}else if( trackStyle != 4 && trackStyle != "" ){
		var sideB = $('trackB'+num).value;
		if( sideB == "" ){ sideB = 0.00; }
		
		if( !isNumericDecimal(sideA) || !isNumericDecimal(sideB) ){
			if( !isNumericDecimal(sideA) ){
				alert("INVALID LENGTH: Setup "+num+" Side A: Your length must be in inches and only contain numerical characters 0-9 and a decimal.");
			} else {
				alert("INVALID LENGTH: Setup "+num+" Side B: Your length must be in inches and only contain numerical characters 0-9 and a decimal.");
			}
		} else {
			totalLength = eval(sideA)+eval(sideB);
			trackTotal = roundUp( ((totalLength+12) / 12) * trackPrice );
			
			$("trackPrice"+num).value = trackTotal;
		}
	
	// Calculate cost of Style 4
	} else if( trackStyle == 4) {
		var sideB = $('trackB'+num).value;
		var sideC = $('trackC'+num).value;
		if( sideB == "" ){ sideB = 0.00; }
		if( sideC == "" ){ sideC = 0.00; }
		
		if( !isNumericDecimal(sideA) || !isNumericDecimal(sideB) || !isNumericDecimal(sideC) ){
			if( !isNumericDecimal(sideA) ){
				alert("INVALID LENGTH: Setup "+num+" Side A: Your length must be in inches and only contain numerical characters 0-9 and a decimal.");
			} else if( !isNumericDecimal(sideB) ){
				alert("INVALID LENGTH: Setup "+num+" Side B: Your length must be in inches and only contain numerical characters 0-9 and a decimal.");
			} else {
				alert("INVALID LENGTH: Setup "+num+" Side C: Your length must be in inches and only contain numerical characters 0-9 and a decimal.");
			}
		} else {
			totalLength = eval(sideA)+eval(sideB)+eval(sideC);
			trackTotal = roundUp( ((totalLength+24) / 12) * trackPrice );
		
			$("trackPrice"+num).value = trackTotal;
		}
	
	// No Style is Selected 
	} else {
		trackTotal = 0;
		trackTotal = trackTotal.toFixed(2);
		$("trackPrice"+num).value = trackTotal;
	}
	
	// Set up track price display
	if( $('onePiece'+num).checked == true && totalLength >= 96 ){
		$("trackPrice"+num).value = 0.00
		$("trackPriceDisplay"+num).innerHTML = "Price: <b>TBD</b> - <span class='required'>Pricing is not available to ship a track of this size in one piece.</span>";
	} else {
		$("trackPriceDisplay"+num).innerHTML = "Price: <b>$"+trackTotal+"</b> <small>per setup</small>";
	}
	
	// Recalculate subtotal
	if( $('trackSubtotal') ){ getTrackSubtotal(); }
}


// getTrackSubtotal()
// Finds the total of all the current track setups on the page
function getTrackSubtotal(){
	var activeRows = getActiveRows();
	var subTotal = 0;
	
	// Add new track prices
	for(var i=0; i<activeRows.length; i++){
		subTotal = subTotal + (eval($("trackPrice"+activeRows[i]).value) * eval($('trackQty'+activeRows[i]).value) );
	}
	
	// Format Subtotal
	if( subTotal == 0 ){ subTotal = "0.00"; }
	else{ subTotal = roundUp(subTotal); }
	
	// If there is a subtotal div on the page load the new sub total
	$('trackSubtotal').innerHTML = "$" + subTotal;
}


// switchTrackFinish()
// Recalculates pricing when track finish is switched
function switchTrackFinish(){
	var activeRows = getActiveRows();
	
	// Get track type
	var carriers = "";
	for (var i=0; i<document.orderForm.trackType.length; i++){
		if( document.orderForm.trackType[i].checked == true ){ carriers = document.orderForm.trackType[i].value; }
	}
		
	if( (carriers == "IFC-100" || carriers == "IFC-600") && document.orderForm.trackColor ){	
		// Get track finish
		for(var i=0; i<document.orderForm.trackColor.length; i++){
			if( document.orderForm.trackColor[i].checked == true ){ finish = document.orderForm.trackColor[i].value;}
		}
		
		// Switch ITEM_ID and ITEM_PRICE
		if( finish == "Aluminum" ){
			$('trackItemID').value = $('ifc98_ID').value;
			$('trackPrice').value = $('ifc98_price').value;
		} else {
			$('trackItemID').value = $('ifc98wht_ID').value;
			$('trackPrice').value = $('ifc98wht_price').value
		}
	
		// Recalculate Track Setup Pricing
		/*
		for(var i=0; i<activeRows.length; i++){
			calculateTrackPrice(activeRows[i]);
		}
		
		// Recalculate Subtotal
		 if( $('trackSubtotal') ){ getTrackSubtotal(); }
		*/
	}
}

// calculateCurtainPrice(num)
// args: num - the number of the curtain set up
// Calculates the price of a given curtain setup
function calculateCurtainPrice(num){
	if( !$('stdCurtainCheck') ){  return false; }
	
	var measureArgs = new2DArray(5,2);
	var curtainHeight = $("height"+num).value;
	var curtainWidth = $("width"+num).value;
	var offFloor = $("offFloor"+num).value;
	var mesh = 0;
	var tieBackPrice = 0;
	var curtainPrice = "0.00";
	
	// Reset error message
	$('error'+num).innerHTML = "";
	
	// Check if there is mesh or not
	if( $('meshChk').checked == true ){
		mesh = 1;	
	}
	
	// Check if there are tiebacks
	if( $('tiebacks').checked == true ){
		if( $('tiebackDrop').value == "White" ){ tieBackPrice = 5; }
		else{ tieBackPrice = 8; }
	}
	
	// Validate Fabric Id
	if( FABRIC_ID == null ){
		alert("YOU MUST SELECT A FABRIC: In order to view pricing on your curtain setups you must make a fabric selection in 'Step 2'.");
	}
	
	// Validate and get pricing
	if( curtainHeight != "" || curtainWidth != "" ){
		//Validate curtain inputs	
		if( !isNumericDecimal(curtainHeight) && curtainHeight != "" ){ 
			alert("INVALID HEIGHT: Curtain "+num+": Your curtain height must be in inches and only contain numerical characters 0-9 and a decimal."); 
		} else if( curtainHeight == "0" ){
			alert("INVALID HEIGHT: Curtain "+num+": Your curtain height must be greater than 0."); 
		} else if( !isNumericDecimal(curtainWidth) && curtainWidth != "" ) {
			alert("INVALID WIDTH: Curtain "+num+": Your curtain width must be in inches and only contain numerical characters 0-9 and a decimal."); 
		} else if( curtainWidth == "0" ){
			alert("INVALID WIDTH: Curtain "+num+": Your curtain width must be greater than 0."); 
		} else if( curtainHeight != "" && curtainWidth != "" ) {
			// Set up 
			measureArgs[0][0] = 'height';
			measureArgs[0][1] = curtainHeight;
			measureArgs[1][0] = 'width';
			measureArgs[1][1] = curtainWidth;
			measureArgs[2][0] = 'offFloor';
			measureArgs[2][1] = offFloor;
			measureArgs[3][0] = 'mesh';
			measureArgs[3][1] = mesh;
			measureArgs[4][0] = 'fabric_id';
			measureArgs[4][1] = FABRIC_ID;
			
			// Run ajax to get price
			curtainPrice = runAJAXsync('get_curtain_price',measureArgs);
		}
	}
	
	// Set up / Validate Price
	if( FABRIC_ID == null ){
		// If fabric is not select display message
		$('error'+num).innerHTML = "<b>You must select a fabric type in 'Step 2' to get pricing.</b>";
		
		$("curtainPrice"+num).value = 0.00;
		$("curtainPriceDisplay"+num).innerHTML = "Price: <b>$0.00</b> <small>per setup</small>";
	} else if( curtainPrice == "FABRIC TO LARGE" ){
		// If curatain heigt is to large display message
		$('error'+num).innerHTML = "<b>Pricing is unavailable for a curtain of this size. Either add your set up to the cart and request a quote, or call our customer service team at 800-791-2946 to get pricing.</b>";
		
		$("curtainPrice"+num).value = 0.00;
		$("curtainPriceDisplay"+num).innerHTML = "Price: <b>TBD</b>";
	} else {
		// If is break out curtain add aditional $1 per foot of length
		if( $('itemID').value == 154013 && eval(curtainWidth) >= 12 ){
			curtainPrice = eval(curtainPrice) + Math.ceil(eval(curtainWidth)/12);
		}
			
		// Add price of tiebacks and format price
		curtainPrice = roundUp(eval(curtainPrice) + tieBackPrice);
		
		$("curtainPrice"+num).value = curtainPrice;
		$("curtainPriceDisplay"+num).innerHTML = "Price: <b>$"+ curtainPrice +"</b> <small>per setup</small>";
	}
	
	// Recalculate curtain subtotal
	 if( $('curtainSubtotal') ){ getCurtainSubtotal(); }
}

// getTrackSubtotal()
// Finds the total of all the current track setups on the page
function getCurtainSubtotal(){
	var activeRows = getActiveRows();
	var subTotal = 0;
	
	// Add new track prices
	for(var i=0; i<activeRows.length; i++){
		if( FABRIC_ID != null ){
			subTotal = subTotal + (eval($("curtainPrice"+activeRows[i]).value) * eval($('qty'+activeRows[i]).value) );
		}
	}
	
	// Format Subtotal
	if( subTotal == 0 ){ subTotal = "0.00"; }
	else{ subTotal = roundUp(subTotal); }
	
	// If there is a subtotal div on the page load the new sub total
	$('curtainSubtotal').innerHTML = "$" + subTotal;
}

// recalculateCurtains()
// Recalculates price of curtains
function recalculateCurtains(){
	var activeRows = getActiveRows();
	
	// Recalculate curtain price
	for(var i=0; i<activeRows.length; i++){
		calculateCurtainPrice(activeRows[i]);
	}
}

/**************************************************************************************
* END CALCULATE PRICE FUNCTIONS
**************************************************************************************/

/**************************************************************************************
* GET REVIEW SETUP FUNCTIONS
**************************************************************************************/

function getTrackReviewData(activeTrackIDs){
	var trackDisplay = "";
	
	//Retrieve and validate track information
	trackArray = getTrackData(activeTrackIDs);
	
	trackDisplay += "<table class='reviewTable' cellpadding='4' cellspacing='0'>";
	
	for(var i=0;i<trackArray.length;i++){
		var A = B = C = itemID = carriers = trackStyle = qty = onePiece = "";
		
		//Set up track arguments array
		itemID = trackArray[i][0];
		carriers = trackArray[i][1];
		trackStyle = trackArray[i][2];
		qty = trackArray[i][3];
		onePiece = trackArray[i][4];
		
		// Set up carriers Display
		if( carriers == "" ){ carriers = "NA"; }
		
		// Set up style display
		if( trackStyle == "" ){ 
			trackStyle = "NA"; 
			A = "No Measurements Entered";	
		} else {
			// Set up Side A display
			if(  trackArray[i][6] != "" ){ A = trackArray[i][6] + "&quot;"; } else { A = "NA" }
			
			// Set up Sides D and C displays
			if( trackStyle != 1 ){
				if( trackArray[i][7] != "" ){
					B = " &#47; <b>Side B:</b> " + trackArray[i][7] + "&quot;";
				} else {
					B = " &#47; <b>Side B:</b> NA";
				}
				
				if( trackStyle == 4 ){
					if( trackArray[i][8] != "" ){
						C = " &#47; <b>Side C:</b> " + trackArray[i][8] + "&quot;";
					} else {
						C = " &#47; <b>SideC:</b> NA";
					}
				}
			}
		}
		
		// Set up IFC-98 / IFC - 50 Info
		if( itemID == 145585 || itemID == 153950 || itemID == 145586 ){	
			if( itemID == 145585 ){
				trackType = "<b>IFC-98 Aluminum Finish </b> w/ <b> " + carriers + "</b> carriers";
			} else if( itemID == 153950 ){
				trackType = "<b>IFC-98 White Finish </b> w/ <b> " + carriers + "</b> carriers";
			} else {
				trackType = "<b>IFC-50</b> w/ <b>IFC-400</b> carriers";
			} 
			
			// Set up edit link
			id = activeTrackIDs[i];
			editLink = "<a class='trkEdit' href='#trackLine"+id+"' onclick='showHideSteps(1)'>Edit</a><a class='crtEdit' href='#trackLine"+id+"' onclick='showHideSteps(3)'>Edit</a><a class='blkOutEdit' href='#trackLine"+id+"' onclick='showHideSteps(1)'>Edit</a>";
			
			// Set up edit type linke
			editTypeLink = "";
			editTypeLink = "<div class='hideEditType'><a class='trkEdit' href='#trackType' onclick='showHideSteps(1)'>Edit</a><a class='crtEdit' href='#trackType' onclick='showHideSteps(3)'>Edit</a><a class='blkOutEdit' href='#trackType' onclick='showHideSteps(1)'>Edit</a></div>";
			
			// Set up row style
			var style = "";
			if( (i+1) == trackArray.length ){ style = " class='noborder'"; }
			
			// Set up table header
			if( i == 0 ){
				trackDisplay += "<tr class='header'><td class='hdrSetupNum'>Setup #</td><td>Track Type</td> <td>&nbsp;</td> <td>Track Style & Track Size</td> <td>&nbsp;</td> <td align='center'>Qty.</td> <td>&nbsp;</td> </tr>\n"
			}
			
			// Set up track row
			trackDisplay += "<tr"+ style +"><td align='center'>"+ id +"</td><td>"+trackType+"</td> <td class='edit'>"+editTypeLink+"</td> <td><b>Style:</b> "+ trackStyle + " &#47; <b>Side A:</b> "+ A + B + C + " <br /> <b>Ship in one piece:</b> " + onePiece +"</td> <td class='edit'>"+editLink+"</td> <td align='center'>"+ qty +"</td> <td class='editQty'>"+editLink+"</td> </tr>\n";
		
		// Set up IFC-69 / IFC-79 Info
		} else if( itemID == 106178 || itemID == 145598 ) {
			if( itemID == 106178 ){ 
				trackType = "<b>IFC-69</b>";
			} else {
				trackType = "<b>IFC-79</b>";
			}
			
			// Set up edit link
			id = activeTrackIDs[i];
			editLink = "<a class='trkEdit' href='#trackLine"+id+"' onclick='showHideSteps(1)'>Edit</a><a class='crtEdit' href='#trackLine"+id+"' onclick='showHideSteps(3)'>Edit</a>";
			editTypeLink = "<a class='trkEdit' href='#trackType' onclick='showHideSteps(1)'>Edit</a><a class='crtEdit' href='#trackType' onclick='showHideSteps(3)'>Edit</a>";
			
			// Set up row style
			var style = "";
			if( (i+1) == trackArray.length ){ style = " class='noborder'"; }
			
			// Set up table header
			if( i == 0 ){
				trackDisplay += "<tr class='header'><td class='hdrSetupNum'>Setup #</td><td>Track Type</td> <td>&nbsp;</td> <td>Track Size</td> <td>&nbsp;</td> <td align='center'>Qty.</td> <td>&nbsp;</td> </tr>\n"
			}
			
			// Set up track row	
			trackDisplay += "<tr"+ style +"><td align='center'>"+ id +"</td><td><b>"+trackType+"</b></td> <td class='edit'>"+editTypeLink+"</td> <td><b>Length:</b> "+ A +" &#47; <b>Ship in one piece:</b> " + onePiece +"</td> <td class='edit'>"+editLink+"</td> <td align='center'>"+ qty +"</td> <td class='editQty'>"+editLink+"</td> </tr>\n";
		} else {
			editTypeLink = "<a class='trkEdit' href='#trackType' onclick='showHideSteps(1)'>Edit</a><a class='crtEdit' href='#trackType' onclick='showHideSteps(3)'>Edit</a>";
			
			trackDisplay += "<tr class='header'><td>Track Type</td> <td></td> <td>Track Size</td> <td></td> <td align='center'>Qty.</td> <td></td> </tr>\n"
			trackDisplay += "<tr class='noborder'><td colspan='5'>No Type Selected<td> <td class='editQty'>"+ editTypeLink +"</td><tr>"	
		}
	} 
	
	trackDisplay += "</table>";
	
	return trackDisplay;
}

function getCurtainReviewData(activeCurtainIDs){
	//Get curtain data
	curtainArray = getCurtainData(activeCurtainIDs);
	
	var curtainDisplay = "";
	curtainDisplay += "<table class='reviewTable' cellpadding='4' cellspacing='0'>";
	curtainDisplay += "<tr class='header'><td class='hdrSetupNum'>Setup #</td><td>Fabric</td><td>&nbsp;</td><td>Curtain Size</td><td>&nbsp;</td><td>Options</td><td>&nbsp;</td><td align='center'>Qty.</td><td>&nbsp;</td></tr>\n"
	
	for(var i=0;i<curtainArray.length;i++){
		//Set up curtain arguments array
		itemID = $("itemID").value;
		
		// Set up ceiling to floor height
		if( curtainArray[i][1] != "" ){ 
			ctfHeight = curtainArray[i][1] + "&quot;"; 
		} else {  
			ctfHeight = "NA";
		}
		
		// Set up ceiling to floor height
		hoFloor = curtainArray[i][2];
		
		// Set up width
		if( curtainArray[i][3] != "" ){ 
			width = curtainArray[i][3] + "&quot;"; 
		} else {
			width = "NA";	
		}
		
		// Set up qty
		qty = curtainArray[i][4];
		
		// Set up fabric name
		fabricPattern = $('selectedPattern').innerHTML;
		fabricColor = $('selectedFabric').innerHTML;
		if( fabricPattern == "" || fabricColor == ""){
			fabricName = "None Selected";
		} else {
			fabricPattern = fabricPattern.replace(" - ","");
			fabricColor = fabricColor.replace(" - ","");
			
			fabricName = fabricPattern + " " + fabricColor;
		}
	
		// Set up tiebacks
		if( $('tiebacks').checked == true){ tiebacks = $('tiebackDrop').value; } else { tiebacks = "None"; }
		
		var tieBackDisplay = "";
		if( itemID == 145584 || itemID == 83101 ){
			tieBackDisplay = "<b>Tie-backs:</b> " + tiebacks;
			
			if( itemID == 145584 ){
				tieBackDisplay += " &#47; ";	
			}
		}
		
		// Set up mesh
		if( $('banding').checked == true){ banding = "Yes"; } else { banding = "No"; }
		if( $('meshChk').checked == true){ mesh = $('meshHeight').value; } else { mesh = 0; }
		
		var meshDisplay = "";
		if( itemID == 145584 || itemID == 145587 ){
			if( mesh > 0 ){
				meshDisplay = "<b>Mesh:</b> " + mesh + "&quot; <br /> <b>Banding:</b> " + banding;
			} else {
				meshDisplay = "<b>Mesh:</b> None";
			}
		}
			
		// Set up row style
		var style = "";
		if( (i+1) == curtainArray.length ){ style = " class='noborder'"; }
		
		// Set up edit link
		id = activeCurtainIDs[i];
		editLink = "<a href='#line"+id+"' onclick='showHideSteps(4)'>Edit</a>";
		
		// Set up table row
		curtainDisplay += "<tr"+ style +"><td align='center'>"+ id +"</td><td><b>"+fabricName+"</b></td> <td class='edit'><a onclick='showHideSteps(2)'>Edit</a></td> <td><b>Ceiling to Floor Height:</b> "+ ctfHeight +" &#47; <b>Height off the Floor:</b> "+ hoFloor +"&quot; <br /> <b>Width:</b> "+ width +"</td> <td class='edit'>"+ editLink +"</td> <td>"+ tieBackDisplay + meshDisplay +"</td> <td class='edit'><a href='#curtainOptions' onclick='showHideSteps(4)'>Edit</a></td> <td align='center'>"+ qty +"</td><td class='editQty'>"+ editLink +"</td></tr>\n";
	}
	
	curtainDisplay += "</table>";
	
	return curtainDisplay;
}

function getBlkOutCurtainReviewData(activeCurtainIDs){
	//Get curtain data
	curtainArray = getCurtainData(activeCurtainIDs);
	
	var curtainDisplay = "";
	curtainDisplay += "<table class='reviewTable' cellpadding='4' cellspacing='0'>";
	curtainDisplay += "<tr class='header'><td class='hdrSetupNum'>Setup #</td><td>Fabric</td><td>Curtain Size</td><td>&nbsp;</td><td>Options</td><td>&nbsp;</td><td align='center'>Qty.</td><td>&nbsp;</td></tr>\n"
	
	for(var i=0;i<curtainArray.length;i++){
		//Set up curtain arguments array
		itemID = $("itemID").value;
		
		// Set up ceiling to floor height
		if( curtainArray[i][1] != "" ){ 
			ctfHeight = curtainArray[i][1] + "&quot;"; 
		} else {  
			ctfHeight = "NA";
		}
		
		// Set up ceiling to floor height
		extraMaterial = curtainArray[i][2];
		
		// Set up width
		if( curtainArray[i][3] != "" ){ 
			width = curtainArray[i][3] + "&quot;"; 
		} else {
			width = "NA";	
		}
		
		// Set up qty
		qty = curtainArray[i][4];
		
		//Get curtain options
		if( $('valChk').checked == true){ valance = $('valHeight').value; } else { valance = 0; }	
		
		if( valance == 0 ){
			curtainOptions = "<b>Valance:</b> None";	
		} else {
			curtainOptions = "<b>Valance:</b> " + valance + "&quot;";
		}
			
		// Set up row style
		var style = "";
		if( (i+1) == curtainArray.length ){ style = " class='noborder'"; }
		
		// Set up edit link
		id = activeCurtainIDs[i];
		editLink = "<a href='#line"+id+"' onclick='showHideSteps(2)'>Edit</a>";
		
		// Set up table row
		curtainDisplay += "<tr"+ style +"><td align='center'>"+ id +"</td><td><b>Apollo Black</b></td> <td><b>Ceiling to Floor Height:</b> "+ ctfHeight +" &#47; <b>Width:</b> "+ width +"<br /> <b>Extra Material:</b> "+ extraMaterial +"&quot;</td> <td class='edit'>"+ editLink +"</td> <td>"+ curtainOptions +"</td> <td class='edit'><a href='#curtainOptions' onclick='showHideSteps(2)'>Edit</a></td> <td align='center'>"+ qty +"</td><td class='editQty'>"+ editLink +"</td></tr>\n";
	}
	
	curtainDisplay += "</table>";
	
	return curtainDisplay;
}

function trackReview(){
	// Get active Ids
	activeTrackIDs = getActiveRows();
	
	// Get track display
	trackDisplay = getTrackReviewData(activeTrackIDs);
	
	// Load track display
	$("trackReview").innerHTML = trackDisplay;
	
	// Hide edit type
	if( $('trackItemID').value == 145586 ){
		$$('.hideEditType').setStyle("display","none");
	}
}

function curtainReview(){
	// Get active Ids
	activeCurtainIDs = getActiveRows();
	
	if( SETUP_TYPE == 1 ){
		// Get track display
		trackDisplay = getTrackReviewData(activeTrackIDs);
		
		// Load track display
		$("trackReview").innerHTML = trackDisplay;
		
		// Show the correct edit link for the curtain page
		$$('.trkEdit').setStyle("display","none");
		$$('.crtEdit').setStyle("display","inline");
	} else {
		$("trackReview").innerHTML = "";
	}
	
	// Get curtain display
	curtainDisplay = getCurtainReviewData(activeCurtainIDs);
	
	// Load track display
	$("curtainReview").innerHTML = curtainDisplay;
}

function blkOutReview(){
	// Get active Ids
	activeCurtainIDs = getActiveRows();
	
	// Get track display
	trackDisplay = getTrackReviewData(activeTrackIDs);
		
	// Load track display
	$("trackReview").innerHTML = trackDisplay;
		
	// Show the correct edit link for the curtain page
	$$('.trkEdit').setStyle("display","none");
	$$('.blkOutEdit').setStyle("display","inline");
	
	// Get curtain display
	curtainDisplay = getBlkOutCurtainReviewData(activeCurtainIDs);
	
	// Load track display
	$("curtainReview").innerHTML = curtainDisplay;
}

/**************************************************************************************
* END GET REVIEW SETUP FUNCTIONS
**************************************************************************************/

/**************************************************************************************
* ONKEYUP VALIDATION FUNCTIONS
**************************************************************************************/

function validateTrackInput(){
	if( 	!isNumericDecimal(this.value) ){
	
		// Set error style
		if( !this.className.match("validationError") ){
			this.className += " validationError";	
		}
		
		// Load error message
		$('trackValidation'+this.name).innerHTML = "Invalide track length:  You must enter a length <u>in inches</u> that only contains numerical characters 0-9 and a decimal.";
	
	} else {
		// Reset style
		this.className = this.className.replace(new RegExp(" validationError\\b"), "");
		
		// Reset error message
		$('trackValidation'+this.name).innerHTML = "";
	}
}

function validateTrackQty(value,id){
	if( 	!isNumeric($('trackQty'+id).value) || $('trackQty'+id).value < 1 ){
	
		// Set error style
		if( !$('trackQty'+id).className.match("validationError") ){
			$('trackQty'+id).className += " validationError";	
		}
		
		// Load error message
		$('trackValidation'+id).innerHTML = "Invalid Quantity: Must be greater than zero and contain only numerical characters 0-9.";
	
	} else {
		// Reset style
		$('trackQty'+id).className = $('trackQty'+id).className.replace(new RegExp(" validationError\\b"), "");
		
		// Reset error message
		$('trackValidation'+id).innerHTML = "";
	}
}

function validateCurtainInput(){
	if( 	!isNumericDecimal(this.value) ){
	
		// Set error style
		if( !this.className.match("validationError") ){
			this.className += " validationError";	
		}
		
		// Load error message
		$('curtainValidation'+this.name).innerHTML = "Invalide measurement:  You must enter a measurement <u>in inches</u> that only contains numerical characters 0-9 and a decimal.";
	
	} else {
		// Reset style
		this.className = this.className.replace(new RegExp(" validationError\\b"), "");
		
		// Reset error message
		$('curtainValidation'+this.name).innerHTML = "";
	}
}

function validateCurtainQty(value,id){
	if( 	!isNumeric($('qty'+id).value) || $('qty'+id).value < 1 ){
	
		// Set error style
		if( !$('qty'+id).className.match("validationError") ){
			$('qty'+id).className += " validationError";	
		}
		
		// Load error message
		$('curtainValidation'+id).innerHTML = "Invalid Quantity: Must be greater than zero and contain only numerical characters 0-9.";
	
	} else {
		// Reset style
		$('qty'+id).className = $('qty'+id).className.replace(new RegExp(" validationError\\b"), "");
		
		// Reset error message
		$('curtainValidation'+id).innerHTML = "";
	}
}

/**************************************************************************************
* END ONKEYUP VALIDATION FUNCTIONS
**************************************************************************************/

/**************************************************************************************
* PAGE INITIALIZATION
**************************************************************************************/

// initOrderForm()
// Function runs on window load, going through tags to attach events to them
function initOrderForm()
{

	//INITIALIZE TRACK TYPE RADIO BUTTONS IF THEY EXIST
	if( document.orderForm.trackType ){
		for (var i=0; i<document.orderForm.trackType.length; i++){
			document.orderForm.trackType[i].onfocus = function (){ this.checked = true; setupTrackBlock(this.getAttribute("value")); return false; }
		}
	}
	
	//INITALIZE TRACK FINISH RADIO BUTTONS
	if( document.orderForm.trackColor ){
		for (var i=0; i<document.orderForm.trackColor.length; i++){
			document.orderForm.trackColor[i].onfocus = function (){ this.checked = true; switchTrackFinish(); return false; }
		}
	}
	
	//INITIALIZE TRACK STYLE CHECK BOXES AND TRACK QUANTITY INPUTS IF THEY EXIST
	for(var i=0; i<measureRowArray.length; i++){
		if( $("trackStyle"+(i+1)) ){
			$("trackStyle"+(i+1)).onchange = function () { setTrackInputs(this.getAttribute("name")); return false; }
		}
		
		//Initialize track quantity inputs
		if( $("trackQty"+(i+1)) ){
			$("trackQty"+(i+1)).onkeyup = function () { changeQty(this.getAttribute("name")); validateTrackQty(this.getAttribute("value"),this.getAttribute("name"));  return false; }
		}
		
		//Initialize curtain quantity inputs
		if( $("qty"+(i+1)) ){
			$("qty"+(i+1)).onkeyup = function () { validateCurtainQty(this.getAttribute("value"),this.getAttribute("name"));  return false; }
		}
		
		/*
		//Initialize ship in one piece check box
		if( $("onePiece"+(i+1)) ){
			$("onePiece"+(i+1)).onchange = function () { calculateTrackPrice(this.getAttribute("name")); return false; }
			$("onePiece"+(i+1)).onclick = function () { this.blur(); }
		}
		
		//Initialize curtain quantity inputs 
		if( $('stdCurtainCheck') ){
			if( $("qty"+(i+1)) ){
				$("qty"+(i+1)).onkeyup = function () { calculateCurtainPrice(this.getAttribute("name")); }		
			}
		}
		*/
	}
	
	//INITIALIZE TRACK STYLE CHECK BOXES AND TRACK QUANTITY INPUTS IF THEY EXIST
	if( document.orderForm.trackCheckEdit ){
		for (var i=0; i<document.orderForm.trackCheckEdit.length; i++){
			document.orderForm.trackCheckEdit[i].onclick = trackMeasureEdit;
		}
	}
	
	//INITIALIZE TRACK ONKEYUP VALIDATION
	if( $$(".trackSide") ){
		var trackInputs = $$(".trackSide");
		for(var i=0; i<trackInputs.length; i++){
			var anchor = trackInputs[i];
			anchor.onkeyup = validateTrackInput;		
		}
	}
	
	//INITIALIZE CURTAIN ONKEYUP VALIDATION
	if( $$(".curtainMeasure") ){
		var curtainInputs = $$(".curtainMeasure");
		for(var i=0; i<curtainInputs.length; i++){
			var anchor = curtainInputs[i];
			anchor.onkeyup = validateCurtainInput;		
		}
	}
	
	
	
	/*
	//INITIALIZE TRACK PRICE CALCULATION
	if( $$(".trackSide") ){
		var trackInputs = $$(".trackSide");
		for(var i=0; i<trackInputs.length; i++){
			var anchor = trackInputs[i];
			anchor.onkeyup = function () { calculateTrackPrice(this.getAttribute("name")); }	
		}
	}
	
	//INITIALIZE CURTAIN PRICE CALCULATION ON MEASUREMENT INPUTS
	if( $$(".curtainMeasure") ){
		var curtainInputs = $$(".curtainMeasure");
		for(var i=0; i<curtainInputs.length; i++){
			var anchor = curtainInputs[i];
			anchor.onkeyup = function () { calculateCurtainPrice(this.getAttribute("name")); }	
		}
	}
	
	//INITIALIZE CURTAIN PRICE CALCULATON ON HEIGHT OFF FLOOR SELECTS
	if( $$(".curtainSelect") ){
		var curtainSelects = $$(".curtainSelect");
		for(var i=0; i<curtainSelects.length; i++){
			var anchor = curtainSelects[i];
			anchor.onchange = function () { calculateCurtainPrice(this.getAttribute("name")); }	
		}
	}
	*/
	
	
	//INITIALIZE STEPS LINKS AND STYLES LINKS
	if (!document.getElementsByTagName){ return; }
	var anchors = document.getElementsByTagName("a");
	
	// loop through all anchor tags and set up onclick calls
	for (var i=0; i<anchors.length; i++){
		var anchor = anchors[i];
		
		if (anchor.getAttribute("rev") && (anchor.getAttribute("rel") == "steps")){
			anchor.onclick = function () {showHideSteps(this.getAttribute("rev")); return false;}
		} else if (anchor.getAttribute("rev") && (anchor.getAttribute("rel") == "stepsTrackReview")){
			anchor.onclick = function () {showHideSteps(this.getAttribute("rev")); trackReview(); return false;}
		} else if (anchor.getAttribute("rev") && (anchor.getAttribute("rel") == "stepsCurtainReview")){
			anchor.onclick = function () {showHideSteps(this.getAttribute("rev")); curtainReview(); return false;}
		} else if (anchor.getAttribute("rev") && (anchor.getAttribute("rel") == "stepsBlkOutReview")){
			anchor.onclick = function () {showHideSteps(this.getAttribute("rev")); blkOutReview(); return false;}
		} else if (anchor.getAttribute("rev") && (anchor.getAttribute("rel") == "selectSetup")){
			anchor.onclick = function () {selectSetup(this.getAttribute("rev")); return false;}
		} else if (anchor.getAttribute("rev") && (anchor.getAttribute("rel") == "styles")){
			anchor.onclick = function () {getPatterns(this.getAttribute("rev"),this.getAttribute("name")); return false;}
		} else if (anchor.getAttribute("rev") && (anchor.getAttribute("rel") == "fabricSteps")){
			anchor.onclick = function () {hideFabricSteps(this.getAttribute("rev")); return false;}
		} else if (anchor.getAttribute("rev") && (anchor.getAttribute("rel") == "fabricStepsShower")){
			anchor.onclick = function () {hideFabricStepsShower(this.getAttribute("rev")); return false;}
		} else if (anchor.getAttribute("rev") && (anchor.getAttribute("rel") == "genMeasure")){
			anchor.onclick = function () {generateMeasurements(this.getAttribute("rev")); return false;}
		} else if (anchor.getAttribute("rev") && (anchor.getAttribute("rel") == "whatsthis")){
			anchor.onclick = function () {whatsThis(this.getAttribute("rev")); return false;}
		} else if (anchor.getAttribute("rev") && (anchor.getAttribute("rel") == "removeRow")){
			anchor.onclick = function () { removeRow(this.getAttribute("rev")); return false; }
		}
	}
}

function fixesForIE(){
	//INITIALIZE TRACK TYPE RADIO BUTTONS IF THEY EXIST
	if( document.orderForm.trackType ){
		for (var i=0; i<document.orderForm.trackType.length; i++){
			document.orderForm.trackType[i].onclick = function (){ this.blur(); return false; }
		}
	}
	
	//INITALIZE TRACK FINISH RADIO BUTTONS
	if( document.orderForm.trackColor ){
		for (var i=0; i<document.orderForm.trackColor.length; i++){
			document.orderForm.trackColor[i].onclick = function (){ this.blur(); return false; }
		}
	}
}

function hideLoading(){ 
	//document.getElementById("loading").className = "loading-invisible";
	$("loading").setStyle("display","none");
}
/**************************************************************************************
* END PAGE INITIALIZATION
**************************************************************************************/

/*************************************************************************************
* ADD LOAD EVENTS
**************************************************************************************/
addLoadEvent(initOrderForm);
addLoadEvent(hideLoading);
/*************************************************************************************
* END ADD LOAD EVENTS
**************************************************************************************/
