j$.ajaxSetup( { timeout: 18000 } );


// *** Service Calling Proxy Class

function serviceProxy(serviceUrl)

{

    var _I = this;

    this.serviceUrl = serviceUrl;



    // *** Call a wrapped object

    this.invoke = function(callback,error,bare)

    {

        // *** Convert input data into JSON - REQUIRES Json2.js

       



        // *** The service endpoint URL

        var url = _I.serviceUrl;



        j$.ajax( {

                    url: url,

                    data: "",

                    type: "GET",

                    processData: false,

                    contentType: "application/json",

                    timeout: 18000,

                    dataType: "text",  // not "json" we'll parse

                    success:

                    function(res)

                    {

                        if (!callback) return;



                        // *** Use json library so we can fix up MS AJAX dates

                        var result = eval("("+res+")");



                        // *** Bare message IS result

                        if (true)

                        { callback(result,"success",null,eval("({url:'"+url+"'})")); 
                        	return; 
                        }



                        // *** Wrapped message contains top level object node

                        // *** strip it off
						if(false){
	                        for(var property in result)
	
	                        {
	
	                            callback( result[property] );
	
	                            break;
	
	                        }
                        }

                    },

                    error:  function(xhr) {

                        if (!error) return;

                        if (xhr.responseText)

                        {

                            //var err = eval("("+xhr.responseText+")");

                            if (false){
								callback({},"error",null,eval("({url:'"+url+"'})"));
                                
							}else{

                                error( { Message: "Unknown server error." });
							}
                        }else{
                        	error( { Message: "Unknown server error." })
                        }

                        return;

                    }

                });

    }

}

// *** Create a static instance



/*
	dispositivo che incapsula il comportamento che esegue la chiamata al servizio.
	In particolare implementa il comportamento della paginazione.
	ATTENZIONE: questa classe DEVE rispettare l'interfaccia di Widget.
	Il consumer può manipolare il "Pager" o il "Widget" senza la necessità di distinguerli.
*/
function Pager(widget,el,key,pageNumbers,labels){
	if(labels==undefined || labels==null){
		labels={pageLabel:"pagina"};
	}
	this.labels=labels;
	this.key=key;
	this.widget=widget;
	this.page="1";
	this.el=el;
	this.pageNumbers=pageNumbers;

	/*
		simula il click
	*/
	this.selectPage=function(page){
		//TODO:
		this.goToPage(page);
	}

	/*
		esegue la chiamata al servizio
	*/
	this.goToPage=function(page){

		this.page=page;
		//fai la chiamata
		this.showValues();

		//ridisegna pager
	}
	var myPagerClass=this;
	this.init=function(){
	var html="";
	    if (pageNumbers>0){
		html="<a class='current'>"+this.labels.pageLabel+":</a>&nbsp;";
		html+="<a class='disabled' href='#' title='"+(0+1)+"'>"+"&lsaquo;&lsaquo;"+"</a>&nbsp;"
		for(var i=0;i<this.pageNumbers;i++){
			if(i==0){
				html+="<a class='current' href='#' title='"+(i+1)+"'>"+(i+1)+"</a>&nbsp;";
			}else{
				html+="<a class='pag' href='#' title='"+(i+1)+"'>"+(i+1)+"</a>&nbsp;";
			}
		}
		}else html="";
		var nextClass="pag";
		if(this.pageNumbers<=1)nextClass="disabled";
		html+="<a class='"+nextClass+"' href='#' title='"+(1+1)+"'>"+"&rsaquo;&rsaquo;"+"</a>&nbsp;";
		j$(j$(this.el).siblings("div.riga")).css("display","block");

		j$(this.el).html("<span>"+html+"</span>");
		if(pageNumbers==0){
			
			
			j$(this.el).css("display","none");
			j$(this.el).siblings(".riga").css("display","none");
		}else{
			j$(this.el).css("display","block");
			j$(this.el).siblings(".riga").css("display","block");
		}
		
		j$(this.el).find("a[@href$='#']").each(
		function(index){

			j$(this).bind("click",
			function(e){
				e.preventDefault();
				if(j$(this).attr("href")!=undefined && (j$(this).attr("href").match("#$")!=null)){

					j$(this).siblings("a").attr("href","#");
					j$(this).attr("href","#");
					j$(this).attr("class","pag");
					j$(this).siblings("a").attr("class","pag");

					//j$(this).siblings("a").attr("href","#");

					var page=parseInt(j$(this).attr("title"));
					var elements=j$(j$(this).parent().find("a[@title='"+page+"']"));
					elements.removeAttr("href");
					elements.attr("class","current");

					//j$(this).removeAttr("href");
					//j$(this).attr("class","selectedPage");


					var prevAttr=String.fromCharCode(8249);
					var nextAttr=String.fromCharCode(8250);
					var prevEl=j$(j$(this).parent().find("a:contains("+prevAttr+")"));
					if(page>1){
						prevEl.attr("class","pag");
						prevEl.attr("href","#");
						prevEl.attr("title",""+(page-1));
					}else{
						prevEl.attr("class","disabled");
						prevEl.removeAttr("href");
					}
					var nextEl=j$(j$(this).parent().find("a:contains("+nextAttr+")"));
					if(page<myPagerClass.pageNumbers){

						nextEl.attr("class","pag");
						nextEl.attr("href","#");
						nextEl.attr("title",""+(page+1));
					}else{
						nextEl.attr("class","disabled");
						nextEl.removeAttr("href");

					}
					myPagerClass.goToPage(page);
					}
			}
			);

		});
	}

	this.showValues=function(data){
		this.widget.showValues(data,"#"+this.key,this.page);
	}
	this.init();
}

/*
	Questa classe gestisce tutta la logica di comunicazione con i relativi servizi in versione AJAX.
	ATTENZIONE: inizializzare l'oggetto nel modo corretto. Il comportamento non è garantito in caso di errori
*/
function Widget(widgetId,sub_service,el,service,widgetPageId,templateFactory,styleClass,timeout,resources){
	if(resources==undefined || resources==null){
		if(typeof(commonPropertyResources)=="undefined" || (commonPropertyResources==undefined || commonPropertyResources==null)){
			commonPropertyResources={dati_non_disponibili:""};
		}
		resources=commonPropertyResources;
		
	}
	this.resources=resources;
	this.sub_service=sub_service;
	//this.el=el;
	this.query="#"+widgetPageId;
	this.id=widgetId;
	this.service=service;
	this.services=new Array();
	this.templateFactory=templateFactory;
	this.styleClass=styleClass;
	this.widgetPageId=widgetPageId;
	var callerObj=this;
	if(timeout==null || timeout==undefined){
		timeout=50;
	}
	this.timeout=timeout;
	function jsonResponse(data,responseStatus,cacheMode,respOb) {
		if(respOb==undefined)respOb=this;
		var root=j$(callerObj.query);
		root._enabled=true;
		if(cacheMode==null || cacheMode==undefined)cacheMode=true;
		if(cacheMode==true && cache!=null){
			if(data.isError==true){
			}else{
			 cache.setItem(respOb.url, data, {expirationAbsolute: null,
                 expirationSliding: callerObj.timeout,
                 priority: CachePriority.High,
                 callback: function(k, v) {  }
                });
            }
		}


		root.find(".testo_senza").css("display","none");
		root.find(".testo").css("display","block");
		
		var table  = callerObj.templateFactory.create(root.find(".testo #"+callerObj.styleClass));
		if(data.isError==true){
			var message="site.err1";
			if(typeof(commonErrors)=="undefined"){
				message="??site.err1??";
			}else{
				message=commonErrors[message];
			}
			table.start();
			table.end(); 
			table.el.html("<br/>"+"<div style='width:100%;height:129px;padding-top:80px;text-align:center;'><a>"+message+"</a></div>");
			//root.find(".testo "+callerObj.styleClass).html("<div style='width:100%;height:129px;padding-top:80px;text-align:center;'><a>"+message+"</a></div>");
		}else{


			

			var k=data.length;

			var kItem=0;
			if(k>0){
				table.start();
				for(kItem=0;kItem<k;kItem++){
					var item=data[kItem];
					table.addProfile(item,item.tit,item.desc,item.cat,"ass_foto01.jpg",item.id);
				}
				table.end();
			}else if(k==0){
				table.start();
				
				table.end();
				table.el.html("<br/>"+callerObj.resources.dati_non_disponibili+"");
			}
		}
	}

	this.showValues=function (data,urlReplacementKey,urlReplacementValue){
		//var el=this.el;
		var sub_service=this.sub_service;

		var root=j$(this.query);
		//var root=j$(el).parents("#"+this.widgetPageId);
		root.find(".testo_senza").css("display","block");
		root.find(".testo").css("display","none");


		var __url=this.service.url;


		if(urlReplacementKey!=null){
			var tmpUrl=__url.replace(urlReplacementKey,urlReplacementValue);
			if(tmpUrl==__url){
				alert("eccezione non prevista");
			}
			__url=tmpUrl;
		}

		if(this.service.output=="json"){
			var jsonurl=__url;
			
			if(cache!=null && cache.getItem(jsonurl)!=null){

				jsonResponse(cache.getItem(jsonurl),"success",false);
			}else{
				var callerObj=this;

		 
				
				var proxy = new serviceProxy(jsonurl);
				proxy.invoke(
	  				  jsonResponse,    
					  function (){
					   	jsonResponse({isError:true},"error",null,eval("("+"{url:'"+jsonurl+"'}"+")"));
					  }         
	            );

				/*
				j$.getJSON(
						jsonurl,
						jsonResponse

				);
				*/
			}
		}else if(this.service.output=="html"){


			j$(root.find(".testo #"+this.styleClass)).load(__url,function(){



				j$(j$(this).parents(".testo")).siblings(".testo_senza").css("display","none");
				j$(j$(this).parents(".testo")).css("display","block");
				reinitialiseScrollPane();
			});
		}else{
			alert("il servizio non esiste:"+this.service.output);
		}

	}
}

/*
	Questa classe gestisce tutta la logica di comunicazione con i relativi servizi in versione STATICA.
	ATTENZIONE: inizializzare l'oggetto nel modo corretto. Il comportamento non è garantito in caso di errori
*/
function StaticWidget(widgetId,service_output,el,widgetPageId,templateFactory,styleClass,resources){
	if(resources==undefined || resources==null){
		if(typeof(commonPropertyResources)=="undefined" || (commonPropertyResources==undefined || commonPropertyResources==null)){
			commonPropertyResources={dati_non_disponibili:""};
		}
		resources=commonPropertyResources;
	}
	this.resources=resources;
	
	this.service_output=service_output;


	this.query="#"+widgetPageId;
	this.id=widgetId;

	this.services=new Array();
	this.templateFactory=templateFactory;
	this.styleClass=styleClass;
	this.widgetPageId=widgetPageId;
	var callerObj=this;

	this.jsonResponse=function(data) {



		var root=j$(this.query);
		root.find(".testo_senza").css("display","none");
		root.find(".testo").css("display","block");

		if(data.isError==true){
			var message="errori nel caricamento";
			//commonErrors[data.localizedMessage];
			root.find(".testo "+this.styleClass).html("<div style='width:100%;height:129px;padding-top:80px;text-align:center;'><a>"+message+"</a></div>");
		}else{


			var table  = this.templateFactory.create(root.find(".testo #"+callerObj.styleClass));

			var k=data.length;

			var kItem=0;
			table.start();
			if(k>0){
				
				for(kItem=0;kItem<k;kItem++){
					var item=data[kItem];
					table.addProfile(item,item.tit,item.desc,item.cat,"ass_foto01.jpg",item.id);
				}
				table.end();
			}else if(k==0){
				table.start();
				
				table.end();
				table.el.html("<br/>"+callerObj.resources.dati_non_disponibili+"");
			}

		}
	}

	this.showValues=function (result){
		if(this.service_output=="json"){


				//var callerObj=this;

				this.jsonResponse(result);



		}else if(this.service_output=="html"){


			alert("servizio non implementato");
		}else{
			alert("il servizio non esiste:"+this.service.output);
		}

	}
}
/*
	dispositivo che incapsula il comportamento che esegue la chiamata al servizio
	tramite l'interfaccia delle tabsheet
*/
function TabSheet(factory,widgetPageId){
	this.factory=factory;
	this.widgetPageId=widgetPageId;
	var callerObj=this;
	/*
		simula il click
	*/
	this.selectTab=function(sub_service){
		//TODO
		this.executeCommand(sub_service);
	}
	/*
		esegue la chiamata al servizio
	*/
	this.executeCommand=function(sub_service){
		var widget=this.factory.create(sub_service);
		widget.showValues();
	}
	this.init=function(){
		j$("#"+this.widgetPageId+" div[@id='"+this.widgetPageId+"_tabs'] div.tab_back_center").mouseup(
			function(){
				var cc=(j$(this).parent().attr('class'));
				if(cc=='bottone_off'){
					//inizializzo div delle pagine
					j$("#"+callerObj.widgetPageId+" div.pageScroller").html("");
					j$("#"+callerObj.widgetPageId+" div.pageScroller").html("");
					j$("#"+callerObj.widgetPageId+" div.riga").css("display","none");
					var tab=j$(this).text();
					var c = j$(this);
					var sub_service=j$(j$(this).siblings("div.frank__mappingName")).text();

					callerObj.executeCommand(sub_service);
				}
				}
			);
	}
	this.init();
}
/*
	dispositivo che incapsula il comportamento che esegue la chiamata al servizio
	tramite l'interfaccia di ricerca widget
*/
function HomeSearcher(factory,widgetId){
	this.factory=factory;
	this.widgetId=widgetId;

	var callerObj=this;
	/*
		esegue la chiamata al servizio
	*/
	this.executeCommand=function(sub_service){
		var widget=this.factory.create(sub_service);
		widget.showValues();
	}
	this.init=function(){
		j$("#"+this.widgetId+" input.btn_salva").each(function(i){

				var j$this = j$(this);

				j$this.click( function(event) {
							event.preventDefault();
							var id = 3;
							var c = j$this;

							var sub_service=(c.parent()).find("li input:checked[@name='service_name']")[0].getAttribute('value');

							callerObj.executeCommand(sub_service);
						});
				});
	}
	this.init();
}

