var timerID     	= 0;
var timerIDNumber  	= 0;
var input      	 	= 0;
var input_value 	= 0;
var previous_value 	= 0;
var currentprovince = 0;
var AllUsers;

/*************************************************************
Check province drop down
to make sure that it loads data if back button is pressed
**************************************************************/


/****************
 office_fetch
***************/

function fetch_offices(state_id, currentTime)
{
	first_option = '';
    //alert("page=officesearch&state=" + state_id + "&content=main&view=fetch_offices");
    
	if(!state_id || state_id == '')
	{
		$('office_list').options[0] = new Option('Please select a region.', '');
		$('state').selectedIndex = 0;
  		return true;
	}
	else
	{
		$('state').selectedValue = state_id;
	}

    $('office_list').disabled = true;
    $('office_list').options.length = 0;
    $('office_list').options[0] = new Option("Loading Offices...","null");
	new Ajax.Request('/index.php',
     {
      	onSuccess : function(response) 
		{
			var Offices = $H(eval("("+response.responseText+")"));
			var option_count =0;

			if ($A(Offices).length==1 && !($A(Offices)[0].value.id))
			{
				$('office_list').options[0] = new Option("No offices in this region.", "null");
				return true;
			}
			// Center map on first office
			if (bMapEnabled)
			{
				oMap.closeInfoWindow();		
				 for (var i=0;i < $A(Offices).length;i++) {
				 
				 	if ( ($A(Offices)[i].value.olatitude) &&  ($A(Offices)[i].value.olongitude)  ){
					var oOfficePos = new GLatLng($A(Offices)[i].value.olatitude, $A(Offices)[i].value.olongitude);
					break;
					}
					
			    	if (($A(Offices)[i].value.glatitude) &&  ($A(Offices)[i].value.glongitude) && (!($A(Offices)[i].value.olatitude)) ){
					var oOfficePos = new GLatLng($A(Offices)[i].value.glatitude, $A(Offices)[i].value.glongitude);
					break;
					}

				}
				oMap.setCenter(oOfficePos, 5);
				
			//clear old markers
			oMap.clearOverlays();
		    //this should be made to work with Repopulate
			// Add office markers
			var oMarker = null;
			for (var i=0;i < $A(Offices).length;i++) 
			{
		        if (($A(Offices)[i].value.olatitude) &&  ($A(Offices)[i].value.olongitude) && (!($A(Offices)[i].value.glatitude)) ){
		        	$A(Offices)[i].value.glatitude = $A(Offices)[i].value.olatitude ;
		        	$A(Offices)[i].value.glongitude = $A(Offices)[i].value.olongitude;
		        }
				oMarker = new GMarker(new GLatLng($A(Offices)[i].value.glatitude, $A(Offices)[i].value.glongitude));

				oMarker.iOfficeID = $A(Offices)[i].value.officeid;
				oMarker.iStateID = $A(Offices)[i].value.reportstate;
				oMap.addOverlay(oMarker);
				g_oMarkers[$A(Offices)[i].value.officeid] = oMarker;
			
								
				GEvent.addListener(oMarker, "click", function () { 
				 	display_office(this.iOfficeID, this);
				});
			}
	
				
				// Show markers (in case they were hidden by the office detail)
				for (key in g_oMarkers)
				{
					if (typeof(g_oMarkers[key])!=='function')
					{
						g_oMarkers[key].show();
					}
				}
			}

		    Offices.each(function(office)
		    {
				if(office.value.activationdate < currentTime)
		    	{
			    	$('office_list').options[option_count] = new Option(office.value.suburb +" -- ("+office.value.name+") ",office.value.id);
			    	option_count++;
		    	}
	    });
		    $('office_list').disabled = false;
		},
		
		onFailure : function(response)
		{
		    $('office_list').options[0] = new Option("Offices could not be loaded.","null");
		},
		parameters : "page=officesearch&state=" + state_id + "&content=main&view=fetch_offices"
	}
    );
}
function RepopulateMap(OfficeGeoData)
{			
			//clear old markers
			oMap.clearOverlays();
		
			// Add office markers
			var oMarker = null;
			for (var i=0; i<OfficeGeoData.length; i++)
			{
				oMarker = new GMarker(new GLatLng(OfficeGeoData[i][0], OfficeGeoData[i][1]));
				oMarker.iOfficeID = OfficeGeoData[i][2];
				oMarker.iStateID = OfficeGeoData[i][3];
				oMap.addOverlay(oMarker);
				g_oMarkers[OfficeGeoData[i][2]] = oMarker;
			
								
				GEvent.addListener(oMarker, "click", function () { 
				 	display_office(this.iOfficeID, this);
				});
			}
			
}
/****************
 office_display
*****************/

function ResetGeoMap()
{
	oMap.closeInfoWindow();

	oMap.setCenter(new GLatLng(-40.930115, 174.924316), 4);
}

function display_office(office_id, oMapMarker)
{
	if(office_id == 'null')
	{
		    return true;
	}
	
	$('office_detail').innerHTML = "<div style='text-align: center'><img src='"+MUFFIN_SHARED_URL+"/images/_lib/loading/remaxloading.gif'></div>";
	new Ajax.Request('/index.php',
     {
		onSuccess : function(response, json) 
		{
			var office_detail =  $H(eval("(" + response.responseText + ")"));
					
			// office_detail['maptoken'] - can be used for google maps
			
			if (bMapEnabled)
			{
				oMap.closeInfoWindow();
				
				if (!oMapMarker)
				{
					oMapMarker = g_oMarkers[office_id];
				}
				if (oMapMarker)
				{
					// Precisely reposition marker when up close
					oMapMarker.setPoint(new GLatLng(office_detail['latlng'][0], office_detail['latlng'][1]));
					oMap.setCenter(oMapMarker.getPoint(), 15);
					oMapMarker.openInfoWindowHtml(office_detail['identifier']);
					
					// Hide other markers
			//		for (key in g_oMarkers)
				//	{
				//		if (typeof(g_oMarkers[key])!=='function' && key != office_id)
				//		{
				//			g_oMarkers[key].hide();
					//	}
				//	}
				}
				else
				{
					var oGeoCoder = new GClientGeocoder();
					oGeoCoder.getLatLng(office_detail['maptoken'], function(oLoc){ oMap.setCenter(oLoc, 15); } );
				}
			}
			
			$('office_detail').innerHTML = office_detail['details'];
		    if(office_detail['profile'])
		    {
		    	  $('OfficeProfile').innerHTML = office_detail['profile'];
		    }
			else 
			{
				 $('OfficeProfile').innerHTML = '';
			}
			
			if(office_detail['officeImage'])
			{
				$('OfficeImage').style.display = 'block';
				$('OfficeImage').innerHTML = office_detail['officeImage'];
				$('OfficeProfile').style.marginLeft = '290px';
			}
			else
			{
     		    $('OfficeImage').style.display = 'none';
				$('OfficeImage').innerHTML = "";
				$('OfficeProfile').style.marginLeft = '0px';
			}
		},
		onFailure : function(response)
		{
		    alert('Error loading agents');
		},
		parameters : "page=officesearch&office_id=" + office_id + "&content=main&json=yes"
	}
    );
}

/****************
 office_population
*****************/


function test(filter)
{
	if(filter.value == ''){filter.value='quick agent search...';}
}

function Load(users)
{
	AllUsers = $H(eval(users));
	
	$('UsersSelect').disabled = true;
	//Set_User_Options($('UsersSelect'),"OnLoading");
}

function contact_onKey_timer(input_element)
{
	input_element.disabled = false;
	input       = input_element;
	input_value = trim(input.value);
	if(input_value  =="")
	{
		input.value="";
	}
	
	if(timerID!=0)
	{
		clearTimeout(timerID);
	}
	timerID = setTimeout('_check_new_filter(input)', 500);
	
}
function _check_new_filter(input)
{
	if(input.value != previous_value && input.value != "")
	{
		previous_value = input.value;
		call_User_search(input);
	}
	else
	{
		emptytSelectOptions($('UsersSelect'), "Select an agent");
	}
}
function call_User_search(filter)
{
	clearTimeout(timerID);
	get_users(filter);	
}


function get_users(filter)
{
	if(filter.value == "")
	{
		Set_User_Options($('UsersSelect'),"OnLoading");
	}
	else
	{
		Set_User_Options($('UsersSelect'),filter.value);
	}
	
}

function Set_User_Options(select,Filter)
{
	var checkObject = Filter.toUpperCase();
	var optioncount=0;
	clearSelect(select);
	select.disabled = false;
	
	AllUsers.each(function(item, index) 
    {
		var UserDetails  = $H(item.value);
		
		UserDetails.LastName = UserDetails.LastName.replace("+", " ");
		UserDetails.LastName = UserDetails.LastName.replace("+", " ");
		switch(Filter)
		{
			case "OnLoading":
				//if(optioncount == 0)
				//{
				//	select.options[optioncount] = new Option('Select a contact', '');
				//	optioncount++;
				//}
				select.options[optioncount]= new Option(unescape(UserDetails.Name) + " " + unescape(UserDetails.LastName), UserDetails.UserID);
				optioncount++;
				//alert(UserDetails.UserID);
			break;
			default:
				var searchObjectName = unescape(UserDetails.Name).substring(0,checkObject.length).toUpperCase();
				var searchObjectSurname = unescape(UserDetails.LastName).substring(0,checkObject.length).toUpperCase();
				if(searchObjectName == checkObject || searchObjectSurname == checkObject)
	       		{
	       			
	       			select.options[optioncount]= new Option(unescape(UserDetails.Name) + " " + unescape(UserDetails.LastName), UserDetails.UserID);
	       			optioncount++;
	       		}
	       	break;
	   	}
	   	//select.options[0].selected =  true;
		//Set_Selected_Number();
	}
	);
	if(optioncount==0)
    {
    	emptytSelectOptions(select,"No agents for search criteria")
    }
}
function emptytSelectOptions(select,Value) 
{
    select.disabled = true;
    clearSelect(select);
    select.options[0] = new Option(Value, 0);
}
function clearSelect(select)
{
	select.options.length = 0;
}
function _Set_Loading(select)
{
	 clearSelect(select);
     select.disabled = true;
	 select.options[0] = new Option("Loading...", 0);
}

function trim(sString)
{
	while (sString.substring(0,1) == ' ')
	{
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}