
/* $Id: em.js 29145 2010-01-24 23:49:41Z pvandijk $ */

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, type) {
    if (type == undefined) {
        type = 2;
    }
    var owin = openWindow(e, '/account/payment/credits.php?popup=true&type='+type, 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 : 700;
    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 customSaveAsTemplate(form, action) {
    if(confirm('Are you sure you want to save this as a Template Email?')) {
        var save_as_template = document.createElement('input');
        save_as_template.setAttribute('id', 'save_as_template');
        save_as_template.setAttribute('name', 'save_as_template');
        save_as_template.setAttribute('type', 'hidden');
        save_as_template.setAttribute('value', 'true');
        form.appendChild(save_as_template);
        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) {
    var id = getRecordId();

    if (id) {
        var message  = 'Are you certain you wish to delete the selected Send?\n\n';

        message += 'Deleting this Send will:\n';
        message += '<ul>';
        message += '<li>Permanently remove the Send</li>';
        message += '<li>Stop recording and remove display of Statistics for this Send</li>';
        message += '<li>Stop processing bounces and complaints for this Send</li>';
        message += '<li>Prevent this Send\'s recipients from using "Send to Friend" links</li>';
        message += '</ul>';

        delayedConfirm(e, 3, message, package_root +'/statistics/del.php?id=' + getRecordId() + '&r=' + escape(document.location), 0, 0, '', '', '', '', 370, 215);

    } 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) {
        if (!oform.csv.value.match(/([^\/\\]+)\.(csv|txt)$/i)) {
            customInfoBubble(getObjectFromEvent(e), 'Files having .csv or .txt are only allowed to be uploaded in this process.');
            return false;
        } else {
            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 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, has_advanced_search) {
    var url = package_root + '/database/mod.php?save_new_db=true';
    url += '&has_advanced_search='+has_advanced_search;

    if (getIdCount() == 0) {
        if (confirm('Are you sure you want to save All Contacts into a new Database?')) {
            url += '&save_entire_db=true';
            posthref(url);
        }

    } else {
        var contact = getIdCount() == 1 ? 'Contact' : 'Contacts';
        if (confirm('Are you sure you want to save ' + getIdCount() + ' ' + contact + ' into a new Database?')) {
            url += '&save_entire_db=false&contact_id=' + getCheckboxIds();
            posthref(url);
        }
    }
}


// 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 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 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();
}

function checkCompileStatus() {
    xmlhttpCall('POST', checkCompileStatusCallback, document_root + '/em/statistics/check_compile_status.php?id=' + compile_status_batch_id);
}

function checkCompileStatusCallback(response) {
    if(response == 1) {
        throbber = document.getElementById('throbber_image');
        throbber.src = '/assets/images/throbber_2_green.gif';

        setTimeout('location.reload();', 800);
    } else {
        setTimeout('checkCompileStatus()', 2000);
    }
}

var csv_click_handler_dd = false, csv_click_handler_url = '';
var wait_wrapper_obj = false, disabled_obj = false;
var click_handler_setup = false;

function reportCSVClickHandler(dest_url)
{
    if(dest_url) {
        csv_click_handler_url = dest_url;
    }

    if(click_handler_setup == false) {
        click_handler_setup = true;

        csv_click_handler_dd = new Disable_Div('csv_click_handler');
        csv_click_handler_dd.addObject(document.body);

        csv_click_handler_div = document.createElement('div');
        csv_click_handler_div.id = 'csv_click_handler_div';
        csv_click_handler_div.innerHTML = '<br/><img src="/assets/images/throbber_2.gif"><br/><br/><span style="font-size: 11pt; color: #afafaf">Compiling Report</span><br/><br/>Please wait while we update the statistical information for your report.</b>';

        csv_click_handler_div.style.textAlign  = 'center';
        csv_click_handler_div.style.background = 'white';
        csv_click_handler_div.style.border     = '1px solid #6f6f6f';
        csv_click_handler_div.style.color      = '#6f6f6f';
        csv_click_handler_div.style.position   = 'fixed';
        csv_click_handler_div.style.fontFamily = 'Tahoma';
        csv_click_handler_div.style.fontSize   = '10pt';
        csv_click_handler_div.style.fontWeight = 'bold';

        csv_click_handler_div.style.top       = 100;
        csv_click_handler_div.style.left      = 220;
        csv_click_handler_div.style.width     = 350;
        csv_click_handler_div.style.height    = 150;

        csv_click_handler_div.style.zIndex  = 100;
        csv_click_handler_div.style.display = 'none';

        document.body.appendChild(csv_click_handler_div);
    }

    xmlhttpCall('POST', checkCompileStatusCallbackCSV, document_root + '/em/statistics/check_compile_status.php?id=' + compile_status_batch_id);
}

function ie_disable_init() {
    csv_click_handler_div.style.cssFloat = 'left';
    csv_click_handler_div.style.position = 'absolute';

    window.onresize        = ie_disable_reposition;
    document.body.onscroll = ie_disable_reposition;
    ie_disable_reposition();

}

function ie_disable_reposition() {
    var view_width = document.body.clientWidth, view_height = document.body.clientHeight;
    var view_x = document.body.scrollLeft, view_y = document.body.scrollTop;

    csv_click_handler_dd.div.style.left  = view_x + 'px';
    csv_click_handler_dd.div.style.top   = view_y + 'px';
    csv_click_handler_dd.div.style.width = view_width + 'px';

    csv_click_handler_div.style.left = (Math.floor(view_width / 2) + view_x - 150) + 'px';
    csv_click_handler_div.style.top = (Math.floor(view_height / 2) + view_y - 50) + 'px';
}

function checkCompileStatusCallbackCSV(response) {
    if(response == 1) {
        csv_click_handler_dd.setVisible(false);
        csv_click_handler_div.style.display = 'none';
        document.location = csv_click_handler_url;
    } else {
        // we actually only blank out the page after the initial call returns..
        csv_click_handler_dd.setVisible(true);
        if(ie) {
            ie_disable_init();
        }
        document.getElementById('csv_click_handler_div').style.display = 'block';
        setTimeout('reportCSVClickHandler()', 2000);
    }
}

function setLastEditing(message_id) {
    APP.XHR.request(
        document_root + '/xmlhttp/set_last_editing_time.php',
        'POST',
        {'action':'set', 'msg_id':message_id},
        false, function () {}, false, false, true
    );
    setTimeout('setLastEditing("'+message_id+'")', 60000);
}

function checkLastEditing(message_id) {
    APP.XHR.request(
        document_root + '/xmlhttp/set_last_editing_time.php',
        'POST',
        {'action':'get', 'msg_id':message_id},
        function (response) {
            showAlert(response, message_id);
        }
    );
}

function showAlert(response, message_id) {
    var response = eval(response);
    if (response['result']) {
        setTimeout('setLastEditing("'+message_id+'")', 60000);
    } else {
        APP.UI.PageWarning.show('This message is currently being edited by another person. <a href="javascript:void(null);" onclick="toggleCheckForSave(true, true); APP.UI.PageWarning.hide();" >Cancel <img src="/assets/images/ddw/delete.png" border="0" style="vertical-align:middle;" /></a>');
    }
}

function toggleCheckForSave(disable_checking, reset_after_delay) {

    // ensure checkForSave is not run when doing formatting (only required for IE)
    if (typeof(parent.APP) != 'undefined' && typeof(parent.APP.DDW) != 'undefined' && typeof(parent.APP.DDW.update_click) != 'undefined') {
        parent.APP.DDW.update_click = disable_checking;

        if (reset_after_delay) {
            setTimeout ( 'toggleCheckForSave(' + !disable_checking + ', false)', 500 );
        }
    }
}

function writeBackup(message_id, message_type) {
    setTimeout(function(){
        var plain_text = '';
        var html       = '';
        var do_backup  = true;

        switch (message_type) {
            case 'html':
                html = getBodySource();
                break;

            case 'plain-html':
                plain_text = JQ('#plain_msg').val();
                html       = getBodySource();
                break;

            case 'plain':
                plain_text = JQ('#plain_msg').val();
                break;

            case 'raw_html':
                html = JQ('#raw_html_msg').val();
                break;

            case 'template':
                if (APP.DDW.Structure.is_autosaving && parent.APP.DDW.requires_backup) {
                    var template = {
                        'id':                   APP.DDW.Structure.template_id,
                        'bg_colour':            '#ffffff',
                        'canvas':               APP.DDW.Structure.getCanvasArray(),
                        'has_text_override':    APP.DDW.Structure.has_text_override,
                        'text':                 (APP.DDW.Structure.has_text_override ? window.parent.APP.DDW.Text.getVal() : ''),
                        'partially_restricted': APP.DDW.partially_restricted
                    }
                    html = JSON.stringify(template);
                } else {
                    do_backup = false;
                }

                break;
        }

        if (do_backup) {
            APP.XHR.request(
                document_root + '/xmlhttp/save_message_backups.php',
                'POST',
                {'action':'save', 'msg_id':message_id, 'msg_type':message_type, 'msg_html':html, 'msg_text':plain_text},
                function (response) {
                    response   = eval(response);
                    var result = response['result'];
                    if (result) {
                        // ....
                    } else {
                        // ....
                    }
                }, false, false, false, true, true
            );

            if (message_type == 'template') {
                parent.APP.DDW.requires_backup = false;
            }
        }

        setTimeout(function(){
            writeBackup(message_id, message_type);
        }, 30000);
    }, 30000);
}

function readBackup(message_id, message_type) {

    if (typeof(message_type) == 'undefined') {
        var message_type = '';
    }

    var url = new Url();
    if (!url.getVar('b')) {
        APP.XHR.request(
            document_root + '/xmlhttp/save_message_backups.php',
            'POST',
            {'action':'read', 'msg_id':message_id, 'type':message_type},
            function (response) {
                response   = eval(response);

                if (response['result']['html'] || response['result']['text']) {
                    if (message_type == 'template' && typeof(APP.DDW) != 'undefined') {
                        APP.DDW.Frame.frame_window.APP.DDW.Message_Area.addMessage('alert', 'Resume editing unsaved message?', '<a href="javascript:void(null);" id="appddwframe_resume_backup">Yes</a> or <a href="javascript:void(null);" onclick="window.parent.toggleCheckForSave(true, true); window.parent.deleteBackup('+message_id+'); APP.DDW.Message_Area.removeCurrent();">No</a>', true);
                        var resume_link = APP.DDW.Frame.frame_window.JQ('#appddwframe_resume_backup');
                    } else {
                        var msg  = 'You were editing '+(message_id ? 'this' : 'a new')+' message'+(response['result']['time'] ? ' on <b>'+response['result']['time']+'</b>' : '')+' and it was not saved. Do you want to resume editing or discard it? ';
                        msg     += '<a href="javascript:void(null);" id="resume_backup">Resume <img src="/assets/images/icon_cleaned.gif" border="0" style="vertical-align:middle;" /></a>&nbsp;<a href="javascript:void(null);" onclick="toggleCheckForSave(true, true); deleteBackup('+message_id+');" >Discard <img src="/assets/images/ddw/delete.png" border="0" style="vertical-align:middle;" /></a>';
                        APP.UI.PageWarning.show(msg);
                        var resume_link = JQ('#resume_backup');
                    }
                } else {
                    return false;
                }
                var html_body = response['result']['html'];
                var text_body = response['result']['text'];
                var type      = response['result']['type'];

                resume_link.click(function(){
                    switch (message_type) {

                        case 'plain-html':
                            JQ('#plain_msg').val(text_body);
                            setBodySource(html_body);
                            break;

                        case 'html':
                            setBodySource(html_body);
                            break;

                        case 'plain':
                            JQ('#plain_msg').val(text_body);
                            break;

                        case 'raw_html':
                            JQ('#raw_html_msg').val(html_body);
                            break;

                        case 'template':
                            var template_json               = APP.DDW.Frame.frame_window.APP.DDW.Structure.getTemplate();
                            template_json.canvas            = html_body.canvas;
                            template_json.text              = html_body.text;
                            template_json.has_text_override = html_body.has_text_override;

                            APP.DDW.Frame.frame_window.APP.DDW.Message_Area.removeCurrent();
                            APP.DDW.Frame.frame_window.APP.DDW.Structure.drawCanvas(template_json);
                            APP.DDW.Frame.frame_window.APP.DDW.Structure.repositionCanvas();
                            break;

                        default:
                            // this must be a new message.
                            var newLoc = false;
                            switch (response['result']['type']) {
                                case 'template':   newLoc = 'ddw/designer.php?b=1';         break;
                                case 'plain-html': newLoc = 'email/html_plain.php?b=1';     break;
                                case 'html':       newLoc = 'email/html.php?b=1';           break;
                                case 'plain':      newLoc = 'email/plain.php?b=1';          break;
                                case 'raw_html':   newLoc = 'email/raw.php?b=1';       break;
                            }
                            if (newLoc) {
                                location.href = newLoc;
                                return;
                            }
                            break;

                    }
                    APP.UI.PageWarning.hide();
                });
            }, false, false, false, true
        );
    }
}

function deleteBackup(message_id) {
    APP.XHR.request(
        document_root + '/xmlhttp/save_message_backups.php',
        'POST',
        {'action':'delete', 'msg_id':message_id},
        function (response) {
            APP.UI.PageWarning.hide();
        }, false, false, false, true
    );
}


