
function find_parent(e,attr_name,attr_value) { 	
while ($(e).attr(attr_name)!=attr_value) {	
	e=$(e).parent(); 		
	if (e==null || $(e).size()==0) {
		alert("internal error: parent element not found.");
		return null;
	}
}
return e;
}

var css_includes=new Array();
var attachs_working=0;

function array_push(elems,elem) {
	elems[elems.length]=elem;
}

function css_include_later(fileName,onload_func) {	
	array_push(css_includes, function () { css_include(fileName,onload_func);});
}

function css_include(fileName,onload_func) {	
	var head= document.getElementsByTagName("head")[0];         
	var css = document.createElement('link');
	css.type = 'text/css';
	css.rel = 'stylesheet';
	css.href = fileName;
	css.media = 'screen';
	css.onload=onload_func;
	
	css.onreadystatechange = function () { //compatibilidad con IE, en lugar de onload.						
  	if (css.readyState == 'loaded') {
    	onload_func();
    }
  }				
	head.appendChild(css);		
}

function js_include(fileName,onload_func) {
    var head=document.getElementsByTagName("head")[0];         
		var script=document.createElement('script');
		script.type = 'text/javascript';
		script.src = fileName;
		script.onload=onload_func;
		
		script.onreadystatechange = function () { //compatibilidad con IE, en lugar de onload.				
        if (script.readyState == 'loaded') {
            onload_func();
        }
    }			
		head.appendChild(script);	

}



function starts_width(s,prefix) {
	return s.match("^"+prefix)==prefix;
}

function on_null(value,default_value) {
	return (value!=null) ? value : default_value;
}

function active_script_src() {
	return active_script().src;
}

function active_script() {	
	var scripts = document.getElementsByTagName('script'); //recuperamos el tag del script activo.		
	var active_script=scripts[scripts.length-1];		
	return active_script;
}

function url_base() {
	var script_src=active_script_src();	
	var index=script_src.lastIndexOf("/");
	return script_src.substring(0,index);	
}

function urldecode(str) {				
	return decodeURIComponent(str);
}							

function urlencode(str) {				
	return encodeURIComponent(str);
}							
     
function excelsos_plugin_json(params,success_action) {									
       $.getJSON(script_url_base+"/../service-json.php?"+params+"&jsoncallback=?",  
					function(response){  	         								
	         var plugin_element=urldecode(response.content).replace(/@xtilde@/g,"'");	   	         
	         success_action(plugin_element);
	        }
        );
}


function active_xplugin() { 
	var xplugin=active_script().attributes.getNamedItem("xplugin").value;
	return xplugin;	
}
function active_plugin_path() {
	var xplugin=active_script().attributes.getNamedItem("xplugin").value;
	var xplugin_fragments=xplugin.split(".");
	var xplugin_path=xplugin_fragments[xplugin_fragments.length-1];
	return xplugin_path;
}

function copy_attributes(source_node,target_node,prefix) {
	var attributes=$(source_node).get(0).attributes;
	for (var i=0;i<attributes.length;i++) {
		var attr_name=attributes[i].name;
		var attr_value=attributes[i].value;
		if (starts_width(attr_name,prefix)) {
			$(target_node).attr(attr_name,attr_value);
		}
	}	
}

function xcollect_values(node,attr_key,attr_value_prefix) {			
		var selector="["+attr_key+"^='"+attr_value_prefix+"']";				
		var c="";
		$(node).find(selector).each(function() {
			c+=("&"+$(this).attr(attr_key)+"="+encodeURIComponent($(this).attr("value")));
		});
		return c;
}

function join_attributes(source_node,prefix) {
	var attributes=$(source_node).get(0).attributes;
	var joined='';
	for (var i=0;i<attributes.length;i++) {
		var attr_name=attributes[i].name;
		var attr_value=attributes[i].value;
		if (starts_width(attr_name,prefix)) {
			joined=joined+"&"+attr_name+"="+attr_value;						
		}
	}	
	return joined;
}
function xhide_all(node) {
	$(node).find("[xhide=true]").hide();	 //ocultamos aquellos que hace falta la primera vez que se carga.	
}

function xtoggle(element) {	
	if ($(element).css("display")=="none") {		
		$(element).fadeIn(500);
	} else {
		$(element).fadeOut(250);
	}
}

function xsetup_toggle(node) {
	$(node).find("[xtogglenext=true]").bind("click",
		function(){
			xtoggle($(this).next());return false;
		}
	);	 //ocultamos aquellos que hace falta la primera vez que se carga.	
	
}

function include_dependencies(plugin_marker) {
	$(plugin_marker).find("span[xdepends]").each(function() {
		var xdepends=$(this).attr("xdepends");				
		css_include(xdepends+'/plugin.css',function() {});					
	});
}

var xplugin_attached=new Array();

function xplugin_attach(plugin_marker,action,extras) {	
	++attachs_working;
	var action_param="";		
	var extras_param="";		
	var querystring=window.location.search.substring(1);
	
	if(action!=null) action_param="&action="+action;	
	if(extras!=null) extras_param="&"+extras;

	var xplugin=$(plugin_marker).attr("xplugin");
	
	var eventid=on_null($(plugin_marker).attr("xeventid"),'');	
	var html_title=encodeURIComponent($("head>title").text());
	
	var plugin_params=join_attributes(plugin_marker,'x');
	
	var first_load=$(plugin_marker).children().size()==0;			
		
	var xhost_url=window.location;	
	var json_query= "plugin_action=plugin_request&"+plugin_params+"&html_title="+html_title+action_param+extras_param+xcollect_values(plugin_marker,'name','x')+"&"+querystring+"&xhost_url="+urlencode(xhost_url);
	
	excelsos_plugin_json(json_query,
	function(html_response) {						
//					alert(html_response); //respuesta HTML
					//DEBUG response - $("body").append($("<br><textarea style=\"width:600pt;height:600pt;\">"+html_response+"</textarea><br>")); //debug en textarea										
	      	var plugin_content=$(html_response);		      	
	      	$(plugin_marker).empty().hide(); //lo ocultamos mientras se configura
		     	$(plugin_marker).append($(plugin_content));
		     	if (first_load) xhide_all(plugin_marker);
		     	xsetup_toggle(plugin_marker);
		     	
		     	include_dependencies(plugin_marker);
					
					array_push(xplugin_attached,plugin_marker);
					
					$(plugin_marker).find("span[class='xstyle']").each(function() {
						$("head").append("<style>"+$(this).html()+"</style>");
					});
		     			     			     	
		     	css_include(xplugin+'/plugin.css',function() {});	//custom css del plugin puntual.


					--attachs_working;
					
					if (attachs_working==0) {						
						css_include('excelsos.plugins/plugin.css',function() {});	 //custom css general.
						for (var i=0;i<xplugin_attached.length;i++) { // muestra todos los plugins al final (configurados)
							$(xplugin_attached[i]).show();
						}
						xplugin_attached=new Array();
					}
	});
	
}
var done=false;

function xplugin_attachs(xplugin) {		
//		$("body").append("<div>xp-attach</div>");
		
		var xplugin_size=$("script[xplugin='"+xplugin+"']").size();
		
		var f=function() {
				$("script[xplugin='"+xplugin+"']").each(function(i) {									
					if ($(this).attr("xplugged")!="true") {
						$(this).attr("xplugged","true");				
						
						var marker=$('<span class="xmarker" xmarker="true"></span>');
						copy_attributes(this,marker,'x');
						$(this).before(marker);
						xplugin_attach(marker);								
					}
					done=true;
				});				
		};
		
		var ie=navigator.userAgent.toLowerCase().indexOf("msie")!=-1;
		
		if (ie && xplugin_size==1) {			
			//$("body").append("<div>xp-attach_SIZE1</div>");
			f();			
		} else {
			$(document).ready(f);													
		}		

}


function excelsos_plugin_start(xplugin) {		
	if (typeof jQuery != 'undefined') { //si jquery ya está cargado.		
			xplugin_attachs(xplugin); //ejecutamos los plugins directamente, ya está cargado jquery.
	} else { //sino				
		
		js_include(script_url_base+'/jquery.js',function() {			
		//$(document).ready(function () {$("body").append("<div>jq-loaded</div>"););
			xplugin_attachs(xplugin);
		});	 //incluimos jquery dinamicamente y procesamos todos los plugins.
		
	}
}


try {
	var script_url_base=url_base();
	var active_plugin_path_value=active_plugin_path();
	var xplugin=active_xplugin(); //lo cargamos aca para que cada llamada lo inicialice.
	excelsos_plugin_start(xplugin);
} catch (e) {
}
 
var xplugin_click=false;

function xsetup_popup_toggle(xplugin_class) {
	var plugin_node=$("[class$='"+xplugin_class+"']");				
  
	$(plugin_node).one("click",function() {		
			xplugin_click=true;
		});
		
	$("body").one("click",function() {
			if (!xplugin_click) {											
				xtoggle(find_parent(plugin_node,"class","xpopup1"));				
			}
			xplugin_click=false;
	});
}

function xpopup_toggle(xplugin_class) {
	var plugin_node=$("[class$='"+xplugin_class+"']");					
	
	xsetup_popup_toggle(xplugin_class);

	xtoggle(find_parent(plugin_node,"class","xpopup1"));
}

function xevents_toggle() {		
	xpopup_toggle("xevents");	
}

function xpopup_toggle_parent(plugin_node) {	
	xtoggle(find_parent(plugin_node,"xhide","true")); //mostramos/ocultamos el panel con autohide.	
}
