﻿// Copyright 2011 Astrium Software Solutions All Rights Reserved.

/**
* @fileoverview Description of file, its uses and information
* about its dependencies.
* @author cornebeukes@astrium.co.za (Corne Beukes)
*/

var ctScripts = [];     // scripts to execute when a tab is closed
var verbsInt = [];      // verbs that the tab is interested in, receiving a broadcast from a matching verb will result in a call to the object
var tabs = [];          // tabs array keeps count of open tabs
var tabcount = -1;
var selected = -1;
var currtab = '';
var busyCount = 0;      // monitor how many requests are being made to the server, if count = 0 then the loading indicator div will be hidden
var modalContinue;      // will monitor if a form has validated
var lastPage = 0;
var swfu;


// register starting events for page
document.observe('dom:loaded', function () {
    SetTooltip('tab_menu');
    SetTooltip('tab_close');
    Event.observe('tab_menu', 'click', showTabMenu);
    Event.observe('tab_close', 'click', removeSelectedTab); // click on close tab icon

    shortcut.add('Ctrl+X', function () { removeSelectedTab(); }, { 'disable_in_input': true });
    shortcut.add('Backspace', function () { previousTab(); }, { 'disable_in_input': true });

    getObjectResponse(0, 300, '', '', '', '');       // start page with login object 170
    addListener(0, 32, 'om_getnotify', '', 300);    // check for new messages every 5 minutes
    new PeriodicalExecuter(function (e) { removeTooltips(); }, 10);  // remove stuck tooltips
});


// validate data entered
function validateobject(checks, fields, descs) {
    modalContinue = true;
    for (var i = 0; i < checks.length; i++) {
        if (checks[i] == "validdate") { if (!validation.validDate($(fields[i]), descs[i])) { modalContinue = false; return false; } }
        if (checks[i] == "validEmail") { if (!validation.validEmail($(fields[i]), descs[i])) { modalContinue = false; return false; } }
        if (checks[i] == "validPassword") {
            if (!validation.validPassword($(fields[i]))) {
                modalContinue = false;
                return false;
            }
        }
        if (checks[i] == "numeric") { if (!validation.validNumber($(fields[i]), descs[i])) { modalContinue = false; return false; } }
        if (checks[i] == "nonblank") { if (!validation.nonBlank($(fields[i]), descs[i])) { modalContinue = false; return false; } }
        if (checks[i] == "selected") { if (!validation.itemSelected($(fields[i]), descs[i])) { modalContinue = false; return false; } }
    }
    return true;
}


function toggleDisplay(from, target) {
    if ($(from).hasClassName('rollup_hide')) {
        $(from).removeClassName('rollup_hide');
        Effect.BlindDown(target);
    }
    else {
        $(from).addClassName('rollup_hide');
        Effect.BlindUp(target);
    }
}


function setHidden(from, target) {
    if ($(from).hasClassName('rollup_hide')) {
        $(from).removeClassName('rollup_hide');
        $(target).show();
    }
    else {
        $(from).addClassName('rollup_hide');
        $(target).hide();
    }
}


// get initials from 'from' input and overwrite 'to' with them
function getInitials(from, to) {
    var letters = $(from).value.toArray();

    if (letters) {
        var antw = letters[0];

        for (var i = 1; i < letters.length; i++) {
            if (letters[i] == ' ') {
                antw = antw + letters[i + 1];
            }
        }
    }
    $(to).value = antw;
}


function updateCombo(id, ref, extra) {
    $('indicator_' + id).show();
    new Ajax.Request('query.aspx?type=combo&value=' + $(ref).value + '&extra=' + extra, { onComplete: function(transport) { getComboData( transport, id);}, onFailure: displayFail });
}


function updateModalBox(id, ref, extra) {
    new Ajax.Request('query.aspx?type=layout&value=' + $(ref).value + '&extra=' + extra, { onComplete: function(transport) { updateMB(transport, id); }, onFailure: displayFail });
}


function updateMB(transport, id) {
    $('mblo_' + id).innerHTML = transport.responseText;
}


// respond to clicks on a dropdown table
// e        element clicked on
// otid     object type
// verb     verb to perform
function getClick(e, otid, verb) {
    if (!e.hasClassName('li_delete') && !e.hasClassName('li_edit')) {
        var row = $(e).findElement('tr');
        if (row) {
            var id = row.down('input');
            getObjectResponse(id.value, otid, verb, '', '', '');
        }
    }
}             


function getComboData( transport, id) {
        //alert( qry);
        var opt;
        var fieldid;
        var fieldname;
        var sel = document.getElementById(id);

        // remove existing items
        for (var i = 0; i < sel.options.length; i++) {
            sel.options[0] = null;
        }

        sel.innerHTML = transport.responseText;
        $('indicator_' + id).hide();
}


// handle the event when an item is selected in an autupdater control
function getSelectionId(text, li) {
    var ccid = text.id.gsub('auto_', '');
    if ($(ccid).value == '' || $(ccid).value == '0') {
        $(ccid).value = li.id;
    }
    else {
        //$(ccid).value = $(ccid).value + ', ' + li.id;
        $(ccid).value = li.id;
    }
}


// return the ids of all the rows with the selected classname
function enumSelected(table) {
    var selList = "";
    
    $$('#' + table + ' tbody tr').each(function(tr) {
        if (tr.hasClassName('selected')) {
            selList += tr.id + ';';
        }
    });
    return selList;
}


// return the ids of all the checkboxes checked in a tableview table
function enumSelected2(table) {
    var selList = "";

    $$('#' + table + ' tbody tr').each(function (tr) {
        if (tr.hasClassName('tdata')) {
            var checkbox = tr.down('input');
            if (checkbox) {
                if (checkbox.checked) {
                    selList += checkbox.id + ';';
                }
            }
        }
    });

    if (selList == '') {
        selList = '-1';
        alert('Nothing selected');
    }   
    
    return selList;
}


// return the values describing signatures added to a document
function enumSelected3(table) {
    var selList = "";
    var x;
    var y;
    var p;

    $$('#' + table + ' tbody tr').each(function(tr) {

        var cell = tr.down(1);
        x = cell.down(0).value;
        y = cell.down(1).value;
        p = cell.down(4).value;

        selList += x + ';' + y + ';' + p + ';';
    });

    if (selList == '') {
        selList = '-1';
        alert('No signatures added.');
    }


    return selList;
}


// check or uncheck all the checkboxes in the tablebody of the given tableview table
function selectRows(table, status) {
    $$('#' + table + ' tbody tr').each(function (tr) {
        if (tr.hasClassName('tdata')) {
            var checkbox = tr.down('input');
            if (checkbox) {
                checkbox.checked = status;
            }
        }
    });
}


// create a new listener objects that queries the given object periodically
function addListener(ob_id, ot_id, verb, param1, seconds) {
    new PeriodicalExecuter(function(e) { getObjectResponse(ob_id, ot_id, verb, param1); }, seconds);
}


// create a new listener objects that queries the given object periodically
function wrapListener(ob_id, ot_id, verb, param1, seconds) {
    new PeriodicalExecuter(function(e) { if ($('objview_' + ob_id + '_' + ot_id)) { getObjectResponse(ob_id, ot_id, verb, $(param1).value); } else { e.stop(); } }, seconds);
}


// add a nice looking tooltip for the given element
function SetTooltip(e) {
    new Tooltip($(e), { backgroundColor: "#333", borderColor: "#333", textColor: "#FFF", textShadowColor: "#000" });
}


// add tooltips to elements referenced by the css selector
function SetTooltips(selector) {
    $$(selector).each(function(e) { SetTooltip(e); });
}


function removeTooltips() {
    $$('.tooltip').each(function(e) { e.remove(); });
}


// handle table displayed in modal box
function checkModalTable(form, table, verb, multi, hide) {
    Event.observe(table, 'click', function(e) {
        if (multi == false) {
            $$('#modaltable tbody tr.selected').each(function(tr) {
                tr.toggleClassName('selected');
                tr.down('td').down('input').checked = false;
            });
        }
        var row = e.findElement('tbody tr');
        if (row) {
            var checkbox = row.down('input');
            if (e.target != checkbox) checkbox.checked = !checkbox.checked;
            row.toggleClassName('selected');
        }
    }).select('input').each(function(input) {
        if (input.getValue()) input.up(1).addClassName('selected');
    })

    Event.observe($('modalOk'), 'click', function () {
        $$('#modaltable tbody tr.selected').each(function (tr) {
            var hiddenData = $('hidden').value;

            getObjectResponse($('mt_ob_id').value, $('mt_ot_id').value, verb, tr.down('input').value, hiddenData, $('mt_st_id').value);
            if (hide) {
                Modalbox.hide();
            }
        });
    });
     
    Event.observe( $('modalCancel'), 'click', function() { Modalbox.hide(); });
}


function GetFormValues(obid, otid, verb, formId) {
    var formFields = '';
    var formValues = '';

    $(formId).getElements().each(function (e) {



    });

    getObjectResponse(obid, otid, verb, formFields, formValues);
}


// add an event to catch submit from the form
function checkModalForm(frm, verb, hide) {
    Event.observe($('modalOk'), 'click', function() {
        if (modalContinue) {
            var formfields = '';
            var formvalues = '';
            var ob_id, ot_id, st_id;
            var elValue;

            $(frm).getElements().each(function(e) {
                if (e.id != 'mt_ob_id' && e.id != 'mt_ot_id' && e.id != 'mt_st_id' && e.id != 'modalOk' && e.id != 'modalCancel') {
                    formfields += e.id + ';';
                    if (e.type == 'checkbox') {
                        if (e.checked) {
                            elValue = 1;
                        }
                        else {
                            elValue = 0;
                        }
                    }
                    else {
                        elValue = e.value;
                        elValue = elValue.gsub('\x27', '~ap') // disguise apostrophes as ~ap, this is to ensure that jscript does not break
                        elValue = elValue.gsub('\x2C', '~co') // disguise commas as ~co
                        elValue = elValue.gsub('\x26', '~am') // disguise ampersand as ~am
                        elValue = elValue.gsub('\x3B', '~sc') // disguise semicolon as ~sc
                        elValue = elValue.gsub('\x3C', '~lt') // disguise less than as ~lt
                        elValue = elValue.gsub('\x3E', '~gt') // disguise greater than as ~gt
                    }
                    
                    formvalues += elValue + ';';
                }
            });

            ob_id = $(frm).down('#mt_ob_id').value;
            ot_id = $(frm).down('#mt_ot_id').value;
            st_id = $(frm).down('#mt_st_id').value;

            getObjectResponse(ob_id, ot_id, verb, formfields, formvalues, st_id);
        }

        if (hide && modalContinue) {
            Modalbox.hide();
        }
    });
    
    Event.observe($('modalCancel'), 'click', function() { Modalbox.hide(); });
}


// retrieves the data for the object referenced by the given id
function getObjectResponse(obid, otid, verb, param1, param2, param3) {

    var params = 'requests.aspx?obid=' + obid + '&otid=' + otid + '&verb=' + verb + '&param1=' + param1 + '&param2=' + param2 + '&param3=' + param3;

    if (verb == "download" || verb == "dlreadonly" || verb == 'dllayout' || verb == 'multiemail' || verb == 'pickingslip' || verb == 'invoice') {
        $('if1').src = params;
    }
    else {
        if (verb != 'refresh') {
            incLoadingStatus();
        }
        new Ajax.Request(params, { onSuccess: updateObject, onFailure: function (e) { displayFail(e) } });
    }
}


function displayFail(transport) {
    if (transport.status == 500) {
        decLoadingStatus();
        var elValue = transport.responseText;
        elValue = elValue.gsub('\x27', '~ap') // disguise apostrophes as ~ap, this is to ensure that jscript does not break
        elValue = elValue.gsub('\x2C', '~co') // disguise commas as ~co
        elValue = elValue.gsub('\x26', '~am') // disguise ampersand as ~am
        elValue = elValue.gsub('\x3B', '~sc') // disguise semicolon as ~sc
        elValue = elValue.gsub('\x3C', '~lt') // disguise less than as ~lt
        elValue = elValue.gsub('\x3E', '~gt') // disguise greater than as ~gt

        getObjectResponse(0, 24, 'err', transport.statusText, '', '');        
    }
}


// modify getObjectResponse parameters for certain verbs
function wrapResponse(obid, otid, verb, verb2, param1, param2) {
    var result = param1;
    var result2 = param2;
    
    switch (verb2) {
        case 'elementvalue':
            result = $(param1).value;
            break;

        case 'selectvalue':
            result = $(param1).SelectedIndex();
            break;
            
        case 'enumselected':
            result = enumSelected(param1);
            break;
            
        case 'enumselected2':
            result = enumSelected2(param1);
            break;

        case 'enumselected3':
            result = enumSelected3(param1);
            break;

        case "changepw":
            result = checkPassword();
            result2 = $('oldpw').value;
            break;
            
        default:            
            break;
    }
    if (result != '-1') {
        getObjectResponse(obid, otid, verb, result, result2);
    }
}


function clearDates() {
    datePickerController.cleanUp();
}


function replaceControlWords(text) {
    text = text.gsub('~ap', '\x27');
    text = text.gsub('~co', '\x2C');
    text = text.gsub('~am', '\x26');
    text = text.gsub('~sc', '\x3B');
    text = text.gsub('~euml', '\xEC');
    text = text.gsub('~ecirc', '\xEB');
    text = text.gsub('~or', 'getObjectResponse');
    text = text.gsub('~eo', 'Event.observe');

    text = text.gsub('~lt', '\x3C');
    text = text.gsub('~gt', '\x3E');
    

    return text;
}   


// unregister events for element and child elements
function unReg(el) {
    if($$(el)){
    Event.stopObserving($$(el + '.*'));
    }
}


// callback function that evaluates the object's response and acts accordingly
// 2009-04-25 changed to accept more than one command
function updateObject(transport) {
    var cmdCount = 1;
    var verb;
    var body;
    var obid;
    var script;
    var title;
    var loc;
    var close;
    var broadcast;
    var verbsInterestedIn;

    try {
        $('div_default').hide();

        if (transport.responseText != '' && transport.responseText != "") {
            if (transport.status == 500) {
                getObjectResponse(0, 24, '', 'Internal Server Error', transport.responseText, '');
            }
            else {

                var respText = transport.responseText.gsub('"', '\\"').gsub( '\'', '"');
				respText = respText.replace(/(\r\n|\n|\r)/gm, " ");
                respText = respText.replace(/\s+/g, " ");

                var json = respText.evalJSON();

                // retrieve the number of commands to perform
                if (json.cmdCount) {
                    cmdCount = eval(json.cmdCount);
                }
                else {
                    cmdCount = 0;
                }

                for (var i = 0; i < cmdCount; i++) {
                    script = eval('json.script_' + i);
                    verb = eval('json.verb_' + i);
                    obid = eval('json.obid_' + i);
                    loc = eval('json.loc_' + i);
                    
                    broadcast = eval('json.broadcast_' + i);
                    
                    verbsInterestedIn = eval('json.verbint_' + i);                    
                    if (!verbsInterestedIn) {
                        verbsInterestedIn = '';
                    }
                    verbsInterestedIn = replaceControlWords(verbsInterestedIn);


                    body = eval('json.body_' + i);
                    if (body) {
                        body = replaceControlWords(body);
                    }                    


                    title = eval('json.title_' + i);
                    if (title) {
                        title = replaceControlWords(title);
                    }                    


                    close = eval('json.close_' + i);
                    if (close) {
                        close = replaceControlWords(close);
                    }


                    // actions that can be performed
                    if (verb == 'showmodal') {                        
                        Modalbox.show(body, { 'title': title, width: 850, afterHide: clearDates });                         
                    }


                    if (verb == 'list') {
                        $('objright_' + obid).innerHTML = body;
                    }


                    if (verb == 'inject') {
                        unReg(loc + '_cleanup');
                        if ($(loc)) {
                            $(loc).innerHTML = body;
                        }
                    }


                    if (verb == 'replace') {
                        $(loc).replace(body);
                    }


                    if (verb == 'close') {
                        removeSelectedTab();
                        if (body != '0') {
                            getObjectResponse(obid, body, '', '', '', '');
                        }
                    }


                    if (verb == 'caption') {
                        $('t_objview_' + obid).innerHTML = body;
                    }


                    if (verb == 'closeall') {
                        removeAllTabs(true);                        
                        getObjectResponse(obid, body, '', '', '', '');
                    }


                    if (verb == 'display') {
                        if ($('objview_' + obid)) { $('objview_' + obid).remove(); }    // remove content if it exists
                        addTab(title, 'objview_' + obid, close, verbsInterestedIn);   // create tab for new content
                        $('obj_body').insert(body);
                        $('tab_menu').show();   // show menu and close tab buttons if not visible                        
                        $('tab_close').show();
                    }


                    if (verb == 'update') {
                        if ($('objview_' + obid)) { $('objview_' + obid).remove(); }
                        $('obj_body').insert(body);
                    }


                    if (script) {
                        script = replaceControlWords(script);
                        eval(script);
                    }


                    // check if there are any tabs interested in the verb
                    if (broadcast) {
                        broadCastVerb(broadcast);
                    }
                }
            }
        }
    }
    catch (e) {
        // display an error page;
        getObjectResponse(0, 24, '', e.message, '', '');
    }
    decLoadingStatus();
}




// iterate through tabs and check for interest in the verb being broadcasted
function broadCastVerb(verbToBroadcast) {
    var verbsInterestedIn;
    var obid;
    var otid;
    var values;
    var params;
    var param1;
    var vb = verbToBroadcast.replace('~sc', ';').split(';');

    for (var i = 0; i < tabs.length; i++) {
        verbsInterestedIn = verbsInt[i].split(';');

        for (var j = 0; j < verbsInterestedIn.length; j++) {
            // check if verb has parameters and strip it
            params = verbsInterestedIn[j].split('_');

            if (params.length > 1) {
                param1 = params[1];
            }
            else {
                param1 = '';
            }


            // check or each bradcasted verb
            for (var k = 0; k < vb.length; k++) {
                if (params[0] == vb[k]) {    // found a verb the tab is listening for, make a call to the object
                    values = tabs[i].split('_');
                    obid = values[1];
                    otid = values[2];

                    getObjectResponse(obid, otid, vb[k], param1, '');
                }
            }
        }
    }
}


