
function RetrieveTemplate(template)
{
    Ext.Ajax.request({
       url: 'index.php?fuse=clients&view=GetTemplate_Async',
       success: function(t) {
            var response = t.responseText.split('||');
            if(response.length > 1){
                document.getElementById('emailSubject').value = response[1];
                if(editorWelcomeEmail==null){
                    document.getElementById('emailMessage').value = response[0];
                }else{
                    editorWelcomeEmail.loadHTML(response[0]);
                }
            }else{
                alert('Can not retrieve template');
            }

       },
       params: {template : template}
    });
}

function GetSelectedPackages(){
    myform = document.forms['packages'];
    intCount = myform.elements.length;

    strpackages="";

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

function AsyncSelectPackage(){
    document.getElementById('packagebuttons').innerHTML = "<img src='" + relativePath + "images/spacer.gif' id='packagebuttonwaiting' />";
    //Get list of buttons for selected invoices

    document.getElementById('packagebuttonwaiting').src = pic1.src;

    strpackages=GetSelectedPackages();

    if(strpackages==""){
         document.getElementById('packagebuttons').innerHTML = "<img src='" + relativePath + "images/spacer.gif' id='packagebuttonwaiting' />";
         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.
    lastSelectedPackageList = strpackages;

    var opt = {
         method: 'post',
         postBody: '&packages='+strpackages,
         onSuccess: onSelectPackageSuccess
    }
    new Ajax.Request('index.php?fuse=clients&view=ShowPackageButtons', opt);
}

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

    if(packagesselected!=lastSelectedPackageList) return;
    
    if(packagesselected==0){
        document.getElementById('packagebuttons').innerHTML = "<img src='" + relativePath + "images/spacer.gif' id='packagebuttonwaiting' />";
    }else{
        document.getElementById('packagebuttons').innerHTML = strButtons;
    }
}

//General function to shoot out the async function performed on packages
function PerformAsyncActionOnPackages(args,successFunction){

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

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

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

function SuspendPackages(){
    strpackages=GetSelectedPackages();
    if (strpackages=="") return;
    
    if(confirm(lang("Click OK if you are sure you want to suspend these packages?"))) {

        setStatus("Working...");
        DisablePackageButtons();
    
        var options = '&packages='+strpackages;
        if (document.forms['options'].elements['serverplugin'] != null && document.forms['options'].elements['serverplugin'].checked == true){
            options = options+'&serverplugin=1';
        }
        var opt = {
             method: 'post',
             postBody: options,
             onSuccess: onSuspendPackagesSuccess
        }
        new Ajax.Request('index.php?fuse=clients&view=SuspendPackageAsync', opt);
    }
}

function onSuspendPackagesSuccess(t){
    unsetStatus("Packages suspended successfully", 2000);
    var response = t.responseText.split('|');
    var packages = response[0].split(',');
    var messages = response[1].replace(/(,)/g, '<br>\n');
    document.getElementById('errMessages').innerHTML = '<font class="redtext"><b>'+messages+'</b></font>';
    for(x=1;x<packages.length;x++){
        document.getElementById('tdPackageStatus'+packages[x]).innerHTML=lang('Suspended');
    }
    AsyncSelectPackage();
    EnablePackageButtons();
}

function UnSuspendPackages(){
    strpackages=GetSelectedPackages();
    if (strpackages=="") return;

    setStatus("Working...");
    DisablePackageButtons();

    var options = '&packages='+strpackages;
    if (document.forms['options'].elements['serverplugin'] != null && document.forms['options'].elements['serverplugin'].checked == true){
        options = options+'&serverplugin=1';
    }
    var opt = {
         method: 'post',
         postBody: options,
         onSuccess: onUnSuspendPackagesSuccess
    }
    new Ajax.Request('index.php?fuse=clients&view=UnsuspendPackageAsync', opt);
}

function onUnSuspendPackagesSuccess(t){
    unsetStatus("Packages unsuspended successfully", 1000);
    var response = t.responseText.split('|');
    var packages = response[0].split(',');
    var messages = response[1].replace(/(,)/g, '<br>\n');
    document.getElementById('errMessages').innerHTML = '<font class="redtext"><b>'+messages+'</b></font>';
    for(x=1;x<packages.length;x++){
        document.getElementById('tdPackageStatus'+packages[x]).innerHTML=lang('Active');
    }

    AsyncSelectPackage();
    EnablePackageButtons();
}


function SendPackageWelcomeEmail(){
    strpackages=GetSelectedPackages();
    if (strpackages=="") return;
    DisablePackageButtons();
    Ext.Ajax.request({
       url: 'index.php?fuse=clients&action=sendWelcomeEmail',
       success: function(xhr) {
            ce.parseAjaxResponse(xhr);
       },
       params: {packages: strpackages}
    });
}

function ActivatePackages(){
    strpackages=GetSelectedPackages();
    if (strpackages=="") return;

    setStatus("Working...");
    DisablePackageButtons();

    var options = '&packages='+strpackages;
    if (document.forms['options'].elements['serverplugin'] != null && document.forms['options'].elements['serverplugin'].checked == true){
        options = options+'&serverplugin=1';
    }
    if (document.forms['options'].elements['registrarplugin'] != null && document.forms['options'].elements['registrarplugin'].checked == true){
        options = options+'&registrarplugin=1';
    }
    if (document.forms['options'].elements['sendwelcomeemail'].checked == true){
        options = options+'&sendwelcomeemail=1';
    }
    var opt = {
         method: 'post',
         postBody: options,
         onSuccess: onActivatePackagesSuccess
    }
    new Ajax.Request('index.php?fuse=clients&view=ActivatePackageAsync', opt);
}

function onActivatePackagesSuccess(t){
    unsetStatus("Packages activated successfully", 2000);
    var response = t.responseText.split('|');
    var packages = response[0].split(',');
    var messages = response[1].replace(/(,)/g, '<br>\n');
    document.getElementById('errMessages').innerHTML = '<font class="redtext"><b>'+messages+'</b></font>';
    for(x=1;x<packages.length;x++){
        document.getElementById('tdPackageStatus'+packages[x]).innerHTML=lang('Active');
    }
    AsyncSelectPackage();
    EnablePackageButtons();
}

function DeletePackages(){
    strpackages=GetSelectedPackages();
    if (strpackages=="") return;

    if(confirm(lang("Click OK if you are sure you want to delete these packages?"))) {
        setStatus("Working...");
        DisablePackageButtons();
        
        var options = '&packages='+strpackages;
        if (document.forms['options'].elements['serverplugin'] != null && document.forms['options'].elements['serverplugin'].checked == true){
            options = options+'&serverplugin=1';
        }
        var opt = {
             method: 'post',
             postBody: options,
             onSuccess: onDeletePackagesSuccess
        }
        new Ajax.Request('index.php?fuse=clients&view=DeletePackageAsync', opt);
    }
}

function onDeletePackagesSuccess(t){
    
    unsetStatus("Packages deleted successfully", 2000);
    var response = t.responseText.split('|');
    var packages = response[0].split(',');
    var messages = response[1].replace(/(,)/g, '<br>\n');
    var hasDomains = response[2];
    var hasDomainsToRegister = response[3];
    var totalDomainsUser = response[4];
    var totalOfPackagesWithPlugin = response[5];

    var divRegister = document.getElementById('trRegistrarActDiv');
    var checkboxRegister = document.getElementById('registrarplugin');
    var spanActivePackages = document.getElementById('activateUsersPackagesSpan');
    var divSendEmail = document.getElementById('sendEmailDiv');
    var divTriggerServer = document.getElementById('TriggerServerDiv');

    if(divRegister != null){ 
        if(hasDomains == 0 ){
            divRegister.style.display = "none";
        }else{
            divRegister.style.display = "";
        }
    }

    if(checkboxRegister != null){
        if(hasDomainsToRegister == 0){
            checkboxRegister.checked = "true";
        }else{
            checkboxRegister.checked = "";
        }
    }

    if(divTriggerServer != null){ 
        if(totalOfPackagesWithPlugin == 0){
            divTriggerServer.style.display  = "";
        }else{
            divTriggerServer.style.display  = "none";
        }
    }

    if(totalDomainsUser == 0){
        if(spanActivePackages != null){ 
            spanActivePackages.style.display  = "none";
        }
        if(divSendEmail != null){  
            divSendEmail.style.display  = "none";
        }
        if(divTriggerServer != null){
            divTriggerServer.style.display  = "none";
        }
    }
    
    document.getElementById('errMessages').innerHTML = '<font class="redtext"><b>'+messages+'</b></font>';
    for(x=1;x<packages.length;x++){
        document.forms['packages'].elements['p'+packages[x]].checked=false;
        document.getElementById('tblPackages').deleteRow(document.getElementById('trPackage'+packages[x]).rowIndex);
    }
    AsyncSelectPackage();
    EnablePackageButtons();
}

function CancelPackages(){
    strpackages=GetSelectedPackages();
    if (strpackages=="") return;

    if(confirm(lang("Click OK if you are sure you want to cancel these packages?"))) {
        setStatus("Working...");
        DisablePackageButtons();
    
        var options = '&packages='+strpackages;
        if (document.forms['options'].elements['serverplugin'] != null && document.forms['options'].elements['serverplugin'].checked == true){
            options = options+'&serverplugin=1';
        }
        var opt = {
             method: 'post',
             postBody: options,
             onSuccess: onCancelPackagesSuccess
        }
        new Ajax.Request('index.php?fuse=clients&view=CancelPackageAsync', opt);
    }
}

function onCancelPackagesSuccess(t){
    unsetStatus("Packages cancelled successfully", 2000);
    var response = t.responseText.split('|');
    var packages = response[0].split(',');
    var messages = response[1].replace(/(,)/g, '<br>\n');
    document.getElementById('errMessages').innerHTML = '<font class="redtext"><b>'+messages+'</b></font>';
    for(x=1;x<packages.length;x++){
        document.getElementById('tdPackageStatus'+packages[x]).innerHTML=lang('Cancelled');
    }
    AsyncSelectPackage();
    EnablePackageButtons();
}

function processForm(fuse, action, message)
{
    if (message == '' || confirm(message)) {
        this.form.action = 'index.php?fuse='+fuse+'&action='+action;
        submitonce(this.form);
        this.form.submit();
    }
}

function CheckDomain(form, domain){ 

    var extension = '';
    var domain_array=domain.split(".");
    for (x=0;x < domain_array.length;x++)
    {
       if (x==0) domain = domain_array[x];
       else extension = extension + "."+ domain_array[x];
    }
    extension = extension.substring(1);
    
    var opt = {
     	 onSuccess	: DomainCheckReturn
    }
    var ajaxexecute = new Ajax.Request('index.php?fuse=clients&action=CheckDomain&domain='+domain+'&extension='+extension, opt);
    return false;
}

function DomainCheckReturn(strReturnValue){

    domainOption = strReturnValue.responseText.split('|');
    document.getElementById('message').style.display = 'block';
    
    switch(domainOption[0]){
        case '-1' :
        var domainMessage = lang('already has an account with us. If you are a current customer please submit a support ticket for assistance.');
        break;
        case '0' :
        var domainMessage = lang('The Domain is available');
        break;
        case '1' :
        var domainMessage = lang('Domain Is Already Registered');
        break;
        case '2' :
        var domainMessage = lang('Domain extension not recognized or supported');
        break;
        case '3' :
        var domainMessage = lang('Domain is not valid. Please try again');
        break;
        case '5' :
        var domainMessage = lang('Could not contact registry to lookup domain');
        break;
        default :
        var domainMessage = lang('There was a problem trying to register this domain');
        break;
    }
    
    document.getElementById('domainMessage').innerHTML = domainMessage;
    document.getElementById('message').style.display = 'block';
     
    return false;
}

function togglePriceOverride()
{
    if (document.getElementById('price_override').checked) {
        document.getElementById('price').value = document.getElementById('altprice').value;
        document.getElementById('price').readOnly = false;
    } else {
        document.getElementById('altprice').value = document.getElementById('price').value;
        document.getElementById('price').value = '';
        document.getElementById('price').readOnly = true;
    }
}

function archiveNotes(clientId)
{
    new Ajax.Request(   'index.php?fuse=clients&action=archiveClientNotes&clientId=' + clientId,
                        {
                            onLoading   : function(){resetStatus(lang('Archiving'))},
                            onSuccess   : completedArchiveNotes
                        }
    );
}

function completedArchiveNotes(responseObj)
{
    unsetStatus(false);

    var responseArr = responseObj.responseText.split('|');

    if (typeof responseArr[1] == 'undefined' || responseArr[0] != 'OK') {
        alert(responseObj.responseText.stripTags());
        return;
    }

    loadClientNotes(0, false);
}

function viewAllNotes()
{
    loadClientNotes(0, true);
}