// JavaScript Document
var num_divs = 1;

function initMultiText() {
    $('.multiTextHolder').each(function() {
        $(this).find('.addMultiText').hide();
        $(this).find('.addMultiText:last').show();
        if ($(this).find('.removeMultiText').size() > 1) {
            $(this).find('.removeMultiText').show();
        } else {
            $(this).find('.removeMultiText').hide();
            $(this).find('input:radio').attr('checked','checked');
        }
        var id = $(this).attr('id').replace('-holder','');
        if ($(this).height() > 0) {
            $('#' + id + '-label').height($('#' + id + '-holder').height());
        } else {
            $('#' + id + '-label').height(28 * $(this).find('.multiTextDiv').size());
        }
    });
}

function getNewDivString(theDiv)
{
    var str='<div>' + $(theDiv).innerHTML + '</div>';
    str = str.replace(/\[0\]/g,"[" + num_divs + "]");
    num_divs++;
    return str;
}

function autocompleteSplit( val , sep) {
    sep = sep || ',';

    regex = new RegExp("\\" + sep + "\\s*");
    return val.split(regex);
}
function autocompleteExtractLast( term , sep ) {
    return autocompleteSplit( term , sep).pop();
}


function selectAutocompleteValue(elem,elem_text,elem_id_field,elem_id) {
    if (window["console"]) console.debug(elem,elem_text,elem_id_field,elem_id);
    if (elem_id == 0) {
        alert('zero id!');
        return;
    }
    $('#' + elem_id_field).val(elem_id);
    $('#'+elem+'_value a#'+elem+'_link').text(elem_text);
    $('#'+elem_id_field).change();
    $('#'+elem).attr('disabled', 'disabled').hide();
    if (window["console"]) console.debug('setting ',elem_id_field,' to:',$('#' + elem_id_field).val());
    initAutocompleteLink(elem,elem_id_field);
    $('#'+elem+'_value').show();
    $('#' + elem + '_value').parents('div.formRow').next('div').find('input:visible,select').focus();
}

function clearAutocompleteValue(el,ac_input,ac_id_field) {
    $(el).parent().hide();
    $('#' + ac_id_field).val(0);
    $('#' + ac_input).show().removeAttr('disabled').val('').focus();
    $('#'+ac_id_field).change();
}

function initAutocompleteLink(elem,elem_id_field) {
    var href = $('#'+elem+'_value a#'+elem+'_link').attr("href").replace(/\d+$/,'') + $('#' + elem_id_field).val();
    $('#'+elem+'_value a#'+elem+'_link').attr('href',href);
}

var multi_text_iterator = 100;
function addMultiTextAutocomplete(holder_id,options) {
    var div = $('#' + holder_id).find('div:first').clone();
    div.show();
    $('#' + holder_id).append(div);
    var input = div.find('.multiAutocomplete');
    var elem_id = input.attr('id').replace(/\d+/,multi_text_iterator);
    input.attr('id',elem_id);
    $('#' + elem_id).autocomplete(options);

    div.find('a').each(function() {
        var id = $(this).attr('id').replace(/\d+/,multi_text_iterator);
        $(this).attr('id',id);
    });

    multi_text_iterator++;
}
function removeMultiTextAutocomplete(el) {
    $(el).parent('div').remove();
}

function selectMultiTextAutocompleteValue(elem,elem_text,elem_id) {
    $('a#'+elem+'_link').text(elem_text);
    $('#'+elem).hide();
    $('#'+elem).val(elem_id);
    $('a#'+elem+'_link').show();
    $('a#'+elem+'_link').parents('div.formRow').next('div').find('input:visible,select').focus();
}

var projectFileStack = [];

function rewindFileBrowser() {
    if (projectFileStack.length > 1) {
        var p = projectFileStack.pop();
        p = projectFileStack.pop();
        openFileBrowser(p.pid,p.fid,p.pt);
    }
    
}

function openFileBrowser(project_id,form_id,project_title) {
    if (!$('#fileIncludeDialog').get(0)) {
        $('<div id="fileIncludeDialog"></div>').appendTo('body');
    }
    var $dialog = $('#fileIncludeDialog');
    $dialog.html('');
		
    projectFileStack.push({pid:project_id,fid:form_id,pt:project_title});
    
    $dialog.load('/file/list/project_id/'+project_id+'/format/html/browse/1',function() {
		
    });
    
    var title = (project_title) ? ' - ' + project_title : '';
    
    $('#fileIncludeDialog').dialog({
        modal: true,
        width: 700,
        title: 'Uploaded files' + title,
        close: function() {
            $dialog.dialog('destroy');
            $dialog.remove();
        },
        buttons: {
            'Select': function() {
                var s = $("#file_grid_browser",$dialog).jqGrid("getGridParam","selarrrow");
                for (var i in s) {
                    var row = $("#file_grid_browser",$dialog).jqGrid("getRowData",s[i]);
                    addAttachment(s[i],row.thumbnail,form_id);
                }
                $dialog.dialog('close');
            }
		
        }
    });
	

}

	
function addAttachment(id,thumb,form_id)
{
    var exists = false;
    $('#attachments').find('input:hidden').each(function() {
        if (id == $(this).val()) {
            exists = true;
        }
    });
    if (exists) {
        return;
    }
            
    var el = $('<input type="hidden" name="to_attach[]" value="' + id + '" id="elem_' + id + '" />');
    $('#attachments').append($('<div id="attach_' + id + '" class="attachment">' + thumb + ' <a href="#" onclick="removeAttachment(' + id + ',\'' + form_id + '\');return false;">[x]</a></div>'))
    .append(el);
}
	
function addAttachments(atts) {
    //console.debug(atts);
    for(var i = 0; i < atts.length; i++) {
        var img = '<img src="/file/thumb/file_id/' + atts[i].file_id +'" class="gridThumb" />' + atts[i].filename;
        addAttachment(atts[i].file_id,img,atts[i].form_id);
    }
}
	
function removeAttachment(id,form_id)
{
    $('#attach_' + id,$('#' + form_id)).remove();
    $('#elem_' + id,$('#' + form_id)).remove();
}
	
function loadTab(tabs,index,url) {
    if (!tabs) {
        return;
    }
    index = index || tabs.tabs('option', 'selected');
    if (url) {
        tabs.tabs('url',index,url);
    }
    tabs.tabs('load',index);
}

function reloadGrid(grid) {
    jQuery("#" + grid).trigger("reloadGrid");
}
	
/*pageLinkCallback = function (el) {
		console.debug('called from main.js',el);
		return true;
	}*/
var dialogWidths = {
    'company': 600,
    'file' : 550,
    'venue' : 650,
    'participant' :500,
    'contact' : 650,
    'project' : 750,
    'task' : 600,
    'event' : 600,
    'order' : 600
}
function standardDialog(type,id,title,callback,options) {
    options = options || {};
    var width = dialogWidths[type] || 500;
    var defaults = {
        title:title,
        callback:callback,
        width:width
    };
    options = $.extend(defaults,options);
    editDialog(type,id,options);
    return;
}

function editLocation(url,title,callback) {
    var url = '/company/edit-location/' + url;
    editDialog('location',url,{
        title:title,
        callback: callback,
        url: url,
        width:600
    });
    return;
}

function addEmailRecipients(email_id,callback) {
    var url = '/email/add-recipients/email_id/' + email_id;
    editDialog('email_recipients',url,{
        title: 'Add recipients to email',
        callback: callback,
        url: url,
        width: 500
    });
}

function editEvent(id,title,callback,options) {
    standardDialog('event',id,title,callback,options);
    return;
}

function editOrder(id,title,callback,options) {
    options = options || {};
    options.openId = id;
    options.onClose = function(opts) {
        if (updated_orders[opts.openId]) {
            if (confirm('There have been changes to this order. Do you want to send a notification email to the customer?')) {
                $.get('/order/process/order_id/' + id);
            }
        }
    }
    options.onSave = function() {
        updated_orders[id] = null;
    }
    options.width = 750;
    standardDialog('order',id,title,callback,options);
    return;
}

function editCompany(id,title,callback,options) {
    standardDialog('company',id,title,callback,options);
    return;
}

function editAccount(id,title,callback,options) {
    standardDialog('accounts',id,title,callback,options);
    return;
}

function editTicketTier(id,title,callback,options) {
    options = options || {};
    id = '/ticket/edit-tier/ticket_tier_id/' + id;
    options.url = id;
    standardDialog('ticket',id,title,callback,options);
    return;
}

function editTicketStub(id,callback,options) {
    options = options || {};
    event_id = id;
    id = '/ticket/stub-edit/event_id/' + id;
    options.url = id;
    options.suppressNew = true;
    standardDialog('ticket',id,'Edit Ticket Stubs (Event #' + event_id + ')',callback,options);
    return;
}

function editProject(id,title,producer_id,root_project_id,options) {
    options = options || {};
    options.url_extra = '/producer_id/' + producer_id + '/root_project_id/' + root_project_id;
    var callback = options.callback || projectCallback;
    standardDialog('project',id,title,callback,options);
    return;
}

function projectCallback(ret_val) {
    if (ret_val.moveToNode) {
        pp.project.tabs.tabs('select','projects');
        $('#projects').load('/project/tree/format/html/project_id/' + ret_val.project_id + '/root_project_id/' + ret_val.moveToNode,function() {
            
            });
    }else {
        window.location.reload();
    }
}

function editFile(id,title,callback,options) {
    options = options || {};
    options.url_extra = options.url_extra || '';
    options.url = '/file/edit/file_id/' + id + '/format/html' + options.url_extra;
    standardDialog('file',id,title,callback,options);
    return false;
}
var task_iterator = 0;
function editTask(id,title,callback,options) {
    options = options || {};
    options.url_extra = options.url_extra || '';
    options.url_extra += '/iteration/' + task_iterator;
    options.url = '/task/edit/task_id/' + id + '/format/html' + options.url_extra;
    options.dialogId = 'editTaskDialog' + task_iterator;
    standardDialog('task',id,title,callback,options);
    task_iterator++;
    return false;
}

function newTaskMini(id,callback,options) {
    options = options || {};
    options.url = '/task/edit-mini/contact_id/' + id;
    standardDialog('task',options.url,'Add new mini task',callback,options);
    return false;
}

function completeTask(id,callback) {
    $.getJSON('/task/complete/task_id/' + id,function(ret) {
        if ($.isFunction(callback)) {
            callback(ret);
        }
    });
}

function viewTaskNotes(id,callback) {
    var dialog = 'viewTaskNotesDialog';
    if (!$('#' + dialog).get(0)) {
        $('<div id="' + dialog + '"></div>').appendTo('body');
    }
    var title = 'View task notes';
    var $dialog = $('#' + dialog);
    $dialog.html('');
    var url = '/task/notes/task_id/' + id + '/format/html';
    $dialog.load(url,function() {
        $('form',$dialog).ajaxForm({
            url: url,
            dataType: 'json',
            success: function(res) {
                if (res.success) {
                    if ($.isFunction(callback)) {
                        callback(res);
                    }
                    $dialog.dialog('close');
                } else {
                    alertErrors(res.errors);
                }
            }
        });
        $dialog.dialog('open');
        $dialog.parent().show();

    });

    $dialog.dialog({
        modal: true,
        autoOpen: false,
        width: 500,
        close: function() {
            $dialog.dialog('destroy');
            $dialog.remove();
        },
        buttons: {
            'Save': function() {
                $('form',$dialog).submit();
            },
            'Close': function () {
                $dialog.dialog('close');
            }
        },
        title: title
    });
}

function viewFile(id) {
    var dialog = 'viewFileDialog';
    if (!$('#' + dialog).get(0)) {
        $('<div id="' + dialog + '"></div>').appendTo('body');
    }
    var title = 'View file';
    var $dialog = $('#' + dialog);
    $dialog.html('');
    var url = '/file/view/file_id/' + id + '/format/html';
    $dialog.load(url,function() {
        $dialog.dialog('open');
        $dialog.parent().show();

    });

    $dialog.dialog({
        modal: true,
        autoOpen: false,
        width: 500,
        close: function() {
            $dialog.dialog('destroy');
            $dialog.remove();
        },
        buttons: {
            'Close': function () {
                $dialog.dialog('close');
            }
        },
        title: title
    });
}

function editVenue(id,title,callback,options) {
    standardDialog('venue',id,title,callback,options);
    return;
}

function editParticipant(id,title,callback,options) {
    standardDialog('participant',id,title,callback,options);
    return;
}

function linkParticipants(project_id,selected,callback) {
    var dialog = 'linkParticipantDialog';
    if (!$('#' + dialog).get(0)) {
        $('<div id="' + dialog + '"></div>').appendTo('body');
    }
    var title = 'Link participants to projects';
    var $dialog = $('#' + dialog);
    $dialog.html('');
    var url = '/participant/link/project_id/' + project_id + '/s/' + selected + '/format/html';
    $dialog.load(url,function() {
        $('form',$dialog).ajaxForm({
            url: url,
            dataType: 'json',
            success: function(res) {
                if (res.success) {
                    callback();
                    $dialog.dialog('close');
                } else {
                    alertErrors(res.errors);
                }
            }
        });
        $dialog.dialog('open');
        $dialog.parent().show();
        
    });

    $dialog.dialog({
        modal: true,
        autoOpen: false,
        width: 500,
        close: function() {
            $dialog.dialog('destroy');
            $dialog.remove();
        },
        buttons: {
            'Save': function() {
                $('form',$dialog).submit();
            },
            'Cancel': function () {
                $dialog.dialog('close');
            }
        },
        title: title
    });
}

function editBudget(id,title,callback,options) {
    standardDialog('budget',id,title,callback,options);
    return;
}

function editLedger(id,title,options) {
    options = options || {};
    if ($.isFunction(options.callback)) {
        var callback = options.callback;
        var cb = function(ret) {
            callback(ret);
            flagUpdatedOrder(ret.order_id);
        }
    } else {
        var cb = function(ret) {
            flagUpdatedOrder(ret.order_id);
        }
    }
    options.callback = cb;
    
    options.title = title;
    options.width = 700;
    editDialog('ledger',id,options);
}

function payTransaction(id,callback) {
    var date = prompt('Please enter the date paid (YYYY-MM-DD):');
    if (!date.match(/^\d{4}\-\d{2}\-\d{2}$/)) {
        alert('You must enter a date in the format YYYY-MM-DD to mark the transaction as paid!');
        return;
    }
    $.post('/ledger/update',{ledger_id: id,status: 'paid',date:date},function(ret) {
        //alert('transaction updated');
        $('.transRow' + id)
            .removeClass('owe')
            .removeClass('overdue')
            .addClass('paid');
        $('.transRow' + id).find('td:first').removeClass('owe').removeClass('overdue').addClass('paid');
        $('.transRow' + id).find('a.payTrans').hide();
        $('.transRow' + id).find('a.cancelTrans').hide();
        
        //check to see if there are any overdue transactions left for the month
        $('.transRow' + id).closest('td.tipable').each(function() {
            var overdue = $(this).find('tr.overdue');
            if (!overdue.get(0)) {
                $(this).removeClass('overdue');
            }
        });
        
    })
}

function cancelTransaction(id,callback) {
    var reason = prompt('Please give a reason for the canceled transaction:');
    if (!reason) {
        alert('You must provide a reason to mark this transaction as canceled!');
        return;
    }
    $.post('/ledger/update',{ledger_id: id,status: 'canceled',reason: reason},function(ret) {
        alert('transaction cancelled');
        if ($.isFunction(callback)) {
            callback(ret);
        }
    });
}

function editAccounts() {
    editDialog('account','',{
        title: 'Edit account list',
        width:500
    });
}

function editContact(id,title,callback,options) {
	
    var enhanced_callback = function(ret) {
        $('#contactCategoriesDialog').remove();
        if ($.isFunction(callback)) {
            callback(ret);
        }
    }
    return standardDialog('contact',id,title,enhanced_callback,options);
}

function editEmail(id,title,project_id,tabs,options) {
    var defaults = {
        width: 800,
        title: title,
        project_id: project_id
    }
    options = $.extend(defaults,options);
	
    options.callback = function(ret) {
        if (tabs) {
            if ($.isFunction(tabs)) {
                return tabs(ret);
            } else {
                loadTab(tabs);
            }
        }
        //close the dialog and open the view.
        $dialog = $('#editEmailDialog');
        $dialog.dialog('close');
        $dialog.remove();
		
        viewEmail(ret.email_id,ret.subject,tabs);
    };
    
    options.onSave = function() {
        $('#message').tinymce().hide();
    }
	
    editDialog('email',id,options);

}

function listTickets(event_id,callback) {
    if (!$('#ticketListDialog').get(0)) {
        $('<div id="ticketListDialog"></div>').appendTo('body');
    }
    title = 'List tickets';
    var $dialog = $('#ticketListDialog');
    $dialog.html('');
    $dialog.load('/ticket/list/format/html/event_id/' + event_id,function() {
        $dialog.dialog('open');
        $dialog.parent().show();
    });

    $dialog.dialog({
        modal: true,
        autoOpen: false,
        width: 750,
        close: function() {
            if ($.isFunction(callback)) {
                callback();
            }
        },
        title: title
    });

}

updated_orders = {}

function flagUpdatedOrder(order_id) {
    if (order_id > 0) {
        updated_orders[order_id] = new Date().getTime();
    }
}

function editTicket(id,title,callback,options) {
    if ($.isFunction(callback)) {
        var cb = function(ret) {
            callback(ret);
            flagUpdatedOrder(ret.order_id);
        }
    } else {
        var cb = function(ret) {
            flagUpdatedOrder(ret.order_id);
        }
    }
    
    standardDialog('ticket',id,title,cb,options);
    return;
/*
    if (!$('#ticketEditDialog').get(0)) {
        $('<div id="ticketEditDialog"></div>').appendTo('body');
    }
    title = title || 'Update ticket information';
    $('#ticketEditDialog').html('');
    if (id == 0) {
        var url = '/event_id/<?php echo $this->event_id ?>';
        title = 'New ticket';
    } else {
        var url = '/ticket_id/' + id;
    }
	
    $('#ticketEditDialog').load('/ticket/edit/format/html' + url,function() {
        $('#ticketEditDialog form').ajaxForm({
            url: '/ticket/edit/format/json' + url,
            dataType: 'json',
            success: function(res) {
                if (res.success) {
                    $('#eventDialog').load('/ticket/list/format/html/event_id/' + res.event_id);
                    $('#ticketEditDialog').dialog('destroy');
                } else {
                    alert(res.errors);
                }
            }
        });
        $('#ticketEditDialog').dialog('open');
        $('#ticketEditDialog').parent().show();
    });
    
    $('#ticketEditDialog').dialog({
        modal: true,
        autoOpen: false,
        width: 500,
        buttons: {
            'Cancel': function () {
                $('#ticketEditDialog').dialog('destroy');
            },
            'Save & new': function () {
                $('#event-ticket-form').submit();
            //code to keep the dialog from closing, but to load the form again.
            },
            'Save & close': function() {
                $('#event-ticket-form').submit();
            }
        },
        title: title
    });*/
}

function editDialog(entity,id,options) {
    options = options || {};
    var Entity = entity.slice(0,1).toUpperCase() + entity.slice(1);
	
    options.callback = options.callback || null;

    options.width = options.width || 600;
    options.title = options.title || 'Edit ' + Entity;
    options.windowType = options.windowType || 'div';
        
    id = '' + id;
    var url = '/'+entity+'/edit/';
    //allow for local urls to be passed as the id field
    if (id.indexOf('/') === 0) {
        url = id;
        options.original_id = id;
    } else if (id.match(/^New: /)) {
        url += 'name/' + encodeURIComponent(id.replace(/^New: /,''));
    } else {
        url += entity + '_id/' + id;
    }
    url = url.replace(/\/$/,'') + '/format/html';
	
    if (options.project_id) {
        url += '/project_id/' + options.project_id;
    }
	
    if (options.url_extra) {
        url += options.url_extra;
    }

    options.openUrl = url;
    
    if (options.windowType == 'div') {
        openDivDialog(Entity,entity,options);
    } else {
        openWindowDialog(Entity,entity,options);
    }
}

var windowDialogCallback = null;
var windowDialogReturnValues = {};

function openWindowDialog(Entity,entity,options) {

    var height = options.height || 400;
    var defaultOpts = {
        'height': height,
        'width':options.width,
        'top': ($(window).height() / 2) - (height / 2),
        'left': ($(window).width() / 2) - (options.width / 2),
        'menubar': 'no',
        'toolbar': 'no',
        'locationbar' : 'no',
        'personalbar' : 'no',
        'scrollbars': 'yes',
        'dialog' : 'yes'
    };

    var features = [];
    for(var item in defaultOpts) {
        features.push(item + '=' + defaultOpts[item]);
    }
    var dialog = window.open(options.openUrl, entity + 'Dialog', features.join(','));
    dialog.arguments = [1,2,3];
}

function setWindowDialogReturnValues(values) {
    windowDialogReturnValues = values;
//console.debug(windowDialogReturnValues);
}

function openDivDialog(Entity,entity,options) {
    var dialog = options.dialogId || 'edit' + Entity + 'Dialog';
	
    if (!$('#' + dialog).get(0)) {
        $('<div id="'+dialog+'"></div>').appendTo('body');
    }
    var $dialog = $('#' + dialog);
	
    $dialog.html('');
									
    $dialog.load(options.openUrl,null,function() {
        $('form',$dialog).ajaxForm({
            url: options.url || '/'+entity+'/edit/format/html',
            dataType: 'json',
            success: function (ret) {
                if (ret.success) {
                    //console.debug(ret);
                    if (ret.openNew) {
                        $dialog.dialog('destroy');
                        var o = options;
                        o.title = 'New ' + Entity;
                        var id = options.original_id || 0;
                        editDialog(entity,id,o);
                        return;
                    } else if ($.isFunction(options.callback)) {
                        options.callback(ret);
                    }
                    $dialog.dialog('close');
                    $dialog.dialog('destroy');
                    $dialog.remove();
                //selectAutocompleteValue('company',ret.name,'autocomplete-company_id',ret.id);
                } else {
                    alertErrors(ret.errors);
                }
            }
        });
        $dialog.dialog('open');
        $dialog.parent().show();
        $('form',$dialog).find('input:first:visible').focus();
		
    });
    
    var buttons = {};
    buttons['Save & close'] = function() {
        if ($.isFunction(options.onSave)) {
            options.onSave();
        }
        $('form',$dialog).submit();
    };
    if (!options.suppressNew) {
        buttons['Save & new'] = function () {
            if ($.isFunction(options.onSave)) {
                options.onSave();
            }
            $('#'+entity+'-form-action').val('new');
            $('form',$dialog).submit();
        }
    }
    buttons['Cancel'] = function () {
        if ($.isFunction(options.onCancel)) {
            options.onCancel();
        }
        clearAutocompleteValue('#'+entity+'_clear',entity,'autocomplete-'+entity+'_id','');
        $dialog.dialog('close');
    };
    
    $dialog.dialog({
        autoOpen: false,
        modal: true,
        width: options.width,
        title: options.title,
        close: function() {
            if ($.isFunction(options.onClose)) {
                options.onClose(options);
            }
            $dialog.dialog('destroy');
            $dialog.remove();
        },
        buttons: buttons
    });
}

function addTagToObject(object_name,elem_id) {
    var tag = prompt('Enter the new tag:');
    $.post('/tag/add-tag-select',{
        object_name: object_name,
        tag: tag
    },function(r) {
        $('#' + elem_id).append('<option value="' + r.id + '">' + tag + '</option>');
        $('#' + elem_id).val(r.id);
    });
}

function jqGridColumnPicker(gridId,names) {
    var dialogId = gridId + '-columnPicker';
    if (!$('#' + dialogId).get(0)) {
        var holder = jQuery('<div id="' + dialogId + '"></div>');
        for (colId in names) {
            var props = jQuery('#' + gridId).jqGrid("getColProp",colId);
            var label = $("<label></label>");
            var check = $('<input id="' + dialogId + '-' + colId + '" type="checkbox" onclick="jqGridToggleColumn(\'' + gridId + '\',this,\'' + colId + '\')" />');
            if (!props.hidden) {
                check.attr("checked","checked");
            }
            label.append(check).append(" " + names[colId]);
            holder.append(label).append("<br />");
        }
        $("body").append(holder);
        
    } else {
        holder = $('#' + dialogId);
    }
	
    holder.dialog({
        title:'Show/Hide Columns',
        close: function() {
            holder.dialog('destroy');
        }
    });
	
}

function jqGridToggleColumn(gridId,el,colId) {
    var action = el.checked ? "showCol" : "hideCol";
    jQuery("#" + gridId).jqGrid(action,colId);
}


function alertErrors(errors) {
    var toAlert = 'The following errors occurred:\n';
    for (var error_field in errors) {
        toAlert += error_field + ':\n';
        for(var errs in errors[error_field]) {
            toAlert += '-' + errors[error_field][errs] + '\n';
        }
    }
    alert(toAlert);
}

function viewEmail(id,title,tabs) {
    var dialog = 'viewEmailDialog', url = '/email/view/' + id + '/format/html/';
	
    if (!$('#' + dialog).get(0)) {
        $('<div id="'+dialog+'"></div>').appendTo('body');
    }
    var $dialog = $('#' + dialog);
    $dialog.html('');
    $dialog.dialog({
        autoOpen: false,
        modal: true,
        width: 750,
        title: title + ' | View Email',
        buttons: {
            'Edit': function() {
                $dialog.dialog('destroy');
                $dialog.remove();
                editEmail(id,title + ' | Edit Email',0,tabs);
            },
            'Cancel': function () {
                $dialog.dialog('destroy');
                $dialog.remove();
            }
		  
        }
    });
    $dialog.load(url,function() {
        $dialog.dialog('open');
        $dialog.parent().show();
    });
}
function Tagger(id,localVar,lookup,saveObject,label) {
    this.setupTags(id,localVar,lookup,saveObject,label);
}
Tagger.prototype = {
    containerId: '',
    lookup: '',
    saveAs: '',
    tags: [],
    input: {},
    inputId: '',
    label: '',
    setupTags: function(id,localVar,lookupObject,saveObject,label) {
        this.localVar = localVar;
        this.label = label;
        this.input = $('#' + id);
        this.containerId = id + '-holder';
        var tags = this.input.val().split(',');
        this.lookup = lookupObject;
        this.saveAs = saveObject;
        this.input.parent().append($('<span id="' + this.containerId + '"></span><span class="tagEditSpan" style="display:none" id="' + this.containerId + '_newTag"><input type="text" /> <a href="javascript:;" title="Cancel" class="ui-icon ui-icon-cancel" onclick="' + this.localVar + '.closeNewTag()"></a><a href="javascript:;" class="ui-icon ui-icon-search" title="Open tag grid" onclick="'+this.localVar+'.openGrid()"></a></span><a href="javascript:;" id="' + this.containerId + '_addTag" class="ui-icon ui-icon-plusthick" title="Add new tag" onclick="'+this.localVar+'.openNewTag()"></a>'));
        this.container = $('#' + this.containerId);
        this.setupInput();
        this.printTags(tags);
    },
		
    setupInput: function() {
        var input = $('#' + this.containerId + '_newTag').find('input');
        var t = this;
        input.css('float','left');
        input.autocomplete({
            source: '/tag/autocomplete/object/' + this.lookup,
            select: function(event, ui) {
                t.addTag(ui.item.value);
                t.closeNewTag();
                return false;
            }
        });

        input.keypress(function(e) {
            var code = e.keyCode ? e.keyCode : e.which;
            if (code == 13 || code == 9) {
                e.preventDefault();
                e.stopPropagation();
                t.addTag(input.val());
                t.closeNewTag();
            }
        });
    },
    openNewTag: function() {
        $('#' + this.containerId + '_newTag').show();
        $('#' + this.containerId + '_newTag').find('input').focus();
        $('#' + this.containerId + '_addTag').hide();
    },
		
    closeNewTag: function() {
        $('#' + this.containerId + '_newTag').hide();
        $('#' + this.containerId + '_newTag').find('input').val('');
        $('#' + this.containerId + '_addTag').show();
    },
		
    printTags: function(tags) {
        this.clearTags();
        for(i=0;i<tags.length;i++) {
            this.addTag(tags[i]);
        }
    },
    clearTags: function() {
        this.tags = [];
        this.container.html('');
        this.setInputValue();
    },
    addTag: function(tag) {
        if ($.inArray(tag,this.tags) < 0 && tag.length > 0) {
            this.tags[this.tags.length] = tag;
            this.container.append($('<span class="tagElement">' + tag + ' <a href="javascript:;" onclick="'+this.localVar+'.removeTag(\'' + tag + '\',this)">[x]</a></span>'));
        }
        this.setInputValue();
    },
    removeTag: function(tag,el) {
        var index = $.inArray(tag,this.tags);
        if (index >= 0) {
            this.tags.splice(index,1);
        }
			
        $(el).parent().remove();
        this.setInputValue();
    },
    setInputValue: function() {
        //console.debug(this.tags);
        this.input.val(this.tags.join(','));
    //console.debug(this.input.val());
    },
    openGrid: function() {
        if (!$('#tagGrid').get(0)) {
            $('body').append('<div id="tagGrid"></div>');
        }
			
        $div = $('#tagGrid');
        var t = this;
        $div.html('');
        $div.load('/tag/grid/object/' + this.lookup,function() {
            $(this).find(':checkbox').each(function() {
                if ($.inArray($(this).val(),t.tags) >= 0) {
                    this.checked = true;
                }
            });
            $div.dialog('open');
            $div.parent().show();
        });
			
        $div.dialog({
            autoOpen: false,
            width: 800,
            height: 400,
            title: 'Existing ' + t.label + ' tags.',
            buttons: {
                'Select': function() {
                    t.clearTags();
                    $div.find(':checked').each(function() {
                        t.addTag(this.value);
                    });
                    $div.dialog('close');
                    t.closeNewTag();
                }
            }
        });
    }
}

function Comm(options) {
	
    this.types = options.types;
    this.localVar = options.localVar;
    this.container = $('#' + options.container + '-element');
    this.label = this.container.prev();
    //this.container.addClass('comm_container');
    this.type_container_temp = this.localVar + '-type-%type%-container';
    var types = options.types;
        
    this.containers = {};
    this.inputs = {};
	
    //create the autocomplete, input and containers for each of the types
    var sel = $('<select id="' + this.localVar + '-autocomplete-input"></select>');
    for (type in types) {
        //create the internal holder
        this[type] = {
            ids: {}
        };
        //create the input and container
        var optLabel = types[type].optLabel || type.substr(0,1).toUpperCase() + type.substr(1) + ':';
        this.containers[type] = $('<fieldset style="display:none" id="' + this.type_container_temp.replace(/%type%/,type) + '"></fieldset>');
        this.containers[type].append('<legend>' + optLabel + '</legend>');
        this.container.append(this.containers[type]);
        var inputName = types[type].inputName || 'recipient_ids[' + type + ']';
        this.inputs[type] = $('<input type="hidden" id="' + this.localVar + '-type-' + type + '-input" name="' + inputName + '" />');
        this.container.append(this.inputs[type]);
        sel.append($('<option value="'+type+'">'+optLabel+'</option>'));
    }
    this.type_select = sel;
    var t = this;
    this.autocomplete = $('<input type="text" id="'+ this.localVar + '-autocomplete-input" />')
    var lookup_opts = {
        source: '/contact/autocomplete',
        select: function (event,ui) {
            if (ui.item.id == -1) {
                editContact(ui.item.label,'New Contact',function(ret) {
                    //data[0] is the label (name [email])
                    //data[1] is the id value [
                    t.setRecip(ret.name,ret.id);
                },{
                    project_id: 0
                });
            } else {
                t.setRecip(ui.item.label,ui.item.id);
                
            }
            return false;
        },
        minChars: 1,
        focus: function() {
            //prevent value from being inserted on focus
            return false;
        },
        search: function(event,ui) {
            var tags = [];
            var project_id = $('#comm-autocomplete-project_id').val();
            if (project_id > 0) {
                tags.push("ProjectParts_" + project_id);
            }
            var event_id = $('#event_id').val();
            if (event_id > 0) {
                tags.push("EventParts_" + event_id);
            }
            tags.push('ContactRow');
            tags.push('CompanyLocationTags');
            $(this).autocomplete('option','source','/contact/autocomplete/tag_lookup/' + tags.join('+'));
                
        }
    }
    this.autocomplete.autocomplete(lookup_opts);
    this.container.prepend(this.autocomplete);
    this.container.prepend(sel);

    this.addSend = function(id,type) {
        if (this[type]['ids'][id]) {
            this[type]['ids'][id]++;
        } else {
            this[type]['ids'][id] = 1;
        }
    };
	
    this.removeSend = function(id,type) {
        if (this[type]['ids'][id]) {
            this[type]['ids'][id]--;
            if (this[type]['ids'][id] < 0) {
                this[type]['ids'][id] = 0;
            }
        }
		
    };

    this.setRecip = function(label,id,type) {
        if (!type) {
            type = this.type_select.val();
        }
        if (this.containers[type].is(':hidden')) {
            this.containers[type].fadeIn();
        }
        console.debug(label);
        if (label.indexOf('tix:') > 0) {
            this.getTixIds(label,type);
            this.addTagLabel(label,label.slice(1, label.length - 1),type);
        } else if (label.indexOf('(project role') > 0) {
            this.getPartIds(label, type);
            this.addTagLabel(label,label.slice(1, label.length - 1),type);
        } else if (label.charAt(0) == '[') {
            this.getTagIds(id,type);
            this.addTagLabel(label,id,type);
        } else {
            this.addSend(id,type);
            this.addLabel(label,id,type);
            this.printIds(type);
        }
		
        this.autocomplete.val('');
    };

        
        
    this.printIds = function (type) {
		
        var ids = this.getIds(type);
        //console.debug(ids);
        var text = this.containers[type].find('legend').text();
        text = text.replace(/\s*\(\d+\scontacts?\)\s*/,'');
        var str = ' (' + ids.length + ' contact';
        if (ids.length != 1) {
            str += 's';
        }
        this.containers[type].find('legend').text(text + str + ')');
        this.inputs[type].val(ids.join(','));
    //console.debug(this.container.height());
    };
		
    this.getIds = function (which) {
        var ids = [];
        var local = this[which]['ids'];
        for (id in local) {
            if (local[id] > 0) {
                ids.push(id);
            }
        }
        return ids;
    };
	
    this.getTagIds = function(tag_id,type) {
        var t = this;
        $.getJSON('/tag/objects/tag_id/' + tag_id,function(r) {
            t.addTagIds(tag_id.replace(':','_'),r,type);
            t.printIds(type);
        });
		
    };
    
    this.addTagIds = function(tag,ids,type) {
        this[type][tag] = ids;
        //console.debug(tag,this[type][tag]);
        for (var i = 0;i<ids.length;i++) {
            this.addSend(ids[i],type);
        }
        
    };

    this.removeTagIds = function(tag,type) {
        var ids = this[type][tag];
        if (ids) {
            for (var i = 0;i<ids.length;i++) {
                this.removeSend(ids[i],type);
            }
        }
    };

    this.clearTagSend = function(id,type,el) {
        this.removeTagIds(id,type);
        this.removeSpan(el,type);
    };

    this.addTagLabel = function(label,id,type) {
        id = id.replace(':','_');
        this.containers[type].append('<span>' + label.replace(/\s/g,'&nbsp;') + '&nbsp;<a title="Remove this tag from '+type+'" href="javascript:;" onclick="' + this.localVar + '.clearTagSend(\'' + id + '\',\'' + type + '\',this)">[x]</a></span> ');
    //this.setLabelHeight();
    };

    

    this.getPartIds = function(label,type) {
        var t = this;
        label = label.slice(1, label.length - 1);
        var tag = label.replace(/\s\(.+$/,'');
        var project_id = $('#comm-autocomplete-project_id').val();
        $.getJSON('/participant/ajaxList/project_id/' + project_id + '/tag/' + tag,function(r) {
            t.addTagIds(label.replace(':','_'),r,type);
            t.printIds(type);
        });
    }
    
    
    //format tix:[event_id]-[all/wait list/canceled/received/reserved/paid]
    this.getTixIds = function(label,type) {
        var t = this;
        label = label.slice(1,label.length - 1).replace(':','_');
        var tag = label.replace('tix_','');
        var parts = tag.split('-');
        var event_id = parts[0];
        var status = parts[1] || 'all';
        $.getJSON('/ticket/ajaxList/event_id/' + event_id + '/status/' + status, function(r) {
            t.addTagIds(label,r,type);
            t.printIds(type);
        });
        
    }
    
    
    this.clearSend = function(id,type,el) {
        this.removeSend(id,type);
        this.removeSpan(el,type);
    };

    
    this.removeSpan = function(el,type) {
        $(el).parent().remove();
        if (!this.containers[type].find('span').get(0)) {
            this.containers[type].fadeOut();
        }
        this.printIds(type);
    };
		
	
    this.addLabel = function(label,id,type) {
        this.containers[type].append('<span>' + label.replace(/\s/g,'&nbsp;') + '&nbsp;<a title="Remove this contact from '+type+'" href="javascript:;" onclick="' + this.localVar + '.clearSend(' + id + ',\'' + type + '\',this)">[x]</a></span> ');
    //this.setLabelHeight();
    };
    
    this.setLabelHeight = function () {
        var h = this.container.height();
        this.label.height(h);
    }

    for (cont_id in options.contacts) {
        this.setRecip(options.contacts[cont_id], cont_id,'to');
    }
}

function doFetchLazyColumn(cell_id) {
    var href = lazyColumnHrefs[cell_id];
    var ids = [];
    $('.' + cell_id + 'Cell').each(function() {
        var id = $(this).attr('id').match(/\d+/);
        ids.push(id[0]);
    })
    $.post(href,{ids: ids},function(ret) {
        $('.' + cell_id + 'Cell').each(function() {
            var $td = $(this).closest('td');
            $td.css('vertical-align','top');
                
            var id = $(this).attr('id').match(/\d+/);
            id = id[0];
            if (ret[id]) {
                $(this).html(ret[id]);
                var $container = $td.find('.LazyColumnCellContainer');
                $container.width($td.width());
                $(this).height($td.height() - $container.find('.LazyColumnHeaderBar').height());
                
                
            }
        })
    });
}

function doFetchLazyColumnCell(el) {
    var $container = $(el).closest('td').find('.LazyColumnCell');
    var cell_id = $container.attr('class').replace('LazyColumnCell ','').replace('Cell','');
    var href = lazyColumnHrefs[cell_id];
    var id = $container.attr('id').match(/\d+/);
    id = id[0];
    $.post(href,{ids:[id]},function(ret) {
        $container.html(ret[id]);
    })
    
}

var tinymce_opts = {
    // Location of TinyMCE script
    script_url : '/js/tinymce/jscripts/tiny_mce/tiny_mce.js',

    // General options
    theme : "advanced",
    plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

    // Theme options
    theme_advanced_buttons1 : "bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,|,formatselect,fontselect,fontsizeselect,|,forecolor,backcolor,|,template,|,link,unlink",
    theme_advanced_buttons2 : "tablecontrols,|,cut,copy,paste,pastetext,pasteword,|,search,replace,|,outdent,indent,blockquote,hr,|,undo,redo,|,removeformat,cleanup,code",
    theme_advanced_buttons3 : "",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    theme_advanced_statusbar_location : "bottom",
    theme_advanced_resizing : true,
    
    inline_styles: true
}
