/*  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){
    document.getElementById(id).innerHTML = "<input onkeypress='return noenter();' type='text' id='check_"+id+"' size=30 maxlength=50 /> <input type=button value='go' onClick=\"UpdateCheck('"+id+"','"+fuse+"','"+action+"');\" class='button_small' />";
    document.getElementById('check_'+id).focus('',300);
}

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

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

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

function ProcessPayment(invoices,fuse,action,successfunc,thirdpartycc){
    
    if(thirdpartycc){
        var answer=confirm("Are you sure you want to process the selected account(s)?");
        var extraargs = 'thirdpartycc=1';
    }else{
        var answer=confirm("Are you sure you want to process the selected account(s) with the CC number(s) on file?");
        var extraargs = 'passphrase=' + encodeURIComponent(document.getElementById("processform_passphrase").value);
    }
    if (!answer){
        return false;
    }
    
    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){
        document.getElementById('invoicebuttons').innerHTML = "<img src='" + relativePath +"images/spacer.gif' id='invoicebuttonwaiting' />";
    }else{
        document.getElementById('invoicebuttons').innerHTML = strButtons;
    }
    cleanUpCCSection();
}

function onShowInvoiceDetails(t){
    document.getElementById('invoicedetails').innerHTML = t.responseText;
    document.getElementById('invoicedetails').style.display="";
    unsetStatus('', 1);
}

function AsyncSelectInvoice(archive){

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

    document.getElementById('invoicebuttonwaiting').src = pic1.src;
    if (document.getElementById('ccinfo') != null) document.getElementById('ccinfo').style.display = 'none';

    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){
         document.getElementById('invoicebuttons').innerHTML = "<img src='" + relativePath +"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
    }
    new Ajax.Request('index.php?archive='+archive+'&invoices='+strinvoices+'&view=InvoiceButtons_Async&fuse=billing&billshowid=-1', opt);
}

//function used to show extra label used for
function ShowPassPhraseWindow(form){
    if (form.disabled) return false;
    hideshow(document.getElementById('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 = document.getElementById('row_ie_'+arrInvoices[invoice_num]);
        em.parentNode.removeChild(em);
        invoice_num+=1;
      }
    }

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


    msg(msg);

    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 action3 = t.responseText.split('|')[6];

    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,'');
        if(action3!='none') UpdateInvoiceColumn('balance_due'+'_'+arrInvoices[invoice_num],arrInvoices[invoice_num],fuse,action3,'');

        invoice_num+=1;
    }

    AsyncSelectInvoice(0);
    EnableInvoiceButons();

    msg(msg);

    //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];
    document.getElementById(id).innerHTML = content;
    unsetStatus('', 1);
}

//send async call to server to return html to update column
function UpdateInvoiceColumn(column,invoice,fuse,view,url){
    var opt = {
        method: 'post',
        postBody: 'invoice='+invoice+'&column='+column+url,
        onSuccess: ReturnContentToReplace
    }
    new Ajax.Request('index.php?fuse='+fuse+'&view='+view, 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(lang('Working ...'));
        DisableInvoiceButtons();
    }

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

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

    var opt = {
         method: 'post',
         postBody: args,
         onSuccess: eval(successFunction)
    }
    new Ajax.Request('index.php?fuse='+fuse+'&action='+action, opt);
}

function AddVariablePayment(invoices){
    popup_window = window.open('index.php?fuse=clients&view=AddVariablePayment&invoices='+invoices,'addVariablePayment','scrollbars=yes,menubar=no,location=no,width=250,height=250,resizable=yes,screenX=200,screenY=200,top=200,left=200');
}

function VariablePayments(form){
    var strinvoices = "";
    if(form.elements.invoices.length != undefined){
        strinvoices = form.elements.invoices[0].value;
        for (var i = 1; i < form.elements.invoices.length; i++) {
            strinvoices = strinvoices + "," + form.elements.invoices[i].value;
        }
    }else{
        var strinvoices = form.elements.invoices.value;
    }

    var strpayments = "";
    if(form.elements.payments.length != undefined){
        strpayments = form.elements.payments[0].value;
        for (var i = 1; i < form.elements.payments.length; i++) {
            strpayments = strpayments + "," + form.elements.payments[i].value;
        }
    }else{
        var strpayments = form.elements.payments.value;
    }
    
    PerformAsyncActionOnInvoices(true,strinvoices,'billing','AddVariablePaymentToInvoices_Async',null,'payments='+strpayments);
    return false;
}

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)
{
    if (pluginArrCC[selectedValue('paymentmethod')] == null) {
        // 3rd party plugin -- forward customer
        location.href = "index.php?fuse="+fuse+"&action="+action+"&invoiceid="+invoice+"&plugin="+selectedValue('paymentmethod');
    } else {
        if (document.getElementById('ccnumber').value == '') {
            document.getElementById('errMessages').innerHTML = '<font class="redtext"><b>'+lang('Missing credit card information')+'</b></font>';
            return;
        }
        if (pluginArrCVV[selectedValue('paymentmethod')] == 1 && document.getElementById('cvv2').value == '') {
            document.getElementById('errMessages').innerHTML = '<font class="redtext"><b>'+lang('Missing CVV2 information')+'</b></font>';
            return;
        }
        // Merchant plugin -- async process payment
        args = 'invoiceid='+invoice+'&ccnumber='+document.getElementById('ccnumber').value+'&ccyear='+document.getElementById('ccyear').value+'&ccmonth='+document.getElementById('ccmonth').value+'&cvv2='+document.getElementById('cvv2').value;
        if (autoArchive) {
            PerformAsyncActionOnInvoices(true,invoice,'billing','PayInvoice_Async&plugin='+selectedValue('paymentmethod'),'RemoveInvoicesSuccess',args);
        } else {
            PerformAsyncActionOnInvoices(true,invoice,'billing','PayInvoice_Async&plugin='+selectedValue('paymentmethod'),null,args);
        }
    }
}

function refreshCCSection()
{
    document.getElementById('invoicebutton_1').style.display = (selectedValue('paymentmethod') != 0)? 'block' : 'none';

    if (pluginArrCC[selectedValue('paymentmethod')] == null) {
        cleanUpCCSection();
    } else {
        for (x = 0; x < 4; x++) {
            if (pluginArrCC[selectedValue('paymentmethod')][x] == 1) {
                document.getElementById(x + '_logo').style.display = '';
            } else {
                document.getElementById(x + '_logo').style.display = 'none';
            }
        }
        if (pluginArrCVV[selectedValue('paymentmethod')] == 1) {
            document.getElementById('cvv2info').style.display = '';
        } else {
            document.getElementById('cvv2').value = '';
            document.getElementById('cvv2info').style.display = 'none';
        }
        document.getElementById('ccinfo').style.display = '';
    }
}

function cleanUpCCSection()
{
    document.getElementById('ccinfo').style.display = 'none';
}

function restoreDefaultPaymentMethod(displayPayButton)
{
    document.getElementById('paymethod_select').style.display = 'none';
    document.getElementById('paymethod_pretty').style.display = '';
    document.getElementById('ccinfo').style.display = 'none'

    document.getElementById('invoicebutton_1').style.display = displayPayButton? 'block' : 'none';
}

function showAlternatePaymentMethods()
{
    document.getElementById('paymethod_select').style.display = '';
    document.getElementById('paymethod_pretty').style.display = 'none';
    document.getElementById('paymentmethod').selectedIndex = 0;
    document.getElementById('invoicebutton_1').style.display = 'none';
}

function AsyncShowInvoiceDetails(invoice,action,fuse){
    if (document.getElementById('i'+invoice).checked == true) document.getElementById('i'+invoice).checked=false;
    else document.getElementById('i'+invoice).checked=true;
    AsyncSelectInvoice("");
    SetInvoiceActive(invoice);
    setStatus('Working ...');
    var opt = {
         onSuccess: onShowInvoiceDetails
    }
    new Ajax.Request('index.php?fuse='+fuse+'&view='+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;
        document.getElementById(tinvoice).className=''
    }

    if(invoice!=null){
         selectedInvoiceId = invoice;
         document.getElementById('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));

    document.getElementById('invoicemove_selectedworks').value = tString;
    if(document.getElementById('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(){
    document.getElementById('invoicedetails').innerHTML = "";
    document.getElementById('invoicedetails').style.display = "none";
    SetInvoiceActive();
}
