/*
 * Jyingo, PHP Ajax Toolkit http://www.jyingo.com
 * Copyright 2007-2008 by SiberianSTAR aka Andrea Pezzino
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
 
function $get(what) { for (var i = 0; i < jyingo.arrCustomObjects.length; i++) {if (jyingo.arrCustomObjects[i].get_name() == what) return jyingo.arrCustomObjects[i];} if ( document.getElementById(what) ) return document.getElementById(what); if (document.forms.form1[what]) return document.forms.form1[what]; return null}
function global_replace(cosa, con, dove) { return dove.split(cosa).join(con); }
function canceldefault(evt) { jyingo.cancelEvent(evt, false); }
Function.createDelegate=function(a,b){return function(){return b.apply(a,arguments)}};


var jyingo = {
	
 arrCustomObjects : new Array(),
 active_timers_array : new Array(),
 is_postback : false,
 loadingHandler : null,
 endLoadingHandler : null,
 currentEvents : new Array(),
 is_under_msgbox : null,

 init : function()
 {
 	 this.addEvent._i = 1;
 	 this.is_under_msgbox = false;
 },
 
 isUnderMsgBox : function()
 {
 	 return this.is_under_msgbox;
 },

 initializeBase : function(name, what, element)
 {
 	  var newArr = new Array();
 	  
   	for (var i = 0; i < this.arrCustomObjects.length; i++)
   	{
   		
   		 // è un duplicato
   		 if (this.arrCustomObjects[i].get_name() == name)
   		 {
   		 	 var obj = this.arrCustomObjects[i];
   		 	 obj.dispose(); 
   		 }
   		 else
   		 {
   		 	 newArr.push(this.arrCustomObjects[i]);
   		 }
   	}
   	
   	this.arrCustomObjects = newArr;
   	what._element = element;
   	what._name = name;   	
   	this.arrCustomObjects.push(what);

   	what.get_name = function()
   	{
   		 return this._name;
   	}
   	
   	what.get_element = function()
   	{
   		 return this._element;
   	},
   	
   	what.set_element = function(element)
   	{
   		 this._element = element;
   	}
   	
   	
   	
   
 	
 },
 
 addEvent : function(o, t, f, l)
 {
 	
 	if (!o) return;

 	for (var i = 0; i < this.currentEvents.length; i++)
 	{
 	
 		 var p = this.currentEvents[i];
 		 if (p[0] == o && p[1] == t && p[2] == f && p[3] == l)
 		 {
 		 	 jyingo.removeEvent(o, t, f, l);
 		 	 this.currentEvents.splice(i, 1);
 		 	 break;
 		 }
 	}
 	
 	this.currentEvents.push(new Array(o, t, f, l));
 	
  var d = 'addEventListener', n = 'on' + t, rO = o, rT = t, rF = f, rL = l;
  if (o[d] && !l) return o[d](t, f, false);
  if (!o._evts) o._evts = {};
  if (!o._evts[t])
  {
   o._evts[t] = o[n] ? { b: o[n] } : {};
   o[n] = new Function('e',
    'var r = true, o = this, a = o._evts["' + t + '"], i; for (i in a) {' +
     'o._f = a[i]; r = o._f(e||window.event) != false && r; o._f = null;' +
     '} return r');
   if (t != 'unload') this.addEvent(window, 'unload', function() {
    jyingo.removeEvent(rO, rT, rF, rL);
   });
  }
  if (!f._i) f._i = this.addEvent._i++;
  o._evts[t][f._i] = f;
 },
 
 removeEvent : function(o, t, f, l)
 {
 	
 	for (var i = 0; i < this.currentEvents.length; i++)
 	{
 		 var p = this.currentEvents[i];
 		 if (p[0] == o && p[1] == t && p[2] == f && p[3] == l)
 		 {
 		 	 this.currentEvents.splice(i, 1);
 		 	 break;
 		 }
 	} 	
 	
  var d = 'removeEventListener';
  if (o[d] && !l) return o[d](t, f, false);
  if (o._evts && o._evts[t] && f._i) delete o._evts[t][f._i];
 },
 
 checkmax : function(who, how)
 {
 	
 	 var el = $get(who);
 
 	 if (el)
 	 {
 	 	 
 	 	 if (el.value.length > how)
 	 	  el.value = el.value.substr(0, how);
 	 	
 	 }
 	
 },
 
 cancelEvent : function(e, c)
 {
   e.returnValue = false;
   if (e.preventDefault) e.preventDefault();
   if (c)
   {
     e.cancelBubble = true;
     if (e.stopPropagation) e.stopPropagation();
   }
  },
   
  postback : function(evtcaller, evtmethod)
  {
  	dopostback(evtcaller, evtmethod);
  },
    
  command : function(data)
  {
	  jyingo.is_postback = true;
	  var arr = data.split("};");
	
		var out = eval('(' + arr[0] + "}"+ ')');
		switch (out['cmd'])
		{
			case 'reload':
			 location.href=location.href;
			break;
			case 'redirect':
			
			 location.href = out['url'].replace('{CURRENT}', escape(location.href));
			break;
			case 'regscript':
		   var js = out['js'];
		   var t;
		   t = global_replace("\\'","[[[[=]]]!]",js)
		   t = global_replace("'","\\'",t)
		   t = global_replace("[[[[=]]]!]","\\\\'",t)
		   t = global_replace("\r\n","", t);
       t = global_replace("\r","", t);
       t = global_replace("\n","", t);
		   eval("setTimeout('"+t+"',0);");
		   
			break;
		
		}
		
		if (arr.length>1)
		{
			
			
			var p =  data.indexOf("};");
			p = data.substring(p+2);
			
			return p;
			
			
		}
		return 0;
 },

 update : function(what)
 {
	 dopostback(what,'update');
 },
 
 start_timer : function(name, interval, code, prevent_postback)
 { 	
  
  code = unescape(code);
  this.stop_timer(name);
  
  if (prevent_postback == false)
   code += "; dopostback('"+name+"','timer');";
  
 	this.active_timers_array[name] = setInterval(code, interval);
 },
 
 stop_timer : function(name)
 {
 	if (this.active_timers_array[name])
 	{
 	  clearInterval(this.active_timers_array[name]);
 	  delete this.active_timers_array[name];	
 	} 	
 }
 
}

// init jyingo
jyingo.init();

jyingo.upload = function (name, element)
{
	 jyingo.initializeBase(name, this, element);
   this.handle = null;
   this._selected = false;
   this._filesize = 0;
   this._filename = 0;
   this._uploading = false;
   this._send_after = false;
   this.file_types = [
   
    {description : "Tutti i file (*.*)",
    extension : "*.*"}
   
   ];
}

jyingo.upload.prototype = {
 
  initialize : function(handle, cb_start, cb_progress, cb_end, send_after,ext_filter)
  {
  	 this.cb_start = cb_start;
  	 this.cb_progress = cb_progress;
  	 this.cb_end = cb_end;
  	 
  	 this._send_after = true;
  	 this.end_service_method = Function.createDelegate(this, this.cb_svbm);
  	 this.handle = handle;
  	 
  	 if (ext_filter)
  	 {
  	 	 var filters = new Array();
  	 	 var vz = 0;
  	 	 var es = ext_filter.split('|');
  	 	 for (vz = 0; vz < es.length; vz+=2)
  	 	 {
  	 	 	 
  	 	 	 filters[vz]= new Array();
  	 	 	 filters[vz]['description'] = es[vz];
  	 	 	 
  	 	 	 filters[vz]['extension'] = es[vz+1];
  	 	 	 
  	 	 	 
  	 	 }
  	 	 this.file_types=filters;
  	 	
  	 }
  	 
  },
  
  cb_svbm : function(arr)
  {
   	 if (this.cb_end)
  	  setTimeout(cb_end + ';',0); 	   	
  },
  
  
  get_filesize : function()
  {
  	 if( this._selected )
  	 return this._filesize;
  	 else
  	 return 0;
  },
  
  get_filename : function()
  {
   	 if( this._selected )
  	 return this._filename;
  	 else
  	 return 0; 	 
  },
  
  get_selected : function()
  {
  	 return this._selected;
  },
  
  get_filetypes : function()
  {
  	 return this.file_types;
  },
  
  push_error : function(err)
  { 
  	var p = new Array();
     	 if (this.cb_end)
  	  setTimeout(this.cb_end + ';',0);  
  	 callservicemethod_fake('upl_'+this.get_name(),p,this.end_service_method);  	 
  },
  
  dispose : function()
  {
  	
  },
  
  show_openfile : function()
  {
  	
     this._element.opendialog();
  },
  
  send : function()
  {
  	if (this._selected == false)
  	 this._send_after=true;
  	else
  	 this._element.start_upload();
  },
  
  upload_end : function()
  {
  	 var p = new Array();
    	 if (this.cb_end)
  	  setTimeout(this.cb_end + ';',0);  	 
  	 callservicemethod_fake('upl_'+this.get_name(),p,this.end_service_method);

  },
  
  is_uploading : function()
  {
  	 return this._uploading;
  },
  
  start_upload : function()
  {

  	 if (this.cb_start)
  	  setTimeout(this.cb_start + ';',0);
  	 
  },
  
  upload_progress : function()
  {
  	 if (this.cb_progress)
  	 setTimeout(this.cb_progress+';',0);
  },
  
  get_bytes_sent : function()
  {
  	 return this._bytes_sent;
  },
  get_bytes_total : function()
  {
  	 return this._bytes_total;
  },
  get_percentage : function()
  {
  	 return this._percent;
  }
};


function dopostback_cb(data)
{
  jyingo.is_postback = true;
  
	var out2 = eval('(' + data + ')');
	
	var narr = new Array();
	
	if (out2['container'] != undefined)
	 narr.push(out2);
	else
	{
	 narr = out2;
   
	}
	
	for (var i = 0; i < narr.length; i++)
	{
	 
   var out = narr[i];
   if (out['container'])
	 if (out['container'] == 'page_body')
	 {
		document.body.innerHTML = out['data'];
	 }
	 else
	 {

		document.getElementById("ctl_"+out['container']).innerHTML = out['data'];
	 }
	
  }

	if (jyingo.endLoadingHandler != null)
	 jyingo.endLoadingHandler();
	
}
function callservicemethod_fake(servicename, data, callback)
{
	 var arr = new Array();
	 arr.push(new Array('jyingo_sessid', document.forms.form1.jyingo_sessid.value));
	 arr.push(data);
	 
	 var jdata = JSON.stringify(arr);
   
	 x_dopostback('_servicemethod', servicename, jdata, dopostback_cb);
}
function callservicemethod(servicename, data, callback)
{
	 var arr = new Array();
	 arr.push(new Array('jyingo_sessid', document.forms.form1.jyingo_sessid.value));
	 arr.push(data);
	 
	 var jdata = JSON.stringify(arr);
   
	 x_dopostback('_servicemethod', servicename, jdata, callback);
}

function dopostback(eventcaller, eventmethod)
{
	
	var frm = document.forms.form1;
	var arr = new Array();
	
	for (var i = 0; i < frm.length; i++)
	{
		 
		if (frm[i].type == undefined) continue;
		 
	  if (frm[i].type.toLowerCase() == 'checkbox')
	  {
	 	 arr.push(new Array(frm[i].name, frm[i].checked));
	  }
	  else
	  if (frm[i].type.toLowerCase() == 'radio')
	  {
	   if (frm[i].name.substr(0,12) == "ctl_optgroup")
	 	  arr.push(new Array(frm[i].id, frm[i].checked));
	 	 else
	 	  arr.push(new Array(frm[i].name, frm[i].checked));	
	  }
	  else	  	
		 arr.push(new Array(frm[i].name, escape(frm[i].value).split('+').join('%2B') ));

	}
	
	for (var i = 0; i < jyingo.arrCustomObjects.length; i++)
	{
		 var obj = jyingo.arrCustomObjects[i];
		 if (obj.get_update_value)
		 {
		 	 
		 	 var uval = obj.get_update_value();
		 	 if (uval != null)
		 	  arr.push(new Array('ctl_' + obj.get_name(), escape(uval)));
		 	 
		 }
	} 
	
  if (jyingo.endLoadingHandler != null)
	 jyingo.loadingHandler();	
	
	x_dopostback(eventcaller, eventmethod, JSON.stringify(arr), dopostback_cb);
	
}

timed_alert = function(txt)
{
	this.txt = txt;
	setTimeout ( Function.createDelegate(this, this.msgbox), 90);
}

timed_alert.prototype = {
	 
	 msgbox : function() { jyingo.is_under_msgbox = true; alert(this.txt); jyingo.is_under_msgbox = false; }
	 
}

function alert_timed(txt)
{
   
	 var p = new timed_alert(txt);
}
