/**
 * Core functions
 * @version	$Id: class.core.js, v1.0 2007/12/12 16:04
 */
var offsetxpoint=10;
var offsetypoint=20;
var ie=document.all;
var ns6=document.getElementById && !document.all;
var enabletip=false;
var tipobj = null;
var ua = navigator.userAgent.toLowerCase();
var is = {
  version: parseInt(navigator.appVersion),
  webtv  : ua.indexOf('webtv') > -1,
  konq   : ua.indexOf('konqueror') > -1,
  ns     : ua.indexOf('navigator') > -1,
  safari : ua.indexOf('applewebkit') > -1 || navigator.vendor == 'Apple Computer, Inc.',
  moz    : navigator.product == 'Gecko' && ua.indexOf('applewebkit') == -1 && ua.indexOf('navigator') == -1,
  ie     : !!(window.attachEvent && !window.opera),
  opera  : !!window.opera,
  win    : ua.indexOf('win') > -1 || ua.indexOf('16bit') > -1,
  mac    : ua.indexOf('mac') > -1
};

/**
 * Some functional prototypes
 */
String.prototype.strip = function()
{
	return this.toString().replace(/^\s*/,'').replace(/\s*$/,'');
};

String.prototype.reverse = function()
{
	return this.split('').reverse().join('');
};

String.prototype.parseURL = function(sep)
{
	var match = this.match(/([^?#]*)(#.*)?$/);
	var hash  = {};
  	
	if (match)
	{
		var pairs = match[1].split(sep || '&');
		
		for (var i = 0; i < pairs.length; i++)
		{
			if ((pair = pairs[i].split('='))[0])
			{
				var key   = decodeURIComponent(pair.shift());
				var value = pair.length > 1 ? pair.join('=') : pair[0];
				
				if (typeof value != 'undefined')
				{
					value = decodeURIComponent(value);
				}
				
				if (key in hash)
				{
					if (hash[key].constructor != Array) hash[key] = [hash[key]];
					hash[key].push(value);
				}
				else
				{
					hash[key] = value;
				}
			}
		}
	}
	
	return hash;
};

String.prototype.supplant = function(o)
{
	return this.replace(/{([^{}]*)}/g, function(a, b){var r = o[b]; return r ? r : a;});
};

/**
 * Represents a mutable string of characters
 */
function StringBuilder(value)
{
    this.strings = new Array('');
    this.append(value);
}

StringBuilder.prototype.append = function(value)
{
    if (value) this.strings.push(value);
}

StringBuilder.prototype.clear = function()
{
    this.strings.length = 1;
}

StringBuilder.prototype.toString = function()
{
    return this.strings.join('');
}

/**
 * Add onload event
 */
function add_onload_event(func)
{
	var oldonload = window.onload;
	
	if (typeof(window.onload) != 'function')
	{
		window.onload = func;
	}
	else
	{
		window.onload = function()
		{
			if (oldonload) oldonload();
			func();
		};
	}
}

/**
 * Stop the browser bubbling events
 */
function cancel_bubble(obj, extra)
{
	if (extra === true) extra = true;
	
	if (!obj || is.ie)
	{
		if (extra) window.event.returnValue = false;
		window.event.cancelBubble = true;
		return window.event;
	}
	else
	{
		obj.stopPropagation();
		if (extra) obj.preventDefault();
		return obj;
	}
}

function cancel_bubble_all(obj)
{
	return cancel_bubble(obj, true);
}

function cancel_bubble_low(obj)
{
	return cancel_bubble(obj, false);
}

/**
 * Various core functions
 */
function core_functions()
{
	//-------------------------------------
	// Form Handling
	//-------------------------------------
	
	// Validation
	this.encrypt = function(f, s)
	{
		if (this.check_form(f, s))
		{
			if (f.password.value.length >= 3)
			{
				f.passhash.value = hex_md5(f.password.value);
				f.password.value = f.password.value.length;
				return true;
			}
			else
			{
				alert("Mat khau can dai it nhat la 3 ky tu");
			}
		}
		
		return false;
	};
	
	this.check_form = function(f, s)
	{
		var total = 0;
		var elems = s.split(',');
		
		for (var i = 0; i < elems.length; i++)
		{
			if (this.check_field(f.elements[elems[i]])) total++;
			else break;
		}
		
		if (total == elems.length) return true;
		else return false;
	};
	
	this.check_field = function(e, msg)
	{
		if (!msg) msg = "Vui long dien day du thong tin yeu cau (*)";
		
		if (e.value.strip() == '' || e.value.length == 0)
		{
			alert(msg); e.value = ''; e.focus();
			return false;
		}
		else
		{
			if (e.name == 'email' || e.name == 'email_2')
			{
				return this.check_email(e);
			}
			else if (e.name == 'date')
			{
				return this.check_date(e);
			}
			else
			{
				return true;
			}
		}
	};
	
	this.check_email = function(e, msg)
	{
		if (!msg) msg = "Vui long cung cap dia chi email hop le theo dinh dang: localpart@domain.example";
		var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
		
		if (!e.value.match(re))
		{
			alert(msg); e.focus();
			return false;
		}
		else
		{
			return true;
		}
	};
	
	this.check_date = function(e, msg)
	{
		if (!msg) msg = "Vui long nhap ngay, thang, nam theo dinh dang: dd/mm/yyyy";
		var re = /^([\d]{1,2})[\.\-/]([\d]{1,2})[\.\-/]([\d]{2,4})$/;
		
		if (!e.value.match(re))
		{
			alert(msg); e.focus();
			return false;
		}
		else
		{
			return true;
		}
	};
	
	// Checkbox handler
	this.check_boxes = function(obj)
	{
		for (var i = 0; i < obj.elements.length; i++)
		{
			var e = obj.elements[i];
			if (e.name != 'allbox' && e.type == 'checkbox' && !e.disabled)
				e.checked = obj.allbox.checked;
		}
	};
	
	this.check_check_boxes = function(obj)
	{
		var TotalBoxes = 0;
		var TotalOn    = 0;
		
		for (var i = 0; i < obj.elements.length; i++)
		{
			var e = obj.elements[i];
			if (e.name != 'allbox' && e.type == 'checkbox')
			{
				TotalBoxes++;
				if (e.checked) TotalOn++;
				else TotalOn--;
			}
		}
		
		if (TotalBoxes == TotalOn)
		{
			obj.allbox.checked = true;
		}
		else
		{
			obj.allbox.checked = false;
		}
	};
	
	this.hl = function(e, css)
	{
		cb = this.get_parent_node(e, 'TR');
		for (i = 0; i < cb.cells.length; i++)
		{
			cb.cells[i].className = css;
		}
 	};
 	
	// Checks if 'Enter' key pressed
	this.enter_keypressed = function(e)
	{
		var key = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
		return (key == 13) ? true : false;
	};
	
	//-------------------------------------
	// Element Handling
	//-------------------------------------
	
	// Show, hide element
	this.my_show_div = function(e)
	{
		if (!e) return;
		e.style.display = '';
	};
	
	this.my_hide_div = function(e)
	{
		if (!e) return;
		e.style.display = 'none';
	};
	
	this.my_show_hide = function(id1, id2)
	{
		if (id1 != '') this.toggleview(id1);
		if (id2 != '') this.toggleview(id2);
	};
	
	this.toggleview = function(id)
	{
		if (e = this.my_getbyid(id))
		{
			if (e.style.display == 'none')
			{
				this.my_show_div(e);
			}
			else
			{
				this.my_hide_div(e);
			}
		}
	};
	
	// Resize textarea
	this.resize_textarea = function(id, to)
    {
		var textarea = this.my_getbyid(id);
		var newrows  = parseInt(textarea.style.height) + (to < 0 ? -150 : 150);
		
		if (typeof(textarea.orig_rows) == 'undefined')
		{
			textarea.orig_rows = parseInt(textarea.style.height);
		}
		
		if (to == 0)
		{
			textarea.style.height = textarea.orig_rows + 'px';
		}
		else
		{
			if (newrows >= textarea.orig_rows && newrows <= textarea.orig_rows * 5)
			{
				textarea.style.height = newrows + 'px';
			}
		}
    }
	
    // Resize image
	this.scale_img = function()
	{
		if (img = CORE.my_getbyid('screenshot'))
		{
			var args = new Array(230, 230, img.width, img.height); // max_width, max_height, cur_width, cur_height
			var ret  = new Array(args[2], args[3]);
			
			if (args[2] > args[0])
			{
				ret[0]  = args[0]; ret[1]  = Math.ceil((args[3]*((args[0]*100)/args[2]))/100);
				args[2] = ret[0] ; args[3] = ret[1];
			}
			
			if (args[3] > args[1])
			{
				ret[1] = args[1]; ret[0] = Math.ceil((args[2]*((args[1]*100)/args[3]))/100);
			}
			
			img.width = ret[0]; img.height = ret[1];
		}
	};
	
	this.getWindowHeight = function() {
 var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
};

	// Show, hide styling element
	this.pv = function(e, num)
	{
		var curLink = "";
		var sr = this.getWindowHeight;
		var srr = this.getPageScroll;
		var span = document.getElementById('pv' + num);
		if(curLink != ""){ curLink.style.display = 'none'; }
		curLink = span;
		if(!document.all){
			span.style.left = e.pageX + 10 + 'px';
			span.style.top = e.pageY + 5 + 'px';
		}else{
			span.style.pixelLeft = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft + 5 + 'px';
			span.style.pixelTop = e.clientY + document.body.scrollTop	+ document.documentElement.scrollTop + 5 + 'px';
		}
		span.style.display = 'block';
		tipobj = span;
		enabletip=true;
		document.onmousemove = this.dopv;
		return false;
	};
	
	this.getPageScroll = function(){
	var yScroll;	
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	};

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}
	
	this.dopv = function(e){	
	if (enabletip){
		var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
		var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;
		//Find out how close the mouse is to the corner of the window
		var leftedge=(offsetxpoint<0)? offsetxpoint*(-1) : -1000		
		//move the horizontal position of the menu to the left by it's width
		if(document.all)
		{
			rightedge =  document.documentElement.clientWidth - event.clientX-offsetxpoint-10;
			bottomedge = document.documentElement.clientHeight - event.clientY-offsetypoint-5;
			if(rightedge < tipobj.offsetWidth) {
				tipobj.style.pixelLeft = 10 + event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - tipobj.offsetWidth;
				tipobj.style.width = '300px';
			}
			else if(curX<leftedge)
				tipobj.style.pixelLeft = 5;
			else
				tipobj.style.pixelLeft = 10 + event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
			if (bottomedge<tipobj.offsetHeight)
				tipobj.style.pixelTop = 10 +event.clientY + document.body.scrollTop	+ document.documentElement.scrollTop - tipobj.offsetHeight;
			else		
				tipobj.style.pixelTop = 10 +event.clientY + document.body.scrollTop	+ document.documentElement.scrollTop;		
			
		}	
		else {
			rightedge = window.innerWidth-e.clientX-offsetxpoint-20;
			bottomedge = 	window.innerHeight-e.clientY-offsetypoint-20;
			if (rightedge < tipobj.offsetWidth)
				tipobj.style.left = window.pageXOffset+e.clientX-tipobj.offsetWidth+"px";
					else if (curX<leftedge)
						tipobj.style.left="5px";
					else
						tipobj.style.left=curX+offsetxpoint+"px"
			if (bottomedge<tipobj.offsetHeight)
						tipobj.style.top = window.pageYOffset+e.clientY-tipobj.offsetHeight-offsetypoint+"px";
			else
						tipobj.style.top=curY+offsetypoint+"px";
		}
		tipobj.style.visibility="visible"
	}
};
	
	this.unpv = function(num)
	{
		var span = document.getElementById('pv' + num );
		span.style.display = 'none';
		enabletip = false;
		window.onmousemove = null;
	};
	
	// Show, hide an in-line messages
	this.show_inline_messages = function()
	{
		var _string  = window.location.toString();
		var _msg_box = null;
		
		if (_string.indexOf('?___msg=') != -1 || _string.indexOf(';___msg=') != -1 || _string.indexOf('&___msg=') != -1)
		{
			try
			{
				if (parent.document.getElementById('ipd-msg-text'))
				{
					_msg_box = parent.document.getElementById('ipd-msg-text');
				}
				else
				{
					_msg_box = this.my_getbyid('ipd-msg-text');
				}
			}
			catch (e)
			{
				alert(e);
			}
			
			var message = _string.replace(/^.*[\?;&]___msg=(.+?)(&.*$|$)/, "$1");
			message = unescape(message);
			
			if (message_pop_up_lang[message])
			{
				try
				{
					_msg_box.innerHTML = message_pop_up_lang[message];
					
					centerdiv          = new center_div();
					centerdiv.divname  = 'ipd-msg-wrapper';
					centerdiv.move_div();
					
					var _this_to = setTimeout("CORE.hide_inline_messages_instant()", 2500);
				}
				catch (err)
				{
					alert(message_pop_up_lang[message]);
				}
			}
		}
	};
	
	this.show_inline_messages_instant = function(msg)
	{
		_msg_box           = this.my_getbyid('ipd-msg-text');
		_msg_box.innerHTML = message_pop_up_lang[msg];
		
		centerdiv          = new center_div();
		centerdiv.divname  = 'ipd-msg-wrapper';
		centerdiv.move_div();
		
		var _this_to = setTimeout("CORE.hide_inline_messages_instant()", 2500);
	};
	
	this.hide_inline_messages_instant = function()
	{
		try
		{
			this.my_getbyid('ipd-msg-wrapper').style.display = 'none';
			parent.document.getElementById('ipd-msg-wrapper').style.display = 'none';
		}
		catch (error) { }
	};
	
	// Dynamic clock
	this.startClock = function()
	{
		var strDay  = new Array("Ch&#7911; Nh&#7853;t","Th&#7913; Hai","Th&#7913; Ba","Th&#7913; T&#432;","Th&#7913; N&#259;m","Th&#7913; S&#225;u","Th&#7913; B&#7843;y");
		var cDate   = new Date();
		var cYear   = cDate.getFullYear();
		var cMon    = cDate.getMonth() + 1;
		var cDay    = cDate.getDay();
		var cHrs    = cDate.getHours();
		var cMins   = cDate.getMinutes();
		var cSecs   = cDate.getSeconds();
		var cAPM    = (cHrs >= 12) ? 'PM' : 'AM';
  		
		if (cHrs >= 13) cHrs -= 12;
		if (cHrs == 0 ) cHrs  = 12;
		if (cHrs  < 10) cHrs  = '0' + cHrs;
		if (cSecs < 10) cSecs = '0' + cSecs;
		if (cMins < 10) cMins = '0' + cMins;
		
		this.my_getbyid('clock').innerHTML = strDay[cDay] + ', ' + cDate.getDate() + '/' + cMon + '/' + cYear + ' ' + cHrs + ':' + cMins + ':' + cSecs + ' ' + cAPM;
	}
	
	//-------------------------------------
	// Document Handling
	//-------------------------------------
	
	// Location jump
	this.location_jump = function(url, full)
	{
		url = url.replace(/&amp;/g, '&');
		if (full) window.location.href = url;
		else window.location.href = base_url + url;
	};
	
	this.jump_page = function(url, id, pages, pp)
	{
		var pages = (pp > 0) ? Math.ceil(pages / pp) : 1;
		var st    = parseInt(this.my_getbyid(id).value);
		url      += '&st=' + (st - 1) * pp;
		
		if (isNaN(st) || st < 1 || st > pages)
		{
			alert('Vui long nhap so thu tu cua trang muon chuyen den');
			return;
		}
		
		this.location_jump(url,1);
	}
	
	// Confirm an action
	this.confirm_action = function(msg, url)
	{
		if (!msg)
		{
			msg = "Vui long xac nhan:\nBan muon thuc thi lenh nay?";
		}
		
		if (confirm(msg))
		{
			if (typeof url != 'undefined') this.location_jump(url,1);
			return true;
		}
		else
		{
			alert("Lenh da duoc huy!");
			return false;
		} 
	};
	
	// Create pop-up window
	this.popup = function(url, width, height, name)
	{
		return window.open(url, (typeof name != 'undefined' ? name : 'Popup'),
						   'statusbar=no,menubar=yes,toolbar=no,scrollbars=yes,resizable=yes'
						   + ( width != 'undefined' ? (',width=' + width) : '1024')
						   + ( height != 'undefined' ? (',height=' + height) : '800')
		);
	};
	
	// Return the ID from an ID title string
	this.get_id_from_text = function(id)
	{
		return id.replace(/.*(\-|_)(\S+)/, "$2");
	};
	
	// Return the name from an ID string
	this.get_name_from_text = function(id)
	{
		return id.replace(/(.*)(\-|_)(\S+)/, "$1");
	};
	
	// Get parent node
	this.get_parent_node = function(e, tag)
	{
		while ((e.nodeName != tag) && (e.nodeName != 'BODY') && (e.nodeName != null))
		{
			e = e.parentNode || e.parentElement;
		}
		
		return e;
 	};
	
	// Get element style width in percentage
	this.get_css_width_p = function(e)
	{
		return Math.round(e.offsetWidth / e.parentNode.offsetWidth * 100);
	};
	
	// Get element style value
	this.get_css_value = function(id, style)
	{
		var e = this.my_getbyid(id);
		
		if (e.currentStyle)
		{
			return e.currentStyle[style];
		}
		else if (window.getComputedStyle)
		{
			return document.defaultView.getComputedStyle(e,'').getPropertyValue(style);
		}
		
		return '';
	};
	
	// Get left object position
	this.get_obj_leftpos = function(obj)
	{
		var curleft = 0;
		
		if (obj.offsetParent)
		{
			while (obj.offsetParent)
			{
				curleft += obj.offsetLeft;
				obj      = obj.offsetParent;
			}
		}
		else if (obj.x)
		{
			curleft += obj.x;
		}
		
		if (is.ie)
		{
			curleft += 5;
		}
		
		return curleft;
	};
	
	// Get top object position
	this.get_obj_toppos = function(obj)
	{
		var curtop = 0;
		
		if (obj.offsetParent)
		{
			while (obj.offsetParent)
			{ 
				curtop += obj.offsetTop;
				obj     = obj.offsetParent;
			}
		}
		else if(obj.y)
		{
			curtop += obj.y;
		}
		
		return curtop;
	};
	
	// Get element by ID
	this.my_getbyid = function(id)
	{
		e = null;
		
		if (document.getElementById)
		{
			e = document.getElementById(id);
		}
		else if (document.all)
		{
			e = document.all[id];
		}
		else if (document.layers)
		{
			e = document.layers[id];
		}
		
		return e;
	};
	
	// Cookie handler
	this.my_getcookie = function(name)
	{
		cookie_name   = name + '=';
		cookie_length = document.cookie.length;
		cookie_begin  = 0;
		
		while (cookie_begin < cookie_length)
		{
			value_begin = cookie_begin + cookie_name.length;
			
			if (document.cookie.substring(cookie_begin, value_begin) == cookie_name)
			{
				var value_end = document.cookie.indexOf(';', value_begin);
				if (value_end == -1) value_end = cookie_length;
				
				return unescape(document.cookie.substring(value_begin, value_end));
			}
			
			cookie_begin = document.cookie.indexOf(' ', cookie_begin) + 1;
			if (cookie_begin == 0) break;
		}
		
		return null;
	};
	
	this.my_setcookie = function(name, value, sticky)
	{
		expires = '';
		domain  = '';
		path    = '/';
				
		if (sticky)
		{
			expires = '; expires=Wed, 1 Jan 2020 00:00:00 GMT';
		}
		
		if (cookie_domain != '')
		{
			domain = '; domain=' + cookie_domain;
		}
		
		if (cookie_path != '')
		{
			path = cookie_path;
		}
		
		document.cookie = cookie_id + name + '=' + escape(value) + '; path=' + path + expires + domain + ';';
	};
	
	this.my_delcookie = function(name)
	{
		document.cookie = cookie_id + name + '=' +  '; path=/' + '; expires=Thu, 1 Jan 1970 00:00:01 GMT';
	}
	
	// Array handler
	this.array_stacksize = function(thearray)
	{
		for (i = 0 ; i < thearray.length; i++)
		{
			if ((thearray[i] == '') || (thearray[i] == null) || (thearray == 'undefined'))
			{
				return i;
			}
		}
		
		return thearray.length;
	};
	
	this.array_pushstack = function(thearray, newval)
	{
		var arraysize = this.array_stacksize(thearray);
		thearray[arraysize] = newval;
	};
	
	this.array_popstack = function(thearray)
	{
		var arraysize = this.array_stacksize(thearray);
		var theval    = thearray[arraysize - 1];
		delete thearray[arraysize - 1];
		
		return theval;
	};
}

var CORE = new core_functions();