/**
 * uutuu utility functions
 *
 * namespace: uutuu.util
 * function: locate, copy
 */

uutuu.Namespace("uutuu.util");

/**
 * get css length style without unit, eg:px
 */
uutuu.util.noUnitCss = function(elem, style, val) {
	if (val === undefined || val == null) {
		var val = $(elem).css(style);
		if (val && val.constructor == String)
			val = val.replace(/[a-zA-Z]/g, "");
		return val ? parseInt(val) : 0;
	}
	else
		$(elem).css(style,val + "px");
};
/**
 * locate target element to a position related to base element.
 * edge: center, top-left, top-right, bottom-left, bottom-right
 * direct: center, left-up, left-down, right-up, right-down;
 */
uutuu.util.locate = function(target, base, edge, direct, offsetY, offsetX) {
	// calculate position
	var elem = (base === undefined || base == null) ? target : base;
	var top = elem.offsetTop;
	var left = elem.offsetLeft;
	var parent = elem.offsetParent;
	while (parent)
	{

		if ($.browser.msie) {
			//top += this.noUnitCss(parent, "paddingTop");
			//left += this.noUnitCss(parent, "paddingLeft");
		}
		else if ($.browser.mozilla) {
			top += this.noUnitCss(parent, "paddingTop");
			left += this.noUnitCss(parent, "paddingLeft");
			top += this.noUnitCss(parent, "borderTopWidth");
			left += this.noUnitCss(parent, "borderLeftWidth");
		}
		else if ($.browser.opera) {
	//		top -= this.noUnitCss(parent, "borderTopWidth");
	//		left -= this.noUnitCss(parent, "borderLeftWidth");
		}

		top += parent.offsetTop;
		left += parent.offsetLeft;
		parent = parent.offsetParent;
	}
	//top += 10; left +=10;
	if (base === undefined || base == null)
		return [top, left];

	var targetWidth = this.width(target);
	var targetHeight = this.height(target);
	var baseWidth = this.width(base);
	var baseHeight = this.height(base);
	if (!direct)
		direct = "";
	if (!offsetY)
		offsetY = 0;
	else
		offsetY = parseInt(offsetY);
	if (!offsetX)
		offsetX = 0;
	else
		offsetX = parseInt(offsetX);
	switch (edge)
	{
		case "center":
			top += baseHeight / 2;
			left += baseWidth / 2;
			break;
		case "top-left":
			break;
		case "top-right":
			left += baseWidth;
			break;
		case "bottom-right":
			top += baseHeight;
			left += baseWidth;
			break;
		case "bottom-left":
		default:
			top += baseHeight;
			break;
	}
	switch (direct)
	{
		case "center":
			left -= targetWidth / 2;
			top -= targetHeight / 2;
		case "left-up":
			left -= targetWidth;
			top -= targetHeight;
			top -= offsetY;
			left -= offsetX;
			break;
		case "left-down":
			left -= targetWidth;
			top += offsetY;
			left -= offsetX;
			break;
		case "right-up":
			top -= targetHeight;
			top -= offsetY;
			left += offsetX;
			break;
		case "right-down":
		default:
			top += offsetY;
			left += offsetX;
			break;
	}
	$(target)
		.css("top", top)
		.css("left", left);
};
uutuu.util.width = function(elem, val) {
	var jElement = $(elem);
	var direction = ["Right", "Left"];
	var style = [["margin",""], ["border","Width"],["padding",""]];
	if (val === undefined || val == null) {
		var width = elem.offsetWidth;
		for (var i = 0; i < direction.length; i++)
		{
			var length = jElement.css("margin" + direction[i]);
			if (length && length.constructor == String)
					length = length.replace(/[a-zA-Z]/g, "");
			width += length ? parseInt(length) : 0;
		}
		return width;
	} else {
		for (var i = 0; i < direction.length; i++)
			for (var j = 0; j < style.length; j++)
			{
				var length = jElement.css(style[j][0] + direction[i] + style[j][1]);
				if (length && length.constructor == String)
					length = length.replace(/[a-zA-Z]/g, "");
				val -= length ? parseInt(length) : 0;
			}
		jElement.width(val);
	}
};
uutuu.util.height = function(elem, val) {
	var jElement = $(elem);
	var direction = ["Top", "Bottom"];
	var style = [["margin",""], ["border","Width"],["padding",""]];
	if (val === undefined || val == null) {
		var height = elem.offsetHeight;
		for (var i = 0; i < direction.length; i++)
		{
			var length = jElement.css("margin" + direction[i]);
			if (length && length.constructor == String)
					length = length.replace(/[a-zA-Z]/g, "");
			height += length ? parseInt(length) : 0;
		}
		return height;
	} else {
		for (var i = 0; i < direction.length; i++)
			for (var j = 0; j < style.length; j++)
			{
				var length = jElement.css(style[j][0] + direction[i] + style[j][1]);
				if (length && length.constructor == String)
					length = length.replace(/[a-zA-Z]/g, "");
				val -= length ? parseInt(length) : 0;
			}
		jElement.height(val);
	}
};
uutuu.util.selectInputText = function(input) {
	if (!input)
		return false;

	if (input.tagName.toLowerCase() != 'textarea' &&
		input.tagName.toLowerCase() != 'input' &&
		input.getAttribute('type') != 'text')
		return false;

	if (input.createTextRange) {
		var range = input.createTextRange();
		range.select();
		return true;
	}
	else if (input.select) {
		input.select();
		return true;
	}
	return false;
};
/**
 * Copyright (C) krikkit - krikkit@gmx.net
 * --> http://www.krikkit.net/
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 */
uutuu.util.copy = function(txt) {
	if (window.clipboardData)
	{
		// the IE-manier
		window.clipboardData.setData("Text", txt);

		return true;
	}
	else if (window.netscape)
	{
		try{
			// dit is belangrijk maar staat nergens duidelijk vermeld:
			// you have to sign the code to enable this, or see notes below
			netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

			// maak een interface naar het clipboard
			var clip = Components.classes['@mozilla.org/widget/clipboard;1']
	           	.createInstance(Components.interfaces.nsIClipboard);
			if (!clip) return false;

			// maak een transferable
			var trans = Components.classes['@mozilla.org/widget/transferable;1']
               	.createInstance(Components.interfaces.nsITransferable);
			if (!trans) return false;

			// specificeer wat voor soort data we op willen halen; text in dit geval
			trans.addDataFlavor('text/unicode');

			// om de data uit de transferable te halen hebben we 2 nieuwe objecten
			// nodig om het in op te slaan
			var str = new Object();
			var len = new Object();

			var str = Components.classes["@mozilla.org/supports-string;1"]
				.createInstance(Components.interfaces.nsISupportsString);

			var copytext = txt;
			str.data=copytext;
			trans.setTransferData("text/unicode",str,copytext.length*2);

			var clipid=Components.interfaces.nsIClipboard;
			if (!clip) return false;

			clip.setData(trans,null,clipid.kGlobalClipboard);
			return true;
		}
		catch(e)
		{
			return false;
		}
	}
	return false;
};
/**
 * portable functions for querying window and document geometry
 *
 * This module defines functions for querying window and document geometry.
 *
 * getScreenX/Y( ): return the position of the window on the screen
 * getInnerWidth/Height( ): return the size of the browser viewport area
 * getScrollWidth/Height( ): return the size of the document
 * getPageXOffset( ): return the position of the horizontal scrollbar
 * getPageYOffset( ): return the position of the vertical scrollbar
 *
 * Note that there is no portable way to query the overall size of the
 * browser window, so there are no getWindowWidth/Height( ) functions.
 *
 * IMPORTANT: This module must be included in the <body> of a document
 *            instead of the <head> of the document.
 */
uutuu.util.getScreenX = function() {
	if (window.screenLeft) // IE and others
	    return window.screenLeft;
	else // Firefox and others
	    return window.screenX;
}
uutuu.util.getScreenY = function() {
	if (window.screenTop) // IE and others
	    return window.screenTop;
	else // Firefox and others
	    return window.screenY;
}
uutuu.util.getInnerWidth = function() {
	if (window.innerWidth) { // All browsers but IE
	    return window.innerWidth;
	}
	else if (document.documentElement && document.documentElement.clientWidth) {
	    // These functions are for IE 6 when there is a DOCTYPE
	    return document.documentElement.clientWidth;
	}
	else if (document.body.clientWidth) {
	    // These are for IE4, IE5, and IE6 without a DOCTYPE
	    return document.body.clientWidth;
	}
}
uutuu.util.getInnerHeight = function() {
	if (window.innerHeight) { // All browsers but IE
	    return window.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight) {
	    // These functions are for IE 6 when there is a DOCTYPE
	    return document.documentElement.clientHeight;
	}
	else if (document.body.clientHeight) {
	    // These are for IE4, IE5, and IE6 without a DOCTYPE
	    return document.body.clientHeight;
	}
}
uutuu.util.getPageXOffset = function() {
	if (window.pageXOffset != undefined) { // All browsers but IE
	    return window.pageXOffset;
	}
	else if (document.documentElement && document.documentElement.scrollLeft != undefined) {
	    // These functions are for IE 6 when there is a DOCTYPE
	    return document.documentElement.scrollLeft;
	}
	else if (document.body.scrollLeft != undefined) {
	    // These are for IE4, IE5, and IE6 without a DOCTYPE
	    return document.body.scrollLeft;
	}
}
uutuu.util.getPageYOffset = function() {
	if (window.getPageYOffset != undefined) { // All browsers but IE
	    return window.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop != undefined) {
	    // These functions are for IE 6 when there is a DOCTYPE
	    return document.documentElement.scrollTop;
	}
	else if (document.body.scrollTop != undefined) {
	    // These are for IE4, IE5, and IE6 without a DOCTYPE
	    return document.body.scrollTop;
	}
}
// These functions return the size of the document. They are not window
// related, but they are useful to have here anyway.
uutuu.util.getScrollWidth = function() {
	if (document.documentElement && document.documentElemnet.scrollWidth) {
	    return document.documentElement.scrollWidth;
	}
	else if (document.body.scrollWidth) {
	    return document.body.scrollWidth;
	}
}
uutuu.util.getScrollHeight = function() {
	if (document.documentElement && document.documentElemnet.scrollHeight) {
	    return document.documentElement.scrollHeight;
	}
	else if (document.body.scrollHeight) {
	    return document.body.scrollHeight;
	}
}
uutuu.util.encodeQueryContext = function(key, withoutPostfix) {
	var encodekey = encodeURIComponent(key);
	encodekey = encodekey.replace(/\!/g, "%21");
	encodekey = encodekey.replace(/\~/g, "%7E");
	encodekey = encodekey.replace(/\*/g, "%2A");
	encodekey = encodekey.replace(/\'/g, "%27");
	encodekey = encodekey.replace(/\(/g, "%28");
	encodekey = encodekey.replace(/\)/g, "%29");
	encodekey = encodekey.replace(/\./g, "~2E");
	encodekey = encodekey.replace(/\-/g, "~2D");
	encodekey = encodekey.replace(/\%2F/g, "-");
	encodekey = encodekey.replace(/\%/g, "~");
	return withoutPostfix ? encodekey : (encodekey + ".htm");
}
// Dynamic load javascript
uutuu.util.loadScript = function(url) {
	var script = document.createElement('script');
	script.type = 'text/javascript';
	document.getElementsByTagName('head')[0].appendChild(script);
	script.src = url;
}
uutuu.util.registerUnloadMonitor = function(elem) {
	if (!elem)	return;
	// link or button
	var func = $(elem).attr("onclick");
	var obj = this;
	if (func) {
		$(elem).attr("onclick", "");
		if (func.constructor == String) {
			eval("c = function() {" + func + "};");
			func = c;
		}
	}
	else if ($(elem).attr("href")) {
		func = function() {
			var link = $(elem).attr("href");
			window.location = link;
		};
	}
	if (!func)
		return;

	// reset click handler
	var obj = this;
	$(elem).click(function(event) {
		uutuu.UI.Panel.message("请稍等……");
		event.preventDefault();
		func();
	});
};
uutuu.util.jQueryAjaxHelper = function(ajaxOptions, errorHandler) {
	if (!errorHandler && ajaxOptions.error) {
		errorHandler = ajaxOptions.error;
	}
	else if (!errorHandler) {
		errorHandler = function(request, type, ex){
			if (ex && ex.message)
				uutuu.UI.Panel.alert(ex.message);
			else
				uutuu.UI.Panel.alert(uutuu.Resource.getResource().entry("INFO_REQUEST_FAILED"));
		};
	}

	if (!ajaxOptions.error) {
		ajaxOptions.error = errorHandler;
	}

	if (ajaxOptions.success) {
		var successCallback = ajaxOptions.success;
		ajaxOptions.success = function(data, textStatus) {
			try {
				successCallback(data, textStatus)
			}
			catch (ex) {
				errorHandler(null, "responseException", ex);
			}
		}
	}

	try {
		jQuery.ajax(ajaxOptions);
	}
	catch (ex) {
		errorHandler(null, "requestException", ex);
	}
};

var gecko_event =
	["altKey",new Function("this.event.stopPropagation();"),"clientX","clientY","ctrlKey","relatedTarget","keyCode",
	new Function("this.event.preventDefault();"),"screenX","screenY","shiftKey","target","currentTarget","type"];
var ie_event =
	["altKey",new Function("this.event.cancelBubble=true;"),"clientX","clientY","ctrlKey","fromElement","keyCode",
	new Function("this.event.returnValue=false;"),"screenX","screenY","shiftKey","srcElement","srcElement","type"];
function BroserEvent(eventobj)
{
	if (!eventobj)
		eventobj = window.event;

	var events = null;
	if ($.browser.msie)
		events = ie_event;
	else
		events = gecko_event;

	this.event = eventobj;
	this.altKey = eventobj[events[0]];
	this.stopPropagation = events[1];
	this.clientX = eventobj[events[2]];
	this.clientY = eventobj[events[3]];
	this.ctrlKey = eventobj[events[4]];
	this.relatedTarget = eventobj[events[5]] ? eventobj[events[5]] : eventobj.toElement;
	this.keyCode = eventobj[events[6]];
	this.preventDefault = events[7];
	this.screenX = eventobj[events[8]];
	this.screenY = eventobj[events[9]];
	this.shiftKey = eventobj[events[10]];
	this.target = eventobj[events[11]];
	this.currentTarget = eventobj[events[12]];
	this.type = eventobj[events[13]];
}
