﻿
        
    // var opacitySupported = $.support.opacity;
    var opacitySupported = true;     
           
    var selectedPanel;

	function left(str, n){
		if (n <= 0)
			return "";
		else if (n > String(str).length)
			return str;
		else
			return String(str).substring(0,n);
	}
	
    function countryChanged(oList) {
        $('.formGroup input').val('');
        if (oList.selectedIndex == 0) {
            updateStates("US");
        } else if (oList.selectedIndex == 1) {
            updateStates("CA");
        } else if (oList.selectedIndex == 2) {
            updateStates("AS");
        } else if (oList.selectedIndex == 3) {
            updateStates("NZ");
        } else if (oList.selectedIndex == 4) {
            updateStates("UK");
        }
    } 

    function updateStates (country, state) {
        var stateddl = document.getElementById('state');
        if (stateddl == null) {
            return true;
        }
        if ('US|CA|AS'.indexOf(country) > -1) {
            enableStates(true);
        } else if ('NZ|UK'.indexOf(country) > -1 ){
            enableStates(false);
        }
        if ('UK'.indexOf(country) > -1) {
            enableUKInputs(true);
        } else {
            enableUKInputs(false);
        }

        for (var i = stateddl.options.length; i >= 0; i--) {
            stateddl.remove(i);
        }
        for (index in myStates) {
            if (myStates[index][1] == country) {
                stateddl.options[stateddl.options.length] = new Option(myStates[index][2], myStates[index][0]);
                if ( myStates[index][0] == state ) {
                    stateddl.selectedIndex = stateddl.options.length - 1;
                }
            }
        }
    }

    /* If the UK is selected, we should provide more room for postal code
    by removing the non-usable state dropdown */
    function enableUKInputs(enable) {
        var zip = $('#ctrlZip');
        var stateDiv = $('#state').parent();
        var city = $('#ctrlCity');

        var watermark = function () {
            zip.val('recommended');
            zip.css('color', 'gray');
            zip.css('font-size', 'x-small');
        };

        var unWatermark = function () {
            zip.css('color', '');
            zip.css('font-size', '');
        };

        if (enable) {
            stateDiv.hide();
            zip.addClass('uk');
            city.addClass('uk');
            if (zip.val() == '') {
                watermark();
            }
            zip.focus(function () {
                if (zip.val() == 'recommended') {
                    zip.val('');
                    unWatermark();
                }
            });
            zip.blur(function () {
                if ($.trim(zip.val()) == '') {
                    watermark();
                }
            });
        } else {
            unWatermark();
            zip.removeClass('uk');
            city.removeClass('uk');
            zip.die(); 
            stateDiv.show();
        }
    }

    function enableStates(enable) {
        var ddlState = $('select[id=\'state\']');
        if (enable == true && ddlState.attr('disabled') == true) {
            ddlState.removeAttr('disabled');
        } else if (enable == false && ddlState.attr('disabled') == false) {
            ddlState.attr('disabled', 'disabled');
        }
    }
    
    function checkForResults() {
    
        var hasResults = false;
	
		$("#ctrlMapDisplay").append("<h1>Perform a search above to find your elected officials</h1><div class='mapBox firstLoad'><img src='images/globalMap.gif'></div><!--<h4>Primary Address</h4><h4 class='half'>Phone</h4><h4 class='half'>Fax</h4><h4>Web Site</h4>-->");
					
        if (window.state_officials) { 
            displayOfficials(state_officials, document.getElementById('ctrlResultsStatePicker'));
			addResultsPanelAnimations("ctrlResultsState", "State");
			hasResults = true;
        }
        if (window.national_officials) {
            displayOfficials(national_officials, document.getElementById('ctrlResultsNationalPicker'));
			addResultsPanelAnimations("ctrlResultsNational", "National");
			hasResults = true;
        }
        if (window.nonlegdistricts) {
            displayDistricts(document.getElementById('ctrlResultsNonLegPicker'));
			addResultsPanelAnimations("ctrlResultsNonLeg", "Non-legislative");
			hasResults = true;
        }
        if (window.local_officials) {
            displayOfficials(local_officials, document.getElementById('ctrlResultsLocalPicker'));
			addResultsPanelAnimations("ctrlResultsLocal", "Local");
        }
        else if (hasResults) {
            var div = $('<div id="noLocalResults">No local results available. ' +
            'Please see our <a href="http://www.azavea.com/Products/Cicero/Learn/' + 
            'CiceroAvailability.aspx" target="_blank" >City Availability List</a>.  ' +
            '<a href="mailto:cicero@azavea.com">Contact us</a> if you would like ' +
            'your city added.</div>');
            div.appendTo('#ctrlResultsLocal');
            div.show();
        }
        
        selectFirstDistrict();
    }
    
    function addResultsPanelAnimations(resultsPanelId, resultType) {
        $("#" + resultsPanelId + "Header").children(".expandButton").empty().append("Click here to toggle " + resultType + " results");
	    $("#" + resultsPanelId + "Header").click(function(event) { 
            $("#" + resultsPanelId + "Header h1").toggleClass("headerActive");

		    event.preventDefault();

            var diff = $("#" + resultsPanelId + "Picker").height();
            var myTop = $('#' + resultsPanelId).position().top;
            selectedPanelTop = $("#" + selectedPanel).position().top;
            
            if (selectedPanelTop > myTop) {
                if ($("#" + resultsPanelId + "Picker").is(':hidden')) {
                    diff = "+=" + diff + "px";
                }
                else {
                    diff = "-=" + diff + "px";                
                }
    		    $("#" + resultsPanelId + "Picker").slideToggle()
                $('#ctrlMapDisplay').animate({"marginTop" : diff}, "normal", fireCiceroResizedEvent);
            }
            else {
    		    $("#" + resultsPanelId + "Picker").slideToggle("normal", fireCiceroResizedEvent)
            }
		});
    }
    
    function selectFirstDistrict() {
        if (window.local_officials) {
            officialSelected(local_officials[0].official.guid, local_officials);
            $("#ctrlResultsLocalHeader h1").toggleClass("headerActive");
    		$("#ctrlResultsStatePicker, #ctrlResultsNationalPicker, #ctrlResultsNonLegPicker").hide();
        }
        else if (window.state_officials) {
            officialSelected(state_officials[0].official.guid, state_officials);
            $("#ctrlResultsStateHeader h1").toggleClass("headerActive");
    		$("#ctrlResultsLocalPicker, #ctrlResultsNationalPicker, #ctrlResultsNonLegPicker").hide();
        }
        else if (window.national_officials) {
            officialSelected(national_officials[0].official.guid, national_officials);
            $("#ctrlResultsNationalHeader h1").toggleClass("headerActive");
    		$("#ctrlResultsLocalPicker, #ctrlResultsStatePicker, #ctrlResultsNonLegPicker").hide();
        }
        else if (window.nonlegdistricts) {
            districtSelected(nonlegdistricts[0].district.identifier);
	        $("#ctrlResultsNonLegHeader h1").toggleClass("headerActive");
        	$("#ctrlResultsLocalPicker, #ctrlResultsStatePicker, #ctrlResultsNationalPicker").hide();
        }
    }    
  
    function submitWithLatLong(latitude, longitude) {
        var latField = document.getElementById('ctrlLatitude');
        latField.value = latitude;

        var lonField = document.getElementById('ctrlLongitude');
        lonField.value = longitude;
        
        __doPostBack();
        
    }
    
    function submitAmbiguous(index) {
        var indexField = document.getElementById('ctrlAmbigIndex');
        indexField.value = index;
        __doPostBack();
        
    }

    
    function officialSelected(guid, officials) {
        var mapControl = document.getElementById('ctrlMapDisplay');
        var officialPanel = getPanelByType(officials[0].official.districttype);
        selectedPanel = officialPanel.id;
        
        for (index in officials) {
            if (officials[index].official.guid == guid) {
                result = TrimPath.processDOMTemplate("officialTemplate", officials[index]);
				
				if (opacitySupported) {
				    $("#ctrlMapDisplay").fadeOut(150, function() {
                        mapControl.innerHTML = result;
                        moveMapDisplay(selectedPanel);
                        showMap(officials[index].official);
				     });
				    $("#ctrlMapDisplay").fadeIn(150);
				}
				else {
				    mapControl.innerHTML = result;
                    moveMapDisplay(selectedPanel);
                    showMap(officials[index].official);
			    }

				$("div.resultRow").removeClass("resultRowFocus");
				$("#" + guid).addClass("resultRowFocus");


                //fire off custom event so resizing works better
                
                return;
            }
        }
    }

    function districtSelected(identifier) {
        var mapControl = document.getElementById('ctrlMapDisplay');
        selectedPanel = 'ctrlResultsNonLeg';

        for (index in nonlegdistricts) {
            if (nonlegdistricts[index].district.identifier == identifier) {
                result = TrimPath.processDOMTemplate("nonLegDistrictTemplate", nonlegdistricts[index]);
				
				if (opacitySupported) {
				    $("#ctrlMapDisplay").fadeOut(150, function() {
				        mapControl.innerHTML = result;
                        moveMapDisplay(selectedPanel);
                        showMap(nonlegdistricts[index].district);
				     });
				    $("#ctrlMapDisplay").fadeIn(150);
                }
                else {
			        mapControl.innerHTML = result;
                    moveMapDisplay(selectedPanel);
                    showMap(nonlegdistricts[index].district);
                }

				$("div.resultRow").removeClass("resultRowFocus");
				$("#" + identifier).addClass("resultRowFocus");

                // fire off custom event so resizing works better
                return;
            }
        }
    }
    
    function displayOfficials(officials, panel) {
        var result = TrimPath.processDOMTemplate("officialPickerTemplate", {data: officials});
        panel.innerHTML = result;
    }
    
    function displayDistricts(panel) {
        var result = TrimPath.processDOMTemplate("nonLegPickerTemplate", {data : nonlegdistricts});
        panel.innerHTML = result;
    }
	
    function makeMap(response) {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map_canvas"));
        var boundaries = new GLatLngBounds(new GLatLng(parseFloat(response.mapinfo.miny), parseFloat(response.mapinfo.minx)), new GLatLng(parseFloat(response.mapinfo.maxy), parseFloat(response.mapinfo.maxx)));
        map.setCenter(boundaries.getCenter(), map.getBoundsZoomLevel(boundaries));
    	
    	var latitude = parseFloat($('#ctrlLatitude').val());
    	var longitude = parseFloat($('#ctrlLongitude').val());
    	var geocodedPoint = new GLatLng(latitude, longitude);

    	var myIcon = new GIcon(G_DEFAULT_ICON);
    	myIcon.image = 'images/gmaps_marker.png';
    	myIcon.iconSize = new GSize(25, 32);

    	var pointMarker = new GMarker(geocodedPoint, myIcon);
        map.addOverlay(pointMarker);
    	
        // ground overlay
        var overlay = new GGroundOverlay(response.mapinfo.imgurl, boundaries);
        map.disableDragging();
        map.disableDoubleClickZoom();
        map.addOverlay(overlay);

        }
    }
      
    function showMap(object) {
        if (object.guid)  { 
            $.getJSON("ViewMap.ashx", {mapHeight: '100', mapWidth: '100', districtID: object.districtid, districtType : object.districttype, city : object.repcity, state : object.repstate, country : object.repcountry}, makeMap);
        }
        else {
            $.getJSON("ViewMap.ashx", {mapHeight: '100', mapWidth: '100', districtID: object.districtid, districtType : object.districttype, city : object.city, state : object.state, country : object.country}, makeMap);
        }
    }
    
    function getPanelByType(distType) {
        if (/local/.test(distType)) {
            return document.getElementById('ctrlResultsLocal');
        }
        if (/state/.test(distType)) {
            return document.getElementById('ctrlResultsState');
        }
        if (/national/.test(distType)) {
            return document.getElementById('ctrlResultsNational');
        }
        return document.getElementById('ctrlResultsNonLeg');
    }

    function moveMapDisplay(officialPanel) {
        var paneltop = $('#' + officialPanel).position().top;
        var maptop = $('#ctrlMapDisplay').position().top;
        var diff = paneltop - maptop;
        $('#ctrlMapDisplay').css("margin-top", diff + "px");
        fireCiceroResizedEvent();
    }
    
    function fireCiceroResizedEvent() {
        $(document).trigger($.Event("ciceroResized"));
    }



