var tokenKey;

if (typeof console == "undefined") {
	this.console = {
		log : function() {
		}
	};
}

function getToken(i) {
	tokenKey = i;
}

function getParam(key, value) {
	return '&' + key + '=' + encodeURIComponent(value);
}

function setCookie(a, b) {
	if (window.widget) {
		widget.setPreferenceForKey(encodeURIComponent(b), a);
	} else {
		document.cookie = a
				+ "="
				+ encodeURIComponent(b)
				+ "; expires="
				+ (new Date(new Date().getTime() + (360 * 24 * 60 * 60 * 1000)))
						.toGMTString() + "; path=/";
	}
}

function getCookie(a) {
	if (window.widget) {
		return decodeURIComponent(widget.preferenceForKey(a)) || null;
	}
	if (new RegExp(a + "=([^;]*);", "").test(document.cookie + ";")) {
		return decodeURIComponent(RegExp.$1);
	}
	return null;
}

function setSession(a, b) {
	if (new RegExp(a + "=([^;]*);", "").test(window.name + ";")) {
	window.name=window.name.replace(new RegExp(a + "=([^;]*);", ""),a
			+ "="
			+ encodeURIComponent(b)
			+ ";");

	}else{
	window.name += a
			+ "="
			+ encodeURIComponent(b)
			+ ";";
	}
}

function getSession(a) {
	if (new RegExp(a + "=([^;]*);", "").test(window.name + ";")) {
		return decodeURIComponent(RegExp.$1);
	}
	return null;
}

function changeLanguage(currLang, newLang, defaultUrl) {
	var str = document.location.pathname;
	var pos = str.toLowerCase().indexOf('/' + currLang);
	var nstr = "";
	if (pos >= 0) {
		nstr = str.substring(0, pos);
		nstr = nstr + "/" + newLang;
		nstr = nstr + str.substring(pos + 3, str.length);
	} else {
		nstr += defaultUrl;
	}
	document.location.pathname = nstr;
};

/* targetName can be class or id */
function loadingImg(targetName) {
	$(targetName).each(function() {
		$(this).loading();
	});
};

function tag(tagId){
	return document.getElementById(tagId);
}

function action(method,servlet,params){
	if($('#action').size()==0){
	var dataString = 'type='+method+'&token=' + tokenKey+'&'+params;
	$.ajax( {
		type : "POST",
		url : "/"+servlet,
		data : dataString,
		success : function(msg) {
		$('body').append('<div id="action"><script>'+msg+'</script></div>');
		$('#action').remove();
		}
	});
	}
}

function getLoadingTag(){
	return $("<img class='loading_img' src='ale-loading.gif'/>");
}

function getBlankSrc(){
	return "/images/blank.gif";
}

(function($) {
	$.fn.groupCheckbox = function(){
		var o = $(this);
		$('input[for=' + o.attr('id') + ']').each(function(){
			$(this).change(function(){
				var cb = $(this);
				var g = jQuery.trim(o.val());
				var c = cb.val();
				if (cb.attr('checked') == undefined) {
					var n = '';
					g = g.split(',');
					for (var i = 0; i < g.length; i++) {
						if (g[i] == c) {
							continue;
						}

						n = (n == '' ? g[i] : n + ',' + g[i]);
					}
					o.val(n);
				} else {
					o.val(g == '' ? c : g + ',' + c);
				}
			});
		});
	}
	
	$.fn.hoverImg = function(hover) {
		var src = $(this).attr("src");
		$(this).bind('mouseover', function(){
			$(this).attr("src", hover);
		});
		$(this).bind('mouseout', function(){
			$(this).attr("src", src);
		});
	};
	
	$.fn.ok = function(action) {
		$(this).bind('focusin', start);
		function start() {
			$(this).bind('focusout', end);
			$(document).bind('keypress', run);
		}
		;
		function end() {
			$(this).unbind('focusout', end);
			$(document).unbind('keypress', run);
		}
		function run(e) {
			if (e.keyCode == 13)
				action();
		}
	};

	$.fn.reloadCaptcha = function() {
		$(this).attr('src', '/actionServlet?type=captcha');
	};

	$.fn.browserClass = function() {
		var browser;
		if ($.browser.mozilla)
			browser = "gecko gecko" + $.browser.version;
		else if ($.browser.msie)
			browser = "ie ie" + $.browser.version;
		else if ($.browser.safari)
			browser = "safari";
		else if ($.browser.opera)
			browser = "opera";
		else
			browser = navigator.appName.toLowerCase();

		$('body').addClass(browser);
	};

	$.fn.showLoading = function(method) {
		$(this).empty();
		getLoadingTag().appendTo(
				$(this));
		if(method!= null){
			$(this).show("fast", method());
		}else{
			$(this).show("fast");
		}
	};

	$.fn.closeLoading = function() {
		$(this).empty();
		$(this).hide();
	};

	$.fn.loading = function() {
		root = $(this);
		src = root.attr('loading');
		if (src != null) {
			op = {
				display : root.css('display'),
				src : src,
				l: null
			};
			root.data('loading', op);
			tag = root[0].tagName;
			pro = root.attr('process');
			
			if (tag == 'IMG' || tag == 'IFRAME') {
				hide(root);
				if (pro != null) {
					root.attr('process', null);
				} else {
					op.l = getLoadingTag();
					op.l.insertAfter(root);
				}
				initEvents(root);
			} else if (tag != 'EMBED') {
				n = $("<img />");
				n.attr('class', root.attr('class'));
				n.attr('style', root.attr('style'));
				n.insertAfter(o);
				n.data('loading', op);
				root.remove();
				if (pro == null) {
					op.l = getLoadingTag();
					op.l.insertAfter(n);
				}
				initEvents(n);
			}
			loadSrc(root);
		}
		
		function hide(o){
			o.css('display', 'none');
		}
		
		function show(o, op){
			o.css('display', op.display);
		}
		
		function loadSrc(o){
			o.attr('loading', null);
			o.attr('src', src);
		}
		
		function initEvents(o){
			o.bind('load', function(event) {
				op = $(this).data('loading');
				if(op.l != null){
					op.l.remove();
				}
				$(this).unbind(event);
				show($(this), op);
				clear($(this));
			});
			o.error(function(){
				$(this).attr('src', getBlankSrc());
			});
		}
		
		function clear(o){
			o.removeData('loading');
		}
	};
})(jQuery);

(function($) {
	$.tiny = $.tiny || {};

	$.tiny.ajaxRequest = {
		options : {
			type: 'GET',
			init: function() {},
			success: function() {},
			error: function() {},
			validate : function() {
				return true;
			},
			sendAll : true ,// Send value of all object have 'ajax' attribute of
							// this apply
			waiting : true ,// Waiting for end of event
			processing : true ,// Show processing images
			process : null ,// Processing object
			show: null,
			apply: null,
			ids : null,
			params: {}
		}
	};

	$.fn.isEmpty = function() {
		return $(this).val() == null || jQuery.trim($(this).val()) == "";
	};
	
	$.fn.disabled = function(o){
		k = 'disabled';
		if(o == null){
			return $(this).data(k);
		}
		
		if(o){
			$(this).attr(k, k);
			$(this).addClass(k);
			$(this).data(k, true);
		}else{
			$(this).attr(k, null);
			$(this).removeClass(k);
			$(this).removeData(k);
		}
	}
	
	$.fn.ajaxRequest = function(o, event, options) {
		root = $(this);
		if(!o.jquery){
			o = $(o);
		}
		opt = $.extend( {}, $.tiny.ajaxRequest.options, options);
		
		if(opt.apply == null){
			opt.apply = root.attr("apply");
		}
		if (opt.sendAll) {
			opt.ids = new Array();
			$('[ajax=true]', root).each(
					function(index) {
						opt.ids[index] = {
								id: encodeURIComponent($(this).attr(
								"id")),
								name: encodeURIComponent($(this).attr("name")),
								type: $(this).attr("type"),
								o: $(this)
							};
					});
		} else if (opt.ids != null) {
			arr = new Array();
			for (var i = 0; i < opt.ids.length; i++) {
				var id = opt.ids[i];
				var obj;
				if(id.jquery){
					obj = id;
				}else{
					obj = $(id);
				}
				arr[i] = data = {
						id: encodeURIComponent(obj.attr(
						"id")),
						name: encodeURIComponent(obj.attr("name")),
						type: obj.attr("type"),
						o: obj
					};
			}
			opt.ids = arr;
		}
		if (opt.process == null && opt.processing) {
			opt.process = $('.processing', root);
			if (opt.process.attr('class') == null) {
				opt.process = $("<div class='processing'></div>");
				opt.process.appendTo(root);
			}
		}
		
		o.data(event, opt);
		o.bind(event, function(e) {
			o = $(this);
			if(!o.disabled()){
				doAjax(o, o.data(e.type), e);
			}
		});
		
		function doAjax(o, opt, e){
			blockEvent(o, opt.waiting);			
			if (opt.validate()) {
				var apply = opt.apply;
				var d = 'type=ajax';
				var id = o.attr("id");
				d += getParam('apply', apply);
				d += getParam('target', id == null ? o.attr('name'): id);
				d += getParam('event', e.type);
				d += getParam('token', tokenKey);
				$.map(opt.params, function(v, i){
					try{
						v = v();
					}catch(err){
						// safe
					}
					if(v != null){
						d += getParam(i, v);
					}
				});
				if(opt.ids != null){
					for (var i = 0; i < opt.ids.length; i++) {
						var data = opt.ids[i];
						var val = getVal(data);
						if (val.length > 0) {
							var id = isRadio(data.o) ? data.name: (data.id == null ? data.name: data.id);
							d += getParam(id, val);
						}
					}
				}
				
				opt.init(e);
				if(opt.process!=null){
					opt.process.empty();
					getLoadingTag().appendTo(opt.process);
				}
				if(opt.show != null){
					opt.show(opt.process);
				}else if(opt.process != null){
					opt.process.show();
				}
				req = $.ajax({
					type : opt.type,
					url : "/actionServlet",
					data : d
				});
				
				req.done(function(data) {
					if (opt.process != null) {
						opt.process.html(data);
					} else {
						$('body').append(data);
					}
					opt.success(data, e);
					unlockEvent(o, opt.waiting);
				});

				req.fail(function(data, status) {
					opt.error(data, e);
					if (data.status == '404') {
						data = getLabel('pagenotfound');
					} else {
						data = getLabel('serviceunavailable');
					}
					if (opt.process != null) {
						opt.process.html("<span class='error'>" + data +"</span>");
					} else {
						alert(data);
					}
					unlockEvent(o, opt.waiting);
				});
			} else {
				if (opt.process != null) {
					opt.process.empty();
				}
				unlockEvent(o, opt.waiting);
			}
		}
	};

	function blockEvent(o, waiting) {
		if (waiting) {
			o.disabled(true);
		}
	}

	function unlockEvent(o, waiting) {
		if (waiting) {
			o.disabled(false);
		}
	}
	
	function isRadio(type){
		return type == 'radio';
	}
	
	function isCheckbox(type){
		return type == 'checkbox';
	}
	
	function isChecked(o){
		return o.attr('checked') != undefined;
	}
	
	function isInput(o){
		return o.tagName == 'INPUT' || o.tagName == 'SELECT' || o.tagName == 'TEXTAREA';
	}
	
	function getVal(data) {
		var o = data.o;
		if((isRadio(data.type) || isCheckbox(data.type))){
			return isChecked(o) ? jQuery.trim(o.val()) : "";
		}
		var val = jQuery.trim(isInput(o[0]) ? o.val() : o.attr('value'));
		val = val.replace(/\s{2,}/, ' ');
		o.val(val);
		if (o.attr('search')) {
			return o.searchVal();
		}
		return jQuery.trim(o.val());
	}
})(jQuery);
