// JavaScript Document

function isString(a) 
{
	if (typeof a == 'string') 
		return true;
	if (typeof a != 'object')
		return false;
		
  	return  a.constructor.toString().match(/string/i) != null;
}

function isObject( what ) 
{ 
	return (typeof what == 'object'); 
}
 
function disableAutoSubmit(e)
{
	return (window.event?window.event.keyCode:e.which) != 13;
}

if (String.prototype.trim === undefined) {
	String.prototype.trim = function() {
		return this.replace(/^\s+|\s+$/g,"");
	}
}

String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

String.prototype.toDate = function() {
	if (!(d = /^(\d{4})-(\d{2})-(\d{2})\s*(?:(\d{1,2}):(\d{1,2}):(\d{1,2})?)?/.exec(this)))
		return null;
	
	if (d[4] == undefined)
		return new Date(d[1],d[2]-1,d[3]);

	return new Date(d[1],d[2]-1,d[3],d[4],d[5],d[6]);
}

// version 0.11 by Daniel Rench
// More information: http://dren.ch/strftime/
// This is public domain software

Number.prototype.pad =
	function (n,p) {
		var s = '' + this;
		p = p || '0';
		while (s.length < n) s = p + s;
		return s;
	};

Date.prototype.isLeap = function() {
	var y=this.getFullYear();
	if (y%4)
		return false;
	if (!(y%400))
		return true;
	if (!(y%100))
		return false;
}

Date.prototype.dpm = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

Date.prototype.mesi = [
		'Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno',
		'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre'
	];
Date.prototype.giornisettimana = [
		'Domenica', 'Lunedì', 'Martedì', 'Mercoledì', 
		'Giovedì', 'Venerdì', 'Sabato' 
	];
	
Date.prototype.getLocaleMonthName = function() {
	return this.mesi[this.getMonth()];
}
Date.prototype.getLocaleDayName = function() {
	return this.giornisettimana[this.getDay()];
}
Date.prototype.getMonthDays = function() {
	if (this.getMonth() != 1)
		return this.dpm(this.getMonth());
	return this.isLeap()?29:28;
}

Date.prototype
Date.prototype.months = [
		'January', 'February', 'March', 'April', 'May', 'June', 'July',
		'August', 'September', 'October', 'November', 'December'
	];
Date.prototype.weekdays = [
		'Sunday', 'Monday', 'Tuesday', 'Wednesday',
		'Thursday', 'Friday', 'Saturday'
	];

Date.prototype.strftime_f = {
		A: function (d) { return d.weekdays[d.getDay()] },
		a: function (d) { return d.weekdays[d.getDay()].substring(0,3) },
		B: function (d) { return d.months[d.getMonth()] },
		b: function (d) { return d.months[d.getMonth()].substring(0,3) },
		C: function (d) { return Math.floor(d.getFullYear()/100); },
		c: function (d) { return d.toString() },
		D: function (d) {
				return d.strftime_f.m(d) + '/' +
					d.strftime_f.d(d) + '/' + d.strftime_f.y(d);
			},
		d: function (d) { return d.getDate().pad(2,'0') },
		e: function (d) { return d.getDate().pad(2,' ') },
		F: function (d) {
				return d.strftime_f.Y(d) + '-' + d.strftime_f.m(d) + '-' +
					d.strftime_f.d(d);
			},
		H: function (d) { return d.getHours().pad(2,'0') },
		I: function (d) { return ((d.getHours() % 12 || 12).pad(2)) },
		j: function (d) {
				var t = d.getDate();
				var m = d.getMonth() - 1;
				if (m > 1) {
					var y = d.getYear();
					if (((y % 100) == 0) && ((y % 400) == 0)) ++t;
					else if ((y % 4) == 0) ++t;
				}
				while (m > -1) t += d.dpm[m--];
				return t.pad(3,'0');
			},
		k: function (d) { return d.getHours().pad(2,' ') },
		l: function (d) { return ((d.getHours() % 12 || 12).pad(2,' ')) },
		M: function (d) { return d.getMinutes().pad(2,'0') },
		m: function (d) { return (d.getMonth()+1).pad(2,'0') },
		n: function (d) { return "\n" },
		p: function (d) { return (d.getHours() > 11) ? 'PM' : 'AM' },
		R: function (d) { return d.strftime_f.H(d) + ':' + d.strftime_f.M(d) },
		r: function (d) {
				return d.strftime_f.I(d) + ':' + d.strftime_f.M(d) + ':' +
					d.strftime_f.S(d) + ' ' + d.strftime_f.p(d);
			},
		S: function (d) { return d.getSeconds().pad(2,'0') },
		s: function (d) { return Math.floor(d.getTime()/1000) },
		T: function (d) {
				return d.strftime_f.H(d) + ':' + d.strftime_f.M(d) + ':' +
					d.strftime_f.S(d);
			},
		t: function (d) { return "\t" },
/*		U: function (d) { return false }, */
		u: function (d) { return(d.getDay() || 7) },
/*		V: function (d) { return false }, */
		v: function (d) {
				return d.strftime_f.e(d) + '-' + d.strftime_f.b(d) + '-' +
					d.strftime_f.Y(d);
			},
/*		W: function (d) { return false }, */
		w: function (d) { return d.getDay() },
		X: function (d) { return d.toTimeString() }, // wrong?
		x: function (d) { return d.toDateString() }, // wrong?
		Y: function (d) { return d.getFullYear() },
		y: function (d) { return (d.getYear() % 100).pad(2) },
//		Z: function (d) { return d.toString().match(/\((.+)\)$/)[1]; },
//		z: function (d) { return d.getTimezoneOffset() }, // wrong
//		z: function (d) { return d.toString().match(/\sGMT([+-]\d+)/)[1]; },
		'%': function (d) { return '%' }
	};

Date.prototype.strftime_f['+'] = Date.prototype.strftime_f.c;
Date.prototype.strftime_f.h = Date.prototype.strftime_f.b;

Date.prototype.strftime =
	function (fmt) {
		var r = '';
		var n = 0;
		while(n < fmt.length) {
			var c = fmt.substring(n, n+1);
			if (c == '%') {
				c = fmt.substring(++n, n+1);
				r += (this.strftime_f[c]) ? this.strftime_f[c](this) : c;
			} else r += c;
			++n;
		}
		return r;
	};
	
if (window.console == undefined)
	window.console = {};
if (console.log == undefined)
	console.log = function () {};
	
function spinControl(id_val,step,min_v,max_v)
{
	var n;
	var onchange;
	var me=this;
	
	if (step == undefined)
		step = 1;
		
	n = parseInt($(id_val).html());

	$(id_val)
		.empty()
		.append(
			$("<span />").attr({className: "spin_ctrl"}).click(function() {
				me.step(-1);
			}).html("-")
		)
		.append(
			$("<span />").attr({className: "spin_val"}).click(function() {
				me.step(-1);
			}).html(n)
		)
		.append(
			$("<span />").attr({className: "spin_ctrl"}).click(function() {
				me.step(1);
			}).html("+")
		)
		.mousewheel(function(ev,s) {
			me.step((s>0)?1:-1)
		});
	
	return me = {
		change: function (f) {
			if (f==undefined)
				return onchange;
			onchange = f;
		},
		step: function(d) {
			n += d*step;
			
			if ((min_v != undefined)&&(n<min_v))
				n = min_v;
			if ((max_v != undefined)&&(n>max_v))
				n = max_v;
			$("span.spin_val", id_val).html(n);
			if (onchange != undefined)
				onchange.call(me);
		},
		val: function(v) {
			if (v==undefined)
				return n;
			n = parseInt(v); 
			$("span.spin_val", id_val).html(n);
		}
	};
}

function restClient( m, u, q, p, successo, errore ) {

	if ((q === null)||(q === undefined)) {
		q = {};
	}	
	q.formato = "xjson";

	var msg = {
	    url: u+"?json="+encodeURIComponent($.toJSON(q)),
	    type: m,
	    processData: false,
		contentType: "application/json; charset=utf-8",
		dataType: "xml",
		success: function(data, textStatus) {
			if (successo)
				return successo($.secureEvalJSON(data.getElementsByTagName("d")[0].firstChild.data), textStatus);
		},
		error: errore
	};

	if ((p !== null) && (p !== undefined)) {
		msg.data =$.toJSON(p);
	} 

	$.ajax(msg);
}

function estendi(s,d) {
	for (var a in d)
		if (!$.isPlainObject(d[a]))
			s[a] = d[a];
		else
			estendi(s[a], d[a]);

	return s;

}

function carica_stati(sel_stati) {
	caboa.rest.get( "stati", null, function(e){
		var opzioni = sel_stati[0].options;
		opzioni.length = 1;
		for (var i=0;i<e.length;i++)
			opzioni[opzioni.length] = new Option(e[i].nome, e[i].stato);
	});
}
