// Check the browser
var BROWSER;
if (document.all) {
	BROWSER = "IE";
 } else {
	BROWSER = "OTHER";
 }

function text(node) {
	return node && node.firstChild ? node.firstChild.nodeValue : '';
}

function getElementByTagName(doc,name) {
	var nodes = doc.getElementsByTagName(name);
	if (!nodes || nodes.length == 0) return 0;
	return nodes[0];
}

function $n(tag,on) {
	var e = document.createElement(tag);
	if (on) on.appendChild(e);
	return e;
}

function $t(text,on) {
	var e = document.createTextNode(text);
	if (on) on.appendChild(e);
	return e;
}


// Constants
//var VOIDLINK = "#";
var VOIDLINK = "javascript:void(0)";



function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=400,left = 262,top = 284');");
}

function popUpBugReport() {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open('bugreport.php', '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=600,height=600,left = 262,top = 284');");
}

function newWindow(URL,id) {
	if (!id) {
		day = new Date();
		id = day.getTime();
	}
	eval("page" + id + " = window.open(URL, '" + id + "', '');");
}

function newWindowFromText(s) {
t="<";
 CONTENT = '<html><body>' + s + '</body></html>';
 pop = window.open("","",'scrollbars=yes,resizable=yes,toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0');
 pop.document.open();
 pop.focus();
 pop.document.write(CONTENT);
 pop.document.close();

}


// ====================================================================
//       URLEncode and URLDecode functions
//
// Copyright Albion Research Ltd. 2002
// http://www.albionresearch.com/
//
// You may copy these functions providing that 
// (a) you leave this copyright notice intact, and 
// (b) if you use these functions on a publicly accessible
//     web site you include a credit somewhere on the web site 
//     with a link back to http://www.albionresarch.com/
//
// If you find or fix any bugs, please let us know at albionresearch.com
//
// SpecialThanks to Neelesh Thakur for being the first to
// report a bug in URLDecode() - now fixed 2003-02-19.
// ====================================================================
function urlencode( plaintext )
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
};

function urldecode( encoded )
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
	 return plaintext;
};

function ajaxDump(url) {
	ajaxText(url, function(s) {alert(s);});
}

function ajaxXML(url, f, e) {
	//ajax(url, f, "xml", true, e);
	ajax(url, {f: f, fType: "xml", asynch: true, e: e});
}

function ajax(url, opts) {

	var f = opts['f'];
	var fType = opts['fType'];
	var asynch = opts['asynch'];
	var e = opts['e'];
	var type = opts['type'];
	var counterF = opts['counter'];
	var counterMsg = opts['counterMsg'];
	var debug = opts['debug'];
	var html = opts['html'];
	
	// defaults
	if (!fType) fType = 'xml';
	if (!type) type = 'GET';
	if (!asynch) asynch = true;
	if (!f) f = function(x) {}
	if (!e && counterF) e = counter(counterF,counterMsg);
	if (!e) e = function(x) {}

	var request = createRequest(); //GXmlHttp.create();
	try {
		if (!html) {
			if (request.overrideMimeType) {
				request.overrideMimeType('text/xml');
			}
		}
		request.open(type, url, asynch);
	} catch (ex) {
		warn('trying to override mime type', ex);
		return;
	}
	
	 request.onreadystatechange = function() {	
		 e(request.readyState);
		 if (request.readyState == 4) {
			 if (fType == "xml") {
				 var xml;
				 if (BROWSER == "IE") {
					 xml = GXml.parse(request.responseText);
				 } else {
					 xml = request.responseXML;
				 }
				 if (xml) {
					 var doc = xml.documentElement;
					 f(doc);
				 }
			 } else {
				 f(request.responseText);
			 }
	
	 }
		 
	};
	request.send(null);
}

function ajaxText(url, f, e) {
	//ajax(url, f, "text", true);
	ajax(url, {f: f, fType: "text", asynch: true});
}

function createRequest() {
	return KATHYMAPS_LOCAL ? createRequestOffline() : createRequestOnline();
}

// true if we're on the index page
function isIndex() {
	var page = document.location.href.replace(/.*\//g,'').replace(/\?.*/,'');
	return page == '' || page == 'index.php';
}

function createRequestOnline() {
	try {
		return GXmlHttp.create();
	} catch (e) {}
	return createRequestOffline();
}

function createRequestOffline() {
  try {
    request = new XMLHttpRequest();
  } catch (trymicrosoft) {
    try {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (othermicrosoft) {
      try {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (failed) {
        request = false;
      }
    }
  }

  if (!request)
    alert("Error initializing XMLHttpRequest!");

	return request;
}

function warn(msg,str) {
	//TODO: for now
	alert("*** WARNING *** " + msg + ":" + str);
}

function reload() {
	window.location.href = document.location.href + '?';
	alert("TODO:reload");
}

function unroll(arr) {
	var s = "{";
	//for (i in arr) s += i + "=>"+ arr[i] + ", ";
	$A(arr).each(function(a) {s += i + "=>"+ a + ", ";});
	s += "}";
	return s;
}

function setInnerHTML(tag, val) {
	var el = e(tag);
	if (!el) {
		if (false && DEBUG) alert("cannot find element '" + tag + "'"); //todo
	} else {
		el.innerHTML = val;
	}
}

function randomHello() {
	var ss = new Array
		(
		 "Hello","Salut","Hallo","Moin Moin","Hola","Dobrý deň","Helo","Ohaio gozaimasu","Ciao","Hej","As-salaam-aleykum","Sabbah-el-hair","Salaam","Namaste","Ahn nyeong ha se yo","Hallo","Pree-vyet","Ni Hao","Shalom Aleychem","G'day","Hei","Oi","Hej","Mingalarbar","Merhaba","Labas","Chao","Kumusta Ka","Saluton","Vanakkam","Jambo","Mbote","Selamat Pagi","Namaskar","Czesc","Aloha","Sawadi-ka","Jo napot","Dobry den","Dobriy ranok","Labdien","Hyvää päivää","Yia sou","Ellohay","Namaskkaram","Adaab","Baagunnara","Moni Bambo!","Wa uhala po, Meme?","Niltze, xs"
		 );
	var r = Math.floor(Math.random()*ss.length);
	var s = ss[r];
	return s;
}

function e(tag) {
	return document.getElementById(tag);
}

function ns(tag) {
	return document.getElementsByTagName(tag);
}

function q(s) {
	var quote = "'";
	return quote + escape(s) + quote;
}

function voidHref() {
	return "href=\"" + VOIDLINK + "\"";
}


function dbno(span) {if (DEBUG) debug(span, '<font color=red> NO</font>');}
function dbyes(span) {if (DEBUG) debug(span, '<font color=green>YES</font>');}

function debug(span, msg) {
	msg = "" + msg;
	if (DEBUG) {
		if (debugWindow) {
			el = debugWindow.document.getElementById(span);
			if (el && el != '') {
				// be nice since this is html
				var s = replaceAll(msg, "\n", "<br/>");
				el.innerHTML = s;
			}
		}
	}
}

function note(msg) {

	//debug('debugspan', msg);
}

var debugWindow;
function debugOnLoad() {
	if (DEBUG) {
		var debugURL = "http://" + KATHYMAPS_DOMAIN + "/debugwindow.php";
		//debugWindow = window.open(debugURL, "debugwindow","");
	}
}


function emptyMarker(v) {
	return !v || v=='' || v==0;
}

function fullPath(s) {
	//return "http://" + KATHYMAPS_DOMAIN + "/" + s;
	return s;
}

var months = ["Jan","Feb","Mar","Apr","May","Jun",
							"Jul","Aug","Sep","Oct","Nov","Dec"];

/** i is a month 1 to 12 */
function number2month(i) {return months[i-1];}

function str2coord(f) {
	return parseFloat(trimCoord(f));
}

function trimCoord(f) {
	// this is bad
	var ss = (""+f).split(".");
	var a = ss[0];
	var b = ss[1];
	var len = b.length;
	var N = 1000;
	if (len > N) b = b.substring(0,N);
	return a + "." + b;
}

function formatRating(rating) {
	if (rating == -1) return 'none';
	var s = sprintf('%1.1f', rating);
	var t = s.replace('/\.0$/','');
	return t;
}

function formatDate(d,noTime) {

	//2006-02-26 06:26:15
	var year      = d.substring( 0, 4);
	var month     = d.substring( 5, 7);
	var day       = d.substring( 8,10);
	var hour      = d.substring(11,13);
	var minutes   = d.substring(14,16);
	var seconds   = d.substring(17,19);

	var monthString = number2month(parseInt(month));
	
	var d = parseInt(day);

	var h = parseInt(hour);
	var m = minutes;
	var s = parseInt(seconds);

	
	var amPm;
	if (h > 12) {
		h -= 12;
		amPm = "pm";
	} else {
		amPm = "am";
	}

	var res = monthString + " " + d + ", " + year;
	if (!noTime) res += " @ " + h + ":" + m + amPm;
	return res;
}

function wrapString(desc) {
	// chop up the description so it doesn't wrap
	var chars = desc.split(' ');
	var count = 0;
	var LIMIT = 50;
	var newDesc = "";
	//for (c in chars) {
	$A(chars).each(function (s) {
									 //var s = chars[c];
		var len = s.length;
		count += len;
		if (count > LIMIT) {
			newDesc += "<br/>";
			count = len;
		}
		newDesc += s + " ";
								 });
	return newDesc;
}

function counter(tag, msg) {
	if (!msg) msg = 'loading';
	return function(val) {
		setInnerHTML(tag,msg + ' .' + dots(val));
	}
}

function dots(n) {
	s = "";
	n.times(function(x) {s += ".";});
	return s;
}

function counters(tags,msg) {
	if (!msg) msg = 'loading';
	return function(val) {
		$A(tags).each(function(t) {setInnerHTML(t,msg + ' .' + dots(val))});
	}
}


function nodeText(node) {
	return node.firstChild.data;
}

function text(res,tag) {
	return nodeText(res.getElementsByTagName(tag)[0]);
}

/****************************** IMAGES ******************************/

function categoryImage(num) {
	return '<img valign="top" border="0" src="images/cat' + num + '.jpg" alt="' + num + '">';
}

function image(src) {
  return '<img border="0" valign="middle" src="images/' + src + '" alt="' + src + '">';
}

/****************************** EMAIL ******************************/

/**
 * DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
function echeck(str) {

	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	if (str.indexOf(at)==-1){
		
		return false;
	}
	
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		
		return false;
	}
	
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		
		return false;
	}
	
	if (str.indexOf(at,(lat+1))!=-1){
		
		return false;
	}
	
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		
		return false;
	}

	if (str.indexOf(dot,(lat+2))==-1){

		return false;
			}
		
	if (str.indexOf(" ")!=-1){

		return false;
			}

	return true;		
}


