/* $Id: functions.js,v 1.1.1.1 2005/08/27 09:21:58 Pham Van Doan Exp $ */

function displayTabTuVan(vId, valid) {
    for (i = 1; i <= 3; i++) {
        if (i == vId) {
            document.getElementById(valid + "_" + i).className = "focus-tab";
            document.getElementById(valid + i).style.display = "";
        }
        else {
            document.getElementById(valid + "_" + i).className = "other-tab";
            document.getElementById(valid + i).style.display = "none";
        }
    }
}

function gotoUrl(url){
	location.href=url;
}

function gotoUrlNewWindow(url){
	if(url != ''){
		window.open(url);
	}
	else{
		return false;
	}
}

function popVideo(theURL,winName,width, height){
	popUpWin = window.open('','',"'resizable=no,scrollbars=no, width=350 ,height=250");
	
	var h = height/2;
	var w = width/2;
	
	popUpWin.moveTo((screen.width/2-w),(screen.height/2-h));	
	
	if (!popUpWin.opener) popUpWin.opener = self;
	with (popUpWin.document) {
		write('<HTML><HEAD><TITLE>FLV Player</TITLE>');
		write('</head>');
		write('<BODY bgcolor="#FFFFFF" topmargin="0" leftmargin="0" marginheight="0" marginwidth="0">');
		write('<EMBED pluginspage=http://www.macromedia.com/go/getflashplayer src=flash/m-player.swf width=350 height=250 type=application/x-shockwave-flash allowfullscreen="true" flashvars="file='+theURL+'&image=">');
		write('</BODY></HTML>');
		close();
	}
}

function popUpImage(theURL,winName,width, height){
	
 	popUpWin = window.open('','',"'resizable=no,scrollbars=no, width="+width+" ,height="+height+"'");
 
	var h = height/2;
	var w = width/2;
	
	popUpWin.moveTo((screen.width/2-w),(screen.height/2-h));
 
 if (!popUpWin.opener) popUpWin.opener = self;
 with (popUpWin.document) {
 	write('<HTML><HEAD><TITLE>View Full Image</TITLE>');
 	write('</head>');
 	write('<BODY bgcolor="#FFFFFF" topmargin="0" leftmargin="0" marginheight="0" marginwidth="0">');
 	write('<IMG SRC="' + theURL + '" alt="Click on image to close window" onclick="window.close()">');
 	write('</BODY></HTML>');
	close();
  }
}
/*
* PopUp display content of record
*/
function popUpContent(url, width, height){
	if(!width) width = 200;
	if(!height) height = 200;
	popUpWin = window.open(url,'',"'resizable=yes,scrollbars=yes, status=yes, width="+width+" ,height="+height+"'");
	var h = height/2;
	var w = width/2;
	popUpWin.moveTo((screen.width/2-w),(screen.height/2-h));
	popUpWin.focus();
	if (!popUpWin.opener) popUpWin.opener = self;
}
/**
 * Displays an confirmation box beforme to submit a "DROP/DELETE/ALTER" query.
 * This function is called while clicking links
 *
 * @param   object   the link
 * @param   object   the sql query to submit
 *
 * @return  boolean  whether to run the query or not
 */
function confirmLink(theLink, theSqlQuery)
{
    // Confirmation is not required in the configuration file
    if (confirmMsg == '') {
        return true;
    }

    var is_confirmed = confirm(confirmMsg + ' :\n' + theSqlQuery);
    if (is_confirmed) {
        theLink.href += '&is_js_confirmed=1';
    }

    return is_confirmed;
} // end of the 'confirmLink()' function


/**
 * Displays an error message if a "DROP DATABASE" statement is submitted
 * while it isn't allowed, else confirms a "DROP/DELETE/ALTER" query before
 * sumitting it if required.
 * This function is called by the 'checkSqlQuery()' js function.
 *
 * @param   object   the form
 * @param   object   the sql query textarea
 *
 * @return  boolean  whether to run the query or not
 *
 * @see     checkSqlQuery()
 */
function confirmQuery(theForm1, sqlQuery1)
{
    // Confirmation is not required in the configuration file
    if (confirmMsg == '') {
        return true;
    }

    // The replace function (js1.2) isn't supported
    else if (typeof(sqlQuery1.value.replace) == 'undefined') {
        return true;
    }

    // js1.2+ -> validation with regular expressions
    else {
        // "DROP DATABASE" statement isn't allowed
        if (noDropDbMsg != '') {
            var drop_re = new RegExp('DROP\\s+(IF EXISTS\\s+)?DATABASE\\s', 'i');
            if (drop_re.test(sqlQuery1.value)) {
                alert(noDropDbMsg);
                theForm1.reset();
                sqlQuery1.focus();
                return false;
            } // end if
        } // end if

        // Confirms a "DROP/DELETE/ALTER" statement
        var do_confirm_re_0 = new RegExp('DROP\\s+(IF EXISTS\\s+)?(TABLE|DATABASE)\\s', 'i');
        var do_confirm_re_1 = new RegExp('ALTER\\s+TABLE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+DROP\\s', 'i');
        var do_confirm_re_2 = new RegExp('DELETE\\s+FROM\\s', 'i');
        if (do_confirm_re_0.test(sqlQuery1.value)
            || do_confirm_re_1.test(sqlQuery1.value)
            || do_confirm_re_2.test(sqlQuery1.value)) {
            var message      = (sqlQuery1.value.length > 100)
                             ? sqlQuery1.value.substr(0, 100) + '\n    ...'
                             : sqlQuery1.value;
            var is_confirmed = confirm(confirmMsg + ' :\n' + message);
            // drop/delete/alter statement is confirmed -> update the
            // "is_js_confirmed" form field so the confirm test won't be
            // run on the server side and allows to submit the form
            if (is_confirmed) {
                theForm1.elements['is_js_confirmed'].value = 1;
                return true;
            }
            // "DROP/DELETE/ALTER" statement is rejected -> do not submit
            // the form
            else {
                window.focus();
                sqlQuery1.focus();
                return false;
            } // end if (handle confirm box result)
        } // end if (display confirm box)
    } // end confirmation stuff

    return true;
} // end of the 'confirmQuery()' function


/**
 * Displays an error message if the user submitted the sql query form with no
 * sql query, else checks for "DROP/DELETE/ALTER" statements
 *
 * @param   object   the form
 *
 * @return  boolean  always false
 *
 * @see     confirmQuery()
 */
function checkSqlQuery(theForm)
{
    var sqlQuery = theForm.elements['sql_query'];
    var isEmpty  = 1;

    // The replace function (js1.2) isn't supported -> basic tests
    if (typeof(sqlQuery.value.replace) == 'undefined') {
        isEmpty      = (sqlQuery.value == '') ? 1 : 0;
        if (isEmpty && typeof(theForm.elements['sql_file']) != 'undefined') {
            isEmpty  = (theForm.elements['sql_file'].value == '') ? 1 : 0;
        }
        if (isEmpty && typeof(theForm.elements['id_bookmark']) != 'undefined') {
            isEmpty  = (theForm.elements['id_bookmark'].value == null || theForm.elements['id_bookmark'].value == '');
        }
    }
    // js1.2+ -> validation with regular expressions
    else {
        var space_re = new RegExp('\\s+');
        isEmpty      = (sqlQuery.value.replace(space_re, '') == '') ? 1 : 0;
        // Checks for "DROP/DELETE/ALTER" statements
        if (!isEmpty && !confirmQuery(theForm, sqlQuery)) {
            return false;
        }
        if (isEmpty && typeof(theForm.elements['sql_file']) != 'undefined') {
            isEmpty  = (theForm.elements['sql_file'].value.replace(space_re, '') == '') ? 1 : 0;
        }
        if (isEmpty && typeof(theForm.elements['id_bookmark']) != 'undefined') {
            isEmpty  = (theForm.elements['id_bookmark'].value == null || theForm.elements['id_bookmark'].value == '');
            isEmpty  = (theForm.elements['id_bookmark'].selectedIndex == 0);
        }
        if (isEmpty) {
            theForm.reset();
        }
    }

    if (isEmpty) {
        sqlQuery.select();
        alert(errorMsg0);
        sqlQuery.focus();
        return false;
    }

    return true;
} // end of the 'checkSqlQuery()' function


/**
 * Displays an error message if an element of a form hasn't been completed and
 * should be
 *
 * @param   object   the form
 * @param   string   the name of the form field to put the focus on
 *
 * @return  boolean  whether the form field is empty or not
 */
function emptyFormElements(theForm, theFieldName)
{
    var isEmpty  = 1;
    var theField = theForm.elements[theFieldName];
    // Whether the replace function (js1.2) is supported or not
    var isRegExp = (typeof(theField.value.replace) != 'undefined');

    if (!isRegExp) {
        isEmpty      = (theField.value == '') ? 1 : 0;
    } else {
        var space_re = new RegExp('\\s+');
        isEmpty      = (theField.value.replace(space_re, '') == '') ? 1 : 0;
    }
    if (isEmpty) {
        theForm.reset();
        theField.select();
        alert(errorMsg0);
        theField.focus();
        return false;
    }

    return true;
} // end of the 'emptyFormElements()' function


/**
 * Ensures a value submitted in a form is numeric and is in a range
 *
 * @param   object   the form
 * @param   string   the name of the form field to check
 * @param   integer  the minimum authorized value
 * @param   integer  the maximum authorized value
 *
 * @return  boolean  whether a valid number has been submitted or not
 */
function checkFormElementInRange(theForm, theFieldName, min, max)
{
    var theField         = theForm.elements[theFieldName];
    var val              = parseInt(theField.value);

    if (typeof(min) == 'undefined') {
        min = 0;
    }
    if (typeof(max) == 'undefined') {
        max = Number.MAX_VALUE;
    }

    // It's not a number
    if (isNaN(val)) {
        theField.select();
        alert(errorMsg1);
        theField.focus();
        return false;
    }
    // It's a number but it is not between min and max
    else if (val < min || val > max) {
        theField.select();
        alert(val + errorMsg2);
        theField.focus();
        return false;
    }
    // It's a valid number
    else {
        theField.value = val;
    }

    return true;
} // end of the 'checkFormElementInRange()' function


/**
 * Ensures the choice between 'transmit', 'zipped', 'gzipped' and 'bzipped'
 * checkboxes is consistant
 *
 * @param   object   the form
 * @param   string   a code for the action that causes this function to be run
 *
 * @return  boolean  always true
 */
function checkTransmitDump(theForm, theAction)
{
    var formElts = theForm.elements;

    // 'zipped' option has been checked
    if (theAction == 'zip' && formElts['zip'].checked) {
        if (!formElts['asfile'].checked) {
            theForm.elements['asfile'].checked = true;
        }
        if (typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked) {
            theForm.elements['gzip'].checked = false;
        }
        if (typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked) {
            theForm.elements['bzip'].checked = false;
        }
    }
    // 'gzipped' option has been checked
    else if (theAction == 'gzip' && formElts['gzip'].checked) {
        if (!formElts['asfile'].checked) {
            theForm.elements['asfile'].checked = true;
        }
        if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
            theForm.elements['zip'].checked = false;
        }
        if (typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked) {
            theForm.elements['bzip'].checked = false;
        }
    }
    // 'bzipped' option has been checked
    else if (theAction == 'bzip' && formElts['bzip'].checked) {
        if (!formElts['asfile'].checked) {
            theForm.elements['asfile'].checked = true;
        }
        if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
            theForm.elements['zip'].checked = false;
        }
        if (typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked) {
            theForm.elements['gzip'].checked = false;
        }
    }
    // 'transmit' option has been unchecked
    else if (theAction == 'transmit' && !formElts['asfile'].checked) {
        if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
            theForm.elements['zip'].checked = false;
        }
        if ((typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked)) {
            theForm.elements['gzip'].checked = false;
        }
        if ((typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked)) {
            theForm.elements['bzip'].checked = false;
        }
    }

    return true;
} // end of the 'checkTransmitDump()' function


/**
 * Sets/unsets the pointer and marker in browse mode
 *
 * @param   object   the table row
 * @param   string   the action calling this script (over, out or click)
 * @param   string   the default background color
 * @param   string   the color to use for mouseover
 * @param   string   the color to use for marking a row
 *
 * @return  boolean  whether pointer is set or not
 */
function setPointer(theRow, theAction, theDefaultColor, thePointerColor, theMarkColor)
{
    var theCells = null;

    // 1. Pointer and mark feature are disabled or the browser can't get the
    //    row -> exits
    if ((thePointerColor == '' && theMarkColor == '')
        || typeof(theRow.style) == 'undefined') {
        return false;
    }

    // 2. Gets the current row and exits if the browser can't get it
    if (typeof(document.getElementsByTagName) != 'undefined') {
        theCells = theRow.getElementsByTagName('td');
    }
    else if (typeof(theRow.cells) != 'undefined') {
        theCells = theRow.cells;
    }
    else {
        return false;
    }

    // 3. Gets the current color...
    var rowCellsCnt  = theCells.length;
    var domDetect    = null;
    var currentColor = null;
    var newColor     = null;
    // 3.1 ... with DOM compatible browsers except Opera that does not return
    //         valid values with "getAttribute"
    if (typeof(window.opera) == 'undefined'
        && typeof(theCells[0].getAttribute) != 'undefined') {
        currentColor = theCells[0].getAttribute('bgcolor');
        domDetect    = true;
    }
    // 3.2 ... with other browsers
    else {
        currentColor = theCells[0].style.backgroundColor;
        domDetect    = false;
    } // end 3

    // 4. Defines the new color
    // 4.1 Current color is the default one
    if (currentColor == ''
        || currentColor.toLowerCase() == theDefaultColor.toLowerCase()) {
        if (theAction == 'over' && thePointerColor != '') {
            newColor = thePointerColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor = theMarkColor;
        }
    }
    // 4.1.2 Current color is the pointer one
    else if (currentColor.toLowerCase() == thePointerColor.toLowerCase()) {
        if (theAction == 'out') {
            newColor = theDefaultColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor = theMarkColor;
        }
    }
    // 4.1.3 Current color is the marker one
    else if (currentColor.toLowerCase() == theMarkColor.toLowerCase()) {
        if (theAction == 'click') {
            newColor = (thePointerColor != '')
                     ? thePointerColor
                     : theDefaultColor;
        }
    } // end 4

    // 5. Sets the new color...
    if (newColor) {
        var c = null;
        // 5.1 ... with DOM compatible browsers except Opera
        if (domDetect) {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].setAttribute('bgcolor', newColor, 0);
            } // end for
        }
        // 5.2 ... with other browsers
        else {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].style.backgroundColor = newColor;
            }
        }
    } // end 5

    return true;
} // end of the 'setPointer()' function

/*
* PopUp display content of record
*/
function popUpOpenFile(url, width, height){
	/*if(!width) width = screen.width - 200;
	if(!height) height = screen.height - 300;
	var h = screen.width - width - 150;
	var w = screen.height - height - 200;
		
	new popUp(w, h, width, height, "Div", '<iframe name="preview_test_frm" src="'+url+'" title="" width="'+(width - 23)+'" height="'+(height - 40)+'"></iframe>', "white", "black", "bold 10pt sans-serif", "Title Bar", "navy", "white", "#dddddd", "gray", "black", true, true, false, true, false);*/
	var width = screen.width;
	var height = screen.height;
	popUpWin = window.open(url,'',"'resizable=yes,scrollbars=yes, width="+width+" ,height="+height+"'");
	var h = height/2;
	var w = width/2;
	popUpWin.moveTo((screen.width/2-w),(screen.height/2-h));
	popUpWin.focus();
	if (!popUpWin.opener) popUpWin.opener = self;
}

/**
 * Checks/unchecks all tables
 *
 * @param   string   the form name
 * @param   boolean  whether to check or to uncheck the element
 *
 * @return  boolean  always true
 */
function setCheckboxes(the_form, do_check)
{
    var elts      = document.forms[the_form].elements['selected_tbl[]'];
    var elts_cnt  = (typeof(elts.length) != 'undefined')
                  ? elts.length
                  : 0;

    if (elts_cnt) {
        for (var i = 0; i < elts_cnt; i++) {
            elts[i].checked = do_check;
        } // end for
    } else {
        elts.checked        = do_check;
    } // end if... else

    return true;
} // end of the 'setCheckboxes()' function


/**
  * Checks/unchecks all options of a <select> element
  *
  * @param   string   the form name
  * @param   string   the element name
  * @param   boolean  whether to check or to uncheck the element
  *
  * @return  boolean  always true
  */
function setSelectOptions(the_form, the_select, do_check)
{
    var selectObject = document.forms[the_form].elements[the_select];
    var selectCount  = selectObject.length;

    for (var i = 0; i < selectCount; i++) {
        selectObject.options[i].selected = do_check;
    } // end for

    return true;
} // end of the 'setSelectOptions()' function


function confirmSubmit(msg)
{
	var agree=confirm(msg);
	if (agree)
		document.theForm.submit();
	else
		return false ;
}

function confirmDeleteForm(url, msg)
{
	var agree=confirm(msg);
	if (agree)
		location.href=url;
	else
		return false ;
}


function set_focus() {
	if (document.DetailView.user_name.value != '') {
		document.DetailView.user_password.focus();
		document.DetailView.user_password.select();
	}
	else document.DetailView.user_name.focus();
}

function toggleDisplay(id){

	if(this.document.getElementById( id).style.display=='none'){
		this.document.getElementById( id).style.display='inline'
		if(this.document.getElementById(id+"link") != undefined){
			this.document.getElementById(id+"link").style.display='none';
		}
	document['options'].src = 'include/images/options_up.gif';		
	}else{
		this.document.getElementById(  id).style.display='none'
		if(this.document.getElementById(id+"link") != undefined){
			this.document.getElementById(id+"link").style.display='inline';
		}
	document['options'].src = 'include/images/options.gif';	
	}
}

function getRef(id)
{
 return document.getElementById(id);
}

function getSty(id)
{
 return getRef(id).style;
}

if (!document.documentElement) alert('Sorry, this page requires a DOM-compatible browser ' +
 'like IE5+ or NS6+.\n\nPlease update your browser accordingly.');

function showTab(tabClass, name)
{
 if (window[tabClass]) getSty(window[tabClass]).display = 'none';
 getSty(name).display = 'block';
 window[tabClass] = name;
}

function setTopTab(name)
{
 if (window.topLink) getRef(window.topLink).className = 'topTabLink';
 getRef(name+'-link').className = 'topTabLink-sel';
 showTab('topTab', name+'-form');
 window.topLink = name+'-link';
}

/*window.onload = function()
{
 setTopTab('frmListTab');
}*/

function gotoPageUrl(url){
	if(url == ''){
		alert('URL is fail!');
	}
	else{
		location.href=url;
	}
}



function sendCompaniesTranFer(){	
	xajax_sendComment(xajax.getFormValues("frmCompaniesTranFer"));
}

function sendPSTranFer(){
	xajax_sendComment(xajax.getFormValues("frmPSTranFer"));
}	

function sendEFeedBack(){		
	xajax_sendComment(xajax.getFormValues("sendEmailFeedBack"));
}


function sendCommand(theForm){		
	xajax_sendComment(xajax.getFormValues(theForm));
}

function showFeedBack(val){		
	document.frmContact.submitForm.value = val;
	xajax_sendComment(xajax.getFormValues("frmContact"));
}
	
function showFormTranfer(val){		
	//document.frmContact.submitForm.value = val;
	xajax_sendComment(xajax.getFormValues("frmTranfer"));
}

function shopCartCalculator(){		
	xajax_sendComment(xajax.getFormValues("frmShoppingCart"));
}

function shopCartSend(){
	var agree=confirm('Xin Quý khách hãy kiểm tra lại các thông tin đặt hàng, chúng tôi sẽ liên hệ với Quý khách qua các thông tin mà Quý khách cung cấp. Nếu các thông tin chính xác Quý khách nhấn OK, ngược lại nhấn Cancel để sửa lại thông tin.\n\nXin Quý khách lưu ý các hình thức thanh toán ở bên dưới để có thêm thông tin.');
	if (agree){	
		xajax_sendComment(xajax.getFormValues("frmShoppingCartCustomers"));
	}
	else{
		return false;
	}
}

	function FloatTopDiv(divid,type,eY){
		if (typeof(eY)=='undefined') {eY=0};
		var startX, startY;
		if (type==1) {startX = document.body.clientWidth - 115;} else {startX = 5;}
		if (type==2) {startY = document.body.clientHeight;} else {startY = 0;}
		if (document.body.clientWidth < 980) {startX = -115};
	
		window.stayFloat=function(ftlObj,type,eY)
		{
			var startX, startY;
			var ns = (navigator.appName.indexOf("Netscape") != -1);
			if (type==1) {startX = document.body.clientWidth - 115;} else {startX = 5;}
			//if (document.body.clientWidth < 980) {startX = -115};
			if (document.body.clientWidth < 980) {
				ftlObj.style.display = 'none';
			} 
			else {
				ftlObj.style.display = '';
				
				if (document.documentElement && document.documentElement.scrollTop)
					var pY = ns ? pageYOffset : document.documentElement.scrollTop;
				else if (document.body)
					var pY = ns ? pageYOffset : document.body.scrollTop;
	
				if (type==2){
					startY = document.body.clientHeight-183;
				}
				else{
					if (document.body.scrollTop > 71){startY = 3} else {startY = 71};
				}
				
				startY = document.body.clientHeight - 40;
				
				ftlObj.y += (pY + startY - ftlObj.y)/8;
				ftlObj.style.left=startX;
				ftlObj.style.top= ftlObj.y + eY;
			}
			setTimeout(function(){stayFloat(ftlObj,type,eY)}, 15);
		}
	
		var ftlObj = document.getElementById?document.getElementById(divid):document.all?d.all[divid]:document.layers[divid];
		if(!ftlObj) return;
		ftlObj.x = startX;
		ftlObj.y = startY;
		stayFloat(ftlObj,type,eY);
	}	
	FloatTopDiv('Loading',2,0);