$(function() {
    $("#close-window").click(function() {
        window.close();
    })
    $("#close-window2").click(function() {
        window.close();
    })
});

$.fn.disable = function() {
    return this.each(function() {
        if (typeof this.disabled != "undefined") this.disabled = true;
    });
}

$.fn.enable = function() {
    return this.each(function() {
        if (typeof this.disabled != "undefined") this.disabled = false;
    });
}

start = 0;

function log(msg) {
    var d = new Date();
    if (start == 0) {
        start = d.getTime();
        var now = 0;
    } else {
        var now = d.getTime() - start;
    }
    console.log('[' + now + '] ' + msg);
}

function open_window(url, name, options) {
    if (typeof options == 'undefined') {
        options = 'width=1000,height=800,toolbar=0,location=0,menubar=0,directories=0,resizable=1,scrollbars=1';
    }
    var win = window.open(url, name, options);
    win.focus();
}

function open_new_window(url, name) {
    var win = window.open(url, name);
    win.focus();
}

function activate_row_selection() {
    $("table.selectrow tbody tr").hover(
        function() {
            $(this).addClass("hoverrow");
        },
        function() {
            $(this).removeClass("hoverrow");
        }
        ).click(
        function() {
            $(this).parent().children().removeClass("selectedrow");
            $(this).addClass("selectedrow");
        }
        );
}

function activate_message_buttons() {
    $("#message-buttons").each(function() {
        $("#refresh", this).click(function() {
            window.location.href = window.location.href;
        })
        $("#new", this).click(function() {
            $(".edit").enable();
            $(".view").disable();
            $("#new-message").fadeIn("slow");
        })
        $("#cancel", this).click(function() {
            $(".edit").disable();
            $(".view").enable();
            $("#new-message").fadeOut("slow");
        });
    });
}

function activate_bplan_window() {
    $("ul.tree li:has(ul) > :checkbox").click(function() {
        $(this).parent().toggleClass('closed');
    }).not(":checked").parent().addClass("closed");
    var oddeven = getTableClasses("oddeven\\d+");
    for (i in oddeven) {
        var n = parseInt(oddeven[i].substring(7));
        if (n > 1) {
            $(".oddeven" + n + " tbody tr").each(function(row) {
                if (((row / n) & 1) == 0) {
                    $(this).addClass("oddgroup");
                }
            });
        }
    }
    init();
}

function activate_background() {
    $("div.background > select").change(function() {
        $(this).parents("div.background").children("table.category").hide();
        $("#" + this.id + "_" + $(this).val()).show();
    });
    $("div.background :radio").click(function(evt) {
        var id = $(this).parents("div.background").children("div.target").text();
        var content = $(this).parent().next().html();
        tinyMCE.execInstanceCommand(id, "mceFocus");
        tinyMCE.activeEditor.setContent(content);
        $(this).attr("checked", false);
    });
}

function activate_form_view() {
    $("ul.document-form table[border]").addClass("form-view-box");
}

function activate_expand() {
    $("table.group-header :button.expand").click(toggle_expand);
}

function activate_expand_tenant() { 
    $("table.edittext_header :button.expand").click(toggle_expand);
}

function toggle_expand() {
    trigger_expand(this);
}

function trigger_expand(button) {
    button.value = button.value == 'Expand' ? 'Collapse' : 'Expand';
    var section = $(button).siblings(".section").text();
    var content = $("#section" + section);
    if (button.value == 'Expand') {
        content.fadeOut('slow');
    } else {
        content.fadeIn('slow');
    }
}

function fieldToolTips(expr) {
    $(expr).tooltip({
        delay: 0,
        showURL: false,
        track: true,
        showBody: ' : '
    });
}

function edit_source() {
    $(this).siblings(":button.edit").enable();
    $(this).siblings(":button.view").disable();
    $(this).disable();
    var section = $(this).siblings(".section").text();
    var content = $("#section" + section);
    if (content.is(":hidden")) {
        trigger_expand($(this).siblings(".expand")[0]);
    }
    var edit = $("#edit" + section);
    edit.children("textarea").val(edit.children("div").text());
    edit.fadeIn();
}

function cancel_edit() {
    $(this).siblings(":button.edit").disable();
    $(this).siblings(":button.view").enable();
    $(this).disable();
    var section = $(this).siblings(".section").text();
    var edit = $("#edit" + section);
    edit.children("textarea").val("");
    edit.fadeOut();
}

function toggle_bundle_document() {
    var cb = this;
    var orderid = $("#document-info .orderid").text();
    var label = $(cb).siblings(".document-label").text();
    if (cb.checked) {
        var url = '/admin/bundle-add-document/' + orderid + '/' + label;
    } else {
        $(cb).parents().siblings(".buttons").find(":button").disable();
        var url = '/admin/bundle-remove-document/' + orderid + '/' + label;
    }
    $.ajax({
        url: url,
        type: 'GET',
        timeout: 5000,
        error: function() {
            if (cb.checked) {
                alert("Failed to add document.");
            } else {
                alert("Failed to remove document.");
            }
            cb.checked = !cb.checked;
        },
        complete: function() {
            if (cb.checked) {
                $(cb).parents().siblings(".buttons").find(":button").enable();
            }
        }
    });
}

function change_site() {
    $(":submit.update").enable();
}

function change_company() {
    $(".party").disable();
    $.ajax({
        url: '/admin/getusers',
        data: {
            member_id: $(this).val()
        },
        dataType: 'json',
        type: 'GET',
        timeout: 5000,
        error: function() {
            alert("Error updating users.  Please reload the page.");
        },
        success: function(data) {
            $("#Company");
            $("#User").html(data.users);
            $("#Phone").val(data.phone),
            $("#Email_Address").val(data.email)
            $(".party").enable();
        }
    });
}

function change_user() {
    $(":submit.update").enable();
}

function revert_changes() {
    document_revert_changes(this, '/admin/order-revert');
}

function document_revert_changes(el, url) {
    var section = $(el).siblings(".section").text();
    var sectiondiv = $("#section" + section);
    if (sectiondiv.is(".content-original")) {
        alert("Document template has not been modified.");
        return;
    }
    var orderid = $("#document-info .orderid").text();
    var textid = $(el).siblings(".textid").text();
    if (!confirm("This will revert ALL changes to this template for this order.\n\nAre you sure you want to revert back to the master document template?")) {
        return;
    }
    var revert = $(el);
    revert.parent().children().disable();
    $.ajax({
        url: url,
        type: 'POST',
        data: {
            orderid: orderid,
            textid: textid,
            label: $("#document-info .document-label").text()
        },
        dataType: 'json',
        timeout: 5000,
        error: function() {
            alert("Error reverting to the document template.");
        },
        success: function(data) {
            $("#edit" + section + " div").text(data.source);
            sectiondiv.html(data.html);
            revert.siblings(".textid").text('');
            sectiondiv.removeClass("content-modified");
            sectiondiv.addClass("content-original");
            fieldToolTips("#section" + section + " .document-field");
        },
        complete: function() {
            revert.parent().children(".view").enable();
        }
    });
}

function save_edit() {
    document_save_edit(this, '/admin/order-modify');
}

function document_save_edit(el, url) {
    var save = $(el);
    save.parent().children().disable();
    var section = $(el).siblings(".section").text();
    var edit = $("#edit" + section);
    var textarea = edit.children("textarea");
    var content = textarea.val();
    textarea.disable();
    var textdiv = $(el).siblings(".textid");
    var textid = textdiv.text();
    var contentid = save.siblings(".contentid").text();
    var orderid = $("#document-info .orderid").text();
    $.ajax({
        url: url,
        type: 'POST',
        data: {
            orderid: orderid,
            label: $("#document-info .document-label").text(),
            contentid: contentid,
            textid: textid,
            content: content
        },
        dataType: "json",
        timeout: 5000,
        error: function() {
            alert("Error saving changes.");
            save.siblings(":button.edit").enable();
            save.enable();
        },
        success: function(data) {
            var sectiondiv = $("#section" + section);
            sectiondiv.removeClass("content-original");
            sectiondiv.addClass("content-modified");
            sectiondiv.html(data.html);
            textdiv.text(data.textid);
            edit.children("div").text(textarea.val());
            textarea.val('');
            edit.fadeOut();
            save.siblings(":button.view").enable();
            fieldToolTips("#section" + section + " .document-field");
        },
        complete: function() {
            textarea.enable();
        }
    });
}

function admin_document_action(url, windowname) {
    var orderid = $("#document-info .orderid").text();
    open_window(url + '/' + orderid, windowname);
}

function admin_edit_document() {
    admin_document_action('/admin/edit-document', 'editdocument');
}

function admin_view_document() {
    admin_document_action('/admin/view-document', 'viewdocument');
}

function admin_preview_document() {
    admin_document_action('/admin/preview-document', 'previewdocument');
}

function admin_view_source() {
    admin_document_action('/admin/view-source', 'viewsource');
}

function admin_download_pdf() {
    var orderid = $("#document-info .orderid").text();
    window.location.href = '/admin/download-pdf/' + orderid;
}

function admin_generate_pdf() {
    var orderid = $("#document-info .orderid").text();
    window.location.href = '/admin/generate-pdf/' + orderid;
}

function admin_bplan_open() {
    admin_document_action('/admin/open-business-plan', 'adminbplan');
}

function admin_bplan_preview() {
    var doc = $("#bplandocument").val();
    var orderid = $("#document-info .orderid").text();
    open_window('/admin/preview-document/' + orderid + '/' + doc, 'previewdocument');
}

function admin_bplan_preview_pdf() {
    var doc = $("#bplandocument").val();
    var orderid = $("#document-info .orderid").text();
    window.location.href = '/admin/generate-pdf/' + orderid + '/' + doc;
}

function admin_bplan_approved_pdf() {
    var doc = $("#bplandocument").val();
    var orderid = $("#document-info .orderid").text();
    window.location.href = '/admin/download-pdf/' + orderid + '/' + doc;
}

function bundle_revert_changes() {
    document_revert_changes(this, '/admin/bundle-revert');
}

function bundle_save_edit() {
    document_save_edit(this, '/admin/bundle-modify');
}

function admin_bundle_action(el, url, windowname) {
    var orderid = $("#document-info .orderid").text();
    var label = $(el).parent().parent().find(".document-label").text();
    open_window(url + '/' + orderid + '/' + label, windowname);
}

function bundle_edit_document() {
    admin_bundle_action(this, '/admin/bundle-edit-document', 'editdocument');
}

function bundle_view_document() {
    admin_bundle_action(this, '/admin/bundle-view-document', 'viewdocument');
}

function bundle_preview_document() {
    admin_bundle_action(this, '/admin/bundle-preview-document', 'previewdocument');
}

function bundle_view_source() {
    admin_bundle_action(this, '/admin/bundle-view-source', 'viewsource');
}

function bundle_download_pdf() {
    var orderid = $("#document-info .orderid").text();
    var label = $(this).parent().parent().find(".document-label").text();
    window.location.href = '/admin/bundle-download-pdf/' + orderid + '/' + label;
}

function bundle_generate_pdf() {
    var orderid = $("#document-info .orderid").text();
    var label = $(this).parent().parent().find(".document-label").text();
    window.location.href = '/admin/bundle-generate-pdf/' + orderid + '/' + label;
}

function client_read() {
    ack_read('/message/read', this);
}

function admin_read() {
    ack_read('/admin/read-message', this);
}

function bookkeeper_read() {
    ack_read('/service/bookkeeping/read-message', this);
}

function ack_read(url, row) {
    if ($(row).hasClass("unread")) {
        var orderid = $(row).find(".orderid").text();
        var messageid = $(row).find(".messageid").text();
        $.ajax({
            url: url + '/' + orderid + '/' + messageid,
            dataType: 'json',
            timeout: 5000,
            success: function(data) {
                $(row).removeClass("unread");
                $(row).find(".status").text("Read");
                $("#message-body textarea").val($(row).find("div.body").text());
            }
        });
    } else {
        $("#message-body textarea").val($(row).find("div.body").text());
    }
}

function log_details() {
    $("#log-details textarea").val($(this).find("div.details").text());
}

function navigate_page(page, formname) {
    if(formname != 1){
        document.forms[0].page.value = page;
        document.forms[0].submit();
    } else {
        document.theFormStaffComms.page.value = page;
        document.theFormStaffComms.submit();
    }
    return true;
}

function form_readonly() {
    $(function() {
        $(".update-document").disable();
        $("table.form :text, table.form textarea").attr("readonly", true);
        $("table.form select").disable().css("color", "black");
        //$("table.form :checked").replaceWith('<div class="selected-readonly">X</div>');
        //$("table.form :radio, table.form :checkbox").replaceWith('<div class="unselected-readonly">&nbsp;</div>');
        $("div.group-content :text, div.group-content textarea").attr("readonly", true);
        $("div.group-content select").disable().css("color", "black");
        //$("div.group-content :checked").replaceWith('<div class="selected-readonly">X</div>');
        //$("div.group-content :radio, div.group-content :checkbox").replaceWith('<div class="unselected-readonly">&nbsp;</div>');
    });
}

function article_toggle_active() {
    var cb = this;
    var id = $(this).parent().next().text();
    $.ajax({
        url: '/admin/article/toggle' + id,
        timeout: 5000,
        dataType: 'json',
        success: function(data) {
            cb.checked = data.checked;
        }
    });
}

function edit_article() {
    var id = $(this).find(":nth-child(2)").text();
    window.location.href = '/admin/article/edit/' + id;
}

function create_newsletter(evt) {
    if ($("#articles :checked").size() == 0) {
        alert("You must select at least one article.");
        evt.preventDefault();
        return;
    }
}

function select_all_newsletters() {
    $("#articles :checkbox").attr("checked", true);
}

function deselect_all_newsletters() {
    $("#articles :checkbox").attr("checked", false);
}

function newsletter_edit_html() {
    $(this).siblings(":button.edit").enable();
    $(this).siblings(":button.view").disable();
    $(this).disable();
    var content = $("#section-html");
    if (content.is(":hidden")) {
        trigger_expand($(this).siblings(".expand")[0]);
    }
    var edit = $("#edit-html");
    edit.children("textarea").val(content.html());
    $("#section-html").fadeOut();
    edit.fadeIn();
}

function newsletter_schedule(){
    var cron = $("#set-cron");
    cron.fadeIn();    
    $(this).siblings(":button.cancel-schedule").enable();
    $(this).disable();
}

function newsletter_schedule_cancel(){
    var cron = $("#set-cron");
    cron.fadeOut();    
    $(this).siblings(":button.set-schedule").enable();
    $(this).disable();
}

function newsletter_save_html() {
    $(this).siblings(":button.edit").disable();
    $(this).siblings(":button.view").enable();
    $(this).disable();
    var old_source = $("#section-html").html();
    var new_source = $("#edit-html textarea").val();
    $("#section-html").html(new_source);
    $("#edit-html").fadeOut();
    if (old_source == new_source) {
        $(this).siblings(".revert").disable();
    } else {
        $(this).siblings(".revert").enable();
    }
}

function newsletter_cancel_html() {
    $(this).siblings(":button.edit").disable();
    $(this).siblings(":button.view").enable();
    $(this).disable();
    $("#edit-html textarea").val($("#section-html").html());
    $("#edit-html").fadeOut();
    $("#section-html").fadeIn();
}

function newsletter_revert_html() {
    var content = $("#edit-html div.content-backup").text();
    $("#section-html").html(content);
    $("#edit-html textarea").val(content);
    $(this).disable();
}

function newsletter_edit_text() {
    $(this).siblings(":button.edit").enable();
    $(this).siblings(":button.view").disable();
    $(this).disable();
    var content = $("#section-text");
    if (content.is(":hidden")) {
        trigger_expand($(this).siblings(".expand")[0]);
    }
    var edit = $("#edit-text");
    edit.children("textarea").val(content.children("pre").text());
    edit.fadeIn();
}

function newsletter_save_text() {
    $(this).siblings(":button.edit").disable();
    $(this).siblings(":button.view").enable();
    $(this).disable();
    var old_source = $("#section-text").html();
    var new_source = $("#edit-text textarea").val();
    $("#section-text pre").text(new_source);
    $("#edit-text").fadeOut();
    if (old_source == new_source) {
        $(this).siblings(".revert").disable();
    } else {
        $(this).siblings(".revert").enable();
    }
}

function newsletter_cancel_text() {
    $(this).siblings(":button.edit").disable();
    $(this).siblings(":button.view").enable();
    $(this).disable();
    $("#edit-text textarea").val($("#section-text pre").text());
    $("#edit-text").fadeOut();
}

function newsletter_revert_text() {
    var content = $("#edit-text div.content-backup").text();
    $("#section-text pre").text(content);
    $("#edit-text textarea").val(content);
    $(this).disable();
}


function get_state_input(state) {
    return document.bp['instate' + state];
}

function get_state_div(state) {
    return find_by_id('statediv' + state);
}

function is_state_checked(state) {
    return get_state_input(state).checked;
}

function set_state(state, checked) {
    get_state_div(state).style.display = checked ? 'block' : 'none';
}

function toggle_state(state) {
    set_state(state, is_state_checked(state));
}

function get_category_input(category) {
    return document.bp[category];
}

function get_category_div(category) {
    return find_by_id('item' + category);
}

function is_category_checked(category) {
    return get_category_input(category).checked;
}

function set_category(category, checked) {
    var catdiv = get_category_div(category);
    if (catdiv != null) {
        catdiv.style.display = checked ? 'block' : 'none';
    }
}

function toggle_category(category) {
    set_category(category, is_category_checked(category));
}

function get_category_input2(category) {
    return document.bp[category];
}

function get_category_div2(category) {
    return find_by_id('__' + category);
}

function is_category_checked2(category) {
    return get_category_input2(category).checked;
}

function set_category2(category, checked) {
    var catdiv = get_category_div2(category);
    if (catdiv != null) {
        catdiv.style.display = checked ? 'block' : 'none';
    }
}

function toggle_category2(category) {
    set_category2(category, is_category_checked2(category));
}

states = ['wa', 'nsw', 'vic', 'sa', 'qld', 'tas', 'nt', 'act'];

function set_all_states(checked) {
    for (var i=0; i<states.length; i++ ) {
        set_state(states[i], checked);
    }
}

function toggle_index(link) {
    /* using <div> instead of <td>*/
    var sidemenu = find_by_id('sidemenu');
    if (sidemenu.style.display == 'none') {
        sidemenu.style.display = 'block';
        link.innerHTML = 'Hide Index';
    } else {
        sidemenu.style.display = 'none';
        link.innerHTML = 'Show Index';
    }
}

function trim(s) {
    return s.replace(/^\s+|\s+$/g, '');
}

function build_plan(current) {
    document.bp.current.value = current;
    document.bp.submit();
    window.open('buildplan.php',
        'buildplan',
        'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=600,height=400,left=100,top=100');
}

function show_plan(current) {
    document.bp.current.value = current;
    document.bp.submit();
    window.open('wholeplan.php',
        'showplan',
        'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=800,height=800,left=100,top=100');
}

function preview(section_name) {
    var window_name = 'preview_' + section_name;
    open_window('', window_name);
    document.bp['planaction'].value = 'preview';
    $("form").attr("target", window_name).submit().removeAttr("target");
    document.bp['planaction'].value = '';
}

function set_page(page, headernumber) {
    var valforcurrent = page + '|' + headernumber;
    document.bp.current.value = valforcurrent;
    document.bp.submit();
}

function find_by_id(id) {
    var returnVar;
    if (document.getElementById)
        returnVar = document.getElementById(id);
    else if (document.all)
        returnVar = document.all[id];
    else if (document.layers)
        returnVar = document.layers[id];
    return returnVar;
}

function show(id) {
    find_by_id(id).style.display = 'block';
}

function hide(id) {
    find_by_id(id).style.display = 'none';
}

function fv(field) {
    var val = parseFloat(document.bp[field].value);
    val = isNaN(val) ? 0 : val;
    return val;
}

function v(field) {
    var f = document.bp[field];
    if (!f) {
        alert("Field " + field + " does not exist.");
        return '';
    }
    if (is_array(f) && f.type != 'select-one') {
        for (i in f) {
            if (f[i].checked) {
                return f[i].value;
            }
        }
    } else if (f.type == 'checkbox') {
        return f.checked ? 'on' : '';
    } else {
        return f == null ? null : f.value;
    }
}

function h(test, set) {
    if (test == false) {
        set.addClass("hidden");
    } else {
        set.removeClass("hidden");
    }
}

function sv(field, value) {
    if (value == 0) {
        value = '';
    }
    document.bp[field].value = value;
}

function is_array(inObj)
{ //returns true if inObj is an array
    if(inObj.constructor == Array)
    {
        return true;
    }
    else if(typeof(inObj[0]) == 'undefined')
    {
        return false;
    }
    else
    {
        return true;
    }
}

function calcall() {
}

function getTableClasses( pattern ){
    var allClassesTmp = {}, allClasses = [];
    var rx = pattern ? (new RegExp(pattern)) : (new RegExp(".*"));

    $('table[class]').each( function(){
        var cn = this.className.split(/\s+/);
        for(var i=cn.length;--i>-1;){
            if(rx.test(cn[i]))allClassesTmp[ cn[i] ] = 1
        }
    });
    for(var i in allClassesTmp)allClasses.push(i);
    return allClasses;
}

function toggle_bplan_index() {
    var index = $("#sidemenu");
    var button = $(this);
    button.disable();
    if (index.is(":hidden")) {
        button.val("Hide Index");
        document.bp['hideindex'].value = 'no';
        index.fadeIn("normal", function() {
            button.enable();
        });
    } else {
        button.val("Show Index");
        document.bp['hideindex'].value = 'yes';
        index.fadeOut("normal", function() {
            button.enable();
        });
    }
}

function admin_plan_preview_whole() {
    var window_name = 'preview_whole';
    open_window('', window_name);
    document.bp['planaction'].value = 'previewwhole';
    $("form").attr("target", window_name).submit().removeAttr("target");
    document.bp['planaction'].value = '';
}

function admin_plan_preview_pdf() {
    document.bp['planaction'].value = 'previewpdf';
    $("form").submit();
    document.bp['planaction'].value = '';
}

function add_row() {
    var row = $("#upload thead tr.template").clone().removeClass("template");
    var rows = $("#upload tbody tr");
    if ((rows.length & 1) == 0) {
        row.addClass("odd");
    }
    var seq = 1;
    if (rows.length > 0) {
        var id = rows[rows.length-1].id;
        seq = parseInt(id.replace('row', '')) + 1;
    }
    row.attr("id", "row" + seq);
    row.find(":file").attr("name", "file" + seq);
    row.find(":text").attr("name", "desc" + seq);
    row.find("select").attr("name", "type" + seq);
    $("#upload tbody").append(row);
    return false;
}

function remove_row() {
    var row = $(this).parents("tr");
    if (row.find("input").val() != '') {
        if (!confirm("Are you sure you want to remove this file?")) {
            return false;
        }
    }
    var tbody = row.parent();
    row.remove();
    tbody.find("tr").removeClass("odd").filter(":nth-child(odd)").addClass("odd");
    var seq = 1;
    tbody.find("tr.existing-file:last").each(function() {
        seq = parseInt(this.id.replace('row', '')) + 1;
    });
    tbody.find("tr.new-file").each(function() {
        $(this).attr("id", "row" + seq);
        $(":file", this).attr("name", "file" + seq);
        $(":text", this).attr("name", "desc" + seq);
        $("select", this).attr("name", "type" + seq);
        seq++;
    });
    check_full();
    return false;
}

function check_full() {
    var empty = 0;
    $("#upload tbody tr.new-file :file").each(function() {
        if (this.value == '') {
            empty++;
        }
    });
    if (empty == 0) {
        add_row();
    }
}

function confirm_lodge(evt) {
    if (!confirm("Are you sure all relevant documentation is attached and the order is ready for Cyba to proceed?")) {
        evt.preventDefault();
    }
}

function confirm_complete(evt) {
    if (!confirm("You are confirming that Cyba Outsourcing has completed all required work for your order. Proceed?")) {
        evt.preventDefault();
    }
}

function ignore(evt) {
    evt.preventDefault();
}

function confirm_approve(evt) {
    if (!confirm("Are you sure you want to approve this order?")) {
        evt.preventDefault();
    }
}

function confirm_return(evt) {
    if (!confirm("Are you sure you want to return this order?")) {
        evt.preventDefault();
    }
}

function confirm_approve_silent(evt) {
    if (!confirm("Are you sure you want to approve this order without sending an email to the client?")) {
        evt.preventDefault();
    }
}

function confirm_rebuild(evt) {
    if (!confirm("Are you sure you want to rebuild this order?")) {
        evt.preventDefault();
    }
}

function confirm_reject(evt) {
    if (!confirm("Are you sure you want to reject this order sending it back to the client?")) {
        evt.preventDefault();
    }
}

function confirm_delete(evt) {
    if (!confirm("Are you sure you want to delete this order?")) {
        evt.preventDefault();
    }
}

function confirm_undelete(evt) {
    if (!confirm("Are you sure you want to undelete this order?")) {
        evt.preventDefault();
    }
}

function admin_open_user() {
    var userid = $("div.userid", this).text();
    window.location.href = '/admin/user/' + userid;
}

function test_newsletter() {
    if ($("#user").val() == "") {
        alert("You must specify a username");
    }
}

function confirm_send_newsletter(evt) {
    if (!confirm("Are you sure you want to send this newsletter as is to all clients?")) {
        evt.preventDefault();
    }
}

function download_contacts() {
    var category = $(this).closest("tr").find("td.category").text();
    window.location.href = '/admin/contacts/download/' + escape(category);
}

function confirm_delete_contacts(evt) {
    var category = $(this).closest("tr").find("td.category").text();
    var count = $(this).closest("tr").find("td.count").text();
    if (!confirm("Are you sure you want to remove all " + count + " contacts in category '" + category + "'?")) {
        evt.preventDefault();
    }
}

function confirm_upload(evt) {
    if ($("#file").val() == "") {
        alert("You have not specified an upload file.");
        evt.preventDefault();
    } else if (!confirm("WARNING: Uploading a file will delete every existing contact in the industry or industries contained within that file.\n\nProceed?")) {
        evt.preventDefault();
    }
}

function email_save() {
    var row = $(this).parents("tr");
    var field = row.find("td.field :text").val();
    if (field == "") {
        alert("Field name not specified.");
        return;
    }
    var status = row.find("td.status :checkbox").is(":checked");
    var description = row.find("td.description :text").val();
    email_request_start(row);
    if (row.attr("id") == '') {
        $.ajax({
            url: '/admin/email/new',
            type: 'POST',
            data: {
                field: field,
                status: status,
                description: description
            },
            dataType: 'json',
            timeout: 5000,
            success: function(data) {
                if (typeof data.id == 'undefined') {
                    alert(data.error);
                    email_request_new_edit(row);
                } else {
                    row.attr("id", data.id);
                    row.find("td.field div.view").text(field);
                    row.find("td.status div.view").text(status ? 'Enabled' : 'Disabled');
                    row.find("td.description div.view").text(description);
                    email_request_existing_view(row);
                }
            },
            error: function() {
                alert("Error saving email");
                email_request_new_edit(row);
            }
        });
    } else {
        $.ajax({
            url: '/admin/email/edit',
            type: 'POST',
            data: {
                id: row.attr("id"),
                field: field,
                status: status,
                description: description
            },
            dataType: 'json',
            timeout: 5000,
            success: function(data) {
                if (typeof data.error != 'undefined') {
                    alert(data.error);
                    email_request_existing_edit(row);
                } else {
                    row.attr("id", data.id);
                    row.removeClass("new");
                    row.find("td.field div.view").text(field);
                    row.find("td.status div.view").text(status ? 'Enabled' : 'Disabled');
                    row.find("td.description div.view").text(description);
                    email_request_existing_view(row);
                }
            },
            error: function() {
                alert("Error saving email");
                email_request_new_edit(row);
            }
        });
    }
}

function email_cancel() {
    var row = $(this).parents("tr");
    email_request_existing_view(row);
}

function email_edit() {
    var row = $(this).parents("tr");
    $("td.field :text", row).val($("td.field div.view", row).text());
    $("td.status :checkbox", row).attr("checked", $("td.status div.view", row).text() == 'Enabled');
    $("td.description :text", row).val($("td.description div.view", row).text());
    email_request_existing_edit(row);
}

function email_open() {
    var id = $(this).parents("tr").attr("id");
    open_window('/admin/email/open/' + id, 'email_' + id);
}

function email_remove() {
    var row = $(this).parents("tr");
    if (row.attr("id") == '') {
        row.remove();
        email_row_styling();
    } else {
        if (confirm("Are you sure you want to delete this email?")) {
            email_request_start(row);
            $.ajax({
                url: '/admin/email/remove',
                type: 'POST',
                data: {
                    id: row.attr("id")
                },
                dataType: 'json',
                timeout: 5000,
                success: function(data) {
                    if (typeof data.error != 'undefined') {
                        alert(data.error);
                        email_request_existing_edit(row);
                    } else {
                        row.remove();
                        email_row_styling();
                    }
                },
                error: function() {
                    alert("Error saving email");
                    email_request_new_edit(row);
                }
            });
        }
    }
}

function email_new() {
    var rows = $("#emails tbody tr").length;
    var new_row = $("#emails thead tr.edit").clone();
    if (rows % 2 == 1) {
        new_row.addClass("odd");
    }
    $("#emails tbody").append(new_row);
    return false;
}

function email_request_start(row) {
    row.find("td.buttons :button").disable();
}

function email_request_new_edit(row) {
    row.removeClass("view").addClass("edit");
    buttons = row.find("td.buttons :button");
    buttons.filter(".save").enable();
    buttons.filter(".cancel").disable();
    buttons.filter(".open").disable();
    buttons.filter(".edit").disable();
    buttons.filter(".remove").enable();
}

function email_request_existing_view(row) {
    row.addClass("view").removeClass("edit");
    buttons = row.find("td.buttons :button");
    buttons.filter(".save").disable();
    buttons.filter(".cancel").disable();
    buttons.filter(".edit").enable();
    buttons.filter(".open").enable();
    buttons.filter(".remove").enable();
}

function email_request_existing_edit(row) {
    row.removeClass("view").addClass("edit");
    buttons = row.find("td.buttons :button");
    buttons.filter(".save").enable();
    buttons.filter(".cancel").enable();
    buttons.filter(".edit").disable();
    buttons.filter(".open").disable();
    buttons.filter(".remove").disable();
}

function email_row_styling() {
    $("#emails tbody tr").removeClass("odd").filter(":nth-child(odd)").addClass("odd");
}

function open_email_add() {
    var last_id = $("#recipients div.new:last").attr("id");
    var n = parseInt(last_id.substring(4)) + 1;
    var item = $("#new-recipient").clone();
    item.attr("id", "new_" + n).addClass("new");
    item.find(":text").val("").attr("name", "new_" + n);
    $("#recipients").append(item);
    return false;
}

function open_email_remove() {
    var parent = $(this).parent();
    if (parent.is(".new")) {
        parent.remove();
    } else {
        parent.addClass("hidden");
        parent.find(":checkbox").attr("checked", true);
    }
}

function adduser_save() {
    var row = $(this).parents("tr");
    var username = row.find("td.username :text").val();
    if (username == "") {
        alert("Username not specified.");
        return;
    }
    var firstname = row.find("td.firstname :text").val();
    var surname = row.find("td.surname :text").val();
    var email = row.find("td.email :text").val();
    if (email == "") {
        alert("E-mail not specified.");
        return;
    }
    var newsletter = row.find("td.newsletter :checkbox").is(":checked");
    adduser_request_start(row);
    if (row.attr("id") == '') {
        $.ajax({
            url: '/account/adduser/new',
            type: 'POST',
            data: {
                username: username,
                firstname: firstname,
                surname: surname,
                email: email,
                newsletter: newsletter
            },
            dataType: 'json',
            timeout: 5000,
            success: function(data) {
                if (typeof data.id == 'undefined') {
                    alert(data.error);
                    adduser_request_new_edit(row);
                } else {
                    row.attr("id", data.id);
                    row.find("td.username div.view").text(username);
                    row.find("td.firstname div.view").text(firstname);
                    row.find("td.surname div.view").text(surname);
                    row.find("td.email div.view").text(email);
                    row.find("td.newsletter div.view").text(newsletter ? 'Enabled' : 'Disabled');
                    adduser_request_existing_view(row);
                }
            },
            error: function() {
                alert("Error adding staff 1");
                adduser_request_new_edit(row);
            }
        });
    } else {
        $.ajax({
            url: '/account/adduser/edit',
            type: 'POST',
            data: {
                id: row.attr("id"),
                firstname: firstname,
                surname: surname,
                email: email,
                newsletter: newsletter
            },
            dataType: 'json',
            timeout: 5000,
            success: function(data) {
                if (typeof data.error != 'undefined') {
                    alert(data.error);
                    adduser_request_existing_edit(row);
                } else {
                    row.attr("id", data.id);
                    row.removeClass("new");
                    row.find("td.username div.view").text(username);
                    row.find("td.firstname div.view").text(firstname);
                    row.find("td.surname div.view").text(surname);
                    row.find("td.email div.view").text(email);
                    row.find("td.newsletter div.view").text(newsletter ? 'Enabled' : 'Disabled');
                    adduser_request_existing_view(row);
                }
            },
            error: function() {
                alert("Error adding staff 2");
                adduser_request_new_edit(row);
            }
        });
    }
}

function adduser_cancel() {
    var row = $(this).parents("tr");
    adduser_request_existing_view(row);
}

function adduser_edit() {
    var row = $(this).parents("tr");
    $("td.username :text", row).val($("td.username div.view", row).text());
    $("td.firstname :text", row).val($("td.firstname div.view", row).text());
    $("td.surname :text", row).val($("td.surname div.view", row).text());
    $("td.email :text", row).val($("td.email div.view", row).text());
    $("td.newsletter :checkbox", row).attr("checked", $("td.newsletter div.view", row).text() == 'Enabled');
    adduser_request_existing_edit(row);
}

function adduser_remove() {
    var row = $(this).parents("tr");
    if (row.attr("id") == '') {
        row.remove();
        adduser_row_styling();
    } else {
        if (confirm("Are you sure you want to archive this staff?")) {
            adduser_request_start(row);
            $.ajax({
                url: '/account/adduser/remove',
                type: 'POST',
                data: {
                    id: row.attr("id")
                },
                dataType: 'json',
                timeout: 5000,
                success: function(data) {
                    if (typeof data.error != 'undefined') {
                        alert(data.error);
                        adduser_request_existing_edit(row);
                    } else {
                        row.remove();
                        adduser_row_styling();
                    }
                },
                error: function() {
                    alert("Error adding staff 3");
                    adduser_request_new_edit(row);
                }
            });
        }
    }
}

function adduser_new() {
    var rows = $("#addusers tbody tr").length;
    var new_row = $("#addusers thead tr.edit").clone();
    if (rows % 2 == 1) {
        new_row.addClass("odd");
    }
    $("#addusers tbody").append(new_row);
    return false;
}

function adduser_request_start(row) {
    row.find("td.buttons :button").disable();
}

function adduser_request_new_edit(row) {
    row.removeClass("view").addClass("edit");
    buttons = row.find("td.buttons :button");
    buttons.filter(".save").enable();
    buttons.filter(".cancel").disable();
    buttons.filter(".edit").disable();
    buttons.filter(".remove").enable();
}

function adduser_request_existing_view(row) {
    row.addClass("view").removeClass("edit");
    buttons = row.find("td.buttons :button");
    buttons.filter(".save").disable();
    buttons.filter(".cancel").disable();
    buttons.filter(".edit").enable();
    buttons.filter(".remove").enable();
}

function adduser_request_existing_edit(row) {
    row.removeClass("view").addClass("edit");
    buttons = row.find("td.buttons :button");
    buttons.filter(".save").enable();
    buttons.filter(".cancel").enable();
    buttons.filter(".edit").disable();
    buttons.filter(".remove").disable();
}

function adduser_row_styling() {
    $("#addusers tbody tr").removeClass("odd").filter(":nth-child(odd)").addClass("odd");
}



