//**** General Utility Functions Start ************************************************************//
//This function used for form validation
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

//actual form validation
function MM_validateForm() {
    var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
    for (i=0; i<(args.length-2); i+=3) {
        test=args[i+2]; val=MM_findObj(args[i]);
        if (val) {
            nm=val.name; if ((val=val.value)!="") {
                if (test.indexOf('isEmail')!=-1) {
                    p=val.indexOf('@');
                    if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
                }
                else if (test!='R') {
                    num = parseFloat(val);
                    if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
                    if (test.indexOf('inRange') != -1) {
                        p=test.indexOf(':');
                        min=test.substring(8,p); max=test.substring(p+1);
                        if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
                    }
                }
            }
            else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n';
        }
    }
    //if (errors) alert('The following error(s) occurred:\n'+errors);
    document.MM_returnValue = (errors == '');
	return errors;
} 
//This function converts form vars to a query string, just pass name of form
function form2QS(formName) {
    var docForm = document.getElementById(formName);
    var strSubmitContent = '';
    var formElem;
    var strLastElemName = '';
    
    for (i = 0; i < docForm.elements.length; i++) {        
        formElem = docForm.elements[i];
        switch (formElem.type) {
            // Text fields, hidden form elements
            case 'text':
            case 'hidden':
            case 'password':
            case 'textarea':
            case 'select-one':
            strSubmitContent += formElem.name + '=' + escape(formElem.value) + '&'
            break;
            
            // Radio buttons
            case 'radio':
            if (formElem.checked) {
                strSubmitContent += formElem.name + '=' + escape(formElem.value) + '&'
            }
            break;
            
            // Checkboxes
            case 'checkbox':
            if (formElem.checked) {
                // Continuing multiple, same-name checkboxes
                if (formElem.name == strLastElemName) {
                    // Strip of end ampersand if there is one
                    if (strSubmitContent.lastIndexOf('&') == strSubmitContent.length-1) {
                        strSubmitContent = strSubmitContent.substr(0, strSubmitContent.length - 1);
                    }
                    // Append value as comma-delimited string
                    strSubmitContent += ',' + escape(formElem.value);
                }
                else {
                    strSubmitContent += formElem.name + '=' + escape(formElem.value);
                }
                strSubmitContent += '&';
                strLastElemName = formElem.name;
            }
            break;         
        }
    }    
    // Remove trailing separator
    strSubmitContent = strSubmitContent.substr(0, strSubmitContent.length - 1);
    return strSubmitContent;
}

//this function pauses the display for the number of milliseconds passed.
function pausecomp(millis){
	date = new Date();
	var curDate = null;
	
	do { var curDate = new Date(); }
	while(curDate-date < millis);
} 
//Remove Filter by reloading page
function reloadPage() {
    document.location.href="index.php";
}

//check for form errors
function checkAddModSite(addmod) {
	errors = "";
	errors = MM_validateForm('title','','R','lat','','RisNum','lon','','RisNum','email','','NisEmail','description','','R');

	if(document.addsite2db.title.value == "") {
		errors+="- title is required \n";
	}
	if(document.addsite2db.rating.value == "") {
		//rating only required for add not mod
		if(addmod == "add") {
			errors+="- rating is required \n";
		}
	}
	if(document.addsite2db.countrycode.value == "") {
		errors+="- country is required \n";
	}	
	if (errors != ""){
		alert('The following error(s) occurred:\n'+errors);
	}
	else {
		//everything good submit
		document.addsite2db.submit();
	}
}

//set num of records to view per page
function setRecNum(value) {
    document.cookie= "RecNum=" + escape(value);;
}

//get a parameter out of URL
function getURLParam(strParamName){
  var strReturn = "";
  var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 ){
    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if (
aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return strReturn;
}
//**** General Utility Fuctions End ************************************************************//

//**** Ajax Functions Start *******************************************************************//
//AJAX for submitting new site and viewing site data
var xmlHttp;

//create HTTP Request
function createXMLHttpRequest() {
    if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }
}

function startRequest(url) {
    document.getElementById("bottomsidebar").innerHTML = "<span class='loading'><blink>Loading...</blink></span>";
    
    createXMLHttpRequest();
    if(url == "addmodsite.php"){
        xmlHttp.onreadystatechange = handleStateChangeAdd;
    }
    else if(url.substring(0,4) == "view"){
        xmlHttp.onreadystatechange = handleStateChangeView;
    }
    else {
        xmlHttp.onreadystatechange = handleStateChangeMod;
    }
    
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}

//Add dive site
function addSite() {
    startRequest("addmodsite.php");
    document.getElementById("pagecontrols").innerHTML= '';
	document.getElementById("scubamap").style.cursor = "hand";
}

//modify dive site
function modSite(id) {
    var modurlstring = "addmodsite.php?id=";
    modurlstring += id;
	//now make sure they go page to same page from result set
	if(getURLParam('page') != "") {
		modurlstring += "&page=" + getURLParam('page');
	}
	//set top page control bar to blank
    document.getElementById("pagecontrols").innerHTML= '';	
    startRequest(modurlstring);
    document.getElementById("scubamap").style.cursor = "hand";
}

//view dive site
function viewSite(id) {
    var viewurlstring = "viewsite.php?id=";
    viewurlstring += id;
    startRequest(viewurlstring);
    document.getElementById("topsidebar").innerHTML = topsidebar_html;
    document.getElementById("opsbar").innerHTML = "<input name=\"Edit Site\" type=\"button\" value=\"Edit Site\" class=\"prettybutton\" onClick=\"modSite(" + id + ")\">";
    document.getElementById("opsbar").innerHTML+=  "<input name=\"Add Gallery\" type=\"button\" value=\"Add Gallery\" class=\"prettybutton\" onClick=\"galAdd(" + id + ")\">";
    document.getElementById("opsbar").innerHTML+=  "<input name=\"Add Operator\" type=\"button\" value=\"Add Operator\" class=\"prettybutton\" onClick=\"opAdd(" + id + ")\">";
    document.getElementById("opsbar").innerHTML+=  "<input name=\"Rate Site\" type=\"button\" value=\"Rate Site\" class=\"prettybutton\" onClick=\"rateSite(" + id + ")\">";
	document.getElementById("opsbar").innerHTML+=  "<input name=\"Cancel\" type=\"button\" value=\"Cancel\" class=\"prettybutton\" onClick=\"window.location.href=('index.php')\" />";

    document.getElementById("scubamap").style.cursor = "default";
}

function handleStateChangeView() {
    if(xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            document.getElementById("bottomsidebar").innerHTML = xmlHttp.responseText;
        }
    }
}

function handleStateChangeAdd() {
    if(xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            //Resize for IE
            if (document.all) {
                document.getElementById("topsidebar").style.setAttribute("cssText","height:425px;");
                document.getElementById("bottomsidebar").style.setAttribute("cssText","visibility:hidden;");
            }
            else {                
                //Resize for Firefox
                document.getElementById("bottomsidebar").setAttribute("style","visibility:hidden;");
				document.getElementById("topsidebar").setAttribute("style","overflow:hidden;");				
				document.getElementById("topsidebar").setAttribute("style","height:425px;");
            }
         
			document.getElementById("bottomsidebar").innerHTML = "";
            document.getElementById("topsidebar").innerHTML = xmlHttp.responseText;
            //set stars
            bigbang();
            
            //Change operations bar
            document.getElementById("opsbar").innerHTML = '<input name="Save" type="button" value="Save" class="prettybutton" onclick="checkAddModSite(\'add\');"/> <input name="Cancel" type="button" value="Cancel" class="prettybutton" onClick="window.location.reload()" />';
			//now open the minimap
			openMinimap();
        }
    }
}
function handleStateChangeMod() {
    if(xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            
            //Resize for IE
            if (document.all) {
                document.getElementById("bottomsidebar").style.setAttribute("cssText","visibility:hidden;");
                document.getElementById("topsidebar").style.setAttribute("cssText","height:425px;");
            }
            else {
                //Resize for Firefox
                document.getElementById("bottomsidebar").setAttribute("style","visibility:hidden;");
				document.getElementById("topsidebar").setAttribute("style","height:425px;");

            }
            //document.getElementById("topsidebar").setAttribute("height","500px");
            document.getElementById("bottomsidebar").innerHTML = "";
			document.getElementById("topsidebar").innerHTML = xmlHttp.responseText;
			//set rating stars
			bigbang();
            //Change operations bar
            document.getElementById("opsbar").innerHTML = '<input name="Save Changes" type="button" value="Save Changes" class="prettybutton"            onclick="checkAddModSite(\'mod\');"/> <input name="Cancel" type="button" value="Cancel" class="prettybutton" onClick="window.location.reload()" />';
        }
    }
}
function addGallery() {
    createXMLHttpRequest();
    xmlHttp.onreadystatechange = handleStateChangeAddGal;
    xmlHttp.open("GET", "addgallery.php", true);
    xmlHttp.send(null);
}

function handleStateChangeAddGal() {
    if(xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            document.getElementById("galleryHere").innerHTML = xmlHttp.responseText;
        }
    }
}

//here we will add a new gallery to an existing site
function galAdd(id) {
    document.getElementById("bottomsidebar").innerHTML = "<span class='loading'><blink>Loading...</blink></span>";
    //Change operations bar
    document.getElementById("opsbar").innerHTML = '<input name="Save Gallery" type="button" value="Save Gallery" class="prettybutton"            onclick="document.addsite2db2.submit()"/> <input name="Cancel" type="button" value="Cancel" class="prettybutton" onClick="window.location.reload()" />';
    createXMLHttpRequest();
    xmlHttp.onreadystatechange = handleStateChangegalAdd;
    
    var galurlstring = "addnewgallery.php?id=";
    galurlstring += id;
    
    xmlHttp.open("GET", galurlstring, true);
    xmlHttp.send(null);
}

function handleStateChangegalAdd() {
    if(xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            document.getElementById("bottomsidebar").innerHTML = xmlHttp.responseText;
            
        }
    }
}

function addOperator() {
    createXMLHttpRequest();
    xmlHttp.onreadystatechange = handleStateChangeAddOp;
    xmlHttp.open("GET", "addoperator.php", true);
    xmlHttp.send(null);
}

function handleStateChangeAddOp() {
    if(xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            document.getElementById("operatorHere").innerHTML = xmlHttp.responseText;
        }
    }
}

//here we will add a new operator to an existing site
function opAdd(id) {
    document.getElementById("bottomsidebar").innerHTML = "<span class='loading'><blink>Loading...</blink></span>";
    //Change operations bar
    document.getElementById("opsbar").innerHTML = '<input name="Save Operator" type="button" value="Save Operator" class="prettybutton" onclick="document.addopp2db.submit()"/> <input name="Cancel" type="button" value="Cancel" class="prettybutton" onClick="window.location.reload()" />';
    createXMLHttpRequest();
    xmlHttp.onreadystatechange = handleStateChangeopAdd;
    
    var opurlstring = "addnewoperator.php?id=";
    opurlstring += id;
    
    xmlHttp.open("GET", opurlstring, true);
    xmlHttp.send(null);
}

function handleStateChangeopAdd() {
    if(xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            document.getElementById("bottomsidebar").innerHTML = xmlHttp.responseText;
            
        }
    }
}

//rate scuba site
function rateSite(id) {
    document.getElementById("bottomsidebar").innerHTML = "<span class='loading'><blink>Loading...</blink></span>";
    //Change operations bar
    document.getElementById("opsbar").innerHTML = '<input name="Save" type="button" value="Save" class="prettybutton" onclick="document.addsite2db.submit()"/> <input name="Cancel" type="button" value="Cancel" class="prettybutton" onClick="window.location.reload()" />';
    createXMLHttpRequest();
    xmlHttp.onreadystatechange = handleStateChangeRateSite;
    
    var rateurlstring = "ratesite.php?id=";
    rateurlstring += id;
    
    xmlHttp.open("GET",rateurlstring, true);
    xmlHttp.send(null);
}

function handleStateChangeRateSite() {
    if(xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            document.getElementById("bottomsidebar").innerHTML = xmlHttp.responseText;
            //now set the stars
            bigbang(true);
        }
    }
}

function rateSiteDB(id) {
    document.getElementById("bottomsidebar").innerHTML = "<span class='loading'><blink>Saving...</blink></span>";
    var queryString = 'ratesitedb.php?id=' + id;
    queryString = queryString + form2QS('addsite2db') + "&timeStamp=" + new Date().getTime();
    createXMLHttpRequest();
    xmlHttp.onreadystatechange = handleStateChangeRateDB(id);
    xmlHttp.open("GET", queryString, true);
    xmlHttp.send(null);
}

function handleStateChangeRateDB(id) {
    if(xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            viewSite(id);
        }
    }
}

//handle fitler count
function countResults() {
    var url = 'sitecount.php?';
    queryString = form2QS('filter') + "&timeStamp=" + new Date().getTime();
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }

    self.xmlHttpReq.open('POST', url, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            filterCount(self.xmlHttpReq.responseText);
        }
    }
    self.xmlHttpReq.send(queryString );
}

function filterCount(str){
    document.getElementById("filterCount").innerHTML = str;
}
//**** Ajax Functions End *******************************************************************//

//**** Google Map Functions Start *******************************************************************//
// A function to create the marker and set up the event window
function createMarker(point,name,html,id,oddoreven) {
    html = '<div class="dispWin">' + html + '</div>';
    var marker = new GMarker(point,flagIcon);
    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(html);
        viewSite(id);
    });
    // save the info we need to use later for the topsidebar
    gmarkers[i] = marker;
    htmls[i] = html;
    
    //alternate background color of results
    if(oddoreven % 2 == 0) {
        divclass = "evenclass";
    }
    else {
        divclass = "oddclass";
    }
    // add a line to the topsidebar html
    topsidebar_html += '<div class="' + divclass + '"><a class="topLink" href="javascript:myclick(' + i + ', ' + id + ')">' + html + '</a></div>';
    i++;
    return marker;
}

// This function picks up the click and opens the corresponding info window
function myclick(i,id) {
    viewSite(id);
    gmarkers[i].openInfoWindowHtml(htmls[i]);
}

//zoom in to a point
function zoomIn(maptype,lon,lat) {
	if (maptype == "satellite") {	
		map.setMapType(G_SATELLITE_TYPE);
	}
	if (maptype == "reg") {	
		map.setMapType(G_MAP_TYPE);
	}
	map.centerAndZoom(new GPoint(lon, lat), 9);
}

//move to a particular location
function moveToLoc() {
	var x = document.getElementById("countryDrop").value.split(",")[0];
	var y = document.getElementById("countryDrop").value.split(",")[1];
	var zoom = document.getElementById("countryDrop").value.split(",")[2];
	map.centerAndZoom(new GPoint(x, y), zoom);
}
//**** Google Map Functions End *******************************************************************//

//**** Minimap Start ***************************************************************************//
//close minimap
function closeMinimap() {
	minimap.setMapType(G_MAP_TYPE);
	//close for IE
    if (document.all) {
    	document.getElementById("minimap").style.setAttribute("cssText","visibility:hidden;");
    	document.getElementById("miniControl").style.setAttribute("cssText","top:488px;");		
    }
	//open for Firefox	
    else {
		document.getElementById("minimap").setAttribute("style","visibility:hidden;");
		document.getElementById("miniControl").setAttribute("style","top:488px;");		
	}
	document.getElementById("miniControl").innerHTML = '<a href="javascript:openMinimap()"><img src="/images/minimap_open.gif" alt="Open MiniMap" name="Open MiniMap" border="0" title="Open MiniMap" /></a>';	
}

//open minimap
function openMinimap() {
	minimap.setMapType(G_SATELLITE_TYPE);
	//open for IE
    if (document.all) {
    	document.getElementById("minimap").style.setAttribute("cssText","visibility:visible;");
  		document.getElementById("miniControl").style.setAttribute("cssText","top:419px;");
    }
	//open for Firefox	
    else {
		document.getElementById("minimap").setAttribute("style","visibility:visible;");
		document.getElementById("miniControl").setAttribute("style","top:419px;");
	}	
	document.getElementById("miniControl").innerHTML = '<a href="javascript:closeMinimap()"><img src="/images/minimap_close.gif" alt="Open MiniMap" name="Open MiniMap" border="0" title="Open MiniMap" /></a>';

}
//**** Minimap End ***************************************************************************//

//**** Star Rating Functions Start *******************************************************************//
function setStar(starsset,saveBtn) {
    //Set hidden var
    document.addsite2db.rating.value=starsset;
    starsnotset = 5 - starsset;
    starfield = "";
    for(i = 1; i <= starsset; i++) {
        starfield = starfield + "<img src=\"/images/star_selected.gif\" alt=\"star selected\"/>";
    }
    for(i = 1; i <= starsnotset; i++) {
        starfield = starfield + "<img src=\"/images/star_notselected.gif\" alt=\"star not selected\"/>";
    }
	if(saveBtn == true) {
		    starfield = starfield + "<INPUT TYPE=\"button\" VALUE=\"Save\" onclick=\"document.addsite2db.submit()\" class=\"prettybutton\">";
	}
    starfield = starfield + "<INPUT TYPE=\"button\" VALUE=\"Reset\" ONCLICK=\"bigbang()\" class=\"prettybutton\">";
    document.getElementById("diveRate").innerHTML=starfield;
}

function bigbang(saveBtn) {
    starsstring = "<ul class='star-rating'>";
    starsstring+="<li><a href='#' title='Rate this 1 star out of 5' class='one-star' onclick=\"setStar('1'," + saveBtn + ")\">1</a></li>";
    starsstring+="<li><a href='#' title='Rate this 2 star out of 5' class='two-stars' onclick=\"setStar('2'," + saveBtn + ")\">2</a></li>";
    starsstring+="<li><a href='#' title='Rate this 3 stars out of 5' class='three-stars' onclick=\"setStar('3'," + saveBtn + ")\">3</a></li>";
    starsstring+="<li><a href='#' title='Rate this 4 stars out of 5' class='four-stars' onclick=\"setStar('4'," + saveBtn + ")\">4</a></li>";
    starsstring+="<li><a href='#' title='Rate this 5 stars out of 5' class='five-stars' onclick=\"setStar('5'," + saveBtn + ")\">5</a></li>";
    starsstring+="</ul>";
    document.getElementById("diveRate").innerHTML=starsstring;
}
//**** Star Rating Functions End *******************************************************************//

//**** Pretty Dropdown Start **********************************************************************//
//change color of select box
function changeSelectColor(id){
    selIndex = document.getElementById(id).selectedIndex;
    
    if(selIndex=="0") {
        document.getElementById(id).style.background = "#5bb0eb";
        document.getElementById(id).style.color = "#FFFFFF";
    }
    else {
        document.getElementById(id).style.background = "#FFFFFF";
        document.getElementById(id).style.color = "#000000";
    }
}

//change color of text input
function changetxtColor(id){
    var changetext = document.getElementById(id);
    if(changetext.value=="") {
        document.getElementById(id).style.background = "#5bb0eb";
        document.getElementById(id).style.color = "#FFFFFF";
    }
    else {
        document.getElementById(id).style.background = "#FFFFFF";
        document.getElementById(id).style.color = "#000000";
    }
}

//pretty checkboxes
//global variables that can be used by ALL the functions on this page.
var inputs;
var imgFalse = '/images/false.gif';
var imgTrue = '/images/true.gif';

//this function runs when the page is loaded, put all your other onload stuff in here too.
function init() {
	replaceChecks();
}

function removeCheckImg() {
    var node = document.getElementById("checkImage1");
    node.removeChild(node.childNodes[0]);
}

function replaceChecks() {
     //get all the input fields on the page
    inputs = document.getElementsByTagName('input');
    
    //cycle through the input fields
    for(var i=0; i < inputs.length; i++) {
        
        //check if the input is a checkbox
        if(inputs[i].getAttribute('type') == 'checkbox') {
            
            //create a new image
            var img = document.createElement('img');
            
            //check if the checkbox is checked
            if(inputs[i].checked) {
                img.src = imgTrue;
                } else {
                img.src = imgFalse;
            }
            
            //set image ID and onclick action
            img.id = 'checkImage'+i;
            //set image
            img.onclick = new Function('checkChange('+i+')');
            //place image in front of the checkbox
            inputs[i].parentNode.insertBefore(img, inputs[i]);
            
            //hide the checkbox
            inputs[i].style.display='none';
        }
    }
}

//change the checkbox status and the replacement image
function checkChange(i) {
      if(inputs[i].checked) {
        inputs[i].checked = '';
        document.getElementById('checkImage'+i).src=imgFalse;
        } else {
        inputs[i].checked = 'checked';
        document.getElementById('checkImage'+i).src=imgTrue;
    }
	countResults();
} 
//**** Pretty Dropdown End **********************************************************************//
