/*  Javascript functions for Invoice Module
 *  12/22/2005 Initial creation
/*--------------------------------------------------------------------------*/
//On Success Functions for all snapshot actions
var aHomeTabTimer = null;
var activeSnapShotDiv;
var currentTabCounts = Array();   

function SnapShotCountTimer(fuse,action){
    //SnapShotStopCountTimer();
    tFunction = "PerformAsyncAction(false,'',"+fuse+","+action+",'onGetSnapShotCountsSuccess')";
    eval(tFunction);
    aHomeTabTimer = window.setInterval(tFunction, 20000);
}

function onGetSnapShotCountsSuccess(t){
    var divs = t.responseText.split('|');   

    for(x=0;x<divs.length;x++){        
        div = divs[x].split(':')[0];
        countid = div+"_count";
        if(activeSnapShotDiv != countid){
            count = divs[x].split(':')[1];
            $(countid).innerHTML = "("+count+")";
            updatecurrentTabCounts(countid,count);
        }
    }
}

function updatecurrentTabCounts(countid,count){    
    found=false;
    tablength=0;
    countupdated = false;
    try{
        tablength=currentTabCounts.length;
    }catch(e){
    
    }
    
    for(y=0;y<tablength;y++){
        if(currentTabCounts[y].split(":")[0]==countid){            
            if(currentTabCounts[y].split(":")[1]!=count){
                countupdated = true;
            }
            currentTabCounts[y]=countid+":"+count;        
            found=true;
        }
    }
    
    if(!found){
         currentTabCounts[currentTabCounts.length]=countid+":"+count;            
    }
        
    if(countupdated){
        Effect.Pulsate($(countid).parentNode.parentNode.id);
    }
}

function SnapShotStopCountTimer(){
    alert(currentTabCounts.length);
    try{
        window.clearInterval(aHomeTabTimer);
    }catch(e){
    
    }
}

function onAssignTicketSuccess(t){
    var response = t.responseText.split('[adminname]');    
    var items = response[0];
    var adminname = response[1];
    var ids = items.split(' ');    
    for(x=0;x<=ids.length;x++){
        try{
            $("assignfield"+ids[x]).innerHTML = adminname;
        }catch(e){
        
        }
    }
    unsetStatus('', 1);    
}

//Async Functions
//hard coded fuse and action since coming from sortable table javascript event
function SetLastColumnUsed(col,desc,name){
    extra = "col="+col+"&desc="+desc+"&instance="+name;
    PerformAsyncAction(false,"",2,2023,"",extra);        
}
function AssignTicket(fuse,action,msgText,mydiv){
	if($('assignadminid').selectedIndex==0) return false;
    //get items from form
    form = document.forms['tickets'];
    strItems = "";
    for(x=1;x<=form.elements.length;x++){
        if (form.elements[x-1].checked){
            if (form.elements[x-1].value!=0){
                strItems += form.elements[x-1].value;
                strItems += " ";
            }
        }
    }
    if (strItems==""){
        alert(msgText);
        $('assignadminid').selectedIndex=0
        return false;
    }
    
    var tString;
    String(tString);
    tString = (strItems.substring(0,strItems.length-1));
    extra = "adminid="+$('assignadminid').value;   
    PerformAsyncAction(true,tString,fuse,action,"onAssignTicketSuccess",extra,mydiv);        
    $('assignadminid').selectedIndex=0;
}

function DeleteTickets(fuse,action,msgText,mydiv){
	var answer=confirm(msgText);
	if (!answer){
		return false;
	}
	
    //get items from form
    form = document.forms['tickets'];
    strItems = "";
    for(x=1;x<=form.elements.length;x++){
        if (form.elements[x-1].checked){
            if (form.elements[x-1].value!=0){
                strItems += form.elements[x-1].value;
                strItems += " ";
            }
        }
    }
    var tString;
    String(tString);
    tString = (strItems.substring(0,strItems.length-1));
    PerformAsyncUpdater(true,tString,fuse,action,"",mydiv);    
    return false;
}

function FilterTickets(fuse,action,obj,mydiv){
    if(obj.value==-1)return false;
    extra = "filter="+obj.value;   
    PerformAsyncUpdater(true,"",fuse,action,extra,mydiv);        
    return false;
}

function CloseTickets(fuse,action,msgText,mydiv){
	var answer=confirm(msgText);
	if (!answer){
		return false;
	}
    //get items from form
    form = document.forms['tickets'];
    strItems = "";
    for(x=1;x<=form.elements.length;x++){
        if (form.elements[x-1].checked){
            if (form.elements[x-1].value!=0){
                strItems += form.elements[x-1].value;
                strItems += " ";
            }
        }
    }
    var tString;
    String(tString);
    tString = (strItems.substring(0,strItems.length-1));
    PerformAsyncUpdater(true,tString,fuse,action,"",mydiv);    
    return false;
}

function toggleAllTickets()
{
    form = document.forms['tickets'];
    check = form.allbox.checked;
    if(check) {
        for(x=1;x<=form.elements.length;x++){
            form.elements[x-1].checked = true;
        }
    } else {
        for(x=1;x<=form.elements.length;x++){
            form.elements[x-1].checked = false;
        }
    }
    TroubleTicketItemCheck();
    return false;
}

function ActivatePendingPackages(fuse,action,activateMsg)
{
    activateClient = 0;
    activateClientPackages = 0;
    form = document.pendingaccounts;
    for (i = 0; i < form.length; i++) {
        if (form.elements[i].name == 'clientid[]' && form.elements[i].checked) {
            activateClient = 1;
            break;
        }
    }    
    if (activateClient) {        
        answer = confirm(activateMsg);
        if (answer) {
            activateClientPackages = 1;
        }
    }
    //build up clientid and domainids
    domainid="";clientid="";    
    for(i=0;i<document.getElementsByName("clientid[]").length;i++){
        if(document.getElementsByName("clientid[]")[i].checked)
            clientid += document.getElementsByName("clientid[]")[i].value+",";
    }
    for(i=0;i<document.getElementsByName("domainid[]").length;i++){
        if(document.getElementsByName("domainid[]")[i].checked)
            domainid += document.getElementsByName("domainid[]")[i].value+",";
    }
    
    extra = "activateclientpackages="+activateClientPackages+"&clientid="+clientid+"&domainid="+domainid;    
    //get checkbox options
    if($('sendwelcomeemail')!=null && $('sendwelcomeemail').checked){    
        extra += "&sendwelcomeemail=true";
    }
    if($('serverplugin')!=null && $('serverplugin').checked){
        extra += "&serverplugin=true";
    }
    if($('registrarplugin')!=null && $('registrarplugin').checked){
        extra += "&registrarplugin=true";    
    }
    
    PerformAsyncUpdater(true,"",fuse,action,extra);       
    return false;
}

function DeletePendingPackages(fuse,action,msg1,msg2,msg3)
{    
    blDeletePackages = false;
    blDeleteClients = false;
    form = document.pendingaccounts;
    for (i = 0; i < form.length; i++) {
        if (form.elements[i].name == 'domainid[]' && form.elements[i].checked) {
            blDeletePackages = true;
        }
        if (form.elements[i].name == 'clientid[]' && form.elements[i].checked) {
            blDeleteClients = true;
        }
    }

    if (blDeletePackages && blDeleteClients) {
        answer = confirm(msg1);        
    } else if (blDeletePackages && !blDeleteClients) {
        answer = confirm(msg2);
    } else if (!blDeletePackages && blDeleteClients) {
        answer = confirm(msg3);
    } else {
        answer = false;
    }
    if (!answer) return false;

    //build up clientid and domainids
    domainid="";clientid="";    
    for(i=0;i<document.getElementsByName("clientid[]").length;i++){
        if(document.getElementsByName("clientid[]")[i].checked)
            clientid += document.getElementsByName("clientid[]")[i].value+",";
    }
    for(i=0;i<document.getElementsByName("domainid[]").length;i++){
        if(document.getElementsByName("domainid[]")[i].checked)
            domainid += document.getElementsByName("domainid[]")[i].value+",";
    }

    extra = "clientid="+clientid+"&domainid="+domainid;
    PerformAsyncUpdater(true,"",fuse,action,extra);
    return false;   
}

function FilterInvoices(fuse,action,obj){
    PerformAsyncUpdater(true,"",fuse,action,"filter="+obj.value);
    return false;
}

function DeleteInvoices(fuse,action,delMessage){
	var answer=confirm(delMessage);
	if (!answer){
		return false;
	}
	
    //get items from form
    form = document.forms['pendinginvoices'];
    strItems = "";
    for(x=1;x<=form.elements.length;x++){
        if (form.elements[x-1].checked){
            if (form.elements[x-1].value!=0){
                strItems += form.elements[x-1].value;
                strItems += " ";
            }
        }
    }
    var tString;
    String(tString);
    tString = (strItems.substring(0,strItems.length-1));
    PerformAsyncUpdater(true,tString,fuse,action,"");
    return false;
}

function MarkInvoicePaid(fuse,action){
    //get items from form
    form = document.forms['pendinginvoices'];
    strItems = "";
    for(x=1;x<=form.elements.length;x++){
        if (form.elements[x-1].checked){
            if (form.elements[x-1].value!=0){
                strItems += form.elements[x-1].value;
                strItems += " ";
            }
        }
    }

    var answer = confirm(lang("Send Receipt? (OK = Yes  CANCEL = No)"));
    if (answer) {
        var extraargs = "sendreceipt=1";
    } else {
        var extraargs = "sendreceipt=0";
    }

    var tString;
    String(tString);
    tString = (strItems.substring(0,strItems.length-1));
    PerformAsyncUpdater(true,tString,fuse,action,extraargs);
    return false;

}
function SendInvoice(fuse,action){
    //get items from form
    form = document.forms['pendinginvoices'];
    strItems = "";
    for(x=1;x<=form.elements.length;x++){
        if (form.elements[x-1].checked){
            if (form.elements[x-1].value!=0){
                strItems += form.elements[x-1].value;
                strItems += " ";
            }
        }
    }
    var tString;
    String(tString);
    tString = (strItems.substring(0,strItems.length-1));
    PerformAsyncUpdater(true,tString,fuse,action,"");
    return false;
}

function DeleteUninvoicedWork(fuse,action,delMessage){

	var answer=confirm(delMessage);
	if (!answer){
		return false;
	}

    //get items from form
    form = document.forms['uninvoicedwork'];
    strItems = "";
    for(x=1;x<=form.elements.length;x++){
        if (form.elements[x-1].checked){
            if (form.elements[x-1].value!=0){
                strItems += form.elements[x-1].value;
                strItems += " ";
            }
        }
    }
    var tString;
    String(tString);
    tString = (strItems.substring(0,strItems.length-1));
    PerformAsyncUpdater(true,tString,fuse,action,"");    
    return false;
}

function ValidateCC(fuse,action){    
    //get items from form
    form = document.forms['validatecc'];
    strItems = "";
    for(x=1;x<=form.elements.length;x++){
        if (form.elements[x-1].checked){
            if (form.elements[x-1].value!=0){
                strItems += form.elements[x-1].value;
                strItems += " ";
            }
        }
    }
    var tString;
    String(tString);
    tString = (strItems.substring(0,strItems.length-1));
    if($('passphrase').value == ""){
        alert("A passphrase is required to validate these credit cards.");
    }else{    
        PerformAsyncUpdater(true,tString,fuse,action,"passphrase="+$('passphrase').value);
    }
    return false;
}

//General function to shoot out the async function performed on invoices
function PerformAsyncAction(bolShowStatus,items,fuse,action,successfunc,extraargs){

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

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

    var opt = {
         method: 'post',
         postBody: args,
         onSuccess: eval(successfunc),
         on404: on404,
         onFailure: onFailure
    }
    new Ajax.Request('index.php', opt);
}
function PerformAsyncUpdater(bolShowStatus,items,fuse,action,extraargs,mydiv){
   mydiv = mydiv || 'activesnapshot';
   
   if (bolShowStatus){
        setStatus('Working ...');
   }

   var args = 'items='+items+'&fuse='+fuse+'&action='+action;
   if(extraargs!="") args = args+"&"+extraargs;
    
   var opt = {
         method: 'post',
         postBody: args,
         onComplete:function(){if($('initialsnapshot')) {$('initialsnapshot').innerHTML=""};unsetStatus('', 1);},
         on404: on404,
         evalScripts:true,
         asynchronous:true,
         onFailure: onFailure
    }
    new Ajax.Updater(mydiv, 'index.php', opt);
}

//Needed for sorting table function
// override getRowValue to support CheckBox
SortableTable.prototype._getRowValue = SortableTable.prototype.getRowValue;
SortableTable.prototype.getRowValue = function (oRow, sType, nColumn) {
    if (sType == "CheckBox") {
        return oRow.cells[nColumn].firstChild.checked ? 1 : 0;
    }
    return this._getRowValue(oRow, sType, nColumn);
};

function SelectSnapShot(fuse,action,snapshot){    
    ToggleSnapShotTabs(snapshot);               
    activeSnapShotDiv = snapshot+"_count";
    PerformAsyncUpdater(true,"",fuse,action,"snapshot="+snapshot);
    return false;    
}

function ToggleSnapShotTabs(snapshot){
    //unselect snapshottab
    items = getElementsByName_iefix("li","snapshottab");
    for(x=0;x<items.length;x++){
        items[x].className = "";
    }
    $(snapshot+"_tab").className = "selected";        
}

//Non Async Functions
function CCItemCheck(skipcheckall){

    var validatecc = false;
    var allmarked = true;

    itemids = document.getElementsByName("ccuserid");
    itemchecked=false;
    for (x=0;x<itemids.length;x++){
        if (itemids[x].checked==true){ itemchecked=true; validatecc=true; }
        else {allmarked=false}
    }

    if(!skipcheckall){
        checkall = document.getElementsByName("allbox");
        if(allmarked) checkall[0].checked=true;
        else checkall[0].checked=false;
    }

    //Validate CC
    if ((validatecc) && (itemchecked)){
        MakeVisable($('btnValidateCC'),0);
        $('btnValidateCC').disabled=false;
    }else{
        MakeVisable($('btnValidateCC'),1);
        $('btnValidateCC').disabled=true;
    }
}

function itemSelected(form,strAlertMessage){
    intCount = form.elements.length;
    bolShowMessage=true;
    for(x=1;x<=intCount;x++){
        if(form.elements[x-1].checked){
                bolShowMessage=false;
        }
    }

    if (bolShowMessage){
       alert(strAlertMessage);
       return false;
    }else{
       return true;
    }
}

function SubmitAction(form, fuse, action, buttonname, isdelete, delMessage){
        var bolSubmit=true;
        form.fuse.value = fuse;
        form.action.value = action;

		form.elements['sendreceipt'].value=0;		
        //if (action==<?php echo cHOME_MARKINVOICEASPAID;?>){
        //  var answer=confirm("<?php echo lang("Send Receipt? (OK = Yes  CANCEL = No)"); ?>");
        //  if (!answer){
        //         form.elements['sendreceipt'].value=0;
        //  }else{
        //         form.elements['sendreceipt'].value=1;
        //  }
        //}

        if (isdelete==1){
			var answer=confirm(delMessage);
			if (!answer){
					bolSubmit=false;
			}
        }

        intItemsChecked = 0;
        strItems = "";
        for(x=1;x<=form.elements.length;x++){
            if (form.elements[x-1].checked){
                if (form.elements[x-1].value!=0){
                    strItems += form.elements[x-1].value;
                    strItems += " ";
                    intItemsChecked++;
                }
            }
        }
        var tString;
        String(tString);
        tString = (strItems.substring(0,strItems.length-1));
        form.selecteditems.value = tString;
        if (bolSubmit) form.submit();
}

function OutstandingInvoiceItemCheck(skipcheckall){
    var sendinvoice = false;
    var deleteinvoice = false;
    var markinvoicepaid = false;
    var allmarked = true;

    itemids = document.getElementsByName("outstandinginvoiceid");
    itemchecked=false;
    for (x=0;x<itemids.length;x++){
        if (itemids[x].checked==true){ itemchecked=true; sendinvoice=true; deleteinvoice=true; markinvoicepaid=true; }
        else {allmarked=false}
    }

    //if(!skipcheckall){
        checkall = document.getElementsByName("allbox");
        if(allmarked) checkall[0].checked=true;
        else checkall[0].checked=false;
    //}

    //Send Invoice
    myElements = document.getElementsByName("sendinvoice");
    if ((sendinvoice) && (itemchecked)){
        MakeVisable(myElements[0],0);
        myElements[0].disabled=false;
    }else{
        MakeVisable(myElements[0],1);
        myElements[0].disabled=true;
    }

    //Mark Invoice Paid Button
    myElements = document.getElementsByName("markpaid");
    if ((markinvoicepaid) && (itemchecked)){
        MakeVisable(myElements[0],0);
        myElements[0].disabled=false;
    }else{
        MakeVisable(myElements[0],1);
        myElements[0].disabled=true;
    }

    //Delete invoice Button
    myElements = document.getElementsByName("deleteinvoice");
    if ((markinvoicepaid) && (itemchecked)){
        MakeVisable(myElements[0],0);
        myElements[0].disabled=false;
    }else{
        MakeVisable(myElements[0],1);
        myElements[0].disabled=true;
    }
}

function TroubleTicketItemCheck(){
        var showbuttons = false;

        itemids = document.getElementsByName("troubleticketid");
        for (x=0;x<itemids.length;x++){
             if (itemids[x].checked==true){ showbuttons=true; }
        }

        //Delete and close buttons
        if ( (showbuttons) ){
                MakeVisable($('deleteticket'),0);
                $('deleteticket').disabled=false;
                MakeVisable($('closeticket'),0);                
                $('closeticket').disabled=false;
        }else{
                MakeVisable($('deleteticket'),1);
                $('deleteticket').disabled=true;
                MakeVisable($('closeticket'),1);
                $('closeticket').disabled=true;
        }
}


function CA(form,myobj){
        itemids = document.getElementsByName("outstandinginvoiceid");
        for (x=0;x<itemids.length;x++){
            if (myobj.checked){
                itemids[x].checked=true;
            }else{
                itemids[x].checked=false;
            }
        }
        OutstandingInvoiceItemCheck(true);
}

//Pending Customer Javascript... will need to refactor into other functions above
var packagesCheckCount = 0;
	
function updateButtonsState()
{
    if (packagesCheckCount > 0) {
        $('activatebtn').disabled = false;
        makevisible($('activatebtn'), 0);        
        $('deletebtn').disabled = false;
        makevisible($('deletebtn'), 0);
    } else {
        $('activatebtn').disabled = true;
        makevisible($('activatebtn'), 1);        
        $('deletebtn').disabled = true;
        makevisible($('deletebtn'), 1);
    }
}

function toggleAllPackages(form)
{
    check = form.allbox.checked;
    for (i = 0; i < form.length; i++) {
        if(form.elements[i].className == 'packageChk' && form.elements[i].checked != check && form.elements[i].disabled != true) {
            form.elements[i].checked = check;
            if (check) packagesCheckCount++;
            else packagesCheckCount--;
        }
    }
    updateButtonsState();
}

function checkPackage(checkBox)
{
    if (checkBox.checked) packagesCheckCount++;
    else packagesCheckCount--;
    UpdatePackageToggleAll();
    updateButtonsState();
}

function UpdatePackageToggleAll(){
    allchecked = true;
    form = document.pendingaccounts;    
    if(form.length==0) allchecked = false;
    for (i = 0; i < form.length; i++) {
        if (form.elements[i].className == 'packageChk' && !form.elements[i].checked && !form.elements[i].disabled) {
            allchecked = false;
            break;
        }
    }
    
    if(allchecked){
        $('allbox').checked = true;
    }else{
        $('allbox').checked = false;    
    }
}

function UninvoicedWorkItemCheck(){
	var deletework = false;

	itemids = document.getElementsByName("workid");
	itemchecked=false;
	for (x=0;x<itemids.length;x++){ if (itemids[x].checked==true){ itemchecked=true; deletework=true; } }

	//Delete invoice Button
	myElements = document.getElementsByName("deleteuninvoicedwork");
	if ((deletework) && (itemchecked)){
		MakeVisable(myElements[0],0);
		myElements[0].disabled=false;
	}else{
		MakeVisable(myElements[0],1);
		myElements[0].disabled=true;
	}
}

/*
function PendingUserItemCheck(){
	var approvependinguser = false;
	var rejectpendinguser = false;

	itemids = document.getElementsByName("pendinguserid");
	itemchecked=false;
	for (x=0;x<itemids.length;x++){ if (itemids[x].checked==true){ itemchecked=true; approvependinguser=true; rejectpendinguser=true;}  }

	//Reject Pending User
	myElements = document.getElementsByName("approvependinguser");
	if ((approvependinguser) && (itemchecked)){
		MakeVisable(myElements[0],0);
		myElements[0].disabled=false;
	}else{
		MakeVisable(myElements[0],1);
		myElements[0].disabled=true;
	}

	//Approve Pending User
	myElements = document.getElementsByName("rejectpendinguser");
	if ((rejectpendinguser) && (itemchecked)){
		MakeVisable(myElements[0],0);
		myElements[0].disabled=false;
	}else{
		MakeVisable(myElements[0],1);
		myElements[0].disabled=true;
	}
}
*/

function ClickDashBoardTab(divtohide,tabid,ajaxAction,updater){
    Element.hide( 'div_quickgraphs' );
    Element.hide( 'div_servicestats' );
    Element.hide( 'div_serverinfo' );

    Element.toggle( divtohide );

    /* remove all classes to tabs */
    Element.removeClassName( 'tab_quickgraphs' , "current" );
    Element.removeClassName( 'tab_servicestats' , "current" );
    Element.removeClassName( 'tab_serverinfo' , "current" );

    Element.addClassName( tabid , "current" );

    if((ajaxAction!=null)&&(ajaxAction!="")){
        var pars = 'fuse=2&action='+ajaxAction;
        if (updater) {
            new Ajax.Updater(divtohide, 'index.php',
                             {onLoading : function(request){resetStatus(lang('Loading'))},
                              onComplete: function(request){unsetStatus(lang('Loaded'), 1000)},
                              parameters: pars});
        } else {
            new Ajax.Request('index.php',
                 {onLoading : function(request){resetStatus(lang('Loading'))},
                  onComplete: function(request){unsetStatus(lang('Loaded'), 1000)},
                  parameters: pars});
    }
    }
}

function switchReport(selObj,fuseReport,userid)
{
		showvalue = document.getElementsByName("showvalues");
		showlegend = document.getElementsByName("showlegend");
		graph = $('quickgraph');
		if(document.forms['reportswitch'].elements['showvalues'].checked==true){
			showvaluesValue = 1;
		} else {
			showvaluesValue = 0;
		}
		if(document.forms['reportswitch'].elements['showlegend'].checked==true){
			showlegendValue = 1;
		} else {
			showlegendValue = 0;
		}
			graph.src = 'index.php?fuse='+fuseReport+'&showvalues='+showvaluesValue+'&showlegend='+showlegendValue+'&graph='+selObj.options[selObj.selectedIndex].value+'&userid='+userid;
}

function submitAdminEntries(myform){
		strWorkItems = "";
		intItemChecked=0;

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

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

/*
function SystemMessageOptions(form) {
	form.submit();
}

function SetSendEmail(){
	// Set Send Email when rejecting or approving email
	if (document.forms['sendemailpendinguser'].elements['sendemail'].checked==0) document.forms['pendingcustomers'].elements['sendemail'].value=0;
	else document.forms['pendingcustomers'].elements['sendemail'].value=1;
}

function CheckEmailOption() {
	if (document.forms['message'].elements['emailmsg'].checked==0) document.forms['message'].elements['emailmsg'].checked=1;
	else document.forms['message'].elements['emailmsg'].checked=0;
}
*/
