/*
Requires Mootools.Core and Mootools.More
*/


var AlloyJS = {
	version: '1.0',
	name: 'AlloyController',
	baseHref: '/www_utils/js_plugins',
	Ajax: {},
	Assets: {},
	stickyWin: null,
	pluginInstances: {},
	
	_onFormEditComplete: null,

	loadPlugin: function(pluginName, onLoad) {
		onLoad = onLoad || $empty;
		if (!this.Assets[pluginName]) {
			var scriptName = this.baseHref + "/" + pluginName + "/" + pluginName + ".js";
			this.Assets[pluginName] = new Asset.javascript(scriptName, {id: pluginName + ".script", onload: onLoad});
		}	
		else {
			onLoad();
		}
	},
	
	loadScript: function(scriptName, onLoad) {
		onLoad = onLoad || $empty;
		var id = scriptName.split('/').pop();
		if (!this.Assets[id]) {
			this.Assets[id] = new Asset.javascript(scriptName, {id: id, onload: onLoad});
		}	
		else {
			onLoad();
		}
	},	

	registerPluginInstance: function(pluginName, pluginObject) {
		if (!this.pluginInstances[pluginName]) {
			this.pluginInstances[pluginName] = Array();
		}	
		
		this.pluginInstances[pluginName].push(pluginObject);
	},
	
	notifyPluginInstances: function(pluginName, methodName, params) {
		params = params || [];
		if (params && typeof params != "array" && typeof params != "object") {
			alert(typeof params);
			params = [params];
		}	
			
		var instances = this.pluginInstances[pluginName];
		if (instances) {
			instances.each(	function(item, key) {
								item[methodName].apply(item, params);
							}
						);
		}
	},
	
	formEdit: function (url, onComplete) {	
		this._onFormEditComplete = onComplete;

		this.Ajax.doRequest(url, {window: "ajax"}, {	onComplete: function(text, xml) {
															show_popup(text, null, null);
															document.fireEvent('AlloyJS.AjaxReady');
														},
														useSpinner: true
													}); 
	},	
	
	_getModalWinOptions: function(anchor, showOptions) {
		var position = { position: 'center' };
		
		showOptions = showOptions || {};
		if (anchor) {
			position = {	relativeTo: anchor,
							position: 'bottomLeft',
							offset: {x:0, y:7} ,
						};
		}
		
		var onDisplay = showOptions.onDisplay || $empty;
		var onClose = showOptions.onClose || $empty;
	
		var options = {		
							draggable: true,
							destroyOnClose:true,
							dragHandleSelector: '.handle', 
							closeOnClickOut: false,
							closeOnEsc: true,
							allowMultiple: true,
							evalScripts: true,
							allowNegative: false,
							maskOptions: {
								style: {
									'background-color':'#606060',
									'opacity': 0.6
								}
			  				},
			  				onDisplay: function() {
			  					document.fireEvent("AlloyJS.popupDisplayed");
								onDisplay(this.win);
			  				},
			  				onClose: function() {
			  					document.fireEvent("AlloyJS.popupClosed");
								onClose(this.win);
			  				},
			  				onDestroy: function() {
								AlloyJS.stickyWin = null;
			  				},
						};

		return Object.merge(options, showOptions, position);
	},	
	
	
	showPopup: function(innerHTML, anchor, showOptions){
		var options = this._getModalWinOptions(anchor, showOptions)
		options.content = innerHTML;
		return new StickyWin.Modal(options); 
	},	
	
	showAjaxPopup: function(url, anchor, showOptions, data){
		var ajaxData = AlloyJS.Ajax.mergeData(data || {}, {window: 'ajax'});
		var options = this._getModalWinOptions(anchor, showOptions)
		var win = new StickyWin.Modal.Ajax(options); 
		win.update(url, {data: ajaxData}); 
		AlloyJS.stickyWin = win
		return win;
	},	
	
	hidePopup: function() {
		$$('div.StickyWinInstance').each(function(sw) {
				sw.retrieve('StickyWin').destroy();
		});
	},
	
	formEditPosted: function() {
		this.hidePopup();
		this._onFormEditComplete();
	}, 
	
	postFormToNewWindow: function(form, action, windowId) {
	    var html = "<html><body onload='javacsript:document." + form.name + ".submit()'>";
	    html = html + "<form action='" + action + "' name='" + form.name + "' id='" + form.name + "' method='POST'>" +  form.get('html') +  '</form></body></html>';
	
	    OpenWindow=window.open("", windowId || "new");
	    OpenWindow.document.write(html);
	    OpenWindow.document.close()
	},
	
	stopEvent: function(event) {
		var myEvent = new DOMEvent(event);
		myEvent.stop();
	},	
	
	initialize: function() {
		new Asset.css('/www_utils/css/AlloyJS.css');
		this.Ajax.refresh();
	},
}

AlloyJS.Ajax = {

	ajaxContents: new Hash(),
	spinner: null,

	refresh: function() {
		 this.ajaxContents.each(    function(item, key) {  
										this.loadContent(key);
									},
									this
									);
	},

	loadContent: function(ajaxContentID, params) {   
		if (this.ajaxContents[ajaxContentID]) {
			var data = this.mergeData(this.ajaxContents[ajaxContentID], params || {});
			this.loadHTML("?mode=get_ajax_content", ajaxContentID, data, {useSpinner: false});
		}	
	},  
	
	registerContent: function(ajaxContentID, params) {
		this.ajaxContents[ajaxContentID] = params;
	},

	toQueryString: function(data) {
		
		switch ($type(data)){
			case 'element': 
				return data.toQueryString(); 
			case 'object': 
			case 'hash': 	
				return Hash.toQueryString(data); 
			case 'string': 
				return data;
		}
	
		return null;
	},
	
	mergeData: function(data1, data2) {
		var str = this.toQueryString(data1).trim();
		var str2 = this.toQueryString(data2).trim();
		if (str2) {
			if (str) str += "&" + str2; 
			else str = str2; 
		}		
		return str;
	},
	
	doRequest: function(url, data, options) {
		//options.useSpinner = false;
		
		if (options.useSpinner) {
			//.. Apply a workaround for an issue in MooTool More (Mask) 
			//   this populates the prototype of the document object with the added methods and properties
			//
			// document.id(document.body);	

			var offsetY = -(window.getScrollSize().y/2) + window.getScroll().y + window.getSize().y/2;
			var spinnerOptions = {message: "Please wait...", 
												containerPosition: {position : "center", 
																	offset: {x: 0, y: offsetY}
																	}
												}

		}
		
		
		var requestOptions = $extend({	url: url, 
			                            method: 'post', 
			                            evalScripts: true,
			                            async: true,
			                            spinnerTarget: document.id(document.body),
			                            spinnerOptions: spinnerOptions,
										onFailure: function(xhr){
											alert("AJAX Request Failure:\n" + 
													xhr.statusText + "\n" + 
													xhr.responseText);
										}	
			                        }, options || {});
			                        	
		var onComplete = options.onComplete || $empty;
		requestOptions.onComplete = function(text, xml) {
										document.fireEvent("AlloyJS.ajaxloaded");
										onComplete(text, xml);
									};
	
	    var ajaxRequest = new Request(requestOptions);
		var str = this.toQueryString(data || {});	
	    ajaxRequest.send({data: str});
	},	

	loadHTML: function(url, targetElement, data, options) {
		var spinnerOptions = {message: "Please wait..."};
		var requestOptions = $extend(	{   url: url, 
		                                    method: 'post', 
		                                    evalScripts: true,
		                                    useSpinner: true,
				                            spinnerOptions: spinnerOptions,
											onFailure: function(xhr){
												$(targetElement).set('html', "<div class='error'><h2>AJAX Request Failure</h2><h3>" + xhr.statusText + "</h3>" + xhr.responseText + "</div>");
											},	
		                                    update: targetElement,
		                                    async: true
		                                }, options || {});

		var onComplete = $empty;
		if (options && options.onComplete)
			onComplete = options.onComplete;
			
		requestOptions.onComplete = function(text, xml) {
										document.fireEvent("AlloyJS.ajaxloaded");
										onComplete(text, xml);
									};

	    var ajaxRequest = new Request.HTML(requestOptions);
		var str = this.toQueryString(data || {});	
	    ajaxRequest.send({data: str});
	}
}

var Toggler = new Class({
	Implements: [Options],
	options: {
		toggler: null,
		target: null,
		class1: "hidden",
		class2: "visible"
	},
	
	initialize: function(options) {
		this.setOptions(options);
		if (this.options.toggler) {
			var el = document.id(this.options.toggler);
			if (!el) {
				dbug.log('Toggler: toggler element is missing - ' + this.options.toggler); 	
			}
			else {
				el.addEvent('click', function(){ 
												this.toggle() 
											}.bind(this)
				);
			}	
		}	
	},
	
	toggle: function(event) {
		var el = document.id(this.options.target);
		if (el) {
			el.setProperty("class", el.getProperty("class") == this.options.class1? this.options.class2 : this.options.class1);
		}
	}
});


document.addEvent('domready', function() {
	dbug.enable();
	dbug.log("DBUG initialized");
	AlloyJS.initialize();
});




