﻿var freedelivery = parseFloat(50);

/* Sky Checkout */
var Sky_Checkout = {
    Basket: {
        Item: {
            Quantity: {
                timeout: null,
                el: null,
                Change: function() {
                    /* Get qty change */
                    var change = jQuery(this).hasClass('up') ? 1 : -1;

                    /* Current qty */
                    currQty = parseInt(jQuery(this).parents('.change:first').find('input.req-qty').val());
                    newQty = currQty;

                    /* If valid change */
                    if ((currQty > 1 && change < 0) || (currQty >= 1 && change > 0)) {
                        /* Set new qty */
                        newQty = currQty + change;
                    }
                    if (newQty <= 0) {
                        newQty = 1;
                    }

                    $qty_max = parseInt(jQuery(this).parents('.change:first').find('input.input_QuantityLimit').val());
                    if (newQty > $qty_max) { newQty = $qty_max; }

                    /* set input qty */
                    jQuery(this).parents('.change:first').find('input.req-qty').val(newQty);

                    /* If we have have clicked on a qty-change a el already */
                    if (Sky_Checkout.Basket.Item.Quantity.el != null) {
                        /* Is it a different basket item? */
                        if (Sky_Checkout.Basket.Item.Quantity.el.attr("id") != jQuery(this).parents('.change:first').find('input.req-qty').attr("id")) {
                            /* Yes, update previous el */
                            Sky_Checkout.Basket.Item.Quantity.Update(Sky_Checkout.Basket.Item.Quantity.el);
                        }
                    }
                    /* Set "active" item */
                    Sky_Checkout.Basket.Item.Quantity.el = jQuery(this).parents('.change:first').find('input.req-qty');

                    /* Clear timeout - so it doesn't fire multiple times */
                    clearTimeout(Sky_Checkout.Basket.Item.Quantity.timeout);

                    /* Set timeout */
                    Sky_Checkout.Basket.Item.Quantity.timeout = setTimeout(function() {
                        /* Update basket item */
                        Sky_Checkout.Basket.Item.Quantity.Update(Sky_Checkout.Basket.Item.Quantity.el);
                        Sky_Checkout.Basket.Item.Quantity.timeout = null;
                    }, 500);

                    return false;
                },
                Update: function(qtyEl) {
                    /* Set ajax data */
                    dataOpts = JSON.stringify({ SKU_Code: qtyEl.siblings('input.sku-code').val(), Quantity: qtyEl.val(), UpdateEl: qtyEl.attr("id") });

                    /* Update item qty in basket */
                    jQuery.ajax({
                        type: "POST",
                        cache: false,
                        beforeSend: function() {
                            /* Set buy button to "processing" */
                            qtyEl.parents('.change:first').append('<img src="/assets/visual/ajax-loader.gif" alt="Updating" title="Updating" class="updating" />');
                        },
                        url: "/shop/basket/update_item",
                        data: dataOpts,
                        contentType: "application/json; charset=utf-8",
                        dataType: "string",
                        success: function(data) {

                            /* get el updated (input id) from data */

                            /* remove updating image */
                            qtyEl.parents('.change:first').children('img').remove();

                            /* Change line-total */
                            var price = qtyEl.parents('.item:first').find('> div.price:first').html();
                            price = parseFloat(price.substring(1, price.length));
                            var linetotal = (price * parseInt(qtyEl.val())).toFixed(2);
                            qtyEl.parents('.item:first').find('> div.line-total').html("&pound;" + linetotal);

                            var cursub = parseFloat(jQuery('#sub').html().replace('£', ''));
                            
                            /* Update totals html */
                            jQuery('#my-basket > div > .footer').find('.totals').remove().end().append(data);

                            var newsub = parseFloat(jQuery('#sub').html().replace('£', ''));


                            if ((newsub < freedelivery && cursub > freedelivery) || (newsub > freedelivery && cursub < freedelivery)) {
                                window.location = '/my-basket';
                            }
                        },
                        error: function(err) {
                            /* remove updating image */
                            qtyEl.parents('.change:first').children('img').remove();
                            alert(err.responseText);
                        }
                    });
                }
            },
            Remove: function() {
                removeEl = jQuery(this);

                /* Set ajax data */
                dataOpts = JSON.stringify({ SKU_Code: removeEl.siblings('.change').find('input.sku-code').val() });

                /* Update item qty in basket */
                jQuery.ajax({
                    type: "POST",
                    cache: false,
                    beforeSend: function() {
                        /* Set buy button to "processing" */
                        removeEl.parents('.qty:first').append('<img src="/assets/visual/ajax-loader.gif" alt="Removing" title="Removing" />');
                    },
                    url: "/shop/basket/remove_item",
                    data: dataOpts,
                    contentType: "application/json; charset=utf-8",
                    dataType: "string",
                    success: function(data) {
                        /* remove updating image */
                        removeEl.parents('.qty:first').children('img').remove();
                        removeEl.parents('.item:first').fadeOut(250, function() { jQuery(this).remove(); });
                        if (jQuery('.items > .item').size() == 1) {
                            location.reload();
                        }

                        var cursub = parseFloat(jQuery('#sub').html().replace('£', ''));

                        /* Update totals html */
                        jQuery('#my-basket > div > .footer').find('.totals').remove().end().append(data);

                        var newsub = parseFloat(jQuery('#sub').html().replace('£', ''));

                        if ((newsub < freedelivery && cursub > freedelivery) || (newsub > freedelivery && cursub < freedelivery)) {
                            window.location = '/my-basket';
                        }
                    },
                    error: function(err) {
                        /* remove updating image */
                        removeEl.parents('.qty:first').children('img').remove();
                        alert(err.responseText);
                    }
                });

                return false;
            }
        },
        CheckPromoCode: function() {
            var el = jQuery(this).html('checking... <img src="/assets/visual/ajax-loader-bluebg.gif" alt="" title="Checking Code..." />');

            /* Set ajax data */
            dataOpts = JSON.stringify({ PromoCode: jQuery(this).prev().find('input').val() });

            /* Apply promo code */
            jQuery.ajax({
                type: "POST",
                cache: false,
                url: "/shop/basket/apply_promotion",
                data: dataOpts,
                contentType: "application/json; charset=utf-8",
                dataType: "string",
                success: function(data) {
                    el.addClass('valid').html('Code Valid!')
                        .nextAll('.action-message.error').remove();
                    /* Update totals html */
                    jQuery('#my-basket > div > .footer').find('.totals').remove().end().append(data);
                },
                error: function(err) 
                {
                    el.removeClass('valid').html('Apply Code');
                    el.nextAll('.action-message').remove().end().after('<div class="action-message error">The code entered is invalid or the promotion has now ended</div>');
                    var t = setTimeout(function() {
                        jQuery(el).nextAll('.action-message').css("overflow", "hidden").animate({ height: 0, opacity: 0 }, 350, function() { jQuery(this).remove(); });
                        t = null;
                    }, 5000);
                }
            });
            return false;
        },
        ChangeDelivery: function() {
            var DelID = jQuery('option:selected', this).val();

            if (DelID > 0) {
                var el = jQuery(this).after('<img src="/assets/visual/ajax-loader.gif" alt="" class="updating" title="Updating..." />');

                /* Set ajax data */
                dataOpts = JSON.stringify({ DeliveryOption: DelID });

                /* Update delivery */
                jQuery.ajax({
                    type: "POST",
                    cache: false,
                    url: "/shop/basket/change_delivery",
                    data: dataOpts,
                    contentType: "application/json; charset=utf-8",
                    dataType: "string",
                    success: function(data) {
                        el.nextAll('.action-message.error, img').remove();
                        jQuery('.checkout').show().filter('.no-delivery-method').hide();
                        /* Update totals html */
                        jQuery('#my-basket > div > .footer').find('.totals').remove().end().append(data);
                    },
                    error: function(err) {
                        el.nextAll('.action-message, img').remove().end().after('<div class="action-message error">' + err.responseText + '</div>');
                    }
                });
            }
            return false;
        }
    }
};

/* Sky Shop */
var Sky_Shop = {
    Product: {
        ID: 0,
        SKU: 0,
        Quantity: 1,
        BaseCost: 0,
        OptionsXSLT: '',
        OptionsRequired: 0,
        OptionSelect: function() {

            $el = jQuery(this); //.parent();

            /* Remove qty, buy button and remove all options on all other option selects */
            $el.parents('.option.select')
                .nextAll(':not(.option.select)').remove().end()
                .nextAll('.option.select').children('option:gt(0)').remove();

            options = {
                selected: [],
                nextType: 0
            };

            /* Get current selected option */
            curr_selection = jQuery('option:selected', $el).val();

            /* Get selected options */
            $el.parents('.option.select').prevAll('.option.select').andSelf().each(function() {
                selected_value = parseInt(jQuery('option:selected', this).val());
                if (!isNaN(selected_value) && selected_value > 0) {
                    options.selected.push(selected_value);
                } else {
                    Sky_Shop.Product.SKU = 0;
                }
            });

            /* Get next option type */
            options.nextType = $el.parents('.option.select').next('.option.select').find('input[type=hidden]').val();
            options.nextType = options.nextType != undefined ? options.nextType : 0;

            if (options.selected.length > 0 && options.nextType > 0) {
                if (curr_selection > 0) {
                    /* Get options for next type */
                    dataOpts = JSON.stringify({ ProductID: Sky_Shop.Product.ID, SelectedOptions: options.selected, OptionTypeID: options.nextType, XSLT: Sky_Shop.Product.OptionsXSLT });

                    jQuery.ajax({
                        type: "POST",
                        cache: false,
                        beforeSend: function() {
                            $el.parents('.option.select').next('.option.select')
                                .append('<img src="/assets/visual/ajax-loader.gif" alt="Checking Options" title="Checking Options" />')
                                .find('select').attr('disabled', 'disabled');
                        },
                        url: "/shop/product/get_options",
                        data: dataOpts,
                        contentType: "application/json; charset=utf-8",
                        dataType: "html",
                        success: function(NextTypeOptions) {
                            /* Append next type options in html and trigger it's change event */
                            $el.parents('.option.select').next('.option.select').remove().end().after(NextTypeOptions);

                            jQuery('.product .options .option select').change(Sky_Shop.Product.OptionSelect);
                        },
                        error: function(ajaxResponse) {
                            $el.parents('.option.select').next('.option.select').find('img.updating').remove().end().find('select').attr('disabled', 'disabled');
                            alert(ajaxResponse.responseText);
                        }
                    });
                }
            }
            else {
                if (curr_selection > 0 && options.selected.length == Sky_Shop.Product.OptionsRequired) {
                    /* Set options for stock item query */
                    dataOpts = JSON.stringify({ ProductID: Sky_Shop.Product.ID, SelectedOptions: options.selected, OptionTypeID: options.nextType, XSLT: Sky_Shop.Product.OptionsXSLT });

                    jQuery.ajax({
                        type: "POST",
                        cache: false,
                        beforeSend: function() {
                            $el.parents('.option.select').nextAll().remove().end()
                                .after('<img src="/assets/visual/ajax-loader.gif" alt="Retrieving Costs" title="Retrieving costs" class="calculating" />');
                        },
                        url: "/shop/product/get_cost",
                        data: dataOpts,
                        contentType: "application/json; charset=utf-8",
                        dataType: "html",
                        success: function(ProductPurchaseHTML) {
                            /* Append html */
                            $el.parents('.option.select').nextAll().remove().end().after(ProductPurchaseHTML);
                            /* Get SKU */
                            Sky_Shop.Product.SKU = $el.parents('.selectors:first').find('#input_SKUCode').val();

                            /* Show Total */
                            Sky_Shop.Product.ShowTotal();
                        },
                        error: function(ajaxResponse) {
                            $el.parents('.option.select').nextAll().remove();
                            alert(ajaxResponse.responseText);
                        }
                    });
                }
            }
        },
        ShowTotal: function() {
            /* Get total */
            $total = Sky_Shop.Product.CalculateCost();
            Sky_Shop.Product.BaseCost = parseFloat(Sky_Shop.Product.BaseCost);

            if ($total < Sky_Shop.Product.BaseCost || $total > Sky_Shop.Product.BaseCost) {
                //jQuery('.product .costs span.price').addClass('changed').html('<span>£'+Sky_Shop.Product.BaseCost.toFixed(2)+'</span><b>£'+$total.toFixed(2)+'</b>');
            }
            else {
                jQuery('.product .costs span.price').removeClass('changed').html('£' + Sky_Shop.Product.BaseCost.toFixed(2));
            }
        },
        CalculateCost: function() {
            $qty = jQuery('.product .purchase .quantity .input_Quantity');
            if (jQuery($qty).is('select')) {
                $qty = parseInt(jQuery('option:selected', $qty).val());
            } else {
                $qty = parseInt($qty.val());
            }
            Sky_Shop.Product.Quantity = $qty;
            $extra = parseFloat(jQuery('#input_SKUCost').val());
            $cost = parseFloat(Sky_Shop.Product.BaseCost);
            $total = ($cost + $extra) * $qty;
            return parseFloat($total);
        },
        AddToBasket: function() {
            $cost = Sky_Shop.Product.CalculateCost();
            buy_img = jQuery(this).find('img');

            /* if we have a sku_code and a quantity > 0, AND not currently adding to basket */
            if (Sky_Shop.Product.SKU > 0 && Sky_Shop.Product.Quantity > 0 && (!buy_img.hasClass('processing'))) {
                /* Set ajax data */
                dataOpts = JSON.stringify({ SKU_Code: Sky_Shop.Product.SKU, Quantity: Sky_Shop.Product.Quantity });

                /* Add product to basket */
                jQuery.ajax({
                    type: "POST",
                    cache: false,
                    beforeSend: function() {
                        /* Set buy button to "processing" */
                        buy_img.addClass('processing').data('img', buy_img.attr('src')).attr('src', '/assets/visual/ajax-loader.gif');
                    },
                    url: "/shop/basket/add_item",
                    data: dataOpts,
                    contentType: "application/json; charset=utf-8",
                    dataType: "string",
                    success: function(data) {
                        /* Update quick-look basket */
                        jQuery('.divHeader .top #basket').html(data);

                        jQuery.prettyPhoto.open('/my-basket/item-added/?ajax=true&width=450&height=80', 'Added To Basket', '');

                        setTimeout(function() {
                            /* Set buy button to normal state */
                            buy_img.removeClass('processing').attr('src', buy_img.data('img'));
                        }, 1000);
                    },
                    error: function(err) {
                        /* Set buy button to normal state */
                        buy_img.removeClass('processing').attr('src', buy_img.data('img'));

                        alert(err.responseText);
                    }
                });
            }

            if (!(Sky_Shop.Product.Quantity > 0)) {
                alert("Please enter the quantity you would like");
            }

            return false;
        },
        MultiAddToBasket: function(e) {
            e.preventDefault();
            buy_img = jQuery(this).find('img');
            
            if (buy_img.hasClass('processing'))
                return;
            
            var products = [];
            jQuery(this).closest('.productsList').find(' > .collection input.input_quantity').each(function(i, el){
                if (jQuery(el).val() > 0)
                {
                    // Get SKU and quantity and add to array
                    products.push([jQuery(el).prev('.sku').val(), jQuery(el).val()]);
                }
            });

            /* if we have a sku_code and a quantity > 0, AND not currently adding to basket */
            if (products.length > 0)
            {
                /* Set ajax data */
                dataOpts = JSON.stringify({ Selections: products });

                /* Add products to basket */
                jQuery.ajax({
                    type: "POST",
                    cache: false,
                    beforeSend: function() {
                        /* Set buy button to "processing" */
                        buy_img.addClass('processing').data('img', buy_img.attr('src')).attr('src', '/assets/visual/ajax-loader.gif');
                    },
                    url: "/shop/basket/add_multipleItems",
                    data: dataOpts,
                    contentType: "application/json; charset=utf-8",
                    dataType: "string",
                    success: function(data) {
                        /* Update quick-look basket */
                        jQuery('.divHeader .top #basket').html(data);

                        jQuery.prettyPhoto.open('/my-basket/item-added/?ajax=true&width=450&height=80', 'Added To Basket', '');

                        buy_img.removeClass('processing').attr('src', buy_img.data('img'));
                    },
                    error: function(err) {
                        /* Set buy button to normal state */
                        buy_img.removeClass('processing').attr('src', buy_img.data('img'));

                        alert(err.responseText);
                    }
                });
            } else {
                alert("Please enter the quantity against each product that you wish to purchase");
            }
        },
        AddToWishList: function() {
            add_img = jQuery(this).find('img');
            /* Add product to wish list - if logged in */
            jQuery.ajax({
                type: "POST",
                cache: false,
                usesNotAcceptable: true,
                beforeSend: function() {
                    /* Set add button to "processing" */
                    add_img.addClass('processing').data('img', add_img.attr('src')).attr('src', '/assets/visual/ajax-loader.gif');
                },
                url: "/shop/basket/add_to_wishlist",
                data: JSON.stringify({ ProductID: Sky_Shop.Product.ID }),
                contentType: "application/json; charset=utf-8",
                dataType: "string",
                success: function(data, textStatus, xhr) {

                    jQuery.prettyPhoto.open('/my-basket/wishlist/?ajax=true&width=450&height=80&status=' + xhr.status, 'Add item to wishlist', '');

                    setTimeout(function() {
                        /* Set add button to normal state */
                        add_img.removeClass('processing').attr('src', add_img.data('img'));
                    }, 1000);
                },
                error: function(err) {
                    /* Set buy button to normal state */
                    add_img.removeClass('processing').attr('src', add_img.data('img'));

                    alert(err.responseText);
                }
            });
            return false;
        },
        OutOfStockReminder: function() {
            var SKU_Code = jQuery(this).siblings('#input_SKUCode').val();
            jQuery.prettyPhoto.open('/product-reminder/?ajax=true&width=460&height=265&sku=' + SKU_Code, 'Product stock reminder', '', function(pp) {
                jQuery('form', pp).submit(function() {
                    /* Get details */
                    frm = jQuery(this);
                    firstname = jQuery('#tbx_Firstname', frm).val();
                    surname = jQuery('#tbx_Surname', frm).val();
                    email = jQuery('#tbx_EmailAddress', frm).val();
                    subscribe = jQuery('#input_Subscribe', frm).is(":checked");

                    if (firstname != "" && surname != "" && email != "") {
                        frmBtn = frm.find('input.button');

                        /* ajax submit */
                        Sky_Shop.RunAjax(frmBtn, { url: "/shop/product-reminder", usesNotAcceptable: true,
                            data: JSON.stringify({ SKU: SKU_Code, Firstname: firstname, Surname: surname, EmailAddress: email, Subscribe: subscribe }),
                            success: function(data, e, xhr) {
                                if (xhr.status == '204') {  /* Show success and remove form */
                                    frm.prevAll('.action-message').remove().end()
                                        .before('<div class="action-message success">Your details have been saved, thank you</div>').remove();
                                } else {
                                    frm.prevAll('.action-message').remove().end()
                                        .before('<div class="action-message error">' + data + '</div>').end();
                                }
                            }
                        });
                    }
                    else {
                        alert("Please enter your name and email address");
                    }

                    return false;
                });
            });
            return false;
        },
        EmailAFriend: function() {
            var product = jQuery('h1').text();
            // alert(SKU_Code);
            jQuery.prettyPhoto.open('/email-a-friend/?width=40%&height=50%&ajax=true', 'Email a Friend', '', function(pp) {
                jQuery('form', pp).submit(function() {
                    /* Get details */
                    frm = jQuery(this);
                    name = jQuery('#input_name', frm).val();
                    email = jQuery('#input_email', frm).val();
                    name2 = jQuery('#input_name2', frm).val();
                    email2 = jQuery('#input_email2', frm).val();
                    message = jQuery('#input_message', frm).val();

                    if (name != "" && name2 != "" && email != "" && email2 != "")
                    {
                        frmBtn = frm.find('input.button');

                        /* ajax submit */
                        Sky_Shop.RunAjax(frmBtn, { url: "/shop/email-a-friend", usesNotAcceptable: true,
                            data: JSON.stringify({ product: product, URL: window.location.href, Name: name, Email: email, Name2: name2, Email2: email2, Message: message }),
                            success: function(data, e, xhr) {
                                if (xhr.status == '204') {  /* Show success and remove form */
                                    frm.prevAll('.action-message').remove().end()
                                        .before('<div class="action-message success">Your email has been sent, thank you</div>').remove();
                                } else {
                                    frm.prevAll('.action-message').remove().end()
                                        .before('<div class="action-message error">' + data + '</div>').end();
                                }
                            }
                        });
                    }
                    else {
                        alert("Please enter your own and your friend's name and email address");
                    }

                    return false;
                });
            });
            return false;
        }
    },
    RunAjax: function(el, settings) {
        o = {
            type: "POST",
            cache: false,
            contentType: "application/json; charset=utf-8",
            beforeSend: function() { /* Hide button */
                el.hide().after('<img src="/assets/visual/ajax-loader.gif" alt="Please wait..." title="Please wait..." class="processing" />');
            },
            dataType: 'html',
            dataFilter: function(data) {
                try {
                    var df = null;
                    if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function') {
                        df = JSON.parse(data);
                    } else {
                        df = eval('(' + data + ')');
                    }
                    if (df.hasOwnProperty('d')) {
                        return df.d;
                    } else {
                        return df;
                    }
                }
                catch (ex) {
                    return data;
                }
            },
            complete: function() {
                el.show().next('img.processing').remove();
            },
            error: function(a, b, c) {
                alert(a.responseText + "\n" + "If you continue to experience problems, please contact us");
            }
        };
        o = jQuery.extend(true, o, settings);

        jQuery.ajax(o);
    }
};



/***********************************/
/*             ACCOUNT             */
/***********************************/
var Sky_Members = {

    ResetPassword: function(frm, email) {

        frmBtn = frm.find('input.button');

        /* Try and reset password */
        Sky_Members.RunAjax(frmBtn, {
            url: "/myaccount/reset_password",
            data: JSON.stringify({ EmailAddress: email }),
            usesNotAcceptable: true,
            success: function(data) {
                if (data.success) {   /* Show success and remove form */
                    frm.prevAll('.action-message').remove().end()
                        .before('<div class="action-message success">Successfully reset password. Please check your email</div>').remove();
                } else {
                    frm.prevAll('.action-message').remove().end()
                        .before('<div class="action-message error">' + data.message + '</div>').end();
                }
            }
        });

        return false;
    },

    CheckEmailAddress: function(elContainer, value, callback) {

        /* Check email address */
        Sky_Members.RunAjax(elContainer, {
            url: "/myaccount/check_email",
            data: JSON.stringify({ EmailAddress: value }),
            usesNotAcceptable: true,
            success: function(data) {
                callback(data.success, data.message);
                if (data.success) {
                    return true;
                } else {
                    return false;
                }
            }
        }); /* end ajax */
    },

    AddNewAddress: function(el, callback) {
        el = jQuery(el);
        var checkout;
        //if (el.attr("class").indexOf("no-js") == "-1") { checkout = "&checkout=1" }
        addressType = el.attr("class").split(" ")[1];
        jQuery.prettyPhoto.open('/my-account/address-details/new/' + addressType + '/?width=705px&height=450px&ajax=true' + checkout, '', '', function() {
            jQuery('#modal form').live('submit', function(e){
                e.preventDefault();
                Sky_Members.SaveAddress(jQuery(this), callback);
            });
        });
        return false;
    },

    SaveAddress: function(frm, callback) {

        frm = jQuery(frm);
        var MemberAddress = {
            ID: jQuery("#input_AddressID", frm).val(),
            AddressType: jQuery("#input_Type", frm).val(),
            Title: jQuery("#ddl_Title", frm).val(),
            Firstname: jQuery("#tbx_Firstname", frm).val(),
            Surname: jQuery("#tbx_Surname", frm).val(),
            AddressLine1: jQuery("#tbx_AddressLine1", frm).val(),
            AddressLine2: jQuery("#tbx_AddressLine2", frm).val(),
            City: jQuery("#tbx_Town", frm).val(),
            County: jQuery("#tbx_County", frm).val(),
            Country: jQuery("#ddl_Country", frm).val(),
            Postcode: jQuery("#tbx_Postcode", frm).val(),
            ContactTel: jQuery("#tbx_ContactNumber", frm).val()
        };

        var AddToDelivery = jQuery('#input_AddToDelivery').is(':checked');
        if (AddToDelivery != true) { AddToDelivery = false; }
        dataOpts = JSON.stringify({ AddressInfo: MemberAddress, AddToDelivery: AddToDelivery });

        /* Add Address */
        frmBtn = frm.find('.button');
        Sky_Members.RunAjax(frmBtn, {
            async: false,
            url: "/myaccount/save_address",
            data: dataOpts,
            success: function(data) {
                if (data.success) {
                    frm.prevAll('.action-message').remove().end().before('<div class="action-message success">' + data.message + '</div>');
                    frm.hide();
                    if (typeof (callback) != "undefined") { callback(); }
                    return true;
                } else {
                    frm.prevAll('.action-message').remove().end().before('<div class="action-message error">' + data.message + '</div>');
                    return false;
                }
            }
        }); /* end ajax */
    },

    DeleteAddress: function() {

        el = jQuery(this);
        el.closest('tr').addClass('red-highlight');

        if (confirm("Are you sure you wish to remove this address?")) {

            var address = el.closest('tr').find('input:hidden').val();

            /* Delete address */
            Sky_Members.RunAjax(el, {
                url: "/myaccount/delete_address",
                data: JSON.stringify({ Address: address }),
                success: function(data) {
                    if (data.success) {
                        el.closest('tr').fadeOut(250, function() { jQuery(this).remove(); });
                    } else {
                        alert(data.message);
                    }
                }
            });
        }

        el.closest('tr').removeClass('red-highlight');

        return false;
    },

    MarkAsDefault: function() {
        el = jQuery(this);
        //el.preventDefault();
        if (!el.hasClass("default")) {

            var address = el.parents('.address:first').find('input:hidden').val();

            /* Mark address as default*/
            Sky_Members.RunAjax(el, {
                url: "/myaccount/default_address",
                data: JSON.stringify({ Address: address }),
                success: function(data) {
                    if (data.success) {
                        el.closest('table').find('td.default a.default').removeClass("default");
                        el.addClass("default");
                    } else {
                        alert(data.message);
                    }
                }
            });
        }
        return false;
    },

    GetLastAddress: function(AddressType, callback) {

        /* Get Address */
        jQuery.ajax({
            type: "POST",
            cache: false,
            url: "/myaccount/get_address",
            data: JSON.stringify({ AddressType: AddressType, Area: 'checkout' }),
            contentType: "application/json; charset=utf-8",
            dataType: "html",
            success: function(html) { callback(html); },
            error: function(err) { alert(err.responseText); }
        });
    },

    RemoveWishListItem: function() {

        el = jQuery(this);

        if (confirm("Are you sure you wish to remove this item from your wish list?")) {

            var address = el.parents('.address:first').find('input:hidden').val();

            /* Delete address */
            Sky_Members.RunAjax(el, {
                url: "/myaccount/remove_wishlist_item",
                data: JSON.stringify({ WishListItem: el.attr('href').substr(el.attr('href').lastIndexOf('/') + 1, el.attr('href').length) }),
                beforeSend: function() { /* Hide button */
                    el.html('<img src="/assets/visual/ajax-loader.gif" alt="Please wait..." title="Please wait..." class="processing" />');
                },
                success: function() {
                    el.parents('li:first').fadeOut(250, function() { jQuery(this).remove(); });
                }
            });
        }

        return false;
    },

    RunAjax: function(el, settings) {
        o = {
            type: "POST",
            cache: false,
            contentType: "application/json; charset=utf-8",
            beforeSend: function() { /* Hide button */
                el.hide().after('<img src="/assets/visual/ajax-loader.gif" alt="Please wait..." title="Please wait..." class="processing" />');
            },
            dataType: 'html',
            dataFilter: function(data) {
                try {
                    var df = null;
                    if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function') {
                        df = JSON.parse(data);
                    } else {
                        df = eval('(' + data + ')');
                    }
                    if (df.hasOwnProperty('d')) {
                        return df.d;
                    } else {
                        return df;
                    }
                }
                catch (ex) {
                    return data;
                }
            },
            complete: function() {
                el.show().next('img.processing').remove();
            },
            error: function(a, b, c) {
                alert(a.responseText + "\n" + "If you continue to experience problems, please contact us");
            }
        };
        o = jQuery.extend(true, o, settings);

        jQuery.ajax(o);
    }
};

jQuery(function(){
    jQuery('#addtobasket').click(Sky_Shop.Product.MultiAddToBasket);
});
