//***************THE FOLLOWING FUNCTIONS ARE USED THROUGHOUT************

function parseQS(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.search);
    if (results == null)
        return '';
    else
        return results[1];
}

function routeOfficeSelection(val) {
    if (val == '') return;
    var str = val.split('|');
    (str[1] == 1) ? location.href = '/office/agentlist.asp?CEQ_OfficeCode=' + str[0] : location.href = str[0];
}

function clearSelect(frmElement) {
    frmElement.selectedIndex = -1
}

function checkEmail(email){
    var regExp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    return regExp.test(email);
}

function openWin(url,windowName,options){
	var WindowHandle=window.open(url,windowName,options);
	WindowHandle.focus();
}

function wopen(url, name, w, h)
{
  // Fudge factors for window decoration space.
  // In my tests these work well on all platforms & browsers.
  w += 32;
  h += 96;
  wleft = (screen.width - w) / 2;
  wtop = (screen.height - h) / 2;
  // IE5 and other old browsers might allow a window that is
  // partially offscreen or wider than the screen. Fix that.
  // (Newer browsers fix this for us, but let's be thorough.)
  if (wleft < 0) {
    w = screen.width;
    wleft = 0;
  }
  if (wtop < 0) {
    h = screen.height;
    wtop = 0;
  }
  var win = window.open(url,
    name,
    'width=' + w + ', height=' + h + ', ' +
    'left=' + wleft + ', top=' + wtop + ', ' +
    'location=no, menubar=no, ' +
    'status=no, toolbar=no, scrollbars=no, resizable=no');
  // Just in case width and height are ignored
  win.resizeTo(w, h);
  // Just in case left and top are ignored
  win.moveTo(wleft, wtop);
  win.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 TrimString(sInString) {
    sInString = sInString.replace(/^\s+/g, '');   // strip leading
    return sInString.replace(/\s+$/g, '');        // strip trailing
}

function swapSides(selFrom, selTo) {
    //takes one or many selected values from side-by-side selectors from one side to the other, and removes selected options from the original.
    var toOptCt = selTo.options.length;

    for (var i = selFrom.options.length - 1; i >= 0; i--) {
        if (selFrom.options[i].selected) {
            selTo.options[toOptCt] = new Option(selFrom.options[i].text, selFrom.options[i].value);
            selFrom.remove(i);
            toOptCt++;
        }
    }
}

//***************THE ABOVE 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 validateEmailByValue(email) {
    var regExp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    return regExp.test(email);
}

function validateTextBox(objTB){
	if (TrimString(objTB.value) == ''){return false;}
	return true;
}

function validateSelectList(objTB){
	if (objTB.selectedIndex==''){return false;}
	return true;
}

function validateCheckBox(objTB) {
    if (objTB.checked == false) { 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);">
			
		*/
		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;
var Max_Number_Properties = 12;

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 compareClear(){
    var compareClassName;
	GLOBAL_CompareList = "";
	GLOBAL_CompareCount = 0;		
	setCookie('VAR_CompareList','',30, '/', '', '' );
	setCookie('CompareCount','',30, '/', '', '' );
	var clearImages = document.getElementsByTagName("a");
	for (var i = 0; i < clearImages.length; i++) {
	    compareClassName = clearImages[i].className;
	    if (clearImages[i].className == compareClassName.replace("propComp-off", "propComp-on")){
    	     clearImages[i].className = compareClassName.replace("propComp-on", "propComp-off");
	    }
	
	}
}


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 addCompare(strAdd,strID){
	//the maximum number of listings a user can check to compare
    var myString = GLOBAL_CompareList;
    
    //Get the new Class Name
    if (document.getElementById(strID)){
		var compareClassName = document.getElementById(strID).className;
		if (compareClassName == compareClassName.replace("propComp-on", "propComp-off")){
		    compareClassName = compareClassName.replace("propComp-off", "propComp-on");
		}else{
		    compareClassName = compareClassName.replace("propComp-on", "propComp-off");
		}
	}

	if(GLOBAL_CompareCount == undefined || isNaN(GLOBAL_CompareCount) == true){
		GLOBAL_CompareCount = 0;
	}

    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;
	        setCookie('VAR_CompareList',GLOBAL_CompareList,'', '/', '', '' );
	        setCookie('CompareCount',GLOBAL_CompareCount,'', '/', '', '' );
	        if (strID){
	            if (document.getElementById(strID)){
                    document.getElementById(strID).className=compareClassName
                    
                    if (document.getElementById(strID.replace("imgeNav","img")) != null){
                        document.getElementById(strID.replace("imgeNav","img")).className=compareClassName
                    }
                    if (document.getElementById(strID.replace("img","imgeNav")) != null){
                        document.getElementById(strID.replace("img","imgeNav")).className=compareClassName
                    }
                }
            }
		}
	}	
	else 
	{
		GLOBAL_CompareCount = parseInt(GLOBAL_CompareCount) - 1
		GLOBAL_CompareList = GLOBAL_CompareList.replace(strAdd,"");

	    setCookie('VAR_CompareList',GLOBAL_CompareList,'', '/', '', '' );
	    setCookie('CompareCount',GLOBAL_CompareCount,'', '/', '', '' );
	    if (strID){
	        if (document.getElementById(strID)){
                document.getElementById(strID).className=compareClassName
                
                if (document.getElementById(strID.replace("imgeNav","img")) != null){
                    document.getElementById(strID.replace("imgeNav","img")).className=compareClassName
                }
                if (document.getElementById(strID.replace("img","imgeNav")) != null){
                    document.getElementById(strID.replace("img","imgeNav")).className=compareClassName
                }
            }
        }
	}
}

function propertyCompareOnload() {
    var compareArray;
    var compareClassName;

    if (GLOBAL_CompareList) {

        compareArray = GLOBAL_CompareList.split(';');

        for (var i = 0; i < compareArray.length; i++) {
            if (document.getElementById('img' + compareArray[i])) {
                compareClassName = document.getElementById('img' + compareArray[i]).className;
                document.getElementById('img' + compareArray[i]).className = compareClassName.replace("propComp-off", "propComp-on");
            }
        }
    }
}

//***************THE ABOVE FUNCTIONS ARE USED BY THE COMPARE TOOL************



//***************THE FOLLOWING FUNCTIONS BELOW ARE USED WITH AJAX************

//**************THE BELOW CODE IS USED FOR PROPERTY SEARCH CRITERIA *********
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;
}

//**************THE CODE BELOW IS USED FOR THE PROPERTY COMPARE *********
function loadPropertyCompareContent(container, script, bnrc, bnrt) {
    var req = XMLHTTPRequest_createRequester();
    var url = script + '?bnrc=' + bnrc + '&bnrt=' + bnrt;
    url += '&VAR_Compare=' + getCookie('VAR_CompareList');
    if (req != null) {
        req.open('GET', url, true);
        req.onreadystatechange = function(aEvt) {
            if (req.readyState == 4) {
                if (req.status == '200' && req.status != undefined && req.responseText != '') {
                    document.getElementById(container).innerHTML = req.responseText;
                }
            }
        }
        req.send(null);
    }
}

//***************THE FOLLOWING FUNCTIONS ARE USED BY THE ICAL FEATURE************

function positionCal(obj,showID)
{
hp = document.getElementById(showID);
// Set position of hover-over popup
hp.style.top = findElementTop(obj) + 18 + 'px';
hp.style.left = findElementLeft(obj) + 17 + 'px';
}

var IE5up = document.getElementById&&document.all;
var NS6up = document.getElementById&&!document.all;
var NS4 = document.layers;
var IE4 = document.all&&!window.print;
var previousLayer='';

function show(layerid){
    
    if (previousLayer != '' && previousLayer != layerid){
	    hide(previousLayer);
    }

    previousLayer = layerid

    if(IE5up||NS6up){
	    document.getElementById(layerid).style.display="";
    }
    else if(NS4){
	    document.layers[layerid].display="";
    }
    else if(IE4){
	    document.all[layerid].style.display="";
    }
}

function hide(layerid){
	if(IE5up||NS6up)
		document.getElementById(layerid).style.display="none";
	else if(NS4)
		document.layers[layerid].display="none";
	else if(IE4)
		document.all[layerid].style.display="none";
}

function findElementTop(obj){var curtop = 0;if(obj.offsetParent){while (obj.offsetParent){curtop += obj.offsetTop;obj = obj.offsetParent;}}else if (obj.y){curtop += obj.y;} return curtop;}   
function findElementLeft(obj){var curleft = 0;if(!obj) return curleft;if(obj.offsetParent){while(obj.offsetParent){curleft += obj.offsetLeft;obj = obj.offsetParent;}}else if (obj.x){curleft = obj.x;}return curleft;}
//***************THE ABOVE FUNCTIONS ARE USED BY THE ICAL FEATURE************


function executeOnloadFunctions() {
    $.checkSignIn();
    propertyCompareOnload();
}


/************************************* THE BELOW CODE IS FOR THE LISTMAILER SAVED PROPERTIES AND SAVED SEARCH ********************************************/

function deleteSavedProperty(MlsNumber, MlsName) {
    var propertyID = MlsNumber + '\\|' + MlsName;   //note the escape \\ - used in jQuery to escape certain characters, like the vertical pipe

    $.get('/_include/listmailercom/AJAX_DeleteSavedProperty.asp', { Subscriber: getCookie('listmailerlogin'), PRM_MLSNumber: MlsNumber, PRM_MLSName: MlsName }, function(data) { 

        if (data == 'propertyDeleted') {
            $('#savedprop_add' + propertyID).show();
            $('#bubble_savedprop_add' + propertyID).show();
            $('#savedprop_delete' + propertyID).hide();
            $('#bubble_savedprop_delete' + propertyID).hide();
        }
        $('#mysearch').load('/_include/modules/mysearch/navlinks.asp');    
    });
}

function addSavedProperty(MlsNumber, MlsName) {
    var propertyID = MlsNumber + '\\|' + MlsName;       //note the escape \\ - used in jQuery to escape certain characters, like the vertical pipe

    $.get('/_include/listmailercom/AJAX_AddSavedProperty.asp', { Subscriber: getCookie('listmailerlogin'), PRM_MLSNumber: MlsNumber, PRM_MLSName: MlsName }, function(data) {

        if (data == 'propertySaved') {                                                  /* Saved Property Record Added to Database*/
            $('#savedprop_add' + propertyID).hide();
            $('#bubble_savedprop_add' + propertyID).hide();
            $('#savedprop_delete' + propertyID).show();
            $('#bubble_savedprop_delete' + propertyID).show();
        }
        else if (data == 'signInUp') {
            setCookie('saveProperty', MlsNumber + '|' + MlsName, '', '/', '', '');          /* Set Temporary Cookie to save property after listmailer login */
            $('#signUpDialog').show();                                                      
            YAHOO.subscriber.signUpDialog.show();                                           /* Sign up or sign in to listmailer */
        }
        $('#mysearch').load('/_include/modules/mysearch/navlinks.asp');
    });
}

function saveSearch(qryStr) {
    $.get('/listmailer/saveSearch.asp?' + qryStr, function(data) {

        if (data == 'searchSaved') {                                        /* Saved Search Added to Database */
            $('#saveSearchImage').attr('src', '/images/saved.gif');
            $('#saveSearchText').html('Search Saved');
        }
        else if (data == 'signInUp') {
            $('#signUpDialog').show();                                      
            setCookie('saveSearch', qryStr, '', '/', '', '');               /* Set Temporary Cookie to save search after listmailer login */
            YAHOO.subscriber.signUpDialog.show();                            /* Sign up or sign in to listmailer */
        }
        $('#mysearch').load('/_include/modules/mysearch/navlinks.asp');
    });
}

/************************************* THE ABOVE CODE IS FOR THE LISTMAILER SAVED PROPERTIES AND SAVED SEARCH ***************************************************/

$.showWelcome = function() {
    $('#listmailerWelcome').show();
    $('#listmailerWelcomeFirstName').html(getCookie('listmailerfirstname'));
    $('#listmailerSignIn').hide();
    $('#listmailerWelcomeBottom').show(); 
    $('#listmailerSignInBottom').hide(); 
}

$.showSignIn = function() { $('#listmailerWelcome').hide(); $('#listmailerSignIn').show(); $('#listmailerWelcomeBottom').hide(); $('#listmailerSignInBottom').show(); }

$.checkSignIn = function() {
    var cookie = getCookie('listmailerlogin');
    (cookie == null || cookie == '') ? $.showSignIn() : $.showWelcome();
}


$(document).ready(function() {

    $('#mysearch').load('/_include/modules/mysearch/navlinks.asp');


    /***********************PROPLIST ENLARGE IMAGE - USES JQUERY ************/

    // get img width 
    var oWidth = $('img.resize').width();

    // get img height 
    var oHeight = $('img.resize').height();

    //You could always multiply the multiplier if you want to make the image adjust to a larger size.  Keep in mind though it will get more blurry
    var mpx = ((oWidth / oHeight) *1.5);
    $('img.resize').hover(function(){
          $(this)
            
            //stops the event from happening in case of an abrupt mouseOut
            .stop()

            //custom animation effect to change the width and height of the img
            .animate({

                //take the original width/height X multipler and tag on the 'px'
                width: (oWidth * mpx) +'px',
                height: (oHeight * mpx) +'px'

                //space the animation out over 1 sec (deals in milliseconds)
            },500);
  },
  //this is just like a mouseOut effect to take the img back to the original size
  function(){
            $(this)

                 //stops the event from happening in case of an abrupt mouseOut
                .stop()

                //this animation shrinks the image back to original size
                .animate({
                     width: oWidth +'px',
                     height: oHeight +'px'
                },500);

  });

});
/***********************END PROPLIST ENLARGE IMAGE ************/
