// Copyright WorldTimeEngine.com 2008, use of this script is PROHIBITED without permission

//
//	Global Variables
//
var clock_js_loaded = true; // variable to check onLoad

var srvClockOffset = 0;

var clockArray = new Array;
var clockTimeOfDay = new Array;
var clockStarted = false;

// Defaults should the locale file not load
var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var day = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];

// -------------------------------------------------------------------------

var WTClock = {

	// initialisation
	initialize: function() {
	},

	// add a location to the clock
	addLocation: function( id, offset, utc) {
		// add clock to clockArray
		clockArray.push(new Array(id, offset, utc));			
	},

	// starts the clock(s) on the page
	start: function() { 
	
		var anchors = getElements();
		
		for (var i=0; i<anchors.length; i++){

			if(anchors[i][0]=='div' || anchors[i][0]=='span') {
				// split the class field to [1]->id, [2]->tzid
				var classArray = anchors[i][1].split(' ');
				if (classArray.length<3 || !classArray[0].toLowerCase().match('wtclock')) continue; // if we don't have 2 parts then we have an error
				var utc=false; if (classArray.length==4) utc=classArray[3];

				// add this location to clocks
				WTClock.addLocation(classArray[1], classArray[2], utc); // id, zoneoffset, utc

			}

		}
		
		// now start the clock(s)
		clockStarted = true;
		WTClock.doTime(true);
		
	},

	/* doTime actually performs the time */
	doTime: function(firstRun) {
		var now = syncSrv.addSrvOffset(syncSrv.getNow());
			if(!firstRun) {
				for(var i = 0; i < clockArray.length; i++){				
					// update the current clock time
					WTClock.showTime(i, now);
				}
			}
		setTimeout("WTClock.doTime(false)", 1000);
	},

	// updates the clock associated to passed id
	showTime: function(i, now) {

		// Parameter mapping 
		var t = now + (clockArray[i][1])*1000; /* server time + current offset */
		// Get id of clockArray[i]
		var id = clockArray[i][0];

		// format a date and time
		var n=new Date();
		n=new Date(t + (n.getTimezoneOffset()*60000));

		// set clock display
		document.getElementById(id).innerHTML = gethr12(n.getHours()) + ":" + (n.getMinutes()<10 ? "0" : "") + n.getMinutes() + ":" + (n.getSeconds()<10 ? "0" : "") + n.getSeconds() + " " + (n.getHours()>11 ? "PM" : "AM") + " " + WTClock.getBridge() + " " + WTClock.getDay(n.getDay()) + ", " + WTClock.getMonth(n.getMonth()) + " " + n.getDate() + ", " + fourdigits(n.getYear());

		var n_h = n.getHours();

		//if(firstRun) 

		if(clockArray[i][2]<1) {
			if(clockTimeOfDay.length<(i+1) || clockTimeOfDay[i]!=n_h) {
		
				// time of day	
				var timeOfDay='';
				var timeOfDayDesc='';
				switch (true) {
					case (n_h<=6):
					case (n_h>22):
						timeOfDay = "Night";
						timeOfDayDesc = "11PM - 7AM";
						break;
					case (n_h>6 && n_h<=7):
						timeOfDay = "Early_Morning";
						timeOfDayDesc = "7AM - 8AM";
						break;
					case (n_h>7 && n_h<=11):
						timeOfDay = "Morning";
						timeOfDayDesc = "8AM - 12PM";
						break;
					case (n_h>11 && n_h<=17):
						timeOfDay = "Afternoon";
						timeOfDayDesc = "12PM - 6AM";
						break;	
					case (n_h>17 && n_h<=22):
						timeOfDay = "Evening";
						timeOfDayDesc = "6PM - 11PM";
						break;
				}
				
				clockTimeOfDay[i] = n_h; // update clock attr

				WTClock.updateTimeOfDay(id,timeOfDay); // update style
				updateMarker(Math.floor(i/2), timeOfDayDesc); // update maps
			}
		
		}

	},

	updateTimeOfDay: function(id, timeOfDay) {
		if (navigator.appVersion.indexOf("MSIE")==-1) {
			document.getElementById(id).setAttribute("class", "time " + timeOfDay);
		} else {
			document.getElementById(id).setAttribute("className", "time " + timeOfDay);
		}
	},

	getDay: function(i) {
		// offset starts at Sunday, change so it starts at Monday
		if(--i<0) i=6;
		
		if(typeof(clockLocale)=="object") {
			return clockLocale.fullDay[i];
		}
		return day[i];
	},

	getMonth: function(i) {
		if(typeof(clockLocale)=="object") {
			return clockLocale.months[i];
		}
		return months[i];
	},

	getBridge: function() {
		if(typeof(clockLocale)=="object") {
			return clockLocale.bridge;
		}
		return 'on';
	}
}

// -------------------------------------------------------------------------

var syncSrv = {

	serverUrl: "/sync/index.php",

	sync: function() {
		syncSrv.getSrvTime();
		setTimeout('syncSrv.sync()', 120000); // redo every 2 minutes
	},

	getSrvTime: function(){
		try{
			var req = new Ajax.Request(syncSrv.serverUrl,{
			onSuccess : syncSrv.parseSrvRes,
		  	method : "get",
		  	parameters : "t=" + syncSrv.getNow()
			});
		} catch(e){ return false; }
	},

  	parseSrvRes: function(data){
		var origtime = parseInt(data.responseText.split(":")[0]);
		var offset = parseInt(data.responseText.split(":")[1]);
		var delay = ((syncSrv.getNow() - origtime) / 2);
		srvClockOffset = offset - delay;
	},
	
	getNow: function(){
    	var date = new Date();
    	return (date.getTime() + (date.getTimezoneOffset() * 60000));
	},
	
	addSrvOffset : function(timeStamp){
		var time = 0;
		if(srvClockOffset) {
			time = timeStamp + srvClockOffset;
		} else {
			time = timeStamp;	
		}
    	return time;
	}
	
}

// -------------------------------------------------------------------------

/* formats hours from 24 to 12-hour format */
function gethr12(hr24) {	
	if(hr24>11) hr24-=12;
	if(hr24==0) hr24=12;
	return hr24;
}

/* formats the returned date appropriately */
function fourdigits(number)	{ 
	return (number < 1000) ? number + 1900 : number; 
}

// -------------------------------------------------------------------------

function initialiseClock() { 
	WTClock.start(); 
}
Event.observe(window, 'load', initialiseClock);


syncSrv.sync();
