// Code Logic
$(document).ready(function() {
    
    if($('#find-project-content .country-selector').get(0)){
       $('#find-project-content .country-selector').change(project_change_country); 
       $('#find-project-content .area-selector').change(project_change_area); 
       
        var cache = {};
        
        // Cache::Options
        cache['options'] = {};
        cache['options']['Default'] = '<option selected="selected" value="None">' + project_strings['areaDropDownDefault'] + '</option>';
        cache['options']['None'] = '<option selected="selected" value="None">' + project_strings['areaDropDownEmpty'] + '</option>';
    
        // Cache::Results
        cache['results'] = {};
        cache['results']['Default'] = '<p style="color:#5C564F">' + project_strings['resultsSectionDefault'] + '</p>';
        cache['results']['None'] = '<p style="color:#5C564F">' + project_strings['resultsSectionEmpty'] + '</p>';
        
        // Cache::Coordinates
        cache['coord'] = {};
        cache['coord']['Default'] = project_coord['Default'];
    }
    
    /**
     * Handle Project Change Country Callback.
     */
    function project_change_country(){
      var value = $(this).find('option:selected').attr('value');
      var coord = null;
      if(value == "None"){
          // Reset Fields.
          
          // Area::DropDown  
          $('#find-project-content .area-selector').html(cache['options']['Default']);
          $('#find-project-content .area-selector').attr("disabled", "");
          
          // Results::Section
          project_results_populate(cache['results']['Default']);
          
          // Map Center;
          coord = cache['coord']['Default'];
          if(coord != "None"){
            project_map_set_center(coord);
          }
      }else if(typeof(project_areas[value]) != "undefined"){
        // country is defined populate the Area::DropDown.
        if(typeof(cache['options'][value]) == "undefined"){
            // Make html for select and cache it.
            if(project_areas[value].length > 0){
                var options = ['<option selected="selected" value="None">' + project_strings['areaDropDownDefault'] + '</option>'];
                $.each(project_areas[value], function(key, area){
                    options[options.length] = '<option value="' + key + '">' + area + '</option>';
                });
                cache['options'][value] = options.join('');
            } else {
                cache['options'][value] = "None"; 
            } 
            
            // Init Cache::Handlers for the result of the given country.
            cache['results'][value] = {};
            cache['results'][value]['all'] = "";
            cache['results'][value]['entries'] = [];
            
            // Make html for results and cache it.
            if(project_results[value].length > 0){
                var links = [];
                $.each(project_results[value], function(key, entries){
                    $.each(entries, function(key, link){
                        links[links.length] = '<li><a href="' + link.href + '">' + link.title + '</a></li>';
                    });
                });
                cache['results'][value]['all'] = '<ul>' + links.join('') + '</ul>';
            }else{
               cache['results'][value]['all'] = "None";
            }
            
            // Init cache for coord
            cache['coord'][value] = {};
            cache['coord'][value]['all'] = {};
            cache['coord'][value]['regions'] = {};
            coord = project_coord[value]['all'];
            if((typeof(coord) == "undefined") || (coord == "None") || (coord == null)){
               coord = "None";
            }
            cache['coord'][value]['all'] = coord;
         }
        
        var content = cache['options'][value];
        if(content != "None"){
           // Set Value for Area::DropDown
           $('#find-project-content .area-selector').html(content);
           $('#find-project-content .area-selector').attr("disabled", "");
           
        } else {
          // Disable Area::DropDown  
          $('#find-project-content .area-selector').html(cache['options']['None']);
          $('#find-project-content .area-selector').attr("disabled", "disabled");
        }
        
        // Results::Section::Area
        content = cache['results'][value]['all'];
        if(content != "None"){
          // We Have Results
          project_results_populate(content);
        } else {
          // No Results
          project_results_populate(cache['results']['None']);
        }
        
        coord = cache['coord'][value]['all'];
        if(coord != "None"){
           project_map_set_center(coord);
        } 
      }
    }
    
    /**
     * Handle Project Change Area Callback.
     */ 
    function project_change_area(){
        var area = $(this).find('option:selected').attr('value');
        var country = $('#find-project-content .country-selector').find('option:selected').attr('value');
        var content = "";
        var coord = null;
       
				// populate results for the area of the given entry.
				if(typeof(cache['results'][country]['entries'][area]) == "undefined"){
					cache['results'][country]['entries'][area] = "None";
					try {
						if(project_results[country][area].length){
							var links = [];
							$.each(project_results[country][area], function(key, link){
								links[links.length] = '<li><a href="' + link.href + '">' + link.title + '</a></li>';
							});
							cache['results'][country]['entries'][area] = '<ul>' + links.join('') + '</ul>';
						}
					}catch(e){
						// supress error, area index/key mismatch. 
					}
					coord = "None";
					if(project_coord[country]['regions'].length > 0){
						coord = project_coord[country]['regions'][area];
						if((typeof(coord) == "undefined") || (coord == "None") || (coord == null)){
							coord = "None";
						}
					}
					cache['coord'][country]['regions'][area] = coord;
				}
				
				if(area != "None"){
						content = cache['results'][country]['entries'][area];
        } else {
            // use the global values.
            content = cache['results'][country]['all'];
        }
        
        // Update Results::Section
        if(content != "None"){
            // We Have Results
            project_results_populate(content);
        } else {
            // No Results
            project_results_populate(cache['results']['None']);
        }
        
        coord = cache['coord'][country]['regions'][area];
        if(coord != "None"){
            project_map_set_center(coord);
        }
    }
    
    /**
     * Populate the Results::Section
     * 
     * @param content   The html content to append onto the results-section.
     */
    function project_results_populate(content){
        // Remove All Other elements than the Heading.
        $('#find-project-content .two-col-container :not(.select-heading)').remove();
        
        // Append Content.
        $('#find-project-content .two-col-container').append(content);
    }
});

// Public Methods.
/**
 * Assign new Center for the map.
 *
 * @param coord   The coord object with the params to call the api with.
 */
function project_map_set_center(coord){
    try{
       	swfobject.getObjectById("project-map-container").setCenter(coord["lat"], coord["lng"], coord["zoom"], true);
    }catch(e){ /* */ }
}

/**
 * Show Info Window
 *
 * @param markerId	The id for the marker to activate and show the infoWindow for.
 */
function project_map_show_info_window(markerId){
	try{
     	swfobject.getObjectById("project-map-container").showInfoWindow(markerId);
  }catch(e){ /* */ }
}
