function delete_flight_confirmation( daily_flight_id ){
    if( confirm( 'You are about to delete a flight.  Deleted records CANNOT BE RECOVERED!  Click OK if you are sure.') ){
        $('flights_view_frm').view_type.value = 'delete';
        $('flights_view_frm').id.value = daily_flight_id;
        $('flights_view_frm').submit();
    }
    return false;
}

function open_user_cardit_itinerary( event ){
    form_data = new Array( 7 );
    for( i = 1 ; i <= 7 ; i++ ){
        if( $( 'prorate_origin_' + i ).value ){
            form_data[i] = $( 'prorate_origin_' + i ).value + ":" + $( 'prorate_destination_' + i ).value;
        }
    }
    setPopupDivVars( '../index.php/user_cardit_itinerary?action=add_from_prorated_rules&sans_header=1&form_data=' + form_data, event, [] );
    popPopupWithDelay( true, 10 );

}

function user_cardit_itinerary_ajax_submit_and_validate(){
    if( validate_user_cardit_itinerary_form() ){
        $( 'ajax_spinner_user_itinerary' ).innerHTML = "<img src='../images/spinner.gif' />";
        new Ajax.Request( 'user_cardit_itinerary?action=save',{
            parameters: $( 'user_itinerary' ).serialize(),
            onComplete: function( response, data ){
                $( 'ajax_spinner_user_itinerary' ).innerHTML = "";
                alert( data.message );
                if( ! data.dups ){
                    Effect.Fade( $( "tooltipMessage" ) );
                }
            }
        })
    }
}

function user_cardit_do_we_have_dow(){
    var f = document.forms[1];
    for(var i=0; i < f.elements.length;i++){
        if(f.elements[i].type=="checkbox"){
            if(f.elements[i].checked){
              return true;
            }
        }
    }
    return false;
}

function validate_user_cardit_itinerary_form(){
    message = '';
    at_least_one_leg = false;

    for(i=1; i <= 7 ; i++){

        carrier = $("leg_" + i + "_carrier").value;
        if(carrier){
            at_least_one_leg = true;
            if( ! carrier.match(/[a-zA-Z0-9]{2,3}/)){
                message += "Leg " + i + " carrier is invalid.\n";
            }
        }

        flight = $("leg_" + i + "_flight_no").value;
        if(flight){
            if( ! flight.match(/[0-9]{1,5}/)){
                message += "Leg " + i + " flight number is invalid.\n";
            }
        }

        origin = $("leg_" + i + "_origin").value;
        if(origin){
            if( ! origin.match(/[a-zA-Z]{3}/)){
                message += "Leg " + i + " origin is invalid.\n";
            }
        }

        if ( i != 7 ) {
            destination = $("leg_" + i + "_destination").value;
            if(destination){
                if( ! destination.match(/[a-zA-Z]{3}/)){
                    message += "Leg " + i + " destination is invalid.\n";
                }
            }
        }
        if(carrier && ! (flight && origin && destination)){
            message += "Leg " + i + " is missing data and cannot be saved.\n";
        }
    }
     if(! at_least_one_leg){
        message += "At least one leg is requried.\n";
    }

    if($("origin_oe").value){
        if( ! $('origin_oe').value.match(/[a-zA-Z]{6}/)){
            message += "Origin OE must be 6 alphanumeric characters.\n";
        }
    }
    else{
        message += "Origin OE is required.\n";
    }

    if($("dest_oe").value){
        if( ! $('dest_oe').value.match(/[a-zA-Z]{6}/)){
            message += "Destination OE must be 6 alphanumeric characters.\n";
        }
    }
    else{
        message += "Destination OE is required.\n";
    }

    if($("scan_loc").value){
        if( ! $('scan_loc').value.match(/[a-zA-Z]{3}/)){
            message += "Scan Location must be 3 alphanumeric characters.\n";
        }
    }
    else{
        message += "Destination OE is required.\n";
    }

    if( ! user_cardit_do_we_have_dow()){
        message += "At least one dow is required.\n";
    }

    if(message){
        alert(message);
        return false;
    }
    return true;
}

function popWindow(url) {
    myWin    = window.open(url, 'Files', 'width=600,height=400,screenX=' + (screen.width-480) + ',screenY=100,scrollbars,resizable')
    myWin.focus()
    return false
}

function popFileWindow(myId) {
    var url    = 'files?id=' + myId;
    myFileWin  = window.open(url, '_blank', 'width=650,height=550,scrollbars,resizable')
    myFileWin.focus()
    return false
}

function openWelcome(mypage) {
    var w      = 650;
    var h      = 450;
    var winl   = (screen.width - w) / 2;
    var wint   = (screen.height - h) / 2;
    var myname = "_blank";
    var scroll = "yes";

    winprops = 'height=' + h + ',width=' + w + ',top=' + wint + ',left=' + winl + ',scrollbars=' + scroll + ',resizable';
    win = window.open(mypage, myname, winprops);
}

clr = new Array('yellow','white','silver');
function highlight(state) {
    element=event.srcElement;
    if (element.tagName=='input' || element.tagName=='select' || element.tagName=='option') {
        etype = element.type;
        if ((etype=='submit' || etype=='reset') && state==1) state=2;
        element.style.backgroundColor=clr[state];
        element.focus();
    }
}

function DisableText(form_name, disabler)
{
    // Will disable all form elements between elements with id = 'start_dis' and id = 'stop_dis';
    var count = form_name.elements.length;
    var inloop;

    for (i=0; i<count; i++)
    {
        var element = form_name.elements[i];
        if (element.id == 'start_dis') {
            inloop = true;
        }

        if (inloop) {
            if (element.disabled == false) {
                if (element.type != 'submit' && element.type != 'hidden') {
                    if (element.name != disabler.name)
                    {
                        element.disabled=true;
                    }
                }
            }
            else {
                element.disabled=false;
            }
        }

        if (element.id == 'stop_dis') {
            inloop = false;
        }

    }
}

function clearIt(form){
    if(form == "img"){
        var layer = (nn4) ? document.steroidForm : browser("steroidForm")
            var form = (nn4) ? layer.document.forms[0] : document.forms[0]
    }
    var confirmit = confirm("To clear visible form elements, press OK. To start over, press Cancel.")
        if(confirmit){
            for(i=0; i<form.elements.length; i++){

                with(form.elements[i]){

                    if(type == "text" || type == "textarea" || type == "password"){
                        value = ""
                    }
                    else if(type.indexOf("select") > -1){
                        for(o=0; o<options.length; o++){

                            if(type == "select-multiple"){
                                options[o].selected = false
                            }
                            else if(name == "*Month and Day"){
                                if(options[o].value == months[month] || options[o].value == date){
                                    selectedIndex = o
                                }
                            }
                            else if(disabled == true) {
                            }
                            else{
                                selectedIndex = 0
                            }

                        }
                    }

                    checked = false
                }// end with
            }//end for

        }
        else{
            location.reload(true)
        }
    }

function confirmSubmit(ask)
{
    if (! ask ) {
        ask = 'Are you sure you want to continue?'
    }
    var agree=confirm(ask);
    if (agree)
        return true ;
    else
        return false ;
}


/* sync*() is used to synchronize the front-end drop-down with hidden multiple-select listbox,
 * to achieve the multi-select drop-down box effect. Used in post office and carrier select boxes.
 * Can be used elsewhere as well.
 */
function syncReal(disp_id, real_id, submit)
{
    var real = document.getElementById(real_id);
    var disp = document.getElementById(disp_id);

    var k = disp.selectedIndex - 1;
    if (k >= 0) {
        real.options[k].selected = !(real.options[k].selected);
    }

    if (submit) {
        real.form.submit();
        return;
    }

    disp.selectedIndex = 0; // always deselect, to work around the bug of option not being cleared when the same option is clicked twice in a row

    if (k >= 0) {
        if (real.options[k].selected) {
            disp.options[k + 1].style.backgroundColor = '#666666';
            disp.options[k + 1].style.color = '#FFFFFF';
        } else {
            disp.options[k + 1].style.backgroundColor = '#FFFFFF';
            disp.options[k + 1].style.color = '#000000';
        }
    }
}

function syncDisp(disp_id, real_id)
{
    var real = document.getElementById(real_id);
    var disp = document.getElementById(disp_id);

    var title = '';

    for (i = 0; i < real.options.length; i++) {
        j = i + 1; // matching index on display, which has one extra option at the beginning
        if (real.options[i].selected) {
            disp.options[j].style.backgroundColor = '#666666';
            disp.options[j].style.color = '#FFFFFF';
        } else {
            disp.options[j].style.backgroundColor = '#FFFFFF';
            disp.options[j].style.color = '#000000';
        }
    }
}

function updateControl(control_id,store_id)
{
    // we are synchronizing store to control. this needs to happen when we load a form for the first time.

    // the purpose of this function is to synchronize two selection lists.
    // control is where the user makes selections, and store is a hidden list where the selections are stored.
    // store drives the submitted form data, and also is used to populate a tooltip box, thereby giving the user
    // a tooltip box that displays what they have selected from the control.
    // functions "syncDisp" and "syncReal" implement this same strategy in another way, and preceed this implementation.
    // this new implementation was needed because of new requirements for the postal authority maint.

    // this allows users to make selections from a large control selection list,
    var control    = document.getElementById(control_id);
    var store      = document.getElementById(store_id);

    for (i = 0; i < store.options.length; i++) {

        j = i + 1; // matching index on control, which has one extra option at the beginning

        // get the correct colors for control
        if (store.options[i].selected) {
            control.options[j].style.backgroundColor = '#666666';
            control.options[j].style.color = '#FFFFFF';
        } else {
            control.options[j].style.backgroundColor = '#FFFFFF';
            control.options[j].style.color = '#000000';
        }
        control.selectedIndex = 0;
    }
}

function updateStore(control_id,store_id)
{
    // the purpose of this function is to synchronize two selection lists.
    // control is where the user makes selections, and store is a hidden list where the selections are stored.
    // store drives the submitted form data, and also is used to populate a tooltip box, thereby giving the user
    // a tooltip box that displays what they have selected from the control.
    // functions "syncDisp" and "syncReal" implement this same strategy in another way, and preceed this implementation.
    // this new implementation was needed because of new requirements for the postal authority maint.

    // this allows users to make selections from a large control selection list,
    var control    = document.getElementById(control_id);
    var store      = document.getElementById(store_id);

    var title = '';

    var ci = control.selectedIndex;
    var si = ci -1; // matching index on control, which has one extra option at the beginning

    if (ci != -1 && si != -1) { // -1,  indicates that nothing is selected, so don't try to set anything or we'll get an error.
        if ( store.options[si].selected) {
            // if selection already exists, remove it.
            store.options[si].selected =  false;
        }
        else {
            // if selection does not exist, add it.
            store.options[si].selected = control.options[ci].selected;
        }
    }

    for (i = 0; i < store.options.length; i++) {

        j = i + 1; // matching index on control, which has one extra option at the beginning

        // if control selected index is -1, we need to clear store.
        if (ci == -1) {
            store.options[i].selected =  false;
        }

        // get the correct colors for control
        if (store.options[i].selected) {
            control.options[j].style.backgroundColor = '#666666';
            control.options[j].style.color = '#FFFFFF';
        } else {
            control.options[j].style.backgroundColor = '#FFFFFF';
            control.options[j].style.color = '#000000';
        }
        control.selectedIndex = 0;
    }
}

function multidropdown_showTip(short_name)
{
    var tip = document.getElementById(short_name + '_tip');
    var real = document.getElementById(short_name);
    if (tip.innerHTML = getSelections(real)) {
        tip.style.display = 'inline';
    }
}

function getSelections(sel)
{
    var str = '';
    for (var i = 0; i < sel.options.length; i++) {
        var opt = sel.options[i];
        if (opt.selected) {
            str += opt.text + '<br />';
        }
    }

    return str;
}

function realPreviousSibling(node){
    var tempNode=node.previousSibling;
    while(tempNode.nodeType!=1){
        tempNode=tempNode.previousSibling;
    }
    return tempNode;
}

function checkAll(f, id_match)
{
    // For each element on the form
    for(i=0;i<f.elements.length;i++) {
        // If the element is a checkbox
        if(f.elements[i].type=="checkbox") {
            // Set the checkbox to checked true
            if ( id_match ) {
                regex = new RegExp('^'+id_match);
                if ( !f.elements[i].id.match(regex) ) {
                    continue
                }
            }

            if (f.elements[i].checked == false) {
                f.elements[i].checked=true;
            }
            else {
                f.elements[i].checked=false;
            }
        }
    }
}

function insertHeader(obj)
{
    var nds = obj.parentNode.childNodes;

    for (var i = 0; i < nds.length; i++) {
        var h = nds[i];
        if (h.tagName == 'thead' || h.tagName == 'THEAD') {
            break;
        }
    }
    var h2 = h.cloneNode(true);
    if (document.all) { // IE
        h2.attachEvent('ondblclick', removeSelf);
    } else { // FireFox
        h2.setAttribute('ondblclick', 'this.parentNode.removeChild(this); return false;');
    }

    h2.title = "Double click to hide";
    obj.parentNode.insertBefore(h2, obj);
    h2.style.display='none';
    Effect.Grow(h2);

    return false;
}

// for the sole purpose of using attachEvent for IE
function removeSelf()
{
    var obj = event.srcElement;
    while (obj.tagName != 'THEAD' && obj.tagName != 'thead') {
        obj = obj.parentNode;
    }
    obj.parentNode.removeChild(obj);
    return false;
}

// show or hide content depending on whether checkbox is checked
// chkbox: controlling checkbox
// elmId: id of the content node
function toggleVis(chkbox, elmId)
{
    elm = document.getElementById(elmId);
    if (chkbox.checked) {
        elm.style.display = '';
    } else {
        elm.style.display = 'none';
    }
}

function sprintf(fstring)
  { var pad = function(str,ch,len)
      { var ps='';
        for(var i=0; i<Math.abs(len); i++) ps+=ch;
        return len>0?str+ps:ps+str;
      }
    var processFlags = function(flags,width,rs,arg)
      { var pn = function(flags,arg,rs)
          { if(arg>=0)
              { if(flags.indexOf(' ')>=0) rs = ' ' + rs;
                else if(flags.indexOf('+')>=0) rs = '+' + rs;
              }
            else
                rs = '-' + rs;
            return rs;
          }
        var iWidth = parseInt(width,10);
        if(width.charAt(0) == '0')
          { var ec=0;
            if(flags.indexOf(' ')>=0 || flags.indexOf('+')>=0) ec++;
            if(rs.length<(iWidth-ec)) rs = pad(rs,'0',rs.length-(iWidth-ec));
            return pn(flags,arg,rs);
          }
        rs = pn(flags,arg,rs);
        if(rs.length<iWidth)
          { if(flags.indexOf('-')<0) rs = pad(rs,' ',rs.length-iWidth);
            else rs = pad(rs,' ',iWidth - rs.length);
          }
        return rs;
      }
    var converters = new Array();
    converters['c'] = function(flags,width,precision,arg)
      { if(typeof(arg) == 'number') return String.fromCharCode(arg);
        if(typeof(arg) == 'string') return arg.charAt(0);
        return '';
      }
    converters['d'] = function(flags,width,precision,arg)
      { return converters['i'](flags,width,precision,arg);
      }
    converters['u'] = function(flags,width,precision,arg)
      { return converters['i'](flags,width,precision,Math.abs(arg));
      }
    converters['i'] =  function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = ((Math.abs(arg)).toString().split('.'))[0];
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        return processFlags(flags,width,rs,arg);
      }
    converters['E'] = function(flags,width,precision,arg)
      { return (converters['e'](flags,width,precision,arg)).toUpperCase();
      }
    converters['e'] =  function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        if(isNaN(iPrecision)) iPrecision = 6;
        rs = (Math.abs(arg)).toExponential(iPrecision);
        if(rs.indexOf('.')<0 && flags.indexOf('#')>=0) rs = rs.replace(/^(.*)(e.*)$/,'$1.$2');
        return processFlags(flags,width,rs,arg);
      }
    converters['f'] = function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        if(isNaN(iPrecision)) iPrecision = 6;
        rs = (Math.abs(arg)).toFixed(iPrecision);
        if(rs.indexOf('.')<0 && flags.indexOf('#')>=0) rs = rs + '.';
        return processFlags(flags,width,rs,arg);
      }
    converters['G'] = function(flags,width,precision,arg)
      { return (converters['g'](flags,width,precision,arg)).toUpperCase();
      }
    converters['g'] = function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        absArg = Math.abs(arg);
        rse = absArg.toExponential();
        rsf = absArg.toFixed(6);
        if(!isNaN(iPrecision))
          { rsep = absArg.toExponential(iPrecision);
            rse = rsep.length < rse.length ? rsep : rse;
            rsfp = absArg.toFixed(iPrecision);
            rsf = rsfp.length < rsf.length ? rsfp : rsf;
          }
        if(rse.indexOf('.')<0 && flags.indexOf('#')>=0) rse = rse.replace(/^(.*)(e.*)$/,'$1.$2');
        if(rsf.indexOf('.')<0 && flags.indexOf('#')>=0) rsf = rsf + '.';
        rs = rse.length<rsf.length ? rse : rsf;
        return processFlags(flags,width,rs,arg);
      }
    converters['o'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = Math.round(Math.abs(arg)).toString(8);
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        if(flags.indexOf('#')>=0) rs='0'+rs;
        return processFlags(flags,width,rs,arg);
      }
    converters['X'] = function(flags,width,precision,arg)
      { return (converters['x'](flags,width,precision,arg)).toUpperCase();
      }
    converters['x'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        arg = Math.abs(arg);
        var rs = Math.round(arg).toString(16);
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        if(flags.indexOf('#')>=0) rs='0x'+rs;
        return processFlags(flags,width,rs,arg);
      }
    converters['s'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = arg;
        if(rs.length > iPrecision) rs = rs.substring(0,iPrecision);
        return processFlags(flags,width,rs,0);
      }
    farr = fstring.split('%');
    retstr = farr[0];
    fpRE = /^([-+ #]*)(\d*)\.?(\d*)([cdieEfFgGosuxX])(.*)$/;
    for(var i=1; i<farr.length; i++)
      { fps=fpRE.exec(farr[i]);
        if(!fps) continue;
        if(arguments[i]!=null) retstr+=converters[fps[4]](fps[1],fps[2],fps[3],arguments[i]);
        retstr += fps[5];
      }
    return retstr;
  }

function CreateMessageBox( box_name, message )
{
    if ( $(box_name) ) {
        $(box_name).remove();
    }
    var html = "<div class='ajax_message' id='" + box_name + "' style='display:none;'>" + message + "</div>";
    new Insertion.Top($('content'), html);

    new Effect.Appear($(box_name));
    return $(box_name);
}

function RemoveMessageBox ( boxname )
{
    var d = $(boxname);
    new Effect.Fade(d);
}

/* only used in manual_registration and manage_cardit. still put it here to avoid code redundance. */
function confirmPrepDate(frm)
{
    if (! validate_form( '#manage_cardit_form', '.barcodeinfo' ) ) {
        return false;
    }

    p_date = Date.UTC(
                frm.elements['preparation_date[Y]'].value,
                frm.elements['preparation_date[m]'].value,
                frm.elements['preparation_date[d]'].value
                );

    l_date = Date.UTC(
                frm.elements['leg_date_1[Y]'].value,
                frm.elements['leg_date_1[m]'].value,
                frm.elements['leg_date_1[d]'].value
                );

    if (l_date < p_date) {
        return confirm('Cardit preparation date is later than leg1 date of the cardit. Continue?');
    } else {
        return true;
    }
}


function updateMultiSelectButton(btnId, chkName)
{
    var v = '';
    var chks = document.getElementsByName(chkName);
    for (i = 0; i < chks.length; i++) {
        var e = chks[i];
        if (e.checked == true) {
            if (v) {
                v += ', ';
            }
            v += e.value;
        }
    }

    if (v == '') { v = '  '; }

    document.getElementById(btnId).value = v;
    document.getElementById(btnId).title = v;
}

function updateMultiSelectTitle(sel)
{
    var v = '';
    var opts = sel.options;
    for (i = 0; i < opts.length; i++) {
        var opt = opts[i];
        if (opt.selected) {
            if (v) {
                v += ', ';
            }
            v += opt.value;
        }
    }

    sel.title = v;
}

function toggleMultiSelectExpand(expandId)
{
    var expand = document.getElementById(expandId);

    if (expand.style.display == 'none') {
        expand.style.display = 'block';
    } else {
        expand.style.display = 'none';
    }
}

// detect if the browser is IE 6 or less
function isIE6minus()
{
    if (navigator.appVersion.indexOf('MSIE') == -1) {
        return false;
    } else {
        temp = navigator.appVersion.split('MSIE');
        version = parseFloat(temp[1]);
        if (version <= 6) {
            return true;
        } else {
            return false;
        }
    }
}

function hideDropDowns()
{
    if (!isIE6minus()) return;
    $$('select').each( function(s) {
        s.style.visibility = 'hidden';
    });
}

function showDropDowns()
{
    if (!isIE6minus()) return;
    $$('select').each( function(s) {
        s.style.visibility = 'inherit';
    });
}

function menuHover(el)
{
    if ($(el).hasClassName('hover')) return;

    collapseMenu();
    var el_parents = $(el).ancestors();
    el_parents.each( function(s) {
        if ( $(s).id == 'nav' )
            throw $break;
        $(s).addClassName('hover');
    });
    $(el).addClassName('hover')
    var desc = $(el).select('ul');
    desc.each( function(s) {
        $(s).addClassName('hover');
        throw $break;
    });
    hideDropDowns();
}

function clickCollapseMenu(e)
{
    if ( e.button && e.button != 1 ) return;
    if ( e.which && e.which != 1 ) return;
    collapseMenu();
    showDropDowns();
}

function collapseMenu()
{
    if ( ! $('nav') ) return

    var hovers = $('nav').select('li.hover, ul.hover')
    hovers.each( function(s) {
        $(s).removeClassName('hover')
    } );
}

function load_vat_countries(union_selection){
    if(union_selection != 0){
        $('countries').style.color = 'purple';
        $('countries').innerHTML = "loading...";
        new Ajax.Request( 'vat?action=load_countries&union=' + union_selection, {
              method: 'get'
            , onComplete: function(transport){
                                if(transport.responseText){
                                    $('countries').style.color = 'black';
                                    $('countries').innerHTML = transport.responseText;
                                }
                            }
        })
    }
    else{
        $('countries').style.color = 'purple';
        $('countries').innerHTML = "You must choose a calc type first.";
    }
}

function vat_edit(vat_id, country){
    $('vat_ajax_messages').innerHTML = 'Saving new rate for ' + country + '...';
    $('vat_'+vat_id).style.backgroundColor = 'pink';
    var rate = $('vat_'+vat_id).value;
    new Ajax.Request( 'vat?action=vat_rate_change&rate=' + rate + '&vat_id=' + vat_id, {
              method: 'get'
            , onComplete: function(transport){
                                if(transport.responseText){
                                    $('vat_'+vat_id).style.backgroundColor = '#D6F8C7';
                                    $('vat_ajax_messages').innerHTML = 'New rate for '+ transport.responseText + ' has been saved.';
                                    var t=setTimeout("restore_vat_results("+ vat_id +")",5000);
                                }
                            }
        })
}

function restore_vat_results(id){
    $('vat_'+id).style.backgroundColor = '';
}

function checkUncheckAll(theElement) {
    var theForm = theElement.form, i = 0;
    for(i=0; i < theForm.length; i++){
        if(theForm[i].type == 'checkbox' && theForm[i].name != 'checkall' && theForm[i].disabled == false){
            theForm[i].checked = theElement.checked;
        }
    }
}

function reset_manual_reg_form(num_barcodes){
    for (i = 1; i <= num_barcodes; i++ ) {
        $('barcodes_' + i + '[origin_country]').value = '';
        $('barcodes_' + i + '[origin_po]').value =  '';
        $('barcodes_' + i + '[dest_country]').value =  '';
        $('barcodes_' + i + '[dest_po]').value =  '';
        $('barcodes_' + i + '[product_type]').value =  '';
        $('barcodes_' + i + '[product_sub_type]').value =  '';
        $('barcodes_' + i + '[year]').value =  '';
        $('barcodes_' + i + '[dispatch_no]').value =  '';
        $('barcodes_' + i + '[item_no]').value =  '';
        $('barcodes_' + i + '[type]').value =  '';
        $('barcodes_' + i + '[weight]').value =  '';
    }
}

function populate_manual_barcode_data(current_row){
    previous_row = current_row - 1;
    $('barcodes_' + current_row + '[origin_country]').value = $('barcodes_' + previous_row + '[origin_country]').value;
    $('barcodes_' + current_row + '[origin_po]').value = $('barcodes_' + previous_row + '[origin_po]').value;
    $('barcodes_' + current_row + '[dest_country]').value = $('barcodes_' + previous_row + '[dest_country]').value;
    $('barcodes_' + current_row + '[dest_po]').value = $('barcodes_' + previous_row + '[dest_po]').value;
    $('barcodes_' + current_row + '[product_type]').value = $('barcodes_' + previous_row + '[product_type]').value;
    $('barcodes_' + current_row + '[product_sub_type]').value = $('barcodes_' + previous_row + '[product_sub_type]').value;
    $('barcodes_' + current_row + '[year]').value = $('barcodes_' + previous_row + '[year]').value;
    $('barcodes_' + current_row + '[dispatch_no]').focus();
}

function doTimeBoxActive( form, el, cart )
{
    var activityType = el.value;
    if ( activityType == 'manual' ) {
        form.elements['new_flt_dates[' + cart + ']'].disabled = false;
        form.elements['new_flt_times[' + cart + ']'].disabled = false;
        form.elements['new_flt_dates[' + cart + ']'].className = null;
        form.elements['new_flt_times[' + cart + ']'].className = null;
    }
    else {
        form.elements['new_flt_dates[' + cart + ']'].disabled = true;
        form.elements['new_flt_times[' + cart + ']'].disabled = true;
        form.elements['new_flt_dates[' + cart + ']'].value = null;
        form.elements['new_flt_times[' + cart + ']'].value = null;
        form.elements['new_flt_dates[' + cart + ']'].className = 'disabled';
        form.elements['new_flt_times[' + cart + ']'].className = 'disabled';
    }

    if ( activityType == 'advance' ) {
        form.elements['carts_to_load[' + cart + ']'].disabled = true;
        form.elements['carts_to_load[' + cart + ']'].checked = false;
    }
    else {
        form.elements['carts_to_load[' + cart + ']'].disabled = false;
    }
}

function check_All(f)
{
    // For each element on the form
    for(i=0;i<f.elements.length;i++)
        // If the element is a checkbox
        if(f.elements[i].type=="checkbox")
            // Set the checkbox to checked true
            if (f.elements[i].checked == false)
                f.elements[i].checked=true;
            else
                f.elements[i].checked=false;
}

function validate_date( el )
{
    var date = /^\d\d\d\d-\d\d-\d\d$/;
    if ( !date.test(el.value) ) {
        alert('The date you have entered is not properly formatted (yyyy-mm-dd).  Please re-enter it.');
        el.value='';
        el.focus();
        el.className='problem';
        return false;
    }
    el.className='';
    return true;
}
function validate_time( el )
{
    var time = /^\d\d:\d\d$/;
    if ( !time.test(el.value) ) {
        alert('The time you have entered is not properly formatted (hh:mm).  Please re-enter it.');
        el.value='';
        el.focus();
        el.className = 'problem';
        return false;
    }
    el.className = '';
    return true;
}
function validate_city( el )
{
    var city = /^\w\w\w$/;
    if ( !city.test(el.value) ) {
        alert('The city you have entered is not properly formatted (hh:mm).  Please re-enter it.');
        el.value='';
        el.focus();
        return false;
    }
    return true;
}

function validate_active_cart_form(f)
{
    allElements = f.getInputs('text');

    var new_date = /^new_flt_dates_(.+)$/;
    var new_time = /^new_flt_times_(.+)$/;

    var valid_date = /^\d\d\d\d-\d\d-\d\d$/;
    var valid_time = /^\d\d:\d\d/;

    for ( var index=0; index < allElements.length; ++index ) {
        var item = allElements[index];

        if ( item.disabled ) continue

        if ( valid_date.test( $F( item ) ) ) {
            var uniq = new_date.exec( item.name );
            var sister = $('new_flt_times_' + uniq[1]);
            if ( ! valid_time.test( $F(sister) ) ) {
                alert("Time is required if entering a manual date!");
                sister.value='';
                sister.focus();
                sister.className = 'problem';
                return false;
            }
        }

        if ( valid_time.test( $F( item ) ) ) {
            var uniq = new_time.exec( item.name );
            var sister = $('new_flt_dates_' + uniq[1]);
            if ( ! valid_date.test( $F(sister) ) ) {
                alert("Date is required if entering a manual time!");
                sister.value='';
                sister.focus();
                sister.className = 'problem';
                return false;
            }
        }

    }
}

function submit_error_to_fogbugz( title, desc )
{
    var Req = new Hash();
    Req.set('ScoutUserName', 'Bug Reports');
    Req.set('ForceNewBug', 0);
    Req.set('FriendlyResponse', 1);
    Req.set('Description', 'Stats automated bug submission: ' + title);
    Req.set('Extra', desc);
    Req.set('submit_request_directly', 1);

    new Ajax.Request('FogBugzRequest', {
        method: 'get'
      , parameters: Req.toQueryString()
    });
}

function controller_access_change(controller_id){
    my_elm = 'access_' + controller_id;
    my_read_elm = 'read_' + controller_id;
    if($(my_read_elm)){
        if($(my_elm).checked == true){
            $(my_read_elm).disabled = false;
        }
        else{
            $(my_read_elm).checked = false;
            $(my_read_elm).disabled = true;
        }
    }
}

function layer_swap( layername ) {
    if( document.getElementById( layername ) ){
            if ( document.getElementById( layername ).style.visibility=='visible' ){
                    document.getElementById( layername ).style.visibility='hidden';
                    document.getElementById( layername ).style.display='none';
            }
            else{
                    document.getElementById( layername ).style.visibility='visible';
                    document.getElementById( layername ).style.display='block';
            }
    }
}

function is_number( e ) {

    keynum;
    keychar;
    numcheck;

    if( window.event ) {// IE
        keynum = e.keyCode;
    }
    else if( e.which ) {// Netscape/Firefox/Opera
        keynum = e.which;
    }

    keychar = String.fromCharCode( keynum );

    if( keynum == 8 ) {//backspace on my machine
        return true;
    }
    numcheck = /\d/;
    return numcheck.test( keychar );

}

function toggleAdvancedOptionsVisibility()
{
    // since the Effect.toggle is likely an asychronous call, we cannot rely on the values of the style.display right after its return.
    // instead, we check the pre-value and do the opposite.
    var aod = document.getElementById('advanced_options_div');
    var aof = document.getElementById('advanced_options_flag');
    if (aod && aof && aod.style.display != 'none') {
        aof.value = '0';
    } else {
        aof.value = '1';
    }

    Effect.toggle('advanced_options_div', 'slide');
}

function togglePrintPopup(title, id)
{
    var popup_id = 'accounting_invoice_print_popup'
    var winsizes = document.viewport.getDimensions();
    var winscroll = document.viewport.getScrollOffsets();
    var popsizes = { width: 400, height: 350 };

    if ( $(popup_id) ) {
        $(popup_id).remove();
    }

    winpos = {
        left: ( (winsizes.width / 2 + winscroll.left) - ( popsizes.width / 2) ),
        top:  ( (winsizes.height / 2 + winscroll.top) - ( popsizes.height / 2 ) )
        };
    win = "<div id='" + popup_id + "' style='position:absolute; top:" + winpos.top + "px; left:" + winpos.left + "px; height:" + popsizes.height + "px; width:" + popsizes.width + "px;'></div>";
    $('wrapper').insert( { top: win } );

    $(popup_id).innerHTML = "<h1 id='" + popup_id + "_header'>" + title + ':<br /> Invoice Id #' + id + "</h1>" +
                    "<ul style='list-style:square;'>" +
                    "<li><a target='_blank' href='accounting_display?action=display_invoices&amp;id=" + id + "&amp;display_option=invoic'>Invoice (HTML)</a></li>" +
                    "<li><a target='_blank' href='accounting_display?action=display_invoices&amp;id=" + id + "&amp;display_option=invoic_pdf'>Invoice (PDF)</a></li>" +
                    "<li><a target='_blank' href='accounting_display?action=display_invoices&amp;id=" + id + "&amp;display_option=cn51'>CN51 (HTML)</a></li>" +
                    "<li><a target='_blank' href='accounting_display?action=display_invoices&amp;id=" + id + "&amp;display_option=cn51_quarterly'>CN51 Quarterly (HTML)</a></li>" +
                    "<li><a target='_blank' href='accounting_display?action=display_invoices&amp;id=" + id + "&amp;display_option=cn51_pdf'>CN51 (PDF)</a></li>" +
                    "<li><a target='_blank' href='accounting_display?action=display_invoices&amp;id=" + id + "&amp;display_option=cn51_pdf_quarterly'>CN51 Quarterly (PDF)</a></li>" +
                    "<li><a target='_blank' href='accounting_display?action=display_invoices&amp;id=" + id + "&amp;display_option=cn51_city_pdf'>CN51 City View (PDF)</a></li>" +
                    "<li><a target='_blank' href='accounting_display?action=display_invoices&amp;id=" + id + "&amp;display_option=cn66'>CN66 (HTML)</a></li>" +
                    "<li><a target='_blank' href='accounting_display?action=display_invoices&amp;id=" + id + "&amp;display_option=cn66_quarterly'>CN66 Quarterly (HTML)</a></li>" +
                    "<li><a target='_blank' href='accounting_display?action=display_invoices&amp;id=" + id + "&amp;display_option=cn66_pdf'>CN66 (PDF)</a></li>" +
                    "<li><a target='_blank' href='accounting_display?action=display_invoices&amp;id=" + id + "&amp;display_option=cn66_pdf_quarterly'>CN66 Quarterly (PDF)</a></li>" +
                    "<li><a target='_blank' href='accounting_display?action=display_invoices&amp;id=" + id + "&amp;display_option=cn66_route_pdf'>CN66 Route View (PDF)</a></li>" +
                    "</ul>" +
                    "<input type='button' value='Cancel' onclick='if(confirm(\"Are you sure?  If you cancel, you will need to go the the Search Invoices page to retrieve and print documents individually.\")) { $(\"" + popup_id + "\").remove() }' />" +
                    "<br />";
    new Draggable(popup_id, { starteffect: false, endeffect: false, handle: $(popup_id + '_header') });
}

top.emptyField = emptyField = function ( element ) {
    if ( ! valid( element ) ) return true;

    var wRE = new RegExp('^\\s+$');

    var defaultRE = new RegExp('--');

    var value = $F(element);

    if ( ! valid( value ) ) return true;

    return wRE.match(value) || defaultRE.match(value) || !element.present() || value == '';
}

top.attachError = attachError = function ( element, msg ) {
    var msgRE = new RegExp('__MSG__');
    var htmlTxt = '<div class="errormsg">__MSG__</div>';
    element.up().insert( htmlTxt.replace( msgRE, msg ) );
    element.addClassName('invalid_input');
}

top.clearErrors = clearErrors = function () {
    $$('.invalid_input').invoke('removeClassName','invalid_input');
    $$('.errormsg').invoke('remove');
}

top.validate_form = validate_form = function ( formIdent, formGroup ) {
    clearErrors();
    var shouldSubmit = true;
    ident = '';
    if (valid(formIdent)) {
        ident = formIdent;
        if (valid(formGroup)) {
            ident += ' ' + formGroup;
        }
    }

    ident += '.inspect';
    var elements = $$(ident);
    if (valid(elements) && elements.length > 0) {
        elements.each( function( element ) {
            var elementValid = true;

            if ( valid( element ) ) {
                if ( ! valid( element.getAttribute( 'ignore' ) ) ) {
                    var value = $F(element);
                    if (elementValid && element.hasClassName('notempty')) {
                        if ( emptyField( element ) ) {
                            elementValid=shouldSubmit=false;
                            msg = 'This required field is empty';
                            attachError(element, msg);
                        }
                    }
                    if (elementValid && element.hasClassName('isnumber')) {
                        if ( ! isNumeric( value ) ) {
                            elementValid=shouldSubmit=false;
                            msg = 'This required field can only be a number';
                            attachError(element, msg);
                        }
                    }
                    if (elementValid && element.hasClassName('notzero')) {
                        if ( ! isNumeric( value ) ) {
                            elementValid=shouldSubmit=false;
                            msg = 'This required field can only be a number';
                            attachError(element, msg);
                        } else if ( toNumeric( value ) == 0 ) {
                            elementValid=shouldSubmit=false;
                            msg = 'This required field cannot be zero';
                            attachError(element, msg);
                        }
                    }
                    if (elementValid && element.hasClassName('positivenumber')) {
                        if ( ! isNumeric( value ) ) {
                            elementValid=shouldSubmit=false;
                            msg = 'This required field can only be a number';
                            attachError(element, msg);
                        } else if ( toNumeric( value ) < 0 ) {
                            elementValid=shouldSubmit=false;
                            msg = 'This required field should be a positive number';
                            attachError(element, msg);
                        }
                    }
                    if (elementValid && element.hasClassName('printrange')) {
                        var printRangeRE = new RegExp('^[\\d\\-,]*$');
                        if ( ! printRangeRE.match( value ) ) {
                            elementValid=shouldSubmit=false;
                            msg = 'This field should be a valid print range.';
                            attachError(element, msg);
                        }
                    }
                    if (elementValid && element.hasClassName('isbarcode')) {
                        var barcodeRE = new RegExp('^[0-9A-Za-z]{25}\\s*$');
                        if ( ! barcodeRE.match( value ) ) {
                            elementValid=shouldSubmit=false;
                            msg = 'Please enter a valid barcode.';
                            attachError(element, msg);
                        }
                    }
                }
            }
        });
    }

    return shouldSubmit;
}

/*
* From http://blog.stevenlevithan.com/archives/faster-than-innerhtml
* Helps alleviate the load (especially in firefox) involved in innerHTML writes
*/

top.replaceHtml = replaceHtml = function (el, html) {
    var oldEl = typeof el === "string" ? document.getElementById(el) : el;
    /*@cc_on // Pure innerHTML is slightly faster in IE
        oldEl.innerHTML = html;
        return oldEl;
    @*/
    var newEl = oldEl.cloneNode(false);
    newEl.innerHTML = html;
    oldEl.parentNode.replaceChild(newEl, oldEl);
    /* Since we just removed the old element from the DOM, return a reference
    to the new element, which can be used to restore variable references. */
    return newEl;
};


