// common variables
var currentProductID = 0;

function search() {
    window.location.href = "search.php?stext=" + clean($('#searchbar').val());
}
function printpdf() {
    window.open("rangePDF.php?rid=" + selectedRange);
}

// objects
function product(product_id, quantity) {
    this.product_id = product_id;
    this.quantity = quantity;
}
var products = new Array(); // products array for the shopping cart

function onAjaxError(XMLHttpRequest, textStatus, errorThrown){
	alert (textStatus);
}

// clean-up text
function clean (str){
    return str = str.replace(/'/g, "\\'");
}

// jump to product details page
function gotoProduct(pid){
	window.location.href = "productdetails.php?pid="+pid;
}

// jump to search page
function gotoSearch(){
    var stext = $('#searchbar').val();
    window.location.href = "search.php?stext="+encodeURIComponent(stext);
}

// jump to range
function backToRange(rid) {
    restoreSnapshot();
}
function snapshot() {
    snapshotCache = $('#contents').html();
}
function restoreSnapshot() {
    // restore snapshot html if possible
    if (typeof snapshotCache == "undefined")
        window.location.href = "category.php";
    else {
        $('#contents').html(snapshotCache);
        // make slider work
        setupRangeScrolling();
    }
}

// store products added to the shopping cart in a cookie
function addToCart(pid) {
    bounce('cart');
    animateCartButton();
    loadCartCookie();
    var exists = false;
    if (products !== null && products.length > 0) 
    {
        for (var p = 0; p < products.length; p++) 
        {
            if (+products[p].product_id == +pid) 
            {
                // product exists in cart, increment quantity
                products[p].quantity = +products[p].quantity + 1;
                exists = true;
                break;
            }
        }
        if (!exists) {
            // product is not in cart, add it
            var P = new product(pid, 1);
            products.push(P);
        }
    }
    else {
        // create the first product in the cart
        var P = new product(pid, 1);
        products.push(P);
    }
    saveCartCookie();
}
function animateCartButton() {
    $('#cartbtn').attr("src", "images/cart_anibtn.gif");
    window.setTimeout("$('#cartbtn').attr('src', 'images/addtocart.png')", 1200);
}
// completely removes a single product from the shopping cart
function removeFromCart(pid) {
    //reload the cookie - ignoring the item to delete - re-save cookie
    var cart = readCookie("belcart");
    products = new Array();
    if (cart != null) {
        var itms = cart.split('-');
        for (var i = 0; i < itms.length; i++) {
            var itm = itms[i].split(',');
            if (+itm[0] != +pid) {
                P = new product(itm[0], itm[1]);
                products.push(P);
            }
        }
    }
    saveCartCookie();
    // hide old row
    slideUpRow("p" + pid);
    refreshTotalsRow();
}
// calc the ex.VAT price of the items in the shopping cart cookie (in pennies)
function getPenniesInCart() {
    var totalPennies = 0;
    // go through the cookie, getting active product ids and collecting prices from the table
    var cart = readCookie("belcart");
    if (cart != null) {
        var itms = cart.split('-');
        for (var i = 0; i < itms.length; i++) {
            var itm = itms[i].split(',');
            var thisProductID = itm[0];

            // find the relevant price (in pennies) from the table
            var thisPrice    = +$('#price' + thisProductID).val();
            var thisQuantity = +$('#q' + thisProductID).val();

            totalPennies += (thisPrice * thisQuantity);
        }
    }

    return totalPennies;
}
// adds or updates a totals row on the bottom of the products table
function refreshTotalsRow() {

    if ($('#totalsdisplay').length == 0) {
        $('#productsTable > tbody').append("<tr id=\"totalsdisplay\"><td class=\"totalsdisplay\" colspan=\"6\" align=\"right\">Total: <span id=\"pricedisplay\">"
                + convertPenniesToPoundsDisplay(getPenniesInCart()) + "</span></td></tr>");
    }
    else
        $('#pricedisplay').html(convertPenniesToPoundsDisplay(getPenniesInCart()));

}
// changes quantities in cart and updates price total accordingly
function setCartQuantities() {
    loadCartCookie();
    if (products !== null && products.length > 0) 
    {
        for (var p = 0; p < products.length; p++) 
        {
            var thisProductID = +products[p].product_id; 
            var thisQuantity = +$('#q' + thisProductID).val();
            products[p].quantity = thisQuantity;
        }
    }
    saveCartCookie();
    refreshTotalsRow();
}
function delivery() {
    window.location.href = "delivery.php";
}
function addTableRow(jQtable) {
    jQtable.each(function () {
        var $table = $(this);
        // Number of td's in the last table row
        var n = $('tr:last td', this).length;
        var tds = '<tr>';
        for (var i = 0; i < n; i++) {
            tds += '<td>&nbsp;</td>';
        }
        tds += '</tr>';
        if ($('tbody', this).length > 0) {
            $('tbody', this).append(tds);
        } else {
            $(this).append(tds);
        }
    });
}
function convertToPennies(strPrice) {
    return +strPrice.replace(/£ /g, '') * 100;
}
function convertPenniesToPoundsDisplay(pennies) {
    var pnds = pennies / 100;
    return "£" + pnds.toFixed(2);
}
function slideUpRow(rowid) {
  $('#'+rowid)
 .find('td')
 .wrapInner('<div style="display: block;" />')
 .parent()
 .find('td > div')
 .slideUp(400, function () {
     $(this).parent().parent().remove();
 });

}
function loadCartCookie() {
    var cart = readCookie("belcart");
    products = new Array();
    if (cart != null) {
        var itms = cart.split('-');
        for (var i = 0; i < itms.length; i++) {
            var itm = itms[i].split(',');
            P = new product(itm[0], itm[1]);
            products.push(P);
        }
    }
}
function saveCartCookie() {
    var str = "";
    for (var p = 0; p < products.length; p++) {
        str += products[p].product_id + "," + products[p].quantity + "-";
    }
    str = str.replace(/-$/, "");
    createCookie("belcart", str, 90);
}
function checkout() {
    // go to checkout page
    window.location.href = "checkout.php";
}

// refresh the product display
function refreshProduct(pid) {
    window.location.href = "productdetails.php?pid=" + pid;

    currentProductID = pid;
//	$.ajax({
//	    type : 'POST',
//	    url : 'getData.php',
//	    dataType : 'json',
//	    data: {
//	        action : 'refreshProductDisplay',
//		    pid : pid
//	    },
//	    success : function(data){	    
//	        // update the product's display table
//	        $('#contents').html(data);
//	    },
//	    error : function(XMLHttpRequest, textStatus, errorThrown) {
//	    }
//    });
}


// COOKIE FUNCTIONS
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

// END OF COOKIE FUNCTIONS

// JQUERY
//jQuery.fn.flash = function (color, duration) {

//    var current = this.css('color');

//    this.animate({ color: 'rgb(' + color + ')' }, duration / 2);
//    this.animate({ color: current }, duration / 2);

//}
function bounce(objID)
{
  $('#'+objID).fadeIn(100).animate({top:"-=10px"},100).animate({top:"+=10px"},100).animate({top:"-=10px"},100)
.animate({top:"+=10px"},100).animate({top:"-=10px"},100).animate({top:"+=10px"},100);
}

// COLOUR SELECTOR
// show in centre of screen
function showColourSelector() {
    var CS = $('#coloursSelector');
    centralise(CS);
    CS.fadeIn();
}
function hideColourSelector() {
    var CS = $('#coloursSelector');
    CS.fadeOut();
}
// centralise jquery object
function centralise(obj) {
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var ht = obj.height();
    var wd = obj.width();
    //centering  
    obj.css({
        "position": "absolute",
        "top": windowHeight / 2 - ht / 2 + $(document).scrollTop(),
        "left": windowWidth / 2 - wd / 2 + $(document).scrollLeft(),
        "z-index": 1000
    });
}
function selectColour(cid) {
    // save selected colour to cookie
    // add click event to colour selectors 
    createCookie("BelmontColour", "colour" + cid, 90);
    // update the displayed image
    $('#examplecolour').removeAttr("class");
    $('#examplecolour').addClass("scolor");
    $('#examplecolour').addClass("colour" + cid);
    // update the example on the colour selector
    $('#selectedexamplecolour').removeAttr("class");
    $('#selectedexamplecolour').addClass("scolor");
    $('#selectedexamplecolour').addClass("colour" + cid);

    hideColourSelector();
}
