//sorting functions

currentCol = 0
previousCol = -1

function CompareAlpha(a, b) {
	if (a[currentCol] < b[currentCol]) { return -1; }
	if (a[currentCol] > b[currentCol]) { return 1; }
	return 0;
}

function CompareAlphaIgnore(a, b) {
	strA = a[currentCol].toLowerCase();
	strB = b[currentCol].toLowerCase();
	if (strA < strB) { return -1; }
	else {
		if (strA > strB) { return 1; }
		else { return 0; }
	}
}

function CompareDate(a, b) {
	datA = new Date(a[currentCol]);
	datB = new Date(b[currentCol]);
	
	if(isNaN(datA) && isNaN(datB))return 0;
	else if(isNaN(datA)) return -1;
	else if(isNaN(datB)) return 1;
	
	if (datA < datB) { return -1; }
	else {
		if (datA > datB) { return 1; }
		else { return 0; }
	}
}

function CompareTime(a, b) {
	var hourA;
	var hourB;
	var AMPM;
	strA = a[currentCol].split(":");
	strB = b[currentCol].split(":");	
	AMPMstrA = strA[2].substring(3,5); 	
	AMPMstrB = strB[2].substring(3,5); 	
	if (AMPMstrA == "PM")
	{
		hourA = (parseInt(strA[0]) + 12);
	//	alert(hourA);
	}
	else 
	{
		hourA = parseInt(strA[0]);
	}
	if (AMPMstrB == "PM")
	{
		hourB = (parseInt(strB[0]) + 12);
	}
	else 
	{
		hourB = parseInt(strB[0]);
	}

	datA = new Date("01", "01", "01", hourA, strA[1], strA[2].substr(0,2));
	datB = new Date("01", "01", "01", hourB, strB[1], strB[2].substr(0,2));
	if (datA < datB) { return -1; }
	else {
		if (datA > datB) { return 1; }
		else { return 0; }
	}
}


function CompareDateEuro(a, b) {
	strA = a[currentCol].split(".");
	strB = b[currentCol].split(".");
	datA = new Date(strA[2], strA[1], strA[0]);
	datB = new Date(strB[2], strB[1], strB[0]);
	if (datA < datB) { return -1; }
	else {
		if (datA > datB) { return 1; }
		else { return 0; }
	}
}

function CompareNumeric(a, b) {
	numA = a[currentCol];
	numB = b[currentCol];
	if(isNaN(numA) && isNaN(numB))return 0;
	else if(isNaN(numA)) return -1;
	else if(isNaN(numB)) return 1;
	else return (numA - numB);
}

function changeImage(table,colNo){
	var cols=table.rows(0).cells.length;
	var currImg="document.sortImage"+colNo+".src";
	var imgSrc=eval(currImg);
	var otherImg;
	var imgName;
	var isDesc=false;
	var pos=imgSrc.lastIndexOf("/");
	
	imgName=imgSrc.substring(pos+1,imgSrc.length);
	if(imgName=="bulletUnselected.gif"){
		imgSrc="images/bulletRotated.gif";
	}else if(imgName=="bulletRotated.gif"){
		isDesc=true;
		imgSrc="images/bulletDescending.gif";
	}else if(imgName=="bulletDescending.gif"){
		imgSrc="images/bulletRotated.gif";
	}
	eval(currImg+"='"+imgSrc+"'");
	
	if(previousCol >=0 && previousCol!=colNo){
		otherImg="document.sortImage"+previousCol+".src='images/bulletUnselected.gif'";
		eval(otherImg);
	}
	return isDesc;
}

function sortTable(table,colNo){
	var rowCount;
	var colCount;
	var isSortDesc=false;
	
	rowCount=table.rows.length;
	if(rowCount <=0) return false;

	colCount = table.rows(0).cells.length;
	if(colCount <=0 || colNo >=colCount) return false;

	isSortDesc=changeImage(table,colNo);
	dataType=eval("document.sortImage"+colNo+".dataType");
	sortData(table,colNo,dataType,isSortDesc);
	
	return false;
}

function refreshSort(table){
	var colCount;
	var rowCount;
	
	rowCount=table.rows.length;
	if(rowCount <=0) return false;
	
	colCount = table.rows(0).cells.length;
	if(colCount <=0) return false;
	
	var currImg;
	var imgSrc;
	var pos;
	var imgName;
	var dataType;
	var isDesc=false;
	
	for(i=0;i < colCount;i++){
		if(eval("parent.document.sortImage"+i) !="[object]") continue
		
		currImg="parent.document.sortImage"+i+".src";
		imgSrc=eval(currImg);
		pos=imgSrc.lastIndexOf("/");
		imgName=imgSrc.substring(pos+1,imgSrc.length);
		if(imgName=="bulletUnselected.gif"){
			continue;
		}else if(imgName=="bulletDescending.gif"){
			isDesc=true;
		}
		dataType=eval("parent.document.sortImage"+i+".dataType");
		sortData(table,i,dataType,isDesc);
		break;
	}
	return;
}

function sortData(table,colNo,dataType,isSortDesc){
	var rowCount;
	var colCount;
	var bArray;
	var oldIndex;
	var bSort;

	rowCount=table.rows.length;
	if(rowCount <=0) return false;

	colCount = table.rows(0).cells.length;
	if(colCount <=0 || colNo >=colCount) return false;
	
	bArray=new Array();
	oldIndex = new Array();
	bSort = false;
	
	currentCol = colNo;
	sortArray = new Array(rowCount);
	htmlArray=new Array(rowCount);

	
	for (i=0; i < rowCount; i++) {
		sortArray[i] = new Array(colCount);
		htmlArray[i]=new Array(colCount);
		for (j=0; j < colCount; j++) {
			sortArray[i][j] = table.rows(i).cells(j).innerText;
			htmlArray[i][j] = table.rows(i).cells(j).innerHTML;
		}
	}
	
   for (i=0; i < sortArray.length; i++){
	   bArray[i] = sortArray[i][currentCol];
   }
	  
	switch (dataType) {
		case "A":		
			sortArray.sort(CompareAlpha);
			break;
		case "AI":
			sortArray.sort(CompareAlphaIgnore);
			break;
		case "D":
			sortArray.sort(CompareDate);
			break;
		case "DE":
			sortArray.sort(CompareDateEuro);
			break;
		case "N":
			sortArray.sort(CompareNumeric);
			break;
		case "T":
			sortArray.sort(CompareTime);
			break;
		default:
			sortArray.sort();
	}
	
	if(isSortDesc) sortArray.reverse();
	
 	for (i=0; i < sortArray.length; i++) { 
        for(j=0; j < bArray.length; j++) {
            if (sortArray[i][currentCol] == bArray[j]) {
                for (c=0; c<i; c++)  if (oldIndex[c] == j) bSort=true;
                if (!bSort) oldIndex[i] = j;
	            bSort = false;
            }
        }
    }

	for (i=0; i < rowCount; i++) {
		for (j=0; j < colCount; j++) {
			table.rows(i).cells(j).innerHTML = htmlArray[oldIndex[i]][j];
		}
	}
	previousCol = colNo;
	
	return;
}
//sorting functions end

function verifyUrl(urlObject) {
	var urlString = urlObject.value;
	var dotCounter = 0;
	var badUrl = false;
	
	if(urlString.substring(0,7).toUpperCase() != "HTTP://")
	{
		badUrl = true;
	}
	for(i = 0;i<(urlString.length);i++)
	{
		if(urlString.substr(i,1) == ".")
		{
			dotCounter++;
		}

	}
	if(dotCounter < 2)
	{
		badUrl = true;
	}
	if(badUrl == true)
	{
		alert("Error: You have entered an invalid URL.  The URL must start with ''http://''.");
		return false;
	}
	return true;
}

function isEmailValid(emailObject) {
		var emailAddress = emailObject.value;
		var goodEmail = true;
		var at="@";
		var dot=".";
		var lat=emailAddress.indexOf(at);
		var lstr=emailAddress.length;
		var ldot=emailAddress.indexOf(dot);
		if (emailAddress.indexOf(at)==-1){
			goodEmail = false;
		}

		if (emailAddress.indexOf(at)==-1 || emailAddress.indexOf(at)==0 || emailAddress.indexOf(at)==lstr){
			goodEmail = false;
		}

		if (emailAddress.indexOf(dot)==-1 || emailAddress.indexOf(dot)==0 || emailAddress.indexOf(dot)==lstr){
			goodEmail = false;
		}

		 if (emailAddress.indexOf(at,(lat+1))!=-1){
			goodEmail = false;
		 }

		 if (emailAddress.substring(lat-1,lat)==dot || emailAddress.substring(lat+1,lat+2)==dot){
			goodEmail = false;
		 }

		 if (emailAddress.indexOf(dot,(lat+2))==-1){
			goodEmail = false;
		 }
		
		 if (emailAddress.indexOf(" ")!=-1){
			goodEmail = false;
		 }

		 if (goodEmail == false) {
		 	alert("Error: You have entered an invalid email address.");
			emailObject.select();
			emailObject.focus();
		    return false;
		}
		else {
			return true;					
		}
}
/************************************************************************************************************** 
* Validate Numeric Fields Functions								BEGIN OF SECTION								  
**************************************************************************************************************/

function checkNumeric(objName,minval, maxval,comma,period,hyphen,fieldName)
{
	var numberfield = objName;
	if (chkNumeric(objName,minval,maxval,comma,period,hyphen,fieldName) == false)
	{
		numberfield.select();
		numberfield.focus();
		return false;
	}
	else
	{
		return true;
	}
}

function chkNumeric(objName,minval,maxval,comma,period,hyphen,fieldName)
{
// only allow 0-9 be entered, plus any values passed
// (can be in any order, and don't have to be comma, period, or hyphen)
// if all numbers allow commas, periods, hyphens or whatever,
// just hard code it here and take out the passed parameters
var checkOK = "0123456789" + comma + period + hyphen;
var checkStr = objName;
var allValid = true;
var decPoints = 0;
var allNum = "";
var formFieldName = "";

for (i = 0;  i < checkStr.value.length;  i++)
{
ch = checkStr.value.charAt(i);
for (j = 0;  j < checkOK.length;  j++)
if (ch == checkOK.charAt(j))
break;
if (j == checkOK.length)
{
allValid = false;
break;
}
if (ch != ",")
allNum += ch;
}
if (!allValid)
{
if(fieldName == "")
	formFieldName = checkStr.name;
else
	formFieldName = fieldName;
	
alertsay = "Error: Please enter only these values \""
alertsay = alertsay + checkOK + "\" in the \"" + formFieldName + "\" field."
alert(alertsay);
return (false);
}

// set the minimum and maximum
var chkVal = allNum;
var prsVal = parseInt(allNum);
if (chkVal != "" && !(prsVal >= minval && prsVal <= maxval))
{
alertsay = "Error: Please enter a value greater than or "
alertsay = alertsay + "equal to \"" + minval + "\" and less than or "
alertsay = alertsay + "equal to \"" + maxval + "\" in the \"" + checkStr.name + "\" field."
alert(alertsay);
return (false);
}
}

/************************************************************************************************************** 
* Validate Numeric Fields Functions								END OF SECTION								  
**************************************************************************************************************/



function isFieldBlank(object, objectType, alertSwitch, fieldName)
{
	if(objectType == "select")
		tempString = object.options[object.selectedIndex].value;	
	else
		tempString = object.value;	

	var counter = 0;
	for (i = 0;i < tempString.length;i++)
	{
		if (tempString.substr(i,1) != ' ')
		{
			counter++;
		}
	}
	if(counter > 0)
		return false; //Indicates the field is not blank
	else {
		if(alertSwitch == "On") {
			if(fieldName == "")
			{
		        alert( "Error: ''" + object.name + "'' field must be entered." );
			}
			else
			{
				alert( "Error: ''" + fieldName + "'' field must be entered." );
			}
		}
   	    object.focus();
		return true; //Indicates the field is blank		
	}
}

function isRightSize(fieldObject, stringSize, fieldName, alertSwitch)
{
	var counter = 0;
	var rightSize = '';
	for (i = 0;i < fieldObject.value.length;i++)
	{
		if (fieldObject.value.substr(i,1) != ' ')		
			counter++;
		else
			counter = counter - 100
	}
	if(counter >= stringSize)
		rightSize = 'Yes';
	else {
		if(alertSwitch = 'On') {
	        alert('Error: "' + fieldName + '" field must be at least ' + stringSize + ' digits long with no spaces and must consist of either numbers and/or characters.');
    	    fieldObject.focus();
		}
		rightSize = 'No';	
	}	
	return rightSize;			
}

function floor(number)
{
  return Math.floor(number*Math.pow(10,2))/Math.pow(10,2);
}

function dosum()
{
  var mi = document.temps.IR.value / 1200;
  var base = 1;
  var mbase = 1 + mi;
  for (i=0; i<document.temps.YR.value * 12; i++)
  {
    base = base * mbase
  }
  document.temps.PI.value = floor(document.temps.LA.value * mi / ( 1 - (1/base)))
  document.temps.MT.value = floor(document.temps.AT.value / 12)
  document.temps.MI.value = floor(document.temps.AI.value / 12)
  var dasum = document.temps.LA.value * mi / ( 1 - (1/base)) +
	document.temps.AT.value / 12 + 
	document.temps.AI.value / 12;
  document.temps.MP.value = floor(dasum);
}

function openWindow(url,target,width,height,resizable,scrollbars)
{
	target = Math.round(Math.random( ) * 10000);
	var features = "scrollbars=yes,width=" + width + ",height=" + height + ",resizable=" + resizable + ",scrollbars=" + scrollbars;	
	window.open(url,target,features);
	return false;
}

function viewNextPID( propertyID )
{
	window.document.forms[0].listingPID.value = propertyID;
	window.document.forms[0].submit();	
	return false ;
}

function backToPIDList()
{
	window.document.forms[0].action = "HomeSearchListing.asp"	
	window.document.forms[0].submit();	
	return false ;
}

function submitForm( indexList )
{
	window.document.forms[0].indexList.value = indexList;
	window.document.forms[0].submit();
	return false ;
}

function viewDetails( propertyID )
{
	window.document.forms[0].listingPID.value = propertyID;
	window.document.forms[0].action = "HomeListing.asp";
	window.document.forms[0].submit();	
	return false ;
}

function closeWindow(){
	window.close();
}

function goToHomeListing(propertyID){
	window.location = "HomeListing.asp?listingPID=" + propertyID
}

/************************************************************************************************************** 
* Function: Date & Time Functions										START 								  
* Description: Validates that valid dates are entered
**************************************************************************************************************/

function  isDateValid(dateObject, fieldLabel, allowPastDates) {
	if(isFieldBlank(dateObject,"text", "On",fieldLabel) == true) {
		return false
	}
	else {
		if (chkdate(dateObject) == false) {
			alert("Error: ''" + fieldLabel + "'' field must be populated with a valid date. (MM/DD/YYYY)");
			dateObject.focus();
			return false; //Indicates it is not a valid date
		}
		else {			
				if (allowPastDates == false) {
					var eventYear = getYearMonthDay(dateObject.value,"Year");
					var eventMon = getYearMonthDay(dateObject.value,"Month");
					var eventDay = getYearMonthDay(dateObject.value,"Day");		
					var eventDate = new Date(eventYear,eventMon,eventDay);
					var todayDate = new Date();
					if(todayDate > eventDate) {
						//Indicates date is not valid because it is in the past
						alert("You have entered a date that has already passed. Please select another date.");
						dateObject.focus();
						return false;
					} else {
						return true; 
					}
				} else {
					return true;
				}
		}
	}
}

function chkdate(dateObject) {
	var strDatestyle = "US"; //United States date style
	var strDate;
	var strDateArray;
	var strDay;
	var strMonth;
	var strYear;
	var intday;
	var intMonth;
	var intYear;
	var booFound = false;
	var datefield = dateObject;
	var strSeparatorArray = new Array("-"," ","/",".");
	var intElementNr;
	var err = 0;
	var strMonthArray = new Array(12);
	strMonthArray[0] = "Jan";
	strMonthArray[1] = "Feb";
	strMonthArray[2] = "Mar";
	strMonthArray[3] = "Apr";
	strMonthArray[4] = "May";
	strMonthArray[5] = "Jun";
	strMonthArray[6] = "Jul";
	strMonthArray[7] = "Aug";
	strMonthArray[8] = "Sep";
	strMonthArray[9] = "Oct";
	strMonthArray[10] = "Nov";
	strMonthArray[11] = "Dec";
	strDate = datefield.value;
	if ((strDate.length < 5) || (strDate.length > 10 )) {
		return false;
	}
	for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {			
		if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
			strDateArray = strDate.split(strSeparatorArray[intElementNr]);
			if (strDateArray.length != 3) {
				err = 1;
				return false;
			}
			else {				
				strDay = strDateArray[0];
				strMonth = strDateArray[1];
				strYear = strDateArray[2];				
			}
			booFound = true;
		}
	}
	
	if (booFound == false) {
		return false;				
	}
	if (strYear.length == 2) {
		strYear = '20' + strYear;
	}
	if (strYear.length > 4) {
		return false;
	}

	if (strDatestyle == "US") {
		strTemp = strDay;
		strDay = strMonth;
		strMonth = strTemp;
	}
	intday = parseInt(strDay, 10);
	if (isNaN(intday)) {
		err = 2;
		return false;
	}
	intMonth = parseInt(strMonth, 10);
	if (isNaN(intMonth)) {
		for (i = 0;i<12;i++) {
			if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
				intMonth = i+1;
				strMonth = strMonthArray[i];
				i = 12;
		    }
		}	

		if (isNaN(intMonth)) {
			err = 3;
			return false;
    	}
	}
	intYear = parseInt(strYear, 10);
	if (isNaN(intYear)) {
		err = 4;
		return false;
	}
	if (intMonth>12 || intMonth<1) {
		err = 5;
		return false;
	}
	if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
		err = 6;
		return false;
	}
	if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
		err = 7;
		return false;
	}
	if (intMonth == 2) {
		if (intday < 1) {
			err = 8;
			return false;
		}
		if (LeapYear(intYear) == true) {
			if (intday > 29) {
				err = 9;
				return false;
			}
		}
		else {
			if (intday > 28) {
				err = 10;
				return false;
			}
		}
	}
return true;
}

function LeapYear(intYear) {
	if (intYear % 100 == 0) {
		if (intYear % 400 == 0) { return true; }
	}
	else {
		if ((intYear % 4) == 0) { return true; }
	}
	return false;
}

function getYearMonthDay(strDate,dateForm)
{
	var strDateArray;
	var strDay;
	var strMonth;
	var strYear;
	
	var strSeparatorArray = new Array("-"," ","/",".");
	for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {			
		if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
			strDateArray = strDate.split(strSeparatorArray[intElementNr]);
			if (strDateArray.length != 3) {
				err = 1;
				return false;
			}
			else {				
				strDay = strDateArray[1];
				strMonth = strDateArray[0] - 1;
				strYear = strDateArray[2];								
			}
		}
	}
	switch ( dateForm )
	{
    	case "Year":
       	{
	        return strYear;
    	    break;
       	}
	    case "Month":
        {
			return strMonth;
	        break;
        }
	    case "Day":
        {
			return strDay;
        	break;
        }
	    default:		
			return false;
	}
}

// This functions only compares the hours of two times
function compareTime(beginTime,endTime) {
	var beginHour;		
	var endHour;		
	if (beginTime.search("P") != -1) 
		beginHour = parseInt(beginTime) + 12;
	else
		beginHour = parseInt(beginTime);
	
	if (endTime.search("P") != -1) 
		endHour = parseInt(endTime) + 12;
	else
		endHour = parseInt(endTime);
	
	if(endHour <= beginHour) {
		alert("Error: ''End Time'' field must be greater than the ''Begin Time'' field.");
		return false;		
	}
	else
		return true;
	
}

function compareDate(date1, date1Label, date2, date2Label) {
	if (date1 != null && date2 != null)
	{		
		date1 = date1.value;
		date2 = date2.value;
		var date1Year = getYearMonthDay(date1,"Year");
		var date1Mon = getYearMonthDay(date1,"Month");
		var date1Day = getYearMonthDay(date1,"Day");
		var date1Date = new Date(date1Year,date1Mon,date1Day);

		var date2Year = getYearMonthDay(date2,"Year");
		var date2Mon = getYearMonthDay(date2,"Month");
		var date2Day = getYearMonthDay(date2,"Day");
		var date2Date = new Date(date2Year,date2Mon,date2Day);
		if(date1Date > date2Date)
		{
			alert("Error: '" + date2Label + "' field must be greater than the '" + date1Label + "' field.");
			return false;
		}
		else {
			return true;
		}
	}
}

//This function compares two string values

function doStringsMatch(string1, string1Label, string2, string2Label) {
	if(string1.value != string2.value)
	{
		alert("Error: '" + string1Label + "' field value and the '" + string2Label + "' field value are not the same.");
		string1.focus();
		return false;
	} else {
		return true;
	}
}


/************************************************************************************************************** 
* Function: Date functions								END 								  
* Description: Validates that valid dates are entered
**************************************************************************************************************/

function warnUser(warningType) {

	switch ( warningType )
	{
    	case "category":
       	{
	        if(confirm("Warning!: Are you sure you want to delete this category?  Once you have deleted this category, this action "
				+ "cannot be reversed.  Deleteing a category will also delete all features associated with the category.") 
				== false)
			{
				return false;							
			}
    	    break;
       	}
	    case "customer":
        {
			if(confirm("Warning!: Are you sure you want to delete this customer?  Once you have deleted this customer, this action "
				+ "cannot be reversed.  Deleteing a customer will also delete all properties associated with the customer.") 
				== false)
			{
				return false;							
			}
	        break;
        }
		case "feature":
       	{
	        if(confirm("Warning!: Are you sure you want to delete this feature?  Once you have deleted this feature, this action "
				+ "cannot be reversed.  Deleteing a feature will delete the feature from all properties that currently have this feature.") 
				== false)
			{
				return false;							
			}
    	    break;
       	}
	    case "property":
        {
	        if(confirm("Warning!: Are you sure you want to delete this property?  Once you have deleted this property, this action "
				+ "cannot be reversed.") 
				== false)
			{
				return false;							
			}
    	    break;
        }
	    default:		
			return false;
	}
	
	return true;
}

/************************************************************************************************************** 
* Function: Navigation									START 								  
* Description: These functions are used for navigating between pages.
**************************************************************************************************************/

function setFormLoc(form, pageLocation) 
{
	form.action = pageLocation;
	form.submit();
	return true;
}

/************************************************************************************************************** 
* Function: Navigation									END								  
* Description: These functions are used for navigating between pages.
**************************************************************************************************************/

/************************************************************************************************************** 
* Function Category: Email									BEGIN								  
* Description: These functions are email related.
**************************************************************************************************************/

function decodeText(theText) {
  output = new String;
  Temp = new Array();
  Temp2 = new Array();
  TextSize = theText.length;
  for (i = 0; i < TextSize; i++) {
    Temp[i] = theText.charCodeAt(i);
    Temp2[i] = theText.charCodeAt(i + 1);
  }

  for (i = 0; i < TextSize; i = i+2) {
    output += String.fromCharCode(Temp[i] - Temp2[i]);
  }
  return output;
}

/************************************************************************************************************** 
* Function Category: Email									END
* Description: These functions are email related.
**************************************************************************************************************/
