document.write("<script type=\"text/javascript\" src=\"assets/scripts/datepicker.js\"></script>");
document.write("<script type=\"text/javascript\" src=\"assets/scripts/lightbox/prototype.js\"></script>");
document.write("<script type=\"text/javascript\" src=\"assets/scripts/lightbox/scriptaculous.js?load=effects,builder\"></script>");
document.write("<script type=\"text/javascript\" src=\"assets/scripts/lightbox/lightbox.js\"></script>");
document.write("<script type=\"text/javascript\" src=\"assets/scripts/EdeptiveAjax.js\"></script>");

var gstrDomain = window.location.protocol + "//" + window.location.host;
var gReviewID;

// Elements by ID shortcut - extracted from prototype.js
// if you pass an array to it, it will return an array of elements
function $() {
	var elements = new Array();

	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);

		if (arguments.length == 1)
			return element;

		elements.push(element);
	}

	return elements;
}

// Elements by className
function getElementsByClassName(oElm, strTagName, strClassName)
{
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++)
	{
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className))
		{
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}
// Get URL Parameters
function gup(name){
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	if(results == null )return "";
	else
		return results[1];
}

// New Window
var win=null;
function NewWindow(mypage,myname,w,h,scroll,pos){
if(pos=="random"){LeftPosition=(screen.width)?Math.floor(Math.random()*(screen.width-w)):100;TopPosition=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;}
if(pos=="center"){LeftPosition=(screen.width)?(screen.width-w)/2:100;TopPosition=(screen.height)?(screen.height-h)/2:100;}
else if((pos!="center" && pos!="random") || pos==null){LeftPosition=0;TopPosition=20}
settings='width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no';
win=window.open(mypage,myname,settings);}

// File Exstension
function getExt(filename) {
   var dot_pos = filename.lastIndexOf(".");
   if(dot_pos == -1)
      return "";
   return filename.substr(dot_pos+1).toLowerCase();
}

// Check Max Length
function ismaxlength(obj){
	var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
	if (obj.getAttribute && obj.value.length>mlength)
	obj.value=obj.value.substring(0,mlength)
}

// Delete a review
function deleteReview(pageURL) {	
	if(confirm('Delete this Review?')) {
		$('status_id').value="255";
		$('page').value=pageURL;
		$('frmReview').submit();
	}
}

// Validate Date as dd/mm/yyyy
function validateDate(fld) {
    var RegExDatePattern = /^((((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))|(((0[1-9]|[12]\d|3[01])(0[13578]|1[02])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|[12]\d|30)(0[13456789]|1[012])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|1\d|2[0-8])02((1[6-9]|[2-9]\d)?\d{2}))|(2902((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00))))$/;
    var errorMessage = 'Please enter valid date as day, month, and four digit year.\n(Format: dd/mm/yyyy) or use the date picker tool.';
    if ((fld.value.match(RegExDatePattern)) && (fld.value!='')) {
        return true;
    } else {
        alert(errorMessage);
        fld.value="";
		fld.focus();
    } 
}

var photoCount = 4;
var maxPhotoCount = 10;

function addMorePhotos() {
	var tableName = "photoupload";
	var theTable = $(tableName);
	var tBody = theTable.getElementsByTagName('tbody')[0];
	var TR, TD;
	
	if ($ && theTable!= null && photoCount <= maxPhotoCount) {
		// Row 1
		TR = document.createElement('tr');
			TR.valign = "top";
			tBody.appendChild(TR);
		TD = document.createElement('td');
			TD.width = "75";
			TD.valign = "middle";
			TD.nowrap = "nowrap";
			TD.innerHTML = "Photo " + photoCount + "&#160;&#160;";
			TR.appendChild(TD);
		TD = document.createElement('td');
			TD.nowrap = "nowrap"
			TD.innerHTML = "<input type='file' class='file_path' size='30' name='file" + photoCount + "'/>";
			TR.appendChild(TD);
		
		// Row 2
		TR = document.createElement('tr');
			TR.valign = "top";
			tBody.appendChild(TR);
		TD = document.createElement('td');
			TD.width = "75";
			TD.innerHTML = "<span class='caption'>Caption</span>";
			TR.appendChild(TD);
		TD = document.createElement('td');
			TD.nowrap = "nowrap"
			TD.innerHTML = "<input type='text' class='file_caption' name='caption" + photoCount + "' value='' size='30' maxlength='100'/>";
			TR.appendChild(TD);	
		
		photoCount++;
		
		
	}
	else {
		 alert("Sorry you cannot add any more photos, you have reached the maximum of " + maxPhotoCount + " images");
	}
}

// This function return a date object after accepting a date string ans dateseparator as arguments
function getDateObject(dateString,dateSeperator)
{
	
	var curValue=dateString;
	var sepChar=dateSeperator;
	var curPos=0;
	var cDate,cMonth,cYear;

	//extract day portion
	curPos=dateString.indexOf(sepChar);
	cDate=dateString.substring(0,curPos);
	
	//extract month portion				
	endPos=dateString.indexOf(sepChar,curPos+1);
	cMonth=dateString.substring(curPos+1,endPos);

	//extract year portion				
	curPos=endPos;
	endPos=curPos+5;			
	cYear=curValue.substring(curPos+1,endPos);
	
	//Create Date Object
	dtObject=new Date(cYear,cMonth,cDate);	
	return dtObject;
}

// Search site
function checkSearchFields(objForm)
{	
		if(trim(objForm.keywords.value) == "") {
			alert("Please enter your keyword(s)");
			objForm.keywords.focus();
			return false;
		}
		else {
			return true;
		}
}

// Set a Rating (e.g stars)
function setRating(objId,rating) {
	// set hidden value
	$(objId).value=objId.substring(objId.lastIndexOf("_")+1) + ":" + rating;
	// change ul style class
	$(objId + '_ul').className='rating star' + rating;	
	// set the special overall rating input if this was the overall rating
	if(objId.substring(objId.lastIndexOf("_")+1) == "0") {
		$('overall').value=rating;
	}
}

// Converts special HTML characters to their entities version, before a form is submitted
function html2entities(){
	var re=/[(<>"'&]/g
	for (i=0; i<arguments.length; i++)
	arguments[i].value=arguments[i].value.replace(re, function(m){return replacechar(m)})
}

function replacechar(match){
	if (match=="<")
	return "&lt;"
	else if (match==">")
	return "&gt;"
	else if (match=="\"")
	return "&quot;"
	else if (match=="'")
	return "&#039;"
	else if (match=="&")
	return "&amp;"
}

// Removes any HTML tags from users entered data 
function stripHTML(){
	var re= /<\S[^><]*>/g
	for (i=0; i<arguments.length; i++)
	arguments[i].value=arguments[i].value.replace(re, "")
}

// Show advanced option for Search Locator for Destinantion
function showAdvanced(objId){
	clearSearchLocator();
	// hide all Advanced options for all radios using its class name (adv)
	var theAdvanceddivs = getElementsByClassName(document,'div','adv');
	for(i = 0; i < theAdvanceddivs.length; i++)
	{
		theAdvanceddivs[i].style.display = 'none';
	}
	// Now show the Advanced div for this radio
	show(objId);
}

// Clear search locator hidden fields
function clearSearchLocator() {
	document.forms["frmlocator"].elements['start'].value='0';
	document.forms["frmlocator"].elements['startReview'].value='0';
	document.forms["frmlocator"].elements['boat'].value='';
	document.forms["frmlocator"].elements['company'].value='';
}

// view Details of a Liveaboard or Dive Center 
function viewDetails(page,gotoanchor,liveaboardID,divecenterID){
	if (document.forms["frmlocator"].elements['start']!= null) {
		document.forms["frmlocator"].elements['start'].value=page;
		document.forms["frmlocator"].elements['startReview'].value='0';
		document.forms["frmlocator"].elements['boat'].value=liveaboardID;
		document.forms["frmlocator"].elements['company'].value=divecenterID;
		if (gotoanchor != null) {
			document.forms["frmlocator"].elements['anchor'].value=gotoanchor;
		}
		document.forms["frmlocator"].submit();
	}
}

// view Reviews via paging
function viewReviews(page){
	if (document.forms["frmlocator"].elements['startReview']!= null) {
		document.forms["frmlocator"].elements['startReview'].value=page;
		document.forms["frmlocator"].elements['anchor'].value='reviews';
		document.forms["frmlocator"].submit();
	}
}

// view Destination Search results
function destinationSearch(){
	clearSearchLocator();
	document.forms["frmlocator"].submit();
}



function movetoAnchor() {
	// Get the anchor name
	var gotoanchor = gup('anchor');
	// Check to see if to go to anchor position
	if (gotoanchor != ""){
		window.location = window.location + "#" + gotoanchor;
	}
}

// Report Review 
function reportReviewOpen(reviewID) {
	show("Report"+reviewID);
	hide("linkReport"+reviewID);
	$("comment_"+reviewID).focus();
}

function reportReview(reviewID){
	
	if (($("Report"+reviewID).style.display='block') && (trim($("comment_"+reviewID).value) != "")) {
		var strUrl = gstrDomain + "/admin_pages/form_save.aspx";
		var formID = "0:39";
		var cid = "264";
		var strParams = "";
		gReviewID = reviewID;
		strParams += (strParams == "" ? "" : "&") + "form_id=" + formID;
		strParams += (strParams == "" ? "" : "&") + "cid=" + cid;
		strParams += (strParams == "" ? "" : "&") + "ReviewID=" + reviewID;
		strParams += (strParams == "" ? "" : "&") + "Reviewing=" + escape($("name_"+reviewID).value);
		strParams += (strParams == "" ? "" : "&") + "Comment=" + escape($("comment_"+reviewID).value);
		try {
			goAjaxReportReview = new EdeptiveAjax();
			goAjaxReportReview.postRequest(strUrl, strParams, onReportResponse);
		} catch(e) {
			displayError(e.description);
		}
		// show loading animation
		show("loading_report"+reviewID);
	}
	else {
		show("Report"+reviewID);
		$("comment_"+reviewID).value="";
		alert("Please enter a reason to report this review.");
	}
}

function onReportResponse() {
	var sStatus = goAjaxReportReview.checkReadyState("devnull", null, null, null);
	
	if(sStatus == "OK") {
		hide("loading_report"+gReviewID);
		hide("Report"+gReviewID);
		show("linkReport"+gReviewID);
		$("comment_"+gReviewID).value="";
		alert("Thank you for reporting this review.");
	}
}

function reportReviewClose(reviewID) {
	hide("Report"+reviewID);
	show("linkReport"+reviewID);
	$("comment_"+reviewID).value="";
}

// starts an Ajax call rate review
function rateReview(reviewID) {
	var strUrl = gstrDomain + "/webservices/review_io.asmx/rateReview";
	var fHelpful = document.forms["frm_Rate"+reviewID].elements["ratereview"][0].checked;
	var strParams = "";
	gReviewID = reviewID;
	
	strParams += (strParams == "" ? "" : "&") + "ReviewID=" + reviewID;
	strParams += (strParams == "" ? "" : "&") + "Helpful=" + fHelpful;
	
	try {
		goAjaxRateReview = new EdeptiveAjax();
		goAjaxRateReview.postRequest(strUrl, strParams, onRateResponse);
	} catch(e) {
		displayError(e.description);
	}
	// show loading animation
	show("loading_rate"+reviewID);
	
}

function onRateResponse() {
	var sStatus = goAjaxRateReview.checkReadyState("devnull", null, null, null);
	
	if(sStatus == "OK") {
		var root = goAjaxRateReview.request.responseXML.documentElement;
		var strHtml = "";
		
		hide("loading_rate"+gReviewID);
		if (root.nodeName != "error") {
			$("number_" + gReviewID).innerHTML= getText(root) + " found this review helpful";
		}
		else {
			alert(getText(root));
		}
	}
}

// displays an error message in the message area
function displayError(sMessage) {
	if($("calMessages")) {
		$("calMessages").innerHTML = sMessage;
	}
}

// Show & Hide
function show(c) {
	if (document.getElementById && document.getElementById(c)!= null)
		node = document.getElementById(c).style.display='block';
	else if (document.layers && document.layers[c]!= null) 
		document.layers[c].display = 'block'; 
	else if (document.all && document.all(c)!= null) 
		document.all[c].style.display = 'block';
} 

function hide(c) {
	if (document.getElementById && document.getElementById(c)!= null)
		node = document.getElementById(c).style.display='none';
	else if (document.layers && document.layers[c]!= null) 
		document.layers[c].display = 'none';
	else if (document.all && document.all(c)!= null) 
		document.all[c].style.display = 'none';
}

//Trim string
function trim(str)
{
   return str.replace(/^\s*|\s*$/g,"");
}
//End Function

//Right Trim string
function rtrim(str)
{
	return str.replace(/\s*$/, ""); 
}
//End Function

//Left Trim string
function ltrim(str)
{
	return str.replace(/^\s*/, ""); 
}
//End Function

/*** add rating ***/
var goAjaxRating = null;
function addRating(sItemID, sReviewID, iRating, iTypeID) {
	var sUrl = "", sParams = "";

	sUrl = gstrDomain + "/webservices/review_io.asmx/addRating";
	sParams += (sParams == "" ? "" : "&") + "ItemID=" + sItemID;
	sParams += (sParams == "" ? "" : "&") + "ReviewID=" + sReviewID;
	sParams += (sParams == "" ? "" : "&") + "Rating=" + iRating;
	sParams += (sParams == "" ? "" : "&") + "TypeID=" + iTypeID;
	try {
		goAjaxRating = new EdeptiveAjax();
		goAjaxRating.postRequest(sUrl, sParams, onAddRatingResponse);
	} catch(e) {
		//displayError(e.description);
	}
}
function onAddRatingResponse() {
	if(goAjaxRating.checkReadyState("addRating", ".", "..", "...") == "OK") {
		// do nothing
	}
}
// mozXPath [http://km0ti0n.blunted.co.uk/mozxpath/] km0ti0n@gmail.com
// Code licensed under Creative Commons Attribution-ShareAlike License 
// http://creativecommons.org/licenses/by-sa/2.5/
if( document.implementation.hasFeature("XPath", "3.0") )
{
	XMLDocument.prototype.selectNodes = function(cXPathString, xNode)
	{
		if( !xNode ) { xNode = this; } 

		var oNSResolver = this.createNSResolver(this.documentElement)
		var aItems = this.evaluate(cXPathString, xNode, oNSResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
		var aResult = [];
		for( var i = 0; i < aItems.snapshotLength; i++)
		{
			aResult[i] =  aItems.snapshotItem(i);
		}
		
		return aResult;
	}
	XMLDocument.prototype.selectSingleNode = function(cXPathString, xNode)
	{
		if( !xNode ) { xNode = this; } 

		var xItems = this.selectNodes(cXPathString, xNode);
		if( xItems.length > 0 )
		{
			return xItems[0];
		}
		else
		{
			return null;
		}
	}

	Element.prototype.selectNodes = function(cXPathString)
	{
		if(this.ownerDocument.selectNodes)
		{
			return this.ownerDocument.selectNodes(cXPathString, this);
		}
		else{throw "For XML Elements Only";}
	}

	Element.prototype.selectSingleNode = function(cXPathString)
	{	
		if(this.ownerDocument.selectSingleNode)
		{
			return this.ownerDocument.selectSingleNode(cXPathString, this);
		}
		else{throw "For XML Elements Only";}
	}

}

/* Go to Anchor on page load */
if (window.addEventListener) //DOM method for binding an event
	{window.addEventListener("load", movetoAnchor, false)}
else if (window.attachEvent) //IE exclusive method for binding an event
	{window.attachEvent("onload", movetoAnchor)}
else if (document.getElementById) //support older modern browsers
	{window.onload=movetoAnchor;}
	

/*** keep alive ***/
var gsDomain = window.location.protocol + "//" + window.location.host;
var gfUsingIP = (((window.location.host.substring(0, 1) >= "0") && (window.location.host.substring(0, 1) <= "9")) || (window.location.host == "localhost"));
var gsFolder = "/";
if(gfUsingIP) {
	gsFolder = "/" + window.location.pathname.substring(1, window.location.pathname.indexOf("/", 1)) + "/";
}
gsDomain += gsFolder;
var goAjax = null;
function keepAlive() {
	var strUrl = "";
	var sTiming = document.lastChild.lastChild.innerHTML;
	var sParams = "";

	sTiming = sTiming.substring(sTiming.lastIndexOf("<!--"));
	sTiming = sTiming.substring(5, sTiming.indexOf("-->"));
	strUrl = gsDomain + "webservices/keep_alive.asmx/PingWithTiming";
	sParams = "Timing=" + sTiming;
	try {
		goAjax = new EdeptiveAjax();
		goAjax.postRequest(strUrl, sParams, onKeepAliveResponse);
	} catch(e) {
		setTimeout("keepAlive()", 1000*1);
	}
}
function onKeepAliveResponse() {
	if(goAjax.checkReadyState("keepAlive", "ping.", "ping..", "ping...") == "OK") {
		if(document.getElementById("keepAlive")) {
			var response = goAjax.request.responseXML.documentElement;
			document.getElementById("keepAlive").innerText = "sid=" + getText(response.firstChild);
		}
		setTimeout("keepAlive()", 1000*60);
	}
}
setTimeout("keepAlive()", 1000*2);
