/*
* The programming and software materials herein are copyright Cyberhomes LLC (CH).
* The programming and software materials are owned, held, or licensed by CH. Personal, educational,
* non-commercial, commercial or any other use of these materials, without the written permission of the
* CH, is strictly prohibited.
*/

/*********************************************************
This file contains JavaScript for Quick Search Widget. 
**********************************************************/ 

// General functions
function replace(string,text,by) 
{
	// Replaces text with by in string
	var strLength = string.length, txtLength = text.length;
	if ((strLength == 0) || (txtLength == 0)) return string;

	var i = string.indexOf(text);
	if ((!i) && (text != string.substring(0,txtLength))) return string;
	if (i == -1) return string;

	var newstr = string.substring(0,i) + by;

	if (i+txtLength < strLength)
		newstr += replace(string.substring(i+txtLength,strLength),text,by);

	return newstr;
}
function IsLetter(sText)
{
	var ValidChars = "-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\'. &,()"
	var IsLetter = true;
	var Char;
	for (i = 0; i < sText.length && IsLetter == true; i++) 
	{ 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) 
		{
			IsLetter = false;
		}
	}
	return IsLetter;

}
function IsChar(sText)
{
	var ValidChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var IsChar = true;
	var Char;
	for (i = 0; i < sText.length && IsChar == true; i++) 
	{ 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) 
		{
			IsChar = false;
		}
	}
	return IsChar;

}

function IsCharPlusSpecial(sText)
{
	var ValidChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^*()_+-=";
	var IsChar = true;
	var Char;
	for (i = 0; i < sText.length && IsChar == true; i++) 
	{ 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) 
		{
			IsChar = false;
		}
	}
	return IsChar;
}

function TrimString(sInString) 
{
	sInString = sInString.replace( /^\s+/g, "" );	// strip leading
	return sInString.replace( /\s+$/g, "" );		// strip trailing
}


// Validate Zip and Adderss Search
function validateZipAndAddress()
{
    var city;
	var state; 
	var zipCd;
	
	if (document.ListingQuickSearch1.elements && document.ListingQuickSearch1.elements['Criteria/City'])
	{
		city = document.ListingQuickSearch1.elements['Criteria/City'].value;
		city = TrimString(city);	
	}
	else 
		city = null;
	
	if (document.ListingQuickSearch1.elements && document.ListingQuickSearch1.elements['Criteria/StateOrProvinceCode'])
		state = document.ListingQuickSearch1.elements['Criteria/StateOrProvinceCode'].value;
	else 
		state = null;
		
	if(document.ListingQuickSearch5.elements && document.ListingQuickSearch5.elements['Criteria/ZipCode'])
	{
		zipCd = document.ListingQuickSearch5.elements['Criteria/ZipCode'].value;
		zipCd = TrimString(zipCd);
	}
	else
		zipCd = null;

    if ((city != null && city != '') && (state != null && state != '') && (zipCd != null && zipCd != ''))
    {
        if ((zipCd.length > 0) && (city.length == 0) && (state.length == 0))
        {
            document.getElementById('Button').name = "Button/ZipCode"; 
            document.getElementById('Criteria/ZipCode').value = zipCd ;
            return validateZipCode();
        }
        else
        {
            if(state.length == 0 && city.length > 0)
            {
                alert('Please select State');
                return false;
            }
            else
            {
                document.getElementById('Button').name = "Button/StreetAddress"; 
                return validateAddress();
            }
        }
    }
}

// Validate Address Search
function validateAddress()
{
	var stNum;
	var stName;
	var city;
	var state;
	
	if (document.ListingQuickSearch1.elements && document.ListingQuickSearch1.elements['Criteria/StreetNumber'])
	{
		stNum = document.ListingQuickSearch1.elements['Criteria/StreetNumber'].value;
		stNum = TrimString(stNum);
	}
	else 
		stNum = null;
	if (document.ListingQuickSearch1.elements && document.ListingQuickSearch1.elements['Criteria/StreetName'])
	{
		stName = document.ListingQuickSearch1.elements['Criteria/StreetName'].value;
		stName = TrimString(stName);	
	}
	else 
		stName = null;
	if (document.ListingQuickSearch1.elements && document.ListingQuickSearch1.elements['Criteria/City'])
	{
		city = document.ListingQuickSearch1.elements['Criteria/City'].value;
		city = TrimString(city);	
	}
	else 
		city = null;
	if (document.ListingQuickSearch1.elements && document.ListingQuickSearch1.elements['Criteria/StateOrProvinceCode'])
		state = document.ListingQuickSearch1.elements['Criteria/StateOrProvinceCode'].value;
	else 
		state = null;
	
	if ( city == null && state != null )
	{
		alert('Quick Search is not set up properly: missing City. \n\nPlease contact administrator.');
		return false;
	}
	// None presents
	if (state == null && city == null && stNum == null && stName == null)
		return true;
	// Address (House Number and Street Name) presents; City doesn't
	if ( (stNum != null || stName != null) && city == null )
		return validateStreetAddress();
	// Address (House Number and Street Name) doesn't present; City does
	if ( (stNum == null && stName == null) && city != null )
		return validateCity();
	
	// The following: Address (House Number and Street Name) and City present
	
	// Neither Address (House Number and Street Name) nor City has input.
	if ((stNum == '' && stName == '') && city == '')
	{
		alert('Please enter House Number, Street Name or City information.');
		return false;
	}
	// Address has input; City doesn't have.
	else if ((stNum != '' || stName !='') && city == '')
	{
		return validateStreetAddress();
	}
	// Address has no input; City has.
	else if ((stNum == '' && stName == '') && city != '')
	{
		return validateCity();
	}
	// Both have input.
	else	// ((stNum != '' || stName !='') && city != '')
	{
		return ( validateStreetAddress() && validateCity() )
	}	
}
function validateStreetAddress() 
{
	var streetNum;
	var streetName;

	if (document.ListingQuickSearch1.elements['Criteria/StreetNumber'])
	{
		streetNum = document.ListingQuickSearch1.elements['Criteria/StreetNumber'].value;
		streetNum = TrimString(streetNum);
	}
	else 
		streetNum = null;	
	if (document.ListingQuickSearch1.elements['Criteria/StreetName'])
	{
		streetName = document.ListingQuickSearch1.elements['Criteria/StreetName'].value;
		streetName = TrimString(streetName);
	}
	else 
		streetName = null;
	
	// (1) Both are not presented.
	if (streetNum == null && streetName == null)
	{
		return true;
	}
	// (2) One presents but another doesn't.
	if ( (streetNum == null && streetName != null) || (streetNum != null && streetName == null) )
	{
		//BOET4799: Non Structured search for Edina and others
		if( (streetNum == null)  && (streetName != null) )
		{
			if (streetName == '')
			{
				alert('Please enter address.');
				return false;
			}
			else
			{
				return true;
			}
		}
		else
		{
			alert('Search is not set up properly. \n\nPlease contact administrator.');
			return false;
		}
	}
	// (1) and (2) handle the null situation. The following always present and have no null.
	
	// (3) Both have no input.
	if (streetNum == '' && streetName == '')
	{
		alert('Please enter House Number or Street Name.');
		return false;
	}										
	// (4) Street Number has input but Street Name doesn't.
	else if (streetNum != '' && streetName == '')
	{
		return validateStreetNumber();
	}
	// (5) Street Number doesn't have input but Street Name does.
	else if (streetNum == '' && streetName != '')
	{
		return validateStreetName();
	}
	// (6) Both have input.
	else	// (streetNum != '' && streetName != '')
	{
		return ( validateStreetNumber() && validateStreetName() )	
	}
}
function validateStreetNumber()
{
	if (document.ListingQuickSearch1.elements['Criteria/StreetNumber'])
	{
		var streetNum = document.ListingQuickSearch1.elements['Criteria/StreetNumber'].value;
		streetNum = TrimString(streetNum);
		if (streetNum.length < 1)
		{
			alert('House Number should be at least 1 character.');
			return false;
		}
		streetNum = replace(streetNum, "'", "");
		document.ListingQuickSearch1.elements['Criteria/StreetNumber'].value = streetNum;
		streetNum = replace(streetNum, ".", "");
		streetNum = replace(streetNum, " ", "");
		var validChar = IsChar(streetNum);
		if (validChar != true)
		{
			alert('House Number should be number or letter.');
			return false;
		}
		return true;
	}
	else 
	{
		return true;
	}
}
function validateStreetName()
{
	if (document.ListingQuickSearch1.elements['Criteria/StreetName'])
	{
		var streetName = document.ListingQuickSearch1.elements['Criteria/StreetName'].value;
		streetName = TrimString(streetName);
		if (streetName.length < 2)
		{
			alert('Street Name should be at least 2 characters.');
			return false;
		}
		streetName = replace(streetName, "'", "");
		document.ListingQuickSearch1.elements['Criteria/StreetName'].value = streetName;
		streetName = replace(streetName, ".", "");
		streetName = replace(streetName, " ", "");
		var validChar = IsChar(streetName);
		if (validChar != true)
		{
			alert('Street Name should be number or letter.');
			return false;
		}
		return true;
	}
	else 
	{
		return true;
	}
}
function validateCity()
{
	if (document.ListingQuickSearch1.elements['Criteria/City'])
	{
		var city = document.ListingQuickSearch1.elements['Criteria/City'].value;
		city = TrimString(city);
		if (city.length < 2)
		{
			alert('City must be at least 2 characters.');
			return false;
		}
		if (city.length > 250)
		{
			alert('City must not be more than 250 characters.');
			return false;
		}
		city = replace(city, "'", "");
		city = replace(city, ".", "");
		city = replace(city, " ", "");
		city = replace(city, ",", ""); // Allow delimited list of cities
		city = replace(city, "-", ""); //BOET:4669 [John Zarate] Allow dashes in city search same as property search
		var validChar = IsLetter(city);
		if (validChar != true)
		{
			alert('City contains invalid characters.');
			return false;
		}
		return true;
	}
	else 
	{
		return true;
	}
}

// Validate Hotline Code
function validateHotline()
{
	if (document.ListingQuickSearch3.elements && document.ListingQuickSearch3.elements['Criteria/HotlineCode'])
	{
		var hotlineCd = document.ListingQuickSearch3.elements['Criteria/HotlineCode'].value;
		if ( hotlineCd.length == 0)
		{
			alert('Please enter Hotline code.');
			return false;
		}
		if ( hotlineCd.length > 10 )
		{
			alert('Hotline code should be less than 10 characters.');
			return false;
		}
		hotlineCd = replace(hotlineCd, " ", "");
		var validChar = IsCharPlusSpecial(hotlineCd);
		if (validChar != true)
		{
			alert('Hotline Code should be letters.');
			return false;
		}
		return true;
	}
	else
	{
		return true;
	}
}

// Validate Zip Code and Price Range
function validatePriceRangeZipCode()
{
	var priceMin;
	var priceMax;
	var zipCd;
	
	if(document.ListingQuickSearch5.elements && document.ListingQuickSearch5.elements['Criteria/MinPrice'])
	{
		priceMin = document.ListingQuickSearch5.elements['Criteria/MinPrice'].value;
		priceMin = TrimString(priceMin);
	}
	else
		priceMin = null;
		
	if(document.ListingQuickSearch5.elements && document.ListingQuickSearch5.elements['Criteria/MaxPrice'])
	{
		priceMax = document.ListingQuickSearch5.elements['Criteria/MaxPrice'].value;
		priceMax = TrimString(priceMax);
	}
	else
		priceMax = null;
		
	if(document.ListingQuickSearch5.elements && document.ListingQuickSearch5.elements['Criteria/ZipCode'])
	{
		zipCd = document.ListingQuickSearch5.elements['Criteria/ZipCode'].value;
		zipCd = TrimString(zipCd);
	}
	else
		zipCd = null;
	
	// Both price range and zip code are not presented on the web page.
	if ( zipCd == null && (priceMin == null && priceMax == null) )
		return true;
	// Price range presents only min or max.
	if ( (priceMin != null && priceMax == null) || (priceMin == null && priceMax != null) )
	{
		alert('Price should be in a range. /nFor example: 50000 to 90000');
		return false;
	}
	// Zip code presents; price range doesn't.
	if ( zipCd != null && (priceMin == null && priceMax == null) )
		return validateZipCode();
	// Zip code doesn't present; price range does.
	if ( zipCd == null && (priceMin != null && priceMax != null) )
		return validatePriceRange();
		
	// The following: both zip code and price range present.
	// Noen has input.
	if ( zipCd == '' && (priceMin == '' && priceMax == '') )	
	{
		alert('Please enter zip code or price range.');
		return false;
	}
	// Zip code has input; price range doesn't.
	else if ( zipCd != '' && (priceMin == '' && priceMax == '') )
		return validateZipCode();
	// Zip code doesn't have input; price range has.
	else if ( zipCd == '' && (priceMin != '' || priceMax != '') )
		return validatePriceRange();
	// Zip code has input; price range has input.
	else // ( zipCd != '' && (priceMin != '' && priceMax != '') )
		return ( validateZipCode() && validatePriceRange() );

}
function validateZipCode()
{
	if(document.ListingQuickSearch5.elements['Criteria/ZipCode'])
	{
		var zipCd = document.ListingQuickSearch5.elements['Criteria/ZipCode'].value;
		zipCd = TrimString(zipCd);
		if (zipCd.length == 0)
		{
			alert('Please enter zip code.');
			return false;
		}
		if (zipCd.length != 5)
		{
			alert('Zip code must be 5 digits.');
			return false;
		}
		if (!IsNumeric(zipCd))
		{	
			alert('Zip code must be numeric.');
			return false;
		}
		return true;	
	}
	else
	{
		return true;
	}
}
function validatePriceRange()
{
	if(document.ListingQuickSearch5.elements['Criteria/MinPrice'] && document.ListingQuickSearch5.elements['Criteria/MaxPrice'])
	{
		var min = document.ListingQuickSearch5.elements['Criteria/MinPrice'].value;
		var max = document.ListingQuickSearch5.elements['Criteria/MaxPrice'].value;
		min = TrimString(min);
		max = TrimString(max);
		min = replace(min, ",", "");
		max = replace(max, ",", "");
		min = replace(min, ".", "");
		max = replace(max, ".", "");
		min = replace(min, "'", "");
		max = replace(max, "'", "");
		min = replace(min, "$", "");
		max = replace(max, "$", "");											
		document.ListingQuickSearch5.elements['Criteria/MaxPrice'].value = max;
		document.ListingQuickSearch5.elements['Criteria/MinPrice'].value = min;
		
		if ( min.length == 0 && max.length == 0)
		{	
			alert('Please enter price range.');
			return false;
		}
		if (!IsNumeric(min) || !IsNumeric(max))
		{
			alert('Price Range should be numeric. \nFor example: 500000');
			return false;
		}
		else if (max-0 < min-0)
		{
			alert('Minimum Price should be less than Maximum Price.');
			return false;
		}
		else
			return true;	
	}
	else
		return true;				
}

// Validate MLS#
function validateMLSNumber()
{
	if (document.ListingQuickSearch4.elements && document.ListingQuickSearch4.elements['Criteria/ListingNumber'])
	{
		var mlsNum = document.ListingQuickSearch4.elements['Criteria/ListingNumber'].value;
		if ( mlsNum.length == 0)
		{
			alert('Please enter MLS Number.');
			return false;
		}
		mlsNum = replace(mlsNum, "-", "");
		mlsNum = replace(mlsNum, " ", "");
		mlsNum = replace(mlsNum, ",", "");	// allow comma because of multiple MLS# input
		var validChar = IsChar(mlsNum);
		if (validChar != true)
		{
			alert('MLS Number should be number or letter.');
			return false;
		}
		return true;
	}
	else
	{
		return true;
	}
}
// This function is in the old page.
function mlsLookup()
{
	if (document.MLSLookup.elements['MLSNumber'])
	{
		var mlsnum = document.MLSLookup.elements['MLSNumber'].value;
		mlsnum = replace(mlsnum, " ", "");
		// if (mlsnum != '' &amp;&amp; IsChar(mlsnum))		// XSL version
		//	document.MLSLookup.action = "<xsl:value-of select="concat('http://', /Render/State/RECo/PublicHostHeader, '/Consumer/Listing/ProcessListingNumberSearch.aspx?ListingNumber=')"/>" + mlsnum
		// else...
		if (mlsnum != '' && IsChar(mlsnum))
		    document.MLSLookup.action = '<%# "http://" + ContextData.RECo.PublicHostHeader + Utils.PublicAppName + "/Listing/ProcessListingNumberSearch.aspx?ListingNumber=" %>' + mlsnum
		else
		{
			alert("Please Enter a Valid MLS Number");
			return false;
		}
	}
}

// Validate Agent Last Name
function validateAgentLastName()
{
	if (document.ListingQuickSearch6.elements && document.ListingQuickSearch6.elements['AgentSearchCriteria/LastName'])
	{
		var aLName = document.ListingQuickSearch6.elements['AgentSearchCriteria/LastName'].value;
		aLName = TrimString(aLName);
		if ( aLName.length == 0 )
		{
			alert('Please enter agent last name.');
			return false;
		}
		if ( aLName.length < 2)
		{
			alert('Agent last name should be at least 2 characters.');
			return false;
		}
		aLName = replace(aLName, " ", "");
		aLName = replace(aLName, "'", "");
		var validChar = IsLetter(aLName);
		if (validChar != true)
		{
			alert('Agent Last Name should be letters.');
			return false;
		}
		return true;
		return true;
	}
	else
	{
		return true;
	}
}

// Clear Quick Search Widget
function clearQuickSearch()
{
	// Loop through forms in page and clear if matches quicksearch
	for(j=0; j < document.forms.length; j++)
	{
		// Address
		if (document.forms[j].name == 'ListingQuickSearch1')
		{
			document.forms[j].reset();	
			if (document.getElementById('Criteria/StateOrProvinceCode'))
			{
				setDefaultState(j);
			}
			var theForm = document.forms[j];
			for(i=0; i<theForm.elements.length; i++)
			{
				if(theForm.elements[i].type == "text")
				{	
					theForm.elements[i].value="";
				}
			}
		}
		
		// Hotline
		if (document.forms[j].name == 'ListingQuickSearch3')
		{
			document.forms[j].reset();
			var theForm = document.forms[j];
			for(i=0; i<theForm.elements.length; i++)
			{
				if(theForm.elements[i].type == "text")
				{	
					theForm.elements[i].value="";
				}
			}
		}
		
		// MLS Number
		if (document.forms[j].name == 'ListingQuickSearch4')
		{
			document.forms[j].reset();
			var theForm = document.forms[j];
			for(i=0; i<theForm.elements.length; i++)
			{
				if(theForm.elements[i].type == "text")
				{	
					theForm.elements[i].value="";
				}
			}
		}
		
		// Zip Code and Price Range
		if (document.forms[j].name == 'ListingQuickSearch5')
		{
			document.forms[j].reset();
			var theForm = document.forms[j];
			for(i=0; i<theForm.elements.length; i++)
			{
				if(theForm.elements[i].type == "text")
				{	
					theForm.elements[i].value="";
				}
			}
		}
		
		// Agent Last Name
		if (document.forms[j].name == 'ListingQuickSearch6')
		{
			document.forms[j].reset();
			var theForm = document.forms[j];
			for(i=0; i<theForm.elements.length; i++)
			{
				if(theForm.elements[i].type == "text")
				{	
					theForm.elements[i].value="";
				}
			}
		}
	}
}

// only for HUS state drop down list
function setDefaultState( formNumber )
{
	if (document.forms[formNumber] && document.forms[formNumber].elements && document.forms[formNumber].elements['Criteria/StateOrProvinceCode'])
	{
		for (i = 0; i < document.forms[formNumber].elements['Criteria/StateOrProvinceCode'].options.length; i++)
		{
			// This is for the .NET version
			if (document.forms[formNumber].elements['Criteria/StateOrProvinceCode'].options[i].value == "<%# DefaultStateCode %>")
			{
				document.forms[formNumber].elements['Criteria/StateOrProvinceCode'].selectedIndex = i;
			}
			// This is for the XSL version. This is directly put in the incQuickSearch.xsl.
			/*
			if ( document.ListingQuickSearch1.elements['Criteria/StateOrProvinceCode'].options[i].value == '<xsl:value-of select="/Render/State/RECo/State/StateCode" />' )
			{
				document.ListingQuickSearch1.elements['Criteria/StateOrProvinceCode'].selectedIndex = i;
			}
			*/
			
		}
	}	
}	

function runOnce()
{
	// Lack of a state drop down selection will indicate that we should set a default based on RECo.
	// RECo might not support State drop down so exclude if element is null.
	// Using browser's back button should not trigger this...
	if (document.ListingQuickSearch1 && document.ListingQuickSearch1.elements && document.ListingQuickSearch1.elements['Criteria/StateOrProvinceCode'])
	{	
		if (document.ListingQuickSearch1.elements['Criteria/StateOrProvinceCode'].selectedIndex == 0)
		{
			setDefaultState();
		}
	}		
}
window.onload = runOnce;	