var searchScript = "/scripts/searchHandler.php";
var shipScript = "/scripts/shippingHandler.php";

var update = false;

var space = new RegExp("\\s+", "g");
var underscore = new RegExp("\_+", "g");
var illegals = new RegExp("[^a-zA-Z0-9\_]", "g");

function accountInfo(type)
{
	if(type)
	{
		return $.site.account[type];
	}
}

function addSpaces(string)
{
	if(string)
	{
		var value = (string).replace(underscore," ");
		return value;
	}
	return null;
}

function arraySplice(array,id)
{
	var newArray = new Array();
	for(var element in array)
	{
		if(element != id)newArray[element] = array[element];
	}
	return newArray;
}

function date_normal(string)
{
	if(string)
	{
		var array = string.split(" ");
		var dateArray = array[0].split("-");
		return dateArray[2]+"/"+dateArray[1]+"/"+dateArray[0]+" "+array[1];
	}
}

function deletePopup(url)
{
	if(url)
	{
		$("#delete_url").attr("href",url);
		$("#delete").show();
	}
}

function get_html_translation_table(table, quote_style) 
{    
    var entities = {}, histogram = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    useTable      = (table ? table.toUpperCase() : 'HTML_SPECIALCHARS');
    useQuoteStyle = (quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT');
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
    
    // Map numbers to strings for compatibilty with PHP constants
    if (!isNaN(useTable)) {
        useTable = constMappingTable[useTable];
    }
    if (!isNaN(useQuoteStyle)) {
        useQuoteStyle = constMappingQuoteStyle[useQuoteStyle];
    }
    
    if (useTable == 'HTML_SPECIALCHARS') {
        // ascii decimals for better compatibility
        entities['60'] = '&lt;';
        entities['62'] = '&gt;';
        entities['38'] = '&amp;';
    } else if (useTable == 'HTML_ENTITIES') {
        // ascii decimals for better compatibility
      entities['38'] = '&amp;';
      entities['60'] = '&lt;';
      entities['62'] = '&gt;';
      entities['160'] = '&nbsp;';
      entities['161'] = '&iexcl;';
      entities['162'] = '&cent;';
      entities['163'] = '&pound;';
      entities['164'] = '&curren;';
      entities['165'] = '&yen;';
      entities['166'] = '&brvbar;';
      entities['167'] = '&sect;';
      entities['168'] = '&uml;';
      entities['169'] = '&copy;';
      entities['170'] = '&ordf;';
      entities['171'] = '&laquo;';
      entities['172'] = '&not;';
      entities['173'] = '&shy;';
      entities['174'] = '&reg;';
      entities['175'] = '&macr;';
      entities['176'] = '&deg;';
      entities['177'] = '&plusmn;';
      entities['178'] = '&sup2;';
      entities['179'] = '&sup3;';
      entities['180'] = '&acute;';
      entities['181'] = '&micro;';
      entities['182'] = '&para;';
      entities['183'] = '&middot;';
      entities['184'] = '&cedil;';
      entities['185'] = '&sup1;';
      entities['186'] = '&ordm;';
      entities['187'] = '&raquo;';
      entities['188'] = '&frac14;';
      entities['189'] = '&frac12;';
      entities['190'] = '&frac34;';
      entities['191'] = '&iquest;';
      entities['192'] = '&Agrave;';
      entities['193'] = '&Aacute;';
      entities['194'] = '&Acirc;';
      entities['195'] = '&Atilde;';
      entities['196'] = '&Auml;';
      entities['197'] = '&Aring;';
      entities['198'] = '&AElig;';
      entities['199'] = '&Ccedil;';
      entities['200'] = '&Egrave;';
      entities['201'] = '&Eacute;';
      entities['202'] = '&Ecirc;';
      entities['203'] = '&Euml;';
      entities['204'] = '&Igrave;';
      entities['205'] = '&Iacute;';
      entities['206'] = '&Icirc;';
      entities['207'] = '&Iuml;';
      entities['208'] = '&ETH;';
      entities['209'] = '&Ntilde;';
      entities['210'] = '&Ograve;';
      entities['211'] = '&Oacute;';
      entities['212'] = '&Ocirc;';
      entities['213'] = '&Otilde;';
      entities['214'] = '&Ouml;';
      entities['215'] = '&times;';
      entities['216'] = '&Oslash;';
      entities['217'] = '&Ugrave;';
      entities['218'] = '&Uacute;';
      entities['219'] = '&Ucirc;';
      entities['220'] = '&Uuml;';
      entities['221'] = '&Yacute;';
      entities['222'] = '&THORN;';
      entities['223'] = '&szlig;';
      entities['224'] = '&agrave;';
      entities['225'] = '&aacute;';
      entities['226'] = '&acirc;';
      entities['227'] = '&atilde;';
      entities['228'] = '&auml;';
      entities['229'] = '&aring;';
      entities['230'] = '&aelig;';
      entities['231'] = '&ccedil;';
      entities['232'] = '&egrave;';
      entities['233'] = '&eacute;';
      entities['234'] = '&ecirc;';
      entities['235'] = '&euml;';
      entities['236'] = '&igrave;';
      entities['237'] = '&iacute;';
      entities['238'] = '&icirc;';
      entities['239'] = '&iuml;';
      entities['240'] = '&eth;';
      entities['241'] = '&ntilde;';
      entities['242'] = '&ograve;';
      entities['243'] = '&oacute;';
      entities['244'] = '&ocirc;';
      entities['245'] = '&otilde;';
      entities['246'] = '&ouml;';
      entities['247'] = '&divide;';
      entities['248'] = '&oslash;';
      entities['249'] = '&ugrave;';
      entities['250'] = '&uacute;';
      entities['251'] = '&ucirc;';
      entities['252'] = '&uuml;';
      entities['253'] = '&yacute;';
      entities['254'] = '&thorn;';
      entities['255'] = '&yuml;';
    } else {
        throw Error("Table: "+useTable+' not supported');
        return false;
    }
    
    if (useQuoteStyle != 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    
    if (useQuoteStyle == 'ENT_QUOTES') {
        entities['39'] = '&#039;';
    }
    
    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal)
        histogram[symbol] = entities[decimal];
    }
    
    return histogram;
}

function htmlentities (string, quote_style) 
{
    var histogram = {}, symbol = '', tmp_str = '', i = 0;
    tmp_str = string.toString();
    
    if (false === (histogram = get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
    
    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
    
    return tmp_str;
}

function inArray(search_for,search_array,compare_array)
{
	var found = -1;
	for(element in search_array)
	{
		if(search_array[element][search_for] == compare_array[search_for])
		{
			found = element;
			break;
		}
	}
	return found;
}

function moreInfo(div)
{
	if($("#"+div).css("display") == "none")
	{
		$("#"+div).show();
		$("#"+div+"_link").html("[-] further information");
	}
	else
	{
		$("#"+div).hide();
		$("#"+div+"_link").html("[+] further information");
	}
}

/*JSON*/
(function($) 
{   
    function toIntegersAtLease(n) 
    // Format integers to have at least two digits.
    {    
        return n < 10 ? '0' + n : n;
    }

    Date.prototype.toJSON = function(date)
    // Yes, it polutes the Date namespace, but we'll allow it here, as
    // it's damned usefull.
    {
        return this.getUTCFullYear()   + '-' +
             toIntegersAtLease(this.getUTCMonth()) + '-' +
             toIntegersAtLease(this.getUTCDate());
    };

    var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;
    var meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        }
        
    $.quoteString = function(string)
    {
        if (escapeable.test(string))
        {
            return '"' + string.replace(escapeable, function (a) 
            {
                var c = meta[a];
                if (typeof c === 'string') {
                    return c;
                }
                c = a.charCodeAt();
                return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
            }) + '"'
        }
        return '"' + string + '"';
    }
    
    $.toJSON = function(o, compact)
    {
        var type = typeof(o);
        
        if (type == "undefined")
            return "undefined";
        else if (type == "number" || type == "boolean")
            return o + "";
        else if (o === null)
            return "null";
        
        // Is it a string?
        if (type == "string") 
        {
            return $.quoteString(o);
        }
        
        // Does it have a .toJSON function?
        if (type == "object" && typeof o.toJSON == "function") 
            return o.toJSON(compact);
        
        // Is it an array?
        if (type != "function" && typeof(o.length) == "number") 
        {
            var ret = [];
            for (var i = 0; i < o.length; i++) {
                ret.push( $.toJSON(o[i], compact) );
            }
            if (compact)
                return "[" + ret.join(",") + "]";
            else
                return "[" + ret.join(", ") + "]";
        }
        
        // If it's a function, we have to warn somebody!
        if (type == "function") {
            throw new TypeError("Unable to convert object of type 'function' to json.");
        }
        
        // It's probably an object, then.
        ret = [];
        for (var k in o) {
            var name;
            var type = typeof(k);
            
            if (type == "number")
                name = '"' + k + '"';
            else if (type == "string")
                name = $.quoteString(k);
            else
                continue;  //skip non-string or number keys
            
            val = $.toJSON(o[k], compact);
            if (typeof(val) != "string") {
                // skip non-serializable values
                continue;
            }
            
            if (compact)
                ret.push(name + ":" + val);
            else
                ret.push(name + ": " + val);
        }
        return "{" + ret.join(", ") + "}";
    }
    
    $.compactJSON = function(o)
    {
        return $.toJSON(o, true);
    }
    
    $.evalJSON = function(src)
    // Evals JSON that we know to be safe.
    {
        return eval("(" + src + ")");
    }
    
    $.secureEvalJSON = function(src)
    // Evals JSON in a way that is *more* secure.
    {
        var filtered = src;
        filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@');
        filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
        filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
        
        if (/^[\],:{}\s]*$/.test(filtered))
            return eval("(" + src + ")");
        else
            throw new SyntaxError("Error parsing JSON, source is not valid.");
    }
})(jQuery);

function objectLength(obj)
{
	var count = 0;
	if(typeof(obj) != "undefined")$.each(obj,function(){count++;})
	return count;
}

function required_check(scan)
{
	var valid = true;
	var requireds = $("#"+scan).find("font[id^='required']");
		
	$.each(requireds,function(iLoop)
	{
		var check = String(this.id).replace("required_","");
		var perform = true;
				
		if(check.match("shipping") && $("#same_as_billing").attr("checked"))
		{
			perform = false;
		}
		
		if(perform)
		{
			if(!$("#"+check).val())
			{
				$("#required").show();
				valid = false;
				$("#invalid_"+check).show();
			}
		}
	});
	
	if(valid)
	{
		if($("#same_as_billing").attr("checked"))setShipping();
	}
	
	return valid;
}

function search(id,type)
{
	if($("#"+id+" :selected").val() != -1)
	{
		if(type == "category")view($.site.unsecure+$.site.webRoot+"products/"+$("#"+id+" :selected").val());
		else if(type == "company")view($.site.unsecure+$.site.webRoot+"search?query="+$("#"+id+" :selected").val()+"&action_company=search");
		else view($.site.unsecure+$.site.webRoot+"search?filter="+$("#"+id+" :selected").val()+"&action_products=search");
	}
}

function show_div(id)
{
	if($("#"+id).css("display") == "none")$("#"+id).show();
	else $("#"+id).hide();
}

/*Site Defaults*/
(function($) 
{		
	$.site = function() {}
	
	$.site.currency_symbol = "&pound;";
	$.site.tax = 0;
	$.site.webRoot = "/";
	$.site.unsecure = "";
	
})(jQuery);

/*Tab System*/
(function($) 
{		
	$.tab = function() {}
	
	$.tab.show = function(id,tab,required,scan)
	{
		var valid = true;
		if(required)valid = required_check(scan);
		
		if(id && valid)
		{
			var tabs  = $("#"+id+" .tab_buttons").find("div[class^='tab']");
			$.each(tabs,function(iLoop)
			{
				if(this.id)
				{
					$("#"+this.id).removeClass();
					$("#tab_content_"+iLoop).removeClass();
					$("#indicator_"+iLoop).removeClass();
					
					if(iLoop == tab)
					{
						$("#"+this.id).addClass("tab_on");
						$("#tab_content_"+tab).addClass("tab_show");
						$("#indicator_"+tab).addClass("indicator_on");
					}
					else
					{
						$("#"+this.id).addClass("tab_off");
						$("#tab_content_"+iLoop).addClass("tab_hide");
						$("#indicator_"+iLoop).addClass("indicator_off");
					}
				}
			});
			$("html").animate({scrollTop:200}, "slow"); 
		}
		else if(!valid)$("html").animate({scrollTop:0}, "slow"); 
	}
	
})(jQuery);

function to2DP(totalPrice)
{
	var price = (totalPrice.toString()).split(".");
	totalPrice = price[0];
	if(price.length == 2)
	{
		if(price[1].length < 2)price[1]=price[1]+"0";
		totalPrice = totalPrice+"."+price[1];
	}
	else totalPrice = totalPrice+".00";
	return totalPrice;
}

function truncate(string,len)
{
	string = string.substring(0,len);
	string += "...";
	return string;
}

function URLEncode (clearString) 
{
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

function validString(string)
{
	var value = (string).replace(space,"_");
	value = (value).replace(illegals,"");
	return value;
}

function view(url)
{
	window.location = url;
}

function view_image(id,target)
{
	var bkup = $("#"+target).attr("src");
	
	$("#"+target).attr("src",String($("#"+id).attr("src")).replace("_thumb.jpg","_thumb2.jpg"));
	$("#full_image").attr("href",String($("#"+id).attr("src")).replace("_thumb.jpg",".jpg"));
	$("#"+id).attr("src",String(bkup).replace("_thumb2.jpg","_thumb.jpg"));
	
}