/**
 * FILE: global_functions.js
 * DESCRIPTION: This file contains global javascript functions.
 * CREATED: 11/25/2002
**/

/**
  *	pbm 2007-01-16 Suppress Enter Key
  *  to use code onKeyPress with a return:
  *   <input type="text" onKeyPress="return checkEnter(event)">
  * when enter key is pressed, false is returned to the browser, preventing submission 
**/
function checkEnter(e){ //e is event object passed from function invocation
    var characterCode //literal character code will be stored in this variable
    
    if(e && e.which){ //if which property of event object is supported (NN4)
        e = e
        characterCode = e.which //character code is contained in NN4's which property
    }
    else{
        e = event
        characterCode = e.keyCode //character code is contained in IE's keyCode property
    }
    
    if(characterCode == 13){ //ascii 13 is enter key
        return false //return false to the event handler
    }
    else{
        return true //return true to the event handler
    }

}



/**
 * Opens a new window
**/

function openNewWindow(url) {

	var w = window.open(url, "Window", "", true);
   	w.focus();

}

function openUrlWindow(url) {
  if ( !( url.length > 7) || !(url.indexOf("http://")==0) ) {
    alert( 'Please enter a valid url ( starting with "http://" and followed by the site address).');
    return;
  }
	openNewWindow(url);
}

var popWindow = null;
var popDone = "False";

function openPop(url, width, height) {

	var browserName = navigator.appName;
//	if (popWindow != null && browserName != "Netscape") { popWindow.close(); }
	var w = window.open(url, "Pop", "width=" + width + ",height=" + height + ",toolbar=no,status=no,directories=no,scrollbars=yes,menubar=no,resizable=yes,screenX=" + 0 + ",left=" + 0 + "screenY=" + window.screenY + ",top=" + window.screenY, true);
    	w.focus();
	popWindow = w;
}

var helpWindow = null;

function openHelp(tmpl, helpKey) {
	var helpPage = "";
	helpPage = ignoreSpaces(helpKey).toLowerCase() + "help.php";

	var helpUrl = tmpl + "?helpLink=" + helpPage + "&helpTitle=" + escape("Help For " + helpKey);

	var w = window.open(helpUrl, "Help", "width=600,height=600,toolbar=no,status=no,directories=no,scrollbars=yes,menubar=no,resizable=yes,screenX=" + 0 + ",left=" + 0 + "screenY=" + window.screenY + ",top=" + window.screenY, true);
   	w.focus();
	helpWindow = w;

}


function popSaveWindow() {
  var newtext = "Saving";
  var winWidth = 220;
  var winHeight= 105;

  var posLeft = (screen.width - winWidth) / 2;
  var posTop = (screen.height - winHeight) / 2;

  features = 'height=' + winHeight + ',width=' + winWidth + ',top=' + posTop + ',left=' + posLeft + ',toolbar=no,status=no,directories=no,scrollbars=no,menubar=no,resizable=no';

  window.open("../core/saving.html", "Pop", features, false);
}

function popDeleteWindow() {
  var newtext = "Deleting";
  var winWidth = 220;
  var winHeight= 105;

  var posLeft = (screen.width - winWidth) / 2;
  var posTop = (screen.height - winHeight) / 2;

  features = 'height=' + winHeight + ',width=' + winWidth + ',top=' + posTop + ',left=' + posLeft + ',toolbar=no,status=no,directories=no,scrollbars=no,menubar=no,resizable=no';

  window.open("/deleting.jsp", "Pop", features, false);

}

function popProcessingWindow() {
  var newtext = "Processing";
  var winWidth = 220;
  var winHeight= 105;

  var posLeft = (screen.width - winWidth) / 2;
  var posTop = (screen.height - winHeight) / 2;

  features = 'height=' + winHeight + ',width=' + winWidth + ',top=' + posTop + ',left=' + posLeft + ',toolbar=no,status=no,directories=no,scrollbars=no,menubar=no,resizable=no';

  var processPopWindow = window.open("/processing.jsp", "Pop", features, false);


}

var lookupWindow = null;

function qbeLookup(column, location) {

  var browserName = navigator.appName;
//  if (lookupWindow != null && browserName != "Netscape") { lookupWindow.close(); }
  var value = column.options[column.selectedIndex].value;
  var listValue = value.substring(value.lastIndexOf(":") + 1, value.lastIndexOf(":") + 2);
  var destUrl;

  //D = Date
  if (listValue == 'D') {
    destUrl = "/webcommon/js/calendar.do?" + location;
    lookupWindow = window.open(destUrl, '', 'width=200,height=210,top=20,left=20' );
    return;
  }

  //L = List
  if (listValue == 'L') {
    destUrl = "/reporting/lookup.do?lookupcolumn=" + value + "&location=" + location;
    lookupWindow = window.open(destUrl, '', 'scrollbars=yes,resizable=yes,width=200,height=418,top=20,left=20' );
    return;
  }


}

function popAssessmentProcessingWindow() {
  var newtext = "Processing";

  var winWidth = 440;
  var winHeight= 300;

  var posLeft = (screen.width - winWidth) / 2;
  var posTop = (screen.height - winHeight) / 2;

  features = 'height=' + winHeight + ',width=' + winWidth + ',top=' + posTop + ',left=' + posLeft + ',toolbar=no,status=no,directories=no,scrollbars=no,menubar=no,resizable=no';

  window.open("/processingAssessment.html", "Pop", features, false);

}

/** Go to the url value in the dd */
function go(what) {
	where = what.options[what.selectedIndex].value;
	if (where == "") return;
	window.location.href = where;
}


/**
 * @param field as a field that has the original value and will hold the new value
 */
function formatPhoneNumber( field ){

	var formattedPhone;
 	var phoneNbr;
    var finalPhoneNbr = "";
    var character = "";
    var numbers = "0123456789";

	phoneNbr = field.value;

    //string out all but numbers
    for( var i=0; i<phoneNbr.length;i++){
       character = phoneNbr.substring(i, i+1);
       if( numbers.indexOf(character) >= 0){
          finalPhoneNbr += character;
       }
    }
    finalPhoneNbr = finalPhoneNbr.substring( 0,10);

    if( finalPhoneNbr.length == 10 ){
      finalPhoneNbr = "(" + finalPhoneNbr.substring(0,3) + ") "
            + finalPhoneNbr.substring(3,6) + "-"
            + finalPhoneNbr.substring(6,10);
    }
    else{
      finalPhoneNbr = phoneNbr;
    }

    field.value = finalPhoneNbr ;


}


function getWindowTitle() {
	var windowTitle = document.title;
	return windowTitle;
}

function ignoreSpaces(string) {
	var temp = "";
	string = '' + string;
	splitstring = string.split(" ");
	for(i = 0; i < splitstring.length; i++)
	temp += splitstring[i];
	return temp;
}

var adminWindow = null;

function openAdmin() {
	var adminUrl = "/admin/adminhome/adminhomepage.jsp";

	var browserName = navigator.appName;
//	if (adminWindow != null && browserName != "Netscape") { adminWindow.close(); }
	var w = window.open(adminUrl, "Admin", "width=800,height=450,toolbar=yes,status=yes,directories=yes,location=yes,scrollbars=yes,menubar=yes,resizable=yes,screenX=" + 0 + ",left=" + 50 + "screenY=" + window.screenY + ",top=" + 50 + window.screenY, true);
    	w.focus();
	adminWindow = w;

}


var trainingWindow = null;

function openTraining(trainingUrl) {
	var browserName = navigator.appName;
    var topX = screen.availWidth - 800 - 12;



// 	if (trainingWindow != null && browserName != "Netscape") { trainingWindow.close(); }

	var w = window.open(trainingUrl, "Training", "width=800,height=600,toolbar=no,status=yes,directories=no,location=no,scrollbars=yes,menubar=no,resizable=yes,top=0,left=" + topX,true);
   	w.focus();
	trainingWindow = w;
}


function fillFieldFromCheckBoxes(list,field) {
	/* @param "list" is the name of 1 or more checkboxes
	*  @param "field" is a text box that will be used to hold a list of changes
	*  @param "original" is a text box that will hold the original values of the checkboxes
	*
	*  Note:
	*  setOriginalCheckBoxValues() somewhere when the form loads or before this
	*  function is called.
	*/
	var resultingString = "";
	var finalString = "";
	var testString = "";
	var pos=0;

	// load the list of checkbox values as it stands at this moment in time
	// the list will come in as ;name=value;name=value
	// add the extra ";" on the end so that all fields are inclosed within semicolons
	resultingString = getCheckBoxValues(list) + ";";



	// only drop the value into the changes text box if
	// it is not the original value
	while( resultingString.length > 0){

		//walk through the resultingString looking for the ;'s and extracting
		// the data between them
		pos=resultingString.indexOf(";");
		if( pos >= 0 ){
			testString=";" + resultingString.substring(0,pos );
			resultingString= resultingString.substring(pos + 1);
		}
		else{
			testString = resultingString;
		}

		if( testString.length > 2){  // avoid scanning an empty string which looks like ";;"
			finalString+=testString;
		}
	}
	// write the final string to the text box that holds the changes
	field.value=finalString;

}


function getCheckBoxValues( list ){
	/* this function returns a string that has the name and value of each checkbox
	*  in the "list".  This string will be of the syntax ";name=value;name=value...
	*  this value will be 1 for checked or 0 for not checked
	*
	*  @param "list" is the name of 1 or more checkboxes
	*/


	var resultingString = "";

	// if the length of the list is more than 1, then it is an array
	// if it is not more than 1, it is a single item.
	if(list.length > 0){
		//if it is an array, walk through each array item
		for (i = 0; i < list.length; i++){
			if(list[i].checked == true){
				resultingString+=";" + list[i].value + ":" + "1";
			}
			else{
				resultingString+=";" + list[i].value + ":" + "0";
			}

		}
	}
	else{
		if(list.checked == true){
			resultingString+=";" + list.value + ":" + "1";
		}
		else{
			resultingString+=";" + list.value + ":" + "0";
		}
	}

	// return the resulting string
	return resultingString;
}

function deleteConfirm (  question, form, deleteFieldPrefix, deleteFieldName, rowCnt ) {
	ask = false;
	for ( i=1; i <= rowCnt; i++ ) {
		if ( 	form.elements[ deleteFieldPrefix + i + '_' + deleteFieldName ] ) {
			if ( form.elements[ deleteFieldPrefix + i + '_' + deleteFieldName ].checked ) {
				ask = true;
				break;
			}
		}
		else {
			break;
		}
	}
	var retValue = true;
	if ( ask ) {
		retValue = confirm ( question );
	}
	if ( retValue ) {
	  popSaveWindow();
	}
	return retValue;
}

function saveConfirm ( question ) {
  var retValue = confirm ( question );
  if ( retValue ) {
    popSaveWindow();
  }
  return retValue;
}

function saveForm ( form, saveProperty, saveValue ) {
  saveForm ( form, saveProperty, saveValue, '' );
}

function reloadForm( form ) {

	action = form.action;
	form.action = action + "?formReload=true";
	form.submit();
	//form.action = action;

}

// pbm 2006-01-08
// Simulate a user clicking on image input button to Reset the Form.
// Image input type returns the x-y coordinates of the location where
// the user clicked on the image. 
// Add reset.x to request so Struts will redirect to the struts reset action.
function resetForm ( form) {

  if ( form[0] && form[1] && form[0].name == form[1].name) {
	  form = form[0];
	}

	action = form.action;
	resetProperty = '?reset.x=000';

	form.action = action + resetProperty;
	form.submit();

}

//this function will navigate to the bookmark if given.
//the bookmark needs to be the full url
//for example "/provider/providerstuff#statechange"
function saveForm ( form, saveProperty, saveValue, bookmark ) {

  if ( form[0] && form[1] && form[0].name == form[1].name) {
  	form = form[0];
	}

	action = form.action;

	if( !bookmark ) { bookmark = ""; }

	if( bookmark.length > 0 ){
		bookmark="#" + bookmark;
	}

	if( !saveProperty) { saveProperty=""; }

	if( saveProperty .length > 0 ){
		saveProperty = '&' + saveProperty + '=' + saveValue;
	}

	form.action = action + saveProperty + bookmark;
	form.submit();

}


function setTextBoxValues( list,listValue ){


	// if the length of the list is more than 1, then it is an array
	// if it is not more than 1, it is a single item.
	if(list.length > 0){
		//if it is an array, walk through each array item
		for (i = 0; i < list.length; i++){
			list[i].value = listValue;
		}
	}
	else{
		list.value = listValue;
	}

}



function moveUp(sourceSelect) {
    if (sourceSelect.length > 1) {
        var options = sourceSelect.options;

        // find which ones are selected...
        var selectedIds = new Array ();
        var index = 0;
        for (var i = 1; i < sourceSelect.length; i++) {
            if (options[i].selected) {
                selectedIds[index] = i;
                index++;
            }
        }

        // move each selected option up
        var selId;
        for (var i = 0; i < selectedIds.length; i++) {
            selId = selectedIds[i];
            privateMoveUp (options, selId);
            options[selId].selected = false;
            options[selId-1].selected = true;
        }

        sourceSelect.focus ();
    }
}

function moveDown(sourceSelect) {
    if (sourceSelect.length > 1) {
        var options = sourceSelect.options;

        // find which ones are selected
        var selectedIds = new Array ();
        var index = 0;
        for (var i = sourceSelect.length-2; i >= 0; i--) {
            if (sourceSelect.options[i].selected) {
                selectedIds[index] = i;
                index++;
            }
        }

        // move each selected element down
        var selId;
        for (var i = 0; i < selectedIds.length; i++) {
            selId = selectedIds[i];
            privateMoveDown (options, selId);
            options[selId].selected = false;
            options[selId+1].selected = true;
        }

        sourceSelect.focus ();
	}
}


function moveTop(sourceSelect) {
    var selIndex = sourceSelect.selectedIndex;

    if (sourceSelect.length > 1 && selIndex > 0) {
        var options = sourceSelect.options;

        for (var i = selIndex; i > 0; i--) {
            privateMoveUp (options, i);
        }

        sourceSelect.focus ();
        sourceSelect.selectedIndex = 0;
    }
}

function moveBottom(sourceSelect) {
    var selIndex = sourceSelect.selectedIndex;

    // gots to have at least 2 items and something selected, but not the last one
    if (sourceSelect.length > 1 && selIndex > -1 && selIndex < sourceSelect.length - 1) {
        var options = sourceSelect.options;

        for (var i = selIndex; i < sourceSelect.length - 1; i++) {
            privateMoveDown (options, i);
        }

        sourceSelect.focus ();
        sourceSelect.selectedIndex = sourceSelect.length - 1;
    }
}

/*
 * Do not call this function directly.
 * As it does NO bounds checking.
 * Please use the moveUp or moveTop calls.
 */
function privateMoveUp (options, index) {
    var newOption = new Option (options[index-1].text, options[index-1].value);
    options[index-1].text = options[index].text;
    options[index-1].value = options[index].value;
    options[index].text = newOption.text;
    options[index].value = newOption.value;
}

/*
 * Do not call this function directly.
 * As it does NO bounds checking.
 * Please use the moveDown or moveBottom calls.
 */
function privateMoveDown (options, index) {
    var newOption = new Option (options[index+1].text, options[index+1].value);
    options[index+1].text = options[index].text;
    options[index+1].value = options[index].value;
    options[index].text = newOption.text;
    options[index].value = newOption.value;
}



/**
 * Used when submitting a dueling list boxes element.
 * Stores all the values into hidden form parameters so we can get them out
 */
function saveAllSelected (fromSelectArray, toArray, delim, emptyLabel) {
    var i,j;
    // loop through all the select elements
    for (i = 0; i < fromSelectArray.length; i++) {
        toArray[i].value = ''; // clear out the value to start
        // now loop through all the values in the select element
        for (j = 0; j < fromSelectArray[i].length; j++) {
            // copy over the value as long as it is not the emptyLabel
            if (!(fromSelectArray[i].length == 1 && fromSelectArray[i].options[0].value == emptyLabel)) {
                toArray[i].value += fromSelectArray[i].options[j].value;
            }

            // add the delimiter (except after the last one)
            if (j + 1 < fromSelectArray[i].length) {
                toArray[i].value += delim;
            }
        }
    }
}

function moveSelectedOptions ( sourceSelect, targetSelect ) {

    var sourceOptions = sourceSelect.options;
    var option;

    // find which ones are selected...
    var selectedIds = new Array ();
    var index = 0;
    for (var i = 0; i < sourceSelect.length; i++) {
		option = sourceOptions[i];
		if (option.selected) {
		 selectedIds[index] = i;
		 index++;
		}
    }

    // move them over one by one
    var targetOptions = targetSelect.options;
    if ( selectedIds.length > 0 ) {
    	targetSelect.selectedIndex = -1;
    	for (var i = 0; i < selectedIds.length; i++) {
      	option = new Option (sourceOptions[selectedIds[i]].text, sourceOptions[selectedIds[i]].value);
		   targetOptions[targetOptions.length] = option;
		   targetOptions[targetOptions.length-1].selected = true;
      }
    }

    // remove values from the source
    for (var i = selectedIds.length; i > -1; i--) {
        sourceOptions[selectedIds[i]] = null;
    }

    // if we moved anything, put the focus on the target list box
    if (selectedIds.length > 0) targetSelect.focus ();
}

function moveAllOptions ( sourceSelect, targetSelect ) {

    var sourceOptions = sourceSelect.options;
    var option;

    // move them over one by one
    var targetOptions = targetSelect.options;
    if ( sourceOptions.length > 0 ) {
    	targetSelect.selectedIndex = -1;
    	for (var i = 0; i < sourceOptions.length; i++) {
      	option = new Option (sourceOptions[i].text, sourceOptions[i].value);
		   targetOptions[targetOptions.length] = option;
		   targetOptions[targetOptions.length-1].selected = true;
      }
    }

    // remove values from the source
    for (var i = sourceOptions.length; i > -1; i--) {
        sourceOptions[i] = null;
    }

    // if we moved anything, put the focus on the target list box
    targetSelect.focus ();
}

function saveSelected(fromSelObj, toHidObj, delim, empty_label) {
    var i;
	toHidObj.value = '';
    for (i=0; i<fromSelObj.length; i++) {
        if (i > 0) {
            toHidObj.value += delim;
        }
        if (!(fromSelObj.length == 1 && fromSelObj.options[0].value == empty_label)) {
            toHidObj.value += fromSelObj.options[i].value;
        }
    }
}

//powersearch scripts
//open training detail
function psTrainVD(trainingId){
    openTraining('/training/displaytraining.do?displayMode=view&trainingId=' + trainingId);
}

//open competency detail
function psCompVD(competencyId){
  var url = "/competency/competencypoppage.jsp?";
  var height = 420;
  var width = 600;

  url = url + 'competencyId=' + competencyId;
  openPop(url, width, height);
}

function psUserVD(userId){
  var url = "/admin/user/editUser.do?userId=" + userId;
  window.location.href = url;
}
//end powersearch scripts

function defaultOnload(timeOutMinutes){
  window.focus();
  setFieldFocus();
  var url = window.location.href;
  if ( url.indexOf("/login/sessionTimeout.do") < 0
       && url.indexOf("/login/loginpage.do") < 0 ) {
    var timeOut = timeOutMinutes * 60 * 1000;
    window.setTimeout("sessionTimeout()",timeOut);
  }

}

function sessionTimeout(){
  window.location.href = '/login/sessionTimeout.do';
}

function setFieldFocus(){
}

