var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function validatenewuser()
{
	if (document.getElementById("first_name").value==="")
	{
		alert("Please enter your first name...");
		document.getElementById("newuserform").first_name.focus();
		return false;
	}
	if (document.getElementById("last_name").value==="")
	{
		alert("Please enter your last name...");
		document.getElementById("newuserform").last_name.focus();
		return false;
	}
	if (echeck(document.getElementById("email_address").value)!=true)
	{
		document.getElementById("newuserform").email_address.focus();
		return false;
	}
	if (document.getElementById("cfm_email_address").value !=document.getElementById("email_address").value)
	{
		alert("Please ensure confirmation e-mail matches original e-mail.");
		document.getElementById("newuserform").cfm_email_address.focus();
		return false;
	}
	if (document.getElementById("password").value==="")
	{
		alert("Please chose a password...");
		document.getElementById("newuserform").password.focus();
		return false;
	}
	validateaddress("newuserform");
}

function validateaddress(formName)
{
	if (document.getElementById("house_number").value==="")
	{
		alert("Please enter the first line for your address...");
		document.getElementById(formName).house_number.focus();
		return false;
	}
	if (document.getElementById("city").value==="")
	{
		alert("Please enter your city...");
		document.getElementById(formName).city.focus();
		return false;
	}
	if (document.getElementById("postcode").value==="")
	{
		alert("Please enter your postcode...");
		document.getElementById(formName).postcode.focus();
		return false;
	}
	if (document.getElementById("state").value==="")
	{
		alert("Please enter your state...");
		document.getElementById(formName).state.focus();
		return false;
	}
	if (document.getElementById("country")==="null")
	{
		alert("Please select your country...");
		document.getElementById(formName).country.focus();
		return false;
	}
}

function updatedefaultoptions(categoryid,defaultoptionid)
{
	if (document.getElementById('productoptions'))
	{
		if (document.getElementById('productoptions'+ defaultoptionid))
		{
			document.getElementById('productoptions'+ defaultoptionid).selected = true;
		}
	}
}
// Opacity and Fade in script.
// Script copyright (C) 2008 http://www.cryer.co.uk/.
// Script is free to use provided this copyright header is included.
function SetOpacity(object,opacityPct)
{
  // IE.
  object.style.filter = 'alpha(opacity=' + opacityPct + ')';
  // Old mozilla and firefox
  object.style.MozOpacity = opacityPct/100;
  // Everything else.
  object.style.opacity = opacityPct/100;
}
function ChangeOpacity(id,msDuration,msStart,fromO,toO)
{
  var element=document.getElementById(id);
  var opacity = element.style.opacity * 100;
  var msNow = (new Date()).getTime();
  opacity = fromO + (toO - fromO) * (msNow - msStart) / msDuration;
  if (opacity<0) 
    SetOpacity(element,0)
  else if (opacity>100)
    SetOpacity(element,100)
  else
  {
    SetOpacity(element,opacity);
    element.timer = window.setTimeout("ChangeOpacity('" + id + "'," + msDuration + "," + msStart + "," + fromO + "," + toO + ")",1);
  }
}
function FadeIn(id)
{
  var element=document.getElementById(id);
  if (element.timer) window.clearTimeout(element.timer); 
  var startMS = (new Date()).getTime();
  element.timer = window.setTimeout("ChangeOpacity('" + id + "',500," + startMS + ",0,100)",1);
}
function FadeOut(id)
{
  var element=document.getElementById(id);
  if (element.timer) window.clearTimeout(element.timer); 
  var startMS = (new Date()).getTime();
  element.timer = window.setTimeout("ChangeOpacity('" + id + "',1000," + startMS + ",100,0)",1);
}
function FadeInImage(foregroundID,newImage,backgroundID)
{
  var foreground=document.getElementById(foregroundID);
  if (backgroundID)
  {
    var background=document.getElementById(backgroundID);
    if (background)
    {
      background.style.backgroundImage = 'url(' + foreground.src + ')';
      background.style.backgroundRepeat = 'no-repeat';
    }
  }
  SetOpacity(foreground,0);
  foreground.src = newImage;
  if (foreground.timer) window.clearTimeout(foreground.timer); 
  var startMS = (new Date()).getTime();
  foreground.timer = window.setTimeout("ChangeOpacity('" + foregroundID + "',500," + startMS + ",0,100)",10);
}


function trackfacebookshare(page)
{
	processAjaxRequest("/inc/ajax.php","?action=trackfacebookshare","nodiv");
	if (page==="checkout")
	{
		window.location = "?page=checkout";
	}
}

function showspecial(specialid)
{
	window.location="?page=viewspecial&specialid=" + specialid;
}

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr)
{
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid date")
		return false
	}
	return true
}




function validatespecialsform()
{
	//alert("Validating");
	//	reset all styles to default

	var proceed = true;
	var alertmessage="";
	var checkeditemcount =0;
	var checkeditems="";
	// get number of checked items
	
	if(!(document.specialsform.product.length))
	{
		//means there's only 1 item being displayed
		if( document.specialsform.product.checked === true)
		{
			checkeditemcount++;
			checkeditems = checkeditems + "&item" + checkeditemcount + "id=" + document.specialsform.product.value;
		}
		
	}
	else
	{
		for (i = 0; i < document.specialsform.product.length; i++)
		{
			if( document.specialsform.product[i].checked === true)
			{
				checkeditemcount++;
				checkeditems = checkeditems + "&item" + checkeditemcount + "id=" + document.specialsform.product[i].value;
			}
		}
	}
	
	//	begin validation
	
	var specialvalue=document.getElementById("specialvalue").value;
	if (specialvalue==="" || specialvalue===0)
	{
		proceed=false;
		alertmessage+="You need to specify a value for this discount\n";
		document.getElementById("specialvalue").style.background='#ff0000';
	}
	if (checkeditemcount===0)
	{
		proceed=false;
		alertmessage+="You need to select at least 1 product for this special\n";
		document.getElementById("productlist").style.background='#ff0000';
	}
	if (isDate(document.getElementById("startdate").value)===false)
	{
		proceed=false;
		alertmessage+="You need to enter a valid start date for this special\n";
		document.getElementById("startdate").style.background='#ff0000';
	}
	if (isDate(document.getElementById("enddate").value)===false)
	{
		proceed=false;
		alertmessage+="You need to enter a valid end date for this special\n";
		document.getElementById("enddate").style.background='#ff0000';
	}
	if (document.getElementById("enddate").value <= document.getElementById("startdate").value)
	{
		//proceed=false;
		//alertmessage+="Your end date needs to be later than your start date\n";
		//document.getElementById("startdate").style.background='#ff0000';
		//document.getElementById("enddate").style.background='#ff0000';
	}
	if (proceed===true)
	{
		//alert(alertmessage);
		return true;
	}
	else
	{	
		alert(alertmessage);
		return false;
	}
}

function previewspecial()
{
	var checkeditems = "";
	var checkeditemcount =0;
	var proceed = true;
	var alertmessage="";

	var specialtype=document.getElementById("specialtype").value;
	var specialvalue=document.getElementById("specialvalue").value;
	if (specialvalue==="" || specialvalue===0)
	{
		proceed=false;
		alertmessage+="You need to specify a value for this discount\n";
	}
	if(!(document.specialsform.product.length))
	{
		//means there's only 1 item being displayed
		if( document.specialsform.product.checked === true)
		{
			checkeditemcount++;
			checkeditems = checkeditems + "&item" + checkeditemcount + "id=" + document.specialsform.product.value;
		}
		
	}
	else
	{
		for (i = 0; i < document.specialsform.product.length; i++)
		{
			if( document.specialsform.product[i].checked === true)
			{
				checkeditemcount++;
				checkeditems = checkeditems + "&item" + checkeditemcount + "id=" + document.specialsform.product[i].value;
			}
		}
	}
	if (checkeditemcount==0)
	{
		proceed=false;
		alertmessage+="You need to select at least 1 product for this special\n";
	}
	if (proceed===true)
	{
		checkeditems = checkeditems + "&numberofitemstoview=" + checkeditemcount;
		//alert("?action=listproducts&categoryid=" + categoryid + "&type=" + type + "&specialvalue=" + specialvalue + checkeditems);
		processAjaxRequest("/inc/ajax.php","?action=previewspecial&type=" + specialtype + "&specialvalue=" + specialvalue + checkeditems,"previewspecial");
		//document.getElementById("productlist").style.display="none";
		document.getElementById("previewspecial").style.display="block";
	}
	else
	{	
		alert(alertmessage);
	}
}//

function updateproductlist(categoryid)
{
	processAjaxRequest("/inc/ajax.php","?action=listproducts&categoryid=" + categoryid,"productlist");
	document.getElementById("productlist").style.display="block";
	document.getElementById("previewspecial").style.display="none";
}

function checkAll(field)
{
for (i = 0; i < field.length; i++)
	field[i].checked = true ;
}

function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
	field[i].checked = false ;
}


function setproductoption(cartentryid,optionvalue)
{
	//alert(optionvalue);
	processAjaxRequest("/inc/ajax.php","?action=setproductoption&cartentryid=" + cartentryid + "&optionvalue=" + optionvalue,"nodiv");
	if (document.getElementById('isoptionselected'))
	{
		document.getElementById('isoptionselected').value="YES";
	}
	
}

function addnewoptionvalue(optionid)
{
	var optionvalue=prompt("Type a value for this option","Option Value");
	processAjaxRequest("/inc/ajax.php","?action=addnewoptionvalue&optionvalue=" + optionvalue + "&optionid=" + optionid,"optionvalues");
	document.getElementById("optionvalues").style.display="block";
}

function savenewoption()
{
	var optionname = document.getElementById("optionname").value;
	var optiondescription = document.getElementById("optiondescription").value;
	processAjaxRequest("/inc/ajax.php","?action=savenewoption&optionname=" + optionname + "&optiondescription=" + optiondescription,"optioncontainer");
}

function addnewoption(optionname,optiondescription)
{
	processAjaxRequest("/inc/ajax.php","?action=addnewoption","optioncontainer");
}

function listoptionvalues(optionid)
{
	processAjaxRequest("/inc/ajax.php","?action=listoptionvalues&optionid=" + optionid,"optionvalues");
	document.getElementById("optionvalues").style.display="block";
}

function updatecartquantities(orderhasproductid)
{
	var newQuantity = document.getElementById(orderhasproductid).value;
	if (newQuantity==="0")
	{
		if (window.confirm("Are you sure you wish to remove this item from your order?"))
		{
			processAjaxRequest("/inc/ajax.php","?action=changecartquantity&orderhasproductid=" + orderhasproductid + "&quantity=" + newQuantity,'cartdisplaycontent');
			processAjaxRequest("/inc/ajax.php","?action=changecartquantity&orderhasproductid=" + orderhasproductid + "&quantity=" + newQuantity + "&area=primarycontent",'primarycontentinner');
		}
	}
	else
	{
		processAjaxRequest("/inc/ajax.php","?action=changecartquantity&orderhasproductid=" + orderhasproductid + "&quantity=" + newQuantity,'cartdisplaycontent');
		processAjaxRequest("/inc/ajax.php","?action=changecartquantity&orderhasproductid=" + orderhasproductid + "&quantity=" + newQuantity + "&area=primarycontent",'primarycontentinner');
	}
	updateminicart();
}

function expandaddress(addressid)
{
	var currentaddressid=document.getElementById("expandedaddress").value;
	document.getElementById("deliveryaddressexpanded" + currentaddressid).style.display="none";
	document.getElementById("deliveryaddress" + currentaddressid).style.outline="none";
	document.getElementById("deliveryaddressexpanded" + addressid).style.display="block";
	document.getElementById("deliveryaddress" + addressid).style.outline="solid #3f9";
	document.getElementById("expandedaddress").value=addressid;
	processAjaxRequest("/inc/ajax.php","?action=setaddressid&addressid=" + addressid,"nodiv");
	window.location="?page=checkout";
}

function validateemail(emailaddress)
{
	var valid = processAjaxRequest("/inc/ajax.php","?action=validateemailaddress&emailaddress=" + emailaddress,"return");
	alert(valid);
}
function loguserin()
{
	processAjaxRequest("/inc/functions.php","?page=loguserin&useremail=" + document.getElementById("useremail").value + "&userpassword=" + userpassword,"loginbox");
	return false;
}

function removitemfromcart(orderhasproductid)
{
	if (window.confirm("Are you sure you wish to remove this item from your order?"))
	{
		processAjaxRequest("/inc/ajax.php","?action=removefromorder&orderhasproductid=" + orderhasproductid,"primarycontentinner");
		updateminicart();
	}
}

function updateminicart()
{
	processAjaxRequest("/inc/ajax.php","?action=updateminicart","cartdisplaycontent");
	
}

function addToCart(productid,numberofoptions)
{
	if (document.getElementById("optionselected"))
	{
		var optionselected=document.getElementById("optionselected").value;
		if (optionselected!="")
		{
			var optionselected=document.getElementById("optionselected").value;
			processAjaxRequest("/inc/ajax.php","?action=addtocart&productid=" + productid + "&optionselected=" + optionselected, "nodiv");
			document.getElementById("addtocartbutton" + productid).innerHTML = "Add another";
			updateminicart();
		}
		else
		{
			alert("Please choose an option before you add this item to your cart");
		}
	}
	else
	{
		processAjaxRequest("/inc/ajax.php","?action=addtocart&productid=" + productid, "nodiv");
		document.getElementById("addtocartbutton" + productid).innerHTML = "Add another";
		updateminicart();	
	}
}
function echeck(str)
{
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1)
		{
			alert("Invalid E-mail Address")
			return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   alert("Invalid E-mail Address")
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    alert("Invalid E-mail Address")
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    alert("Invalid E-mail Address")
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    alert("Invalid E-mail Address")
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    alert("Invalid E-mail Address")
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    alert("Invalid E-mail Address")
		    return false
		 }

 		 return true					
}
 
function processAjaxRequest(URL,queryString,DivForOutput)
{
	var ajaxRequest = makeajaxobject();
	var date=new Date();
	queryString+="&randdate=" + date;
	ajaxRequest.open("GET", URL + queryString, true);
	ajaxRequest.onreadystatechange = function()
	{
		if ( ajaxRequest.readyState == 4 )
		{  // 4 is "complete" 
			{
				var response = ajaxRequest.responseText;
				if (response)
				{
					if (document.getElementById(DivForOutput))
					{
						document.getElementById(DivForOutput).innerHTML = response;
					}
					else if (DivForOutput==="alert")
					{
						
						alert(response);
					}
					else
					{
						return response;
					}
				}
				//else
				{
					//alert(URL + queryString);
				}
			}
		}
	}
	
	ajaxRequest.send(null);
}

function makeajaxobject()
{
	var ajaxRequest;
	try
	{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e)
	{
		// Internet Explorer Browsers
		try
		{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e)
		{
			try
			{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e)
			{
				// Something went wrong
				alert("Your browser broke!");
				return false;
			}
		}
	}
	return ajaxRequest;
}
