// Copyright WorldTimeEngine.com (c) 2008 - this script is not to be used without permission

/** LOAD APPROPRIATE LANGUAGE/LOCALE */

function setLocale(locale) {

	// Load the appropriate language file
	var loc = "/resources/js/lang/" + locale + ".js";

	var script  = document.createElement('script');
	script.type = "text/javascript";
	script.src  = loc;
	script.setAttribute("charset", "utf-8");

	document.getElementsByTagName('head')[0].appendChild(script);
	script  = null;
}

/** SEARCH FUNCTIONS */

function initialiseSearch(date) {
	var anchors = getElements();
	for (var i=0; i<anchors.length; i++){		
		if(anchors[i][0]=='input' && anchors[i][1]=='searchbox') {
			searchId = anchors[i][2];
			searchComponent = document.getElementById(searchId);
			
			//fill_textbox(searchId); // fill textbox on load
			//initialiseAutoComplete(searchId);
		}
	}
	// set the time if we have a time box
	if(date>1) selectToday('date-sel', date);

}

/*function initialiseAutoComplete(id) {
	var options = { script: function (input) { return ('autocomplete.php?place='+input); }, callback: function (obj) {  }	};	
	var xml=new AutoComplete(id,options);
	return true;
}*/

function getSearchText() { if (typeof(searchLocale) === "object") { return searchLocale.defaultText;	} return "please enter a place or co-ordinates"; }
function clear_textbox(id) { if (document.getElementById(id).value == getSearchText()) { document.getElementById(id).value = ""; document.getElementById(id).style.color = '#000000'; } }
function fill_textbox(id) { if (!document.getElementById(id).value || document.getElementById(id).value == getSearchText()){ document.getElementById(id).value =  getSearchText(); document.getElementById(id).style.color = '#666666'; } }
function selectToday(id, time) { today = new Date(time); today.setTime(today.getTime() + (today.getTimezoneOffset() * 60000)); todayDay = today.getDate()-1; todayMonth = today.getMonth(); todayYear = fourdigits(today.getYear()) - 2005; todayHours = today.getHours()+1; todayMinutes = Math.floor((today.getMinutes())/5) + 1; document.getElementById(id+'-dd').selectedIndex = todayDay; document.getElementById(id+'-mm').selectedIndex = todayMonth; document.getElementById(id).selectedIndex = todayYear; document.getElementById(id+'-h').selectedIndex = todayHours; document.getElementById(id+'-i').selectedIndex = todayMinutes; }
function fourdigits(number)	{ return (number<1000) ? number + 1900 : number; }
function enableDate() { document.timeForm.d.disabled=false; document.timeForm.m.disabled=false; document.timeForm.y.disabled=false; document.timeForm.h.disabled=false; document.timeForm.i.disabled=false; }
function disableDate() { document.timeForm.d.disabled=true; document.timeForm.m.disabled=true; document.timeForm.y.disabled=true; document.timeForm.h.disabled=true; document.timeForm.i.disabled=true; }

function addPlaceBox(form,id) {
	if(id>4) return;
	var searchBox  = document.createElement('input');
	searchBox.type = "text";
	searchBox.name = "q" + id;
	searchBox.id = "q" + id;
	searchBox.value = "";
	searchBox.size = 60;
	searchBox.maxlength = 300;
	if (navigator.appVersion.indexOf("MSIE")==-1) {
		searchBox.setAttribute('class', 'searchbox');
	} else {
		searchBox.setAttribute('className', 'searchbox');
	}
	searchBox.setAttribute('onblur', "fill_textbox('q" + id + "')");
	searchBox.setAttribute('onkeypress', "clear_textbox('q" + id + "')");
	searchBox.setAttribute('onclick', "clear_textbox('q" + id + "')");
	document.getElementById(form).appendChild(searchBox);
	if(id<4) {
		var addPlaceButton  = document.createElement('text');
		addPlaceButton.innerHTML = '<br /><a href="javascript:addPlaceBox(\''+form+'\', ' + ++id + ')" onclick="hide()">Add Place Box</a>';
		document.getElementById(form).appendChild(addPlaceButton);
	}

}


/** LIKE OUR SITE FUNCTIONS */

//Contents for menu 1
var resultsMenu=new Array()
resultsMenu[0]='<a href="/bookmark_us">Bookmark Us</a>';
resultsMenu[1]='<span class="referPage"><a href="/refer">Tell a Friend</a></span>';
resultsMenu[2]='<a href="/desktop_shortcut">Desktop Shortcut</a>';
resultsMenu[3]='<a href="/developer_resources">Developer Resources</a>';
resultsMenu[4]='<a href="/faq#link_to_us">Link To Us</a>';

var mainMenu=new Array()
mainMenu[0]='<a href="/bookmark_us">Bookmark Us</a>';
mainMenu[1]='<span class="referPage"><a href="/refer?url=wte">Tell a Friend</a></span>';
mainMenu[2]='<a href="/desktop_shortcut">Desktop Shortcut</a>';
mainMenu[3]='<a href="/developer_resources">Developer Resources</a>';
mainMenu[4]='<a href="/faq#link_to_us">Link To Us</a>';

var menuwidth='165px' //default menu width
var menubgcolor='lightyellow'  //menu bgcolor
var disappeardelay=250  //menu disappear speed onMouseout (in miliseconds)
var hidemenu_onclick="yes" //hide menu when user clicks within menu?

/////No further editting needed

var ie4=document.all
var ns6=document.getElementById&&!document.all

if (ie4||ns6)
document.write('<div id="likeoursite" style="visibility:hidden;width:'+menuwidth+';background-color:'+menubgcolor+'" onMouseover="clearhidemenu()" onMouseout="dynamichide(event)"></div>')

function getposOffset(what, offsettype){
var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
var parentEl=what.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
//  drop-up menu so change offset
if(offsettype!="left") totaloffset -= 122;
return totaloffset;
}


function showhide(obj, e, visible, hidden, menuwidth){
if (ie4||ns6)
dropmenuobj.style.left=dropmenuobj.style.top="-500px"
if (menuwidth!=""){
dropmenuobj.widthobj=dropmenuobj.style
dropmenuobj.widthobj.width=menuwidth
}
if (e.type=="click" && obj.visibility==hidden || e.type=="mouseover")
obj.visibility=visible
else if (e.type=="click")
obj.visibility=hidden
}

function iecompattest(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function clearbrowseredge(obj, whichedge){
var edgeoffset=0
if (whichedge=="rightedge"){
var windowedge=ie4 && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-15 : window.pageXOffset+window.innerWidth-15
dropmenuobj.contentmeasure=dropmenuobj.offsetWidth
if (windowedge-dropmenuobj.x < dropmenuobj.contentmeasure)
edgeoffset=dropmenuobj.contentmeasure-obj.offsetWidth
}
else{
var topedge=ie4 && !window.opera? iecompattest().scrollTop : window.pageYOffset
var windowedge=ie4 && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
dropmenuobj.contentmeasure=dropmenuobj.offsetHeight
if (windowedge-dropmenuobj.y < dropmenuobj.contentmeasure){ //move up?
edgeoffset=dropmenuobj.contentmeasure+obj.offsetHeight
if ((dropmenuobj.y-topedge)<dropmenuobj.contentmeasure) //up no good either?
edgeoffset=dropmenuobj.y+obj.offsetHeight-topedge
}
}
return edgeoffset
}

function populatemenu(what){
if (ie4||ns6)
dropmenuobj.innerHTML=what.join("")
}


function dropdownmenu(obj, e, menucontents, menuwidth){
if (window.event) event.cancelBubble=true
else if (e.stopPropagation) e.stopPropagation()
clearhidemenu()
dropmenuobj=document.getElementById? document.getElementById("likeoursite") : likeoursite
populatemenu(menucontents)

if (ie4||ns6){
showhide(dropmenuobj.style, e, "visible", "hidden", menuwidth)
dropmenuobj.x=getposOffset(obj, "left")
dropmenuobj.y=getposOffset(obj, "top")
dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(obj, "rightedge")+"px"
dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+"px"
}

return clickreturnvalue()
}

function clickreturnvalue(){
if (ie4||ns6) return false
else return true
}

function contains_ns6(a, b) {
while (b.parentNode)
if ((b = b.parentNode) == a)
return true;
return false;
}

function dynamichide(e){
if (ie4&&!dropmenuobj.contains(e.toElement))
delayhidemenu()
else if (ns6&&e.currentTarget!= e.relatedTarget&& !contains_ns6(e.currentTarget, e.relatedTarget))
delayhidemenu()
}

function hidemenu(e){
if (typeof dropmenuobj!="undefined"){
if (ie4||ns6)
dropmenuobj.style.visibility="hidden"
}
}

function delayhidemenu(){
if (ie4||ns6)
delayhide=setTimeout("hidemenu()",disappeardelay)
}

function clearhidemenu(){
if (typeof delayhide!="undefined")
clearTimeout(delayhide)
}

if (hidemenu_onclick=="yes")
document.onclick=hidemenu


/* PREFERENCES (SESSION MANAGEMENT) */

function preferences(id, action, parameters) {

	this.serverUrl = '/session/index.php';
	this.id = id;
	this.action = action;
	this.params = '';
	this.result = -1;
	this.data = '';
	var o = this;

	// on init, populate the parameters info
	for(var i=0; i<parameters.length; i++) {
		o.params += parameters[i];
		if (i<parameters.length-1) {
			o.params += ',';
		}
	}

	o.execute = function() {
		if (!this.ajaxRequest()) o.result = 0;
	};

	o.ajaxRequest = function(){
		try{
			var req = new Ajax.Request(o.serverUrl,{
			onSuccess : o.ajaxResponse,
		  	method : "get",
		  	parameters : "f=" + o.action + "&p=" + o.params
			});
		} catch(e){ return false; }
		return true;
	};

	o.ajaxResponse = function(data){
		o.data = data.responseText;
		if(o.data) {
			o.result = 1;
		} else {
			o.result = 0;
		}		
		ajaxResult(o);
	};

	o.getResult = function() {
		switch(o.result) {
			case 0:
				return 'failed';
			case 1:
				return 'success';
			default:
				return false;
		}
	};

	o.getResponseData = function() {
		return o.data;
	}

	o.getID = function() {
		return o.id;
	};

	o.getAction = function() {
		return o.action;
	};

	o.execute();

};

function PreferencesController(id) {
	var anchors = getElements();
	for (var i=0; i<anchors.length; i++){		
		if((anchors[i][0]=='div' || anchors[i][0]=='span') && (anchors[i][1].search(/preferences/g)!=-1) && anchors[i][2]==id) {
			var objectId = anchors[i][2];
			var objectOptions = anchors[i][1].split(' ');
			objectOptions = ArraySplice(objectOptions, 0);
			var action = objectOptions[0]; // action
			objectOptions = ArraySplice(objectOptions, 0);
			var parameters = objectOptions; // parameters array

			// perform action
			o = new preferences(id, action, parameters);
			
			// set 'processing' action state (remove the link to this action)
			switch (o.getAction()) {
				case 'setDefaultLocation':
					document.getElementById('sethome-' + o.getID()).innerHTML = '';
					break;
				case 'removeDefaultLocation':
					document.getElementById('removehome-' + o.getID()).innerHTML = '';
					break;
				default:
					break; // do nothing
			}
						
			break; // only one update per request
		}	
	}
}

function ajaxResult(o) {

	switch (o.getAction()) {
		case 'setDefaultLocation':
			if (navigator.appVersion.indexOf("MSIE")==-1) {
				document.getElementById('sethome-' + o.getID()).setAttribute('class', 'sethome-' + o.getResult() );
			} else {
				document.getElementById('sethome-' + o.getID()).setAttribute('className', 'sethome-' + o.getResult() );
			}
			break;
		case 'removeDefaultLocation':
			if (navigator.appVersion.indexOf("MSIE")==-1) {
				document.getElementById('removehome-' + o.getID()).setAttribute('class', 'removehome-' + o.getResult() );
			} else {
				document.getElementById('removehome-' + o.getID()).setAttribute('className', 'removehome-' + o.getResult() );
			}
			break;
		default:
			break; // do nothing
	}
	
}

function prefs(id) {
	PreferencesController(id);
}

function ArraySplice(array,index) {
	var result = new Array();
	for (var i=0; i<array.length; i++) {
		if(i==index) continue;
		result.push( array[i] );
	}
	return result;
}

/* ONLOAD CONTROLLER */

var components = new Array(); // [0] 'locale' [1] 'search_loaded', [2] 'maps_js_loaded', [3] 'clock_js_loaded'
var elements = new Array();

function registerComponents(search, maps, clock) {
	components.push(search, maps, clock);
}

function getElements() {
	if(elements.length<1) {
		var elementTypes = new Array('div', 'span', 'input'); // document elements to load in to elements array
		for (var x=0; x<elementTypes.length; x++) {
			if (!document) { setTimeout('', 500); }
			if (!document.getElementsByTagName){ return; }
			var anchors = document.getElementsByTagName(elementTypes[x]);
			// loop through all anchor tags of this type
			if(anchors) {
				for (var i=0; i<anchors.length; i++){
					var anchor = anchors[i];
					// get the class info...
					classAttribute = false;
					if (navigator.appVersion.indexOf("MSIE")==-1) {
						classAttribute = String(anchor.getAttribute("class"));
					} else {
						classAttribute = String(anchor.getAttribute("className"));
					}
					// get the id info...
					idAttribute = false;
					idAttribute = String(anchor.getAttribute("id"));

					elements.push(new Array(elementTypes[x], classAttribute, idAttribute));
				}
			}
		}
	}
	return elements;
}

function init() {
	// initialise components
	if(components[0]) initialiseSearch(components[0]);
//	if(components[1]) initialiseMaps();
//	if(components[2]) initialiseClock();
}

Event.observe(window, 'load', init);
