function onPageLoad(){
    //initRTE('../rte/images/', '../rte/', '', true);
    var urlWindow=window.location.href; 
    if(urlWindow.indexOf("create.jsp")!=-1 || urlWindow.indexOf("modify.jsp")!=-1 ){
        intializeAjaxElements();
        disableAll();
    }
}

function copyDate(formElement,form) {
    fieldname=formElement.name;
    if (fieldname.indexOf("*")!=-1) {
        fieldname = fieldname.substring(0,fieldname.indexOf("*"));
        //alert('Changed fieldname to ' + fieldname);
    }
    else {
        //alert('fieldname is ' + fieldname);
    }
    elall=form[fieldname];
    var eld = form[fieldname + '*date'];
    var elh = form[fieldname + '*hours'];
    var elm = form[fieldname + '*minutes'];
    if (elall != null) {
        //alert('elall.value is now: ' + elall.value);
        //alert('elall.name is now: ' + elall.name);
    } 
    else {
        //alert('elall is null');
    }
    var hours="00";
    var minutes="00";
    
    if(elh!=null && elh.selectedIndex!= -1 ){
        hours=elh.options[elh.selectedIndex].text ;
    }
    if(elm!=null && elm.selectedIndex != -1 ){
        minutes=elm.options[elm.selectedIndex].text;
    }    
    
    
    if (eld != null && hours != null && minutes != null && elall != null) {
        var url=window.location.href;
        if(url.indexOf("create.jsp") !=-1){
            elall.value = eld.value + ' ' +hours+ ':' + minutes;
        } 
        else{
            var dateStr = eld.value;
            if (dateStr == null || dateStr == '') {
                elall.value = '';
                return;
            }
            else if (dateStr == 'today') {
                var now = new Date();
                dateStr = "" + now.getDate() + "/" + (now.getMonth()+1) + "/" + now.getYear();
            }
            elall.value = dateStr + ' ' +hours+ ':' + minutes;
        }
        //alert('Copied to elall.value: ' + elall.value);
    }
}

var allHiddens = new Array();
var thisHidden;
var extraFunc = null;
function populate(field, value, visible) {
    
    //alert( "Field " + field + " value : " + value + " visible " + visible );
    var vmForm;
    if ( window.opener ){
        vmForm = window.opener.document.forms['vmForm'];
    }else{
    vmForm = document.forms['vmForm'];
}

var url=window.location.href;
if(url.indexOf("create.jsp") !=-1){
    var el = document.vmForm.elements[visible];
    if (el != null) {
        var myNewOption = new Option(value, '' + field.substring(1));
        el.options[el.options.length] = myNewOption;
    }
}else{
var element = vmForm.elements[field];
var element2;
try{
    element2 = vmForm.elements[field + "_visible"];
}catch(ignore){}
if (element == null) {
    element = vmForm.elements["_" + field];
    element.name = element.name.substring(1);
}
if (element != null) {
    if (element.type == "select-multiple") {
        if ( window.opener ){
            window.opener.addOption(field, value, visible);
        }else{
        addOption(field, value, visible);
    }
    /*
    var opt = new Option(value, visible);
    element.options[element.options.length] = opt;
    */
}else if (element.type == "select-one") {
if ( window.opener ){
    window.opener.addOption(field, value, visible);
}else{
addOption(field, value, visible);
}
}else {
element.value = value;
element2.value = visible;
}
}

if (extraFunc != null) {
    eval(extraFunc.replace('PAGEOBJECT', 'a' + value));
}
try{
    sendHidden( "a"+value,field);
}
catch ( e ){
}

if ( element2 ){
    element2.focus();
}else{
element.focus();
}

if ( window.opener ){
    element.focus();
    window.close();
}else{
try{
    hideAjaxViewDiv( element.id );
}catch(e){
alert( "Hide div failed: " + e );
}
}
}
}

function addOption(fieldName, value, visible) {
    var element = document.forms['vmForm'].elements[fieldName];
    var opt = new Option(visible, value);
    element.options[element.options.length] = opt;
    opt.selected = true;
}

var totalStrokes;
var lastKeyTime = new Date().getTime();
var lastEl = null;

function checkDropdownKey(key, el) {
    // alert("key = " + key + ", el = " + el);
    /*
    if (key == 104) {
    el.focus();
    return false;
    }
    */
    if (lastEl != el) {
        lastKeyTime = 0;
    }
    if (key == 9) {
        lastEl = el;
        lastKeyTime = 0;
    }
    if ((key != 32) && (key < 48 || (key > 57 && key < 65) || (key > 90 && key < 97) || (key > 122))) {
        return;
    }
    var t = new Date().getTime();
    // alert("t = " + t);
    if (t - lastKeyTime < 2000) {
        totalStrokes += String.fromCharCode(key);
    } else {
    totalStrokes = '' + String.fromCharCode(key);
}
lastKeyTime = t;

// alert("totalStrokes = " + totalStrokes);
var ind = findIndex(totalStrokes.toLowerCase(), el);
// alert("found index = " + ind);
if (ind != -1) {
    el.selectedIndex = ind;
}

lastEl = el;


return false;
}

function findIndex(strokes, el) {
    var options = el.options;
    var thisOption = el.selectedIndex;
    // alert("index = " + thisOption);
    var i=0;
    while (i<options.length) {
        var optext = options[i].text;
        // alert("optext = " + optext);
        optext = optext.toLowerCase();
        if (optext.indexOf(strokes) == 0) {
            // alert("option = " + options[i].text);
            return i;
        }
        i++;
    }
    
    return -1;
}

var mandatories = new Array();
var manLabels = new Array();
var disableAjax=new Array();
var ajaxValues=new Array();

function vmFormOnSubmit(){
    try{
        try{
            copyToHidden()
        }
        catch(e){}
        return checkMandatory();
    }
    catch( e ) {
        return confirm( "The form check has failed: " + e + " Are you sure you want to continue?");
    }
    
}

function checkMandatory() {
    for (i=0;i< document.forms['vmForm'].elements.length;i++) {
        formElement = document.forms['vmForm'].elements[i];
        if(formElement.disabled==true)
            continue;
        
        mandatory = false;
        label = formElement.name;
        if ("yes" == mandatories[formElement.name]) {
            mandatory = true;
            label = manLabels[formElement.name];
        }
        if (formElement.attributes && formElement.attributes['mandatory'] && "yes" == formElement.attributes['mandatory'].value){
            mandatory = true;
            label = "\""+document.getElementById( formElement.name+"_label" ).innerHTML +"\"";
        }
        if (!mandatory){
            continue;
        }
        
        if (formElement.type == 'select-one') {
            if ((formElement.options == null) || (formElement.options.length == 0)) {
                alert('There is no data available for ' + label + ' therefore this form cannot be submitted');
                return false;
            } else {
            if (formElement.options[formElement.selectedIndex].value==null || formElement.options[formElement.selectedIndex].value=="" ) {
                alert('Please fill in a value for ' + label);
                return false;
            }
        }
    } else {
    if (formElement.value == '') {
        alert('Please fill in a value for ' + label);
        return false;
    }
}
}
return true;
}

function  checkIfAlreadyPresent(elementId){
    if(document.getElementById(elementId)==null)
        return false;     
    else
        return true;
}

function popup(url,name,width, height) {
    if (width == null) {
        width = 650;
    }
    if (height == null) {
        height = 500;
    }
    if(name==null){
        name="popup";
    }
    var win = window.open(url,name, "toolbar=no,scrollbars=yes,width=" + width + ",height=" + height + ",location=no,directories=no,status=yes,menubar=no,resizable=yes");
    return win;
}

function popupText(field) {
    var win = popup('../fieldText.jsp?field='+field, 700, 350);
    try{
        win.document.forms['fieldText'].theText.value = this.document.forms['vmForm'].elements[field].value;
        win.document.forms['fieldText'].field.value = field;
    }
    catch(exception){
    }   
}

//- helper script that uses the calendar -->   
var oldLink = null;
// code to change the active stylesheet
function setActiveStyleSheet(link, title) {
    var i, a, main;
    for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
        if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
            a.disabled = true;
            if(a.getAttribute("title") == title) a.disabled = false;
        }
    }
    if (oldLink) oldLink.style.fontWeight = 'normal';
    oldLink = link;
    link.style.fontWeight = 'bold';
    return false;
}

// This function gets called when the end-user clicks on some date.
function selected(cal, date) {
    cal.sel.value = date; // just update the date in the input field.
    if (cal.sel.id == "sel1" || cal.sel.id == "sel3")
        // if we add this call we close the calendar on single-click.
    // just to exemplify both cases, we are using this only for the 1st
    // and the 3rd field, while 2nd and 4th will still require double-click.
    cal.callCloseHandler();
    if(cal.sel.name.indexOf("*")!=-1){
        copyDate(cal.sel,cal.sel.form);    
    }
}
// And this gets called when the end-user clicks on the _selected_ date,
// or clicks on the "Close" button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
    cal.hide();                        // hide the calendar
}

function popToday(id) {
    // Find the element named
    var el = document.getElementById(id);
    // Populate it with today's date...
    if (el != null) {
        el.value = "today";
    }
    // Ideally we'd like to show the real date but this will do for now.
}

function popTomorrow(id) {
    // Find the element named
    var el = document.getElementById(id);
    // Populate it with tomorrow's date...
    if (el != null) {
        el.value = "tomorrow";
    }
    // Ideally we'd like to show the real date but this will do for now.
}


// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar(id, format) {
    var el = document.getElementById(id);
    if (calendar != null) {
        // we already have some calendar created
        calendar.hide();                 // so we hide it first.
    } else {
    // first-time call, create the calendar.
    var cal = new Calendar(false, null, selected, closeHandler);
    // uncomment the following line to hide the week numbers
    // cal.weekNumbers = false;
    cal.mondayFirst = true;
    calendar = cal;                  // remember it in the global var
    cal.setRange(2003, 2070);        // min/max year allowed.
    cal.create();
}
calendar.setDateFormat(format);    // set the specified date format
calendar.parseDate(el.value);      // try to parse the text in field
calendar.sel = el;                 // inform it what input field we use
calendar.showAtElement(el);        // show the calendar below it

return false;
}

var MINUTE = 60 * 1000;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var WEEK = 7 * DAY;

// If this handler returns true then the "date" given as
// parameter will be disabled.  In this example we enable
// only days within a range of 10 days from the current
// date.
// You can use the functions date.getFullYear() -- returns the year
// as 4 digit number, date.getMonth() -- returns the month as 0..11,
// and date.getDate() -- returns the date of the month as 1..31, to
// make heavy calculations here.  However, beware that this function
// should be very fast, as it is called for each day in a month when
// the calendar is (re)constructed.
function isDisabled(date) {
    var today = new Date();
    return (Math.abs(date.getTime() - today.getTime()) / DAY) > 10;
}

function flatSelected(cal, date) {
    var el = document.getElementById("preview");
    el.innerHTML = date;
}
function showFlatCalendar() {
    var parent = document.getElementById("display");
    
    // construct a calendar giving only the "selected" handler.
    var cal = new Calendar(false, null, flatSelected);
    
    // hide week numbers
    cal.weekNumbers = false;
    
    // We want some dates to be disabled; see function isDisabled above
    cal.setDisabledHandler(isDisabled);
    cal.setDateFormat("DD, M d");
    
    // this call must be the last as it might use data initialized above; if
    // we specify a parent, as opposite to the "showCalendar" function above,
    // then we create a flat calendar -- not popup.  Hidden, though, but...
    cal.create(parent);
    
    // ... we can show it here.
    cal.show();
}


var prefillArray = new Array();
var prefillNameArray = new Array();
function prefill() {
    var len = prefillNameArray.length;
    if ( len == 0 ){
        alert( 'There are no previous values available.' );
    }
    // alert('len = ' + len);
    for (i=0; i<len; i++) {
        var name = prefillNameArray[i];
        // alert('name[' + i + '] = ' + name);
        var el = document.forms['vmForm'].elements[name];
        if (el == null) {
            continue;
        }
        if ((el.type == 'text') || (el.type == 'textarea') || (el.type == 'hidden')) {
            el.value = prefillArray[name];
            // alert('el.value = ' + el.value);
        }
        else if (el.type == 'select-one') {
            var ellen = el.options.length;
            for (j=0; j<ellen; j++) {
                if (el.options[j].value == prefillArray[name]) {
                    el.selectedIndex = j;
                }
            }
        } 
        else {
            // alert('el.type = ' + el.type);
        }
    }
}


function sendHidden(arg,returnTo) {
    var hid = allHiddens[arg];
    for (i in hid) {
        // alert('i = ' + i);
        // alert('val = ' + hid[i]);
        // Translate i (e.g. Person.phone1.theNumber) into the parent
        // field, which will be e.g. Tenancy.tenant.phone1.theNumber
        var shortI = i.substring(i.indexOf('.'));
        if (returnTo != null) {
            shortI = returnTo + shortI;
        }
        
        var element = window.opener.document.forms['vmForm'].elements[shortI];
        if (element == null) {
            element = window.opener.document.forms['vmForm'].elements['_' + shortI];
        }
        else {
            element.name = '_' + element.name;
        }
        if (element != null) {
            element.value = hid[i];
            element.disabled = true;
        }
    }
}

function untickAll() {
    var els = document.forms.refineForm.elements;
    // alert('Testing with els ' + els.length);
    var i=0;
    for (i=0; i<els.length; i++) {
        var el = els[i];
        // alert('Testing el.name ' + el.name + ' ' + el.type);
        if (el.name == null) {
            continue;
        }
        if (el.name.substring(0, 5) == 'keep.' && (el.type == 'checkbox')) {
            // alert('Unchecked ' + el.name + ' ' + el.type);
            el.checked = false;
        }
        else {
            // alert('Not unchecked ' + el.name + ' ' + el.type);
        }
    }
}


function toggleTicks(box) {
    
    var els = document.forms.refineForm.elements;
    // alert('Testing with els ' + els.length);
    var i=0;
    for (i=0; i<els.length; i++) {
        var el = els[i];
        // alert('Testing el.name ' + el.name + ' ' + el.type);
        if (el.name == null) {
            continue;
        }
        if (el.name.substring(0, 5) == 'keep.' && (el.type == 'checkbox')) {
            // alert('Unchecked ' + el.name + ' ' + el.type);
            el.checked = box.checked;
        }
        else {
            // alert('Not unchecked ' + el.name + ' ' + el.type);
        }
    }
    
}


function getExpressions(type){
    if("decimal" ==  type){
        return /^[-+]?[0-9]+(\.[0-9]+)?$/;
    } 
    if("integer" ==  type ){
        return /^[0-9]*$/;
        
    }
    if("currency" ==  type ){
        return  /^[1-9][0-9]{0,2}(,[0-9]{3})*(\.[0-9]{2})*$/;
    }
    return "";
    
}
function validateInput(element,type){
    str = element.value;
    if(!(getExpressions(type).test(str))){
        alert("Invalid input!\nValue entered must be of a "+type+" format.");
        element.value="";
        return false;
    }
    return true;
}

function validateEmail(element) {
    
    var at="@"
    var dot="."
    var str=element.value;
    var lat=str.indexOf(at)
    var lstr=str.length
    var ldot=str.indexOf(dot)
    if (str.indexOf(at)==-1){
        alert("Invalid E-mail ID!\nEmail must contain '@'");
        element.value="";
        return false
    }
    
    if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr-1){
        alert("Invalid E-mail ID!\nThe '@' must not be in the beginning or end of the E-mail ID");
        element.value="";
        return false
    }
    
    if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.lastIndexOf(dot)==lstr-1 ){
        alert("Invalid E-mail ID!\nThe '.' must not be in the beginning or end of the Email ID");
        element.value="";
        return false
    }
    
    if (str.indexOf(at,(lat+1))!=-1){
        alert("Invalid E-mail ID!\nThere can only be one '@'");
        element.value="";
        return false
    }
    
    if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
        alert("Invalid E-mail ID!\nPlease enter a domain" );
        element.value="";
        return false
    }
    
    if (str.indexOf(dot,(lat+2))==-1){
        alert("Invalid E-mail ID!\nThe domain entered is incorrect");
        element.value="";
        return false
    }
    
    if (str.indexOf(" ")!=-1){
        alert("Invalid E-mail ID!\nSpaces are not allowed ");
        element.value="";
        return false
    }
    
    return true					
}

