﻿
/* 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 );
                            
                            /* Update totals html */
                            jQuery('#my-basket > div > .footer').find('.totals').remove().end().append(data);
                        },
                        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(); });
                        
                        /* Update totals html */
                        jQuery('#my-basket > div > .footer').find('.totals').remove().end().append(data);
                    },
                    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">' + err.responseText + '</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('#main .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 (Sky_Shop.Product.SalePrice > 0)
            {
                $was_price = Sky_Shop.Product.FullPrice;
                $now_price = $total;
                
                // Check if there is an option cost
                $extra_Cost = $total - Sky_Shop.Product.BaseCost;
                if ($extra_Cost > 0)
                {
                    // product on sale and has option cost, add option cost to a temp full price
                    $was_price = $extra_Cost + Sky_Shop.Product.FullPrice;
                } 
                jQuery('#main .product .costs span.price').addClass('changeds').html('<img src="/assets/visual/product/was.jpg" style="margin-bottom:-3px" alt="was" /> £<strike>' + $was_price.toFixed(2) + '</strike> <img src="/assets/visual/product/now.jpg" style="margin-bottom:-3px" alt="now" /> <span style="color:#ec2745">£' + $now_price.toFixed(2) + '</span>');
            }
            else
            {
                if ($total < Sky_Shop.Product.BaseCost || $total > Sky_Shop.Product.BaseCost)
                {
                    jQuery('#main .product .costs span.price').addClass('changed').html('<span>£'+Sky_Shop.Product.BaseCost.toFixed(2)+'</span><b>£'+$total.toFixed(2)+'</b>');
                }
                else
                {
                    jQuery('#main .product .costs span.price').removeClass('changed').html('£'+Sky_Shop.Product.BaseCost.toFixed(2));
                }
            }
        },
        CalculateCost: function(){
            $qty = jQuery('#main .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('#header .basket').html(data);
                        
                        jQuery.prettyPhoto.open('/my-basket/item-added/?ajax=true&width=450&height=60', '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;
        },
        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;
        }
    },
    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);
        addressType = el.attr("class").split(" ")[2];
        jQuery.prettyPhoto.open('/my-account/address-details/new/'+addressType+'/?width=705px&height=450px&ajax=true','','', function(){
            /* Create validator */
            jQuery('#modal form').validate({
                rules: { 
                    tbx_Firstname: { required: true, maxlength: 40 },
                    tbx_Surname: { required: true, maxlength: 40 },
                    tbx_AddressLine1: { required: true, maxlength: 50 },
                    tbx_Town: { required: true, maxlength: 50 },
                    tbx_Postcode: { required: true, maxlength: 10 },
                    tbx_ContactNumber: { required: true, maxlength: 20 }
                }, 
                messages: { 
                    tbx_Firstname: {
                        required: "Please enter your firstname",
                        maxlength: jQuery.format("Maximum length: {0} characters")
                    }, 
                    tbx_Surname: {
                        required: "Please enter your surname",
                        maxlength: jQuery.format("Maximum length: {0} characters")
                    },
                    tbx_AddressLine1: {
                        required: "Please enter house number and road name",
                        maxlength: jQuery.format("Maximum length: {0} characters")
                    },
                    tbx_Town: {
                        required: "Please enter your town/city",
                        maxlength: jQuery.format("Maximum length: {0} characters")
                    },
                    tbx_Postcode: {
                        required: "Please enter your postal/zip code",
                        maxlength: jQuery.format("Maximum length: {0} characters")
                    },
                    tbx_ContactNumber: {
                        required: "Please enter a contact number",
                        maxlength: jQuery.format("Maximum length: {0} characters")
                    }
                }, 
                errorPlacement: function(error, element) { 
                    element.parent().parent().addClass("error")
                        .find('span').remove().end().append('<span><b></b>' + error.html() + '</span>');
                }, 
                submitHandler: function(frm){
                    /* Form valid, ajax submit */
                    Sky_Members.SaveAddress(frm, callback);
                },
                /* field is valid */
                success: function(label) {
                    var el = '#' + label.attr("for");
                    jQuery(el).parents('div.item').removeClass('error').find('span').remove(); 
                } 
            });
        });
        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.preventDefault();
        
        if (confirm("Are you sure you wish to remove this address?")){
        
            var address = el.parents('.address:first').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.parents('.address:first').fadeOut(250, function(){ jQuery(this).remove(); });
                    } else {                
                        alert(data.message);
                    }
                }
            });
        }

        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.parents('.account-addresses:first').find('span.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);
    }
};
