﻿
/* 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).siblings('input.req-qty').val());    
                    newQty = currQty;
                    
                    /* If valid change */
                    if ( (currQty > 1 && change < 0) || (currQty >= 1 && change > 0) )
                    {
                        /* Set new qty */
                        newQty = currQty + change;
                    }
                    /* set input qty */
                    jQuery(this).siblings('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).siblings('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).siblings('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('.qty: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('.qty: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('.qty: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);
                        },
                        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('#main .product .info .costs span.price').addClass('changed').html('<span>£'+Sky_Shop.Product.BaseCost.toFixed(2)+'</span><b>£'+$total.toFixed(2)+'<i>(inc. options)</i></b>');
            }
            else
            {
                jQuery('#main .product .info .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=100', '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;
        }
    }
};
