/**************************************************
Name: Calendar.js
Purpose: Contains js for Eynsford What's On page
Author: Delphine Bantock
Date: 20/05/2007
Version: 2.0
Modifications: resolved file download issue with ie
***************************************************/

/**************************************************
//Loads the main body of the page
***************************************************/
//This contains the xslt logic to transform the source xml file into HTML:
var stylesheet="CalendarView.xsl";

function loadContent(){
  var dt = new Date();
  var dd = dt.getDate();
  var MM = (dt.getMonth() + 1);
  var YY = dt.getUTCFullYear();
  var today = dd + "/" + MM + "/" + YY;
  //alert("date = " + today);
  var XMLsource;
  switch(MM)
  {
  case 1: 
    XMLsource = "January-" + YY + ".xml";
    break;
  case 2: 
    XMLsource = "February-" + YY + ".xml";
    break;
  case 3: 
    XMLsource = "March-" + YY + ".xml";
    break;
  case 4: 
    XMLsource = "April-" + YY + ".xml";
    break;
  case 5: 
    XMLsource = "May-" + YY + ".xml";
    break;
  case 6: 
    XMLsource = "June-" + YY + ".xml";
    break;
  case 7: 
    XMLsource = "July-" + YY + ".xml";
    break;
  case 8: 
    XMLsource = "August-" + YY + ".xml";
    break;
  case 9: 
    XMLsource = "September-" + YY + ".xml";
    break;
  case 10: 
    XMLsource = "October-" + YY + ".xml";
    break;
  case 11: 
    XMLsource = "November-" + YY + ".xml";
    break;
  case 12: 
    XMLsource = "December-" + YY + ".xml";
    break;
  }
  //alert("XML source file = " + XMLsource);
  loadCalendar(XMLsource,MM,YY); 
}

/**************************************************
Initially loads the calendar using the current month
**************************************************/
function loadCalendar(XMLsource,MM,YY) {
//alert("XMLSource " + XMLsource);
if(window.ActiveXObject){
	document.all.bodyContent.innerHTML = "<h3 class=\"calloading\">Loading What's on content: please wait...</h3>";
} else{
	document.getElementById("bodyContent").innerHTML = "<h3 class=\"calloading\">Loading What's on content: please wait...</h3>";
}
	if (transformCalXML(XMLsource)){
	 	buildQuickList(MM,YY);
	}
}

/************************************************
Triggered by moving around in the calendar
************************************************/
function reloadCalendar(newMonthToDisplay) {
//alert("newMonthToDisplay = " + newMonthToDisplay);
	var MM = parseInt(leftString(newMonthToDisplay, "-"));
	var YY = parseInt(rightString(newMonthToDisplay,"-"));
	var XMLsource = translateMth(MM)+"-"+YY+".xml";
	//alert("XMLsource = " + XMLsource);
	if (transformCalXML(XMLsource)){
		buildQuickList(MM,YY);	
	}		
}


/**************************************************
Builds a select list for 12 months forward looking..
This is not called if there is a problem loading the 
selected source
**************************************************/
function buildQuickList(MM,YY){
//alert("in buildQuickList with MM = " + MM + " - YY = " + YY);
foo = false;
var dynamicHTML;
var dynamicHTMLstart = "<select name='months' onchange='reloadCalendar(this.value)'>";
var dynamicBody = dynamicHTMLBody(MM, YY);
var dynamicHTMLfinish = "</select>";

//put it all together....
dynamicHTML=dynamicHTMLstart+dynamicBody+dynamicHTMLfinish;
//alert(dynamicHTML);
//paste it into the page.......change id!!
if (window.ActiveXObject){
	document.all.month_Picker.innerHTML=dynamicHTML;
} else {
	document.getElementById("month_Picker").innerHTML=dynamicHTML;
}

}

/***********************************************************************
Dynamically builds the appropriate list of options for the Calendar drop-down list
List will always consist of 12 options which are forwards looking for the year ahead
***********************************************************************/
//used to indicate when the YY parm should be incremented - initialised to false to start with...
var foo = false;
function dynamicHTMLBody(MM, YY){
//1st value should always be the current month and shown as 'selected'...
var dynamicHTML;
dynamicHTML = buildOption(MM, YY, true, true);
// call for all other 11 months....
MM = nxtMonth(MM);
var nMth = nxtMonth(MM);
//alert("nMth = " + nMth);
var count = 11;
for (i=0;i<count;i++){
	iYear(MM);
	//alert("foo = " + foo);
	if (foo){ // need to increase the yr by 1 as ticked over into a new year!! 
		dynamicHTML = dynamicHTML + buildOption(MM, YY, false, false);
		//alert(dynamicHTML);
	} else { 
		dynamicHTML = dynamicHTML + buildOption(MM, YY, false, true);
		//alert(dynamicHTML);
	}	
	MM = nMth;
	nMth = nxtMonth(nMth);	
	//alert("MM = " + MM + " - nMth = " + nMth);
}

//alert(dynamicHTML);
return dynamicHTML;

}

/******************************************
Indicates when year needs to be incremented
*******************************************/
function iYear(MM){
	if (MM == 1){
		foo = true;
	}
}

/*********************
Increments the year
*********************/
function translateYr(YY){
	return (YY+1);
}

/*********************
Increments the month
**********************/
function nxtMonth(MM){
var nxtMth;
	if (MM < 12){
		nxtMth = (MM + 1);
	} else {
		nxtMth = 1;
	}
return nxtMth;
}

/**********************************
Builds the HMTML for select option
**********************************/
function buildOption(MM, YY, selected, currYr){
var thisOption;
	// used to ensure that the first option in the list is the current month and always selected..
	if (selected){
		thisOption = "<option value='"+MM+"-"+YY+"' selected='selected' >"+translateMth(MM)+" "+YY+"</option>";
		//alert(thisOption);
		return thisOption;
	}
	
	// used to increase the yr if appropriate!
	if (currYr){
		 thisOption = "<option value='"+MM+"-"+YY+"' >"+translateMth(MM)+" "+ YY +"</option>";
	//	 alert(thisOption);
		 return thisOption;
	} else {
		thisOption = "<option value='"+MM+"-"+translateYr(YY)+"' >"+translateMth(MM)+" "+translateYr(YY) +"</option>";
		 //alert(thisOption);
		return thisOption;
	}

}

/****************************************
Translates numeric month to textual month
*****************************************/
function translateMth(MM){
var m;
switch(MM)
  {
  case 1: 
    m = "January";
    break;
  case 2: 
    m = "February";
    break;
  case 3: 
    m = "March";
    break;
  case 4: 
    m = "April";
    break;
  case 5: 
    m = "May";
    break;
  case 6: 
    m = "June";
    break;
  case 7: 
    m = "July";
    break;
  case 8: 
    m = "August";
    break;
  case 9: 
    m = "September";
    break;
  case 10: 
    m = "October";
    break;
  case 11: 
    m = "November";
    break;
  case 12: 
    m = "December";
    break;
  }
  //alert("m = " + m);
  return m;
}

/************************************************
Used by both loadCalendar and reloadCalender to setup
xsl and xml objects ready for transformation
************************************************/
function transformCalXML(xmlSrc) {
	loadXMLData(xmlSrc);
	//if data was loaded successfully then..
	if (xmldocloaded){
		loadXSLData();
		//if both sources loaded OK then do the magic!
		if(xsldocloaded){
			doTransformation("bodyContent");
			return true;
		}
	
	} else {
		// redirects user back to page that can load!!
		//window.location.reload();	
	}	
}

/************************************************
Loads default (ie current month) or specified
xml data source file.
************************************************/
var xmldocloaded = false;
var xsldocloaded = false;
var xmldoc;
var xsldoc;
function loadXMLData(xmlSrc){
//alert("in loadXMLData with = " + xmlSrc);
var file = "../xml/"+xmlSrc;
//alert("file = " + file);

if(window.XSLTProcessor){
	alert("loading data for mozilla");
	xmldoc = document.implementation.createDocument("", "", null);
	xmldoc.load(file);
	xmldoc.onload=onXMLLoad();
	alert("xml data = " + xmldoc.xml);
	
} else if (window.ActiveXObject){
	//alert("loading data for ie");
	xmldoc = new ActiveXObject("Microsoft.XMLDOM");
	xmldoc.async=false;
	xmldoc.load(file);	
	//try and catch error for not such file or invalid xml formed file
	if (xmldoc.parseError.errorCode != 0) {
		showError("bodyContent",xmldoc);
	}
	//alert("xml data = " + xmldoc.xml);
	onXMLLoad();	
} else{
	alert("ATTENTION: your browser does not support XSLT transformations. \n\n This is required for using the part of the site. \n\n Please look into upgrading your web browser to a more up-to-date version.");	
}
}

/************************************************
Set variable indicating xml source fully loaded
************************************************/
function onXMLLoad(){
		xmldocloaded = true;
}

/************************************************
Loads default stylesheet
************************************************/
function loadXSLData(){
//alert("in loadXSLData");

var file = "../xml/"+stylesheet;
//alert("file = " + file);

if(window.XSLTProcessor){

	alert("loading xsl for mozilla");
	xsldoc = document.implementation.createDocument("", "", null);
	xsldoc.load(file);
	xsldoc.onload=onXSLLoad();
	alert("xsl data = " + xsldoc);	
	
} else if (window.ActiveXObject){
	//alert("xsl data loading for ie");
	xsldoc = new ActiveXObject("Microsoft.XMLDOM");
	xsldoc.async=false;
	xsldoc.load(file);
	
	//catch any errors when loading stylesheet here
	if (xsldoc.parseError.errorCode != 0) {
		showError("bodyContent",xsldoc);
	}
	//alert("xsl data = " + xsldoc.xml);
	onXSLLoad();	
}
}

/***********************************************************
Set variable indicating xsl source (stylesheet) fully loaded
************************************************************/
function onXSLLoad(){
	xsldocloaded = true;
}

/*******************************************************************
Performs xslt transformation of xml into HTML if both sources are 
successfully loaded and paints this into the page
*******************************************************************/
function doTransformation(contentID){
//alert("in doTansformation");
	if ((xmldocloaded) && (xsldocloaded)){
		if(window.XSLTProcessor){

			var xsltProcessor = new XSLTProcessor();
			xsltProcessor.importStylesheet(xsldoc);
			var results = xsltProcessor.transformToFragment(xmldoc, document);
				alert("results = " + results.text);
				var htmlObj = document.getElementById("bodyContent");
				htmlObj.innerHTML = results;
				self.refresh;
				
		} else if (window.ActiveXObject){
			//alert('ready to transform');
			if (getReadyState(xmldoc)) {
				results = xmldoc.transformNode(xsldoc);
				//alert(results.xml);
				var htmlObj = eval("document.all."+contentID);
				htmlObj.innerHTML = results;
				}
			self.refresh;
			
		}	
	}
}

/************************************************
##### OLD Completes transformation of xml into HTML and paints
this into the page
************************************************/
function doTransform(xmlDoc, xslDoc, contentID) {
//alert('in doTransform');
if (getReadyState(xmlDoc)) {
	results = xmlDoc.transformNode(xslDoc);
	//alert(results);
	var htmlObj = eval("document.all."+contentID);
	htmlObj.innerHTML = results;
}
self.refresh;
}  

/************************************************
Checks to make sure xml source is fully loaded
before attempting transformation
************************************************/
function getReadyState(xmlDoc) {
	if (xmlDoc.readyState == 4) {
	//alert('indicating ready');
		return true;
	}
setTimeout("getReadyState()", 100);
}

/*****************************************************
Error handling if source is not present or well-formed!
*****************************************************/
function showError(contentID, xObj) {
var strError = new String;
var err = xObj.parseError;

if (err.errorCode == -2146697211){
	alert("ATTENTION: Unfortunately, this information is not available on the site as yet!");
	xmldocloaded = false;
	xsldocloaded = false;
} else if(err.errorCode == -1072896751){
	alert("ATTENTION: Unfortunately, there is a problem loading this calendar page! \n\n Please report it to the content authors asap.");
	xmldocloaded = false;
	xsldocloaded = false;
} else {

	strError = 'Error!\n' + 'file url: '+ err.url + ' \n' + 'line no.: '+ err.line + '\n' + 'char: ' + err.linepos + '\n' + 'source: ' + err.srcText + '\n' + 'code: ' + err.errorCode+'\n'+ 'description: ' + err.reason + '\n';
	alert(strError);
	var htmlObj = eval("document.all."+contentID);
	htmlObj.innerHTML = strError;

}
}


/*********************************************************
JS equivalent of @Left
************************************************************/
function leftString(fullString, subString) {
   if (fullString.indexOf(subString) == -1) {
      return "";
   } else {
      return (fullString.substring(0, fullString.indexOf(subString)));
   }
}

/*********************************************************
JS equivalent of @Right
************************************************************/
function rightString(fullString, subString) {
 fullString += "";
 subString += "";
 if (subString != "" && fullString != "" && fullString.indexOf(subString) > -1){
  return (fullString.substring(fullString.indexOf(subString) + subString.length, fullString.length));
 }else{
  return fullString;
 }
}


