/*  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();   
var reportURL;

function SnapShotCountTimer(fuse,action)
{
    //SnapShotStopCountTimer();
    tFunction = "PerformAsyncAction(false,'','"+fuse+"','"+action+"','onGetSnapShotCountsSuccess', true)";
    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 && $(countid) != null){
            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(responseObj)
{
    var responseArr = responseObj.responseText.split('|');
    if (typeof responseArr[1] == 'undefined' || responseArr[0] != 'OK') {
        alert(responseObj.responseText.stripTags());
        return;
    }

    var response = responseArr[1].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,"",'admin','StoreColumnSelected_Async',"",extra);        
    
}

function RemovedServiceFromDashboard(responseObj){
    
    var responseArr = responseObj.responseText.split('|');
    if (typeof responseArr[1] == 'undefined' || responseArr[0] != 'OK') {
        alert(responseObj.responseText.stripTags());
        return;
    }    
    
    $(responseArr[1]).style.display="none";
    unsetStatus('', 1);
}

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 SendOverdueInvoice(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{    
        var passphrase = encodeURIComponent($('passphrase').value);
        PerformAsyncUpdater(true,tString,fuse,action,"passphrase=" + passphrase);
    }
    return false;
}

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

//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 (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 sendoverdue = true;
    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;
            if ($(itemids[x].value+'_overdue').value == false) sendoverdue = false;
        }
        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;
    }
    
    //Send Invoice
    myElements = document.getElementsByName("sendoverdue");
    if ((sendoverdue) && (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) ){
                if (document.getElementById('deleteticket') != null) {
                    MakeVisable($('deleteticket'),0);
                    $('deleteticket').disabled=false;
                }
                if (document.getElementById('closeticket') != null) {
                    MakeVisable($('closeticket'),0);                
                    $('closeticket').disabled=false;
                }
        }else{
                if (document.getElementById('deleteticket') != null) {
                    MakeVisable($('deleteticket'),1);
                    $('deleteticket').disabled=true;
                }
                if (document.getElementById('closeticket') != null) {
                    MakeVisable($('closeticket'),1);
                    $('closeticket').disabled=true;
                }
        }
}

function DomainItemCheck()
{
        var showbuttons = false;

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

        //Delete and close buttons
        if ( (showbuttons) ){
                if (document.getElementById('deletedomain') != null) {
                    MakeVisable($('deletedomain'),0);
                    $('deletedomain').disabled=false;
                }
                if (document.getElementById('renewdomain') != null) {
                    MakeVisable($('renewdomain'),0);                
                    $('renewdomain').disabled=false;
                }
                if (document.getElementById('reminddomain') != null) {
                    MakeVisable($('reminddomain'),0);                
                    $('reminddomain').disabled=false;
                }
        }else{
                if (document.getElementById('deletedomain') != null) {
                    MakeVisable($('deletedomain'),1);
                    $('deletedomain').disabled=true;
                }
                if (document.getElementById('renewdomain') != null) {
                    MakeVisable($('renewdomain'),1);
                    $('renewdomain').disabled=true;
                }
                if (document.getElementById('reminddomain') != null) {
                    MakeVisable($('reminddomain'),1);
                    $('reminddomain').disabled=true;
                }
        }
}


function toggleAllDomains()
{
    form = document.forms['domains'];
    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;
        }
    }
    DomainItemCheck();
    return false;
}

function DeleteDomain(fuse,action,msgText,mydiv)
{
	var answer=confirm(msgText);
	if (!answer){
		return false;
	}
    //get items from form
    form = document.forms['domains'];
    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 SendDomainReminder(fuse,action)
{
    //get items from form
    form = document.forms['domains'];
    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 FilterDomains(fuse,action,obj)
{
    PerformAsyncUpdater(true,"",fuse,action,"filter="+obj.value);
    return false;
}


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
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 ClickDashBoardTab(divtohide, tabid, ajaxFuse, ajaxView)
{
    for (var i = 0; i < tabDivs.length; i++) {
        Element.hide('div_'+tabDivs[i]);
        Element.removeClassName('tab_'+tabDivs[i] , "active" );
    }

    Element.toggle( divtohide );
    Element.addClassName( tabid , "active" );

    if((ajaxView != null)&&(ajaxView != "")){
        new Ajax.Updater(divtohide, 'index.php?fuse='+ajaxFuse+'&view='+ajaxView,
                         {onLoading : function(request){resetStatus(lang('Loading'))},
                          onComplete: function(request){unsetStatus(lang('Loaded'), 1000)}});
    }
}

function switchReport(data)
{

        newGraph = data.split("-");
        
        swf = newGraph[0];
        report = newGraph[1];
        type = newGraph[2];
        
        graph = newGraph[1]+"-"+newGraph[2];
        
        url = "index.php?indashboard=1&noheaderfooter=1&graphdata=1&view=ViewReport&fuse=reports&report="+report+"&type="+type;
        retrieveReportData(url,"../classes/fusioncharts/"+swf); //loaded in report.js
       	
        PerformAsyncAction(false,'',"clients","SetDashboardGraph",'','graph='+encodeURIComponent(graph));	    
}

function clickOnGraph()
{
    location.href = reportURL;
}

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();
}
