﻿//Variable global para el menu
var menuData = null;

//Creación de plugin para manejo de menús
function onError(html,xsl,xml,obj,ex) {
	alert("Error: " + ex.message);
}
function onSuccess(html,xsl,xml,obj) {
	alert("Success");
}

function onComplete() {
	alert("Complete");
}

function gup( name )
{
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null )
		return null;
	else
		return (results[1]);
}

function cargar_editor ( pagina )
{
	$.ajax({
		url: pagina,
		timeout: 20000,
		contentType: "application/x-www-form-urlencoded;charset=iso-8859-1",
		success: function (responseText, textStatus, XMLHttpRequest) {tinyMCE.get("web-editor").setContent(responseText)}
	});
	$("#pagina").val(pagina);
}

function tableOddEven() {
	$(document).ready(function(){
		$('.tablework tr:odd').addClass('odd');
		$('.tablework tr:even').addClass('even');
	});
}

function cargar_pagina ( pagina )
{
	$("#main-work").empty();
	$("#main-work").load(pagina);
}

jQuery.menu = {

    load : function(id, menuId, file, outid) {

        $.get(file, function(data) {
            //guardar fichero en memoria
			menuData = data;
			
			//Limpiar área de menu
	        $(id).empty();
			
			//Crear menu
	        html = '<div id="' + menuId + '">';
		    $(data).find('section').each(function() {
		        var $section = $(this);
		        html += '<h3 style="font-size: 1em;"><a id="'+ $section.attr('id') + '" href="#">' + $section.attr('title') + '</a></h3>';
		        html += '<div style="font-size: 1em;"><table class="navegator" width="100%" cellspacing="0" cellpadding="0">';
		        $section.find('item').each(function() {
			        html += '<tr><td><a id="' + $(this).attr('id') + '" href="#">' + $(this).attr('title') + '</a></td></tr>';
		        });
		        html += '</table></div>';
    		    
	        });
		    html += '</div>';
			$(id).append($(html));
			
    		//Crear eventos
	        var html = '<script type="text/javascript">';
	        html += '$(document).ready(function(){ ';
            $(data).find('section').each(function() {
                var $section = $(this);
                html += '$("#' + $section.attr('id') + '").click(function() { $("' + outid + '").load("' + $section.attr('href') + '"); });';
                $section.find('item').each(function() {
			        html += '$("#' + $(this).attr('id') + '").click(function() { $("' + outid + '").load("' + $(this).attr('href') + '"); });';
		        });
            });
	        html += '});';
	        html += '</script>';
	        $(id).append($(html));

	        //Poner estilos al menu
	        $(id).accordion({
		        header: "h3",
		        alwaysOpen: false,
		        icons: {
			        header: "ui-icon-circle-arrow-e",
			        headerSelected: "ui-icon-circle-arrow-s"
		        }
	        });
	    });
    }
	,
	
	load2 : function(id, menuId, file, outid) {
		
		
        $.get(file, function(data) {
			
			//Obtener parámetro de entrada
			var idParam = gup('id');
			var isSelected = false;
			var hrefSelected = null;
			var sectionSelected = null;
			var isSection = false;
			var itemSelected = false;
			var isExtern = false;
			
			//Limpiar  valores
	        $(id).empty();
			
			//Crear menu
			$menu = $('<div></div>').attr('id', menuId);
		    $(data).find('section').each(function() {
		        var $section = $(this);
				
				//Seccion para determinar 
				id_section = $section.attr('id');
				if (id_section==idParam) {
					isSelected = true;
					hrefSelected = $section.attr('href');
					sectionSelected = '#'+id_section;
					isSection = true;
					isExtern = $section.attr('extern')=='1';
				}
				//Crear referencia de sección
				if ($section.attr('extern')== '1') 
					var $section_link = $('<a></a>').attr('id', id_section).attr('href', $section.attr('href')).attr('target', '_BLANK')
										.text($section.attr('title'));
				else
					var $section_link = $('<a></a>').attr('id', id_section).attr('href', '#'+id_section)
										.text($section.attr('title'));
				
				//Crear sección
				porletMenu = ($section.find('item').length>0) ? 'portlet-menu' : 'portlet-menu2';
				porletMenuHeader = ($section.find('item').length>0) ? 'portlet-menu-header' : 'portlet-menu2-header';
				$section_content = $('<div></div>').addClass(porletMenu)
										.append(
											$('<div></div>').attr('id', $section.attr('id')).addClass(porletMenuHeader)
						     				.append($section_link)
									);
				
				//Crear items si existen
				if($section.find('item').length>0){//Sin items
					$navegator = $('<ul></ul>').addClass('portlet-navegator');
					$section.find('item').each(function() {
						//Item para parámetro externo
						id_item = $(this).attr('id');
						if (id_item==idParam) {
							isSelected = true;
							hrefSelected = $(this).attr('href');
							sectionSelected = '#'+id_section;
							itemSelected = '#'+id_item;
							isExtern = $(this).attr('extern')=='1';
						}
						var $submenu = $(this);
						var $item = $('<a></a>').attr('id', $(this).attr('id')).attr('href', '#'+id_item).text($(this).attr('title'));
						$navegator.append( $('<li></li>').append($item) );
					});
					$section_content.append(
						$('<div></div>').addClass('portlet-menu-content')
							.append($navegator)
					);
				}

				$menu.append($section_content);
	        });

			$(id).append($menu);
			
    		//Crear eventos
	        var html = '<script type="text/javascript">';
	        html += '$(document).ready(function(){ ';
            $(data).find('section').each(function() {
                var $section = $(this);
				if ($section.attr('href')!=null){
					if ($(this).attr('extern')==null)
                		html += '$("#' + $section.attr('id') + '").click(function() { $("' + outid + '").load("' + $section.attr('href') + '"); });';
				}
                $section.find('item').each(function() {
					if ($(this).attr('href')!=null) {
						if ($(this).attr('extern')!=null) {
							var extern = $(this).attr('extern');
							if (extern="1") 
								html += '$("#' + $(this).attr('id') + '").click(function() { newWindow = window.open("' + $(this).attr('href') + '","_blank"); newWindow.focus( ); });';
						}
			        	else
							html += '$("#' + $(this).attr('id') + '").click(function() { $("' + outid + '").load("' + $(this).attr('href') + '"); });';
					};
		        });
            });
	        html += '});';
	        html += '</script>';
	        $(id).append($(html));

	        //Poner estilos al menu
	        $(".portlet-menu2").addClass("ui-widget ui-helper-clearfix ")
				.find(".portlet-menu2-header")
					.addClass("ui-state-default ui-corner-all")
					.end();	
					
			$(".portlet-menu").addClass("ui-widget ui-helper-clearfix ")
				.find(".portlet-menu-header")
					.addClass("ui-state-default ui-corner-all")
					.prepend('<span class="ui-icon ui-icon-plusthick"></span>')
					.end()
				.find(".portlet-menu-content");
			
			//Inicializar minimizado
			$('.portlet-menu-header').each(function() {
				$(this).toggleClass("ui-icon-minusthick");
				$(this).parents(".portlet-menu:first").find(".portlet-menu-content").toggle();
			});
			
			//Administración del manejo de parámetro---------------------------------------
			if (isSelected) {
				if(isExtern) {
					newWindow = window.open(hrefSelected); 
					newWindow.focus();
				}
				else {
					if(!isSection) { 
						$(sectionSelected).children(".ui-icon").toggleClass("ui-icon-minusthick");
						$(sectionSelected).parents(".portlet-menu:first").find(".portlet-menu-content").toggle();
						$(id_item).addClass('portlet-navegator-selected');
					}
					$(outid).load(hrefSelected);
				}
			}
			//-----------------------------------------------------------------------------
			
			//Ajustar evento de click
			$(".portlet-menu-header").click(function() {
				$(this).children(".ui-icon").toggleClass("ui-icon-minusthick");
				$(this).parents(".portlet-menu:first").find(".portlet-menu-content").toggle();
			});
	    });
    } 
	
	,
	
	load2_editor : function(id, menuId, file, outid) {
		
		
        $.get(file, function(data) {
			
			//Obtener parámetro de entrada
			var idParam = gup('id');
			var isSelected = false;
			var hrefSelected = null;
			var sectionSelected = null;
			var isSection = false;
			var itemSelected = false;
			var isExtern = false;
			
			//Limpiar  valores
	        $(id).empty();
			
			//Crear menu
			$menu = $('<div></div>').attr('id', menuId);
		    $(data).find('section').each(function() {
		        var $section = $(this);
				
				//Seccion para determinar 
				id_section = $section.attr('id');
				if (id_section==idParam) {
					isSelected = true;
					hrefSelected = $section.attr('href');
					sectionSelected = '#'+id_section;
					isSection = true;
					isExtern = $section.attr('extern')=='1';
				}
				//Crear referencia de sección
				if ($section.attr('extern')== '1') 
					var $section_link = $('<a></a>').attr('id', id_section).attr('href', $section.attr('href')).attr('target', '_BLANK')
										.text($section.attr('title'));
				else
					var $section_link = $('<a></a>').attr('id', id_section).attr('href', '#'+id_section)
										.text($section.attr('title'));
				
				//Crear sección
				porletMenu = ($section.find('item').length>0) ? 'portlet-menu' : 'portlet-menu2';
				porletMenuHeader = ($section.find('item').length>0) ? 'portlet-menu-header' : 'portlet-menu2-header';
				$section_content = $('<div></div>').addClass(porletMenu)
										.append(
											$('<div></div>').attr('id', $section.attr('id')).addClass(porletMenuHeader)
						     				.append($section_link)
									);
				
				//Crear items si existen
				if($section.find('item').length>0){//Sin items
					$navegator = $('<ul></ul>').addClass('portlet-navegator');
					$section.find('item').each(function() {
						//Item para parámetro externo
						id_item = $(this).attr('id');
						if (id_item==idParam) {
							isSelected = true;
							hrefSelected = $(this).attr('href');
							sectionSelected = '#'+id_section;
							itemSelected = '#'+id_item;
							isExtern = $(this).attr('extern')=='1';
						}
						var $submenu = $(this);
						var $item = $('<a></a>').attr('id', $(this).attr('id')).attr('href', '#'+id_item).text($(this).attr('title'));
						$navegator.append( $('<li></li>').append($item) );
					});
					$section_content.append(
						$('<div></div>').addClass('portlet-menu-content')
							.append($navegator)
					);
				}

				$menu.append($section_content);
	        });

			$(id).append($menu);
			
    		//Crear eventos
	        var html = '<script type="text/javascript">';
	        html += '$(document).ready(function(){ ';
            $(data).find('section').each(function() {
                var $section = $(this);
				if ($section.attr('href')!=null){
					if ($(this).attr('extern')==null)
					{
						html += '$("#' + $section.attr('id') + '").click(function() {';
						html +=	'  cargar_editor ( "'+ $section.attr('href') +'" )';
						html +='});';
					}
				}
                $section.find('item').each(function() {
					if ($(this).attr('href')!=null) {
						if ($(this).attr('extern')!=null) {
							var extern = $(this).attr('extern');
							if (extern="1") 
								html += '$("#' + $(this).attr('id') + '").click(function() { newWindow = window.open("' + $(this).attr('href') + '","_blank"); newWindow.focus( ); });';
						}
			        	else
						{
							html += '$("#' + $(this).attr('id') + '").click(function() {';
							html +=	'  cargar_editor ( "'+ $(this).attr('href') +'" )';
							html +='});';
						}
					};
		        });
            });
	        html += '});';
	        html += '</script>';
	        $(id).append($(html));

	        //Poner estilos al menu
	        $(".portlet-menu2").addClass("ui-widget ui-helper-clearfix ")
				.find(".portlet-menu2-header")
					.addClass("ui-state-default ui-corner-all")
					.end();	
					
			$(".portlet-menu").addClass("ui-widget ui-helper-clearfix ")
				.find(".portlet-menu-header")
					.addClass("ui-state-default ui-corner-all")
					.prepend('<span class="ui-icon ui-icon-plusthick"></span>')
					.end()
				.find(".portlet-menu-content");
			
			//Inicializar minimizado
			$('.portlet-menu-header').each(function() {
				$(this).toggleClass("ui-icon-minusthick");
				$(this).parents(".portlet-menu:first").find(".portlet-menu-content").toggle();
			});
			
			//Administración del manejo de parámetro---------------------------------------
			if (isSelected) {
				if(isExtern) {
					newWindow = window.open(hrefSelected); 
					newWindow.focus();
				}
				else {
					if(!isSection) { 
						$(sectionSelected).children(".ui-icon").toggleClass("ui-icon-minusthick");
						$(sectionSelected).parents(".portlet-menu:first").find(".portlet-menu-content").toggle();
						$(id_item).addClass('portlet-navegator-selected');
					}
					$(outid).load(hrefSelected);
				}
			}
			//-----------------------------------------------------------------------------
			
			//Ajustar evento de click
			$(".portlet-menu-header").click(function() {
				$(this).children(".ui-icon").toggleClass("ui-icon-minusthick");
				$(this).parents(".portlet-menu:first").find(".portlet-menu-content").toggle();
			});
	    });
    } 
	
	,

	load3 : function(id, menuId, file, outId) {
		$(id).empty();
		//With XSL parameter
		$(id).transform({
			xslParams:{menu_id: "#menu", out_id: "#main-work"},
			xml:"menu.xml",
			xsl:"menu.xslt",
			error:onError,
			success:onSuccess,
			complete:onComplete
		});
		//Poner estilos al menu
		$(id).accordion({
			header: "h3",
			alwaysOpen: false,
			icons: {
				header: "ui-icon-circle-arrow-e",
				headerSelected: "ui-icon-circle-arrow-s"
			}
		});
	}
	
	,
	
	help : function() {
		$(".portlet").addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all")
			.find(".portlet-header")
				.addClass("ui-widget-header ui-corner-all")
				.prepend('<span class="ui-icon ui-icon-plusthick"></span>')
				.end()
			.find(".portlet-content");
		$(".portlet-header .ui-icon").click(function() {
			$(this).toggleClass("ui-icon-minusthick");
			$(this).parents(".portlet:first").find(".portlet-content").toggle();
		});
	}

}
