// When the user hits 'Submit', the listing_category_SUFFIX may not
// have their selections selected, which won't get passed through.
// So we need to iterate through all selections and select all
function pre_submission() {
    var listings = document.getElementsByClassName( 'suffix', $('listings') );
    for ( var i = 0; i < listings.length; i++ ) {
        var suffix = listings[i].value;
        var select_control = $('listing_category' + suffix);
        var categories = select_control.options;
        for ( var j = 0; j < categories.length; j++ ) {
            categories[j].selected = true;
        }
    }
}

// Using Observer vs. EventObserver because Observer will
// catch updates as they type vs. hitting 'Tab'
new Form.Observer( $('onesource_form'), 1, form_changed );

function form_changed( form, serialized_form_skip ) {
//alert( 'form_changed() func' );
    var listings = document.getElementsByClassName( 'suffix', $('listings') );
    var hash = $H(form.serialize( true ));
    hash['rm'] = 'ajax_first_convert';
    var serialized_form = hash.toQueryString();
    for ( var i = 0; i < listings.length; i++ ) {
        var suffix = listings[i].value;
//alert( "checking out subform suffix = " + suffix );
        if ( $('listing_website' + suffix).checked ) {
            if ( $('listing_website_url' + suffix).disabled ) {
                $('listing_website_url' + suffix).disabled = false;
            }
        } else {
            if ( ! $('listing_website_url' + suffix).disabled ) {
                $('listing_website_url' + suffix).disabled = true;
            }
        }
        if ( $('listing_email' + suffix).checked ) {
            if ( $('listing_email_address' + suffix).disabled ) {
                $('listing_email_address' + suffix).disabled = false;
            }
        } else {
            if ( ! $('listing_email_address' + suffix).disabled ) {
                $('listing_email_address' + suffix).disabled = true;
            }
        }
        if ( $('listing_add_description' + suffix).checked ) {
            if ( $('listing_description' + suffix).disabled ) {
                $('listing_description' + suffix).disabled = false;
            }
        } else {
            if ( ! $('listing_description' + suffix).disabled ) {
                $('listing_description' + suffix).disabled = true;
            }
        }
        var link_checks = document.getElementsByClassName( 'weblink_checkbox' );
        for ( var j = 0; j < link_checks.length; j++ ) {
            var check_name = link_checks[j].name;
            var re = new RegExp( '^listing_weblink(.+)$' );
            var matches = check_name.match( re );
            var check_suffix = matches[1];

            if( link_checks[j].checked ) {
                // enable, if disabled
                if ( $('listing_weblinktext' + check_suffix).disabled ) {
                    $('listing_weblinktext' + check_suffix).disabled = false;
                }
                if ( $('listing_weblinkurl' + check_suffix).disabled ) {
                    $('listing_weblinkurl' + check_suffix).disabled = false;
                }
            } else {
                // disable, if enabled
                if ( ! $('listing_weblinktext' + check_suffix).disabled ) {
                    $('listing_weblinktext' + check_suffix).disabled = true;
                }
                if ( ! $('listing_weblinkurl' + check_suffix).disabled ) {
                    $('listing_weblinkurl' + check_suffix).disabled = true;
                }
            }
        }


        // need to also pull in the destination category options
        var categories = $('listing_category' + suffix).options;
        for ( var j = 0; j < categories.length; j++ ) {
            if ( hash['listing_category' + suffix] ) {
                if ( hash['listing_category' + suffix].indexOf( categories[j].value ) == -1 ) {
                    hash['listing_category' + suffix].push( categories[j].value );
                }
            } else {
                hash['listing_category' + suffix] = new Array( categories[j].value );
            }
            var cat_string = '&listing_category' + suffix +
                    '=' + categories[j].value;
            // let's see if the string is already there (if the user
            // selected it)
            if ( serialized_form.indexOf( cat_string ) == -1 ) {
//alert( "category loop: j=" + j + " and length = " + categories.length );
                    serialized_form += cat_string;
            }
        }
    }
//alert( "Form data = " + hash.toQueryString() );
    var ajax_request = new Ajax.Request(
            'http://' + window.location.host + '/advertising/onesource/getlisted/ajax',
            {
                method: 'post',
                parameters: hash,
                onSuccess: regen_previews
            }
        );
}

function reportError( request ) {
    //alert( "Sorry, there was an error!\nResponse: " + request.responseText + "\nStatus: " + request.statusText + " (" + request.status + ")" );
}

function regen_previews( original_request, json ) {
    var data = eval('(' + original_request.responseText + ')');
//alert( "rec'd the response: " + json );
    for ( var element in data ) {
        $(element).innerHTML = data[element];
    }
}

function optional_reset( control, default_string ) {
    if ( control.value == default_string ) {
        control.value = '';
    }
}

function put_back_default( control, default_string ) {
    if ( control.value == '' ) {
        control.value = default_string;
    }
}

function add_categories( listing_number ) {
    var options = $('all_categories' + listing_number).options;
    var dest_control = $('listing_category' + listing_number);
    var dc_index = dest_control.options.length;
    var i;

    for ( i=0; i<options.length; i++ ) {
        if ( options[i].selected ) {
            if ( _not_already_here( options[i].value, dest_control.options ) ) {
                dest_control.options[dc_index] = new Option( options[i].text, options[i].value, false, false );
                dc_index++;
            }
        }
    }
    form_changed( $('onesource_form'), '' );
    return false;
}

function _not_already_here( value, options ) {
    var not_already_here = true;
    var i;

    for ( i=0; i<options.length; i++ ) {
        if ( options[i].value == value ) {
            not_already_here = false;
            break;
        }
    }
    return not_already_here;
}

function remove_categories( listing_number ) {
    var dest_control = $('listing_category' + listing_number);
    var options = dest_control.options;
    var i;
    var len = options.length;
    var options_to_remove = new Array();

    for ( i=0; i<len; i++ ) {
        if( options[i].selected ) {
            options_to_remove.push( options[i] );
        }
    }

    len = options_to_remove.length;
    for ( i=0; i<len; i++ ) {
        dest_control.removeChild( options_to_remove[i] );
    }
    form_changed( $('onesource_form'), '' );
    return false;
}

function add_new_listing() {
    var listing_block = document.getElementsByClassName( 'listing_block', $('listings') )[0];
//alert( "Got the listing_block = " + listing_block );
    var listing_html = listing_block.innerHTML;
    var re = /_1/g;
    var new_number = parseInt($('number_of_listings').value) + 1;
    var new_html = listing_html.replace( re, '_' + new_number );
//alert( "new_html = " + new_html );
    var new_block = document.createElement( 'div' );
    new_block.setAttribute( 'id', 'listing_block_' + new_number );
    new_block.innerHTML = new_html;
    $('listings').appendChild( new_block );
    $('listing_block_' + new_number).addClassName( 'listing_block' );
    $('number_of_listings').value = new_number;
//alert( 'about to call form_changed()' );
    form_changed( $('onesource_form'), '' );
//alert( 'called form_changed()' );
}

function remove_listing( suffix ) {
    $('listings').removeChild( $('listing_block'+suffix) );
    form_changed( $('onesource_form'), '' );
}

function add_new_link( suffix ) {
    var listing_block = document.getElementsByClassName( 'listing_links', $('links'+suffix) )[0];
//alert( "Got the listing_block = " + listing_block );
    var listing_html = listing_block.innerHTML;
    var new_number = parseInt($('number_of_links'+suffix).value) + 1;
    var new_html = listing_html.replace( /-1/g, '-' + new_number );
    new_html += '<a href="javascript:remove_link(\'' + suffix + '\',' + new_number + ');void(0);">Remove Link?</a>';
//alert( "new_html = " + new_html );
    var new_block = document.createElement( 'div' );
    new_block.setAttribute( 'id', 'listing_links' + suffix + '-' + new_number );
    new_block.innerHTML = new_html;
    $('links'+suffix).appendChild( new_block );
    $('listing_links'  + suffix + '-' + new_number).addClassName( 'listing_links' );
    $('number_of_links'+suffix).value = new_number;
    form_changed( $('onesource_form'), '' );
}

function remove_link( suffix, link_id ) {
    $('links'+suffix).removeChild( $('listing_links'+suffix+'-'+link_id) );
    form_changed( $('onesource_form'), '' );
}

form_changed( $('onesource_form'), '' );
