/*

Utility class

Requires: prototype framework v.1.4.0 (http://prototype.conio.net/)

author: Ken Hoetmer
email:  ken@geobirds.com

*/

/*
	Extension to prototype library: Class.extend(source,additions)
*/
Object.extend(Class, {
	extend: function(source,additions) {
		var newclass = Class.create();
		if ($C(source)) {
			Object.extend($C(newclass),$C(source));
		}
		Object.extend($C(newclass), additions);
		return newclass;
	}
});

function $C(object) { return object.prototype; }

var isIE = (navigator.appName.indexOf("Microsoft") != -1);
var isMoz = (navigator.appName.indexOf("Netscape") != -1);

var Utils = {

	movie: function(movieName) {
		return (isIE) ? window[movieName] : document[movieName];
	},
	
	createObjects: function(request,objectClass) {

		var theobjects = [];
		var members = [];
		
//		var xmlDoc = GXml.parse(request.responseText);
		var xmlDoc = request.responseXML;

		var schemaNode = (isIE) ? xmlDoc.childNodes[1].firstChild : xmlDoc.firstChild.firstChild;
		if ( (schemaNode) && (schemaNode.tagName == 'schema') ) {

			var schemaNodes = schemaNode.childNodes;
			for (var i = 0; i < schemaNodes.length; i++) {
				members[i] = (schemaNodes[i].firstChild) ? schemaNodes[i].firstChild.nodeValue : '';
			} 

			var dataNodes = xmlDoc.getElementsByTagName("r");	
			for (var i = 0; i < dataNodes.length; i++) {
				var elems = dataNodes[i].childNodes;
				var theObject = new objectClass();

				for (var j = 0; j < elems.length; j++) {
					theObject[members[j]] = (elems[j].firstChild) ? elems[j].firstChild.nodeValue : '';
				}
				if (theObject.getReady) theObject.getReady();
				theobjects.push(theObject);
			}
			
		}
	
		return theobjects;	
	},

	ajaxRequest: function(server,method,params,onDataReceive,object,evalScripts) {
		var reqstr = "<root><method>" + method + "</method><params>";
		for (var i = 0; i < params.length; i++) {
			reqstr += "<p>"+ params[i] +"</p>";
		}
		reqstr += "</params></root>";
		
		new Ajax.Request(server, {
			method: 'post',
			postBody: reqstr,
			onComplete: function(request) {
				onDataReceive.call(object,request);
				if (evalScripts) { request.responseText.evalScripts(); }			
			}
		});
	},
	
	ajaxFunction: function(method, params, onDataReceive, object, evalScripts) {
		Utils.ajaxRequest("/resources/lib/db/ajaxServer.php", method, params,
				onDataReceive, object, evalScripts);
	},
	
	commentHTML: function(objects) {
		var commentHTML = '';
		for (var i = 0; i < objects.length; i++) {
			commentHTML += 'On ' + Utils.date_string(objects[i].date) + ', ';
			commentHTML += '<a href="/user/'+objects[i].user+'"><span class="redtext">' + objects[i].user + '</span></a> said:';
			commentHTML += '<div class="commenttext">' + objects[i].comment + '</div><hr>';
		}

		if (objects.length == 0) { commentHTML = '<hr>'; }
		return commentHTML;

	},	

	checkError: function(request,alertFunc) {
		var xmlDoc = GXml.parse(request.responseText);
		if (!xmlDoc) { 
			return false;
		} else {
			var rootNode = (isIE) ? xmlDoc.childNodes[1] : xmlDoc.firstChild;
			if ((rootNode) && (rootNode.tagName == 'error')) {
				return false;		
			} else {
				return true;
			}
		}
	},
	
	apply: function(str, object) {
		return str.replace( /<!([^!]*)!>/g, function(str,p1) { return object[p1];} );
	},
	
	removeChildren: function(node) {
		if (!node) return;
		while (node.hasChildNodes()) {
			this.removeChildren(node.firstChild);
			node.removeChild(node.firstChild);
		}
	},
	
	jsdate2mysql: function(datetime) {
		var month = datetime.getMonth() + 1;
		var year = datetime.getYear();
			
		if (isMoz) {
			year = Number(year) + 1900;
		}
		
		return year + '-' +
			month + '-' +
			datetime.getDate() + ' ' + 
			datetime.getHours() + ':' +
			datetime.getMinutes() + ':00';
	},
	
	mysqldate2js: function(mysqldate) {
		var arr = mysqldate.split('-');
		var arr2 = arr[2].split(' ');
		var jsstr = Utils.num2month(Number(arr[1])) + ' ' + arr2[0] + ', ' + arr[0] + ' ' + arr2[1];
		return new Date(jsstr);
	},

	short_months: ['Jan','Feb','Mar','Apr','May','June','July','Aug','Sept','Oct','Nov','Dec'],

	num2mon: function(num) {
		return Utils.short_months[num-1];
	},
	
	short_date_string: function(datetime) {
		return Utils.num2mon(datetime.getMonth()+1) + ' ' + datetime.getDate();
	},

	long_months: ['January','February','March','April','May','June','July','August','September','October','November','December'],

	num2month: function(num) {
		return Utils.long_months[num-1];
	},
	
	date_string: function(datetime) {
		if (isIE) {
			return datetime.toString().replace(/\d+:.*/, '') + datetime.getFullYear();
		} else {
			return datetime.toString().replace(/\d+:.*/, '').replace(/\s$/,'');;
		}
	},
	
	name_rarity_sort: function(a,b) {
		if (a.name == b.name) {
			if (a.rarity == b.rarity) return 0;
			else if (Utils.rarity_value(a.rarity) > Utils.rarity_value(b.rarity)) return 1;
			else return -1;
		}
	
		else if (a.name > b.name) return 1;
		else return -1;
	
	},
	
	date_sort: function(a,b) {
		if (a.date == b.date) return 0;
		else if (a.date > b.date) return -1;
		else return 1;
	},
	
	user_sort: function (a,b) {
		if (a.user.toLowerCase() == b.user.toLowerCase()) return 0;
		else if (a.user.toLowerCase() > b.user.toLowerCase()) return 1;
		else return -1;
	},
	
	name_sort: function(a,b) {
		if (a.name.toLowerCase() == b.name.toLowerCase()) return 0;
		else if (a.name.toLowerCase() > b.name.toLowerCase()) return 1;
		else return -1;
	},
	
	geoposition_sort: function(a,b) {
		if (a.latitude == b.latitude) {
				if (a.longitude == b.longitude) {
					if (a.name > b.name) { return 1; }
					else if (a.name < b.name) { return -1; }
					else { return 0; }
				} else {
					return a.longitude - b.longitude;
				}
		} else {
			return a.latitude - b.latitude;
		}
	},
	
	rarity_value: function(str) {
		if (str.match(/extremely/i)) {
			return 5;
		} else if (str.match(/rare/i)) {
			return 4;
		} else if (str.match(/uncommon/i)) {
			return 3;
		} else if (str.match(/season/i)) {
			return 2;
		} else if (str.match(/low/i)) {
			return 1;
		} else if (str.match(/high/i)) {
			return 0;
		} else {
			return 0;
		}		
	},
	
	closeEnough: function(a,b,map) {
		var pixel1 = latLongToPixel(map,new GLatLng(a.latitude,a.longitude),map.getZoom());
		var pixel2 = latLongToPixel(map,new GLatLng(b.latitude,b.longitude),map.getZoom());
		
		return ( (Math.abs(pixel1.x - pixel2.x) <= 1) && (Math.abs(pixel1.y - pixel2.y) <= 1) );
	}

};

if (window.GLatLngBounds) {

	GLatLngBounds.prototype.expand = function(bounds) {
		this.extend(bounds.getSouthWest());
		this.extend(bounds.getNorthEast());
		return this;
	}

	GLatLngBounds.prototype.split = function(n) {
		var ret = [];
		var diff = Math.floor(((this.getNorthEast().lng() - this.getSouthWest().lng()) / n) * 10000) / 10000;

		for (var i = 0; i < (n-1); i++) {
			var newbounds = new GLatLngBounds(new GLatLng( this.getSouthWest().lat(), (this.getSouthWest().lng() + (i * diff)) ), 
							  new GLatLng( this.getNorthEast().lat(), (this.getSouthWest().lng() + ((i+1) * diff)) ) );
			ret.push(newbounds);
		}
		ret.push(new GLatLngBounds( new GLatLng( this.getSouthWest().lat(), (this.getSouthWest().lng() + ((n-1) * diff)) ),
					    new GLatLng( this.getNorthEast().lat(), this.getNorthEast().lng()) ) );

		return ret;
	}
}
