//
// File : station.js
//
// Description : Javascript functions for Weather
//
// Contents    : 





var stations = null;
var savedStationId = getStationId();


  //
  // Initialize this page's widgets
  //
  function initWeather () {
 	//alert('station : ' + savedStationId);   
    setStation( document.getElementById("acisstationselect") );  
     
    //Cookies are required for this ajax-y thing to work without a hundred forms ...
    cookiesRequiredPrompt();
    
	updateContent();
  }
  
  //
  // Load the stations selectbox
  //
  var loadStations = function(data) {
     stations = data;
  
   	 var selectBox = parent.document.getElementById("acisstationselect");

	 // create select options for each station
   	 for(var i=0;i<stations.length; i++) {	   		
		selectBox.appendChild( createSelectOption( stations[i] ) );
     }
     //alert('station : ' + savedStationId);
     setStation(selectBox);
  }



  

  
  //
  // create a select box option for an station obj
  //
  function createSelectOption(station) {
    var id = getStationId();
  	var _option=document.createElement("OPTION");
	_option.value=station.id;
	if(station.id == id )
	  _option.selected=true;
	_option.innerHTML=station.name;
	return _option;  
  }
  
  //
  // The station value was changed
  //
  function stationChanged(selectBox) {
    var options = selectBox.options;
  	var index = selectBox.selectedIndex;
  	
	var stationId = options[index].value;
	savedStationId = stationId;
	
    setCookie("acisStationId", stationId);

	updateContent();
  }

 
  
  //
  // Get the station Id from a cookie or saved var
  //
  function getStationId() {
  	var stationId = getCookie("acisStationId");
  	if(stationId == null) 
  	  stationId = savedStationId;
  	else
  	  savedStationId = stationId;
  	  
  	if(stationId == null) 
  	  stationId = '205'; //Edmonton  
  	return stationId;
  }

  //
  // Set the currently selected station
  //
  function setStation(selectBox) {
  	if(!selectBox) return;
  	
	var id = getStationId();
  	for (i=0; i<selectBox.options.length; i++) {
		if (selectBox.options[i].value == id) {
  		  selectBox.selectedIndex = i;
			break;
		}
	} 
	
  }

	var stationDetailWindow;
	var stationMapWindow;
	
	//
	// Shows the station detail dialog for the currently selected
	// acis station
	//
	function showStationDetail()
	{
	    var options = document.getElementById("acisstationselect").options;
  	    var index = document.getElementById("acisstationselect").selectedIndex;
  	
	    var stationId = options[index].value;
	
		var url = 'http://www2.agric.gov.ab.ca/app10/loadstationinfo?id=' + stationId;
		stationDetailWindow=window.open(url,'','width=550,height=440,scrollbars=yes,resizable=yes');
		if (stationDetailWindow && window.focus) {stationDetailWindow.focus()}
	}


	//
	// Shows the station map dialog for the currently selected locality
	//
	function showStationMap()
	{
		var url = '/app21/rtw/weather/stationmap.jsp';
		stationMapWindow=window.open(url,'','width=700,height=675,scrollbars=yes,resizable=yes');
		if (stationMapWindow && window.focus) {stationMapWindow.focus()}
	}
	
	

    //
    // returns the selected period
    //
    function getSelectedPeriod() {
        var periodSelector = document.getElementById("periodSelect");
	  	if(!periodSelector)
	  	   return;
    
	    var options = periodSelector.options;
  		var index = periodSelector.selectedIndex;
	  	var period = options[index].value;
	  	var periodTxt = options[index].text;
    
        return period;
    }


    //
    // Called when the period changed
    //
    function periodChanged() {
    	setCookie('period', getSelectedPeriod());
		
		updateContent();
    }

	//
	// updates the content for the current page
	//
	function updateContent() {	
		updateAlmanac();
		updateGraph();
		//updateGraphImage();	
		updateDetail();
		updateSummary();
	}
//
// Tabs
//
      function setPreferredTab(tab) {
	      setCookie('preferredTempTab', tab);
      }

	  function getPreferredTab() {
	      var tab = 'summary';
	      var pref = getCookie('preferredTempTab');
	      if(pref)
	         tab = pref;
	      return tab;
	  }

      function showPreferredTab() {
        var tab = getPreferredTab();
        var panel = tab + 'Panel';
        
      	showPanel(this, panel, tab);
      }
      
      //
      // http://concepts.waetech.com/dhtml_tabs/stretch.cfm
      //
      var panels = new Array('detailPanel','summaryPanel','graphPanel' );
      var selectedTab = null;
      
      //
      // Set the selected panel/tab
      //
      function showPanel(tab, name, type)
      {
      
	for(i = 0; i < panels.length; i++)
        try { 
        if(document.getElementById(panels[i]) && document.getElementById(panels[i]).style)
	      	document.getElementById(panels[i]).style.display = (name == panels[i]) ? 'block':'none';
		
			
        if (selectedTab) 
        {
          // change the previous selected tab back to normal
          if(!selectedTab.style)
	          selectedTab.style = ''; 
          selectedTab.style.backgroundColor = '';
          selectedTab.style.fontWeight = 'normal';
          selectedTab.style.paddingTop = '';
          selectedTab.style.marginTop = '4px';
        }
        if(tab) {
          selectedTab = tab;
          if(!selectedTab.style)
          	selectedTab.style = ''; 
		  selectedTab.style.backgroundColor = 'silver';
		  selectedTab.style.fontWeight = 'bold';
		  selectedTab.style.paddingTop = '6px';
		  selectedTab.style.marginTop = '0px';
	    }
		
		setPreferredTab(type);	
		} catch(e) {}
		
        return false;
      }

      
      
      ///
      /// Graphing
      ///
      
      function getDefaultParameterId() {
	  	 return "1";	  
	  }
	  
	  function getCurrentStationId() {
	     return "1";
	  }
	  
	  //
	  //
	  //
	  
	  function getParameterId() {
	    var selectBox = document.getElementById("parameterSelect");
	    if(!selectBox) return 0;
	    
	    var options = selectBox.options;
  		var index = selectBox.selectedIndex;
  		
	  	var parameterId = options[index].value;
	  	var parameterName = options[index].text;
	  	if(!parameterId)
	  		parameterId = getDefaultParameterId();
	
	  	return parameterId;	  
	  }
  
   	  //
	  // Update the graph tab
	  //
	  function updateGraph() {
	    if( document.getElementById('graphContent') ) {
	  		ajaxpage('/app21/weathergraph', 'graphContent');
	  	}	  	
	  }

   	  //
	  // Update the graph tab
	  //
	  var updateAlmanac = function () {
	    var div = document.getElementById('almanac');
	    if( div ) {
	    	var url = '/app21/weatheralmanac';
	  		ajaxpage(url, 'almanac');
	  	}	  	
	  }
	  
	  
	function almanacChanged() {
	 	var options = document.getElementById("almanacDaysSelect").options;
  		var index = document.getElementById("almanacDaysSelect").selectedIndex;
		var days = options[index].value;

		setCookie('almanacDays', days);
		updateAlmanac();
	}

  	  //
	  // Update the detail tab
	  //
	  function updateDetail() {
	    if( document.getElementById('detailContent') ) {
	  		ajaxpage('/app21/weatherdetail', 'detailContent');
	  	}
	  }
	  
	  //
	  // Update the detail tab
	  //
	  function updateSummary() {
	    if( document.getElementById('summaryContent') ) 
	  		ajaxpage('/app21/weathersummary', 'summaryContent');
	  }

/***********************************************
* Dynamic Ajax Content- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

var bustcachevar=1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects=""
var rootdomain="http://"+window.location.hostname
var bustcacheparameter=""

function startLoadingMessage(container) {
	var div = document.getElementById(container);
	if( div )  {
		var width = div.style.width;
		div.innerHTML = '<div style="width: ' + width + ';"><p/><img src="/app21/rtw/icons/loading.gif"><p/>&nbsp;<p/></div>';
	}
}

//
// load a page using ajax methods
//
function ajaxpage(url, containerid){
	var page_request = false
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest()
	else if (window.ActiveXObject){ // if IE
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP")
		} 
		catch (e){
			try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP")
			}
			catch (e){}
		}
	}
	else
		return false

	startLoadingMessage(containerid);
	
	page_request.onreadystatechange=function(){
		loadpage(page_request, containerid)
	}

	if (bustcachevar) //if bust caching of external page
		bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
	page_request.open('GET', url+bustcacheparameter, true)
	page_request.send(null)
}

//
// load page
//
function loadpage(page_request, containerid){
	if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)) {
		document.getElementById(containerid).innerHTML=page_request.responseText		
	}
}

//
// load objs
//
function loadobjs(){
	if (!document.getElementById)
		return
	for (i=0; i<arguments.length; i++){
		var file=arguments[i]
		var fileref=""
		if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
			if (file.indexOf(".js")!=-1){ //If object is a js file
			fileref=document.createElement('script')
			fileref.setAttribute("type","text/javascript");
			fileref.setAttribute("src", file);
		}
		else if (file.indexOf(".css")!=-1){ //If object is a css file
			fileref=document.createElement("link")
			fileref.setAttribute("rel", "stylesheet");
			fileref.setAttribute("type", "text/css");
			fileref.setAttribute("href", file);
		}
	}
	
		if (fileref!=""){
			document.getElementsByTagName("head").item(0).appendChild(fileref)
			loadedobjects+=file+" " //Remember this object as being already added to page
		}
	}
}
	  

	        
