//***************THE FOLLOWING FUNCTIONS ARE USED THROUGHOUT************
function openWin(url,windowName,options){
	var WindowHandle=window.open(url,windowName,options);
	WindowHandle.focus();
}

var ns6=document.getElementById&&!document.all
var ie=document.all

function showSpan(spanID,thetext){
	if (ie) eval("document.all."+spanID).innerHTML=thetext
	else if (ns6) document.getElementById(spanID).innerHTML=thetext
}
function hideSpan(spanID){
	if (ie) eval("document.all."+spanID).innerHTML=' '
	else if (ns6) document.getElementById(spanID).innerHTML=' '
}

function getElementBy(elemTag){
	var elem = document.getElementById (elemTag);
	if (elem)
		return elem;
	var elems = document.getElementsByName (elemTag);
	if (elems.length > 0)
		return elems[0];
	return null;
}

function toggleOpenCloseElem(elemName){
	var elem = getElementBy (elemName);
	if (!elem)
		return;
	if (elem.style.display == "")
		elem.style.display = "none";
	else
		elem.style.display = "";
}

function CreateBookmarkLink() {
    title = document.title; 
    url = window.location.href;

    if (window.sidebar) { // Mozilla Firefox Bookmark
        window.sidebar.addPanel(title, url,"");
    }
    else if( window.external ) { // IE Favorite
        window.external.AddFavorite( url, title); }
    else if(window.opera && window.print) { // Opera Hotlist
        return true; 
    }
}
//***************THE ABOVE FUNCTION IS USED THROUGHOUT************



//***************THE FOLLOWING FUNCTION IS USED FOR FORM VALIDATION************
function confirmPrompt(msg,url){
	if(confirm(msg)) 
		document.location = url;
}

function validateLength(objTB,maxChar){
	if (objTB.value.length > maxChar){return false;}
	return true;
}

function validateEmail(objTB){
	var invalidChars = "*|,\":<> []{}`\';()&$#%";
	if (objTB.value.indexOf('@') < 0 || objTB.value.indexOf('.') < 0 || objTB.value.length < 5){return false;}
	for (var i = 0; i < objTB.value.length; i++){
	   if (invalidChars.indexOf(objTB.value.charAt(i)) != -1){return false;}
	}
	return true;
} 

function validateEmailNonReq(objTB){
	var invalidChars = "*|,\":<> []{}`\';()&$#%";
	if (objTB.value.length > 0){
		if (objTB.value.indexOf('@') < 0 || objTB.value.indexOf('.') < 0 || objTB.value.length < 5){return false;}
		for (var i = 0; i < objTB.value.length; i++){
		   if (invalidChars.indexOf(objTB.value.charAt(i)) != -1){return false;}
		}
		return true;
	}
	return true;
} 

function validateTextBox(objTB){
	if (objTB.value==''){return false;}
	return true;
}

function validateSelectList(objTB){
	if (objTB.selectedIndex==''){return false;}
	return true;
}

function validateNumberTextBoxNonReq(objTB){
	if (isNaN(objTB.value)){return false;}
	return true;
}

function validateNumberTextBox(objTB){
	if (objTB.value=='' || isNaN(objTB.value)){return false;}
	return true;
}

function restrictNumberKeys(e){
		/*
		Description: This function restricts an input box to only accept numerics, dashes,
					 parentheses and spaces.
		  
		Usage:
			<input onKeyPress="return restrictNumberKeys(event);">
			
		Known Browser Support: MSIE 6.0, FireFox 1.0.4, Safari 2.0
		Written By: Chris Pietschmann, MCSD, MCAD
		*/
		var keyCode;
		
		if(window.event) //MSIE
			keyCode = e.keyCode;
		else //FireFox
			keyCode = e.which;

		if(keyCode >= 48 && keyCode <= 57 //Numeric Digits 0-9
			|| (keyCode == 8) //Backspace
			|| (keyCode == 0) //keys like Enter and Delete will return zero
			|| (keyCode == 99 && e.ctrlKey) // Ctrl-C
			|| (keyCode == 118 && e.ctrlKey) // Ctrl-V
			)
			return true;
		else
			return false;
	}
	
	function isInteger(s){
	var i;
    for (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 stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

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 DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
var dtCh="/";
var minYear=1900;
var maxYear=2100;

	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	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 : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		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(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}

//***************THE ABOVE FUNCTION IS USED FOR FORM VALIDATION************



//***************THE FOLLOWING FUNCTIONS ARE USED BY THE PROPERTY COMPARE FEATURE************
var thecookie = document.cookie;

function setCookie(name, value, expires, path, domain, secure) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime(today.getTime());

    /*
    if the expires variable is set, make the correct 
    expires time, the current script below will set 
    it for x number of days, to make it for hours, 
    delete * 24, for minutes, delete * 60 * 24
    */
    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date(today.getTime() + (expires));

    document.cookie = name + "=" + escape(value) + ((expires) ? ";expires=" + expires_date.toGMTString() : "") + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ((secure) ? ";secure" : "");
}

// this fixes an issue with the old method, ambiguous values 
// with this test document.cookie.indexOf( name + "=" );
function getCookie(check_name) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split(';');
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for (i = 0; i < a_all_cookies.length; i++) {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split('=');


        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if (cookie_name == check_name) {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if (a_temp_cookie.length > 1) {
                cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return null;
    }
}

// this deletes the cookie when called
function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }
}

function commitCompareList(){		
	setCookie("VAR_CompareList",GLOBAL_CompareList);
	setCookie("CompareCount",GLOBAL_CompareCount);
	//
}		

function sendToCompare(){


	if (GLOBAL_CompareCount < 2){
		alert('Please check more than 1 property!');
	}else{
		if (GLOBAL_CompareCount > 10){
			alert('Please check no more than 10 properties!');
		}else{



			window.location = "/property/propertycompare.asp?VAR_CompareList=" + GLOBAL_CompareList + "&CompareCount=" + GLOBAL_CompareCount;
		}
	}
}
		
function compareClear(){

    var currentURL = location.pathname.toLowerCase();
    clearImage = getCookie('VAR_CompareList').split(';'); 
    for(var i=0; i < clearImage.length - 1; i++){
        if (document.getElementById('img' + clearImage[i]) != null){
            if (currentURL == '/property/property.asp'){
                document.getElementById('img' + clearImage[i]).src="/images/propCompare_off2.gif";
            }
            else{
                document.getElementById('img' + clearImage[i]).src="/images/propCompare_off3.gif";
            }
        }
    }
         
	GLOBAL_CompareList = "";
	GLOBAL_CompareCount = 0;	
	Set_Cookie('VAR_CompareList','',30, '/', '', '' );
	Set_Cookie('CompareCount','',30, '/', '', '' );	
}

function propertyComapreOnload() {
    var compareArray;
    var clearImages = document.getElementsByTagName("img");
    var currentURL = location.pathname.toLowerCase();

    for (var i = 0; i < clearImages.length; i++) {
        if (currentURL == '/property/property.asp') {
            if (Right(clearImages[i].src, 19) == 'propCompare_on2.gif') {
                clearImages[i].src = '/images/propCompare_off2.gif'
            }
        }
        else {
            if (Right(clearImages[i].src, 19) == 'propCompare_on3.gif') {
                clearImages[i].src = '/images/propCompare_off3.gif'
            }
        }
    }

    if (GLOBAL_CompareList) {

        compareArray = GLOBAL_CompareList.split(';');

        for (var i = 0; i < compareArray.length; i++) {
            if (document.getElementById('img' + compareArray[i])) {
                document.getElementById('img' + compareArray[i]).src = (currentURL == '/property/property.asp' ? '/images/propCompare_on2.gif' : '/images/propCompare_on3.gif');
            }
        }
    }
}

function compareClear2(){
	GLOBAL_CompareList = "";
	GLOBAL_CompareCount = 0;		
	Set_Cookie('VAR_CompareList','',30, '/', '', '' );
	Set_Cookie('CompareCount','',30, '/', '', '' );
	clearImages = document.getElementsByTagName("img");
	for (var i=0; i < clearImages.length; i++){
	    if (Right(clearImages[i].src,19) =='propCompare_on3.gif'){
            clearImages[i].src="/images/propCompare_off3.gif"
        }
        else if (Right(clearImages[i].src,19) =='propCompare_on2.gif'){
            clearImages[i].src="/images/propCompare_off2.gif"
	    }
	
	}
}



function resetCompare(){
	GLOBAL_CompareList = "";
	GLOBAL_CompareCount = 0;		
	setCookie("VAR_CompareList","");
	setCookie("CompareCount","");
	for(i=0; i<document.frmCompare.elements.length; i++)
		{
			if(document.frmCompare.elements[i].type=="checkbox")
		{
			document.frmCompare.elements[i].checked=false;
		}
	}	

}



//***************THE ABOVE FUNCTIONS ARE USED BY THE COMPARE TOOL************



//***************THE FOLLOWING FUNCTIONS BELOW ARE USED WITH AJAX************
function XMLHTTPRequest_createRequester()
{
      var myRequest;
    try{
        myRequest = new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){
        try{
            myRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(oc){
            myRequest = null;
        }
    }
 
    if(!myRequest && typeof XMLHttpRequest != "undefined"){
        myRequest = new XMLHttpRequest();
    }
    return myRequest;
}

function AjaxSwapCriteria(selLabel,selOptionValueField,selOptionTextField,selSelectListName,selSpanID,selShowGeoCodedData,selClassStyle,selMultiple,selBlankFirstOption,selMLSName,selSearchSwapVal){

	var AJAXRequest = ''; //this must be set to nothing
    var xmlDoc;
	var selOptions = '';
	
	//Check if <SPAN> tag exists
	if(testForObject(selSpanID)){

		//Build the <SELECT> tag
		var selTag = '<select name="' + selSelectListName + '" id="' + selSelectListName + '" ' + selClassStyle + ' ' + selMultiple + '>'
		
		//Optionally insert blank first option
		if(selLabel != '' && selBlankFirstOption == true){selTag = selTag + '<option value="">Any ' + selLabel.toLowerCase(); + '</option>'}	
	
		//Reset inner HTML of <SPAN> tag
		document.getElementById(selSpanID).innerHTML = selTag + '</select>'

		//Submit AJAX request
		AJAXRequest = XMLHTTPRequest_createRequester();
		if(AJAXRequest != null){
			var date = new Date();
			var timestamp = date.getTime();
		    AJAXRequest.open('GET', '/_Include/AJAXSwapCriteria.asp?VAR_selLabel=' + selLabel + '&VAR_selOptionValueField=' + selOptionValueField + '&VAR_selOptionTextField=' + selOptionTextField + '&VAR_MLSName=' + selMLSName + '&VAR_selSearchSwapVal=' + selSearchSwapVal + '&VAR_selShowGeoCodedData=' + selShowGeoCodedData + '&time=' + timestamp, true);
		    AJAXRequest.onreadystatechange = function(aEvt){
		        if(AJAXRequest.readyState == 4){ //The load is complete when readyState equals 4
					//alert(AJAXRequest.status);
					//alert(AJAXRequest.responseText);
		            if(AJAXRequest.status == '200' && AJAXRequest.status != undefined && AJAXRequest.responseText != ''){
						if(window.ActiveXObject){
						    //Internet Explorer
						    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
						    xmlDoc.async = false;
						    xmlDoc.loadXML(AJAXRequest.responseText);
						}else if(document.implementation && document.implementation.createDocument){
						    //Mozilla
						    xmlDoc = AJAXRequest.responseXML;
						}

						//Build select list options
						var SearchCriteriaList = xmlDoc.documentElement.getElementsByTagName(selOptionValueField);

						for (var i = 0; i < SearchCriteriaList.length; i++){
						    selOptions = selOptions + '<option value="' + SearchCriteriaList[i].getAttribute("Value") + '">' + SearchCriteriaList[i].getAttribute("Text") + '</option>';
						}
						
						//Reset inner HTML of <SPAN> tag
						document.getElementById(selSpanID).innerHTML = selTag + selOptions + '</select>';
		            }
		        }
		    }
		    AJAXRequest.send(null);
		}
	}
}

function testForObject(Id){
	var o = document.getElementById(Id);
	if (o){return true;}return false;
}
//***************THE ABOVE FUNCTIONS ARE USED WITH AJAX************

function checkMyEmail(){
    if (checkEmail( document.getElementById("subEmail").value ) == false){
	    document.getElementById("emailError").innerHTML = "Please enter a valid Email Address";
	    return false;
    }	
    return true;
}

function checkEmail(email){
    var regExp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    return regExp.test(email);
}

// this fixes an issue with the old method, ambiguous values 
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}				
	
// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
if ( Get_Cookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function Set_Cookie( name, value, expires, path, domain, secure ) 
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct 
expires time, the current script below will set 
it for x number of days, to make it for hours, 
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
( ( path ) ? ";path=" + path : "" ) + 
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

function addCompareV2(strAdd,strID){
    
    var currentURL = location.pathname.toLowerCase();
    var Max_Number_Properties = 12;
    var myString = GLOBAL_CompareList;
    
    if (myString.indexOf(strAdd) == -1 )
	{
		if (GLOBAL_CompareCount == Max_Number_Properties) {			
			alert('You have already chosen ' + Max_Number_Properties + ' properties!');
		}
		else {
			GLOBAL_CompareList = GLOBAL_CompareList + strAdd;
			GLOBAL_CompareCount = parseInt(GLOBAL_CompareCount) + 1;

	        Set_Cookie('VAR_CompareList',GLOBAL_CompareList,'', '/', '', '' );
	        Set_Cookie('CompareCount',GLOBAL_CompareCount,'', '/', '', '' );
	        if (strID){
	            if (currentURL == '/property/property.asp'){
                    document.getElementById(strID).src="/images/propCompare_on2.gif"
                }
                else{
			        document.getElementById(strID).src="/images/propCompare_on3.gif"
			    }
            }
            //alert('Property has been added to your compare list');
		}
	}	
	else 
	{
		GLOBAL_CompareCount = parseInt(GLOBAL_CompareCount) - 1
		GLOBAL_CompareList = GLOBAL_CompareList.replace(strAdd,"");

	    Set_Cookie('VAR_CompareList',GLOBAL_CompareList,'', '/', '', '' );
	    Set_Cookie('CompareCount',GLOBAL_CompareCount,'', '/', '', '' );
	    if (strID){
			var compareIconElement = document.getElementById(strID)
			
			if (compareIconElement != null) {
				if (currentURL == '/property/property.asp'){
					compareIconElement.src="/images/propCompare_off2.gif"
				}
				else
				{
					compareIconElement.src="/images/propCompare_off3.gif"
				}
			}
        }
        //alert('This Property has been removed from your list');
	}
}

//***************THE ABOVE FUNCTIONS ARE USED BY THE COMPARE TOOL************

//***************USED FOR ETOURS***********************************
function commitEtourList(){		
	setCookie("VAR_EtourList",GLOBAL_EtourList);
	setCookie("EtourCount",GLOBAL_EtourCount);
}		

function sendToEtour(AgentBranding){
	if (GLOBAL_EtourCount < 2){
		alert('Please check more than 1 property!');
	}else{
		if (GLOBAL_EtourCount > 15){
			alert('Please check no more than 15 properties!');
		}else{
		//    alert(GLOBAL_EtourList);
		    openWin('http://www.myetours.com/ubertest/default.asp?AgentBranding='+ AgentBranding +'&title=Century 21 Joe Guy Hagan&ClientCode=c21hagan&Domain=http://c21haganprod.e-net.com&MlsNameNumberList='+ GLOBAL_EtourList,'','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=760,height=480')
		}
	}
}

		
function EtourClear(){
	GLOBAL_EtourList = "";
	GLOBAL_EtourCount = 0;		
	setCookie("VAR_EtourList","");
	setCookie("EtourCount","");
}


function resetEtour(){
	GLOBAL_EtourList = "";
	GLOBAL_EtourCount = 0;		
	setCookie("VAR_EtourList","");
	setCookie("EtourCount","");
	for(i=0; i<document.frmCompare.elements.length; i++)
		{
			if(document.frmCompare.elements[i].type=="checkbox")
		{
			document.frmCompare.elements[i].checked=false;
		}
	}	

}

function addEtour(obj){
	//the maximum number of listings a user can check to compare
	var Max_Number_Properties = 15;
	
	if (obj.checked == true) 
	{
		if (GLOBAL_EtourCount == Max_Number_Properties) {			
			obj.checked = false;
			alert('You have already chosen ' + Max_Number_Properties + ' properties!');
		}
		else {
			GLOBAL_EtourList = GLOBAL_EtourList + obj.value;
			GLOBAL_EtourCount = parseInt(GLOBAL_EtourCount) + 1;
		}
	}	
	else 
	{
		GLOBAL_EtourCount = parseInt(GLOBAL_EtourCount) - 1
		GLOBAL_EtourList = GLOBAL_EtourList.replace(obj.value,"");
	}
}
//***************Above USED FOR ETOURS***********************************

function Right(str, n)
/***
        IN: str - the string we are RIGHTing
            n - the number of characters we want to return

        RETVAL: n characters from the right side of the string
***/
{
        if (n <= 0)     // Invalid bound, return blank string
           return "";
        else if (n > String(str).length)   // Invalid bound, return
           return str;                     // entire string
        else { // Valid bound, return appropriate substring
           var iLen = String(str).length;
           return String(str).substring(iLen, iLen - n);
        }
}

function executeOnloadFunctions() {
    propertyComapreOnload();
}
