/**
 *  This file contains functions for music catalog search.
 *
 *  $Id: search_utils.js,v 1.18 2010/06/12 16:23:55 ethan Exp $
 *
 *  $Log: search_utils.js,v $
 *  Revision 1.18  2010/06/12 16:23:55  ethan
 *  *** empty log message ***
 *
 *  Revision 1.17  2010/06/12 16:23:26  ethan
 *  Mode popup dimensions in px instead of em.
 *
 *  Revision 1.16  2010/06/12 16:04:20  ethan
 *  Mode popup dimensions in px instead of em.
 *
 *  Revision 1.15  2010/06/09 23:53:22  ethan
 *  *** empty log message ***
 *
 *  Revision 1.14  2010/06/09 23:46:20  ethan
 *  Use popup positioning from css file.
 *
 *  Revision 1.13  2010/06/09 23:10:44  ethan
 *  Fixed IE oddities.
 *
 *  Revision 1.12  2010/06/09 22:52:03  ethan
 *  Added functions for adding songs to customer projects.
 *
 *  Revision 1.11  2009/02/21 17:38:10  ethan
 *  Added quick search handling.
 *
 *  Revision 1.10  2008/12/18 17:44:32  ethan
 *  Removed debug alerts.
 *
 *  Revision 1.9  2008/12/18 17:42:22  ethan
 *  Added escape quotes for set_file_for_play innerHTML.
 *
 *  Revision 1.8  2008/12/18 16:50:07  ethan
 *  Added "all or any" for genres and keywords.
 *
 *  Revision 1.7  2008/12/03 01:53:14  ethan
 *  Fixed IE problem with DOM-created table display by adding TBODY element.
 *
 *  Revision 1.6  2008/11/30 19:17:07  ethan
 *  Added song detail popup action.
 *
 *  Revision 1.5  2008/11/29 21:13:52  ethan
 *  Deploy with audio player working.
 *
 *  Revision 1.4  2008/11/26 03:20:36  ethan
 *  Added functions for search by part number and search by title.
 *
 *  Revision 1.3  2008/11/25 05:33:25  ethan
 *  Search types Category, Keyword, Time Period, and Tempo complete.
 *
 *  Revision 1.2  2008/11/24 04:14:20  ethan
 *  Deploy for search page.
 *
 *  Revision 1.1  2008/11/23 16:02:17  ethan
 *  Initial revision
 *
 *
 * Author
 *	Ethan Brown (ethan@ethanbrown.org)
 */

var server_loc = "search_utils.php";
var project_server_loc = "project_utils.php";

// Callback functions for search type actions
var catAjax = null;
var genreAjax = null;
var songsAjax = null;

var keywordAjax = null;
var time_periodAjax = null;
var tempo_typeAjax = null;
var titleAjax = null;
var part_numberAjax = null;

var comments_tf_nchars = 45;
var in_process = false;

window.onload = init_page;

/**
 *  On page initialization, check to see if a quick search string
 *  has been set.  If so, do the quick search and display results
 *  in the search results section.
 */
function init_page()
{
    var qs_el = document.getElementsByName('quick_search_str')[0];

    if (qs_el && qs_el.value)
    {
	show_songs_for_quick_search(qs_el.value);
    }
}

/**
 *  Get songs for quick search.
 */
function show_songs_for_quick_search(qs_string)
{
    songsAjax = new sack();

    songsAjax.requestFile = server_loc;    
    songsAjax.setVar('Action', 'get_songs_for_quick_search');

    songsAjax.setVar('quick_search_string', qs_string);
    
    songsAjax.onCompletion = handle_song_selection_display;
    songsAjax.runAJAX();		// Execute AJAX function

}


/**
 *  This function is called when the user clicks on the song title
 *  in the search result set.  It pops up a separate window with
 *  the song details.
 */
function show_song_detail_window(song_id)
{
    var window_url = "song_detail.php?songID=" + song_id;
    window.open (window_url,"popwin",
		 config="width=770,height=430,location=no,status=no,directories=no,toolbar=no,scrollbars=no,menubar=no,resizable=no,top=100,left=50");
}

function show_cat_form()
{
    if (catAjax == null)
    {
	catAjax = new sack();
    }

    catAjax.requestFile = server_loc;

    catAjax.setVar('Action', 'get_catalog_search_form');
    
    catAjax.onCompletion = handle_cat_search_form_display;
    catAjax.runAJAX();		// Execute AJAX function
    clear_search_results();
}

/**
 * AJAX callback for displaying the search form.
 */
function handle_cat_search_form_display()
{
    var search_form_div = document.getElementById('search_form');
    if (!search_form_div)
    {
	alert('search_form_div not found on page!');
	return;
    }
    
    var content = catAjax.response;
    search_form_div.innerHTML = content;
}

/**
 * Callback for when user selects a category from the category list.
 * Request the list of associated genres via AJAX.
 */
function show_genres_for_category()
{
    var cat_list = document.getElementsByName('category_id')[0];
    if (! cat_list)
    {
	alert("Couldn't find category list in page.");
	return;
    }

    var cat_id = cat_list.value;
    
    if (genreAjax == null)
    {
	genreAjax = new sack();
    }

    genreAjax.requestFile = server_loc;

    genreAjax.setVar('Action', 'get_genre_selection');
    genreAjax.setVar('category_id', cat_id);
    
    genreAjax.onCompletion = handle_genre_selection_display;
    genreAjax.runAJAX();		// Execute AJAX function
}

function handle_genre_selection_display()
{

    var genre_div = document.getElementById('genre_cbs');
    if (!genre_div)
    {
	alert('genre_div not found on page!');
	return;
    }
    
    var content = genreAjax.response;
    genre_div.innerHTML = content;

    //var button = make_button('My Search Catalog', show_songs_by_genres);
    //genre_div.appendChild(button);
    clear_search_results();
}

function make_button(label, onclick_function)
{
    var button = document.createElement("input");    
    button.type = 'button';
    button.value = label;
    button.onclick = onclick_function;
    
    return button;
}

/**
 * Callback function for Category/Genre search button click.
 */
function show_songs_by_genres()
{
    var genre_cbs = document.getElementsByName('genre_id[]');
    var all_or_any = document.getElementsByName('all_or_any');    

    if (genre_cbs.length == 0)
    {
	return;
    }

    if (all_or_any.length == 0)
    {
	alert('Program error: all_or_any radio buttons not found.');
	return;
    }

    var all_or_any_val = null;
    for (var i = 0; i < all_or_any.length; i++)
    {
	if (all_or_any[i].checked)
	{
	    all_or_any_val = all_or_any[i].value;
	}
    }

    if (all_or_any_val == null)
	all_or_any_val = 'any';
    
    
    var genre_ids = new Array();

    for (var i = 0; i < genre_cbs.length; i++)
    {
	if (genre_cbs[i].checked)
	{
	    genre_ids.push(genre_cbs[i].value);
	}
    }

    if (genre_ids.length == 0)
    {
	alert('Please select at least one genre for your search.');
	return;
    }

    songsAjax = new sack();

    songsAjax.requestFile = server_loc;    
    songsAjax.setVar('Action', 'get_songs_for_genres');

    for (var i = 0; i < genre_ids.length; i++)
    {
	songsAjax.setVar('genre_id[]', genre_ids[i]);
    }

    songsAjax.setVar('all_or_any', all_or_any_val);
    
    songsAjax.onCompletion = handle_song_selection_display;
    songsAjax.runAJAX();		// Execute AJAX function
}

/**
 *  General function for displaying a song search return set.
 *
 *  Create a table of class 'song_search_result'.  Create flash player
 *  for each song if a snippet path is provided.
 *
 *  The response string is of the form
 *  Status:OK|ERROR
 *  song_id<TAB>snippet_url<TAB>title<TAB>description<TAB>add_to_project_link<RETURN>
 *  ....
 *
 *  If there are no tabs in the set, it's assumed it is a non-fatal
 *  status error to be printed directly.
 *
 *  Note that the flash music player needs a container div, so
 *  the document is modified and then the flash players are
 *  set.
 */
function handle_song_selection_display()
{
    var search_results_div = document.getElementById('search_results');
    if (! search_results_div)
    {
	alert('genre_div not found on page!');
	return;
    }
    
    var response = songsAjax.response;
    var list_values = response.split("\n");

    // Successful response string will have "OK" as the first line:
    if (list_values[0].indexOf('OK') == -1)
    {
	alert("Error:\n" + response);
	return;
    }

    // Check for tab in second row.  If there isn't one, print as content.

    var content = "";
    if (list_values[1].indexOf("\t") == -1)
    {
	for (var i = 1; i < list_values.length; i++)
	{
	    content += list_values[i];
	}
	search_results_div.innerHTML = content;
	return;
    }

    // Generate table of search result set

    var res_table = document.createElement("table");
    res_table.className = 'song_search_result';
    var tbody = document.createElement("tbody");

    var row = document.createElement("tr");
    var h0 = document.createElement("th");
    var h1 = document.createElement("th");
    var h2 = document.createElement("th");
    var h3 = document.createElement("th");
    h0.innerHTML = "Play";
    h1.innerHTML = "Title";
    h2.innerHTML = "Description";
    h3.innerHTML = " ";
    row.appendChild(h0);
    row.appendChild(h1);
    row.appendChild(h2);
    row.appendChild(h3);
    tbody.appendChild(row);

    var snippets = new Array();
    for (var i = 1; i < list_values.length; i++)
    {
	var row_tokens = list_values[i].split("\t");
	var song_id = row_tokens[0];
	var snippet_file = row_tokens[1];
	var title = row_tokens[2];
	var description = row_tokens[3];
	var add_to_project = row_tokens[4];
	
	if (! title)
	    continue;
	
	var row1 = document.createElement("tr");
	
	var td0 = document.createElement("td");
	if (snippet_file == '-')
	{
	    td0.innerHTML = '-';
	}
	else
	{
	    td0.innerHTML = ""
		+ "<a href='javascript:set_file_for_play(\""
		+ escape_quotes(snippet_file) + "\",\""
		+ escape_quotes(title) + "\")' >"
		+ "<img src='images/icon-speaker.gif' border='0'>"
		+ "</a>";
 	}
	snippets.push(snippet_file);

	
	var td1 = document.createElement("td");
	td1.innerHTML = "<a href='javascript:show_song_detail_window("
	    + song_id
	    + ")' title='Click title for details'>" + title + "</a>";
	var td2 = document.createElement("td");
	td2.innerHTML = description;
	var td3 = document.createElement("td");
	td3.innerHTML = add_to_project;

	row1.appendChild(td0);
	row1.appendChild(td1);
	row1.appendChild(td2);
	row1.appendChild(td3);
	tbody.appendChild(row1);
    }

    clear_search_results();
    res_table.appendChild(tbody);
    search_results_div.appendChild(res_table);

    return;
}

function set_file_for_play(file_url, title)
{
    var audio_wrapper = document.getElementById('audioplayer_wrapper');    
    audio_wrapper.innerHTML = "<div id='audioplayer_container'> </div>";    
    
    AudioPlayer.embed('audioplayer_container',
		      {soundFile: file_url,
		      autostart: "yes"});
}    



function show_keyword_form()
{
    if (keywordAjax == null)
    {
	keywordAjax = new sack();
    }

    keywordAjax.requestFile = server_loc;

    keywordAjax.setVar('Action', 'get_keyword_search_form');
    
    keywordAjax.onCompletion = handle_keyword_search_form_display;
    keywordAjax.runAJAX();		// Execute AJAX function
    clear_search_results();
    
}

/**
 * AJAX callback for displaying the keyword search form.
 */
function handle_keyword_search_form_display()
{
    var search_form_div = document.getElementById('search_form');
    if (!search_form_div)
    {
	alert('search_form_div not found on page!');
	return;
    }
    
    var content = keywordAjax.response;
    search_form_div.innerHTML = content;
}

/**
 * Callback function for keyword search button click.
 */
function show_songs_for_keywords()
{
    var keyword_cbs = document.getElementsByName('keyword_id[]');

    if (keyword_cbs.length == 0)
    {
	return;
    }

    var all_or_any = document.getElementsByName('all_or_any');
    if (all_or_any.length == 0)
    {
	alert('Program error: all_or_any radio buttons not found.');
	return;
    }

    var all_or_any_val = null;
    for (var i = 0; i < all_or_any.length; i++)
    {
	if (all_or_any[i].checked)
	{
	    all_or_any_val = all_or_any[i].value;
	}
    }
    
    
    var keyword_ids = new Array();

    for (var i = 0; i < keyword_cbs.length; i++)
    {
	if (keyword_cbs[i].checked)
	{
	    keyword_ids.push(keyword_cbs[i].value);
	}
    }

    if (keyword_ids.length == 0)
    {
	alert('Please select at least one keyword for your search.');
	return;
    }

    songsAjax = new sack();

    songsAjax.requestFile = server_loc;    
    songsAjax.setVar('Action', 'get_songs_for_keywords');

    for (var i = 0; i < keyword_ids.length; i++)
    {
	songsAjax.setVar('keyword_id[]', keyword_ids[i]);
    }

    songsAjax.setVar('all_or_any', all_or_any_val);
    
    songsAjax.onCompletion = handle_song_selection_display;
    songsAjax.runAJAX();		// Execute AJAX function
}
    


function show_time_period_form()
{
    if (time_periodAjax == null)
    {
	time_periodAjax = new sack();
    }

    time_periodAjax.requestFile = server_loc;

    time_periodAjax.setVar('Action', 'get_time_period_search_form');
    
    time_periodAjax.onCompletion = handle_time_period_search_form_display;
    time_periodAjax.runAJAX();		// Execute AJAX function
    clear_search_results();
}

/**
 * AJAX callback for displaying the time_period search form.
 */
function handle_time_period_search_form_display()
{
    var search_form_div = document.getElementById('search_form');
    if (!search_form_div)
    {
	alert('search_form_div not found on page!');
	return;
    }
    
    var content = time_periodAjax.response;
    search_form_div.innerHTML = content;
}

/**
 * Callback function for time_period search button click.
 */
function show_songs_for_time_periods()
{
    var time_period_cbs = document.getElementsByName('time_period_id[]');

    if (time_period_cbs.length == 0)
    {
	return;
    }

    var time_period_ids = new Array();

    for (var i = 0; i < time_period_cbs.length; i++)
    {
	if (time_period_cbs[i].checked)
	{
	    time_period_ids.push(time_period_cbs[i].value);
	}
    }

    if (time_period_ids.length == 0)
    {
	alert('Please select at least one time period for your search.');
	return;
    }

    songsAjax = new sack();

    songsAjax.requestFile = server_loc;    
    songsAjax.setVar('Action', 'get_songs_for_time_periods');

    for (var i = 0; i < time_period_ids.length; i++)
    {
	songsAjax.setVar('time_period_id[]', time_period_ids[i]);
    }
    
    songsAjax.onCompletion = handle_song_selection_display;
    songsAjax.runAJAX();		// Execute AJAX function
}



function show_tempo_form()
{
    if (tempo_typeAjax == null)
    {
	tempo_typeAjax = new sack();
    }

    tempo_typeAjax.requestFile = server_loc;

    tempo_typeAjax.setVar('Action', 'get_tempo_type_search_form');
    
    tempo_typeAjax.onCompletion = handle_tempo_type_search_form_display;
    tempo_typeAjax.runAJAX();		// Execute AJAX function
    clear_search_results();
}

/**
 * AJAX callback for displaying the tempo_type search form.
 */
function handle_tempo_type_search_form_display()
{
    var search_form_div = document.getElementById('search_form');
    if (!search_form_div)
    {
	alert('search_form_div not found on page!');
	return;
    }
    
    var content = tempo_typeAjax.response;
    search_form_div.innerHTML = content;
}

/**
 * Callback function for tempo_type search button click.
 */
function show_songs_for_tempo_types()
{
    var tempo_type_cbs = document.getElementsByName('tempo_type_id[]');

    if (tempo_type_cbs.length == 0)
    {
	return;
    }

    var tempo_type_ids = new Array();

    for (var i = 0; i < tempo_type_cbs.length; i++)
    {
	if (tempo_type_cbs[i].checked)
	{
	    tempo_type_ids.push(tempo_type_cbs[i].value);
	}
    }

    if (tempo_type_ids.length == 0)
    {
	alert('Please select at least one time period for your search.');
	return;
    }

    songsAjax = new sack();

    songsAjax.requestFile = server_loc;    
    songsAjax.setVar('Action', 'get_songs_for_tempo_types');

    for (var i = 0; i < tempo_type_ids.length; i++)
    {
	songsAjax.setVar('tempo_type_id[]', tempo_type_ids[i]);
    }
    
    songsAjax.onCompletion = handle_song_selection_display;
    songsAjax.runAJAX();		// Execute AJAX function
}



function show_title_form()
{
    if (titleAjax == null)
    {
	titleAjax = new sack();
    }

    titleAjax.requestFile = server_loc;

    titleAjax.setVar('Action', 'get_title_search_form');
    
    titleAjax.onCompletion = handle_title_search_form_display;
    titleAjax.runAJAX();		// Execute AJAX function
    clear_search_results();
}

/**
 * AJAX callback for displaying the title search form.
 */
function handle_title_search_form_display()
{
    var search_form_div = document.getElementById('search_form');
    if (!search_form_div)
    {
	alert('search_form_div not found on page!');
	return;
    }
    
    var content = titleAjax.response;
    search_form_div.innerHTML = content;
}

/**
 * Callback function for title search button click.
 */
function show_songs_for_title()
{
    var title_tf = document.getElementsByName('title')[0];

    var title = trim(title_tf.value);
    if (title.length == 0)
    {
	alert("Please enter part of the title you're searching for.");
	return;
    }

    songsAjax = new sack();

    songsAjax.requestFile = server_loc;    
    songsAjax.setVar('Action', 'get_songs_for_title');

    songsAjax.setVar('title', title);
    
    songsAjax.onCompletion = handle_song_selection_display;
    songsAjax.runAJAX();		// Execute AJAX function
}



function show_part_number_form()
{
    if (part_numberAjax == null)
    {
	part_numberAjax = new sack();
    }

    part_numberAjax.requestFile = server_loc;

    part_numberAjax.setVar('Action', 'get_part_number_search_form');
    
    part_numberAjax.onCompletion = handle_part_number_search_form_display;
    part_numberAjax.runAJAX();		// Execute AJAX function
    clear_search_results();
}

/**
 * AJAX callback for displaying the part_number search form.
 */
function handle_part_number_search_form_display()
{
    var search_form_div = document.getElementById('search_form');
    if (!search_form_div)
    {
	alert('search_form_div not found on page!');
	return;
    }
    
    var content = part_numberAjax.response;
    search_form_div.innerHTML = content;
}

/**
 * Callback function for part_number search button click.
 */
function show_songs_for_part_number()
{
    var part_number_tf = document.getElementsByName('part_number')[0];

    var part_number = trim(part_number_tf.value);
    if (part_number.length == 0)
    {
	alert("Please enter the part number you're searching for.");
	return;
    }

    if (part_number.match(/\D+/))
    {
	alert("A part number contains only numbers (ex: 056453423).");
	return;
    }

    songsAjax = new sack();

    songsAjax.requestFile = server_loc;    
    songsAjax.setVar('Action', 'get_songs_for_part_number');

    songsAjax.setVar('part_number', part_number);
    
    songsAjax.onCompletion = handle_song_selection_display;
    songsAjax.runAJAX();		// Execute AJAX function
}

    



function clear_search_results()
{
    var search_results_div = document.getElementById('search_results');    

    if (search_results_div)
    {
	search_results_div.innerHTML = "";
    }
}

/**
 *  Precede any single or double quotes with a backslash.
 */
function escape_quotes(str)
{
    str = str.replace(/\'/g, "&#39;");
    str = str.replace(/\"/g, '\\"');

    return str;
}


// Attribution:  http://www.somacon.com/p355.php
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

/// Add to project functions

/**
 * Show a popup form for user to associate a song with one of their projects.
 */
function show_add_to_project_popup(project_id, multi_projects, anchor_id)
{
//     alert(project_id);
//     alert(multi_projects);

    if (in_process)
    {
	alert('You are already in the middle of adding a song to a project.');
	return;
    }
    in_process = true;
    
    if (multi_projects)
    {
	get_add_to_project_multi(project_id, anchor_id);
    }
    else
    {
	show_add_to_project_solo(project_id, anchor_id);
    }

    return;
}


/**
 * Send request to server to get the project list so that
 * it can be displayed in a select list.
 */
function get_add_to_project_multi(song_id, anchor_id)
{
    var myAjax = new sack();
    myAjax.requestFile = project_server_loc;    

    myAjax.setVar('Action', 'ajax_get_project_list');
    
    myAjax.onCompletion = function() {
	show_add_to_project_multi(myAjax, song_id, anchor_id);
    };
    myAjax.runAJAX();
}

/**
 * show a popup with the project select and comments field.
 */
function show_add_to_project_multi(myAjax, song_id, anchor_id)
{
    var proj_select_content = myAjax.response;

    if (proj_select_content.match(/^Status:ERROR/))
    {
	alert(proj_select_content);
	return;
    }
	
    var prompt = 'Enter comments about how this song relates to your project';
    var button_callback = function() {handle_add_to_project_multi();};
    var button_text = "Add To Project";
    var content_div = create_proj_select_form_content(song_id, prompt, proj_select_content,
						      button_text, button_callback);

//     var height = '12em';
//     var width = '28em';
    var height = '200px';
    var width = '500px';
    var name = 'popup_form';
    var top_offset = 0;
    var left_offset = 500;
    
    var anchor = document.getElementById(anchor_id);
    if (! anchor)
    {
	alert("Couldn't find anchor div!");
	return;
    }

    var parent = anchor;
    var top = -40;
    var left = 45;

    var name = 'popup_form';

    close_func = function () { in_process = false;};

    create_popup_window(parent, name, height, width, top, left, content_div, close_func);
}

/**
 * Callback function to add a song to a project when there are multiple projects.
 */
function handle_add_to_project_multi()
{
    in_process = false;

    var proj_id_el = document.getElementsByName('project_id')[0];
    if (! proj_id_el)
    {
	alert("Couldn't find proj_id element!");
	return;
    }
    
    var comments_el = document.getElementsByName('comments')[0];
    if (! comments_el)
    {
	alert("Couldn't find comments element!");
	return;
    }

    var song_id_el = document.getElementsByName('song_id')[0];
    if (! song_id_el)
    {
	alert("Couldn't find the song ID element!");
	return;
    }
    
    var comments = comments_el.value;
    var song_id = song_id_el.value;
    var project_id = proj_id_el.value;

    var myAjax = new sack();
    myAjax.requestFile = project_server_loc;    

    myAjax.setVar('Action', 'ajax_add_song_to_project_multi');
    myAjax.setVar('comments', comments);    
    myAjax.setVar('song_id', song_id);    
    myAjax.setVar('project_id', project_id);    
    
    myAjax.onCompletion = function() {
	var response = myAjax.response;
	var list_values = response.split("\n");
	if (list_values[0] != 'OK')
	{
	    alert(response);
	    return;
	}

	alert("The song has been added to your project.");
    };
    myAjax.runAJAX();
    
    close_popup_window('popup_form');


}


/**
 * Create a div with a textfield for notes.
 */
function create_proj_select_form_content(song_id, prompt, proj_select_content,
						      button_text, button_callback_func)
{
    var sel_div = document.createElement("div");
    sel_div.style.padding = '2em';
    sel_div.style.paddingBottom = '1em';

    var proj_select_div = document.createElement("div");
    proj_select_div.innerHTML = proj_select_content;

    var proj_label = document.createElement("span");
    proj_label.className = 'popup_prompt_label';
    proj_label.appendChild(document.createTextNode('Select project:'));

    
    var comment_field = document.createElement("input");
    comment_field.type = "text";
    comment_field.name = "comments";
    comment_field.id = "comments";
    comment_field.size = comments_tf_nchars;

    var span = document.createElement("span");
    span.className = 'popup_prompt_label';
    span.appendChild(document.createTextNode(prompt + ":"));

    var hidden = document.createElement("input");
    hidden.type = "hidden";
    hidden.name = "song_id";
    hidden.id = "song_id";    
    hidden.value = song_id;
    
    
    var setButton = document.createElement("input");
    setButton.type="button";
    setButton.value= button_text;
    setButton.onclick = button_callback_func;

    sel_div.appendChild(proj_label);
    sel_div.appendChild(proj_select_div);
    
    //sel_div.appendChild(document.createElement("br"));
    
    sel_div.appendChild(span);
    sel_div.appendChild(comment_field);
    sel_div.appendChild(hidden);
    
    sel_div.appendChild(document.createElement("br"));
    sel_div.appendChild(document.createElement("br"));    
    sel_div.appendChild(setButton);

    return sel_div;
}


/**
 *  Show a popup with a comments field only.
 */
function show_add_to_project_solo(song_id, anchor_id)
{
    var prompt = 'Enter comments about how this song relates to your project';
    var button_callback = function() {handle_add_to_project_solo();};
    var button_text = "Add To Project";
    var content_div = create_comment_form_content(song_id, prompt, button_text, button_callback);

//     var height = '10em';
//     var width = '28em';
    var height = '160px';
    var width = '500px';
    var name = 'popup_form';
    var top_offset = -50;
    var left_offset = 500;
    
    var anchor = document.getElementById(anchor_id);
    if (! anchor)
    {
	alert("Couldn't find anchor div!");
	return;
    }

    var parent = anchor;
    var top = -40;
    var left = 45;

    var name = 'popup_form';

    close_func = function () { in_process = false;};

    create_popup_window(parent, name, height, width, top, left, content_div, close_func);
}


function handle_add_to_project_solo()
{
    in_process = false;
    var comments_el = document.getElementsByName('comments')[0];
    if (! comments_el)
    {
	alert("Couldn't find comments element!");
	return;
    }

    var song_id_el = document.getElementsByName('song_id')[0];
    if (! song_id_el)
    {
	alert("Couldn't find the song ID element!");
	return;
    }
    
    var comments = comments_el.value;
    var song_id = song_id_el.value;

    var myAjax = new sack();
    myAjax.requestFile = project_server_loc;    

    myAjax.setVar('Action', 'ajax_add_song_to_project_solo');
    myAjax.setVar('comments', comments);    
    myAjax.setVar('song_id', song_id);    
    
    myAjax.onCompletion = function() {
	var response = myAjax.response;
	var list_values = response.split("\n");
	if (list_values[0] != 'OK')
	{
	    alert(response);
	    return;
	}

	alert("The song has been added to your project.");
    };
    myAjax.runAJAX();
    
    close_popup_window('popup_form');
}

/**
 * Create a div with a textfield for notes.
 */
function create_comment_form_content(song_id, prompt, button_text, button_callback_func)
{
    var sel_div = document.createElement("div");
    sel_div.style.padding = '2em';
    sel_div.style.paddingBottom = '1em';

    var comment_field = document.createElement("input");
    comment_field.type = "text";
    comment_field.name = "comments";
    comment_field.id = "comments";
    comment_field.size = comments_tf_nchars;

    var span = document.createElement("span");
    span.className = 'popup_prompt_label';
    span.appendChild(document.createTextNode(prompt + ":"));

    var hidden = document.createElement("input");
    hidden.type = "hidden";
    hidden.name = "song_id";
    hidden.id = "song_id";        
    hidden.value = song_id;
    
    
    var setButton = document.createElement("input");
    setButton.type="button";
    setButton.value= button_text;
    setButton.onclick = button_callback_func;

    sel_div.appendChild(span);
    sel_div.appendChild(comment_field);
    sel_div.appendChild(hidden);
    
    sel_div.appendChild(document.createElement("br"));
    sel_div.appendChild(document.createElement("br"));    
    sel_div.appendChild(setButton);

    return sel_div;
}



/**
 * Create a popup window with a given geometry and a div containing the content.
 * Only one popup window of a specific name is allowed to be displayed.
 *
 */
var displayed_popup_windows = new Object();
function create_popup_window(parent_element, name, height, width, top, left, content_div, close_callback)
{
    // Only allow a single popup of given name to be displayed.
    if (displayed_popup_windows[name])
	return;
    
    var div = document.createElement("div");
    div.className = "popup_div";
    div.name = name;
    div.id = name;
    
//     div.style.top = top;
//     div.style.left = left;
    div.style.height = height;
    div.style.width = width;

    var close = document.createElement("a");
    close.onclick = function ()
 	{
 	    close_popup_window(name);
	    if (close_callback)
	    {
		close_callback();
	    }
 	};
    var aspan = document.createElement("span");
    aspan.style.fontWeight = 'bold';
    aspan.style.cursor = 'pointer';
    aspan.appendChild(document.createTextNode(" [Close]"));
    aspan.className = 'close_link';
    close.appendChild(aspan);

    div.appendChild(content_div);
    div.appendChild(close);
    
    parent_element.appendChild(div);

    displayed_popup_windows[name] = true;
    return;
}

function close_popup_window(name)
{
    var win = document.getElementById(name);
    if (! win)
    {
	alert("Couldn't find popup window to close: " + name);
	return;
    }
    win.parentNode.removeChild(win);
    
    delete displayed_popup_windows[name];
    
    return;
}


/**
 * Attribution: http://www.quirksmode.org/js/findpos.html
 */
function findPos(obj)
{
    var curleft = curtop = 0;
    if (obj.offsetParent)
    {
	do
	{
	    curleft += obj.offsetLeft;
	    curtop += obj.offsetTop;
	} while (obj = obj.offsetParent);
    }
    
    return [curleft,curtop];
}
