var Commons = {

	ctx : "/ug",

	init : function(ctx) {
		if (ctx) {
			Commons.ctx = ctx;
		}
		$(document).ajaxSend(function(e, xhr, settings) {
			if (xhr) {
				xhr.setRequestHeader('ajax_request', 'ajax_request');
			}
		});
		$(document).ajaxSuccess(function(e, xhr, settings) {
			if (xhr) {
				if (xhr.getResponseHeader('ajax_location')) {
					window.location = xhr.getResponseHeader('ajax_location');
				} else if (xhr.getResponseHeader('ajax_reload')) {
					Commons.reload();
				}
			}
		});
	},

	changeLocale : function(locale) {
		$.post(Commons.url("/locale"), {
			request_locale : locale
		}, function() {
			Commons.reload();
		});
	},

	redirect : function(url, target) {
		if (target && target != '') {
			var opened = window.open(url, target);
			opened.focus();
		} else {
			document.location = url;
		}
	},

	reload : function() {
		document.location.reload();
	},

	injectJavascript : function(src) {
		src = $.trim(src);
		if (src.length > 0) {
			if (!Commons.javascripts) {
				Commons.javascripts = {};
			}
			if (!Commons.javascripts[src]) {
				$('head').append(
						'<script type="text/javascript" src="' + src
								+ '"  ></script>');
				$.extend(Commons.javascripts, {
					src : src
				});
			}
		}
	},

	injectStylesheet : function(href) {
		href = $.trim(href);
		if (href.length > 0) {
			if (!Commons.stylesheets) {
				Commons.stylesheets = {};
			}
			if (!Commons.stylesheets[href]) {
				$('head').append(
						'<link rel="stylesheet" href="' + href
								+ '" type="text/css" />');
				$.extend(Commons.stylesheets, {
					href : href
				});
			}
		}
	},

	url : function(value) {
		return Commons.ctx + value;
	},

	Button : {
		onclick : function(btn) {
			var button = $(btn);
			var type = button.attr("type");
			var action = button.attr("ie7value");

			if (type == "submit") {
				var parent = button.parent();
				while (!parent.is('form') && !parent.is('body')) {
					parent = parent.parent();
				}
				if (parent.is('form')) {
					form = parent;
					form.attr('action', action);
					form.submit();
				} else {
					alert("form not found!!!");
				}

			} else if (type == "button") {
				Commons.redirect(action);
			}
		}
	},

	verticalText : function(selector) {
		if ($.browser.opera) {
			$(selector).each(function() {
				var target = $(this);
				var html = target.html();
				var text = "";
				for (i = 0; i < html.length; i++) {
					text = text + html.charAt(i) + "<br />";
				}
				target.html(text);
			});
		}
	}

};


$(document).ready(function() {
	Commons.init();
});

