if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

function toggleDiv(strId)
{
	if ( $(".secondMenu.shown").length === 0)
	{
	  $("#"+strId).addClass("shown").show("slide",{ direction: "up" });
	}
	else
	{
	  $(".secondMenu.shown").removeClass("shown").hide("slide",{ direction: "up" }, function() {
		$("#"+strId).addClass("shown").show("slide", { direction: "up" });
	  });
	}
}

function validateForm(strForm)
{
  var bOk = true;

  $("#error").html("");
  $("#error").removeClass("errorBox");
  $(":input").each(function()
  {
    if ($(this).attr("needed") + "" == "true" && $(this).val() == "")
    {
      $("#error").html("Please complete the required elements");
      $("#error").addClass("errorBox");
      bOk = false;
    }
    
  });


  if (!bOk)
  {
	  $('html,body').animate({ scrollTop: $("#error").offset().top - 64 }, { duration: 'slow', easing: 'swing' });
	  return false;
  }
  
  return true;

}

function validateContactForm()
{
	var bValid = true;
	var strError = "Please complete the required elements";

	bValid = validateItem("firstname", bValid);
	bValid = validateItem("surname", bValid);
	bValid = validateItem("email", bValid);
	bValid = validateEmail("email", bValid);

	$("#error").removeClass("errorBox");

	if (bValid)
	{
		strCaptura = $("#recaptcha_response_field").val();
		strChallenge = $("#recaptcha_challenge_field").val();

		$.ajax({
		      url: "/ajax.php?x=checkCaptcha",
		      type: "POST",
		      data: ({captcha : strCaptura,
		            challenge : strChallenge}),
		      dataType: "html",
		      async:false,
		      success: function(data)
		        {
		        	if (data != '')
		        	{
		        		bValid = false;
		        		strError = "Please complete the reCaptcha correctly.";
		        	}

		        }
		   }
		);
	}

	if (!bValid)
	{
		$("#error").html(strError);
		$("#error").addClass("errorBox");
		$('html,body').animate({ scrollTop: $("#error").offset().top - 64 }, { duration: 'slow', easing: 'swing' });
	}

	return bValid;
}


function currencyFormatted(dAmount)
{
	var dMoney = parseFloat(dAmount);
	var cMinus = '';
	
	if(isNaN(dMoney))
	{ 
		dMoney = 0.00; 
	}
	
	if(dMoney < 0) 
	{
		cMinus = '-'; 
	}
	
	dMoney = Math.abs(dMoney);
	dMoney = parseInt((dMoney + .005) * 100);
	dMoney = dMoney / 100;
	
	var sMoney = new String(dMoney);
	
	if(sMoney.indexOf('.') < 0)
	{ 
		sMoney += '.00'; 
	}
	
	if(sMoney.indexOf('.') == (sMoney.length - 2))
	{ 
		sMoney += '0'; 
	}
	
	sMoney = cMinus + sMoney;
	
	return sMoney;
}


function validateItem(strId, bValid)
{
  var bItemValid = false;

  if ($("[name=" + strId + "]").val() != "")
  {
	  $("[name=" + strId + "]").removeClass("errorInput");
	  bItemValid = true;
  }
  else
  {
	  $("[name=" + strId + "]").addClass("errorInput");
  }

  if (bValid && bItemValid)
  {
	  return true;
  }
  else
  {
  	  return false;
  }
}

function validateEmail(strId, bValid)
{
  var bItemValid = false;

  var strEmail = $("[name=" + strId + "]").val()

  var strExpression = "^[\\w-_\.+]*[\\w-_\.]\@([\\w-_]+\\.)+[\\w]+[\\w]$";
  var objReg = new RegExp(strExpression);

  if ( objReg.test(strEmail))
  {
	  $("[name=" + strId + "]").removeClass("errorInput");
	  bItemValid = true;
  }
  else
  {
	  $("[name=" + strId + "]").addClass("errorInput");
  }

  if (bValid && bItemValid)
  {
	  return true;
  }
  else
  {
  	  return false;
  }

}

function numericOnly(objEvent)
{
  var objReg = new RegExp("^\d*\.?\d*$");
  var objEvent = objEvent || window.event;
  var strKeyCode = objEvent.keyCode || objEvent.which;

  var strKey = String.fromCharCode(strKeyCode);
  var strRegEx = /[0-9]|\./;

  if (!strRegEx.test(strKey) && strKeyCode != "9" && strKeyCode != "8" && strKeyCode != "37" && strKeyCode != "39")
  {
    objEvent.returnValue = false;

    // Not valid for IE
    try
    {
      objEvent.preventDefault();
    }
    catch (e) { }
  }
}

var objMenu = null;

function checkHover()
{
    if (objMenu)
    {
        objMenu.find('[rel^=innerMenu]').slideUp();
    }
}

function checkHovering(objMenu)
{
	$('.hovering > [rel^=innerMenu]').slideDown('fast');
}

function loginPopup(objURL)
{

	var strHTML = $("#loginForm").html();
	
	$.prompt(strHTML,{
		
	buttons:{}
	});
	
	
	return false;
}

function inlineLogin(objForm)
{
	var strEmail = $("[name=email]", objForm).val();
	var strPassword = $("[name=password]", objForm).val();
	var strRedirect = $("[name=redirect]", objForm).val();
	
	var objDiv = $(".loginError", objForm);

	$.post(
        '/user/logininline',
        {
           email : strEmail,
           password : strPassword
        },
        function(strData)
        {
        	if (strData == "true")
        	{
        		document.location.href = strRedirect;
        	}
        	else
        	{
        		$(objDiv).html("Sorry, email address or password not recognised");
        	}
        }
    );

	return false;
}

  
function postcodeSearch(strStub)
{
    var strPostcode = $("#" + strStub + "PostcodeLookup").val();
    
    if (strPostcode != "")
    {
    	$("#" + strStub + "Loading").show();
    	
        $.post(
        '/postcode/lookup',
        {
          postcode: strPostcode,
          stub : strStub
        },
        function(strHtml)
        {
        	$("#" + strStub + "Loading").hide();
            $("#" + strStub + "PostcodeResults").html(strHtml);
        }
        );
    }
    else
    {
        alert("Please enter a postcode first");
    }
    
    return false;
}

function changeAddress(objSelect, strStub)
{
    var objOption = $(objSelect.value);
    
    $("[name=" + strStub + "Address1]").val($(objOption).attr("address1"));
    $("[name=" + strStub + "Address2]").val($(objOption).attr("address2"));
    $("[name=" + strStub + "City]").val($(objOption).attr("town"));
    $("[name=" + strStub + "County]").val($(objOption).attr("county"));
    $("[name=" + strStub + "PostCode]").val($(objOption).attr("postcode"));
}

$(document).ready(function()
{ 
    	//Partial Sliding (Only show some of background)
	$('.boxgrid.home').hover(function(){
		$(".cover", this).stop().animate({top:'120px'},{queue:false,duration:160});
	}, function() {
		$(".cover", this).stop().animate({top:'0px'},{queue:false,duration:160});
	});
	
	$('.boxgrid.category').hover(function(){
		$(".cover", this).stop().animate({top:'182px'},{queue:false,duration:160});
	}, function() {
		$(".cover", this).stop().animate({top:'0px'},{queue:false,duration:160});
	});


	$('.headerBasket').click(function() {
		window.location.href = "/basket"
	});
	
    $('[rel^=hoverMenu] > [rel^=innerHover]').hover(function()
    {
    	$(this).addClass('hovering');
    },
    function()
    {
    	$(this).removeClass('hovering');
    }
	);

    $('[rel^=hoverMenu] > [rel^=innerHover]').hover(function()
    {
        if (objMenu)
        {
            objMenu.find('[rel^=innerMenu]').slideUp('slow');
            objMenu = null;
        }

        if($(this).find('[rel^=innerMenu]').css('display') != 'block')
        {

        	objMenu = $(this);
        	setTimeout("checkHovering(objMenu)", 100);

        }
    }, function()
    {
        objMenu = $(this);
        setTimeout(
            "checkHover()",
            100
        );
    });

    $(".youtube").click(function ()
    {
    	
    	objDiv = $("#popupContent");
    	
    	$.prompt(objDiv.html(), {classes: "youtube", buttons: {}});
    	
    	var objPopup = $("#jqi");
    	
    	objH2 = $("h2", objPopup);
    	
    	objH2.html($(this).attr("rel"));
    	
    	objIFrame = $("iframe", objPopup);
    	$(objIFrame).attr("src", $(this).attr("href")); 

    	return false;
    });
    
    $(".productthumb").click(function ()
    {
		$(".productmain").attr("href", $(this).attr("href"));
		$(".productmain > img").attr("src", $(this).attr("rel"));
		
		return false;
    });
    
    function howarthHoverOver(){
	
	$("div.arrow").hide();
	var objMenu = $(this);
	
	var objPosition = $(objMenu).position();
	
	var iLeft = objPosition.left + ($(objMenu).width() / 2) - ($(objMenu).find("div.arrow").width() / 2);
	
	var iTop = objPosition.top + $(objMenu).height() - 6;
		
	$(objMenu).find("div.arrow").css({top: iTop, left: iLeft});
	$(objMenu).find("div.arrow").show();
	
	$(this).find(".catSubMenu").stop().fadeTo('fast', 1, function()
	{
		$(this).show();
	}); //Find sub and fade it in
	
	(function($) {
		
		//Function to calculate total width of all ul's
		jQuery.fn.calcSubWidth = function()
		{
			rowWidth = 0;
			
			//Calculate row
			$(this).find(".subMenuUL").each(function() { //for each ul...
				rowWidth += $(this).width(); //Add each ul's width together
			});

		};
	})(jQuery);

	/*if ( $(this).find(".row").length > 0 )
	{
		//If row exists...
		var biggestRow = 0;

		$(this).find(".row").each(function()
		{
			//for each row...
			$(this).calcSubWidth(); //Call function to calculate width of all ul's
			//Find biggest row
			if(rowWidth > biggestRow) {
				biggestRow = rowWidth;
			}
		});

		$(this).find(".catSubMenu").css({'width' :biggestRow}); //Set width
		$(this).find(".row:last").css({'margin':'0'});  //Kill last row's margin

	}
	else
	{
		//If row does not exist...
		$(this).calcSubWidth();  //Call function to calculate width of all ul's
		$(this).find(".catSubMenu").css({'width' : rowWidth}); //Set Width

	}*/
}

//On Hover Out
function howarthHoverOut(){
 
  $(this).find("div.arrow").hide();
  $(this).find(".catSubMenu").stop().fadeTo('fast', 0, function() { //Fade to 0 opactiy
	$(this).hide();  //after fading, hide it
	
  });
  
  
}

//Set custom configurations
var config = {
	 sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
	 interval: 200, // number = milliseconds for onMouseOver polling interval
	 over: howarthHoverOver, // function = onMouseOver callback (REQUIRED)
	 timeout: 100, // number = milliseconds delay before onMouseOut
	 out: howarthHoverOut // function = onMouseOut callback (REQUIRED)
};

	$("div.headerNavigation ul.catMenu li div.catSubMenu").css({'opacity':'0'}); //Fade sub nav to 0 opacity on default

  if($("div.headerNavigation ul.catMenu li.top").size())
   $("div.headerNavigation ul.catMenu li.top").hoverIntent(config); //Trigger Hover intent with custom configurations

});

function initializeMap()
{
    var objGirds = new google.maps.LatLng(51.54780976480297, -2.4324140548705);

	var arrOptions =
	{
      zoom: 15,
      center: objGirds,
      mapTypeId: google.maps.MapTypeId.HYBRID
	};

	var objMap = new google.maps.Map(document.getElementById("map_canvas"),
			arrOptions);

	 var objMarker = new google.maps.Marker({
	      position: objGirds,
	      map: objMap,
	      title: "Apec Braking"
	  });
  }
  

function dump(arr,level) {
    var dumped_text = "";
    if(!level) level = 0;
	
    //The padding given at the beginning of the line.
    var level_padding = "";
    for(var j=0;j<level+1;j++) level_padding += "    ";
	
    if(typeof(arr) == 'object') { //Array/Hashes/Objects
        for(var item in arr) {
            var value = arr[item];
			
            if(typeof(value) == 'object') { //If it is an array,
                dumped_text += level_padding + "'" + item + "' ...\n";
                dumped_text += dump(value,level+1);
            } else {
                dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
            }
        }
    } else { //Stings/Chars/Numbers etc.
        dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
    }
    return dumped_text;
}

