﻿/**
 * Create Object Page
 * 
 * @author     banhthidiem <banhthidiem@gmail.com>
 * @copyright  2007 Bach Khoa Computer Inc.
 * @version    $Id: CreateObjectPage.js, v2.0 2007/10/18
 */

String.prototype.addslashes = function()
{
	return this.replace(/(["\\\.\|\[\]\^\*\+\?\$\(\)])/g, '\\$1');
};

String.prototype.trim = function()
{
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
};

Date.prototype.toVNString = function()
{
	var a_pm = "AM"; 
	var hours = this.getHours();
	if (hours > 12)
	{
		hours = hours - 12;
		a_pm = "PM";
	}
	return this.getDate() + "/" + (this.getMonth() + 1) + "/" + this.getFullYear() + " " + hours + ":" + this.getMinutes() + ":" + this.getSeconds() + " " + a_pm;
};

Date.prototype.subtract = function(d)
{
	return (this - d) / (1000 * 60 * 60 * 24);
};

Date.maxDateInMonth = function(month, year)
{
	var d = 0;
	switch(month)
	{
		case 1 : case 3 : case 5 : case 7 : case 8: case 10 : case 12 :
			d =31; 
			break;
		case 4 : case 6 : case 9 : case 11 :
			d = 30; 
			break;
		case 2 :
			if(((year % 400) == 0) || (( (year % 4) == 0) && ( (year % 100) != 0 )))
				d = 29;
			else 
				d = 28;
		break;
	}
	return d;
};

Date.check = function(day, month, year)
{
  if(isNaN(day) || isNaN(month) || isNaN(year)) return false;
  if(day <= 0 || month <= 0 || year <= 0) return false;
  else
    {
        var dayspermonth  =  Date.maxDateInMonth(month,year);
        if( day <=  dayspermonth) 
         {
            return true;
         }
        else 
        {
            return false;
        }
    }
};
Date.checkStringVN = function(dateString) {
	var arrDate = dateString.split("/");
	if (arrDate.length < 3) return false;
	if (isNaN(arrDate[0]) || isNaN(arrDate[1]) || isNaN(arrDate[2])) return false;
	return Date.check(parseInt(arrDate[0], 10), parseInt(arrDate[1], 10), parseInt(arrDate[2], 10));
};

Date.parseDateVN = function(strDateVN)
{
	var arrDate = strDateVN.split("/");
	if (arrDate.length <= 1)
	{
		arrDate = strDateVN.split("-");
	}
	return new Date(parseInt(arrDate[2],10), parseInt(arrDate[1],10) - 1, parseInt(arrDate[0]),10);
};

// Remove IE mouse flickering.
try
{
	document.execCommand("BackgroundImageCache", false, true);
}
catch (e)
{
	// We have been reported about loading problems caused by the above
	// line. For safety, let's just ignore errors.
}

function Util$BTD()
{
	this.wd = window;
	this.d = this.wd.document;
	var ua = navigator.userAgent.toLowerCase();
	this.isSafari = (ua.indexOf("safari") != -1);
	this.isOpera = (ua.indexOf("opera") != -1);
	this.isMaxthon = (ua.indexOf("maxthon") != -1);
	this.isIE = ((ua.indexOf("msie") != -1) && (!this.isOpera) && (ua.indexOf("webtv") == -1));
	this.isFF = (ua.indexOf("firefox") != -1);
	this.isDoctype = (this.d.compatMode && this.d.compatMode != "BackCompat");
	if (this.isIE)
	{
		this.appVersion = parseFloat(ua.substr(ua.indexOf("msie") + 4, 2));
	}
	else
	{
		this.appVersion = parseFloat(navigator.appVersion.substr(0, navigator.appVersion.indexOf("(")));
	}
	
	this.listActionsOnScroll = new Array();
};

Util$BTD.prototype = 
{
	/*
	 * Get element by id
	 */
	getElById : function(strId)
	{
		return this.d.getElementById(strId);
	},
	
	/*
	 * Get element by id
	 */
	isStringEmpty : function(s)
	{
		return ((s == null) || (s.trim() == ""));
	},
	
	/*
	 * Create Element
	 */
	createEl : function(tagName)
	{
		return this.d.createElement(tagName);
	},
	
	/*
	 * Set Title Document
	 */
	setTitleDocument : function(title)
	{
		this.d.title = title;
	},
	
	/*
	 * Create Script
	 */
	createScript : function(id, src)
	{
		try
		{
			var o = this.getElById(id);
			if (o == null)
			{
				var o = this.createEl("SCRIPT");
				o.id = id;
				o.type = "text/javascript";
				o.src = src;
				this.d.getElementsByTagName("HEAD")[0].appendChild(o);
			}
		}
		catch (e)
		{ }
	},
	
	cutStringByNum : function(content, numberChar)
	{
		content = this.stripHtmlTags(content);
		if (content.length <= numberChar) return content.trim();

		for (var i = 0; i < 10; i++)
		{
			numberChar = numberChar + 1;
			if ((numberChar >= content.length) 
				|| (numberChar < content.length && content.charAt(numberChar) == " ")
				)
			{
				break;
			}
		}
		return content.substring(0, numberChar) + "...";
	},
	
	/*
	 * Append Element to body
	 */
	addChildToBody : function(el)
	{
		this.d.body.appendChild(el);
	},
	
	/*
	 * Create Style
	 */
	createStyle : function(cssStr)
	{
		try
		{
			var eStyle = this.createEl("STYLE");
			eStyle.setAttribute("type", "text/css");
			this.d.getElementsByTagName("HEAD")[0].appendChild(eStyle);
			if(eStyle.styleSheet)
			{ 
				eStyle.styleSheet.cssText = cssStr;
			}
			else 
			{
				// w3c
				var cssText = this.createElText(cssStr);
				eStyle.appendChild(cssText);
			}
		}
		catch (e)
		{ }
	},
	
	createElText : function(text)
	{
		return this.d.createTextNode(text);
	},

	stripHtmlTags : function(strText)
	{
		var regEx = /<[^>]*>/g;
		return strText.replace(regEx, "");
	},

	encodeTagUL : function(con)
	{
		con = this.stripHtmlTags(con.trim());
		con = con.replace(/\r\n/g, "\n");
		var lines = con.split("\n");
		if (lines.length == 0) return "";
		if (lines.length == 1) return con.trim();
		var re = "<ul>";
		for (var i = 0; i < lines.length; i++)
		{
			if (lines[i].trim() != "")
				re += "<li>" + lines[i] + "</li>";
		}
		re += "</ul>";
		return re;
	},

	decodeTagUL : function(con)
	{
		con = con.replace(/\r\n/g, "\n");
		con = con.replace(/\n/g, "");
		con = con.replace(/<UL>/gi, "");
		con = con.replace(/<\/UL>/gi, "");
		con = con.replace(/<LI>/gi, "");
		con = con.replace(/<\/LI>/gi, "\n");
		return con;
	},
	
	/*
	 * Add Attribute for Element
	 */
	createAttribute : function(obj, atb_name, value)
	{
		obj[atb_name] = value;
	},
	
	/*
	 * Get Document
	 */
	getDocument : function()
	{
		return (this.isDoctype ? this.d.documentElement : this.d.body);
	},
	
	/*
	 * Get Document Scroll
	 */
	getDocumentScroll : function()
	{
		return (!this.isSafari ? this.d.documentElement : this.d.body);
	},

	//----------------Add or Remove Event of Element------------------
	
	createEventOnScroll : function()
	{
		var self = this;
		if (self.isIE && self.appVersion == 7)
		{
			self.d.body.onscroll = function()
			{
				self.doActionOnScroll();
			}
		}
		else
		{
			self.wd.onscroll = function()
			{
				self.doActionOnScroll();
			}
		}
		
	},
	
	doActionOnScroll : function()
	{
		for (var i = 0; i < this.listActionsOnScroll.length; i++)
		{
			this.listActionsOnScroll[i]();
		}
	},
	
	isNumber : function(v) 
	{
		return typeof(v) == 'number' && isFinite(v);
	},
	
	isUserName : function(v)
	{
		var filter  = /^([a-zA-Z0-9_\.\-])+$/;
		if (filter.test(v)) return true;
		else return false;
	},
	
	isEmail : function(v)
	{
		var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if (filter.test(v)) return true;
		else return false;
	},
	
	isDateVN : function(v)
	{
		var filter  = /^([0-9]{1,2})+\/([0-9]{1,2})+\/([0-9]{4,4})+$/;
		if (!filter.test(v)) return false;
		var arr = v.split("/");
		var d = parseInt(arr[0], 10);
		var m = parseInt(arr[1], 10);
		var y = parseInt(arr[2], 10);
		if (d > Date.maxDateInMonth(m, y) || d < 1) return false;
		if (m > 12 || m < 1) return false;
		return true;
	},
	
	deleteActionOnScroll : function(func)
	{
		try
		{
			for (var i = 0; i < this.listActionsOnScroll.length; i++)
			{
				if (this.listActionsOnScroll[i] == func) break;
			}
			this.listActionsOnScroll.splice(i, 1);
		}
		catch (er) { }
	},
	
	addEvent : function(obj, eventName, func)
	{
		if (eventName.toLowerCase() == "scroll")
		{
			if (!this.firstCallOnScroll)
			{
				this.firstCallOnScroll = true;
				this.createEventOnScroll();
			}
			this.listActionsOnScroll[this.listActionsOnScroll.length] = func;
			return;
		}
		if (obj.attachEvent)
		{
			obj.attachEvent("on" + eventName, func);
		}
		else if(obj.addEventListener)
		{
			obj.addEventListener(eventName, func, true);
		}
		else
		{
			obj["on" + eventName] = func;
		}
	},
	
	removeEvent : function(obj, eventName, func)
	{
		if (eventName.toLowerCase() == "scroll")
		{
			this.deleteActionOnScroll(func);
			return;
		}
		if (obj.detachEvent)
		{
			obj.detachEvent("on" + eventName, func);
		}
		else if(obj.removeEventListener)
		{
			obj.removeEventListener(eventName, func, true);
		}
		else
		{
			obj["on" + eventName] = null;
		}
	},
	
	stopEvent : function(e)
	{
		var evt = (typeof(e) != "undefined") ? e : this.getWindowEvent();
		if (typeof(evt.stopPropagation) != "undefined")
		{
			evt.stopPropagation();
			evt.preventDefault();
		}
		else if(typeof(evt.cancelBubble) != "undefined")
		{
			evt.cancelBubble = true;
			evt.returnValue = false;
		}
	},
	
	disableContextMenu : function(element)
	{
		element.oncontextmenu = function()
		{
			return false;
		}
	},
	
	enableContextMenu : function(element)
	{
		element.oncontextmenu = null;
	},
	
	disableSelection : function(target)
	{
		if (this.isIE || this.isOpera || this.isSafari) //IE route
		{
			target.onselectstart = function()
			{
				return false;
			}
		}
		else if (typeof(target.style.MozUserSelect) != "undefined")
		{
			target.style.MozUserSelect = "none";
		}
		target.style.cursor = "default";
	},
	
	rand : function(n)
	{
		return ( Math.floor(Math.random() * n + 1) );
	},
	
	enableSelection : function(target)
	{
		if (this.isIE || this.isOpera) //IE route
		{
			target.onselectstart = null;
		}
		else if (typeof(target.style.MozUserSelect) != "undefined")
		{
			target.style.MozUserSelect = "";
		}
		target.style.cursor = "default";
	},
	
	mouseCoords : function(ev)
	{
		if(ev.pageX && ev.pageY)
		{
			return { X: ev.pageX, Y: ev.pageY };
		}
		var de = this.getDocument();
		var deScroll = this.getDocumentScroll();
		return { X: ev.clientX + deScroll.scrollLeft, Y: ev.clientY + deScroll.scrollTop };
	},
	
	mouseCoordsAndPosEl : function(e, el)
	{
		var clientX = e.clientX, clientY = e.clientY;
		var oW = el.offsetWidth, oH = el.offsetHeight;
		var de = this.getDocument();
		var deScroll = this.getDocumentScroll();
		var posX = clientX + oW > de.clientWidth ? clientX - oW - 5 : 5 + clientX;
		var posY = clientY + oH > de.clientHeight ? clientY - oH - 5 : 5 + clientY;
		return { X: posX + deScroll.scrollLeft, Y: posY + deScroll.scrollTop };
	},
	
	getPositionMenuByMouse : function(e, pos)
	{
		var de = this.getDocument();
		switch (pos)
		{
			case "top":
				if (e.clientY < de.clientHeight / 2)
					pos = "bottom";
				break;
			case "bottom":
				if (e.clientY >= de.clientHeight / 2)
					pos = "top";
				break;
			case "left":
				if (e.clientX < de.clientWidth / 2)
					pos = "right";
				break;
			case "right":
				if (e.clientX >= de.clientWidth / 2)
					pos = "left";
				break;
		}
		return pos;
	},
	
	coordsElChildByParentIntelligent : function(e, elChild, elParent)
	{
		e = this.getWindowEvent();
		var height = this.getElementSize(elParent).height + e.clientY + this.getElementSize(elChild).height;
		var pos = height > this.getDocument().clientHeight ? "top" : "bottom";
		return this.coordsElChildByParent(elChild, elParent, pos);
	},
	
	coordsElChildByParent : function(elChild, elParent, pos)
	{
		var posParent = this.getElementPosition(elParent);
		var size = null;
		switch (pos)
		{
			case "top":
				return { X: posParent.X, Y: posParent.Y - this.getElementSize(elChild).height };
				break;
			case "bottom":
				return { X: posParent.X, Y: posParent.Y + this.getElementSize(elParent).height };
				break;
			case "left":
				return { X: posParent.X - this.getElementSize(elChild).width, Y: posParent.Y };
				break;
			case "right":
				return { X: posParent.X + this.getElementSize(elParent).width, Y: posParent.Y };
				break;
			case "topLeft":
				size = this.getElementSize(elChild);
				return { X: posParent.X -  size.width, Y: posParent.Y - size.height };
				break;
			case "topRight":
				return { X: posParent.X + this.getElementSize(elParent).width, Y: posParent.Y - this.getElementSize(elChild).height };
				break;
			case "bottomLeft":
				return { X: posParent.X -  this.getElementSize(elChild).width, Y: posParent.Y + this.getElementSize(elParent).height };
				break;
			case "bottomRight":
				size = this.getElementSize(elParent);
				return { X: posParent.X + size.width, Y: posParent.Y + size.height };
				break;
			default:
				return { X: 0, Y: 0 };
				break;
		}
	},
	
	getElPosCenterWebPage : function(el)
	{
		var s = this.getElementSize(el);
		var de = this.getDocument();
		var deScroll = this.getDocumentScroll();
		return {
			X: (s.width > de.clientWidth ? deScroll.scrollLeft : (de.clientWidth - s.width) / 2 + deScroll.scrollLeft), 
			Y: (s.height > de.clientHeight ? deScroll.scrollTop : (de.clientHeight - s.height) / 2 + deScroll.scrollTop) 
		};
	},
	
	getElementSize : function(el)
	{
		var result = { width: 0, height: 0 };
		var dip = el.style.display;
		if(dip == "none")
		{
			el.style.display = "";
		}
		result.width = el.offsetWidth;
		result.height = el.offsetHeight;
		el.style.display = dip;
		return result;	
	},
	
	getElementPosition : function(el)
	{
		var c = { X: 0, Y: 0 };
		while ( el )
		{	c.X += el.offsetLeft;
			c.Y += el.offsetTop;
			el = el.offsetParent;
		}
		return c;
	},
	
	getElement : function()
	{
		var e = this.getWindowEvent();
		if (e != null)
			return this.isIE || this.isOpera ? e.srcElement : e.currentTarget;
		else
			return null;
	},
	
	getTargetElement : function()
	{
		var e = this.getWindowEvent();
		if (e != null)
			return this.isIE || this.isOpera ? e.srcElement : e.target;
		else
			return null;
	},
	
	getWindowEvent : function()
	{
		if(this.isIE || this.isOpera)	return this.wd.event;
		func = this.getWindowEvent.caller;
		while(func != null)
		{
			var arg0 = func.arguments[0];
			if(arg0)
			{
				if((arg0.constructor == Event || arg0.constructor == MouseEvent)
					|| (typeof(arg0) == "object" && arg0.preventDefault && arg0.stopPropagation))
				{
					return arg0;
				}
			}
			func = func.caller;
		}
		return null;
	},
	
	changeStyleAll : function(o, styleDefault, style, word)
	{
		for (var i = 0; i < o.childNodes.length; i++)
		{
			var child = o.childNodes[i];
			var className = child.className;
			if (className)
			{
				if (className != "" && className.indexOf(word) != -1)
				{
					child.className = className.replace(styleDefault, style);
				}
			}
			this.changeStyleAll(child, styleDefault, style, word);
		}
	},
	
	getCookie : function(name) 
	{
		var results = this.d.cookie.match( name + '=(.*?)(;|$)' );
		if (results)
			return ( unescape( results[1] ) );
		else
			return null;
	},

	setCookie : function(name, value, expires, path, domain, secure) 
	{
		var date = new Date();
		date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000));
		this.d.cookie = name + "=" + escape(value) + 
			( (expires) ? ";expires=" + expires.toGMTString() : ";expires=" + date.toGMTString()) + 
			( (path) ? ";path=" + path : "") + 
			( (domain) ? ";domain=" + domain : "") + 
			( (secure) ? ";secure" : "");
	},

	deleteCookie : function(name, path, domain)
	{
		if (this.getCookie(name)) this.d.cookie = name + "=" + 
			( (path) ? ";path=" + path : "") + 
			( (domain) ? ";domain=" + domain : "") + 
			";expires=Thu, 01-Jan-70 00:00:01 GMT"; 
	},
	
	getQueryStringByCharSharp : function()
	{
		var pos = location.href.indexOf("#");
		if (pos != -1)
		{
			var queryString = location.href.substr(pos + 1);
			if (queryString != "") 
			{
				return queryString;
			}
			else
			{
				return "Home";
			}
		}
		else
		{
			return "Home";
		}
	},
	
	analyseURL : function(url, tail)
	{
		if (typeof(tail) == "undefined") tail = "";
		var para = [];
		var arrTemp = url.split("?");
		if (arrTemp.length > 1)
		{
			var arrPara = arrTemp[1].split("&");
			for (var i = 0; i < arrPara.length; i++)
			{
				var arrSub = arrPara[i].split("=");
				para[arrSub[0]] = arrSub[1];
			}
		}
		return {page : (arrTemp[0].indexOf(tail) == -1 ? arrTemp[0] + tail : arrTemp[0]), paramater : para};
	},
	
	isSelected : function(o)
	{
		for (var i = 0; i < o.length; i++)
		{
			if (o[i].selected) return true;
		}
		return false;
	},
	
	isImage : function(file)
	{
		if (file.trim() == "")	return false;
		var pos = file.lastIndexOf(".") + 1;
		var tail = file.substring(pos, file.length).toLowerCase();
		if ((tail != "gif") && (tail != "jpg") && (tail != "png") && (tail != "bmp"))
			return false;
		return true;
	},
	
	// myField accepts an object reference, myValue accepts the text strint to add 
	insertTextAtCursor : function(myField, myValue)
	{
		//IE support 
		if (this.d.selection)
		{ 
			myField.focus(); 
			var sel = this.d.selection.createRange();
			sel.text = myValue; 
		} 
		//Mozilla/Firefox/Netscape 7+ support 
		else if (myField.selectionStart || myField.selectionStart == '0')
		{
			var startPos = myField.selectionStart; 
			var endPos = myField.selectionEnd; 
			myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length); 
		}
		else
		{
			myField.value += myValue;
		}
	},
	
	changeBackgroundColor : function(o, checked)
	{
		while (o.tagName != "TR" && o != null)
		{
			o = o.parentNode;
		}
		o.style.backgroundColor = checked ? "#F2FEC5" : "#fff";
	},
	
	addItemToSelectBox : function(elSel, text, value)
	{
		var elOption = this.createEl("OPTION");
		elOption.value = value;
		elOption.text = text;
		try
		{
			elSel.add(elOption, null); // standards compliant
		}
		catch(ex)
		{
			elSel.add(elOption); // IE only
		}
	},
	
	checkOrSelect : function(o, value)
	{
		for	(var i = 0; i < o.length; i++)
		{
			if (value == o[i].value)
			{
				if (o.tagName.toLowerCase() == "select")
				{
					o[i].selected = true;
				}
				else
				{
					o[i].checked = true;
				}
				return;
			}
		}
	},
	
	clearItemSelect : function(oSel)
	{
		for (var i = oSel.length - 1; i >= 0; i--)
		{
			oSel.remove(i);
		}
	},
	
	doCheck : function(oElAll, oElItems, objChk, isAll)
	{
		if (isAll == 0)
		{
			this.changeBackgroundColor(objChk, objChk.checked);
		}
		var flag = true;
		var len = oElItems.length;
		if (len != null)
		{
			if (isAll == 0)
			{
				if (objChk.checked == true)
				{
					for (var i = 0; i < len; i++)
					{
						if (oElItems[i].checked == false)
						{
							flag = false;
							break;
						}
					}
					oElAll.checked = flag;
				}
				else
				{
					oElAll.checked = false;
				}
			}
			else
			{
				for (var i = 0; i < len; i++)
				{
					if (!oElItems[i].checked) this.changeBackgroundColor(oElItems[i], objChk.checked);
					oElItems[i].checked = objChk.checked;
				}
			}	
		}
		else
		{
			if (isAll == 0)
			{
				oElAll.checked = objChk.checked;
			}
			else
			{
				oElItems.checked = objChk.checked;
				this.changeBackgroundColor(oElItems, oElItems.checked);
			}	
		}
	},

	// ---------------------------Use for insert or remove value have comma---------------------------------
	removeStrIncludeComma : function(str, v)
	{
		if (str.indexOf(v) != 0)
		{
			v = "," + v;
		}
		else
		{
			v = (str.indexOf(",") != -1) ? v + "," : v;
		}
		return str.replace(v, "");
	},

	addStrIncludeComma : function(str, v)
	{
		if (str != "")
		{
			str += ",";
		}
		str += v;
		return str;
	},
	
	//
	// ---------------------------Find the parent by tagname of element---------------------------------
	//
	getParentByTagName : function(element, tagName)
	{
		while (element)
		{
			if (element.tagName == tagName)
			{
				return element;
			}
			element = element.parentNode;
		}
		return null;
	},
	
	formatNumber: function(num, charSep) {
		var s = num + "";
		var arrTemp = s.split(".");
		var re = arrTemp[0];
		if (arrTemp[0].length > 3) {
			var first = arrTemp[0].length % 3;
			first = first == 0 ? 3 : first;
			re = "";
			var counter = 0;
			for (var i = 0; i < arrTemp[0].length; i++) {
				re += arrTemp[0].charAt(i);
				if (i + 1 > first) {
					counter++;
					if (counter == 3 && arrTemp[0].length > i + 1) {
						re += charSep;
						counter = 0;
					}
				}
				else if (i + 1 == first) {
					re += charSep;
				}
			}
		}
		if (arrTemp[1] != null && arrTemp[1].trim().length > 0) {
			re += (charSep == "." ? "," : ".") + arrTemp[1];
		}
		return re;
	}
};

var utilObj = new Util$BTD();

