/*
* Name:    Nguyen Van Cuong
* Email:   vancuong3682@yahoo.com
* Website: http://www.quyluatvang.com
*/

/*
	Kiem tra mot chuoi co nam trong mot chuoi khac hay khong
	Return 0 : neu khong tim thay
	Return n : neu tim thay - n la so lan duoc tim thay
*/
function inStr(strSource, strFind)
{
	var s = strSource.length;
	var f = strFind.length;
	var c = 0;

	for (var i = 0; i < s; i++)
		if (strSource.substr(i, f) == strFind)
			c++;
	
	return c;
}

/*
	Thay doi textarea thanh editor
	object : la doi tuong textarea can thay doi thanh editor
	path : la duong dan den thu muc chua editor
	height : la chieu cao editor
	toolbar : la nhung chuc nang can hien thi
*/
function addEditor(strObject, strPath, intHeight, strToolBar)
{
	$(function() {
		$('#' + strObject).fck({
			path:    strPath,
			height:  intHeight,
			toolbar: strToolBar
		});		
	});
}

function addEditorFull(strObject, strPath, intWidth, intHeight, strToolBar)
{
	$(function() {
		$('#' + strObject).fck({
			path:    strPath,
			width:   intWidth,
			height:  intHeight,
			toolbar: strToolBar
		});		
	});
}

function setEditor(txt_name, txt_data)
{
	var oEditor = FCKeditorAPI.GetInstance(txt_name);
	oEditor.SetData(txt_data);
}

/*
	Kiem tra mot chuoi co phai dang email address hay khong
	Return true : la email
	Return false: chua phai la email
*/
function isEmail(strEmail)
{
	return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(strEmail);
}

/*
	Kiem tra mot chuoi co phai la so hay khong
	Return true : neu la so
	Return false : neu khong la so
*/
function isNum(strNum)
{
	return /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(strNum);
}

/*
	Kiem tra mot chuoi co phai la degit hay khong
	Return true : neu la degit
	Return false : neu khong la degit
*/
function isDigit(strDigit)
{
	return /^\d+$/.test(strDigit);
}

/*
	Kiem tra mot chuoi co phai la url hay khong
	Return true : neu la url
	Return false : neu khong la url
*/
function isUrl(strUrl)
{
	return /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(strUrl);
}

/*
	Kiem tra mot chuoi co phai la ngay hay khong
*/
function isDate(strDate)
{
	return !/Invalid|NaN/.test(new Date(strDate));
}

/*
	Cat khoang trong 2 dau cua chuoi
*/
function lTrim(str)
{
	return str.replace( /^\s*/, "" );
}

function rTrim(str)
{
	return str.replace( /\s*$/, "" );
}

function strTrim(str)
{
	if (str == '') return '';
	return  lTrim(rTrim(str));
}

function myValidator(ob, type, req, mes)
{
	var value = strTrim(ob.value);
	
	if (req == 'req' && (value == '' || parseFloat(value) == 0))
	{
		alert(mes);
		ob.focus();
		return false;
	}
	
	switch (type)
	{
		case 'num':
			if (!isNum(value) && value != '')
			{
				alert(mes);
				ob.focus();
				return false;
			}
			break;
		
		case 'str':
			if (value == '')
			{
				alert(mes);
				ob.focus();
				return false;
			}
			break;
			
		case 'email':
			if (!isEmail(value))
			{
				alert(mes);
				ob.focus();
				return false;
			}
			break;
	}
	
	return true;
}


/*
	Chuyen nam-thang-ngay ==> ngay-thang-nam
*/
function dmy(strDate)
{
	if (strDate == '0000-00-00')
		return '';
	if (!isDate(strDate) && (strDate == '' || strDate == ' '))
		return '';
	strDate = strDate.split('-');
	return strDate[2] + '-' + strDate[1] + '-' + strDate[0];
}

/*
	Chuyen nam-thang-ngay ==> ngay-thang-nam
*/
function ymd(strDate)
{
	if (strDate == '')
		return '0000-00-00';
	if (!isDate(strDate) && (strDate == '' || strDate == ' '))
		return '';	
	strDate = strDate.split('-');
	return strDate[2] + '-' + strDate[1] + '-' + strDate[0];
}

/*
	Lay left cua mot doi tuong
*/
function getElementLeft(Elem)
{
	var elem;
	if (document.getElementById)
		var elem = document.getElementById(Elem);
	else if (document.all)
		var elem = document.all[Elem];
	xPos   = elem.offsetLeft;
	tempEl = elem.offsetParent;
	while (tempEl != null)
	{
		xPos  += tempEl.offsetLeft;
		tempEl = tempEl.offsetParent;
	}
	return xPos;
}

/*
	Lay top cua mot doi tuong
*/
function getElementTop(Elem)
{
	if(document.getElementById)
		var elem = document.getElementById(Elem);
	else if (document.all)
		var elem = document.all[Elem];
	yPos   = elem.offsetTop;
	tempEl = elem.offsetParent;
	while (tempEl != null)
	{
		yPos  += tempEl.offsetTop;
		tempEl = tempEl.offsetParent;
	}
	return yPos;
}

/*
	Canh giua cho div
*/
function isCenter(obj)
{
	var left = 0;
	var top  = 0;
	var winWidth     = $(window).width();
	var winHeight    = $(window).height();
	var dialogHeight = $(obj).height();
	var dialogWidth  = $(obj).width();

	if ($.browser.msie)
	{
		left = document.body.scrollLeft || document.documentElement.scrollLeft;
		top  = document.body.scrollTop || document.documentElement.scrollTop;
	}
	else
	{
		left = window.pageXOffset;
		top  = window.pageYOffset;
	}

	var topOff    = top + winHeight/2 - dialogHeight/2 - 20;
	var	leftOff   = left + winWidth/2 - dialogWidth/2;
	var topFixed  = topOff - top - 20;
	var	leftFixed = leftOff - left;
	
	if ($.browser.msie && parseInt($.browser.version) < 7)
	{
		$("select").hide();
		$(obj + " select").show();
		$(obj).css({top: topOff < 0 ? 0 : topOff, left: leftOff < 0 ? 0 : leftOff});
	}
	else 
		$(obj).css({top: topFixed < 0 ? 0 : topFixed, left: leftFixed < 0 ? 0 : leftFixed});
	return $(obj);
}

function isCenterOf(ob, where , whereId)
{
	var top  = getElementTop(whereId) + where.height() / 2 - ob.height() / 2;
	var	left = getElementLeft(whereId) + where.width() / 2 - ob.width() / 2;
	ob.css({left:left,top:top});
	return ob;
}

function ajaxLoader(ob, win)
{
	var top  = getElementTop('main') - 7;
	var	left = win.width() - ob.width() - 15;
	ob.css({left:left,top:top});
	return ob;
}

/*
	Dat block div for processing or loading
*/
function setBlock(over, under , underId)
{
	over.css({left:getElementLeft(underId),top:getElementTop(underId),width:under.width(),height:under.height()});
	return over;
}

function setBlockAll(over, window)
{
	over.css({left:0,top:0,width:window.width(),height:window.height()});
	return over;
}

/*
	Kiem tra nam co phai la nam nhuan hay khong
*/
function isLeapYear(curYear)
{
    if(Math.round(curYear/4) == curYear/4)
    {
        if(Math.round(curYear/100) == curYear/100)
        {
            if(Math.round(curYear/400) == curYear/400)
                return true;
            else 
                return false;
        }
        else 
            return true;
    }
}

/*
	Thiet lap style cho text, textarea
*/
function selectInput(tag)
{
	var arrInput = document.getElementsByTagName(tag);
	
	for (var i = 0; i < arrInput.length; i++)
	{
		if( (tag == 'input' && arrInput[i].type == 'text') || tag == 'textarea')
		{
			arrInput[i].onfocus = function()
			{
				this.style.background    = '#EEEEEE';
				this.style.border        = '1px solid #7f9db9';
				this.style.paddingTop    = '2px';
				this.style.paddingBottom = '2px';
				this.style.paddingLeft   = '2px';
			}
			arrInput[i].onblur = function() {this.style.background = 'white';}
		}
	}
}

/*
	Check all checkbox
*/
function CheckAll(all)
{
	var ob  = document.frm_list.chb_list;
	for (var i = 0; i < ob.length; i++)
		if (ob[i].checked != all)
		{
			ob[i].checked = all;
			var tr        = document.getElementById('tr_' + i);
			tr.className  = tr.className == 'TR_White' ? 'TR_Marked' : 'TR_White';	
		}
}

/*
	Lay da lua chon tu checkbox
*/
function getChecked(ob)
{
	if (typeof(ob) == 'undefined') return '';
	
	var rValue = '';
	for (var i = 0; i < ob.length; i++)
		if (ob[i].checked && parseInt(ob[i].value, 10) > 0)
			rValue += ob[i].value + '_';
	return rValue.substring(0, rValue.length - 1);
}

/*
	Tao ra cac lua chon
*/
function setSelected(ob, data)
{
	for (var i = 0; i < ob.options.length; i++)
		if (inStr(data,'_' + ob.options[i].value + '_') > 0)
			ob.options[i].selected = true;
		else
			ob.options[i].selected = false;
}

/*
	Lay da lua chon tu select [option]
*/
function getSelected(ob)
{
	var rValue = '';
	for (var i = 0; i < ob.options.length; i++)
		if (ob.options[i].selected)
			rValue += ob.options[i].value + '_';
	return rValue.substring(0, rValue.length - 1);
}

/*
	Doi mau khi click chuot len tr va checked checkbox
*/
function rowSelected(ob, id)
{
	var obchb     = document.frm_list.chb_list[id];
	ob.className  = ob.className == 'TR_White' ? 'TR_Marked' : 'TR_White';
	obchb.checked = !document.frm_list.chb_list[id].checked;
	obchb.checked = ob.className == 'TR_Marked' && document.getElementById('chb_all').checked == false ? true : false;
	obchb.checked = ob.className == 'TR_White' ? false : true;
	var i = 0;
	var o = document.frm_list.chb_list;
	for (i = 0; i < o.length; i++)
		if (o[i].checked == false)
			break;
	if (i == o.length)
		document.getElementById('chb_all').checked = i == o.length ? true : false;
	o = document.frm_list.chb_list;
	for (i = 0; i < o.length; i++)
		if (o[i].checked == false)
		{
			document.getElementById('chb_all').checked = false;
			break;
		}
}

/*
	Hien thi tab theo so thu tu
*/
var curTab = 0;
function showTab(numTab, total)
{
	for (var i = 1; i <= total; i++)
		if (i == numTab)
		{
			$("#tab_" + i).addClass("_tab_row_selected");
			curTab = i;
			$("#tab_content_" + i).fadeIn('slow');
		}
		else
		{
			$("#tab_" + i).removeClass("_tab_row_selected");
			$("#tab_content_" + i).hide();
		}
}

/*
	Print
*/
var DialogPrint = 0;
function showDialogPrint(url)
{
	/*var wei = 225; Canh giữa - dialog box
	var hei = 450;
	var top = (screen.height - hei - 30) / 2;
	var lef = (screen.width - wei - 30) / 2 + 330;*/
	var wei = screen.width;
	var hei = screen.height;
	var top = 0;
	var lef = 0;
	
	if (DialogPrint)
		if (!DialogPrint.closed) 
			DialogPrint.close();
	
	DialogPrint = open(url, 'DialogPrint', 'toolbar = no, location = no, directories = no, status = no, menubar = no, scrollbars = yes, resizable = no, copyhistory = no, width = ' + wei + ',height = ' + hei + ', left = ' + lef + ', top = ' + top + ', screenX = 0, screenY = 0');
}

/*
	Size chart
*/
var DialogSizeChart = 0;
function showDialogSizeChart(url)
{
	var wei = 500;
	var hei = 300;
	var top = (screen.height - hei - 30) / 2;
	var lef = (screen.width - wei - 30) / 2 + 330;
	
	if (DialogSizeChart)
		if (!DialogSizeChart.closed) 
			DialogSizeChart.close();
	
	DialogSizeChart = open(url, 'DialogPrint', 'toolbar = no, location = no, directories = no, status = no, menubar = no, scrollbars = yes, resizable = no, copyhistory = no, width = ' + wei + ',height = ' + hei + ', left = ' + lef + ', top = ' + top + ', screenX = 0, screenY = 0');
}

/*
	Hien thi thong bao khi nguoi su dung khong co quyen tren chuc nang cua module
*/
function showDeny(type)
{
	var please  = "Thành thật xin lỗi ! Bạn không có quyền ";
	var arrDeny = {1 : "xem !", 3 : "thêm !", 5 : "sửa !", 7 : "xóa !", 9 : "gởi email !", 11 : "lập lịch !", 13 : "xem lịch !"};
	return please + arrDeny[type];
}

/*
	Them mot option moi
*/
function addOption(ob, val, txt)
{
	var obN   = document.createElement('option');
	obN.value = parseInt(val, 10);
	obN.text  = txt;
	try {ob.add(obN, null);} catch(ex) {ob.add(obN);}
	ob.value  = parseInt(val, 10);
}

/*
	Nhung function phuc vu cho viec cau hinh cot de in
*/
function addAll()
{
	var obS = document.getElementById("cbo_source");
	var obD = document.getElementById("cbo_destination");
	
	for (var i = 0; i < obS.options.length; i++)
	{
		var obN   = document.createElement('option');
		obN.text  = obS[i].text;
		obN.value = obS[i].value;
		try {obD.add(obN, null);} catch(ex) {obD.add(obN);}
	}
}

function addBefore(strV, strT)
{
	var obD = document.getElementById("cbo_destination");
	if (obD.selectedIndex >= 0) 
	{
		var obN   = document.createElement('option');
		obN.text  = strT;
		obN.value = strV;
		var obOld   = obD.options[obD.selectedIndex];
		try {obD.add(obN, obOld);} catch(ex) {obD.add(obN, obD.selectedIndex);}
	}
}

function addLast()
{
	var obS = document.getElementById("cbo_source");
	var obD = document.getElementById("cbo_destination");
	
	if (obS.selectedIndex < 0)
			return false;
	
	for (var i = 0; i < obS.options.length; i++)
	{
		if (obS[i].selected)
		{
			var obN   = document.createElement('option');
			obN.text  = obS[i].text;
			obN.value = obS[i].value;
			try {obD.add(obN, null);} catch(ex) {obD.add(obN);}
		}
	}
}

function removeSelected()
{
	var ob = document.getElementById("cbo_destination");
	for (var i = ob.length - 1; i >= 0; i--)
		if (ob.options[i].selected)
			ob.remove(i);
}

function upSelected()
{
	var ob = document.getElementById("cbo_destination");
	if (ob.selectedIndex > 0)
	{
		var obSel   = ob.selectedIndex;
		var obNew   = document.createElement('option');
		obNew.value = ob.options[ob.selectedIndex].value;
		obNew.text  = ob.options[ob.selectedIndex].text;
		var obOld   = ob.options[ob.selectedIndex - 1];
		try {ob.add(obNew, obOld);} catch(ex) {ob.add(obNew, ob.selectedIndex - 1);}
		ob.remove(obSel + 1);
		ob.selectedIndex = obSel - 1;
	}
}

function downSelected()
{
	var ob = document.getElementById("cbo_destination");
	if (ob.selectedIndex < ob.options.length - 1)
	{
		var obSel   = ob.selectedIndex;
		var obNew   = document.createElement('option');
		obNew.value = ob.options[ob.selectedIndex + 1].value;
		obNew.text  = ob.options[ob.selectedIndex + 1].text;
		var obOld   = ob.options[ob.selectedIndex];
		try {ob.add(obNew, obOld);} catch(ex) {ob.add(obNew, ob.selectedIndex);}
		ob.remove(obSel + 2);
		ob.selectedIndex = obSel + 1;
	}
}

/*
	Mau tim kiem tat ca
*/
function getSearchAll()
{
	return '_*_tatca_tat ca_tất cả_tấtcả_all_';
}

/*
	Show modal dialog
*/
function ModalDialog (boxSpec)
{
    var OVERLAY_ELEMENT_ID = "s--modalbox-overlay";
    var OVERLAY_Z_INDEX    = 20;
    var OVERLAY_OPACITY    = 0.2;
    var _boxSpec           = boxSpec;

    function getViewport()
	{
        return {
            x: window.pageXOffset || document.documentElement && document.documentElement.scrollLeft   || document.body.scrollLeft,
            y: window.pageYOffset || document.documentElement && document.documentElement.scrollTop    || document.body.scrollTop,
            w: window.innerWidth  || document.documentElement && document.documentElement.clientWidth  || document.body.clientWidth,
            h: window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body.clientHeight
        };
    };

    var styleStr    = "top:0; left:0; z-index:" + OVERLAY_Z_INDEX + "; display:none; background-color:#000; filter:alpha(opacity=" + (100 * OVERLAY_OPACITY) + ");";
    var vp          = getViewport();
    var overlayHTML = null;
    var sizeSpec    = "width:100%; height:100%;";
    
	if (jQuery.browser.msie && (jQuery.browser.version < 7))
	{
        sizeSpec    = "width:" + (vp.x + vp.w) + "px; height:" +  Math.max(vp.y + vp.h,jQuery(document.body).height()) + "px;";
        styleStr   += "filter: alpha(opacity=" + ( (100*OVERLAY_OPACITY)) + ");position: absolute;" + sizeSpec;
        overlayHTML = "";
    }
	else
	{
		styleStr   += "position:fixed; opacity:" + OVERLAY_OPACITY + ";" + sizeSpec;
        overlayHTML = "<div src='javascript:false' id='" + OVERLAY_ELEMENT_ID + "' style='" + styleStr + "'></div>";
    }
	
    jQuery("body").append(overlayHTML);
    var overlayElt = jQuery("#" + OVERLAY_ELEMENT_ID);
	
    if (jQuery.browser.msie && (jQuery.browser.version < 7))
	{
        var eltDoc = document.getElementById (OVERLAY_ELEMENT_ID).contentWindow.document;
        eltDoc.open();
        eltDoc.write("<html><body style='background-color:#000; filter:alpha(opacity=" + (100 * OVERLAY_OPACITY) + ");'></body></html>");
        eltDoc.close();
    }

    this.show = function()
	{
        var vp  = getViewport();
        overlayElt.css({display: "block"});
        var box = $(_boxSpec);
        box.css({display: "block", zIndex:OVERLAY_Z_INDEX+1, top:(vp.y + (vp.h - box.height())/2) + "px",  left: (vp.x + (vp.w - box.width())/2) + "px"});
    };

    this.hide = function()
	{
        overlayElt.css({display: "none"});
        $(_boxSpec).css({display: "none"});
    };
};

/*
	Set page title
*/
	function setPageTitle(title)
	{
		$("#module_title").html(title);
	}
/*
	Dump object
*/
	var MAX_DUMP_DEPTH = 20;
    function dumpObj(obj, name, indent, depth)
	{
        if (depth > MAX_DUMP_DEPTH)
            return indent + name + ": <Maximum Depth Reached>\n";
		if (typeof obj == "object")
		{
			var child = null;
			var output = indent + name + "\n";
			indent += "\t";
			for (var item in obj)
			{
				try {
						child = obj[item];
					} catch (e) {
						child = "<Unable to Evaluate>";
					}
					if (typeof child == "object")
					{
						output += dumpObj(child, item, indent, depth + 1);
					}
					else
					{
						output += indent + item + ": " + child + "\n";
					}
			}
			return output;
		}
		else
		{
			return obj;
		}
	}
/*
	Get site parameters
*/
	function get_parameter(name)
	{
		return $("#siteparameters option[value='" + name + "']").text();
	}

