/*
    Copyright (c) 2009-2010, SpatialPoint, LLC.
    
    www.spatialpoint.com
*/
$(document).ready(function() 
{
    // Checks for Enter key, and submits geocode request.
    function testForEnter(e)
    {
        if (isKeyPressed(e, 13))
        { 
            findLocation(); 
            
            return false;
        }
    }
    
    //
    // Input field L&F during user interaction.
    //     
    $('input[type="text"], select.locationFinder').addClass("idleField");

	$('input[type="text"], select.locationFinder').focus(function() 
	{
		$(this).removeClass("idleField").removeClass("setField").addClass("focusField");
	    
	    if (this.value == this.defaultValue)
	    { 
	    	this.value = '';
		}
		if ((this.value != this.defaultValue) && this.select)
		{
			this.select();
		}
	});
	
	$('input[type="text"], select.locationFinder').blur(function() 
	{
		$(this).removeClass("focusField");
		
	    if ($.trim(this.value) == '')
	    {
	    	this.value = (this.defaultValue ? this.defaultValue : '');
		
    		$(this).addClass("idleField");
		}
		else
		{
		    if (this.value != this.defaultValue)
		    {
        		$(this).addClass("setField");
  		    }
		    else
		    {
        		$(this).addClass("idleField");
		    }
		}
		
	});

    //
    // Side Bar.
    //
    
    //
    // Phone Survey
    //
    
    $("input.phoneSurvey").click(function()
    {
        function getSortedKeys(hashtable)
        {
            var list = [];
            
            for (var i in hashtable)
            {
                list.push(i);
            }
            
            list.sort();

            return list;
        }

        // Hide messages.
        $("div.band_message").css("display", "none");
        
        // Clear lookups.
        $("#mfg").empty();
        setOptions("mfg", ["Manufacturer"].concat(getSortedKeys(phones[this.id])));

        $("#model").empty().append("<option>Model</option>");
    
        $get("mfg").phoneType = this.id;
    });

    $("select#mfg").change(function()
    {
        $("div.band_message").css("display", "none");

        var mfg = this.options[this.selectedIndex].text;

        if (mfg == "Manufacturer")
        {
            $("#model").empty().append("<option>Model</option>");
        }
        else
        {
            setOptions("model", ["Model"].concat(getFieldValues(phones[this.phoneType][mfg], "DisplayName")));
        }
    });
    
    $("select#model").change(function()
    {
        function getPhone(manufacturer, model)
        {
            for (var i = 0; i < phoneList.length; i++)
            {
                var phone = phoneList[i];
                
                if ((phone.Manufacturer == manufacturer) && (phone.DisplayName == model))
                {
                    return phone;
                }
            }
            
            return "Unknown";
        }

        $("div.band_message").css("display", "none");
        
        var sel1 = $get("mfg");
        var sel2 = $get("model");

        if ((sel1.selectedIndex > 0) && (sel2.selectedIndex > 0))
        {
            var phone = getPhone(sel1.options[sel1.selectedIndex].text, sel2.options[sel2.selectedIndex].text);
            
            if (phone.Band == "Dual-band")
            {
                $("#dualBandMessage").css("display", "block");
            }
            else
            {
                $("#triBandMessage").css("display", "block");
            }
            
            if (phone.Acquisition == "MetroFLASH")
            {
                $("#metroFLASHMessage").css("display", "block");
            }
        }
    });

    //    
    // Find A Store.
    //
    
    $("#findAStore").click(function()
    {
        var zipcode = $("#findAStoreZip").val();
        
        if (!/^\d{5}$/.test(zipcode))
        {
            alert("Please enter a 5 digit ZIP Code!");
            return;
        }
        
        window.location.href = "http://www.metropcs.com/storelocator/default.aspx?zipcode=" + zipcode;
    });
    
    $("#shopForPhones").click(function()
    {
        window.location.href = "http://www.metropcs.com/shop/phonelist.aspx";
    });
    
    //
    // Find Location.
    //
    
    // For input fields and State selection lists.
    $("input.locationFinder, select.locationFinder").keypress(testForEnter);

    // Use this to reset several forms at once.
    $("a.clear").click(function() 
    {
        $("form").each(function() 
        {
            this.reset();
        });

    	$('input[type="text"], select').each(function(i) { $(this).removeClass("setField").addClass("idleField"); });

		$(this).removeClass("focusField");

        // Hide matches/results.
        $("div.form_row_matches").css("display", "none");    
        
        // Remove pushpin.
        removePushpin();

        // Perform custom actions.
        onClearLocation();
    });

    $("a.find").click(function() 
    {
        findLocation();
    });

    //
    // Map tab controls.
    //
    
    $("area.map_tab").click(function() 
    {
        setActiveMapTab($(this).attr("tabId"));
    });

    $("a.map_tab").click(function() 
    {
        setActiveMapTab(this.id);
    });

    $("a.generaltab").click(function() 
    {
        setActiveMapTab("tab_generalcoverage");
    });

    $("a.dualbandtab").click(function() 
    {
        setActiveMapTab("tab_dualband");
    });

    $("a#tab_dualband").click(function() 
    {
	    $("div.popup").css("display", "none");
	    $("div#popup_dualband").css("display", "block");
    });

    $("a.button.close").click(function() 
    {
	    $("div.popup").css("display", "none");
    });

    // 
    // Helper functions.
    //
    
    // Construct a hashtable of phones broken down first by if they're MetroFlash or not, and then by manufacturer.
    function loadPhones()
    {
        var acquisition;
        var manufacturer;
        
        for (var i = 0; i < phoneList.length; i++)
        {
            // Fix phoneList DisplayName.
            phoneList[i].DisplayName = phoneList[i].DisplayName.replace("�", "™");
            
            acquisition = phoneList[i].Acquisition;
            key = phoneList[i].Manufacturer;
            
            if (phones[acquisition][key])
            {
                phones[acquisition][key].push(phoneList[i]);
            }
            else
            {
                phones[acquisition][key] = [phoneList[i]];
            }
        }
        
        // Select the MetroPCS type phones by default.
        $("#MetroPCS").click();
    }
        
    // Change png to gif references if/where appropriate.
    function updateGraphicsReferences()
    {
        // Change over to GIFs for the spheres if necessary.
        for (var i = 0; i < dots.length; i++)
        {
            dots[i] += (imageFormat == ".png") ? ".png" : ".gif";
        }

        if (imageFormat != ".png")
        {
            // Perform a global change to the "GIF" version.
            
            $("img.homeArea").attr("src", dots[0]);
            $("img.extendedArea").attr("src", dots[1]);
            $("img.futureArea").attr("src", dots[2]);
        }
    }

    function computePopupPositions()
    {
        var offset = $("#ve_map").offset();

        var centroid = 
        {
            top: offset.top + ($("#ve_map").height() / 2),
            left: offset.left + ($("#ve_map").width() / 2)
        };
        
        $("#popup_dualband")
            .css("top", centroid.top - ($("#popup_dualband").height() / 2))
            .css("left", centroid.left - ($("#popup_dualband").width() / 2));
        
        $("#tab_address_match")
            .css("top", centroid.top - ($("#tab_address_match").height() / 2))
            .css("left", centroid.left - ($("#tab_address_match").width() / 2));
        
    }
    
    //
    // Startup.
    //
    
    updateGraphicsReferences();
    
    loadPhones();

    computePopupPositions();
        
    // Perform the remaining (map oriented) setup routines.   
    appSetup();
});
