
(function($){
	if (/1\.(0|1|2)\.(0|1|2)/.test($.fn.jquery) || /^1.1/.test($.fn.jquery)) {
	    alert('mLeg requires jQuery v1.2.3 or later!  You are using v' + $.fn.jquery);
	    return;
	}

	$.fn.mLeg=function(o){
		var pDef={
			dsSymb: null,
			baseURL: null,
			onThmChk: F
		};		
		return this.each(function(){ return pr=$.extend({}, pDef, o || {}); });
	};
	
	$.fn.inicLeg=function(tmJSON){
		if(pr.dsSymb==null || pr.baseURL==null) { alert('Aviso: DataSource ou baseURL indefinidos!'); return; }
		this.html($.mLeg.renderTemas(tmJSON));
		
		this.find("ul:first-child").css({"padding-left":"0px", "margin-left":"10px", "margin-top":"4px"});
				
		this.find("div.grp").click($.mLeg.expandeGrupo).end()
			.find("div.grp1").click($.mLeg.expandeGrupo).end()
			.find("div.thm").click($.mLeg.expandeTema).end()
			.find("div.chk,div.unChk").click($.mLeg.changeChecked).end();
		
		//this.find("ul:first-child").hide();
		this.collapseAll();
		//this.find("ul:first-child").show();
	};
	
	// Altera propriedade checked do tema na posicao themeIndex para o estado checked
	$.fn.setThemeChecked = function(themeIndex, checked) {
		var li = this.find("li[nTema='" + themeIndex + "']");
		if (li.length > 0) {
			if (!li.hasClass('thm-disable')) {
				var divChk = li.children('div.item').children('div.ctrl');
				if (divChk.hasClass('unChk') && checked) {
					divChk.removeClass('unChk').addClass('chk');
					if (pr.onThmChk) { pr.onThmChk(themeIndex, true); }
				} else if (divChk.hasClass('chk') && !checked) {
					divChk.removeClass('chk').addClass('unChk');
					if (pr.onThmChk) { pr.onThmChk(themeIndex, false); }
				}
			}
		}
	};
	
	$.fn.getThemeChecked = function(themeIndex) {
		var li = this.find("li[nTema='" + themeIndex + "']");
		if (li.length > 0) {
			if (!li.hasClass('thm-disable')) {
				var divChk = li.children('div.item').children('div.ctrl');
				if (divChk.hasClass('unChk')) {
					return false;
				} else if (divChk.hasClass('chk')) {
					return true;
				}
			}
		}
		return false;
	};
	
	// Altera propriedade disable do tema na posicao themeIndex para o estado enable
	$.fn.setThemeState = function(themeIndex, enabled) {
		var li = this.find("li[nTema='" + themeIndex + "']");
		if (li.length > 0) {
			if (enabled) {
				li.removeClass('thm-disable');
				if ($.browser.msie) li.find('.item').removeClass('thm-disable');
				li.find('.def-cur').removeClass('def-cur').addClass('btn');
			}
			else {
				// fechar tema ao torná-lo desactivo
				var dv = li.find("div.thm-expd");
				if (dv.length > 0) {
					dv.removeClass('thm-expd').addClass('thm-clpsd');
					li.find('UL').slideUp();
				}
				li.addClass('thm-disable');
				if ($.browser.msie) li.find('.item').addClass('thm-disable');
				li.find('.btn').removeClass('btn').addClass('def-cur');
			}
		}
	};
	
	// perminte obter o estado (enable / disable) do tema na posicao themeIndex
	$.fn.getThemeState = function(themeIndex) {
		var li = this.find("li[nTema='" + themeIndex + "']");
		return !li.hasClass('thm-disable');
	};
	
	$.fn.collapseAll = function() {
		//var grp = this.find('div.grp');
		var grp1 = this.find('div.grp1');  // grupos apenas com legenda
		//grp.parent().parent().children('UL').slideUp();
		grp1.parent().parent().children('UL').slideUp();
		//grp.children('div.ctrl').removeClass('grp-expd').addClass('grp-clpsd');
		grp1.children('div.ctrl').removeClass('grp-expd').addClass('grp-clpsd');
		
		var thm = this.find('div.thm');
		thm.parent().parent().children('UL').slideUp();
		thm.children('div.ctrl').removeClass('thm-expd').addClass('thm-clpsd');
	};
	
	$.mLeg={		
		renderTemas:function(temas){
			var htmlStr = "";
			for (var tema in temas) {
				if (temas[tema].nome != undefined) {
					htmlStr += $.mLeg.renderTema(temas[tema], tema);
				}
			}
			htmlStr = "<ul class='mLeg'>" + htmlStr + "</ul>";
			return htmlStr;
		},
		
		renderTema:function(tema, index){
			var htmlStr = "";
			if ((tema.grp != undefined) && (tema.grp == true)){ // um grupo
				var chk = tema.checked;		
				htmlStr = "<li id=" + tema.id + "><div class='item'>";
				var idt = 1;
				if (chk!=undefined) {
					htmlStr += "<div class='ctrl btn idt" + idt + (chk?" chk":" unChk") + "'>&nbsp;</div>";
					idt++;
				}
				htmlStr += "<div class='grp btn'><div class='ctrl idt" + idt + " grp-expd'>&nbsp;</div>";
				idt++;
				htmlStr += "<div class='labl idt" + idt + "'>" + tema.nome + "</div></div></div>";
				
				htmlStr += $.mLeg.renderTemas(tema.temas);
				
				htmlStr += "</li>";
				return htmlStr;
			}
			else if ((tema.leg != undefined) && (tema.leg == true)){ // um grupo apenas de legenda
				htmlStr = "<li id=" + tema.id + "><div class='item'>";
				htmlStr += "<div class='grp1 btn'><div class='ctrl idt1 grp-expd'>&nbsp;</div>";
				htmlStr += "<div class='labl idt2'>" + tema.nome + "</div></div></div>";
				if (tema.symbols!=undefined) htmlStr += $.mLeg.renderSymbols(tema.symbols);
				htmlStr += "</li>";
			}
			else { // um tema
				var comSymb = tema.symbol != undefined;
				var loaded = !comSymb && tema.symbols != undefined;
				var chk = (tema.checked != undefined) && (tema.checked == true);
				
				var w = 20;
				var h = 16;
				if (comSymb && tema.symbol.w != undefined) w = tema.symbol.w;
				if (comSymb && tema.symbol.h != undefined) h = tema.symbol.h;
				
				var minZLev = (tema.minZLevel != undefined ? tema.minZLevel : -1);
				var maxZLev = (tema.maxZLevel != undefined ? tema.maxZLevel : -1);
								
				htmlStr = "<li nTema=" + p + (comSymb ? "" : " loaded=" + loaded) + ">";
				htmlStr += "<div class='item'><div class='ctrl btn idt1" + (chk?" chk":" unChk") + "'>&nbsp;</div>";
				htmlStr += (comSymb?"<img class='symb idt2' src='" + pr.baseURL + "/omserver?sty=" + tema.symbol.style + "&w=" + w + "&h=" + h + "&ds=" + pr.dsSymb + "'/>":"<div class='thm btn'><div class='ctrl idt2 thm-expd'>&nbsp;</div>");
				htmlStr += "<div class='labl idt3'>" + tema.nome + "</div>" + (comSymb?"":"</div>");
				htmlStr += "</div>";
				if(loaded) { htmlStr += $.mLeg.renderSymbols(tema.symbols); }
				htmlStr += "</li>";
				p++;
			}
			return htmlStr;
		},
		
		renderSymbols:function(symbols){
			var htmlStr = "";
			for (var sym in symbols) {
			  if (symbols[sym].style != undefined) {
				var w = 20;
				var h = 16;
				if (symbols[sym].w != undefined) w = symbols[sym].w;
				if (symbols[sym].h != undefined) h = symbols[sym].h;
				
				htmlStr += "<li><div class='item'>";
				htmlStr += "<img class='symb1' src='" + pr.baseURL + "/omserver?sty=" + symbols[sym].style + "&w=" + w + "&h=" + h + "&ds=" + pr.dsSymb + "'/>";
				htmlStr += "<div class='labl idt2'>&nbsp;" + symbols[sym].texto + "</div></div></li>";
			  }
			}			
			htmlStr = "<ul class='mLeg'>" + htmlStr + "</ul>";
			return htmlStr;
		},
		
		expandeGrupo:function() {
			var icon = $(this).find('div.ctrl');
			if(icon.hasClass('grp-clpsd')) { // Expand
				//$(this).parent().parent().children('UL').slideDown("slow");
				$(this).parent().parent().children('UL').slideDown({ duration: 700, easing: 'easeOutBounce' });
				icon.removeClass('grp-clpsd').addClass('grp-expd');
			} else { // Collapse
				//$(this).parent().parent().children('UL').slideUp("slow");
				$(this).parent().parent().children('UL').slideUp({ duration: 700, easing: 'easeOutBounce' });
				icon.removeClass('grp-expd').addClass('grp-clpsd');
			}
		},
		
		expandeTema:function() {
			if (!$(this).parent().parent().hasClass('thm-disable')) {
				var icon = $(this).children('div.ctrl');
				if(icon.hasClass('thm-clpsd') ) { // Expand				
					$(this).parent().parent().children('UL').slideDown("fast");
					//$(this).parent().parent().children('UL').slideDown({ duration: 700, easing: 'easeOutBounce' });
					icon.removeClass('thm-clpsd').addClass('thm-expd');
				} else { // Collapse
					$(this).parent().parent().children('UL').slideUp("fast");
					//$(this).parent().parent().children('UL').slideUp({ duration: 700, easing: 'easeOutBounce' });
					icon.removeClass('thm-expd').addClass('thm-clpsd');
				}
			}
		},

		changeChecked:function() {
			if (!$(this).parent().parent().hasClass('thm-disable')) {
				var activo = $(this).hasClass('chk');
				if (activo)
					$(this).removeClass('chk').addClass('unChk');
				else $(this).removeClass('unChk').addClass('chk');
				if($(this).find('+ div').hasClass('grp')) { // grupo
					// obter temas do grupo e alterar-lhes estado
					var lis = $(this).parent().parent().children('UL').children('li');
					lis.each( function () {
						var indx = $(this).attr('nTema');
						if (indx != undefined && pr.onThmChk) {
							if (activo)
								$(this).children('div').children('div.ctrl').removeClass('chk').addClass('unChk');
							else $(this).children('div').children('div.ctrl').removeClass('unChk').addClass('chk');
							pr.onThmChk($(this).attr("nTema"), !activo ); 
						}
					});
				} else { // tema
					if (pr.onThmChk) { pr.onThmChk($(this).parent().parent().attr('nTema'), !activo ); }
				}
			}
		}
	};
	var pr=null, F=false, p=0;
})(jQuery);
