/*
 * Javacript for the 3P product.
 */

cgi = "/cgi-bin/tide-shc.cgi"

    // Time zone acronyms. Listed in the order in which they will appear in
    // the time zone list in the region window.
var TZNames = new Array ("UTC", 
                         "NDT", "NST",                         
                         "ADT", "AST", 
                         "EDT", "EST", 
                         "CDT", "CST",        
                         "MDT", "MST",
                         "PDT", "PST"
                         );

    // Time zone long names
var TZLongNames = {
               UTC_english: "UTC (0)",
               UTC_french:  "UTC (0)",
               NDT_english: "NDT (+2.5)",
               NDT_french:  "HATN (+2.5)",
               NST_english: "NST (+3.5)",
               NST_french:  "HNTN (+3.5)",               
               ADT_english: "ADT (+3)",
               ADT_french:  "HAA (+3)",
               AST_english: "AST (+4)",
               AST_french:  "HNA (+4)",               
               EDT_english: "EDT (+4)",
               EDT_french:  "HAE (+4)",
               EST_english: "EST (+5)",
               EST_french:  "HNE (+5)",               
               CDT_english: "CDT (+5)",
               CDT_french:  "HAC (+5)",               
               CST_english: "CST (+6)",
               CST_french:  "HNC (+6)",
               MDT_english: "MDT (+6)",
               MDT_french:  "HAR (+6)",
               MST_english: "MST (+7)",
               MST_french:  "HNR (+7)",
               PDT_english: "PDT (+7)",
               PDT_french:  "HAP (+7)",
               PST_english: "PST (+8)",
               PST_french:  "HNP (+8)"
              };


	/*
       * Station list status. Needed to circumvent Netscape failure
       * to provide an 'onClick()' method on <select> tags.
       * See function 'matchStationTZ()'.
       */
var stationListStatus = new Object();
stationListStatus . setTimeoutOn = 0;  // 1 if setTimeout() called in matchStationTZ()
stationListStatus . setTimeoutId = 0;  // id returned by setTimeout()


function initStationListStatus ()    {

    with (document.query.stnnum)    {
            // currentSelected: index of currently selected station
            // mapClicked:      1 if station selected through region map
        stationListStatus . currentSelected = options[options.selectedIndex].value;
        stationListStatus . mapClicked = 0;
        }
    }

function selectRealTZ()    {
    // Select standard od daylight time in the form drop-down menu for the exact date

	for (var i = 0; i < document.query.TZ.options.length; i++) 
	{   
		if (document.query.TZ.options[i].selected)      
			var oldTZ =  document.query.TZ.options[i].value;
	}
	
	var newTZ = oldTZ;

	
	//jour
	for (var i = 0; i < document.query.day.options.length; i++) 
	{   
		if (document.query.day.options[i].selected)      
			var jour =  document.query.day.options[i].value;
	}

	//mois 
	for (var i = 0; i < document.query.month.options.length; i++) 
	{   
		if (document.query.month.options[i].selected)      
			var mois =  document.query.month.options[i].value;
	}

	//an
	for (var i = 0; i < document.query.year.options.length; i++) 
	{   
		if (document.query.year.options[i].selected)      
			var an =  document.query.year.options[i].value;
	}

	if (oldTZ == "UTC")
		return false;

	/* Si ancienne condition avant 2007 */
	if (an < 2007)
	{
		/* Si heure normale */  
		if (mois == 1 || mois == 2 || mois == 3 || mois == 11 || mois == 12)
	    {
			newTZ = oldTZ.charAt(0) + "S" + oldTZ.charAt(2);
		   
			with (document.query.TZ)    {
	        for (var i = 0; i < options.length; i++)    {
	            if (options[i].value == newTZ)    {
	                selectedIndex = i;
	                }
	            }
			}	  
	    }
		else
	    {
			/* Si heure avancee */  
			if (mois == 5 || mois == 6 || mois == 7 || mois == 8 || mois == 9)
	        {
				newTZ = oldTZ.charAt(0) + "D" + oldTZ.charAt(2);
		   
				with (document.query.TZ)    {
					for (var i = 0; i < options.length; i++)    {
						if (options[i].value == newTZ)    {
			                selectedIndex = i;
				        }
					}
				}	  
	        }
			else
	        {
				/* Le mois ou on change en heure normal */ 
				if (mois == 4)
				{
					// premier avril 2000 = samedi
					var dif_an = (an - 2000) / 4;
					var num_jour = 5 * (Math.floor(dif_an));
					num_jour = ((dif_an - Math.floor(dif_an)) * 4) + num_jour;
					//date du premier dimanche d avril
					num_jour = num_jour - (Math.floor(num_jour / 7) * 7);

					if (num_jour != 1)
						num_jour = 8 - num_jour + 1;

					/* Si on est dans la premiere semaine (Modif 04042002) */
					if (jour >= num_jour)
					{
						newTZ = oldTZ.charAt(0) + "D" + oldTZ.charAt(2);
		   
						with (document.query.TZ)    {
					        for (var i = 0; i < options.length; i++)    {
								if (options[i].value == newTZ)    {
					                selectedIndex = i;
							    }
						    }
						}	  
				    }
					else
					{
						newTZ = oldTZ.charAt(0) + "S" + oldTZ.charAt(2);
		   
						with (document.query.TZ)    {
							for (var i = 0; i < options.length; i++)    {
					            if (options[i].value == newTZ)    {
								    selectedIndex = i;
							    }
				            }
						}	  
				    }
				}
				else
				{
					/* Pour le changement en octobre */
					// dernier dimanche octobre 1992 = dimanche
					var dif_an = (an - 1992) / 4;
					var num_jour = 5 * (Math.floor(dif_an));
					num_jour = ((dif_an - Math.floor(dif_an)) * 4) + num_jour;

					//alert(num_jour);
					//date du dernier dimanche d octobre
					num_jour = num_jour - (Math.floor(num_jour / 7) * 7);
					
					if (num_jour != 0)
						num_jour = 7 - num_jour + 25;
					else
						num_jour = 25;
		
					if (jour < num_jour)
					{
						newTZ = oldTZ.charAt(0) + "D" + oldTZ.charAt(2);
		   
						with (document.query.TZ)    {
							for (var i = 0; i < options.length; i++)    {
					            if (options[i].value == newTZ)    {
								    selectedIndex = i;
							    }
				            }
						}	 
					}
					else
					{
						newTZ = oldTZ.charAt(0) + "S" + oldTZ.charAt(2);
		   
						with (document.query.TZ)    {
							for (var i = 0; i < options.length; i++)    {
					            if (options[i].value == newTZ)    {
								    selectedIndex = i;
							    }
				            }
						}	 
					}
				}
			}
		}
	}
	else
	{
	/* On est passé 2007, on gère le nouveau changement d'heure */
	/* Si heure normale */  
		if (mois == 1 || mois == 2 || mois == 12)
	    {
			newTZ = oldTZ.charAt(0) + "S" + oldTZ.charAt(2);
		   
			with (document.query.TZ)    {
	        for (var i = 0; i < options.length; i++)    {
	            if (options[i].value == newTZ)    {
	                selectedIndex = i;
	                }
	            }
			}	  
	    }
		else
	    {
			/* Si heure avancee */  
			if (mois == 4 || mois == 5 || mois == 6 || mois == 7 || mois == 8 || mois == 9 || mois ==10)
	        {
				newTZ = oldTZ.charAt(0) + "D" + oldTZ.charAt(2);
		   
				with (document.query.TZ)    {
					for (var i = 0; i < options.length; i++)    {
						if (options[i].value == newTZ)    {
			                selectedIndex = i;
				        }
					}
				}	  
	        }
			else
	        {
				/* Le mois ou on change en heure normal - Ajouter 2011 à 2015    IBeaulieu 19 oct 2010*/ 
				if (mois == 3)
				{					
					if ((an == 2007 && jour >= 11) || (an == 2008 && jour >= 9) || (an == 2009 && jour >= 8) 
					|| (an == 2010 && jour >= 14) || (an == 2011 && jour >= 13) || (an == 2012 && jour >= 11) 
					|| (an == 2013 && jour >= 10) || (an == 2014 && jour >= 9) || (an == 2015 && jour >= 8))
					{
						newTZ = oldTZ.charAt(0) + "D" + oldTZ.charAt(2);
		   
						with (document.query.TZ)    {
					        for (var i = 0; i < options.length; i++)    {
								if (options[i].value == newTZ)    {
					                selectedIndex = i;
							    }
						    }
						}	  
				    }
					else
					{
						newTZ = oldTZ.charAt(0) + "S" + oldTZ.charAt(2);
		   
						with (document.query.TZ)    {
							for (var i = 0; i < options.length; i++)    {
					            if (options[i].value == newTZ)    {
								    selectedIndex = i;
							    }
				            }
						}	  
				    }
				}
				else
				{
					/* Pour le changement en novembre  - Ajouter 2011 à 2015    IBeaulieu 19 oct 2010*/
							
					if ((an == 2007 && jour < 4) || (an == 2008 && jour < 2) || (an == 2009 && jour < 1) 
					|| (an == 2010 && jour < 7) || (an == 2011 && jour < 6) || (an == 2012 && jour < 4)
					 || (an == 2013 && jour < 3) || (an == 2014 && jour < 2) || (an == 2015 && jour < 1))
					{
						newTZ = oldTZ.charAt(0) + "D" + oldTZ.charAt(2);
		   
						with (document.query.TZ)    {
							for (var i = 0; i < options.length; i++)    {
					            if (options[i].value == newTZ)    {
								    selectedIndex = i;
							    }
				            }
						}	 
					}
					else
					{
						newTZ = oldTZ.charAt(0) + "S" + oldTZ.charAt(2);
		   
						with (document.query.TZ)    {
							for (var i = 0; i < options.length; i++)    {
					            if (options[i].value == newTZ)    {
								    selectedIndex = i;
							    }
				            }
						}	 
					}
				}
			}
		}	
	}		
}

function getTZLongName (tz, language)    {
    // Return the long name of the given time zone in the 
    // specified language.

    var idx = tz + "_" + language;
    return TZLongNames[idx];
    }

    // Animation data.
    // The images make up an animated wave while the prediction
    // is computed.

	

function stationList (doc)    {
    // Build a drop down list for all stations of region 'num' inside
    // document 'doc'
    // alert("entering stationlist");

        // The 'onClick()'method works only under IE.
        // Netscape will ignore it. Another technique has to be
        // used in this case (see function matchStationTZ() ).

	doc.write ('\n<select name="stnnum" onChange="document.changeStation.submit()">\n');

	for (var n = 0; n < stationArr.length; n++)    {
        var tok = stationArr [n] . split ('|');
		doc.write ('<option value=' + tok[0] + '>' + tok[1] + '</option>\n');
	}      
    doc.write ('</select>\n');
    }

function selectTZ(tz)    {
    // Select given timezone in the form drop-down menu.

    with (document.query.TZ)    {
        for (var i = 0; i < options.length; i++)    {
            if (options[i].value == tz)    {
                selectedIndex = i;
                return false;
                }
            }
	}
    return false;
    }

function tzListOption (doc, value, selected, tz, language)    {

    doc.write ('<option value="' + value + '" ' + selected + '>' + 
               getTZLongName (tz, language) + '</option>\n');
    }

function tzList (doc, tz, language)    {
    // Build a drop down list of time zone names inside document 'doc'.
    // Select entry for time zone 'tz'.
    // Show names in the given 'language' (french or english).


   
    doc.write ('\n<select name="TZ" size="1">\n');

    for (var n = 0; n < TZNames . length; n++)    {
        var s, name;
        name = TZNames [n];
        if (tz == name)
            s = "selected";
        else
            s = "";
        doc.write ('<option value="' + name + '" ' + s + '>' + 
                   getTZLongName (name, language) + '</option>\n');
        }

    doc.write ('</select>\n');
    }

function selectStationTZ (stn)    {
    // Select the default timezone for the given station.

    for (var n = 0; n < stationArr.length; n++)    {
        var tok = stationArr [n] . split ('|');
        if (tok [0] == stn)    {
            selectTZ (tok [2]);
            return false;
            }
        }
    return false;
    }

function selectSelectedStationTZ ()    {
    // Set the time zone to the default timezone for the selected station in
    // the station dropdown list.

    with (document.changeStation.stnnum)    {
        var stn = options[options.selectedIndex].value;
        }
    selectStationTZ (stn);
    return false;
    }

function matchStationTZ ()    {
    // Make sure that the selected time zone reflects the default time zone for the
    // selected station following a manual selection in the station
    // list. This is done here because Netscape does not allow 
    // an 'onClick()' method on <select> tags.
    // The idea is to constantly monitor the selected station, watching for a 
    // change. If a change is detected, see if it is a consequence of a
    // click on the region map. If no click occured, then the change necessarily
    // results from a manual selection in the station list.

        // IE v4 and above has the right onClick() method.
    if (browser.ie4up)    {
        stationListStatus . setTimeoutOn = 0;
        return;
        }
        // Do it the hard way on other browsers
    with (document.query.station)    {
            // The 'onClick()' method of the <area> tag already
            // updated the station and time zone lists.
        if (stationListStatus . mapClicked)
            stationListStatus . mapClicked = 0;
        else    {
            if (stationListStatus . currentSelected != options . selectedIndex)    {
                    // User manually selected a station in the list.
                    // Update the time zone selection.
                var stn = options[options.selectedIndex].value;
                selectStationTZ (stn);
                //selectSelectedStationTZ ();
                stationListStatus . currentSelected = options . selectedIndex;
                }
            }
        }
        // Reschedule the call in 1 second.
    stationListStatus . setTimeoutId = setTimeout ("matchStationTZ()", 1000);
    stationListStatus . setTimeoutOn = 1;
    }

function cancelSetTimeout ()    {
    // Cancel the automatic procedures attached to the region window.
    // This function is called before a new region window is loaded
    // to prevent the execution of the procedures while the windw is in an inconsistent state.

    if (stationListStatus . setTimeoutOn)    {
        clearTimeout (stationListStatus . setTimeoutId);
        stationListStatus . setTimeoutOn = 0;
        }
    }

function selectStation(stn)    {
    // Select given station in the form drop-down menu.
	with (document.changeStation.stnnum)    {
        for (var i = 0; i < options.length; i++)    {
            if (stn == 'first' || options[i].value == stn)    {
                selectedIndex = i;
				
				//document.query.submit();
				
				return false;
                }
            }
	}
	return false;
    }

function selectStationThroughMap (stn)    {
    // Select station `stn' and note that the selection occured
    // indirectly through the region map.

    selectStation (stn, 1);
    stationListStatus . mapClicked = 1; 
    return false;
    }



// Error handler. Taken from "Javascript: The Definitive Guide", by
// David Flanagan, 3rd edition.

// A variable we use to ensure that each error window we create is unique.
var error_count = 0;

// Set this variable to your email address.
var email = "STSHC@dfo-mpo.gc.ca";

// Define the error handler. It generates an HTML form so
// the user can report the error to the author.
function report_error(msg, url, line)  {

   var w = window.open("",                    // URL (none specified)
                       "error"+error_count++, // Name (force it to be unique)
                       "resizable,status,width=625,height=400"); // Features
   var d = w.document;    // We use this variable to save typing!

   // Output an HTML document, including a form, into the new window.
   d.write('<DIV>');
   d.write('<FONT SIZE=7 FACE="helvetica"><B>');
   d.write('OOPS.... A JavaScript Error Has Occurred!');
   d.write('</B></FONT><BR><HR SIZE=4 WIDTH="80%">');
   d.write('<FORM ACTION="mailto:' + email + '" METHOD=post');
   d.write(' ENCTYPE="text/plain">');
   d.write('<FONT SIZE=3>');
   d.write('<I>Click the "Report Error" button to send a bug report.</I><BR>');
   d.write('<INPUT TYPE="submit" VALUE="Report Error">&nbsp;&nbsp;');
   d.write('<INPUT TYPE="button" VALUE="Dismiss" onClick="self.close()">');
   d.write('</DIV><DIV>');
   d.write('<BR>Your e-mail <I>(optional)</I>: ');
   d.write('<INPUT SIZE=42 NAME="name" VALUE="">');
   d.write('<BR>Error Message: ');
   d.write('<INPUT SIZE=42 NAME="message" VALUE="' + msg + '">');
   d.write('<BR>Document: <INPUT SIZE=42 NAME="url" VALUE="' + url + '">');
   d.write('<BR>Line Number: <INPUT SIZE=42 NAME="line" VALUE="' + line +'">');
   d.write('<BR>User Agent: ');
   d.write('<INPUT SIZE=42 NAME="useragent" VALUE="'+ browser.userAgent + '">');
   d.write('<BR>Browser version: ');
   d.write('<INPUT SIZE=42 NAME="version" VALUE="'+ browser.minor + '">');
   d.write('</DIV></FONT>');
   d.write('</FORM>');
   // Remember to close the document when we're done.
   d.close();

   // Return true from this error handler, so that JavaScript does not
   // display its own error dialog.
   return true;
   }


