// May need to try closure tool to reduce size
// http://code.google.com/closure/compiler/docs/gettingstarted_ui.html
// For debugging purpose
var hf_debug = '';

// Just ignore Firefox console functions for non FF browsers
if (!window.console) window.console = {log: function(x) {}};



// Added Ruby style Array.include method
Array.prototype.index = function(val) {
  for(var i = 0, l = this.length; i < l; i++) {
    if(this[i] == val) return i;
  }
  return null;
}

Array.prototype.include = function(val) {
  return this.index(val) !== null;
}




//********************GENERATE URL FUNCTIONS**********************



function generate_map_url_from_province(vlocation, city, cid){
  path = vlocation.pathname.split('/')[2];
	params = extract_province_id_from_params(vlocation.search,cid);
	send_omniture(city.replace(/\./g,"").replace(/ /g,""));
	return (vlocation.protocol + '//' + vlocation.host + '/map/' + city.replace(/\./g,"").replace(/ /g,"") + params);
}

function get_value_from_select(element){
	var select = $(element);
	return select.options[select.selectedIndex].innerHTML.replace("/","+").replace(/\./g,"").replace(/ /g,"");
}

function generate_prime_admin_from_city(vlocation, city, cid){
  return (vlocation.protocol + '//' + vlocation.host + '/cms/setup_prime_listings?cid=' + cid);
}


function generate_url_from_neigh(vlocation,neigh,nid) {
	path = vlocation.pathname.split('/')[2].split(',');
	params = alter_value_in_params(vlocation.search,'nid',nid);
	send_omniture(neigh.replace(/\./g,"").replace(/ /g,""));
	return (vlocation.protocol + '//' + vlocation.host + '/search/' + neigh.replace(/\./g,"").replace(/ /g,"") + ',' + path[1] + ',' + path[2] + params);
}

function generate_url_from_street(vlocation,neigh,nid) {
	path = vlocation.pathname.split('/')[2];
	return (vlocation.protocol + '//' + vlocation.host + '/search/' + neigh.replace(/\./g,"").replace(/ /g,"") + ',' + path + vlocation.search + '&nid=' + nid);
}

function extract_city_id_from_params(vsearch,nid) {
	// split get params from search string
	params = vsearch.split('?')[1].split('&');
	v_final = '?';
	first = true;
	
	// keep all except cid
	for(i=0;i<params.length;i++) {
		if (params[i].substring(0,3) != 'cid') {
			if (first) {
				first = false;
				v_final = v_final + params[i];
			} else {
				v_final = v_final + '&' + params[i];
			}
		} else {
			if (first) {
				first = false;
				v_final = v_final + 'nid=' + nid;
			} else {
				v_final = v_final + '&nid=' + nid;
			}
		}
	}
	
	return v_final;
}

function extract_province_id_from_params(vsearch,cid) {
	// split get params from search string
	params = vsearch.split('?')[1].split('&');
	v_final = '?';
	first = true;
	
	// keep all except cid
	for(i=0;i<params.length;i++) {
		if (params[i].substring(0,3) != 'pid') {
			if (first) {
				first = false;
				v_final = v_final + params[i];
			} else {
				v_final = v_final + '&' + params[i];
			}
		} else {
			if (first) {
				first = false;
				v_final = v_final + 'cid=' + cid;
			} else {
				v_final = v_final + '&cid=' + cid;
			}
		}
	}
	
	return v_final;
}

// alters a param value in the url, or adds it if not present
// receives the params string (window.location.search), the param name to alter, and the value to be set
function alter_value_in_params(vsearch,param,vvalue) {
	// split get params from search string
	params = vsearch.split('?')[1].split('&');
	v_final = '?';
	first = true;
	found = false;
	
	for(i=0;i<params.length;i++) {
		if (params[i].substring(0,param.length) != param) {
			if (first) {
				first = false;
				v_final = v_final + params[i];
			} else {
				v_final = v_final + '&' + params[i];
			}
		} else {
			found = true;
			if (first) {
				first = false;
				v_final = v_final + param + '=' + vvalue;
			} else {
				v_final = v_final + '&' + param + '=' + vvalue;
			}
		}
	}
	
	if (!found) {
		v_final = v_final + '&' + param + '=' + vvalue;
	}
	
	return v_final;
}

//********************END GENERATE URL FUNCTIONS******************

//********************SHOW MODAL AND RELATED FUNCTIONS************
var modal = null;

function show_modal(element) {
	if(modal != null){
		close_modal();
	}
	modal = $(element);
	
	var my_top,my_left;
	var viewport = getViewPortSize();
	var scroll = getScroll();
	
	my_top = scroll[1] + ( Math.round(viewport[1]/2) - Math.round(modal.offsetHeight/2) ) - 50;
	my_left = scroll[0] + ( Math.round(viewport[0]/2) - Math.round(modal.offsetWidth/2) );

	toggleOverlay();

	show_modal_coords(element,my_top,my_left);
}

function close_modal() {
	if(modal != null){
		modal.style.visibility = 'hidden';
		modal = null;	
	}
	if($('overlay').visible()){
		toggleOverlay();
	}	
	try
	{
	   $('registration_modal').style.visibility = 'hidden';
	   $('features_preview').style.visibility = 'hidden';
	   add_dropdowns();	//IE6 Related
	}
	catch(e){}
}

function show_modal_coords(element,my_top,my_left){
	var arrayPageSize = getPageSize();
	
	if((my_left+modal.offsetWidth) > arrayPageSize[0]){
		modal.style.right = "10px";
		modal.style.left = "auto";
	}else{
		modal.style.right = "auto";
		modal.style.left = my_left+"px";
	}
	
	modal.style.top = my_top+"px";
	modal.style.visibility = 'visible';
}

function toggleOverlay(){
	var ov = $('overlay');
	var ie6 = (readIEVersion() == 6);
	
	if(ov.visible()){
		if(ie6){
			showOrHideAllDropDowns('visible');
		}
		ov.hide();
	}else{
		var height = getPageSize()[1];
		var width = getPageRealSize()[0];
		
		ov.style.height = height+"px";
		ov.style.width = width+"px";

		if(ie6){
			showOrHideAllDropDowns('hidden');
		}
		ov.show();
	}
}

function getScroll(){
	var x,y;
	if (self.pageYOffset) // all except Explorer
	{
		x = self.pageXOffset;
		y = self.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop)
		// Explorer 6 Strict
	{
		x = document.documentElement.scrollLeft;
		y = document.documentElement.scrollTop;
	}
	else if (document.body) // all other Explorers
	{
		x = document.body.scrollLeft;
		y = document.body.scrollTop;
	}
	return [x,y];
}

function getViewPortSize(){
	var x,y;
	if (self.innerHeight) // all except Explorer
	{
		x = self.innerWidth;
		y = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
		// Explorer 6 Strict Mode
	{
		x = document.documentElement.clientWidth;
		y = document.documentElement.clientHeight;
	}
	else if (document.body) // other Explorers
	{
		x = document.body.clientWidth;
		y = document.body.clientHeight;
	}
	return [x,y];
}

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
}

function getPageRealSize(){
	var x,y;
	var test1 = document.body.scrollHeight;
	var test2 = document.body.offsetHeight;
	if (test1 > test2) // all but Explorer Mac
	{
		x = document.body.scrollWidth;
		y = document.body.scrollHeight;
	}
	else // Explorer Mac;
	     //would also work in Explorer 6 Strict, Mozilla and Safari
	{
		x = document.body.offsetWidth;
		y = document.body.offsetHeight;
	}
	return [x,y];
}

//panel specific functions
function focusFeedback() {
	if($('from').disabled) {
		$('message').focus();
	} else {
		$('from').focus();
	}
}

//seems to be an IE6 related function
function readIEVersion(){
	var ua = navigator.userAgent;
	var IEOffset = ua.indexOf("MSIE ");
	return parseFloat(ua.substring(IEOffset + 5, ua.indexOf(";", IEOffset)));
}


function showOrHideAllDropDowns(newState) {   
	var elements = document.documentElement.getElementsByTagName('select');
	for (var i=0; i<elements.length; i++) {
		if(elements[i].id != "wl_city")
			elements[i].style.visibility = newState;
	}
}

function add_dropdowns()
{
    try
    {
        if (is_ie6)
        {            
            document.getElementById("type_select").style.display = "inline";
            document.getElementById("beds_select").style.display = "inline";
            document.getElementById("baths_select").style.display = "inline";
            document.getElementById("order_by").style.display = "inline";
        }
    }
    catch(e){}
}
//****************END SHOW MODAL AND RELATED FUNCTIONS************
//********************URL MONITOR TIMER***************************
//Initial window location - hash and search string
var hashString = null;
var bPostBackAJAX = true;
var bTimerStarted = false;
var URLMonitorCallback = null;
var bFirstLoad = true;

//function to monitor for any changes in 
//the URL # hash parameters
//Monitor the URL hash and then
//fire ajax requests when the URL changes
function URLMonitorTimer(callbackFunc)
{
    var searchString;
    var i;
    var j;
    var bFound;   
   
    bTimerStarted = true;
    
    if(callbackFunc!=null)
        URLMonitorCallback = callbackFunc;

     //Monitor change
    if(hashString!=window.location.hash)
    {
        hashString = ""+window.location.hash;

        if(bPostBackAJAX==true)
        {
            //Need to grab all parameters from window.location.search & hash
            //and post these
            searchString = getQueryParamArray(window.location.search, '?', '&');
            var qArray = getQueryParamArray(hashString, '#', '&' );

            //Add any elements from the searchString into the qArray - if they
            //don't already exist in the qArray.... qArray is the array of reference.
            for(i=0;i<searchString.length;i++)
            {
                var searchStringComp = searchString[i];
                
                //Does the original search element exist?
                bFound = false;
                for(j=0;j<qArray.length && bFound==false;j++)
                {
                   if(searchStringComp.split('=')[0]==qArray[j].split('=')[0])
                   {
                      bFound = true;
                   }
                }
                
                //Nope.... push it onto the qArray.  If it does, do not include it again.
                //qArray is precidents
                if(bFound == false)
                {
                    qArray.push(searchStringComp);
                }
            }
    
            //build query string
            var qString = ""; //window.location.search;
            //this is interesting.... if a hash parameter replaces a query string parameter,
            //then don't post both, but take the last one
            
            for(i=0;i<qArray.length;i++)
            {
                if(qString==0)
                    qString +="?";
                else
                    qString +="&";
                    
                qString += qArray[i];
            }

            //Default Ruby AJAX call or JS map ajax call
            if(URLMonitorCallback==null)
            {   
                if (!bFirstLoad)             
                {
                    if(qString.length==0)
                    {
                        new Ajax.Request(window.location.search, 
                                         { asynchronous:true, 
                                           evalScripts:true}
                                         );   
                    }
                    else
                    {                      
                        new Ajax.Request(window.location.pathname+qString, 
                                         { asynchronous:true, 
                                           evalScripts:true}
                                         );
                    }
                }
                else
                {
                    bFirstLoad = false;
                }
             }
             else
             {
                //callback - need to call GetPolys function with params
                URLMonitorCallback(qString);
             }
        }
        else //bPostBackAJAX==false;
        {
            bPostBackAJAX = true;
        }
    }
    
    //Set timer to monitor
    setTimeout("URLMonitorTimer(null)", 150);
}

//Gets the URL query param - sep. by ? chars.
function getQueryParamArray(locationHash, startChar, sepChar )
{
    var mainParams;
    var hashParams = locationHash.split(startChar);
    var queryArray = new Array();
    var qParams;

    for(var j=0;j<hashParams.length && locationHash.length>0;j++)
    {
        mainParams = hashParams[j];
        qParams = mainParams.split(sepChar);
        for(var i=0;i<qParams.length && mainParams.length>0;i++)
        {
            queryArray.push(qParams[i]);
        }
    }
    
    return queryArray;
}
//************************END URL MONITOR TIMER*******************************

//If the same param already exists in the redirect.
function redirectParamExists(windowLocation, parm, value)
{
    //Check for parameters name & value in search string
    //var paramArray = window.location.hash.split("&");    
    var paramString = windowLocation.search +"&"+ windowLocation.hash;
    paramArray = paramString.split("&");
    var szSearchString = parm+"="+value;
    for (var i = 0; i < paramArray.length; i++)
    {
        if( paramArray[i] == szSearchString || 
            paramArray[i] == "?" + szSearchString || 
            paramArray[i]=='#'+szSearchString)
        {
            return true;
        }
    }
    
    return false;
}

//Find the custom query string and modify the value
//or add the value if it does not already exist
//Takes an array of NameValuePairs in the form of [[name,value],[name,value],[name,value]]
function alter_custom_query_hash(oldHash, nvpArray)//name, value)
{
    var mainParams;
    var hashParams = oldHash.split('#');//[1];
    var qParams;
    var nvpOrig;
    var qString = "";
    var bFound = false;

    for(var j=0;j<hashParams.length && oldHash.length>0;j++)
    {
        mainParams = hashParams[j];
        
        qParams = mainParams.split('&');
        for(var i=0;i<qParams.length && mainParams.length>0;i++)
        {
            if(qParams.length>0)
            {
                nvpOrig = qParams[i].split('=');
        
                if(i>0)
                {
                   qString += "&";
                }
                
                bFound = false;
                //Go through the nvpArray to see if we have a match
                for( var k=0;k<nvpArray.length && bFound==false;k++ )
                {
                   nvp = nvpArray[k];
                   if(nvpOrig[0]==nvp[0])
                   {
                      qString += nvp[0]+"="+nvp[1];
                      nvpArray.splice(k, 1);
                      bFound = true;
                   }
                }
                
                if(!bFound)
                {
                    qString += nvpOrig[0] + "=" + nvpOrig[1];
                }
            }
        }
    }

    if(nvpArray.length>0)
    {
        for(var a=0;a<nvpArray.length;a++)
        {
            nvp = nvpArray[a];
            if(qString.length>0)
                qString += "&";
            qString += nvp[0]+"="+nvp[1];
        }
    }
    
    //Add the first param
    if(qString.length > 0 )
        qString = "#"+qString;
    
    return qString;
}


function UpdateHistoryHash( arrayOfHash )
{
    var element;
    var newHash;
    
    newHash = alter_custom_query_hash(window.location.hash, arrayOfHash);

    if(is_ie5up)
    {
        try
        {
           element = window.frames["loader"];
           element.window.location.search = newHash.replace('#','?');
        }
        catch(error)
        {
        }    
    }
    else if (is_safari)
    {
        //do nothing
    }
    else
    {
        //For FF.
        window.location.hash = newHash;
    }    
}

function send_omniture(p_title) 
{
	try
	{
		if(p_title === 'undefined' || p_title === null ) {	
			if(current_location_info.name !== null)
				p_title = current_location_info.name;
			else
				p_title = 'MapSearch: Unknown'; 
		}
		s.pageName=p_title;
    // void(s.t());
    s.t();
	}
	catch(error)
	{}
}



var street_stop_words = {
	'st': 'St',
	'st.': 'St',
	'street': 'St',
	'road': 'Rd',
	'rd': 'Rd',
	'rd.': 'Rd',
	'avenue': 'Ave',
	'ave': 'Ave',
	'ave.': 'Ave',
	'square': 'Sq',
	'sq.': 'Sq',
	'sq': 'Sq',
	'blvd': 'Blvd',
	'boulevard': 'Blvd',
	'blvd.': 'Blvd',
	'cres': 'Cres',
	'crescent': 'Cres',
	'cres.': 'Cres',
	'drive': 'Dr',
	'dr.': 'Dr',
	'dr': 'Dr',
	'trail': 'Tr',
	'tr': 'Tr',
	'tr.': 'Tr',
	'ct': 'Ct',
	'ct.': 'Ct',
	'crt': 'Ct',
	'crt.': 'Ct',
	'path': 'Path',
	'circ.': 'Circ',
	'circ': 'Circ',
	'circle': 'Circ',
	'line': 'Line',
	'gdns': 'Gdns',
	'terr': 'Terr',
	'terr.': 'Terr',
	'terrace': 'Terr',
	'way': 'Way',
	'lane': 'Lane',
	'pl': 'Pl',
	'pl.': 'Pl',
	'place': 'Pl',
	'gfwy': 'Gfwy',
	'gfwy,': 'Gfwy',
	'golfway': 'Gfwy',
	'grove': 'Grve',
	'grv': 'Grve',
	'grve': 'Grve',
	'ln': 'Lane',
	'lane': 'Lane'
};


// All namespace variables
var dummy_map = null;
var Metroland = {};
Metroland.common = null;
Metroland.search = null;
Metroland.map = null;
Metroland.visual = null;
Metroland.admin = null;

// All onload events should go here
document.observe("dom:loaded", function(event) {
	var tab = null;
	
	$$('.tabs').each(function(tab_group){  
		tab = new Control.Tabs(tab_group,{  
		    afterChange: function(new_container){},
				beforeChange: function() {}
		});
	});  
	
	if (tab != null) {	
		setDefaultTab(tab);
	}
	// Image Gallery Initiation
	/*if( ($('gallery') != null) && ($$('#thumbs li img').size() > 0) )
	{
		setTimeout(function() {  slideShow.init(); slideShow.lim(); }, 500);
	}
*/

	Metroland.visual.setupCalendars();


  if($('dwt_video') != null) {
    setTimeout("Metroland.visual.showDefaultVideo()", 2000);
  }


});




//////////////////////////////////////// Common Library Functions ///////////////////////////////////

Metroland.common = (function() {
	// private attributes
	
	// private methods
	
	return {
		//Public methods 
		number_to_currency: function(number)
		{
		    number = "" + number;
		    if (number.length > 3)
		    {
		        var mod = number.length % 3;
		        var output = (mod > 0 ? (number.substring(0,mod)) : "");
		        for (i = 0; i < Math.floor(number.length / 3); i++)
		        {
		            if (mod != 0 || i != 0)
		            {
		                output += ",";
		            }
		            output += number.substring(mod + 3 * i, mod + 3 * i + 3);

		        }
		        return "$" + output;
		    }
		    return "$" + number;  
		},
		
		
		jsonToQueryString: function(json, remove_words) {
      var object_array = [];


      // Don't forget to use "var", otherwise IE will hate you!
      for(var item in json) {
        if(typeof json[item] !== 'undefined' && !remove_words.include(json[item].toString())) { 
          object_array.push(item + "=" + json[item]); 
        }
      }

      return object_array.join('&');
    },
    
		
		getSelectedLabel: function(eId) {
			return document.getElementById(eId)[document.getElementById(eId).selectedIndex].innerHTML;
		},
		
		// This function collects all user input elements values in a div
		getDivValues: function(div, json_object) {
      if(!div) {
        return;
      }

			// JSON object for return value
			var vals = {}

			
      div = (typeof div === "string") ? document.getElementById(div) : div;
      var elms = div.getElementsByTagName("*");
      for(var i = 0, maxI = elms.length; i < maxI; ++i) {
        var elm = elms[i];
        switch(elm.type) {
          case "text":
          case "textarea":
          case "button":
          case "file":
          case "hidden":
          case "password":
          case "image":
          case "checkbox":
          case "select-one":
          case "select-multiple":
						// console.log(elm.type + " : " + elm.name + " : " + elm.value);
						if(elm.name != 'undefined' && elm.name != "") {
							if(elm.value != 'undefined' && elm.value != "" && elm.value != 'DD/MM/YYYY') {
								vals[elm.name] = elm.value;
							}
						}
            //console.log("Type: " + elm.type + "\nName: " + elm.name + "\nId: " + elm.id + "\nValue: " + elm.value);
						break;
          case "radio":
						if(elm.name != 'undefined' && elm.name != "") {
							if(vals[elm.name] !== null) {
								vals[elm.name] = $$('input:checked[type="radio"][name="' + elm.name + '"]').pluck('value')[0];
							}
						}
						break;
          case "reset":
          case "submit":
						// Do nothing for these elements
						break;
					default:
						break;
        }
      }


			// Merge JSON Object
			if(typeof json_object !== 'undefined') {
				for(var k in json_object) {
					vals[k] = json_object[k];
				}
			}
			
			
			return vals;
    },


		getSelectNameValue: function(select_id) {
			select = document.getElementById(select_id);
			return {
				'name': select.options[select.selectedIndex].innerHTML,
				'value': select.options[select.selectedIndex].value
			};
		},
		
		message: function(msg) {
			var msg_div = document.createElement('div');
			msg_div.setAttribute("class", "panel_top");
			msg_div.innerHTML = msg;
			return msg_div;
		},
		
		insertJavascript: function(script_url) {
			var headID = document.getElementsByTagName("head")[0];         
			var newScript = document.createElement('script');
			newScript.type = 'text/javascript';
			newScript.src = script_url;
			headID.appendChild(newScript);
		}
		
	}
})();



/////////////////////////////// Search and Search Filter Related Functions ///////////////////////////////

Metroland.search = (function() {
	// private attributes
	
	// private methods
	
	function _isValidInput(params) {
    var alert_message = [];
		if ( (params.min_price != null && params.max_price != null) && 
		     (parseInt(params.min_price) > parseInt(params.max_price) ) )
		{
			alert_message.push('Max price must be greater than min price.');
		}
		
	
		if ( (params.min_date != null && params.max_date != null) && 
		     (params.min_date.gsub(/\D/,'') > params.max_date.gsub(/\D/,'') ) )
		{
			alert_message.push('Open house end date must be later than the start date.');
		}

  
		return alert_message;
  }


	return {
		//Public methods 
		resetWarnings: function()
		{
		  if($('filter_error')) $('filter_error').innerHTML = '';
      if($('postal_warning')) $('postal_warning').innerHTML = "";
      if($('city_warning')) $('city_warning').innerHTML = "";
      if($('mls_warning')) $('mls_warning').innerHTML = "";		  
		},
		
		filterSearch: function(loc)
		{
      this.resetWarnings();

			if (loc == 'top')
				var breadcrumb = Metroland.common.getDivValues('breadcrumb-container-top');
			else
				var breadcrumb = Metroland.common.getDivValues('breadcrumb-container-bottom');
			
			var refine = Metroland.common.getDivValues('refinement', breadcrumb);

      var msg = _isValidInput(refine); 
      if(msg.size() > 0)
      {
        
        $('filter_error').innerHTML = msg.join("<br/>");
        new Effect.Highlight('filter_error');
        // alert(msg.join("\n"));
      } else {
			  var goto_url = $('filterform').action + "/?" + Object.toQueryString(refine);
        window.location.href = goto_url;
      }
		},
		
		submitfilterSearch: function(e) {
			if (e.keyCode == 13) {
				this.filterSearch();
			}
		},

		redirectToCity: function(css_id, province) {
			var city = Metroland.common.getSelectNameValue(css_id);
			var search = window.location.search.sub(/\?/, "");
			search = search.gsub(/(pid|province)=\d+&/,"");
			search = search.gsub(/(province)=\w+/,"");
			var goto_url = "/search/city/" + city.name.replace(/\./g,"").replace(/ /g,"") + "/" + province.replace(/\./g,"").replace(/ /g,"") + "?cid=" + city.value + "&" + search;
			window.location.href = goto_url;
		},
		
		
		redirectToNeighborhood: function(css_id, city, province) {
			var neighborhood = Metroland.common.getSelectNameValue(css_id);
			var search = window.location.search.sub(/\?/, "");
			search = search.gsub(/(nid|cid)=\d+&/,"");
			var goto_url = "/search/neighborhood/" + neighborhood.name.replace(/\./g,"").replace(/ /g,"") + "/" + city.replace(/\./g,"").replace(/ /g,"") + "/" + province.replace(/\./g,"").replace(/ /g,"") + "?nid=" + neighborhood.value;
			window.location.href = goto_url;
		}

		
	}
})();




//////////////////////////////////////// Visual Library Functions ///////////////////////////////////

Metroland.visual = (function() {
	// private attributes
	
	// private methods
	
	return {
		//Public methods 
		showURLPopup: function(t_url, t_title, t_width, t_height) {
			var win = new Window({className: "darkX", title: t_title, 
			                      width:t_width, height:t_height, 
			                      url:t_url, showEffectOptions: {duration:0.5}});
			win.showCenter();                                            
			
			
		},
		zoomMap: function() {
			var target_zoom = 13;
			var current_zoom = map.GetZoomLevel();
			if (current_zoom > 13) {
				target_zoom = current_zoom;
			}
			map.SetZoomLevel(target_zoom+1);
		},
		
		// Popup Calendar Widget
		setupCalendars: function() {
		  // Popup Calendar
			['c_min_date', 'c_max_date', 'd_min_date', 'd_max_date' ].each(function(item) {
				if(document.getElementById(item)) Calendar.setup( {dateField: item, triggerElement: item} );
			});
		},

    showVideo: function(video_url, thumbnail_img, play_mode) {
			try {
				so.addVariable("file", video_url);
				so.addVariable("thumbnail", thumbnail_img);
				if(play_mode === true) {
				  so.addVariable('clipautoplay','yes');
				}
				so.write("dwt_video");
			} catch (e) {
				console.log(e);
			}
		},
		
    showDefaultVideo: function() {
      new Ajax.Request('/defaultvideo', {
          method: 'get',
          asynchronous:true, 
          evalScripts:true}
      );
    },
    
    showJWVideo: function(width, height, target_div, video_url, preview_url, autostart) {
      // var video_url = "rtmp://metroland.fcod.llnwd.net/a3158/o29/DanCooper_Ep1_VintageGardener.flv";

      var so = new SWFObject('/video/player.swf','mpl',width ,height,'9');
      so.addVariable('width', width);
      so.addVariable('height', height);
      so.addVariable("autostart", autostart);
      so.addParam('allowfullscreen','true');
      so.addParam('allowscriptaccess','always');
      so.addParam('wmode','opaque');
      so.addParam('quality', 'high');
      so.addVariable('enablejs', 'true');
      so.addVariable('stretching','fill');
      so.addParam('type', "application/x-shockwave-flash");
      so.addVariable('image', preview_url);
      so.addVariable('skin','/video/dwtvskin.swf');
      so.addVariable('abouttext','Copyright (C) MetrolandWest Media Group.');
      so.addVariable('aboutlink','http://metroland.com');

      // so.addVariable('streamer','rtmp://metroland.fcod.llnwd.net/a3158/o29');
      // so.addVariable('file','DanCooper_Ep1_VintageGardener.flv');

      var streamer = video_url.substring(0, video_url.lastIndexOf("/"));
      var streamname = video_url.substring(video_url.lastIndexOf("/")+1, video_url.length);
      so.addVariable('file', streamname);
      so.addVariable('streamer', streamer);


      so.write(target_div);
      
    }

	}
})();



//////////////////////////////////////// Map Related Functions ///////////////////////////////////


Metroland.map = (function() {
	// private attributes

	var basic_params = ['authenticity_token', 'type', 'distance_sr_type', 'radius'];
		
	var intersection_search_params = ['street1', 'street2', 'intersection_city'];
	var postal_code_search_params = ['pcode'];
	var address_search_params = ['address', 'city'];
	
	var optional_params = [
		'beds','baths','max_price','min_price', 
		'min_sqft','max_sqft'
	];
	
	
	
	var remove_words = [
	  "Intersection street name", "city name", "street#, street name",
	  "Postal code", "Enter city or Neighbourhood"
	];

		
	var retry_cnt = 0;

	// private methods
	

	function _intersectionSearch(params) {
    Metroland.search.resetWarnings();
    
    query_string = params.sub('&intersection_city', '&city');
    query_string = params.sub('&distance_sr_type', '&sr_type');
    
    new Ajax.Request('/search/base/intersection', {
      method: 'get',
      parameters: query_string
    });
    
		
		
	}


	function _addressSearch(params) {

		Metroland.search.resetWarnings();
		
		query_string = params.sub('&distance_sr_type', '&sr_type');
		

		new Ajax.Request('/search/base/address', {
			method: 'get',
			parameters: query_string
		});
		
		
	}


	function _postalcodeSearch(params) {
    Metroland.search.resetWarnings();
    
    query_string = params.sub('&distance_sr_type', '&sr_type');
		
		new Ajax.Request('/search/base/postalcode', {
			method: 'get',
			parameters: query_string
		});

	}
	
	// All Public methods should be here 
	
	return {
		
		submitDistanceSearch: function(e) {
			if (e.keyCode == 13) {
				Metroland.map.distanceSearch();
			}
		},
		
	
		distanceSearch: function() {
		  
			params = Metroland.common.getDivValues('distance_search');
			var request_params = "";
		
			
			
			var alert_message = [];
			if ( params['min_price'] != null && params['max_price'] != null && 
				( parseInt(params['min_price']) > parseInt(params['max_price']) ) )
			{
				alert_message.push('Max price must be greater than min price.');
			}
			
			if ( (params['min_date'] != null && params['max_date'] != null) && 
					 (params['min_date'].gsub(/\D/,'') > params['max_date'].gsub(/\D/,'') ) )
			{
				alert_message.push('Open house end date must be later than the start date.');
			}
			
			switch(params.distance_type) {
				case "intersection":
					
					Metroland.search.resetWarnings();
          
					if(typeof(params.street1) === 'undefined' || 
							typeof(params.street2) === 'undefined' || 
							typeof(params.intersection_city) === 'city name' || 
							params.street1 === 'Intersection street name' || 
							params.street2 === 'Intersection street name') 
					{
						alert_message.push('Please enter street name and type for each street name (e.g. Main St).');
					}
					else
					{
						if (typeof(params.street1.split(' ')[1]) === 'undefined' || typeof(params.street2.split(' ')[1]) === 'undefined')
						{
							alert_message.push('Please enter street name and type for each street name (e.g. Main St).');
						}
					}
					
					if (alert_message.size() > 0)
					{
            $('postal_warning').innerHTML = alert_message.join("<br/>");
            new Effect.Highlight('postal_warning');
					  
            // alert(alert_message.join("\n"));
					}
					else
					{
						request_params = Metroland.common.jsonToQueryString(params, remove_words);
						_intersectionSearch(request_params);
					}
					break;
				case "address":
					
					Metroland.search.resetWarnings();
          
					if(typeof(params.address) === 'undefined' || typeof(params.city) === 'undefined' || 
						params.address === 'street#, street name' || params.city === 'city name' ||
						params.address.split(" ").length < 3) 
					{
						alert_message.push("Please enter full address including street number, name and city (e.g. 123 Main St Toronto).");
					}
					
					if (alert_message.size() > 0)
					{
					  $('postal_warning').innerHTML = alert_message.join("<br/>");
            new Effect.Highlight('postal_warning');
            
            // alert(alert_message.join("\n"));
					}
					else
					{
						request_params = Metroland.common.jsonToQueryString(params, remove_words);
						_addressSearch(request_params);
					}
					break;
				case "postalcode":
				
				  Metroland.search.resetWarnings();
          
					if(params.pcode === 'Postal code') 
					{
						alert_message.push('Please enter valid postal code');
					}
					
					if (alert_message.size() > 0)
					{
					  $('postal_warning').innerHTML = alert_message.join("<br/>");
            new Effect.Highlight('postal_warning');
            
            // alert(alert_message.join("\n"));
					}
					else
					{	
						request_params = Metroland.common.jsonToQueryString(params, remove_words);
						_postalcodeSearch(request_params);
					}
					break;
			}
			
		}

	}
})();



//////////////////////////////////////// Admin Related Functions ///////////////////////////////////

Metroland.admin = (function() {

	
	// private methods
	
	return {
		//Public methods 
		change_agent_profile_mode: function(id, mode) {
			new Ajax.Request('/admin/edit_broker', {
				method: 'get',
				parameters: 'id=' + id + '&mode=' + mode
			});

		}
	}
})();

