LocationsControl = function(locations, id)
{
    this.Constructor(locations, id);
}

LocationsControl.prototype.Constructor = function(locations, id)
{
    var obj = $getControl(id + '_obj');
    if (obj)
        obj = eval(obj.value);
        
    this.ID = id ? id : __getGUID();
    this.Locations = locations ? locations : obj ? obj.Locations:null;
    this.StateControl = new DropDownBox(this.ID + '_state', 'State');
    this.CountyControl = new DropDownBox(this.ID + '_county', 'County'); 
}

LocationsControl.prototype.Render = function() {
    if (!this.Locations)
        return null;

    var search = document.createElement('table'),
        row = search.insertRow(),
		button = document.createElement('<input type="button" />'),
		obj = document.createElement('<input type="hidden" />'),
		helpLink = document.createElement('a'),
		memberContactLink = document.createElement('a');

    search.id = this.ID;
    obj.id = this.ID + '_obj';
    obj.value = '(' + JSONstring.make(this) + ')';

    for (var i = 0; i < this.Locations.length; i++)
        this.StateControl.AddOption(this.Locations[i].abbr, this.Locations[i].name);
    this.StateControl.OnChange = '__locationsControl_setCounties("' + this.ID + '");';

    for (var i = 0; i < this.Locations[0].counties.length; i++)
        this.CountyControl.AddOption(this.Locations[0].counties[i].env, this.Locations[0].counties[i].name);
    this.CountyControl.OnChange = '__locationsControl_changeCounty("' + this.ID + '");';

    button.id = this.ID + '_button';
    button.value = 'Get Emergency Contacts';
    button.onclick = "__setMap();";

    helpLink.href = GetBaseUrl() + "/Documents/EmergencyContactHelp.pdf";
    helpLink.appendChild(document.createTextNode("Help"));
    helpLink.target = "_blank";
    helpLink.className = "link";

    memberContactLink.href = GetBaseUrl() + "/Centers/USAN/MemberContacts.aspx";
    memberContactLink.appendChild(document.createTextNode("Click here if you have a ticket number"));
    memberContactLink.className = "link";

    row.insertCell().appendChild(this.StateControl.Render());
    row.insertCell().appendChild(this.CountyControl.Render());
    row.insertCell().appendChild(button);
    row.insertCell().appendChild(helpLink);
    row.insertCell().appendChild(memberContactLink);
    search.insertRow().insertCell().appendChild(obj);

    return search;
}

__setMap = function()
{
    PageMethods.GetServiceAreaContacts(GetMap().NewDigSiteGeometryAsJson, __getServiceAreaContacts_onComplete);
}

__getServiceAreaContacts_onComplete = function(result, response, method)
{
    if (result.substring(2, 0) != "({")
    {
        //  If doesn't start with "({" then it's an error message
        alert(result);
        return;
    }

    var serviceAreas = eval(result).ServiceAreas,
        container = document.createElement('div'),
        contactTable = document.createElement('table'),
        header = contactTable.insertRow();

    header.className = 'datagridHeader';
    container.id = 'emergencyContactTable';
    contactTable.className = 'datagrid';
    contactTable.style.width = '95%';
    contactTable.id = container.id + '_grid';

    header.insertCell().innerHTML = 'Member Utility';
    header.insertCell().innerHTML = 'Main Contact#';
    header.insertCell().innerHTML = 'Vacuum Contact#';
    header.insertCell().innerHTML = 'Emergency Contact#';
    header.insertCell().innerHTML = 'After Hours Contact#';
    for (var i = 0; i < serviceAreas.length; i++)
    {
        var row = contactTable.insertRow();
        row.className = 'datagridCell';
        row.insertCell().innerHTML = serviceAreas[i].Name;
        row.insertCell().innerHTML = serviceAreas[i].Main;
        row.insertCell().innerHTML = serviceAreas[i].Vacuum;
        row.insertCell().innerHTML = serviceAreas[i].Emergency;
        row.insertCell().innerHTML = serviceAreas[i].AfterHours;
    }

    $getControl('MapFrame').style.visibility = 'hidden';
    $getControl('MapFrameInstructions').style.visibility = 'hidden';
    var search = $getControl('EmergencyContactSearch'),
		button = document.createElement('<input type="button" />'),
		printVersion = document.createElement('a'),
		spacer = document.createElement('div');

    spacer.innerHTML = '&nbsp;';
    button.value = 'Another Search?';
    button.onclick = "$getControl('EmergencyContactSearch').removeChild($getControl('emergencyContactTable'));$getControl('EmergencyContactLocations').style.display='block';$getControl('MapFrame').style.visibility = 'visible';$getControl('MapFrameInstructions').style.visibility = 'visible';";
    button.id = container.id + '_button';

    printVersion.innerHTML = 'Printer friendly version';
    printVersion.className = 'hyperlink';
    printVersion.onclick = "__emergencyContacts_print();";
    printVersion.id = container.id + '_print';


    container.appendChild(contactTable);
    container.appendChild(button);
    container.appendChild(spacer);
    container.appendChild(printVersion);
    search.appendChild(container);
    new Event().RefreshAll(button.id);
    new Event().RefreshAll(printVersion.id);
    $getControl('EmergencyContactLocations').style.display = 'none';
}

__getStates_onComplete = function(result, response, method) {
    if (!result) return;

    var locations = new LocationsControl(eval(result).states, 'EmergencyContactLocations');
    $getControl('EmergencyContactSearch').appendChild(locations.Render());
    var e = new Event();
    e.RefreshAll(locations.StateControl.Control);
    e.RefreshAll(locations.CountyControl.Control);
    e.RefreshAll(locations.ID + '_button');

    var mapFrame = $getControl('MapFrame');
    mapFrame.style.visibility = 'visible';
    mapFrame.style.width = '800px';
    mapFrame.style.height = '500px';

    $getControl('MapFrameInstructions').style.visibility = 'visible';

    //Should only need to do this here to resize the map correctly.  This gets called when you choose the 
    //  "I Accept" from the disclaimer portion. And since we are changing the Map size we should resize it.
    ResizeMap();

    //  The map may still be loaded the map def, so use a timer to periodically check to see
    //  when it's finished.  Otherwise, we may try to position before the map is loaded which will
    //  cause it to not be positioned at all.
    setTimeout("CheckMapEvents()", 500);
}

function CheckMapEvents()
{
    var map = GetMap();
    
    if ((map != null) && map.IsMapDefinitionLoaded)
    {
        var loc = new LocationsControl(null, 'EmergencyContactLocations');
        map.ZoomToEnvelopeFromJson(loc.CountyControl.GetSelectedValue());
    } else
    {
        //  Still not loaded, need to try again
        setTimeout("CheckMapEvents()", 500);
    }
}

__locationsControl_setCounties = function(locationsID)
{
    var loc = new LocationsControl(null, locationsID),
        currentState = loc.StateControl.GetSelectedValue();

    loc.CountyControl.Clear();

    for (var i = 0; i < loc.Locations.length; i++)
        if (loc.Locations[i].abbr == currentState)
        break;

    loc.Locations[i].counties.sort(function(a, b) {
        var aText = a.name.toLowerCase(),
		bText = b.name.toLowerCase();
        if (aText < bText) return -1;
        if (aText > bText) return 1;
        return 0;
    });
    for (var j = 0; j < loc.Locations[i].counties.length; j++)
        loc.CountyControl.AddOption(loc.Locations[i].counties[j].env, loc.Locations[i].counties[j].name);

    GetMap().ZoomToEnvelopeFromJson(loc.CountyControl.GetSelectedValue());
}

__locationsControl_changeCounty = function(locationsID)
{
    var loc = new LocationsControl(null, locationsID);
    GetMap().ZoomToEnvelopeFromJson(loc.CountyControl.GetSelectedValue());
}

GetMap = function()
{
    return window.frames['MapFrame'].document.getElementById('_Map');
}

__emergencyContacts_print = function()
{
    var win = window.open('', 'printwin', 'directories=0,location=0,menubar=0,scrollbars=0,titlebar=0,toolbar=0');
    win.document.write('<head><link id="stylesheet" href="' + GetBaseUrl() + '/Css/stylesheet.css" rel="stylesheet" type="text/css"/></head><body>' + $getControl('emergencyContactTable_grid').outerHTML + '</body>');
    win.document.close();
    win.document.location.reload(true);
    win.print();
    //win.close();
}


