/*The following functions are common functions used throughout the SLIM site:

Common_Go_Back - go back (or forward) the specified number of pages
Common_Check - check or uncheck all the specified (parameter) checkboxes
Common_getRadioButtonValue - Get checked value from radio button.
Common_handleChangeEventFunction - check the associated radio button (when an item in the associated list box is selected)
Common_ForceEntry - force a value to be entered in the specified(parameter) text box
Common_isWhitespace - check whether any valid text is in the string
Common_isEmpty - check whether string is empty
Common_ShowCalendar - display calendar page and return value to specified text box
Common_StreetLookup - (same as StreetLookup, but allows flexibility in form name and location of source page)
Common_open_new_win - pass in an url, height,width,x,y and a pop up window opens

Currently most of the SLIM pages that used the above functions have them physically included in the
page.  As SLIM pages are edited - they should be also modified to remove the local copies of these functions and
instead reference this file as shown in the following line of code:
<SCRIPT Language = "Javascript" SRC="global/slim.js"></SCRIPT>
*/
// This include file is a library of client-side Javascript functions used in SLIM pages

// To reference the following in your code, qualify the property with top (top.RunningIE55 ...)
window.Browser = getBrowser();
window.RunningIE = (window.Browser == "Internet Explorer");
window.Version = getVersion();
window.RunningMacIE = (window.RunningIE && (window.OS == "Macintosh 68K" || window.OS == "Macintosh PPC"));
window.RunningIE55 = (window.RunningIE && window.Version == "5.5");
window.mapWidth = null;
window.gObjMapView = null;	//used for svg support on windows IE

if (navigator.javaEnabled() < 1) window.java_enabled  = false;
if (navigator.javaEnabled() == 1) window.java_enabled  = true;


//go back (or forward) the specified number of pages
function Common_Go_Back(intNumberOfPages)
{
	window.history.go(intNumberOfPages);
}

//check or uncheck all the specified (parameter) checkboxes
function Common_Check(obj, Ischecked)
{
  if(!obj.length)
		obj.checked = Ischecked;
	else
	{
		for (var i=0; i < obj.length; i++) 
		{			
			obj[i].checked = Ischecked;
		}
	}		
}

// Get checked value from radio button.
function Common_getRadioButtonValue (radio)
{   
	var blnReturn = false;
	for (var i = 0; i < radio.length; i++)
    {   if (radio[i].checked) 
		{ 
			blnReturn = true;
			break; 
		}
    }
    if (blnReturn)
		return radio[i].value
	else
		return false;
}

// check the associated radio button (when an item in the associated list box is selected)
function Common_handleChangeEventFunction(obj)
// Change the radio button here
{ 
  obj[1].checked = true;
}


/***********************************************************************************/

var Common_whitespace = " \t\n\r";

/***********************************************************************************/

// Check whether string s is empty
function Common_isEmpty (s)
{ return ((s == null) || (s.length == 0))  }

/***********************************************************************************/

//check whether any valid text is in the string
 function Common_isWhitespace (s) 
{
  var i; 

  // Is s empty? 
  if (Common_isEmpty(s)) return true; 

  for (i = 0; i < s.length; i++)
  {
     var c = s.charAt(i);

     if (Common_whitespace.indexOf(c) == -1) return false; 
  }

  // All Characters are whitespace
  return true;
}

//force a value to be entered in the specified(parameter) text box
function Common_ForceEntry(val, str) 
{
     var strInput = new String(val.value); 
     
     if (Common_isWhitespace(strInput)) 
     {
         alert(str);
         return false;
     } 
     else 
         return true;
}

//display calendar page and return value to specified text box
function Common_ShowCalendar(obj,strPathToCalendar)
{
	var d;
	d = window.showModalDialog(strPathToCalendar + "?InitialDate=" + obj.value, null,"dialogheight:224px;dialogwidth:280px;status:no;resizable:no;help:no;");
	if (typeof(d) != "undefined")
	{
		obj.value = d;
	}
}

function Common_StreetLookup(strname,strValue,strUrl,strFormName)
{
	var strQS = "Type=Street&Name=" + escape(strname) + "&Value=" + escape(strValue) + "&frmName=" + escape(strFormName);
	if(strUrl.indexOf("?") > 0)
		strQS = "&" + strQS;
	else
		strQS = "?" + strQS;
	window.open(strUrl + strQS,"StreetLookup","menubar=no,location=no,resizable=no,scrollbars=no,width=400,height=200")
}

function Common_open_new_win(urlto_gotto,width,height,x,y)
{
	MyWindow = window.open(urlto_gotto, "CommonWindow", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=" + width + ",height=" + height + " dependent=yes,screenX=" + x + ",screenY=" + y);
}


// alert("Browser is " + window.Browser + "\n" + "Version is " + window.Version + "\n" + "OS is " + window.OS);
// alert("java_enabled is " + window.java_enabled);

// Determine the browser name and version
function getBrowser()
{
  var ua = navigator.userAgent;
  if (ua.indexOf("MSIE ") > 0) 
  {  
		return "Internet Explorer";
  } 
  else 
  { 
		if(ua.indexOf("Safari") > 0)
			return "Safari";
		else
			return "Netscape Navigator";
  }
}

// Determine the major and minor version numbers
function getVersion()
{
  if (window.RunningIE) {  // is Microsoft Internet Explorer
    var ua = navigator.userAgent;
    var msie_pointer = ua.indexOf("MSIE ");
    return ua.substring ( msie_pointer+5, ua.indexOf ( ";", msie_pointer ) );
//  Not returning float cuz 4 beta is 4.b or 4.p
//  return parseFloat ( ua.substring ( msie_pointer+5 ) );
  } else { // is other browser
    var bNum  = parseFloat(navigator.appVersion);
  	if (bNum >= 3) return bNum;
    else return 2;
  }
}

// Display string s in status bar.
function setStatus(s)
{   window.status = s;
}

// Retuns today's date.
function getDate() {
  var now = new Date();
  // alert(now.toString()); -- Thu Feb 19 14:09:50 Mountain Standard Time 1998
  var locale = now.toLocaleString();
  return locale;
}

// Get checked value from radio button.
function getRadioButtonValue (radio)
{
   for (var i = 0; i < radio.length; i++)
    {   if (radio[i].checked) { break }
    }
    return radio[i].value;
}

// Create array constructor
// One could call Array() instead except this is not available in Netscape Navigator 2.0
// To instantiate it in your code: var m_list = new top.array_object();
// Array object declaration
function array_object() {
  this.size = 0;
  this.add = addElement;
  this.clear = clearElements;
  this.exists = existsElement;
  this.find = findElement;
  return this;
}
// Adds an element to the array and increments the size
function addElement(theElement) {
  var idx = this.find(theElement);
  if (idx == -1) {
    this[this.size++] = theElement;
  } else {
    this[idx].checked = theElement.checked;
  }
}
// Sets each element in the array to a null string
function clearElements() {
  for (i = 0; i < this.size; i++) {
    this[i] = null;
  }
  this.size = 0;
}
// Returns true if the element is in the array, or false if it is not
function existsElement(theElement) {
  var found = false;
  var i;
  for (i = 0; i < this.size && !found; i++) {
    found = (this[i] == theElement);
  }
  return found;
}
// Returns index if the element is in the array, or -1 if it is not
function findElement(theElement) {
  var found = false;
  var i;
  for (i = 0; i < this.size && !found; i++) {
    found = (this[i] == theElement);
  }
  if (found) {
    return i - 1;
  } else {
    return -1;
  }
}

//------------------------------------------------------------
//  Opens the legend window (address specified by urlto_gotto
//------------------------------------------------------------

function open_new_win(urlto_gotto)
{
	MyWindow = window.open(urlto_gotto, 'Legend', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=300,height=200 dependent=yes,screenX=200,screenY=200');
}

//------------------------------------------------------------
//  Calls the Save Layer page which then calls the create map page with the passed in url
//------------------------------------------------------------
function CommonCreateMap1(strMapToCreate)
{
	var dtDate = new Date();
	//check that the frame exists and all that before trying to access it
	
	if (top.frames["layers"]!=null)			
		if(top.frames["layers"].document)		
			//forces Netscape to try again until frmHidden is sited on page			
				if(top.frames["layers"].document.frmHidden)
				{					
					//this forces the querystring to be different each time and
					//forces netscape to refresh the page (sometimes netscape inores the response.expires command)
					if (strMapToCreate !='')
						strMapToCreate +="&Date=" + escape(dtDate)
											
					//now force a submit on the layers page to ensure the layers are all up to date
					if (top.frames["layers"].Submit(true,strMapToCreate))
					{								
						top.frames["layers"].document.frmHidden.submit();
					
					}
				}
				else
				{
					window.setTimeout("CommonCreateMap('" + strMapToCreate + "')", 500, "javascript");
				}
}

function CommonCreateMap(strMapToCreate, relative)
{	
	if (relative == null)
		relative = "../";

	if (relative == "nil")
		relative = "";
		
	var dtDate = new Date();					
	//this forces the querystring to be different each time and
	//forces netscape to refresh the page (sometimes netscape inores the response.expires command)
	if (strMapToCreate !='')
		strMapToCreate +="&Date=" + escape(dtDate)

	ToggleSVGProgressBar(true);
	top.frames["hidden"].location.href = relative + "Get_Map.asp?" + strMapToCreate;	
}

function ToggleSVGProgressBar(on)
{
	if (top.gObjMapView != null)		
	{		
		if (on)
			top.gObjMapView.showProgressBar();
		else
			top.gObjMapView.hideProgressBar();
	}
}
//------------------------------------------------------------
//  Displays the assessment disclaimer
//------------------------------------------------------------

function ShowAssessmentDisclaimer()
{
	var bReturn = window.confirm("The information is collected for property assessment interpretation purposes only.\nThe City of Edmonton does not warrant or guarantee the completeness and accuracy of the information presented. \nThe City of Edmonton does not assume responsibility nor accept any liability arising from any use of the information other than for property assessment interpretation. \nThis information is proprietary to the City of Edmonton and may not be reproduced without the express written consent of the City of Edmonton.")
	return bReturn
}

function Disclaimer(bStatic,strPage,strPath)
{
	ViewDisclaimer(bStatic,strPage,strPath);	
}

function ViewDisclaimer()
{
	var message = "The City of Edmonton takes reasonable measures to provide accurate information in the following maps and screens but the City of Edmonton does not warrant the completeness or accuracy of the information presented. \n\n"   
	message += "The City of Edmonton does not assume responsibility nor accept any liability arising from any use of the information presented.  The information presented is intended to serve only as a first step in researching the land use status of a parcel of property.  You are advised not to rely on the"  
	message += " information presented in the maps alone.  Please contact the Planning and Development Department for up to date and accurate information on the land use provisions that apply to a particular property. \n\n"
	message += "Press the OK button if you acknowledge having read and agree to this disclaimer, otherwise select Cancel."
	var result = window.confirm(message);
	if (!result)	
	{
		alert("Cannot enter site without accepting disclaimer");	
	}
	else
	{
		if(arguments.length == 3)
			top.window.location = arguments[2] + "?Static=" + arguments[0] + "&Page=" + arguments[1];
	}
	return result; 	
}

function StreetLookup(strname)
{
	var strValue= document.forms.SearchType.elements[strname].value;
	var strRoot = top.location.toString();
	if(strRoot.indexOf("Scripts") > 0)
		strRoot = strRoot.substring(0,strRoot.indexOf("Scripts"));
	window.open(strRoot + "global/Lookup/Lookup.asp?Type=Street&Name=" + escape(strname) + "&Value=" + escape(strValue),"StreetLookup","menubar=no,location=no,resizable=no,scrollbars=no,width=400,height=200")
}

function NamedLocationLookup(strRoot)
{
	var strValue= document.forms.SearchType.elements["namedLocation"].value;
	window.open(strRoot + "global/Lookup/Lookup.asp?Type=Named%20Location&Value=" + escape(strValue),"NamedLocationLookup","menubar=no,location=no,resizable=yes,scrollbars=yes,width=400,height=200")
}

// create trim, ltrim and rtrim functions as part of the String object
String.prototype.ltrim=new Function("return this.replace(/^\\s+/,'')")
String.prototype.rtrim=new Function("return this.replace(/\\s+$/,'')")
String.prototype.trim=new Function("return this.replace(/^\\s+|\\s+$/g,'')")

function IsLegalInput(src)
{
	//returns true if all characters are permissable
	var regex=new RegExp("[a-zA-Z][0-9]*$", "i");
	return regex.test(src.trim());
}

/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "-";
var minYear=1900;
var maxYear=2100;
var daysInMonth = new Array(12);

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function SetDaysArray(n) {
	for (var i = 1; i <= n; i++) {
		daysInMonth[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {daysInMonth[i] = 30}
		if (i==2) {daysInMonth[i] = 29}
   } 
}

function GetMonthFromName(strMonthName)
{
	var strMonth;
	
	switch(strMonthName)
	{
		case "JAN":
			strMonth = "1";
			break;
		case "FEB":
			strMonth = "2";
			break;
		case "MAR":
			strMonth = "3";
			break;
		case "APR":
			strMonth = "4";
			break;
		case "MAY":
			strMonth = "5";
			break;
		case "JUN":
			strMonth = "6";
			break;
		case "JUL":
			strMonth = "7";
			break;
		case "AUG":
			strMonth = "8";
			break;
		case "SEP":
			strMonth = "9";
			break;
		case "OCT":
			strMonth = "10";
			break;
		case "NOV":
			strMonth = "11";
			break;
		case "DEC":
			strMonth = "12";
			break;
		default:
			strMonth = "13";		
	}
	return strMonth;
}

function isInteger(s){
 
    for (var i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);       
        if ((c < "0") || (c > "9")) 
			return false;			
    }
    // All characters are numbers.  
    return true;
}

function isDate(dtStr){
	SetDaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strDay=dtStr.substring(0,pos1);
	var strMonthName=dtStr.substring(pos1+1,pos2);
	var strYear=dtStr.substring(pos2+1);
	var strMonth = GetMonthFromName(strMonthName.toUpperCase());
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : dd-mmm-yyyy");
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month abbreviation (i.e AUG)");
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day");
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || !isInteger(strDay) || !isInteger(strYr)){
		alert("Please enter a valid date");
		return false
	}
return true
}

function isValidFromToDate(dtFromDate,dtToDate)
{
	var isValid = false;
	var pos1;
	var pos2;
	var i;
	var strFromDay;
	var strFromMonthName;
	var strFromYear;
	var strFromYr;
	var strFromMonth;
	var strToDay;
	var strToMonthName;
	var strToYear;
	var strToYr;
	var strToMonth;
	var frommonth;
	var tomonth;
	var fromday;
	var today;
	var fromyear;
	var toyear;
	
	pos1=dtFromDate.indexOf(dtCh)
	pos2=dtFromDate.indexOf(dtCh,pos1+1)
	strFromDay=dtFromDate.substring(0,pos1)
	strFromMonthName=dtFromDate.substring(pos1+1,pos2)
	strFromYear=dtFromDate.substring(pos2+1)
	strFromMonth = GetMonthFromName(strFromMonthName.toUpperCase())
	
	strFromYr=strFromYear
	if (strFromDay.charAt(0)=="0" && strFromDay.length>1) strFromDay=strFromDay.substring(1)
	if (strFromMonth.charAt(0)=="0" && strFromMonth.length>1) strFromMonth=strFromMonth.substring(1)
	for (i = 1; i <= 3; i++) {
		if (strFromYr.charAt(0)=="0" && strFromYr.length>1) strFromYr=strFromYr.substring(1)
	}
	
	frommonth=parseInt(strFromMonth)
	fromday=parseInt(strFromDay)
	fromyear=parseInt(strFromYr)
	
	pos1=dtToDate.indexOf(dtCh)
	pos2=dtToDate.indexOf(dtCh,pos1+1)
	strToDay=dtToDate.substring(0,pos1)
	strToMonthName=dtToDate.substring(pos1+1,pos2)
	strToYear=dtToDate.substring(pos2+1)
	strToMonth = GetMonthFromName(strToMonthName.toUpperCase())
	
	strToYr=strToYear
	if (strToDay.charAt(0)=="0" && strToDay.length>1) strToDay=strToDay.substring(1)
	if (strToMonth.charAt(0)=="0" && strToMonth.length>1) strToMonth=strToMonth.substring(1)
	for (i = 1; i <= 3; i++) {
		if (strToYr.charAt(0)=="0" && strToYr.length>1) strToYr=strToYr.substring(1)
	}
	
	tomonth=parseInt(strToMonth)
	today=parseInt(strToDay)
	toyear=parseInt(strToYr)
	if (toyear>fromyear ||(toyear==fromyear && tomonth>frommonth)||(toyear==fromyear && tomonth==frommonth && today>=fromday))
		isValid = true;
	else
		alert("To Date must be greater than or equal to From Date")

	return isValid;

}

function HotSpot(strUrl, strFrame)
{	
	//need to strip out quotes added by xml in svg - Perry

	var re = new RegExp('"', 'gi');
	var strNewFrame = strFrame.replace(re, '');

	strFrame = strNewFrame.trim();		
	strUrl = strUrl.trim();		

	//need to prefix first parameter with ? and subsequent with &
	strUrl = strUrl.replace("?","&");	//convert all ? to &
	var position = strUrl.search("&");
		
	if (position > 0)
		strUrl = strUrl.substr(0, position) + "?" + strUrl.substr(position + 1, strUrl.length);
		
	if (strUrl !='')
	{	
		top.frames[strFrame].location.href = strUrl;																				
	}		
}

function SaveLayer(layer, on)
{
	top.frames["hidden"].location.href = "Save_SVG_Layer.asp?layer=" + layer + "&save=" + on;
}

function CreateXmlHttp()
{
	var XmlHttp;
    //Creating object of XMLHTTP in IE
    try
    {
        XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
        try
        {
            XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(e)
        {
            XmlHttp = null;
        }
    }
    //Creating object of XMLHTTP in Mozilla and Safari
    if(!XmlHttp)
    {
		if(typeof XMLHttpRequest != "undefined")
			XmlHttp = new XMLHttpRequest();
    }
    return XmlHttp;
}

function getOpera()
{
	var bReturn = false;
	var strNav = navigator.userAgent.toUpperCase();
	var iOP;
	var strChar;
	var strVer = "";
	if(strNav.indexOf("OPERA") >= 0)
	{
		iOP = strNav.indexOf("OPERA")+6;
		for(var x = iOP; x<strNav.length;x++)
		{
			strChar = strNav.charAt(x);
			if(!isNaN(strChar) || strChar == ".")
			{
				strVer += strChar;
			}
			if(strChar == " ")
				x=strNav.length;
		}
		if(parseFloat(strVer) >= 9.23)
			bReturn = true;
	}
	return bReturn;
}
