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();
			}
		}
	});
	return valid;
}

function search(id,type,cat)
{
	if($("#"+id+" :selected").val() != -1)
	{
		if(cat)cat = "&category="+cat;
		else cat = "";
		
		if(type == "category")view($.site.unsecure+"products/view/"+$("#"+id+" :selected").val());
		else if(type == "company")view($.site.unsecure+"search?query="+$("#"+id+" :selected").val()+"&action_company=search"+cat);
		else view($.site.unsecure+"search?filter="+$("#"+id+" :selected").val()+"&action_products=search"+cat);
	}
}

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)
				{
					$("#"+id+" #"+this.id).removeClass();
					$("#"+id+" #tab_content_"+iLoop).removeClass();
					$("#"+id+" #indicator_"+iLoop).removeClass();
					
					if(iLoop == tab)
					{
						$("#"+id+" #"+this.id).addClass("tab_on");
						$("#"+id+" #tab_content_"+tab).addClass("tab_show");
						$("#"+id+" #indicator_"+tab).addClass("indicator_on");
					}
					else
					{
						$("#"+id+" #"+this.id).addClass("tab_off");
						$("#"+id+" #tab_content_"+iLoop).addClass("tab_hide");
						$("#"+id+" #indicator_"+iLoop).addClass("indicator_off");
					}
				}

				if(tab == (tabs.length-1))$("#hidden_tab").show();
				else $("#hidden_tab").hide();
			});
			$("html").animate({scrollTop:200}, "slow"); 
		}
		else if(!valid)$("html").animate({scrollTop:0}, "slow"); 
	}
	
})(jQuery);

(function($) 
{		
	$.sub_section = function() {}
	
	$.sub_section.show = function(id,tab,type,update)
	{		
		if(id)
		{
			var tabs  = $("#"+id+" .section_buttons").find("div[class^='section']");
			$.each(tabs,function(iLoop)
			{
				if(this.id)
				{
					$("#"+id+" #"+this.id).removeClass();
					$("#"+id+" #section_content_"+iLoop).removeClass();
					$("#"+id+" #indicator_"+iLoop).removeClass();
					
					if(iLoop == tab)
					{
						$("#"+id+" #"+this.id).addClass("section_on");
						$("#"+id+" #section_content_"+tab).addClass("section_show");
						$("#"+id+" #indicator_"+tab).addClass("indicator_on");
					}
					else
					{
						$("#"+id+" #"+this.id).addClass("section_off");
						$("#"+id+" #section_content_"+iLoop).addClass("section_hide");
						$("#"+id+" #indicator_"+iLoop).addClass("indicator_off");
					}
				}
			});
		}
		
		$("#"+update+"_display").html(type);
		$("#"+update).val(type);
	}
})(jQuery);

function to2DP(value)
{
	return parseFloat(value).toFixed(2);
}

function truncate(string,len)
{
	string = string.substring(0,len);
	string += "...";
	return string;
}

function updateQuantity(input,id,type)
{
	if(type == "website")
	{
		if(String($("#"+id+" :selected").text()).match("out of stock"))
		{
			$("#"+input+"_buy").html('<font class="out_of_stock"><a href="'+$.site.unsecure+'outofstock">some items are out of stock</a></font>');
		}
		else $("#"+input+"_buy").html('<br><button class="button_border" type="submit">Buy</button><input type="hidden" name="action_add" value="'+$.site.product_id+'"/>');
	}
	else
	{
		var id_num = parseInt(String(id).replace("attribute_",""));
		if($("#"+id+" :selected").val() != "0")
		{
			if(!String($("#"+id+" :selected").text()).match("out of stock"))$("#input_form #"+input).html('<input name="quantity['+id_num+']"/>');
			else $("#input_form #"+input).html('<strong>Out of stock</strong>');
		}
		else $("#input_form #"+input).html('<strong>Please select an attribute</strong>');
	}
}

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"));
	
}

jQuery(document).ready(function($) 
{
	var clicked = false;
	$("#searchBox").click(
	function()
	{
		if(!clicked)
		{
			$("#searchBox").val("");
			clicked = true;
		}
	});
	
	$("#scroll_top").click(function()
	{
		$('html,body').animate({scrollTop:0},800);
	});
	
	$("#search_advanced").click(function()
	{
		if($("#pat_finder").css("display") == "none")$("#pat_finder").show();
		//else $("#pat_finder").hide();
	});
	
	$("a.leaveTestimonial").fancybox(
	{
		hideOnContentClick:false,
		overlayShow:true,
		overlayOpacity:0.5
	});
	
	var menus = $("#header_sub_menu").find(".header_sub_menu_item");
	$.each(menus,function(i)
	{
		$(this).bind("mouseenter",function(e)
		{
			$("#sub_menu_"+i).show();
		});
		
		$(this).bind("mouseleave",function(e)
		{
			$("#sub_menu_"+i).fadeOut();
		});
	});
});

var mouseX = 0;
var mouseY = 0;
  
$(document).mousemove(function(e)
{
	mouseX = e.pageX;
 	mouseY = e.pageY;
});

function buyItem(id)
{
	var html = "<div id='buy_"+id+"' style='position:absolute;z-index:999'>";
	html += $("#item_"+id).html();
	html += "</div>";
	$("#product_"+id+" .product").append(html);
					
	$("#buy_"+id+" img").animate({width:"1",height:"1"},980);
	$("#buy_"+id).animate({	left:"830px",
							top:"0px"}
							,1000,
							function()
							{
								$("#product_"+id).submit();
							});
}

function showQty(id)
{
	if($("#qty"+id).css("margin-top") == "-105px")$("#qty"+id).animate({marginTop:"10px"});
	else $("#qty"+id).animate({marginTop:"-105px"});
}

function search()
{
	if(!$("#check_testers").attr("checked") && !$("#check_kits").attr("checked"))
	{
		$("#check_testers").attr("checked",true);
		$("#check_kits").attr("checked",true);
	}
	$('#pat_finder_form').submit();
}

function sendFeedback()
{
	var valid = false;
	var inputs = $("#fancybox-inner").find("[class^=input]");
	
	var send = "action_save=true&";
	var missing = "";
	if(inputs.length)
	{
		$.each(inputs,function(i)
		{
			if($(this).attr("class") == "input_full_required")
			{
				if(this.value)
				{
					send += this.id+"="+this.value+"&";
					valid = true;
				}
				else
				{
					missing += this.id;
					valid = false;
				}
			}
			else send += this.id+"="+this.value+"&";
		});
	}
				
	if(valid)
	{
		var div = $("#fancybox-inner").find("#send_loading");
		$(div).show();
		div = $("#fancybox-inner").find("#table_form");
		$(div).hide();		
		var url = $.site.webRoot+"feedback-send?"+send;
		$.getJSON(url,
		function(data)
		{
			if(data.status)
			{
				$("#fancybox-inner #send_form").hide();
				$("#fancybox-inner #sent_form").show();
			}
			else
			{
				$("#fancybox-inner #failed_form").show();
			}	
		});
	}
	else alert("Please fill in all the fields mark with \"*\"");
}	