// this is a java script function library for Jobpartners

// comparator to be used by array sorting
function ignoreCase(a, b) {
    var newa = a.toLowerCase();
    var newb = b.toLowerCase();
    if (newa < newb)
        return -1;
    if (newa > newb)
        return 1;
    return 0;
}

function initialiseMultiSelect(selectElement, buildText, buildValues) {
    selectElement.length = 0;
    for (i = 0; i < buildText.length; i++) {
        selectElement.options[i] = new Option();
        selectElement.options[i].text = buildText[i];
        selectElement.options[i].value = buildValues[i];
    }

    sortMultiSelect(selectElement);
}

function sortMultiSelect(selectElement) {
    var values = new Array();
    var text = new Array();
    var tempText = new Array(); //use to synchronize the value and the text

    for (i = 0; i < selectElement.options.length; i++) {
        values[i] = selectElement.options[i].value;
        text[i] = selectElement.options[i].text;
        tempText[i] = selectElement.options[i].text;
    }

    text.sort(ignoreCase);
    selectElement.options.length = 0; //clear the original list
    for (i = 0; i < text.length; i++) {
        selectElement.options[i] = new Option();
        selectElement.options[i].text = text[i];

        for (e = 0; e < tempText.length; e++) {
            if (tempText[e] == text[i]) {
                selectElement.options[i].value = values[e]; //asign the syn value to the element
                break;
            }
        }
    }
}

function moveOption(from, to) {
    for (i = 0; i < from.options.length; i++) { //start from the first index
        if (from.selectedIndex != "-1") {
            if (from.options[i].selected) {
                var newValue = new Option(from.options[i].text, from.options[i].value, false, false);
                to.options[to.options.length] = newValue;
                from.options[i] = null; //remove from list and it won't effact the index because it is the last selected one
                i--;
            }
        }
    }
    sortMultiSelect(from);
    sortMultiSelect(to);
}

function moveOptionExport(from, to) {
    for (i = 0; i < from.options.length; i++) { //start from the first index
        if (from.selectedIndex != "-1") {
            if (from.options[i].selected) {
                var newValue = new Option(from.options[i].text, from.options[i].value, false, false);
                to.options[to.options.length] = newValue;
                from.options[i] = null; //remove from list and it won't effact the index because it is the last selected one
                i--;
            }
        }
    }
}

function moveOptionExportAll(from, to) {
    for (i = 0; i < from.options.length; i++) { //start from the first index
        var newValue = new Option(from.options[i].text, from.options[i].value, false, false);
        to.options[to.options.length] = newValue;
        from.options[i] = null; //remove from list and it won't effact the index because it is the last selected one
        i--;
    }
}

function up(list, msg) {
    var currentItem = null;
    var itemAbove = null;
    var itemBelow = null;
    var currentIndex = null;
    var listSize = null;
    currentIndex = list.selectedIndex;
    var d = 0;
    for (i = 0; i < list.length; i++) {
        if (list[i].selected) {
            d = d + 1;
        }
    }
    if (d > 1) {
        alert(msg);
        return false;
    }
    if (currentIndex > 0) {
        currentItem = list.options[currentIndex];
        itemAbove = list.options[currentIndex - 1];
        list.options[currentIndex - 1] = new Option(currentItem.text, currentItem.value);
        list.options[currentIndex] = new Option(itemAbove.text, itemAbove.value);
        list.selectedIndex = currentIndex - 1;
        //reOrder(form);
    }
}

function down(list, msg) {
    var currentItem = null;
    var itemAbove = null;
    var itemBelow = null;
    var currentIndex = null;
    var listSize = null;
    listSize = list.options.length;
    var d = 0;

    for (i = 0; i < list.length; i++) {
        if (list[i].selected) {
            d = d + 1;
        }
    }

    if (d > 1) {
        alert(msg);
        return false;
    }

    currentIndex = list.selectedIndex;
    if (currentIndex < (listSize - 1) && d == 1 ) {
        currentItem = list.options[currentIndex];
        itemBelow = list.options[currentIndex + 1];
        list.options[currentIndex + 1] = new Option(currentItem.text, currentItem.value);
        list.options[currentIndex] = new Option(itemBelow.text, itemBelow.value);
        list.selectedIndex = currentIndex + 1;
        //reOrder(form);
    }
}

function reOrder(form) {
    var currentItem = null;
    var listSize = null;
    list.orderedFormElementPositions.value = '';
    listSize = window.document.list.options.length;
    for (var i = 0; i < listSize; i++) {
        currentItem = window.document.list.options[i];
        window.document.form.orderedFormElementPositions.value = window.document.form.orderedFormElementPositions.value + currentItem.value + ',';
    }
}

// Generic popup name/employeeid search function
function doPersonSearch(contextpath, argCaller, argFormName, type, empIdField, nameField, personIdField, arrayField) {
    var popupWindow = window.open(contextpath+"/search/PopupSearch.do?quicksearchtype="+type+"&formName="+argFormName+"&caller="+argCaller+"&empIdField="+empIdField+"&nameField="+nameField+"&personIdField="+personIdField+"&arrayField="+arrayField,"Search_Popup","scrollbars=yes,height=300,width=350,left=80,top=80");
}

// Method to limit the number of characters entered into a textarea.
// Call this method thus: <textarea name="fieldName" onkeyup="textLimit(document.forms['formName'].fieldName, 200, '<i18n:dynaJS key="max_length_cap" />');" ...>
function textLimit(field, maxlen, msg) {
    if (field.value.length > maxlen) {
        field.value = field.value.substring(0, maxlen);
        alert(msg);
        field.focus();
    }
}

//
//              Date picker functions
//

// This opens a calendar with a smaller window, and is called when ErmConfig.showDateEntryFields() returns false
// as the manual date entry fields are not displayed.
function openCal(contextPath, longDate, textDate, formName, timeZone, additionalParams) {
    window.open(contextPath+'/system/DatePicker.do?datePickerTimeZone='+timeZone+'&datePickerLongDateField='+longDate+'&datePickerTextDateField='+textDate+'&datePickerFormName='+formName+"&NavigationPopUp=true" + additionalParams,'datepicker','height=280,width=280,top=200,left=250,toolbar=no,menubar=no,scrollbars=no,resizable=yes,status=no,directories=no,location=no');
}

// This opens a calendar with a bigger window, and is called when ErmConfig.showDateEntryFields() returns true,
// as the manual date entry fields are displayed.
function openFullCal(contextPath, longDate, textDate, formName, timeZone, additionalParams) {
    window.open(contextPath+'/system/DatePicker.do?datePickerTimeZone='+timeZone+'&datePickerLongDateField='+longDate+'&datePickerTextDateField='+textDate+'&datePickerFormName='+formName+"&NavigationPopUp=true" + additionalParams,'datepicker','height=350,width=310,top=200,left=250,toolbar=no,menubar=no,scrollbars=no,resizable=yes,status=no,directories=no,location=no');
}

// check that the date is valid and set as it is required
function datePickerValidationNew(form, textDateField, longDateField, msg) {
    datePickerValidationNotRequired(form, textDateField, longDateField, msg);

    // Check that the field is set
    if(namedPass())
    {
        _namedIsValid = (form.elements[longDateField].value != "");
        if (!namedPass())
        {
            alert(msg);
            form.elements[textDateField+"DD"].focus();
        }
    }
    return namedPass();
}

// check that the date is valid - or empty
function datePickerValidationNotRequired(form, textDateField, longDateField, msg) {
    datePickerValidation(form.elements[textDateField+"DD"], dp_day_tokens,
                         form.elements[textDateField+"MM"], dp_month_tokens,
                         form.elements[textDateField+"YY"], dp_year_tokens,
                         form.elements[longDateField], msg);
    return namedPass();
}

function dpInFuture(form, textDateField, longDateField, msg) {
    if (new Date() > form.elements[longDateField].value) {
        alert(msg);
        form.elements[textDateField+"DD"].focus();
        _namedIsValid = false;
    }
}

function dpTodayOrInFuture(form, textDateField, longDateField, msg) {
    var d = new Date();
    d.setHours(0);
    d.setMinutes(0);
    d.setSeconds(0);
    d.setTime(d.getTime()-999);
    if (d.getTime() > form.elements[longDateField].value) {
        alert(msg);
        form.elements[textDateField+"DD"].focus();
        _namedIsValid = false;
    }
}



function dpTheDate(yy,mm,dd,valtype,yy2,mm2,dd2, errMsg)
{

// changed to parseFloat to avoid wierd error where parseInt("09") returns 0
var nowDate = new Date();
var nowYear = nowDate.getYear();
var nowMonth = nowDate.getMonth()+1;
var nowDay = nowDate.getDate();

if (nowYear<1000) {nowYear += 1900;}

var selDay = parseFloat(dd.value);
var selMonth = parseFloat(mm.value);
var selYear = parseFloat(yy.value);

var selSortDate=selYear*10000+selMonth*100+selDay;
var nowSortDate=nowYear*10000+nowMonth*100+nowDay;

if (valtype=="today"){
    if (nowSortDate==selSortDate){
        return true;
    }else{
        return false;
    }
}

if ((valtype=="compare")||(valtype=="onlycompare")||(valtype=="for_logging")){
var selDay2 = parseFloat(dd2.value);
var selMonth2 = parseFloat(mm2.value);
var selYear2 = parseFloat(yy2.value);
var selSortDate2=selYear2*10000+selMonth2*100+selDay2;
}

if(((dd.selectedIndex!=0)||(mm.selectedIndex!=0)||(valtype=="post")||(valtype=="pre"))&&(yy.selectedIndex==0)){
  alert(isreq44 + fieldName+ isreqa44);
  yy.focus();
  return false;
}

if(((dd.selectedIndex!=0)||(yy.selectedIndex!=0))&&(mm.selectedIndex==0)){
  alert(isreq44 + fieldName2 + isreqa44)
  mm.focus();
  return false;
}

if(((mm.selectedIndex!=0)||(yy.selectedIndex!=0))&&(dd.selectedIndex==0)){
  alert(isreq44 + fieldName3 + isreqa44);
  dd.focus();
  return false;
}

if( ((selDay==31)&&((selMonth==4)||(selMonth==6)||(selMonth==9)||(selMonth==11))) || ((selDay>29)&&(selMonth==2)) )
{
alert(isreq13);
dd.focus();
return false;
}

if( ((selYear%4)!=0)&&(selDay==29)&&(selMonth==2) )  // Leap-year Check
{
alert(isreq12);
dd.focus();
return false;
}

if ((valtype=="post")&&(nowSortDate>selSortDate))
{
  alert(isreq9)
  yy.focus();
  return false;
}

if ((valtype=="pre")&&(nowSortDate<selSortDate))
{
  alert("The date you have selected cannot be later than the current date.")
  yy.focus();
  return false;
}

if (valtype=="for_logging")
{
    if (((selSortDate != 0) && (selSortDate2 == 0)) || ((selSortDate == 0) && (selSortDate2 != 0)))
    {
      alert(isreq56);
      yy.focus();
      return false;
    }

  if ((selSortDate > nowSortDate)||(selSortDate2 > nowSortDate)) {
    alert(isreq59);
    yy.focus();
    return false;
  }
}

if (((valtype=="onlycompare")||(valtype=="for_logging")||(valtype="comp_date2"))
                &&(selSortDate<selSortDate2)&&(selSortDate!=0)&&(selSortDate2!=0))
{
  if (errMsg) {
	alert(errMsg);
  } else {
	alert(isreq54);
  }
  yy.focus();
  return false;
}

if (selSortDate2==0)selSortDate2=selSortDate;
if ((valtype=="compare")&&(selSortDate>0)&&((selSortDate2<selSortDate)||(nowSortDate>selSortDate)))
{
  alert(isreq53);
  yy.focus();
  return false;
}

return true;
}

function validateDateRange(form, textDateField1, textDateField2, errMsg)
{
    var res = dpTheDate(form.elements[textDateField1+"YY"],
                     form.elements[textDateField1+"MM"],
                     form.elements[textDateField1+"DD"],
                     "onlycompare",
                     form.elements[textDateField2+"YY"],
                     form.elements[textDateField2+"MM"],
                     form.elements[textDateField2+"DD"],
                     errMsg);

    if (!res)
    {
        _namedIsValid = res;
    }

    return res;
}

function datePickerDataPresent(dayInput, monthInput, yearInput) {
    if (dayInput.value.length > 0 || monthInput.value.length > 0 || yearInput.value.length > 0) {
        if (onlyDigits(dayInput.value) && onlyDigits(monthInput.value) && onlyDigits(yearInput.value)) {
            return true;
        }
    }
    
    return false;
}

function onlyDigits(fieldValue) {
    var digits = "0123456789";
    for (i = 0; i < fieldValue.length; i++ ) {
        var ch = fieldValue.charAt( i );
        if (digits.indexOf(ch, 0) == -1) {
            return false;
        }
    }
    
    return true;
}

/*
  This function performs the validation for the date picker. If the arrays for the Allowed parameters are
  populated and subsequently matched, then validation will be bypassed and the long date value will be reset to ''.
  params:
    dayInput: The element containing the day
    dayAllowed: The values considered valid for day
    monthInput: The element containing the month
    monthAllowed: The values considered valid for month
    yearInput: The element containing the year
    yearAllowed: The values considered valid for year
    longDate: The element that will be populated with the long date value providing all checks are passed
    msg: The message to display on error
*/
function datePickerValidation(dayInput, dayAllowed, monthInput, monthAllowed, yearInput, yearAllowed, longDate, msg) {
    var passed = true;
    var dayIsAllowed = false;
    var monthIsAllowed = false;
    var yearIsAllowed = false;
    _jpjsV3ErrMsg = msg;

    if (_namedIsValid) {


        // day
	    dayIsAllowed = dayInput.value.length == 0;
	    if (!dayIsAllowed) {
	        for (var i = 0; i < dayAllowed.length; i++) {
	            if (dayInput.value == dayAllowed[i]) {
	                dayIsAllowed = true;
	                break;
	            }
	        }
        }
        if (!dayIsAllowed) {
            if (passed && !validateNumber(dayInput,dp_day_field)) {
                passed = false;
                dayInput.focus();
            }
        }

        // month
        monthIsAllowed = monthInput.value.length == 0;
        if (!monthIsAllowed) {
	        for (var i = 0; i < monthAllowed.length; i++) {
	            if (monthInput.value == monthAllowed[i]) {
	                monthIsAllowed = true;
	                break;
	            }
	        }
        }
        if (!monthIsAllowed) {
            if (passed && !validateNumber(monthInput,dp_month_field)) {
                passed = false;
                monthInput.focus();
            }
        }

        // year
		yearIsAllowed = yearInput.value.length == 0;
        if (!yearIsAllowed) {
	        for (var i = 0; i < yearAllowed.length; i++) {
	            if (yearInput.value == yearAllowed[i]) {
	                yearIsAllowed = true;
	                break;
	            }
	        }
        }
        if (!yearIsAllowed) {
            if (passed && !validateNumber(yearInput,dp_year_field)) {
                passed = false;
                yearInput.focus();
            }
        }


        if (dayIsAllowed && monthIsAllowed && yearIsAllowed) {
            longDate.value = ''; // Clear the contents of the long date field
            // Make sure there is not a mix n match of types going on....
            if (!(dayInput.value.length == 0 && monthInput.value.length == 0 && yearInput.value.length == 0)) {
                dayIsAllowed = (dayInput.value.length != 0);
                monthIsAllowed = (monthInput.value.length != 0);
                yearIsAllowed = (yearInput.value.length != 0);
                if (!dayIsAllowed && !monthIsAllowed && !yearIsAllowed) {
                    dayIsAllowed = true;
                    monthIsAllowed = true;
                    yearIsAllowed = true;
                }
            }
        }

        if (passed && !dayIsAllowed && !monthIsAllowed && !yearIsAllowed) {
            var daysInMonth = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
            var day = dayInput.value * 1;
            var month = (monthInput.value * 1) - 1; // Months are zero based
            var year = yearInput.value * 1;

            dayIsAllowed = true;
            monthIsAllowed = true;
            yearIsAllowed = true;

            // check that the value is a valid day
            if (day <= 0 || day > 31) {
                dayInput.focus();
                passed = false;
            }

            // check that the value is a valid month
            if (month < 0 || month > 11) {
                monthInput.focus();
                passed = false;
            }

            // check that the value is a valid year
            if (year < 1000 || year > 9999) {
                yearInput.focus();
                passed = false;
            }

            if (passed) {
                // At this point, we have a valid non-blank integer for the date and a valid month
                // - now check that it's valid for the month chosen

                // This checks for a leap year
                if (month == 1) { // Feb
                    daysInMonth[1] = ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) ? 29 : 28;
                }
                if (day > daysInMonth[month]) {
                    dayInput.focus();
                    passed = false;
                }

                if (passed) {
                    var date = new Date(year, month, day);
                    longDate.value = date.getTime();
                }
            }

            if (!passed) {
                alert(msg);
            }
        }
        if (!passed) {
            _namedIsValid = false;
        } else if (!(dayIsAllowed && monthIsAllowed && yearIsAllowed)) {
            dayInput.focus();
            alert(msg);
            _namedIsValid = false;
        }
    }
    return passed;
}

// This fuction will make sure that the start date is less than the end date.
function dateValidation(startDate, endDate, msg) {
    if (_namedIsValid) {
        if (endDate.value > 0) {
            var start = startDate.value * 1;
            var end = endDate.value * 1;
            if (start > end) {
                alert(msg);
                _namedIsValid = false;
            }
        }
    }
}

// this function has been implemented to speed up the date validation where many date fields are to be validated
function validateNumber(e, msg) {
    fieldName = msg; // Popup message
    valid = allowed_text(e,"valnum");
    return valid;
}

function showHelp(elem) {
	target = elem.nextSibling;
	while(target.id != 'helpDiv') {
		target = target.nextSibling;
	}
	if(target && target.id == 'helpDiv') {
		target.style.visibility = 'visible';
	}
}
function hideHelp(elem) {
	target = elem.nextSibling;
	while(target.id != 'helpDiv') {
		target = target.nextSibling;
	}
	if(target && target.id == 'helpDiv') {
		target.style.visibility = 'hidden';
	}
}
