// include our JavaScript stuff for Ajax
var pickers = new Array();
var group_pickers = new Array();
var search_data = null;
var page_now = null;
var sort_col_index_now =null;
var sort_col_desc = false;
var sort_page_last = null;

var expand_all_arrows = false;

// stores which are expanded by their cue_id
var expanded_cue_arrows = new Array();

var text_box_timer = null;
//var search_retry_timer = null;

// the ajaxml object we need to make our calls
var ajax_r = make_new_ajax_request();
var search_ajax_busy = false;

var max_page_links_to_draw = 5;

var columns = new Array();

any_search_yet = false;
showing_search = true;

col = new Object();
col.pretty_name = "Cue Code";
col.ajax_name = "cueCodeProper";
col.width = 122;
columns.push(col);

col = new Object();
col.pretty_name = "Cue Title";
col.ajax_name = "cueTitle";
col.width = 225;
columns.push(col);

col = new Object();
col.pretty_name = "Cue Description";
col.ajax_name = "cue_description";
col.width = 375;
columns.push(col);

col = new Object();
col.pretty_name = "Length";
col.ajax_name = "length_new";
col.width = 25;
columns.push(col);

var result_rows = null;

// every time a cue is fetched we put it here with an assoc array.
//  believe it or not the main reason I added this was because I wanted to 
//  'show info' in the preview properly
var all_cue_data = new Array();
var bin_data = new Array();
var last_preview_cue_id = null;

var last_text_box_val = null;

function launch_page(is_nr)
{  
   init_panels();

   if (standalone)
   {  do_update(false);  
   }
   else
   {  request_picker_data();
      document.getElementById("top_bar").style.display = "block";
      if (!is_nr) {
         unhide_search_results();
      }
   }

   handle_form_changed();
   show_intro_text();
play_preview(121043, false);

}


function make_export_filename(cue_id)
{
   cue_code = all_cue_data[cue_id].cue_code;
   cue_title = all_cue_data[cue_id].cue_title;

   file_name = "";
   if (user.file_naming_mode == 2) // cue code
   {  file_name = cue_code;
   }
   else if (user.file_naming_mode == 1) // cue code_tracktitle
   {  file_name = cue_code + " - " + cue_title;
   }
   else if (user.file_naming_mode == 0) // tracktitle_cudecode
   {  file_name = cue_title+ " - " + cue_code;
   }
   return file_name;
}


function make_download_path(cue_id)
{
   cue_str = all_cue_data[cue_id].cue_code;
   re = new RegExp(/^[ ]*([0-9a-z]*[a-z]+)([0-9][^_]+)*(_([0-9]*))[ ]*$/i);
   re.exec(cue_str);

//  e.g. iota/iota2006
   path = RegExp.$1.toLowerCase() + DIR_SEP + RegExp.$1.toLowerCase() + 
      RegExp.$2 + DIR_SEP + cue_str;
   return path;
}

/*
 * XML Spec
 * <SearchRequest>
 *   <Attribute>
 *      <Name>Genre</Name>
 *      <CombineMode>or</CombineMode> // or 'and'
 *      <Values>
 *        <Value>Bossa Nova</Value>
 *        <Value>Jazz</Value>
 *      </Values>
 *   </Attribute>
 *   ...
 * </SearchRequest>
 */

function  make_page_link(page_num, txt)
{
   return "<A HREF=\"javascript:do_search(" + page_num + "," +
      sort_col_index_now + ");\">" + txt + "</A>&nbsp;";
}

function search_callback()
{  update_cart_status_line();

   if (ajax_r.readyState == 4) {
      if (ajax_r.status == 200) {
         any_search_yet = true;

         // Get the response from the server - conveniently already
         //  as an XML tree (requires some subtle header settings in 
         //  the server script
         var d = ajax_r.responseXML;
         if (d == null)
         {  //alert("caught the Safari problem");
            search_ajax_busy = false;
            return;
         }
         node = d.getElementsByTagName('TotalTitleCount')[0];
         total_title_count= 0;
         if (node)
         {  total_title_count = Number(node.childNodes[0].nodeValue);
         }
         tracks_returned = 0;
         node = d.getElementsByTagName('TrackCount')[0];
         if (node)
         {  tracks_returned = Number(node.childNodes[0].nodeValue);
         }
   
         show_search(true);
         show_search_form(true);

         search_string = null;
         node = d.getElementsByTagName('SearchDescrip')[0];
         if (node && node.childNodes[0])
         {  search_string = node.childNodes[0].nodeValue;
         }

         node = d.getElementsByTagName('SearchWarning')[0];
         if (node)
         {  search_warning = node.childNodes[0].nodeValue;
            el = document.getElementById("search_warning");   
            el.innerHTML = search_warning;
         }
         else
         {
            el = document.getElementById("search_warning");   
            el.innerHTML = "";
         }

      if (total_title_count)
      {  
         out = "Found " + total_title_count + " titles ";
         if (search_string)
         {  out += " for <B>" + search_string + "</B>";
         }
         clear_results_table();
         draw_results_table_title();

         node = d.getElementsByTagName('Page')[0];

      // get the page number we are currently showing.  if we don't cast
      //  this as a number we get into trouble as we do arithmetic on it
      //  below in drawing the page links
         if (node)
         {  page_num = Number(node.childNodes[0].nodeValue);
         }
         
         if (Number(total_title_count) > Number(max_results_per_page))
         {  first = 1 + ((page_num - 1)*max_results_per_page);
            last = total_title_count - first > max_results_per_page ? 
               page_num*max_results_per_page : total_title_count; 
            out += " - showing titles " + first + " to " + last;
         }
         out += " (" + tracks_returned + " tracks)";

      // how many pages total do we have?
         last_page = Math.ceil(total_title_count / (max_results_per_page));

      // the var where we prep what we're going to dump out the page links
         page_pick_out = "";

         if (last_page > 1)
         {
            first_page_link = (page_num - Math.round(max_page_links_to_draw/2) + 
               max_page_links_to_draw % 2);
            if (first_page_link < 1)
            {  first_page_link = 1;
            }

            last_page_link = (first_page_link + max_page_links_to_draw - 1);
            if (last_page_link > last_page)
            {  last_page_link = last_page;
            }
            if (first_page_link > 1)
            {  page_pick_out += make_page_link(1, "(first)") +"&nbsp;";
               left = Math.max(1, page_num - max_page_links_to_draw);
               page_pick_out += make_page_link(left, "&lt;&lt;") +"&nbsp;";
            }
      // previous page link            
            if (page_num > 1)
            {  page_pick_out += make_page_link(page_num - 1, "&lt;") +"&nbsp;";
            }
            for (i = first_page_link; i <= last_page_link; i++)
            {  if (i > first_page_link) 
               {  page_pick_out += " ";
               }
               if (i == page_num)
               {  page_pick_out += "<B>" + i + "</B>";
               }
               else
               {  page_pick_out += make_page_link(i, i);
               }
               page_pick_out += "&nbsp;";
            }
      // previous page link            
            if (page_num < last_page)
            {  page_pick_out += make_page_link((page_num + 1), '&gt;') + 
                  '&nbsp';
            }
            if (last_page_link < last_page)
            {  right = Math.min(last_page, page_num + max_page_links_to_draw);
               page_pick_out += make_page_link(right, '&gt;&gt;') + 
                  "&nbsp;";
               page_pick_out += make_page_link(last_page, '(last)');
            }            
         }
         page_pick_out += "<DIV CLASS='tight'></DIV>";
      // find the elemend where we draw our page links
         page_el = document.getElementById("page_picker_top");
         page_el.innerHTML = page_pick_out;
         page_el = document.getElementById("page_picker_bottom");
         page_el.innerHTML = page_pick_out;

      // now draw the results in a table
         table = document.getElementById("results_table");
         item_groups = d.getElementsByTagName('ItemGroup');

         result_rows = new Array();

         row_now = 0;
         for (ig = 0; ig < item_groups.length; ig++)
         {  
            items = item_groups[ig].getElementsByTagName('Item');
            if (items.length > 0)
            {  
               for (i = 0; i < items.length; i++)
               {  //title = items[i].getElementsByTagName("CueTitle").textContent;
                  row = table.insertRow(row_now);
                  col = 0;

                  row.className = "result_" + (ig%2 ? "odd" : "even");
                  row.isOdd = (ig%2 != 0);
   
                  cat_id = items[i].getElementsByTagName("CatalogID")[0].childNodes[0].nodeValue;
                  cue_id= items[i].getElementsByTagName("CueKey")[0].childNodes[0].nodeValue;

                  cell = row.insertCell(col++);
                  cell.className = "mainTextTable";
              // cue code field 
                  cell.width = "116";
                  out2 = '';
                  rhs_arrow = '';

                  if (items.length > 1 && i == 0)
                  {  //alert(ig); 
                  
                     out2 += '<IMG SRC="/img/arrow_closed_' + 
                        (domain_info.white_on_black_results_bin ? "light" : "dark") +
                        '.gif" ALIGN="TOP" onclick="javascript:toggle_arrow_row('+ row_now +')" style="padding:2px 3px 0px 0px;display:none" ID="arrow_rt_' + cue_id + '">';

                    out2 += '<IMG SRC="/img/arrow_open_' +
                        (domain_info.white_on_black_results_bin ? "light" : "dark") +
                        '.gif" ALIGN="TOP" onclick="javascript:toggle_arrow_row('+ row_now +')" style="padding:2px 3px 0px 0px;display:none" ID="arrow_dn_' + cue_id + '">';
                     rhs_arrow += '<IMG SRC="/img/arrow_closed_flipped_' + 
                        (domain_info.white_on_black_results_bin ? "light" : "dark") +
                        '.gif" ALIGN="TOP" onclick="javascript:toggle_arrow_row('+ row_now +')" style="padding:2px 3px 0px 0px;display:none" ID="arrow_rt_rhs_' + cue_id + '">';

                    rhs_arrow += '<IMG SRC="/img/arrow_open_' +
                        (domain_info.white_on_black_results_bin ? "light" : "dark") +
                        '.gif" ALIGN="TOP" onclick="javascript:toggle_arrow_row('+ row_now +')" style="padding:2px 3px 0px 0px;display:none" ID="arrow_dn_rhs_' + cue_id + '">';
                  }
                  else if (i == 0)
                  {  rhs_arrow = out2;
                     out2 += '&nbsp;&nbsp;&nbsp;&nbsp;';
                  }
              
                  if (i != 0)
                  {  out2 += "&nbsp;&nbsp;- " + cat_id;
                     rhs_arrow = "&nbsp;-";
                  }
                  else
                  {  out2 += cat_id;
                  }
                  cell.innerHTML = out2;

                  cue_title_in = items[i].getElementsByTagName("CueTitle")[0].childNodes[0];
                  if (cue_title_in)
                  {  cue_title = cue_title_in.nodeValue;
                  }
                  else
                  {  cue_title = "-";
                  }
                  cell = row.insertCell(col++);
                  cell.className = "mainTextTable";
                  cell.width = 225;
                  cell.style.padding = "1px 5px 1px 0px";
                  cell.innerHTML = cue_title;

                  album_title_in = items[i].getElementsByTagName("AlbumTitle")[0].childNodes[0];
                  if (album_title_in)
                  {  album_title = album_title_in.nodeValue;
                  }
                  else
                  {  album_title = "-";
                  }
/* we no longer draw the album title, but we do store it for later
                  cell = row.insertCell(col++);
                  cell.className = "mainTextTable";
                  cell.width = 300;
                  cell.innerHTML = album_title;
*/
                  composer_in = items[i].getElementsByTagName("Composer")[0].childNodes[0];
                  if (composer_in)
                  {  composer= composer_in.nodeValue;
                  }
                  else
                  {  composer = "";
                  }

                  publisher_in = items[i].getElementsByTagName("Publisher")[0].childNodes[0];
                  if (publisher_in)
                  {  publisher= publisher_in.nodeValue;
                  }
                  else
                  {  publisher = "";
                  }

                  cue_description_in = items[i].getElementsByTagName("CueDescription")[0].childNodes[0];
                  if (cue_description_in)
                  {  cue_description = cue_description_in.nodeValue;
                  }
                  else
                  {  cue_description = "-";
                  }

                  // cue description
                  cell = row.insertCell(col++);
                  cell.className = "mainTextTable";
                  cell.style.padding = "1px 5px 1px 0px";
                  cell.width = 375; // biggest one; force width
                  cell.innerHTML = cue_description;

                  cue_length_in = items[i].getElementsByTagName("Length")[0].childNodes[0];
                  if (cue_length_in)
                  {  cue_length = cue_length_in.nodeValue;
                  }
                  else
                  {  cue_length = "-";
                  }
                  cell = row.insertCell(col++);
                  cell.className = "mainTextTable";
                  cell.width = 25;
                  cell.innerHTML = cue_length;

                  cell = row.insertCell(col++);
                  cell.className = "mainTextTable";
                  cell.width = 22;
                  cell.innerHTML = rhs_arrow;

                  preview_id = items[i].getElementsByTagName("PreviewCode")[0].childNodes[0].nodeValue;
                  cell = row.insertCell(col++);
                  cell.className = "mainTextTable";
                  cell.valign="middle";
                  if (search_only)
                  {  cell.width = 40;
                  }
                  else
                  {  cell.width = 100;
                  }

                  this_row = new Object();
                  this_row.el = row;
                  this_row.cue_id = cue_id;
                  this_row.cue_code = cat_id;
                  this_row.cue_title = cue_title;
                  this_row.cue_length = cue_length;
                  this_row.disc_title = album_title;
                  this_row.cue_description = cue_description;
                  this_row.publisher = publisher;
                  this_row.composer = composer;
                  this_row.preview_id = preview_id;
                  // arrow stuff
                  this_row.expanded = expand_all_arrows;

                  if (expanded_cue_arrows[cue_id] != undefined)
                  {  this_row.expanded = true;
                  }

                  this_row.children = new Array();

                  result_rows[row_now] = this_row;
                  all_cue_data[cue_id] = this_row;

                  if (items.length > 1)
                  {
                     if (i == 0)
                     {  last_parent_row = this_row;
                        document.getElementById("arrow_dn_" + this_row.cue_id).style.display = 
                           this_row.expanded ? "" : "none";
                        document.getElementById("arrow_rt_" + this_row.cue_id).style.display = 
                           !this_row.expanded ? "" : "none";
                        document.getElementById("arrow_dn_rhs_" + this_row.cue_id).style.display = 
                           this_row.expanded ? "" : "none";
                        document.getElementById("arrow_rt_rhs_" + this_row.cue_id).style.display = 
                           !this_row.expanded ? "" : "none";
                     }
                     else
                     {  last_parent_row.children.push(this_row);
                        this_row.el.style.display = (last_parent_row.expanded ? "" : "none")
                     }
                  }

                  out2 = '';
                  if (standalone)
                  {  
                  }


                   out2 += "<A HREF=\"javascript:play_preview(" + cue_id + ");\"><img src=\"/img/speaker_" + (domain_info.white_on_black_results_bin ? "light" : "dark") + ".gif\" style=\"border-style:none;\"></A>&nbsp;&nbsp;";
                  if (items.length > 1 && i == 0)
                  {  //alert(ig); 
                  }
                  if (!search_only)
                  {
                     out2 += get_cart_link(cue_id, row_now);
                  }
   /*               if (!standalone)
                  { 
                     out2 += "&nbsp;&nbsp;&nbsp;";
                     out2 += "<A HREF=\"javascript:show_info_request(true, " + 
                        cue_id + ");\"><img src=\"/img/info.gif\" style=\"border-style:none;\"></A>";
                  }
   */
                  out2 += "&nbsp;&nbsp;";
                  cell.innerHTML = out2;
                  if (!search_only)
                  {
                     popup_control = document.createElement('img');
                     button_id = "search_button_" + cue_id;
                     popup_control.setAttribute('id', button_id);
                     popup_control.style.cursor = "pointer";
                     popup_control.src = '/img/gear_' + 
                        (domain_info.white_on_black_results_bin ? "light" : "dark") +".gif";
                     popup_control.cue_id = cue_id;
                     popup_control.onclick = show_gear_menu;
                     cell.appendChild(popup_control);
                  }
                  row_now++;
               }
            }
         }
         
      }
      else if (total_title_count == 0)
      {  if (search_string)
         {  out = "Found no results for <B>" + search_string + "</B>";
         }
         else
         {  out = "Found no results";
         }
         clear_results_table();
      } 
      else if (total_title_count == -1)
      {  out = "SEARCH ERROR";
      }
      search_ajax_busy = false;
   }

  highlight_preview_row();

  el = document.getElementById("search_count");   
  el.innerHTML = out;
  document.getElementById("intro_text").innerHTML = '';
      
   }
}

function toggle_arrow_row(row_id)
{
   row = result_rows[row_id];
   row.expanded = !row.expanded;
   thing ="arrow_dn_" + row.cue_id;
 
   document.getElementById(thing).style.display = 
      row.expanded ? "" : "none";
   document.getElementById("arrow_rt_" + row.cue_id).style.display = 
      !row.expanded ? "" : "none";

   thing ="arrow_dn_rhs_" + row.cue_id;
 
   document.getElementById(thing).style.display = 
      row.expanded ? "" : "none";
   document.getElementById("arrow_rt_rhs_" + row.cue_id).style.display = 
      !row.expanded ? "" : "none";
  
   for (i = 0; i < row.children.length; i++)
   {  
      row.children[i].el.style.display = (row.expanded ? "" : "none");
   }
}

function play_dummy()
{  
   el = document.getElementById("preview_quicktime");   
   el.innerHTML = 
"<OBJECT CLASSID=\"clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B\" WIDTH=\"320\" HEIGHT=\"16\" CODEBASE=\"http://www.apple.com/qtactivex/qtplugin.cab\" HIDDEN>" + 
"<EMBED SRC=\"/null.mp3\"" + 
"WIDTH=\"320\" HEIGHT=\"16\" AUTOPLAY=\"true\" KIOSKMODE=TRUE CONTROLLER=\"false\" LOOP=\"false\" PLUGINSPAGE=\"http://www.apple.com/quicktime/\" HIDDEN>" +
"</EMBED>" +
"<PARAM NAME=\"HIDDEN\" VALUE=\"true\">" + 
"<PARAM NAME=\"src\" VALUE=\"/null.mp3\">" + 
"<PARAM NAME=\"autoplay\" VALUE=\"true\">" +
"<PARAM NAME=\"controller\" VALUE=\"false\">" +
"<PARAM NAME=\"loop\" VALUE=\"false\">" + 
"</OBJECT>";
   el.style.display = "none";
}

function play_preview_mini(cue_id)
{ 
   if (standalone && !check_for_preview_file(cue_id))
   {  return;
   }

   cue_code  = all_cue_data[cue_id].cue_code;   
   cue_title = all_cue_data[cue_id].cue_title;
   preview_id = all_cue_data[cue_id].preview_id;

   var el = document.getElementById("preview_cue_code_mini"); 
   el.innerHTML = cue_code;

   el = document.getElementById("preview_cue_title_mini");
   el.innerHTML = cue_title.toUpperCase();

   el = document.getElementById("preview_quicktime_mini");   
   el.style.display = "";

 // NOTE !!
 // if I don't urlencode *here* things will break.  It seems as if JS
 //  does a URL decode on the link that we make that calls this function.
 //
   el.innerHTML = get_audio_block("/preview.php?k=" + urlencode(preview_id));
 
   el = document.getElementById("audio_preview_mini");   
   el.style.display = "block";
   draw_cart_in_table();
}

function highlight_preview_row()
{
   // redraw the row we're doing next with the preview style
   if (last_preview_cue_id &&
      result_rows && all_cue_data[last_preview_cue_id])
   {  
      if (all_cue_data[last_preview_cue_id] && all_cue_data[last_preview_cue_id].el) {
         all_cue_data[last_preview_cue_id].el.className = "result_picked";
      }
   }
}

function update_preview_cart() {
   var cart_control = document.getElementById("preview_cart");
   if (!cart_control) return;

   cart_control.innerHTML = "<A HREF=\"javascript:add_to_cart(" + 
      last_preview_cue_id + ");" +
      "\"><img src=\"/img/" + (is_in_cart(last_preview_cue_id) ?
      "cart_full_" : "cart_empty_") +
      (domain_info.white_on_black_results_bin ? "dark" : "light")
      + '.gif" ' +
      "style=\"border-style:none;\"></A>";
}

function play_preview(cue_id, autoplay)
{  
   if (autoplay === undefined) autoplay = true;
   if (standalone && !check_for_preview_file(cue_id))
   {  return;
   }
   cue_code  = all_cue_data[cue_id].cue_code;   
   cue_title = all_cue_data[cue_id].cue_title;
   preview_id = all_cue_data[cue_id].preview_id;
   disc_title = all_cue_data[cue_id].disc_title;
   disc_code = cue_code.split('_')[0]; 

   // if something in the result list had been the preview track before,
   //  change it back to its normal row color/style (from the green preview
   //  highlight style)
   if (result_rows != null && last_preview_cue_id != null)
   {  
      row = all_cue_data[last_preview_cue_id].el;
      if (row) {
         row.className = (row.isOdd ? "result_odd" : "result_even");
      }
   }
   last_preview_cue_id = cue_id;
   highlight_preview_row();

   var pc = document.getElementById("preview_gear");
   if (pc) {
   pc.style.cursor = "pointer";
   pc.src = '/img/gear_' + 
      (domain_info.white_on_black_results_bin ? "dark" : "light") +".gif";
   pc.cue_id = cue_id;
   pc.onclick = show_gear_menu;
   }

   update_preview_cart(cue_id);

 // NOTE !!
 // if I don't urlencode *here* things will break.  It seems as if JS
 //  does a URL decode on the link that we make that calls this function.
 //

   el = document.getElementById("jump_to_disc_link_cover");   
   if (el) 
   {  el.href = "javascript:jump_to_disc('" + disc_code + "')";
   }

   el = document.getElementById("album_art");   
   el.src = "/album_art.php?k=" + cue_id;

   el = document.getElementById("preview_disc_code");   
   el.innerText = disc_code;

   el = document.getElementById("preview_disc_title");   
   el.innerHTML = disc_title.toUpperCase();

   el = document.getElementById("jump_to_disc_link");   
   if (el) 
   {  el.href = "javascript:jump_to_disc('" + disc_code + "')";
   }

   el = document.getElementById("preview_cue_code");   
   el.innerHTML = cue_code;

   el = document.getElementById("preview_cue_title");   
   el.innerHTML = cue_title.toUpperCase();
   el = document.getElementById("preview_quicktime");   
   el.style.display = "block";
   el.innerHTML = get_audio_block("/preview.php?k=" + urlencode(preview_id), 300, autoplay);

   el = document.getElementById("audio_preview");   
   el.style.display = "block";
   draw_cart_in_table();
}

function get_audio_block(media, width, autoplay) {
   if (!width) width = 300;
   if (autoplay === undefined) autoplay = true;

   var is_IE = (browser()=="ie");
   var mimetype = (is_IE ?  'audio/x-ms-wma' : 'audio/mpeg')
   var tralse = autoplay ? "true" : "false";

   var src;
   if (!is_IE) {
   src = '<object type="'+mimetype+'" data="'+media+'" '
 + 'width="'+width+'" height="16">'
 + '<param name="src" value="'+media+'">'
 + '<param name="autoplay" value="' + tralse +'">'
 + '<param name="bgcolor" value="' + domain_info.bg_color + '">'
 + '<param name="kioskmode" value="true">' 
 + '<param name="volume" value="100">'
 + '<param name="loop" value="false">'
 + '<param name="autoStart" value="0">'
 + 'alt : <a href="'+media+'">'+media+'</a>'
 + '</object>';
   } else {
   src = 
"<OBJECT CLASSID=\"clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B\" WIDTH=\""+width+"\" HEIGHT=\"16\" KIOSKMODE=\"" + tralse +"\" BGCOLOR=\"" + domain_info.bg_color + "\" CODEBASE=\"http://www.apple.com/qtactivex/qtplugin.cab\">" + 
//"<EMBED SRC=\"http://69.20.5.173:9666/o1engine-licensing/actions/getMov.do?playID=" + cue_id + "\"" + 
"<EMBED SRC=\"" + media + "\" " + 
"WIDTH=\""+width+"\" HEIGHT=\"16\" AUTOPLAY=\"" + tralse + "\" KIOSKMODE="+tralse+" BGCOLOR=\"" + domain_info.bg_color + "\" CONTROLLER=\"true\" LOOP=\"false\" PLUGINSPAGE=\"http://www.apple.com/quicktime/\">" +
"</EMBED>" +
"<PARAM NAME=\"src\" VALUE=\"" + media + "\">" + 
"<PARAM NAME=\"bgcolor\" VALUE=\"" + domain_info.bg_color + "\">" +
"<PARAM NAME=\"kioskmode\" VALUE=\""+tralse + "\">" +
"<PARAM NAME=\"autoplay\" VALUE=\"" + tralse + "\">" +
"<PARAM NAME=\"controller\" VALUE=\"true\">" +
"<PARAM NAME=\"loop\" VALUE=\"false\">" + 
"</OBJECT>";
   }
   return src;
}

function clear_preview_nr(zone, row)
{
   i = 0;
   while (true)
   {
      el = document.getElementById("nr_preview_area" + i);
      if (el)
      {  el.style.display = "none";

         el = document.getElementById("nr_cue_table" + i);

         for (j = 1; j < el.rows.length; j++)
         {
            if (i == zone && j == row)
            {  el.rows[j].className = "mainTextTable result_picked";
            }
            else
            {  el.rows[j].className = "mainTextTable result_"+
                  (j % 2 ? 'even' : 'odd');   
            }
         }
         i++;
      }
      else
      {  break;
      }     
   }
}

function play_preview_nr(cue_id, zone, row)
{
   clear_preview_nr(zone, row);

   cue_code  = all_cue_data[cue_id].cue_code;   
   cue_title = all_cue_data[cue_id].cue_title;
   preview_id = all_cue_data[cue_id].preview_id;

   el = document.getElementById("nr_preview_area" + zone);
   el.style.display = "block";

   el = document.getElementById("nr_preview_cue_title" + zone);
   el.innerHTML = cue_title;

   el = document.getElementById("nr_preview_cue_code" + zone);
   el.innerHTML = cue_code;

   el = document.getElementById("nr_preview" + zone);
   el.innerHTML = get_audio_block(
      "/preview.php?k=" + urlencode(preview_id), 300);
}

function jump_to_disc(disc)
{
   search_data = new Object;
   search_data.attributes = new Array();

   search_data.search_text_box = "=" + disc;
   do_search(1, null);
}

function do_search(page, sort_col_index)
{ 
   // if we're in the midst of a search already, schedule ourselves to
   //  do the search after 1000 ms.  Also, cancel any other delayed &
   //  scheduled searchces 
//   if (search_ajax_busy)
//   {  clearTimeout(search_retry_timer);
      //search_retry_timer = 
      //   setTimeout('do_search(' + page + ',' + sort_col_index + ')', 500);
//      return;
//   }
   
   search_ajax_busy = true;
   log_debug("ajax busy");
   page_now = page;

   // if this is the same page and column, then toggle the desc
   if (sort_page_last == page && sort_col_index_now == sort_col_index)
   {  sort_col_desc = !sort_col_desc;
   }
   // if it's a different sort column, reset to sort ascend
   else if (sort_col_index_now != sort_col_index)
   {  sort_col_desc = false;
   }
   // else, leave the sorting along

   sort_col_index_now = sort_col_index;
   sort_page_last = page;
//var search_retry_timer = null;
 
   if (!search_data)
   {  return -1;
   }
   xml = "<\?xml version=\"1.0\"\?><SearchRequest>";

   // if this is an initial search, we have no sort columns yet.  We want
   //  to search by added_date.  This is a funky case.  But bascially if
   //  sort_col_index is null, we won't tell the backend what to order by,
   //  and so it will order by its default, which is added_date
   if (sort_col_index_now != null)
   {  
      xml += "<SortBy>" + columns[sort_col_index_now].ajax_name + "</SortBy>";
   }
   xml += "<SortDesc>" + (sort_col_desc ? '1' : '0') + "</SortDesc>";
   xml += "<Page>" + page + "</Page>";

   if (search_data.search_text_box)
   {  
      xml += "<SearchTextBox>" + xml_escape(search_data.search_text_box) +
         "</SearchTextBox>";
   }

   for (i = 0; i < search_data.attributes.length; i++)
   {  
      this_attr = search_data.attributes[i];
      if (this_attr.values.length)
      {
         xml += "<Attribute>" +
            "<Name>" + this_attr.name + "</Name>";
         xml += "<Values>";
         for (j = 0; j < this_attr.values.length; j++)
         {
            xml += "<Value>" + xml_escape(this_attr.values[j]) + "</Value>";
            xml += "<Pretty>" + xml_escape(this_attr.pretties[j]) + "</Pretty>";
         }
         xml += "</Values>";
         xml += "</Attribute>";
      }      
   }

   xml += "</SearchRequest>";
   xml = "xml=" + escape(xml);
   ajax_r.open("POST", "/search_backend.php", true);
   ajax_r.onreadystatechange = search_callback;
   ajax_r.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   ajax_r.send((xml));

/*

         "<Attribute>"
 *      <Name>Genre</Name>
 *      <CombineMode>or</CombineMode> // or 'and'
 *      <Values>
 *        <Value>Bossa Nova</Value>
 *        <Value>Jazz</Value>
 *      </Values>
 *   </Attribute>
 *   ...
 * </SearchRequest>
*/
}

function handle_text_box_changed(keyCode, val) 
{  
/*   if (val.length <= 0)
   {  return;
   }*/
   if (keyCode == 13)
   {  clearTimeout(text_box_timer);
      handle_form_changed();
   }
   // character or delete key pressed; reschedule
   else if (keyCode > 40 || keyCode == 8) 
   {  clearTimeout(text_box_timer);
      text_box_timer = setTimeout(handle_form_changed, 500);
   }
}

function log_debug(s)
{  el = document.getElementById("debug");
   if (el)
   {  el.innerHTML = s;
   }
}

// note, we break up the thing that gets the query from the things that
//  do the ajax submission on purpose
function handle_form_changed()
{  
   needs_search = false;

   search_data = new Object;
   search_data.attributes = new Array();

   text_in = trim(document.getElementById('search_text_box').value);
   
   if (text_in)
   {  search_data.search_text_box = text_in;
      needs_search = true;
   }
   for (i=0; i < group_pickers.length; i++)
   {

      ctl = group_picker_ctls[group_pickers[i]];
      attrib_name = ctl.my_name;
      
      // one attribute per 'picker'
      attribute = new Object;
      search_data.attributes.push(attribute);
      attribute.name = attrib_name;
      attribute.values = new Array();
      attribute.pretties = new Array();

      for (j = 0; j < ctl.picked.length; j++)
      {
         rd = ctl.row_data[ctl.picked[j]];
         attribute.values.push(rd.val);
         attribute.pretties.push(rd.pretty);
         needs_search = true;
   }  }  

   for(i =0 ; i < pickers.length; i++)
   { 
      attrib_name = pickers[i];
      // strip off the prefix I give to attributes
      attrib_name = attrib_name.replace(attr_prefix, "");

      // one attribute per 'picker'
      attribute = new Object;
      search_data.attributes.push(attribute);
      attribute.name = attrib_name;
      attribute.values = new Array();
      attribute.pretties = new Array();

   // get the HTML/DOM element
      el = document.getElementById(pickers[i]);   
      s = "";

      for (j = 0; j < el.options.length; j++)
      {
         if (el.options[j].selected)
         {
            attribute.values.push(el.options[j].value);
            attribute.pretties.push(el.options[j].text); //?

   // don't search if only length is picked
            if (attrib_name != "Length")
            {  needs_search = true;
   }  }  }  

}

   // do a 'clean' search
   if (needs_search)
   {
//      clearTimeout(search_retry_timer);
      do_search(1, null);
   }
   else
   {  clear_results_table();
   }
}

function draw_results_table_title()
{
   var table = document.getElementById("results_table_header");
   row = table.insertRow(0);
   row.className = "result_title";
   row.style.height = "25";
   for (i = 0; i < columns.length; i++)
   {  
      cell = row.insertCell(i);
      cell.innerHTML = '<B>' +
         (columns[i].pretty_name == "Cue Code" ? "&nbsp;&nbsp;&nbsp;&nbsp;" : "" ) +
         '<A class="mainTextTableHeader" HREF="javascript:'+
         'do_search(' + page_now + ',' + i + ');">' + 
         columns[i].pretty_name + '</B>' + "</A>&nbsp;";
//      if (columns[i].pretty_name == "Length")
//      {  cell.colSpan="2";
//      }
      cell.width = columns[i].width;
   }

   // draw arrow on RHS
//   cell = row.insertCell(i++);

   // draw special case cart thing
   cell = row.insertCell(i++);
   cell.style.padding = "0px 0px 0px 28px";
   cell.innerHTML = '<SPAN id="main_cart_icon">'+
// hack
   '<IMG SRC="' + "/img/cart_empty_" + 
   (domain_info.white_on_black_results_bin ? "dark" : "light") + ".gif" +
   '">' 
+'</SPAN><span id="cart_in_table"></SPAN>';

//   cell.innerHTML = '<span id="cart_in_table" class="mainTextTableHeader"></SPAN>'; //Preview
   cell.width = 100;
   draw_cart_in_table();
}

function clear_preview()
{  
   el = document.getElementById("preview_quicktime");   
   el.innerHTML = "";
   el = document.getElementById("audio_preview");   
   el.style.display = "none";
   el = document.getElementById("audio_preview_mini");
   if (el)
   {  el.style.display = "none";
   }
}

function show_intro_text()
{  clear_preview();
   el = document.getElementById("intro_text");   
   if (!el)
   {  return;
   }
   out =   
'<table class="mainText" border="0" width="655">' +
'  <tr>' +
'    <td>' +
'      <p align="center" class="mainTextBold">Welcome to ';

   if (standalone)
   {   out += "the Opus1 Standalone Engine.";
   }
   else
   {  out += domain_info.display_name + ' online o1engine.</p>';
   }
 
   if (domain_info.domain_logo)
   {  out += '<CENTER><IMG SRC="/img/domain_logos/' + domain_info.domain_logo + '"></CENTER>';
   }
   out += domain_info.intro_text;
   el.innerHTML = out;
}


function show_search(show)
{  showing_search = show;
   table = document.getElementById("search_section");
   if (table)
   {  table.style.display = (show ? "block" : "none");
   }
   table = document.getElementById("search_results_div");
   if (table)
   {  table.style.display = (show ? "block" : "none");
   }
}

function show_search_form(show)
{  showing_search = show;
   table = document.getElementById("search_form_section");
   if (table)
   {  table.style.display = (show ? "" : "none");
   }
}

function unhide_search_results()
{  
   show_cart(false);
   show_my_bins(false);
   show_bin(false, 0);
   show_info_request(false, 0);
   show_login(false);
   show_order_summary(false, null);
   show_share(false, null);
   show_register(false);
   if (standalone)
   {  show_prefs(false);
      show_updater(false);
   }
   show_needledrop(false);
   show_data_find(false);
   show_new_releases(false);
   show_cue_sheets(false);

   show_search(true);
   show_search_form(true);
   update_cart_status_line();
   update_breadcrumb("SEARCH", false);   

   if (!any_search_yet)
   {  show_intro_text();
   }
}


function clear_results_table()
{
   /*el.innerHTML = TEST.exportCueSheet_("This is a complex string");*/
   document.getElementById("search_count").innerHTML = ''; 
   document.getElementById("page_picker_top").innerHTML = ''; 
   document.getElementById("page_picker_bottom").innerHTML = ''; 

   var table = document.getElementById("results_table");
   var row_count = table.rows.length;
   var result_rows = null;

   for (var i = row_count; i > 0; i--)
   {  table.deleteRow(0);
   }

   table = document.getElementById("results_table_header");
   row_count = table.rows.length;
   result_rows = null;

   for (i = row_count; i > 0; i--)
   {  table.deleteRow(0);
   }
}


function clear_pickers()
{
   for (ii=0; ii < group_pickers.length; ii++)
   {  
      ctl = group_picker_ctls[group_pickers[ii]];
      ctl.clear_picks();
   }

   for(i =0 ; i < pickers.length; i++)
   {  
   // get the HTML/DOM element
      el = document.getElementById(pickers[i]);   
      picked = new Array();
      s = "";

      while (el.selectedIndex != -1)
      {
         el.options[el.selectedIndex].selected = false;
         el.blur();
      }
   }
}

function clear_choices()
{  
   search_data = null;
   clear_results_table();
   show_intro_text();  
   unhide_search_results(); 

   el = document.getElementById('search_text_box').value = "";

   clear_pickers();   
}

