﻿$(document).ready(function(){
    
    $(document).pngFix();

    // Highlight link in navigation bars
    if (location.href.indexOf('.aspx') == -1){
        $('#nav li:first').addClass('on');
    }
    else{
        $('li a[href*=' + location.href.split('/')[location.href.split('/').length - 1] + ']').parent().addClass('on');
        if ($('#nav li.on').length == 0){
            $('#nav li a[href*=' + location.href.split('/')[location.href.split('/').length - 2] + ']').parent().addClass('on');
        }
        $('#nav li.on:not(:last)').removeClass('on');
    }
        
    // Checkout only - Select the country if in the querystring 
    if (urlParameter('country')){
        $('.iCountry option[value=' + urlParameter('country').toUpperCase() + ']').attr('selected','selected');
    }
    if ($('.iCountry option:selected').is('.EU') && $('.iCountry').val() != 'GB'){
        $('#validateVat:hidden').show();
    }
    else{   
        $('#validateVat:visible').hide();
    }
    $('select[preselect]').each(function(){
        $(this).find('option:contains(' + $(this).attr('preselect') + ')').attr('selected','selected');
    });
    
    // Move the message box with scrolling
    $(window).scroll(function(){
        $('#userMsg').css('top',$(window).scrollTop() + $(window).height()/3 + 'px');
    });
    
    // Duplicate contact number for visibility
    $('#header').append('<div id="contactShadow">' + $('#contact').html() + '</div>');
    
    // Swap cart tabs
    $('.tab').click(function(){
        if (!$(this).is('.open')){
            $('.tab.open').removeClass('open');
            $(this).addClass('open');
            $(this).parents('.box').find('table').hide();
            $(this).parents('.box').find('#' + $(this).attr('view')).show();
            $('#checkout').val($(this).attr('complete'));
            checkEmpty();
        }
        if ($(this).attr('view') != 'shopping'){
            $('#minOrder').hide();
        }
        else{
            $('#minOrder').show();
        }
    });
    
    // Contact form validation and storing data
    $('.submit').click(function(){
		if ($(this).parents('form').find('.mandatory').length > 0){
		    $('.mandatory').each(function(){
			    if (this.value == ''){
				    $(this).addClass('error');
			    }
		    });
		    if ($('.error').length > 0){
			    alertUser('Please complete all fields marked with an asterisk.');
			    return false;	
		    }
		}
		// Store user data
        var aryUserDetails = [];
        $('.remember').each(function(){
            if (this.value != ''){
                aryUserDetails.push($(this).attr('name') + ':' + this.value);
            }
            else if ($(this).find('option:selected').text() != ''){
                aryUserDetails.push($(this).attr('name') + ':' + $(this).find('option:selected').text());
            }
        });
        $.cookie('userDetails',aryUserDetails.join('|'), { expires: 90, path: '/' });
        
	});
	
	$('.mandatory').blur(function(){
		if (this.value != ''){
			$(this).removeClass('error');
		}		
	});
    
    // Present stored form data
    if ($.cookie('userDetails')){
        userDetails = $.cookie('userDetails').split('|');
        for (udIndex=0; udIndex < userDetails.length; udIndex++){
            if ($('input[name=' + userDetails[udIndex].split(':')[0] + ']') && $('input[name=' + userDetails[udIndex].split(':')[0] + ']').val() == ''){
                $('input[name=' + userDetails[udIndex].split(':')[0] + ']').val(userDetails[udIndex].split(':')[1]);
            }
            if ($('select[name=' + userDetails[udIndex].split(':')[0] + ']') && $('select[name=' + userDetails[udIndex].split(':')[0] + ']').val() == ''){
                $('select[name=' + userDetails[udIndex].split(':')[0] + '] option[text=' + userDetails[udIndex].split(':')[1] + ']').attr('selected','selected');
            }
        }
    }
    
    
    // Populate carts if cookie is found
    if ($.cookie('cart')){
        cartItems = $.cookie('cart').split('|');  
        totalCost = 0;
        for (i=0; i < cartItems.length; i++){
            itemDetails = cartItems[i].split('#');
            totalCost += parseFloat(itemDetails[2]);
            $('#shopping tbody').append('<tr title="' + decodeURI(itemDetails[3]) + '" pid="' + itemDetails[0] + '" cost="' + itemDetails[2] + '" qty="' + itemDetails[1] + '"><td class="wide">' + itemDetails[0] + '</td><td>' + itemDetails[1] +'</td><td basecost="' + itemDetails[2] + '">' + CurrencyFormatted(itemDetails[2]) + '</td><td><img src="_images/delete.png" class="remove" /></td></tr>');    
            $('#cartButtons').show();
            $('#cartEmpty').hide();
            $('tr[pid=' + itemDetails[0] + '] .qty').val(itemDetails[1]);
            $('tr[pid=' + itemDetails[0] + '] .add').val('Update').addClass('edit');
        }
        $('#shopping tfoot tr td').eq(2).attr('basecost',totalCost).text(CurrencyFormatted(totalCost));
    }
    
    if ($.cookie('quote')){
        quoteItems = $.cookie('quote').split('|');  
        for (i=0; i < quoteItems.length; i++){
            itemDetails = quoteItems[i].split('#');
            $('#quote tbody').append('<tr title="' + decodeURI(itemDetails[3]) + '" qty="' + itemDetails[1] + '" quotetype="' + itemDetails[0] + '"><td class="wide">' + decodeURI(itemDetails[0]) +'</td><td>' + itemDetails[1] + '</td><td><img src="_images/delete.png" class="remove" /></td></tr>');    
            $('#cartButtons').show();
            $('#cartEmpty').hide();
            //$('tr[pid=' + itemDetails[0] + '] .qty').val(itemDetails[1]);
            //$('tr[pid=' + itemDetails[0] + '] .add').val('Update').addClass('edit');
        }
    }
    
    checkEmpty();
    
    // Change user preferences if cookie is found
    if ($.cookie('prefUnits')){
        $('#prefUnits option[value=' + $.cookie('prefUnits') + ']').attr('selected','selected');
    }
    changeUnits();

    if ($.cookie('prefCcy')){
        if ($('#prefCcy').length > 0){
            $('#prefCcy li.on').removeClass('on');
            $('#prefCcy a#' + $.cookie('prefCcy')).parent().addClass('on');
        }
        $('.ccyLabel').text($.cookie('prefCcy').toUpperCase());
    }
    if (!urlParameter('OrderID')){
        changeCcy();
    }
    
    // Check the quantity boxes
    $('.qty')
        .bind('focus',function(){
            $(this).addClass('focus');
            if ($(this).val()){ $(this).attr('oldVal',$(this).val()); }
            $(this).parents('tr').find('.add').removeAttr('disabled');
            $(this).val('');
        })
        .bind('blur',function(){
            $(this).removeClass('focus');
            if (this.value == ''){
                this.value = $(this).attr('oldVal');
                $(this).parents('tr').find('.add').attr('disabled','disabled');
            }
            else if (!IsNumeric(this.value)){
                alertUser('Only numbers are allowed in this field. Please try again.',false);
                this.value = $(this).attr('oldVal');
                $(this).parents('tr').find('.add').attr('disabled','disabled');
            }
        });

    // Add to cart buttons
    $('.add').live('click', function(){
        if (!$(this).attr('disabled')){
    
            r = $(this).parents('tr');
            pid = r.attr('pid');
            prc = r.attr('price');
            qty = r.find('.qty').val();
            descr = getDescription(r);
            
            if (qty == 0 && (!pid || $('#shopping tbody tr[pid=' + pid + ']').length == 0)){
                alertUser('Please type in the quantity of this item you wish to purchase.',false);
            }
            else if (IsNumeric(qty)){
                // If there's no product id, then add to the quote cart
                if (!pid){
                    quotetype = 'Custom ' + $('.products li.on').text().toLowerCase();
                    addToQuote(descr,qty,quotetype);                
                }
                else{
                    addToCart(pid, qty, prc, descr);
                    $(this).val('Update').addClass('edit').attr('disabled','disabled');
                }
            }
        }
    });

    $('.cart tbody tr').live('click', function(){
        if (!$(this).is('.on')){
            $('.cart tbody tr.on').removeClass('on');
            r = $(this);
            
            // Find out which column is the qty
            qty = r.children().eq(1).text();
            r.addClass('on').children().eq(1).html('<input type="text" value="' + qty + '" class="update qty" />');    
        
            $(this).one('outerClick', function(){
                newQty = r.find('input').val();
                $(this).removeClass('on').children().eq(1).text(newQty);
                if (newQty != qty){
                    if (r.parents('table').is('#shopping')){
                        $('tr[pid=' + r.attr('pid') + ']').find('.qty').val(newQty);
                        updateCart();
                    }
                    else{
                        r.attr('qty', newQty);
                        updateQuote();
                    }
                }
            });
        }
    })
    .live('mouseover', function(e){
        if (!$(this).is('.on')){
            $('body').append('<div id="tooltip">' + $(this).attr('title') + '</div>');
            $('#tooltip').css('left',e.pageX + 10 + 'px').css('top',e.pageY + 10 + 'px');
            
            $(this).attr('title','').mousemove(function(e){
                $('#tooltip').css('left',e.pageX + 10 + 'px').css('top',e.pageY + 10 + 'px');
            });   
                
            $(this).mouseout(function(){
                $(this).attr('title', $('#tooltip').text()).unbind('mouseout').unbind('mousemove');
                $('#tooltip').remove();
                
            });
        }
    });

    // Dynamic remove buttons
    $('.remove').live('click', function(){
        if (confirm('Are you sure you want to remove this item from your cart?')){
            r = $(this).parents('tr'); 
            
            if ($('#shopping').is(':visible')){
                $('tr[pid=' + r.attr('pid') + ']').find('.qty').val('0');
                $('tr[pid=' + r.attr('pid') + ']').find('.add').val('Add');
                r.remove();
                updateCart();
            }
            else{
                r.remove();
                updateQuote();
            }
        }
    });

    // Empty shopping cart
    $('#empty').click(function(){
        if (confirm('Are you sure you want to remove all items?')){
            if ($('#shopping').is(':visible')){
                $('#shopping tbody tr').each(function(){
                    $('tr[pid=' + $(this).attr('pid') + ']').find('.qty').val('0');
                    $('tr[pid=' + $(this).attr('pid') + ']').find('.add').val('Add');
                    $(this).remove();
                });
                updateCart();
            }
            else{
                $('#quote tbody tr').remove();
                updateQuote();
            }
        }
    });

    // Adding or updating items to a cart 
    function addToCart(pid,qty,prc, descr){
        $('#shopping tbody tr[pid=' + pid + ']').remove();
        if (qty > 0){
            $('#shopping tbody').append('<tr title="' + descr + '" pid="' + pid + '" cost="' + qty*prc + '" qty="' + qty + '"><td>' + pid + '</td><td>' + qty +'</td><td basecost="' + roundNumber(qty*prc, 4) + '">' + roundNumber(qty*prc, 4) + '</td><td><img src="_images/delete.png" class="remove" /></td></tr>');
        }
        else{
            $('tr[pid=' + r.attr('pid') + ']').find('.add').val('Add to cart');
        }
        updateCart();
    }
    
    // Adding or updating items to the quote
    function addToQuote(descr,qty,quotetype){
        $('#quote tbody tr[title=' + descr + ']').remove();
        if (qty > 0){
            $('#quote tbody').append('<tr title="' + descr + '" qty="' + qty + '" quotetype="' + quotetype + '"><td>' + quotetype + '</td><td>' + qty +'</td><td><img src="_images/delete.png" class="remove" /></td></tr>');
        }
        /*else{
            $('tr[pid=' + r.attr('pid') + ']').find('.add').val('Add to cart');
        }*/
        updateQuote();
    }

    // Common update cart function
    function updateCart(){
        
        checkEmpty();
        
        var totalPrice = 0;
        var aryCart = [];
        
        $('#shopping tbody tr').each(function(){
            
            if ($(this).children().eq(1).text() != $(this).attr('qty')){
                newQty = $(this).children().eq(1).text();                 
                unitCost = Math.round($(this).attr('cost')/$(this).attr('qty'));
                $(this).attr('cost', unitCost*newQty);
                $(this).attr('qty', newQty);
                $(this).children().eq(2).text(CurrencyFormatted($(this).attr('cost')));
            }
            
            if ($(this).attr('cost') == "0"){
                $(this).remove();
            }
            else{    
                totalPrice = (totalPrice + parseFloat($(this).attr('cost')));             
                aryCart.push($(this).attr('pid') + '#' + $(this).attr('qty') + '#' + $(this).attr('cost') + '#' + encodeURI($(this).attr('title')));
            }
        });
        if (aryCart.length > 0){
            $.cookie('cart',aryCart.join('|'), { expires: 90, path: '/' });
        }
        else{
            $.cookie('cart', null, {path: '/'});
        }
        $('#shopping tfoot tr td').eq(2).attr('basecost',totalPrice).text(CurrencyFormatted(totalPrice));
        changeCcy();
        
        if ($.cookie('cart')){
            alertUser('The cart has been updated. <br />Please add more items, or click the \'Checkout\' button to complete your Order.', true);
        }
    }
    
    // Update quote cookie
    function updateQuote(){
        
        checkEmpty();
        
        var aryQuote = [];
        $('#quote tbody tr').each(function(){
            aryQuote.push($(this).attr('quotetype') + '#' + $(this).attr('qty') + '#0#' + encodeURI($(this).attr('title')));
        });
        if (aryQuote.length > 0){
            $.cookie('quote',aryQuote.join('|'), { expires: 90, path: '/' });
        }
        else{
            $.cookie('quote', null, {path: '/'});
        }
        alertUser('The quote request has been updated.<br />Please add more items, or click the \'Send request\' button to complete your quote request.', true);
    }
    
    // Check if the current cart is empty
    function checkEmpty(){
        currTable = '.cart#' + $('.tab.open').attr('view');
        if ($(currTable + ' tbody tr').length > 0){
            $(currTable + ', #cartButtons').show();
            $('#cartEmpty').hide();
        }
        else{
            $(currTable + ', #cartButtons').hide();
            $('#cartEmpty').show();
        }
    }
    
    $('#checkout').click(function(){
        if ($.cookie('cart') && $('.cart:visible').attr('id') == 'shopping'){
            if ($('#shopping tfoot tr td').eq(2).attr('basecost') < 25){
                alertUser('You don\'t have enough items to meet the minimum order. Please add more items to proceed.');
            }
            else{
                location.href = '/Checkout.aspx';
            }
        }
        else if ($.cookie('quote') && $('.cart:visible').attr('id') == 'quote'){
            location.href = '/Checkout.aspx?type=quote';
        }
        else{
            alertUser('You have no items on your cart yet.',false);
        }
    });

    // Change user preferences
    $('#prefUnits').change(function(){ 
        // Reset tooling table
        if ($('#boxDimensions').length > 0){
            if (!$('#boxDimensions').is(':visible') || confirm('Changing units will reset the tool. Is that OK?')){
                $('#dlMaterial option').eq(0).attr('selected','selected');
                resetView();
            }
            else{
                $('input[name=radUnits]:not([value=' + this.value + '])').attr('checked','checked');
            }
        }
        // Change units dynamically
        changeUnits(); 
    });
    
    $('#prefCcy a').click(function(){ 
        if (!$(this).parent().is('on')){
            $('#prefCcy .on').removeClass('on');
            $(this).parent().addClass('on');
            changeCcy(); 
        }
        return false;
    });

    function changeUnits(){
        if ($('#prefUnits').val() == 'mm'){
            $('td[baselength], option[baselength]').each(function(){
                if ($(this).attr('baseunits') == 'mm'){
                    $(this).text($(this).attr('baselength'));
                }
                else if (IsNumeric($(this).attr('baselength'))){
                    $(this).text(trim($(this).attr('baselength')*25.4, 2) + 'mm');                      
                }
            });
        }
        else{
            $('td[baselength], option[baselength]').each(function(){
                if ($(this).attr('baseunits') == 'mm'){
                    $(this).text(roundNumber($(this).attr('baselength')/25.4, 4));
                }
                else if (IsNumeric($(this).attr('baselength'))){
                    $(this).text($(this).attr('baselength') + '"');  
                }
            });
        }
        $.cookie('prefUnits',$('#prefUnits').val(), { expires: 90, path: '/' });

    }
    
    function changeCcy(){
        
        var newCcy = $('#prefCcy li.on a').length > 0 ? $('#prefCcy li.on a').attr('id') : $.cookie('prefCcy');
        
        if (newCcy == 'usd'){
            xe = xeRate[0];
            ccy = '$'
        }
        else if (newCcy == 'eur'){
            xe = xeRate[1];
            ccy = '€'
        }
        else{
            xe = 1;
            ccy = '£';
        }
        
        $('td[basecost], span[basecost]').each(function(){
            if (IsNumeric($(this).attr('basecost'))){
                $(this).text(ccy + roundNumber($(this).attr('basecost')*xe, 4));  
            }
        });
        $.cookie('prefCcy',newCcy, { expires: 90, path: '/' });
    }

    // Admin functions
    // --------------------------------------------
    
    // Calculate subtotal in Admin area
    $('._productCost, ._pricePandP, ._priceVAT')
        .bind('focus',function(){
            if ($(this).val()){ $(this).attr('oldVal',$(this).val()); }
        })
        .bind('blur',function(){
            if (this.value == ''){
                this.value = $(this).attr('oldVal');
            }
            else if (!IsNumeric(this.value)){
                alertUser('Only numbers are allowed in this field. Please try again.',false);
                this.value = $(this).attr('oldVal');
            }
            else{
                var subTotal = 0;
                $('._productCost').each(function(){
                    subTotal = subTotal + parseFloat($(this).val());
                });
                $('._priceSubtotal').val(subTotal);
                
                if ($('._priceVAT').val() != '0'){
					var vatPrice = (subTotal + parseFloat($('._pricePandP').val() ? $('._pricePandP').val() : 0))*15/100;
					$('._priceVAT').val(vatPrice);
                }
                var grandTotal = subTotal + parseFloat($('._pricePandP').val() ? $('._pricePandP').val() : 0) + parseFloat($('._priceVAT').val());
                $('._priceTotal').val(grandTotal);
            }
        });
    
    // Get bend cost
    $('._calcBend').click(function(){
        alert($(this).parents('tr').children().eq(1).text());
        return false;
    });

});

// Alert the user
function alertUser(msg,success){
    clearTimeout(t);
    img = success ? 'tick' : 'cross';
    $('#userMsg').hide().html(msg).slideDown(100).unbind('click').click(function(){
        if (!$(this).is(':animated')){ $(this).slideUp(200); }
    });

    var t = setTimeout(function(){
        $('#userMsg').trigger('click');
    }, 4000);
}

// Change URL with new country selection
function changeCountry(cty){
    newUrl = 'Checkout.aspx?'
    newUrl += urlParameter('type') ? 'type=' + urlParameter('type') + '&' : '';
    newUrl += 'country=' + cty;
    location.href = newUrl;
}

// Create item description from row
function getDescription(r){
    var descr = r.parents('.box').find('.header').text();
    var header = r.parents('.box').find('thead tr td'); 
    
    r.find('td').each(function(i){
        if ($(this).find('input[type=text]:not(.qty)').length > 0){
            descr += ', ' + header.eq(i).text() + ': ' + $(this).find('input[type=text]').val();
        }
        else if ($(this).find('select').length > 0){
            descr += ', ' + header.eq(i).text() + ': ' + $(this).find('select option:selected').text();
        }
        else if ($(this).find('input').length == 0){
            descr += ', ' + header.eq(i).text() + ': ' + $(this).text();
        }
    });
    descr += ". Units set in " + $('#prefUnits option:selected').text();
    descr = descr.replace(/\*/g,'').replace(/"/g,'in').replace(/£/g,'&pound;')
    return descr;
}


// Check if string is numeric
function IsNumeric(sText){
	var ValidChars = "0123456789.";
	var IsNumber=true;	
	var Char;
 
	for (i = 0; i < sText.length && IsNumber == true; i++){ 
		Char = sText.charAt(i); 
	    if (ValidChars.indexOf(Char) == -1) {
	        IsNumber = false;
	    }
	}
	return IsNumber;
}

// Formats number for currency
function CurrencyFormatted(num){
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '\u00A3' + num + '.' + cents);
}

// Arrange decimals
function trim(wert, digits_aftercomma){
  var ntmp  = eval(wert)
  var before  = Math.floor(ntmp)
  var after = ntmp - before
  var factor  = Math.pow(10, digits_aftercomma)
  return(before + (Math.round(after * factor) / factor))
}

// Clear cart after order has been completed
function completeOrder(){
    $.cookie('cart', null, {path: '/'});
}

// Get URL parameters
// --------------------------------------------- 
function urlParameter(name){
	name = name.toLowerCase().replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  
	var regexS = "[\\?&]"+name+"=([^&#]*)"; 
	var regex = new RegExp(regexS); 
	var results = regex.exec(window.location.href.toLowerCase());  
	if (results == null){
		return ""; 
	}
	else{
		return results[1];
	}
}
