﻿// JScript File
var map;

window.onload = function(){
 
    var tilelayer2 = new GTileLayer(new GCopyrightCollection(), 0, 17);
    tilelayer2.getTileUrl = function(a,b) {
        b=this.maxResolution()-b;
        return "http://maps.google.com/mapsdt?id=http://ibis.htcreative.com/KML/simple_hot_clean3b.kml&x="+a.x+"&y="+a.y+"&zoom="+b;
    }
    tilelayer2.isPng = function() {return true;}
    
    
    map = new GMap2(document.getElementById("map"));
			
	// Add the map controls
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.addControl(new GScaleControl());
	
	map.setCenter(new GLatLng(25.44867367928756, -83.6328125), 5);
	map.addOverlay( new GTileLayerOverlay(tilelayer2) );
	
	map.enableContinuousZoom();
	 //enable new double click feature
	 map.enableDoubleClickZoom();
	//setupStateStyles();
	
	//storymap.fct_GRABCITY_COUNTY_STATE(1, countyCallback);
	initDecades();
	initYears();
	initCities();
}

function countyCallback(response){
    var ds = response.value;
	if( ds != null && typeof(ds) == "object" && ds.Tables != null ){
		// The number of rows
		var nos = ds.Tables[0].Rows.length;
		// Go through each of the data rows
		//start at row 1 to get rid of header -- Mo, if you change the returned Dataset, change this back to 0
		for( var i=0; i < nos; i++ ){
            var row = ds.Tables[0].Rows[i];
           // for (prop in row){
            //    console.log(prop + ": " + row[prop]); 
            //}   
        }
    }
}






function grabCityData(state, cityId, elem){
    cityControl(cityId);
    map.clearOverlays();
    //cityID = parseInt(cityId);
    
    storymap.fct_GRABH_CITY_STRIKE(state, cityId, 1, grabCityData_callback);
}

var currentLocationMarker;
//currentLocationIcon


var cityName;
var stateID;
function grabCityData_callback(response){
  
    var ds = response.value;
   	if( ds != null && typeof(ds) == "object" && ds.Tables != null ){
		// The number of rows
		var nos = ds.Tables[0].Rows.length;
		// Go through each of the data rows
		//start at row 1 to get rid of header -- Mo, if you change the returned Dataset, change this back to 0
		
		var theText = "";
	    cityName = ds.Tables[0].Rows[0]["PLACEFIP"];
	    stateID = ds.Tables[0].Rows[0]["STATE_AB"];
		for( var i=0; i < nos; i++ ){
            var row = ds.Tables[0].Rows[i];
            var sName = row["STORM_NAME"];
            var dist = row["DISTANCE"];
            var year = row["YEAR_SEASON"];
            var sId = row["BTID"];
            
            
            /*DEBUG*/
            //for (prop in row){
            //    console.log(prop + ": " + row[prop]); 
           // }
            
            
            if(i == 0){
                map.removeOverlay(currentLocationMarker);
                var lat = row["LAT"];
                var lng = row["LON"];
                var p1 = new GLatLng(lat, lng);
		        map.setCenter(p1, 6);
		        currentLocationMarker = new GMarker(p1,currentLocationIcon);
		        map.addOverlay(currentLocationMarker);
		       
		    }
            
             
           theText += "<span class='stormItem'><p style='color:#000000; display:inline; padding:0; margin:0;'>&bull;</p>" + sName + " " + year + " - " + dist + "miles</span><br />";
           theText += "<span><span class='addStormLink' onclick='addStorm(\""+sId+"\", this)'> &nbsp;&nbsp; Add to map</span></span><br />";
                      //" | " +
                      //"<span class='removeStormLink' onclick='removeStorm(\""+sId+"\")'>Remove from map</span><br />";
        }
       e("storms"+cityName).innerHTML = theText;
    }
}



var stormObject = new Object;

function addStorm(id, elem){
    if(stormObject["sid"+id] == null){
        stormObject["sid"+id] = new Array();
        storymap.fct_GETHSTORM(id, addStorm_callback);
        elem.innerHTML = "<span class='red'> &nbsp;&nbsp; Remove from map</span>";
    }else{
       for(var i = 0; i < stormObject["sid"+id].length; i++){
            map.removeOverlay(stormObject["sid"+id][i]);
        }
         stormObject["sid"+id] = null;
         elem.innerHTML = "Add to map";
    }
}


function clearAllStorms(){
    map.clearOverlays();
    stormObject = null;
    stormObject = new Object();
    grabCityData(stateID, cityName)
/*    for(prop in stormObject){
       if(typeof(stormObject[prop]) == "object"){
            for(var i = 0; i < stormObject[prop].length; i++){
                map.removeOverlay(stormObject[prop][i]);
            }
            stormObject[prop] = null;
        }
    }*/
}


var stormColorOffset = 0;
var stormColors = [
	'#000000',
	'#FF0000',
	'#00FF00',
	'#0000FF',
	'#FF6633',
	'#CC33FF',
	'#00FFFF',
	'#FFFF00',
	'#FF00FF'
];


function addStorm_callback(response){

     var ds = response.value;
   
	if( ds != null && typeof(ds) == "object" && ds.Tables != null ){
		// The number of rows
		var nos = ds.Tables[0].Rows.length;
		// Go through each of the data rows
		//start at row 1 to get rid of header -- Mo, if you change the returned Dataset, change this back to 0
		
		var overlayArray = stormObject["sid"+ds.Tables[0].Rows[0]["BTID"]];
		
		var pointsArray = [];
		var markerHTMLArray = [];
		for( var i=0; i < nos; i++ ){
            var row = ds.Tables[0].Rows[i];
            
            //DEBUG
            //if(i == 0){
            //    for(prop in row){
           //         console.log(prop + ": " + row[prop]);
           //     }
           // }
           
		    var p1 = new GLatLng( row.LAT, row.LONG);
		    
		    pointsArray.push(p1);
		    
		    
		    //myMarker = new GMarker(p1, stormIcon);
		     //BUILD MARKER FOR POINTS
		        var markerHTML = "<div class='caneInfoContainer'><div class='caneInfoPopup'><div id='caneDataHolder'>" + 
					                "<h3 style='padding:0; margin:2px'><span class='startCaneName'>"+row.NAME + "</span></h3>" + 
		                            "<span class='caneInfoLeft'><strong>Wind:</strong></span><span class='caneInfoRight'>" + row.WIND_KTS + "mph</span>"+
					                "<span class='caneInfoLeft'><strong>Forward Speed: </strong></span><span class='caneInfoRight' >"+row.FORWARDMPH + "mph<br />&nbsp;</span>"+
					                "<span class='caneInfoLeft'><strong>Heading:</strong></span><span class='caneInfoRight'>" + row.HEADING + "</span>"+
					                "<span class='caneInfoLeft'><strong>Bearing:</strong></span><span class='caneInfoRight'>" + row.BEARS + "</span>"+
					                "<span class='caneInfoLeft'><strong>Date/Time:</strong></span><span class='caneInfoRight'>" + row.AD_TIME  + "</span>"+
					                "<span class='caneInfoLeft'><strong>Category:</strong></span><span class='caneInfoRight'> " + row.CAT + "</span>"+
					                "<span class='caneInfoLeft'><strong>Pressure:</strong></span><span class='caneInfoRight'> " + row.PRESSURE + "</span>"+
					                "<span class='caneInfoLeft'><strong>Coordinates: </strong></span><span class='caneInfoRight'>" + row.LAT + " Lat., " + row.LONG+" Lon. </span>"+
		                         "</div></div></div>";
		        
		        //markerHTMLArray.push(new GInfoWindowTab("Info",markerHTML));
		        //markerHTMLArray.push(markerHTML);
		        //overlayArray[i].myHtml = markerHTML;
		        //overlayArray[i].myLatLng = p1;
		      //  GEvent.addListener(myMarker, "click", function(){
		             //Then open an info window
		      //      myMarker.openInfoWindowHtml(markerHTML);
		     //       e("output").innerHTML = markerHTML;
	        //    }); 
	        var ic = fctHICON(row.CAT);
		    myMarker = createMarker(p1, markerHTML,ic);
	        map.addOverlay(myMarker);
	        overlayArray.push(myMarker);
	   }
	   
	   /*for(var x = 0; x<pointsArray.length; x++){
	        var m = new GMarker(pointsArray[x], stormIcon);
	        
	        //console.log(pointsArray[x]);
	        //console.log(markerHTMLArray[x]);
	        
	        GEvent.addListener(m, "click", function(){
		            // Then open an info window
		            m.openInfoWindowHtml(markerHTMLArray[x]);
	        }); 
	        
	        map.addOverlay(m);
		    overlayArray.push(m);
	   
	   }*/
	  
	    color = stormColors[stormColorOffset];
		if(stormColorOffset++ >= stormColors.length){ stormColorOffset = 0;}
		var newLine = createLine(pointsArray, color);
	    
	    //draw entire line at once
	    map.addOverlay(newLine);
	    overlayArray.push(newLine);
	   
    }
}


function createLine(pts, color){
    var newLine =  new GPolyline(pts,color,5,.6);
    return newLine
}

function createMarker(point,html,ic) {
        var marker = new GMarker(point,ic);
        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml(html);
        });
        return marker;
      }

function fctHICON(cat){
	var icon = new GIcon();
	
	icon.image = "/beta/images/icons/" + 
		( cat.substr(0,1) == 'H' ? 'HUR.-' : '' ) + cat + "_s.png";
	icon.iconSize = new GSize(12, 20);
	icon.iconAnchor = new GPoint(3, 17);
	icon.infoWindowAnchor = new GPoint(5, 1);
	
	return icon;
}


function initKML(){

}

var stateBGRight = "url(/beta/css/rightArrow.gif) #A3A4C3 no-repeat right center";
var stateBGDown = "url(/beta/css/downArrow.gif) #A3A4C3 no-repeat right bottom";
var countyBGRight = "url(/beta/css/rightArrow.gif) #BDBEE2 no-repeat right center";
var countyBGDown = "url(/beta/css/downArrow.gif) #BDBEE2 no-repeat right bottom";
var cityBGRight = "url(/beta/css/rightArrow.gif) #8A8AA5 no-repeat right center";
var cityBGDown = "url(/beta/css/downArrow.gif) #8A8AA5 no-repeat right bottom";

//FOR MENU
/*
*The following four functions are pretty similar, and can possibly be combined or refactored or something
*basically, each one gets the proper element in the hurricane history heirarchy based on tag name (h2, h4, h5)
*and applies a style and an onclick handler to it. This allows for a substantial file-size difference in data coming from the server
*because there is so much innformation and every piece of markup is multiplied by a huge number
*/

//globals for the history of storm tabs
var theCurrentState = null;
var theCurrentCounty = null;
var theCurrentCity = null;



function initDecades(){
    var historyContainer = e("stormHistory");
    var theStates = historyContainer.getElementsByTagName("H4");
    for(var i=0; i<theStates.length; i++){
        var state = theStates[i];
        state.className = "stateHeader";
        state.onclick = function(){
            stateControl(this.id);
        }
    }
}
function initYears(){
    var historyContainer = e("stormHistory");
    var theCounties = historyContainer.getElementsByTagName("H5");
    for(var i=0; i<theCounties.length; i++){
        var county = theCounties[i];
        county.className = "countyHeader";
        county.onclick = function(){
            countyControl(this.id);
        }
    }
}

function initCities(){
    var historyContainer = e("stormHistory");
    var theCities = historyContainer.getElementsByTagName("SPAN");
    for(var i=0; i<theCities.length; i++){
        var city = theCities[i];
        city.className = "cityHeader";
    }
}




function stateControl(theNewState){
    var theStateContainer = e("d" + theNewState);
    var theCurrentStateContainer = e("d"+theCurrentState);
    var currentStyle = theStateContainer.style.display;
    var theState = e(theNewState);
    if (currentStyle == "block"){
        theStateContainer.style.display = "none";
        theState.style.background = stateBGRight;
    }else{
        if(theCurrentState != null){
            theCurrentStateContainer.style.display="none";
            e(theCurrentState).style.background = stateBGRight;
        }
        theStateContainer.style.display = "block";
        theState.style.background = stateBGDown;
    }
    theCurrentState = theNewState;
}

function countyControl(theNewCounty){
   
    var theCities = e("y"+theNewCounty+"Container");
    var theCurrentCountyContainer = e("y"+theCurrentCounty+"Container");
    var currentStyle = theCities.style.display;
    var theCounty = e(theNewCounty);
    if (currentStyle=="block"){
        theCities.style.display = "none";
        theCounty.style.background = countyBGRight;
    }else{
        
         if(theCurrentCounty!=null){
            theCurrentCountyContainer.style.display="none";
            e(theCurrentCounty).style.background= countyBGRight;
        }
        theCities.style.display = "block";
        theCounty.style.background = countyBGDown;
    }
    theCurrentCounty=theNewCounty;
}

function cityControl(theNewCity){
   
    var theCanes = e("storms"+theNewCity);
    var theCurrentCityContainer = e("storms"+theCurrentCity);
    var currentStyle = theCanes.style.display;
    var theCity = e(theNewCity);
    if (currentStyle=="block"){
        theCanes.style.display = "none";
        theCity.style.background = cityBGRight;
    }else{
        
         if(theCurrentCity!=null){
            theCurrentCityContainer.style.display="none";
            e(theCurrentCity).style.background= cityBGRight;
        }
        theCanes.style.display = "block";
        theCity.style.background = cityBGDown;
    }
    theCurrentCity=theNewCity;
}


function e(s){
    return document.getElementById(s);
}


var currentLocationIcon = new GIcon();
currentLocationIcon.image = "images/locImage.png";
currentLocationIcon.shadow = "images/shadow50.png";
currentLocationIcon.iconAnchor = new GPoint(6, 34);
currentLocationIcon.infoWindowAnchor = new GPoint(5, 1);
currentLocationIcon.iconSize = new GSize(18, 33);

var stormIcon = new GIcon();
stormIcon.image = "images/stormIcon.png";
stormIcon.iconAnchor = new GPoint(5, 17);
stormIcon.infoWindowAnchor = new GPoint(5, 1);
stormIcon.iconSize = new GSize(9, 17);