// Author: AnhDT6

//Global Function
function GetParam(name)
{
  var start=location.search.indexOf("?"+name+"=");
  if (start<0) start=location.search.indexOf("&"+name+"=");
  if (start<0) return '';
  start += name.length+2;
  var end=location.search.indexOf("&",start)-1;
  if (end<0) end=location.search.length;
  var result='';
  for(var i=start;i<=end;i++) {
    var c=location.search.charAt(i);
    result=result+(c=='+'?' ':c);
  }
  return unescape(result);
}


/*
Function
	getObject(id)
	getControlById(id)
	showControl(control)
	hideControl(control)
	setColor(control, color)
	
	setClassName(control, className)
	getClassName(control)
	addClass(control, className)
	removeClass(control, className)
	toggleClass(control, className)
	hasClass(control, className)
	replaceClass(control, oldClassName, newClassName)
	
	getMin(agruments)
	getmax(agruments)
	ExtractNumber(value)
	findPos(obj)
	setPosition(control, pos)
	getPosition(obj)
	getAbsolutePosition(obj)
	getAbsoluteLeft(obj)
	getAbsoluteTop(obj)
	
	onKeyPress(evt, act, c, a, s)
	
	String.trim()
	Date.format('dd/mm/yyyy')
*/


// Control & Object
function getObject(id)
{
    return defaultObjMgr.get(id);
}

function getControlById(id)
{
    return document.getElementById(id);
}

function showControl(control)
{
    if (!control) return;
    if (typeof control == 'string') control = getControlById(control);
    if (control) control.style.display = 'block';
}

function hideControl(control)
{
    if (!control) return;
    if (typeof control == 'string') control = getControlById(control);
    if (control) control.style.display = 'none';
}

// Class & Style

function setColor(control, color)
{
    if (!control) return;
    if (typeof control == 'string') control = getControlById(control);
    if (control) control.style.color = color;
}

// private
classReCache = {};

function setClassName(control, className)
{
    if (!control) return;
    if (typeof control == 'string') control = getControlById(control);

    control.className = className;
}

function getClassName(control)
{
    if (!control) return null;
    if (typeof control == 'string') control = getControlById(control);

    return control.className;
}

function addClass(control, className)
{
    if (!control) return;
    if (typeof control == 'string') control = getControlById(control);

    if(className instanceof Array)
    {
        for(var i = 0; i < className.length; i++) 
        {
    	    addClass(control, className[i]);
        }
    }
    else
    {
        if(className && !hasClass(control, className))
        {
	    control.className = control.className + " " + className;
        }
    }
}

function removeClass(control, className)
{
    if (!control) return;
    if (typeof control == 'string') control = getControlById(control);

    if(!className || !control.className)
    {
        return control;
    }
    if(className instanceof Array)
    {
        for(var i = 0, len = className.length; i < len; i++)
        {
    	    this.removeClass(className[i]);
        }
    }
    else
    {
        if(hasClass(control, className))
        {
            var re = classReCache[className];
            if (!re)
            {
               re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', "g");
               classReCache[className] = re;
            }
            control.className = control.className.replace(re, " ");
        }
    }
}

function toggleClass(control, className)
{
    if (!control) return;
    if (typeof control == 'string') control = getControlById(control);
    
    if(hasClass(control, className))
    {
        removeClass(control, className);
    }
    else
    {
        addClass(control, className);
    }
}

function hasClass(control, className)
{
    if (!control) return;
    if (typeof control == 'string') control = getControlById(control);

    return className && (' ' + control.className + ' ').indexOf(' ' + className + ' ') != -1;
}

function replaceClass(control, oldClassName, newClassName)
{
    if (!control) return;
    if (typeof control == 'string') control = getControlById(control);

    removeClass(control, oldClassName);
    addClass(control, newClassName);
}


// Position
function getMin()
{
    var r;
    for (var i = 0; i < arguments.length; i++)
    {
        if (!r || r > arguments[i]) r = arguments[i];
    }
    return r;
}

function getMax()
{
    var r;
    for (var i = 0; i < arguments.length; i++)
    {
        if (!r || r < arguments[i]) r = arguments[i];
    }
    return r;
}

function ExtractNumber(value)
{
    var n = parseInt(value);
	
    return n == null || isNaN(n) ? 0 : n;
}

function findPos(obj) 
{
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }
    return [curleft, curtop];
}

function setPosition(control, pos)
{
    if (typeof control == "string") control = getControlById(control);
    control.style.top = pos.top + 'px';
    control.style.left = pos.left + 'px';
}

function getPosition(obj)
{
	// Get an object position
	var o = obj;
	if (typeof obj == "string") o = getControlById(obj);
	
	return {top: o.offsetLeft, left: o.offsetTop, width: o.offsetWidth, height: o.offsetHeight};
}

function getAbsolutePosition(obj) 
{
	// Get an object position from the upper left viewport corner
	var o = obj;
	if (typeof obj == "string") o = getControlById(obj);
	
	var oWidth = o.offsetWidth      // Get width of the object
	var oHeight = o.offsetHeight    // Get height of the object
	var oLeft = o.offsetLeft        // Get left position from the parent object
	var oTop = o.offsetTop          // Get top position from the parent object
	while(o.offsetParent) {         // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oLeft += oParent.offsetLeft // Add parent left position
		oTop += oParent.offsetTop   // Add parent top position
		o = oParent
	}
	return {top: oTop, left: oLeft, width: oWidth, height: oHeight};
}

function getAbsoluteLeft(obj) 
{
	// Get an object left position from the upper left viewport corner
	var o = obj;
	if (typeof obj == "string") o = getControlById(obj);
	
	var oLeft = o.offsetLeft        // Get left position from the parent object
	while(o.offsetParent) {         // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oLeft += oParent.offsetLeft // Add parent left position
		o = oParent
	}
	return oLeft
}

function getAbsoluteTop(obj) 
{
	// Get an object top position from the upper left viewport corner
	var o = obj;
	if (typeof obj == "string") o = getControlById(obj);

	var oTop = o.offsetTop          // Get top position from the parent object
	while(o.offsetParent) {         // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oTop += oParent.offsetTop   // Add parent top position
		o = oParent
	}
	return oTop
}

function setPositionCenterByLeft(obj)
{
    if(obj)
    {
        var mvleft = document.documentElement.clientWidth;            
        mvleft = (mvleft - parseInt(obj.clientWidth))/2;  
        obj.style.left = (mvleft - 4) + 'px';
    }
}


//Mix
function GetParentControl(obj)
{
    if (typeof obj == 'string') obj = getControlById(obj);
    if (obj.parentNode)
    {
        return obj.parentNode;
    }
    else if (obj.parentElement)
    {
        return obj.parentElement;
    }
    
    return null;
}

function onKeyPress(evt, act, c, a, s)
{
    var e = (window.event) ? window.event : evt;
    var mykey, alt, ctrl, shift, str;
    if (!c) c = false;
    if (!a) a = false;
    if (!s) s = false;

    mykey = e.keyCode;
    ctrl = e.ctrlKey;
    alt = e.altKey;
    shift = e.shiftKey;

    if ((mykey == 13) && (ctrl == c) && (alt == a) && (shift == s)) //Enter
    {
        act();
        if (e.preventDefault) e.preventDefault() // For Presto and Gecko
        else e.returnValue = false; // For Trident
    }
}

/* Object extend */

Object.extend = function(target, source) {
  for (var property in source) {
    target[property] = source[property];
  }
  return target;
}

/* End Common */



/* String extend */
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

/* Format Date extend */
var dateFormat = function () {
	var	token        = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloZ]|"[^"]*"|'[^']*'/g,
		timezone     = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (value, length) {
			value = String(value);
			length = parseInt(length) || 2;
			while (value.length < length)
				value = "0" + value;
			return value;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask) {
		// Treat the first argument as a mask if it doesn't contain any numbers
		if (
			arguments.length == 1 &&
			(typeof date == "string" || date instanceof String) &&
			!/\d/.test(date)
		) {
			mask = date;
			date = undefined;
		}

		date = date ? new Date(date) : new Date();
		if (isNaN(date))
			throw "invalid date";

		var dF = dateFormat;
		mask   = String(dF.masks[mask] || mask || dF.masks["default"]);

		var	d = date.getDate(),
			D = date.getDay(),
			m = date.getMonth(),
			y = date.getFullYear(),
			H = date.getHours(),
			M = date.getMinutes(),
			s = date.getSeconds(),
			L = date.getMilliseconds(),
			o = date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4)
			};

		return mask.replace(token, function ($0) {
			return ($0 in flags) ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":       "ddd mmm d yyyy HH:MM:ss",
	shortDate:       "m/d/yy",
	mediumDate:      "mmm d, yyyy",
	longDate:        "mmmm d, yyyy",
	fullDate:        "dddd, mmmm d, yyyy",
	shortTime:       "h:MM TT",
	mediumTime:      "h:MM:ss TT",
	longTime:        "h:MM:ss TT Z",
	isoDate:         "yyyy-mm-dd",
	isoTime:         "HH:MM:ss",
	isoDateTime:     "yyyy-mm-dd'T'HH:MM:ss",
	isoFullDateTime: "yyyy-mm-dd'T'HH:MM:ss.lo"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask) {
	return dateFormat(this, mask);
}
