﻿// "Traverse Florida" interface
// part of Virtual Oklawaha County
// http://www.oklawaha.org
// 
// 
//
// Version History
// ------------------------------------
// v1.0b2.1 Prevented an error occuring as the result of trying to determine the activeCounty before init
// v1.0b2 IE couldn't see logo.  Also, various internal dns handlings, they're all now manually mapped to GR.com
// v1.0b  First weekend release candidate
// v0.6   Added integrative citizenship form
// v0.5.5 Removed extra li in adj county list (caused extra bottom spacing for IE), added proper removal of clearQueue button on 0 subpanels via click-to-activate
// v0.5.4 Fixed large spacing issue between towns and adj counties in IE
// v0.5.3 Added "jumping" title to map
// v0.5.2 Fixed casing issue that resulted in multi-case county subpanels to not be activated and possibly duplicated instead
// v0.5.1 Added progressive opacity to subpanels.  Fixed DeSoto bug
// v0.5   Removed chance of duplicate subpanels, added highlight and cursor change to subpanels/buttons, resynced map/subpanel toggle, added max subpanel feature
// v0.4.1 Added GRMS + linkage, removed town of Oklawaha
// v0.4   Fixed two-word county subpanel error
// v0.3   Added transition, button rounding
// v0.2.1 Linked OC places on mini-map
// v0.2   Popup mini-map for OC, queueing/subpanels
// v0.1   Map, database-o-doom
//
// Known Bugs
// -------------------------------------
// (1) = IE   (2) = FF  (3) = Browser Independent
//
// 1 Lack of rounding of subpanels and status in IE6
// 1 Clear Queue doesn't work in IE6
// 3 Minimap/Subpanel visibility syncing issues when minimap is toggle consecutively
// 1 Lack of variable opacity subpanels
// 1 Field don't clear for IE citizenship form
//
// Future additions
// -------------------------------------
// -Lesser opacity of subpanels as older (currently the hover resets opacity) [fix for IE]
// -correspond OC on large map with miniMap
// -have option for subpanels to represent adjacent counties instead of recently selected
 


//*********OPTIONS******************

var maxNumberOfPanels = 5;  //
var progressiveFadingSubPanels = true;
var removeSubPanelOnClick = true;


//**********************************

var activeCounty = false;   //whether a county is currently selected
var activeCountyName = "";  //if selected, name of county (this could be revised to remove the activeCounty bool
var counties = [];          //all counties as an array of JS County objects
var status;                 //the summary box DOM object
var subPanelCount = 0;      //non-redundant length value of subpanels array (used for function beyond .length)
var subPanels = [];         //array of DOM nodes, as FF counts whitespace as a DOM node

// (*) doesn't appear to display correctly in IE6
var logoHTML = "<div id=\"logoBox\"><img src=\"_images/title.gif\" alt=\"FLORIDA - according to the doctrine of Gamble Rogers\" /></div>";

window.onload = function() {
	var map = document.getElementById('florida_Map');   //The <map> tag
	var countiesRaw = map.childNodes;                   //the DOM nodes
	status = document.getElementById('status');         //the little summary box
	var spinner = document.getElementById('spinner');  
	spinner.style.display = 'block';                    //accessibility.  Spinner is initially hidden, then displayed here and later hidden
	                                                    //  if page loads completely.
	
	
	for(var i=0; i<countiesRaw.length; i++){
	 //* definition
	 	counties[i] = new County(i, countiesRaw[i].href);   	//maps new county object to JS array
        countiesRaw[i].county = counties[i];                    //link map coords to JS object
		
	 //* behavior
		countiesRaw[i].onmouseover = countiesRaw[i].county.onmouseover; //onmouseover, show name
		countiesRaw[i].onmouseout = function() {                        //onmouseout, either hide if no new onmouseover county
		    try{                                                        //will fail if county selected before county objects initialized
		        if(activeCounty) {return;}}                             //    or, if clicked and mouseout, do nothing
		    catch(e) {
		        return;}
		    $('h1#' + this.county.name + "_title").hide("fast");};
		countiesRaw[i].onclick = countiesRaw[i].county.onclick;         //onclick, do behavior of corresponding JS object

    }   //end for
    
    
    //remove spinner from view, all crucial data loaded.
    var spinner = document.getElementById('spinner');  
    spinner.parentNode.removeChild(spinner);
   
   
    //prefs for rounded corners
      settings = {            
          tl: { radius: 20 },   tr: { radius: 20 },   
          bl: { radius: 20 },   br: { radius: 20 },   
          antiAlias: true,      autoPad: true, validTags: ["div"]};
          
      var myBoxObject = new CurvyCorners(settings, "statii");
      myBoxObject.applyCornersToAll();
      
      var myBoxObject2 = new CurvyCorners(settings, "helpBox");
      myBoxObject2.applyCornersToAll();
      
      
      
      //prevents the help box from popping up on every visit, currently disabled for dev
      if(showHelpAtStart){$('#helpBox').fadeIn('normal');}
                          
      //attempt to give IE NiftyCorners.  Gecko STOPs here
      if(!(BrowserDetect.browser == "Explorer")) {return;} //only IE gets nifty borders, FF uses -moz
      if(!(new NiftyCheck())){return;}

      $("#help").corner("round 10px");      //the help button, round corners (IE)
      $("#help").css({border: "0"});        //the help button, no border (IE)
      $("#clearQueue").corner("round 10px;");   //the clearQueue button, round corners (IE)
      var cq = document.getElementById('clearQueue');
      var hp = document.getElementById('help');
      cq.onmouseover = function() {this.style.cursor = 'pointer'; this.style.filter = 'alpha(opacity=100)'};
      cq.onmouseout = function() {this.style.filter = 'alpha(opacity=60)'};
      hp.onmouseover = function() {this.style.cursor = 'pointer'; this.style.filter = 'alpha(opacity=100)'};
      hp.onmouseout = function() {this.style.filter = 'alpha(opacity=60)'};
      
      $("#clearQueue").css({border: "0"});
      
      $("#status").corner("round 10px");    //the status box
};



    function showCounty(id) {
        counties[id].displayInfo(this.name);}

    function splitName(name)
	{
	    switch(name){
	        case "Santarosa":
	            return "Santa Rosa";
            case "Palmbeach":
	            return "Palm Beach";
	        case "Stjohns":
	            return "St Johns";
	        case "Dade":
	            return "Miami-Dade";  
	        case "Desoto":
	            return "DeSoto";  
	        case "Indianriver":
	            return "Indian River";  
            case "Stlucie":
	            return "St Lucie";  
	        default:
	            return name;}
	}
	


function County(id, name)
{   
	if(name === "" || !name) {return;}     //don't construct invalid nodes
 
    this.name = determineCountyNameFromHref(name); //takes # out from respective href and uses as name. also capitalizes

	this.onmouseover = function(){try{if(!activeCounty) {displayName(this.county.name); $('#fl_title').css('bottom',60 + $('#status').height() + "px");}}catch(e){} return false;};
	this.onclick = function(){
	    // * The current county is the active one
	    if(activeCounty && activeCountyName == this.county.name) {              
	        activeCounty = false; 
	        activeCountyName = this.county.name;
	        $("p.subpanel").fadeOut("slow");  //hide subpanels
	        ocmap(this.county.name);
	        
	        if(subPanels.length > 0) {
	            $("#clearQueue").fadeOut("slow");}
	                                           
	        $("ul#" + this.county.name + "_moreinfo").slideToggle("slow");
	         
	        }    //"closes" county
	        
	    // * There is no active county
	    else if(!activeCounty){      
	                                          
	        if(subPanels.length > 0)  {$('#clearQueue').fadeIn("slow"); }       //show clearQueue button if multiple subpanels
	        $("p.subpanel").fadeIn("slow");                                     //show subpanels
	        
	        if((hasSubPanel(this.county.name))) {removeSubPanel(this.county.name);} //remove selected county's subpanel, if exists
	        
	        //Show county information
	        displayInfo(this.county.name, this.county.population.innerHTML, this.county.towns.innerHTML,this.county.adjacentCounties.innerHTML, this.county.squareMiles.innerHTML, this.county.url.innerHTML);
            ocmap(this.county.name);    //show Oklawaha map if selected county is OC

	        activeCountyName = this.county.name;
	        $("ul#" + this.county.name + "_moreinfo").slideDown("slow");    //smooth transition to show county info
	        //$('#fl_title').css('bottom',60 + $('#status').height() + "px");
	        }
	    else {  //there's already an active county and it is not the selected one
	        if(subPanels.length === 0)  {$('#clearQueue').fadeIn("fast");}              //show clearQueue button
            else if(subPanels.length > 0)  {$('#clearQueue').css({display: "block"});}  //now (at least) 1 subpanel; show clearQueue
            else { $('#clearQueue').css({display: "none"}); }                           //invalid number of subpanels [error condition]                         
            
            if(!(hasSubPanel(this.county.name))){   //subpanel for selected county doesn't currently exist
                addSubPanel(activeCountyName);      
                displayInfo(this.county.name, this.county.population.innerHTML, this.county.towns.innerHTML,this.county.adjacentCounties.innerHTML, this.county.squareMiles.innerHTML, this.county.url.innerHTML);
                ocmap(this.county.name);
            }
            else {  //subpanel already exists,
              //load subpanel                                                              
              if(!(hasSubPanel(activeCountyName))){addSubPanel(activeCountyName);}
              displayInfo(this.county.name, this.county.population.innerHTML, this.county.towns.innerHTML,this.county.adjacentCounties.innerHTML, this.county.squareMiles.innerHTML, this.county.url.innerHTML);
              ocmap(this.county.name);
              removeSubPanel(this.county.name); //remove subpanel
              
            } //end else else
	   }                 //end else
                    //	   var s = 'bottom: ' + (60 + $('#status').height()) + 'px';
                    //	   alert(s);
                    //	   $('#fl_title').animate(s,"fast");
	   $('#fl_title').css('bottom',60 + $('#status').height() + "px");
	}; //end this.onclick handler


    ocmap = function(countyname) {  //displays Oklawaha mini-map if applicable
        var miniMap = $('#occutout');               //attach node to JS var
        
        if(countyname == "Oklawaha"){               //selected county is OC
            if(miniMap.css("display") != "block"){  //if going from OC displayed to no county
                $('p.subpanel').fadeOut('fast');}  
            miniMap.slideToggle('slow');            //toggle map's visibility

            }
        else if(subPanels.length > 0 && subPanels[subPanels.length - 1].innerHTML == "Oklawaha County"){//selected county is NOT OC
            miniMap.fadeOut('slow');                //hide miniMap
            $('p.subpanel').fadeIn('fast');         //show subpanels again (they toggle visib with miniMap)
            }            
    };  //finish ocmap function

    //removes a subpanel from the queueing
	removeSubPanel = function(name) {
	   name = splitName(name) + " County";
	
	   var panelRemoved = false;
	   
	   var str = "";    //testing
	   var panelToRemove;
	    for(var i=0; i<subPanels.length; i++)
	    {
	        if(panelRemoved) {subPanels[i-1].innerHTML = subPanels[i].innerHTML;}
	        else if(subPanels[i].innerHTML == name) { panelRemoved = true; panelToRemove = i; break;}
	    }
	    //alert(name + " being removed");
	    if(panelRemoved) {
	        
	        subPanels[0].parentNode.removeChild(subPanels[panelToRemove]); //remove DOM node

	        subPanels.splice(panelToRemove,1);  //remove the subpanel from the JS array
	        subPanelCount--;
	        panelRemoved = false;
	        
	        //foremost, check if no subpanels remain, if so, fadeout clearQueue button and return
	        if(!subPanels.length){
	            $("#clearQueue").fadeOut("fast");
	            return;}
	        
	        try{var origBottom = subPanels[panelToRemove].style.bottom;}
	        catch(e){}
	        
	        //move all panels higher in the array down to take the place of the removed
	        for(var panelToReposition = panelToRemove; panelToReposition<subPanels.length; panelToReposition++)
	        {
	            subPanels[panelToReposition].style.bottom = 50+30*(panelToReposition) + "px"; //repositions subpanels
	        }
	    }
       if(progressiveFadingSubPanels){resolveOpacity();}
	}; //end remove subpanel
	
	//adds a subpanel to the queueing
	addSubPanel = function(name) {
	    
	    subPanelCount++;
        $("ul#" + activeCountyName + "_moreinfo").slideToggle("slow");
        var test = document.createElement('p');
        
        test.onclick = function() {
            displayInfo(name, document.getElementById(splitName(name) + "_population").innerHTML, document.getElementById(splitName(name) + "_towns").innerHTML, document.getElementById(splitName(name) + "_adjacentCounties").innerHTML, document.getElementById(splitName(name) + "_squareMiles").innerHTML, document.getElementById(splitName(name) + "_url").innerHTML);
            
            if(subPanelCount < 0) {
                $("#clearQueue").css("display","none"); subPanelCount = 1;}              
            if(name == "Oklawaha"){
                ocmap('Oklawaha');}
            $('#fl_title').css('bottom',60 + $('#status').height() + "px");
            if(removeSubPanelOnClick) {removeSubPanel(name);}
                
        };
        $(test).addClass("subpanel");
        $(test).css("bottom",50+30*(subPanelCount-1) + "px");        
        
        
        var text = document.createTextNode(splitName(activeCountyName) + " County");
        test.appendChild(text);
        test.onmouseover = function() {this.style.opacity = '0.8'; this.style.filter = 'alpha(opacity=80)'; this.style.cursor = 'pointer';};
        test.onmouseout = function() {if(progressiveFadingSubPanels){resolveOpacity();} this.style.cursor = 'pointer';};
        test.style.opacity = 0.7;

        $(test).insertBefore("#status");
        subPanels[subPanelCount-1] = test;
        $(test).fadeIn("fast");
        
        //if more than 6 subpanels, remove lowest and move down
        
        if(subPanels.length > maxNumberOfPanels){removeSubPanel(subPanels[0].innerHTML.split(" ",1));}
        
        if(progressiveFadingSubPanels){resolveOpacity();}
	};
	
	resolveOpacity = function()
	{
	    var l = subPanels.length;

	    for(var i=0; i<l; i++)
	    {
	        subPanels[i].style.opacity = .90-.15*l+.10*i;
	        subPanels[i].style.filter = 'alpha(opacity=' + .90-.15*l+.10*i + ')'
	    }
	}
	
	
  
	
	hasSubPanel = function(name) {              //does subpanel already exist for county?
	    name = splitName(name) + " County";     //well-form the name

	    for(var i=0; i<subPanels.length; i++)   //check all subpanels
	    {
	        if(subPanels[i].innerHTML.toUpperCase() == name.toUpperCase()) { return true;}  //check value of subpanels, return if found
	    }
	    
	    return false;   //subpanel for county not found
	};
	
	    	
	this.id = document.getElementById(splitName(this.name) + "_id");    	
	this.population = document.getElementById(splitName(this.name) + "_population");
	this.towns = document.getElementById(splitName(this.name) + "_towns");
	this.adjacentCounties = document.getElementById(splitName(this.name) + "_adjacentCounties");
	this.squareMiles = document.getElementById(splitName(this.name) + "_squareMiles");
	this.url = document.getElementById(splitName(this.name) + "_url");
	
    displayInfo = function(name,population,towns,adjCounties,sqMiles,url)
    {
            activeCounty = true;
	        activeCountyName = name;
            status.innerHTML = "";
            
            
            var h1 = document.createElement("h1");
            h1.id = name + "_title";
            h1.innerHTML = splitName(name) + " County";
            status.appendChild(h1);
            
            var ul = document.createElement("ul");
            ul.id = name + "_moreinfo";
            
            var li1 = document.createElement("li"); //population
            var li2 = document.createElement("li"); //towns
            var li3 = document.createElement("li"); //adjacent counties
            var li4 = document.createElement("li"); //size (in square miles)
            var li5 = document.createElement("li"); //url of county


            
            li1.innerHTML = "Population: " + population;
            if(h1.innerHTML == "Oklawaha County") {li1.innerHTML += calcpop;}
            li2.innerHTML = "Towns: " + towns;
            li3.innerHTML = "Adjacent Counties: " + adjCounties;
            li4.innerHTML = "Size: " + sqMiles + " mi<sup>2</sup>";
            li5.innerHTML = "URL: " + url;

            li1.id = "status_1";
            li2.id = "status_2";
            li3.id = "status_3";
            li4.id = "status_4";
            li5.id = "status_5";

            ul.appendChild(li1);
            ul.appendChild(li2);
            ul.appendChild(li3);
            ul.appendChild(li4);
            ul.appendChild(li5);
            
            if(!isIE()){
                status.innerHTML = logoHTML + status.innerHTML;}
            else {
                var d = document.createElement('div');
                var i = document.createElement('img');
                
                
                
                d.id = "logoBox";
                i.src = "_images/titleIE.gif";
                
                d.appendChild(i);
                status.appendChild(d);
                }
                
                
                
               
  
            status.appendChild(ul);        
    };

    if(!isIE()){ // IE errors here and doesn't fun the function
         clearQueue = function()
         {
            $("p.subpanel").fadeOut("fast");
            $("#clearQueue").fadeOut("fast");
            $("p.subpanel").remove();
            subPanels = [];
            subPanelCount = 0;
         };    //end function clear
    }


    function isIE()
    {
       if(BrowserDetect.browser == "Explorer"){
            return true;}
       return false;
    }
 
    function displayName(name)
    {
        $('h1#' + name + "_title").show("slow");
        $('ul#' + name + "_moreinfo").show("slow");
        if(isIE()){ //IE doesn't handle DOM manipulation through text (should use textElements nodes?)
             status.innerHTML = splitName(name) + " County";
            return;
        }
        status.innerHTML = logoHTML + "<h1 id=\"" +name + "_title\">" + splitName(name) + " County</h1>";
        $('#fl_title').css('bottom',60 + $('#status').height() + "px");
    }
    
    function determineCountyNameFromHref(name)
    {
        var sansSharp = name.substring(name.search('#')+1);                             
        return (sansSharp.substring(0,1).toUpperCase() + sansSharp.substring(1));    
    }

	combineName = function(name) {
	    //take out spaces and remove "county"
        name = name.toLowerCase().replace(/ /g,"");
        name = name.replace(/county/g,"");
        name = name.charAt(0).toUpperCase() + name.substring(1);
	    return name;
	};    
    
    function splitName(name)
	{
	    switch(name){
	        case "Santarosa":
	            return "Santa Rosa";
            case "Palmbeach":
	            return "Palm Beach";
	        case "Stjohns":
	            return "St Johns";
	        case "Dade":
	            return "Miami-Dade";  
	        case "Desoto":
	            return "DeSoto";  
	        case "Indianriver":
	            return "Indian River";  
            case "Stlucie":
	            return "St Lucie";  
	        default:
	            return name;}
	}

}
