// Main Cart Functions | copyright (c) 2011 Rebellion A/S
// @author JDH

var root_uri            = new String();
var product_id          = new Number();
var VAT                 = new Number(1.2);
var currency            = new String('&pound;');
var current_size        = new String();
var customer_choices    = new Array();
var standard_colour     = new String()
var exists              = new Boolean(false);
var percentage_increase = new Number(0.25);
var poa_check           = new Boolean(false);
var c                   = new Number(1);

$(document).ready(function() 
{
    // setup layout...
    // document.forms['customise'].reset();
    pinstriping("hide");
    toggle_fr("hide");
    toggle_confirm("hide");
    toggle_colours("hide");
    toggle_choices("hide");
    
    var cartBlock = $('#cart');
    
    // cart move
    $(window).scroll( function(){
        
        if ($(window).scrollTop() > 898)
        {
            var cart_margin = $(window).scrollTop() - 838;
            cartBlock.stop().animate({marginTop : cart_margin}, "slow");
        }
        else
        {
            cartBlock.css('margin-top', 0);
        }
        
    })    
});

/**
* Ajax JSON
* Performs an AJAX call, returning JSON data
*/
function ajaxJson(type)
{
    var ajax_json_uri = new String("http://www.pasttents.com/ajax/"+type+"/"+product_id);
    
    $.getJSON(ajax_json_uri, function(json)
    {
        data_handler(json.data, type);
    });    
}

function update(reference, type, name, price)
{        
    /**
    * customer_choices
    * [0] = reference | what comes in from forms (obj) for array reference
    * [1] = type      |
    * [2] = name      | - shown to customer
    * [3] = price     |
    */
    
    // remove?
    if (name == "remove")
    {
        for (var i in customer_choices)
        {
            if (customer_choices[i][0] == type)
            {
                customer_choices.splice(i, customer_choices[i].length);
            }
        }
    }
    else
    {
        for (var i in customer_choices)
        {
            if (customer_choices[i][0] == type)
            {
                exists = true;
                
                if (type == "size")
                {
                    // clear array and start over...
                    customer_choices.splice(0, customer_choices.length);
                    customer_choices.push(new Array("size", "Tent Size", name, reference.value));
                    current_size = name;
                    ajaxJson("options");                 
                }
                else if (type == "Tent Colour")
                {
                    customer_choices[i][2] = name;
                    if (name != standard_colour)
                    {
                        customer_choices[i][3] = 1;
                    }
                    else
                    {
                        customer_choices[i][3] = 0;
                    }                
                }
                else
                {

                    if ($(reference).is('input:checkbox'))
                    {                   
                        // remove for checkboxes
                        customer_choices.splice(i, 1);
                    }
                    else
                    {
                        // keep for radio
                        customer_choices[i][2] = name;
                        customer_choices[i][3] = price;
                    }
                }       
            }        
        }
        
        if (exists == false)
        {
            if (type == "size")
            {
                customer_choices.push(new Array("size", "Tent Size", name, price));
                current_size = name;
                ajaxJson("options");            
            }
            else
            {
                customer_choices.push(new Array(type, type, name, price));
            }
        }        
    }
    
    exists = false;
    load_template();
}

function data_handler(data, type)
{
    var page = new String();
    var ps   = new String();
    
    /**
    * TENT SIZE DISPLAY
    */
    if (type == "sizes")
    {
        if (Object.size(data) == 1)
        {
            // if there's only one select it as default
            page += '<ul class="options">';        
            
            for (var i in data)
            {
                
                var price       = new Number(data[i][0]);
                var sale_price  = new Number(data[i][1]);

                // sale on?
                if (sale_price > 0)
                {
                    page += ' <li class="sizes">';
                    page += '       <div class="option_title">'+i+'</div>';
                    page += '       <div class="product_details_lists"><img src="'+root_uri+'/media/images/sizes/'+i+'.gif" alt="'+i+'" title="'+i+'" /></div>';
                    page += '       <div class="product_details_lists"><input type="radio" onclick="update(this, \'size\', \''+i+'\', '+sale_price+')" name="sizes" value="'+sale_price+'" checked/></div>';
                    page += '       <div class="product_details_lists"><span class="old_price"><s>'+currency+price+'</s></span></div>';
                    page += '       <div class="product_details_lists"><span class="sale_price">'+currency+sale_price+'</span></div>';
                    page += '       <br class="break" />';
                    page += ' </li>';
                    update("size", "size", i, sale_price);
                }
                // POA
                else if (price == 0)
                {
                    page += ' <li class="sizes">';
                    page += '       <div class="option_title">'+i+'</div>';
                    page += '       <div class="product_details_lists"><img src="'+root_uri+'/media/images/sizes/'+i+'.gif" alt="'+i+'" title="'+i+'" /></div>';
                    page += '       <div class="product_details_lists"><input type="radio" onclick="update(this, \'size\', \''+i+'\')" name="sizes" value="1" checked/></div>';
                    page += '       <div class="product_details_lists"><span class="price">'+currency+'POA</span></div>';
                    page += '       <br class="break" />';
                    page += ' </li>';
                    update("size", "size", i, 1);                                                         
                }
                else
                {
                    page += ' <li class="sizes">';
                    page += '       <div class="option_title">'+i+'</div>';
                    page += '       <div class="product_details_lists"><img src="'+root_uri+'/media/images/sizes/'+i+'.gif" alt="'+i+'" title="'+i+'" /></div>';
                    page += '       <div class="product_details_lists"><input type="radio" onclick="update(this, \'size\', \''+i+'\', '+price+')" name="sizes" value="'+price+'" checked/></div>';
                    page += '       <div class="product_details_lists"><span class="price">'+currency+price+'</span></div>';
                    page += '       <br class="break" />';
                    page += ' </li>';
                    update("size", "size", i, price);                                        
                }                              
                
                current_size = i;
                ajaxJson("options");
            }
            page += '</ul>';
        }
        else
        {            
            // SIZE CHOICES
            page += '<ul class="options">';        
            for (var i in data)
            {
                
                var price       = new Number(data[i][0]);
                var sale_price  = new Number(data[i][1]);                
                var alias       = new String(data[i][2]);
                
                page += ' <li>';
                page += '       <div class="option_title">'
                
                
                if (alias != 'undefined')
                {
                    page += alias; 
                }
                else
                {
                    page += i;
                }
                
                page += '</div>';
                page += '       <img src="'+root_uri+'/media/images/sizes/'+i+'.gif" alt="'+i+'" title="'+i+'" />';

                if (price == 0)
                {
                    page += '       <div class="product_details_lists"><input type="radio" onclick="update(this, \'size\', \''+i+'\')" name="sizes" value="1" /></div>';
                    page += '       <div class="product_details_lists"><span class="price">&pound;POA</span></div>';                    
                }
                else
                {
                    if (sale_price > 0)
                    {
                        page += '       <div class="product_details_lists"><input type="radio" onclick="update(this, \'size\', \''+i+'\', '+sale_price+')" name="sizes" value="'+sale_price+'" /></div>';
                        page += '       <div class="product_details_lists"><span class="old_price"><s>'+currency+price.toFixed(2)+'</s></span></div>';
                        page += '       <div class="product_details_lists"><span class="sale_price">'+currency+sale_price.toFixed(2)+'</span></div>';
                    }
                    else
                    {
                        page += '       <div class="product_details_lists"><input type="radio" onclick="update(this, \'size\', \''+i+'\', '+price+')" name="sizes" value="'+price+'" /></div>';
                        page += '       <div class="product_details_lists"><span class="price">'+currency+price.toFixed(2)+'</span></div>';                        
                    }
                }
                page += ' </li>';
            }
            page += '</ul>';            
        }

        load_template(page, "sizes");
        
    }
    else
    {
        /**
        * MAIN OPTIONS
        */
        var ot = new String();
        var ct = new String();
        
            /**
            * COLOURS
            */
            ct += '<ul class="colour_options">';
            ct += '<li class="colour_guide">';
            ct += ' <div class="colour_info">Reference</div>'
            ct += ' <div class="colour_info">Canvas</div>'
            ct += ' <div class="colour_info">Fire Retardant</div>'
            ct += '</li>';
        
            for (var i in data.colours)
            {
                var colour = i;
                var standard = data.colours[i][0];
                if (standard == 1)
                {
                    ct += '<li class="standard_colour">';
                }
                else
                {
                    ct += '<li>';
                }
                ct += '     <img src="'+root_uri+'/media/images/colours/'+colour+'.png" alt="'+colour+'" title="'+colour+'" />';            
                ct += '     <div class="product_details_lists">'+colour+'</div>';
                ct += '     <div class="product_details_lists"><input type="radio" onclick="update(this, \'Tent Colour\', \''+i+'\', 0)" name="colour" value="'+colour+'" ';
                // set as default (checked) if it's the standard colour
                if (standard == 1)
                {
                    // set standard colour
                    standard_colour = i;                    
                    
                    ct += "checked"
                    // add to breakdown if default
                    update("colour", "Tent Colour", i, 0);
                }
                ct += ' /></div>';
                ct += '</li>';
                
            }
        
            ct += '<br class="break" />';
            ct += '</ul>';
                
            // OPTION CUSTOMISE
            ot += '<div class="details_block">';        
            for (var option_type in data.options)
            {
                if (option_type != "Pinstriping")
                {
                    ot += '<ul class="main_options">';                
                    ot += '<strong>'+ option_type + '</strong><br />';
                    
                    // OPTION DESCRIPTIONS
                    ot += "<p>";
                    switch (option_type)
                    {
                        case "Scalloping" :
                            ot += "This is a distinctive and decorative border that is stiched around the top of the tent.";
                            break;
                        case "Main Wooden Poles" :
                            ot += "The main support poles (including ridge poles) can either come at their full tent height or be split at cost to help with transportation.";
                            break;
                        case "Hook on Walls" :
                            ot += "As standard the tent walls are stiched on. However, on certain tents we offer the option of having the walls hook on.";
                            break;
                        case "Doors" :
                            ot += "From tent-to-tent there can be multiple ways to customise the entrance to your tent.";
                            break;
                        case "Awnings" :
                            ot += "Having an awning offers external shelter and the ability to open your tent up to the outside world. Take in the views from the comfort and warmth of inside your tent!";
                            break;
                        case "Awning Walls" :
                            ot += "Additional protection from the elements for your awning.";
                            break;
                        case "Groundsheets" :
                            ot += "An optional groundsheet made with a plastic underlayer for waterproofing and a hessian topsheet.  Some people like a groundsheet for completeness, some prefer to add their own rugs and blankets.";
                            break;
                        case "Optional" :
                            ot += "Additional options worth considering for your tent.";
                            break;
                        default :
                            break;
                            
                    }
                    ot += "</p>";                    
                    
                    ot += '<img src="'+root_uri+'/media/images/options/'+option_type+'.png" width="80" height="75" />';
                }
                var none_added = 0;                             
                for (var option_name in data.options[option_type])
                {

                    for (var values_array in data.options[option_type][option_name])
                    {
                        // if option appropriate for size
                        if (data.options[option_type][option_name][values_array].size == current_size || data.options[option_type][option_name][values_array].size == null)
                        {
                            
                            // format details
                            var option_poa         = data.options[option_type][option_name][values_array].POA;
                            var option_standard    = data.options[option_type][option_name][values_array].standard;
                            var option_value;
                            
                            if (option_poa == 1)
                            {
                                option_value = 1;
                            }
                            else
                            {
                                option_value = data.options[option_type][option_name][values_array].price;
                            }
                            
                            if (option_type == "Pinstriping")
                            {
                                
                                if (option_value == 1)
                                {
                                    ps = 'Please add <span class="option_name">Pinstriping</span> to my tent for '+currency + "POA" + 
                                    '&nbsp;<input type="checkbox" name="pinstriping" onclick="update(this, \'Pinstriping\', \'Yes\') "value="'+option_value+'">';                                
                                }
                                else
                                {
                                    ps = 'Please add <span class="option_name">Pinstriping</span> to my tent for '+currency + option_value + 
                                    '&nbsp;<input type="checkbox" name="pinstriping" onclick="update(this, \'Pinstriping\', \'Yes\', '+option_value+') "value="'+option_value+'">';                                
                                }
                                
                                pinstriping(ps, "show");
                                 
                            }
                            else
                            {
                                
                                if (option_standard == 1)
                                {
                                    // Standard option (none equivilient)
                                    if (option_name == "Not Available")
                                    {
                                        ot += option_name;
                                    }
                                    else
                                    {
                                        ot += '<li><input type="radio" name="'+option_type+'" onclick="update(this, \''+option_type+'\', \''+option_name+'\', '+option_value+') "value="'+option_value+'" checked />';
                                        ot += option_name;
                                        if (option_type != "Scalloping")
                                        {
                                            ot += "&nbsp[Standard]";
                                        }
                                        ot += "</li>";
                                        
                                        update(option_type, option_type, option_name, option_value);
                                    }                                
                                }
                                else
                                {
                                    // switch on type to see if "none" is applicable
                                    switch (option_type)
                                    {                                 
                                        case "Groundsheets" :
                                            if (none_added == 0)
                                            {
                                                ot += '<input type="radio" name="'+option_type+'" onclick="update(this, \''+option_type+'\', \'remove\') "value="0" checked/>None';
                                                none_added = 1;                                                
                                            }
                                            break;
                                        case "Hook on Walls" :
                                            if (none_added == 0)
                                            {
                                                ot += '<input type="radio" name="'+option_type+'" onclick="update(this, \''+option_type+'\', \'remove\') "value="0" checked/>None';
                                                none_added = 1;                                                
                                            }
                                            break;
                                        case "Awnings" :
                                            if (none_added == 0)
                                            {
                                                ot += '<input type="radio" name="'+option_type+'" onclick="update(this, \''+option_type+'\', \'remove\') "value="0" checked/>None';
                                                none_added = 1;                                              
                                            }
                                            break;
                                        case "Awning Walls" :
                                            if (none_added == 0)
                                            {
                                                ot += '<input type="radio" name="'+option_type+'" onclick="update(this, \''+option_type+'\', \'remove\') "value="0" checked/>None';
                                                none_added = 1;                                                
                                            }
                                            break;                                                                                                                         
                                        default :
                                            break;
                                    }
                                    
                                    ot += '<li>';
                                    
                                    if (option_type == "Optional")
                                    {
                                       // Optionals are checkboxes as you can have more than one
                                        ot += '<input type="checkbox" name="'+option_type+'" onclick="update(this, \''+option_type+c+'\', \''+option_name+'\', '+option_value+') "value="'+option_value+'" />';
                                        ot += option_name;
                                        c++;
                                    }
                                    else
                                    {
                                        ot += '<input type="radio" name="'+option_type+'" onclick="update(this, \''+option_type+'\', \''+option_name+'\', '+option_value+') "value="'+option_value+'" />';
                                        ot += option_name;
                                    }
                                    
                                    if (option_value > 0 && option_poa == 0)
                                    {
                                        ot += "&nbsp;[Add&nbsp;" + currency + option_value + "]";                                 
                                    }
                                    if (option_poa == 1)
                                    {
                                        ot += "&nbsp;[POA]";
                                    }                                 
                                    
                                    ot += '</li>';
                                }                           
                            }
                            
                        }
                    }
                }
                
                if (option_type != "Pinstriping")
                {
                    ot += '<br class="break" />';
                    ot += '</ul>';              
                }
                
            }
        
        load_template(ct, "colours");
        load_template(ot, "options");
        toggle_fr("show");
        toggle_confirm("show"); 
    }
    c=1; 
}

function refresh_cart()
{
    var breakdown           = new String();
    var basket_totals       = new String();
    var current_sub_total   = new Number(0);
    var current_total       = new Number(0);
    
    var size_price          = new Number(0);
    var awning_price        = new Number(0);
    var awning_wall_price  = new Number(0);
    
    // PERCENTAGE UPDATES
    for (var i in customer_choices)
    {
        // update size price
        if (customer_choices[i][0] == "size")
        {
            size_price = customer_choices[i][3];
        }
    }
    
    for (var i in customer_choices)
    {
        if (customer_choices[i][0] == "Tent Colour")
        {
            if (customer_choices[i][2] != standard_colour)
            {
                customer_choices[i][3] = (size_price + awning_price + awning_wall_price) * percentage_increase;
            }
        }        
    }
    
    for (var i in customer_choices)
    {
        if (customer_choices[i][0] == "Fire Retardant")
        {
            customer_choices[i][3] = (size_price + awning_price + awning_wall_price) * percentage_increase;
        }
    }
    
    // BREAKDOWN
    poa_in_cart = false;
    for (var i in customer_choices)
    {
        /**
        * customer_choices
        * [0] = reference (i.e. what comes in from forms etc)
        * [1] = type      |
        * [2] = name      | - shown to customer
        * [3] = price     |
        */        

        // add price (check for POA's)
        if (customer_choices[i][3] == 1)
        {
            poa_in_cart = true;
        }
        else
        {
            current_sub_total += customer_choices[i][3]*1;
        }
        
        // for display
        breakdown += '<p>';      
        breakdown += '<strong>'+customer_choices[i][1] + "</strong><br />";
        breakdown += customer_choices[i][2] + "<br />";
        if (customer_choices[i][0] == "colour" && customer_choices[i][3] == 0)
        {
            breakdown += "Standard<br />";
        }
        else
        {
            // another POA check...
            var item_price = customer_choices[i][3]*1;
            if (item_price == 1)
            {
                breakdown += "POA<br />";
            }
            else
            {
                breakdown += currency + item_price.toFixed(2) + "<br />";
            }
        }
        breakdown += '</p>';
    }
    
    // TOTALS
    current_total       = current_sub_total * VAT
    
    // DISPLAY
    if (current_total == 0 && customer_choices.length == 0)
    {
        basket_totals += '<-- Choose Size to Begin';
    }
    else
    {
        if (poa_in_cart == true)
        {
            basket_totals += '<strong>Total </strong>(inc. VAT) '+currency+'<span class="basket_total_price">POA</span>';
        }
        else
        {
            basket_totals += '<strong>Sub Total </strong>(ex. VAT) '+currency+'<span class="basket_sub_total_price">'+current_sub_total.toFixed(2)+'</span><br />';            
            basket_totals += '<strong>Total </strong>(inc. VAT) <span class="gold">'+currency+current_total.toFixed(2)+'</span>';
        }
        
    }
    
    // update basket
    $('#basket_summary').html(breakdown);
    $('#basket_total').html(basket_totals);
    
    // additional step to add hidden fields for postdata
    var hf = new String();
    var bo = $('#buildOrder');
    hf += '<input type="hidden" name="product_id" value="'+product_id+'" />';
    hf += '<input type="hidden" name="total" value="'+current_sub_total+'" />';
    for (var i in customer_choices)
    {
        hf += '<input type="hidden" name="order[]" value="'+customer_choices[i][1]+"|"+customer_choices[i][2]+"|"+customer_choices[i][3]+'" />';
    }
    
    bo.html(hf);
     
}

function load_template(template, choice)
{

    refresh_cart();  
    
    if (choice == "sizes")
    {
         $('#sizes').html(template).hide().slideDown("slow");
    }
    else if (choice == "options")
    {
        $('#choices').html(template);        
        toggle_choices("show");
    }
    else if (choice == "colours")
    {
        $('#options_colours').html(template);
        toggle_colours("show");
    }
    else
    {
        
    }
}

/**
* MISC FUNCTIONS
*/
function pinstriping(content, direction)
{
    if (direction == "show")
    {
        $('#pinstriping_cont').html(content);
        $('#pinstriping').show().slideDown("slow");
    }
    else
    {
        $('#pinstriping').hide();
    }    
}

function toggle_fr(direction)
{
    if (direction == "show")
    {
        $('#fire_retardant').show().slideDown("slow");
    }
    else
    {
        $('#fire_retardant').hide();
    }
}

function toggle_confirm(direction)
{
    if (direction == "show")
    {
        $('#confirm_order').show().slideDown("slow");
    }
    else
    {
        $('#confirm_order').hide();
    }    
}

function toggle_choices(direction)
{
    if (direction == "show")
    {
        $('#choices_toggle').show().slideDown("slow");
    }
    else
    {
        $('#choices_toggle').hide();
    }    
}

function toggle_colours(direction)
{
    if (direction == "show")
    {
        $('#colours_toggle').show().slideDown("slow");
    }
    else
    {
        $('#colours_toggle').hide();
    }
}

/**
* Prototype Size for counting objects
*/
Object.size = function(obj)
{
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};


