//-------------------------------
// Function: submit_confirm()
// Desc: OnClick Delete Confirm
//-------------------------------

function submit_confirm(txt,url)
{
    var txt;
    var url;
    var confirmSub = confirm(txt);
    if (confirmSub)
    {
        window.location = url;
    }
    else
    {
        return false;
    }
}

//-------------------------------
// Function: popWindow()
// Desc: Generic Pop Up Window
//-------------------------------

function popWindow(URL,LEFT,TOP,WIDTH,HEIGHT,SCROLLBARS,RESIZE)
{
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=" + SCROLLBARS + ",location=0,statusbar=0,menubar=0,left=" + LEFT + ",top=" + TOP + ",screenX=0,screenY=0,resizable=" + RESIZE + ",width=" + WIDTH + ",height=" + HEIGHT + "');");
}

//-------------------------------
// Function: JS_centerer()
// Desc: Centers all elements with class JS_center
//-------------------------------

function JS_centerer() {
    var margin = 0;
    $(".js_center").each(function(){
        margin = ( $(window).width() - $(this).width() ) / 2;
        $(this).css('margin-left',margin);
    });
}

//-------------------------------
// Function: show_category(category_id)
// Desc: loads contents of the category into the product info table
//-------------------------------

function show_category(cid) {
    $('.ce'+cid).css('background','#DDDDDD');
    flush_category_bgs();
    $('.ce'+cid).css('background','#DDDDDD');
    $('#dynamic_table').html('<div id="loading"><img src="images/ajax-loader.gif"></div>');
    $.ajax({
        type: "GET",
        url: 'index.php?cmd=category&cat_id='+cid,
        success: function(msg) {
            msg = removeNL(msg);

            if (msg!='Your search returned 0 results') {
                var content = '<table width="100%" id="product_table" border="1"><tr><th>Serial</th><th>Description</th><th>Price</th><th>(Click for details)</th></tr>'+msg;
            }
            else
            {
                var content = msg;

            }
            $('#dynamic_table').html(content);
        }});
}


//-------------------------------
// Function: inject_category(category_id)
// Desc: loads contents of the category into the product info table - can be used several times per page
//-------------------------------

function inject_category(cid) {
    $('.ce'+cid).css('background','#DDDDDD');
    flush_category_bgs();
    $('.ce'+cid).css('background','#DDDDDD');
    $('#dynamic_table').hide();
    $('#content_container').html($('#content_container').html()+'<div id="dynamic_table'+cid+'">');
    $('#dynamic_table'+cid).html('<div id="loading"><img src="images/ajax-loader.gif"></div>');
    $.ajax({
        type: "GET",
        url: 'index.php?cmd=category&cat_id='+cid,
        success: function(msg) {
            msg = removeNL(msg);

            if (msg!='Your search returned 0 results') {
                if ($('#current_currency').val()=='CAD' )
                {
                    var currency_switch = '<br><span id="cad_option" style="font-weight: bold;"><a href="javascript:void(0);" onclick="javascript:currencyChange(\'CAD\')">CAD <img src="images/canada_colour.gif" height="16px"></a></span>&nbsp;|&nbsp;<span id="usd_option" style="font-weight: normal;"><a href="javascript:void(0);" onclick="javascript:currencyChange(\'USD\')"><img src="images/usa_grey.gif" height="16px">USD</a></span>';
                }
                else
                {
                    var currency_switch = '<br><span id="cad_option" style="font-weight: normal;"><a href="javascript:void(0);" onclick="javascript:currencyChange(\'CAD\')">CAD <img src="images/canada_grey.gif" height="16px"></a></span>&nbsp;|&nbsp;<span id="usd_option" style="font-weight: bold;"><a href="javascript:void(0);" onclick="javascript:currencyChange(\'USD\')"><img src="images/usa_colour.gif" height="16px">USD</a></span>';
                }
                var content = '<table width="100%" id="product_table" border="1"><tr><th>Serial</th><th>Description</th><th>Price' + currency_switch + '</th><th>(Click for details)</th></tr>'+msg;
            }
            else
            {
                var content = msg;

            }
            $('#dynamic_table'+cid).html(content+'</div>');
        }});
}

//-------------------------------
// Function: inject_custom_search(criteria)
// Desc: loads contents of the specified search category into the product info table - can be used several times per page
//-------------------------------

function inject_custom_search(criteria) {
    var cid = parseInt(Math.random()*10000)+60000;
    $('#dynamic_table').hide();
    $('#content_container').html($('#content_container').html()+'<div id="dynamic_table'+cid+'">');
    $('#dynamic_table'+cid).html('<div id="loading"><img src="images/ajax-loader.gif"></div>');
    $.ajax({
        type: "GET",
        url: 'index.php?cmd=search&keywords='+criteria,
        success: function(msg) {
            msg = removeNL(msg);

            if (msg!='Your search returned 0 results') {
                if ($('#current_currency').val()=='CAD' )
                {
                    var currency_switch = '<br><span id="cad_option" style="font-weight: bold;"><a href="javascript:void(0);" onclick="javascript:currencyChange(\'CAD\')">CAD <img src="images/canada_colour.gif" height="16px" width="24px"></a></span>&nbsp;|&nbsp;<span id="usd_option" style="font-weight: normal;"><a href="javascript:void(0);" onclick="javascript:currencyChange(\'USD\')"><img src="images/usa_grey.gif" height="16px"> USD</a></span>';
                }
                else
                {
                    var currency_switch = '<br><span id="cad_option" style="font-weight: normal;"><a href="javascript:void(0);" onclick="javascript:currencyChange(\'CAD\')">CAD <img src="images/canada_grey.gif" height="16px" width="24px"></a></span>&nbsp;|&nbsp;<span id="usd_option" style="font-weight: bold;"><a href="javascript:void(0);" onclick="javascript:currencyChange(\'USD\')"><img src="images/usa_colour.gif" height="16px"> USD</a></span>';
                }

                var content = '<table width="100%" id="product_table" border="1"><tr><th>Serial</th><th>Description</th><th>Price' + currency_switch + '</th><th>(Click for details)</th></tr>'+msg;
            }
            else
            {
                var content = msg;

            }
            $('#dynamic_table'+cid).html(content+'</div>');
        }});
}

//-------------------------------
// Function: show_category_independent(category_id)
// Desc: loads contents of the category into the product info table - can be used several times per page
//-------------------------------

function inject_static_content(content_id) {

    $('#content_container').html($('#content_container').html() + $('#'+content_id).html());

}

//-------------------------------
// Function: flush_category_bgs()
// Desc: resets category backgrounds to #EEEEEE to allow selected category highlighting
//-------------------------------

function flush_category_bgs() {
    $("#category_entry").each(function(){
        $(this).css('background','#EEEEEE');
    });
    for (i=0;i<20;i++) {
        $('.ce'+i).css('background','#EEEEEE');
    }
}

//-------------------------------
// Function: highlight_top(id)
// Desc: highlights the selected category in the top row of the category selection menu
//-------------------------------

function highlight_top(id) {
    $('#'+id).attr('class','selected_category');
}

//-------------------------------
// Function: highlight_sub(id)
// Desc: highlights the selected category in the sub row of the category selection menu
//-------------------------------

function highlight_sub(id) {
    $('#'+id).attr('class','sub_selected');
}

//-------------------------------
// Function: do_search()
// Desc: performs keyword search and outputs result into info table
//-------------------------------

function do_search() {
    $('#content_container').html('<div id="dynamic_table"></div>');
    $('#dynamic_table').fadeIn('normal');
    $('#dynamic_table').html('<div id="loading"><img src="images/ajax-loader.gif"></div>');
    flush_category_bgs();
    keywords = $('#search_input').val();
	$.ajax({
        type: "GET",
        url: 'index.php?cmd=search&keywords='+keywords,
        success: function(msg) {
            msg = removeNL(msg);
            if (msg!='Your search returned 0 results' && keywords != "") {
                var content = '<table width="100%" id="product_table" border="1"><tr><th>Serial</th><th>Description</th><th>Price</th><th>(Click for details)</th></tr>'+msg;
                $('#dynamic_table').html(content);
            }
            else
            {
                var content = msg;
                $('#dynamic_table').html(content);
            }


        }});
}

//-------------------------------
// Function: add_to_cart(id)
// Desc: adds the current item to the cart
//-------------------------------

function add_to_cart(id) {
    quantity = $('#quantity'+id).val();
    $('#cart_addition_feedback'+id).fadeIn('slow');
    $('#cart_addition_feedback'+id).html('<span id="quantity_highlight">'+quantity+'</span>' + (quantity==1?' item':' items') + ' added');
    $('#cart_addition_feedback'+id).fadeOut('slower');
    $('#cart_addition_feedback'+id).show();

    $.ajax({
        type: "GET",
        url: 'index.php?cmd=cart&action=add&quantity='+quantity+'&prod_id='+id,
        success: function(msg) {
            msg = removeNL(msg);
            var info = msg.split('##');
            if (info[0] == 'added') {
                $('#cart_count').html(info[1]);
            }
        }});
        updateNumbers();
}

//-------------------------------
// Function: updateQty(id)
// Desc: update the quantity of goods in the cart upon user input
//-------------------------------

function updateQty(id) {
    quantity = $('#qty'+id).val();
    $.ajax({
        type: "GET",
        url: 'index.php?cmd=cart&action=update&quantity='+quantity+'&id='+id,
        success: function(msg) {
            msg = removeNL(msg);
            var info = msg.split('##');
            if (info[0] == 'updated') {
                var price = info[1].split('**');
                $('#price'+id).html(parseFloat(price[1]).toFixed(2));
            }
        }});


        redo_shipping();
		// Should we take this out? Experiment soon
        show_shipping_form();
        $('#shipping_options').html('The quote needs to be computed again');
        $('#shipping_module').fadeIn('slower');
        updateNumbers();
}

//-------------------------------
// Function: removeItem(id)
// Desc: removes item from the cart
//-------------------------------

function removeItem(id) {
    $.ajax({
        type: "GET",
        url: 'index.php?cmd=cart&action=remove&id='+id,
        success: function(msg) {
            msg = removeNL(msg);
            if (msg == 'removed') {
                $('#row'+id).fadeOut('slow');
            }
        }});
        redo_shipping();
        show_shipping_form();
        $('#shipping_module').fadeIn('slow');
        updateNumbers();
}

//-------------------------------
// Function: updateNumbers()
// Desc: updates counts and prices in the cart when any change is made
//-------------------------------

function updateNumbers() {
    $.ajax({
        type: "GET",
        url: 'index.php?cmd=cart&action=refreshUI',
        success: function(msg) {
            msg = removeNL(msg);
            var items = msg.split('##');
            if (items[0] == 'refresh') {
                var info = items[1].split('**');
                if (info[0]==0) {
                    $('#cart_contents').html('Your Shopping Cart is Empty');
                }
                $('#cart_count').html(info[0]);
				var moredata = info[1].split('++');
                $('#cart_total').html(moredata[0]);
                $('#cart_total_shipping').html('Order total: $<span id="cart_total">'+moredata[0]+'</span>');
				$('#orderdata').val(moredata[1]);
                // if (info[0]==0) { window.location="index.php"; }
            }
        }});
}

//-------------------------------
// Function: getCPQuote()
// Desc: request of Canada Post quote
//-------------------------------

function getCPQuote(isDebug) {
    country = $('#countrylist').val();
	zip = $('#zipcode').val();
//	var s = document.getElementById('countrylist');
//	alert(s);
//	country = s.options[s.selectedIndex].text;
//    var z = document.getElementById('zipcode');
//	alert(z);
//	zip = z.value;

    $('#shipping_options').html('<div id="loading"><img src="images/ajax-loader.gif"></div>');
if (isDebug)
{    $.ajax({
        type: "POST",
        url: 'index2.php?cmd=cart&action=getquote&country='+country+'&zip='+zip,
        success: function(msg) {
            $('#shipping_options').html(msg);
        }});
} else {
	$.ajax({
        type: "POST",
        url: 'index.php?cmd=cart&action=getquote&country='+country+'&zip='+zip,
        success: function(msg) {
            $('#shipping_options').html(msg);
        }});
}

}

//-------------------------------
// Function: show_shipping_form()
// Desc: draws shipping form
//-------------------------------

function show_shipping_form() {
    var zip = $('#zipcode').val();        

    $.ajax({
        type: "GET",
        url: 'index.php?cmd=cart&action=showform&zip='+zip,
        success: function(msg) {
            msg = removeNL(msg);
            $('#shipping_form_holder').html(msg);
        }});
}

//-------------------------------
// Function: shipmentChosen(name)
// Desc: update system shipping price when user clicks on shipping options
//-------------------------------

function shipmentChosen(name) {
//    $('#checkout_button').disabled = false;
    rate = $("input[@name='shipment_methods']:checked").val();
    $.ajax({
        type: "GET",
        url: 'index.php?cmd=cart&action=refreshUI',
        success: function(msg) {
            msg = removeNL(msg);
            msg = removeCommas(msg);
//			alert(msg);
            var items = msg.split('##');
            if (items[0] == 'refresh') {
                var info = items[1].split('**');
                var total = parseFloat(info[1])+parseFloat(rate);
                $('#cart_total').html(total.toFixed(2) + " " + $('#current_currency').val());
				$('#emailcheckoutshippingcost').val(rate); // This should set the hidden input on the cart page ZAT
//				alert(rate + " with " + name);
				$('#emailcheckoutshippingname').val(name);
				$('#cart_total_input').val(rate);
                shippingChoiceMade(name);
            }
        }});
}

//-------------------------------
// Function: shippingChoiceMade(name)
// Desc: updates the total price in the cart when user clicks on a shipping option
// name is the shipping method
//-------------------------------

function shippingChoiceMade(name) {
//    method = 'Shipping';//$("input[@name='shipment_methods']:checked").val();
//	method = $('#emailcheckoutshippingname').val();
	method = name;
    country = $('#country').val();
    zip = $('#zipcode').val();
    stotal = $('#cart_total_input').val();
    $.ajax({
        type: "GET",
        url: 'index.php?cmd=cart&action=shippingchoicemade&method='+method+'&country='+country+'&zip='+zip+'&stotal='+stotal,
        success: function(msg) {
			document.getElementById("checkout_button").disabled = false;
            msg = removeNL(msg);
        }});
}

//-------------------------------
// Function: redo_shipping()
// Desc: reset all prices
//-------------------------------

function redo_shipping() {

    $.ajax({
        type: "GET",
        url: 'index.php?cmd=cart&action=redoshipping',
        success: function(msg) {
            msg = removeNL(msg);

        }});
}

//-------------------------------
// Function: null_cart_count()
// Desc: set cart count to 0
//-------------------------------

function null_cart_count() {
    $('#cart_count').html('0');
    setTimeout("window.location=\'index.php\';",2500);
}

//-------------------------------
// Function: removeNL(s)
// Desc: removes new line chars from the input
//-------------------------------
function removeNL(s) {
    r = "";
    for (i=0; i < s.length; i++) {
        if (s.charAt(i) != '\n' &&
        s.charAt(i) != '\r' &&
        s.charAt(i) != '\t') {
            r += s.charAt(i);
        }
    }
    return r;
}

//-------------------------------
// Function: removeCommas(s)
// Desc: remove commas from the input
//-------------------------------
function removeCommas(s) {
    r = "";
    for (i=0; i < s.length; i++) {
        if (s.charAt(i) != ',') {
            r += s.charAt(i);
        }
    }
    return r;
}

//-------------------------------
// Function: redirectToCart()
// Desc: not used in the code. Checkes whether there is anything in the cart and produces an error msg when the cart is empty
//-------------------------------
function redirectToCart()
{

    $.ajax({
        type: "GET",
        url: 'index.php?cmd=cart&action=emptycheck',
        success: function(msg) {
            msg = removeNL(msg);
            if (msg=='good') { window.location="index.php?cmd=cart&amp;action=view"; }
            if (msg=='bad')  { alert('Ooops... Your Cart is empty'); }
        }});

}

//-------------------------------
// Function: paginationSwitchToPage(pg, place, id)
// Desc: shows contents of a particular page based on pagination
//-------------------------------
function paginationSwitchToPage(pg, place, id)
{
    if (place=='category') {
        $.ajax({
            type: "GET",
            url: 'index.php?cmd=category&cat_id='+id+'&start='+pg,
            success: function(msg) {
                msg = removeNL(msg);

                if (msg!='Your search returned 0 results') {
                    var content = '<table width="100%" id="product_table" border="1"><tr><th>Serial</th><th>Description</th><th>Price</th><th>(Click for details)</th></tr>'+msg;
                }
                else
                {
                    var content = msg;
                }
                $('#dynamic_table').html(content);
                flush_category_bgs();
                $('.ce'+id).css('background','#DDDDDD');
            }});
    }

    if (place=='search') {
        flush_category_bgs();
        keywords = $('#search_input').val();
        $.ajax({
            type: "GET",
            url: 'index.php?cmd=search&keywords='+keywords+'&start='+pg,
            success: function(msg) {
                msg = removeNL(msg);
                if (msg!='Your search returned 0 results') {
                    var content = '<table width="100%" id="product_table" border="1"><tr><th>Serial</th><th>Description</th><th>Price</th><th>(Click for details)</th></tr>'+msg;
                }
                else
                {
                    var content = msg;
                }

                $('#dynamic_table').html(content);
            }});
    }
}

//-------------------------------
// Function: clear_cart()
// Desc: clear the cart with confirmation
//-------------------------------

function clear_cart() {

// Took out red box, couldn't get formatting proper -ZAT
/*    if( $("input[@id='clear_confirm']").attr("checked")==false ) {
        $("#red_box").fadeIn('slow');
		$("#red_box").fadeOut('slower');
    } else { */
        $.ajax({
            type: "GET",
            url: 'index.php?cmd=cart&action=clear',
            success: function(msg) {
                updateNumbers();
            }});
/*    } */

}


//-------------------------------
// Function: flush_cart()
// Desc: clear the cart
//-------------------------------

function flush_cart() {
    $.ajax({
        type: "GET",
        url: 'index.php?cmd=cart&action=clear',
        success: function(msg) {
            updateNumbers();
        }});
}

//-------------------------------
// Function: currencyChange(cur)
// Desc: change the currency and update all corresponding numbers on the screen
//-------------------------------

function currencyChange(cur)
{
    var current_cur = $('#current_currency').val();
    if (cur!=current_cur) {
        var loc = window.location;
        $.ajax({
            type: "GET",
            url: 'index.php?cmd=currencychange&currency='+cur,
            success: function(msg) {
                msg = removeNL(msg);
                if (msg=='CAD') {

                    // $('#cad_option').each(function(){ $(this).css('font-weight','bold'); });
                    // $('#usd_option').each(function(){ $(this).css('font-weight','normal'); });
					var allels = document.getElementsByTagName('SPAN');
                    for(var i=0, elm; elm = allels[i++];)
                    {
                        if (elm.tagName == 'SPAN' && elm.id == 'cad_option') {
                            elm.style.fontWeight = 'bold';
							elm.innerHTML = '<a href="javascript:void(0);" onclick="javascript:currencyChange(\'CAD\')">CAD <img src="images/canada_colour.gif" height="16px"></a>';
                        }
                        if (elm.tagName == 'SPAN' && elm.id == 'usd_option') {
                            elm.style.fontWeight = 'normal';
							elm.innerHTML = '<a href="javascript:void(0);" onclick="javascript:currencyChange(\'USD\')"><img src="images/usa_grey.gif" height="16px">USD</a>';
                        }
                    }
                }

                if (msg=='USD') {
                    // $('#cad_option').each(function(){ $(this).css('font-weight','normal'); });
                    // $('#usd_option').each(function(){ $(this).css('font-weight','bold'); });
					var allels = document.getElementsByTagName('SPAN');
                    for(var i=0, elm; elm = allels[i++];)
                    {
                        if (elm.tagName == 'SPAN' && elm.id == 'cad_option') {
                            elm.style.fontWeight = 'normal';
							elm.innerHTML = '<a href="javascript:void(0);" onclick="javascript:currencyChange(\'CAD\')">CAD <img src="images/canada_grey.gif" height="16px"></a>';
                        }
                        if (elm.tagName == 'SPAN' && elm.id == 'usd_option') {
                            elm.style.fontWeight = 'bold';
							elm.innerHTML = '<a href="javascript:void(0);" onclick="javascript:currencyChange(\'USD\')"><img src="images/usa_colour.gif" height="16px">USD</a>';
                        }
                    }
                }

                $('#current_currency').val(cur);
                //if (msg=='USD') {
                //    $('#cad_option').css('font-weight','normal');
                //    $('#usd_option').css('font-weight','bold');
                //}

                if ($('#zipcode').val()!= undefined) {
                    cart_price_updater(msg);
                    $(".qtyvalue").each(function(){
                        var info = $(this).attr('id').split('qty');
                        updateQty(info[1]);
                    });
                }

                currencyChangeGeneral(msg);

            }});
    }

}

//-------------------------------
// Function: currencyChangeGeneral(cur)
// Desc: change the currency and update all corresponding numbers on the screen
//-------------------------------
function currencyChangeGeneral(msg)
{
    $(".price_holder").each(function(){
        var info = $(this).attr('id').split('price_holder');
        var id = info[1];
        var price_displayed = parseFloat($('#price_display'+id).html());
        var price_stored = parseFloat($('#price_holder'+id).val());

        $('#price_display'+id).html((price_stored.toFixed(2) + " " + msg));
        $('#price_holder'+id).val(price_displayed.toFixed(2));
    });
}
//-------------------------------
// Function: cart_price_updater(cur)
// Desc: updates the interface with new numbers - based on the selected currency
//-------------------------------

function cart_price_updater(cur) {

    if (cur=='USD') {
        $('#currency').html("USD");

        var value = $('#cart_total_input').val()/parseFloat($('#exchange_rate').val());
        $('#cart_total_input').val(value.toFixed(2));

        $(".shipping_rate").each(function(){
            if (parseFloat($(this).html()) == 15) { var val = 15;	} else { var val = parseFloat($(this).html())/parseFloat($('#exchange_rate').val()); }
            $(this).html(val.toFixed(2));

        });
        $(".shipment_methods").each(function(){
            if (parseFloat($(this).val()) == 15) { var val = 15;	} else { var val = parseFloat($(this).val())/parseFloat($('#exchange_rate').val()); }
            $(this).val(val.toFixed(2));
        });
    }

    if (cur=='CAD') {
        $('#currency').html("CAD");
        var value = $('#cart_total_input').val()*parseFloat($('#exchange_rate').val());
        $('#cart_total_input').val(value.toFixed(2));

        $(".shipping_rate").each(function(){
            if (parseFloat($(this).html()) == 15) { var val = 15;	} else { var val = parseFloat($(this).html())*parseFloat($('#exchange_rate').val()); }
            $(this).html(val.toFixed(2));
        });
        $(".shipment_methods").each(function(){
            if (parseFloat($(this).val()) == 15) { var val = 15; } else { var val = parseFloat($(this).val())*parseFloat($('#exchange_rate').val()); }
            $(this).val(val.toFixed(2));
        });
    }


    $("input[@id='shipment_methods']:checked").attr("checked",false);

}

//-------------------------------
// Function: catchEnter(evt)
// Desc: checks charcode of the pressed button and if enter, runs search funciton
//-------------------------------

function catchEnter(evt) {
    var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
    if (charCode == 13 || charCode == 3) {
        do_search();
        return false;
    }
    return true;
}

function catchShipEnter(evt) {
    var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
    if (charCode == 13 || charCode == 3) {
        getCPQuote();
        return false;
    }
    return true;

}

//-------------------------------
// Function: redirectTo(http)
// Desc: redirects users browser to a different page
//-------------------------------

function redirectTo(http) {
    window.location(http);
}

