
/* $Id: em.js 18812 2008-06-20 00:10:05Z bkuskopf $ */

var EASY_START_WIZARD = 1;


function doAdd(x){
    var mcounter = document.getElementById('mail_counter');
    var num = parseInt(mcounter.innerHTML);
    num = Math.abs(num)+x;
    mcounter.innerHTML = num;
}


function showBuyCreditsWindow(e) {
    var owin = openWindow(e, '/account/payment/credits.php?popup=true', 620, 460);
    owin.focus();
}

function showCreditPricing(e, url) {
     var owin = openWindow(e, url, 490, 570, 'status=yes,scrollbars=yes');
     owin.focus();
}


function checkDisabledFooterButton() {
    if (document.getElementById('footer') && sms_message_ids && getRecordId()) {
        if (sms_message_ids[getRecordId()]) {
            document.getElementById('footer').disabled = true;
        } else {
            document.getElementById('footer').disabled = false;
        }
    }
}

function openCampaignMap(e, campaign_id) {
	if (campaign_id) {
		openWindow(e,'/em/campaign/view.php?id=' + campaign_id, 600, 600);
	} else {
		 customInfoBubble(getObjectFromEvent(e), 'Please select a Campaign');
	}
}


function previewMessage(e, email_id) {
    var force_sms = arguments[3] ? arguments[3] : false;
    var w           = (force_sms) ? 260 : 700;
    var h           = (force_sms) ? 465 : 430;
    var win_attribs = (force_sms) ? 'resizable=no' : 'resizable=yes';
    var window_name = (force_sms) ? 'sms_preview' : 'email_preview';
    var is_batch_id = arguments[2] || false;

    if(email_id) {
        openWindow(e, package_root + '/message/preview.php?id=' + email_id + '&is_batch_id=' + is_batch_id,w,h,win_attribs, window_name);
    } else {
        customInfoBubble(getObjectFromEvent(e), 'Please select a Message');
    }
}


function deleteMessage(e, id) {
    if (id) {
        delayedConfirm(e, 3, 'Deleting a Message will also remove its associated Statistics and the ability for recipients to view its online version.<br><br>Do you really want to delete the selected message?', 'func', 0, 0, false, 'opener.confirmDeleteMessage('+id+');');
    } else {
        customInfoBubble(getObjectFromEvent(e), 'Please select a Message');
    }
}


function confirmDeleteMessage(id) {
    document.location.href = package_root + '/message/del.php?id='+id+'&r='+escape(document.location.href);
}


function customSaveAsNew(form, action) {
    if(confirm('Are you sure you want to save this as a new Email?')) {
        var save_as_new = document.createElement('input');
        save_as_new.setAttribute('id', 'save_as_new');
        save_as_new.setAttribute('name', 'save_as_new');
        save_as_new.setAttribute('type', 'hidden');
        save_as_new.setAttribute('value', 'true');
        form.appendChild(save_as_new);
        form.action = action;
        if(update_click) {
            update_click = true;
        }
        if(action == 'plain.php') {
            form.submit();
        } else {
            save(form);
        }
     }
}

function editSelectedDatabase(db_id) {
    document.location=package_root + "/database/mod.php?id="+db_id;
}

function checkVarcharFieldSize(e, max_size) {
    obj = getObjectFromEvent(e);
    if(obj.value > max_size) {
        obj.value = max_size;
        alert('A Text Field will hold a maximum of ' + max_size + ' characters\n\nTo store more characters, please use a Comment Field.');
    }
}

function reOrderFields(oform) {
    osel        = oform.order_fld;

    for (i=0; i<osel.length; i++) {
        ohid = document.createElement('INPUT');
        ohid.setAttribute('type', 'hidden');
        ohid.setAttribute('name', 'order[]');
        ohid.setAttribute('value', osel[i].value);
        oform.appendChild(ohid);
    }
}


function editMessageDetails(e, eid){
    if(eid) {
        var owin = openWindow(e, package_root + '/message/details.php?id='+eid+'&popup=true', 510, 365);
        owin.focus();
    } else {
        customInfoBubble(getObjectFromEvent(e), 'Please select a Message');
    }
}

function customEditEmailDetails(e, mid){
    if(mid) {
		var owin = openWindow(e, package_root + '/message/email/details.php?id='+mid+'&popup=true', 510, 365);
		owin.focus();
    } else {

    }
}

function deleteBounces(e, batch_id){
    if (batch_id) {
        var sms = arguments[2] ? 'true' : 'false';
        var owin = openWindow(e, package_root + '/users/bounced/delete.php?bid=' + batch_id + '&sms=' + sms, 460, 292);
        owin.focus();
    } else {
        customInfoBubble(getObjectFromEvent(e), 'Please select a Batch');
    }
}

function viewBounceDetails(e, type, email_id) {
    if(getRecordId()) {
        var page = arguments[3] ? 'failed_sms_detail.php' : 'detail.php';
        document.location=page+"?t="+type+"&eid="+email_id+"&id="+getRecordId();
    } else {
        customInfoBubble(getObjectFromEvent(e), 'Please select a Batch to view');
    }
}


function deleteBatch(e) {
    if (getRecordId()){
        if(confirm('Deleting this send will prevent its recipients from using "Send to Friend".\n\nAre you sure you wish to continue?')) {
            location.href= package_root +'/statistics/del.php?id=' + getRecordId() + '&r=' + escape(document.location);
        }
    } else {
        customInfoBubble(getObjectFromEvent(e), 'Please select a send to delete');
    }
}


function checkUnsubscribeLink(obj) {
    // Firefox 3 workaround.
    var tmp_checked;
    if (ie) {
        tmp_checked = dd_unsub.getVisible();
    } else {
        tmp_checked = !obj.target.checked; // we have to use the object now since Fx3 reversed the order of events.
    }
    if(tmp_checked) {
        if(confirm('IMPORTANT INFORMATION\n\nYou may breach the SPAM Act by removing the Unsubscribe facility.\n\nThe Act requires you to provide a method for recipients to unsubscribe from your electronic Messages.\n\nPlease ensure your Message contains an alternate unsubscribe method if you choose not to include the one provided.\n\nSelect CANCEL to keep the Unsubscribe facility or OK to continue.')) {
            return true;
        } else {
            dd_unsub.setVisible(false);
            setSelection(1, obj);
            this.checked = true;
            return false;

        }
    } else {
        return true;
    }
}


//
// SEND FUNCTIONS
//


function handleCSVUpload(e, oform) {
    if (oform.csv.value.length > 4) {
        var owin = openWindow(e, '/assets/blank.html', 210, 165, null, 'csvprocess');
        owin.document.open();
        owin.document.write('<br><div align="center" style="background:#EFEFEF; border: solid 1px gray; padding:20px;"><font face=arial size=2><b>Uploading</b><br><img src="' + document_root + '/assets/images/loading.gif" border="0" vspace=10><br><small>Please Wait</small></div>');
        owin.document.close();
        owin.document.title = 'Uploading CSV ...';
        owin.focus();
        return true;
    } else {
        customInfoBubble(getObjectFromEvent(e), 'Please select a File to upload');
        return false;
    }
}

function reSend(e, db_id) {
    if(getIdCount() > 0) {
        document.getElementById('rid').value = getCheckboxIds();
        document.getElementById('rdb').value = db_id;
        document.forms.resend.submit();
    } else {
        customInfoBubble(getObjectFromEvent(e), 'Please select a Contact to resend to');
    }

}


function execSend(id, count, send_cap, e, sendbutton) {
    if((send_cap !=0) && (count > send_cap)) {
        msg = "You are currently limited to " +  send_cap + " Emails per send.\n\n  Only the first " + send_cap + " recipients will receive this Email.\n\n                     Send anyway?"
    } else {
        msg = 'This will immediately send an Email to ' + count + " Contacts.\n\n                   Are you sure?"
    }

    if(confirm(msg)) {
        if(sendbutton) {
            sendbutton.disabled = true;
            sendbutton.value = "Now Sending...";
        }
        openWindow(e, package_root + "/send/exec_send.php?email_id=" + id,210,165);
    }
}

function scheduleSend(id, to) {
    if(confirm('This send will be saved, and sent at a time you specify.\n\n                              Continue?')) {
        window.location=package_root + "/send/schedule/schedule.php?email_id=" + id + "&to=" + to;
    }
}

function viewSendList(rcpt_count, url, e, dupes, message_id, db_id, quicksend){
    var db_id = db_id ? db_id : getRecordId();
    var quicksend_db_id = quicksend ? db_id : 0;
    if (db_id > 0) {
        if ((rcpt_count < 200) || confirm('There are over 200 Contacts, Are you sure you wish to view them all?')) {
            dupes = dupes ? '1' : '0';
            message_id = message_id ? message_id : '0';
            return openWindow(e,package_root + '/send/view_list.php?message_id='+message_id+'&db_id='+db_id+'&show_dupes='+dupes+'&quicksend_db_id='+quicksend_db_id+'&url=' + escape(url),600,430,'status=yes,scrollbars=yes,resizable=yes');
        }
    } else {
        customInfoBubble(getObjectFromEvent(e), 'Please select a Database');
        return false;
    }
}


function templateSaveAsNew(form) {
    if(confirm('Are you sure you want to Save this as a New Email?')) {
        form.inEdit.value=0;
        form.email_id.value=0;
        form.submit();
     }
}


function finishSend(name, count, time) {
    //if not minimized
    if(window.screenTop > 0 || (typeof(window.screenTop) == 'undefined')) {
        window.opener.location.replace("./index.php?msg=Email (" + name + ") sent to " + count + " subscribers in " + time + " secs");
    }
    window.close();

}

function copyMessage(e, message_id) {
    if(message_id) {
        var owin = openWindow(e, package_root + '/message/copy.php?id='+message_id+'', 510, 300);
    } else {
        customInfoBubble(getObjectFromEvent(e), 'Please select a Message to copy');
    }
}

function copyMessagePrompt(e, account_ids, message_id, message_type) {
    if(account_ids) {
        document.getElementById('copy_account_ids').value = account_ids;
        delayedConfirm(e, '3', 'Are you sure you wish to copy this ' + message_type + ' message to the chosen accounts?<br><br>This will copy the selected message to the accounts\' "Default" message folder. If this folder doesn\'t exist, the message will be copied to a "Copied ' + message_type + '" folder.', 'func', 0, 0, null, 'opener.copyMessageToAccounts();');
    } else {
        customInfoBubble(getObjectFromEvent(e), 'Please select an account to copy Message to');
    }
}

function copyMessageToAccounts(account_ids) {
    document.getElementById('message_copy_form').submit();
}

function moveMessage(e, eid) {
    if (eid) {
        var owin = openWindow(e, package_root + '/folders/move.php?t=2&id='+eid, 250, 131);
        owin.focus();
    } else {
        customInfoBubble(getObjectFromEvent(e), 'Please select a Message');
    }
}

function deleteFolder(fid, t) {
    if (confirm('      Are you sure you want to delete this Folder?\n\nAll items within this Folder will be assigned to another Folder.')) {
        location.href = package_root + '/folders/del.php?t='+t+'&id='+fid;
    }
}

function openLinkWindow(url) {
    var xWin = window.open(url,'links_popup', 'status=yes,width=580,height=480,scrollbars=no,resizable=yes');
    xWin.focus();
}


function saveAsNewDb(e, loc, count) {
    count == 1 ? contact = 'Contact' : contact = 'Contacts';
    if(count > 0) {
        if(confirm('Are you sure you want to save ' + count + ' ' + contact + ' into a new Database?')) {
            page = loc.replace(package_root, '').substring(1,loc.replace(package_root, '').length);
            page = page.substring(page.indexOf('/')+1, page.length);

            if(loc.indexOf('?') != -1 || page == 'users.php') {
                qstring = (loc.indexOf('?')!=-1) ? loc.substring(loc.indexOf('?'), loc.length) + '&save_new_db=true' : '?save_new_db=true';
                document.location = package_root + '/database/mod.php' + qstring;
            }
        }
    } else {
        customInfoBubble(getObjectFromEvent(e), 'There are currently no Contacts to save');
    }
}


// This is needed for save navaigate warning
function compactString(string) {
    string = string.replace(/[ \n\r]*/ig, '');
    string = string.replace(/(&nbsp;)*/ig, '');
    return string.toLowerCase();
}



function advancedSearch(e, js_window, page_name){
    //js_window = name of js window  to return to, vould be opener etc..
    //page_name = location that above window should return to.
    var win = openWindow(e,package_root + "/adv_search.php?page=" + escape(page_name) + "&jsw=" + js_window,550,400);
    return win;
}

function databaseInfo(event, db_id) {
    var oWin = openWindow(event, package_root + '/database/info.php?id=' + db_id,400,220, 'scrollbars=no,status=no');
        oWin.focus();
}

function openDbEmailPreview(event,selectname) {
    oSelect=document.getElementById(selectname);
    if(oSelect.options[oSelect.selectedIndex].value == 0) {
        return false;
    } else {
        return openWindow(event, package_root + '/preview.php?id='+oSelect.options[oSelect.selectedIndex].value, 500,500);
    }
}

function checkDbModMessageId(e) {
    if(document.getElementById('message_id').value == 0) {
        customInfoBubble(getObjectFromEvent(e), 'You must select a Message to copy or move');
        return false;
    } else {
        return true;
    }
}

function viewSendManagerPage(e, completed) {
    var id = getRecordId();
    if(id) {
        if(!completed) {
            switch(id) {
                case '1':
                    document.location = 'manage/pending.php';
                    break;
                case '2':
                    document.location = 'manage/progress.php';
                    break;
                default:
                    document.location = 'manage/paused.php';
                    break;
            }
        } else {
            switch(id) {
                case '1':
                    document.location = 'manage/completed.php';
                    break;
                case '2':
                    document.location = 'manage/rejected.php';
                    break;
                default:
                    document.location = 'manage/cancelled.php';
                    break;
            }
        }
    } else {
        customInfoBubble(getObjectFromEvent(e), 'Please select a send type');
    }
}


function rejectBatch(e, redir) {
    if(getRecordId()) {
        if(approval_ok[getRecordId()]) {
            openWindow(e, 'approval_confirm.php?a=reject&id='+getRecordId(), '450', '400');
        } else {
            alert('You must be the approver to approve a send');
        }
    } else {
        alert('Please select a send');
    }
}

function approveBatch(e, redir) {
    if(getRecordId()) {
        if(approval_ok[getRecordId()]) {
            openWindow(e, 'approval_confirm.php?a=approve&id='+getRecordId(), '450', '400');
        } else {
            alert('You must be the approver to approve a send');
        }
    } else {
        alert('Please select a send');
   }
}


function reinstateBatch(e, redir) {
    if(getRecordId()) {
        openWindow(e, 'approval_confirm.php?a=reinstate&id='+getRecordId(), '450', '400');
    } else {
        alert('Please select a send');
    }
}

function cancelBatch(obj, redir, id) {
    if(!id) {
        id = getRecordId();
    }
    if(id) {
        if(confirm('Are you sure you want to Cancel the Send?')) {
            document.location="../send/send_mod.php?t=cancel&id="+id+"&r="+redir;
        }
    } else {
        customInfoBubble(obj, 'Please select a send');
    }
}
function pauseBatch(obj, redir, id) {
    if(!id) {
        id = getRecordId();
    }
    if(id) {
        if(confirm('Are you sure you want to Pause the Send?')) {
            document.location="../send/send_mod.php?t=pause&id="+id+"&r="+redir;
        }
    } else {
        customInfoBubble(obj, 'Please select a send');
    }
}

function togglePauseBatch(obj, redir, id) {
    if(!id) {
        id = getRecordId();
    }
    if(id) {
        if(confirm('Are you sure you want to Pause / Resume the Send?')) {
            document.location="../send/send_mod.php?t=togglepause&id="+id+"&r="+redir;
        }
    } else {
        customInfoBubble(obj, 'Please select a send');
    }
}

function unpauseBatch(obj, redir, id) {
    if(!id) {
        id = getRecordId();
    }
    if(id) {
        if(confirm('Are you sure you want to resume sending?')) {
            document.location="../send/send_mod.php?t=unpause&id="+id+"&r="+redir;
        }
    } else {
        customInfoBubble(obj, 'Please select a send');
    }
}

function rescheduleBatch(obj, redir, id) {
    if(!id) {
        id = getRecordId();
    }
    if(id) {
        document.location="../send/reschedule.php?id="+id+"&r="+redir;
    } else {
        customInfoBubble(obj, 'Please select a send');
    }
}

function monitorBatch(obj, email_id) {
    id = getRecordId();
    if(id) {
        document.location="../send/monitor.php?email_id="+email_id+"&batch_id="+id;
    } else {
        customInfoBubble(obj, 'Please select a send');
    }
}


function updateThrottle(num, openerupdate) {
    limit = document.getElementById('throttle_limit').value;
    delay = document.getElementById('throttle_delay').value;
    updatediv = document.getElementById('_updated_total');

    if(limit > 0) {
        per_hour = (limit / (delay / 3600));

        rate = (Math.round(num / per_hour));
        if(rate > 24) {
            rate = Math.round(rate / 24);
            if(rate == 1) {
                str = ' Day';
            } else {
                str = ' Days';
            }
        } else {
            if(rate == 1) {
                str = ' Hour';
            } else {
                str = ' Hours';
            }
        }
    } else {
        rate = '';
        str = 'Immediate';
    }
    updatediv.innerHTML =  rate + str;
    if(openerupdate == 1) {
        window.opener.updateOpenerThrottle(limit, delay, (rate + str));
        window.close();
    }
}

function updateOpenerThrottle(limit, delay, est) {

    if(limit == 0) {
        txt = 'None';
    } else if(delay == 60) {
        txt = limit + ' per Minute';
    } else if(delay == 3600) {
        txt = limit + ' per Hour';
    } else {
        txt = limit + ' per Day';
    }
    document.getElementById('_time_to_send').innerHTML = est;
    document.getElementById('_send_rate_text').innerHTML = txt;
    document.getElementById('_throttle_delay').value = delay;
    document.getElementById('_throttle_limit').value = limit;
}

function emailApprovalDetails(e, batch_id) {
    openWindow(e, 'approval_details.php?id='+batch_id, '450', '400');
}

function previewTemplate(e, alias) {
    if (typeof(selected_tpl) != 'undefined') {
        openWindow(e, '/' + alias + '/message/email/view.php?id=' + selected_tpl + '&a=' + selected_tpl_account, 650, 600, 'scrollbars=1');
    } else {
        customInfoBubble(getObjectFromEvent(e), 'Please select a Template');
    }
}

function useTemplate(e) {
    if (typeof(selected_tpl) != 'undefined') {
        location.href = 'wizard/design.php?id=' + selected_tpl;
    } else {
        customInfoBubble(getObjectFromEvent(e), 'Please select a Template');
    }
}

function checkSpam(e, email_id) {
    openWindow(e, '/' + package_alias + '/message/email/spam_check.php?id=' + email_id, 600, 400, 'scrollbars=1');
}

function createSend(e, id) {
    if(getRecordId()) {
        document.location='options.php?message_id='+id;
    } else {
        customInfoBubble(getObjectFromEvent(e), 'Please select a Message');
    }
}


function confirmCancelSmsRequest(btn) {
    if (confirm('This will cancel your request for SMS features.\n\nIf you wish to have SMS features enabled in the future, please contact your Administrator.')) {
        location.href='index.php?sms_action=cancel';
    }
}


function confirmResendSmsCode(btn) {
    if (confirm('Please confirm you wish your confirmation code to be sent once again.')) {
        location.href='index.php?sms_action=resend';
    }
}



function gotoModifyAccountMobilePhone() {
    document.location.href = '/account/details.php';
}


function recursiveEnableButtons(elem) {
    if(elem && elem.childNodes) {
        for(var i=0; i < elem.childNodes.length; i++) {
            recursiveEnableButtons(elem.childNodes[i]);
            if(elem.childNodes[i].nodeName == 'INPUT') {
                elem.childNodes[i].disabled = false;
            }
        }
    }
}


function enableEmailSaveButtons() {
    recursiveEnableButtons(document.getElementById('qf_footer'));
    recursiveEnableButtons(document.getElementById('qf_footer_2'));
    source_view_elem = document.getElementById('source_button');
    if(source_view_elem) {
        source_view_elem.disabled = false;
    }
}


function unsubscribeContactsFromResponses(unsubscribe_button) {
    if (getRecordId() == '') {
        customInfoBubble(unsubscribe_button, 'Please select at least one Contact to Unsubscribe.');
    } else {
        var url = new Url();
        url.delVar('unsubscribe_responses');
        url.setVar('unsubscribe_responses', getRecordId());
        document.location.replace(url.getUrl());
    }
}

function handleBounceSMSClick() {
    document.location.href = "failed_sms.php?id=" + getRecordId();
}
