/**
 * @author ddugat
 */
(function(){
	var $ = jQuery;
	
	$aw = {};
	$aw.data = {};
	$aw.lib  = {};
	$aw.panelString = "";
	$aw.hide = [];	
	
	$aw.init = function( panel, root ) {
		if (typeof root == "undefined") 
		{
			root = document;			
		}
		
		this._parse(panel, $(root));
	}
	
	$aw._parse = function( panel, root ) {
		var panels = panel.split(',');		

		for (var i = 0; i < panels.length; i++) 
		{
			panel = $.trim(panels[i]);
			this._load(panel, root);
		}
	}
	
	$aw._load = function( panel, root ) {
		var self = this;
		var name = panel.replace(/-/g, '_');
		
		$("." + panel, root).each ( function(i) {
			if (typeof self.data[this.id] === 'undefined') 
			{
				if (name in self.lib) 
				{
					if (!this.id) 
					{
						this.id = name + i;						
					} 
					
					var component = new self.lib[name](this, root);
					self.data[this.id] = component;
					
					self.panelString += name;
				}
			}
		}); 
	}
	
	$aw.refresh = function( panel, root ) {
		if (typeof panel == "undefined") 
		{
			this.init(this.panelString);
		} 
		else 
		{
			this.init(panel, root);			
		}
	}
	
	$aw.ready = function( onReady ) {
		$(document).ready( function()
		{
			if (typeof onReady == "function") 
			{
				onReady();			
			}			
		});
	}
	
	$aw.ajaxReplaceLinks = function( el ) {
	  if (!el.replacedLinks) 
	  {
	  	var anchors = $('a.aw-ajax', el);
		anchors.each( function() {
			var link = $(this).attr("href");
			var anchor = $(this);
			var request = $.ajax({url: link, async: false});
			$(this).replaceWith(request.responseText);
	 	});
	 	el.replacedLinks = true;
	  }
	}	
	
	$aw.ajaxLoading = function( el ) {
		var self = this;
		el.ajaxStart( function() {
			el.prepend('<span class="aw-loading"><img src="' + self.config.image_path + 'loading.gif"/></span>');
		});
		
		el.ajaxStop( function() {
			$(".aw-loading", el).remove();
		});
	}
	
	$aw.showPicker = function(input, picker) {
		var pos = input.offset();
		picker.css({'position':'absolute', 'top':pos.top + input.height() + 6, 'left':pos.left});		
		picker.show();
		$aw.hide.push(picker);			
	}

	$aw.pickerOver = function() {
		if ($(this).is(':empty')) return false;		
		$(this).addClass('aw-calendar-hover');
	}

	$aw.pickerOut = function() {
		if ($(this).is(':empty')) return false;		
		$(this).removeClass('aw-calendar-hover');		
	}		

	$aw.test = function() {
		alert("aw.js");
	}

	$aw.log = function( txt, element ) {
		if (element == null) 
		{
			element = "body";
		}
		
		$("<div class = \"aw-log\">" + txt + "</div>").appendTo(element);		
	}
	
	$(document).ready( function() {
		$aw.refresh("aw-tab, aw-accordion, aw-calendar");
	});
	
	$(document).click(function() {
		var a = $aw.hide;
		for(var i=0; i<a.length; i++) $(a[i]).hide();
		a.length=0;
	});	
	
})(jQuery);