var calurl = "http://" + location.host + "/newspaper/nav";

var monthlist = [
	'January', 'February', 'March', 'April', 'May', 'June',
  'July', 'August', 'September', 'October', 'November', 'December'
];

var fsection, fyear, fmonth, fdate;
var csection, cyear, cmonth, cdate, matchlist, req;

var prettytd   = true;
var thisdaytd  = 'td_orange';
var thisweektd = 'td_white';

fsection = '';

var urlprefix = '';

function loadXMLDoc(url) {

	if (csection == 'breaking') {
		buildCalendar();
		return;
	}

	// branch for native XMLHttpRequest object
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
		req.onreadystatechange = processReqChange;
		req.open("GET", url, true);
		req.send(null);
	// branch for IE/Windows ActiveX version
	} else if (window.ActiveXObject) {
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			req.onreadystatechange = processReqChange;
			req.open("GET", url, true);
			req.send();
		}
	}
}

function processReqChange() {

	// only if req shows "complete"
	if (req.readyState == 4) {
		// only if "OK"
		if (req.status == 200) {
			// ...processing statements go here...
			matchlist = new Array(31);

			response  = req.responseXML.documentElement;
			// Make sure the document contains some nodes
			if (response.hasChildNodes()) {
				// Loop through all the items...
				itemlist = response.getElementsByTagName('item');
				for(i=0;i<itemlist.length;i++) {

					// Loop through the sections if there are any...
					if (itemlist[i].hasChildNodes()) {
						sectionlist = itemlist[i].getElementsByTagName('section');

						for(j=0;j<sectionlist.length;j++) {
							sectionname = sectionlist[j].firstChild.data;
							sectionname = sectionname.toLowerCase().replace(' ', '');
							//if (sectionlist[j].firstChild.data == csection) {
							if (sectionname == csection || csection.indexOf('archive') == 0) {
                var mydate = itemlist[i].getAttribute('date');
								mydate = (mydate.substring(0,1) == '0'?mydate.substring(1,2):mydate);
								matchlist[ parseInt(mydate) ] = csection;
							}
							//console.log( sectionname + " " + csection );
						}
					}

				}
			}

			//console.log( matchlist );

			buildCalendar();
		
		//} else {
		//	alert("There was a problem retrieving the XML data:\n" + req.statusText);
		}
	}

}

function buildCalendar() {
	var row, col, currdate, monday, sunday, breaking, today;

	today = new Date();

	if (cdate != -1) { // Highlight Week?
		currdate = makedate(cyear,cmonth,cdate);
		monday = getMonday(currdate).getTime();
		sunday = getSunday(currdate).getTime();
	}
 
  if ( cyear == 2011 && cmonth == 1 ) { // Fake 1st Jan 2011 publish
    matchlist[ 1 ] = 'articleindex';
  }
	
	// Month nav, clean table cells
	for(var i=0;i<=6;i++) {
		for(var j=0;j<=7;j++) {
			cleanTableCell( document.getElementById( "cal"+i+j ) );
		}
	}

	row = 1;
	for(var i=makedate(cyear,cmonth,1).getDate();i<=daysinmonth(cyear,cmonth);i++) {
		var thisdate = makedate( cyear, cmonth, i );

		var col = thisdate.getDay();

		var cell = document.getElementById( "cal"+row+col );
		cleanTableCell( cell );

		if (cdate != -1 && prettytd) { 
			if (thisdate.getDate() == cdate) {
				cell.className = thisdaytd;
			} else if ( thisdate.getTime() >= monday && thisdate.getTime() <= sunday ) {
				cell.className = thisweektd;
			}
		}

		
		if (
			csection=='breaking'
			&& today.getTime()-thisdate.getTime() > 0)
			breaking = true;
		else
			breaking = false;
	
		if (breaking
			|| (matchlist && matchlist[ i ] == csection)) {
			ahref = document.createElement('a');
			var myurl = makeurl( csection,cyear,cmonth,i );
			if ( myurl.indexOf( 'javascript:' ) == 0 ) {
				//ahref.setAttribute('onClick', myurl.substring(11));
				//ahref.onclick = function() { myurl.substring(11); };
				
				ahref.onclick = new Function( "return " + myurl.substring(11) );
				ahref.setAttribute('href', '#' );

			} else {
				ahref.setAttribute('href', myurl );
			}
			ahref.appendChild( document.createTextNode( i + " " ) );

			cell.appendChild( ahref );
		} else {
			cell.appendChild( document.createTextNode( i + " " ) );
		}

		if (thisdate.getDay() == 0) row++;
	}

	document.getElementById('currentmonthyear').innerHTML =
		monthlist[cmonth-1]+" "+cyear;

	setBackLink( 'cal_back', csection, cyear, cmonth );
	setForwLink( 'cal_forw', csection, cyear, cmonth );
}

// Date Functions...
function getMonday(mydate) {
	var dow = mydate.getDay();
	return (dow == 1 ? mydate : addDays( mydate, dow == 0 ? (-1 * 6) : -1 * (dow-1) ));
}
function getSunday(mydate) {
	var dow = mydate.getDay();
	return (dow == 0 ? mydate : addDays( mydate, dow == 1 ? 6 : 7-dow ));
}
function addDays(myDate,days) {
	return new Date(myDate.getTime() + days*24*60*60*1000);
}
function daysinmonth(year, month) {
	daylist = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	return (month == 2 && isleapyear(year) ? 29 : daylist[month-1]);
}
function isleapyear(year) {
	//return (year%4 == 0 && year%100 != 0 && year%400 == 0 ? true : false);
	return new Date(year,2-1,29).getDate()==29;
}
function makedate(year,month,day) {
	return new Date( year, month-1, day, 0, 0, 0 );
}

// Misc Functions
function makeurl(s, y, m, d) {
	if (urlprefix == '/games/crosswords') {
		return "javascript:setXWDate(" + y + ',' + m + ',' + d + ");";
	} else if (urlprefix != '') {
		return urlprefix + '/' + y + '/'
			+ (m < 10?"0":"") + m + (d < 10?"0":"") + d + "/index.html";
	}

	return '/newspaper/' + s + '/' + y + '/'
		+ (m < 10?"0":"") + m + (d < 10?"0":"") + d + "/"
		+ (csection.indexOf('archive') == 0?"Pg001.html":"index.html");
}

function initCalendar(s, y, m, d) {

	if (s == 'todayspaper') {
		urlprefix = '/todayspaper';
		s = 'articleindex';
	} else if (s == 'crosswords') {
		urlprefix = '/games/crosswords';
		s = 'articleindex';
	}

	csection = s;
	cyear    = y;
	cmonth   = m;
	cdate    = d;

	if (fsection == '') { // Remember the initial date setting...
		fsection = s;
		fyear    = y;
		fmonth   = m;
		fdate    = d;
	}

	// If the user have navigated back to the current date,
	// use the first initial date setting...
	if (cyear == fyear && cmonth == fmonth && cdate == -1) {
		csection = fsection;
		cyear    = fyear;
		cmonth   = fmonth;
		cdate    = fdate;
	}

	if (document.getElementById && document.getElementsByTagName)  {
		cmonth = parseInt( cmonth, 10 );
		loadXMLDoc(calurl + "/" + cyear + "/" + (cmonth<10?"0"+cmonth:cmonth) + ".xml");
	}
}

function cleanTableCell ( c ) {
	if (!(c && c.firstChild)) return;
	c.removeChild( c.firstChild )
	if (prettytd) c.className = ''
}

function setBackLink(l, s, y, m) {
	document.getElementById( l ).onclick = 
		function () { initCalendar(s, (m==1?y-1:y), (m==1?12:m-1), -1); return false; };
}
function setForwLink(l, s, y, m) {
	var today = new Date(); // Sanity Check - check it is not current month...
	if (today.getMonth()+1 == m && today.getFullYear() == y) return;
	document.getElementById( l ).onclick = 
		function () { initCalendar(s, (m==12?y+1:y), (m==12?1:m+1), -1); return false; };
}

//advert code
window._ittile1loaded = false;
window._ittile2loaded = false;
window._ittile3loaded = false;
window._ittile4loaded = false;

