/*global Anastasis,anastasis,$,jQuery */

function maximize(target,config)
{

	var $div_to_max=$('#'+config.div_to_max);
	$div_to_max.width($('#main').width()-parseInt($div_to_max.css("padding-left"),10)-parseInt($div_to_max.css("padding-right"),10));
	//todo fare in modo che ricordi l'altezza prima di cambiarla (stile tooltip che si ricorda il testo)
	if (config.height != null && config.height!="")
	{
		$div_to_max.height(config.height+'px');
	}
	$("#"+config.icon_id).addClass("min_icon");
	$("#"+config.icon_id).removeClass("max_icon");
	
	for(var i in config.divs_to_hide)
	{
		$('#'+config.divs_to_hide[i]).hide(config.speed);
	}
	

	$.cookie('maximized_for_'+config.div_to_max,'open');
	$("#"+config.div_to_max)[0].maximized=true;
	return false;
}

function minimize(target,config)
{
	var $div_to_max=$('#'+config.div_to_max);
	
	$div_to_max.width('');
	//todo fare in modo che recuperi l'altezza (stile tooltip che si ricorda ricarica il testo)
	$("#"+config.icon_id).addClass("max_icon");
	$("#"+config.icon_id).removeClass("min_icon");

	for(var i in config.divs_to_hide)
	{
		$('#'+config.divs_to_hide[i]).show(config.speed);
	}
	$.cookie('maximized_for_'+config.div_to_max,'');
	$div_to_max[0].maximized=false;
	return false;
}

function toggle(controller,id,cookie_name,speed)
{
	if(controller)
	{
		$(controller).toggleClass("toggle_opened");
		$(controller).toggleClass("toggle_closed");
	}
	if(!speed) speed="slow";

	if ($('#'+id).is(':visible'))
	{
		if(cookie_name) $.cookie(cookie_name,'closed');
		$('#'+id).hide(speed);
	}
	else
	{
		if(cookie_name) $.cookie(cookie_name,'opened');
		$('#'+id).show(speed);
	}

	return false;
}

/**
 var defaults = {
               div_to_max:	'contentwrap',
               divs_to_hide: ['sidebarwrap'],
               icon_id:		'max_min_icon',
               speed:		'slow',
               height:		null                            
           }; 
 */
function max_min_imize(target,config)
{
	var div=$("#"+config.div_to_max)[0];
	var maximized=div.maximized;
	
	if (!maximized)
	{
		maximize(target,config);
	}
	else
	{
		minimize(target,config);
	}
	return false;
}



//Variabile statica che contiene il tooltip corrente
_the_tooltip=null;

/**
   var defaults = {
               class_name: "tooltip",
               title:	"",
               position: "local",            // local | fixed | growl
               duration: "20",				//	in millisec, defaults are 20 | 3000 | 8000 (base on position)
               max_width: 400,
               max_height: 300,
               anchor: "",                    //if position is fixed, the ID of the anchor element
               vertical_alignment: "bottom",
               horizontal_alignment: "right",
               vertical_offset: 10,
               horizontal_offset: -10,
               opacity: 0.75,
               speed: 300,
               content: "",
               ajax: false,
               url: ""                        //if ajax=true
           };
   */
function showTooltip(target,config)
{
   if(target.tooltip)
   {
   	if(target.tooltip.timeout) clearTimeout(target.tooltip.timeout);
   	return;
   }

   if(config.ajax)
   {
       if(target.tooltipText || target.tooltipText=="")
       {
       	config.content=target.tooltipText;
       }
       else
       {
			config.content = $.ajax({
	           url: config.url,
	           async: false,
	           type: "GET",
	           cache: false
	           }).responseText;
			target.tooltipText=config.content;
	   }
   }

	if(config.content=="") return;

   if(_the_tooltip)
   {
   	if(_the_tooltip.timeout) clearTimeout(_the_tooltip.timeout);
   	_the_tooltip.target.tooltip=null;
   	$(_the_tooltip).remove();
   }

   var tooltip=document.createElement("div");
   tooltip.config=config;
   $(tooltip).addClass(config.class_name);
   $(tooltip).css("opacity",config.opacity);
   $(tooltip).css("position","absolute");
   $(tooltip).css("display","none");

   $("body").append(tooltip);

   _the_tooltip=tooltip;

   $(tooltip).hover(function(){target.stopHideTooltip=true;},function(){hideTooltip(target,true)});

   var content=document.createElement("div");
   $(content).addClass("tooltip_content");
   $(content).html(config.content);
   $(tooltip).append(content);

   if(config.title)
   {
   	var $title=$("<div>");
   	$title.addClass("tooltip_title ui-widget-header ui-corner-top");
   	$title.html("<span class=\"title_text\">"+config.title+"</span>");

   	var $close=$("<a>");
   	$close.attr("href","#");
   	$close.addClass("ui-corner-all close_button");
   	$tmp=$("<span>");
   	$tmp.html("chiudi");
   	$close.click(function(){doHideTooltip(tooltip,target,true);})
   	$close.append($tmp);
	$title.append($close);

   	$(content).addClass("ui-corner-bottom ui-widget-content");
   	$(content).before($title);
   	$(tooltip).addClass("with_title ui-widget");
   	$(tooltip).css("opacity",1);
   }
   else
   {
	   var pointer=document.createElement("div");
	   $(pointer).addClass("tooltip_pointer");
	   $(tooltip).append(pointer);
   }

   if($(tooltip).outerHeight()>config.max_height) $(tooltip).height(config.max_height);
   if($(tooltip).outerWidth()>config.max_width) $(tooltip).width(config.max_width);

   switch(config.position)
   {
           case "fixed":
       var top=0;
       var left=0;
       switch(config.vertical_alignment)
       {
               case "bottom":
           top=$("#"+config.anchor).offset().top+$("#"+config.anchor).outerHeight()+config.vertical_offset;
           break;
               case "top":
           top=$("#"+config.anchor).offset().top-$(tooltip).outerHeight()+config.vertical_offset;
           break;
       }
       switch(config.horizontal_alignment)
       {
               case "left":
           left=$("#"+config.anchor).offset().left+config.horizontal_offset-$(tooltip).outerWidth();
           break;
               case "right":
           left=$("#"+config.anchor).offset().left+$("#"+config.anchor).outerWidth()+config.horizontal_offset-$(tooltip).outerWidth();
           break;
       }
       $(tooltip).css("top",top+"px");
       $(tooltip).css("left",left+"px");
       break;

           case "local":
       $(tooltip).css("top",($(target).offset().top - $(tooltip).outerHeight() - config.vertical_offset) + "px");
       $(tooltip).css("left",($(target).offset().left + config.horizontal_offset) + "px");
       break;

           case "growl":
	  if($.browser.msie && $.browser.version.match(/^6\./))	//ie 6
       {
       	$(tooltip).css("position","absolute");
       	$(tooltip).css("top",$(window).scrollTop());
       }
       else
       {
		$(tooltip).css("position","fixed");
		$(tooltip).css("top",10);
       }

       $(tooltip).css("left",$("body").innerWidth()+config.horizontal_offset-30-$(tooltip).outerWidth());
       $(tooltip).addClass("growl");
       break;
   }

   if(parseInt($(tooltip).css("top"))<0) $(tooltip).css("top",0);
   if(parseInt($(tooltip).css("left"))<0) $(tooltip).css("left",0);
   var diff=$(tooltip).offset().left+$(tooltip).outerWidth-$("body").innerWidth();
   if(diff>0)  $(tooltip).css("left",parseInt($(tooltip).css("left"))-diff);
   //TODO: controllare anche se finisce in giu' fuori dalla pagina - come si fa?

   $(tooltip).fadeIn(config.speed);

   target.tooltip=tooltip;
   tooltip.target=target;
}

function hideTooltip(target,force)
{
	if(!_the_tooltip) return;
	var tooltip=_the_tooltip;
	var action=function(){
		   doHideTooltip(tooltip,target,force);
	   };

	_the_tooltip.timeout=setTimeout(action,tooltip.config.duration);

}

function doHideTooltip(tooltip,target,force)
{
	if(tooltip && (!target.stopHideTooltip || force))
   {
       $(tooltip).fadeOut(tooltip.config.speed, function(){$(tooltip).remove();});
       target.stopHideTooltip=false;
       target.tooltip=null;
       if(tooltip.timeout) clearTimeout(tooltip.timeout);
   }
}

/**
 * Attiva l'autocompletamento
 * @param id L'id dell'input dove l'utente scrive il testo
 * @param address L'url a cui fare la richiesta remota
 * @param mustMatch Flag che indica se bisogna accettare i valori solo in caso di match esatto
 * @param instanceInputId L'id dell'input dove inserire l'id dell'istanza che e' stata selezionata dell'utente
 * @param minChars Il numero di caratteri digitati dopo i quali deve partire l'autocomplete (di default e' 2)
 * (da inserire solo in caso di detail edit)
 */
function activateAutocomplete(id, address, mustMatch, instanceInputId, minChars)
{
	/**
	 * Formatta il risultato. La funzione viene chiamata per ogni item.
	 * @param item L'item da formattare. Nel nostro caso e' un array che ha come primo elemento l'ID Serena
	 * e come secondo elemento il valore vero e proprio
	 * @param value Il valore che, salvo modifiche della funzione, viene considerato come risultato
	 * @returns Cio' che viene considerato risultato, se tale item verra' selezionato dall'utente.
	 * Nel nostro caso il valore (cioe' il secondo elemento di item)
	 */
	function formatResult(row, value)
	{
		return row[1].replace(/&quot;/g, "\"");
	}

	/**
	 * Formatta un item cosi' per farlo visualizzare nel menu a tendina
	 * @param row L'item da modificare (ha almeno due valori: 
	 * il primo e' il value e il secondo e' il description)
	 * @param rowIndex L'indice dell'item
	 * @param totalRows Il numero di tutti gli item
	 * @param textSearched Il testo cercato
	 * @returns L'item formattato: elimina le informazioni sull'ID, mostra normalmente l'informazione principale
	 * e tutte le altre tra parentesi).
	 */
	function formatItem(row,rowIndex,totalRows,textSearched)
	{
		var ret=row[1];
		if(row.length>2)
		{
			ret+="(";
			for(var i=2;i<row.length;i++) {ret+=row[i]+",";}
			ret=ret.substring(0,ret.length-1)+")";
		};
		
		return ret;
	}

	/**
	 * Funzione eseguita subito dopo che l'utente ha selezionato l'elemento dal menu a tendina.
	 * Nel nostro caso valorizza, se esiste (come in detail edit), il campo nascosto relativo 
	 * all'ID dell'istanza Serena selezionata
	 * @param event L'evento scatenante
	 * @param data I dati selezionati
	 * @param formatted I dati selezionati gia' formattati
	 */
	function result(event, data, formatted) 
	{
		var $input = $(document.getElementById(instanceInputId));
		if (data)
		{
			if (instanceInputId)
			{
				$input.val(formatted);	
			}
			
		}
		else
		{
			$input.val("");	
		}
	}
	
	if (!minChars)
	{
		minChars = 2;
	}
	
	var element = document.getElementById(id);
	$(element).autocomplete(
			 address,
			 {
			 minChars:minChars,
			 formatItem:formatItem,
			 formatResult:formatResult,
			 mustMatch:mustMatch
			 });

	$(element).result(result);
}


function ajaxSubmit(from,target,replace,address,target_result,showMessage,messageCode,callback)
{
	var reply="";

	var $message=$(messageCode);

	if(showMessage)
	{
		if(replace)
			$("#"+target).replaceWith($message);
		else
			$("#"+target).html(messageCode);
	}

	if($(from)[0].tagName.toLowerCase()=="a")
	{
		reply=$.ajax({
	           url: address,
	           async: false,
	           type: "GET",
	           cache: false
	           }).responseText;
	}
	else	//form
	{
		var dati=$(from).serialize();
		reply=$.ajax({
	           url: address,
	           async: false,
	           data: dati,
	           type: $(from).attr("method"),
	           cache: false
	           }).responseText;
	}


	var $result=null;
	if (target_result)
	{
		var $reply=$(reply);
		$result=$('#'+target_result,$reply);
	}
	else
	{
		$result=$(reply);
	}
	if(replace)
	{
		if(showMessage)
			$message.replaceWith($result);
		else
			$("#"+target).replaceWith($result);
	}
	else
		$("#"+target).html($result);

	if(callback) callback();

	return false;
}

/*
 * defaults:
 * {
 * 	title: "",
 *  address: "",
 *  width: 300,
 *  height: 300,
 *  draggable: true,
 *  ok_button: false,
 *  loading: false,
 *  close: function(){},
 *  open: function(){},
 *  allow_deletion: true,
 *  popup_detail_edit: true
 * }
 */
function openPopup(from,config)
{
	var reply="";
	
	if(config.loading) loading(from,{text: "Caricamento in corso..."});
	
	setupConfigPopupDetailEdit(config);
	var address=config.address;
	
	if(!from || $(from)[0].tagName.toLowerCase()=="a")
	{
		reply=$.ajax({
	           url: address,
	           async: false,
	           type: "GET",
	           dataType: "html",
	           cache: false
	           }).responseText;
	}
	else	//form
	{
		var dati=$(from).serialize();
		reply=$.ajax({
	           url: address,
	           async: false,
	           data: dati,
	           type: $(from).attr("method"),
	           dataType: "html",
	           cache: false
	           }).responseText;
	}

	//reply=reply.replace(/detailEdit\./g,"popupDetailEdit.");

	var buttons={};
	if(config.ok_button)
	{
		buttons={'Ok': function() {$(this).dialog('close');}};
	}

	var $dialog=$("<div class='widget-dialog'>");
	$dialog.attr("title",config.title);
	$("body").append($dialog);
	$dialog.html('<a href="#" style="height: 0;font-size: 0em; width: 0px; display: block; float: left;" id="ancora_popup">(aperto popup)</a>'+reply);
	

	$dialog.dialog({
			bgiframe: true,
			autoOpen: false,
			width: config.width,
			height: config.height,
			modal: true,
			draggable: config.draggable,
			buttons: buttons,
			resizable: config.resizable,
			open: function(event, ui) 
					{ 
							//Mantenuto per retrocompatibilita', usa la variabile globale onopen_dialog
						if(typeof(onopen_dialog)=="function") 
							onopen_dialog($dialog); 
						else
						{
							if(typeof(config.open)=="function")
								config.open($dialog);
							$('#ancora_popup').focus();
						}
						Anastasis.SerenaUtils.initContent($dialog);
					},
			close: function() 
					{ 
							//Mantenuto per retrocompatibilita', usa la variabile globale onclose_dialog
						if(typeof(onclose_dialog)=="function") 
							onclose_dialog($dialog);  
						else 
						{
							if(typeof(config.close)=="function")
								config.close($dialog);
							$(this).remove();
						}
					}
		});
	
	if(config.loading) stopLoading();

	$dialog.dialog('open');

	return false;
}

function setupConfigPopupDetailEdit(config)
{	
	if(config.popup_detail_edit ) //Se e' un popup di un detail edit 
	{
		anastasis.syncLoadScript("serena/PopupDetailEdit",true);
		window.popupDetailEdit=Anastasis.PopupDetailEdit.initialize();

		config.open=function($dialog){popupDetailEdit.onopen_dialog($dialog,config);}
	}
	return config;
}

/*
 * defaults:
 * {
 * 	local: false,
 * 	target:	null,
 * 	text: "Caricamento in corso..."
 * }
 */
function loading(from,config)
{	
	if(config.local)
	{
		alert("Funzione non ancora supportata: Sere-na supporta solo una richiesta per volta dalla stessa sessione...");
	}
	else
	{
		var $div=$("<div>");
		var $a=$("<a>");
		$a.html(config.text);
		$a.attr("href","#");
		$a.attr("title",config.text);
		$div.append($a);
		$div.addClass("loading_box");
		$div.css("top",$("body").innerHeight()/2-280);
		$div.css("left",$("body").innerWidth()/2-100);	
		$("body").append($div);
		document.body.overlay=new $.ui.dialog.overlay();
		document.body.message=$div;
		$("body").addClass("loading");
		$("body").unload(function(){stopLoading(from)});
		//$("body").keypress(function(event){ event.preventDefault(); });
	}
}

function stopLoading(from)
{	
	if(!from) from=document.body;
	if(!$(from).hasClass("loading")) return;
	from.overlay.destroy();
	from.message.remove();
	$(from).removeClass("loading");
	//$(from).unbind('keypress');
}

/*--------------MAIN--------------*/

$(document).ready(function()
{
	if(window.location.href.match("activate="))
	{
		var id=window.location.href.match(/activate=([^&]*)/)[1];
		$('#'+id).click();
	}
});

