/*
WARP: Web-based Asynchronous Remote Procedures
 (c) 2007 Messaging Architects

Written by:
 Joshua C. Faul
 Micah N. Gorrell
 Owen J. Swerkstrom

Requires:
 MooTools 1.11
 Firebug Lite
*/


var Warp = {
	Version: '0.1',

	addCSS: function (cssFile) {
		new Asset.css(cssFile);
	},

	addJS: function (jsFile, id) {
		if(id) {
			new Asset.javascript(jsFile, {"id": id});
		} else {
			new Asset.javascript(jsFile);
		}
	},

	preload: function(widget, callback) {
		var jsFile = ["/warp/widgets/", widget, "/", widget, ".js"];
		var id = null;
		if(callback) {
			id = "warp_" + widget;
			var check = function() {
				if($(id)) {
					callback();
				} else {
					check.delay(10);
				}
			};
			check.delay(10);
		}
		Warp.addJS(jsFile.join(""), id);
		return;
	},

	bodyClass: function () {
		var theBody = document.getElementsByTagName("BODY")[0];

		if (window.ie) { theBody.className = "IE"; }
		if (window.opera) { theBody.className = "Opera"; }
		if (window.webkit) { theBody.className = "Safari"; }
		if (window.gecko) { theBody.className = "Firefox"; }
	},

	// Container for all of the widgets
	widgets: {},

	// currently-loading widget names
	loading: [],

	evolve: function(widgetList) {
		// a-synchronize this function
		var func = function() {
			$each(widgetList, function(widg) {
				var oozeElm = $(widg.element);

				if(Warp.widgets[widg.widget]) {
					if(widg.widget == "setupInputPulldown") {
					}
					// we have the widget code, no need to load
					oozeElm.widget = new Warp.widgets[widg.widget](oozeElm,
																   widg.options);
				} else if(Warp.loading.contains(widg.widget)) {
					// widget code is loading, wait for it
					var check = function() {
						if(Warp.widgets[widg.widget]) {
							oozeElm.widget = new Warp.widgets[widg.widget](oozeElm, widg.options);
						} else {
							check.delay(100);
						}
					};
					check.delay(100);
				} else {
					// we don't have the code and it isn't loading
					Warp.loading.include(widg.widget);
					var jsFile = ["/warp/widgets/", widg.widget, "/", widg.widget];
					jsFile.push(".js");
					var loadWidget = function() {
						new Ajax(jsFile.join(""), {
							"method": "get",
							"evalScripts": true,
							"onComplete": function() {
								Warp.loading.remove(widg.widget);
								oozeElm.widget = new Warp.widgets[widg.widget](oozeElm, widg.options);
							}
						}).request();
					};
					if(Warp.Language.initialized) {
						loadWidget();
					} else {
						Warp.Language.startup(loadWidget);
					}
				}
			});
		};
		func.delay(0);
		return;
	},

	remote: function(sendObj, callback, path) {
		return new Json.Remote(path ? path : "/handleajaj", {
			"onComplete": callback
// sometimes null's out response in safari... "secure": true
// likely a bug in mootools
		}).send(sendObj);
	},

	globalResizeEventHandler: function (e) {
		$each($$('.hasResizeHandler'), function(element) {
			if($(element) && $(element).widget && $(element).widget.element) {
				$(element).widget.eventResize(null);
			}
		});
		return;
	},

	Util: {
		uniq: 0,

		smallDate: function (d, skipTime) {
			var nd = new Date(d * 1000);
			var ret = "";

			// MM/DD/YYYY
			var month = nd.getMonth() + 1;
			var day = nd.getDate();
			var year = nd.getFullYear();

			month = month < 10 ? "0" + month : month;
			day = day < 10 ? "0" + day : day;

			ret += month + "/" + day + "/" + year;

			if(!skipTime) {
				// HH:MM{AM,PM}
				var h = nd.getHours();
				var m = nd.getMinutes();
				var ampm = h > 12 ? Warp.lang("PM") : Warp.lang("AM");

				h = h == 0 ? 12 : h;
				h = h > 12 ? h - 12 : h;
				h = h < 10 ? "0" + h : h;
				m = m < 10 ? "0" + m : m;

				ret += " " + h + ":" + m + ampm;
			}
			return(ret);
		},

		fixupData:  function (d, i) {
			var ret = [];

			$A(d).each( function( elm, index ) {
				ret.push(
					[d.length - index, elm[i]]
				);
			});
			return ret.reverse();
		},

		uniqueID: function() {
			Warp.Util.uniq ++;
			return Warp.Util.uniq;
		}
	},

	//localization
	Language: {
		startup: function(callWhenDone) {
			if(Warp.Language.initialized === true) {
				return;
			}
			new Json.Remote("/strings.json", {
				method: "get",
				onComplete: function(response) {
					Warp.Language.strings = response || {};
					Warp.Language.initialized = true;
					if(typeof(callWhenDone) === "function") {
						callWhenDone();
					}
				}
			}).send();
			return;
		},
		initialized: false,
		strings: {}
	},

	lang: function(string) {
		//if there's a localized string, return it; fall back on passed string
		return Warp.Language.strings[string] || string;
	}
};

//handy GET access
var $GET = {};
$each($A(window.location.search.replace("?", "").split("&")), function(s) {
	$GET[s.split("=")[0]] = unescape(s.split("=")[1]);
});

//Handy array extensions
Array.extend({
	pluck: function(property) {
		var results = [];
		this.each(function (value, index) {
			results.push(value[property]);
		});

		return results;
	},

	uniq: function () {
		var results = [];
		this.each(function (value, index) {
			if (!results.contains(value)) {
				results.push(value);
			}
		});

		return results;
	}
});

Element.extend({
	'up': function(elements, index){
		elements = $$(elements);
		index = $pick(index, 1);
		var parent = this;
		while (parent.getParent && (parent = $(parent.getParent()))) {
			if (elements.contains(parent)) index--;
			if (!index) return parent;
		}
		return null;
	}
});

//We don't want mootools adding "json=" to the post data
//so we're reimplementing Json.Remote here
Json.Remote = XHR.extend({
	initialize: function(url, options){
		this.url = url;
		this.addEvent('onSuccess', this.onComplete);
		this.parent(options);
		this.setHeader('X-Request', 'JSON');
	},

	send: function(obj){
		return this.parent(this.url, Json.toString(obj));
	},

	onComplete: function(){
		this.fireEvent('onComplete', [Json.evaluate(this.response.text, this.options.secure)]);
	}
});

//mootools window.getWidth() and getHeight() return 0 on IE6
window.getWidth = function() {
	if(!window.innerWidth) {
		//IE
		if(!(document.documentElement.clientWidth == 0)) {
			//strict mode
			return document.documentElement.clientWidth;
		} else {
			//quirks mode
			return document.body.clientWidth;
		}
	} else {
		//w3c
		return window.innerWidth;
	}
};
window.getHeight = function() {
	if(!window.innerWidth) {
		if(!(document.documentElement.clientWidth == 0)) {
			return document.documentElement.clientHeight;
		} else {
			return document.body.clientHeight;
		}
	} else {
		return window.innerHeight;
	}
};

// All post-load Warp initialization is done here
window.addEvent("domready", function () {
	Warp.bodyClass();
	window.addEvent("resize", Warp.globalResizeEventHandler);

	//Setup the lightbox widget so that others can use it
	var lightboxDiv = new Element("div", { id: "lightbox" });
	document.getElementsByTagName("BODY")[0].appendChild(lightboxDiv);
	Warp.evolve([
		{ element: "lightbox", widget: "lightbox" }
	]);
});
