/********************************************************************
* Name: util.js
* Description: common function.
* Note: Must include prototype.js before use this file.
* Created: 	May 29th, 2007
* Updated:	May 29th, 2007
* Author: Vo huynh vinh
* Mobile: 0989-831-911
* Email: vohuynhvinh@yahoo.com
* Use: Call function direct.
********************************************************************/

/**
 * Description: Set cookie on user site
 * Name: setCookie.
 */
function setCookie(name, value, days, path, domain, secure)
{
	var expireDate = new Date();
	var expString = (typeof days!="undefined")? expireDate.setDate(expireDate.getDate()+parseInt(days)) : expireDate.setDate(expireDate.getDate()-5);
	var curCookie = name + "=" + escape(value) + ((expString) ? "; expires=" + expireDate.toGMTString() : "") + ((path) ? "; path=" + path : "") +((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
	document.cookie = curCookie;
}

/**
 * Description: Get cookie on user site
 * Name: getCookie.
 */
function getCookie(name)
{
	var re=new RegExp(name+"=[^;]+", "i"); //construct RE to search for target name/value pair
	if (document.cookie.match(re)) //if cookie found
		return unescape(document.cookie.match(re)[0].split("=")[1]); //return its value
	return null;
}

/**
 * Description: Delete cookie on user site
 * Name: deleteCookie.
 */
function deleteCookie(name, path, domain)
{
	setCookie(name, '', 0);	
}

/**
 * Description: Open popup window.
 * Name: openPopup.
 */
function openPopup(url, w, h, f) {
	if (!f)	
    window.open(url,"pop", 'toolbar=no,status=no,scrollbars=yes,resizable=no,menubar=no,location=no,direction=no,width='+w+',height='+h+',left=0, top=0,screenX=0,screenY=0');
	else
		window.open(url,"pop", 'toolbar=yes,status=yes,scrollbars=yes,resizable=yes,menubar=yes,location=yes,direction=yes,width='+w+',height='+h+',left=0, top=0,screenX=0,screenY=0');
}

/**
 * Description: Checking string is empty or not.
 * Name: isEmpty.
 */
function isEmpty(str) {
    if (str != "")
    	while (str.charAt(0) == " ")
            str = str.substr(1, str.length);

    return str == "" ? true : false;
}

/**
 * Description: Check ListBox is empty or not.
 * Name: checkedListBox.
 */
function checkedListBox(objId)
{
    var status = true;
    var value_;
	var errorid = 'err_' + $(objId).id;

    value_ = $(objId)[$(objId).selectedIndex].value;
	
	try {
		if (value_ == "-1") {		
			$(errorid).style.display = '';
	
			$(objId).focus();
			status = false;
		} else
			$(errorid).style.display = 'none';
	} catch (ex) {
		return false;
	}

    return status;
}

/**
 * Description: Checking a value of object is empty or not.
 * Name: checkedEmpty.
 */
function checkedEmpty(objId)
{
    var status = true;
    var str = $(objId).value;
	var errorid = 'err_' + $(objId).id;

	try {
		if (isEmpty(str)) {
			$(errorid).style.display = '';
	
			$(objId).focus();
			$(objId).select();
			status = false;
		} else
			$(errorid).style.display = 'none';
	} catch (ex) {
		return false;
	}

    return status;
}

/**
 * Description: Checking field number. Value of object only content digit number 0-9 with length optional.
 * Name: checkedNumber.
 */
function checkedNumber(objId)
{
    var pattern = /^[0-9]*\.?[0-9]*$/;
    var status = true;
	var errorid = 'err_' + $(objId).id;
	
	try {
		if (!pattern.test($(objId).value)) {    	
			$(errorid).style.display = '';
	
			$(objId).focus();
			$(objId).select();
			status = false;
		} else
			$(errorid).style.display = 'none';
	} catch (ex) {
		return false;
	}

    return status;
}

/**
 * Description: Checking distance number. Value of object  min<=obj.length<=max
 * Name: checkedDistanceNumber.
 */
function checkedDistanceNumber(objId, min, max) {
    var status = true;
	var errorid = 'err_' + $(objId).id;

	try {
		if ($(objId).value < min || $(objId).value > max) {        
			$(errorid).style.display = '';
	
			$(objId).focus();
			$(objId).select();
			status = false;
		} else
			$(errorid).style.display = 'none';
	} catch (ex) {
		return false;
	}
    return status;
}

/**
 * Description: Cheking email address.
 * Name: checkedEmail.
 */
function checkedEmail(objId) {
    var status = true;
    var goodEmail = $(objId).value.search(/^([-\w][-\.\w]*?)?[-\w]@([-!#\$%&*+\\\/=?\w^`{|}~]+\.)+[a-zA-Z]{2,6}$/gi);
	var errorid = 'err_' + $(objId).id;

	try {
		if (goodEmail==-1) {        
			$(errorid).style.display = '';
	
			$(objId).focus();
			$(objId).select();
			status = false;
		} else
			$(errorid).style.display = 'none';
	} catch (ex) {
		return false;
	}

    return status;
}

/**
 * Description: Checking length of object. Value's length of object is equal or great or less than of length value
 * Name: checkedLength.
 */
function checkedLength(objId, length, kind) {
    var mgs = '';
    var status = true;
	var errorid = 'err_' + $(objId).id;

    if (kind == 1 && $(objId).value.length != length) {// Chieu dai bang.
        status = false;
    }
    else if (kind == 2 && $(objId).value.length < length) {// Chieu dai hon.
        status = false;
    }
    else if (kind == 3 && $(objId).value.length > length) {// Chieu ngan hon.
        status = false;
    }

	try {
		if (status==false) {
			$(errorid).style.display = '';
	
			$(objId).focus();
			$(objId).select();        
		} else
			$(errorid).style.display = 'none';
	} catch (ex) {
		return false;
	}

    return status;
}

/**
 * Description: Compare two values of object is equal or not.
 * Name: compareValues.
 */
function compareValues(objId, objId_) {
	var errorid = 'err_' + $(objId_).id;

	try {
		if ($(objId).value != $(objId_).value) {        
			$(errorid).style.display = '';
	
			$(objId_).focus();
			$(objId_).select();
			return false;
		} else
			$(errorid).style.display = 'none';
	} catch (ex) {
		return false
	}

    return true;
}

/**
 * Description: !!!.
 * Name: resize.
 */
function resize(imgWidth, imgHeight) {
  var height  = screen.height;
  var width   = screen.width;
  var leftpos = width / 2 - imgWidth / 2;
  var toppos  = height / 2 - imgHeight / 2;
  
  self.resizeTo(imgWidth, imgHeight);
  self.moveTo(leftpos, toppos);
}

//self.focus();
//resize(650, 750);

/**
 * Description: Change image from user.
 * Name: changeImage.
 */
function changeImage(imgObjId, src_new, src_old)
{
    if (!isEmpty(src_new)) {
		$(imgObjId).src = src_new;
    } else if (isEmpty(src_new) && !isEmpty(src_old)) {
		$(imgObjId).src = src_old;
    }
}

/**
 * Description: Switch content of 2 object.
 * option==1: input and input.
 * option==2: input and div|span.
 * option==3: div|span and div|span.
 * Name: switchContent.
 */
function switchContent(objId_1, objId_2, option)
{
    var _tmp;

    if (option==1) {
        _tmp = $(objId_1).value;
        $(objId_1).value = $(objId_2).value;
        $(objId_2).value = _tmp;
    } else if (option==2) {
        _tmp = $(objId_1).value;
        $(objId_1).value = $(objId_2).innerHTML;
        $(objId_2).innerHTML = _tmp;
    } else if (option==3) {
        _tmp = $(objId_1).innerHTML;
        $(objId_1).innerHTML = $(objId_2).innerHTML;
        $(objId_1).innerHTML = _tmp;
    }
}

/**
 * Description: Switch source of 2 image object.
 * Name: switchImg.
 */
function switchImg(imgObjId_1, imgObjId_2)
{
    var src_tmp = $(imgObjId_1).src;

    $(imgObjId_1).src = $(imgObjId_2).src;
    $(imgObjId_2).src = src_tmp;
}

/**
 * Description: Add new row into you form
 * Name: addRow.
 */
function addRow(objId, contents)
{
    var len = contents.length;

    tabBody = $(objId);

    row = document.createElement('tr');
    for (i = 0; i < len; i++)
    {
    	cell = document.createElement('td');
    	cell.innerHTML=contents[i];
    	row.appendChild(cell);
    }
    tabBody.appendChild(row);
}

/**
 * Description: Delete row into you form
 * Name: deleteRow.
 */
function deleteRow(node)
{
    // Obtain a reference to the containing tr. Use a while loop
    // so the function can be called by passing any node contained by
    // the tr node.
    var tr = node.parentNode;

    while (tr.tagName.toLowerCase() != "tr")
		tr = tr.parentNode;

    // Remove the tr node and all children.
    tr.parentNode.removeChild(tr);
}

/****************************************************************************
 * Lib part 
 ****************************************************************************/
/**
 * PickList Begin
 */
<!--
// PickList script- By Sean Geraty (http://www.freewebs.com/sean_geraty/)
// Visit JavaScript Kit (http://www.javascriptkit.com) for this JavaScript and 100s more
// Please keep this notice intact

// Control flags for list selection and sort sequence
// Sequence is on option value (first 2 chars - can be stripped off in form processing)
// It is assumed that the select list is in sort sequence initially
var singleSelect = true;  // Allows an item to be selected once only
var sortSelect = true;  // Only effective if above flag set to true
var sortPick = true;  // Will order the picklist in sort sequence

// Adds a selected item into the picklist
function addIt(selectList_, pickList_) {
  var selectList = document.getElementById(selectList_);
  var selectIndex = selectList.selectedIndex;
  var selectOptions = selectList.options;
  var pickList = document.getElementById(pickList_);
  var pickOptions = pickList.options;
  var pickOLength = pickOptions.length;

  // An item must be selected
  while (selectIndex > -1) {
    pickOptions[pickOLength] = new Option(selectList[selectIndex].text);
    pickOptions[pickOLength].value = selectList[selectIndex].value;
    // If single selection, remove the item from the select list
    if (singleSelect) {
      selectOptions[selectIndex] = null;
    }
    if (sortPick) {
      var tempText;
      var tempValue;
      // Sort the pick list
      while (pickOLength > 0 && pickOptions[pickOLength].value < pickOptions[pickOLength-1].value) 				      {
        tempText = pickOptions[pickOLength-1].text;
        tempValue = pickOptions[pickOLength-1].value;
        pickOptions[pickOLength-1].text = pickOptions[pickOLength].text;
        pickOptions[pickOLength-1].value = pickOptions[pickOLength].value;
        pickOptions[pickOLength].text = tempText;
        pickOptions[pickOLength].value = tempValue;
        pickOLength = pickOLength - 1;
      }
    }
    selectIndex = selectList.selectedIndex;
    pickOLength = pickOptions.length;
  }
  try {
  	selectOptions[0].selected = true;
  }
  catch(ex)
  {
  	pickOptions[0].selected = true;
  }
}
//-->
/**
 * PickList End
 */

/**
 * Homepage-Bookmark Begin
 */
function homepage(page) {
	var _browserInfo = navigator.userAgent;

	if(_browserInfo.indexOf("Firefox") != -1)
	{
		alert('Ch\u1ee9c n\u0103ng "L\u00e0m trang ch\u1ee7" kh\u00f4ng h\u1ed7 tr\u1ee3 tr\u00ean tr\u00ecnh duy\u1ec7t Firefox');
	}
	else if(_browserInfo.indexOf("Opera") != -1)
	{
		alert('Ch\u1ee9c n\u0103ng "L\u00e0m trang ch\u1ee7" kh\u00f4ng h\u1ed7 tr\u1ee3 tr\u00ean tr\u00ecnh duy\u1ec7t Opera');
	} else { // MSIE
		document.body.style.behavior='url(#default#homepage)';
		document.body.setHomePage(page);
	}
}

function bookmark(page) { 
	var _browserInfo = navigator.userAgent;
	
	if(_browserInfo.indexOf("Firefox") != -1)
	{
		alert('\u0110\u1ec3 nh\u1edb trang, nh\u1ea5n t\u1ed5 h\u1ee3p ph\u00edm CTRL+D');
	}
	else if(_browserInfo.indexOf("Opera") != -1)
	{
		alert('\u0110\u1ec3 nh\u1edb trang, nh\u1ea5n t\u1ed5 h\u1ee3p ph\u00edm CTRL+T');
	} else { // MSIE
		window.external.AddFavorite(page, 'Website'); 		
	}
}
/**
 * Homepage-Bookmark End
 */

/**
 * DataTime Begin
 * www.wsabstract.com
 * Use: <div name="time" id="time" style="display:inline " align="left"></div> - <div name="day" id="day" style="display:inline " align="left"></div><script type="text/javascript">startclock();showday('vn');</script>
 */
var timerID = null;
var timerRunning = false;

function startclock(){
    stopclock();
    showtime();
}

function stopclock(){
    if(timerRunning)
        clearTimeout(timerID);
    timerRunning = false;
}

function showtime(){
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    var timeValue = "" + ((hours > 12) ? hours - 12 : hours);
    timeValue  += ((minutes < 10) ? ":0" : ":") + minutes;
    timeValue  += ((seconds < 10) ? ":0" : ":") + seconds;
    timeValue  += (hours >= 12) ? " PM " : " AM ";

	$('time').innerHTML=timeValue;
	
    timerID = setTimeout("showtime()",1000);
    timerRunning = true;
}

function showday(lg) {
	var mydate=new Date();
	var year=mydate.getFullYear();
	var day=mydate.getDay();
	var month=mydate.getMonth();
	var daym=mydate.getDate();
	if (daym<10) daym="0"+daym;
	
	if (lg == 'vn' || lg == 'VN') {
		var dayarray= 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&aacute;u","Th&#7913; b&#7843;y");
		//var montharray= new Array("Th&aacute;ng 1","Th&aacute;ng 2","Th&aacute;ng 3","Th&aacute;ng 4","Th&aacute;ng 5","Th&aacute;ng 6","Th&aacute;ng 7","Th&aacute;ng 8","Th&aacute;ng 9","Th&aacute;ng 10","Th&aacute;ng 11","Th&aacute;ng 12");
		var montharray= new Array("01","02","03","04","05","06","07","08","09","10","11","12");
		//var dateValue = "" + dayarray[day]+", Ng&agrave;y "+daym+"/"+montharray[month]+"/"+year;
		var dateValue = "" + dayarray[day]+", "+daym+"-"+montharray[month]+"-"+year;
	} else {
		var dayarray= new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
		//var montharray= new Array("January","February ","March","April","May","June","July","August","September","October","November","December");
		var montharray= new Array("01","02","03","04","05","06","07","08","09","10","11","12");
		//var dateValue = "" + dayarray[day]+", "+montharray[month]+" "+daym+ ", "+year;
		var dateValue = "" + dayarray[day]+", "+daym+"-"+montharray[month]+"-"+year;
	}

	$('day').innerHTML=dateValue;
}
/**
 * DataTime End
 */
