var Shin = {
	
	_config: {'basepath':'', 'decimalPoint':'', 'domain':'', 'env':'', 'lang':'', 'rootnotweb':0, 'sessionId':'', 'thousandsSep':''},
	
	_popups: {},
	
	addToSerializedField: function(element, value) {
		var cleanValues = [];
		var cleanValue = '';
		var newValue = '';
		if ( $('#'+element).val()=='' ) {
			newValue = ''+value; 	
		} else {
			newValue = $('#'+element).val()+','+value;
		} 
		var newValues = newValue.split(',');
		for (var i=0; i<newValues.length; ++i) {
			if (!Shin.inArray(newValues[i], cleanValues)) {
				cleanValues.push(newValues[i]);
			}
		}
		$('#'+element).val(cleanValues.join(','));
	},
	
	alert: function(type, title, message, actionText, actionHref) {
		if ($("#alert_overlay").length>0) {
			if (typeof actionText == 'undefined') actionText = 'OK';
			$("#overlay").show();
			$("#alert_overlay").removeClass().addClass('alert type_'+type);
			$("#alert_overlay_title").html(title);
			$("#alert_overlay_message").html(message);
			if (typeof actionHref != 'undefined'){
				$("#alert_overlay_action").attr('onclick','');
				$("#alert_overlay_action").attr('href',actionHref);
			}	
			$("#alert_overlay_action").html(actionText);
			$("#alert_overlay").show();
		}
	},
	
	closeAlert: function() {
		$("#alert_overlay").hide();
		$("#overlay").hide();
		$("#alert_overlay").removeClass();
		$("#alert_overlay_title").html('');
		$("#alert_overlay_message").html('');
		$("#alert_overlay_action").html('');
	},
	
	closeIframe: function() {
		$('html').css('overflow', 'auto');
		$("#iframe_overlay").hide();
		$("#overlay").hide();
		$("#iframe_overlay_title").html('');
		$("#iframe_overlay_action").html('');
	},
	
	closePrompt: function() {
		$("#prompt_overlay").hide();
		$("#overlay").hide();
		$("#prompt_overlay").removeClass();
		$("#prompt_overlay_title").html('');
		$("#prompt_overlay_message").html('');
		$("#prompt_overlay_type_form_container").html('');
		$("#prompt_overlay_type_text_container").hide();
		$("#prompt_overlay_type_text").val('');
		$("#prompt_overlay_submit").html($("#prompt_overlay_submit").attr('title'));
		$("#prompt_overlay_cancel").html($("#prompt_overlay_cancel").attr('title'));
	},
	
	countSerializedField: function(element) {
		var values = $('#'+element).val().split(',');
		var actualValues = [];
		for (var i=0; i < values.length; ++i) {
			if (values[i]!='') actualValues.push(values[i]);
		}
		return actualValues.length;
	},
	
	cutSerializedField: function(element, length) {
		var values = $('#'+element).val().split(',');
		var newValues = [];
		for (var i=0; i < values.length; ++i) {
			if (values[i]!='') newValues.push(values[i]);
		}
		newValues = newValues.slice(0,length);
		$('#'+element).val(newValues.join(','));
	},
	
	floatVal: function(value) {
		if (typeof value.replace == 'function') {
			if (Shin._config.decimalPoint!='') {
				value = value.replace(Shin._config.decimalPoint, '.');
			}
			if (Shin._config.thousandsSep!='') {
				value = value.replace(Shin._config.thousandsSep, '');
			}
		}
		return parseFloat(value);
	},
	
	hideFeedback: function(index) {
		$('#feedback_'+index).css('display','none');
	},
	
	hideProgress: function(keepOverlay) {
		if (typeof keepOverlay=='undefined') keepOverlay = false;
		if ($("#progress_overlay").length>0) {
			if (!keepOverlay) $("#overlay").hide();
			$("#progress_overlay").hide();
			$("#progress_overlay_bar_inner").css('width', '0%');
			$("#progress_overlay_title").html('');
			$("#progress_overlay_message").html('');
		}
	},
	
	href: function(href, includeHost) {
		if (typeof includeHost=='undefined') includeHost = true;
		var host = ( includeHost ? Shin._config.basepath : '' ) + '/';
		if (Shin._config.rootnotweb) {
			var hrefEnd = href.substr(href.lastIndexOf('/'));
			if (href.indexOf('.')>-1) {
				host = host + 'web/';
			}
		}
		if (typeof href=='undefined') return Shin._config.domain;
		var url;
		switch(href.substr(0,1)) {
			case ';':
				return host + href.substr(1);
				break;
			case ':':
				return host + Shin._config.lang + '/' + href.substr(1);
				break;
			case '|':
				return host + href.substr(1) + '/' + window.location.pathname.substr(4) + window.location.search;
				break;
			case '~':
				return host + window.location.pathname.substr(1) + '/' + href.substr(1);
				break;
			case '#':
				return host + window.location.pathname.substr(1) + ( window.location.search == '' ? '?' : window.location.search+'&' ) + href.substr(1);
				break;
			case '@':
				if (href.substr(1).indexOf('@')>-1) url = href.substr(1);		
				else url = href.substr(1) + '@' + Shin._config.domain;
				url = 'mailto:'+url;
				break;
			case '!':
				// For security reason, this cannot be called in JS !
				return host + href.substr(1);
				break;
			default:
				url = href;
				break;	
		}
		url = url.replace(/\/\//g, '/');
		url = url.replace(':/', '://');
		return url;
	},
	
	i18n: function(slug, escapeHtml) {
		var value = $.ajax({
			type: "POST",
			url: Shin.href(";ajax/i18n.ajax.php?shin_rootnotweb="+Shin._config.rootnotweb+"&shin_isadmin="+(Shin.isAdmin() ? '1' : '0')),
			data: 'i18n_slug='+slug+'&i18n_lang='+Shin._config.lang,
			async: false
		}).responseText;
		if ( typeof escapeHtml == 'undefined' || escapeHtml ) {
			return $('<div/>').text(value).html().replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br />$2');
		} else {
			return (value+'').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
		}
	},
	
	iframe: function(url, title, message, closeText) {
		if ($("#iframe_overlay").length>0) {
			$('html').css('overflow', 'hidden');
			if (typeof title == 'undefined') title = '';
			if (typeof closeText == 'undefined') closeText = 'OK';
			$("#overlay").show();
			$("#iframe_overlay").removeClass().addClass('iframe');
			$("#iframe_overlay_title").html(title);
			$("#iframe_overlay_message").html(message);
			$("#iframe_overlay_action").html(closeText);
			$("#iframe_overlay_content").attr('src', url);
			$("#iframe_overlay").show();
			$("#iframe_overlay_content").height($("#iframe_overlay").height()-52);
			if ($(window).width()>1200) {
				$("#iframe_overlay").css({
					'margin-left': '-550px',
					'width': '1100px'
				}); 
				$("#iframe_overlay_content").css({
					'width': '1100px'
				});
			}
		}
	},
	
	inArray: function(needle, haystack) {
		var key = '';
		for (key in haystack) {
			if (haystack[key] == needle) {
				return true;
			}
		}
		return false;
	},
	
	init: function(config) {
		$.extend(Shin._config, config);
		while (Shin._config.basepath.substr(-1)=='/') {
			Shin._config.basepath = Shin._config.basepath.substr(0,Shin._config.basepath.length-1);
		}
		Shin._config.IE6 = false;
		Shin._config.IE7 = false;
		Shin._config.IE8 = false;
	},
	
	isAdmin: function() {
		return ((window.location.pathname.substr(0,7)=='/admin/') || (window.location.pathname.substr(3,7)=='/admin/'));	
	},
	
	isIE6: function() {
		return Shin._config.IE6;
	},
	
	isIE7: function() {
		return Shin._config.IE7;
	},
	
	isIE8: function() {
		return Shin._config.IE8;
	},
	
	isIE: function() {
		return (Shin._config.IE6 || Shin._config.IE7 || Shin._config.IE8);
	},
	
	itsIE6: function() {
		Shin._config.IE6 = true;
	},
	
	itsIE7: function() {
		Shin._config.IE7 = true;
	},
	
	itsIE8: function() {
		Shin._config.IE8 = true;
	},
		
	loadJavascript: function(href, loading) {
		if (typeof loading == 'undefined') loading = false;
		if (loading) Shin.startLoading();
		url = Shin.href(href);
		var ok = false;
		jQuery.ajax({
			async: false,
			type: "POST",
			url: url,
			success: function() { ok = true; },
			dataType: 'script'
		});
		if (loading) Shin.StopLoading();
		return ok;
	},	
	
	log: function() {
		Shin._history = Shin._history || [];
		Shin._history.push(arguments);
		if (console) {
			console.log( Array.prototype.slice.call(arguments) );
		}
	},
	
	nl2br: function(text) {
		return text.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br />$2');
	},
		
	orderSerializedField: function(domElement, valueElement) {
		var values = [];
		var value = '';
		$('#'+domElement).children().each(function() {
			value = $(this).attr('rel');
			if (typeof value != 'undefined') values.push(value);	
		});
		$('#'+valueElement).val(values.join(','));
	},
	
	popup: function(name, href, width, height) {
		if (!Shin._popups[name]) {
			Shin._popups[name] = window.open(Shin.href(href),name,"width="+width+",height="+height+",resizable=no,status=no,scrollbars=no,menubar=no,toolbar=no");
		}
		Shin._popups[name].focus();
	},
	
	prompt: function(type, title, message, callback, submitText, cancelText) {
		if ($("#prompt_overlay").length>0) {
			$("#overlay").show();
			$("#prompt_overlay").removeClass().addClass('alert type_prompt type_prompt_'+type);
			$("#prompt_overlay_title").html(title);
			$("#prompt_overlay_message").html(message);
			$("#prompt_overlay_type_"+type+"_container").show();
			$("#prompt_overlay_submit").unbind('click').click(function(){
				if (typeof callback == 'function') {
					return callback( $('#prompt_overlay_type_'+type).val() );
				} else if (typeof callback == 'string') {
					callback = 'var prompted=$(\'#prompt_overlay_type_\''+type+'\').val();' + callback
					eval(callback);
				}
				return true;
			});
			if (typeof submitText == 'string') {
				$("#prompt_overlay_submit").html(submitText);
			}
			if (typeof cancelText == 'string') {
				$("#prompt_overlay_cancel").html(cancelText);
			}
			$("#prompt_overlay").show();
		}
	},
	
	redirect: function(href) {
		Shin.startLoading();
		url = Shin.href(href);
		window.location.href = url;
	},
	
	removeFromSerializedField: function(element, value) {
		if ($('#'+element).val()=='') return;
		var values = $('#'+element).val().split(',');
		var newValues = [];
		for (var i=0; i < values.length; ++i) {
			if (values[i]!=value) newValues.push(values[i]);
		}
		$('#'+element).val(newValues.join(','));
	},
	
	script: function(name, params, onSuccess, onError) {
		if (typeof params=='undefined') params = '';
		params = params+'&i18n_lang='+Shin._config.lang;
		$.ajax({
			type: "POST",
			url: Shin.href(";ajax/"+name+".ajax.php?sessid="+Shin._config.sessionId+"&shin_rootnotweb="+Shin._config.rootnotweb+"&shin_isadmin="+(Shin.isAdmin() ? '1' : '0')),
			data: params,
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				if (typeof onError=='function') onError(XMLHttpRequest, textStatus, errorThrown);
			}, 
			success: function(value) {
				if (typeof onSuccess=='function') onSuccess(value);
			}
		});
	},
	
	showProgress: function(value, title, message) {
		if ($("#progress_overlay").length>0) {
			$("#overlay").show();
			$("#progress_overlay").show();
			if (typeof title!='undefined' && title!=null) {
				$("#progress_overlay_title").html(title);
			}
			if (typeof message!='undefined' && message!=null) {
				$("#progress_overlay_message").html(message);
			}
			if (value>-1) {
				value = Math.ceil(value*100);
				if (value>100) value=100;
				$("#progress_overlay_bar_inner").css('width', value+'%').html(''+value+'%&nbsp;');
			} else {
				if (value==-2) $("#progress_overlay_bar_inner").css('visibility','hidden');
			}
		}
	},
	
	startLoading: function() {
		if ($("#loading_overlay").length>0) {
			$("#overlay").show();
			$("#loading_overlay").show();
		}
	},
	
	stopLoading: function() {
		if ($("#loading_overlay").is(":visible")) {
			if (!$("#alert_overlay").hasClass('alert') && !$('#iframe_overlay').is(":visible")) $("#overlay").hide();
			$("#loading_overlay").hide();
		}
	},
	
	submit: function(form, loading) {
		if (typeof loading=='undefined') loading = true;
		if (loading && (($('#'+form).attr('target')=='') || ($('#'+form).attr('target')=='_self'))) Shin.startLoading();
		$('#'+form).submit();
	}, 
	
	syncScript: function(name, params, loading) {
		if ((typeof loading=='undefined') || (loading)) Shin.startLoading();
		if (typeof params=='undefined') params = '';
		params = params+'&i18n_lang='+Shin._config.lang;
		var response = $.ajax({
			type: "POST",
			url: Shin.href(";ajax/"+name+".ajax.php?sessid="+Shin._config.sessionId+"&shin_rootnotweb="+Shin._config.rootnotweb+"&shin_isadmin="+(Shin.isAdmin() ? '1' : '0')),
			data: params,
			async: false
		}).responseText;
		if ((typeof loading=='undefined') || (loading)) Shin.stopLoading();
		return response;
	},
	
	updateContentScript: function(element, script, params) {
		if (typeof params == 'string') params = params+'&i18n_lang='+Shin._config.lang;
		html = Shin.syncScript(script, params);
		$('#'+element).html(html);
	}
};
