function check_for_event_match(id, event_name) {
    var el = document.getElementById(id);
    el.innerHTML = "";
    loadJSON('ajax_event_match.php?q=' + event_name, function(data) {handle_event_match(id, data);});
}

function handle_event_match(id, data) {
    if (data && data.length > 0) {
        var el = document.getElementById(id);
        
        var heading = document.createElement('span');
        heading.innerHTML = "<b><i>The following events currently exist on the site.  Is one of them the event you are trying to post?</i></b> (Click on the event to see it in a new window)";

        el.appendChild(heading);
        el.appendChild(document.createElement('BR'));

        var ul = document.createElement('ul');
        for (i=0; i<data.length; i++) {
            var link = document.createElement('A');
            link.href = data[i]['link'];
            link.target = '_blank';
            link.innerHTML = data[i]['name'];
            var li = document.createElement('li');
            li.appendChild(link);
            ul.appendChild(li);
        }
        el.appendChild(ul);
    }
}

last_venue_search = {query:'', request:null};
function search_venues(query) {
    query = query.strip();
    // only search for reasonable-length venue searches
    // don't search for exactly the same string again
    if (query.length > 2 && last_venue_search.query!=query){
        last_venue_search.query = query;
        $('venue_search_processing').show();
        //attempt to cancel the last request if it is still active
        if(last_venue_search.request){
            try {
                last_venue_search.request.transport.abort(); 
            } catch(e) {}
        }
        last_venue_search.request = new Ajax.Request('ajax/venue_starts_with.php', {
            method: 'get',
            parameters: {
                q: query
            },
            onSuccess: function(t){
                last_venue_search.request = null;
                $('venue_results').update(t.responseJSON.content);
                $('make_venue_link').show();
                $('venue_search_processing').hide();
            }
        });
    }
}

function can_submit(form, is_invite, is_approved_promoter) {
    if (!is_approved_promoter || !is_invite){
        if($('convert_to_promoting_1') && $('convert_to_promoting_1').checked){
            return confirm("Are you sure you want to add an RSVP list?  You can't take it off.");
        }
        return true;
    }

    var fields = getFormFieldByName(form, 'url_name[]');

    var set_fields = new Array();
    for (var i=0; i<fields.length; i++) {
        if (fields[i].value.trim() != '') set_fields[set_fields.length] = fields[i];
    }

    return set_fields.length > 0 ||  
        confirm("Are you sure you don't want to add a Promo URL? \nPress \"cancel\" to go back and add one.");
}

function escape_value(value) {
    if (value == null || value == undefined) return '';
    if (typeof value != 'string') return value;

    return value.replace('"', '&quot;')
}

function add_ticket(can_view_fee, can_edit_fee_percent, id, basename, index, values, errors) {
    var html = "<TABLE " + (values['status'] == 'hidden' ? "class='hidden'" : '') + ">";
    html += "<TR class='header'><TD></TD><TD>Ticket Type</TD><TD>Price $</TD><TD>Total # Available</TD><TD>Max. per person</TD></TR>";
    html += "<TR><TD>" + index + ".</TD>";
    html += "<TD class='ticket-type'><input type='text' name=\"" + basename + "[type]\" value=\"" + escape_value(values['type']) + "\"" + ((values['sold'] && values['sold'] > 0) ? ' READONLY' : '') + "class=\"text" + (errors[basename+"[type]"] ? " errors" : "") + "\"/></TD>";
    html += "<TD><input type='text' name=\"" + basename + "[price]\" size='5' value=\"" + escape_value(values['price']) + "\"" + ((values['sold'] && values['sold'] > 0) ? ' READONLY' : '') + "class=\"text"+(errors[basename+"[price]"] ? " errors" : "") + "\"/></TD>";
    html += "<TD><input type='text' name=\"" + basename + "[inventory]\" size='5' value=\"" + escape_value(values['inventory']) + "\"" + "class=\"text"+(errors[basename+"[inventory]"] ? " errors" : "") + "\"/></TD>";
    html += "<TD><SELECT class=\"select\" name=\"" + basename + "[max_quantity]\">";
    for (i=1; i<=10; i++) {
        html += "<OPTION" + (values['max_quantity'] == i ? ' SELECTED' : '') + ">" + i + "</OPTION>";
    }
    html += "</SELECT>&nbsp;&nbsp;&nbsp;";
    if (values['id'] != null) {
        if (values['sold'] && values['sold'] > 0) {
            if (values['status'] == 'hidden') html += "<A href='#' onclick=\"submitForm('update_ticket_status', [['id', " + values['id'] + "], ['status', 'enabled']]); return false;\">Show Ticket Type</A>";
            else html += "<A href='#' onclick=\"submitForm('update_ticket_status', [['id', " + values['id'] + "], ['status', 'hidden']]); return false;\">Hide Ticket Type</A>";
        } else html += "<A href='#' onclick=\"if (confirm('Are you sure you want to delete this ticket type?  You will not be able to bring it back.')) {submitForm('update_ticket_status', [['id', " + values['id'] + "], ['status', 'deleted']]);} return false;\">Delete Ticket Type</A>";
    }
    html += "</TD></TR>";

    if (can_edit_fee_percent) {
        html += "<TR class='header'><TD></TD>";
        html += "<TD colspan='2'><span class='hlg-only-small'>Transaction Fee (%)</span> </TD><TD><INPUT type='text' size='5' maxlength='5' value='" + values['txn_fee_percent'] + "' name='" + basename + "[txn_fee_percent]'/></TD></TR>";
    } 

    if (values['price'] && can_view_fee && values['txn_fee_config']) {
        html += "<TR class='header'><TD></TD>";
        html += "<TD colspan='2'><span class='hlg-only-small'>Transaction Fee</span> <i class='small-font-size'>(save for updated value)</i></TD><TD> " + (values['txn_fee_config'][0] == '$' ? '$' : '') + values['txn_fee_config'][1] + (values['txn_fee_config'][0] == '%' ? '%' : '') + "</TD></TR>";
    }

    html += "<TR class='header'><TD></TD>";
    html += "<TD colspan='4'>Description <i class='small-font-size'>Details about this ticket, will be shown to buyers</i></TD></TR>";
    html += "<TR><TD></TD>";
    html += "<TD colspan='4'><textarea class='mceNoEditor textarea' name=\"" + basename + "[description]\" rows='2'>" + escape_value(values['description']) + "</textarea></TD></TR>";
    if (values['id']) {
        html += "<TR class='summary'><TD></TD>";
        html += "<TD colspan='4'><label>Tickets sold:</label> <span>" + escape_value(values['sold']) + "</span><label>Tickets remaining:</label> <span>" + escape_value(values['remaining']) + "</span></TD></TR>";
    }
    html += "</TABLE>";
    html += "<input type='hidden' name=\"" + basename + "[id]\" value=\"" + escape_value(values['id']) + "\"/>";
    html += "<input type='hidden' name=\"" + basename + "[sold]\" value=\"" + escape_value(values['sold']) + "\"/>";
    html += "<input type='hidden' name=\"" + basename + "[remaining]\" value=\"" + escape_value(values['remaining']) + "\"/>";
    html += "<HR/>";
    
    var div = E('DIV');
    div.innerHTML = html;

    $(id).appendChild(div);
}

function show_end_date(skip_focus){
    $('end_date_calendar').show();
    $('end_date_label').show();
    $('show_end_date_calendar').hide();
    $('start_date_label').show();
    if(!skip_focus){
        $('end_date').focus();
    }
    $('has_end_date').value=1; 
}
function hide_end_date(){
    $('show_end_date_calendar').show();
    $('end_date_calendar').hide(); 
    $('end_date_label').hide(); 
    $('start_date_label').hide(); 
    $('end_date').value = '';
    $('has_end_date').value=0;
}
function change_weekly_recurrence(select){
    if(select.value != -1){
        show_end_date(true);
        $('hide_end_date_calendar').hide();
    }else{
        $('hide_end_date_calendar').show();
    }
}

HLG.Class('PostEvent',{
    attach: {
        context: '#postAnEvent',
        'tr.benefits input, tr.benefits select': function(i) {
            i.obs('focus', this.benefits_change);
        },
        'tr.benefits input.default': function(i) {
            i.default_value = $F(i);
            i.obs('focus', this.default_focus);
            i.obs('blur', this.default_blur);
        },
        '#ticketing_details .ticket-message textarea.default': function(i) {
            i.default_value = $F(i);
            i.obs('focus', this.default_focus);
            i.obs('blur', this.default_blur);
        },
        'div#make_venue_link input': function(i){
            i.obs('click', this.make_venue);
        }
    },
    make_venue: function(e){
        div = e.findElement('div');
        if(div.down('input').checked){
            div.next().show();
        }else{
            div.next().hide();
        }
    },

    initialize: function(context) {
        this.context = context;
        
        this.benefits_change = this.benefits_change.bindAsEventListener(this);
        this.default_focus = this.default_focus.bindAsEventListener(this);
        this.default_blur = this.default_blur.bindAsEventListener(this);
    },
    
    benefits_change: function(event) {
        var el = event.findElement('input');
        if(!el){
            var el = event.findElement('select');
        }

        //if they've selected an input that has a radio next to, select that radio
        if (el.type != 'radio' && el.up('li').down('input[type="radio"]')){
            el.up('li').down('input[type="radio"]').checked = true;
        }

        //if they've chosen the rsvp-benefits radio
        if (el.readAttribute('name') == 'rsvp_benefits') {
            //if they don't have a sub-radio selected, choose the first one
            if (!el.up('li').select('.rsvp-benefits input[type="radio"]').find(function(r) {return r.checked;}))
                el.up('li').down('.rsvp-benefits input[type="radio"]').checked = true;
        }

        //if they've selcted a sub-radio of rsvp-benefits, select the parent radio 
        else if (el.up('ul.rsvp-benefits')) {
            this.context.down('tr.benefits input[name="rsvp_benefits"]').checked=true;
        }
        //else they've chosen a more normal option
        else {
            rsvp_b = this.context.down('tr.benefits input[name="rsvp_benefits"]');
            if(rsvp_b){
                rsvp_b.checked = false;
            }
        }

        if (el.next('input[type="text"]')){
            el.next('input[type="text"]').focus();
        }

        //disable the option to turn off rsvp required if rsvp_benefits is checked
        rsvp_r = $('rsvp_required_1');
        if(rsvp_r && !$('rsvp_change_disabled')){
            if(this.context.down('tr.benefits input[name="rsvp_benefits"]').checked || 
                    el.readAttribute('name')=='rsvp_benefits'){
                //using click() fires the onclick event, which is what we want
                if(!rsvp_r.checked){
                    rsvp_r.click()
                }
                rsvp_r.disabled='disabled';
                //store value in hidden field, disabled input fields are not submitted
                $('rsvp_required_1_default').value = '1';
            }else{
                rsvp_r.disabled=null;
                //set default field back to default value now that checkbox is enabled again
                $('rsvp_required_1_default').value = '0';
            }
        }
    },

    default_focus: function(event) {
        var i = event.findElement('input');
        if (!i) i = event.findElement('textarea');

        if (i.hasClassName('default'))
            i.clear();

        i.removeClassName('default');
    },

    default_blur: function(event) {
        var i = event.findElement('input');
        if (!i) i = event.findElement('textarea');

        if ($F(i).blank()) {
            i.addClassName('default');
            i.value = i.default_value;
        }
    }
});
