//#######################################################
//#######################################################
//####
//#### Generic system routines
//####
//#######################################################
//#######################################################

//*******************************************************
//DROP A COOKIE
//
//Enter:
//PARAM 1: Cookie Name
//PARAM 2: Cookie Value
//PARAM 3: Cookie Expiry (in days)
//*******************************************************

function setCookie(c_name,value,exdays)
	{
	var exdate=new Date();		
	exdate.setDate(exdate.getDate() + exdays);

	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()+"; path=/");
	document.cookie=c_name + "=" + c_value;
	}

//*******************************************************
//RETRIEVE A COOKIE
//
//Enter:
//PARAM 1: Cookie Name
//*******************************************************

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
	{
  	x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  	y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  	x=x.replace(/^\s+|\s+$/g,"");
  	if (x==c_name)
    	{
    	return unescape(y);
    	}
  	}
return('');
}	
	
//*******************************************************
//GENERIC AJAX INVOKING ROUTINE
//
//Enter:
//PARAM 1: Routine to Run
//PARAM 2: String to Pass in
//PARAM 3: Routine to Execute on Return
//*******************************************************

function primeAjax(PARAM1,PARAM2,PARAM3)
	{
	if (window.XMLHttpRequest)
		{
		// code for IE7+, Firefix, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
		}
	else if (window.ActiveXObject)
		{
		// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	else
		{
		}
		
	xmlhttp.onreadystatechange=function()
		{
		if (xmlhttp.readyState==4)
			{
			PARAM3(xmlhttp.responseText);
			}
		}	
		
//Start AJAX transaction
	
	xmlhttp.open("post",PARAM1,true);
	xmlhttp.send(PARAM2);				
	}

//#######################################################
//#######################################################
//####
//#### Individual Page Routines
//####
//#######################################################
//#######################################################

//*******************************************************
//Construct hidden password box to be displayed
//When Log-In clicked.
//
//This is attached to the window.onload event so 
//including this file in a page automatically adds
//the log in link SO LONG AS the page contains
//relevant styles
//*******************************************************

window.onload=function()
	{
	var tmp="";
	
//Dynamically create a div to load Log-On box
	var divTag = document.createElement("div");
	divTag.id = "loghold";
	document.body.appendChild(divTag);

	tmp=tmp + "<form name='LOGIN'>";
	tmp=tmp + "<div id='login'>";
	tmp=tmp + "<div id='close'><a href=\"#\" onclick=\"document.getElementById('loghold').style.visibility='hidden'\">x</a></div>";
	tmp=tmp + "<div id='logtit'>NORTHCLIFFE AND SEAVIEW HOLIDAY PARKS<br />OWNER LOG-IN:-</div>";
	tmp=tmp + "<div>";
	tmp=tmp + "<ul style='clear:both;width:350px;height:26px;'>";
	tmp=tmp + "<li class='lbw'>USERNAME:</li>";
	tmp=tmp + "<li><input name='USERNAME' type='text' /></li>";
	tmp=tmp + "</ul>";
	tmp=tmp + "</div>";
	tmp=tmp + "<div>";
	tmp=tmp + "<ul style='clear:both;width:350px;height:26px;'>";
	tmp=tmp + "<li class='lbw'>PASSWORD:</li>";
	tmp=tmp + "<li><input name='PASSWORD' type='password' /></li>";
	tmp=tmp + "</ul>";
	tmp=tmp + "</div>";
	tmp=tmp + "<div style='margin:20px 20px 0 0;float:right;'><input name='' value='SUBMIT' type='button' onclick='SendPass();'/></div>";
	tmp=tmp + "</div>";
	tmp=tmp + "</form>";

	document.getElementById('loghold').innerHTML = tmp;
	logBar();
	}
	
//Submit and verify un/pw using AJAX when submit button is clicked 
//on Log-In box
	
function SendPass()
	{
	if (document.LOGIN.USERNAME.value.length==0)
		{
		alert("ERROR: USERNAME FIELD CANNOT BE BLANK");
		}
	else if (document.LOGIN.PASSWORD.value.length==0)
		{
		alert("ERROR: PASSWORD FIELD CANNOT BE BLANK");
		}
	else
		{
		sendstr=escape(document.LOGIN.USERNAME.value+'!'+document.LOGIN.PASSWORD.value).replace(/%/gi,"^");
		primeAjax("http://www.northcliffe-seaview.com/cgi-bin/ownerlog.cgi",sendstr,tryLog);
		}
	}

//Called via AJAX (on complete) when Password has been verified

function tryLog(str)
	{
	if (str.substr(0,1) =="Y") 
		{
		var Temp=str.substr(1).split("!");

		setCookie("LOG",Temp[0],1)			
		setCookie("EXPIRES",Temp[1],1)			

		logBar();
		document.getElementById('loghold').style.visibility='hidden'
		alert ("Logged in.");
		window.location="http://www.northcliffe-seaview.com/cgi-bin/owner.cgi?TASK=OwnerFront";
		} 
	else 
		{
		alert("Error: Your USERNAME and/or PASSWORD is incorrect.\n\nPlease note, PASSWORDS are CASE SENSITIVE.");
		}
	}

//Display the relevant Log-In bar dependant on whether
//user is logged in or not.

function logBar()
	{
	if (getCookie('LOG') !="")
		{
		document.getElementById('topbar').innerHTML = "<a href=\"#\" onclick=\"window.location='http://www.northcliffe-seaview.com/cgi-bin/owner.cgi?TASK=OwnerFront'\">PROFILE</a><span style=\"color:#f8d848;\">&nbsp;|&nbsp;</span><a href=\"#\" onclick=\"logOut();\">LOG OUT&nbsp;[USER:"+getCookie('LOG')+"]</a>";	
		}
	else
		{
		document.getElementById('topbar').innerHTML = "<a href=\"#\" onclick=\"document.LOGIN.USERNAME.value='';document.LOGIN.PASSWORD.value='';document.getElementById('loghold').style.visibility='visible'\">LOG IN&nbsp;</a>";	
		}
	}

//Log user out by setting cookie date 1000 days in past.

function logOut()
	{
	if (confirm("Are you sure you wish to log out?"))
		{
		setCookie("LOG","",-1000);
		window.location="http://www.northcliffe-seaview.com";
		}
	}

//Fetch back the 'buy gas form' using Ajax.  Needed because various
//parameters (including Gas Price and Card surcharge) must be fetched
//from database as they can change.

function getGas()
	{
	primeAjax("http://www.northcliffe-seaview.com/cgi-bin/fetchgas.cgi","",gotGas);		
	}
	
function gotGas(str)
	{
	Temp=str.split("!");
	document.CFORM.CardSurcharge.value=Temp[1];
	document.CFORM.GasPrice.value=Temp[0];
	//document.getElementById('B1').disabled = true;
	document.getElementById('gp').innerHTML = Temp[1];
	document.getElementById('gasDiv').style.visibility='visible'

	if (document.CFORM.HEADER.value.substr(0,1)!="!")
		{
		document.getElementById('CREDMESS').style.visibility='visible';
		document.getElementById('LINE1').style.height='32pt';
		document.getElementById('LINE1').innerHTML="<b>"+document.CFORM.HEADER.value+"</b> - "+document.CFORM.BODY.value;
		}
		
	gasCalc();
	}
	
function gasCalc()
	{
	if (document.CFORM.gasQty.value!="0" && document.CFORM.gasPay.value!="0")
		{
		vl=1;
		if (document.CFORM.gasPay.value=="2") {vl+=(document.CFORM.CardSurcharge.value)/100;}
		document.CFORM.B1.disabled = false;
		res=(document.CFORM.gasQty.value*document.CFORM.GasPrice.value)*vl;
		res=Math.round(res*Math.pow(10,2))/Math.pow(10,2); //round to 2 decimal places
		document.getElementById('gt').innerHTML=res;
		document.CFORM.Tot.value = res;
		}
	else
		{
		document.CFORM.B1.disabled = true;
		}
	}

//#######################################################
//#######################################################
//####
//#### Sage Pay Routines
//####
//#######################################################
//#######################################################

//Get a valid Sage Pay encryption string

function sendPay()
	{
	str=escape(document.CFORM.Tot.value+"!"+document.CFORM.Description.value+getCookie('LOG')+"!"+document.CFORM.Success.value+"!"+document.CFORM.Fail.value).replace(/%/gi,"^");
	primeAjax("http://www.northcliffe-seaview.com/cgi-bin/encode.cgi",str,gotCrypt);		
	}

function gotCrypt(str)
	{
	document.CFORM.crypt.value=str;
	alert("You will now be re-directed to our payment provider Sage Pay to enter your credit/debit card details");
	document.CFORM.submit();
	}
	
//#######################################################
//#######################################################
//####
//#### Pay Bills
//####
//#######################################################
//#######################################################

function payBills()
	{
	primeAjax("http://www.northcliffe-seaview.com/cgi-bin/getbills.cgi",getCookie('LOG'),showBills);
	}
	
function showBills(str)
	{
	if (document.CFORM.HEADER.value.substr(0,1)!="!")
		{
		document.getElementById('CREDMESS').style.visibility='visible';
		document.getElementById('LINE1').style.height='32pt';
		document.getElementById('LINE1').innerHTML="<b>"+document.CFORM.HEADER.value+"</b> - "+document.CFORM.BODY.value;
		}

	document.getElementById('bills').innerHTML = str;
	}


//#######################################################
//#######################################################
//####
//#### Upload Pics
//####
//#######################################################
//#######################################################

function picField()
	{
	primeAjax("http://www.northcliffe-seaview.com/cgi-bin/setpics.cgi",getCookie('LOG'),showUpPics);
	}
	
function showUpPics(str)
	{
	document.getElementById('pickList').innerHTML = str;
	document.getElementById('pickList').style.visibility='visible';
	reparsePics();
	}
	
function sendPics()
	{
	var error="";
	var hit="";
	
	for (lp=0;lp<5;lp++)
		{
		if (document.CFORM["FILE"+lp].value.length>0 || document.CFORM["NAME"+lp].value.length>0 || document.CFORM["DESCRIPTION"+lp].value.length>0)
			{
			hit="Y";
			if ((document.CFORM["FILE"+lp].value.length==0 || document.CFORM["NAME"+lp].value.length==0 || document.CFORM["DESCRIPTION"+lp].value.length==0) && error.length==0)
				{
				var enm=lp+1;
				error="ERROR: Photo "+enm+" has incomplete fields and cannot be processed";
				}
			}
		}

	if (error.length>0) {alert(error);} else {if (hit=="Y") {document.CFORM.ACCNUM.value=getCookie('LOG');document.CFORM.submit();}}
	}
	
function delIt(str)
	{
	if ((confirm("WARNING - You are about to delete this Image - This CANNOT be undone, do you wish to continue?")))
		{
		document.CFORM.TASK.value="deleteIt";
		document.CFORM.DELETE.value=str;
		sendPics();
		}
	}
	
function picGallery()
	{
	primeAjax("http://www.northcliffe-seaview.com/cgi-bin/setgallery.cgi","0^"+getCookie('LOG'),drawGallery);
	}

function drawGallery(str)
	{
	var temp=str.split("^");
	
	for (lp=1;lp<=temp[0];lp++)
		{
		document.getElementById("PAGENUM").options[lp-1] = new Option("PAGE:"+lp, lp-1);
		}
	
	document.getElementById('box8').innerHTML = temp[1];
	reparsePics();
	}

function reparsePics()
	{
	$(document).ready(function() 
		{
		$("a[rel=example_group]").fancybox(
			{
			'transitionIn'		: 'elastic',
			'transitionOut'		: 'elastic',
			'title'				: "NC & SV Holiday Parks",
			'titlePosition' 	: 'over',
			'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) 
				{
				return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
				}
			});
		});
	}
	
function pageAjax()
	{
	primeAjax("http://www.northcliffe-seaview.com/cgi-bin/setgallery.cgi",document.CFORM.PAGENUM.value+"^"+getCookie('LOG'),redrawGallery);
	}
	
function redrawGallery(str)
	{
	var temp=str.split("^");
	document.getElementById('box8').innerHTML = temp[1];
	reparsePics();
	}
	
function votePic(str)
	{
	primeAjax("http://www.northcliffe-seaview.com/cgi-bin/picvote.cgi",getCookie('LOG')+"^"+str,redrawFav);		
	}
	
function redrawFav(str)
	{
	var count = document.getElementsByTagName("SPAN");
	for(i = 0; i < count.length; i++)
		{
		if (count[i].id.substr(0,3)=="TH_")
			{
			var tmp=count[i].id.substr(3);

			fname="vote_thumb.png";if (tmp==str) {fname="thumb_tick.png";}

			document.getElementById(count[i].id).innerHTML="<img src=\"http://www.northcliffe-seaview.com/owners/graphics/"+fname+"\">";
			}
		}
	}
	
function managePics(str)
	{
	document.CFORM.submit();
	//alert(str);
	}
	
function getVotes()
	{
	primeAjax("http://www.northcliffe-seaview.com/cgi-bin/votetot.cgi","",drawVotes);		
	}
	
function drawVotes(str)
	{
	document.getElementById("votes").innerHTML=str;
	}
