﻿// Globals vars
var priceRange = '';
var priceBreaks = new Array();
var stock = null;

function addToWishList()
{
    var pcode = $('#ProductCode').val();
    
    $.post('/wishlist_add.aspx', { productcode: pcode }, function() {
        $('#addtowishlist').html('<span class="error">Added To Wish List</span> <a href="/wishlist/">View</a> &raquo;');
        // alert('Added to wishlist');
    });
}

// Show the 'Email to a Friend' form
function showRecommendationBox()
{
    var pos = $('#emailtoafriend').position();

    $('#recommendationform').css('top', pos.top - 200).css('left', pos.left - 182);
    $('#recommendationform').show();
}

// Show the delivery info popup
function showDeliveryBox()
{
    var pos = $('#deliveryinfo').position();

    $('#deliveryinfobox').css('top', pos.top - 100).css('left', pos.left - 182);
    $('#deliveryinfobox').show();
}

// Show the 'Notify me when this comes back into stock' form
function showStockNotify()
{
    var pos = $('#stocknotify').position();

    $('#notifyform').css('top', pos.top - 200).css('left', pos.left - 182);
    $('#notifyform').show();
}

// Show the review information popup box
function showReviewInfo()
{
    var pos = $('#reviewinfolink').position();

    $('#reviewinfo').css('top', pos.top - 200).css('left', pos.left - 182);
    $('#reviewinfo').show();
}


// Check the user has filled in both fields in the 'Email to a Friend' form
function validateRecommendationForm()
{
    $('#recommendationform .required').remove();

    var email = $('#RecommendationEmail').val();
    var emailRegex = /[a-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b/gi;

    if(email == '')
    {
        $('#recommendationform textarea').parent().after('<p class="required">You must fill in your friend\'s email address.</p>');
        return false;
    }
    else if(!email.match(emailRegex))
    {
        $('#recommendationform textarea').parent().after('<p class="required">The email address you entered is not a valid address.</p>');
	    return false;
    }
    else
    {
        return true;
    }
}

// Check the user has filled in both fields in the 'Product Review' form
function validateReviewForm()
{
    $('#reviewform .required').remove();

	if ($('#FullName').val() == "")
	{
        $('#reviewform textarea').parent().after('<p class="required">You must fill in your name.</p>');
        return false;
	}

    var email = $('#Email').val();
    var emailRegex = /[a-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b/gi;

    if(email == '')
    {
        $('#reviewform textarea').parent().after('<p class="required">You must fill in your email address.</p>');
        return false;
    }
    else if(!email.match(emailRegex))
    {
        $('#reviewform textarea').parent().after('<p class="required">The email address you entered is not a valid address.</p>');
	    return false;
    }
    else
    {
        return true;
    }
}

// Check the user has filled in both fields in the 'Email to a Friend' form
function validateNotifyForm()
{
    $('#notifyform .required').remove();

    var email = $('#NotifyEmail').val();
    var emailRegex = /[a-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b/gi;

    if(email == '')
    {
        $('#notifyform #NotifyEmail').parent().after('<p class="required">You must fill in your email address.</p>');
        return false;
    }
    else if(!email.match(emailRegex))
    {
        $('#notifyform #NotifyEmail').parent().after('<p class="required">The email address you entered is not a valid address.</p>');
	    return false;
    }
    else
    {
      $("#NotifySizeCode").val($('#SizeCode').val());
      $("#NotifyColourCode").val($('#ColourCode').val());
      $("#NotifyOptionCode").val($('#OptionCode').val());
      return true;
    }
}

// Show the box that allows user to fill in special instructions
function showSpecialInstructionsBox()
{
    var pos = $('#AddToOrder').position();
    var box = $('#specialinstructionscontainer');
    var width = $('#Width').val();
    
    if (parseInt(width))
    {
      // This product uses the sheet metal template, so the special instructions are added automatically
      return true;
    }

    switch(parseInt($('#SpecialInstructionDisplay').attr('value'), 10))
    {
        case 0:
            return true;
        case 10:
        case 20:
            var top = (pos.top - (box.height() - 60));
            // alert((top + box.height()) + '-' + $(window).height());
            box.css('top',top).css('left', pos.left - 182);
            box.show();
            return false;
    }
}

// Check that the user has selected one of each available option before adding product to cart
function checkOptions()
{
    var option = $('#OptionCode').css('background', 'none');
    var colour = $('#ColourCode').css('background', 'none');
    var size = $('#SizeCode').css('background', 'none');
    var quantity = $('#Quantity').css('background', 'none');
    var code = $('#ProductCode').val();
    var stockStatus = parseInt($('#StockStatus').val(), 10);
    var stockLevel = parseInt($('#StockLevel').val(), 10);

    $('#adderror').remove();

    var errors = new Array();
    var msgs = new Array();
    // Separate array for stuff that will not be displayed in bright red
    var msgs2 = new Array();

    // We first check whether each item is a hidden field - if this is the case there 
    // is only one option so we don't need to validate
    if(!option.is('input:hidden') && option[0].selectedIndex == 0) { errors.push(option); msgs.push('Please select an Option.'); }
    if(!colour.is('input:hidden') && colour[0].selectedIndex == 0) { errors.push(colour); msgs.push('Please select a Colour.'); }
    if(!size.is('input:hidden') && size[0].selectedIndex == 0) { errors.push(size); msgs.push('Please select a Size.'); }
    if(quantity.is('input:hidden'))
    {
      if(isNaN(parseInt(quantity.val())) || quantity.val() == '0')
      {
        if (code != "A82" && code != "SO1273")
        {
          errors.push(quantity); msgs.push('The width and length multiplied together must be a whole number. Width and length must be a whole number, or can contain .5');
        } else {
          errors.push(quantity); msgs.push('The width and length must be whole numbers.');
        }          
      }
    } else {
      if(isNaN(parseInt(quantity.val())) || quantity.val() == '0') { errors.push(quantity); msgs.push('Quantity must be numeric.'); }
      if (isNaN(quantity.val()) || (parseInt(quantity.val()) != Number(quantity.val())))
      {
          errors.push(quantity); 
          msgs.push('Please enter a round number and no symbols in the quantity box.');
      }
    }    
    if(stockStatus == 2 && parseInt(quantity.val()) > stockLevel)
    {        
        errors.push(quantity); 
        msgs.push('Please adjust the Quantity - we currently only have ' + stockLevel + ' in stock.');
    }
    
    if(stockStatus == 1 && parseInt(quantity.val()) > stockLevel && $('#stockconfirm').val() != 1)
    {
      errors.push(quantity);
      msgs.push('We only have ' + stockLevel + ' of this item available.');
      msgs2.push('<a href=\"#\" onclick=\"confirmStock();\">Click here</a> to continue adding to your basket. Any items you order that are currently out of stock will be despatched as soon as they come back into stock, with no additional postage (UK).');
      msgs2.push('Alternatively, if you would like us to email you when this comes back into stock, <a id=\"stocknotify\" href=\"#\" onclick=\"showStockNotify();\">click here</a>.');
    }

    var minimumOrder = parseInt($('#MinimumOrder').val());
    var qty = parseInt(quantity.val());
    if(minimumOrder != 0 && qty < minimumOrder)
    {
        errors = new Array();
        msgs = new Array();
        msgs2 = new Array();
        errors.push(quantity);
        msgs.push("Sorry, you must order at least " + minimumOrder + " of this item");
    }

    if(errors.length > 0)
    {
        for(e in errors)
            errors[e].css('backgroundColor', '#b1f7ff');

        $('#stocknotify').remove();
        $('#stockwarning').remove();
        $('#stockwarning2').remove();
        $('.requiredmsg2').remove();
        $('#AddToOrder').parent().before('<p class="required" id="adderror">' + msgs.join(', ') + '</p>');
        $('#AddToOrder').parent().before('<p class="requiredmsg2">' + msgs2.join('</p><p class="requiredmsg2">') + '</p>');

        return false;
    }
    else
    {
        return showSpecialInstructionsBox();
    }
}

function confirmStock()
{
  // Used if the item can be backordered and they want to order more than are currently available.
  // This is called if they confirm that they want to go ahead
  $('#stockconfirm').val(1);
  $('#addtoorderform').submit();
}

// TODO: Is this needed any longer?
function toggleAddButtonEnable(enable)
{
    if(enable)
        $('#AddToOrder').removeAttr('disabled');
    else
        $('#AddToOrder').attr('disabled', 'disabled');
}

// Show the price of the current option depending on quantity
function showPrice(quantity)
{
    ConvertUnits();
    var priceHtml = '';
    // If using sheet metal template, quantity will be zero until they have typed in the dimensions.
    // So, show pricing for one item in that case
    if (quantity == 0) { quantity = 1; }

    for(var x=0; x<priceBreaks.length; x++)
    {
        if(priceBreaks[x][0] <= quantity && priceBreaks[x][1] >= quantity) 
        {
            priceHtml = '&pound;' + priceBreaks[x][2] + ' each';

            // If this isn't the last price break, show the next one underneath the current price
            if(x != priceBreaks.length - 1) 
                priceHtml += '<span>Buy <b>' + priceBreaks[(x+1)][0] + '</b> or more: &pound;' + priceBreaks[(x+1)][2] + ' each!</span>';

            return priceHtml;
        }
    }
}

function ConvertUnits()
{
    // Shows the currently selected quantity in metres if the selected size is in centimetres
    var converted = "";
    if ($('#SizeCode').val() == "-615")
    {
        converted = Number($('#Quantity').val()) / 100;
        converted = "(" + converted + " metres)";
    } else {
        converted = "";
    }   
    $('#Converted').html(converted);
}

function showSheetPrice(quantity)
{
    var priceHtml = '';

    for(var x=0; x<priceBreaks.length; x++)
    {
        if(priceBreaks[x][0] <= quantity && priceBreaks[x][1] >= quantity) 
        {
          var price = priceBreaks[x][2] * quantity;
          price = price.toFixed(2);
          priceHtml = '&pound;' + price;
          return priceHtml;
        }
    }
}

// Get the price breaks for a product option
function getPriceBreaks(jsonItems)
{
    priceBreaks.length = 0;

    $.each(jsonItems, function(i, item) {
        priceBreaks.push([item.min, item.max, item.price]);
    });
}

// Get the stock remaining for a particular product option
function getStock(productOptionCode)
{
    var stockLevel = 0;

    $.each(stock.items, function(i, item) {
        if(item.code == productOptionCode) 
            stockLevel = parseInt(item.stock, 10);
    });

    return stockLevel;
}

// Get the stock status for a particular product option
function getStatus(productOptionCode)
{
    var stockStatus = 0;

    $.each(stock.items, function(i, item) {
        if(item.code == productOptionCode) 
            stockStatus = parseInt(item.status, 10);
    });

    return stockStatus;
}

// Displays the stock warning message if option is not in stock
function showStockWarning(option)
{
    $('#stockwarning').remove();
    $('#stockwarning2').remove();
    $('#stocknotify').remove();

    // If stock is null, it means we were unable to get the live stock updates from the 
    // remote server and so we need to use the stock data from our database
    var stockCount = (stock == null) ? parseInt(option.stock, 10) : getStock(option.code);
    var stockStatus = (stock == null) ? parseInt(option.status, 10) : getStatus(option.code);
    
    $('#StockLevel').attr('value', stockCount);
    $('#StockStatus').attr('value', stockStatus);

    if(stockCount == 0)
    {
        switch(stockStatus)
        {
            case 1: // Allow back order
                var warningText = '<p id="stockwarning2"><span class="stockwarning">Sorry, this item is currently out of stock.</span> However, you can still place your order and we will dispatch it when it becomes available.</p>';
                warningText += "<p id=\"stocknotify\">Alternatively, if you would like us to email you when this comes back into stock, <a id=\"stocknotify\" href=\"#\" onclick=\"showStockNotify();\">click here</a>.</p>";
                $('#pricedisplay').after(warningText);
                break;
            case 2: // Don't allow back order
                $('#pricedisplay').after('<p id="stockwarning">Sorry, this item is currently out of stock.</p>');
                // Disable the button/show warning
                break;
            case 3: // Don't sell - these should never be displayed on the site anyway
                break;
            default: // Free stock, never show message
                break;
        }
    }
}

// Display the price for a specific product option
function getPrice(productCode, colourCode, sizeCode, optionCode)
{
    if(colourCode == '' || sizeCode == '' || optionCode == '')
    {
        // toggleAddButtonEnable(false);

        $('#stockwarning').remove();
        $('#stocknotify').remove();
        $('#pricedisplay').html(priceRange);
    }        
    else
    {
        // toggleAddButtonEnable(true);

        $.getJSON('/ajax_price.aspx', { id: productCode, c: colourCode, s: sizeCode, o: optionCode }, function(option) 
        {   
            getPriceBreaks(option.pricebreaks);

            $('#pricedisplay').html(showPrice(parseInt($('#Quantity').val(), 10)));
            $('#Price-Sheet').html(showSheetPrice(Number($('#Quantity').val()))); 
            $('#MinimumOrder').val(option.minimumorder)
            showStockWarning(option);
        });
    }
}

// Populate the colour drop-down
function getColours(productCode)
{
    $.getJSON('/ajax_colour.aspx', { id: productCode }, function(json) 
    {
        var o = new Array('<option value="">Please Select</option>');
        
        $.each(json.items, function(i, item){
             o[o.length] = '<option value="' + item.id + '">' + item.t + '</option>';
        });
        
        $('#ColourCode').html(o.join(''));
    });
}

// Populate the size drop-down
function getSizes(productCode, colourCode)
{
    $.getJSON('/ajax_size.aspx', { id: productCode, c: colourCode }, function(json) 
    {    
        var o = new Array('<option value="">Please Select</option>');
        
        $.each(json.items, function(i, item){
             o[o.length] = '<option value="' + item.id + '">' + item.t + '</option>';
        });
        
        $('#SizeCode').html(o.join(''));
    });
}

// Populate the option drop-down
function getOptions(productCode, colourCode, sizeCode)
{
    $.getJSON('/ajax_option.aspx', { id: productCode, c: colourCode, s: sizeCode }, function(json) 
    {    
        var o = new Array('<option value="">Please Select</option>');
        
        $.each(json.items, function(i, item){
             o[o.length] = '<option value="' + item.id + '">' + item.t + '</option>';
        });
        
        $('#OptionCode').html(o.join(''));
    });
}

// Actions to perform as soon as DOM is ready
$(document).ready(function()
{
    // If stockJson is empty it means we failed to get the live stock update from KC
    // If not, we can eval it straight into an object for later use
    if(stockJson != '');
        stock = eval(stockJson);      

    // toggleAddButtonEnable(false);

    $('#reviewform').hide();
    $('#reviewlink').bind('click', function() { $('#reviewform').show(); $(this).hide(); });

    $('#addtoorderform').bind('submit', checkOptions);

    $('#SubmitSpecialInstructions').bind('click', function() {
        $('#specialinstructionscontainer .required').remove();
        if(parseInt($('#SpecialInstructionDisplay').attr('value'), 10) == 20)
        {
            if($('#SpecialInstructionsPopup').attr('value') == '')
            {
                $('#specialinstructionscontainer textarea').parent().after('<p class="required">You must fill in the special instructions for this product</p>');
                return false;
            }
        }

        $('#SpecialInstructions').attr('value', $('#SpecialInstructionsPopup').attr('value'));
        $('#addtoorderform').unbind('submit').submit();
        
    });

    $('#emailtoafriend a').bind('click', showRecommendationBox);
    $('#addtowishlist a').bind('click', addToWishList);
    $('#deliveryinfo a').bind('click', showDeliveryBox);

    // Make thumbnail images change the large image src
    $('#thumbnails a').bind('click', function() 
    { 
        $('#largeimage').attr('src', $(this).attr('href'));
        $('#largeimage').parent().attr('href', $(this).attr('href').replace(/\/lge\//gi, '\/xlge\/'));
        return false;
    });

    // Bind HighSlide to large image's link
    $('#largeimage').parent().bind('click', function() 
    {
        // console.log($(this)[0]);
        hs.expand($(this)[0]);
        return false;
    });

    // Change price display when quantity is changed - show price and next price break
    $('#Quantity').bind('keyup', function() 
    { 
        $('#pricedisplay').html(showPrice(parseInt($(this).val(), 10)));
    });

    priceRange = $('#pricedisplay').html();

    var productCode = $('#ProductCode').val();
    var colourCode = $('#ColourCode').val() ;
    var sizeCode = $('#SizeCode').val();
    var optionCode = $('#OptionCode').val();

    // If we already have a value for all three, at this point, there is only one option, 
    // so just show the price for that option and don't do anything else!
    if(colourCode != '' && sizeCode != '' && optionCode != '')
    {
        getPrice(productCode, colourCode, sizeCode, optionCode);
    }
    else // There's more than one option, so start figuring out what to show
    {
        if(colourCode == '') // There's more than one colour
        {
            // populate the colour drop down
            getColours(productCode);

            // When user changes colour drop down
            $('#ColourCode').bind('change', function()
            {
                // If there is a size drop down
                if(!$('#SizeCode').is('input:hidden'))
                {
                    // Populate the size drop down
                    getSizes(productCode, $(this).val());

                    // If there's an option drop down
                    if(!$('#OptionCode').is('input:hidden')) 
                    {
                        // Populate the options drop down (this will just clear it, because there's no size selected)
                        getOptions(productCode, $(this).val(), '');
                    }
                    else
                    {
                        // We know the option value so just get the price
                        getPrice(productCode, $('#ColourCode').val(), $('#SizeCode').val(), $('#OptionCode').val());
                    }
                }
                else // There isn't a size drop down
                {
                    // If there's an option drop down
                    if(!$('#OptionCode').is('input:hidden'))
                    {
                        // We know the colour and size, so populate the options
                        getOptions(productCode, $(this).val(), $('#SizeCode').val());
                    }
                    else
                    {
                        // We know all the codes, so show the price
                        getPrice(productCode, $('#ColourCode').val(), $('#SizeCode').val(), $('#OptionCode').val());
                    }
                }
            });
        }
        else // There's only one colour option, so we can get the sizes
        {
            // If there is a size drop down
            if(!$('#SizeCode').is('input:hidden'))
            {
                // Populate the sizes menu
                getSizes(productCode, colourCode);
            }
        }

        if(sizeCode == '') // There's more than one size
        {
            $('#SizeCode').bind('change', function()
            {
                // If there's an option drop down
                if(!$('#OptionCode').is('input:hidden'))
                {
                    // We know the colour and size, so populate the options
                    getOptions(productCode, $('#ColourCode').val(), $(this).val());
                }
                else
                {
                    // We know all the codes, so show the price
                    getPrice(productCode, $('#ColourCode').val(), $('#SizeCode').val(), $('#OptionCode').val());
                }
            });
        }
        else // There's only one size option, so show the options
        {
            // If there is an option drop down
            if(!$('#OptionCode').is('input:hidden'))
            {
                // Populate the options
                getOptions(productCode, $('#ColourCode').val(), $('#SizeCode').val());
            }
        }

        if(optionCode == '') // There's more than one option
        {
            $('#OptionCode').bind('change', function()
            {
                // Show the price
                getPrice(productCode, $('#ColourCode').val(), $('#SizeCode').val(), $(this).val());
            });
        }
        else 
        {
            // We shoudn't ever get here because this is the first case we check for
            // getPrice(productCode, $('#ColourCode').val(), $('#SizeCode').val(), $('#OptionCode').val());
        }
    }

    // No idea why, but this button intermittently gets disabled on refresh in Firefox
    $('#SubmitReview').removeAttr('disabled');
    
    $('#Width').bind('keyup', UpdateSheetQuantity); 
    $('#Length').bind('keyup', UpdateSheetQuantity); 
    
    $('#reviewinfolink').bind('click', function() {
		showReviewInfo();
		return(false);
    });
});

function UpdateSheetQuantity()
{
  {
    var width = Number($('#Width').val());
    var length = Number($('#Length').val());

    var pcode = $('#ProductCode').val();
    
    if (!isNaN(width) && !isNaN(length) && Number(width) == parseInt(width) && Number(length) == parseInt(length))
    {
      $('#Quantity-Sheet').html(String(width * length)); 
      $('#Quantity').val(String(width * length));
      $('#Price-Sheet').html(showSheetPrice(Number($('#Quantity').val()))); 
      $('#SpecialInstructions').val(String(width) + " x " + String(length));
    } else if (pcode != "A82" && pcode != "SO1273" && Number(width * 2) == parseInt(width * 2) && Number(length * 2) == parseInt(length * 2) && Number(width * length) == parseInt(width * length)) {
      // One dimension contains .5, but when multiplied together this is still a whole number of units
      $('#Quantity-Sheet').html(String(width * length)); 
      $('#Quantity').val(String(width * length));
      $('#Price-Sheet').html(showSheetPrice(Number($('#Quantity').val()))); 
      $('#SpecialInstructions').val(String(width) + " x " + String(length));
    } else {
      $('#Quantity-Sheet').html(""); 
      $('#Quantity').val("0");
      $('#Price-Sheet').html(""); 
      $('#SpecialInstructions').val("");
    }
  }
}