﻿var objMenu = null;
var bHideMenu = false;
var hMenu = 0;
var hMenuOut = 0;
var iAdCount = null;
var iCurrentAd = 1;
var iNextId = 2;
var hRotator = 0;
var bCancel = false;

var iCurrentImg = 1;

$(document).ready(function()
{   
  $('html').click(function(objEvent)
  {
    hideMenu(objEvent);
  });
  $(window).resize(function(objEvent)
  {
    
    hideMenu(objEvent, true);
  });
});

function rotateImages()
{
	
    setTimeout("_rotateToImgDown(1)", 2000);
}

function _rotateToImgDown(iImg)
{
  bCancel = false;
  
  $("#imageRot_" + iImg).fadeOut('slow', function()
  {
     hRotator = setTimeout("_rotateToImgUp(" + (iImg+1) + ")", 10);
  });
}

function _rotateToImgUp(iImg)
{
  strDivName = "#imageRot_" + iImg;
  
  if ($(strDivName).length <= 0)
  {
    iImg = 1;
    strDivName = "#imageRot_1";
  }
 
  $(strDivName).fadeIn(2000, function()
  {
     setTimeout("_rotateToImgDown(" + iImg + ")", 3000);
  });
}

function repSearch()
{
  if (validateForm("repForm"))
  {
    $("#repForm").attr("action", "repLocator/search/" + $("#postcode").val());
    $("#repForm").submit();
  }
}

function adPositionClick(event, strNextId)
{
  clearTimeout(hRotator);
  
  iNextId = strNextId;
  bCancel = true;
    
  hRotator = setTimeout("_rotateToAdDown(" + iCurrentAd + ")", 1000);
  
  return false;
}

function adRotatorStart()
{
	if (iAdCount == null)
	{
		iAdCount = $("#rotatorCount").val();
	}
	
	hRotator = setTimeout("_rotateToAdDown(1)", 2000);
}

function _rotateToAdDown(iAd)
{
  bCancel = false;
  
  $("#ad" + iAd).fadeOut('slow', function()
  {
    if (!bCancel)
    {
     hRotator = setTimeout("_rotateToAdUp(" + (iNextId) + ")", 10);
    }
  });
}

function _rotateToAdUp(iAd)
{
  if (iAd > iAdCount)
  {
    iAd = 1;
  }
  
  iNextId = iAd + 1;
  
  if (iNextId > iAdCount)
  {
    iNextId = 1;
  }
  
  iCurrentAd = iAd;
 
  $("#ad" + iAd).fadeIn(2000, function()
  {
    if (!bCancel)
    {
      hRotator = setTimeout("_rotateToAdDown(" + iAd + ")", 3000);
    }
  });
}

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") 
	{ 
		objEvent.returnValue = false;
		
		// Not valid for IE
		try
		{
			objEvent.preventDefault();
		}
		catch (e){}
	}
}

function validateForm(strForm)
{
  var bOk = true;

  $("#error").html("");
  $("#error").removeClass("errorBox");
  $(":input").each(function()
  {
    if ($(this).attr("required") == "true" && $(this).val() == "")
    {
      $("#error").html("Please complete the required elements");
      bOk = false;
    }

    if ($(this).attr("email") == "true")
    {
      var strExpression = "^[\\w-_\.+]*[\\w-_\.]\@([\\w-_]+\\.)+[\\w]+[\\w]$";
      var objReg = new RegExp(strExpression);

      if (!objReg.test($(this).val()))
      {
        $("#error").html("Please enter a valid email address");
        bOk = false;
      }
    }
  });

  if (!bOk)
  {
    $("#error").addClass("errorBox");
    $('html,body').animate({ scrollTop: $("#error").offset().top - 64 }, { duration: 'slow', easing: 'swing' });
    
  }

  return bOk;
}

function quickSearch()
{
    var searchTerm = encodeURIComponent($('input#searchInput').val());
    document.location = '/product/search/' + searchTerm;
}

function hideMenu(objEvent, bForceHide)
{
  if ($(objMenu).length > 0)
  {

    bRemove = true;

    if (bForceHide)
    {
      $(objMenu).hide();
    }
    else if (objEvent.target.id == $(objMenu).attr("id"))
    {
      bRemove = false;
    }
    else
    {
      objParent = objEvent.target;

      while (bRemove && $(objParent).length > 0)
      {
        objParent = $(objParent).parent();

        if ($(objParent).attr("id") == $(objMenu).attr("id"))
        {
          bRemove = false;
        }
      }
    }

    if (bRemove)
    {
      $("[name=categoryMenu]").removeClass("hover");
      $(objMenu).hide();
    }
  }
}

function hoverOverSubCategory(objItem)
{
  $("[name=subCategory]").removeClass("hover");
  $(objItem).addClass("hover");
}

function mouseOutMenu()
{
  if (bHideMenu)
  {
    $("[name=categoryMenu]").removeClass("hover");
    $(objMenu).hide();
  }
}

function showSubCatMenu(objEvent, strId, strCatCode)
{
  objEvent.cancelBubble = true;  
  
  if (hMenu > 0)
  {
    clearTimeout(hMenu);
  }
  
  if (hMenuOut > 0)
  {
    clearTimeout(hMenuOut);
  }
  
  hMenu = setTimeout("showMenu('" + strCatCode + "','" + strId + "')", 500);
  
  return;
}

function cancelMenu()
{
  if (hMenu > 0)
  {
    clearTimeout(hMenu);
  }
  hMenuOut = setTimeout("mouseOutMenu()", 1000);
}

function showMenu(strCatCode, strId)
{
  strData = $("#subMenu_" + strCatCode).html();
  
  objItem = $("#" + strId);
  
  if ($("div#popupMenu").length > 0)
  {
    $("div#popupMenu").remove();
  }

  $("body").append('<div id="popupMenu">' + strData + '</div>');

  bHideMenu = true;

  $("div#popupMenu").hover(function(objEvent)
  {
    bHideMenu = false;
  }, function(objEvent)
  {
    if (hMenuOut > 0)
    {
      clearTimeout(hMenuOut);
    }
    
    bHideMenu = true;
    setTimeout("mouseOutMenu()", 1000);

  });


  var iLeftPos = $(objItem).position().left + $(objItem).width();  //+ 12;
  var iTopPos = $(objItem).position().top;

  $("div#popupMenu").css({ left: iLeftPos, top: iTopPos, display: "none" });
  $("div#popupMenu").show();
  objMenu = $("div#popupMenu");

  $("[name=categoryMenu]").removeClass("hover");
  $(objItem).addClass("hover");
}

function decreaseQuantity(strId)
{
  var iValue = $(strId).val();

  if (isNaN(iValue))
  {
    iValue = 0;
  }
  else if (parseInt(iValue) > 0)
  {
    iValue = parseInt(iValue) - 1;
  }

  $(strId).val(iValue);
}

function increaseQuantity(strId)
{
  var iValue = $(strId).val();

  if (isNaN(iValue))
  {
    iValue = 0;
  }
  else if (parseInt(iValue) > 99)
  {
    iValue = 99;
  }
  else
  {
    iValue++;
  }

  $(strId).val(iValue);
}

function updateBasket()
{
  $("#basketForm").submit();
}

function processOrder()
{ 
  $("#buy").val("true");
  $("#basketForm").submit();
}

function validateItem(strId, bValid)
{
  if (!bValid)
  {
    return false;
  }
  
  if ($("[name=" + strId + "]").val() != "")
  {
    return true;
  }
  
  return false;
}

function validateEmail(strId, bValid)
{
  if (!bValid)
  {
    return false;
  }
  
  var strEmail = $("[name=" + strId + "]").val()

  var strExpression = "^[\\w-_\.+]*[\\w-_\.]\@([\\w-_]+\\.)+[\\w]+[\\w]$";
  var objReg = new RegExp(strExpression);

  return objReg.test(strEmail);
}

function isBillingAddressValid()
{
  var bValid = true;

  bValid = validateItem("billingAddress1", bValid);
  bValid = validateItem("billingCity", bValid);
  bValid = validateItem("billingCounty", bValid);
  bValid = validateItem("billingPostCode", bValid);
  
  if (!bValid)
  {
    $("#error").html("Please complete your billing address");
  }
  
  return bValid;
}

function checkProducts()
{
  $("#error").html("");

  bOk = false;
  
  $("[name*=quantity_]").each (function()
  {
    if($(this).val() != "")
    {
      bOk = true;
    }
  });
  
  if (!bOk)
  {
    $("#error").html("Please choose some products to add first");
    $('html, body').animate({ scrollTop: $("#error").position().top }, 'slow');
  }
  
  return bOk;
}

function isDeliveryAddressValid()
{
  var bValid = true;

  bValid = validateItem("deliveryFirstName", bValid);
  bValid = validateItem("deliveryLastName", bValid);
  bValid = validateItem("deliveryAddress1", bValid);
  bValid = validateItem("deliveryCity", bValid);
  bValid = validateItem("deliveryCounty", bValid);
  bValid = validateItem("deliveryPostCode", bValid);

  if (!bValid)
  {
    $("#error").html("Please complete your delivery address");
  }

  return bValid;
}

function areDetailsValid()
{
  var bValid = true;

  bValid = validateItem("billingFirstName", bValid);
  bValid = validateItem("billingSurname", bValid);
  bValid = validateItem("billingPhone", bValid);
  bValid = validateItem("billingMobile", bValid);

  if (bValid)
  {
    bValid = validateEmail("customerEmail", bValid);

    if (!bValid)
    {
      $("#error").html("Please enter a valid email address");
    }
    else if ($("[name=customerConfirmEmail]").val() != $("[name=customerEmail]").val())
    {
      bValid = false;

      $("#error").html("Please confirm your email addresses match");
    }
    
  }
  else
  {
    $("#error").html("Please complete your contact details");
  }

  return bValid;
}

function confirmDelete(strOrderId)
{
	if (confirm("Are you sure you want to delete this order?  This cannot be reversed"))
	{
		document.location.href = "/user/delete/" + strOrderId;
	}
}

function completeDeliveryDetails()
{
  $("#error").html("");

  var bValid = false;

  if (areDetailsValid())
  {
    if (isBillingAddressValid())
    {
      if ($("[name=deliveryDifferent]").is(":checked"))
      {
        if (isDeliveryAddressValid())
        {
          bValid = true;
        }
      }
      else
      {
        bValid = true;
      }
    }
  }

  if (!bValid)
  {
    $('html, body').animate({ scrollTop: $("#error").position().top }, 'slow');
  }
  
  return bValid;
}

function toggleDeliveryAddress()
{
  if ($("[name=deliveryDifferent]").is(":checked"))
  {
    $("[name=deliveryAsBilling]").val("false");
    $("#deliveryAddress").show("slide");
  }
  else
  {
    $("[name=deliveryAsBilling]").val("true");
    $("#deliveryAddress").hide("slide");
  }
}

function showOrder(strId)
{
  document.location.href = "/user/orders/view/" + strId;
}

function showApprovalOrder(strId)
{
	document.location.href = "/user/approval/view/" + strId;
}

function saveDetails()
{
  $("#error").html("");

  var bValid = false;

  if (areDetailsValid())
  {
    if (isBillingAddressValid())
    {
      if ($("[name=deliveryDifferent]").is(":checked"))
      {
        if (isDeliveryAddressValid())
        {
          bValid = true;
        }
      }
      else
      {
        bValid = true;
      }
    }
  }

  if (!bValid)
  {
    $('html, body').animate({ scrollTop: $("#error").position().top }, 'slow');
  }

  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 calculateFin()
{

  var dCash = $("#cashValue").val();
 
  if (!isNaN(dCash) && dCash > 0)
  {
    var arrEst = Array(34.5, 27, 23);
    var arrNew = Array(36.5, 29.5, 25.5);
    
    for (var i = 0; i < 3; i++)
    {
      $("#monthlyEst" + (i + 3)).html("£" + currencyFormatted(dCash * arrEst[i] / 1000));
      $("#weeklyEst" + (i + 3)).html("£" + currencyFormatted(dCash * arrEst[i] * 12 / 52000));
      $("#dailyEst" + (i + 3)).html("£" + currencyFormatted(dCash * arrEst[i] * 12 / 364000));
      
      $("#monthlyNew" + (i + 3)).html("£" + currencyFormatted(dCash * arrNew[i] / 1000));
      $("#weeklyNew" + (i + 3)).html("£" + currencyFormatted(dCash * arrNew[i] * 12 / 52000));
      $("#dailyNew" + (i + 3)).html("£" + currencyFormatted(dCash * arrNew[i] * 12 / 364000));
    }
    
  }
  else
  {
   for (var i = 0; i < 3; i++)
    {
      $("#monthlyEst" + (i + 3)).html("N/A");
      $("#weeklyEst" + (i + 3)).html("N/A");
      $("#dailyEst" + (i + 3)).html("N/A");
      
      $("#monthlyNew" + (i + 3)).html("N/A");
      $("#weeklyNew" + (i + 3)).html("N/A");
      $("#dailyNew" + (i + 3)).html("N/A");
    }
    
  }
  
  
}

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"));
}

function deleteAddress()
{
	if (confirm("Are you sure you want to delete the selected address?"))
	{
		$("[name=mode]").val('delete');
		return true;
	}
	
	return false;
}

function changeAddressEdit(objSelect, strStub)
{
    var objOption = $(objSelect.value);
    
    
    $("[name=delivery_id]").val($(objOption).attr("delivery_id"));
    
    if (objSelect.value == "")
	{
    	$("#deleteButton").css("display", "none");

        $("[name=" + strStub + "Address1]").val("");
        $("[name=" + strStub + "Address2]").val("");
        $("[name=" + strStub + "City]").val("");
        $("[name=" + strStub + "County]").val("");
        $("[name=" + strStub + "PostCode]").val("");
	}
    else
    {
    	$("#deleteButton").css("display", "inline");

        $("[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"));
    }
}


function postcodeSearch(strStub)
{
    var strPostcode = $("#" + strStub + "PostcodeLookup").val();
    
    if (strPostcode != "")
    {
    
        $.post(
        '/ajax.php?x=postcodeLookup',
        {
          postcode: strPostcode,
          stub : strStub
        },
        function(strHtml)
        {
            $("#" + strStub + "PostcodeResults").html(strHtml);
        }
        );
    }
    else
    {
        alert("Please enter a postcode first");
    }
    
    return false;
}
