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

Anastasis.Sito=function()
{};

Anastasis.Sito.prototype.sendAndReload=function(url)
{
	url=url.replace("+","%2B");
	$.get(url,null,function(/*xml*/){window.location.reload();},"text");
};

Anastasis.Sito.prototype.popupNode=function(from,title,id,onopen,onclose)
{
	var config=
	{
			title: title,
			address: "ModuleIndex?q=object/detail&p=_system_cms_node/_a_ID/_v_"+id+"&t=plain_system_cms_node",
			width: 700,
			height: 550,
			draggable: false,
			ok_button: true,			
			open: function($dialog)
			{
				$('a[href^="http://"]',$(".ui-dialog-content")).each(function(){
					$(this).attr("target","_blank");
					$(this).attr("title",$(this).attr("title")+" - Apre una nuova finestra");
					$(this).addClass("external_link");
				});
				if(typeof(onopen)=="function") { onopen($dialog); } 
			},
			close: onclose
	};
	openPopup(from,config);	
	return false;
};
Anastasis.Sito.prototype.openDetailHere=function(from)
{
	var address=$(from).attr("href");
	if(address.match(/^Index/)) { address="Module"+address; }
	else { address="ModuleIndex"+address; }
	var reply=$.ajax({
	           url: address,
	           async: false,
	           type: "GET"
	           }).responseText;
	$("#content").html(reply);
	var $a=$("<a>");
	$a.attr("id","ancora_openDetailHere");
	$a.attr("href","#");
	$a.html("Segue il contenuto caricato dinamicamente");
	$("#content").prepend($a);
	$a.focus();
	$a.addClass("NoVisibility");

	//Accrocchio, non andrebbe qui, ma non fa danno...
	$("#link_torna_scheda_prodotto").show("fast");

	return false;
};

Anastasis.Sito.prototype.closeMenu=function($element)
{
	var $controller=$element.siblings(".titolo_menu").children("a");
	if ($element.is(':visible') && $controller.is(':visible'))
	{
		$element.hide();
		$controller.toggleClass("toggle_opened");
		$controller.toggleClass("toggle_closed");
	}

};
Anastasis.Sito.prototype.fixSidebarHeight=function()
{
	var sidebar_h=$("#sidebarwrap").outerHeight();
	var content_h=$("#contentwrap").outerHeight();
	if(content_h>sidebar_h)
	{
		$("#sidebar_filler").height(content_h-sidebar_h);
	}
};
Anastasis.Sito.prototype.stopAndWait=function()
{
	//Impedisce all'utente di fare qualunque cosa fino al ricaricamento
	//$(document).bind('click', function(event) { event.preventDefault();	});
	//$(document).bind('keypress', function(event) { event.preventDefault();	});
	var $div=$("<div>");
	$div.addClass("loading");
	$div.css("left",parseInt((($("body").innerWidth()/2)-100),10)+"px");
	var $img=$("<img>");
	$img.attr("src","app/Template/metaAmbiente/standard/img/loader_animation_large.gif");
	$img.attr("alt","Attendere...");
	$div.append($img);
	$("body").append($div);
	try
	{
		document.body.overlay=new $.ui.dialog.overlay();
	} catch(e){}
};
Anastasis.Sito.prototype.hideSidebar=function()
{
	$( "#sidebarwrap" ).hide();
	$( "#contentwrap" ).addClass("maximized");
};
Anastasis.Sito.highlightWarnOnLoad=function(idDiv)
{
	$(document).ready(function(){
		setTimeout(function(){$("#"+idDiv).fadeIn(1000,function(){$("h3",$("#"+idDiv)).effect("highlight",{color: '#FC0106'},3000);});},500);
	});
};
Anastasis.Sito.prototype.popupInsertDiscountCode=function(from,address)
{
	var onopen=function($dialog)
			{
				$dialog.dialog('option','buttons', {'Invia': function() {
														if(!$("#discount_code").val()) 
														{
															$("#discount_code").val($("#discount_code_1").val()+"-"+$("#discount_code_2").val());
														}
														ajaxSubmit($("#insertcode_form"),'insertcode_div',false,address,'',false,'');														
													},
													'Chiudi': function() {$(this).dialog('close'); }
													});
			};
	var onclose=function(){};

	var config= {	title: 'Inserisci codice sconto',   
					address: address,   
					width: 620,   
					height: 340,   
					draggable: true,   
					ok_button: false,   
					loading: false,	
					resizable: false,	
					allow_deletion: false,	
					popup_detail_edit: false,
					open: onopen,
					close: onclose
				};
	return openPopup(from,config);
};

Anastasis.Sito.prototype.removeDiscountCode = function(address) {
	$.ajax({
		url : address,
		success : function() 
			{
				// se siamo nella pagina dell'ordine...
				if (typeof (window.onchangeAction) == "function") {
					window.onchangeAction();
				} else {
					window.location.reload();
			}
		}
	});
};

// -------------------------------------------//
Anastasis.ECommerce=function()
{
	this.path={};
	this.path.set_quantita="ModuleIndex?q=ecommerce/cartedit&action=set&quantita=@QUANTITA@&articolo=@ARTICOLO@";
	this.path.empty_cart="ModuleIndex?q=ecommerce/cartedit&action=empty";
	this.path.set_order_status="ModuleIndex?q=operatori/setorderstatus/id=@ID@/status=@STATUS@";
	this.path.confirm_order="ModuleIndex?q=operatori/confirmorder/id=@ID@/target=@TARGET@";
	this.path.cancel_order="ModuleIndex?q=operatori/cancelorder/id=@ID@";
	this.path.annulla_sessione_corso="ModuleIndex?q=myanastasis/annulla_sessione_corso/id_sessione_corso=@ID@";
	this.path.annulla_corsista="ModuleIndex?q=myanastasis/annulla_corsista/id_corsista=@ID@";
	this.path.segna_pagato="ModuleIndex?q=myanastasis/segna_pagato/id_corsista=@ID@";
	this.path.elabora_spostamento="ModuleIndex?q=myanastasis/elabora_spostamento/id_corsista=@ID_CORSISTA@/id_sessione_corso=@ID_SESSIONE@";
};

Anastasis.ECommerce.prototype.emptyCart=function()
{
	if(confirm("Vuoi davvero svuotare il carrello?"))
	{
		$.get(this.path.empty_cart,null,function(/*xml*/){location.reload();},"text");
	}
};

Anastasis.ECommerce.prototype.setQuantita=function(input_quantita,articolo)
{
	var quantita=$(input_quantita).val();
	if(quantita<1)
	{
		 quantita=1;
		 $(input_quantita).val(1);
	}
	var url=this.path.set_quantita.replace("@QUANTITA@",quantita).replace("@ARTICOLO@",articolo);
	url=url.replace("+","%2B");
	$.get(url,null,function(/*xml*/){location.reload();},"text");
};

Anastasis.ECommerce.prototype.checkResponseStatus=function(xmlreply)
{
	try
	{
		var msg=Anastasis.XMessage.buildXMessage(xmlreply);
		if(msg.isErrorMessage())
		{
			alert("ERRORE:\n"+msg.error);
			return false;
		}
		else
		{
			return true;
		}
	} catch(e)
	{
		alert("Errore sconosciuto.\n"+xmlreply);
		return false;
	}
};

Anastasis.ECommerce.prototype.setOrderStatus=function(id,status)
{
	var url=this.path.set_order_status.replace("@ID@",id).replace("@STATUS@",status);
	anastasis.sito.stopAndWait();
	$.get(url,null,function(xml){anastasis.ecommerce.checkResponseStatus(xml); location.reload();},"xml");
	return false;
};

Anastasis.ECommerce.prototype.confermaOrdine=function(id,target)
{
	var url=this.path.confirm_order.replace("@ID@",id).replace("@TARGET@",target);	
	anastasis.sito.stopAndWait();
	var handleReply=function(xml)
	{
		var msg=Anastasis.XMessage.buildXMessage(xml);
		if(msg.isErrorMessage())
		{
			alert("ERRORE:\n"+msg.error);
			location.reload();
		}
		else
		{
			var content=msg.getContentOf("esito");
			Anastasis.SerenaUtils.popupMessage("Esito operazione",content,function(){location.reload();},null,700,450);		
		}
	};
	$.get(url,null,handleReply,"xml");
	return false;
};

Anastasis.ECommerce.prototype.elaboraSpostamento=function(id_corsista,id_sessione)
{
	var url=this.path.elabora_spostamento.replace("@ID_CORSISTA@",id_corsista).replace("@ID_SESSIONE@",id_sessione);	
	anastasis.sito.stopAndWait();
	var handleReply=function(xml)
	{
		var msg=Anastasis.XMessage.buildXMessage(xml);
		if(msg.isErrorMessage())
		{
			alert("ERRORE:\n"+msg.error);
			location.reload();
		}
		else
		{
			var content=msg.getContentOf("esito");
			Anastasis.SerenaUtils.popupMessage("Esito operazione",content,function(){location.reload();},null,700,450);		
		}
	};
	$.get(url,null,handleReply,"xml");
	return false;
};


Anastasis.ECommerce.prototype.annullaSessione=function(id)
{
	var url=this.path.annulla_sessione_corso.replace("@ID@",id);	
	anastasis.sito.stopAndWait();
	var handleReply=function(xml)
	{
		var msg=Anastasis.XMessage.buildXMessage(xml);
		if(msg.isErrorMessage())
		{
			alert("ERRORE:\n"+msg.error);
			location.reload();
		}
		else
		{
			var content=msg.getContentOf("esito");
			Anastasis.SerenaUtils.popupMessage("Esito operazione",content,function(){location.reload();},null,700,450);		
		}
	};
	$.get(url,null,handleReply,"xml");
	return false;
};

Anastasis.ECommerce.prototype.annullaCorsista=function(id)
{
	var url=this.path.annulla_corsista.replace("@ID@",id);	
	anastasis.sito.stopAndWait();
	var handleReply=function(xml)
	{
		var msg=Anastasis.XMessage.buildXMessage(xml);
		if(msg.isErrorMessage())
		{
			alert("ERRORE:\n"+msg.error);
			location.reload();
		}
		else
		{
			var content=msg.getContentOf("esito");
			Anastasis.SerenaUtils.popupMessage("Esito operazione",content,function(){location.reload();},null,700,450);		
		}
	};
	$.get(url,null,handleReply,"xml");
	return false;
};

Anastasis.ECommerce.prototype.segnaPagato=function(id)
{
	var url=this.path.segna_pagato.replace("@ID@",id);	
	anastasis.sito.stopAndWait();
	var handleReply=function(xml)
	{
		var msg=Anastasis.XMessage.buildXMessage(xml);
		if(msg.isErrorMessage())
		{
			alert("ERRORE:\n"+msg.error);
			location.reload();
		}
		else
		{
			var content=msg.getContentOf("esito");
			Anastasis.SerenaUtils.popupMessage("Esito operazione",content,function(){location.reload();},null,700,450);		
		}
	};
	$.get(url,null,handleReply,"xml");
	return false;
};

Anastasis.ECommerce.prototype.annullaOrdine=function(id)
{
	if(confirm("Annullare l'ordine "+id+" ?\nN.B. L'operazione è irreversibile!"))
	{
		var url=this.path.cancel_order.replace("@ID@",id);	
		anastasis.sito.stopAndWait();
		var handleReply=function(xml)
		{
			var msg=Anastasis.XMessage.buildXMessage(xml);
			if(msg.isErrorMessage())
			{
				alert("ERRORE:\n"+msg.error);
				location.reload();
			}
			else
			{
				var content=msg.getContentOf("esito");
				Anastasis.SerenaUtils.popupMessage("Esito operazione",content,function(){location.reload();},null,700,450);		
			}
		};
		$.get(url,null,handleReply,"xml");
	}
	return false;
};

/**
 * Restituisce l'element con di tag tag con nome name
 */
Anastasis.ECommerce.prototype.getElementWithNameInOrderConfirm=function(tag,name)
{
	var i;	//usata nel for
	var els=document.getElementsByTagName(tag);
	for(i=0;i < els.length;i++)
	{ 
		if(els[i] && els[i].id)
		{
			var nome=els[i].id.match(/#ID_Ordine#_#obj_\.(.*)/);
			if(nome && nome[1]==name) { return els[i]; }
		}
	}
	return null;
};

/**
 * Restituisce l'element con di tag tag con nome name
 */
Anastasis.ECommerce.prototype.getElementWithNameInEditUser=function(tag,name)
{
	var i;	//usata nel for
	var els=document.getElementsByTagName(tag);
	for(i=0;i < els.length;i++)
	{
		if(els[i] && els[i].id)
		{
			var nome=els[i].id.match(/#ID__system_user_sito#_#obj_\d+\.contatto\.#ID_Contatto#_#obj_\d+\.(.*)/);
			if(nome && nome[1]==name) { return els[i]; }
		}
	}
	return null;
};

Anastasis.ECommerce.prototype.acquista=function(id_articolo)
{
	var acquista_path="ModuleIndex?q=ecommerce/cartedit&action=add&articolo=";

	var action=function()
	{
		var popup_path="ModuleIndex?q=ecommerce/cartpage&t=popupcart";
		var title="Prodotti nel carrello";
		var width=640;
		var height=480;

		var reply=$.ajax({
	           url: popup_path,
	           async: false,
	           type: "GET",
	           cache: false
	           }).responseText;

		var $dialog=$('<div title="'+title+'">'+reply+"</div>");

		$dialog.dialog({
				bgiframe: true,
				autoOpen: true,
				width: width,
				height: height,
				modal: true,
				draggable: false,
				buttons: {
							'Ok': function() {$(this).dialog('close');}
						 },
				close: function() { $(this).remove(); }
			});

	};

	$.get(acquista_path+encodeURIComponent(id_articolo),null,function(/*xml*/){action();},"text");
};


//---------------------------------------------//

//Azioni eseguite all'onload della pagina
$(document).ready(function(){
			//Apre tutti i link esterni in nuove finestre
			$('a[href^="http"]').each(function(){
						$(this).attr("target","_blank");
						$(this).attr("title",$(this).attr("title")+" - Apre una nuova finestra");
						$(this).addClass("external_link");
				});
			if($("a[rel^='prettyPhoto']").length>0)
			{
				$("a[rel^='prettyPhoto']").prettyPhoto();
			}

			setTimeout(anastasis.sito.fixSidebarHeight,400);

		});

anastasis.sito=new Anastasis.Sito();
anastasis.ecommerce=new Anastasis.ECommerce();

