/*  Javascript functions for Invoice Module
 *  12/22/2005 Initial creation
/*--------------------------------------------------------------------------*/

/*********************************/
/* Used in sectionInvoices.tpl   */
/*********************************/
var invoicesSelected = 0;
var selectedInvoiceId = 0;
var lastSelectedInvoiceList = "";

function ShowEditBox(id,fuse,action){
    $(id).innerHTML = "<input onkeypress='return noenter();' type='text' id='check_"+id+"' size=6 maxlength=10 /> <input type=button value='go' onClick=\"UpdateCheck('"+id+"','"+fuse+"','"+action+"');\" class='button_small' />";
    $('check_'+id).focus();
}

function UpdateCheck(id,fuse,action){
    var url;
    var invoiceid;

    var checknum = $('check_'+id).value;
    if (checknum.length > 10){
        checknum = checknum.substring(0,10);
        alert(checknum);
    }

    setStatus('Working ...');
    invoiceid = id.split('_')[1];
    url = "&checknum="+checknum;
    UpdateInvoiceColumn(id,invoiceid,fuse,action,url);
}

function ProcessPayment(invoices,fuse,action,successfunc){

    var answer=confirm("Are you sure you want to process the selected account(s) with the CC number(s) on file?");
    if (!answer){
        return false;
    }
    var extraargs = 'passphrase='+$("processform_passphrase").value;
    PerformAsyncActionOnInvoices(true,invoices,fuse,action,successfunc,extraargs);
}

function onSelectInvoiceSuccess(t) {
    //in the event that multiple checks were performed
    //we only want to disable the waiting status on the
    //last one selected
    var invoicesselected = t.responseText.split('|')[0];
    var strButtons = t.responseText.split('|')[1];

    if(invoicesselected!=lastSelectedInvoiceList) return;

    if(invoicesSelected==0){
        $('invoicebuttons').innerHTML = "<img src='images/spacer.gif' id='invoicebuttonwaiting' />";
    }else{
        $('invoicebuttons').innerHTML = strButtons;
    }
}

function onShowInvoiceDetails(t){
    $('invoicedetails').innerHTML = t.responseText;
    if(bolUseEffects ){ new Effect.BlindDown($('invoicedetails')); }
    else{ $('invoicedetails').style.display=""; }
    unsetStatus('', 1);
}

function StatusMessageThenFade(strMessage){
    if(bolUseEffects ){
        $('statusMsg').innerHTML=strMessage;
        new Effect.Appear($('statusContainer'));
        new Effect.Fade($('statusContainer'), {duration: 5.0,transition: Effect.Transitions.linear, from: 1.0, to: 0.0} );
    }
}

function AsyncSelectInvoice(archive){

    $('invoicebuttons').innerHTML = "<img src='images/spacer.gif' id='invoicebuttonwaiting' />";
    //Get list of buttons for selected invoices
    myform = document.forms['invoices'];
    intCount = myform.elements.length;

    $('invoicebuttonwaiting').src = pic1.src;

    invoicesSelected=0;
    strinvoices="";

    for (x=1;x<=intCount;x++)
    {
       if (myform.elements[x-1].checked == true){
          bolSubmit=true;
          strinvoices=strinvoices+","+myform.elements[x-1].value;
          invoicesSelected++;
       }
    }

    if(invoicesSelected==0){
         $('invoicebuttons').innerHTML = "<img src='images/spacer.gif' id='invoicebuttonwaiting' />";
         //unsetStatus('', 1);
         return;
    }

    if(strinvoices==""){
         onSelectInvoiceSuccess("Error:  Not recognizing invoices (AsyncSelectInvoice)");
         return;
    }

    //Set the last list of invoices to global 'lastSelectedInvoiceList'
    //when we get back from async process compare with this last list
    //if not match then continue showing waiting and do not show buttons
    //this will prevent any lag issues with previous clicks returning bogus
    //button list that do not apply to the selected invoices.
    lastSelectedInvoiceList = strinvoices;

    var opt = {
         onSuccess: onSelectInvoiceSuccess,
         on404: on404,
         onFailure: onFailure
    }
    new Ajax.Request('index.php?archive='+archive+'&invoices='+strinvoices+'&action=4030&fuse=4&billshowid=-1', opt);
}

//function used to show extra label used for
function ShowPassPhraseWindow(form){
    if (form.disabled) return false;
    hideshowCommon($('passphrasediv'));
}

function RemoveInvoicesSuccess(t){
    //can be used for archived or deleted or unarchived
    var msg = t.responseText.split('|')[0];
    var remove=true;

    //check if msg has error.  If so then do not hide
    if(msg.indexOf('**')>=0){
        msg = msg.substring(2);
        remove=false;
    }

    if(remove){
      var invoices = t.responseText.split('|')[2];
      var arrInvoices=invoices.split(',');
      var invoice_num=0;
      while (invoice_num < arrInvoices.length)
      {
        em = $('row_ie_'+arrInvoices[invoice_num]);
        em.parentNode.removeChild(em);
        invoice_num+=1;
      }
    }

    //Reset Certain Parts of Screen
    invoicesSelected=0;
    lastSelectedInvoiceList = "";
    $('invoicebuttons').innerHTML = "<img src='images/spacer.gif' id='invoicebuttonwaiting' />";
    unsetStatus('', 1);
    CloseInvoiceDetails();

    StatusMessageThenFade(msg); //show what action was completed

    return;
}

function onInvoiceActionSuccess(t){

    if(t.responseText=="") return;

    unsetStatus('',1); //hide working message on top right

    var msg = t.responseText.split('|')[0];
    var viewdetailaction = t.responseText.split('|')[1];
    var invoices = t.responseText.split('|')[2];
    var fuse = t.responseText.split('|')[3];
    var action1 = t.responseText.split('|')[4];
    var action2 = t.responseText.split('|')[5];

    var arrInvoices=invoices.split(',');
    var invoice_num=0;

    while (invoice_num < arrInvoices.length)
    {
        if(action1!='none') UpdateInvoiceColumn('amount'+'_'+arrInvoices[invoice_num],arrInvoices[invoice_num],fuse,action1,'');
        if(action2!='none') UpdateInvoiceColumn('status'+'_'+arrInvoices[invoice_num],arrInvoices[invoice_num],fuse,action2,'');

        invoice_num+=1;
    }

    AsyncSelectInvoice(0);
    EnableInvoiceButons();

    StatusMessageThenFade(msg); //show what action was completed

    //check and see if active invoice is part of the invoice array
    //if so then reopen the details for that invoice
    //selectedInvoiceId
    if(InArray(arrInvoices,selectedInvoiceId)){
        //reopen invoicedetails
        AsyncShowInvoiceDetails(selectedInvoiceId,viewdetailaction,fuse);
    }
}

//called after any column needs updating
function ReturnContentToReplace(t){
    var id = t.responseText.split('||')[0];
    var content = t.responseText.split('||')[1];
    $(id).innerHTML = content;
    unsetStatus('', 1);
}

//send async call to server to return html to update column
function UpdateInvoiceColumn(column,invoice,fuse,action,url){
    var opt = {
        method: 'post',
        postBody: 'invoice='+invoice+'&fuse='+fuse+'&action='+action+'&column='+column+url,
        onSuccess: ReturnContentToReplace,
        on404: on404,
        onFailure: onFailure
    }
    new Ajax.Request('index.php', opt);
}

//General function to shoot out the async function performed on invoices
function PerformAsyncActionOnInvoices(bolShowStatus,invoices,fuse,action,successfunc,extraargs){
    var successFunction = "onInvoiceActionSuccess";

    if (bolShowStatus){
        setStatus('Working ...');
        DisableInvoiceButtons();
    }

    if (successfunc != null){
        successFunction = successfunc;
    }

    var args = 'invoices='+invoices+'&fuse='+fuse+'&action='+action;
    if(extraargs!="") args = args+"&"+extraargs;

    var opt = {
         method: 'post',
         postBody: args,
         onSuccess: eval(successFunction),
         on404: on404,
         onFailure: onFailure
    }
    new Ajax.Request('index.php', opt);
}

function DisableInvoiceButtons(){
    elements = document.getElementsByName('invoicebutton');
    for (i=0;i<elements.length;i++){
        var tempobj=elements[i]
        tempobj.disabled=true;
    }
}

function EnableInvoiceButons(){
    elements = document.getElementsByName('invoicebutton');
    for (i=0;i<elements.length;i++){
        var tempobj=elements[i]
        tempobj.disabled=false;
    }
}

function PayInvoice(invoice,action,fuse){
    location.href = "index.php?fuse="+fuse+"&action="+action+"&invoiceid="+invoice;
}

function AsyncShowInvoiceDetails(invoice,action,fuse){
    if ($('i'+invoice).checked == true) $('i'+invoice).checked=false;
    else $('i'+invoice).checked=true;
    AsyncSelectInvoice("");
    SetInvoiceActive(invoice);
    setStatus('Working ...');
    var opt = {
         onSuccess: onShowInvoiceDetails,
         on404: on404,
         onFailure: onFailure
    }
    new Ajax.Request('index.php?fuse='+fuse+'&action='+action+'&billdetailid='+invoice, opt);
}

function SetInvoiceActive(invoice){
    intCount = document.forms['invoices'].elements.length;
    for (x=1;x<=intCount;x++){
        tinvoice =  'row_ie_'+document.forms['invoices'].elements[x-1].value;
        $(tinvoice).className=''
    }

    if(invoice!=null){
         selectedInvoiceId = invoice;
         $('row_ie_'+invoice).className='invoice_selected'
    }else{
         selectedInvoiceId = 0;
    }
}


/**********************************/
/*  Used in sectionInvoiceDetails */
/**********************************/
function itemSelected(form){
    strAlertMessage = "You need to select entry(s) to perform this action on";
    intCount = document.forms['workitems'].elements.length;
    bolShowMessage = true;
    for (x=1;x<=intCount;x++)
    {
        if (document.forms['workitems'].elements[x-1].checked == true){
             bolShowMessage=false;
        }
    }

    if (bolShowMessage){
        if(document.forms['invoicemerge']!=null){
            document.forms['invoicemerge'].elements['billdetailid'].selectedIndex=0;
        }else if(document.forms['invoicemove']!=null){
            document.forms['invoicemove'].elements['invoiceid'].selectedIndex=0;
        }
        alert(strAlertMessage);
        return false;
    }else{
        return true;
    }
}

function submitDelete(myform,bShowDeleteAllWarning){

    strMessage = "Click OK if you are sure you want to delete the selected entries."
    strWorkItems = "";
    intItemChecked=0;

    intCount = document.forms['workitems'].elements.length;

    for (x=1;x<=intCount;x++)
    {
        if (document.forms['workitems'].elements[x-1].checked == true){
             strWorkItems += document.forms['workitems'].elements[x-1].value;
             strWorkItems += " ";
             intItemChecked++;
        }
    }

    if ((intItemChecked==intCount)&&(bShowDeleteAllWarning)) strMessage += "\n\nWarning: By deleting all of the remaining entries, this invoice will be deleted as well.";
    var tString;
    String(tString);
    tString = (strWorkItems.substring(0,strWorkItems.length-1));
    myform.selectedworks.value=tString;

    var answer=confirm(strMessage);
    if (answer){
        myform.submit();
    }
}

function submitMoveEntries(myform,bShowMergeAllWarning){
    strWorkItems = "";
    intItemChecked=0;

    intCount = document.forms['workitems'].elements.length;

    for (x=1;x<=intCount;x++)
    {
        if (document.forms['workitems'].elements[x-1].checked == true){
             strWorkItems += document.forms['workitems'].elements[x-1].value;
             strWorkItems += " ";
             intItemChecked++;
        }
    }

    var tString;
    String(tString);
    //delete last space in string
    tString = (strWorkItems.substring(0,strWorkItems.length-1));

    $('invoicemove_selectedworks').value = tString;
    if($('invoicemove_invoiceid').value == "") return;

    if ((intItemChecked==intCount)&&(bShowMergeAllWarning)){
        strMessage = lang("WARNING: By moving all of the remaining entries, this invoice will be deleted.");
        var answer=confirm(strMessage);
        if (answer){
            myform.submit();
        }else{
            document.forms['invoicemove'].elements['invoiceid'].selectedIndex=0;
        }
    }else{
        myform.submit();
    }
}

function CreateInvoiceFromEntry(myform){

    intSelectedCount=0;
    strWorkItems = "";
    for (x=1;x<=intCount;x++)
    {
        if (document.forms['workitems'].elements[x-1].checked == true){
             strWorkItems += document.forms['workitems'].elements[x-1].value;
             strWorkItems += " ";
             intSelectedCount++;
        }
    }

    var tString;
    String(tString);
    tString = (strWorkItems.substring(0,strWorkItems.length-1));
    myform.selectedworks.value=tString;
    myform.submit();

}

function CloseInvoiceDetails(){
    $('invoicedetails').innerHTML = "";
    $('invoicedetails').style.display = "none";
    SetInvoiceActive();
}
