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 = '';
    //zalert("page=officesearch&state=" + state_id + "&content=main&view=fetch_offices");
    
	if(!state_id || state_id == '')
	{
		if(false) {
			state_id = $('state').options[$('state').selectedIndex].value;
		}
		else {
			$('office_list').options[0] = new Option('Please select a province.', '');
			$('state').selectedIndex = 0;
	  		return true;
		}
	}

    $('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 province.", "null");
				return true;
			}

            if (bMapEnabled)
			{
				oMap.closeInfoWindow();
				var oOfficePos = new GLatLng(Offices[0]["pglatitude"], Offices[0]["pglongitude"]);
				oMap.setCenter(oOfficePos, 7);
			}
		    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"
	}
    );
}

/****************
 office_display
*****************/

function display_office(office_id, oMapMarker)
{
    if(office_id == 'null') return true;

    $('office_detail').innerHTML = "<div style='text-align: center'>\n\
                                        <img src='"+MUFFIN_SHARED_URL+"/images/_lib/loading/remaxloading.gif'>\n\
                                    </div>";
    new Ajax.Request('/index.php',
    {
        onSuccess : function(response, json)
        {
            var office_detail =  $H(eval("(" + response.responseText + ")"));
            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']);
                } 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']) {
                 $('office_detail_profile').innerHTML = office_detail['profile'];
            } else {
                 $('office_detail_profile').innerHTML = '';
            }
        },
        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;
}

function ResetGeoMap()
{
	oMap.closeInfoWindow();
	oMap.setCenter(new GLatLng(-30.5594820,22.9375060), 5);
}