/* Simple AJAX Code-Kit (SACK) */
/* ©2005 Gregory Wild-Smith */
/* www.twilightuniverse.com */
/* Software licenced under a modified X11 licence, see documentation or authors website for more details */

function sack(file){
	this.AjaxFailedAlert = "Your browser does not support the enhanced functionality of this website, and therefore you will have an experience that differs from the intended one.\n";
	this.requestFile = file;
	this.method = "POST";
	this.URLString = "";
	this.encodeURIString = true;
	this.execute = false;

	this.onLoading = function() { };
	this.onLoaded = function() { };
	this.onInteractive = function() { };
	this.onCompletion = function() { };

	this.createAJAX = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (err) {
				this.xmlhttp = null;
			}
		}
		if(!this.xmlhttp && typeof XMLHttpRequest != "undefined")
			this.xmlhttp = new XMLHttpRequest();
		if (!this.xmlhttp){
			this.failed = true; 
		}
	};
	
	this.setVar = function(name, value){
		if (this.URLString.length < 3){
			this.URLString = name + "=" + value;
		} else {
			this.URLString += "&" + name + "=" + value;
		}
	}
	
	this.encVar = function(name, value){
		var varString = encodeURIComponent(name) + "=" + encodeURIComponent(value);
	return varString;
	}
	
	this.encodeURLString = function(string){
		varArray = string.split('&');
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split('=');
			if (urlVars[0].indexOf('amp;') != -1){
				urlVars[0] = urlVars[0].substring(4);
			}
			varArray[i] = this.encVar(urlVars[0],urlVars[1]);
		}
	return varArray.join('&');
	}
	
	this.runResponse = function(){
		eval(this.response);
	}
	
	this.runAJAX = function(urlstring){
		this.responseStatus = new Array(2);
		if(this.failed && this.AjaxFailedAlert){ 
			alert(this.AjaxFailedAlert); 
		} else {
			if (urlstring){ 
				if (this.URLString.length){
					this.URLString = this.URLString + "&" + urlstring; 
				} else {
					this.URLString = urlstring; 
				}
			}
			if (this.encodeURIString){
				var timeval = new Date().getTime(); 
				this.URLString = this.encodeURLString(this.URLString);
				this.setVar("rndval", timeval);
			}
			if (this.element) { this.elementObj = document.getElementById(this.element); }
			if (this.xmlhttp) {
				var self = this;
				if (this.method == "GET") {
					var totalurlstring = this.requestFile + "?" + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					this.xmlhttp.open(this.method, this.requestFile, true);
				}
				if (this.method == "POST"){
  					try {
						this.xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded')  
					} catch (e) {}
				}

				this.xmlhttp.send(this.URLString);
				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState){
						case 1:
							self.onLoading();
						break;
						case 2:
							self.onLoaded();
						break;
						case 3:
							self.onInteractive();
						break;
						case 4:
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;
							self.onCompletion();
							if(self.execute){ self.runResponse(); }
							if (self.elementObj) {
								var elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								if (elemNodeName == "input" || elemNodeName == "select" || elemNodeName == "option" || elemNodeName == "textarea"){
									self.elementObj.value = self.response;
								} else {
									self.elementObj.innerHTML = self.response;
								}
							}
							self.URLString = "";
						break;
					}
				};
			}
		}
	};
this.createAJAX();
}

// CLASSE AJAX

function ClassAJAX () {

	this.xmlhttp = null ;
	this.stato = "" ;
	//var urlstring="www.moboffice.it";
	this.reset = function() {
		
		this.execute = false; //se true fatica come sappiamo....mette codice ottenuto da file php in id_span
		this.returnVal = false ;
		this.html = "" ;
  		this.element = null;	// Ã¨ l'id dell'oggetto (l'id_span)
		this.elementObj = null;
		this.responseStatus = new Array(2);
		this.vars = Array () ;
		this.stato = "" ;
		this.actionType = "" ;
		this.spanLoading = "loading" ;
		this.flagLoading = false ;
		this.method="GET" ;
		
		this.movex=0 ;
		this.movey=0 ;
		this.xdiff=0 ;
		this.ydiff=0 ;
		this.ystart=0 ;
		this.xstart=0 ;
		this.elFake ;
		this.x ;
		this.y ;
		
		this.onFailed = function() { };
	};
	
	//	creo oggetto XHTMLHTTP compatibile col browser altrimenti setto 
	//	variabile booleana this.failed = true ;
	this.createAJAX = function() {
		
		/*try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
			alert("1");
		} catch (e1) {*/
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				//alert("2");
			} catch (e2) {
				this.xmlhttp = null;
				//alert("3");
			}
	//	}
		if (! this.xmlhttp) {
			if (typeof XMLHttpRequest != "undefined") {
				this.xmlhttp = new XMLHttpRequest();
				//alert("4");
			} else {
				this.failed = true;
				//alert("5");
			}
		}
	};
	
	
	// metodo che mi ritorna il codice dall' url che passo come parametro
	this.runAJAX = function(urlstring) {
		
	
		if (this.failed) {
			//se ho avuto problemi in createAJAX vado in function onFailed()
			this.onFailed() ;
		} else {			
			
			if (this.element) {
				this.elementObj = document.getElementById(this.element);
			}
			
			if (this.xmlhttp) {
			
				var self = this ;
				
				this.xmlhttp.open(this.method, urlstring, true);
				
				this.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				this.xmlhttp.setRequestHeader("Content-length", urlstring.length);
				this.xmlhttp.setRequestHeader("connection", "close");
				this.xmlhttp.setRequestHeader("keep-alive", 0);
				this.xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
				this.xmlhttp.setRequestHeader("Pragma", "no-cache");
				this.xmlhttp.setRequestHeader("Accept-Encoding", "gzip, deflate");
						
				this.xmlhttp.onreadystatechange = function() {

					switch (self.xmlhttp.readyState) {
			
						case 1:
							self.onLoading();
						break;
						
						case 2:
							self.onLoaded();
						break;
						
						case 3:
							self.onInteractive();
						break;
						
						case 4:
							
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;
							
							if (self.execute) {	//se devo fare l'innerHTML del contenuto dinamico nell'elemento
								self.changeHtml();
							}
							else if (self.returnVal) {
								self.storeHtml();
							}
							else {
								
								/*
									QUI CAZZI PER AUTOCOMPLETE etc ....
								*/
								switch (self.actionType) {
										
									default :
									
										if (self.elementObj) {
											
											elemNodeName = self.elementObj.nodeName;
											elemNodeName.toLowerCase();
																							
											if (elemNodeName == "input" || elemNodeName == "select" || elemNodeName == "option" || elemNodeName == "textarea") {
												//self.elementObj.value = self.response;
												showSuggest(self.response, '', self.vars) ;
																						
											} else {
												//self.elementObj.innerHTML = self.response;
												showSuggest(self.response, 'inner', self.vars) ; 
											}
										}
										
										if (self.responseStatus[0] == "200") {
											self.onCompletion();
											alert("sono in 200="+self.xmlhttp.readyState);	
											
										} else {
											self.onError();
										}
									break ;
																		
								}
							}
							
							self.onComplete() ;
							
						break;
					}
				} ;		
				//this.xmlhttp.open(this.method, urlstring, true);
				this.xmlhttp.send(null);
			}
		}
		
	}
	
	this.setMethod = function (m) {
		this.method = m ;
	};
	
	this.changeHtml = function () {
		this.elementObj.innerHTML = '' ;
		this.elementObj.innerHTML = this.response ;
	};
	
	this.storeHtml = function () {
		this.html = this.response ;
	};
	
	this.getHtml = function () {
		if (this.html) {
			return this.html ;
		} else {
			return false;	
		}
	};
	
	this.setElement = function(elementId) {
		this.element = elementId ;
	};
	
	this.setExecute = function(bool) {
		this.execute = bool ;
	};
	
	this.setReturn = function(bool) {
		this.returnVal = bool ;
	};
			
	this.setActionType = function(actType) {
		this.actionType = actType ;
	};
	
	this.setVars = function (key,val) {
		this.vars[key] = val ;
	};
	
	this.setLoading = function (spanloading) {
		this.spanLoading = spanloading ;
	};

	this.onFailed = function () {
		alert ("onFailed") ;
	};
	
	
	this.onLoading = function () {
		
		if (this.spanLoading) {
			
			switch (this.spanLoading) {
				
				default :
										
					//var l = (window.innerWidth - 300) / 2 ;
					//var t = (window.innerHeight - 100) / 2 ;
					
					var arrayPageSize = getPageSize();
					var w = arrayPageSize[0] ;
					var h = arrayPageSize[1] ;
					
					
									
					var bodyPage = document.getElementById("body") ;
					
					var divNode = document.createElement('div') ;
					
					
					
					divNode.setAttribute('id', this.spanLoading) ;	
					divNode.style.display="" ;
					divNode.style.backgroundImage="url(http://"+window.location.host+"/img/griglia.gif)" ;
					divNode.style.position="absolute" ;
					divNode.style.width=w+"px" ;
					divNode.style.height=h+"px";
					
					divNode.style.zIndex="91";	
					divNode.style.top = "0px" ;
					divNode.style.left = "0px" ;
					
					var divLoad = document.createElement('div') ;
					var l = (screen.width - 300) / 2;
				    var t = (screen.height - 200) / 2;
				     
				    var offset = 0;
					if (navigator.appName == "Microsoft Internet Explorer")
						offset = document.documentElement.scrollTop;
					else offset = window.pageYOffset;
					var offsetstr = offset.toString() + "px";
					
					
					
				    divLoad.style.top = offset+t+"px";
				    divLoad.style.left = l+"px" ;
							
					divLoad.innerHTML = '<div id="'+this.spanLoading+'_inner" style="display: table; position:absolute; background-color:#fff; border:2px solid #1e4a97 ; left:'+l+'px; top:'+t+'px; width:300px; height:100px;">' +  

										'<div style="#position: absolute; #top: 50%;display: table-cell; vertical-align: middle;">' +
										'<div style=" #position: relative; #top: -50%; text-align:center">' +
										'<img src="http://'+window.location.host+'/img/ajax-loader.gif">' +
										'</div>' +
										'</div>' +
		
										'</div>' ;
					 				
					divNode.appendChild(divLoad) ; 				
					bodyPage.appendChild(divNode) ;
					
					this.flagLoading = true ;
				
				break ;
			}
		}
		
		
	};
	
	
	/*this.onLoading = function () {
		
		if (this.spanLoading) {
			
			switch (this.spanLoading) {
				
				default :
										
					var l = (window.innerWidth - 300) / 2 ;
					var t = (window.innerHeight - 100) / 2 ;
					
					var arrayPageSize = getPageSize();
					var w = arrayPageSize[0] ;
					var h = arrayPageSize[1] ;
					
					var bodyPage = document.getElementById("body") ;
					
					var divNode = document.createElement('div') ;
					
					divNode.setAttribute('id', this.spanLoading) ;	
					divNode.style.display="" ;
					divNode.style.backgroundImage="url(http://admin.moboffice.it/img/griglia.gif)" ;
					divNode.style.position="absolute" ;
					divNode.style.width=w+"px" ;
					divNode.style.height=h+"px";
					
					divNode.style.zIndex="91";	
					divNode.style.top = "0px" ;
					divNode.style.left = "0px" ;
							
					divNode.innerHTML = '<div id="'+this.spanLoading+'_inner" style="position:absolute; left:'+l+'px; top:'+t+'px; width:300px; height:100px;">' + 
										'<table class="caricamento" border="0" cellpadding="0" cellspacing="0" width="300" height="100">' +
										'<tr><td valign="middle" align="center">' +
										'<b>Attendere...</b>' +
										'</td></tr>'+
										'<tr><td align="center"><img src="http://admin.moboffice.it/img/loader.gif"></td></tr>'+
										'</table>' +
										'</div>' ;
											
									
					bodyPage.appendChild(divNode) ;
					
					this.flagLoading = true ;
					
					this.setVariables() ;
					this.checkLocation() ;
									
				break ;
			}
		}
		
		
	};*/
	
	this.onComplete = function () {
		
		if (this.flagLoading) {		
			
			var bodyPage = document.getElementById("body") ;
			var divNode = document.getElementById(this.spanLoading);
			
			bodyPage.removeChild(divNode) ;
			
			this.flagLoading = false ;
		}
	};
	
	this.onLoaded = function () {
		this.stato = "loaded" ;
	};
	
	this.onInteractive = function () {
		//alert ("onInteractive") ;
	};
	
	this.onCompletion = function () {
		//alert ("onCompletion") ;	
	};
	
	this.onError = function () {
		//alert ("onError") ;
	};
	
	this.getStatus = function () {
		
		return this.stato ;
	};
	
	this.getUrlParams = function (the_form) {
		
		var num = the_form.elements.length;
		var url = "";
		var radio_buttons = new Array();
		var nome_buttons = new Array();
		var check_buttons = new Array();
	
		// submit radio values
		var j = 0;
		var a = 0;
		for(var i=0; i<the_form.length; i++){
			var temp = the_form.elements[i].type;
			if ( (temp == "radio") && ( the_form.elements[i].checked) ) { 
				nome_buttons[a] = the_form.elements[i].name;
				radio_buttons[j] = the_form.elements[i].value; 
				j++; 
				a++;
			}
		}
		for(var k = 0; k < radio_buttons.length; k++) {
			url += nome_buttons[k] + "=" + radio_buttons[k] + "&";
		}
	
		// submit checkbox values
		var j = 0;
		var a = 0;
		for(var i=0; i<the_form.length; i++){
			var temp = the_form.elements[i].type;
			if ( (temp == "checkbox") && ( the_form.elements[i].checked) ) { 
				nome_buttons[a] = the_form.elements[i].name;
				check_buttons[j] = the_form.elements[i].value; 
				j++; 
				a++;
			}
		}
		for(var k = 0; k < check_buttons.length; k++) {
			url += nome_buttons[k] + "=" + check_buttons[k] + "&";
		}
	
		// submit all kind of input		
		for (var i = 0; i < num; i++){	
			var chiave = the_form.elements[i].name;
			var valore = the_form.elements[i].value;
			var tipo = the_form.elements[i].type;
	
			if ( (tipo == "submit") || (tipo == "radio") || (tipo == "checkbox") ){}
			else {
				url += chiave + "=" + valore + "&";
			}
		}
	
		var parameters = url;
		return url ;
	};
	
	this.setVariables = function (){
		
		if (navigator.appName == "Netscape") {
			if (parseInt(navigator.appVersion) >= 5){
				v=".top=";
				h=".left=";
				dS="document.getElementById(\"";sD="\").style";
				this.y="window.pageYOffset";
				this.x="window.pageXOffset";
			}
			else {
				v=".top=";
				h=".left=";
				dS="document.";
				sD="";
				this.y="window.pageYOffset";
				this.x="window.pageXOffset";
			}
		}
		else {
		//ENTRO QUI
			h=".pixelLeft=";
			v=".pixelTop=";
			dS="";
			sD=".style";
			this.y="document.body.scrollTop";
			this.x="document.body.scrollLeft";
		}
				
		this.checkLocationA() ;
	};
	
	
	this.checkLocation = function(){
		
		try {
		
			object="obj";
			yy=eval(this.y);
			xx=eval(this.x);
			this.ydiff=this.ystart-yy;
			this.xdiff=this.xstart-xx;
			
			if ((this.ydiff<(-1))||(this.ydiff>(1))) {
				this.movey=Math.round(this.ydiff/10) ;
				this.ystart-=this.movey ;
			}
			if ((this.xdiff<(-1))||(this.xdiff>(1))) {
				this.movex=Math.round(this.xdiff/10) ; 
				this.xstart-=this.movex ;
			}
			
			var divNode = document.getElementById(this.spanLoading+'_inner');
			
			if (this.ystart>=10){
				
				var newY = this.ystart+10 ;
				divNode.style.top=newY+'px' ;
				
			} 
			else {
				
				var newY = 10 ;
				divNode.style.top=newY+'px' ;
			}
		
			var newX = this.xstart ;
			divNode.style.left=newX+'px' ;
			
			//alert("sposto in left:" + newX + " top:" + newY) ;
			
			if (this.flagLoading) {
				var self = this;
				setTimeout(function(){
					self.checkLocation();
				}, 10);
			}
		}
		catch(e) {}
		
	}
	
	this.checkLocationA = function(){
		this.ystart=eval(this.y);
		this.xstart=eval(this.x);
	}
	
	this.reset();
	this.createAJAX();
}
/*
 ---------------------------------
*/


function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}



