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 = '';
    
    if(!state_id || state_id != '')
    {
        if(false) {
            state_id = $('state').options[$('state').selectedIndex].value;
        }
        else {
            //commenting out because once the province select box is removed/commented out
            // in the _include/view/view/officesearch/_default/class.www_view.php file
            // it throws a js error on page load.

            $('office_list').options = new Option('Please select a province.', '');
            $('state').selectedIndex = 0;
            return true;
        }
    }
    ele = document.getElementById('office_list');
    ele.disabled = true;
    ele.options.length = 0;
    ele.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)
            {
                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"
    });
}

function reveal( hideDiv , showDiv , userID , webRef, media, refSource){
    
     document.getElementById(hideDiv).style.visibility='hidden';
     document.getElementById(hideDiv).style.display='none';
     document.getElementById(showDiv).style.visibility='visible';
     document.getElementById(showDiv).style.display='block';
     
     url2='http://'+document.domain+'/?page=api_speed&content=main&params=feed:contacts_build;&user_id='+userID+'&web_ref='+webRef+'&contactMedia='+media+'&referralSource='+refSource+''
     new Ajax.Request(url2,
    {
        onSuccess : function(response)
        {
           // window.location = "http://"+document.domain+"/"+response.responseText+jQuery("#"+eleName).val()+"/";
        },
        onFailure : function(response)
        {
            //alert('Error loading advanced search');
        }
    });
}

function fetch_offices_enhanced(state_id, currentTime)
{
    first_option = '';
    ele = document.getElementById('office_list');
    ele.disabled = true;
    ele.options.length = 0;
    ele.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;
            Offices.each(function(office)
            {
                if(office.value.activationdate < currentTime)
                {
                    ele.options[option_count] = new Option(office.value.suburb +" - ("+office.value.name+")",office.value.id);
                    option_count++;
                }
            });
            ele.disabled = false;
        },
        onFailure : function(response)
        {
            ele.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' || office_id == 'Please select a province.') return true;
    ele = document.getElementById('office_detail');
    ele.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) {
                oMap.closeInfoWindow();
                if (!oMapMarker) {
                    oMapMarker = g_oMarkers[office_id];
                }
                if(oMapMarker == undefined){
                    var oMapMarker = new GMarker(new GLatLng(office_detail['latlng'][0], office_detail['latlng'][1]),markerOptions);
                    oMap.addOverlay(oMapMarker);
                    oMap.setCenter(oMapMarker.getPoint(), 15);
                }
                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);
                    });
                }
            }
            ele.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"
    });
}

function enhanced_display_office(ele_id_str ){
    if(office_geolocation_str == 'null' || office_geolocation_str == 'Please select a province.') return true;
    var od = document.getElementById('office_detail');
    $('office_detail').innerHTML = "<div style='text-align: center'>\n\
                                        <img src='"+MUFFIN_SHARED_URL+"/images/_lib/loading/remaxloading.gif'>\n\
                                    </div>";
    var ele = document.getElementById(ele_id_str);
    var office_geolocation_str = ele.value;
    var office_geo_arr = office_geolocation_str.split(" - ");
    new Ajax.Request('/index.php',
    {
        onSuccess : function(response, json)
        {
            var office_detail =  $H(eval("(" + response.responseText + ")"));
                if (!oMapMarker) {
                    var oMapMarker = new GMarker(new GLatLng(office_detail['latlng'][0], office_detail['latlng'][1]),markerOptions);
                    oMap.addOverlay(oMapMarker);
                    oMap.setCenter(oMapMarker.getPoint(), 15);
                }
                if (oMapMarker) {
                    // Precisely reposition marker when up close
                    //oMapMarker.setPoint(new GLatLng(office_detail['latlng'][0], office_detail['latlng'][1]));
                    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);
                    });
                }
//                if (bMapEnabled && oMap) {
//                    //oMap.closeInfoWindow();
//                    var oMapMarker = new GMarker(new GLatLng(office_detail['latlng'][0], office_detail['latlng'][1]));
//                    oMap.setCenter(oMapMarker.getPoint(), 15);
//                    oMapMarker.openInfoWindowHtml(office_detail['identifier']);
//                }
            
            $('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&officename="+ office_geo_arr[0] + "&suburb="+ office_geo_arr[1] + "&city="+ office_geo_arr[2] + "&state="+ office_geo_arr[4]+"&json=yes&content=main&view=quick&ajax=true"
    });
}



/****************
 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()
{
    if(oMap) {
        oMap.closeInfoWindow();
        oMap.setCenter(new GLatLng(-30.5594820,22.9375060), 5);
    }
}


