﻿/* Sky Shop */
var Sky_Shop = {
    Root: '',
    Basket: {
        Free: 0,
        Trade: 0
    },
    Checkout: {},
    Product: {
        ID: 0,
        SKU: 0,
        Quantity: 1,
        BaseCost: 0,
        OptionsXSLT: '',
        OptionsRequired: 0,
        Back: ''
    },
    Trade: {},
    Error: function(msg){
        alert(msg);
    },
    RunAjax: function(el, settings){
        o = {
            type: "POST",
            cache: false,
            contentType: "application/json; charset=utf-8",
            beforeSend: function() {
                if (el != null) { el.addClass('processing'); }
                if (settings.overlay) {
                    Sky_Shop.PageOverlay.Show();
                }
            },
            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() {
                if (el != null) { el.removeClass('processing'); }
                if (settings.overlay) {
                    Sky_Shop.PageOverlay.Remove();
                }
            },
            error: function(a, b, c) {
                Sky_Shop.Error(a.responseText + "\n" + "If you continue to experience problems, please contact Skylight Media");
                return false;
            }
        };
        o = jQuery.extend(true, o, settings);
        
        if (o.async)
            Sky_Shop.PageOverlay.Show();
            
        jQuery.ajax(o);
    }
};

Sky_Shop.PageOverlay = {};
Sky_Shop.PageOverlay.Show = function(){};
Sky_Shop.PageOverlay.Remove = function(){};

/* Init product page purchasing */
Sky_Shop.Product.Init = function(){

    /* How many option selections are required to purchase? */
    Sky_Shop.Product.OptionsRequired = jQuery('#site-main .product .purchase .option.select').size();
    
    /* Product option change */
	jQuery('#site-main .product .purchase .option.select select').change(Sky_Shop.Product.OptionSelect);
	
	/* Quantity change */
	jQuery('#site-main .product .purchase .quantity input.input_Quantity').live('keyup', Sky_Shop.Product.ShowTotal);
	jQuery('#site-main .product .purchase .quantity select.input_Quantity').bind("change", function(){}).live("change", Sky_Shop.Product.ShowTotal);
	
	/* Buy click */
	jQuery('#site-main .product .purchase .addtobasket').live('click', Sky_Shop.Product.AddToBasket);
};

/********************************************/
/*    Option drop down selection changed    */
/********************************************/
Sky_Shop.Product.OptionSelect = function(){
    $el = jQuery(this);
    
    /* Remove qty, buy button and remove all options on all other option selects */
    $el.closest('.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();
    
    if (curr_selection > 0)
    {        
        /* Get selected options */
        $el.closest('.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;
            }
        });
                    
        if (options.selected.length > 0 && options.selected.length < Sky_Shop.Product.OptionsRequired)
        {   	   
            /* Get next option type */
            options.nextType = $el.closest('.option.select').next('.option.select').find('input[type=hidden]').val();
            options.nextType = options.nextType != undefined ? options.nextType : 0;
             
            Sky_Shop.RunAjax(null, {
                beforeSend: function(){
                    $el.closest('.option.select').next('.option.select').addClass('checking').find('select').attr('disabled','disabled');
                    $el.closest('.selectors').nextAll('.buy').remove();
                },
                url: Sky_Shop.Root + "/product/get_options",
                data: JSON.stringify({ ProductID: Sky_Shop.Product.ID, OptionTypeID: options.nextType, OptionsSelected: options.selected, XSLT: Sky_Shop.Product.OptionsXSLT }),
                success: function(data, xhr){
                    /* Add next type options in html and trigger it's change event */
                    $el.closest('.option.select').next('.option.select').removeClass('checking').find('select').removeAttr('disabled').html(data);
                    
                    if ($el.closest('.option.select').next('.option.select').find('select > option').size() == 1){
                        $el.closest('.option.select').next('.option.select').find('select').trigger('change');
                    }
                }
           });
        }
        else if (options.selected.length > 0 && options.selected.length == Sky_Shop.Product.OptionsRequired)
        {            	    
            Sky_Shop.RunAjax(null, {
                beforeSend: function(){
                    $el.closest('.option.select').addClass('checking');
                },
                url: Sky_Shop.Root + "/product/get_cost",
                data: JSON.stringify({ ProductID: Sky_Shop.Product.ID, OptionsSelected: options.selected, XSLT: Sky_Shop.Product.OptionsXSLT }),
                success: function(data, xhr){
                    /* Append html */
                    $el.closest('.option.select').removeClass('checking').closest('.selectors').nextAll().remove().end().after(data);
                    
                    /* Get SKU */
                    Sky_Shop.Product.SKU = $el.closest('.selectors').next().find('#input_SKUCode').val();
                    
                    /* Show Total */
                    Sky_Shop.Product.ShowTotal();
                }
            });
        }
    } else {
        /* Clear everything after and reset the costs */
        $el.closest('.option.select').next().find('select').find('> option').remove().end().append('<option value="0">Please select '+$el.prevAll('span').text()+'</option>');
        $el.closest('.selectors').nextAll('.buy').remove();
        Sky_Shop.Product.ShowBaseCost();
    }
};

/********************************************/
/*         Refresh total on the page        */
/********************************************/
Sky_Shop.Product.ShowTotal = function(){
    /* Get total */
    $totals = Sky_Shop.Product.CalculateCosts();
    
    if ($totals.extras > 0 || $totals.quantity > 1)
    {                                
        jQuery('#site-main .product .info .costs .price').addClass('changed').html('<span>£'+$totals.base.toFixed(2)+'</span><b>£'+$totals.total.toFixed(2)+'</b>');
        if ($totals.extras > 0){
            jQuery('#site-main .product .info .costs .price b').append('<i>(inc. options)</i>');
        }
    }
    else
    {
        jQuery('#site-main .product .info .costs .price').removeClass('changed').html('£'+$totals.total.toFixed(2));
    }
};

/*********************************************/
/*   Calculate costs based on options made   */
/*********************************************/
Sky_Shop.Product.CalculateCosts = function(){
    $qty = jQuery('#site-main .product .purchase .quantity .input_Quantity');
    if (jQuery($qty).is('select')){
        $qty = parseInt(jQuery('option:selected', $qty).val());
    } else {
        $qty = parseInt($qty.val());
    }
    if (isNaN($qty)){
        $qty = 1;
    }
    Sky_Shop.Product.Quantity = $qty;
    $extra = parseFloat(jQuery('#input_SKUCost').val());
    if (isNaN($extra)){
        $extra = 0;
    }
    $cost = parseFloat(Sky_Shop.Product.BaseCost);
    $total = parseFloat(($cost+$extra) * $qty);
    return { base: $cost, total: $total, extras: $extra, quantity: $qty };
};

Sky_Shop.Product.ShowBaseCost = function(){
    jQuery('#site-main .product .info .costs .price').html('£'+Sky_Shop.Product.BaseCost.toFixed(2));
};

/**********************************************/
/* Add selected product and options to basket */
/**********************************************/
Sky_Shop.Product.AddToBasket = function(e){
    e.preventDefault();
    buy_img = jQuery(this).find('img');
    Sky_Shop.Product.SKU = jQuery('#input_SKUCode').val();
    
    /* 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')))
    {                    
        /* Add product to basket */
        Sky_Shop.RunAjax(buy_img, {
            url: Sky_Shop.Root + "/basket/add_item",
            data: JSON.stringify({ SKU_Code: Sky_Shop.Product.SKU, Quantity: Sky_Shop.Product.Quantity }),
            success: function(data, xhr) {
                jQuery.prettyPhoto.open(Sky_Shop.Root + '/basket/item_added/?ajax=&force_action=&width=450&height=70&backurl=' + Sky_Shop.Product.Back, 'Added To Basket', '');
            }
        });
    }
    
    if (!(Sky_Shop.Product.Quantity > 0))
    {
        alert("Please select/enter a quantity");
        Sky_Shop.Product.ShowBaseCost();
    }
};


Sky_Shop.Basket.Item = {};
Sky_Shop.Basket.Item.Timer = null;
Sky_Shop.Basket.Item.QtyEl = null;
/*********************************************/
/*        Basket Item Quantity Click         */
/*********************************************/
Sky_Shop.Basket.Item.QuantityClick = function(e) {

    e.preventDefault();

    Sky_Shop.Basket.Free = jQuery(".inpFree").val();
    Sky_Shop.Basket.Trade = jQuery(".inpMember").val();

    if (jQuery(this).hasClass('remove')) {
        Sky_Shop.Basket.Item.Remove(jQuery(this).prev().find('input.sku'));
    }
    else if (jQuery(this).hasClass('up')) {
        Sky_Shop.Basket.Item.UpdateQuantity(jQuery(this).siblings('input.qty'), 1);
    }
    else if (jQuery(this).hasClass('down')) {
        Sky_Shop.Basket.Item.UpdateQuantity(jQuery(this).siblings('input.qty'), -1);
    }
};
/*********************************************/
/*        Change basket item quantity        */
/*********************************************/
Sky_Shop.Basket.Item.UpdateQuantity = function(input_el, direction){
    /* Current qty */
    currQty = parseInt(input_el.val());    
    newQty = currQty;
    
    /* Check for any max quantities */
    maxQty = parseInt(input_el.siblings('input.max').val());
    
    if (direction > 0)
    {
        /* If there is a max qty allowed and it's going to exceed it, return */
        if ((!isNaN(maxQty) && (currQty == maxQty)))
        {
            return;
        }
    }
    
    /* If valid change */
    if ( (currQty > 1 && direction < 0) || (currQty >= 1 && direction > 0) )
    {
        /* Set new qty */
        newQty = currQty + direction;
    }
    else { return; }
    /* set input qty */
    input_el.val(newQty);
    
    /* If we have have clicked on a qty-change a el already */
    if (Sky_Shop.Basket.Item.QtyEl != null) {
        /* Is it a different basket item? */
        if (Sky_Shop.Basket.Item.QtyEl.attr("id") != input_el.attr("id")) {
            
            /* Yes, update previous el */
            Sky_Shop.Basket.Item.UpdateQuantity_Do(Sky_Shop.Basket.Item.QtyEl);
        }    
    }
    /* Set "active" item */
    Sky_Shop.Basket.Item.QtyEl = input_el;
    
    /* Clear timeout - so it doesn't fire multiple times */
    clearTimeout(Sky_Shop.Basket.Item.Timer);
    
    /* Set timeout */
    Sky_Shop.Basket.Item.Timer = setTimeout(function(){
        /* Update basket item */
        Sky_Shop.Basket.Item.UpdateQuantity_Do(Sky_Shop.Basket.Item.QtyEl);
        clearTimeout(Sky_Shop.Basket.Item.Timer);
    },500);
};
/*********************************************/
/*        Update basket item quantity        */
/*********************************************/
Sky_Shop.Basket.Item.UpdateQuantity_Do = function(el){
    sku_code = jQuery(el).siblings('input.sku').val();
    qty = parseInt(jQuery(el).val());
    
    /* Update basket item */
    Sky_Shop.RunAjax(el, {
        url: Sky_Shop.Root + "/basket/update_item",
        data: JSON.stringify({ SKU_Code: sku_code, Quantity: qty }),
        success: function(data, xhr){
            /* Update line total */
            price_el = jQuery(el).closest('.item').find('.price');
            var price = price_el.html();
            price = parseFloat(price.substring(1, price.length));
            var linetotal = (price * qty).toFixed(2);
            jQuery(el).closest('.item').find('.line-total').html(price_el.html().substring(0,1) + linetotal);
            
            /* Update totals */
            Sky_Shop.Basket.UpdateTotals();
        }
    });
};

/*********************************************/
/*            Remove basket item             */
/*********************************************/
Sky_Shop.Basket.Item.Remove = function(sku_el){
    sku_code = sku_el.val();
    
    /* Remove basket item */
    Sky_Shop.RunAjax(sku_el, {
        url: Sky_Shop.Root + "/basket/update_item",
        data: JSON.stringify({ SKU_Code: sku_code, Quantity: 0 }),
        success: function(data, xhr){
            sku_el.closest('.item').fadeOut(250, function(){ jQuery(this).remove(); });
            
            /* Update totals */
            Sky_Shop.Basket.UpdateTotals();
        }
    });
};

/*********************************************/
/*            Update basket totals           */
/*********************************************/
Sky_Shop.Basket.UpdateTotals = function() {
    /* Get basket totals */
    Sky_Shop.RunAjax(null, {
        url: Sky_Shop.Root + "/basket/get_totals",
        success: function(data, status, xhr) {
            /* Update totals */

            var cursub = parseFloat(jQuery('#subtotal').html().replace('£', ''));
            jQuery('#my-basket .footer .right').html(data);
            var newsub = parseFloat(jQuery('#subtotal').html().replace('£', ''));

            /* Check any delivery response headers */
            var deliveryHeader = xhr.getResponseHeader('DeliveryValid');
            if (deliveryHeader != null && deliveryHeader == 'false') {
                /* Delivery method error, remove checkout button */
                deliveryErr = xhr.getResponseHeader('DeliveryError');
                deliveryErr = deliveryErr.replace(/&lt;/g, "<");
                deliveryErr = deliveryErr.replace(/&gt;/g, ">");
                jQuery('#my-basket .checkout a').hide().after('<div class="delivery-error">' + deliveryErr + '</div>');
            }
            else {
                jQuery('#my-basket .checkout a').show().nextAll().remove();
            }

            /* Check any promotional code response headers */
            var promoHeader = xhr.getResponseHeader('PromoValid');
            if (promoHeader != null && promoHeader == 'false') {
                promoErr = xhr.getResponseHeader('PromoError');
                promoErr = promoErr.replace(/&lt;/g, "<");
                promoErr = promoErr.replace(/&gt;/g, ">");
                jQuery('#my-basket .promocode').find('div.error').remove().end().append('<div class="action-message error">' + promoErr + '</div>');
            }
            else {
                jQuery('#my-basket .promocode div.error').remove();
            }

            if (Sky_Shop.Basket.Trade) {
                if ((newsub < Sky_Shop.Basket.Free && cursub > Sky_Shop.Basket.Free) || (newsub > Sky_Shop.Basket.Free && cursub < Sky_Shop.Basket.Free)) {
                    window.location = '/my-basket';
                }
            }
        }
    });
};


Sky_Shop.Basket.Delivery = {}
/*********************************************/
/*          Delivery Method Changed          */
/*********************************************/
Sky_Shop.Basket.Delivery.Changed = function(e){
    $Delivery = parseInt(jQuery(this).val());
    if ($Delivery > 0)
    {
        /* Change basket delivery */
        Sky_Shop.RunAjax(jQuery(this).closest('div.delivery'), {
            url: Sky_Shop.Root + "/basket/change_delivery",
            data: JSON.stringify({ DeliveryMethod: $Delivery }),
            success: function(data, xhr){                
                /* Update totals */
                Sky_Shop.Basket.UpdateTotals();
            }
        });
    }
};

Sky_Shop.Basket.PromoCode = {}
/*********************************************/
/*            Promo code entered             */
/*********************************************/
Sky_Shop.Basket.PromoCode.Apply = function(e){
    e.preventDefault();
    $btn = jQuery(this);
    $PromoCode = $btn.siblings('input#input_PromoCode').val();
    if ($PromoCode.length > 0)
    {
        /* Apply promo code */
        Sky_Shop.RunAjax($btn.closest('div.promocode'), {
            url: Sky_Shop.Root + "/basket/apply_promocode",
            data: JSON.stringify({ PromoCode: $PromoCode }),
            success: function(data, xhr){                
                /* Update totals */
                Sky_Shop.Basket.UpdateTotals();
            },
            error: function(xhr, status){
                $btn.closest('div.promocode').find('.error').remove().end().append('<div class="action-message error">'+xhr.responseText+'</div>');
            }
        });
    }
};

Sky_Shop.Trade.Item = {};
Sky_Shop.Trade.Item.Timer = null;
Sky_Shop.Trade.Item.QtyEl = null;
/*********************************************/
/*        Trade Item Quantity Click         */
/*********************************************/
Sky_Shop.Trade.Item.QuantityClick = function(e) {
    e.preventDefault();
    if (jQuery(this).hasClass('up')) {
        Sky_Shop.Trade.Item.UpdateQuantity(jQuery(this).siblings('input.qty'), 1);
    }
    else if (jQuery(this).hasClass('down')) {
        Sky_Shop.Trade.Item.UpdateQuantity(jQuery(this).siblings('input.qty'), -1);
    }
};
/*********************************************/
/*        Change Trade item quantity        */
/*********************************************/
Sky_Shop.Trade.Item.UpdateQuantity = function(input_el, direction) {

    /* Current qty */
    currQty = parseInt(input_el.val());
    newQty = currQty;

    /* Check for any max quantities */
    //maxQty = parseInt(input_el.siblings('input.max').val());

    //if (direction > 0) {
    /* If there is a max qty allowed and it's going to exceed it, return */
    //  if ((!isNaN(maxQty) && (currQty == maxQty))) {
    //    return;
    //}
    //}

    /* If valid change */
    if ((currQty > 0 && direction < 0) || (direction > 0)) {
        /* Set new qty */
        newQty = currQty + direction;
    }
    else { return; }

    /* set input qty */
    input_el.val(newQty);
    input_el.parent().siblings('.lblQty').text(newQty);

    /* If we have have clicked on a qty-change a el already */
    if (Sky_Shop.Trade.Item.QtyEl != null) {
        /* Is it a different basket item? */
        if (Sky_Shop.Trade.Item.QtyEl.attr("id") != input_el.attr("id")) {
            /* Yes, update previous el */
            Sky_Shop.Trade.Item.UpdateQuantity_Do(Sky_Shop.Trade.Item.QtyEl);
        }
    }
    /* Set "active" item */
    Sky_Shop.Trade.Item.QtyEl = input_el;

    /* Clear timeout - so it doesn't fire multiple times */
    clearTimeout(Sky_Shop.Trade.Item.Timer);

    /* Set timeout */
    Sky_Shop.Trade.Item.Timer = setTimeout(function() {
        /* Update basket item */
        Sky_Shop.Trade.Item.UpdateQuantity_Do(Sky_Shop.Trade.Item.QtyEl);
        clearTimeout(Sky_Shop.Basket.Item.Timer);
    }, 500);
};
/*********************************************/
/*        Update Trade item quantity        */
/*********************************************/
Sky_Shop.Trade.Item.UpdateQuantity_Do = function(el) {

    sku_code = jQuery(el).siblings('input.sku').val();
    qty = parseInt(jQuery(el).val());

    /* Update basket item */
    Sky_Shop.RunAjax(el, {
        url: Sky_Shop.Root + "/basket/update_item",
        data: JSON.stringify({ SKU_Code: sku_code, Quantity: qty }),
        success: function(data, xhr) {
            jQuery(el).parent().parent().addClass("active");
        }
    });

    /* Update basket item */
    Sky_Shop.RunAjax(el, {
        url: Sky_Shop.Root + "/basket/get_basket",
        data: '',
        success: function(data, xhr) {
            jQuery("#divBasket").html(data);
        }
    });
};


/* Global shop initialisers */
jQuery(function() {
    jQuery('.shop a.load-login').click(function(e) {
        e.preventDefault();
        jQuery.prettyPhoto.open('/assets/login.aspx?ajax=&width=330&height=230&redirect=' + window.location.href, 'Enter your login details', '');
    });
});



