﻿/// <reference path="../jquery-1.3.2-vsdoc2.js" />

function selectAllText(textbox) {
	textbox.focus();
	textbox.select();
}

$(document).ready(function() {
	$("#loading").bind("ajaxSend", function() {
		$(this).fadeIn('fast');
	}).bind("ajaxComplete", function() {
		$(this).hide();
	}).bind("ajaxError", function(event, XMLHttpRequest, ajaxOptions, thrownError) {
		// $(document).html(XMLHttpRequest.responseText);
		alert(XMLHttpRequest.responseText);
	});

	// finzionalità per la pressione del tasto di ricerca ( tutti i documenti)
	$("#search-input").focus(function() {
		selectAllText($(this)[0]);
	});

	$('.create-link').setcreate();

	$(".account input").focus(function() {
		var el = $(this);
		if (this.name.endsWith('assword') && el.attr("type") != 'password') {
			var el2 = $('<input/>').attr("type", "password").attr("name", this.name);
			el.after(el2);
			el.remove();
			el2.focus();
		}
		this.select();

	}).blur(function() {
		if (!this.value) { this.value = $(this).attr("title"); }
	});

	$("#acc a").each(function(i) {

		var a = $(this);

		a.mouseover(function() {
			a.addClass("active");
		});

		a.tooltip({
			tip: '#loginscroll',
			position: 'bottom right',
			offset: [-10, -77],
			delay: 400,
			predelay: 200,
			onShow: function(e) {
				a.addClass("active");
			},
			onBeforeHide: function(e, i) {
				a.removeClass("active");
			}
		});
	});

	$(document).keydown(function(e) {
		if (e.keyCode == 27) { closeAcc(); }
	});

	$("#changePassword").submit(function() {
		return formSubmit(this, function() {
			location.reload();
		});
	});

	$("#login").submit(function() {
		return formSubmit(this, function() {
			location.reload();
		});
	});
});

function closeAcc() {
	$("#loginscroll, #signup").slideUp().find(".error").hide();
	$("#acc a").removeClass("active");
}

(function($) {
	$.fn.log = function(msg) {
		if (typeof (console) == "undefined")
			console = { log: function() { } };
		if (console)
			console.log("%s: %o", msg, this);
		return this;
	}
})(jQuery);

$.fn.serializeObject = function() {
	var o = {};
	var a = this.serializeArray();
	$.each(a, function() {
		if (o[this.name]) {
			if (!o[this.name].push) {
				o[this.name] = [o[this.name]];
			}
			o[this.name].push(this.value || '');
		} else {
			o[this.name] = this.value || '';
		}
	});
	return o;
};

$.fn.parseTemplate = function(data) {
	var str = (this).html();
	var _tmplCache = {}
	var err = "";
	try {
		var func = _tmplCache[str];
		if (!func) {
			var strFunc =
            "var p=[],print=function(){p.push.apply(p,arguments);};" +
                        "with(obj){p.push('" +
            str.replace(/[\r\t\n]/g, " ")
               .replace(/'(?=[^#]*#>)/g, "\t")
               .split("'").join("\\'")
               .split("\t").join("'")
               .replace(/<#=(.+?)#>/g, "',$1,'")
               .split("<#").join("');")
               .split("#>").join("p.push('")
               + "');}return p.join('');";

			//alert(strFunc);
			func = new Function("obj", strFunc);
			_tmplCache[str] = func;
		}
		return func(data);
	} catch (e) { err = e.message; }
	return "< # ERROR: " + err.toString() + " # >";
};

$.fn.deserialize = function(d, config) {
	var data = d;
	me = this;

	if (d === undefined) {
		return me;
	}

	config = $.extend({ isPHPnaming: false,
		overwrite: true
	}, config);

	// check if data is an array, and convert to hash, converting multiple entries of 
	// same name to an array
	if (d.constructor == Array) {
		data = {};
		for (var i = 0; i < d.length; i++) {
			if (typeof data[d[i].name] != 'undefined') {
				if (data[d[i].name].constructor != Array) {
					data[d[i].name] = [data[d[i].name], d[i].value];
				} else {
					data[d[i].name].push(d[i].value);
				}
			} else {
				data[d[i].name] = d[i].value;
			}
		}
	}

	// now data is a hash. insert each parameter into the form
	$('input,select,textarea', me)
	.each(function() {
		var p = this.name;
		var v = [];

		// handle wierd PHP names if required
		if (config.isPHPnaming) {
			p = p.replace(/\[\]$/, '');
		}
		if (p && data[p] != undefined) {
			v = data[p].constructor == Array ? data[p] : [data[p]];
		}
		// Additional parameter overwrite
		if (config.overwrite === true || data[p]) {
			switch (this.type || this.tagName.toLowerCase()) {
				case "radio":
				case "checkbox":
					this.checked = false;
					for (var i = 0; i < v.length; i++) {
						this.checked |= (this.value != '' && v[i] == this.value);
					}
					break;
				case "select-multiple" || "select":
					for (i = 0; i < this.options.length; i++) {
						this.options[i].selected = false;
						for (var j = 0; j < v.length; j++) {
							this.options[i].selected |= (this.options[i].value != '' && this.options[i].value == v[j]);
						}
					}
					break;
				case "button":
				case "submit":
					this.value = v.length > 0 ? v.join(',') : this.value;
					break;
				default:
					this.value = v.join(',');
			}
		}
	});
	return me;
};

$.fn.setdetails = function(url) {
	var self = $(this);
	var selctor = self.selector;
	self.overlay({
		expose: { color: '#eeeeee', loadSpeed: 200, opacity: 0.8 },
		closeOnClick: false,
		api: true,
		onStart: function(event) {
			var api = this;
			var dialog = api.getOverlay();
			var id = api.getTrigger().prev().text();
			dialog.find(".content").html('<div class="progress"></div>').load(url + "/" + id, null, function() {
				form = dialog.find("form");
				form.submit(function(e) {
					$.post(form.attr("action"), form.serialize(), function(result) {
						if (!result.valid) {
							alert(result.errors);
							return false;
						}
						api.close();
						var target = api.getTrigger().closest("div.row");
						target.html(result.html);
						target.find(selctor).setdetails(url)
					}, "json");
					return e.preventDefault();
				});
			});
		}
	});
};

$.fn.setcreate = function() {
	var self = $(this);
	var selctor = self.selector;
	self.overlay({
		expose: { color: '#fff', loadSpeed: 200, opacity: 0.8 },
		closeOnClick: false,
		api: true,
		onStart: function(event) {
			var api = this;
			var dialog = api.getOverlay();
			var id = api.getTrigger().prev().text();
			dialog.find(".content").html('<div class="progress"></div>').load(self.attr("url"), null, function() {
				form = dialog.find("form");
				form.submit(function(e) {
					$.post(form.attr("action"), form.serialize(), function(result) {
						if (!result.valid) {
							alert(result.errors);
							return false;
						}
						api.close();
					}, "json");
					return e.preventDefault();
				});
			});
		}
	});
};

if (!String.prototype.endsWith) {
	String.prototype.endsWith = function(suffix) {
		var startPos = this.length - suffix.length;
		if (startPos < 0) {
			return false;
		}
		return (this.lastIndexOf(suffix, startPos) == startPos);
	};
}

jQuery.fn.fadeTo = function(speed, to, callback) {
	return this.animate({ opacity: to }, speed, function() {
		if (to == 1 && jQuery.browser.msie)
			this.style.removeAttribute('filter');
		if (jQuery.isFunction(callback))
			callback();
	});
};


function formSubmit(form, fn) {

	form = $(form); //.fadeTo(100, 0.6);


	$.post(form.attr("action"), form.serialize(), function(res) {
		//form.fadeTo(200, 1);

		if (res.message) {
			var pop = form.find(".message");
			pop.html(res.message).show();
			setTimeout(function() { pop.slideUp(); if (fn) fn.call(); }, 2000);
		} else if (res.alert) {
			alert(res.alert);
			if (typeof fn == 'string') { err.html(fn); }
			else { fn.call(); }
		} else if (res.error) {
			var pop = form.find(".error");
			pop.html(res.error).show();
			setTimeout(function() { pop.slideUp(); }, 3000);
		} else if (res.redirct) {
			
		} else {
			if (typeof fn == 'string') { err.html(fn); }
			else { fn.call(); }
		}
	}, "json");

	return false;
}
