var QuoteTotal = new Array();

window.addEvent('domready', function() {	
	var accordion = new Fx.Accordion($$('#QuoteSteps h3'),$$('.QuoteBox'), {
		opacity: 0, 
    	onActive: function(toggler) { toggler.setStyle('color', '#000000'); }, 
    	onBackground: function(toggler) { toggler.setStyle('color', '#cf1a14'); } 
  	}); 
	var optaccordion = new Fx.Accordion($$('#OptionBox h4'),$$('.OptionList'), {
		opacity: 0, 
    	onActive: function(toggler) { toggler.setStyle('color', '#000000'); }, 
    	onBackground: function(toggler) { toggler.setStyle('color', '#666666'); } 
  	});	
	
	$('BuildingWidth').addEvent('change',function(e){
		//var NewWidth = $('BuildingWidth').getSelected().getProperty('value');
		DynamicLength('quote');										  
		//GetBuildingQuote();
	});
	
	$('BuildingLength').addEvent('change',function(e){		
		GetBuildingQuote();		
	});
	
	$$('#ShingleBox > div').each(function(chip,i) {
		var state = false;
		chip.addEvent('click',function(e) {
			state = !state;
			if(state) {
				$('ShingleBox').getElements('div').removeClass('active');
				chip.addClass('active');
				var ShingleColor = chip.getProperty('title');
				$('ShingleID').setProperty('value',chip.getProperty('shingleID'));
				$('ShingleBox').getElements('input').setProperty('value',ShingleColor);
				$('ShingleColor').setProperty('value',ShingleColor);
				ShingleValue = $('ShingleColor').getProperty('value');
			}
			else {
				chip.removeClass('active');	
				$('ShingleBox').getElements('input').setProperty('value','');
				$('ShingleColor').setProperty('value','Not Selected');
				$('ShingleID').setProperty('value','NULL');
			}
		});
	});
	
	$$('#SidingBox > div').each(function(chip,i) {
		var state = false;
		chip.addEvent('click',function(e) {
			state = !state;
			if(state) {
				$('SidingBox').getElements('div').removeClass('active');
				chip.addClass('active');
				$('Building_PaintID').setProperty('value',chip.getProperty('paintID'));
				var SidingColor = chip.getProperty('title');
				$('SidingBox').getElement('input').setProperty('value',SidingColor);
				$('SidingPaint').setProperty('value',SidingColor);
			}
			else {
				chip.removeClass('active');		
				$('SidingBox').getElement('input').setProperty('value','');
				$('SidingPaint').setProperty('value','Not Selected');
				$('Building_PaintID').setProperty('value','NULL');
			}
		});
	});
	
	$$('#TrimBox > div').each(function(chip,i) {
		var state = false;
		chip.addEvent('click',function(e) {
			state = !state;
			if(state) {
				$('TrimBox').getElements('div').removeClass('active');
				chip.addClass('active');
				$('Trim_PaintID').setProperty('value',chip.getProperty('paintID'));
				var TrimColor = chip.getProperty('title');
				$('TrimBox').getElement('input').setProperty('value',TrimColor);
				$('TrimPaint').setProperty('value',TrimColor);
			}
			else {
				chip.removeClass('active');
				$('TrimBox').getElement('input').setProperty('value','');
				$('TrimPaint').setProperty('value','Not Selected');
				$('Trim_PaintID').setProperty('value','NULL');
			}
		});
	});
	
	$$('#Quote-Colors select').each(function(userchoice,i){
		//set the initial selected value for the total
		UpdateColorTotal();
		//set the initial selected value for the summary
		SetColorOptions();
		//update the total and colors when the user changes the selections
		userchoice.addEvent('change',function(e){
			UpdateColorTotal();
			SetColorOptions();
		});
	});
	
	$$('#Quote-Options input').each(function(userchoice,i){
		//update the total when the user changes the selections
		userchoice.addEvent('keyup',function(e){
			validateOptions.validate();		
		});
	});
	
	$$('#Quote-Specialty input').each(function(userchoice,i){
		//update the total when the user changes the selections
		userchoice.addEvent('keyup',function(e){
			validateSpecialty.validate();
		});
	});

	//form validations
	var validateOptions = new FormValidator.Tips($('Quote-Options'), {
		pointyTipOptions: {point: 'down'},
		scrollToErrorsOnSubmit: false,
		onFormValidate: function(passed, myform, event) {
			if(passed){			
				UpdateOptions();
			}
		}
	});	

	var validateSpecialty = new FormValidator.Tips($('Quote-Specialty'), {
		pointyTipOptions: {point: 'down'},
		scrollToErrorsOnSubmit: false,
		onFormValidate: function(passed, myform, event) {
			if(passed){			
				UpdateSpecialtyPackages();
			}
		}
	});
	
	new FormValidator.Tips($('Quote-Summary'), {
		pointyTipOptions: {point: 'down'},
		scrollToErrorsOnSubmit: false,
		onFormValidate: function(passed, myform, event) {
			//if (passed) alert('Nice job!');
			event.preventDefault();
			if(passed){			
				SaveBuildingQuote();
			}
		}
	});
	DynamicLength('init');
});

function GetBuildingQuote(){
	$('Quote-Building').set('send',{
		useSpinner: true,
		spinnerTarget: 'QuoteSteps',
		onSuccess: function(txt) {
			var PriceArray = txt.split("|");
			var ModelID = PriceArray[0];
			var BasePrice = PriceArray[1];	
			var FormatedBasePrice = '$' + (Number(BasePrice)).numberFormat();
			$('BuildingTotal').innerHTML = FormatedBasePrice;
			$('BasePrice').setProperty('value',FormatedBasePrice);
			QuoteTotal[0]=($('BuildingTotal').innerHTML).replace(/[$,]/g,"");
			
			var SelectedPaint = $('PaintSelect').getSelected();
			var PaintPrice = PriceArray[2];
			if(PaintPrice > 0){								
				var Paint = 'ICI Exterior Paint';				
			}
			else{
				$('PaintSelect').getFirst('option').dispose();
				var Paint = 'Not Available';
			}
			
			$('PaintSelect').getFirst('option').setProperty('price',PaintPrice);
			//store this value to reset if the appearance package is removed
			$('PaintSelect').getFirst('option').store('price',PaintPrice);
			//store this value to reset if the appearance package is removed
			$('PaintSelect').getFirst('option').store('label',Paint);
			var PaintLabel = Paint + ' (+ $' + Number(PaintPrice).numberFormat() + ')';
			$('PaintSelect').getFirst('option').setProperty('label',PaintLabel);
			$('PaintSelect').getFirst('option').setProperty('text',PaintLabel);
			UpdateColorSelection(SelectedPaint);
			
			var Width = $('BuildingWidth').getSelected().getProperty('value');
			$('Width').setProperty('value',Width);
			var Length = $('BuildingLength').getSelected().getProperty('value');
			$('Length').setProperty('value',Length);
			
			var SqFt = (Width * Length);
			var SelectedShingle = $('ShingleSelect').getSelected();
			var SelectedShingleID = SelectedShingle.getProperty('value');
			var Shingles = $('ShingleSelect').getChildren('option');
			for(var i=0; i<Shingles.length; i++){
				var sqftPrice = Shingles[i].getProperty('sqftPrice');
				var ShinglePrice = 0;
				var ShinglePriceLabel = '';
				if(Shingles[i].getProperty('included') == 0){
					ShinglePrice = Number(SqFt * sqftPrice).numberFormat();
					ShinglePriceLabel = ShinglePrice;
				}
				else{
					ShinglePriceLabel = ' Included PRO Upgrade';
				}
				Shingles[i].setProperty('price',ShinglePrice);
				//store this value to reset if the appearance package is removed
				Shingles[i].store('price',ShinglePrice);
				var Shingle = Shingles[i].getProperty('shingle');
				//store this value to reset if the appearance package is removed
				Shingles[i].store('label',Shingle);
				var ShingleLabel = Shingle + ' (+ $' + ShinglePriceLabel + ')';
				Shingles[i].setProperty('label',ShingleLabel);
				Shingles[i].setProperty('text',ShingleLabel);
				
				var ShingleID = Shingles[i].getProperty('value');
				if(SelectedShingleID == ShingleID){
					UpdateColorSelection(Shingles[i]);	
				}
			}
			if(ModelID != ''){
				GetOptionPackages(ModelID,Width,Length,PaintPrice);
			}
			UpdateTotal();
		},
		onFailure: function() {
			$('QuoteSteps').set('opacity',0.2);
			$('SaveQuote').dispose();
			//$('QuoteSteps').empty();
			var Message = 'The Delivery Zip Code you have entered is outside the TUFF SHED service area. If you have entered your Delivery Zip Code incorrectly, please try again.';			
			/* var Messenger = new StickyWin({
			  draggable: true,
			  content: StickyWin.ui('TUFF SHED Service Areas', Message, {
				width: '300px',
				height: '300px',
				cornerHandle: false				
			  })
			}); */
			alert(Message);
		}
	});
	
	$('Quote-Building').send();
};

function SetColorOptions(){
	$('Shingles').setProperty('value',$('ShingleSelect').getSelected().getProperty('label'));
	if($('ShingleSelect').getSelected().getProperty('value') == 55){
		var ShingleChips = $('ShingleBox').getElements('div');
		for(var i=0; i<ShingleChips.length; i++){
			if(ShingleChips[i].getProperty('pro') == 0){
				ShingleChips[i].setStyle('opacity',0.1);
			}
		}
	}
	else{
		var ShingleChips = $('ShingleBox').getElements('div');
		for(var i=0; i<ShingleChips.length; i++){
			ShingleChips[i].setStyle('opacity',1);
		}
	}
	$('Paint').setProperty('value',$('PaintSelect').getSelected().getProperty('label'));
	if($('PaintSelect').getSelected().getProperty('value') == 0){
		$('SidingBox').setStyle('opacity',0.1);
		$('SidingPaint').setProperty('value','N/A');
		$('TrimBox').setStyle('opacity',0.1);
		$('TrimPaint').setProperty('value','N/A');
	}
	else{
		//restore the siding color selector
		$('SidingBox').setStyle('opacity',1);
		//reset the siding color in the summary
		var SidingColor = $('SidingBox').getElement('input').getProperty('value');
		if(SidingColor == ''){var SidingColor = 'Not Selected'};
		$('SidingPaint').setProperty('value',SidingColor);
		//restore the trim color selector
		$('TrimBox').setStyle('opacity',1);
		//reset the trim color in the summary
		var TrimColor = $('TrimBox').getElement('input').getProperty('value');
		if(TrimColor == ''){var TrimColor = 'Not Selected'};
		$('TrimPaint').setProperty('value',TrimColor);
	};
};

function UpdateColorTotal(){
	$('ColorTotal').innerHTML = '$0.00';
	$$('#Quote-Colors select').each(function(userchoice,i){
		//set the initial selected value for the total
		var OptionAmount = userchoice.getSelected().getProperty('price');
		var ColorTotal = ($('ColorTotal').innerHTML).replace(/[$,]/g,"");
		var FinalColorTotal = (Number(OptionAmount) + Number(ColorTotal)).numberFormat();
		$('ColorTotal').innerHTML='$' + FinalColorTotal;		
	});
	QuoteTotal[1]=($('ColorTotal').innerHTML).replace(/[$,]/g,"");
	UpdateTotal();
};

function UpdateColorSelection(SelectedElement){
	SelectedElement.setProperty('selected',false);
	SelectedElement.setProperty('selected',true);
	UpdateColorTotal();
	SetColorOptions();
};

function GetOptionPackages(ModelID,Wdth,Len,PaintPrice){
	var validateOptPkg = new FormValidator.Tips($('Quote-OptPkg'), {
		pointyTipOptions: {point: 'down'},
		scrollToErrorsOnSubmit: false
	});
	
	var GetPackages = new Request.JSON({
		url: '/products_getoptpkg.cfm',
		method: 'get',
		onSuccess: function(jsonObj) {			
			//empty the previous packages
			$('Quote-OptPkg').empty();			
			var packages = jsonObj.package;
			
			if(packages.length < 1){
				var pkglabel = new Element('label');
				pkglabel.inject($('Quote-OptPkg'));
				pkglabel.appendText('No Option Packages Available');
			}
			for(var i=0; i<packages.length; i++){
				var pkglabel = new Element('label');
				pkglabel.inject($('Quote-OptPkg'));
				var pkginput = new Element('input',{
					'name': packages[i].id,
					'label': packages[i].name,
					'price':'',
					'type':'text',
					'size':'3',
					'maxlength':'3',
					'class': 'validate-integer',
					'events': {
						'keyup':function(){
							validateOptPkg.validate();
							UpdateOptionPackages();		
						}
					}
				});
				pkginput.inject(pkglabel);
				//pkginput.addClass('validate-integer');
				pkglabel.appendText(' ' + packages[i].name);
				
				var pkgdesc = new Element('p');
				pkgdesc.addClass('PackageDescription');
				pkgdesc.inject($('Quote-OptPkg'));
				var packageprice = 0;
				var packageoptions = packages[i].option;
				for(var d=0; d<packageoptions.length; d++){
					var optiondesc = packageoptions[d].qty + ' ' + packageoptions[d].unit + ' - ' + packageoptions[d].name;
					pkgdesc.set('html',pkgdesc.get('html') + optiondesc + '<br />');
					if(packageoptions[d].included == 0){
						packageprice += Number(packageoptions[d].price);
					}
				}
				
				packageprice = Number(packageprice - (packageprice * packages[i].discount));
				pkginput.setProperty('price',packageprice);
				var pkgpricelabel = new Element('span');
				pkgpricelabel.addClass('UpgradePrice');
				pkgpricelabel.inject(pkglabel);
				pkgpricelabel.appendText(' (+ $' + packageprice.numberFormat() + ')');				
			}
		},
		onFailure: function() {
			alert('No Option Packages');
		}
	})	
	var SendQuery = 'ModelID=' + ModelID + '&W=' + Wdth + '&L=' + Len + '&PaintPrice=' + PaintPrice;
	GetPackages.send(SendQuery);
};

function UpdateOptionPackages(){
	//reset the initial total of the options to 0
	$('OptPkgTotal').innerHTML = '$0.00';
	//reset the summary options list to blank and textarea size to 1
	$('OptionPackages').setProperty('value','');
	$('OptionPackages').setProperty('rows',1);
	$('OptionPkgQty').setProperty('value','');
	$('OptionPkgs').setProperty('value','');
	
	var PaintOption = $('PaintSelect').getFirst('option');	
	var ShingleOption = $('ShingleSelect').getLast('option');
	//go through each of the options and update the total and option list for selected options
	$$('#Quote-OptPkg input').each(function(userchoice,i){
		if(userchoice.getProperty('value') > 0){
			//update the total
			var OptPkgAmount = (Number(userchoice.getProperty('price')) * Number(userchoice.getProperty('value')));	
			var OptPkgTotal = ($('OptPkgTotal').innerHTML).replace(/[$,]/g,"");
			var FinalOptPkgTotal = (Number(OptPkgAmount) + Number(OptPkgTotal)).numberFormat();
			$('OptPkgTotal').innerHTML='$' + FinalOptPkgTotal;
			//update the list
			var OptPkgSummary = $('OptionPackages').getProperty('value');
			var OptPkgPrice = Number(userchoice.getProperty('price')).numberFormat();
			var OptionPackage = userchoice.getProperty('value') + " - " + userchoice.getProperty('label') + " (+ $" + OptPkgPrice + ')';
			$('OptionPackages').setProperty('value',OptPkgSummary + OptionPackage + "\n");
			//expand the option textarea list
			var OptPkgRows = Number($('OptionPackages').getProperty('rows'));
			OptPkgRows++;
			$('OptionPackages').setProperty('rows',OptPkgRows);
			
			$('OptionPkgQty').setProperty('value',$('OptionPkgQty').getProperty('value') + userchoice.getProperty('value') + ',');
			$('OptionPkgs').setProperty('value',$('OptionPkgs').getProperty('value') + userchoice.getProperty('name') + ',');
			
			//include the paint & shingles for the Appearance Package
			if(userchoice.getProperty('name') == 'APP'){
				PaintOption.setProperties({
					price: 0,
					label: PaintOption.retrieve('label') + ' (+ $ Included w/Appearance Pkg)'
				});	
				UpdateColorSelection(PaintOption);
				
				ShingleOption.setProperties({
					price: 0,
					label: ShingleOption.retrieve('label') + ' (+ $ Included w/Appearance Pkg)'
				});	
				UpdateColorSelection(ShingleOption);
			}
		}
		else{
			//reset the paint & shingles for no Appearance Package
			if(userchoice.getProperty('name') == 'APP'){
				PaintOption.setProperties({
					price: PaintOption.retrieve('price'),
					label: PaintOption.retrieve('label') + ' (+ $' + PaintOption.retrieve('price') + ')'
				});
				UpdateColorSelection(PaintOption);
				
				var PriceLabel = ShingleOption.retrieve('price');
				if(PriceLabel == 0){
					var PriceLabel = ' Included PRO Upgrade';
				}
				ShingleOption.setProperties({
					price: ShingleOption.retrieve('price'),
					label: ShingleOption.retrieve('label') + ' (+ $' + PriceLabel + ')'
				});
				UpdateColorSelection(ShingleOption);
			}
		}
	});
	QuoteTotal[4]=($('OptPkgTotal').innerHTML).replace(/[$,]/g,"");
	if($('OptionPackages').getProperty('value') == ''){
		$('OptionPackages').setProperty('value','None Selected');
	};
	UpdateTotal();
};

function UpdateOptions(){
	//reset the initial total of the options to 0
	$('OptionsTotal').innerHTML = '$0.00';
	//reset the summary options list to blank and textarea size to 1
	$('Options').setProperty('value','');
	$('Options').setProperty('rows',1);
	$('OptionsQty').setProperty('value','');
	$('OptionsList').setProperty('value','');
	
	//go through each of the options and update the total and option list for selected options
	$$('#Quote-Options input').each(function(userchoice,i){
		if(userchoice.getProperty('value') > 0){
			//update the total
			var OptionAmount = (Number(userchoice.getProperty('price')) * Number(userchoice.getProperty('value')));	
			var OptionsTotal = ($('OptionsTotal').innerHTML).replace(/[$,]/g,"");
			var FinalOptionsTotal = (Number(OptionAmount) + Number(OptionsTotal)).numberFormat();
			$('OptionsTotal').innerHTML='$' + FinalOptionsTotal;
			//update the list
			var OptionSummary = $('Options').getProperty('value');
			if(OptionAmount > 0){
				var OptionPrice = Number(userchoice.getProperty('price')).numberFormat();
			}
			else{
				var OptionPrice = "Custom Quote"; 
			};
			var Option = userchoice.getProperty('value') + " " + userchoice.getProperty('label') + " (+ $" + OptionPrice + '/' + userchoice.getProperty('unit') + ')';
			$('Options').setProperty('value',OptionSummary + Option + "\n");
			//expand the option textarea list
			var OptionRows = Number($('Options').getProperty('rows'));
			OptionRows++;
			$('Options').setProperty('rows',OptionRows);
			
			$('OptionsQty').setProperty('value',$('OptionsQty').getProperty('value') + userchoice.getProperty('value') + ',');
			$('OptionsList').setProperty('value',$('OptionsList').getProperty('value') + userchoice.getProperty('name') + ',');
		}
	});
	QuoteTotal[3]=($('OptionsTotal').innerHTML).replace(/[$,]/g,"");
	if($('Options').getProperty('value') == ''){
		$('Options').setProperty('value','None Selected');
	};
	UpdateTotal();
};

function UpdateSpecialtyPackages(){
	//reset the initial total of the options to 0
	$('SpecialtyTotal').innerHTML = '$0.00';
	//reset the summary options list to blank and textarea size to 1
	$('SpecialtyPackages').setProperty('value','');
	$('SpecialtyPackages').setProperty('rows',1);
	$('SpecialtyItemsQty').setProperty('value','');
	$('SpecialtyItems').setProperty('value','');
	
	//go through each of the options and update the total and option list for selected options
	$$('#Quote-Specialty input').each(function(userchoice,i){
		if(userchoice.getProperty('value') > 0){
			//update the total
			var SpecialtyAmount = (Number(userchoice.getProperty('price')) * Number(userchoice.getProperty('value')));	
			var SpecialtyTotal = ($('SpecialtyTotal').innerHTML).replace(/[$,]/g,"");
			var FinalSpecialtyTotal = (Number(SpecialtyAmount) + Number(SpecialtyTotal)).numberFormat();
			$('SpecialtyTotal').innerHTML='$' + FinalSpecialtyTotal;
			//update the list
			var SpecialtySummary = $('SpecialtyPackages').getProperty('value');
			var SpecialtyPrice = Number(userchoice.getProperty('price')).numberFormat();
			var SpecialityPackage = userchoice.getProperty('value') + " - " + userchoice.getProperty('label') + " (+ $" + SpecialtyPrice + ')';
			$('SpecialtyPackages').setProperty('value',SpecialtySummary + SpecialityPackage + "\n");
			//expand the option textarea list
			var SpecialtyRows = Number($('SpecialtyPackages').getProperty('rows'));
			SpecialtyRows++;
			$('SpecialtyPackages').setProperty('rows',SpecialtyRows);
			
			$('SpecialtyItemsQty').setProperty('value',$('SpecialtyItemsQty').getProperty('value') + userchoice.getProperty('value') + ',');
			$('SpecialtyItems').setProperty('value',$('SpecialtyItems').getProperty('value') + userchoice.getProperty('name') + ',');
		}
	});
	QuoteTotal[4]=($('SpecialtyTotal').innerHTML).replace(/[$,]/g,"");
	if($('SpecialtyPackages').getProperty('value') == ''){
		$('SpecialtyPackages').setProperty('value','None Selected');
	};
	UpdateTotal();
};

function UpdateTotal(){
	var GrandTotal = 0;
	for(var i=0; i<QuoteTotal.length; i++){
		if(QuoteTotal[i] != undefined){
			GrandTotal += Number(QuoteTotal[i]);
		}
	}
	GrandTotal = Number(GrandTotal);
	if(isNaN(GrandTotal) == false){
		var DisplayTotal = '$' + Number(GrandTotal).numberFormat();
		$('SummaryTotal').innerHTML = 'Total: ' + DisplayTotal;
		$('Total').setProperty('value',DisplayTotal);
		$('DBTotal').setProperty('value',GrandTotal);
	}
};

function SaveBuildingQuote(){
	$('Quote-Summary').set('send',{		
		useSpinner: true,
		spinnerTarget: 'SaveQuote',
		onSuccess: function(txt) {
			var PDFViewer = new StickyWin({
			  draggable: true,
			  content: StickyWin.ui('TUFF SHED Quote (#' + txt + ') - Print &amp; Save', '<iframe src="/quotes/' + txt + '.pdf" width="100%" height="600"></iframe>', {
				width: '800px',
				cornerHandle: false
				
			  })
			});
			//analytics tracking
			try{
				_gaq.push(['_setAccount', 'UA-XXXXX-X']);
				_gaq.push(['_trackPageview','/products_savequote.cfm']);
				_gaq.push(['_addTrans',
				   txt,           // order ID - required
				   'TUFF SHED', // affiliation or store name
				   $('DBTotal').getProperty('value'),          // total - required
				   '0',           // tax
				   '0',          // shipping
				   $('City').getProperty('value'),       // city
				   $('State').getProperty('value'),     // state or province
				   'USA'             // country
				]);
				_gaq.push(['_addItem',
				   txt,           // order ID - necessary to associate item with transaction
				   $('ModelID').getProperty('value'),           // SKU/code - required
				   $('Model').getProperty('value'),        // product name
				   $('Width').getProperty('value') + 'x' + $('Length').getProperty('value'),   // category or variation
				   $('DBTotal').getProperty('value'),          // unit price - required
				   '1'               // quantity - required
				]);
				_gaq.push(['_trackTrans']);
			}
			catch(err){}
		},
		onFailure: function() {
			alert('Error saving quote, please try again!');
		}
	});
	
	$('Quote-Summary').send();
};



