/*Copyright (c) 2009

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
"Software"), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject to 
the following conditions: 

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software. 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

var ct = null;		//Current active tab
var c_left, c_center, c_right;		//The three main containers
var helper;			//Extra helper atop main containers

Array.prototype.each = function(f) {
	for (var i=0; i < this.length; i++)
		f(this[i],i,this);
};
Array.prototype.remove = function(m) {
	for (var i=0; i < this.length; i++)
		if (this[i] === m) this.splice(i, 1);
	return this;
};
Array.prototype.test = function(id) {
	for (var i=0; i < this.length; i++)
		if (this[i].id == id) return this[i];
	return false;
};

// Self-remove
jQuery.fn.rm = function() {
	return this.each(function() {
		this.parentNode.removeChild(this);
	});
};

// For DIV.module to load content
jQuery.fn.loadContent = function(url) {
	return this.each(function() {
		var x = jQuery(".art_portal_moduleContent", this);
		//x.load(url || this.url, prepModule);
		x.load('index.php?option=com_artportal&task=viewmodule&moduleid=' + this.id.substr(4), prepModule);
		//x[0].innerHTML = '<iframe src="' + this.url + '" style="border:none"></iframe>';
		this.loaded = true;
	});
};

// Load layout defined in modules.js
function loadLayout() {
	// Predefined layout from modules.js is used here, but you can use
	// dynamic script to load customized layout instead
	var list = _layout;

	layout(eval(list));

	function layout(l) {
		jQuery.each(l.reverse(), function(i,m) {
			if (m) {
				var x = eval("_modules."+m.i);
				if (jQuery("#"+m.t).size() > 0)
					jQuery("#"+m.c).addModule({id:m.i, title:x.t, url:x.l, tab:m.t, color:(x.c || null)});
			}
		});
	}
};

// Used on pre-formated <DIV><UL.tabsul><DIVs></DIV> section
jQuery.fn.Tabs = function() {
	return this.each(function() {
		x = jQuery(this);
		var targets = x.children("div").addClass("tabsdiv").hide();

		x.children(".tabsul").children("li").each(function(i) {
			this.target = targets[i];
			jQuery(this).click(function() {
				if (jQuery(this).is(".on")) return;

				y = jQuery(this).siblings(".on");
				y.add(this).toggleClass("on");
				if ((this.id) && (!this.loaded)) {
					jQuery(this.target).load(eval("_modules."+this.id+".l"),prepModule);
					this.loaded = true;
				}
				jQuery(this.target).add(y.size() > 0 ? y[0].target : null).toggle();
			});
		}).eq(0).click();
	});
};

// Used on pre-formated <DL> section
// Exclusive accordion, only one on at a time
jQuery.fn.Accordion = function() {
	return this.each(function (i) {
		x = jQuery(this);

		x.children("dt").click(function(){
			y = jQuery(this);
			if (y.is(".on")) return;

			y.siblings("dt.on").andSelf().toggleClass("on");
			y.siblings("dd:visible").add(y.next()).slideToggle();
		});

		x.children("dt:first").click();
	});
};

// Used on pre-formated <DL> section
// Mutiple accordions, individual on/off control
jQuery.fn.MAccordion = function() {
	return this.each(function (i) {
		x = jQuery(this);

		x.addClass("accordion").children("dd").slideDown();
		x.children("dt").addClass("on").click(function(){
			jQuery(this).toggleClass("on").next().slideToggle();
		});
	});
};

jQuery.fn.NavIcon = function() {
	return this.each(function(i){
		t = jQuery(this).attr("title");
		jQuery(this).wrap("<div class='navdiv'><a href=# id='" + this.id +"'></a></div>");
		x = jQuery(this.parentNode);
		x.append("<br/>"+t);
		x.click(ReplaceModule);
	});
};

jQuery.fn.NavLi = function() {
	return this.addClass("navli").click(ReplaceModule);
};

// When a NavLi (or NavIcon) item is clicked, close all modules in column2 (c2)
// and add a new module designated by the NavLi's ID 
function ReplaceModule() {
	if (!this.id) return;
	i = this.id;
	x = jQuery(".art_portal_module:visible",c2);
	jQuery(".action_close",x).mousedown();
	c2.addModule({id:i,
				title:eval("_modules."+i+".t"),
				url:eval("_modules."+i+".l"),
				color:eval("_modules."+i+".c")||null});
};

//RSS Side Menu (Text Link)
jQuery.fn.RSSLi = function()  {
	jQuery("a", this).click(LoadRSSModule);
	return this.addClass("rssli");
};

// When a RSSLi item is clicked, close all modules in column2 (c2)
// and add a new module with dynamic RSS content
function LoadRSSModule() {
	x = jQuery(".art_portal_module:visible",c2);
	jQuery(".action_close",x).mousedown();
	c2.addModule({id:'m000',			//Module ID doesn't matter now
				title:jQuery(this).text(),	//Link text as module title
				url:'rss.php?q='+encodeURIComponent(this.href)});	//Original link turn into proxy query
	return false;
};

// Process the content of a newly loaded module before showing
function prepModule() {
	jQuery(this).slideDown();
};

//Used on DIV.main_container only, 'tab' is used only when loading layouts
//When 'tab' is omitted, ct (current tab) is used instead
jQuery.fn.addModule = function(settings) { //id, title, url, tab, class
	return this.each(function() {
		var options = jQuery.extend({
			title	: null,
			tab		: null,
			color	: null
		}, settings);

		var tx = options.tab ? document.getElementById(options.tab) : ct;
		if (!options.tab && (m = ct.modules.test(options.id))) {
			jQuery(m).fadeTo('fast', 0.5).fadeTo('fast', 1);
			return; //Disable duplicate in a same tab
		}

		y = jQuery("#art_portal_module_template").clone(true);
		x = y[0];
		x.loaded = false;
		x.url = options.url;
		x.tab = tx.id;
		x.id = options.id;

		tx.modules.push(x);

		if (options.title) jQuery(".art_portal_moduleTitle", x).text(options.title);
		else jQuery(".art_portal_moduleHeader",x).rm();

		if (options.color) jQuery(x).addClass(options.color);

		if (tx === ct) jQuery(x).show();
		jQuery(this).prepend(x);

		if (!options.tab) {
			jQuery(x).loadContent();
		}
	});
};

// Actions taken when you click a header tab
function HeaderTabClick(){
	if (this === ct) return;	//Return if click on current active tab
	jQuery(this).siblings(".on").andSelf().toggleClass("on");

	//Hide last tab's modules
	jQuery(".art_portal_module:visible").hide();

	ct = this;
	x = eval("_tabs."+ct.id);

	// Load an extra helper content block if defined
	// with a file name default to current tab's id
	helper.hide();
	if (x.helper) {
		helper[0].innerHTML = jQuery('#helper_' + ct.id)[0].innerHTML; helper.show();
	} else helper.hide().empty();

	//Ajust column widths
	c_left.css({width:x.c_left});
	c_center.css({width:x.c_center});
	if (x.c_center == "auto") {
		c_center.css({'float':"none", marginLeft:x.c_left});
	} else {
		c_center.css({'float':"left", marginLeft:0});
	}
	c_right.css({width:(x.c_right || 0)});

	//Load content and show module
	this.modules.each(function(m,i){
		// Lazy loading when the tab is activated
		if(!m.loaded) jQuery(m).loadContent();
		jQuery(m).fadeIn();
	});
};

jQuery(function(){
	c_left = jQuery("#c_left");
	c_center = jQuery("#c_center");
	c_right = jQuery("#c_right");
	helper = jQuery("#art_portal_helper");

	jQuery("#art_portal_header_tabs li").each(function(){
		// During initialization, attach a "modules" array to each tab
		this.modules = [];
		jQuery(this).click(HeaderTabClick);
	});

	try {
		jQuery(".art_portal_main_containers").sortable({
			connectWith: '.art_portal_main_containers',
			handle: '.art_portal_moduleHeader',
			tolerance: 'pointer'
		});
	} catch (e) {}

	// Load module definitions for each tab
	loadLayout();

	jQuery("#art_portal_expd").click(showAll);
	jQuery("#art_portal_clps").click(hideAll);
	jQuery(".action_refresh").mousedown(loadContent);
	jQuery(".action_show").mousedown(showModule);
	jQuery(".action_min").mousedown(minModule);
	jQuery(".action_max").mousedown(maxModule);
	jQuery(".action_close").mousedown(closeModule);

	setTimeout("jQuery('#art_portal_header_tabs li:first').click()", 200);
});

// Container Actions, apply on modules
function showAll() {
	jQuery(".art_portal_moduleContent").show();
	jQuery(".action_min").show();
	jQuery(".action_max").hide();
	jQuery("#art_portal_expd").hide();
	jQuery("#art_portal_clps").show();
};

function hideAll() {
	jQuery(".art_portal_moduleContent").hide();
	jQuery(".action_max").show();	
	jQuery(".action_min").hide();	
	jQuery("#art_portal_expd").show();
	jQuery("#art_portal_clps").hide();
};

// Module Actions, apply on current module
function loadContent() {
	jQuery(this).parents(".art_portal_module").loadContent();
};

function minModule() {
	jQuery(this).hide().parents(".art_portal_moduleFrame").children(".art_portal_moduleContent").hide();
	jQuery(this).siblings(".action_max").show();
};

function maxModule() {
	jQuery(this).hide().parents(".art_portal_moduleFrame").children(".art_portal_moduleContent").show();
	jQuery(this).siblings(".action_min").show();
};

function showModule() {
	if (jQuery(this).parents(".art_portal_moduleFrame").children(".art_portal_moduleContent").children("iframe") && jQuery(this).parents(".art_portal_moduleFrame").children(".art_portal_moduleContent").children("iframe")[0]) {
		var link = jQuery(this).parents(".art_portal_moduleFrame").children(".art_portal_moduleContent").children("iframe")[0].src;
		if (link) {
			link = link.replace('index2.php', 'index.php');
			location.href = link;
		}
	}
}

function closeModule() {
	var m = jQuery(this).parents(".art_portal_module");
	ct.modules.remove(m[0]);
	m.rm();
};
/*
jQuery(window).bind("unload", function() {
	cookieString = '';
    jQuery(".art_portal_module").each(function() {
		cookieString += this.id + '|' + this.offsetTop + '|' + this.offsetLeft + ';';
	});
	jQuery.cookie('art_portal', cookieString, { expires: 365 });
});

jQuery(window).bind("load", function() {
	var cookieString = jQuery.cookie('art_portal');
	if (cookieString) {
		var modules = cookieString.split(';');
		var mLength = modules.length;
		for (i=0 ; i < mLength; i++) {
			var module = modules[i];
			if (module) {
				var par = module.split('|');
				if (document.getElementById(par[0])) {
					//document.getElementById(par[0]).style.position = 'absolute';
					document.getElementById(par[0]).style.left = par[1] + 'px';
					document.getElementById(par[0]).style.top = par[2] + 'px';
					//alert(document.getElementById(par[0]).style.top);
				}
			}
		}
	}
});
*/
