//  Takes a simple array and populates a given select box (use the ID)
function fillSelect ( objId, data ) {

    var obj = $(objId);

    if ( !obj ) {

        return false;

    } else {

        for ( i = 0; i < data.length; i++ ) {

            obj.options[obj.length] = new Option (data[i], data[i]);

        }

    }

}


//  Takes a postcode sector and returns the price
function postCodePrice ( postcode ) {

    var found        = false;
    var index, price = null;

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

        if ( postcode != deliveryPostCodes[i] ) {

            continue;

        } else {

            found = true;
            index = i;
            price = postCodePrices[i];

        }

    }

    return ( found ) ? [price, index] : false;

}

// new delivery prices as of sept 10
var deliveryPostCodes = new Array( 'BN', 'BR', 'CM', 'CR', 'CT', 'DA', 'E', 'EC', 'EN', 'GU', 'HA', 'IG', 'KT', 'ME', 'NW', 'RH', 'RM', 'SE', 'SM', 'SS', 'SW', 'TN', 'TW', 'UB', 'W', 'WC', 'WD' );
var postCodePrices    = new Array( '50', '0', '50', '0', '0', '0', '50', '50', '50', '50', '50', '50', '0', '0', '50', '0', '0', '50', '0', '0', '50', '0', '50', '50', '50', '50', '50' );

//var deliveryPostCodes = new Array( 'BN', 'BR', 'CM', 'CR', 'CT', 'DA', 'E', 'EC', 'EN', 'GU', 'HA', 'IG', 'KT', 'ME', 'NW', 'RH', 'RM', 'SE', 'SM', 'SS', 'SW', 'TN', 'TW', 'UB', 'W', 'WC', 'WD' );
//var postCodePrices    = new Array( '40', '0', '40', '0', '0', '0', '40', '40', '40', '40', '40', '40', '0', '0', '40', '0', '0', '40', '0', '0', '40', '0', '40', '40', '40', '40', '40' );



Event.observe(window, 'load', function ( e ) {

    if ( $('addToBasketLink') ) {

        Event.observe('addToBasketLink', 'click', function ( e ) {

        	Event.stop(e);

            if ( $('addToBasket') ) {
                $('addToBasket').submit();
            }

        });

    }


    if ( $('recalculate') && $('basket_summary') && $('command') ) {

        Event.observe( 'recalculate', 'click', function (e) {

        	Event.stop(e);

            if (document.all) {
				$('basket_summary').action = 'shop/basket.html';
			} else {
				$('basket_summary').action = 'shop/basket.html';
			}

            $('command').value = 'recalculate';
            $('basket_summary').submit();

        });

    }


    if ( $('deliveryPostcode') && $('deliveryPostcode').type != 'hidden' ) {

        //  Populate the dropdown with postcodes
        //fillSelect( 'deliveryPostcode', limitedPostCodes );
        fillSelect( 'deliveryPostcode', deliveryPostCodes );

        //  Attach the function to get the price and add it
        Event.observe( 'deliveryPostcode', 'change', function (e) {

            var obj = $('deliveryPostcode');
            var value = obj.options[obj.selectedIndex].value

            if ( value == '' ) {

                $('delivery_cost').update('0');

            } else {

                var index       = obj.selectedIndex - 1;

                var delivery    = postCodePrice ( value );
                var price       = delivery[0];

                var price_text  = ( price == '0') ? 'FREE' : price;
                var final_total = ( price == '0') ? $('basket_total').value : ( parseInt( $('basket_total').value ) + parseInt( postCodePrice( deliveryPostCodes[index] ) ) );

                $('delivery_cost').update( price_text );
                $('final_total_label').update( final_total );
            }

            //  Save to AJAX
                if (document.all) {
                	var url = 'php/ajax.php';
				} else {
                	var url = 'php/ajax.php';
				}

            url += '?command=save_delivery'
                    + '&session_id=' + $('session_id').value
                    + '&price=' + price
                    + '&index=' + delivery[1];

            new Ajax.Request(url, {
                method: 'get'
            });

        });


        //  Loading for the first time so check for saved delivery information
        if (document.all) {
            var url = 'php/ajax.php';
		} else {
            var url = 'php/ajax.php';
		}

        url     += '?command=load_delivery'
                + '&session_id=' + $('session_id').value

        new Ajax.Request(url, {
            method: 'get',
            onSuccess: function (transport) {
                var text = transport.responseText;

                if (text != ',') {

                    text = text.split(',');

                    var price = ( postCodePrices[text[1]] == '0') ? 'FREE' : postCodePrices[text[1]];
                    var final_total = ( postCodePrices[text[1]] == '0') ? $('basket_total').value : ( parseInt( $('basket_total').value ) + parseInt( text[0] ) );

                    $('delivery_cost').update( price );
                    $('final_total_label').update( final_total );

                    $('deliveryPostcode').selectedIndex = parseInt( text[1] ) + 1;

                }

            }
        });

    }


    if ( $('addressForm') ) {

        /*******************************
            Checkout form validation
        *******************************/

        Event.observe( 'addressForm', 'submit', function (e) {

            //  RegExp for roughly matching a postcode
            var postcode_regexp = new RegExp( '^([A-Z]{1,2})[1-9][0-9]?[A-Z]? [0-9][A-Z]{2}$' );
            var submitForm = true;

            //  Change to upper case
            $('postcode').value = $('postcode').value.toUpperCase();
            $('delPostcode').value = $('delPostcode').value.toUpperCase();

            //  Remove non-alphanumeric characters
            $('postcode').value = $('postcode').value.replace( /[^A-Z0-9]/g, '' );
            $('delPostcode').value = $('delPostcode').value.replace( /[^A-Z0-9]/g, '' );

            //  Insert space (Outcode + [space] + Incode)
            $('postcode').value = $('postcode').value.substring( 0, $('postcode').value.length-3 ) + ' ' + $('postcode').value.substring( $('postcode').value.length-3 );
            $('delPostcode').value = $('delPostcode').value.substring( 0, $('delPostcode').value.length-3 ) + ' ' + $('delPostcode').value.substring( $('delPostcode').value.length-3 );

            var postCode = ( $('openForm2').checked ) ? $('delPostcode').value : $('postcode').value;



            //  Test entry
            if ( !postcode_regexp.test( postCode ) ) {

                //  Not ok
                alert('Sorry, your postcode appears to be invalid');
                Event.stop(e);
                return false;

            } else {

				var deliveryIndex = $('delivery_index').value;

                //  Save sector found in RegExp
                var postCodeSector = RegExp.$1;

                //  If they don't match
                if ( postCodeSector != deliveryPostCodes[deliveryIndex] ) {

                    //  Stop form submission
                    Event.stop(e);

                    //  Message to show to user
                    var message = 'The post code you entered does not match the one selected for delivery.'
                                    + '\nWould you like to change the order?'
                                    + '\n'
                                    + '\n-> Click "Ok" to change the delivery on the order.  (Any information on this form will be lost.)'
                                    + '\n-> Click "Cancel" to change the postcode on this form.'

                    //  Show message and stay/go depending on user's action
                    if ( !confirm( message ) ) {
                        submitForm = false;
                        //alert("cancel");
                    } else {
                        if (document.all) {
                            document.location.href = 'basket.html';
                        } else {
                            document.location.href = 'shop/basket.html';
                        }
                    }

                }

            }

            //alert((submitForm)?"submit":"leave");
            //if (!submitForm) {
                //return false;
            //}

        });

    }

});

