
document.onmousemove = getMouseCoordinates;

function getMouseCoordinates(event){
	ev = event || window.event;
	mouseX = ev.pageX;
	mouseY = ev.pageY;
}



var popUpWin = 0;
function popLocationSelectPage(lat,lon){
	var width = 800;
	var height = 600;
	var left = 10;
	var top = 10;
	if(popUpWin){
		if(!popUpWin.closed) popUpWin.close();
	}
		// should be in the admin directory
	popUpWin = open('http://visitadirondacks.com/admin/chooseLocationGoogle.php?latitude='+lat+'&longitude='+lon, 'popUpWin', 'toolbar=no,location=no,directories=no,status=1,menubar=no,scrollbars=1,resizable=1,copyhistory=yes,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
}

function extensionChecker(formName,fileName){
	if ( (fileName.indexOf(".jpg") != -1) || (fileName.indexOf(".jpeg") != -1) || (fileName.indexOf(".png") != -1) || (fileName.indexOf(".gif") != -1)){
        return validateForm(fileName);
    }
    else{
        return false;
    }
}

//either shows or hides an element based on its current status
function showHideElement(elementId){
	if(document.getElementById(elementId).style.display=='none'){
		document.getElementById(elementId).style.display = '';
	}
	else{
		document.getElementById(elementId).style.display = 'none';
	}
}

function showHideParentElement(elementId){

	if(!parent.document.getElementById(elementId)){
		return false;
	}
	if(parent.document.getElementById(elementId) && parent.document.getElementById(elementId).style.display=='none'){
		parent.document.getElementById(elementId).style.display = '';
		return true;
	}
	if(parent.document.getElementById(elementId)){
		parent.document.getElementById(elementId).style.display = 'none';
		return true;
	}
	if(opener.document.getElementById(elementId) && opener.document.getElementById(elementId).style.display=='none'){
		opener.document.getElementById(elementId).style.display = '';
		return true;
	}
	if(opener.document.getElementById(elementId)){
		opener.document.getElementById(elementId).style.display = 'none';
		return true;
	}
}

function hideElement(elementId){
	if(document.getElementById(elementId)){
		document.getElementById(elementId).style.display = 'none';
	}
}

function showElement(elementId){
	if(document.getElementById(elementId)){
		document.getElementById(elementId).style.display = '';
	}
}

function changeHTML(elementId, str){
    document.getElementById(elementId).innerHTML = str;
}

function positionItAtMouse(elementID){
	//define universal dsoc left point
	var dsocleft = document.body.scrollLeft;
	//define universal dsoc top point
	var dsoctop = document.body.scrollTop;

	//if the user is using IE 4+ or Firefox/ NS6+
	if (document.all||document.getElementById){
		if(document.getElementById(elementID)){
			document.getElementById(elementID).style.left=parseInt(mouseX)+5+"px";
			document.getElementById(elementID).style.top=mouseY+5+"px";
		}
	}
}

function xmlhttpPost(strURL, formId, updateElementId, loadingElement, doNotHide){
	if(!doNotHide){
		hideElement(updateElementId);
		showElement(loadingElement);
	}
    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', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            updatePageHTML(updateElementId, self.xmlHttpReq.responseText);
			if(!doNotHide){
				hideElement(loadingElement);
				showElement(updateElementId);
			}
        }
    }
    self.xmlHttpReq.send(getquerystring(formId));
}

function getquerystring(formId) {
	qstr = '';
	var obj = document.forms[formId]
	for (i=0; obj.elements[i]; i++) {
		currentElement = obj.elements[i].name;
		currentValue = obj.elements[i].value;
    	qstr = qstr + currentElement + '=' + escape(currentValue) + '&';  // NOTE: no '?' before querystring
	}
    return qstr;
}

function updatePageHTML(elementId, str){
    document.getElementById(elementId).innerHTML = str;
}

function validateString(element){
      
    stringType = element.substr(0, 4);
	if(!document.getElementById(element)){
		return false;
	}
    stringToTest = document.getElementById(element).value;
	re = /^$/;
	canBeEmpty = element.substr(4,1);
	if(canBeEmpty=='t'){
		canBeEmpty = true;
	}
	else if(canBeEmpty=='f'){
		canBeEmpty = false;
	}
	if(canBeEmpty==true && stringToTest==''){
		if(document.getElementById(element+'_valid_image')){
			document.getElementById(element+'_valid_image').src = 'http://visitadirondacks.com/admin/themes/Default/images/form_valid.gif';
		}
		return true;
	}
if(stringType=='blnk'){re = /.$/;}
if(stringType=='date'){re = /^([01]){1,1}([0-9]){1,1}\/([0-3]){1,1}([0-9]){1,1}\/([0-9]){4,4}$/;}
if(stringType=='emal'){re = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;}
if(stringType=='flot'){re = /^\-{0,1}[0-9]{1,6}[\.]{0,1}[0-9]{0,13}$/;}
if(stringType=='gtxt'){re = /^[\nA-Za-z0-9\ \.\-_\(\)\,&!\?\:\;\\'\/\#\$\%\^\*"\@\|]+$/;}
if(stringType=='htxt'){re = /^[\nA-Za-z0-9\ \.\-_\(\)\,&!\?\:\;\\'\/\#\$\%\^\*"\<\>\/\=@]+$/;}
if(stringType=='keyp'){re = /^[A-Za-z0-9\ \.\-_\(\)\,&!\?]+$/;}
if(stringType=='link'){re = /^(?:(?:ftp|https?):\/\/){0,1}(?:[a-z0-9](?:[-a-z0-9]*[a-z0-9])?\.)+(?:com|edu|biz|org|gov|int|info|mil|net|name|museum|coop|aero|mobi|tv|us|[a-z][a-z])\b(?:\d+)?(?:\/[^;"\'<>()\[\]{}\s\x7f-\xff]*(?:[.,?]+[^;"\'<>()\[\]{}\s\x7f-\xff]+)*)?/;}
if(stringType=='ltxt'){re = /^[A-Za-z0-9\ \.\-_\(\)\,&!\?\'\/\;]+$/;}
if(stringType=='mdes'){re = /^[A-Za-z0-9\ \.\-_\(\)\,&!\?]+$/;}
if(stringType=='name'){re = /^([a-zA-Z0-9\ \-\,\.\(\)\/\:\\\']){1,64}$/;}
if(stringType=='numb'){re = /^\-{0,1}([0-9]+)$/;}
if(stringType=='pass'){re = /^.*(?=.{6,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/;}
if(stringType=='phon'){re = /^\(([0-9]){3}\) ([0-9]){3}\-([0-9]){4}$/;}
if(stringType=='ptle'){re = /^[A-Za-z0-9\ \.\-_\(\)\,&!\?\'\;]{3,255}$/;}
if(stringType=='spas'){re = /^([\S]{6,32})$/;}
if(stringType=='stxt'){re = /[^"&<>]/;}
if(stringType=='urls'){re = /^[\nA-Za-z0-9\ \.\-_\(\)\,&!\?\:\;\\'\/\#\$\%\^\*"\@\|=]+$/;}
if(stringType=='user'){re = /^[a-zA-Z0-9]{4,32}$/;}
if(stringType=='zipc'){re = /^[A-Za-z0-9\-]{5,20}$/;}
	goodString = false;

	goodString = re.test(stringToTest);
	if(goodString){
		if(document.getElementById(element+'_valid_image')){
			document.getElementById(element+'_valid_image').src = 'http://visitadirondacks.com/admin/themes/Default/images/form_valid.gif';
		}
		return true;
	}
	else{
		if(document.getElementById(element+'_valid_image')){
			document.getElementById(element+'_valid_image').src = 'http://visitadirondacks.com/admin/themes/Default/images/form_not_valid.gif';
		}
		return false;
	}
}

function validateDescription(stringType){
if(stringType=='blnk'){return 'Any characters are allowed here.';}
if(stringType=='date'){return 'A date must be in the format mm/dd/yyyy.  For example 03/19/1982,';}
if(stringType=='emal'){return 'An email address must contain the @ symbol and a valid domain name; like joe@example.com.';}
if(stringType=='flot'){return 'ption=A floating point number can be a whole number or a decimal like "6" or "5.347834631" (out to 13 decimal places).';}
if(stringType=='gtxt'){return 'General text that can contain most special characters with a few exceptions.  Like "This is my \'Description\'!?".';}
if(stringType=='htxt'){return 'HTML text that can contain most special characters and html tags with a few exceptions.  Like "<b>My Title</b>Here are the options<ul><li>a</li></ul>".';}
if(stringType=='keyp'){return 'Provide a unique phrase or word that best describes the content found on this page. If you wish to use more keyphrases, simply seperate them with a comma.';}
if(stringType=='link'){return 'A Link to a website.  A link must contain the full protocol.  Like "http://www.example.com".';}
if(stringType=='ltxt'){return 'This is the "clickable" link text in a menu or other website navigation object.  In the case of an image link, this text will appear as the image description. Like "My Page Title". Several special characters like &gt; and &lt; are NOT allowed.';}
if(stringType=='mdes'){return 'Provide a concise description of the content found on this page, no more than 155 characters.  Include if appropriote, a couple of the most relevant key phrases within your sentence based statement.';}
if(stringType=='name'){return 'A person\'s name can contain any combination of letters, spaces, dashes, and can be up to 64 characters long. Like Anne, or Smith.';}
if(stringType=='numb'){return 'A whole number containing no decimals, commas, or spaces.  Like 23, -158, or 79932.';}
if(stringType=='pass'){return 'A password must be between 6 and 32 characters long and have at least 1 number, at least one uppercase letter and at least one lowercase letter.';}
if(stringType=='phon'){return 'A phone number must be in the format (555) 555-5555.';}
if(stringType=='ptle'){return 'This is the title that will show up in search engine results, and when users bookmark your page.  You should pick something short and descriptive like "Our Home Page".  It is also the basis for the filename of your page, e.g. "Our Home Page" turns into "Our-Home-Page.html".';}
if(stringType=='spas'){return 'A password must be between 6 and 32 characters long and should consist of as many letters, numbers, and special characters as possible.';}
if(stringType=='stxt'){return 'Text that contains special characters. Like "This is my \'Description\'!?".';}
if(stringType=='urls'){return 'Links to Websites or internal files.';}
if(stringType=='user'){return 'A username must be between 4 and 32 characters long and can consist of numbers and letters; like Matt';}
if(stringType=='zipc'){return 'A zip code most be in the format 12345, 12345-54321, or A1B2C3.';}
	return ''; // no matches
}

function validateForm(formName){
      
      var obj = document.forms[formName]
      deleting = false;
      delre = /delete/;  //regular expression for delete check box
      
      for (i=0; obj.elements[i]; i++) {
            
            currentElement = obj.elements[i].name;
            currentValue = obj.elements[i].value;
            isValid = true;
            
            if(delre.test(currentElement)){
                  if(obj.elements[i].checked==true) deleting = true;
            }
            
            if(currentElement.substr(4,2)=='t-' || currentElement.substr(4,2)=='f-'){
                  stringType = currentElement.substr(0,4);
                  canBeEmpty = currentElement.substr(4,1);
				 
                  if(canBeEmpty=='t'){
                        canBeEmpty = true;
						canBeEmptyDescription = 'You can leave this field empty.';
                  }
                  else if(canBeEmpty=='f'){
                        canBeEmpty = false;
						canBeEmptyDescription = 'You can NOT leave this field empty.';
                  }
                  if(canBeEmpty && document.getElementById(currentElement).value=='') isValid = true;
                  else isValid = validateString(currentElement);
            }
            
            if(!isValid){
                  alert('There is an error with one of your fields!' + '\n' + validateDescription(stringType) + '\n' + canBeEmptyDescription + '\nYou will need to fix this before continuing. ');
                  obj.elements[i].focus();
                  //obj.elements[i].className='formElementError';
                  return false;
                  break;
            }
            else{
                  //obj.elements[i].className='';
            }
      }
      
      if(deleting==true){
            return confirm('You have objects selected for deletion.\n This cannot be undone!\n Are you sure you wish to continue?');
      }
      return true;
}

function formatPhoneNumber(elementID){
	if(document.getElementById(elementID)){
		number_final = '';
		number = document.getElementById(elementID).value;
		for(i=0; i<number.length; i++){
			temp_number = number.substr(i, 1);
			if(isNumber(temp_number)){
				number_final = number_final + temp_number;
			}
		}
		if(number_final.length>7){
			document.getElementById(elementID).value = '(' + number_final.substr(0, 3) + ') ' + number_final.substr(3, 3) + '-' + number_final.substr(6, 4);
		}
	}
}

function roundFloat(floatNum,dec){
	floatNum = parseFloat(floatNum);
    return floatNum.toFixed(dec);
}

function isNumber(number){
    re = /^[0-9\.]+$/;
    return re.test(number);
}

function windowWidth(){
	var myWidth = 0;
	if(typeof(window.innerWidth)=='number'){
		//Non-IE
		myWidth = window.innerWidth;
	}
	else if(document.documentElement && document.documentElement.clientWidth){
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
	}
	else if(document.body && document.body.clientWidth){
		//IE 4 compatible
		myWidth = document.body.clientWidth;
	}
	return myWidth;
}

function windowHeight(){
	var myHeight = 0;
	if(typeof(window.innerHeight)=='number'){
		//Non-IE
		myHeight = window.innerHeight;
	}
	else if(document.documentElement && document.documentElement.clientHeight){
		//IE 6+ in 'standards compliant mode'
		myHeight = document.documentElement.clientHeight;
	}
	else if(document.body && document.body.clientHeight){
		//IE 4 compatible
		myHeight = document.body.clientHeight;
	}
	return myHeight;
}

function setElementSize(elementID, newWidth, newHeight, maximizeWidth, maximizeHeight) {
	if(maximizeWidth){
		newWidth = windowWidth()-25;
	}
	if(maximizeHeight){
		newHeight = windowHeight()-100;
	}
	if(newWidth){
		document.getElementById(elementID).width = newWidth;
	}
	if(newHeight){
		document.getElementById(elementID).height = newHeight;
	}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a && i<a.length && (x=a[i]) && x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

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;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


if(typeof GMap2 != 'undefined')
{
	//-------------------------------------------------------------------------------------------	
	 var map = new GMap2(document.getElementById("map")); 
	 map.addControl(new GLargeMapControl());
	 var point = new GLatLng(44.0,-74.47288);
	 map.setCenter(point,8);
	//-------------------------------------------------------------------------------------------
	// Create our "click" marker icon
	var icon = new GIcon();
	icon.image = "http://visitadirondacks.com/images/map-save-this-location.gif";
	icon.iconSize = new GSize(129, 32);
	icon.iconAnchor = new GPoint(8, 32);
	
	var saveLocationIcon = "";
    
    
    GEvent.addListener(map, 'click', function(overlay, point){
	 if(typeof overlay == "undefined" || overlay== null){ //only check if the save marker was NOT clicked
		 saveTempLocation(point);
	 }
 });
}
 
function saveTempLocation(point)
 {
	map.setCenter(point) ;
	if(saveLocationIcon != ''){
		map.removeOverlay(saveLocationIcon);
	}
	
	var marker = new GMarker(point, icon);
 	
	GEvent.addListener(marker, "click", saveLocation);
	map.addOverlay(marker);
	saveLocationIcon = marker;
 }

function saveLocation()
{	
	var center = map.getCenter();
	var newLati = new String(center.lat());
    var newLongi = new String(center.lng());
    
    
	//test for fields, catch errors
	try{
		opener.document.getElementById("flott-latitude").value = newLati.substr(0,15);
		opener.document.getElementById("flott-longitude").value =  newLongi.substr(0,15);
	}
	catch(e)
	{
		opener.document.getElementById("flott-lati").value =  newLati.substr(1,16);
		opener.document.getElementById("flott-longi").value =  newLongi.substr(1,16);
	}
	//opener.document.forms[0].flott-longitude.value = center.lng();
	close();
}

function updateVideoTitleField(formID){
	var getSelectedIndex = document.getElementById('special').selectedIndex;
	var getSelectedOptionText = document.getElementById('special')[getSelectedIndex].text;
    
    if ( getSelectedOptionText == 'Video' ){
    	document.getElementById('video-admin-title').style.visibility = 'visible';
        document.getElementById('video-admin-title').style.display = 'table-row';
    }
    else {
    	document.getElementById('video-admin-title').style.visibility = 'hidden';
        document.getElementById('video-admin-title').style.display = 'none';
    }
    

}
function eventTrackingDelayed(category,action,label,path,o){
	o.removeAttribute("href");
    //alert('DEBUG');
	pageTracker._trackEvent(category,action,label);
	setTimeout('document.location = "'+path+'" ', 100);
}
function nextPage(pageNum)
{
	var theLocation = new String(document.location)
	var varCheck = theLocation.indexOf("?");
	var placeholder = theLocation.indexOf("currentPage=");
	if(varCheck == -1)//there were no URL vars, so append currentpage and load new url
	{
		document.location = document.location+"?currentPage="+pageNum;
	}
	else if(placeholder != -1)//there was already a currentPage var , get rid of it and reload w/ new page num.
	{
		var tmpLocation = theLocation.slice(0,placeholder);
		document.location = tmpLocation+"currentPage="+pageNum;
	}
	else
	{
		document.location = document.location+"&currentPage="+pageNum;
	}
}
function submitPageNumFor(pageNum)
{
	document.selectPageForm.currentPage.value = pageNum;
	document.selectPageForm.submit();
}
function showHideOthers(current,numRegions){
	for(i=1; i<=numRegions; i++){
    	if ((i!=current) && (document.getElementById("category"+i).style.display=='')){
           	document.getElementById("category"+i).style.display = 'none';
        }
    }
}
