/****
 *   common.js v 1.0
 */

$J(document).ready(function(){
	// IE6 check
	if($J.browser.msie && $J.browser.version=="6.0") {
		IE6popup();
	}
	
    /**************** Main Page - *****************/
    /* Newsletter signup */
    $J('input.signupfield').focus(function(e){
        e.preventDefault();
        $J(this).val('');
    });

    // JS - jul 17 2011
    $J('#search').focus(function (e) {
      
      $val = $J(this).val();
      if ($val=='Product or keyword'){
         $J(this).val('');
      }
    });


    $J('input.go').click(function (e) {
        e.preventDefault();

        var email = $J('input.signupfield').val();
        $J.ajax({
            type: 'POST',
            url: __NEWSLETTER_URL,
            data: {
                email:email
            },
            cache: false,
            async: true,
            complete: function (data){
                alert ('Thank you for signing up for our newsletter!');
            }
        });
    });

    if ($J('#slide').length!=0){
        $J('#slide').nivoSlider({
            effect: 'fade', //'sliceDown', //Specify sets like: 'fold,fade,sliceDown'
            //slices:15,
            animSpeed:1000,
            pauseTime:3000,
            startSlide:0, //Set starting Slide (0 index)
            directionNav:false, //Next & Prev
            directionNavHide:false, //Only show on hover
            controlNav:true, //1,2,3...
            controlNavThumbs:false, //Use thumbnails for Control Nav
            controlNavThumbsFromRel:false, //Use image rel for thumbs
            controlNavThumbsSearch: '.jpg', //Replace this with...
            controlNavThumbsReplace: '_thumb.jpg', //...this in thumb Image src
            keyboardNav:true, //Use left & right arrows
            pauseOnHover:true, //Stop animation while hovering
            manualAdvance:true, //Force manual transitions
            captionOpacity:0.8, //Universal caption opacity
            beforeChange: function(){},
            afterChange: function(){},
            slideshowEnd: function(){} //Triggers after all slides have been shown
        });
    }

    /* Sign-In Popup */
    var SignIn = {
        redirectToUrl: null,
        container: null,
        bind: function(){
            $J('#topaccount a.sign-in').click(function (e) {
                e.preventDefault();
                SignIn.init();
            });
        },
        init: function (redirectToUrl) {
            if (redirectToUrl!=undefined){
                SignIn.redirectToUrl = redirectToUrl;
            }
            $J('#signin-content').modal({
                overlayId: 'signin-overlay',
                containerId: 'signin-container',
                closeHTML: null,
                minHeight:230,
                opacity:40,
                overlayClose:true,
                onShow:SignIn.show,
                onClose:SignIn.close
            });
        },
        show: function (d) {
            $J('#signin-container button.signin').click(function (e) {
                e.preventDefault();

                var email = $J('#signin-container #username').val();
                var password = $J('#signin-container #password').val().replace(/^\s+|\s+$/g,"");

                $J.ajax({
                    type: "POST",
                    url: __LOGIN_URL,
                    cache: false,
                    data: "login[username]=" + email + "&login[password]=" + password,
                    success: function(data){
                        if (data.search(/error-msg/i) == -1){
                            if (SignIn.redirectToUrl!=null){
                                window.location = SignIn.redirectToUrl;
                            }
                            else {
                                window.location.reload();	       /* Login OK, reload current page */
                            }
                        } else {
                            window.location.href= __LOGIN_PAGE + '?badlogin=1&user=' + email; /* Login Failed, reload to login page */
                        }
                    }
                });
            });

            $J('#signin-container #password').keydown(function(e){
                if (e.keyCode == 13){
                    e.preventDefault();
                     $J('#signin-container button.signin').trigger('click');
                }
            });

        },
        close: function (d) {
            var self = this;
            d.container.animate(
            {
                top:"-" + (d.container.height() + 20)
            },
            500,
            function () {
                self.close(); // or $.modal.close();
            }
            );
        }
    };
    SignIn.bind();



    /* Forced Sign-In Popup */
    var ForcedSignIn = {
        redirectToUrl: null,
        container: null,
        init: function (redirectToUrl) {
            if (redirectToUrl!=undefined){
                ForcedSignIn.redirectToUrl = redirectToUrl;
            }
            $J('#forced-signin-content').modal({
                overlayId: 'forced-signin-overlay',
                containerId: 'forced-signin-container',
                closeHTML: null,
                minHeight:230,
                opacity:40,
                overlayClose:true,
                onShow:ForcedSignIn.show,
                onClose:ForcedSignIn.close
            });
        },
        show: function (d) {
            $J('#forced-signin-container button.btn-signin').click(function (e) {
                e.preventDefault();

                var email = $J('#forced-signin-container #username').val();
                var password = $J('#forced-signin-container #password').val().replace(/^\s+|\s+$/g,"");

                $J.ajax({
                    type: "POST",
                    url: __LOGIN_URL,
                    cache: false,
                    data: "login[username]=" + email + "&login[password]=" + password,
                    success: function(data){
                        if (data.search(/error-msg/i) == -1){
                            if (ForcedSignIn.redirectToUrl!=null){
                                window.location = ForcedSignIn.redirectToUrl;
                            }
                            else {
                                window.location.reload();	       /* Login OK, reload current page */
                            }
                        } else {
			    window.location.href= __LOGIN_PAGE + '?badlogin=1&user=' + email; /* Login Failed, reload to login page */
                        }
                    }
                });
            });

            $J('#forced-signin-container button.btn-continue-as-guest').click(function (e) {
                e.preventDefault();
                $J.modal.close();
                //self.close();
                // JS - jul 16 2011 - user closed popup, set cookie so they wont be prompted again
                manipulateCookie("SKIP_LOGIN_PROMPT", "true", { expires: 1, path:'/' });

                window.location = ForcedSignIn.redirectToUrl;

            });

            $J('#forced-signin-container #password').keydown(function(e){
                if (e.keyCode == 13){
                    e.preventDefault();
                    $J('#forced-signin-container button.btn-signin').trigger('click');
                }
            });

        },
        close: function (d) {
            // JS - jul 16 2011 - user closed popup, set cookie so they wont be prompted again
            manipulateCookie("SKIP_LOGIN_PROMPT", "true", { expires: 1, path:'/' });

            var self = this;
            d.container.animate(
               { marginLeft: "100%"} ,
               500,
               function () {
                  //self.close(); // or $J.modal.close();
                    $J.modal.close();

                  window.location = ForcedSignIn.redirectToUrl;

               }
           );
        }
    };



    /***** Forgot Password Page  ****/
    $J('#loginagain').submit(function(e){
        e.preventDefault();

        hideError();
        var validator = new Validation($('form-validate1'));
        validator.reset();
        if (!validator.validate()){
            return false;
        }

        $J.ajax({
            type: "POST",
            url: __LOGIN_URL,
            cache: false,
            data: "login[username]=" + $J('#loginagain #login-email').val() + "&login[password]=" + $J('#loginagain #login-password').val(),
            success: function(data){
                if (data.search(/error-msg/i) == -1){
                    window.location.href=__ACCOUNT_PAGE; /* Login OK, redirect to account page */
                } else {
                    showError('div.col-main', 'Invalid login or password.');
                }
            }
        });
    });

    /*********** Gift Reminders on Account page ********/
    if ($J('#gift-reminders').length!=0){

       function deleteGiftReminder(e){
            e.preventDefault();
            x = $J(e.currentTarget).parents('.one-gift-reminder').remove();
            __TOTAL_GIFT_REMINDERS--;
        }

        function updateDaysInMonth(obj){
              var monthsDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
              var month = (($J(obj).val() ) * 1) -1;
              var daysInThisMonth = monthsDays[month];

              var daySelectCtrl = $J(obj).parent().find('select.reminder-day');
              daySelectCtrl.children().remove();
              daySelectCtrl.children().end().append( '<option value="">Day</option>') ;
              for (i=1; i<=daysInThisMonth; i++){
                var entry = '<option value="' + ((i <10) ? ('0'+i) : i) + '">' + i + '</option>'
                daySelectCtrl.children().end().append(entry) ;
              }
        }

        function addAnotherGiftReminder(reminderId){
            var cloned = $J('#gift-reminder-template').clone(false);
            cloned.attr('id', ('gift-reminder_' + reminderId));
            cloned.css('display', 'block');

            cloned.find('input.first-name').attr('name', ('giftreminders[' + reminderId + '][firstname]'));
            cloned.find('input.last-name').attr('name', ('giftreminders[' + reminderId + '][lastname]'));

            cloned.find('select.reminder-month').attr('name', ('giftreminders[' + reminderId + '][month]'));
            cloned.find('select.reminder-day').attr('name', ('giftreminders[' + reminderId + '][day]'));

            cloned.find('select.occasion').attr('name', ('giftreminders[' + reminderId + '][occasion]'));

            $J('#all-reminders').append(cloned);

            $J('#gift-reminder_' + reminderId + ' .delete-gift-reminder').click(function(e){
                deleteGiftReminder(e);
            });

            $J('#gift-reminder_' + reminderId + ' select.reminder-month').change(function() {
              updateDaysInMonth(this);
            });


            __LAST_GIFT_REMINDER_ID = reminderId;
            __TOTAL_GIFT_REMINDERS++;
            $J('#giftReminderInformation button[type=submit]').show();
        }

        /* Add 4 initial gift reminders */
        //for (i=1; i<5; i++){
        //    addAnotherGiftReminder(i);
        // }

        $J('.add-gift-reminder').click(function () {
            addAnotherGiftReminder(__LAST_GIFT_REMINDER_ID+1);
        });

        $J('.delete-gift-reminder').click(function (e) {
            deleteGiftReminder(e);
        });

        $J('select.reminder-month').change(function() {
              updateDaysInMonth(this);
        });


        $J('#giftReminderInformation').submit(function () {
            hideError();

            var reminderValidator = new Validation($('giftReminderInformation'));
            if (!reminderValidator.validate()){
               return false;
            }

            $J.ajax({
                type: "POST",
                url: __UPDATE_GIFT_MESSAGES_URL,
                cache: false,
                data: $J('#giftReminderInformation').serialize() ,
                success: function(data){
                    if (data!=null){
                        var jsonData = $J.parseJSON(data);
                        if (jsonData.success){
                            showSuccess('#giftReminderMessages', 'Gift Reminders saved successfully');
                        }
                        else {
                            showError('#giftReminderMessages', 'Error saving Gift Reminders');
                        }
                    }
                    else {
                        showError('#giftReminderMessages', 'Error saving Gift Reminders');
                    }
                }
            });
            return false;
        });
    }

    
    /*********** GiftVoucher page ************/

    $J('select[name=voucher_ammount]').change(function (e){
         var total=($J('#voucher_ammount').val() * $J('#voucher_qty').val());
         if ($J('input[name=deliver_by_post]').is(':checked')){ total = parseFloat(total) + __VOUCHER_POSTAGE_COST};
         $J('#voucher_total').text(__STORE_CURRENCY_SYMBOL + total);
     });

    $J('select[name=voucher_qty]').change(function (e){
         var total=($J('#voucher_ammount').val() * $J('#voucher_qty').val());
         if ($J('input[name=deliver_by_post]').is(':checked')){total = parseFloat(total) +  __VOUCHER_POSTAGE_COST};
         $J('#voucher_total').text(__STORE_CURRENCY_SYMBOL + total);
    });

    $J('input[name=deliver_by_post]').click (function (e){
        if ($J(this).is(':checked')){
            var total=($J('#voucher_ammount').val() * $J('#voucher_qty').val()) + __VOUCHER_POSTAGE_COST;
            $J('#voucher_total').text(__STORE_CURRENCY_SYMBOL + total);
        }
        else {
            var total=($J('#voucher_ammount').val() * $J('#voucher_qty').val());
            $J('#voucher_total').text(__STORE_CURRENCY_SYMBOL + total);
        }
    });
    
    

    /*********** Product page ************/
    if ($J('#tabs').length!=0){
        $J("#tabs").tabs();
        $J('.toolbar').click(function(){
            if($J(this).next().css('display') == "none"){
                $J(this).next().show();
            }else{
                $J(this).next().hide();
            }
        });

        /* Once the tabs have been converted, un-hide the tabs */
        $J('.product-view .product-shop #tabs').show();

        // Ship to Countries combo
        $J('select[name=product-ship-to-countries]').change(function (e){
            countryCode = $J(this).val();

            // Clear message first
            $J('#product-shipping-price').empty().append('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;').addClass('content-loading');
            $J('#product-delivery-time').empty().append('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;').addClass('content-loading');
            $J.ajax({
                type: "POST",
                url: __GET_SHIPPING_DETAILS_URL,
                cache: false,
                data: "country_id=" + countryCode + "&product_id=" + __PRODUCT_ID + "&product_lead_time=" + __PRODUCT_DELIVERY_LEAD_TIME + "&incl_tax=1" ,
                success: function(data){
                    var jsonData = $J.parseJSON(data);

                    var message ='';
                    var days = ' Working Day(s)';
                    
                    
                    if (__STORE_URL == 'http://www.readersoffers.ie/'){
                        days = ' Day(s)';
                    }
                    if (jsonData.min == jsonData.max){
                        if (jsonData.min != 0){
                            message = "Estimated Delivery Time:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + jsonData.min + days;
                        }
                        else {
                            message = 'Estimated Delivery Time:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;5-7' + days;
                        }
                    }
                    else {
                        message = "Estimated Delivery Time:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + jsonData.min + " - "  + jsonData.max + days;
                    }
                    if (jsonData.numberOfShippingRates>1){
                        var stockCategory = $J('#product_stock_category').val();
                        if (countryCode=='IE' && stockCategory!='READ'){
                            message += '<br/>Same Day delivery to Dublin 1 to 24 available if you order before 12:30 GMT';
                        }
                        else {
                            message += '<br/>Other delivery options are available on checkout';
                        }
                    }
                    
//                    if ( new Date()<new Date(2011, 12, 25, 0, 1, 0, 0)){
//                    	message += "<br/><b>Guaranteed pre Christmas</b>";
//                    }
                    
                    
                    
                    $J('#product-delivery-time').removeClass('content-loading').empty().append(message);

                    if (jsonData.shipping){
                        message =  jsonData.shipping;
                    }
                    else{
                        message = 'Delivery cost unavailable';
                    }
                    
                    $J('#product-shipping-price').removeClass('content-loading').empty().append(message);
                }
            });
        });

       if ($J('.delivery-options-checkbox').length!=0){
            $J('.delivery-options-checkbox').click(function (e){
                var value = "";
                $J('.delivery-options-checkbox').each(function (e){
                    if ($J(this).is(':checked')){
                        var id = $J(this).attr('id');
                        if (value==""){
                            value = id;
                        }
                        else{
                            value += "," + id;
                        }
                    }
                });
                $J('#delivery-options-value').val(value);
            });
        }
    }

    if ($J('.personalisation-block').length!=0){
        $J('input.pers-user-input').keyup(function(e){
            var item_no = $J(this).attr('id').split('_')[1];
            var len = $J(this).val().length;

            maxlength = parseInt($J('#pers-max-length_' + item_no).val());
            if(len >= maxlength) {
                $J(this).val($J(this).val().substring(0, maxlength));
            }
            var charsLeft = (maxlength - len);
            if (charsLeft>=0){
                $J('#pers-remaining-chars_' + item_no).empty().append(charsLeft);

                $J('#label-line_' + item_no).empty().append($J(this).val().substring(0, maxlength));

            }
        });
    }

    /****** Main Navigation Menu in header ********/
    function megaHoverOver(){
        $J(this).find(".sub").stop().fadeTo('fast', 1).show();

        //Calculate width of all ul's
        (function($) {
            jQuery.fn.calcSubWidth = function() {
                rowWidth = 0;
                //Calculate row
                $J(this).find("ul").each(function() {
                    rowWidth += $J(this).width();
                });
            };
        })(jQuery);

        if ( $J(this).find(".row").length > 0 ) { //If row exists...
            var biggestRow = 0;
            //Calculate each row
            $J(this).find(".row").each(function() {
                $J(this).calcSubWidth();
                //Find biggest row
                if(rowWidth > biggestRow) {
                    biggestRow = rowWidth;
                }
            });
            //Set width
            $J(this).find(".sub").css({
                'width' :biggestRow
            });
            $J(this).find(".row:last").css({
                'margin':'0'
            });

        } else { //If row does not exist...

            $J(this).calcSubWidth();
            //Set Width
            $J(this).find(".sub").css({
                'width' : rowWidth
            });

        }
    }

    function megaHoverOut(){
        $J(this).find(".sub").stop().fadeTo('fast', 0, function() {
            $J(this).hide();
        });
    }

    var config = {
        sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
        interval: 100, // number = milliseconds for onMouseOver polling interval
        over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
        timeout: 500, // number = milliseconds delay before onMouseOut
        out: megaHoverOut // function = onMouseOut callback (REQUIRED)
    };

    $J("ul#topnav li .sub").css({
        'opacity':'0'
    });
    $J("ul#topnav li").hoverIntent(config);


    /******** Plus/Minus buttons on cart page & delivery page  ********************/
    if ($J('button.cart-plus-qty-button').length!=0){

        $J('button.cart-minus-qty-button').click(function (e){
            e.preventDefault();
            qtyInput = $J(this).parent().find('input.qty');
            qty = qtyInput.val();

            qty = parseInt(qty);
            if (isNaN(qty)){qty = 2};
            qty--;
            if (qty<0){qty =0;}
            qtyInput.val(qty);
        });

        $J('button.cart-plus-qty-button').click(function (e){
            e.preventDefault();
            qtyInput = $J(this).parent().find('input.qty');
            qty = qtyInput.val();
            qty = parseInt(qty);
            if (isNaN(qty)){qty = 0};
            qty++;
            qtyInput.val(qty);
        });
    }

    /*********** Cart Page       *********************/
    if ($J('.btn-checkout').length!=0){
        $J('.btn-checkout').click(function (e){
            /* Check if user has modified quantites without pressing update button */
            var problemQty = null;
            $J('input.qty').each(function (e){
                var qtyNow = $J(this).val().replace(/^\s+|\s+$/g,"");
                var originalQty = $J(this).parent().find('input.original-qty').val().replace(/^\s+|\s+$/g,"");
                if (qtyNow!=originalQty){
                    problemQty = $J(this);
                }
            })

            if (problemQty!=null){
                 $J(problemQty).bt('You have modified this quantity. Please press Update to adjust your cart total' +
                   '<br/><center><button type="button" style="align:center" onclick="$J(\'.bt-wrapper\').hide();" class="btn-update button"><span><span>OK</span></span></button></center>',
                   {width: 300, cssStyles: {fontSize: '11px'}, trigger: 'none',  positions: ['top','bottom']});
                 $J(problemQty).btOn();
                 return false;
            }

            var url = __STORE_URL + 'expresscheckout/';
            if (__SIGNED_IN){
                window.location= url;
            }
            else {
                var cookieVal = manipulateCookie("SKIP_LOGIN_PROMPT");
                if (cookieVal == 'true'){
                  window.location= url;
                }
                else {
                   ForcedSignIn.init(url);
                }

            }
        });
    }
    
    /******** Express Checkout page ********/
    var __GIFT_MESSAGE_LENGTH = 220;
	var __GIFT_MESSAGE_LINES=5;
    var __SHIP_CONTACTS = new Object;
    var __SHIP_ADDRESSES = new Object;

    if ($J('.delivery-details-link').length !=0){
        /* Control exists, so bind all other controls */

        $J('a.remove-item-link').click(function (e){
            e.preventDefault();
            var item_no = $J(this).attr('id').split('_')[1];
            $J('#ship-qty_' + item_no).val('0');
            shipping_submitted = true;
            $J('#can_continue_flag').val(0)
            $J('#checkout_multishipping_form').submit();
        });

        $J('.delivery-details-link').click(function (e){
            e.preventDefault();

            var item_no = $J(this).attr('id').split('_')[1];
            $J('#not-assigned_' + item_no).hide();
            $J('#assigned_' + item_no).hide();
            $J('#delivery-selection_' + item_no).show();

            var showError = $J('#show-delivery-error_' + item_no).val();
            if (showError=='1'){
                setTimeout(function () {
                         $J('#country_' + item_no).bt(
                          "Unfortunately this item cannot be delivered to the country you specified above." +
                          '<br/><center><button type="button" style="align:center" onclick="$J(\'.bt-wrapper\').hide();" class="btn-update button"><span><span>OK</span></span></button></center>',
                          {width: 300, cssStyles: {fontSize: '11px'}, trigger: 'click',  positions: ['top','bottom']});
                         $J('#country_' + item_no).btOn();
                    }, 400);
            }
        });

        /* Gift Message code */
        $J('.no-giftmessage').click (function (e){
            if ($J(this).is(':checked')){
                var parent = $J(this).parents('.gift-message');
                parent.find('input.gift-message-from').val('').attr('disabled','disabled').addClass('disabled');
                parent.find('input.gift-message-line').val('').attr('disabled','disabled').addClass('disabled').removeClass('required-entry');
            }
            else {
                var parent = $J(this).parents('.gift-message');
                parent.find('input.gift-message-from').removeAttr('disabled').removeClass('disabled');
                parent.find('input.gift-message-line').removeAttr('disabled').removeClass('disabled');
                parent.find('input.gift-message-line1').addClass('required-entry');
            }
        });

        /*
        $J('textarea.gift-message-text').keyup(function(e){
			var code = e.keyCode || e.which;
            var parent = $J(this).parents('.gift-message');

			var text = parent.find('textarea.gift-message-text').val();
			var len = text.length;
			var curLineCount = text.replace(/\r/g,'').split('\n').length-1;

				if(curLineCount >= __GIFT_MESSAGE_LINES){
					curLineCount=__GIFT_MESSAGE_LINES;
				text=text.replace(/\n+/g,'\n');
				var lines = text.split('\n');
				var part1 = lines.splice(0,__GIFT_MESSAGE_LINES);
				var part2 = lines.splice(__GIFT_MESSAGE_LINES,lines.length-__GIFT_MESSAGE_LINES);
				text = part1.join('\n')+part2.join(' ');

				text=text.replace(/\n$/g,'');
				}
				$J(this).val(text);
			if(code==13 || code==8 || code==46){
				parent.find('.gift-message-line-length').empty().append(__GIFT_MESSAGE_LINES - curLineCount);
				return;
			}

            if(len >= __GIFT_MESSAGE_LENGTH) {
                $J(this).val($J(this).val().substring(0, __GIFT_MESSAGE_LENGTH));
            }
            var charsLeft = (__GIFT_MESSAGE_LENGTH - len);
            if (charsLeft>=0){
                parent.find('.gift-message-length').empty().append(charsLeft);
            }
        }); */

        $J('input.gift-message-line').keydown(function (e){
            var id = $J(this).attr('id');
            var gm_no = id.split('_')[1];
            var gm_line_no = id.split('_')[2];
            var code = e.keyCode;
            if (code == 13){
                e.preventDefault();
                // If enter is pressed proceed to next control.
                gm_line_no++;
                if (gm_line_no<=5){
                    $J('#gift-message-line_' + gm_no + '_' + gm_line_no).focus();
                }
                else {
                    $J('#gift-message-from_' + gm_no).focus();
                }
            }
        });

        $J('.no-personalizationmessage').click (function (e){
            var item_no = $J(this).attr('id').split('_')[1];
            if ($J(this).is(':checked')){
                $J('#delivery-selection_' + item_no + ' input.personalization-message-text').each(function (e){
                    $J(this).val('').attr('disabled','disabled').addClass('disabled').removeClass('required-entry');
                });
            }
            else {
                $J('#delivery-selection_' + item_no + ' .personalization-message-text').each(function (e){
                    $J(this).removeAttr('disabled').removeClass('disabled');
                    if ($J(this).hasClass('mandatory')){
                        // Only turn back on the required class, if it the option is
                        // actually configured to be required
                        $J(this).addClass('required-entry');
                    }
                });
            }
        });

        function setRecipientDetailsToThis(from, to, contactVal){
            $J('#shipment-recipient_' + to).val(contactVal);
            $J('#prefix_' + to).val( $J('#prefix_' + from).val() );
            $J('#firstname_' + to).val( $J('#firstname_' + from).val() );
            $J('#lastname_' + to).val( $J('#lastname_' + from).val() );
            $J('#phone_' + to).val( $J('#phone_' + from).val() );
        }

        function fireProtoEvent(element,event){
            if (document.createEventObject){
                // dispatch for IE
                var evt = document.createEventObject();
                return element.fireEvent('on'+event,evt)
            }
            else{
                // dispatch for firefox + others
                var evt = document.createEvent("HTMLEvents");
                evt.initEvent(event, true, true ); // event type,bubbling,cancelable
                return !element.dispatchEvent(evt);
            }
        }

        function setAddressDetailsToThis(from, to, addressVal){
            $J('#shipment-address_' + to).val(addressVal);
            $J('#company_' + to).val( $J('#company_' + from).val() );
            $J('#country_' + to).val( $J('#country_' + from).val() );

            // Fire my change event handlers
            $J('#country_' + to).trigger('change');

            // Fire protoype change event handlers
            fireProtoEvent (document.getElementById('country_' + to), 'change');

            $J('#street_' + to + '_1').val( $J('#street_' + from + '_1').val() );
            if ($J('#street_' + to + '_2').length !=0)
                $J('#street_' + to + '_2').val( $J('#street_' + from + '_2').val() );
            if ($J('#street_' + to + '_3').length !=0)
                $J('#street_' + to + '_3').val( $J('#street_' + from + '_3').val() );
            $J('#city_' + to).val( $J('#city_' + from).val() );
            $J('#region_' + to).val( $J('#region_' + from).val() );
            $J('#region-id_' + to).val( $J('#region-id_' + from).val() );
            $J('#zip_' + to).val($J('#zip_' + from).val());
        }

        function presentShippingSummary(item_no){
            var summary = '';

            prefix = $J('#prefix_' + item_no).val().replace(/^\s+|\s+$/g,"");
            if (prefix!=''){
                summary += prefix + ' ' +
                       $J('#firstname_' + item_no).val().replace(/^\s+|\s+$/g,"") + ' ' +
                       $J('#lastname_' + item_no).val().replace(/^\s+|\s+$/g,"");
            }
            else {
                summary += $J('#firstname_' + item_no).val().replace(/^\s+|\s+$/g,"") + ' ' +
                       $J('#lastname_' + item_no).val().replace(/^\s+|\s+$/g,"");
            }

            if ($J('#company_' + item_no).length!=0){
                company = $J('#company_' + item_no).val().replace(/^\s+|\s+$/g,"");
                    if (company!=""){summary += ",<br/>" + company;}
                summary += ',<br/>' + $J('#street_' + item_no + '_1').val().replace(/^\s+|\s+$/g,"");
                if ($J('#street_' + item_no + '_2').length !=0){
                    street2 = $J('#street_' + item_no + '_2').val().replace(/^\s+|\s+$/g,"");
                        if (street2!="") {summary += ',<br/>' + street2;}
                }
                if ($J('#street_' + item_no + '_3').length !=0){
                    street3 = $J('#street_' + item_no + '_3').val().replace(/^\s+|\s+$/g,"");
                        if (street3!="") {summary += ',<br/>' + street3;}
                }
                summary += ',<br/>' + $J('#city_' + item_no).val().replace(/^\s+|\s+$/g,"");

                /* Take value of state/province from drop down/edit depending on which is visible */
                region = '';
                if ( $J('#region_' + item_no).css('display')!='none'){
                    region = $J('#region_' + item_no).val();
                }
                else {
                    region = $J('#region-id_' + item_no + ' option:selected').text()
                }
                summary += ',<br/>' + region.replace(/^\s+|\s+$/g,"") + ' ' +
                    $J('#zip_' + item_no).val().replace(/^\s+|\s+$/g,"");
                summary += ', ' + $J('#country_' + item_no + ' option:selected').text().replace(/^\s+|\s+$/g,"");
            }
            return (summary);
        }

        function valueExistsInObject(theObject, value){
            var lowerValue = value.toLowerCase();
            for (var key in theObject){
                if (theObject.hasOwnProperty(key)) {
                     var obj = theObject[key];
                     if (obj.toLowerCase() == lowerValue)
                         return true;
                }
            }
            return false;
        }

        function loadComboOptions(comboId, options, selected){
            for (var key in options){
                if (options.hasOwnProperty(key)) {
                     var obj = options[key];
                     if (obj == selected){
                         $J(comboId).append($J("<option></option>").attr('selected', 'selected').attr("value",key).text(options[key]));
                     }
                     else{
                         $J(comboId).append($J("<option></option>").attr("value",key).text(options[key]));
                     }
                }
            }
        }

        function prepareNameId (item_no){
            var id = '';
            if ($J('#prefix_' + item_no).length != 0){
              id += $J('#prefix_' + item_no + ' option:selected').text();
            }
            id += '||' + $J('#firstname_' + item_no).val().replace(/^\s+|\s+$/g,"");
            id += '||' + $J('#lastname_' + item_no).val().replace(/^\s+|\s+$/g,"");
            id += '||' + $J('#phone_' + item_no).val().replace(/^\s+|\s+$/g,"")
            return id;
        }


        function prepareAddressId (item_no){
            var id = '';
            id += $J('#company_' + item_no).val().replace(/^\s+|\s+$/g,"");
            id += '||' +  $J('#street_' + item_no + '_1').val().replace(/^\s+|\s+$/g,"");
            id += '||';
            if ($J('#street_' + item_no + '_2').length !=0){
                id += $J('#street_' + item_no + '_2').val().replace(/^\s+|\s+$/g,"");
            }
            id += '||';
            if ($J('#street_' + item_no + '_3').length !=0){
                id += $J('#street_' + item_no + '_3').val().replace(/^\s+|\s+$/g,"");
            }
            id += '||' + $J('#city_' + item_no).val().replace(/^\s+|\s+$/g,"");

            if ( $J('#region_' + item_no).css('display')!='none'){
                region = $J('#region_' + item_no).val().replace(/^\s+|\s+$/g,"");
                id += '||'  + '||' +  region;
            }
            else {
                regionId = $J('#region-id_' + item_no).val();
                region = $J('#region-id_' + item_no + ' option:selected').text();
                id += '||' + regionId + '||' + region;
            }

            id += '||' + $J('#zip_' + item_no).val().replace(/^\s+|\s+$/g,"");
            id += '||' + $J('#country_' + item_no).val();
            id += '||' + $J('#country_' + item_no + ' option:selected').text();
            return id;
        }

        function updateAllContactComboboxes(item_no){
            var entry = __SHIP_CONTACTS[item_no];
            /* If there is an entry for this id, delete it */
            //if (entry!=undefined){
            //    delete __SHIP_CONTACTS[item_no];
            // }

            entry = '';
            prefix = $J('#prefix_' + item_no).val().replace(/^\s+|\s+$/g,"");
            if (prefix!=''){
                entry = prefix + ' ' +
                       $J('#firstname_' + item_no).val().replace(/^\s+|\s+$/g,"") + ' ' +
                       $J('#lastname_' + item_no).val().replace(/^\s+|\s+$/g,"") + ' ' +
                       $J('#phone_' + item_no).val().replace(/^\s+|\s+$/g,"");
            }
            else {
                entry = $J('#firstname_' + item_no).val().replace(/^\s+|\s+$/g,"") + ' ' +
                       $J('#lastname_' + item_no).val().replace(/^\s+|\s+$/g,"") + ' ' +
                       $J('#phone_' + item_no).val().replace(/^\s+|\s+$/g,"");
            }

            id = prepareNameId(item_no);

            /* Loop thru and see does an entry with these details exist already */
            if (!valueExistsInObject(__SHIP_CONTACTS, entry) &&
                !valueExistsInObject(__ADDRESSBOOK_SHIP_CONTACTS, entry) ){
                /* add new entry */
                __SHIP_CONTACTS[id] = entry;
                /* Update all other combo lists */
                for (i=1; ;i++){
                    if ( i>1 && $J('#shipment-recipient_' + i).length == 0)
                        break;
                    else {
                       if (item_no!=i && $J('#shipment-recipient_' + i).length != 0){
                           var selected = $J('#shipment-recipient_' + i + ' option:selected').text()
                           $J('#shipment-recipient_' + i).empty();
                           $J('#shipment-recipient_' + i).append($J("<option></option>").attr("value","").text("Select"));
                           loadComboOptions(('#shipment-recipient_' + i), __SHIP_CONTACTS, selected);
                           loadComboOptions(('#shipment-recipient_' + i), __ADDRESSBOOK_SHIP_CONTACTS, selected);
                       }
                    }
                }
            }
            return id;
        }

        function updateAllAddressComboboxes(item_no){
            var entry = __SHIP_ADDRESSES[item_no];
            /* If there is an entry for this id, delete it */
            //if (entry!=undefined){
            //    delete __SHIP_ADDRESSES[item_no];
            //}

            entry = '';
            company = $J('#company_' + item_no).val().replace(/^\s+|\s+$/g,"");
                if (company!=""){entry += company + ', ';}
            entry += $J('#street_' + item_no + '_1').val().replace(/^\s+|\s+$/g,"");
            if ($J('#street_' + item_no + '_2').length !=0){
                street2 = $J('#street_' + item_no + '_2').val().replace(/^\s+|\s+$/g,"");
                if (street2!="") {entry += ', ' + street2;}
            }
            if ($J('#street_' + item_no + '_3').length !=0){
                street3 = $J('#street_' + item_no + '_3').val().replace(/^\s+|\s+$/g,"");
                if (street3!="") {entry += ', ' + street3;}
            }
            entry += ', ' + $J('#city_' + item_no).val().replace(/^\s+|\s+$/g,"");

            /* Take value of state/province from drop down/edit depending on which is visible */
            region = '';
            if ( $J('#region_' + item_no).css('display')!='none'){
                region = $J('#region_' + item_no).val();
            }
            else {
                region = $J('#region-id_' + item_no + ' option:selected').text()
            }
            entry += ', ' + region.replace(/^\s+|\s+$/g,"") + ' ' +
                  $J('#zip_' + item_no).val().replace(/^\s+|\s+$/g,"");
            entry += ', ' + $J('#country_' + item_no + ' option:selected').text().replace(/^\s+|\s+$/g,"");

            id = prepareAddressId(item_no);

            /* Loop thru and see does an entry with these details exist already */
            if (!valueExistsInObject(__SHIP_ADDRESSES, entry) &&
                !valueExistsInObject(__ADDRESSBOOK_SHIP_ADDRESSES, entry) ){

                /* add new entry */
                __SHIP_ADDRESSES[id] = entry;
                /* Update all other combo lists */
                for (i=1; ;i++){
                    if ( i>1 && $J('#shipment-address_' + i).length == 0)
                        break;
                    else {
                       if (item_no!=i && $J('#shipment-address_' + i).length != 0){
                           var selected = $J('#shipment-address_' + i + ' option:selected').text()
                           $J('#shipment-address_' + i).empty();
                           $J('#shipment-address_' + i).append($J("<option></option>").attr("value","").text("Select"));
                           loadComboOptions(('#shipment-address_' + i), __SHIP_ADDRESSES, selected);
                           loadComboOptions(('#shipment-address_' + i), __ADDRESSBOOK_SHIP_ADDRESSES, selected);
                       }
                    }
                }
            }
            return id;
        }

      function copyPersonalisationToAll (item_no){
            $J('.copy-personalizationmessage-all').removeAttr('checked');

            if ($J('#no-personalizationmessage_' + item_no).is(':checked')){
                $J('.no-personalizationmessage').attr('checked','checked');
                $J('input.personalization-message-text').each(function(e){
                  $J(this).val('').attr('disabled','disabled').addClass('disabled').removeClass('required-entry');
                })
            }
            else {
                // Only copy personlisation to items with the same personalisation types
                items = $J('#delivery-selection_' + item_no).find('input.personalization-message-text');
                if (items.length!=0){
                    for(i=0; i<items.length; i++){
                        var persObj = items[i];
                        var persObjVal = persObj.value;
                        var classList = persObj.className.split(/\s+/);
                        for (c = 0; c < classList.length; c++) {
                            var classN = classList[c];
                            if ( classN.substr(0,10) == 'p18n_type_') {
                                // Found personalisation type - set all of this type
                                $J('.' + classN).val(persObjVal);
                                // Enable (in case previously disabled)
                                $J('.' + classN).removeAttr('disabled').removeClass('disabled');
                                if ($J('.' + classN).hasClass('mandatory')){
                                    // Only turn back on the required class, if it the option is
                                    // actually configured to be required
                                    $J('.' + classN).addClass('required-entry');
                                }

                                // Since we altered the text, turn off the 'no-personalisation'
                                // chekbox if it is on
                                if (i==0){
                                    $J('.' + classN).parents('.personall').find('.no-personalizationmessage').removeAttr('checked');
                                }
                            }
                        }
                    }
                }
            }
            $J('#copy-personalizationmessage-all_' + item_no).attr('checked','true');
        }

        function itemCanShipToThisAddress(item_no, address){
            addressParts = address.split(',');
            country = addressParts[addressParts.length-1].replace(/^\s+|\s+$/g,"");
            x = $J('#country_' + item_no).find('option[text=' + country + ']');
            if (x.length!=0)
                return true;
            else
                return false;
        }

        function formDataisValid(item_no){
            var contactValid = false, addressValid = false, giftValid = false;
            var persValid = false, virtualValid = false;

            // reset all
            new Validation($('enter-recipient_' +  item_no)).reset();
            if ($J('#enter-address_' +  item_no).length!=0){
            new Validation($('enter-address_' +  item_no)).reset();
            }
            new Validation($('gift-message_' +  item_no)).reset();
            if ($J('#personalisation_' + item_no).length!=0){
                new Validation($('personalisation_' +  item_no)).reset();
            }

            // Clear any outstanding advice messages
            $J('#delivery-selection_' + item_no).find('.validation-advice').each(function (e){
                $J(this).hide();
            })

            shipQty = parseInt($J('#ship-qty_' +  item_no).val() );
            if (isNaN(shipQty)){
                alert ('Please specify a quantity for this item');
                $J('#ship-qty_' +  item_no).focus();
                return false;
            }
            else if (shipQty!=1){
                alert ('You have modified the quantity for this item. Please press Update');
                $J('#ship-qty_' +  item_no).focus();
                return false;
            }

            if ($J('#virtual-product_' + item_no).length!=0){
                new Validation($('virtual-product_' + item_no)).reset();

                validator = new Validation($('virtual-product_' + item_no));
                virtualValid = validator.validate();
            }
            else {virtualValid = true;}

            validator = new Validation($('enter-recipient_' +  item_no));
            contactValid = validator.validate();

            if ($J('#enter-address_' +  item_no).length!=0){
            validator = new Validation($('enter-address_' +  item_no));
            addressValid = validator.validate();
            }
            else {addressValid = true; }

            if ($J('#gift-message_' + item_no).find('.no-giftmessage').is(':checked')){
                $J('#gift-message_' + item_no).find('input.gift-message-from').removeClass('required-entry');
                $J('#gift-message_' + item_no).find('textarea.gift-message-text').removeClass('required-entry');
            }
            else{
                $J('#gift-message_' + item_no).find('input.gift-message-from').addClass('required-entry');
                $J('#gift-message_' + item_no).find('textarea.gift-message-text').addClass('required-entry');
            }
            validator = new Validation($('gift-message_' +  item_no));
            giftValid = validator.validate();

            if ($J('#personalisation_' + item_no).length!=0){
                if ($J('#no-personalizationmessage_' + item_no).is(':checked')){
                    $J('#personalisation_' + item_no).find('input.personalization-message-text').removeClass('required-entry');
                }
                else{
                    $J('#personalisation_' + item_no).find('input.personalization-message-text').each(function(e){
                        if ($J(this).hasClass('mandatory')){
                            // Only turn back on the required class, if it the option is
                            // actually configured to be required
                            $J(this).addClass('required-entry');
                        }
                    })
                }
                validator = new Validation($('personalisation_' +  item_no));
                persValid = validator.validate();
            }
            else{
                persValid = true;
            }

            if (contactValid && addressValid && giftValid && virtualValid && persValid)
                return true;
            else
                return false;
        }

        $J('.btn-detail').click(function (e) {
            e.preventDefault();

            var item_no = $J(this).attr('id').split('_')[1];

            // First, clear any error flagged from earlier
            $J('#show-delivery-error_' + item_no).val('0');

            if (formDataisValid(item_no)){

                var contactAdded = '';
                contactAdded = updateAllContactComboboxes(item_no);

                var addressAdded = '';
                if ($J('#enter-address_' + item_no).length!=0){
                addressAdded = updateAllAddressComboboxes(item_no);
                }
                /* Is this address to be used as delivery address - If so uncheck all others */
                if ($J('#use-delivery-address-checkbox_' + item_no).is(':checked')){
                    $J('.use-delivery-address-checkbox').removeAttr('checked');
                    $J('#use-delivery-address-checkbox_' + item_no).attr('checked','checked');
                }

                /* Prepare shipping summary */
                summaryAddress = presentShippingSummary(item_no);
                summary = 'Assigned to: ' + summaryAddress;

                /* Set all shipping addresses to this one ? */
                if ($J('#send-all-items-checkbox_' + item_no).is(':checked')){
                    $J('.send-all-items-checkbox').removeAttr('checked');
                    for (i=1; ;i++){
                        if ( $J('#delivery-selection_' + i).length == 0)
                            break;
                        else {
                            if (i != item_no){
                                setRecipientDetailsToThis (item_no, i ,contactAdded);

                                if (itemCanShipToThisAddress(i, summaryAddress)){
                                    setAddressDetailsToThis(item_no, i, addressAdded);

                                    // Change summary if it is shown
                                    if ($J('#assigned_' + i).css('display')!='none'){
                                        $J('#assigned_' + i + ' span.assigned-to-address').empty().append(summary);
                                    }
                                }
                                else {
                                    // Change summary if it is shown
                                    $J('#assigned_' + i + ' span.assigned-to-address').empty();
                                    $J('#assigned_' + i).hide();
                                    $J('#delivery-selection_' + i).hide();
                                    $J('#not-assigned_' + i).show();
                                    $J('#show-delivery-error_' + i).val('1');
                                }
                            }
                        }
                    }
                    $J('#send-all-items-checkbox_' + item_no).attr('checked','true');
                }

                /* Copy this personalisation message to all shipments ? */
                if ($J('#copy-personalizationmessage-all_' + item_no).is(':checked')){
                    copyPersonalisationToAll(item_no);
                }

                /* Copy this gift message to all shipments ? */
                if ($J('#gift-message_' + item_no).find('.copy-giftmessage-all').is(':checked')){
                    for (i=1; i<6; i++){
                        var line = $J('#gift-message_' + item_no).find('input.gift-message-line' + i).val();
                        $J('input.gift-message-line' + i).val( line );
                    }

                    var from = $J('#gift-message_' + item_no).find('input.gift-message-from').val();
                    $J('input.gift-message-from ').val( from );

                    var nogiftmess = $J('#gift-message_' + item_no).find('.no-giftmessage').is(':checked')
                    if (nogiftmess){
                        $J('.no-giftmessage').attr('checked','checked');
                        $J('input.gift-message-from ').attr('disabled','disabled').addClass('disabled');
                        $J('input.gift-message-line').attr('disabled','disabled').addClass('disabled');
                        $J('input.gift-message-line1').removeClass('required-entry');
                    }
                    else {
                        $J('.no-giftmessage').removeAttr('checked');
                        $J('input.gift-message-from ').removeAttr('disabled').removeClass('disabled');
                        $J('input.gift-message-line').removeAttr('disabled').removeClass('disabled');
                        $J('input.gift-message-line1').addClass('required-entry');
                    }
                    $J('.copy-giftmessage-all').removeAttr('checked');
                    $J('#gift-message_' + item_no).find('.copy-giftmessage-all').attr('checked','true');
                }

                /* Finally update sumary, hide shipping section, display completed section */
                $J('#delivery-selection_' + item_no).hide();
                $J('#assigned_' + item_no + ' span.assigned-to-address').empty().append(summary);
                $J('#assigned_' + item_no).show();
                $J('#not-assigned_' + item_no).hide();

                /* If user said set all addresses to this, try validate all
                 * sections of the form without submitting */
                if ($J('#send-all-items-checkbox_' + item_no).is(':checked')){
                    var submit = validateShippingAddresses(false);
                    //if (submit){
                    //    $J('#checkout_multishipping_form').submit();
                    //}
                }
                
               // $J.scrollTo($J('#shipment' + item_no),500);
            }
        });

        $J('input.postcode').blur(function (e) {
            var item_no = $J(this).attr('id').split('_')[1];
            var country = $J('#country_' + item_no).val();
            if (country=='US' || country=='GB'){

               var city = $J('#city_' + item_no).val();
               var postcode = $J(this).val();

               var region = '';
               if ( $J('#region_' + item_no).css('display')!='none'){
                    region = $J('#region_' + item_no).val();
               } else {
                    region = $J('#region-id_' + item_no + ' option:selected').text();
               }

               var geocoder = new google.maps.Geocoder();
               var address = (postcode + "," + country);
               if (geocoder) {
                  geocoder.geocode({'address': address}, function (results, status) {
                     if (status == google.maps.GeocoderStatus.OK) {
                         var postalCodeResult = false;
                         var types = results[0].types;
                         for (i=0; i<types.length; i++){
                             if (types[i]=='postal_code' || types[i]=='postal_code_prefix'){
                                 postalCodeResult = true;
                             }
                         }

                         if (postalCodeResult){
                             num_fields = results[0].address_components.length;
                             if (country=='US'){
                                 geo_state = results[0].address_components[(num_fields-2)].long_name;
                                 geo_city = results[0].address_components[(num_fields-3)].long_name;
                                 if (city=='' && (region=='' || region=='Please select region, state or province')){
                                     // Nothing entered so fill fields.
                                     $J('#city_' + item_no).val(geo_city);
                                     option = $J('#region-id_' + item_no).find('option[text=' + geo_state + ']');
                                     if (option.length!=0){
                                        $J('#region-id_' + item_no).val( option.val() );
                                     }
                                 }
                                 else {
                                     if (geo_state.toLowerCase() != region.toLowerCase() ||
                                         geo_city.toLowerCase() != city.toLowerCase()){

                                         $J('#zip_' + item_no).bt('According to our records this zip/postal code is for ' +
                                           geo_city + ', ' + geo_state + '. Are you sure you have entered it correctly?' +
                                           '<br/><center><button type="button" style="align:center" onclick="$J(\'.bt-wrapper\').hide();" class="btn-update button"><span><span>OK</span></span></button></center>',
                                           {width: 300, cssStyles: {fontSize: '11px'}, trigger: 'none',  positions: ['top','bottom']});
                                         $J('#zip_' + item_no).btOn();
                                     }
                                 }
                             }
                             else if (country=='GB'){
                                 geo_city = results[0].address_components[1].long_name;
                                 geo_state = results[0].address_components[2].long_name;
                                 if (city=='' && region==''){
                                    $J('#city_' + item_no).val(geo_city);
                                    if (geo_state !='United Kingdom'){
                                        $J('#region_' + item_no).val(geo_state);
                                    }
                                 }
                                 else {
                                     if (geo_state.toLowerCase() != region.toLowerCase() ||
                                         geo_city.toLowerCase() != city.toLowerCase()){

                                         $J('#zip_' + item_no).bt('According to our records this zip/postal code is for ' +
                                           geo_city + ', ' + geo_state + '. Are you sure you have entered it correctly?' +
                                           '<br/><center><button type="button" style="align:center" onclick="$J(\'.bt-wrapper\').hide();" class="btn-update button"><span><span>OK</span></span></button></center>',
                                           {width: 300, cssStyles: {fontSize: '11px'}, trigger: 'none',  positions: ['top','bottom']});
                                         $J('#zip_' + item_no).btOn();
                                     }
                                 }
                             }
                         }
                         else {
                            $J('#zip_' + item_no).bt('According to our records this zip/postal code is not valid. Are you sure you have entered it correctly?' +
                               '<br/><center><button type="button" style="align:center" onclick="$J(\'.bt-wrapper\').hide();" class="btn-update button"><span><span>OK</span></span></button></center>',
                               {width: 300, cssStyles: {fontSize: '11px'}, trigger: 'none',  positions: ['top','bottom']});
                            $J('#zip_' + item_no).btOn();
                        }
                     }
                     else {
                        $J('#zip_' + item_no).bt('According to our records this zip/postal code is not valid. Are you sure you have entered it correctly?' +
                           '<br/><center><button type="button" style="align:center" onclick="$J(\'.bt-wrapper\').hide();" class="btn-update button"><span><span>OK</span></span></button></center>',
                           {width: 300, cssStyles: {fontSize: '11px'}, trigger: 'none',  positions: ['top','bottom']});
                        $J('#zip_' + item_no).btOn();
                     }
                  });
               }
            }
        });

      $J('select.country').change(function (){
            var item_no = $J(this).attr('id').split('_')[1];
            var sel = $J(this).val();
            if (sel == 'GB'){
                // Turn off mandatory State/Province if UK
                $J('#region_' + item_no).removeClass('required-entry');
                $J('#region-id_' + item_no).removeClass('validate-select');
                $J('.state-required-label').hide();
            }
            else {
//                $J('#region_' + item_no).addClass('required-entry');
                $J('.state-required-label').show();
            }
            // blank controls
            //$J('#street_' + item_no + '_1').val('');
            //if ($J('#street_' + item_no + '_2').length!=0) {$J('#street_' + item_no + '_2').val('');}
            //if ($J('#street_' + item_no + '_3').length!=0) {$J('#street_' + item_no + '_3').val('');}
            //$J('#zip_' + item_no).val('');
            //$J('#city_' + item_no).val('');

            //if ( $J('#region_' + item_no).css('display')!='none'){
            //   $J('#region_' + item_no).val('');
            //} else {
            //   $J('#region-id_' + item_no).val('')
            //}
 
            // Send ajax request back end to update product price
            var product_id = $J(this).attr('product_id');
            $J.ajax({
                type: "POST",
                url: __SECURE_STORE_URL + 'checkout/cart/updateItemPrice',
                cache: false,
                data: "country_id=" + sel + "&product_id=" + product_id ,
                success: function(data){
                    var jsonData = $J.parseJSON(data);
                    if (jsonData.success && jsonData.success == '1'){
                        // Update only if valid response
                        var price = new Number(jsonData.product_price);
                        $J('#table-delivery_' + item_no + ' span.price').empty().text(__STORE_CURRENCY_SYMBOL + price.toFixed(2));
                    }
                }
            });
        });

        $J('.shipping-contacts').change(function(e){
            var item_no = $J(this).attr('id').split('_')[1];
            if( $J(this).val() != ''){
                $contact_parts = $J(this).val().split('||');
                $J('#prefix_' + item_no).val($contact_parts[0]);
                $J('#firstname_' + item_no).val($contact_parts[1]);
                $J('#lastname_' + item_no).val($contact_parts[2]);
                $J('#phone_' + item_no).val($contact_parts[3]);
            }
        });

        $J('.shipping-addresses').change(function(e){
            var item_no = $J(this).attr('id').split('_')[1];
            if( $J(this).val() != ''){
                $address_parts = $J(this).val().split('||');

                var country = $address_parts[9];
                x = $J('#country_' + item_no).find('option[text=' + country + ']');
                if (x.length!=0){

                    $J('#company_' + item_no).val($address_parts[0]);
                    $J('#country_' + item_no).val($address_parts[8]);

                    $J('#country_' + item_no).trigger('change');

                    // Fire protoype change event handlers
                    fireProtoEvent (document.getElementById('country_' + item_no), 'change');

                    $J('#street_' + item_no + '_1').val($address_parts[1]);
                    if ($J('#street_' + item_no + '_2').length !=0){
                        $J('#street_' + item_no + '_2').val($address_parts[2])
                    }
                    if ($J('#street_' + item_no + '_3').length !=0){
                        $J('#street_' + item_no + '_3').val($address_parts[3])
                    }
                    $J('#city_' + item_no).val($address_parts[4])

                    if ( $J('#region_' + item_no).css('display')!='none'){
                        $J('#region_' + item_no).val($address_parts[6]);
                    }
                    else {
                        $J('#region-id_' + item_no).val($address_parts[5]);
                    }
                    $J('#zip_' + item_no).val($address_parts[7]);
                }
                else{
                     $J('#country_' + item_no).bt(
                      "Unfortunately you can't send the selected item to this country. e.g. Alcohol can't be delivered outside the EU. Please select an alternate item" +
                      '<br/><center><button type="button" style="align:center" onclick="$J(\'.bt-wrapper\').hide();" class="btn-update button"><span><span>OK</span></span></button></center>',
                      {width: 300, cssStyles: {fontSize: '11px'}, trigger: 'click',  positions: ['top','bottom']});
                     $J('#country_' + item_no).btOn();
                }
            }
        });

        $J('.virtual-deliver-by-email').click(function (e){
            var item_no = $J(this).attr('id').split('_')[1];

            var checked = $J(this).is(':checked');
            if (checked){
                $J('#email_' + item_no).removeAttr('disabled').removeClass('disabled').addClass('required-entry');
            }
            else{
                $J('#email_' + item_no).attr('disabled','disabled').addClass('disabled').removeClass('required-entry');
            }
        });

        function toggleAddressControls(item_no, state){
            if (state){
                $J('#shipment-address_' + item_no).val('Select');
                $J('#shipment-address_' + item_no).attr('disabled','disabled').addClass('disabled');
                $J('#company_' + item_no).attr('disabled','disabled').addClass('disabled');
                $J('#street_' + item_no + '_1').attr('disabled','disabled').addClass('disabled').removeClass('required-entry');
                if ($J('#street_' + item_no + '_2').length !=0)
                    $J('#street_' + item_no + '_2').attr('disabled','disabled').addClass('disabled');
                if ($J('#street_' + item_no + '_3').length !=0)
                    $J('#street_' + item_no + '_3').attr('disabled','disabled').addClass('disabled');
                $J('#city_' + item_no).attr('disabled','disabled').addClass('disabled').removeClass('required-entry');

                $J('#region_' + item_no).attr('disabled','disabled').addClass('disabled');
                $J('#region-id_' + item_no).attr('disabled','disabled').addClass('disabled');
                if ( $J('#region_' + item_no).css('display')!='none'){
                    $J('#region_' + item_no).removeClass('required-entry');
                }
                else {
                    $J('#region-id_' + item_no).removeClass('validate-select');
                }

                //$J('#zip_' + item_no).attr('disabled','disabled').addClass('disabled').removeClass('required-entry');
                $J('#country_' + item_no).attr('disabled','disabled').addClass('disabled').removeClass('validate-select');
            }
            else {
                $J('#shipment-address_' + item_no).removeAttr('disabled').removeClass('disabled');
                $J('#country_' + item_no).val('').removeAttr('disabled').removeClass('disabled').addClass('validate-select');

                $J('#country_' + item_no).trigger('change');

                // Fire protoype change event handlers
                fireProtoEvent (document.getElementById('country_' + item_no), 'change');

                $J('#company_' + item_no).removeAttr('disabled').removeClass('disabled');
                $J('#street_' + item_no + '_1').removeAttr('disabled').removeClass('disabled').addClass('required-entry');
                if ($J('#street_' + item_no + '_2').length !=0)
                    $J('#street_' + item_no + '_2').removeAttr('disabled').removeClass('disabled');
                if ($J('#street_' + item_no + '_3').length !=0)
                    $J('#street_' + item_no + '_3').removeAttr('disabled').removeClass('disabled');
                $J('#city_' + item_no).removeAttr('disabled').removeClass('disabled').addClass('required-entry');

                $J('#region_' + item_no).removeAttr('disabled').removeClass('disabled');
                $J('#region-id_' + item_no).removeAttr('disabled').removeClass('disabled');
                if ( $J('#region_' + item_no).css('display')!='none'){
                    $J('#region_' + item_no).addClass('required-entry');
                }
                else {
                    $J('#region-id_' + item_no).addClass('validate-select');
                }

                $J('#zip_' + item_no).removeAttr('disabled').removeClass('disabled').addClass('required-entry');
            }
        }


        $J('.virtual-deliver-by-regular').click(function (e){
            var item_no = $J(this).attr('id').split('_')[1];

            var checked = $J(this).is(':checked');
            if (checked){
                toggleAddressControls(item_no, false);
            }
            else{
                toggleAddressControls(item_no, true);
            }
        });

        $J('select.reminder-month').change(function() {
            var monthsDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
            var month = (($J(this).val() ) * 1) -1;
            var daysInThisMonth = monthsDays[month];

            var daySelectCtrl = $J(this).parent().find('select.reminder-day');
            daySelectCtrl.children().remove();
            daySelectCtrl.children().end().append( '<option value="">Day</option>') ;
            for (i=1; i<=daysInThisMonth; i++){
                var entry = '<option value="' + ((i <10) ? ('0'+i) : i) + '">' + i + '</option>'
                daySelectCtrl.children().end().append(entry) ;
            }
        });

        $J('input.firstname').blur(function () {
            var val  = $J(this).val();
            var name = $J(this).attr('name');
            var pre = name.substr (0, name.indexOf("[firstname]") );
            var reminder = pre + '[reminder-firstname]';
            $J('input[name="' + reminder + '"]').val(val);
        });

        $J('input.lastname').blur(function () {
            var val  = $J(this).val();
            var name = $J(this).attr('name');
            var pre = name.substr (0, name.indexOf("[lastname]") );
            var reminder = pre + '[reminder-lastname]';
            $J('input[name="' + reminder + '"]').val(val);
        });

        $J('select.occasion').change(function (){
            var val  = $J(this).val();
            var name = $J(this).attr('name');
            var pre = name.substr (0, name.indexOf("[occasion]") );
            var reminder = pre + '[reminder-occasion]';
            $J('select[name="' + reminder + '"]').val(val);
        });

        $J('#activate_reminders').click (function (e){
            var checked = $J(this).is(':checked');
            if (checked){
                enableGiftReminders();
            }
            else {
                disableGiftReminders();
            }
        });



    }

    if ($J('#multishipping-billing-form').length !=0){
	var MultiShippingVoucherRedeem = {
			init: function () {
				$J('#multi-shipping-voucher-redeem-content').modal({
					overlayId: 'multi-shipping-voucher-redeem-overlay',
					containerId: 'multi-shipping-voucher-redeem-container',
					closeHTML: null,
					minHeight:230,
					opacity:40,
					overlayClose:true,
					onShow:MultiShippingVoucherRedeem.show,
					onClose:MultiShippingVoucherRedeem.close
				});
			},
			show: function (d) {
				$J('#multi-shipping-voucher-redeem-container button.btn-continue-voucher').click(function (e) {
					e.preventDefault();
					$J.modal.close();
				});
			},

			close: function (d) {
				var self = this;
				d.container.animate(
				   { marginLeft: "100%"} ,
				   500,
				   function () {
					  self.close(); // or $J.modal.close();
				   }
			   );
			}
		};

        /* Control exists, so bind all other controls */
        $J('input.ship-method-radio').click(function (){
            if (!billing_submitted) {
                $J('#multishipping-billing-form')[0].setAttribute('action', __APPLY_SHIPPING_URL);
                billing_submitted = true;
                $J('#multishipping-billing-form').submit();
            }
        });

        $J('select.country').change(function (){
            $sel = $J(this).val();
            if ($sel == 'GB'){
                // Turn off mandatory State/Province if UK
                $J('#billing_region').removeClass('required-entry');
                $J('.state-required-label').hide();
            }
            else {
                $J('#billing_region').addClass('required-entry');
                $J('.state-required-label').show();
            }
            // blank controls
            $J('#billing_addr1').val('');
            if ($J('#billing_addr2').length!=0) {$J('#billing_addr2').val('');}
            if ($J('#billing_addr3').length!=0) {$J('#billing_addr3').val('');}
            $J('#billing_postcode').val('');
            $J('#billing_city').val('');

            if ( $J('#billing_region').css('display')!='none'){
               $J('#billing_region').val('');
            } else {
               $J('#billing_region_id').val('')
            }

        });

        // TODO: remove duplicate
        $J('#billing_postcode').blur(function (e) {
            var country = $J('#billing_country_id').val();
            if (country=='US' || country=='GB'){
               var postcode = $J(this).val();
               var city = $J('#billing_city').val();

               var region = '';
               if ( $J('#billing_region').css('display')!='none'){
                    region = $J('#billing_region').val();
               } else {
                    region = $J('#billing_region_id option:selected').text()
               }

               var geocoder = new google.maps.Geocoder();
               var address = (postcode + "," + country);
               if (geocoder) {
                  geocoder.geocode({'address': address}, function (results, status) {
                     if (status == google.maps.GeocoderStatus.OK) {
                         var postalCodeResult = false;
                         var types = results[0].types;
                         for (i=0; i<types.length; i++){
                             if (types[i]=='postal_code' || types[i]=='postal_code_prefix'){
                                 postalCodeResult = true;
                             }
                         }

                         if (postalCodeResult){
                             num_fields = results[0].address_components.length;
                             if (country=='US'){
                                 geo_state = results[0].address_components[(num_fields-2)].long_name;
                                 geo_city = results[0].address_components[(num_fields-3)].long_name;
                                 if (city=='' && (region=='' || region=='Please select region, state or province')){
                                     // Nothing entered so fill fields.
                                     $J('#billing_city').val(geo_city);
                                     option = $J('#billing_region_id').find('option[text=' + geo_state + ']');
                                     if (option.length!=0){
                                        $J('#billing_region_id').val( option.val() );
                                     }
                                 }
                                 else {
                                     if (geo_state.toLowerCase() != region.toLowerCase() ||
                                         geo_city.toLowerCase() != city.toLowerCase()){

                                         $J('#billing_postcode').bt('According to our records this zip/postal code is for ' +
                                           geo_city + ', ' + geo_state + '. Are you sure you have entered it correctly?' +
                                           '<br/><center><button type="button" style="align:center" onclick="$J(\'.bt-wrapper\').hide();" class="btn-update button"><span><span>OK</span></span></button></center>',
                                           {width: 300, cssStyles: {fontSize: '11px'}, trigger: 'none',  positions: ['top','bottom']});
                                         $J('#billing_postcode').btOn();
                                     }
                                 }
                             }
                             else if (country=='GB'){

                                 geo_city = results[0].address_components[1].long_name;
                                 geo_state = results[0].address_components[2].long_name;
                                 if (city=='' && region==''){
                                    $J('#billing_city').val(geo_city);
                                    if (geo_state !='United Kingdom'){
                                        $J('#billing_region').val(geo_state);
                                    }
                                 }
                                 else {
                                     if (geo_state.toLowerCase() != region.toLowerCase() ||
                                         geo_city.toLowerCase() != city.toLowerCase()){

                                         $J('#billing_postcode').bt('According to our records this zip/postal code is for ' +
                                           geo_city + ', ' + geo_state + '. Are you sure you have entered it correctly?' +
                                           '<br/><center><button type="button" style="align:center" onclick="$J(\'.bt-wrapper\').hide();" class="btn-update button"><span><span>OK</span></span></button></center>',
                                           {width: 300, cssStyles: {fontSize: '11px'}, trigger: 'none',  positions: ['top','bottom']});
                                         $J('#billing_postcode').btOn();
                                     }
                                 }

                             }
                         }
                         else {
                            $J('#billing_postcode').bt('According to our records this zip/postal code is not valid. Are you sure you have entered it correctly?' +
                               '<br/><center><button type="button" style="align:center" onclick="$J(\'.bt-wrapper\').hide();" class="btn-update button"><span><span>OK</span></span></button></center>',
                               {width: 300, cssStyles: {fontSize: '11px'}, trigger: 'none',  positions: ['top','bottom']});
                            $J('#billing_postcode').btOn();
                        }
                     }
                     else {
                        $J('#billing_postcode').bt('According to our records this zip/postal code is not valid. Are you sure you have entered it correctly?' +
                           '<br/><center><button type="button" style="align:center" onclick="$J(\'.bt-wrapper\').hide();" class="btn-update button"><span><span>OK</span></span></button></center>',
                           {width: 300, cssStyles: {fontSize: '11px'}, trigger: 'none',  positions: ['top','bottom']});
                        $J('#billing_postcode').btOn();
                     }
                  });
               }
            }
        });

        $J('#btn-apply-coupon').click(function (e) {
            e.preventDefault();
            if (!billing_submitted){
                if ($J('#btn-apply-coupon').text()!='Apply'){
                    // Removing coupon
                    $J('input[name=billing_remove_promocode]').val('1');
                    billing_submitted = true;
                    $J('#multishipping-billing-form')[0].setAttribute('action', __APPLY_VOUCHER_URL);
                    $J('#multishipping-billing-form').submit();
                }
                else {
                    // Applying coupon
                    if ((coupon = $J('input[name=billing_promocode]').val().replace(/^\s+|\s+$/g,"")) != ''){
                        
			//for vouchers (code>12 eg. 4DC6E79C6DC05) with multiple shipping address'
			if(coupon.length>12){
				var multiShipping=__ADDRESS_TOTALS.length>1;
				if(multiShipping){
					$J('input[name=billing_promocode]').val('');
					MultiShippingVoucherRedeem.init();
					return;
				}
			}
			//
			$J('input[name=billing_apply_promocode]').val('1');
                        billing_submitted = true;
                        $J('#multishipping-billing-form')[0].setAttribute('action', __APPLY_VOUCHER_URL);
                        $J('#multishipping-billing-form').submit();
                    }
                }
            }
        });

        $J('.btn-back-to-address').click(function (e){
            e.preventDefault();
            billing_submitted = true;
            $J('#multishipping-billing-form')[0].setAttribute('action', __APPLY_EDIT_URL);
            $J('#multishipping-billing-form').submit();
        });

    }

    /* Success page */
    if ($J('#request-vat-link').length!=0){
        $J('#request-vat-link').click(function (e){
            e.preventDefault();

            $J.ajax({
                type: "POST",
                url: __SECURE_STORE_URL + 'checkout/cart/emailInvoice',
                cache: false,
                data: "oid=" + $J('#oid').val() + "&code=" + $J('#code').val() ,
                success: function(data){
                    var jsonData = $J.parseJSON(data);
                    if (jsonData.success && jsonData.success == '1'){
                        $J('#request-vat-link').bt('A VAT receipt has been emailed to you, please check your mail' +
                           '<br/><center><button type="button" style="align:center" onclick="$J(\'.bt-wrapper\').hide();" class="btn-update button"><span><span>OK</span></span></button></center>',
                           {width: 300, cssStyles: {fontSize: '11px'}, trigger: 'none',  positions: ['top','bottom']});
                        $J('#request-vat-link').btOn();
                    }
                    else {
                        $J('#request-vat-link').bt('There was a problem emailing your VAT receipt, please contact us' +
                           '<br/><center><button type="button" style="align:center" onclick="$J(\'.bt-wrapper\').hide();" class="btn-update button"><span><span>OK</span></span></button></center>',
                           {width: 300, cssStyles: {fontSize: '11px'}, trigger: 'none',  positions: ['top','bottom']});
                        $J('#request-vat-link').btOn();
                    }
                }
            });

        });
    }

    /*
     * jQuery.ScrollTo
     * Copyright (c) 2007-2009 Ariel Flesler
     * Dual licensed under MIT and GPL.
     * @version 1.4.2
     */
    (function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;else if(jQuery(n).length==0)return;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);
});


function hideError(){
    $J('ul.messages').remove();
}

function showError(parent, error){
    hideError();
    $J(parent).prepend('<ul class="messages"><li class="error-msg"><ul><li>' + error + '</li></ul></li></ul>');
}

function showSuccess(parent, message){
    hideError();
    $J(parent).prepend('<ul class="messages"><li class="success-msg"><ul><li>' + message + '</li></ul></li></ul>');
}

function clearDefault(d){
    if(d.defaultValue==d.value)d.value=""
};
function restoreDefault(d){
    if(d.value=="")d.value=d.defaultValue;
};


/****** Customer Account Pages - Personal Information *******/
function savePersonalDetails(){
    var formkey = $J('#personalInformation input[name=form_key]').val();
    var prefix = $J('#personalInformation select[name=prefix]').val();
    var fname =  $J('#personalInformation input[name=firstname]').val();
    var lname =  $J('#personalInformation input[name=lastname]').val();
    var displayemail = $J('#emailInformation span.displayemail').text();

    $J.ajax({
        type: "POST",
        url: __ACCOUNT_EDIT_PAGE,
        cache: false,
        data: "confirmation=&current_password=&password=&form_key=" + formkey + "&prefix=" + prefix + "&firstname=" + fname + "&lastname=" + lname + "&email=" + encodeURIComponent(displayemail),
        success: function(data){
            if (data.search(/<title>Customer Login/i) !=-1){
                window.location.href = __LOGIN_PAGE;
            }
            else {
                if (data.search(/error-msg/i) != -1){
                    var error = parseError (data);
                    showError('#personalInformationMessages', error);

                } else {
                    showSuccess('#personalInformationMessages', 'Name details changed successfully');
                    $J('#topaccount span.welcome-msg').empty().text('Welcome ' + fname);
                    $J('#hidden_prefix').val(prefix);
                    $J('#hidden_firstname').val(fname);
                    $J('#hidden_lastname').val(lname);
                }
            }
        }
    });
};


function saveEmailDetails(){
    var formkey = $J('#emailInformation input[name=form_key]').val();
    $J('#emailInformation input[name=currentemail]').removeClass('validation-failed');
    $J('#emailInformation #advice-required-entry-currentemail').remove();
    $J('#emailInformation input[name=newemail]').removeClass('validation-failed');
    $J('#emailInformation #advice-required-entry-newemail').remove();
    $J('#emailInformation input[name=confirmemail]').removeClass('validation-failed');
    $J('#emailInformation #advice-required-entry-confirmemail').remove();

    var displayemail = $J('#emailInformation span.displayemail').text();
    var currentemail = $J('#emailInformation input[name=currentemail]').val();

    if (displayemail!=currentemail){
        $J('#emailInformation input[name=currentemail]').addClass('validation-failed');
        $J('#emailInformation input[name=currentemail]').parent().append(
            '<div style="" id="advice-required-entry-currentemail" class="validation-advice">This does not match your current email address.</div>');
        return;
    }

    var newemail = $J('#emailInformation input[name=newemail]').val();
    if (newemail==displayemail){
        $J('#emailInformation input[name=newemail]').addClass('validation-failed');
        $J('#emailInformation input[name=newemail]').parent().append(
            '<div style="" id="advice-required-entry-newemail" class="validation-advice">This email address is the same as your current email address.</div>');
        return;
    }

    var confirmemail = $J('#emailInformation input[name=confirmemail]').val();
    if (confirmemail!=newemail){
        $J('#emailInformation input[name=confirmemail]').addClass('validation-failed');
        $J('#emailInformation input[name=confirmemail]').parent().append(
            '<div style="" id="advice-required-entry-confirmemail" class="validation-advice">Please make sure your email addresses match.</div>');
        return;
    }

    var prefix = $J('#hidden_prefix').val();
    var fname =  $J('#hidden_firstname').val();
    var lname =  $J('#hidden_lastname').val();

    $J.ajax({
        type: "POST",
        url: __ACCOUNT_EDIT_PAGE,
        cache: false,
        data: "confirmation=&current_password=&password=&form_key=" + formkey + "&email=" + encodeURIComponent(newemail) +
        "&firstname=" + fname + "&lastname=" + lname + "&prefix=" + prefix,
        success: function(data){
            if (data.search(/<title>Customer Login/i) !=-1){
                window.location.href = __LOGIN_PAGE;
            }
            else {
                if (data.search(/error-msg/i) != -1){
                    var error = parseError (data);
                    showError('#emailInformationMessages', error);

                } else {
                    $J('#emailInformation input[name=currentemail]').val('');
                    $J('#emailInformation input[name=newemail]').val('');
                    $J('#emailInformation input[name=confirmemail]').val('');
                    showSuccess('#emailInformationMessages', 'Email changed successfully');
                    $J('#emailInformation span.displayemail').text(newemail);
                }
            }
        }
    });
}

function saveNewsletterDetails(){
    var newsletterStatus =  $J('#hidden_newsletter').val();
    var subscribed = $J('#newsletterInformation input[name=newslettersignup]').is(':checked')?true:false;
    if (newsletterStatus=='subscribed' && subscribed==false){
        /* unsubscribe */

        $J.ajax({
            type: "POST",
            url: $J('#hidden_newsletter_unsubscribe_url').val(),
            cache: false,
            success: function(data){
                if (data.search(/<title>Customer Login/i) !=-1){
                    window.location.href = __LOGIN_PAGE;
                }
                else {
                    showSuccess('#newsletterInformationMessages', 'You have been unsubscribed from the newsletter');
                    $J('#hidden_newsletter').val('unsubscribed');
                }
            }
        });
    }
    else if (newsletterStatus=='unsubscribed' && subscribed==true){
        /* subscribe */
        $J.ajax({
            type: 'POST',
            url: __NEWSLETTER_URL,
            data: {
                email:$J('#emailInformation span.displayemail').text()
            },
            cache: false,
            success: function(data){
                if (data.search(/<title>Customer Login/i) !=-1){
                    window.location.href = __LOGIN_PAGE;
                }
                else {
                    showSuccess('#newsletterInformationMessages', 'You have subscribed to the newsletter');
                    $J('#hidden_newsletter').val('subscribed');
                }
            }
        });
    }
}


function parseError (data){
    var error = '';
    var searchTerm = '<li class="error-msg"><ul><li>';
    var pos1 = data.indexOf(searchTerm);
    if (pos1!=-1){
        var startpos = (pos1+searchTerm.length);
        var pos2 = data.indexOf('</li>', startpos)
        if (pos2!=-1){
            error = data.substr((pos1+searchTerm.length), (pos2-startpos));
        }
    }
    return error;
}

function savePasswordDetails(){
    var displayemail = $J('#emailInformation span.displayemail').text();
    var prefix = $J('#hidden_prefix').val();
    var fname =  $J('#hidden_firstname').val();
    var lname =  $J('#hidden_lastname').val();

    var formkey = $J('#passwordInformation input[name=form_key]').val();
    var current_password = $J('#passwordInformation input[name=current_password]').val();
    var password = $J('#passwordInformation input[name=password]').val();
    var confirmation = $J('#passwordInformation input[name=confirmation]').val();

    $J.ajax({
        type: "POST",
        url: __ACCOUNT_EDIT_PAGE,
        cache: false,
        data: "change_password=1&confirmation=" + confirmation + "&current_password=" + current_password + "&password=" + password + "&form_key=" + formkey + "&email=" + encodeURIComponent(displayemail) + "&firstname=" + fname + "&lastname=" + lname + "&prefix=" + prefix ,
        success: function(data){
            if (data.search(/<title>Customer Login/i) !=-1){
                window.location.href = __LOGIN_PAGE;
            }
            else {
                if (data.search(/error-msg/i) != -1){
                    var error = parseError (data);
                    showError('#passwordInformationMessages', error);

                } else {
                    $J('#passwordInformation input[name=current_password]').val('');
                    $J('#passwordInformation input[name=password]').val('');
                    $J('#passwordInformation input[name=confirmation]').val('');
                    showSuccess('#passwordInformationMessages', 'Password changed successfully');
                }
            }
        }
    });
}


function saveBillingDetails(){
    var formkey = $J('#billingInformation input[name=form_key]').val();

    var prefix = $J('#billingInformation select[name=prefix]').val();
    var firstname =  $J('#billingInformation input[name=firstname]').val();
    var lastname =  $J('#billingInformation input[name=lastname]').val();
    var company =  $J('#billingInformation input[name=company]').val();

    var streets = '';
    for (i=1; ;i++){
        if ($J('#billingInformation #street_' + i).length==0)
            break;
        else
            streets += ('&street[]=' + $J('#billingInformation #street_' + i).val());
    }

    var region_id='', region='';
    if ($J('#billingInformation select[name=region_id]').css('display') != 'none'){
        region_id = $J('#billingInformation select[name=region_id]').val();
    }
    else {
        region = $J('#billingInformation input[name=region]').val();
    }

    var city =  $J('#billingInformation input[name=city]').val();
    var postcode =  $J('#billingInformation input[name=postcode]').val();
    var country_id =  $J('#billingInformation select[name=country_id]').val();

    var telephone =  $J('#billingInformation input[name=telephone]').val();
    var fax =  $J('#billingInformation input[name=fax]').val();

    var default_shipping = $J('#hidden_default_shipping').val();

    // TODO: encodeURIComponent on param names & param values

    $J.ajax({
        type: "POST",
        url: $J('#hidden_address_save_url').val(),
        cache: false,
        data: "default_billing=1" + /*&default_shipping=" + default_shipping + */
        "&prefix=" + prefix + "&firstname=" +
        firstname + "&lastname=" + lastname + "&company=" + company + streets + "&region_id=" + region_id +
        "&region=" + region + "&postcode=" + postcode + "&country_id=" + country_id +
        "&telephone=" + telephone + "&fax=" + fax + "&form_key=" + formkey + "&city=" + city,
        success: function(data){
            if (data.search(/<title>Customer Login/i) !=-1){
                window.location.href = __LOGIN_PAGE;
            }
            else {
                if (data.search(/error-msg/i) != -1){
                    var error = parseError (data);
                    showError('#billingInformationMessages', error);

                } else {
                    //$J('#passwordInformation input[name=current_password]').val('');
                    //$J('#passwordInformation input[name=password]').val('');
                    //$J('#passwordInformation input[name=confirmation]').val('');
                    showSuccess('#billingInformationMessages', 'Billing details changed successfully');
                }
            }
        }
    });
}

var shipping_submitted = false;
function validateShippingAddresses(submitform){
    if (shipping_submitted) {
        return false;
    }

    var complete = true;
    var scrollToId = null;
    for (var i=1; ;i++){
        if ( $J('#assigned_' + i).length == 0)
            break;
        else {
            var assigned_visible = $J('#assigned_' + i).css('display');
            if (assigned_visible != 'none'){
                // Shipment is assigned - continue
                continue;
            }
            else {
                var not_assigned_visible = $J('#not-assigned_' + i).css('display');
                var deliveryError = $J('#show-delivery-error_' + i).val();
                if (not_assigned_visible!='none' && deliveryError=='1'){
                    // This item is not assigned - See if there is a delivery error
                    // flagged. If there isn't try validate the contents
                    //var deliveryError = $J('#show-delivery-error_' + i).val();
                    //if (deliveryError=='1'){
                        if (scrollToId==null){scrollToId = ('#delivery-selection_' + i);}
                        complete = false;
                }
                else {
                    $J('#add-delivery-details-link_' + i).click();

                    // Attempt to click the save button (if form is complete we will
                    // continue to next item
                    $J('#btn-detail_' + i).click();
                    var delivery_section_visible = $J('#delivery-selection_' + i).css('display');
                    if (delivery_section_visible!='none'){
                        if (scrollToId==null){scrollToId = ('#delivery-selection_' + i);}
                        complete = false;
                    }
                }
            }
        }
    }

    if (submitform){
        $J('#can_continue_flag').val('1');
        enableGiftReminders();
    }

    if (!complete){
        if (scrollToId!=null){
            // Scroll to the offending area
            var targetOffset = ($J(scrollToId).offset().top);
            $J('html, body').animate({scrollTop:targetOffset}, 'slow');
        }
    }
    return (complete);
}

var billing_submitted = false;
function validateBillingDetails(){
    if (billing_submitted) {
        return false;
    }

    $ratesError = $J('#shipping-rates-error').val();
    if ($ratesError!=''){
        alert ($ratesError);
        return false;
    }
    
    if ($J('#billing_apply_promocode').val() == '1'){
        billing_submitted = true;
        return true;
    }


    if ($J('dl.pay-methods input[type=radio]:checked').val() == 'realex'){
        // Check if cvv number is needed & validate
        card = $J('#realex_cc_type').val();
        if (card=='AE' || card=='VI' || card=='MC'){  // || card=='SS'
            $J('#realex_cc_cid').addClass('validate-cc-cvn');
        }
        else {
            $J('#realex_cc_cid').removeClass('validate-cc-cvn');
        }
    }

    var billingValidator = new Validation($('multishipping-billing-form'));
    billingValidator.reset();
    $J('#advice-validate-cc-cvn-realex_cc_cid').hide();

    // Fix for bug where error message under zip is not removed ..
    if ($J('#advice-required-entry-billing_postcode').length!=0){
        $J('#advice-required-entry-billing_postcode').hide();
    }
    // Fix for bug where error message under sate/province is not removed ..
    if ($J('#advice-required-entry-billing_region').length!=0){
        $J('#advice-required-entry-billing_region').hide();
    }

    if (!billingValidator.validate()){
       return false;
    }

    if ($J('checkout-agreements')) {
        var checkboxes = $J('#checkout-agreements input');
        for (var i=0, l=checkboxes.length; i<l; i++) {
            if (!checkboxes[i].checked) {
                alert("Please agree to all Terms and Conditions before placing the order.");
                return false;
            }
        }
    }

    // If user is not signed in and they have provided a password - check if the
    // email address is already registered
    var submitOrder = true;
    if ($J('#create-account-section').length!=0){
        if ($J('#billing_password').val().replace(/^\s+|\s+$/g,"") != ''){
            $J.ajax({
                type: "POST",
                async: false,
                url: __CHECK_EMAIL_PAGE,
                cache: false,
                data: "email=" + $J('#billing_email').val(),
                success: function(data){
                    var jsonData = $J.parseJSON(data);
                    if (jsonData.exists){
                        alert ('An Account with the email address you provided already exists at this store.');
                        $J('#billing_email').focus();
                        submitOrder = false;
                    }
                }
            });
        }
    }

    if (submitOrder){
        billing_submitted = true;
        return true;
    }
    else
        return false;
}



var forgotPassword_submitted = false;
function validateForgotPassword(){
    if (forgotPassword_submitted) {
        return false;
    }

    var validator = new Validation($('form-validate2'));
    validator.reset();
    if (validator.validate()){
        forgotPassword_submitted = true;
        return true;
    }
    else {
        return false;
    }
}

var voucher_submitted = false;
function addVoucherToCart(){
    if (voucher_submitted){
        return;
    }

    hideError();

    $deliveryByPost = $J('input[name=deliver_by_post]').is(':checked')?'1':'0';
    $deliveryByEmail = $J('input[name=deliver_by_email]').is(':checked')?'1':'0';

    if ($deliveryByPost=='0' && $deliveryByEmail=='0'){
        showError('div.col-main', 'You must select how you want to send the voucher.');
        return;
    }

    var __GIFT_VOUCHER_IDS = '3614,3615,3617,3618,6827,3616,6828,6829,6830,6831,6832,6833,6834,3619';
    
    var ids =  __GIFT_VOUCHER_IDS.split(',');
    var qty    = $J('#voucher_qty').val();
    var method =  $J('#voucher_method option:selected').text()
    var amount =  $J('#voucher_ammount').val();
    var occasion = $J('#voucher_occasion').val();


    // Start replace voucher adding  
    var voucherid = ids[0];
    var vdenoms = new Array(5,10,20,50,75,100,150,200,250,300,350,400,450,500);
       
    for (i=0;i<=ids.length;i++){
    	if(vdenoms[i] == amount){
    		voucherid = ids[i];
    	}
    }    
    // End Voucher Adding

//    var voucherid = ids[0];
//    if (amount=='5')
//        voucherid = ids[0];
//    else if (amount=='10')
//        voucherid = ids[1];
//    else if (amount=='20')
//        voucherid = ids[2];
//    else if (amount=='50')
//        voucherid = ids[3];
//    else if (amount=='100')
//        voucherid = ids[4];
//    else if (amount=='500')
//        voucherid = ids[5];

    voucher_submitted = true;
    window.location = __STORE_URL + 'checkout/cart/addVoucher?pid=' + voucherid + '&qty=' + qty
        + '&dbe=' + $deliveryByEmail + '&dbp=' + $deliveryByPost + '&occ=' + encodeURIComponent(occasion);
}

var buyNowSubmitted = false;
function buyNow(url){
    if (!buyNowSubmitted){
        buyNowSubmitted = true;
        window.location.href = url;
    }
}

function productBuyNow(){
    hideError();

    if ($J('.delivery-options-checkbox').length!=0){
        var noneSelected = true;
        $J('.delivery-options-checkbox').each(function (e){
            if ($J(this).is(':checked')){
                noneSelected = false;
            }
        });
        if (noneSelected){
            showError('#messages_product_view', 'Please Select How you Would Like Your Voucher Delivered');
            return false;
        }
    }
    // Call original submit for form.
    return (productAddToCartForm.submit());
}

function brochureRequest(){
    var text = 'Please send me one of your brochures to - \n\n' +
            $J('#name').val() + '\n' +
            $J('#company').val() + '\n' +
            $J('#street1').val() + '\n' +
            $J('#street2').val() + '\n' +
            $J('#street3').val() + '\n' +
            $J('#city').val() + '\n' +
            $J('#region').val() + ' ' + $J('#zip').val() + '\n' +
            $J('#country_id option:selected').text() + '\n';
    $J('#comment').val(text);
}

function viewScrollTo(e,elmClass){
	e.preventDefault();
	var elm=$J("."+elmClass);
	$J("html, body").animate({scrollTop:elm.offset().top-10},2000);
	return false;
}

function manipulateCookie (name, value, options) {
                if (typeof value != 'undefined') { // name and value given, set cookie
                options = options || {};
                if (value === null) {
                    value = '';
                    options.expires = -1;
                }
                var expires = '';
                if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                    var date;
                    if (typeof options.expires == 'number') {
                        date = new Date();
                        date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                    } else {
                        date = options.expires;
                    }
                    expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
                }
                // CAUTION: Needed to parenthesize options.path and options.domain
                // in the following expressions, otherwise they evaluate to undefined
                // in the packed version for some reason...
                var path = options.path ? '; path=' + (options.path) : '';
                var domain = options.domain ? '; domain=' + (options.domain) : '';
                var secure = options.secure ? '; secure' : '';
                document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
            } else { // only name given, get cookie
                var cookieValue = null;
                if (document.cookie && document.cookie != '') {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = jQuery.trim(cookies[i]);
                        // Does this cookie string begin with the name we want?
                        if (cookie.substring(0, name.length + 1) == (name + '=')) {
                                var rawVal =  cookie.substring(name.length + 1);
                        while (rawVal.indexOf("+")!=-1){
                           rawVal = rawVal.replace("+", "%20");
                        }
                        cookieValue = decodeURIComponent(rawVal);
                            break;
                        }
                    }
                }
                return cookieValue;
            }
}


        function enableGiftReminders(){
            $J('#gift-reminders-table').find('input').each(function(){
               $J(this).removeAttr('disabled').removeClass('disabled').addClass('required-entry');
            });
            $J('#gift-reminders-table').find('select').each(function(){
               $J(this).removeAttr('disabled').removeClass('disabled').addClass('required-entry');
            });
        }

        function disableGiftReminders(){
            $J('#gift-reminders-table').find('input').each(function(){
               $J(this).removeAttr('disabled').attr('disabled','disabled').addClass('disabled').removeClass('required-entry');
            });
            $J('#gift-reminders-table').find('select').each(function(){
               $J(this).removeAttr('disabled').attr('disabled','disabled').addClass('disabled').removeClass('required-entry');
            });
        }


//FOR IE6 users download other browser popup
function  IE6popup(){
	if(ReadCookie("ie6modal")==""){
		var pop = '<div id="browser_download_popup"> We have detected that your are using IE6. This is an older browser which this site does not fully support. <br/>';
		pop += 'We have included links below to alternate browsers which give a superior browsing experience.<br/>';
		pop += '<ul class="mod-browsers-list">';
		pop += '<li><a target="_blank" href="http://windows.microsoft.com/en-US/internet-explorer/downloads/ie"><img src="http://www.giftsdirect.com/media/misc/browsers/ie.jpeg"/><span>Internet Explorer</span></a></li>'
		pop += '<li><a target="_blank" href="https://www.google.com/chrome"><img src="http://www.giftsdirect.com/media/misc/browsers/chrome.jpg"/><span>Chrome</span></a></li>'
		pop += '<li><a target="_blank" href="http://www.mozilla.org/en-US/firefox/new/"><img src="http://www.giftsdirect.com/media/misc/browsers/firefox.jpg"/><span>Firefox</span></a></li>'
		pop += '</ul><br/><a href="javascript:$J.modal.close()">[Close]</a></div>';
		$J("body").append(pop);
		$J("#browser_download_popup").css({"width":"440px","margin":"auto","background":"white","padding":"15px"});
		$J(".mod-browsers-list").css({"padding-left":"135px","padding-top":"20px"});
		$J(".mod-browsers-list li").css({"padding":"5px","text-align":"left"});
		$J(".mod-browsers-list li span").css({"margin":"10px","position":"absolute"});
		$J("#browser_download_popup").modal({"opacity":"50","modal":"false","overlayCss": {"backgroundColor":"#aaa"}});
		document.cookie="ie6modal=1";
	}
}

//Get cookie routine 
function ReadCookie(cookieName) {
	 var theCookie=" "+document.cookie;
	 var ind=theCookie.indexOf(" "+cookieName+"=");
	 if (ind==-1) ind=theCookie.indexOf(";"+cookieName+"=");
	 if (ind==-1 || cookieName=="") return "";
	 var ind1=theCookie.indexOf(";",ind+1);
	 if (ind1==-1) ind1=theCookie.length; 
	 return unescape(theCookie.substring(ind+cookieName.length+2,ind1));
}
