
var ajax_r = make_new_ajax_request();
var showing_login = false;
var cart_cue_to_add = null;
var new_release_to_dl_after_login = null;


function update_login_bar()
{  
   el = document.getElementById("login_bar");
   
   out = '';
   out += '<TABLE class="minimal_table"><TR valign="middle">';
   if (standalone)
   {  
      out += '<TD NOWRAP>' + get_export_bar() + '</TD>';
//      out += "&nbsp;&nbsp;";

      out += /*'&nbsp;&nbsp;*/'<TD><A class="loginBarText" HREF="javascript:show_prefs(true);">' + mk_button("PREFS")  + '</A></TD>';
   }
   else if (search_only)
   {
   }
   else
   {  
      out += "<TD>";

      if (user.is_guest)
      {  out += /*'Guest&nbsp;&nbsp;*/'<A class="loginBarText" href="javascript:show_login(true)">' +mk_button('LOGIN') + '</A>&nbsp;<A class="loginBarText" href="javascript:show_register(true)">' + mk_button("REGISTER") + '</A>';
      }
      else
      {  //out += user.welcome_name;
         out += /*'&nbsp;&nbsp;*/'<A class="loginBarText" HREF="javascript:show_register(true, true);">' + mk_button("MY ACCOUNT")  + '</A>';
         out += '&nbsp;<A class="loginBarText" href="javascript:logout()">' + mk_button("LOGOUT") + '</A>';
      }
   }
   out += "</TD><TD>";

   if (standalone || (!search_only && !user.is_guest))
   {
      out += '&nbsp;<A HREF="javascript:show_cart(true);">' +
         '<IMG style="border:0px;" '+
         'SRC="/img/cart_' + (cart_order.length > 0 ? 'full_' : 'empty_') +
         (domain_info.white_on_black ? "light" : "dark")  +'.gif">' +
         '</A></TD><TD><A HREF="javascript:show_cart(true);">'+
         'Cart</A>';
 
      var el2 = document.getElementById("main_cart_icon");
      if (el2) {
         el2.innerHTML = 
            '<A HREF="javascript:show_cart(true);">' +
            '<IMG style="border:0px;" '+
            'SRC="/img/cart_' + (cart_order.length > 0 ? 'full_' : 'empty_') + 
            (domain_info.white_on_black ? "light" : "dark")  +'.gif">' +
            '</A>';/*<A HREF="javascript:show_cart(true);">'+ 'Cart</A>';*/
      }
   }
   out += "<TD>";
   out += '&nbsp;'+
      '<A class="loginBarText" HREF="javascript:show_help();">' +
      '<IMG style="border:0px;" SRC="/img/info_' +
      (domain_info.white_on_black ? "light" : "dark") +'.gif"></A>'; 

   out += '</TD></TR></TABLE>';
   el.innerHTML = out;
}

function show_help()
{
window.open("/styles/usa/help.html","Window1",
"menubar=no,width=600,height=500,toolbar=no,scrollbars=yes");

}

function reset_password()
{  
   val = document.getElementById("user_input").value;
   if (!isValidEmail(val))
   {  showAlert("To reset your password, please first enter in the email " +
         "address for your account");
      return;
   }

   if (doConfirm("Did you forget your password?\r\n" + 
      "Are you sure you want to reset your password?\r\n" +
      "Your current password will be replaced with a random, temporary one " +
      "and sent to your email address."))
   {  
      xml  = "<\?xml version=\"1.0\"\?><AccountEditRequest>" +
         "<Mode>password_reset</Mode>" +
         "<Email>" + xml_escape(val) + "</Email>" +
         "</AccountEditRequest>";
      xml = "xml=" + escape(xml);
      ajax_r.open("POST", "/account_edit_backend.php", true);
      ajax_r.onreadystatechange = password_reset_callback;
      ajax_r.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      ajax_r.send(xml);
   }
}



function password_reset_callback()
{
   if (ajax_r.readyState == 4) {
      if (ajax_r.status == 200) {

         // 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;

         node = d.getElementsByTagName('Result')[0];
         if (!node ||  node.childNodes[0].nodeValue != "Success")
         {
            s = "Error talking to server";
            node = d.getElementsByTagName('Error')[0];
            if (node)
            {  s += "\n" + node.childNodes[0].nodeValue;
            }
            showAlert(s);
         }
         else
         {
            node = d.getElementsByTagName('AccountResult')[0];
            if (node.childNodes[0].nodeValue != "Success")
            {  errors = new Array();
               node = d.getElementsByTagName('Error');
               if (node)
               {
                 for (i = 0; i < node.length; i++)
                  {  errors.push(node[i].childNodes[0].nodeValue);
                  }
               }
               else
               {  errors.push("Unknown error talking to server");
               }
               showAlert(errors);
            }
            else
            {  
               showAlert("A new password has been sent to your email addres.");
            }
         }
      }
   }
}


function show_admin_login(show)
{
   el = document.getElementById("login_section");
   if (el == null)
   {  return;
   }
   el.style.display = (show ? "block" : "none");

   showing_login = show;

   if (show != true)
   {  // all done now 
      return;
   }
   update_breadcrumb("LOGIN", false);
   set_status('', false); 
}

function show_login(show, cart_cue)
{  
   cart_cue_to_add = cart_cue;
   el = document.getElementById("login_section");
   if (el == null)
   {  return;
   }

   el.style.display = (show ? "block" : "none");

   showing_login = show;

   if (show != true)
   {  // all done now 
      return;
   }
   update_breadcrumb("LOGIN", false);
   set_status('', false); 

   clear_preview();
   show_cart(false);
   show_my_bins(false); 
   show_bin(false, 0); 
   show_info_request(false, 0);
   show_order_summary(false, null);
   show_search(false);
   show_search_form(false);
   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);

   update_cart_status_line();
}



function handle_login_text_box_changed(keyCode)
{  if (keyCode == 13) // enter
   {  el = document.getElementById("login_form");
      el.submit();
   }
}

function submit_login(is_admin)
{  user_in   = document.getElementById("user_input").value;
   pass_in   = document.getElementById("password_input").value;
   process_login(user_in, pass_in, true, cart_cue_to_add, is_admin);
}

function set_status(text, is_error)
{
   el = document.getElementById("login_status");
   el.style.color = (is_error ? "red" : "black");
   el.innerHTML = text;
}

function process_login(user_in, pass_in, is_login, cue_id, is_admin)
{
   xml  = "<\?xml version=\"1.0\"\?><LoginRequest>";
   xml += "<Login>" + (is_login ? "1" : "0") + "</Login>";

   if (is_login)
   {  xml += "<Username>" + xml_escape(user_in) + "</Username>";
      xml += "<Password>" + xml_escape(pass_in) + "</Password>";
      xml += "<Admin>" + (is_admin ? "1" : "0") + "</Admin>";
      if (cue_id)
      {  xml += "<AddCueIDToCart>" + xml_escape(cue_id) + "</AddCueIDToCart>";
      }
   }
   xml += "</LoginRequest>";
   xml = "xml=" + escape(xml);

   set_status("Communicating with the server", false);
   ajax_r.open("POST", "/login_backend.php", true);
   ajax_r.onreadystatechange = login_callback;
   ajax_r.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   ajax_r.send(xml);
}

function logout()
{  
   reset_user_data();
   unhide_search_results();
   reset_cart_icons();
   process_login(null, null, false, null);
}


function login_callback()
{
   if (ajax_r.readyState == 4) {
      if (ajax_r.status == 200) {

         // 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;

         admin_mode = false;
         node = d.getElementsByTagName('Admin')[0];
         if (node && node.childNodes[0].nodeValue == 1)
         {  admin_mode = true;
         }
         node = d.getElementsByTagName('Result')[0];

         if (!node ||  node.childNodes[0].nodeValue != "Success")
         {  
            s = "Error talking to server";
            node = d.getElementsByTagName('Error')[0];
            if (node)
            {  s += "\nError: " + node.childNodes[0].nodeValue;
            }
            set_status(s, true);
         }
         else
         {  node_in  = d.getElementsByTagName('LoginResult')[0];
            node_out = d.getElementsByTagName('LogoutResult')[0];
            if (node_in)
            {  if (node_in.childNodes[0].nodeValue != "Success")
               {
                  msg = '???';
                  node = d.getElementsByTagName('ErrorMsg')[0];
                  if (node)
                  {  msg = node.childNodes[0].nodeValue;
                  }
                  set_status("Login failed: " + msg, true)
               }
               else
               {  if (admin_mode)
                  {  window.location = "/webadmin/main.php";
                     return;
                  }
                  node_in = d.getElementsByTagName('Redirect')[0];
                  if (node_in)
                  {  redirect_to = node_in.childNodes[0].nodeValue;
                     showAlert("You're account is configured to use a different site; you will now be redirected.  Please login again when you arrive.");
                     window.location = redirect_to;
                     return;
                  }
                  set_status("Authentication successful..." + 
                     "processing info from the server", false);

         // process the user data
                  reset_user_data();
         
                  user.is_guest = false;

                  node =  d.getElementsByTagName('LoginMessage')[0];
                  if (node)
                  {  showAlert(node.childNodes[0].nodeValue);
                  }

                  node =  d.getElementsByTagName('FirstName')[0].childNodes[0];
                  if (node)
                  {  user.first_name = node.nodeValue;
                  }
                  node =  d.getElementsByTagName('LastName')[0].childNodes[0];
                  if (node)
                  {  user.last_name = node.nodeValue;
                  }
                  node =  d.getElementsByTagName('PrettyName')[0].childNodes[0];
                  if (node)
                  {  user.pretty_name = node.nodeValue;
                  }
                  if (user.first_name)
                  {  user.welcome_name = user.first_name;
                  }
                  else if (user.last_name)
                  {  user.last_name = user.last_name;
                  }
                  else
                  {  user.welcome_name = "User";
                  }
                  
                  node =  d.getElementsByTagName('Breadcrumb')[0].childNodes[0];
                  if (node)
                  {  user.breadcrumb = node.nodeValue;
                  }
                  node =  d.getElementsByTagName('IsAnnual')[0].childNodes[0];
                  if (node)
                  {  user.is_annual = (node.nodeValue == "1" ? true : false);
                  }
                  node =  d.getElementsByTagName('Preset')[0].childNodes[0];
                  if (node)
                  {  user.preset = node.nodeValue;
                  }
                  node =  d.getElementsByTagName('City')[0].childNodes[0];
                  if (node)
                  {  user.city = node.nodeValue;
                  }
                  node =  d.getElementsByTagName('State')[0].childNodes[0];
                  if (node)
                  {  user.state = node.nodeValue;
                  }
                  node =  d.getElementsByTagName('Zip')[0].childNodes[0];
                  if (node)
                  {  user.zip = node.nodeValue;
                  }
                  node =  d.getElementsByTagName('Address')[0].childNodes[0];
                  if (node)
                  {  user.address = node.nodeValue;
                  }
                  node =  d.getElementsByTagName('Country')[0].childNodes[0];
                  if (node)
                  {  user.country = node.nodeValue;
                  }
                  node =  d.getElementsByTagName('Phone')[0].childNodes[0];
                  if (node)
                  {  user.phone = node.nodeValue;
                  }
                  node =  d.getElementsByTagName('Fax')[0].childNodes[0];
                  if (node)
                  {  user.fax = node.nodeValue;
                  } 
                  node =  d.getElementsByTagName('Email')[0].childNodes[0];
                  if (node)
                  {  user.email = node.nodeValue;
                  }
                  node =  d.getElementsByTagName('Company')[0].childNodes[0];
                  if (node)
                  {  user.company = node.nodeValue;
                  }
                  node =  d.getElementsByTagName('UserID')[0].childNodes[0];
                  if (node)
                  {  user.user_id = node.nodeValue;
                  }
                  node =  d.getElementsByTagName('FileNamingMode')[0].childNodes[0];
                  if (node)
                  {  user.file_naming_mode = node.nodeValue;
                  }

         // we do not want to erase our cue data as we may need it
         //  for dealing with a pre-login search - but do purge the bin
         //  and cart data
                  n  = d.getElementsByTagName('CueData')[0];
                  if (n)
                  {  
                     cues  = n.getElementsByTagName('Cue');
                     for (i = 0; i < cues.length; i++)
                     {  this_n = cues[i];
                        c = new Object();
                        c.cue_id = this_n.getElementsByTagName('CueID')[0].childNodes[0].nodeValue;
                        c.cue_code = this_n.getElementsByTagName('CueCode')[0].childNodes[0].nodeValue;
                        node = this_n.getElementsByTagName('CueTitle')[0].childNodes[0];
                        if (node)
                        {  c.cue_title = node.nodeValue;
                        }
                        node = this_n.getElementsByTagName('CueDescription')[0].childNodes[0];
                        if (node)
                        {  c.cue_description= node.nodeValue;
                        }
                        node = this_n.getElementsByTagName('CueLength')[0].childNodes[0];
                        if (node)
                        {  c.cue_length= node.nodeValue;
                        }
                        node = this_n.getElementsByTagName('DiscTitle')[0].childNodes[0];
                        if (node)
                        {  c.disc_title = node.nodeValue;
                        }
                        c.preview_id = this_n.getElementsByTagName('PreviewCode')[0].childNodes[0].nodeValue;
                        all_cue_data[c.cue_id] = c;
                     }
                  }
         // load in bin data
                  n  = d.getElementsByTagName('BinData')[0];
                  bins = n.getElementsByTagName('Bin');
                  for (i = 0; i < bins.length; i++)
                  {  this_n = bins[i];
                     c = new Object();
                     c.bin_name = this_n.getElementsByTagName('BinName')[0].childNodes[0].nodeValue;
                     c.bin_key = this_n.getElementsByTagName('BinKey')[0].childNodes[0].nodeValue;
                     c.cues = new Array();
                     bin_cues = this_n.getElementsByTagName('CueID');
                     for (j = 0; j < bin_cues.length; j++)
                     {  c.cues.push(bin_cues[j].childNodes[0].nodeValue);
                     } 
                     bin_data[c.bin_key] = c;
                  }
         // load in cart data
                  n  = d.getElementsByTagName('CartData')[0];
                  cart_cues = n.getElementsByTagName('CueID');
                  for (i = 0; i < cart_cues.length; i++)
                  {  cart_cue = cart_cues[i].childNodes[0].nodeValue;
                     c = new Object();
                     c.is_pending_cart = 0;
        // seesm a bit weird but saved me rewriting a bunch of code
                     cart_order.push(cart_cue);
                     icon = document.getElementById("cart_" + cart_cue);
                     if (icon)
                     {  icon.src = "/img/cart_full_" +
                           (domain_info.white_on_black_results_bin ? "light" : "dark") 
                           + ".gif";
                     }
                  }
                  update_login_bar();
                  update_cart_status_line();
                  request_picker_data();
                  if (cart_cue_to_add)
                  {  show_cart(true);
                  }
                  else if (new_release_to_dl_after_login)
                  {  show_new_releases(true, '');
                     start_nr_download_callback();
                  }
                  else
                  {  unhide_search_results();
                  }
                  cart_cue_to_add = null; 
               }
            }
            else if (node_out)
            {  if (node_out.childNodes[0].nodeValue != "Success")
               {  showAlert("logout failed somehow");
               }
               else
               {  node =  d.getElementsByTagName('Preset')[0].childNodes[0];
                  if (node)
                  {  user.preset = node.nodeValue;
                  }
                  request_picker_data();
               }
            }
         }
      }
   }
}

function reset_user_data()
{
   user = new Object();
   user.is_guest = true;
   user.is_share_guest = false;

   user.first_name = '';
   user.last_name = '';
   user.welcome_name = '';
   user.pretty_name = '';
   user.company = '';
   user.breadcrumb = 'SEARCH';
   user.is_annual = false;
   user.address = '';
   user.city = '';
   user.state = '';
   user.zip = '';
   user.country = '';
   user.phone = '';
   user.fax = '';
   user.email = '';
   user.preset = '';
   user.file_naming_mode = 0;
   
   cart_order = new Array();

   bin_data = new Array();
   update_login_bar();
   update_cart_status_line();
}

// we really don't do anything with this; the Ajax to update breadcrumbs
//  is only for the server's benefit
/*
function breadcrumb_callback()
{
   if (ajax_r.readyState == 4) {
      if (ajax_r.status == 200) {

         // 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;
         node = d.getElementsByTagName('Result')[0];

         if (!node ||  node.childNodes[0].nodeValue != "Success")
         {  
         }
         else
         {  
         }
      }
   }
}
*/

