/* 04.04.28 print ready
   04.04.29 pop single schedule
   04.05.11 print ready, redo bug fix
   06.10.03 textual content changes
   08.05.08 allow embedded schedule tables to work in all browsers. add date in querystring to choose a timetable.
   08.08.13 RAD: add "Schedule Preloading" animation
*/
var isNetscape = (navigator.appName == 'Netscape');
var isMac = false;
var nuagent = navigator.userAgent.toLowerCase();
if (nuagent.indexOf("mac")>=0) isMac = true;

var selectedScheduleIndex = 0; // the currently selected schedule (NOTE: different from "selectIndex")

var UpComingSchedule = document.getElementById("UpComingSchedule"); // <SELECT ID="UpComingSchedule">
var ferriesTimetableElements = new Array();

var cookieExpirationDays = 1;

function getCookie(key) {
	var ck = document.cookie;
    var i = ck.indexOf(key + "=");
    if (i<0) return '';
    i = ck.indexOf("=", i) + 1;
    var iend = ck.indexOf(";", i);
    if (iend<0) iend = ck.length;
    //alert(ck.toString());
    return unescape(ck.substring(i, iend));
  }

function addScheduleLink() {
        //
	// hide "Schedule Preloading" animation
	el = document.getElementById("preloadingDiv");
	if (el) {
		el.style.display = "none";
	}
	//
	// initialize timetable array
     initTimetableElementsArray(); 
	/*
	if (isMac || isNetscape) 
        {
         buildMozillaLinks(schedules);
         return;
        }
	*/
	var i, ptr1, ptr2;
	var tblcnt = 0;
	var href = new String("");
	var strlink = "";
    //var debugStr = "Inserting " + scheduleTitle +"\n";
	//
	// add all timetables as Select options
	for (i=schedules.length-2; i>=0; i--) {
           //debugStr += scheduleTitle + " : " + schedules[i].title + "<BR>";
		if (schedules[i].title==scheduleTitle) { // this schedule applies to our current route. Add it.
			UpComingSchedule.options[UpComingSchedule.options.length] = new Option(schedules[i].dateFrom + " - " + schedules[i].dateTo, i );
			tblcnt++;
			//debugStr += i + ": "+ schedules[i].dateFrom + " - " + schedules[i].dateTo + "\n";
		}
	}

	//alert(debugStr);

	if (tblcnt>0) {	// show first table, or table-N (N saved as cookie)
		//
		// get date from query string (?DATE=mm/dd/yy) then find date in schedule if possible
		// if no date, or not found in schedule, try cookie. Otherwise, use first schedule.
		var useCookie = true;
		var selectIndex = 1; // default, use 1st schedule in list
		//
		// check if sailing date specified in query string
		var sailingDate = getQueryDate(); // get date from query string, if present
		//alert("sailingDate = "+sailingDate);
		if (sailingDate != null) { // we have a sailingDate, try to find it in schedule
			useCookie = false;
			selectIndex = getSelectIndexByDate(scheduleTitle, sailingDate);
			if (selectIndex == -1) {
				selectIndex = 1; // use 1st schedule
			}
			//alert("checking selectIndex="+selectIndex);
		}
		//
		if (useCookie == true) {
			var selectIndex = 1;
			var cookieBcf = "";
			var crumbs;
			cookieBcf = getCookie("selectedSchedule");
			if (cookieBcf.length>0) {
				crumbs = cookieBcf.split("ZZZ");
				if (crumbs[0]==scheduleTitle) {
					selectIndex = new Number( crumbs[1] );
					if ((selectIndex<=0) || (selectIndex>schedules.length-2)) {
						selectIndex = 1;
					}
				}
			}
		}
		//
		// show selected schedule
		jumpScheduleByIndex(selectIndex);
	}
	//
	// workaround to make named anchors from print pages work when redirected to schedule pages
	// this is not normal behviour, but is desired by BCF. And the customer is always right.
	if (document.URL.indexOf("#") > 0) { // there is a named anchor in the request
		document.location = document.location; // make sure named anchor link is followed.
	}		
}

//
// Jump to current schedule defined by <select id="UpComingSchedule" >
function jumpSchedule() {
	if (UpComingSchedule.selectedIndex<=0) return;
	jumpScheduleByIndex(UpComingSchedule.selectedIndex);
}

//
// shows a specific schedule based on the index of the <select> combo box
// NOTE: There are 2 "indexes": the index from the combobox and the index of the array of timetables
function jumpScheduleByIndex(index) {
	//
	// make the selected schedule's timetable block visible
	i = UpComingSchedule.options[index].value;
	selectedScheduleIndex = i; // Set this global variable represents currently selected schedule
	showTimetableById(i);
	//
    // ED - addition to set the date
	getSchedDate(schedules,i); // gets the correct date and displays it in "from ... to ...." format
	//
	// remember the selected schedule (in cookies)
	saveScheduleIndexInCookie(scheduleTitle, index);
}
//
// save current selection in cookie 
function saveScheduleIndexInCookie(scheduleTitle, index) {
	var now = new Date( new Date().getYear(), new Date().getMonth(), new Date().getDate());
	var todayonly = new Date( now.getYear(), now.getMonth(), now.getDate()+1 );
	//document.cookie = "selectedSchedule="+escape(scheduleTitle)+"ZZZ"+index+"; path=/; expires="+todayonly.toGMTString();
    //document.cookie = "selectedScheduleIndex=" + index +";path=/; expires="+todayonly.toGMTString();
	createCookie("selectedSchedule", escape(scheduleTitle)+"ZZZ"+index, cookieExpirationDays);
    createCookie("selectedScheduleIndex", index, cookieExpirationDays);
    createCookie(window.location+",selectedScheduleIndex", index, cookieExpirationDays);
}


// ADDITION TO GET THE CORRECT DATE FOR PRINT VERSION
function getSchedDate(schedules,schIndx) {

 strRoute = schedules[schIndx].title;

 if (UpComingSchedule.options.length > 2) {
	strSchedDate = "Schedule in Effect:<br>" + schedules[schIndx].dateFrom + " to " + schedules[schIndx].dateTo;
 } else {
	 if (getException(schedules[schIndx].title) > 0) {
		strSchedDate = "Schedule in Effect:<br>" + schedules[schIndx].dateFrom + " to " + schedules[schIndx].dateTo;
	} else {
		strSchedDate = "Schedule in Effect: Year Round";
	}
 }
 displaySchedDate(strSchedDate);
}

//GET ANY EXCEPTIONS
function getException(strSchedule)
{
//jsDEBUG.innerHTML = "CURRENT SCHEDULE: " + strSchedule;

if (strSchedule == "Inside Passage - Day Cruise (Prince Rupert - Port Hardy)")
{return 1;}

if (strSchedule == "Queen Charlotte Islands Fall/Winter/Spring")
{return 1;}

if (strSchedule == "Positioning Cruise (Port Hardy - Tsawwassen)")
{return 1;}

if (strSchedule == "Queen Charlotte Islands Summer")
{return 1;}

if (strSchedule == "Discovery Coast Passage")
{return 1;}

if (strSchedule == "Sechelt - Powell River")
{return 1;}

if (strSchedule == "Langdale to Gambier Island & Keats Island")
{return 1;}

if (strSchedule == "Inside Passage Fall/Winter/Spring")
{return 1;}

if (strSchedule == "Bowen Island - Vancouver")
{return 1;}

if (strSchedule == "Salt Spring Island (Vesuvius Bay) - Crofton")
{return 1;}

if (strSchedule == "Vancouver - Nanaimo")
{return 1;}

if (strSchedule == "West Van - Nanaimo")
{return 1;}

if (strSchedule == "West Van - Sunshine Coast")
{return 1;}

if (strSchedule == "Galiano Island Departures")
{return 1;}

if (strSchedule == "Mayne Island Departures")
{return 1;}

if (strSchedule == "Pender Island Departures")
{return 1;}

if (strSchedule == "Salt Spring Island Departures")
{return 1;}

if (strSchedule == "Saturna Island Departures")
{return 1;}

if (strSchedule == "Victoria Departures")
{return 1;}

if (strSchedule == "Vancouver Departures")
{return 1;}

if (strSchedule == "Day Trip from Swartz Bay")
{return 1;}

if (strSchedule == "Salt Spring Island - Victoria")
{return 1;}

if (strSchedule == "Comox - Powell River")
{return 1;}

// if (strSchedule == "Vancouver Island - Denman Island")
// {return 1;}

// if (strSchedule == "Nanaimo Harbour - Gabriola Island")
// {return 1;}

if (strSchedule == "Alliford Bay - Skidegate")
{return 1;}

return 0;
}

// for MAC or NS, output the links now
//ED'S REWRITE
function buildMozillaLinks(schedules) {
	//alert("buildMozillaLinks()");
	var i, ptr1, ptr2;
	var href = new String("");
	var strlink = "";

	for (i=schedules.length-2; i>=0; i--) {
		if (schedules[i].title==scheduleTitle) {
			href = schedules[i].url;
			ptr1 = href.indexOf("href=") + 5;
			ptr2 = href.indexOf(">",ptr1);
			href = href.substring(ptr1,ptr2);
			if (strlink.length==0) {
				strlink = "<font size=2><b>" + schedules[i].url.replace('marker',schedules[i].dateFrom + " - " + 
					schedules[i].dateTo).replace('<a href','<a target=bcferry href') + "</b></font><P>";
			} else {
				strlink = strlink + schedules[i].url.replace('marker',schedules[i].dateFrom + " - " + 
					schedules[i].dateTo).replace('<a href','<a target=bcferry href') + "<P>";
			}
		}
	}

	//setting .cssText not working in Mac-NS
	var selbox = document.getElementById("scheduleList");
	selbox.style.display = "none";
			
	strSchedDate = "<div align='center'><strong><font color='#333399' face='Arial, Verdana, Sans-Serif'><font size='3'>Schedules:</font><br><br></font></strong><table border='2' cellpadding='5' cellspacing='0' bordercolorlight='#E0EAEE' bordercolordark='#E0EAEE'><tr><td bgcolor='#E0EAEE'><strong><font color='#333399' face='Arial, Verdana, Sans-Serif' size='2'>** Click on a date below to view the Schedule **</font></strong></td></tr><tr><td><div align='center'><p>" + strlink + "</div><p align='center'><br></p></td></tr></table></div>";	
		
	document.getElementById("mozillaLinks").innerHTML = strSchedDate;
}

//
// Used by "copy and paste" link to pop up the current schedule in a new window
function popSchedule() {
	var url = schedules[selectedScheduleIndex].url;
	var i = url.indexOf( "href=" );
	var j = url.indexOf( ">" );
	//alert("popSchedule("+selectedScheduleIndex+") "+schedules[selectedScheduleIndex].url);
     
	 /*
	if (isNetscape) { 
		mStrDsiplay = "Schedule: ";
		for (i=schedules.length-2; i>=0; i--)  {
		   if (schedules[i].title==scheduleTitle)  { 
			  x = schedules[i].url.indexOf( "href=" );
			  y = schedules[i].url.indexOf( ">" );
			  mStrDsiplay = schedules[i].url.substring(x+5,y); 
		   }
		}
	    alert(mStrDsiplay);
		window.open( mStrDsiplay, "bcf" );
	}
	*/

	if ((i>0) && (j>0)) {
	 	var newWindow = window.open(url.substring(i+5,j), "bcf");
		newWindow.focus();
	}
}

/*** NEW COOKIE FUNCTIONS ****/
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

//
// each timetable date range is stored in a span in the HTML. Each span uses id="ferries"
// extract all SPANs with ID = "ferries" and save into array
// these elements hold the individual timetables for each date range and route
// by toggling the visibility of these elements, we can show different date ranges on demand
function initTimetableElementsArray() {
	// get all spans
	var allSpans = document.body.getElementsByTagName("SPAN");
	// find spans with ID = "ferries"
	for (var i=0; i < allSpans.length; i++) {
		if (allSpans[i].id == "ferries") {
			ferriesTimetableElements[ferriesTimetableElements.length] = allSpans[i]; // save this element
		}
	}
}
//
// shows a schedule timetable block by array Id
function showTimetableById(id) {
	var i = 0;
	for (i=0; i<ferriesTimetableElements.length; i++) { 
		if (i == id) {
			ferriesTimetableElements[i].style.display = "block";
		} else {
			ferriesTimetableElements[i].style.display = "none";
		}
	}
}
//
// displays text in the "schedDate" element
function displaySchedDate(textString) {
	 document.getElementById("schedDate").innerHTML = textString;
}
//
// find the correct select index for a given date in the current schedule
// and return the index. Otherwise, return "-1" (not found)
// Note: date is expected in internal date format.
function getSelectIndexByDate(routeTitle, date) {
	//alert("routeTitle="+routeTitle+"\ndate = "+date);
	if (routeTitle == "" || date == null) return -1;
	//
	// find schedule index in schedule array for our date
	var schedIndex = -1;
	for (var i=schedules.length-2; i>=0; i--) {
		if (schedules[i].title==routeTitle) {
			if (date >= Date.parse(schedules[i].dateFrom) && date <= Date.parse(schedules[i].dateTo) ) {
				schedIndex = i; // date found in range
				break;
			}
		}
	}
	//
	// now find the <select> index with this schedule index
	if (schedIndex >= 0) {
		for (var i=1; i <= UpComingSchedule.options.length-1; i++) {
				if (schedIndex == UpComingSchedule.options[i].value) { // we've found it
				return i; // done. This is the selectIndex we want.
			}
		}
	}
	return -1; // not found
}
//
// returns the date if speficied in the query string
// assumes date is in internal (milliseconds) format
function getQueryDate() {
	var queryDate = getQueryStringVariable("date");
	if (queryDate == null) return null; // no date
	//
	//var queryDate = Date.parse(queryDate);
	if (isNaN(queryDate)) {
		return null; // not valid date
	}
	return queryDate;
}
//
// parses the query string for a given key and returns the value
function getQueryStringVariable(key) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == key) {
			return pair[1];
		}
	}
	return null;
}



