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(){
    $('packagebuttons').innerHTML = "<img src='images/spacer.gif' id='packagebuttonwaiting' />";
    //Get list of buttons for selected invoices

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

    strpackages=GetSelectedPackages();

    if(strpackages==""){
         $('packagebuttons').innerHTML = "<img src='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,
         on404: on404,
         onFailure: onFailure
    }
    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){
        $('packagebuttons').innerHTML = "<img src='images/spacer.gif' id='packagebuttonwaiting' />";
    }else{
        $('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,
         on404: on404,
         onFailure: onFailure
    }
    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;

    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,
         on404: on404,
         onFailure: onFailure
    }
    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');
    $('errMessages').innerHTML = '<font class="red"><b>'+messages+'</b></font>';
    for(x=1;x<packages.length;x++){
        $('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,
         on404: on404,
         onFailure: onFailure
    }
    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');
    $('errMessages').innerHTML = '<font class="red"><b>'+messages+'</b></font>';
    for(x=1;x<packages.length;x++){
        $('tdPackageStatus'+packages[x]).innerHTML=lang('Active');
    }

    AsyncSelectPackage();
    EnablePackageButtons();
}


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

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

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

function onSendPackageWelcomeEmailSuccess(t){
    unsetStatus("Welcome emails sent", 2000);
    $('errMessages').innerHTML = '<font class="red"><b>'+t.responseText+'</b></font>';
}

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,
         on404: on404,
         onFailure: onFailure
    }
    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');
    $('errMessages').innerHTML = '<font class="red"><b>'+messages+'</b></font>';
    for(x=1;x<packages.length;x++){
        $('tdPackageStatus'+packages[x]).innerHTML=lang('Active');
    }
    AsyncSelectPackage();
    EnablePackageButtons();
}

function DeletePackages(){
    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: onDeletePackagesSuccess,
         on404: on404,
         onFailure: onFailure
    }
    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 = $('trRegistrarActDiv');
    var checkboxRegister = $('registrarplugin');
    var spanActivePackages = $('activateUsersPackagesSpan');
    var divSendEmail = $('sendEmailDiv');
    var divTriggerServer = $('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";
        }
    }
    
    $('errMessages').innerHTML = '<font class="red"><b>'+messages+'</b></font>';
    for(x=1;x<packages.length;x++){
        document.forms['packages'].elements['p'+packages[x]].checked=false;
        $('tblPackages').deleteRow($('trPackage'+packages[x]).rowIndex);
    }
    AsyncSelectPackage();
    EnablePackageButtons();
}

function CancelPackages(){
    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: onCancelPackagesSuccess,
         on404: on404,
         onFailure: onFailure
    }
    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');
    $('errMessages').innerHTML = '<font class="red"><b>'+messages+'</b></font>';
    for(x=1;x<packages.length;x++){
        $('tdPackageStatus'+packages[x]).innerHTML=lang('Cancelled');
    }
    AsyncSelectPackage();
    EnablePackageButtons();
}

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('|');
    $('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;
    }
    
    $('domainMessage').innerHTML = domainMessage;
    $('message').style.display = 'block';
     
    return false;
}

function togglePriceOverride()
{
    if ($('price_override').checked) {
        $('price').value = $('altprice').value;
        $('price').readOnly = false;
    } else {
        $('altprice').value = $('price').value;
        $('price').value = '';
        $('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);
}
