var xmlHttp; 
var is_ie = (navigator.userAgent.indexOf('MSIE') >= 0) ? 1 : 0; 
var is_ie5 = (navigator.appVersion.indexOf("MSIE 5.5")!=-1) ? 1 : 0; 
var is_opera = ((navigator.userAgent.indexOf("Opera6")!=-1)||(navigator.userAgent.indexOf("Opera/6")!=-1)) ? 1 : 0; 
//netscape, safari, mozilla behave the same??? 
var is_netscape = (navigator.userAgent.indexOf('Netscape') >= 0) ? 1 : 0; 
var MapPage = 2;
var PageMaxRetrieved = MapPage - 1;
var start = 0;
var attributes = {scroll: { by: [0, 429] } };
var endOfListings = false;
//LISTING FAVORITE
	function favoriteSet(memberId, sourceId, mlsNum, isFavorite, urlXmlPost, ajaxCallType)
	{
		xmlHttp = GetXmlHttpObject(stateChangeHandlerDoNothing);
		xmlHttp_Get(xmlHttp, urlXmlPost + '?IsAjaxRequest=true&AjaxCallType=' + ajaxCallType + '&MemberId=' + memberId + '&SourceId=' + sourceId + '&MlsNumber=' + mlsNum + '&IsFavorite=' + isFavorite); 
	}
	//LISTING FAVORITE
	function favoriteSetResults(sourceId, mlsNum, urlXmlPost, ajaxCallType, isFavorite)
	{
		xmlHttp = GetXmlHttpObject(stateChangeHandlerFavorite);
		xmlHttp_Get(xmlHttp, urlXmlPost + '?IsAjaxRequest=true&AjaxCallType=' + ajaxCallType + '&SourceId=' + sourceId + '&MlsNumber=' + mlsNum+ '&IsFavorite=' + isFavorite);		
	}


var idxAjax = {
	//QUICKHOMES LOGIN
	login: function (userName, pw, saveLogin, urlXmlPost, ajaxCallType)
	{
			$("#loginLoading").show();
			//the dock event is fired twice. once on the undock and once on the dock
			//we are not interested in the first event, so if the eventargs elem id is null, exit the function
			xmlHttp = GetXmlHttpObject(stateChangeHandlerLogin);  
			//Send the xmlHttp get to the specified url 
			xmlHttp_Get(xmlHttp, urlXmlPost + '?IsAjaxRequest=true&AjaxCallType=' + ajaxCallType + '&un=' + userName + '&pw=' + pw + '&sl=' + saveLogin); 
	},
	forgotLogin: function (userName, urlXmlPost, ajaxCallType)
	{
			$("#emailSending").show();
			$(".btnSendPW").hide();
			//the dock event is fired twice. once on the undock and once on the dock
			//we are not interested in the first event, so if the eventargs elem id is null, exit the function
			xmlHttp = GetXmlHttpObject(stateChangeHandlerForgotLogin);  
			//Send the xmlHttp get to the specified url 
			xmlHttp_Get(xmlHttp, urlXmlPost + '?IsAjaxRequest=true&AjaxCallType=' + ajaxCallType + '&un=' + userName); 
	},
	logoff: function()
	{
		xmlHttp = GetXmlHttpObject(stateChangeHandlerLogout);  
		//Send the xmlHttp get to the specified url 
		
		xmlHttp_Get(xmlHttp, window.location + '?IsAjaxRequest=true&IsLogout=true'); 
	},
	CreateMember:function (member, urlXmlPost, ajaxCallType)
	{
			var error = "";
			//the dock event is fired twice. once on the undock and once on the dock
			//we are not interested in the first event, so if the eventargs elem id is null, exit the function
			xmlHttp = GetXmlHttpObject(stateChangeHandlerReg);  
			//Send the xmlHttp get to the specified url 
			var firstName = ""; 
			if(member.FirstName.length != 0)
			{
				firstName = "&fn=" + member.FirstName;
			}
			else
			{
				error += "First Name";
			}
			var lastName = ""; 
			if(member.LastName.length != 0)
			{
				lastName += "&ln=" + member.LastName;
			}
			else
			{
				if(error != "")
				{
					error += ", ";
				}
				error += "Last Name";
			}
			var email = "";
			if(member.Email.length != 0)
			{
				email = "&em=" + member.Email;
			}
			else
			{
				if(error != "")
				{
					error += ", ";
				}
				error += "Email";
			}
			var pw = ""; 
			if(member.Password.length != 0)
			{
				pw = "&pw=" + member.Password;
			}
			else
			{
				if(error != "")
				{
					error += ", ";
				}
				error += "Password";
			}
			var address = ""; 
			if(member.Address.length != 0)
			{
				address = "&ad=" + member.Address;
			}
			var city = ""; 
			if(member.City.length != 0)
			{
				city = "&city=" + member.City;
			}
			var state = ""; 
			if(member.State.length != 0)
			{
				state = "&state=" + member.State;
			}
			var zip = ""; 
			if(member.Zip.length != 0)
			{
				zip = "&zip=" + member.Zip;
			}
			var pPhoneType = "";
			var pPhone = ""; 
			if(member.PrimaryPhone.length != 0)
			{
				pPhoneType = "&ptype=" + member.PrimaryPhoneType;
				pPhone = "&phone=" + member.PrimaryPhone;
			}
			var sPhoneType = ""; 
			var sPhone  = ""; 
			if(member.SecondayPhone.length != 0)
			{
				sPhoneType = "&stype=" + member.SecondaryPhoneType;
				sPhone = "&sphone=" + member.SecondayPhone;
			}
			var ei  = ""; 
			if(member.EmailInt != null)
			{
				ei = "&ei=" + member.EmailInt;
			}
			if(error == "")
			{
				xmlHttp_Get(xmlHttp, urlXmlPost + '?IsAjaxRequest=true&AjaxCallType=' + ajaxCallType + firstName + lastName + email + pw + address + city + state + zip + pPhoneType + pPhone + sPhoneType + sPhone + ei); 
			}
			else
			{
				$("#errors").html("These fields cannot be blank: " + error);
			}
	},
	pageListings: function(urlXmlPost)
	{
		xmlHttp = GetXmlHttpObject(stateChangeHandlerPageListing);  
		//Send the xmlHttp get to the specified url
		xmlHttp_Get(xmlHttp, urlXmlPost + '?IsAjaxRequest=true&AjaxCallType=5&PageNum=' + MapPage + '&time=' + new Date());
	},
	runSearch:function(coords)
	{
		xmlHttp = GetXmlHttpObject(stateChangeHandlerRunSearch);  
		//Send the xmlHttp get to the specified url
		xmlHttp_Get(xmlHttp, window.location + '?IsAjaxRequest=true&AjaxCallType=7&mapCoords=' + coords + '&time=' + new Date());
		$("#propCount").slideDown("fast");
		$("#propCount").html("<img src='../../Images/ajax-loader.gif' /> Calculating selected area");
		
	},
	saveSearch: function(name, ajaxCallType, urlXmlPost)
	{
		if(name != "")
		{
			//show saving msg
			$("#savingMsg").show();
			//hide buttons
			$(".btnSaveSearch").hide();
			$(".btnSaveCancel").hide();
			//the dock event is fired twice. once on the undock and once on the dock
			//we are not interested in the first event, so if the eventargs elem id is null, exit the function
			xmlHttp = GetXmlHttpObject(stateChangeHandlerSave);			
			//Send the xmlHttp get to the specified url 
			xmlHttp_Get(xmlHttp, urlXmlPost + '?IsAjaxRequest=true&AjaxCallType=' + ajaxCallType + '&name=' + name);
		}
		else
		{
			$("#savedError").html("Search name cannot be blank");
			$("#savedError").show();
		}
	},
	checkRates: function(propValue, loanAmount, zip, propType, sortField, sortAscend, urlXmlPost, ajaxCallType)
	{
		xmlHttp = GetXmlHttpObject(stateChangeHandlerCheckRates);  
		//Send the xmlHttp get to the specified url 
		xmlHttp_Get(xmlHttp, urlXmlPost + '?IsAjaxRequest=true&AjaxCallType=' + ajaxCallType + 
		                '&propValue=' + propValue + '&loanAmount=' + loanAmount + '&zip=' + zip + '&propType=' + propType + 
		                '&sortField=' + sortField + '&sortAscend=' + sortAscend + '&rnd=' + Math.random());
		var checkRatesModal = document.getElementById("CheckRatesModal");
		var checkRatesData = document.getElementById("CheckRatesData");
		checkRatesData.innerHTML = "<h2 style='text-align: center;'>Searching for Rates...</h2>";
		checkRatesModal.style.display = "block";
		window.scroll(0,0);
	}

};
//stateChangeHandler will fire when the state has changed, i.e. data is received back 
// This is non-blocking (asynchronous) 
function stateChangeHandlerLogin() 
{ 
    //readyState of 4 or 'complete' represents that data has been returned 
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete'){
		var jsonResponse = eval(xmlHttp.responseText);
        if(jsonResponse.IsValid == "False")
		{
	       $("#loginError").slideDown("fast");
	       $("#loginLoading").hide(); 
	      
		} 
		else
		{
			//hide all login and register controls
			$(".qhLogin").slideUp("fast");
			$("#loginLoading").hide();
			$(".qhRegisterLink").hide();
			$(".qhLoginLink").hide();
			$(".loginOverlay").hide();
			//show all member controls
			$(".memberControls").show();
			$("#memberName").show();
			//if the pageType is Results(2) show the save search link
			if(jsonResponse.pageType == 2)
			{
				$(".saveSeachLink").show();
			}
			//set memberName
			$("#memberName").html("Welcome: " + jsonResponse.memberName);
			
			//Show their member Favorites
			if(jsonResponse.memberFavorite != "")
			{
				var favorites = jsonResponse.memberFavorites.split(",");
				if(favorites.length > 0)
				{
					for(var i = 0; i < favorites.length; i++)
					{

						$("#"+ favorites[i] + "_non").hide();
						$("#"+favorites[i]).show();
					}
				}
			}
		}
    } 
} 
//stateChangeHandler will fire when the state has changed, i.e. data is received back 
// This is non-blocking (asynchronous) 
function stateChangeHandlerForgotLogin() 
{ 
	//readyState of 4 or 'complete' represents that data has been returned 
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete'){
		var jsonResponse = eval(xmlHttp.responseText);
		if(jsonResponse.IsMember == "False")
		{
			$(".ForgotErrorPanel").html("The email provided is not in our records");
			$(".ForgotErrorPanel").slideDown("fast");
			$("#emailSending").hide();
			$(".btnSendPW").show();
		} 
		else
		{
			$(".ForgotErrorPanel").html("Your password has been sent to the email address provided.");
			$(".ForgotErrorPanel").slideDown("fast");
			$("#emailSending").hide();
			$(".btnSendPW").show();
		}
	}
}  

function stateChangeHandlerReg() 
{ 
    //readyState of 4 or 'complete' represents that data has been returned 
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete'){ 
		var jsonResponse = eval(xmlHttp.responseText);
        if(jsonResponse.IsValid == "False")
		{
	       $("#errors").html(jsonResponse.errorMsg);      
		} 
		else
		{
			//hide all login and register controls
			$(".pnlRegister").slideUp("fast");
			$(".qhRegisterLink").hide();
			$(".qhLoginLink").hide();
			$(".loginOverlay").hide();
			//show all member controls
			$(".memberControls").show();
			$("#memberName").show();
			$("#memberName").html("Welcome: " + jsonResponse.memberName);
		}
    } 
} 
function stateChangeHandlerLogout() 
{ 
	//readyState of 4 or 'complete' represents that data has been returned 
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
	{
		//show all login controls
		$("#loginLoading").show();
		$(".qhRegisterLink").show();
		$(".qhLoginLink").show();
		$(".loginOverlay").show();
		//hide all member controls
		$(".memberControls").hide();
		$("#memberName").hide();
	}
} 
//default state change handler when no action is required
function stateChangeHandlerDoNothing()
 {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete'){ 
        if(xmlHttp.responseText == 'False')
			{
				$(".loginOverlay").show();
			} 
    } 
 } 
//state change handler for favorites
function stateChangeHandlerFavorite()
 {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete'){ 
		var jsonResponse = eval(xmlHttp.responseText); 
        if(jsonResponse.IsSuccess == 'False'){
			$(".loginOverlay").show();
			$("#closeBubble").show();
			$("#bubble").show();
		} 
		else{
			if(jsonResponse.IsFavorite == "True"){
				$("#"+ jsonResponse.MLSNum + "_non").hide();
				$("#" + jsonResponse.MLSNum).show();
			}
			else{
				$("#"+ jsonResponse.MLSNum + "_non").show();
				$("#" + jsonResponse.MLSNum).hide();
			}
		}
    } 
 }  
//state change handler for saveing Search
function stateChangeHandlerSave()
{
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete'){ 
		$(".pnlSaveSearch").slideUp("fast");
    } 
}

//state change handler for pageing map listings
function stateChangeHandlerPageListing()
{
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete'){ 
		var anim = new YAHOO.util.Scroll('listingContainer', attributes, .2);
		$(".propControls").show();
		$(".loadProperties").hide();
		MapPage++;
		PageMaxRetrieved++;
		if((start+4) < listings)
		{
			start = start + 4;
		}
		if((start +4) > listings)
		{
			$("#listingContainer").append(xmlHttp.responseText);
			anim.animate();
			pages.innerHTML = (start +1) +" to " + listings;
			endOfListings = true;
		}
		else
		{
			$("#listingContainer").append(xmlHttp.responseText);
			anim.animate();
			pages.innerHTML = (start +1) +" to " +  (start +4);
		}
		
    } 
}

//state change handler for running mapsearch Search
function stateChangeHandlerRunSearch()
{
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete'){
		var response = xmlHttp.responseText;
		$("#propCount").slideDown("fast");
		$("#propCount").html(response + " properties in selected area");
    } 
}

//state change handler for checking mortgage rates (MortgageRatesModule)
function stateChangeHandlerCheckRates()
{
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete'){
	    var response = xmlHttp.responseText;
	    var checkRatesModal = document.getElementById("CheckRatesModal");
	    var checkRatesData = document.getElementById("CheckRatesData");
	    if (checkRatesModal && checkRatesModal.style.display == "block") // Should be true, unless user Closed overlay
	    {
		    if (response == "")
		    {
		        checkRatesData.innerHTML = "<h3 style='text-align: center;'>Sorry, we are unable to retrieve any Mortgage Rates at the moment.</h3>";
		    }
		    else
		    {
		        checkRatesData.innerHTML = response;
		    }
		}
    } 
}


// XMLHttp send GET request 
function xmlHttp_Get(xmlhttp, url) { 
    xmlhttp.open('GET', url, true); 
    xmlhttp.send(null); 
} 

function GetXmlHttpObject(handler) { 
    var objXmlHttp = null;    //Holds the local xmlHTTP object instance 

    //Depending on the browser, try to create the xmlHttp object 
    if (is_ie){ 
        //The object to create depends on version of IE 
        //If it isn't ie5, then default to the Msxml2.XMLHTTP object 
        var strObjName = (is_ie5) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP'; 
         
        //Attempt to create the object 
        try{ 
            objXmlHttp = new ActiveXObject(strObjName); 
            objXmlHttp.onreadystatechange = handler; 
        } 
        catch(e){ 
        //Object creation errored 
            alert('IE detected, but object could not be created. Verify that active scripting and activeX controls are enabled'); 
            return; 
        } 
    } 
    else if (is_opera){ 
        //Opera has some issues with xmlHttp object functionality 
        alert('Opera detected. The page may not behave as expected.'); 
        return; 
    } 
    else{ 
        // Mozilla | Netscape | Safari 
        objXmlHttp = new XMLHttpRequest(); 
        objXmlHttp.onload = handler; 
        objXmlHttp.onerror = handler; 
    } 
     
    //Return the instantiated object 
    return objXmlHttp; 
} 
function echeck(str) {
		var error = "";
		var at="@";
		var dot=".";
		var lat=str.indexOf(at);
		var lstr=str.length;
		var ldot=str.indexOf(dot);
		if (str.indexOf(at)==-1){
		   error = "Email Address is not in the correct format";
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   error = "Email is not in the correct format";
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    error = "Email is not in the correct format";
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    error = "Email is not in the correct format";
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    error = "Email is not in the correct format";
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    error = "Email is not in the correct format";
		 }
		
		 if (str.indexOf(" ")!=-1){
		    error = "Email is not in the correct format";
		 }
		return error; 
	}

var validation = {
ValidateEmail:function (emailID){
		var error = "";
		error = echeck(emailID);
		return error;
	}
}; 

function CloseRegistration()
{
	$(".pnlRegister").slideUp("fast");
}

