// Function for running multiple functions "ON-LOAD"
// see http://www.webreference.com/programming/javascript/onloads/ for more details
//	not used at present

function addLoadEvent(func) { 
	  var oldonload = window.onload; 
	  if (typeof window.onload != 'function') { 
	    window.onload = func; 
	  } else { 
	    window.onload = function() { 
	      if (oldonload) { 
	        oldonload(); 
	      } 
	      func(); 
	    } 
	  } 
	} 
	 
	  /* more code to run on page load  
 * CREATED BY ADI SCOARTA
 * EMAIL: adi@codetale.com
 * Version: 1.08
 * Build Date: June 21st, 2009
 */

if(typeof(iMonth)=="undefined")
	iMonth = new Date().getMonth();
if(typeof(iYear)=="undefined")
	iYear = new Date().getFullYear();
if(typeof(iDay)=="undefined")
	iDay = new Date().getDate();
if(typeof(itype) == "undefined")
	itype = "loose" //loose->any date|strict->limit to maxDays
if(typeof(imaxDays) == "undefined")
	imaxDays = 330 //counts only if itype=strict. Enable selection imaxDays from start date
if(typeof(startDay) == "undefined")
	startDay = iDay; //enable selection from this date
if(typeof(startMonth) == "undefined")
	startMonth = iMonth;
if(typeof(startYear) == "undefined")
	startYear = iYear;
if(typeof(addZero) == "undefined")
	addZero = true; //true|false. Put 0 in front of days&months if <10
if(typeof(offX) == "undefined")
	offX = 10 // x distance from the mouse.
if(typeof(offY) == "undefined")
	offY = -10 // y distance from the mouse.cdate
if(typeof(formatInputs) == "undefined")
	formatInputs = 1 // Gather the data from no. of inputs
if(typeof(formatSplitter) == "undefined")
	formatSplitter = "-" // Character to add betwen day/month/year
if(typeof(monthFormat) == "undefined")
	monthFormat = "mm";
if(typeof(yearFormat) == "undefined")
	yearFormat = "yyyy";
if(typeof(folowMouse) == "undefined")
	folowMouse = true;
if(typeof(formatType) == "undefined")
	formatType = yearFormat+formatSplitter+monthFormat+formatSplitter+"dd"; //Format data type

if(typeof(callNotice) == "undefined")
	callNotice = "fallsilent()"; //call another function that a date has been selected.
if(typeof(sundayOff)=="undefined")
	sundayOff = false;
if(typeof(saturdayOff)=="undefined")
	saturdayOff = false;
if(typeof(sundayFirst)=="undefined")
	sundayFirst = false;

if (window.addEventListener)
	window.addEventListener("load", createBase, false)
else if (window.attachEvent)
	window.attachEvent("onload", createBase)
else if (document.getElementById)
	window.onload=createBase



document.onmousemove = getMouseXY;

var IE = document.all?true:false
if (!IE) document.captureEvents(Event.MOUSEMOVE)

var tempX = 0
var tempY = 0

function getMouseXY(e) {
  if (IE) { // grab the x-y pos.s if browser is IE
    tempX = event.clientX + document.body.scrollLeft
    tempY = event.clientY + document.body.scrollTop
  } else {  // grab the x-y pos.s if browser is NS
    tempX = e.pageX
    tempY = e.pageY
  }  
  if (tempX < 0){tempX = 0}
  if (tempY < 0){tempY = 0}  

  return true
}


function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}



/*
 * Shortcut functions to ease the implementation.
 */

var d = document;
function cel(obj){ return d.createElement(obj);  }
function sa(obj, atname, atprop){ return  obj.setAttribute(atname, atprop);  }
function appendc(obj, elem){ return  obj.appendChild(elem); }
function cNode(obj, txt){ return obj.appendChild(d.createTextNode(txt)); }
function getID(elem){ return d.getElementById(elem); }

var DayCol = new Array("M", "T", "W", "T", "F", "S", "S");
if(sundayFirst)
{
	newDayCol = new Array(DayCol[DayCol.length-1]);
	for(x=0; x<DayCol.length-1;x++)
		newDayCol[newDayCol.length] = DayCol[x];
	DayCol = newDayCol;
}
var MonthCol = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov", "Dec")

function getDaysInMonth(mnt, yr)
{
	var DaysInMonth = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	if (mnt == 1)
	  DaysInMonth[1] = ((yr % 400 == 0) || ((yr % 4 == 0) && (yr % 100 !=0))) ? 29 : 28;
	return DaysInMonth[mnt];
}
/*
 * Base object for the widget
 */  
 
var cw = {
	currMonth: iMonth,
	currYear: iYear,
	currDay: iDay,
	selMonth: iMonth,
	selYear: iYear,
	selDay: iDay,
	config: itype,
	maxDays: imaxDays,
	stMonth : startMonth,
	stYear : startYear,
	stDay : startDay,
	endMonth : 11,
	endYear : iYear,
	endDay : 31,
	addZ: addZero, 
	setMarks: function()
	{
		if(this.config=='strict')
		{
			this.stDay = startDay;
			this.stMonth = startMonth;
			this.stYear = startYear;
			this.getEnd();
		}
	},
	getConfMonths: function()
	{
		if(this.config=='strict')
			cw.setMarks();
		mthCol = cel("ul");
		mthCol.id = "months";
		k=0;
		  for(i=0;i<12; i++)
		  {
				mth = cel("li");
				if(cw.isValidMonth(i))
				{
					mth.className = "months";
					if(cw.isCurrentMonth(i))
						mth.className = "currMonth";
					mtha = cel("a");
					mtha.href = "javascript:modMonth("+this.selYear+"," + i + ")";
					mtha.innerHTML = MonthCol[i];
					appendc(mth, mtha);
				}
				else
				{
					mth.className = "monthDisabled";
					mth.innerHTML = MonthCol[i];
				}
				appendc(mthCol, mth)
				
		  }
		cw.setBrowseYears();		
		
		return mthCol ;
	},
	getConfDays: function()
	{
		dayCol = cel("ul");
		dayCol.id = "days";
		for(i=0;i<7;i++)
		{
			dayCell = cel("li");
			dayCell.className = "headDay";
			dayCell.innerHTML = DayCol[i];
			appendc(dayCol, dayCell);
		}
		var iFirstDay = new Date(this.selYear, this.selMonth, 1).getDay();
		if (!sundayFirst) {
			iFirstDay--;
		}
		if(iFirstDay<0){iFirstDay=6}
		for(i=0;i<iFirstDay;i++)
		{
			dayCell = cel('li');
			dayCell.className = "dayBlank";
			dayCell.innerHTML = "&nbsp;";
			appendc(dayCol, dayCell)
		}
		for(i=1;i<=getDaysInMonth(this.selMonth, this.selYear); i++)
		{
			dayCell = cel('li');
			if(cw.isValidDate(i))
			{
				dayCell.className = "dayNormal";
				if(cw.isWeekend(i))
					dayCell.className = "dayWeekend";
				if(cw.isCurrentDay(i))
					dayCell.className = "dayCurrent";
				dayLink = cel('a');
				dayLink.href="javascript: newDay("+ i + ");fillBackDate("+i+","+this.selMonth+","+ this.selYear+")";
				dayLink.innerHTML = i;
				appendc(dayCell, dayLink);
			}
			else
			{
				dayCell.className = "dayDisabled";
				dayCell.innerHTML = i;
			}
			appendc(dayCol, dayCell)
		}
		return dayCol;
	},
	getEnd: function()
	{
		imaxD = imaxDays - (getDaysInMonth(this.stMonth, this.stYear) - this.stDay);
		tmpM = this.stMonth;
		tmpY = this.stYear;
		if (imaxD < 0) {
			tmpD = this.stDay+(imaxD*(-1));
			this.endMonth = tmpM;
			this.endDay = tmpD;
			this.endYear = tmpY;
			return;
		}
		else if(imaxD == 0)
		{
			tmpD = getDaysInMonth(this.stMonth, this.stYear);
			this.endMonth = tmpM;
			this.endDay = tmpD;
			this.endYear = tmpY;
			return;
		}
		else if(imaxD < (getDaysInMonth(this.stMonth, this.stYear) - this.stDay))
		{
			tmpD = imaxD;
		}
		i=0;
		while(imaxD >= getDaysInMonth(tmpM, tmpY))
		{
			inc = true;
			tmpM++
			if(tmpM>11)
			{
				tmpM=0
				tmpY++;
			}
			tmpD = imaxD -= getDaysInMonth(tmpM, tmpY);
		}
		tmpM++
		if(tmpM>11){tmpM=0; tmpY++}
		this.endMonth = tmpM;
		this.endDay = tmpD;
		this.endYear = tmpY;

	},
	isValidDate: function(tDay)
	{
		if(saturdayOff || sundayOff)
		{
			sun = new Date(this.selYear, this.selMonth, tDay);
			sun = sun.getDay()
			if((sun==6 && saturdayOff) || (sun==0 && sundayOff))
				return false;
		}	
		if(this.config == "loose")
			return true;
		cdate = new Date(this.selYear, this.selMonth, tDay).getTime();
		sdate = new Date(this.stYear, this.stMonth, this.stDay).getTime();
		edate = new Date(this.endYear, this.endMonth, this.endDay).getTime();
		if(cdate<sdate || cdate>edate)
			return false;
		return true;
		if(this.selYear==this.stYear)
		{
			if(this.selMonth<this.stMonth)
				return false;
			if(this.selMonth==this.stMonth && tDay <this.stDay)
				return false;
		}
		if(this.selYear==this.endYear)
		{
			if(this.selMonth>this.endMonth)
				return false;
			if(this.selMonth==this.endMonth && tDay>this.endDay)
				return false;
				
		}
		if(this.selYear == this.endYear && this.selYear==this.stYear){
			if(this.selMonth> this.endMonth || this.selMonth<this.stMonth)
				return false;
			}
		if(this.selYear>this.endYear)
			return false;
		return true;
		
	},
	isWeekend: function(tDay)
	{
		sun = new Date(this.selYear, this.selMonth, tDay).getDay();
		if(sun==6||sun==0)
			return true;
		return false;
	},
	isCurrentDay: function(tDay)
	{
		if(this.selDay == tDay)
			return true;
		return false;
	},
	setBrowseYears: function()
	{
		brsY = cel('li');
		brsY.className = "yearBrowse";
		if(this.selYear <= this.stYear && this.config == "strict")
		{
			backB = cel('span');	
		}
		else
		{
			backB= cel('a');
			backB.href = "javascript: modYear(-1)";
		}
		backB.innerHTML = "&laquo;";
		yText = cel("b");
		yText.innerHTML = cw.selYear;
		if(this.selYear >= this.endYear && this.config == "strict")
			fwdB = cel('span');
		else
		{
			fwdB = cel('a');
			fwdB.href= "javascript: modYear(1)";
		}
		fwdB.innerHTML = "&raquo;";
		appendc(brsY, backB);
		appendc(brsY, yText);
		appendc(brsY, fwdB);
		appendc(mthCol, brsY);
	},
	isValidMonth: function(m)
	{
		if(this.config == "loose")
			return true;
		else
		{
			if(this.selYear< this.stYear)
				return false;
			if(this.selYear==this.stYear && m<this.stMonth)
				return false;
			if(this.selYear>this.endYear)
				return false;
			if(this.selYear==this.endYear && m>this.endMonth)
				return false;
		}	
		return true;
	},
	isCurrentMonth: function(i)
	{
		if(i==this.selMonth)
			return true
		return false;
	}
}

cw.setMarks();
function createBase()
{

	var el = cel('div');
	el.id="calendar";
	el.style.display="none";
	if(typeof(elToAppend) == "undefined")
		tDocument = document.getElementsByTagName('body').item(0);
	else
	{
		var tt = elToAppend;
		tDocument = document.getElementById(tt);
	}
	appendc(tDocument, el);	
}


function createCalendarElements()
{
	var el = 'calendar';
	var calCon = cel('div');
	calCon.id = "elements";
	while(document.getElementById(el).firstChild)
		document.getElementById(el).removeChild(document.getElementById(el).firstChild);
	appendc(document.getElementById(el), calCon);
	mthCol = cw.getConfMonths();
	appendc(calCon, mthCol);
	dayStruct = cw.getConfDays();
	appendc(calCon, dayStruct);

	closeBtn = cel('div');
	closeBtn.id = "closeBtn";
	closeBtna = cel('a');
	closeBtna.href = "javascript: closeCalendar()";
	closeBtna.innerHTML = "close";
	appendc(closeBtn, closeBtna);
	appendc(document.getElementById(el), closeBtn);
}
function modMonth(newY, newM)
{
	cw.selYear = newY;
	cw.selMonth = newM;
	createCalendarElements();
}
function newDay(newD)
{
	cw.selDay = newD;
	createCalendarElements();
}
function modYear(way)
{
	cw.selYear = parseInt(cw.selYear) + parseInt(way);
	createCalendarElements();	
}
var datas;
var elem1;
var elem2;
var elem3;
var mA=0;
var yA=0;
var mm = new Array('mm', 'mmm');
var yy = new Array('yy', 'yyyy');

function fPopCalendar(param)
{
	document.getElementById("myf").style.visibility="hidden";
	tmpString = new String();
	elem1 = param;
	tmpString = document.getElementById(elem1).value;
	datas  = tmpString.split(formatSplitter);
	tmpo = formatType.split(formatSplitter);
	dC="";tC="";
	if(datas.length == tmpo.length)
	{
		for(i=0;i<datas.length;i++)
		{
			if(datas[i].length<2)
				datas[i] = "0"+datas[i];
			dC +=datas[i];
			tC +=tmpo[i]; 
		}
		if(dC.length == tC.length)
			orderData();
	}
	else
		datas = new Array(cw.selDay, cw.selMonth, cw.selYear);
	createCalendarElements();
	offsets = getScrollXY();
	document.getElementById('calendar').style.display = "block";

	if(folowMouse)
	{
		var browser=navigator.appName;
		if(browser=="Microsoft Internet Explorer")
		{
			document.getElementById('calendar').style.left = parseInt(tempX)+parseInt(offX)+parseInt(offsets[0]) + 'px';
		    document.getElementById('calendar').style.top = parseInt(tempY)+parseInt(offY)+parseInt(offsets[1]) + 'px';
		}
		else
		{
			document.getElementById('calendar').style.left = parseInt(tempX)+parseInt(offX)+ 'px';
		    document.getElementById('calendar').style.top = parseInt(tempY)+parseInt(offY)+ 'px';
		}
	}
document.getElementById("calendar").style.left = "40%";
			
	order = new String(formatType).split(formatSplitter);

	for(i=0;i<mm.length;i++)
	{
		for(j=0;j<order.length;j++)
		{
			if(mm[i] == order[j])
				mA = i;
			if(yy[i] == order[j])
				yA = i;
		}
	}
}

function orderData()
{

	order = new String(formatType).split(formatSplitter);

	for(i=0;i<order.length;i++)
	{
		for(j=0;j<mm.length;j++)
		{
			if(mm[j] == order[i])
			{
				cw.selMonth = datas[i];
				if(cw.selMonth.slice(0, 1) == 0)
					cw.selMonth = parseInt(cw.selMonth.slice(1, cw.selMonth.length))-1;
				else if(cw.selMonth.length<3)
					cw.selMonth = parseInt(cw.selMonth)-1;
				if(j==1)
				{
					for(k=0;k<MonthCol.length;k++)
					{
						if(MonthCol[k].toLowerCase() == cw.selMonth.toLowerCase() )
						{
							cw.selMonth = k;
							break;
						}
					}
				}
			}
			if(yy[j] == order[i])
			{
				cw.selYear = datas[i];
				if(cw.selYear.slice(0, 1) == 0)
					cw.selYear = parseInt(cw.selYear.slice(1, cw.selYear.length));
				if(j==0)
					cw.selYear =2000 + parseInt(cw.selYear);
			}				
		}
		if(order[i].toLowerCase() == 'dd')
		{
			cw.selDay = datas[i];
			if(cw.selDay.slice(0, 1) == 0)
				cw.selDay = parseInt(cw.selDay.slice(1, cw.selDay.length));
		}
	}
}

function fillBackDate(tDay, tMonth, tYear)
{
if(mA==1)
		tMonth = MonthCol[tMonth];
	if(mA==0)
	{
		tMonth++;
		if(tMonth<10  && cw.addZ == true)
			tMonth = "0"+tMonth;
	}
	if(yA==0)
		tYear = new String(tYear).slice(2,4);
	if(tDay<10 && cw.addZ == true)
	{
		tDay = "0"+tDay;
	}
	
	order = new String(formatType).split(formatSplitter);
	vali = "";
	
	for(x = 0; x <order.length; x++)
	{
		if (order[x] == "yy" || order[x] == "yyyy") 
			vali += tYear;
		if (order[x] == "mm" || order[x] == "mmm") 
			vali += tMonth;
		else if(order[x] == "dd")
			vali += tDay;
		if(x < order.length-1)
			vali += formatSplitter;
	}
	
	document.getElementById(elem1).value = vali
	setTimeout(callNotice, 0);
	
	closeCalendar();
}

function closeCalendar()
{
	var el = 'calendar';
	document.getElementById(el).style.display = "none";
}
function fallsilent(){}


function gotadate(){
	// control comes here when a date has been selected
	// make the form and contents visible after calculating the captions etc for the input and button
    
	var selecteddate = document.getElementById("datepicked").value;
    var datebits = selecteddate.split(formatSplitter,3);
    var datepicked = new Date(datebits[0],datebits[1]-1,datebits[2]);
    // if published date is Sunday, use the saturday
		if(datepicked.getDay()==0) 
		{
			datepicked.setDate(datepicked.getDate() - 1);
		}
    ukpubdate = calc_ukpubdate(datepicked);
   	var ozpuzzno = calcozpuzzno(datepicked);
//   	var ozpuzzno = calcozpuzzno(datebits[0],datebits[1]-1,datebits[2]);
		  


    // modify ukpubdate if a sunday to the saturday before
		if(ukpubdate.getDay()==0) 
		{
			ukpubdate.setDate(ukpubdate.getDate() -1);
		}
    // modify link if a saturday to the following saturday
 		if(ukpubdate.getDay()==6) 
		{
			ukpubdate.setDate(ukpubdate.getDate() + 7);
		}
    // Disallow if date precedes first blog on 1/11/2006  or is in the future

   var firstukdate = new Date(2006,10,2);
    if(ukpubdate < firstukdate) {
    	alert("You have selected an Australian publication date of " + shortdate(datepicked) + " The earliest blog available is for the puzzle published in The London Times on 2/11/2006 which corresponds approximately to 9/12/2006 in The Australian");
    	return;
    } 
   var latestukdate = new Date();
    if(ukpubdate > latestukdate) {
    	alert("You have selected an Australian publication date of " + shortdate(datepicked) + " which corresponds to a puzzle not yet published in The London Times");
    	return;
    } 
			mthno = ukpubdate.getMonth() + 1;
			if(mthno < 10) mthno = "0" + mthno;
			dno = ukpubdate.getDate();
			if(dno < 10) dno = "0" + dno;
						
			linkstr = ukpubdate.getFullYear() + "/" + mthno + "/" +dno + "/";
			mylink = "http://community.livejournal.com/times_xwd_times/" + linkstr;
			dno = datepicked.getDay();
			var dpicked = weekday[dno] + ", " + shortdate(datepicked) + puzznodescr(ozpuzzno);
			document.getElementById("mytext").value = dpicked;
			document.getElementById("myf").style.visibility="visible";
	
}
function showblog(form){
		document.getElementById("myf").style.visibility="hidden";
    window.open(mylink,"_self","status=1,menubar=1,resizable=1,scrollbars=1");
}

function myalert(cmsg,showalerts){
	if(showalerts){
		showalerts = confirm(cmsg + "\r\n\r\nClick Cancel to disable future alerts. ");
	}
}

function CalcSeason(ozdate){
var y = ozdate.getFullYear();
var pindx;
var xday = new Date(y-1,11,25)	//xmas last year
var dx = days_between(xday,ozdate,0);	// days since xmas last year
var gf = new Date(y,gfm[y - 2004]-1,gfd[y - 2004]);	// good friday this year
var dg = days_between(ozdate,gf,0);	// days till good friday this year
pindx = 2;	// default, between easter and xmas this year
/* 			$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
				$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
				
				The Hack below is temporary and will invalidate searches pre June 3 2010
				
				The whole program needs to be re-written to allow for older dates

   			$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
				$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
				
*/
if((dx<=31) || (dx > 365)) {  // value was 38
	
	pindx = 0;	//xmas to late january
	return pindx;
	}
if(dg> 0 ) {
	pindx = 1;  //before easter
	}
	return pindx;
}		 		//else pindx = 2   feb to easter

	//																**********	FUNCTION CALC_UKPUBDATE  *************************

function calc_ukpubdate(ozpubdate){
	//	calculate uk publishing date depending on the day of the week and time of year
	//	Determine the relevant period of the year as one of 
	//	SeasonalAdjust = 0, corresponding to Christmas until xmaspubdate (about Feb 1)
	//	SeasonalAdjust = 1, corresponding to xmaspubdate until Good Friday
	//	SeasonalAdjust = 2, corresponding to Good Friday until Christmas
	var SeasonalAdjust = CalcSeason(ozpubdate);
	if(SeasonalAdjust==0) {
										// 		case 0:  // Xmas to xmaspubdate
			
     	switch(ozpubdate.getDay()){
	    	case 1:	//Monday 	> Thursday Crossword
	    		pubdiff = 32;
	   			break;
	    	case 2:	//Tuesday >	Friday Crossword
	    		pubdiff = 32;
	   			break;
	    	case 3:	//Wednesday >	Saturday Crossword
	    		pubdiff = 11;																		// DONE FOR 2011 ONLY
	   			break;
	    	case 4:	//Thursday >	Monday Crossword
	    		pubdiff = 31;
	   			break;
	    	case 5:	//Friday >	Tuesday Crossword
	    		pubdiff = 31;
	   			break;
	    	case 6:	//Saturday >	Wednesday Crossword
	    		pubdiff = 31;
	   			break;
    	}
   }else if(SeasonalAdjust==1){
 										// 		case 1:  // xmaspubdate until Good Friday
    	switch(ozpubdate.getDay()) {
	    	case 1:	//Monday -	Thursday Crossword
	    		pubdiff = 32;
	   			break;
	    	case 2:	//Tuesday >	Friday Crossword
	    		pubdiff = 32;
	   			break;
	    	case 3:	//Wednesday >	Saturday Crossword
    		pubdiff = 25;
	   			break;
	    	case 4:	//Thursday >	Monday Crossword
	    		pubdiff = 31;
	   			break;
	    	case 5:	//Friday >	Tuesday Crossword
	    		pubdiff = 31;
	   			break;
	    	case 6:	//Saturday >	Wednesday Crossword
	    		pubdiff = 31;
	   			break;
	    	}
	    } else if(SeasonalAdjust==2){
										// 		case 2:  // Good Friday to Xmas
	    switch(ozpubdate.getDay()) {
	    	case 1:	//Monday 	> Thursday Crossword
	    		pubdiff = 32;
	   			break;
	    	case 2:	//Tuesday >	Friday Crossword
	    		pubdiff = 32;
	   			break;
	    	case 3:	//Wednesday >	Saturday Crossword
	    		pubdiff = 25;
	   			break;
	    	case 4:	//Thursday >	Monday Crossword
	    		pubdiff = 31;
	   			break;
	    	case 5:	//Friday >	Tuesday Crossword
	    		pubdiff = 31;
	   			break;
	    	case 6:	//Saturday >	Wednesday Crossword
	    		pubdiff = 31;
	   			break;
    		}
		}
	//	Correct the pubdiff variable to reflect the omission of 6 crosswords (1 week) from June 3 2010
		changedate = new Date(2010,5,2);

		ukpubdate = new Date();
		ukpubdate.setTime(ozpubdate.getTime() - pubdiff * ONE_DAY);
		
		// disallow xmas and sunday publication in uk
		if((ukpubdate.getDate() == 25) && (ukpubdate.getMonth() == 11)){
			switch(ukpubdate.getDay()){
				case 0:	//Sunday - should not occur
					ukpubdate.setTime(ukpubdate.getTime() + 1 * ONE_DAY); 
				break;
				case 6:  // Saturday - the following Saturday 1st January
					ukpubdate.setTime(ukpubdate.getTime() + 2 * ONE_DAY); 
	   			break;
				case 5:  // Friday - blog on the following Monday 28th December
					ukpubdate.setTime(ukpubdate.getTime() + 3 * ONE_DAY); 
	   			break;
	    	default:	// the next day
					ukpubdate.setTime(ukpubdate.getTime() + 1 * ONE_DAY);
			} 
		}
return ukpubdate;
}
function puzznodescr(ozpuzzno){
	if(ozpuzzno >= 8709){
		puzzoffset = 15819;
		} else {
		puzzoffset = 15813;
	}
	return " [ " + ozpuzzno + " = " + (ozpuzzno + puzzoffset) + "]";
}
function ukpuzcode(ozpuzzno){
// alert("ukpuzcode " + ozpuzzno);
	if(ozpuzzno >= 8709){
		ukpuzcode = 15819 + parseInt(ozpuzzno);
		} else {
		ukpuzcode = 15813 + parseInt(ozpuzzno);
	}
	return ukpuzcode;
}

function googlesearch(ukcode) {
alert("googlesearch  called " + ukcode);
if(ukcode<=23176){
	alert("Puzzle number " + ukcode + " was published before the earliest Blog available (23177)");
	return;
}
if(ukcode<=23435) {
	str1 = "http://www.google.com.au/search?q=times-for-the-times+" + ukcode;
}else{
	str1 = "http://www.google.com.au/search?q=times_xwd_times+" + ukcode;
}
return(str1);
}

function showgoogle(form)
{
ozpuzzno = document.forms['myf2'].getozcode.value;
ukpuzzno = ukpuzcode(ozpuzzno);
// alert("ukpuzzno =  " + ukpuzzno);    
var linkstr = googlesearch(ukpuzzno); 
// alert("linkstr =" + linkstr);    
window.open(linkstr,"_self","status=1,menubar=1,resizable=1,scrollbars=1");
}
	//																**********	FUNCTION SETUP  *************************
function setup(){
	 count1 = 0;
	 count2 = 0;
	 count3 = 0;
	 showalerts = true;
	 mylink = "";

	//	establish today's date
	thisdate = new Date();
	ozpubdate = new Date();
 ONE_DAY = 1000 * 60 * 60 * 24
 // DAYS OF THE WEEK **********
weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
	
baseserialno = 8558;
basedateyr = 2009;
basedatemo = 11;	//December ... Javascript style
basedateday = 7;
basedate = new Date(basedateyr,basedatemo,basedateday);
var dayno = basedate.getDay();
// ensure basedate is a sunday with baseserialno corresponding to the day before, even if it is Xmas day
while(dayno!=0)
{
		basedate.setDate(basedate.getDate() - 1);
	baseserialno = baseserialno - 1;

dayno  = basedate.getDay();
}
// calculate date of publication of Xmas day in oz (Feb 1st)
xmaspubdate = new Date(thisdate.getFullYear(),1,1);

// handle good fridays when no papers are published
gfm = new Array(4,3,  4,4, 3,   4,4, 4,4, 3, 4,4, 3, 4, 4, 4, 4,4, 4,4 );	//month of good friday 2004 to 2019
gfd = new Array(9,25,14,6,21,  10,2,22,6,29,18,3,25,14,30,19,10,2,15,7);	//day of good friday 2004 to 2019
/*gfm[0]=4;	//2004
gfd[0]=9;	*/

today= new Date();
fy = today.getFullYear();
// get index for above arrays
gfindex = fy -2004;
// get date of good friday this year
gfdate = new Date(fy,gfm[gfindex]-1,gfd[gfindex]);
var dayssincegf = days_between(today, gfdate,0);
// alert("dayssincegf calc 924 gf = " + gfdate + " dayssince = " + dayssincegf);
// IsEaster = 	(dayssincegf >= 1)&& (dayssincegf < 7);
xmasdate = new Date(fy,11,25);
var dayssincexmas = days_between(today, xmasdate,0);
IsChristmas = 	(dayssincexmas >= 1);
// alert("leaving setup, dayssincexmas = " + xmasdate + "; " + dayssincegf + "; " + dayssincexmas); 
}
	//																**********	FUNCTION ISCHRISTMAS  *************************


function isxmas() {
var today = new Date();
var xmasday = new Date(today.getFullYear(),11,25);
var dayssincexmas = days_between(xmasday,today,0);
return (dayssincexmas >= 1)
}
	//																**********	FUNCTION ISEASTER  *************************

function IsEaster() {
var today = new Date();
var gfriday = new Date(today.getFullYear(),gfm[gfindex]-1,gfd[gfindex]);
var dayssincegf = days_between(gfriday,today,0);
return (dayssincegf <= 6) && (dayssincegf > 0)
}

	//																**********	FUNCTION DAYS_BETWEEN  *************************


function days_between(date1,date2,res_type) {
// alert("days_between called date1, date2, restype = " + date1 + "  " + date2 + "  " + res_type + "  ");
    // The number of milliseconds in one day
   
    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()
		//	res_type = 0	returns integer calendar days from date1 to date2
		//	res_type = 1	returns rounded integer days from date1 to date2
		//	res_type = 2	returns integer complete days from date1 to date2
		//	res_type = 3	returns fractional days from date1 to date2
		//	res_type = 4	returns ABSOLUTE (integer calendar days from date1 to date2)
		//	res_type = 5	returns ABSOLUTE (rounded integer days from date1 to date2)
		//	res_type = 6	returns ABSOLUTE (integer complete days from date1 to date2)
		//	res_type = 7	returns ABSOLUTE (fractional days from date1 to date2)

    // Calculate the difference in milliseconds
//    var difference_ms = Math.abs(date2_ms - date1_ms)  // **** ABSOLUTE ****
    var difference_ms = date2_ms - date1_ms
    
    // Convert back to days 
    var fracdays = difference_ms/ONE_DAY;
    // var fracdays = Math.round(difference_ms/ONE_DAY);
    var res
    switch(res_type)
    {
    	case 0:
		//	res_type = 0	returns integer calendar days from date1 to date2
    		res =  Math.round(fracdays + 0.4999);	
    	break;
     	case 1:
		//	res_type = 1	returns rounded integer days from date1 to date2
    		res =  Math.round(fracdays);	
    	break;
    	case 2:
		//	res_type = 3	returns fractional days from date1 to date2
    		res =  Math.floor(fracdays);	
    	break;
    	case 3:
		//	res_type = 3	returns fractional days from date1 to date2
				res = fracdays;
    	break;
    	case 4:
		//	res_type = 4	returns ABSOLUTE (integer calendar days from date1 to date2)
    		res =  Math.round(fracdays + 0.4999);
    		res = Math.abs(res);	
    	break;
    	case 5:
		//	res_type = 5	returns ABSOLUTE (rounded integer days from date1 to date2)
    		res =  Math.round(fracdays);	
    		res = Math.abs(res);	
    	break;
    	case 6:
		//	res_type = 6	returns ABSOLUTE (integer complete days from date1 to date2)
    		res =  Math.floor(fracdays);	
    		res = Math.abs(res);	
    	break;
   		case 7:
		//	res_type = 7	returns ABSOLUTE (fractional days from date1 to date2)
				res = fracdays;
   		res = Math.abs(res);	
     	break;
     	default:
    }
    	return res

}	
		dayname = "";  //global
	//																**********	FUNCTION day_of_week  *************************
//	returns weekday name for any date	object
function day_of_week(anydate) {
return weekday[anydate.getDay()]
}


	//																**********	FUNCTION DAYSAGO  *************************

	function daysago(firstdate,daysoffset){
		
	// returns description of the day daysoffset before firstdate in the form
	//	The Australian 2 days ago - Monday, 22/03/2010
	if(daysoffset==0) {msg = "Today - "};
	if(daysoffset==1) {msg = "Yesterday - "};
	if(daysoffset>=2) {msg = daysoffset + " days ago - "};
	var dd = new Date();
	dd.setTime(firstdate);
	dd.setDate (dd.getDate() - daysoffset);
		var zyrno = dd.getFullYear();
	zmthno = dd.getMonth() + 1;
	zdno = dd.getDate();
	dayname = weekday[dd.getDay()];
if (zdno <= 9) zdno = "0" + zdno; 
if (zmthno <= 9) zmthno = "0" + zmthno; 
// msg = msg + "  " + dayname + ", " + zdno + "/" + zmthno + "/" + zyrno;
msg = msg + "  " + dayname + ", " + shortdate(dd);
		return msg;
}

	//																**********	FUNCTION SHORTDATE  *************************
function shortdate(anydate) {
	return anydate.getDate() + "/" + (anydate.getMonth() + 1) + "/" + anydate.getFullYear();
}
	
	//																**********	FUNCTION WRITELINK  *************************
function writelink(firstdate) {
	// calculate oz publication date
	// alert("writelink called with " + shortdate(firstdate));
 ozpubdate.setTime(firstdate.getTime() - offset * ONE_DAY);
		var isSunday =(ozpubdate.getDay() == 0);
		var isgf = (ozpubdate.getMonth() + 1 == gfm[gfindex]-1) && (ozpubdate.getDate() == gfd[gfindex]);
		var isXmas = (ozpubdate.getMonth() == 11) && (ozpubdate.getDate() == 25);
		var ozPublished = (!isSunday && !isgf && !isXmas);
		// alert(shortdate(firstdate) + " ozPublished = " + ozPublished );
		 // exit if not published in oz
		 if(!ozPublished)return;
		// calculate uk publication date
			// calculate publishing delay (pubdiff)
			ukpubdate = calc_ukpubdate(ozpubdate);
			var ozpuzzno = calcozpuzzno(ozpubdate);
//			var ozpuzzno = calcozpuzzno(ozpubdate.getFullYear(),ozpubdate.getMonth(),ozpubdate.getDate());

		var daypuboz = daysago(firstdate,offset);

		var mthno = ukpubdate.getMonth() + 1;
		if(mthno < 10) mthno = "0" + mthno;
		var dno = ukpubdate.getDate();
		if(dno < 10) dno = "0" + dno;
		var linkstr = ukpubdate.getFullYear() + "/" + mthno + "/" +dno + "/";
	document.write('<A HREF=\"http://community.livejournal.com/times_xwd_times/' + linkstr + '\"><br>' + daypuboz +'</A>' + puzznodescr(ozpuzzno));

if (IsMisfiled(ozpuzzno)) {
	ukcode = ukpuzcode(ozpuzzno);
	linkstr = googlesearch(ukcode);
	document.write("<span id='yellowbg'><br><b><font size=3 color=black>The Blog for the above crossword has been misfiled. Click <a href='" + linkstr + "'> Here</a></b>  to use Google search.</font></span>");
	}
}
function IsMisfiled(ozno){
	ret = false;
	// Oz puzz numbers misfiled in blogs on livejournal 
var misfiledstr = "#8905#8893#8802#1111#";
var oznostr = "#" + ozno + "#";
	if(misfiledstr.indexOf(oznostr)>=0) ret = true;
	return ret;
	}


	//																**********	FUNCTION CALCOZPUZZNO  *************************
function calcozpuzzno(ozdate)  {
	//	returns Australian crossword serial number, given publication date [month is Javascript style (0 - 11)]
//Get difference in days
// var basedate = new Date(2010,2,9);
// var baseserialno = 8636;
var daysdiff = days_between(basedate,ozdate,0) - 1;
var sundaysdiff = Math.floor(daysdiff/7) + (basedate.getDay() > ozdate.getDay()) ;
var yno = ozdate.getFullYear();
var mno = ozdate.getMonth();
var dno = ozdate.getDate();
// count intervening Xmas Days
var xmascount = 0;
xmascount = yno - basedate.getFullYear();
if((mno == 11) && (dno > 25)) xmascount ++;	// it is post xmas in december

// count intervening Good Fridays
var gfcount = 0;
gfcount = yno - basedate.getFullYear();  
gfbase = new Date(basedate.getFullYear(),gfm[basedate.getFullYear()-2004]-1,gfd[basedate.getFullYear()-2004]);
var db = days_between(gfbase,basedate,0);
if(db > 1) gfcount = gfcount -1; // the -1 is to allow for basedate being post good friday
gfdte = new Date(yno,gfm[yno-2004]-1,gfd[yno-2004]);
db = days_between(gfdte,ozdate,0);
if(db >= 1) gfcount ++;	// if it is now post Good Friday in year

var nopub = 0;
/*
// reduce serial no. by 1 if xmas or good friday
if((mno == 11) && (dno == 25)) nopub = 1;
if((mno == gfm[yno - 2010]) && (dno == gfd[yno - 2010])) nopub = 1;
*/
//	reduce xmascount by 1 to allow for xmas days being on a Sunday in 2011, 2016,2022,2033,2039
xmasonsunday = new Array(2011,2016,2022,2033,2039,0);
x=0;
	while(xmasonsunday[x]>0)
	{
//		alert(xmasonsunday[x]);
	testdate = new Date(xmasonsunday[x],0,16);
		if(ozdate >=testdate) {
			xmascount = xmascount - 1;
			x = x + 1;
	}	else{
		break;
	}
}
p = baseserialno + daysdiff - sundaysdiff - xmascount - gfcount;
// p = sundaysdiff * 6 + daysdiff % 7 + baseserialno - nopub - xmascount - gfcount;
return p;
}
	//																**********	FUNCTION SHOWSELECTED  *************************
function showselected (form) {
    var selecteddate = form.inputbox.value;
    var spl = selecteddate.split(" ",2);
    var datebits = spl[1].split("/",3);
    var yy = datebits[2].split(" ",1);
    var datepicked = new Date(yy[0],datebits[1]-1,datebits[0]);
    // if published date is Sunday, use the saturday
		if(datepicked.getDay()==0) 
		{
			datepicked.setDate(datepicked.getDate() - 1);
		}
    ukpubdate = calc_ukpubdate(datepicked);
    var ozpuzzno = calcozpuzzno(yy[0],datebits[1]-1,datebits[0]);
    // modify ukpubdate if a sunday to the saturday before
		if(ukpubdate.getDay()==0) 
		{
			ukpubdate.setDate(ukpubdate.getDate() -1);
		}
    // modify link if a saturday to the following saturday
 		if(ukpubdate.getDay()==6) 
		{
			ukpubdate.setDate(ukpubdate.getDate() + 7);
		}
    // Disallow if date precedes first blog on 1/11/2006
   var firstukdate = new Date(2006,10,2);
    if(ukpubdate < firstukdate) {
    	myalert("You have selected an Australian publication date of " + shortdate(datepicked) + " The earliest blog available is for the puzzle published in The London Times on 2/11/2006 which corresponds approximately to 9/12/2006 in The Australian",showalerts);
    	return;
    } 
			mthno = ukpubdate.getMonth() + 1;
			if(mthno < 10) mthno = "0" + mthno;
			dno = ukpubdate.getDate();
			if(dno < 10) dno = "0" + dno;
						
			linkstr = ukpubdate.getFullYear() + "/" + mthno + "/" +dno + "/";
			var mylink = "http://community.livejournal.com/times_xwd_times/" + linkstr;
    window.open(mylink,"_self","status=1,menubar=1,resizable=1,scrollbars=1");
 }

