function bSelectCategory(){
	var catID = $F('productCategory');
	c_nc = new Array('0007', '0031');
	for(i=0;i<c_nc.length;i++){
		if (catID == c_nc[i]) {
			$('productCoverage').hide();
			$('whichSku').value = '1';
			break;
		}else{
			$('productCoverage').show();
			$('whichSku').value = '0';
		}
	}
	new Ajax.Updater('productMake', '/includes/files/basket_search.php', {
		method: 'post',
		parameters: {
			a: 'selectCategory',
			catID : catID
		}
	});
}

function bSelectMake(){
	var catID = $F('productCategory');
	var makeID = $F('productMake');
	new Ajax.Updater('productModel', '/includes/files/basket_search.php', {
		method: 'post',
		parameters: {
			a: 'selectMake',
			catID : catID,
			makeID : makeID			
		}
	});
}

function bSelectModel(){
	var catID = $F('productCategory');
	var makeID = $F('productMake');
	var modelID = $F('productModel');
	new Ajax.Updater('productCoverage', '/includes/files/basket_search.php', {
		method: 'post',
		parameters: {
			a: 'selectModel',
			catID : catID,
			makeID : makeID,	
			modelID : modelID
		}
	});
}

function addToCart(){
	if ($F('whichSku') == '1') {
		var sku = $F('productModel');
	}else{
		var sku = $F('productCoverage');
	}	
	new Ajax.Request('/includes/files/basket_search.php', {
		method: 'post',
		parameters: {
			a: 'addToCart',
			sku : sku
		},
		onSuccess: function(transport) {
			var r = transport.responseText;	
			if(r=="success"){
				window.parent.location='/basket.php?intcmp=quickAddBasket';
			}else{
				$('addToError').update('Could not add item');
				return false;
			}
		}
	});
}

/* creates the price property of all HTMLOptionElements for making it easier to pass the option's price around */
//HTMLOptionElement.prototype.price = 0;
/*
 * Class: ShippingCalculator
 * Handles the shipping calculator in basket.php
 */
var ShippingCalculator = Class.create({
    /*
    * Constructor
    * Not much needs to be done here, set a few member variables and watch for some events
    * Params: subtotal - float - the initial subtotal of all items in the cart
    */
    initialize: function (subtotal) {
        /* creates the price property of all HTMLOptionElements for making it easier to pass the option's price around */
        //HTMLOptionElement.prototype.price = 0;
        /* basic initialization of needed DOM Objects */
        this.shipping_calc_form = $('shipping_calc_form');
        this.shipping_zip = $('shipping_zip');
        this.shipping_country = $('shipping_country');
        this.shipping_method = $('shipping_method');
        this.shipping_value = $('shipping_value');
        this.order_total = $('order_total');
        this.error_box = $('ship_calc_error');
        this.subtotal = subtotal;
        this.ajax_loader = $('ajax_loader');
        this.dollar_sign_present = false; // used when setting the HTML value for shipping
        this.first = true;

        /* watch for some custom events */
        document.observe('shipping:started', this.loading.bind(this)); // onCreate in getShippingRates
        document.observe('shipping:complete', this.complete.bind(this)); // onComplete in getShippingRates
        document.observe('totals:changed', this.getShippingRates.bind(this)); // this allows external classes to trigger the recalc of shipping rates
        document.observe('subtotal:changed', this.changeSubtotal.bind(this)); // this lets external classes reset the subtotal

        /* watch some built-in events */
        this.shipping_zip.observe('keyup', this.changeToUnitedStates.bind(this));
        //this.shipping_country.observe('change', this.getShippingRates.bind(this));
        this.shipping_calc_form.observe('submit', this.getShippingRates.bind(this));
        this.shipping_method.observe('change', this.updateTotals.bind(this));

        /* run the calc if zip and country are not empty */
        if (!this.shipping_zip.value.empty() && !this.shipping_country.value.empty())
            this.getShippingRates();
    },
    changeToUnitedStates: function () {
        if (this.shipping_zip.value.length == 5) {
            new Ajax.Request('/store/checkout/ajax/safe_cart_ajax.php?nocache='+this.noCacheString(), {
                method: 'post',
                parameters: {
                    zip: this.shipping_zip.value,
                    func: 'isZipUnitedStates'
                },
                onSuccess: function (e) {
                    if (e.responseText == 'true') {
                        this.shipping_country.value = 461;
                    }
                }.bind(this)
            });
        }
    },
    /*
     * changeSubtotal
     * changes the classes subtotal value.  Useful when firing the subtotal:changed event from an external class that interfaces with the shipping calc
     */
    changeSubtotal: function (event) {
        this.subtotal = event.memo;
    },
    /*
    * getShippingRates
    * creates and AJAX request that gets the shipping rates based on the form values for zip and country
    */
    getShippingRates: function (event) {
        // make sure both zip and country are selected
        if (!this.shipping_zip.value.empty() && !this.shipping_country.value.empty() && this.subtotal > 0) {
            this.error_box.hide();
            $('ship_calc_zip_error').hide();
            if (this.shipping_country.value == '461' && this.shipping_zip.value.length != 5) {
                $('ship_calc_zip_error').show();
            }
            else {
                // run some ajax to get the shipping rates
                new Ajax.Request('/store/checkout/ajax/safe_cart_ajax.php?nocache='+this.noCacheString(), {
                    method: 'post',
                    parameters: {
                        szip: this.shipping_zip.value,
                        scountry: this.shipping_country.value,
                        func: 'getShippingRates'
                    },
                    onCreate: function () {
                        document.fire('shipping:started'); // calls: loading()
                    },
                    onComplete: function (e) {
                        document.fire('shipping:complete', e.responseText.evalJSON()); // calls: complete()
                    }
                });
            }
        }
        else {
            // clear out the shipping method dropdown
            //this.removeShippingOptions();
            this.shipping_method.update('<option value="">-- select --</option>');
            
            if (event.memo != 'hide_error')
                this.error_box.show();
            // set shipping rate to 0
            if (!this.first)
                $('shipping_value').update('0.00');
            this.first = false;
        }
    },
    /*
    * loading
    * This is for the onCreate in the Ajax object in getShippingRates.  It shows the ajax loader gif and resets
    * the first entry in the shipping method drop down
    */
    loading: function () {
        this.ajax_loader.show();
        this.shipping_method[0].text = '-- click calculate --';
    },
    /*
    * complete
    * This is for the onComplete in the Ajax object in getShippingRates.  It hides the ajax loader and handles
    * the response from the Ajax request.
    * params: event - the event that triggered this call.  event.memo will contain all the useful data
    */
    complete: function (event) {
        /* remove the old options */
        for (var i = this.shipping_method.length; i > 0; i--) {
            if (this.shipping_method[i] != undefined)
                this.shipping_method[i].remove();
        }
        /* reset the prices */
        this.shipping_value.innerHTML = '0.00';
        this.order_total.innerHTML = this.subtotal.toFixed(2);

        if (Object.isArray(event.memo)) { // if there is more than one shipping method, it will be an Array
            // loop through all the shipping methods
            for (var i = 0; i < event.memo.length; i++) {
                // create a new option Element and set the values of various properties
                var option = new Element('option', {
                    value: event.memo[i].post_value
                });
                option.price = event.memo[i].price;
                option.text = event.memo[i].display_name + ' -- $' + option.price.toFixed(2);
                if (event.memo[i].select_rate)
                    option.selected = true;
                
                // free shipping ? - let the user know
                if (event.memo[i].price == 0)
                    option.text = 'FREE ' + option.text;

                // add this option to the drop down
                this.shipping_method.options.add(option);
            }
        }
        else { // if there is only on shipping method it will not be an Array
            // create a new option Element and set the values of various properties
            var option = new Element('option', {
                value: event.memo.post_value
            });
            option.price = event.memo.price;
            option.text = event.memo.display_name + ' -- $' + option.price.toFixed(2);
            if (event.memo.select_rate)
                option.selected = true;

            // free shipping ? - let the user know
            if (event.memo[i].price == 0)
                    option.text = 'FREE ' + option.text;

            // add this option to the drop down
            this.shipping_method.options.add(option);
        }

        this.removeShippingOptions();
        this.updateTotals(); // update the grand total to reflect the newly selected shipping option
        this.ajax_loader.hide(); // hide the ajax loader gif
    },
    removeShippingOptions: function () {
        /* stupid cross browser hack */
        try {
            // works in everything but IE 6/7
            this.shipping_method[0].remove(); // remove the first option (it will be something like --select--)
        }
        catch (e) {
            // holding IE's hand - (works in everything but Firefox)
            this.shipping_method.options.remove(0); // remove the first option (it will be something like --select--)
        }
    },
    /*
    * updateTotals
    * This will update the totals displayed in the basket based on the currently selected shipping options
    */
    updateTotals: function () {
        // first set the shipping method
        this.setSelectedShippingMethod(this.shipping_method.options[this.shipping_method.selectedIndex]);
        // set the innerHTML for shipping price
        this.shipping_value.innerHTML = this.shipping_method[this.shipping_method.selectedIndex].price.toFixed(2);
        
        /* if the $ is already there, we don't want to add it again */
        if (!this.dollar_sign_present) {
            this.shipping_value.insert({before: '$'});
            this.dollar_sign_present = true;
        }

        // update the order total
        this.order_total.innerHTML = (this.subtotal + this.shipping_method[this.shipping_method.selectedIndex].price).toFixed(2);
    },
    /*
    * setSelectedShippingMethod
    * a quick Ajax request to set the selected shipping method in a session.  This is done so the user (when moving to
    * checkout) will have the same option selected when the shipping options are loaded on that page.
    */
    setSelectedShippingMethod: function (option) {
        // ajax request to setShipping
        new Ajax.Request('/store/checkout/ajax/safe_cart_ajax.php?nocache='+this.noCacheString(), {
            method: 'post',
            asynchronous: false,
            parameters: {
                option: option.value,
                func: 'setShipping'
            }
        });
    },
    noCacheString: function () {
        return Math.random();
    }
});

function lostPassword(){
	new Ajax.Request('/lost_password.php?nocache='+Math.random(), {
        method: 'post',
        asynchronous: false,
        parameters: {
			action: 'check',
			ajax: 'true',
            email: $F('lostEmail')
        },
        onSuccess: function(response) {
			var resp = response.responseText;
			$('lostResponse').update(resp);
        }
    });
}
