/**

* @author Arthur Kay (art@akawebdesign.com)

* @version 1.3

* @lastedit May 19, 2009

*/



var grandTotalObject = function() {

    var thisObj = this;

    

    this.id = 'grandTotal';

    this.sideId = 'grandTotalSide';



    this.price = parseFloat(0.00);

    

    this.items = new Array();

    

    this.refreshPrice = function() {

        thisObj.price = parseFloat(0.00); //reset the price to 0, then recalculate



        for (var i=0; i<thisObj.items.length; i++) {

            thisObj.price += parseFloat(thisObj.items[i].price);

        }

        

        thisObj.updateDom();

    };

    

    this.updateDom = function() {

        document.getElementById(thisObj.id).innerHTML='<b>$' + thisObj.price.toFixed(2) + '</b>';

        document.getElementById(thisObj.sideId).innerHTML='<b>$' + thisObj.price.toFixed(2) + '</b>';

    };



};



// =====================

//Grand total

// to display at bottom and right-hand column

// =====================

var totalCost = new grandTotalObject();



var totalCostObject = function(domId) {

    var thisObj = this;

    

    this.id = domId;



    this.price = parseFloat(0.00);

    

    this.items = new Array();

    

    this.refreshPrice = function() {

        thisObj.price = parseFloat(0.00); //reset the price to 0, then recalculate



        for (var i=0; i<thisObj.items.length; i++) {

            thisObj.price += parseFloat(thisObj.items[i].price);

        }

        

        thisObj.updateDom();

        totalCost.refreshPrice();

    };

    

    this.updateDom = function() {

        document.getElementById(thisObj.id).innerHTML='<b>$' + thisObj.price.toFixed(2) + '</b>';

    };

};



var priceObject = function(parentObj, domId) {

    var thisObj = this;



    this.price = parseFloat(0.00);

	this.costBeforeDiscount = parseInt(0.00);



    this.id = domId;

	this.parent = parentObj;

	this.multiplicationValue = parseFloat(1);

	this.subtractTenPercent = false;

    

    this.updatePrice = function(cost) {

        thisObj.price = parseFloat(cost) * thisObj.multiplicationValue;

        thisObj.costBeforeDiscount = thisObj.price;



        if (thisObj.subtractTenPercent) {

            var tenPercentDiscount = parseFloat(thisObj.costBeforeDiscount) * parseFloat(0.10);

            thisObj.price = thisObj.price - tenPercentDiscount;

        }



        thisObj.updateDom();

        thisObj.parent.refreshPrice();

    };



    this.updateDom = function() {

        var domElement = document.getElementById(thisObj.id);



        if (domElement) {

            domElement.innerHTML = '$' + thisObj.price.toFixed(2);

        }

    };

    

    this.onLoad = function() {

        var domElement = document.getElementById(thisObj.id);

        

        if (domElement) {

            var stringValue = domElement.innerHTML;



            try {

                // grabs value after "$"

                // and converts to a floating point number

                thisObj.price = parseFloat(stringValue.split('$')[1].split('<')[0]);

                thisObj.costBeforeDiscount= parseFloat(stringValue.split('$')[1].split('<')[0]);

            }

            catch (e) {

                thisObj.price = parseFloat(0.00);

            }

        }

    };

};



function recalculateBoxes(numOfMoves) {

    if (additionalBoxesPrice.multiplicationValue == 2 && numOfMoves == 1) {

        additionalBoxesPrice.multiplicationValue = parseFloat(1);

        additionalBoxesPrice.updatePrice(additionalBoxesPrice.costBeforeDiscount / 2);

        wardrobeBoxesPrice.multiplicationValue = parseFloat(1);

        wardrobeBoxesPrice.updatePrice(wardrobeBoxesPrice.costBeforeDiscount / 2);

		

		plastic_storage.multiplicationValue = parseFloat(1);

        plastic_storage.updatePrice(plastic_storage.costBeforeDiscount / 2);

    }

    else if (additionalBoxesPrice.multiplicationValue == 1 && numOfMoves == 2) {

        additionalBoxesPrice.multiplicationValue = parseFloat(2);

        additionalBoxesPrice.updatePrice(additionalBoxesPrice.costBeforeDiscount);

        wardrobeBoxesPrice.multiplicationValue = parseFloat(2);

        wardrobeBoxesPrice.updatePrice(wardrobeBoxesPrice.costBeforeDiscount);

		

		plastic_storage.multiplicationValue = parseFloat(2);

        plastic_storage.updatePrice(plastic_storage.costBeforeDiscount);

    }

};



function calculateDiscount(trueOrFalse) {

	additionalBoxesPrice.subtractTenPercent = trueOrFalse;

	wardrobeBoxesPrice.subtractTenPercent = trueOrFalse;

	plastic_storage.subtractTenPercent = trueOrFalse;

};



function swapRadioButtons(newId, price) {

	oneWayFall.updatePrice(0.00);

	oneWaySpring.updatePrice(0.00);

	roundTrip.updatePrice(0.00);

	storageOnly.updatePrice(0.00);

	if (oneWayFall.id == newId) {

        calculateDiscount(false);

		recalculateBoxes(1);

		oneWayFall.updatePrice(price);

	}

	else if (oneWaySpring.id == newId) {

        calculateDiscount(false);

        recalculateBoxes(1);

        oneWaySpring.updatePrice(price);

    }

	else if (roundTrip.id == newId) {

        calculateDiscount(true);

        recalculateBoxes(2);

		

        //coupon only good on one-way trips. Clear the code and recalculate.

        document.getElementById('couponCodeBox').value = '';

        couponCodeDiscountPercent = parseFloat(0.00);

        couponCodePrice.updatePrice(0.00);



        roundTrip.updatePrice(price);

    }

    else if (storageOnly.id == newId) {

        calculateDiscount(false);

        recalculateBoxes(1);

        storageOnly.updatePrice(price);

    }

};



function updateRoundTrip(){

		if(documnet.getElementById('RTrip').value > 0 || documnet.getElementById('RTrip').value != ''){

		//roundTrip

		var pr1 = documnet.getElementById('RTrip').value*2; 

		var pr2 = (pr1*2)/100; 

		roundTrip.updatePrice(pr1+pr2); 

		//alert(pr1+pr2);

	}

}



function calculateCost(currentObj, pricePerUnit, numOfunits) {

    var newCost = numOfunits * pricePerUnit;

    currentObj.updatePrice(parseFloat(newCost));

    applyDiscount();

};





// =====================

//Moving Services

// =====================

var movingServicesTotal = new totalCostObject('movingServicesTotal');

totalCost.items.push(movingServicesTotal);



    var couponCodeDiscountPercent = parseFloat(0.00);



    function applyDiscount() {

        couponCodePrice.updatePrice(parseFloat(0.00));



		var discountPrice = parseFloat(movingServicesTotal.price * couponCodeDiscountPercent);



		couponCodePrice.updatePrice('-' + discountPrice);

    };



    var couponCodePrice = new priceObject(movingServicesTotal, 'couponCodePrice');

    movingServicesTotal.items.push(couponCodePrice);



    var oneWayFall = new priceObject(movingServicesTotal, 'oneWayFall');

    movingServicesTotal.items.push(oneWayFall);

    var oneWaySpring = new priceObject(movingServicesTotal, 'oneWaySpring');

    movingServicesTotal.items.push(oneWaySpring);

    var roundTrip = new priceObject(movingServicesTotal, 'roundTrip');

    movingServicesTotal.items.push(roundTrip);

    var storageOnly = new priceObject(movingServicesTotal, 'storageOnly');

    movingServicesTotal.items.push(storageOnly);



    var additionalBoxesPrice = new priceObject(movingServicesTotal, 'additionalBoxesPrice');

    movingServicesTotal.items.push(additionalBoxesPrice);

    var wardrobeBoxesPrice = new priceObject(movingServicesTotal, 'wardrobeBoxesPrice');

    movingServicesTotal.items.push(wardrobeBoxesPrice);

	var plastic_storage = new priceObject(movingServicesTotal, 'plastic_storage');

    movingServicesTotal.items.push(plastic_storage);

	

    var emptyBoxes = new priceObject(movingServicesTotal, 'emptyBoxes');

    movingServicesTotal.items.push(emptyBoxes);



	var fridgediv = new priceObject(movingServicesTotal, 'fridgediv');

    movingServicesTotal.items.push(fridgediv);

	

	var TvUpTo39div = new priceObject(movingServicesTotal, 'TvUpTo39div');

    movingServicesTotal.items.push(TvUpTo39div);

	

	var TvUpTo40div = new priceObject(movingServicesTotal, 'TvUpTo40div');

    movingServicesTotal.items.push(TvUpTo40div);

	

	var futondiv = new priceObject(movingServicesTotal, 'futondiv');

    movingServicesTotal.items.push(futondiv);

	

	var bicyclediv = new priceObject(movingServicesTotal, 'bicyclediv');

    movingServicesTotal.items.push(bicyclediv);



// =====================

//Additional Moving Supplies

// =====================

var additionalMovingSuppliesTotal = new totalCostObject('additionalMovingSuppliesTotal');

totalCost.items.push(additionalMovingSuppliesTotal);



    var addlBoxes = new priceObject(additionalMovingSuppliesTotal, 'addlBoxes');

    additionalMovingSuppliesTotal.items.push(addlBoxes);



    var addlWardrobeBoxes = new priceObject(additionalMovingSuppliesTotal, 'addlWardrobeBoxes');

    additionalMovingSuppliesTotal.items.push(addlWardrobeBoxes);



    var addlTape = new priceObject(additionalMovingSuppliesTotal, 'addlTape');

    additionalMovingSuppliesTotal.items.push(addlTape);



    var addlOpeners = new priceObject(additionalMovingSuppliesTotal, 'addlOpeners');

    additionalMovingSuppliesTotal.items.push(addlOpeners);





// =====================

//Rentals

// =====================

var rentalsTotal = new totalCostObject('rentalsTotal');

totalCost.items.push(rentalsTotal);



    var rentalAppliance = new priceObject(rentalsTotal, 'rentalAppliance');

    rentalsTotal.items.push(rentalAppliance);





// =====================

//Storage

// =====================

var storageTotal = new totalCostObject('storageTotal');

totalCost.items.push(storageTotal);





// =====================

//Gas Surcharge

// =====================

var gasSurchargeTotal = new priceObject(totalCost, 'gasSurchargeTotal');

totalCost.items.push(gasSurchargeTotal);





// =====================

// ON LOAD

// =====================

function loadPageData() {

    for (var i=0; i<totalCost.items.length; i++) {

        var subsection = totalCost.items[i];

        

        if (subsection.items) {

            for (var j=0; j<subsection.items.length; j++) {

                subsection.items[j].onLoad();

            }

            subsection.refreshPrice();

        }

    }//end FOR



	//Fire the onclick event for the Choose Your Service radio input

	var serviceRadioButton = document.getElementsByName('Trip');

	for (var z=0; z<serviceRadioButton.length; z++) {

	    if (serviceRadioButton[z].checked) {

		    serviceRadioButton[z].onclick();

	    }

	}



    var couponCodeInputBox = document.getElementById('couponCodeBox');

    if (couponCodeInputBox.value) {

        validateCode(couponCodeInputBox.value);

    }



    var homeZipCode = document.getElementsByName('HomeZip')[0];

    if (homeZipCode.value) {

        homeZipCode.onblur();

    }



	// rental items need the price updated a different way

	var rentalItems = document.getElementsByName('Rental');

	for (var a=0; a < rentalItems.length; a++) {

		if (rentalItems[a].checked) {

			rentalItems[a].onclick();

		}

	}

};





// =====================

// Validate Coupon Code

// =====================

function validateCode(couponCode) {

	if (roundTrip.price == 0.00) {

		if (couponCodePrice.price == 0.00) {

			var ajaxConnection = new Ext.data.Connection();

			

			ajaxConnection.request({

				url: 'coupon.php',

				params: {

					c: couponCode

				},

				callback: function(options, success, response){

					if (success) {

						if (response.responseText != 'false') {

							couponCodeDiscountPercent = parseFloat(response.responseText) * parseFloat(0.01);

							applyDiscount();

						}

						else {

							//alert('The supplied coupon code does not offer a discount.');

							couponCodePrice.updatePrice(0.00);

						}

					}

					else {

						alert('The validation service is currently unavailable. The coupon will be checked for validity when this form has been submitted.');

					}

				}

			});

		}//end if (couponCodePrice.price == 0.00)

	}//end if (roundTrip.price == 0.00)

	else {

		alert('Coupons may only be used on one-way moves.');

	}

};



function checkZipcodeForSurcharge(zipcode) {

	var ajaxConnection = new Ext.data.Connection();

	

	ajaxConnection.request({

		url: 'zip.php',

		params: {

			z: zipcode

		},

		callback: function(options, success, response) {

			if (response.responseText == 'out') {

				gasSurchargeTotal.updatePrice(50.00);

			}

			else {

				gasSurchargeTotal.updatePrice(0.00);

			}

		}

	});

};





/**

* Below are methods which assist the CSS slide effects

*/

var layoutAreas = [

    'bar-chooseyourschedule',

    'bar-additionalmovingsupplies',

    'bar-rentals',

    'bar-storage'

];



function turnArrowDown(domId) {

    document.getElementById(domId).className = 'arrow-down';

}



function turnArrowToSide(domId) {

    document.getElementById(domId).className = 'arrow-side';

}



function swapArrows(domId) {

    var currentClass = document.getElementById(domId).className;



    if (currentClass == 'arrow-side') { 

        turnArrowDown(domId);

    }

    else {

        turnArrowToSide(domId);

    }

}



function chooseScheduleOption(option, price) {

    var fallSchedule = document.getElementById('row-fallSchedule');

    var springSchedule = document.getElementById('row-springSchedule');

    

    var scheduleSection = document.getElementById('section-chooseyourschedule');

    var movingSuppliesSection = document.getElementById('section-additionalMovingSupplies');

    var rentalsSection = document.getElementById('section-rentals');



    if (option == 'oneWaySpring') {

        fallSchedule.style.display = 'none';

        springSchedule.style.display = '';

        scheduleSection.style.display = '';

        movingSuppliesSection.style.display = '';

        rentalsSection.style.display = '';



        swapRadioButtons(option, price);

		change_price();

        ddaccordion.toggleone('headerBar', 0, 'expand');

        turnArrowToSide('bar-chooseyourschedule');

    }

    else if (option == 'oneWayFall') {

        fallSchedule.style.display = '';

        springSchedule.style.display = 'none';

        scheduleSection.style.display = '';

        movingSuppliesSection.style.display = '';

        rentalsSection.style.display = '';

		change_price();

        swapRadioButtons(option, price);

        ddaccordion.toggleone('headerBar', 0, 'expand');

        turnArrowToSide('bar-chooseyourschedule');

    }

    else if (option == 'roundTrip') {

        fallSchedule.style.display = '';

        springSchedule.style.display = '';

        scheduleSection.style.display = '';

        movingSuppliesSection.style.display = '';

        rentalsSection.style.display = '';

		//alert(price);

		change_price();

        swapRadioButtons(option, price);

		

        ddaccordion.toggleone('headerBar', 0, 'expand');

        turnArrowToSide('bar-chooseyourschedule');

    }

    else { //summer storage only

        fallSchedule.style.display = 'none';

        springSchedule.style.display = 'none';

        scheduleSection.style.display = 'none';

        movingSuppliesSection.style.display = 'none';

        rentalsSection.style.display = 'none';

		change_price();

        swapRadioButtons(option, price);



        //clear input values in Choose Your Schedule section

        document.getElementsByName('pickupboxes')[0].click();





        var dropBoxOne = document.getElementsByName('ExtraBoxes')[0];



        dropBoxOne.options[0].selected = true;



        if (dropBoxOne.onchange) { dropBoxOne.onchange(); }



        var dropBoxTwo = document.getElementsByName('ExtraWardrobe')[0];



        dropBoxTwo.options[0].selected = true;



        if (dropBoxTwo.onchange) { dropBoxTwo.onchange(); }



        document.getElementById('couponCodeBox').value = '';

        couponCodeDiscountPercent = parseFloat(0.00);

        couponCodePrice.updatePrice(0.00);



        ddaccordion.toggleone('headerBar', 3, 'expand');

        turnArrowToSide('bar-storage');

    }

}



