// Copyright 1995-2009 (C) Otto de Voogd - http://www.7is7.com/
// Original URL: http://www.7is7.com/otto/countdclock.html
//
// ALL RIGHTS RESERVED

// Javascript library for countdown clock generation.

// Global vars
var countdown_url = 'http://www.7is7.com/otto/countdown.html';
var popup_props = "'resizable=yes,width=250,height=360,scrollbars=no,left=50,top=50'";
// var popup_props = "'resizable=yes,width=250,height=365,scrollbars=no,status=no,toolbar=no,menubar=no,location=no,left=50,top=50'";
var framestyle_default='width:15.6em;height:22.8em;overflow:hidden;';
var preview_blanc='http://www.7is7.com/otto/countdown/preview.html';

// Generate a W3C compliant URL for the countdown clock
function generateURL_compliant(input) {
	return generateURL_raw(input).replace(/&/g,"&amp;");
}

// Generate query string arguments other than the date
function generateQsBase(input) {
	// Default values
	var mode='t';
	var cdir='down';
	var show='';

	// Set show
	if (typeof(input.show_years)!="undefined" && input.show_years.checked)
		show+='Y';
	if (typeof(input.show_months)!="undefined" && input.show_months.checked)
		show+='M';
	if (typeof(input.show_weeks)!="undefined" && input.show_weeks.checked)
		show+='W';
	if (typeof(input.show_days)!="undefined" && input.show_days.checked)
		show+='d';
	if (typeof(input.show_hrs)!="undefined" && input.show_hrs.checked)
		show+='h';
	if (typeof(input.show_min)!="undefined" && input.show_min.checked)
		show+='m';
	if (typeof(input.show_sec)!="undefined" && input.show_sec.checked)
		show+='s';

	if (typeof(input.mode)!="undefined" && input.mode.value)
		mode=escape(input.mode.value);
	if (typeof(input.cdir)!="undefined" && input.cdir.value)
		cdir=escape(input.cdir.value);

	// Return QS part
	return 'lang='+escape(input.lang.value)+'&show='+show+'&mode='+mode+'&cdir='+cdir+'&bgcolor='+escape(input.bgcolor.value)+'&fgcolor='+escape(input.fgcolor.value)+'&title='+escape(input.title.value);
}

// Generate query string arguments for the date part
function generateQsDate(input) {
	var hrs=0;
	var ts=24;
	var min=0;
	var sec=0;
	var lz='local';

	// Set ts and hrs
	if (typeof(input.hrs)!="undefined") {
		hrs=escape(input.hrs.value);
		if (typeof(input.tsap)!="undefined") {
			if ((input.tsap.value=="pm") || (input.tsap.value=="am")) {
				ts=12;
				if (12==hrs) { hrs=0; }
				if (input.tsap.value=="pm") { hrs=hrs-0+12; }
			}
		}
	}
	if (typeof(input.min)!="undefined") { min=escape(input.min.value); }
	if (typeof(input.sec)!="undefined") { sec=escape(input.sec.value); }
	if (typeof(input.tz)!="undefined") { tz=escape(input.tz.value); }

	// Return QS part
	return 'year='+escape(input.year.value)+'&month=' + escape(input.month.value)+'&date=' + escape(input.date.value)+'&hrs='+hrs+'&ts='+ts+'&min='+min+'&sec='+sec+'&tz='+tz;
}

// For a raw URL with just & (no &amp;)
function generateURL_raw(input) {
	// Define URL (with target date or free)
	if (
		typeof(input.year)!="undefined" &&
		(
			typeof(input.settarget)=="undefined" ||
			(
				typeof(input.settarget)!="undefined" &&
				input.settarget.checked!=false
			)
		)
	) {
		return countdown_url+'?'+generateQsDate(input)+'&'+generateQsBase(input);
	} else {
		return countdown_url+'?'+generateQsBase(input);
	}
}

// Replace text
function replace_text_ById(id,str) {
	if (
		document.getElementById(id) &&
		document.getElementById(id).firstChild
	) {
		document.getElementById(id).firstChild.nodeValue=unescape(str);
	}
}

// Replace attribute
// This causes problems:
// document.getElementById(id).getAttribute(attr)!=val
function replace_attr_ById(id,attr,val) {
	if (
		document.getElementById(id) &&
		document.getElementById(id).getAttribute(attr)
	) {
		document.getElementById(id).setAttribute(attr,val);
	}
}

// We are trying to match the entire name.
// Which means preceded by the start of the string or a seperator (pre)
// and followed by "=".
function getObjVal(obj,pre,sep,name) {
	name = name + "=";
	var start = obj.indexOf (name,0);
	if (start == -1) return start;
	if (start != 0) {
		name = pre + name;
		var start = obj.indexOf (name,0)
		if (start == -1) return start;
	}
	start += name.length;
	var end = obj.indexOf (sep,start);
	if (end == -1) end = obj.length;
	return trimWhitespace(unescape(obj.substring (start,end)));
}

// Use getObjVal to extract a value from the Query String.
function getQsVal(name) {
	return getObjVal(location.search.substring(1),"&","&",name);
}

// Use getObjVal to extract a cookie value.
function getCookieVal(name) {
	return getObjVal(document.cookie,"; ",";",name);
}

// Trim leading and trailing whitespace
function trimWhitespace(str) {
	return str.replace(/^\s+|\s+$/,'');
}

// Toggle target display
function toggleTargetDisplay() {
	if (document.getElementById('setTarget')) {
		if (document.getElementById('setTarget').checked==false) {
			document.getElementById('target').style.display='none';
			document.getElementById('t_msg1').style.display='inline';
			document.getElementById('t_msg2').style.display='none';
		} else {
			document.getElementById('target').style.display='block';
			document.getElementById('t_msg1').style.display='none';
			document.getElementById('t_msg2').style.display='inline';
		}
	}
}

// Update preview frame
function showPreview(input,preview,styleflag) {
	var url = generateURL_raw(input);
	replace_attr_ById(preview,'src',preview_blanc);
	if (styleflag) {
		replace_attr_ById(preview,'frameborder',setBorder(input));
		replace_attr_ById(preview,'style',fullStyle(input));
	} else {
		replace_attr_ById(preview,'frameborder',1);
		replace_attr_ById(preview,'style',framestyle_default);
	}
	replace_attr_ById(preview,'src',url);
}

// Code for bookmarklet
function generateBookmarklet(input,link,preview) {
	var url = generateURL_raw(input);
	var bookmarklet_url = "javascript:(function(){countdwin=window.open('" + escape(url) + "','_blank'," + popup_props + ");if(window.focus){countdwin.focus();setTimeout('countdwin.focus()',125)};void(0);})()";
	replace_attr_ById(link,'href',bookmarklet_url);
	replace_text_ById(link,input.title.value);
	var thecode_popup = lt + 'a href="' + bookmarklet_url + '"' + gt + input.title.value + lt + "/a" + gt;
	input.coderes.value=thecode_popup;
	showPreview(input,preview,false);
}

// Code for search plugin
function generateSearchPlugin(input,link,preview) {
	var qs = generateQsBase(input);
	var searchplugin_url = "javascript:if(typeof(window.external)=='object'){try{window.external.AddSearchProvider('http://www.7is7.com/software/firefox/plugins/countdown.php?"+escape(qs)+"');}catch(e){alert('Your%20browser%20does%20not%20support%20OpenSearch%21');}};void(0);";
	replace_attr_ById(link,'href',searchplugin_url);
	replace_text_ById(link,input.title.value);
	var thecode_popup = lt + 'a href="' + searchplugin_url + '"' + gt + input.title.value + lt + "/a" + gt;
	input.coderes.value=thecode_popup;
	showPreview(input,preview,false);
}

// Code generation for Pop-up countdown clock
function generateCodePopup(input,preview) {
	var url = generateURL_compliant(input);
	var thecode_popup = lt + 'a href="' + url + '" onclick="cdwin=window.open(' + "this.getAttribute('href'),'_blank'," + popup_props + ");if(window.focus)cdwin.focus();" + 'return(false);"' + gt + input.title.value + lt + "/a" + gt;
	input.coderes.value=thecode_popup;
	showPreview(input,preview,false);
}

// Code generation for iframe countdown clock
function generateCodeIframe(input,preview) {
	var url = generateURL_compliant(input);
	var style = fullStyle(input);
	var border = setBorder(input);
	// if (input.border.checked) { border = 1 } else { border = 0 }
	var thecode_iframe = lt+'iframe src="'+url+'" width="250" height="365" scrolling="no" frameborder="'+border+'" style="'+style+'"'+gt+lt+'a href="'+url+'"'+gt+input.title.value+lt+'/a'+gt+lt+'/iframe'+gt;
	input.coderes.value=thecode_iframe;
	showPreview(input,preview,true);
}

// Code generation for object countdown clock
// This is not well supported by Internet Explorer not even in IE7
// in spite of this being the standard compliant solution for strict pages.
// function generateCodeObject(input,preview) {
	// var url = generateURL_compliant(input);
	// var style = fullStyle(input);
	// var border = setBorder(input);
	// var thecode_object = lt + 'object type="text/html" standby="' + input.title.value  + '" data="' + url + '" width="250" height="365" style="border:'+border+';'+style+'"' + gt + lt + 'a href="' + url + '"' + gt + input.title.value + lt + '/a' + gt + lt + '/object' + gt
	// input.coderes.value = thecode_object;
	// showPreview(input,preview,true);
// }

// Code generation for a raw URL
function generateCodeURL_raw(input,preview) {
	var url=generateURL_raw(input);
	input.coderes.value=url;
	showPreview(input,preview,false);
}

// Code generation for a W3C compliant URL
function generateCodeURL_compliant(input,preview) {
	var url=generateURL_compliant(input);
	input.coderes.value = url;
	showPreview(input,preview,false);
}

// Code generation for a BBcode link
function generateCodeBBcode(input,preview) {
	var url=generateURL_raw(input);
	var thecode_bbcode='[url='+url+']'+input.title.value+'[/url]';
	input.coderes.value=thecode_bbcode;
	showPreview(input,preview,false);
}

// Code generation for a short link
// External Service for shortening URLs
// The following code was adapted from code made available by xrl.in
function getShorturl(input,preview,mtype) {
	var url=generateURL_raw(input);
	input.coderes.value="Retrieving short URL... please wait";
	showPreview(input,preview,false);
	var httpRequest;
	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
		httpRequest = new XMLHttpRequest();
		if (httpRequest.overrideMimeType) {
			httpRequest.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { // IE
		try {
		httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!httpRequest) {
		input.coderes.value='Error: Cannot create an XMLHTTP instance. Please use another option.'; return;
	}
	httpRequest.onreadystatechange = function() { handleXrlResponse(httpRequest,input,mtype); };
	httpRequest.open('GET', '/otto/countdown/ext-shorturl.php?pro=' + input.provider.value + '&url=' + encodeURIComponent(url), true);
	httpRequest.send('');
}

function handleXrlResponse(httpRequest,input,mtype) {
	if (httpRequest.readyState == 4) {
		if (httpRequest.status == 200) {
			var shorturl = httpRequest.responseText;
			if (shorturl!='!' && shorturl.length>0 ) {
				if (mtype == 'tweet' ) {
					input.coderes.value=input.title.value+" "+shorturl+" #countdown";
				} else {
					input.coderes.value=shorturl;
				}
			} else { input.coderes.value='Error: Invalid code received. Please use another option.'; }
		} else { input.coderes.value='Error: There was a problem with the request. Please use another option.'; }
	}
}
// End of short URL code

function generateCodeURL_short(input,preview) {
	getShorturl(input,preview,"short");
}

function generateCodeURL_tweet(input,preview) {
	getShorturl(input,preview,"tweet");
}

// Return style string
function setBorder(input) {
	if (input.border.checked) { return 1; } else { return 0; }
}

// Return style string
function fullStyle(input) {
	var style;
	if (input.style.value && ''!=input.style.value) {
		style='overflow:hidden;'+input.style.value;
	} else {
		style=framestyle_default;
	}
	return style;
}

// Set initial title according to cdir value
function updateTitle(input) {
	if (typeof(input.cdir)!="undefined" && input.cdir.value=="up") {
		if (input.title.value=="Countdown To") {
			input.title.value="Time Elapsed Since";
		}
	} else {
		if (input.title.value=="Time Elapsed Since") {
			input.title.value="Countdown To";
		}
	}
}

// We *try* to check if number is a number
function isNumber(number) {
	if (isFinite) {
		if (!isFinite(number)) return 0;
	} else if (isNaN) {
		if (!isNaN(number)) return 0;
	}
	return 1;
}

// getFull year returns the proper year
// old browsers use getYear implemented here to work until 2070.
function retYear(now) {
	var year = 2000;
	if (now.getFullYear) {
		year = now.getFullYear();
	} else if (now.getYear) { 
		year = now.getYear() % 100;
		year += (year<70) ? 2000 : 1900;
	}
	return year;
}

// Set Value for given field
// Don't set if value == -1
function setValue(i,val) {
	if (-1!=val && i) i.value=val;
}

// Set Selected for given field
// Don't set if val == -1
function setSelected(sel,val) {
	if (-1!=val && (a=document.getElementById(sel+val))) a.selected=true;
}

// Initialise target date
// Preset certain values based on the following priority rules:
// 1. Preset values (preset in the page).
// 2. Values entered via the query string.
// 3. Values found in cookies.
// 4. Default values.
function setup_genform (input,previewframe) {
	now=new Date();
	// Initialize values
	title=-1;
	year=-1;
	mon=-1;
	dat=-1;
	hrs=-1;
	min=-1;
	sec=-1;
	ts=-1;
	tz=-1;
	lang=-1;
	cdir='down';
	mode='t';
	bgcolor='#CCFFFF';
	fgcolor='#000000';
	style='width:15.6em;height:22.8em;';

	if ("undefined"==typeof(preset_target_name)) {
		// If location.search exists and the year is set we assume that
		// the date needs to be set from the querystring.
		// Otherwise we check the cookies.
		if (location.search) {
			// Risky to allow people to externally modify the title
			title=getQsVal("title");
			cdir=getQsVal("cdir");
			ts=getQsVal("ts");
			tz=getQsVal("tz"); // datestr case needs looking into.
			lang=getQsVal("lang");
			mode=getQsVal("mode");
			bgcolor=getQsVal("bgcolor");
			fgcolor=getQsVal("fgcolor");
			style=getQsVal("style");
			if (-1!=getQsVal("datestr")) {
				var datestr=getQsVal("datestr");
				datestr=datestr.replace(/\+/g," ");
				target=new Date(Date.parse(datestr));
				if (!isNumber(target.getTime())) alert (datestr+" is not a valid date!");
				year=target.getFullYear();
				mon=target.getMonth()+1;
				dat=target.getDate();
				hrs=target.getHours();
				min=target.getMinutes();
				sec=target.getSeconds();
			} else if ((-1!=getQsVal("year"))||(-1!=getQsVal("next"))) {
				year=getQsVal("year");
				mon=getQsVal("month");
				dat=getQsVal("date");
				hrs=getQsVal("hrs");
				min=getQsVal("min");
				sec=getQsVal("sec");
			}
		} else if (document.cookie) {
			year=getCookieVal("year");
			mon=getCookieVal("month");
			dat=getCookieVal("date");
			hrs=getCookieVal("hrs");
			min=getCookieVal("min");
			sec=getCookieVal("sec");
			// Theoretical - no way to set these cookies yet
			ts=getCookieVal("ts");
			tz=getCookieVal("tz");
			title=getCookieVal("title");
			lang=getCookieVal("lang");
		}

		// Set Default values if values are not appropriate
		if (year==-1 || year.length<1 || (year != "next" && !isNumber(year))) year=retYear(now)+1;
		if (mon==-1 || mon.length<1 || !isNumber(mon)) mon=1;
		if (dat==-1 || dat.length<1 || !isNumber(dat)) dat=1;
		if (hrs==-1 || hrs.length<1 || !isNumber(hrs)) hrs=0;
		if (min==-1 || min.length<1 || !isNumber(min)) min=0;
		if (sec==-1 || sec.length<1 || !isNumber(sec)) sec=0;
		if (ts!="am" && ts!="pm") ts="24";
		if (tz==-1 || tz!="UTC" && !isNumber(tz)) tz="local";
		// if (title==-1) title="Countdown To";
		// if (lang==-1 || lang.length<1) lang="en";

	} else {
		setTarget(preset_target_name);
	}

	if (input) {
		setValue(input.title,title);
		setValue(input.year,year);
		setValue(input.month,mon);
		setValue(input.date,dat);
		setValue(input.hrs,hrs);
		setValue(input.min,min);
		setValue(input.sec,sec);
		// if (i=input.title) i.value=title;
		// if (i=input.year) i.value=year;
		// if (i=input.month) i.value=mon;
		// if (i=input.date) i.value=dat;
		// if (i=input.hrs) i.value=hrs;
		// if (i=input.min) i.value=min;
		// if (i=input.sec) i.value=sec;
		setSelected("cdir_",cdir);
		setSelected("tsap_",ts);
		setSelected("tz_",tz);
		setSelected("lang_",lang);
		setSelected("mode_",mode);
		// if (a=document.getElementById("tsap_"+ts)) a.selected=true;
		// if (a=document.getElementById("tz_"+tz)) a.selected=true;
		// if (a=document.getElementById("lang_"+lang)) a.selected=true;
		setValue(input.mode,mode);
		setValue(input.bgcolor,bgcolor);
		setValue(input.fgcolor,fgcolor);
		setValue(input.style,style);
		updateTitle(input); // Possible correction of title if cdir changed
	}

	// Show the preview if set
	showPreview(input,previewframe,false);
}

// Update Target
// function used in sample pages
function updTarget(target_name) {
	preset_target_name=target_name;
	setup_genform(document.genform,'preview');
}

// Starting Stuff
function start() {
	init(); // from sitescript.js
	setup_genform(document.genform,'preview');
	toggleTargetDisplay();
}

// Library loaded
var loaded_countdclock_js = 1;
var countdclock_version="countdclock_2.0.11";

window.onload=start;

// That's All Folks!
