var __objText = {
	"autocomplete":
	{
		"en" : "Make your choice among these suggestions" ,
		"fr" : "Sélectionner votre choix parmi les suggestions"
	}
};

var _lang = getCookie( "site_language" );
_lang = _lang.toLowerCase().substring( 0, 2 );
 
 
var _objUi = null;
function setAgentAutoUi(objUi){
	_objUi = objUi;
}
function getAgentAutoUi(){
	return _objUi;
}

$(document).ready(function(){
	
	var remainder = 0;
	var spaceLeftTotal = 0;
	var spaceLeftRemainder = 0;
	var NavItemCount = 0;
	var ArrElements = new Array();
	var wIndex = 0;
	var navLength = 0;
	var totalLength = 0;
	var spaceLeft = 0;
	var j = 0;

// Detecting if client browser is compatible with this website
	
	/****************************** Header Search box ******************************/

	function aucompleteProperty(){
		// Auto complete search box.
		$( "#header_location" ).autocomplete( {
			source: VARLanguagePath+"/modules/property_listing/frontend/includes/ajax.AutoComplete.php?fromQuickSearch=1",
			minLength: 2,
			select: function( event, ui ) {
				$( "#header_location" ).val( ui.item.label );
				strSubIdentifier =ui.item.specialId.substring(0,1);
				if(strSubIdentifier !="")
					strSubIdentifier +="::";
					
				if(ui.item.propertyId != undefined && ui.item.propertyId)
					$('#propertyAutoCompleteValue').val(ui.item.propertyId);
				else
					$('#propertyAutoCompleteValue').val(strSubIdentifier + ui.item.value);
				
				$("#header_search_btn").attr('disabled',false);
				return false;		// Cancels the Jquery select event from overwritting my event.
			},
			close: function( event, ui ) {
				$("#header_search_btn").attr('disabled',false);
				return false;		// Cancels the Jquery select event from overwritting my event.
			},
			focus: function( event, ui ) {
				$("#header_search_btn").attr('disabled',true);
				$( "#header_location" ).val( ui.item.label );
				$('#propertyAutoCompleteValue').val(ui.item.specialId.substring(0,1) + '::' + ui.item.value);
				return false;		// Cancels the Jquery select event from overwritting my event.
			}
		} );
		
		$('#header_search_container').removeClass("agent_header_class");  
		$('#header_search_container').addClass("property_header_class");  
		
		$('#agent_search_box').hide();
		$('#property_search_box').show();
	
		// Set the property as selected
		setCookie("selectedQuicksearch", "header_property", 30);
	}
	
	function aucompleteAgent(){
		$('#header_agent_location').autocomplete({
			source: VARLanguagePath+"/modules/agent_search/frontend/ajax.getAutoComplete.php",
		    minLength: 2,
		    select: function( event, ui ) {      
		      setAgentAutoUi(ui);
		      $('#agent_search_box #agent_search_a input[name=autocomplete]').val(ui.item.label);
		      $('#agent_search_box #agent_search_a input[name=autoFirst]').val(ui.item.first);
		      $('#agent_search_box #agent_search_a input[name=autoLast]').val(ui.item.last);
		      $('#agent_search_box #agent_search_a input[name=autoOffice]').val(ui.item.office);
		      
		      if(ui.item.type == 'office' && ui.item.office_id != null){
		    	  $('#agent_search_box #agent_search_a input[name=officeId]').val(ui.item.office_id);
		      }else if(ui.item.first != null && ui.item.last != null){
		    	  $('#agent_search_box #agent_search_a input[name=agentId]').val(ui.item.agent_id);
		    	  $('#agent_search_box #agent_search_a input[name=officeId]').val(ui.item.office_id);
		      } else {
		    	  $('#agent_search_box #agent_search_a input[name=agentId]').val('');
		    	  $('#agent_search_box #agent_search_a input[name=officeId]').val('');
		      }
		      $('#agent_region').val('');
		      return false;   // Prevents the Jquery select event from overwritting my event.
		    },
		    focus: function( event, ui ) {
		      $('#agent_search_box #agent_search_a input[name=autocomplete]').val(ui.item.label);
		      $('#agent_search_box #agent_search_a input[name=autoFirst]').val(ui.item.first);
		      $('#agent_search_box #agent_search_a input[name=autoLast]').val(ui.item.last);
		      $('#agent_search_box #agent_search_a input[name=autoOffice]').val(ui.item.office);
		      $('#agent_search_box #agent_search_a input[name=officeId]').val(ui.item.office_id);
		      if(ui.item.first != null && ui.item.last != null){
		    	  $('#agent_search_box #agent_search_a input[name=agentId]').val(ui.item.agent_id);
		    	  $('#agent_search_box #agent_search_a input[name=officeId]').val(ui.item.office_id);
		      }
		      else{
		    	  $('#agent_search_box #agent_search_a input[name=agentId]').val('');
		    	  $('#agent_search_box #agent_search_a input[name=officeId]').val('');
		      }
		      return false;   // Prevents the Jquery select event from overwritting my event.
		    }
			});
			
			$('#header_search_container').removeClass("property_header_class");  
			$('#header_search_container').addClass("agent_header_class");   
			
			$('#property_search_box').hide();	
			$('#agent_search_box').show();

			// Set the agent as selected
			setCookie("selectedQuicksearch", "header_agent", 30);
	}
	
	function aucompleteAgentRegion(){
		$( "#agent_region" ).autocomplete( {
			source: VARLanguagePath+"/modules/property_listing/frontend/includes/ajax.AutoComplete.php",
	        minLength: 2,
	        select: function( event, ui ) {
	            $( "#agent_region" ).val( ui.item.label );
	         	setAutocompleteAgentRegionsSearch(ui);
				$("#header_search_btn").attr("disabled", false);
				$("#header_agent_location").val("");
				$('#agent_search_box #agent_search_a input[name=agentId]').val('');
		    	$('#agent_search_box #agent_search_a input[name=officeId]').val('');
		    	
	            return false;		// Cancels the Jquery select event from overwritting my event.
	        },
	        focus: function( event, ui ) {
	            $( "#agent_region" ).val( ui.item.label );
	            setAutocompleteAgentRegionsSearch(ui);
	            $("#header_search_btn").attr("disabled", true);
	            return false;		// Cancels the Jquery select event from overwritting my event.
	        },
			close: function (event,ui){
				//disabled the button to make time to select it
				$("#header_search_btn").attr("disabled", false);
	    	}
	    });
	}
	
	$('#header_property').unbind('click');
	$('#header_property').bind('click', function () { aucompleteProperty(); });
	
	$('#header_agent').unbind('click');
	$('#header_agent').bind('click', function () { aucompleteAgent() });

	$("a#searchCta").click( function() {
		$("form#propertyQuickSearch").submit();
	});
	
	aucompleteProperty();
	aucompleteAgentRegion();
	
	
	// Check for a cookie indicating which quicksearch is selected
	var selectedQuicksearch = getCookie("selectedQuicksearch");
	if (selectedQuicksearch != "") {
		$('#' + selectedQuicksearch).click();
		
	} else {
		// Click the property quicksearch
		$('#header_property').click();
	}
	
	/******************************* Javascript to resize a small page **************/
	
	var pageSize = $("#contentContainer").height();
	var curUri=location.href;
	var favFound=curUri.indexOf("visitor_favourites");
	
	if (favFound==0) {
		if (pageSize < 250)
		{
			$("#contentContainer").css("height", 250);
		}
	}
	
							
});

function submitPropertyQuickSearchForm() {
	//fix transaction type to "Purchase"
	$('#propertyQuickSearch').append('<input type="hidden" name="transactionTypes[]" value="30" />');
	
	// Deal with the autocomplete box
	// Make sure that something was entered
	
	if ($('#header_location').val() != "" && $('#header_location').val() != defaultPropertyAutocompleteText) {
	
		  // Check if it is an autocomplete value
	    if ($('#propertyAutoCompleteValue').val() != "") {
	    
	    		// Add the input element
	    		$('#propertyQuickSearch').append('<input type="hidden" name="localization[]" value="' + $('#propertyAutoCompleteValue').val() + '" />');
			
	    } else {
	    
	    	// If corpo only
	    	if(getClientGroupId()==1){
		    	// use the autocomplete
		    	alert(__objText.autocomplete[_lang]);
		    	return false;
	    	}else{
   			    // MLS/LCV number
		  		// Add the input element
	  			$('#propertyQuickSearch').append('<input type="hidden" name="localization[]" value="' + $('#header_location').val() + '" />');
	    	}
	    }
	    $('#propertyQuickSearch').append('<input type="hidden" name="fromQuickSearch" value="1" />');
		
	} else {
		// Wipe out the value
		$('#header_location').val('');
	}
	
	// Deal with the property types
	var propType = $('#property_type').val();
	if (propType != "") {
	
		// multiple selection from 1 single drop down box
		if(propType.indexOf('MULTI||')!=-1){
		
			// get the propertytype
			var tblPropType =propType.split(':');
			// first one is the propertytype
			// seconds are the registration type
			$intPropertyType =tblPropType[0].replace('MULTI||','');
			
			strFieldName ='resPropertyType[]';
			if($intPropertyType ==11 )
				strFieldName ='comPropertyType[]';
			if($intPropertyType ==12 )
				strFieldName ='mulPropertyType[]';
			
			$('#propertyQuickSearch').append('<input type="hidden" name="registrationType" value="' + $intPropertyType + '" />');
			for(var intCounter = 1;intCounter<tblPropType.length;intCounter++)
				$('#propertyQuickSearch').append('<input type="hidden" name="'+strFieldName+'" value="'+tblPropType[intCounter]+'" />');
		}else{
			if (propType.length > 2) {
				// Dealing with a propertyType, figure out what type it is, and add the appropriate elements
				switch(propType.charAt(0)) {
				case '1':
					// Residential
					$('#propertyQuickSearch').append('<input type="hidden" name="resPropertyType[]" value="' + propType + '" />');
					$('#propertyQuickSearch').append('<input type="hidden" name="registrationType" value="10" />');
					break;
					
				case '2':
					// Commercial
					$('#propertyQuickSearch').append('<input type="hidden" name="comPropertyType[]" value="' + propType + '" />');
					$('#propertyQuickSearch').append('<input type="hidden" name="registrationType" value="11" />');
					break;
					
				case '3':
					// Multiplex
					$('#propertyQuickSearch').append('<input type="hidden" name="mulPropertyType[]" value="' + propType + '" />');
					$('#propertyQuickSearch').append('<input type="hidden" name="registrationType" value="12" />');
					break;
				}
			} else {
				// Dealing with a registration type, add the appropriate elements
				$('#propertyQuickSearch').append('<input type="hidden" name="registrationType" value="' + propType + '" />');
				
			}
		}
	}
	
	return true;
}

function mapSubmitForm() {
	// Append the map displayMode element 
	$('#propertyQuickSearch').append('<input type="hidden" name="displayMode" value="map" />');
	// Submit the form (the rest will be handled by the onSubmit)
	$('#propertyQuickSearch').submit();
	
}

function submitAgentQuickSearchForm() {
  // Make sure something was entered in the autocomplete box, and wipeit out if nothing was
  if ($('#agent_search_box #header_agent_location').val() == defaultAgentAutocompleteText) {
    $('#agent_search_box #header_agent_location').val('');
    
  }
  
  // Decide what the selected geography is, if any
  var geo = $('#agent_search_box #agent_region').val();
  
  
  
  if(getClientGroupId()==1){
  	var strAgentLocation = $('#header_agent_location').val();
  	if(strAgentLocation!=''){
  		
        objUi =getAgentAutoUi(); 
		// compare with each elements of the autocomplete
		blnMatch = false;

		if(objUi !=null){
			if(strAgentLocation ==objUi.item.label)
				blnMatch = true;
			if(strAgentLocation ==$('#agent_search_box #agent_search_a input[name=autoFirst]').val())
				blnMatch = true;
			if(strAgentLocation ==$('#agent_search_box #agent_search_a input[name=autoLast]').val())
				blnMatch = true;
				
			if(strAgentLocation ==$('#agent_search_box #agent_search_a input[name=autoOffice]').val())
				blnMatch = true;			
		}
		if(!blnMatch){
			alert(__objText.autocomplete[_lang]);
		    return false;
		}
  	}
  }
  
  if (geo != '') {
    // Split on the -
    var geo = geo.split('-');
    $('#agent_search_box form').append('<input type="hidden" name="fromQuickSearch" value="1" />');
    
    var ui = getAutocompleteAgentRegionsSearch();
    if(ui !=null){
    
		$('#agent_search_box form').append('<input type="hidden" name="regions" value="' + ui.item.regionId + '" />');
		$('#agent_search_box form').append('<input type="hidden" name="cities" value="' + ui.item.cityId + '" />');    
    }else{
	    if(getClientGroupId()==1){
		    if($('#agent_search_box #agent_region').val() !=''){
		    	// use the autocomplete
		    	alert(__objText.autocomplete[_lang]);
		    	return false;
		    }
		    
	    }
        // Check what was entered and create the appropriate hidden element(s)
	    if (geo[0] == 'r') {
	      $('#agent_search_box form').append('<input type="hidden" name="regions" value="' + geo[1] + '" />');
	      
	    } else {
	      $('#agent_search_box form').append('<input type="hidden" name="regions" value="' + geo[1] + '" />');
	      $('#agent_search_box form').append('<input type="hidden" name="cities" value="' + geo[2] + '" />');
	      
	    }
    }
  }
  
  return true;
}
var globalUi=null;
function setAutocompleteAgentRegionsSearch(ui){globalUi=ui;}
function getAutocompleteAgentRegionsSearch(){return globalUi;}

// Wipe the 3 specific autocomplete inputs when backspace or delete are pressed
function autoQuickSearchCompleteKeyUp(event) {
  if (event.keyCode == 8 || event.keyCode == 46) {
    $('#agent_search_box #agent_search_a input[name=autoFirst]').val('');
    $('#agent_search_box #agent_search_a input[name=autoLast]').val('');
    $('#agent_search_box #agent_search_a input[name=autoOffice]').val('');
  }
}

function setCookie(name, value, expireMinutes) {
	var exdate = new Date();
	exdate.setDate(exdate.getMinutes() + expireMinutes);
	document.cookie = name + "=" + escape(value) + ((expireMinutes == null) ? "" :  ";expires=" + exdate.toUTCString()) + ";path=/";
}

function getCookie(name) {

	if (document.cookie.length > 0) {
		start = document.cookie.indexOf(name + "=");
		
		if (start != -1) {
			start = start + name.length + 1;
			end = document.cookie.indexOf(";", start);
			
			if (end == -1) {
				end = document.cookie.length;
				
			}
			
			return unescape(document.cookie.substring(start, end));
		}
	}else{
		if(strLangDocument !=undefined && name =='site_language')
			return strLangDocument;
	}
	
	
	return "";
}

function logoff() {
    	$.getJSON(VARLanguagePath+"/modules/visitor_manager/frontend/includes/ajax.logoff.php", function(dataJson) {
        if (dataJson.result==1) {
                //window.location='/';
                window.location=dataJson.redirect;
		}
	});

}
/**
* used to insert statistic into the DB
**/
function insertStats(strData,strAction){
	var strActionParam = '';
	if(strAction != undefined)
		strActionParam ='&action='+strAction;
	
	// creating the object is enough to add stats	
	var objImg = document.createElement("img");
		objImg.src = "/web-services/stats/?data="+strData+strActionParam;

}

