/***** Global variables *****/
g_DEV_PORT = 8888;
if (window.location.port == g_DEV_PORT || window.location.href.indexOf("seamap-dev") > 0 || window.location.href.indexOf("seamap2") > 0) {
	g_DEV = true;
} else {
	g_DEV = false;
}


if (g_DEV) {
	if (window.location.href.indexOf("seamap-dev") > 0 || window.location.href.indexOf("seamap2") > 0) {
		if (window.location.href.indexOf("seamap-dev") > 0) {
			g_ROOT_URL = "http://seamap-dev.env.duke.edu";
		} else if (window.location.href.indexOf("seamap2") > 0) {
			g_ROOT_URL = "http://seamap2.env.duke.edu";
		}
		BASE_PLONE_URL = '/functions/';
		BASE_URL = '/';
	} else {
		g_ROOT_URL = "http://seamap.env.duke.edu:8888";
		BASE_PLONE_URL = '/plone_dev/';
		BASE_URL = '/dev/';
	}
} else {
	g_ROOT_URL = "http://seamap.env.duke.edu";
	//BASE_PLONE_URL = '/';
	BASE_PLONE_URL = '/functions/';
	BASE_URL = '/';
}

/***** Common Javascript Functions *****/
/***** Date/Time format *****/
// Obtained from http://www.codeproject.com/jscript/dateformat.asp
// a global month names array
var gsMonthNames = new Array(
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
);

// a global day names array
var gsDayNames = new Array(
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
);

// the date format prototype
Date.prototype.format = function(f)
{
    if (!this.valueOf())
        return '&nbsp;';

    var d = this;

    return f.replace(/(yyyy|mmmm|mmm|mm|dddd|ddd|dd|hh|nn|ss|a\/p)/gi,
        function($1)
        {
            switch ($1.toLowerCase())
            {
            case 'yyyy': return d.getFullYear();
            case 'mmmm': return gsMonthNames[d.getMonth()];
            case 'mmm':  return gsMonthNames[d.getMonth()].substr(0, 3);
            //case 'mm':   return (d.getMonth() + 1).zf(2);
            case 'mm':   return leading_zero(d.getMonth() + 1);
            case 'dddd': return gsDayNames[d.getDay()];
            case 'ddd':  return gsDayNames[d.getDay()].substr(0, 3);
            //case 'dd':   return d.getDate().zf(2);
            case 'dd':   return leading_zero(d.getDate());
            //case 'hh':   return ((h = d.getHours() % 12) ? h : 12).zf(2);
            case 'hh':   return leading_zero((h = d.getHours() % 12) ? h : 12);
            //case 'nn':   return d.getMinutes().zf(2);
            case 'nn':   return leading_zero(d.getMinutes());
            //case 'ss':   return d.getSeconds().zf(2);
            case 'ss':   return leading_zero(d.getSeconds());
            case 'a/p':  return d.getHours() < 12 ? 'a' : 'p';
            }
        }
    );
}

// This function is called by Date.prototype.format
function leading_zero(value) {
	if (value.toString().length == 1) {
		value = '0' + value.toString();
	}

	return value;
}

/***** Show Terms of Use in a floating DIV
The calling page should have the following DIV tag
<div id="legalese_content"
	style="position:absolute; top:200px; left:300px; display:none;
			background:#dee7ec; width:600px; padding: 20px; border-color:#007700; border-width:1px; border-style:solid;">
</div>

The scripts use AJAX. Thus the calling page should include AJAX-related scripts.
http://seamap.env.duke.edu/mapservice/scripts/identify_browser.js
*****/
function show_terms_of_use() {
	var div = $("termsofuse");
	var winW = GetWindowSize('width');
	var width = Math.min(800, winW * 0.8);
	var left = (winW - width) / 2;
	if (is_ie) {
		var top = getScrollXY()[1] + 10;
	} else {
		var top = document.documentElement.scrollTop + 10;
	}
	div.setStyle({width: width + "px", left: left + "px", top: top + "px"});
	var url = g_ROOT_URL + "/about/";
	if (gSEAMAP2) {
		url += "termsofuse.html";
	} else {
		url += "legalese_content";
	}
	/* legalese_content is populated by page template's TAL: structure context/about/termsofuse.html
	to reduce the initial AJAX calls
	if ($("legalese_content").innerHTML.strip() == "") {
		new Ajax.Updater("legalese_content", url);
	}
	*/
	div.show();
}

function terms_agreed(status) {
	$("termsofuse").hide();
	if (status) {
		var jar = new CookieJar({
			expires:"",   // At the end of session
			path: '/'
		});	
		jar.put('agreed2terms', "true");		
	} else {
		if (gSEAMAP2) {
			window.location.href = g_ROOT_URL + "/about/termsofuse_disagree";
		} else {
			window.location.href = g_ROOT_URL;
		}
	}
	if (typeof(gAgreedToTerms) != "undefined") {
		gAgreedToTerms = status;
	}
	if (typeof(gAgreedToTermsForDownload) != "undefined") {
		gAgreedToTermsForDownload = status;
	}
	return status;
}

function GetWindowSize(type){
    switch(type){
	case "width":
		if(document.all){
			if(document.documentElement && document.documentElement.clientWidth){ // IE
			   return document.documentElement.clientWidth;
			}
			else if(document.body && document.body.clientWidth){
			   return document.body.clientWidth;
			}
		}else if(document.layers){
			return(innerWidth);
		}else{
			return(innerWidth);
			//return(-1);
		}
	break;
	case "height":
		if(document.all){
			if(document.documentElement && document.documentElement.clientHeight){ // IE
				return (document.documentElement.clientHeight);
			}
			else if(document.body && document.body.clientHeight){
		 		return (document.body.clientHeight);
			}
		}else if(document.layers){
			return(innerHeight);
		}else{
			return(innerHeight);
			//return(-1);
		}
	break;
	default:
		return(-1);
	break;
    }
}

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

function isNumeric(x) {
	// I use this function like this: if (isNumeric(myVar)) { }
	// regular expression that validates a value is numeric
	var RegExp = /^[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?\b/; // Note: this WILL allow a number that ends in a decimal: -452.
	// compare the argument to the RegEx
	// the 'match' function returns 0 if the value didn't match
	var result = x.match(RegExp);
	return result;
}

function int_format(a_number, short_format) {
	if (a_number == "") {
		var s = "0";
	} else {
		a_number = parseInt(a_number);
		if (short_format) {
			if (a_number >= 1000000) {
				a_number = a_number / 1000000;
				var s = number_format(a_number, 2, '.', ',') + "M";
			} else if (a_number >= 100000) {
				a_number = a_number / 1000;
				var s = number_format(a_number, 1, '.', ',') + "K";
			} else {
				var s = number_format(a_number, 0, '.', ',');
			}
		} else {
			var s = number_format(a_number, 0, '.', ',');
		}
	}
	return s;
}

// number_format is copied from php.js.
// consider including this function in common.js or include php.js itself.
function number_format( number, decimals, dec_point, thousands_sep ) {
    // Format a number with grouped thousands
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/
    // +       version: 804.1712
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://crestidg.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)    
    // *     example 1: number_format(1234.5678, 2, '.', '');
    // *     returns 1: 1234.57     

    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "," : dec_point;
    var t = thousands_sep == undefined ? "." : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}// }}}

function radio_value(form_name, radio_name) {
	var value = Form.getInputs(form_name,'radio',radio_name).find(function(radio) { return radio.checked; }).value;

	return value;
}

function wait(miliseconds) {
	var date = new Date();
	var curDate = null;

	do {
		curDate = new Date();
	} while(curDate-date < miliseconds);
}

/***** XML Utility *****/
function getXmlNodeValue(xml, node_name) {
	if (xml.getElementsByTagName(node_name).length > 0) {
		if (xml.getElementsByTagName(node_name)[0].childNodes.length > 0) {
			var value = xml.getElementsByTagName(node_name)[0].childNodes[0].nodeValue;
		} else {
			var value = "";
		}
	} else {
		var value = "";
	}

	return value;
}