// Form Element functions.
// goes in the common main.js file FE == form elements
function FE_isemail(el) {
	if (el.value.length > 0) {
		return (el.value.search (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/) == 0);
	}
	return true;
}

function FE_istextonly(el) {
	/*if (el.value.match (/^[a-zA-Z\s\-\.\'ÁÉÍÓÚÝáéíóúýÀÈÌÒÙàèìòùÂÊÎÔÛâêîôûçÇ\s]*$/)) {
		alert ("text")
	} else {
		alert ("not text")
	}*/
	return (el.value.match (/^[a-zA-Z\s\-\.\'ÁÉÍÓÚÝáéíóúýÀÈÌÒÙàèìòùÂÊÎÔÛâêîôûçÇ\s]*$/));
}

function FE_isalphanumeric(el) {
	return (el.value.match (/^[a-zA-Z0-9\s\-\.\'ÁÉÍÓÚÝáéíóúýÀÈÌÒÙàèìòùÂÊÎÔÛâêîôûçÇ\s]*$/));
}

function FE_isphone(el) {
	if (el.value.length > 0) {
		return (el.value.search (/^[0-9\-\. \s\(\)]*$/) == 0);
	}
	return true;
}

function FE_ispostal(el) {
	return (el.value.search (/^\w\d\w(\s)?\d\w\d$/) == 0);
}

function FE_iszip(el) {
	return (el.value.search (/^\d{5,5}$/) == 0);
}

function FE_isblank(el) {
	
/*	if (el.value.match (/^[\s ]*$/)) {
		alert ("blank")
	} else {
		alert ("not blank")
	} */
	return (el.value.match (/^[\s ]*$/));
}

function FE_islengthlt (el, m_l) {
	return el.value.length < m_l;
}

function FE_islengthgt (el, m_l) {
	return (el.value.length > m_l);
}

function FE_isinteger(el) {
	return (el.value.match (/^[\d]*$/));
}

function FE_iscurrency(el) {
	return el.value.match (/^\s*[$]?\s*\d+(\s*(,)?\s*\d+)*(\s*[.|,]?\s*\d+)?\s*[$]?\s*$/);
}
// ----------- 
// combo boxes 

function FE_valueis (el, m_l) {
	return (el.value == m_l)
}

function SH (id) {
	var d = document;
	el = d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
	try{
	if (window.innerHeight && el.document){ 
		el.style.height =  0;
		el.style.height = Math.max (400, el.document.height + 40) + "px";
	} 
	if ( document.body.clientHeight && window.frames[id].document) {
		el.style.height =  0;
		el.style.height =  Math.max (400, window.frames[id].document.body.scrollHeight + 40) + "px";
	} 
	
	if (!navigator.userAgent.toLowerCase().match(/safari/)) {
		window.location="#toppage";
	}
	}
	catch(e){el.style.height = "1000px"}
}

function showPS () {
	var d = document;
	id ="propertySearch";
	el = d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
	el.className = "searchRegion"
	id ="agentSearch";
	el = d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
	el.className = "searchRegionHidden"
	id ="officeSearch";
	el = d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
	el.className = "searchRegionHidden"

	id ="PSLabel";
	el = d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
	el.className="searchButton searchSelected";
	id ="ASLabel";
	el = d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
	el.className="searchButton searchUnselected";
	id ="OSLabel";
	el = d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
	el.className="searchButton searchUnselected";
}

function showAS () {
	var d = document;
	id ="propertySearch";
	el = d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
	el.className = "searchRegionHidden"
	id ="agentSearch";
	el = d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
	el.className = "searchRegion"
	id ="officeSearch";
	el = d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
	el.className = "searchRegionHidden"

	id ="PSLabel";
	el = d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
	el.className="searchButton searchUnselected";
	id ="ASLabel";
	el = d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
	el.className="searchButton searchSelected";
	id ="OSLabel";
	el = d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
	el.className="searchButton searchUnselected";
}

function showOS () {
	var d = document;
	id ="propertySearch";
	el = d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
	el.className = "searchRegionHidden"
	id ="agentSearch";
	el = d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
	el.className = "searchRegionHidden"
	id ="officeSearch";
	el = d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
	el.className = "searchRegion"

	id ="PSLabel";
	el = d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
	el.className="searchButton searchUnselected";
	id ="ASLabel";
	el = d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
	el.className="searchButton searchUnselected";
	id ="OSLabel";
	el = d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
	el.className="searchButton searchSelected";
}

function setButtons () {
	id ="html";
	var d = document;
	el = d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
}
function showSLZR () {
	if (( typeof( window[ 'showShare' ] ) != "undefined" ) && (showShare)) {
		var swHTML =element ("saTemp");
		var swTitleContainer = element ("mainContent");

		var yy = swTitleContainer.getElementsByTagName("span");
		var zz= null;
		var found = false; 
		for (i=0; i<yy.length;i++) {
			if (yy.item(i).className == "title" ) {
				zz = yy.item(i);
				yy.item(i).style.cssText="";
				found = true;
				break;
			}
		}
		if (!found) {
			yy = swTitleContainer.getElementsByTagName("H1");

			for (i=0; i<yy.length;i++) {
				zz = yy.item(i);
				found = true;
				break;
			}

		}
	}
}
function init () {
	setButtons ();
	showSLZR () ;
}

function element (id) {
	var d = document;
	el = d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
	return el;
}

var secondLevel = true;
var thirdLevel = true;
var firstLevelNavName = "";
var secondLevelNavName = "";
var secondLevelLabel = "";
var actLikeURL = "";
var breadcrumbs = "";
var showOSNav = false;
var showASNav = false;


function populate(el, a) {
	var x = element (el.parentNode.parentNode.id.replace(/^dd/, ""));
	if (x != null) {
		x.value = a;
	}
}
function swapA() {
	secondLevel = true;
	thirdLevel = false;
	nav();
}
function swapB() {
	secondLevel = true;
	thirdLevel = true;
	nav();
}


function showDD(a) {
	var x = element ("dd" + a.id);
	x.className="dd show";
}
function hideDD(a) {
	setTimeout("delayHideDD('dd"+a.id+"')", 500)
}
function delayHideDD(a) {
	var x = element (a);
	x.className="dd hide";
}


function nav () {
	var bc_one = "";
	var bc_two = "";
	var bc_three = "";
	var bc_four = "";


	x = element ("navigationContainer");
	if (x != null) {
		x.className = "";
	}
	if (!secondLevel) {

		var x = element ("secondary")
		if (x != null) {
			x.className = "hide";
		}
	}

	if (secondLevel) {
		var x = element ("navigation")
		if (x != null) {
			x.className = secondLevelNavName;
		}
	}

	if (firstLevelNavName != "" ) {
		x = element (firstLevelNavName);
		y = x.getElementsByTagName("a");
		y.item(0).className += " selected";
	}

	if (secondLevelLabel != "" ) {
		x = element (secondLevelLabel);
		y = x.getElementsByTagName("a");
		y.item(0).className += " subMenuItemselected";
	}


	x = element ("thirdNav");
	aLURL = (window.location.href.substring(0, window.location.href.indexOf("/", 9)) + actLikeURL).toUpperCase();
	// the "9" is the first slash after "http://" (7 chars) or "https://" (8 chars)
	if (x != null) {
		var x = el.getElementsByTagName("a");
		for (i=0;i<x.length;i++) {
			//alert (aLURL + " (act like url) \n" + x.item(i).toString().toUpperCase() + " (link url)\n" + window.location.href.toUpperCase() + " (page url)" );
			if (window.location.href.toUpperCase() == x.item(i).toString().toUpperCase() || (aLURL ==  x.item(i).toString().toUpperCase() ) ) {
				x.item(i).parentNode.className +=" thirdLevelSelected";
				//bc_three = x.item(i).parentNode.innerHTML;
			}
		}
	
	}
	//breadcrumbs = "<div id=\"breadcrumbs\">" + " > " + bc_three + "</div>"
}

function replaceQuotes(input)
{
	var s = input.replace(/’/g,"'").replace(/’/g,"`").replace(/´/g,"'");
	return s;
}

function submitSearch () 
{
	var cityBox = element('propertySearchBox');
	if(cityBox == null)
	{
	    cityBox = element('ctl00_propertySearchBox');
	}
	
	var city = cityBox.value;
	if(cityBox.className == "hint")
	{
	    city = "";
	}
	
	var s = "";
	if(city != "")
    {
    	city = escape(utf8encode(replaceQuotes(city)));
        var propObj = element('pType');
	    var lowObj = element('min');
	    var highObj = element('max');
	    var bedObj = element('beds');
	    var bathObj = element('baths');
	   
	    /* noteto self: clean this up krishan - MESSY/SLOPPY CODE */
	    var language = "en";
	    var locale="en"
	    if (isFrench()) {
		    language="fr";
		    locale = "fr_CA"
	    }
	    /* end note */

	    s="/jumplisting/googleMapSearch.do?brandId=rlp&bb=1&language=" + language + "&locale="+ locale+"&source=2&country=CAN&city=" + city + "&low=" + lowObj.value.replace(/,/, "") + "&hi=" +highObj.value.replace(/,/, "") +"&bed=" + bedObj.value+"&bath=" + bathObj.value + "&type=" + propObj.value;
	}
	else {

	    if (isFrench()) {
		    alert ("Vous devez inscrire une ville et province, un code postal ou un no. MLS® pour lancer une recherche.");
		return s;
	    }
		alert ("You must enter a city & province, postal code or MLS®# to begin a search.");
	}
	return s;	
}
function submitEnter (myfield, e, whichsearch) {
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13) {
		if (whichsearch == 'a') {
			submitAgent ();
		}
		else if (whichsearch == 'o') {
			submitOffice ();
		}
		else if (whichsearch == 'ac') {
		    submitAgentComm ();
		}
		else {
			submitList();
		}

		return false;
	}
	else {
		return true;
	}
}

function utf8encode(string){
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	}

function submitList () {
	var x = submitSearch () ;
	if(x != "")
	{
	    top.location.href = x + "&view=list";
	}
}
function submitMap () {
	var x = submitSearch () ;
	if(x != "")
	{
	    top.location.href = x + "&view=map";
    }
}
function submitAgentComm () 
{
    var url = getAgentSearchUrl().replace(/AgentResults/g,"AgentResultsComm");
    if(url != "")
    {
        top.location.href = url;
    }
}
function submitAgent () {
    var url = getAgentSearchUrl();
    if(url != "")
    {
        top.location.href = url;
    }
}
function getAgentSearchUrl() {
    var url = "";
	var name = element('agentNameSearchBox').value;
	if(element('agentNameSearchBox').className== "hint" )
	{
	    name = "";
	}
	
	var cityBox = element('agentCitySearchBox');
	if(cityBox == null)
	{
	    cityBox = element('ctl00_agentCitySearchBox');
	}
	
	var city = cityBox.value;
	if(cityBox.className == "hint" )
	{
	    city = "";
	}

	if (name =="" && city =="" ) 
	{
		if (isFrench()) {
		    alert ("Vous devez inscrire le nom d’un agent ou une ville pour lancer une recherche.");
			return url;
	    }
		else 
		{
			alert ("You must enter an agent name or city to begin a search.");
			return url;
		}
	}
	if (name =="" && city.length < 3 ) 
	{
		if (isFrench()) 
		{
		    alert ("Vous devez inscrire au moins 3 caractères dans le champ Ville.");
			return url;
	    }
		else 
		{
			alert ("You must enter at least 3 characters under City.");
			return url;
		}
	}
	if (name !="" && name.length < 2 ) 
	{
		if (isFrench()) 
		{
		    alert ("Vous devez inscrire au moins 2 caractères dans le champ nom d'agent.");
			return url;
	    }
		else 
		{
			alert ("You must enter at least 2 characters under Agent's Name.");
			return url;
		}
	}
	
	
	var languageObj = element('ASlanguage');
	var languageValue = (languageObj[languageObj.selectedIndex].value );
	var specObj = element('ASspec');
	var specValue = (specObj[specObj.selectedIndex].value );

    if(!(name=="" && city==""))
    {
    	city = escape(utf8encode(replaceQuotes(city)));
	    var folder = "";
	    if (isFrench()) 
	    {
		    folder="/francais";
	    }

        var url = folder+"/AgentSearch/AgentResults.aspx?Name="+name+"&City="+city+"&PropSpec="+specObj.value+"&Language="+languageValue+"&Number=10";
	    if(element('eagent')!= null && element('eagent').checked)
	    {
	        url += "&eagent=1"
	    }
	    if(element('sres') != null && element('sres').checked)
	    {
	        url += "&sres=1"
	    }
	    if(element('nagab') != null && element('nagab').checked)
	    {
	        url += "&nagab=1"
	    }
	    if(element('shelter') != null && element('shelter').checked)
	    {
	        url += "&shelter=1"
	    }
	    if(element('social') != null && element('social').checked)
	    {
	        url += "&social=1"
	    }
	    if(element('abr') != null && element('abr').checked)
	    {
	        url += "&abr=1"
	    }
	}
	return url;
}
function submitOffice () {


	    var folder = "";
	    if (isFrench()) {
		    folder="/francais";
	    }

	var cityBox = element('officeCitySearchBox');
	if(cityBox == null)
	{
	    cityBox = element('ctl00_officeCitySearchBox');
	}
	
	var city = cityBox.value;	
    if(cityBox.className == "hint")
	{
	    city = "";
	}
	
    if(city != "")
    {
    	city = escape(utf8encode(replaceQuotes(city)));
	    top.location.href = folder+"/OfficeSearch/OfficeResults.aspx?txtSearchType=address&City="+city+"&cmbNumberResultsPerPage=10";
	}
	if (city =="" ) {

	    if (isFrench()) 
	    {
		    alert ("Vous devez inscrire une ville et province pour lancer une recherche.");
		    return;
	    }
	    
		alert ("You must enter a city & province to begin a search.");
		return;
	}
}

function isFrench()
{
    if ((document.location.href.search(/\/fr\//) > 0) || (document.location.href.search(/francais/) > 0) || 
	    (document.location.href.search(/language=fr/) > 0) || (document.location.href.search(/_fr\./) > 0))
	{
	    return true;
	}
	return false;
}

function checkAS() {
	SubmitAgent();	
}
function checkOS() {
	SubmitAgent();	
}

window.onload = init;




/**************************************** form validation stuff *****************************************/
// Form Element functions.
// goes in the common main.js file FE == form elements
function FE_isemail(el) {
	if (el.value.length > 0) {
		return (el.value.search (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/) == 0);
	}
	return true;
}

function FE_istextonly(el) {
	/*if (el.value.match (/^[a-zA-Z\s\-\.\'ÁÉÍÓÚÝáéíóúýÀÈÌÒÙàèìòùÂÊÎÔÛâêîôûçÇ\s]*$/)) {
		alert ("text")
	} else {
		alert ("not text")
	}*/
	return (el.value.match (/^[a-zA-Z\s\-\.\'ÁÉÍÓÚÝáéíóúýÀÈÌÒÙàèìòùÂÊÎÔÛâêîôûçÇ\s]*$/));
}

function FE_isalphanumeric(el) {
	return (el.value.match (/^[a-zA-Z0-9\s\-\.\'ÁÉÍÓÚÝáéíóúýÀÈÌÒÙàèìòùÂÊÎÔÛâêîôûçÇ\s]*$/));
}

function FE_isphone(el) {
	if (el.value.length > 0) {
		return (el.value.search (/^[0-9\-\. \s\(\)]*$/) == 0);
	}
	return true;
}

function FE_ispostal(el) {
	return (el.value.search (/^\w\d\w(\s)?\d\w\d$/) == 0);
}

function FE_iszip(el) {
	return (el.value.search (/^\d{5,5}$/) == 0);
}

function FE_isblank(el) {
	
/*	if (el.value.match (/^[\s ]*$/)) {
		alert ("blank")
	} else {
		alert ("not blank")
	} */
	return (el.value.match (/^[\s ]*$/));
}

function FE_islengthlt (el, m_l) {
	return el.value.length < m_l;
}

function FE_islengthgt (el, m_l) {
	return (el.value.length > m_l);
}

function FE_isinteger(el) {
	return (el.value.match (/^[\d]*$/));
}

function FE_iscurrency(el) {
	return el.value.match (/^\s*[$]?\s*\d+(\s*(,)?\s*\d+)*(\s*[.|,]?\s*\d+)?\s*[$]?\s*$/);
}
// ----------- 
// combo boxes 

function FE_valueis (el, m_l) {
	return (el.value == m_l)
}

function searchCT(city, province, language) {
    if(city == "" || province == "")
    {
        return;
    }
    window.top.location = "/" + language + "/find_home/luxury/searchResultsCT.aspx?province=" + province + "&city=" + city + "&relatedcontent=" + (language=="fr"?"454":"298");
}

function getQueryStringValue(name)
{
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++)
    {
        var pair = vars[i].split("=");
        if (pair[0] == name)
        {
            return pair[1];
        }
    }
} 

function selectCityFromList(list)
{
    if(getQueryStringValue("city") != "")
    {
        var el = document.getElementById(list);
        if(el != null)
        {
            var city = getQueryStringValue("city");
            if(city != null)
            {
                city = unescape(city.replace(/%20/g," "));
                el.value = city;
            }
        }
    }   
}
