// Redirect to specified target url
function redirect(strPage) {
	window.location = strPage;
}

// Change edit status
function change() {
    blnChange = 'true';
}

// Delete confirmation
function deleteConfirm(strMessage, strTrueDest, strFalseDest) {
    var blnAnswer = window.confirm(strMessage);
    if (blnAnswer) {
        window.location = strTrueDest;
    } else {
        if (strFalseDest) {
            window.location = strFalseDest;
        }
    }
}

// Limit textarea character
function limitChar(strFieldID, strFieldIDCounter, intMaxChar) {
    var strFieldValue = document.getElementById(strFieldID).value;
    if (strFieldValue.length > intMaxChar) {
        document.getElementById(strFieldID).value = strFieldValue.substring(0, intMaxChar);
    }
    strFieldValue = document.getElementById(strFieldID).value;
    document.getElementById(strFieldIDCounter).value = intMaxChar - strFieldValue.length;
}

// Ajax Initialization
function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		alert('Status: Cound not create XmlHttpRequest Object.' + 'Consider upgrading your browser.');
	}
}

// Change Element on the fly
function changeElement(URL, divID) {
	var ajaxChangeElement = getXmlHttpRequestObject();
    if (ajaxChangeElement.readyState == 4 || ajaxChangeElement.readyState == 0) {
		ajaxChangeElement.open("POST", URL, true);
		ajaxChangeElement.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		ajaxChangeElement.onreadystatechange = function() {
			if (ajaxChangeElement.readyState == 4) {
			    var response = ajaxChangeElement.responseText;
			    document.getElementById(divID).innerHTML = response;
			}
		}
    }
    ajaxChangeElement.send(null);
}

// Submit HTTP get
function submitHTTP(URL) {
	var ajaxChangeElement = getXmlHttpRequestObject();
    if (ajaxChangeElement.readyState == 4 || ajaxChangeElement.readyState == 0) {
		ajaxChangeElement.open("POST", URL, true);
		ajaxChangeElement.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		ajaxChangeElement.onreadystatechange = function() {
			if (ajaxChangeElement.readyState == 4) {
			    var response = ajaxChangeElement.responseText;
			    return response;
			}
		}
    }
    ajaxChangeElement.send(null);
}

// Return amount of browser width
function getBrowserWidth() {
	return document.documentElement.clientWidth;
}

// Return amount of browser height
function getBrowserHeight() {
	return document.documentElement.clientHeight;
}

// Return amount of vertical scroll
function getScrollY() {
	var sy = 0;
	if (document.documentElement && document.documentElement.scrollTop)
	sy = document.documentElement.scrollTop;
	else if (document.body && document.body.scrollTop)
	sy = document.body.scrollTop;
	else if (window.pageYOffset)
	sy = window.pageYOffset;
	else if (window.scrollY)
	sy = window.scrollY;
	return sy;
}

// Return amount of horizontal scroll
function getScrollX() {
	var sx = 0;
	if (document.documentElement && document.documentElement.scrollLeft)
	sx = document.documentElement.scrollLeft;
	else if (document.body && document.body.scrollLeft)
	sx = document.body.scrollLeft;
	else if (window.pageXOffset)
	sx = window.pageXOffset;
	else if (window.scrollX)
	sx = window.scrollX;
	return sx;
}

// Add option list on select form element
function optionAdd(objOption, objOptionActual, optionValue, optionName, allowDuplicate) {
	if (optionValue != '' & optionName != '') {
		var addStatus = true;

		// Check duplicate entry
		if (allowDuplicate == 'no') {
		    for (i = 0; i < objOption.options.length; i++)	 {
		    	if (objOption.options[i].value == optionValue) {
		    		alert('Duplicate entry');
		    		addStatus = false;
		    	}
		    }
		}

		if (addStatus == true) {
	        if (objOption.options.length > 0) {
    	        objOption.options[objOption.options.length] = new Option(optionName, optionValue);
	        } else {
	        	objOption.options[0] = new Option(optionName, optionValue);
	        }

	        if (objOptionActual.value) {
	            objOptionActual.value = objOptionActual.value + "," + optionValue;
	        } else {
	            objOptionActual.value = optionValue;
	        }
		}
	} else {
	    alert('Error!');
	}
}

// Clear option list on select element
function optionClear(optionID, optionIDActual) {
	var optionObj = document.getElementById(optionID);
	optionObj.options.length = 0;
	document.getElementById(optionIDActual).value = "";
}

// Remove selected option on select element
function optionRemove(objOption, objOptionActual) {
	for (i = 0; i < objOption.options.length; i++) {
	    if (objOption.options[i].selected) {
	        //alert(objOption.options[i].value);
	        objOption.remove(i);
	    }
	    //alert("(" + objOption.options[i].value + ")")
	}

	var newvalue = "";
	//alert(objOptionAfter.options.length);
	for (i = 0; i < objOption.options.length; i++) {
	    newvalue = newvalue + objOption.options[i].value + ",";
	}
	objOptionActual.value = newvalue.substring(0, newvalue.length - 1);
	//alert(newvalue.substring(0, newvalue.length - 1));
}

// Add Table Row
function addDT(form, strTableID, url) {
	var ajaxRequestFieldDT = getXmlHttpRequestObject();
	var arrFields = new Array();
	var intSuffix = 1;

	// Get Latest DT field name
    for (var i = 0; i < document[form].elements.length; i++) {
        var strFieldPrefix = document[form].elements[i].name;
        if (strFieldPrefix.substring(0,5) == 'dtrow') {
        	intSuffix = parseInt(strFieldPrefix.substring(5, 7)) + 1;
        }
    }
    //alert(intSuffix);
    url = url + '&suffix=' + intSuffix;

    if (ajaxRequestFieldDT.readyState == 4 || ajaxRequestFieldDT.readyState == 0) {
		ajaxRequestFieldDT.open("POST", url, true);
		ajaxRequestFieldDT.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		ajaxRequestFieldDT.onreadystatechange = function() {
			if (ajaxRequestFieldDT.readyState == 4) {
			    var response = eval("(" + ajaxRequestFieldDT.responseText + ")");
			    for (i = 0; i < response.field.field.length; i++) {
			        arrFields[i] = response.field.field[i].field;
			    }
			    insTableRow(strTableID, arrFields);
			}
		}
    }
    ajaxRequestFieldDT.send(null);
}

// Delete Table Row
function delDT(strTableID, r) {
	var i = r.parentNode.parentNode.rowIndex;
	document.getElementById(strTableID).deleteRow(i);
}

// Add Row on a table
function insTableRow(strTableID, arrField) {
	var totRow = document.getElementById(strTableID).rows.length;
	var row = document.getElementById(strTableID).insertRow(totRow);

	for (i = 0; i < arrField.length; i++) {
  	    var cell = row.insertCell(i);
  	    cell.innerHTML = arrField[i];
	}
}

// Check all checkbox with pattern
function checkAll(strFormName, strPattern) {
    for (var i = 0; i < document[strFormName].elements.length; i++) {
        var strFieldPrefix = document[strFormName].elements[i].name;
        if (strFieldPrefix.substr(0, strPattern.length) == strPattern) {
            if (document[strFormName].elements[i].checked == false) {
                document[strFormName].elements[i].checked = true;
            } else {
                document[strFormName].elements[i].checked = false;
            }
        }
    }
}

function number_format(number) {
	number += '';
	x = number.split(',');
	x1 = x[0];
	x2 = x.length > 1 ? ',' + x[1] : ',00';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + '.' + '$2');
	}
	return x1 + x2;
}

// Perform validating on empty fields before submitting
function submit_form(strFormID, strFormField) {
    var blnCancelSubmit = false;
    if (strFormField != "") {
        arrFormField = strFormField.split(",");
        for (i = 0; i < arrFormField.length; i++) {

            if (document.getElementById(arrFormField[i]).type == "checkbox") {
                //alert(document.getElementById(arrFormField[i]).checked);
                if (document.getElementById(arrFormField[i]).checked == false) {
                    document.getElementById(arrFormField[i]).style.backgroundColor = '#FFC8FF';
                    blnCancelSubmit = true;
                } else {
                    document.getElementById(arrFormField[i]).style.backgroundColor = '';
                }
            } else {
            if (document.getElementById(arrFormField[i]).value == '') {
               document.getElementById(arrFormField[i]).style.backgroundColor = '#FFC8FF';
               blnCancelSubmit = true;
            } else {
               document.getElementById(arrFormField[i]).style.backgroundColor = '';
            }
            }
        }
    }
    if (blnCancelSubmit == true) {
        alert('Anda belum mengisi form dengan lengkap');
    } else {
        document.getElementById(strFormID).submit();
    }
}


// Update regular page upon change page
function update_page(strPage) {
    strPage+= "&fldPageNo=" + document.getElementById('fldPageNo').value;
    strPage+= "&fldKeyword=" + document.getElementById('fldKeyword').value;
    strPage+= "&fldSortCriteria=" + document.getElementById('fldSortCriteria').value;
    strPage+= "&fldSortType=" + document.getElementById('fldSortType').value;
    window.location = strPage;
}

// Get value from group of radio buttons. (id must be add suffix from 1 to ...)
function getRadioValue(form, radioName) {
    var intRadio = 0;
    for (i = 0; i < document[form].elements.length; i++) {
        if (document[form].elements[i].name == radioName) {
            intRadio++;
        }
    }

    for (i = 1; i <= intRadio; i++) {
        if (document.getElementById(radioName + i).checked) {
            return(document.getElementById(radioName + i).value);
        }
    }
}

// Find X Position of an object
function findPosX(obj) {
    var curleft = 0;
    if(obj.offsetParent)
    while(1) {
        curleft += obj.offsetLeft;
        if(!obj.offsetParent)
        break;
        obj = obj.offsetParent;
    }
    else if(obj.x) {
        curleft += obj.x;
    }
    return curleft;
}

// Find Y Position of an object
function findPosY(obj) {
    var curtop = 0;
    if(obj.offsetParent)
    while(1) {
        curtop += obj.offsetTop;
        if(!obj.offsetParent)
        break;
        obj = obj.offsetParent;
    }
    else if(obj.y) {
        curtop += obj.y;
    }
    return curtop;
}

function map_object(x, y, object) {
    object.style.position = 'absolute';
    object.style.top = y + 'px';
    object.style.left = x + 'px';
    //alert(x + '-' + y);
}

// Get window width
function getWindowWidth() {
    var width;
    if (document.layers) {
        width = window.innerWidth;
    }
    else {
        width = document.body.clientWidth;
    }
    return width;
}

// Get window height
function getWindowHeight() {
    if (document.layers) {
        return window.innerHeight;
    }
    else {
        return document.body.clientHeight;
    }
}

// Set value of an object
function set_value(objElement, value) {
    objElement.value = value;
}

function sort(strFieldName, strSortType) {
    var strSort;
    var strSearch;

    objSort   = document.getElementById('fldSort');
    strSort   = objSort.value;
    strSearch = strFieldName + " " + strSortType + ",";
    strSearch.toString();

    if (strSortType == "asc") strSort = strSort.replace(strFieldName + " desc" + ",", "");
    if (strSortType == "desc") strSort = strSort.replace(strFieldName + " asc" + ",", "");

    if (strSort.indexOf(strSearch) > -1) {
        strSort = strSort.replace(strSearch, "");
    } else {
        strSort = strSort + strFieldName + " " + strSortType + ",";
    }

    objSort.value = strSort;
}

// Submit a form
function go(objForm) {
    objForm.submit();
}

// This function formats numbers by adding commas
function numberFormat(nStr){
  nStr += '';
  x = nStr.split(',');
  x1 = x[0];
  x2 = x.length > 1 ? ',' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1))
    x1 = x1.replace(rgx, '$1' + '.' + '$2');
  return x1 + x2;
}

// This function removes non-numeric characters
function stripNonFormatedNumber( str ){
  str += '';
  var rgx = /^\d|\,|-$/;
  var out = '';
  for( var i = 0; i < str.length; i++ ){
    if( rgx.test( str.charAt(i) ) ){
      if( !( ( str.charAt(i) == ',' && out.indexOf( ',' ) != -1 ) ||
             ( str.charAt(i) == '-' && out.length != 0 ) ) ){
        out += str.charAt(i);
      }
    }
  }
  return out;
}

function stripNonNumeric( str ){
  str += '';
  var rgx = /^\d$/;
  var out = '';
  for( var i = 0; i < str.length; i++ ){
    if( rgx.test( str.charAt(i) ) ){
      //if( !( ( str.charAt(i) == '-' && out.length != 0 ) ) ){
        out += str.charAt(i);
      //}
    }
  }
  return out;
}

// Show hide element
function show_hide(elementId) {
    element = document.getElementById(elementId);
    if (element.style.visibility == "hidden") {
        element.style.visibility = "visible";
        element.style.position   = "relative";
    } else {
        element.style.visibility = "hidden";
        element.style.position   = "absolute";
    }
}

// ---------------------------------------------------------------------------
// --------------------------- Uncommon functions ----------------------------
// ---------------------------------------------------------------------------

// Reposition menu
function reposition_menu() {
    xpos = findPosX(document.getElementById('header'));
    xpos = xpos + 640;
    document.getElementById('menu_faq').style.left = xpos;
    document.getElementById('menu_faq').style.visibility = 'visible';
    xpos = xpos - 90;
    document.getElementById('menu_about_us').style.left = xpos;
    document.getElementById('menu_about_us').style.visibility = 'visible';
    xpos = xpos - 90;
    document.getElementById('menu_collections').style.left = xpos;
    document.getElementById('menu_collections').style.visibility = 'visible';
    xpos = xpos - 90;
    document.getElementById('menu_home').style.left = xpos;
    document.getElementById('menu_home').style.visibility = 'visible';
}

// Set Time out to close Main Menu
function hideMenu(menuID) {
	if (menuID == "Administrator") {
	    menuAdministrator    = "";
	    timeoutAdministrator = window.setTimeout("processHideMenu('" + menuID + "')", 2000);
	}
	if (menuID == "Reports") {
	    menuReports    = "";
	    timeoutReports = window.setTimeout("processHideMenu('" + menuID + "')", 2000);
	}
	if (menuID == "Setting") {
	    menuSetting    = "";
	    timeoutSetting = window.setTimeout("processHideMenu('" + menuID + "')", 2000);
	}
	if (menuID == "AddOns") {
	    menuSetting    = "";
	    timeoutSetting = window.setTimeout("processHideMenu('" + menuID + "')", 2000);
	}
}

// Hide Main Menu
function processHideMenu(menuID) {
	if (menuID == "Administrator"){
		if (menuAdministrator == "selected"){
			clearTimeout(timeoutAdministrator);
			return;
		} else {
			menuAdministrator = "";
		}
	}

	if (menuID == "Setting"){
		if (menuSetting == "selected"){
			clearTimeout(timeoutSetting);
			return;
		} else {
			menuSetting = "";
		}
	}

	if (menuID == "AddOns"){
		if (menuSetting == "selected"){
			clearTimeout(timeoutSetting);
			return;
		} else {
			menuSetting = "";
		}
	}

	document.getElementById("menu" + menuID).style.visibility = 'hidden';
}

// Display Lookup
function displayLookup(strLookupDestinationField, strLookupType, intWidth, intHeight) {
	var intMessageWidth  = parseInt(intWidth.replace("px", ""));
	var intMessageHeight = parseInt(intHeight.replace("px", ""));
	var floatLookup      = document.getElementById('floatLookup');

	floatLookup.style.width           = intWidth;
	floatLookup.style.height          = intHeight;
	floatLookup.style.border          = "2px dotted";
	floatLookup.style.visibility      = "visible";
	floatLookup.style.position        = "absolute";
	floatLookup.style.backgroundColor = "#E9E9E9";
	floatLookup.style.padding         = "5px";

	if (getBrowserWidth() < intMessageWidth) {
		floatLookup.style.left = "0px";
	} else {
	    floatLookup.style.left = ((getBrowserWidth() - intMessageWidth) / 2) + "px";
	}
	if (getBrowserHeight() < intMessageHeight) {
		floatLookup.style.top = getScrollY() + "px";
	} else {
	    floatLookup.style.top = (((getBrowserHeight() - intMessageHeight) / 2) + getScrollY()) + "px";
	}
	var URL = '?mod=lookup&fldLookupType=' + strLookupType + '&fldLookupDestinationField=' + strLookupDestinationField;
	updateLookup(URL);
}

// Update Lookup
function updateLookup(URL) {
	document.getElementById('floatLookup').innerHTML = "<center><img src='templates/images/loading.gif'> Please wait loading lookup list</center>";

	var ajaxRequestLookup = getXmlHttpRequestObject();

    if (ajaxRequestLookup.readyState == 4 || ajaxRequestLookup.readyState == 0) {
		ajaxRequestLookup.open("POST", URL, true);
		ajaxRequestLookup.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		ajaxRequestLookup.onreadystatechange = function() {
			if (ajaxRequestLookup.readyState == 4) {
			    document.getElementById('floatLookup').innerHTML = ajaxRequestLookup.responseText;
			}
		}
    }
    ajaxRequestLookup.send(null);
}

// Update Lookup by user interaction
function lookupGo(strFormName) {
	var URL = '?mod=lookup&';
	var URLSeparator = ''
    for (var i = 0; i < document[strFormName].elements.length; i++) {
        var strFieldPrefix = document[strFormName].elements[i].name;
        if (strFieldPrefix.substr(0, 3) == 'fld') {
            URL = URL + URLSeparator + document[strFormName].elements[i].name + '=' + document[strFormName].elements[i].value;
		    URLSeparator = "&";
        }
    }
    //alert(URL);
    updateLookup(URL);
}

// Hide Float Lookup
function fadeLookup() {
	document.getElementById('floatLookup').style.visibility = 'hidden';
}

// Set lookup value on destination field
function lookupSetValue(field, value) {
	var arrField = field.split(',');
	var arrValue = value.split(',');

	for(i = 0; i < arrField.length; i++) {
	    document.getElementById(arrField[i]).value = arrValue[i];
	}
	change();
	fadeLookup();
}

// Check user id
function checkUserID(strUserID, strURL) {
    changeElement('?mod=member&act=check&id=' + strUserID, 'divCheckUserIDMessage')
}

// Check char left
function checkCharLeft(intMinimumChar, strString, strDivID) {
    intCharLeft = intMinimumChar - strString.length;
    if (intCharLeft < 0) intCharLeft = 0;
    document.getElementById(strDivID).value = intCharLeft;
}

// Check if variable is int
function is_int(value){
    if((parseFloat(value) == parseInt(value)) && !isNaN(parseInt(value))){
        return true;
    } else {
        return false;
    }
}
