/*==============================================================================
$Id: $
Copyright (c) 2008 aatranslations

General purpose functions specific to Liebre/FluentWork/aa.
==============================================================================*/


var __months_sl = [
	"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"
];
var __months_sf = [
	"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];

/*------------------------------------------------------------------------------
Checks if a string can be converted into a generic value without decimals.
Returns a numeric value (rounded to integer) or null if the string cannot
be converted.
NOTE: Keep in sync with checkGeneric() in common/inc/lib.php.
------------------------------------------------------------------------------*/

function checkGeneric(str){
	var n;
	if((n = checkNumber(str, ",", ".")) != null)
		return round(n);
	return null;
}

/*------------------------------------------------------------------------------
Formats generic number (without decimals) to show.
NOTE: Keep in sync with FormatGeneric() in common/inc/lib.php.
------------------------------------------------------------------------------*/

function formatGeneric(number){
	return formatNumber(number, ",", ".", 0, 0)
}

/*------------------------------------------------------------------------------
Checks if a string can be converted into a 'number of words' value.
Returns a numeric value (rounded to integer) or null if the string cannot
be converted or the resulting value is out of range (0 - 4294967295).
NOTE: Keep in sync with CheckWords() in common/inc/lib.php.
------------------------------------------------------------------------------*/

function checkWords(str){
	var n;
	if((n = checkNumber(str, ",", ".")) != null && n >= 0 && n <= 4294967295)
		return round(n);
	return null;
}

/*------------------------------------------------------------------------------
Formats a 'number of words' value to show.
NOTE: Keep in sync with FormatWords() in common/inc/lib.php.
------------------------------------------------------------------------------*/

function formatWords(words){
	return formatNumber(words, ",", ".", 0, 0);
}

/*------------------------------------------------------------------------------
Checks if a string can be converted into a 'number of hours' value.
Returns a numeric value (rounded to integer) or null if the string cannot
be converted or the resulting value is out of range (0 - 65535).
NOTE: Keep in sync with CheckHours() in common/inc/lib.php.
------------------------------------------------------------------------------*/

function checkHours(str){
	var n;
	if((n = checkNumber(str, ",", ".")) != null && n >= 0 && n <= 65535)
		return round(n);
	return null;
}

/*------------------------------------------------------------------------------
Formats a 'number of hours' value to show.
NOTE: Keep in sync with FormatHours() in common/inc/lib.php.
------------------------------------------------------------------------------*/

function formatHours(hours){
	return formatNumber(hours, ",", ".", 0, 0);
}

/*------------------------------------------------------------------------------
Checks if a string can be converted into a money value.
Returns a numeric value (rounded to 2 decimals) or null if the string cannot
be converted or the resulting value is out of range (-9999999.99 - 9999999.99).
NOTE: Keep in sync with CheckMoney() in common/inc/lib.php.
------------------------------------------------------------------------------*/

function checkMoney(str){
	var n;
	if((n = checkNumber(str, ",", ".")) != null && n >= -9999999.99 && n <= 9999999.99)
		return round(n, 2);
	return null;
}

/*------------------------------------------------------------------------------
Formats a money value to show.
NOTE: Keep in sync with FormatMoney() in common/inc/lib.php.
------------------------------------------------------------------------------*/

function formatMoney(amount, idcurrency){
	var s;
	s = formatNumber(amount, ",", ".", 2, 2);
	switch(idcurrency){
		case undefined:	return s; 
		case 1:	return s + "€";
		case 2:	return "£" + s;
		case 3:	return "$" + s;
	}
}

/*------------------------------------------------------------------------------
Checks if a string can be converted into a rate.
Returns a numeric value (rounded to 4 decimals) or null if the string cannot
be converted or the resulting value is out of range (-999.9999 - 999.9999).
NOTE: Keep in sync with CheckRate() in common/inc/lib.php.
------------------------------------------------------------------------------*/

function checkRate(str){
	var n;
	if((n = checkNumber(str, ",", ".")) != null && n >= -999.9999 && n <= 999.9999)
		return round(n, 4);
	return null;
}

/*------------------------------------------------------------------------------
Formats a rate to show.
NOTE: Keep in sync with FormatRate() in common/inc/lib.php.
------------------------------------------------------------------------------*/

function formatRate(rate){
	return formatNumber(rate, ",", ".", 2, 4);
}

/*------------------------------------------------------------------------------
Checks if a string can be converted into a percentage.
Returns a numeric value (rounded to 1 decimal) or NULL if the string cannot
be converted or the resulting value is out of range (0 - 999.9).
NOTE: Keep in sync with CheckPercentage() in common/inc/lib.php.
------------------------------------------------------------------------------*/

function checkPercentage(str){
	var n;
	if((n = checkNumber(str, ",", ".")) != null && n >= 0 && n <= 999.9)
		return round(n, 1);
	return null;
}

/*------------------------------------------------------------------------------
Formats a percentage to show.
NOTE: Keep in sync with FormatPercentage() in common/inc/lib.php.
------------------------------------------------------------------------------*/

function formatPercentage(percentage){
	return formatNumber(percentage, ",", ".", 0, 1);
}

/*------------------------------------------------------------------------------
Formats a rating value to show.
NOTE: Keep in sync with FormatRating() in common/inc/lib.php.
------------------------------------------------------------------------------*/

function formatRating(rating){
	return formatNumber(rating, ",", ".", 1, 2);
}

/*------------------------------------------------------------------------------
Formats a file size to show.
'format' -- 1 to suppress trailing decimal 0s in MBs and GBs; 2 to keep them.
NOTE: Keep in sync with FormatFilesize() in common/inc/lib.php.
------------------------------------------------------------------------------*/

function formatFilesize(size, format){
	var s;
	if(size < 1024)
		return formatNumber(size, ",", ".", 0, 0) + " " + (size == 1 ? "byte" : "bytes");
	else if(size < 1048576)
		return formatNumber(size / 1024, ",", ".", 0, 0) + " KB";
	else if(size < 1073741824)
		return formatNumber(size / 1048576, ",", ".", format == 1 ? 0 : 1, 1) + " MB";
	else
		return formatNumber(size / 1073741824, ",", ".", format == 1 ? 0 : 2, 2) + " GB";
}

/*------------------------------------------------------------------------------
Checks if a string can be converted into a date.
Returns the date in ISO8601 format or null of if the string cannot be
converted.
NOTE: Keep in sync with CheckDate_() in common/inc/lib.php.
------------------------------------------------------------------------------*/

function checkDate(str, format){
	var a, b, d, m, y, h, n;
	switch(format){
		case 3: /* 6/9/2008 9:05 */
			if(str.match(/^\d{1,2}\/\d{1,2}(\/(\d{2}|\d{4}))? \d{1,2}:\d{2}$/, str)){
				a = str.split(" ");
				b = a[1].split(":");
				a = a[0].split("/");
				d = a[0] - 0;
				m = a[1] - 0;
				y = (a[2] != undefined ? a[2] - 0 : new Date().getFullYear());
				if(y < 100) y = 1951 + (y + 49) % 100;
				h = b[0] - 0;
				n = b[1] - 0;
				if(
					m >= 1 && m <= 12 && d >= 1 && d <= (m == 4 || m == 6 || m == 9 || m == 11 ?
					30 : (m != 2 ? 31 : 28 + (!(y % 4) && (y % 100 > 0 || !(y % 400))))) &&
					h >= 0 && h <= 23 && n >= 0 && n <= 59
				){
					if(m < 10) m = "0" + m;
					if(d < 10) d = "0" + d;
					if(h < 10) h = "0" + h;
					if(n < 10) n = "0" + n;
					return y + "-" + m + "-" + d + " " + h + ":" + n + ":00";
				}
			}
			return null;
		case 5: /* 6/9/2008 */
			if(str.match(/^\d{1,2}\/\d{1,2}(\/(\d{2}|\d{4}))?$/, str)){
				a = str.split("/");
				d = a[0] - 0;
				m = a[1] - 0;
				y = (a[2] != undefined ? a[2] - 0 : new Date().getFullYear());
				if(y < 100) y = 1951 + (y + 49) % 100;
				if(
					m >= 1 && m <= 12 && d >= 1 && d <= (m == 4 || m == 6 || m == 9 || m == 11 ?
					30 : (m != 2 ? 31 : 28 + (!(y % 4) && (y % 100 > 0 || !(y % 400)))))
				){
					if(m < 10) m = "0" + m;
					if(d < 10) d = "0" + d;
					return y + "-" + m + "-" + d;
				}
			}
			return null;
	}
}

/*------------------------------------------------------------------------------
Formats an ISO8601 date to show.
NOTE: Keep in sync with FormatDate() in common/inc/lib.php.
------------------------------------------------------------------------------*/

function formatDate(date, format){
	var a, b;
	switch(format){
		case 1: /* sep 6[, 2008] 9:05 */
			a = date.split(" ");
			b = a[1].split(":");
			a = a[0].split("-");
			return __months_sl[a[1] - 1] + " " + (a[2] - 0) + (date.substr(0, 4) != (new Date()).getFullYear() ? (", " + a[0]) : "") + " " + (b[0] - 0) + ":" + b[1];
		case 3: /* 6/9/2008 9:05 */
			a = date.split(" ");
			b = a[1].split(":");
			a = a[0].split("-");
			return (a[2] - 0) + "/" + (a[1] - 0) + "/" + a[0] + " " + (b[0] - 0) + ":" + b[1];
		case 4: /* Sep 6[, 2008] */
			a = date.split(" ");
			a = a[0].split("-");
			return __months_sf[a[1] - 1] + " " + (a[2] - 0) + (date.substr(0, 4) != (new Date()).getFullYear() ? (", " + a[0]) : "");
		case 5: /* 6/9/2008 */
			a = date.split(" ");
			a = a[0].split("-");
			return (a[2] - 0) + "/" + (a[1] - 0) + "/" + a[0];
	}
}

/*------------------------------------------------------------------------------
Returns current date in ISO8601 format.
NOTE: Keep in sync with Today() in common/inc/lib.php.
------------------------------------------------------------------------------*/

function today(){
	var o, m, d;
	o = new Date();
	m = o.getMonth() + 1;
	d = o.getDate();
	return o.getFullYear() + "-" + (m < 10 ? "0" : "") + m + "-" + (d < 10 ? "0" : "") + d;
}

/*------------------------------------------------------------------------------
Sets a form up.
'options' -- are the following options:
    'form' is the form object.
    'spinner' is the spinner element.
    'buttons' (optional) is an array of button names to disable on submit.
    'files' (optional) is an array of file uploading element prefixes.
    'progress' (only if files set) is the progress element.
    'redirect' (optional) is the URL to redirect to after success.
    'onFileSelect' (optional) is the function to call after a successful file
        selection. The function receives the prefix of the altered file
        uploading element.
    'onSubmit' (optional) is the function to call before submitting the form.
Returns a reference object that can be used to dynamically add more file
uploading elements via addFormFiles(), remove all of them via
removeAllFormFiles(), or enable or disable existing ones via switchFormFiles().
------------------------------------------------------------------------------*/

var __setupForm_iframe_loaded__ = false;

function setupForm(options){
	var o, s, e;
	o = {
		form: $(options.form),
		spinner: options.spinner,
		buttons: options.buttons != undefined ? options.buttons : [],
		progress: options.progress,
		redirect: options.redirect != undefined ? options.redirect : location.href,
		onFileSelect: options.onFileSelect,
		onSubmit: options.onSubmit,
		uploaders: [],
		result: function(t){ _sf_result(t, o); },
		fail: function(x){ _sf_fail(x, o); },
		failAlerted: false,
		basicUploader: false
	};
	if(options.files != undefined)
		addFormFiles(o, options.files);
	s = "__setupForm_iframe__";
	if(!(e = $(s)))
		(e = new Element("iframe", {
			id: s,
			name: s,
			styles: { display: "none" },
			events: {
				load: function(){ if(!__setupForm_iframe_loaded__) __setupForm_iframe_loaded__ = true; else _sf_result($(this.contentWindow.document.body).get("text"), o); }
			}
		})).inject(document.body);
	o.form.enctype = "multipart/form-data";
	o.form.target = s;
	o.form.onsubmit = function(){ return _sf_submit(o); }
	o.form.__setupForm__ = { object: o };
	return o;
}

function addFormFiles(o, files){
	files.each(function(e){
		$(e + "_filename").set("html", "<span class=\"notset\">(no file selected)</span>");
		o.uploaders.push({
			prefix: e,
			swiff: new Swiff.Uploader({
				path: "common/ext/Swiff.Uploader.swf",
				multiple: false,
				target: e + "_btn",
				url: location.href,
				timeLimit: 120,
				appendCookieData: true,
				onLoad: function(){
					this.target.addEvents({
						mouseenter: function(){
							this.addClass("hover");
						},
						mouseleave: function(){
							this.removeClass("hover");
						}
					});
				},
				onFail: function(){
					if(!o.failAlerted){
						alert("To enable the embedded uploader, install the latest Adobe Flash plugin and unblock it in your browser.");
						o.failAlerted = true;
					}
				},
				onSelectSuccess: function(files){
					var s;
					if(this.fileList.length == 2)
						this.fileList[0].remove();
					if((s = files[0].name).length > 25)
						s = s.substr(0, 12) + "..." + s.substr(-12);
					$(e + "_filename").set("html", s);
					if(o.onFileSelect != undefined)
						o.onFileSelect(e);
				},
				onFileProgress: function(){
					var l, s;
					l = 0;
					s = 0;
					o._uploaders.each(function(e){ e = e.swiff; l += e.bytesLoaded; s += e.size; });
					o.progress.set("text", l < s ? (formatFilesize(l, 2) + " of " + formatFilesize(s, 1) + " uploaded") : "Please wait...");
				},
				onFileComplete: function(file){
					var i, s;
					if((i = o.form[s = e + "_id"]) == undefined)
						o.form.adopt(i = new Element("input", { "type": "hidden", "name": s }));
					i.value = file.response.error || checkIntUnsigned(file.response.text) == null ? "0" : file.response.text;
					if((i = o.form[s = e + "_isuploaded"]) == undefined)
						o.form.adopt(i = new Element("input", { "type": "hidden", "name": s }));
					i.value = "1";
					_sf_start(o);
				}
			})
		});
	});
}

function removeAllFormFiles(o){
	o.uploaders.empty();
}

function switchFormFiles(o, files, f){
	var u;
	o.uploaders.each(function(e){
		if(files.contains(e.prefix)){
			e.swiff.target.disabled = !f;
			e.swiff.options.container.style.display = (f ? "" : "none");
			if(u = o.form[e.prefix + "_file"] != undefined) u.disabled = !f;
		}
	});
}

function switchToBasicUploader(){
	var j, o;
	for(j = 0; j < document.forms.length; j++){
		(o = document.forms[j].__setupForm__.object).basicUploader = true;
		o.uploaders.each(function(e){
			(o = $(e.prefix + "_filename")).style.display = "none";
			(o = o.getNext()).style.display = "none";
			(o = o.getNext()).style.display = "table-cell";
			(o = o.getNext()).style.display = "none";
			o.getNext().style.display = "block";
		});
	}
}

function switchToStandardUploader(){
	var j, o;
	for(j = 0; j < document.forms.length; j++){
		(o = document.forms[j].__setupForm__.object).basicUploader = false;
		o.uploaders.each(function(e){
			(o = $(e.prefix + "_filename")).style.display = "table-cell";
			(o = o.getNext()).style.display = "table-cell";
			(o = o.getNext()).style.display = "none";
			(o = o.getNext()).style.display = "block";
			o.getNext().style.display = "none";
		});
	}
}

function _sf_submit(o){
	var j, i;
	if(o.form.submitbtn != undefined){
		if(o.form.submitbtn.disabled)
			return false;
		o.form.submitbtn.disabled = true;
	}
	o._buttons = [];
	o.buttons.each(function(e){
		if(!o.form[e].disabled){
			o.form[e].disabled = true;
			o._buttons.push(e);
		}
	});
	o._uploaders = [];
	o.uploaders.each(function(e){
		if(!e.swiff.target.disabled){
			e.swiff.setEnabled(false);
			e.swiff.target.disabled = true;
			o._uploaders.push(e);
		}
	});
	if(o.progress != undefined){
		o.progress.set("text", "");
		o.progress.setStyle("visibility", "visible");
	}
	if(o.onSubmit != undefined)
		o.onSubmit();
	o.uploaders.each(function(e){
		if((i = o.form[e.prefix + "_id"]) != undefined && i.value == "0")
			e.swiff.fileList.each(function(e){ e.requeue(); });
	});
	_sf_start(o);
	return false;
}

function _sf_start(o){
	var j, f;
	if(!o.basicUploader)
		for(j = 0; j < o._uploaders.length; j++)
			if((f = o._uploaders[j].swiff.fileList[0]) != undefined && f.status == 0){
				o._uploaders[j].swiff.start();
				return;
			}
	if(o.progress != undefined)
		o.progress.setStyle("visibility", "hidden");
	o.spinner.setStyle("visibility", "visible");
	if(!o.basicUploader)
		new Request({ url: location.href, method: o.form.method, data: o.form }).addEvents({ success: o.result, failure: o.fail }).send();
	else
		o.form.submit();
}

function _sf_result(t, o){
	var s, e, u, j, a, k;
	o.spinner.setStyle("visibility", "hidden");
	if(t == "")
		location.href = o.redirect;
	else
	if((s = t.split(" #!", 2)).length == 2){
		if(s[0] != "")
			alert(s[0]);
		location.href = s[1] != "" ? s[1] : location.href;
	}else{
		o._buttons.each(function(e){ o.form[e].disabled = false; });
		o._uploaders.each(function(e){ e.swiff.setEnabled(true); e.swiff.target.disabled = false; if(u = o.form[e.prefix + "_file"] != undefined) u.disabled = false; });
		if(o.form.submitbtn != undefined)
			o.form.submitbtn.disabled = false;
		s = t.split("::", 2);
		if(s[1] == undefined){
			if(s[0] == "@"){
				$(document.body).grab(e = new Element("div", { "class": "postok" }));
				(function(){ e.set("tween", { duration: 1000, onComplete: function(){ e.destroy(); } }).fade("out") }).delay(250);
			}else
				alert(s[0]);
		}else{
			if((j = s[0].lastIndexOf(" ")) != -1){
				eval(s[0].substr(0, j));
				s[0] = s[0].substr(j + 1);
			}
			if(s[0] != ""){
				a = s[0].split("*", 2);
				if(a[1] != undefined){
					if(a[1].charAt(0) != "=")
						o.form[a[0]][a[1]].focus();
					else{
						k = new RegExp(a[1].substr(1));
						o = o.form[a[0]];
						for(j = 0; j < o.length; j++)
							if(o[j].value.match(k)){
								o[j].focus();
								break;
							}
					}
				}else
					o.form[a[0]].focus();
			}
			alert(s[1]);
		}
	}
}

function _sf_fail(x, o){
	var u;
	o.spinner.setStyle("visibility", "hidden");
	o._buttons.each(function(e){ o.form[e].disabled = false; });
	o._uploaders.each(function(e){ e.swiff.setEnabled(true); e.swiff.target.disabled = false; if(u = o.form[e.prefix + "_file"] != undefined) u.disabled = false; });
	if(o.form.submitbtn != undefined)
		o.form.submitbtn.disabled = false;
	alert("Operation failed. Please try it again later.");
}

