//
// Created on March 10, 2004
// 
// Author: Sirbu V. Dorin
// E-mail: dorin.sirbu@ist.ro
//
// ? INDUSTRIAL SOFTWARE TECHNOLOGIES 2004. All rights reserved. 
//

// Retuns the current user browser language. 
function utilGetUserLanguage()
{
	var lang; 
	if (navigator.appName == 'Netscape')
		lang = navigator.language;
	else
		lang = navigator.browserLanguage;
	return lang.substring(0, 2);	
}

function utilRandomValue(low, high) 
{
    return Math.floor(Math.random() * (1 + high - low) + low);
}
  
function utilRandomValue1(high) 
{
	return 1 + Math.floor(Math.random() * high);
}

function trim(str) 
{
	// Removes leading and trailing spaces from the passed string. Also removes
	// consecutive spaces and replaces it with one space. If something besides
	// a string is passed in (null, custom object, etc.) then return the input.
	var whitespace = ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000';
	for (var i = 0; i < str.length; i++) {
		if (whitespace.indexOf(str.charAt(i)) === -1) {
			str = str.substring(i);
			break;
		}
	}
	for (i = str.length - 1; i >= 0; i--) {
		if (whitespace.indexOf(str.charAt(i)) === -1) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}	

function utilGetFieldValue(field)
{
   switch(field.type)
   {
      case "text" :
      case "textarea" :
      case "password" :
      case "hidden" :
         return field.value;

      case "select-one" :
         var i = field.selectedIndex;
         if (i == -1)   return "";
         // else   return (field.options[i].value == "") ? field.options[i].text : field.options[i].value;
         else   return field.options[i].value;

      case "select-multiple" :
         var allChecked = new Array();
         for(i = 0; i < field.options.length; i++)
            if(field.options[i].selected)
               allChecked[allChecked.length] = (field.options[i].value == "") ? field.options[i].text : field.options[i].value;
         return allChecked;

      case "button" :
      case "reset" :
      case "submit" :
         return "";

      case "radio" :
      case "checkbox" :
         if (field.checked) { return field.value; } else { return ""; }
      default :
         if(field[0].type == "radio")
         {
            for (i = 0; i < field.length; i++)
               if (field[i].checked)
                  return field[i].value;

            return "";
         }
         else if(field[0].type == "checkbox")
         {
            var allChecked = new Array();
            for(i = 0; i < field.length; i++)
               if(field[i].checked)
                  allChecked[allChecked.length] = field[i].value;

            return allChecked;
         }
         else
            var str = "";
            for (x in field) { str += x + "\n"; }
            alert("I couldn't figure out what type this field is...\n\n" + field.name + ": ???\n\n\n" + str + "\n\nlength = " + field.length);
         break;
   }
   return "";
}

function utilSetDroplist(drop, value)
{
	for(i = 0; i < drop.options.length; i++)
	{
		if(drop.options[i].value == value)
		{
			drop.selectedIndex = i;
			break;
		}
	}
} 

// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function utilGetRadioValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function utilSetRadioValue(radioObj, newValue) {
	if(!radioObj) {
		return;
	}
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}

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;
  }

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 updateHeaderPos(parent, child) {
	var p = document.getElementById(parent);
	if(p) {
		c = document.getElementById(child);
		if(c) {
			// c.style.position = 'absolute';
			// c.style.width = '100px';
			// alert(p.width);
			alert(parent.scrollTop-1);
			c.top = 120; // parent.scrollTop-1;
			// c.style.top = findPosX(p);
			// c.style.left = findPosY(p);
		}
	}
}

function searchOptionFinder(oSelect, oEvent) {
	var sKeyCode = oEvent.keyCode;
	var sToChar = String.fromCharCode(sKeyCode);
	if(sKeyCode >47 && sKeyCode<91){
		var sNow = new Date().getTime();
		if (oSelect.getAttribute("finder") == null) {
			oSelect.setAttribute("finder", sToChar.toUpperCase())
			oSelect.setAttribute("timer", sNow)
		} else if( sNow > parseInt(oSelect.getAttribute("timer"))+2000) { //Rest all;
			oSelect.setAttribute("finder", sToChar.toUpperCase())
			oSelect.setAttribute("timer", sNow) //reset timer;
		} else {
			oSelect.setAttribute("finder", oSelect.getAttribute("finder")+sToChar.toUpperCase())
			oSelect.setAttribute("timer", sNow); //update timer;
		}
		var sFinder =  oSelect.getAttribute("finder");
		var arrOpt = oSelect.options
		var iLen = arrOpt.length
		for (var i = 0; i < iLen ; i++) {
			sTest  = arrOpt[i].text;
			if(sTest.toUpperCase().indexOf(sFinder) == 0) {
				arrOpt[i].selected = true;
				break;
			}
		}
		oEvent.returnValue = false;
	} else{
		//Not a digit;
	}
}

// sort function - ascending (case-insensitive)
function sortFuncAsc(record1, record2) {
    var value1 = record1.optText.toLowerCase();
    var value2 = record2.optText.toLowerCase();
    if (value1 > value2) return(1);
    if (value1 < value2) return(-1);
    return(0);
}

// sort function - descending (case-insensitive)
function sortFuncDesc(record1, record2) {
    var value1 = record1.optText.toLowerCase();
    var value2 = record2.optText.toLowerCase();
    if (value1 > value2) return(-1);
    if (value1 < value2) return(1);
    return(0);
}

function sortSelect(selectToSort, ascendingOrder) {
    if (arguments.length == 1) ascendingOrder = true;    // default to ascending sort

    // copy options into an array
    var myOptions = [];
    for (var loop=0; loop<selectToSort.options.length; loop++) {
        myOptions[loop] = { optText:selectToSort.options[loop].text, optValue:selectToSort.options[loop].value };
    }

    // sort array
    if (ascendingOrder) {
        myOptions.sort(sortFuncAsc);
    } else {
        myOptions.sort(sortFuncDesc);
    }

    // copy sorted options from array back to select box
    selectToSort.options.length = 0;
    for (var loop=0; loop<myOptions.length; loop++) {
        var optObj = document.createElement('option');
        optObj.text = myOptions[loop].optText;
        optObj.value = myOptions[loop].optValue;
        selectToSort.options.add(optObj);
    }
}

function tableEnableField(checkbox, tableName, fieldName) {
	window.location = '/admin/ctrl/tablefield.php?t=' + encodeURIComponent(tableName) + '&field=' + encodeURIComponent(fieldName) + '&enable=' + (checkbox.checked?'1':'0') + '&ref=' + encodeURIComponent(window.location);
}

function textareaLimit(limitField, limit, showAlert) {
    if (limitField.value.length > limit) {
    	if(showAlert) alert('Numarul maxim de caractere admis in aceasta casuta postala este ' + limit + ' caractere.');
    	limitField.value = limitField.value.substring(0, limit);
    	// a.value.split("\n").length
    }
}
