// $RCSfile: streetprices.js,v $
// Copyright (c) 2008 StreetPrices.com Inc.
// All rights reserved.
var undefined;
var page;
if (!page)                { page = new Object(); }
if (!page.editors)        { page.editors = new Object(); }
if (!page.products)       { page.products = new Object(); }
if (!page.wishlist_array) { page.wishlist_array = new Array; }

page.prefURL   = "/pref/";
page.loginURL  = "/pref/login.pl";
page.turingURL = "https://secure.streetprices.com/pref/vt.pl";
page.secureLoginURL = "https://secure.streetprices.com/accounts/login.pl";

page.MAX_SPID_HISTORY = 250;
page.beta_left_beta = 787287374; //authority is beta.h

var dashboard;  // leave this undefined

// functions for creating accounts and writing reviews
page.checkUsernameInfo = new Object();

page.checkUsernameAvailability = function page_checkUsernameAvailability(username) {
  var req = new Ajax.Request(page.loginURL + '?cmd=avail&user=' + encodeURIComponent(username), { onSuccess: page.usernameIsAvailable, on403: page.usernameNotAvailable, onError: page.usernameNotAvailable });
};
page.checkUsername = function page_checkUsername(username,response_div,next_div)
{
   page.checkUsernameInfo.username = username;
   page.checkUsernameInfo.response_div = response_div;
   page.checkUsernameInfo.next_div = next_div;

   page.checkUsernameInfo.error_msg = page.invalidUsername(username);

   if (!page.checkUsernameInfo.error_msg) {
      page.checkUsernameAvailability(username);
   } else {
      page.usernameNotAvailable();
   }
}

page.usernameNotAvailable = function page_usernameNotAvailable(t) {
   var response_div = page.checkUsernameInfo.response_div;
   var next_div = page.checkUsernameInfo.next_div;
   var error_msg = page.checkUsernameInfo.error_msg;

   if (response_div) {
      response_div.innerHTML = '<br>sorry, this username is not available' + 
                        ((error_msg) ? "<br>" + error_msg : "");
      response_div.style.color = 'red';
      response_div.style.display = '';
   }
   if (next_div) {
      next_div.style.display = 'none';
   }
}

page.usernameIsAvailable = function page_usernameIsAvailable(t)
{
   var response_div = page.checkUsernameInfo.response_div;
   var next_div = page.checkUsernameInfo.next_div;

   if (response_div) {
      response_div.innerHTML = 'yes!';
      response_div.style.color = 'green';
      response_div.style.display = '';
   }
   if (next_div) {
      next_div.style.display = '';
   }
};

page.checkPassword = function page_checkPassword(pass,pass2,response_div)
{
   var error_msg = page.invalidPassword(pass,pass2);
   
   if (!error_msg) {
      if (response_div) {
         response_div.innerHTML = '';
         response_div.style.color = 'green';
         response_div.style.display = '';
      }
   } else {
      if (response_div) {
         response_div.innerHTML = error_msg;
         response_div.style.color = 'red';
         response_div.style.display = '';
      }
   }
};
page.checkEmail = function page_checkEmail(email,response_div)
{
   var error_msg = page.invalidEmail(email);

   if (!error_msg) {
      if (response_div) {
         response_div.innerHTML = '';
         response_div.style.color = 'green';
         response_div.style.display = '';
      }
   } else {
      if (response_div) {
         response_div.innerHTML = error_msg;
         response_div.style.color = 'red';
         response_div.style.display = '';
      }
   }
};

page.refreshTuring = function page_refreshTuring(field,img) {
   field = $(field);
   if (field) {
      img = $(img);
      var r = Math.random();
      if (r) {
         img.src = page.turingURL + '?' + r;
         field.value = r;
      }
   }
}


page.accountCreationFailed = function page_accountCreationFailed(reason)
{
   if (!page.createAccountInfo) {
      return false;
   }
   var response_div = page.createAccountInfo.response_div;
   var show_nodes = page.createAccountInfo.show_nodes;
   var hide_nodes = page.createAccountInfo.hide_nodes;
   var username_div = page.createAccountInfo.username_div;

   if (response_div) {
      if (typeof reason == 'string') {
         response_div.innerHTML = 'hmm, there was a problem creating your account.  ' + reason;
      } else {
         response_div.innerHTML = 'Hmm, there was a problem creating your account.  Please try again.';
      }
      response_div.style.color = 'red';
      response_div.style.display = '';
   }
   page.refreshTuring('create_account_form_rand_field','create_account_form_turing_img');

   if (hide_nodes && hide_nodes.length) {
      for (var i in hide_nodes) {
         if (hide_nodes[i] && hide_nodes[i].style) {
            hide_nodes[i].style.display = 'none';
         }
      }
   }
   if (show_nodes && show_nodes.length) {
      for (var i in show_nodes) {
         if (show_nodes[i] && show_nodes[i].style) {
            show_nodes[i].style.display = '';
         }
      }
   }
   return true;
};

page.accountCreationSucceeded = function page_accountCreationSucceeded(t)
{
   var response_div = page.createAccountInfo.response_div;
   var show_nodes = page.createAccountInfo.show_nodes;
   var hide_nodes = page.createAccountInfo.hide_nodes;
   var username_div = page.createAccountInfo.username_div;
   var username = page.createAccountInfo.username;

   if (response_div) {
      response_div.innerHTML = 'account created!';
      response_div.style.color = 'green';
      response_div.style.display = '';
   }

   // if there's a username div, we're refreshing _just this form_ inline
   // (ie for reviews) and replacing the create-acct form with the text username
   //
   // otherwise, it's normal, just refresh the page
   if (username_div) {
      username_div.innerHTML=username;
   
      for (var div in hide_nodes) {
         if (hide_nodes[div].style) {
            hide_nodes[div].style.display = 'none';
         }
      }
      for (var div in show_nodes) {
         if (show_nodes[div].style) {
            show_nodes[div].style.display = '';
         }
      }
   } else {
      window.location.reload(true);
      // don't bother hiding or showing -- we're refreshing the page!
   }
};


page.finishReviewSubmit = function page_finishReviewSubmit() 
{
   $('product_review_div').style.display='none';
   $('product_review_form_link').style.display='';
   $('product_review_form_link').innerHTML='edit your review';
   $('product_review_id').value = 2; // XXX -- get real ID
};

page.checkAccountValues = function page_checkAccountValues(username,pass,pass2,email,newsletter,turing,rand,response_div,turing_img,rand_field,hide_nodes,show_nodes,username_div) 
{
   // do some simple checks
   if (!pass || !pass2) {
      page.accountCreationFailed("please fill in both password fields");
   }
   if (!username) {
      page.accountCreationFailed("please choose a username");
   }
   if (!email) {
      page.accountCreationFailed("please include your email address so we can confirm your account");
   }
   var msg;
   if ((msg = page.invalidPassword(pass,pass2))) {
      page.accountCreationFailed("please choose a different password: " + msg);
   }
   if ((msg = page.invalidUsername(username))) {
      page.accountCreationFailed("please choose a longer username (at least 3 letters long)");
   }
   if ((msg = page.invalidEmail(email))) {
      page.accountCreationFailed("please check the email address you gave us: " + msg);
   }
}


page.invalidUsername = function page_invalidUsername(username)
{
   var msg = '';

   if (username.length < 4) {
      msg += "username must be at least four letters long<br>";
   } else if (username.length > 20) {
      msg += "your username must be 20 letters at most<br>";
   }
   if (!username.match(/^[A-Za-z0-9\@\.\-]+$/)) {
      msg += "username may only contain letters and numbers (no spaces), plus @.-<br>";
   }

   return msg;
}

page.invalidPassword = function page_invalidPassword(pass,pass2)
{
   var msg = '';

   if (pass && pass2 && (pass != pass2)) {
      msg += "Oops!  Your passwords don't match.<br>";
   }
   if (pass && pass.length < 8 || 
       !(pass.match(/[a-z]/i) && pass.match(/[^a-z]/i))) 
   {
      msg += "Passwords must be at least <b>8 letters long</b>,<br> and contain at least <b>one letter</b> and <b>one number</b>/punctuation.<br>";
   }

   return msg;
}

page.invalidEmail = function page_invalidEmail(email)
{
   var msg = '';

   if (!email.match(/^[\w\-\.]+\@[a-z0-9\-]+\.([a-z]{2,3}|[a-z]{2}.[a-z]{2})$/i)) {
      msg += "your email address looks funny; please check for typos<br>";
   }

   return msg;
}

page.validateAccountVariables = function page_validateAccountVariables(args) 
{
   var error_messages = '';
   var msg = '';
   var valid = 1;

   if (args['username']) {
      msg = page.invalidUsername($F(args['username']));
      if (msg) { 
         valid = 0; 
         error_messages += msg; 
         if (args['username_response']) {
            args['username_response'].innerHTML = msg; 
            args['username_response'].style.color = 'red';
            args['username_response'].style.display = '';
         }
      }
   }

   if (args['pass'] && args['pass2']) {
      msg = page.invalidPassword($F(args['pass']),$F(args['pass2']));
      if (msg) { 
         valid = 0; 
         error_messages += msg; 
         if (args['password_response']) {
            args['password_response'].innerHTML = msg; 
            args['password_response'].style.color = 'red';
            args['password_response'].style.display = '';
         }
      }
   }

   if (args['email']) {
      msg = page.invalidEmail($F(args['email']));
      if (msg) { 
         valid = 0; 
         error_messages += msg; 
         if (args['email_response']) {
            args['email_response'].innerHTML = msg; 
            args['email_response'].style.color = 'red';
            args['email_response'].style.display = '';
         }
      }
   }

   if (args['response']) {
         args['response'].innerHTML = error_messages; 
   }

   return valid;
};

// create a layer greying-out the entire page
// everything with a z-index <= 100 will be greyed out
page.greyOut = function page_greyOut(options)
{
   if (!options) { options = {}; }

   if (!page.shadow) {
      var shadow = document.createElement("div");
      var height = 0;
      var test1 = document.body.scrollHeight;
      var test2 = document.body.offsetHeight
      if (document.body.scrollHeight > document.body.offsetHeight)
      {
         height = document.body.scrollHeight;
      }
      else
      {
         height = document.body.offsetHeight;
      }
      if (window.innerHeight && height < window.innerHeight) {
         height = window.innerHeight;
      }

      shadow.id = "page_shadow";
      shadow.style.position = "absolute";
      shadow.style.top = 0;
      shadow.style.left = 0;
      shadow.style.height = height + "px";
      shadow.style.width = "100%";
      shadow.style.backgroundColor = '#000000';
      shadow.style.display = 'none';
      var div = $('sp_page_content');
      if (div) {
         div.appendChild(shadow);
      } else {
         document.body.appendChild(shadow);
      }
      page.shadow = $('page_shadow');
   }

   // update it based on the options chosen, and show it!
   page.shadow.style.zIndex  = (options['z_index']) ? options['z_index'] : 100;
   page.shadow.style.opacity = (options['opacity']) ? options['opacity'] : 0.5;
   page.shadow.style.filter= 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + (((options['opacity']) ? options['opacity'] : 0.5) * 100) + ')';
   page.shadow.style.display = '';
}
page.removeGrey = function page_removeGrey()
{
   if (page.shadow) {
      page.shadow.style.display = 'none';
   }
}

page.showForm = function page_showForm(form, focusField, greyOut) 
{
   if (form) {
      form = $(form);
      if (form && form.style) {

         if (form.id == 'price_alert_form_container') {
             var link = $('price_alert_link_container');
             if (link) { link.hide(); } 
//             try {
//               new Effect.BlindDown(form.id);
//             } catch(e) {
               form.show();
//             }
         } else {
            form.show();
         }

         if (greyOut) { page.greyOut({}); }
      }
      // If a focusField was supplied, put the focus there
      if (focusField) {
         
         focusField = $(focusField);

	 try {
	    focusField.focus();
	 } catch (e) {};
      }
   }
   return false;
}
page.hideForm = function page_hideForm(form) 
{
   page.removeGrey();
   if (form) {
      form = $(form);
      if (form && form.style) {
         if (form.id == 'price_alert_form_container') {
             try {
               new Effect.BlindUp(form.id, { afterFinish: function() { $('price_alert_link_container').show(); }});
             } catch(e) {
                var link = $('price_alert_link_container');
                link.show();
                form.hide();
             }
         } else {
            form.hide();
         }
      }
   }
   return false;
}

page.resetPassword = function page_resetPassword(username)
{
   try{
   if (!username && document.getElementById('login_form_username_field'))
   {
      username = document.getElementById('login_form_username_field').value;
   }
   if (!username && page.getCookie) {
      username = page.getCookie('user');
   }
  if (username) {
      new Ajax.Updater('login_form_message_div', page.loginURL, {
         method: 'post',
         postBody: 'cmd=resetpass&user=' + username,
         onComplete: function() { 
                        if (document.getElementById('login_form_username_section'))
                        {
                           var div = document.getElementById('login_form_message_div');
                           div.innerHTML += 
                              "<a href=\"javascript:void(null);\" style=\"float: right; margin-top: 10px;\" onClick=\"document.getElementById('login_form_username_section').style.display=''; document.getElementById('login_form_contents').style.display=''; document.getElementById('reset_password_form_contents').display='none'; document.getElementById('login_form_message_div').style.display='none'; return false;\">log in</a>";
                        } else {
                           var login_link = document.getElementById('login_link');
                           if (login_link && login_link.style.display != 'none')
                           { 
                              login_link.style.display='none'; 
                              document.getElementById('password_info').style.display=''; 
                              document.getElementById('forgot_link').style.display=''; 
                              document.getElementById('login_button').style.display=''; 
                              document.getElementById('forgot_button').style.display='none'; }
                           }
                        }
      });
   }
   }catch(e){alert(e);}
}

page.userNeedsToLogIn = function page_userNeedsToLogIn()
{
   return false;
//   return (page.getCookie && 
//           page.getCookie('user') && 
//          !page.getCookie('SID'));
}
page.forceLogin = function page_forceLogin(form)
{
   form = $(form);
   var login_form = $('login_form');
   if (!login_form) {
      var c = $('login_form_container');
      if (c) { 
         page.createLoginForm(c); 
         login_form = $('login_form');
      }
   }
   if (login_form)
   {
      var f = $('login_form_pop_form_field');
      if (f && form) { f.value = form.id; }

      if ($('login_form_message_div')) {
         $('login_form_message_div').innerHTML = "Please log in first.";
      }

      try
      {
         login_form.style.top = '30%';
         login_form.style.right = '30%';
         $('login_form_message_div').innerHTML = "Please log in first.";
      }
      catch (e)
      {
      }

      page.showForm('login_form_container', "login_form_password_field",1);
   }
}

page.createAccountForm = function page_createAccountForm(target) 
{
   target = $(target);

   if (target && target.innerHTML == "") {
      target.innerHTML = 
      "<form id=\"create_account_form\" class=\"form_box\" action=\"" + page.secureLoginURL + "\" method=\"post\" target=\"create_account_form_secure_frame\" onsubmit=\"document.getElementById('create_account_button').disabled = true; return true;\" style=\"display: inline\" accept-charset=\"UTF-8\">" +
      "<input type=\"hidden\" id=\"cmd\" name=\"cmd\" value=\"new\">" +
      "<input type=hidden name=\"continue_hostname\" value=\"" + ((window.location.hostname) ? window.location.hostname : "www.streetprices.com") + "\">" +
      "<div id=\"create_account_form_header\">" +
      "<a class=\"x_toggle\" href=\"javascript:void(null);\" onclick=\"page.toggleForm('create_account_form',1); return false;\">X</a>" +
      "<b>create an account</b>" +
      "</div>" +
      "<table><tr><td style=\"width: 125px; vertical-align: top\">" +
      "<label id=\"create_account_username\" class=\"required_field\" for=\"username\">username</label>" + 
      "</td><td>" +
      "<input type=\"text\" id=\"create_account_form_username_field\" name=\"user\" size=\"12\" maxlength=\"20\" onkeydown=\"$('create_account_form_checkusername_button').disabled = false; $('step2').style.display = 'none'; $('create_account_form_username_response').innerHTML='';\" onBlur=\"var button = $('create_account_form_checkusername_button'); if (button && !button.disabled) { button.click();}\">" +
      "<input type=submit name=\"checkusername_button\" id=\"create_account_form_checkusername_button\" onClick=\"page.checkUsername($F('create_account_form_username_field'),$('create_account_form_username_response'),$('step2')); page.refreshTuring('create_account_form_rand_field','create_account_form_turing_img'); return false;\" value=\"is it available?\" disabled>" +
      "<span id=\"create_account_form_username_response\" class=\"message_div\" style=\"margin-left: 6px;\"></span>" +
      "</td></tr></table>" +
      "<div id=\"step2\" style=\"display: none\">" +
      "<table><tr><td style=\"width: 125px;\">" +
      "<label for=\"create_account_form_pass_field\" id=\"create_account_password\" class=\"required_field\">password</label></td><td><input type=\"password\" id=\"create_account_form_password_field\" name=\"newpass1\" size=\"12\" maxlength=\"20\" onBlur=\"page.checkPassword($F('create_account_form_password_field'),$F('create_account_form_pass2_field'),$('create_account_form_password_response'));\">" +
      "</td></tr><tr><td>" +
      "<label id=\"create_account_password2\"for=\"create_account_form_pass2_field\" class=\"required_field\">confirm&nbsp;password</label></td><td><input type=\"password\" id=\"create_account_form_pass2_field\" name=\"newpass2\" size=\"12\" maxlength=\"20\" onBlur=\"page.checkPassword($F('create_account_form_password_field'),$F('create_account_form_pass2_field'),$('create_account_form_password_response'));\"><br>" +
      "<div id=\"create_account_form_password_response\" class=\"message_div\"></div>" +
      "</td></tr><tr><td style=\"vertical-align: top\">" +
      "<label id=\"create_account_email\" for=\"email\" class=\"required_field\">email</label></td><td><input type=\"text\" id=\"create_account_form_email_field\" name=\"email\" size=\"40\" maxlength=\"60\" onBlur=\"if ($F('create_account_form_email_field')) { page.checkEmail($F('create_account_form_email_field'), $('create_account_form_email_response')); }\"><br>" +
      "<span style=\"font-size: smaller;\">needed to verify your account.</span>" +
      "<a href=\"javascript:void(null);\" class=\"morelink\" style=\"margin-left: 20px;\" onclick=\"this.nextSibling.style.display=(this.nextSibling.style.display == 'none') ? 'block' : 'none'; return false;\">privacy</a><div style=\"display: none; font-size: smaller\">we hate spam.  we won't spam you or share your email address with anyone.</div>" +
      "<div id=\"create_account_form_email_response\" class=\"message_div\" style=\"margin-bottom: 6px;\"></div>" +
      "<input type=\"checkbox\" name=\"newsletter\" id=\"create_account_form_newsletter_field\" value=\"1\"> send me the newsletter <span style=\"font-size: x-small; margin-left: 6px;\">3-4 times/year</span>\n<br>" + 
      "</td></tr></table>" +
      "<br>\n<img id=\"create_account_form_turing_img\" src=\"\" alt=\"turing test\"><br>" +
      "<input type=\"hidden\" id=\"create_account_form_rand_field\" name=\"rand\" value=\"\">" +
      "<input type=\"text\" id=\"create_account_form_turing_field\" name=\"turing\" size=\"10\" maxlength=\"10\">" +
      "&nbsp;<label for=\"create_account_form_turing_field\" style=\"white-space: nowrap;\">what letters and numbers do you see in the box above?</label><br><br>\n" +
      "<input type=\"submit\" id=\"create_account_button\" value=\"create account\">" +
      "<div id=\"create_account_form_message_div\" class=\"message_div\" style=\"margin-top: 6px;\"></div>" +
      "</div></form>" +
      "<iframe id=\"create_account_form_secure_frame\" name=\"create_account_form_secure_frame\" style=\"width:1px; height:1px; border:0\" src=\"about:blank\"></iframe>";
   }
}
page.createReviewForm = function page_createReviewForm(target) 
{
   target = $(target);
   if (target && target.innerHTML == "") {
      target.innerHTML = "";
   }
}
page.createLoginForm = function page_createLoginForm(target) 
{
   if (!target.id) { target = document.getElementById(target); }

   if (target && target.innerHTML == "") {
      var username = page.getCookie('user');
      if (!username) { username = ""; }

      target.innerHTML = 
        "<form id=\"login_form\" class=\"form_box\" action=\"" + page.secureLoginURL + "\" method=\"post\" target=\"login_form_secure_frame\" style=\"display: inline; width: 250px;\" onSubmit=\"document.getElementById('login_button').disabled = true; return true;\" accept-charset=\"UTF-8\">" + 
        "<a class=\"x_toggle\" href=\"javascript:void(null);\" onclick=\"page.toggleForm('login_form',1);return false;\" style=\"float: right; width: 10px;\">X</a>" +
        "<br style=\"clear: both\">" +
        "<input type=\"hidden\" id=\"cmd\" name=\"cmd\" value=\"basic\">" +
        "<input type=\"hidden\" id=\"login_form_pop_form_field\" name=\"pop_form\" value=\"\">" +
        "<input type=hidden name=\"continue_hostname\" value=\"" + ((window.location.hostname) ? window.location.hostname : "www.streetprices.com") + "\">" +
        "<div id=\"login_form_message_div\" class=\"message_div\"></div>" +
        "<div id=\"login_form_username_section\">" + 
        "<label for=\"username\" style=\"font-weight: bold;\">username</label> <input type=\"text\" id=\"login_form_username_field\" name=\"user\" value=\"" + username + "\" size=\"20\" maxlength=\"20\"><br>" +
        "</div>" +
        "<div id=\"login_form_contents\">" + 
        "<label for=\"password\" style=\"font-weight: bold;\">password</label> <input type=\"password\" id=\"login_form_password_field\" name=\"pass\" size=\"20\" maxlength=\"20\"><br>" +
        "<input id=\"login_button\" type=\"submit\" value=\"log in\">" +
       "<a href=\"javascript:void(null);\" style=\"float: right; margin-top: 10px;\" onClick=\"document.getElementById('reset_password_form_contents').style.display=''; document.getElementById('login_form_contents').style.display='none'; return false;\">forgot password?</a>" +
        "</div>" +
        "<div id=\"reset_password_form_contents\" style=\"display: none;\">" + 
        "<input id=\"reset_password_button\" type=\"submit\" value=\"reset your password\" onClick=\"page.resetPassword(); document.getElementById('reset_password_form_contents').style.display='none'; document.getElementById('login_form_username_section').style.display='none';  return false;\">" +
       "<a href=\"javascript:void(null);\" style=\"float: right; margin-top: 10px;\" onClick=\"document.getElementById('login_form_contents').style.display=''; document.getElementById('reset_password_form_contents').style.display='none'; return false;\">log in</a>" +
        "</div>" +
        "<iframe id=\"login_form_secure_frame\" name=\"login_form_secure_frame\" style=\"width:1px; height:1px; border:0\" src=\"about:blank\"></iframe>" +
    "</form>";
   }
}
page.createZipcodeForm = function page_createZipcodeForm(target) 
{
   target = $(target);

   if (target && target.innerHTML == "") {
      var zip = page.getCookie('zip');
      if (!zip) { zip = ""; }

      target.innerHTML = 
      "<form id=\"zip_code_form\" name=\"zip_code_form\" class=\"form_box\" onsubmit='page.toggleForm(\"zip_code_form\", 1); page.submitZipToCookie(\"zip_code_form_zip_field\", 1); return false;' action=\"javascript:void(null)\" accept-charset=\"UTF-8\">" +
      "<a class=\"x_toggle\" href=\"javascript:void(null);\" onclick=\"page.toggleForm('zip_code_form',1); return false;\">X</a>" +
      "<span style=\"font-weight: bold; white-space: nowrap;\">zip code <input id=\"zip_code_form_zip_field\" type=text name=zip size=5 value=\"" + zip + "\">" + 
      "<input type=submit value=\"change\"></span>" +
      "</form>";
   }
}
page.createExitFeedbackForm = function page_createExitFeedbackForm(target) 
{
   target = $(target);

   if (target && target.innerHTML == "") {

      target.innerHTML = 
      "<form id=\"exit_feedback_form\" name=\"exit_feedback_form\" class=\"form_box\" onsubmit=\"page.sendExitFeedback(); return false;\" action=\"/ajax/send_feedback.cgi\" accept-charset=\"UTF-8\">" +
      "<a class=\"x_toggle\" href=\"javascript:void(null);\" onclick=\"page.toggleForm('exit_feedback_form',1); return false;\">X</a>" +
      "<div id=\"exit_feedback_form_message_div\"></div>" +
      "<div id=\"exit_feedback_form_contents\" style=\"text-align: left;\">" +
      "<span style=\"font-weight: bold; white-space: nowrap;\">What?!  You want to go back to the old site?</span><br>" + 
      "<a style=\"white-space: nowrap;\" href=\"javascript:void(null);\" onclick=\"page.toggleForm('exit_feedback_form',1); return false;\">Whoa Nelly!  Take me back to that beautiful site!</a><br>" + 
      "<br>" +
      "<span style=\"white-space: nowrap;\">How can we do better?<br>" + 
      "<textarea id=\"exit_feedback_form_feedback_field\" name=\"feedback\" rows=8 cols=30>" +
      "</textarea>" +
      "<p style=\"white-space: normal; margin-bottom: 0;\">We are reading comments as they come in, and fixing the problems.  If you want to know when we've fixed this issue, please <b><nobr>leave us your email or phone#</nobr></b></p>" +
      "<input type=hidden id=\"exit_feedback_form_exit_sneak_preview_field\" name=\"exit_sneak_preview\" value=\"1\">" +
      "<input type=hidden id=\"exit_feedback_form_url_field\" name=\"url\" value=\"" + window.location.href + "\"><br>" +
      "<input type=submit value=\"submit\"></span>" +
      "&nbsp;" +
      "<input type=submit value=\"cancel\" onclick=\"page.toggleForm('exit_feedback_form',1); return false;\"></span>" +
      "</div>" +
      "<div id=\"exit_feedback_form_escape_div\">" +
      "<br><a href=\"javascript:void(null);\" title=\"exit new look and feel\" style=\"cursor:pointer;\" onclick=\"page.setCookie('beta'," + page.beta_left_beta + ", { domain: page.cookieDomain }); window.location.reload(true); return false;\">Just let me out of here!</a>" +
      "</div>" +
      "</form>";
   }
}
page.createFlagFeedbackForm = function page_createFlagFeedbackForm(target) 
{
   target = $(target);

   if (target && target.innerHTML == "") {

      target.innerHTML = 
      "<form id=\"flag_feedback_form\" name=\"flag_feedback_form\" class=\"form_box\" onsubmit=\"page.sendFlagFeedback(); return false;\" action=\"/ajax/send_feedback.cgi\" accept-charset=\"UTF-8\">" +
      "<a id=\"flag_feedback_form_x\" class=\"x_toggle\" href=\"javascript:void(null);\" onclick=\"page.toggleForm('flag_feedback_form',1); return false;\">X</a>" +
      "<div id=\"flag_feedback_form_message_div\"></div>" +
      "<div id=\"flag_feedback_form_contents\" style=\"text-align: left;\">" +
      "<span style=\"font-weight: bold;\">What part of the page needs attention?</span><br>" + 
      "<input type=\"radio\" id=\"flag_feedback_form_problem_field_specs\" name=\"problem\" value=\"specs\"> specs<br>" +
      "<input type=\"radio\" id=\"flag_feedback_form_problem_field_listings\" name=\"problem\" value=\"listings\"> store listings (prices, descriptions, etc)<br>" +
      "<input type=\"radio\" id=\"flag_feedback_form_problem_field_other\" name=\"problem\" value=\"other\" checked> something else<br><br>" +
      "<b>Please explain what we should fix:</b><br>" + 
      "<textarea id=\"flag_feedback_form_feedback_field\" name=\"feedback\" rows=8 cols=30>" +
      "</textarea>" +
      "<p style=\"white-space: normal; margin-bottom: 0;\">If you want to know when we've fixed this issue, please leave us your <i>email</i> or <i>phone #</i>.</p>" +
      "<input type=hidden id=\"flag_feedback_form_url_field\" name=\"url\" value=\"" + window.location.href + "\"><br>" +
      "<input type=submit value=\"submit flag\">" +
      "&nbsp;" +
      "<input type=submit value=\"cancel\" onclick=\"page.toggleForm('flag_feedback_form',1); return false;\"></span>" +
      "</div>" +
      "</form>";
   }
}
page.createFeedbackForm = function page_createFeedbackForm(target) 
{
   target = $(target);

   if (target && target.innerHTML == "") {

      target.innerHTML = 
      "<form id=\"feedback_form\" name=\"feedback_form\" class=\"form_box\" onsubmit=\"page.sendFeedback(); return false;\" action=\"/ajax/send_feedback.cgi\" accept-charset=\"UTF-8\">" +
      "<a class=\"x_toggle\" href=\"javascript:void(null);\" onclick=\"page.toggleForm('feedback_form',1); return false;\">X</a>" +
      "<div id=\"feedback_form_message_div\"></div>" +
      "<div id=\"feedback_form_contents\" style=\"text-align: left;\">" +
      "<span style=\"font-weight: bold; white-space: nowrap;\">Tell us what you think</span><br>" + 
      "<br>" +
      "<span style=\"white-space: nowrap;\">How can we make the site better?<br>" + 
      "<textarea id=\"feedback_form_feedback_field\" name=\"feedback\" rows=8 cols=30 onclick=\"if(this.innerHTML=='We especially savor specific suggestions!') { this.innerHTML=''; }\" onKeyPress=\"if(this.innerHTML=='We especially savor specific suggestions!') { this.innerHTML=''; }\">" +
      "We especially savor specific suggestions!" + 
      "</textarea>" +
      "<p>Or, you can <a href=\"http://www.streetprices.com/feedback/\">review a merchant here</a>.</p>" +
      "<p style=\"white-space: normal; margin-bottom: 0;\">If you'd like to hear back from us when this is fixed, please <b><nobr>leave your email or phone#</nobr></b></p>" +
      "<input type=hidden id=\"feedback_form_exit_sneak_preview_field\" name=\"exit_sneak_preview\" value=\"0\">" +
      "<input type=hidden id=\"feedback_form_url_field\" name=\"url\" value=\"" + window.location.href + "\"><br>" +
      "<input type=submit value=\"submit\"></span>" +
      "&nbsp;" +
      "<input type=submit value=\"cancel\" onclick=\"page.toggleForm('feedback_form',1); return false;\"></span>" +
      "</div>" +
      "</form>";
   }
}
page.createChangeEmailForm = function page_createChangeEmailForm(target) 
{
   target = $(target);
   var user = page.getCookie('user');

   if (!user) {
      alert("Username cookie is missing; please log in again.");
   }

   if (user && target && target.innerHTML == "") {
      target.innerHTML = 
      "<form method=\"POST\" id=\"change_email_form\" name=\"change_email_form\" class=\"form_box\" action=\"" + page.secureLoginURL + "\" target=\"change_email_form_secure_frame\" accept-charset=\"UTF-8\">" +
      "<a class=\"x_toggle\" href=\"javascript:void(null);\" onclick=\"page.toggleForm('change_email_form',1); return false;\" style=\"float:right\">X</a>" +
      "<br style=\"clear: both\">" +
      "<div id=\"change_email_form_message\"></div>" +
      "<div id=\"change_email_form_contents\">" + 
      "<input type=hidden name=cmd value=\"setemail\">" +
        "<input type=hidden name=\"continue_hostname\" value=\"" + ((document.location.hostname) ? document.location.hostname : "www.streetprices.com") + "\">" +
      "<input type=hidden name=user value=\"" + user + "\">" +
      "<label class=\"tabular\" for=\"change_email_form_email_field\" style=\"font-weight: bold; white-space: nowrap;\">email</label> <input class=\"tabular\" id=\"change_email_form_email_field\" type=text name=email size=20 value=\"" + ((page.email) ? page.email : "") + "\"><br>" +
      "<label class=\"tabular\"</label><input class=\"tabular\" type=submit value=\"change email address\">" +
      "<span id=\"change_email_form_pending_verification\"></span>" +
      "</div>" +
      "<iframe id=\"change_email_form_secure_frame\" name=\"change_email_form_secure_frame\" style=\"width:1px; height:1px; border:0\" src=\"about:blank\"></iframe>" +
      "</form>";

      if (!page.email) {
         new Ajax.Request(page.loginURL, {
            method: 'get', 
            parameters: "cmd=getemail",
            onSuccess:  function(req) { 
                           if (req && req.responseText) { 
                              page.email = eval(req.responseText); 
                              var field = $('change_email_form_email_field'); 
                              if (page.email && field) { 
                                 field.value = page.email; 
                              } 
                           } 
                        }
         });
      }
   }
}
page.createChangePasswordForm = function page_createChangePasswordForm(target) 
{
   target = $(target);
   var user = page.getCookie('user');

   if (!user) {
      alert("Username cookie is missing; please log in again to re-set it.");
   }

   if (user && target && target.innerHTML == "") {
      target.innerHTML = 
      "<form method=\"POST\" id=\"change_password_form\" name=\"change_password_form\" class=\"form_box\" action=\"" + page.secureLoginURL + "\" target=\"change_password_form_secure_frame\" accept-charset=\"UTF-8\">" +
      "<a class=\"x_toggle\" href=\"javascript:void(null);\" onclick=\"page.toggleForm('change_password_form',1); return false;\" style=\"float:right\">X</a>" +
      "<br style=\"clear: both\">" +
      "<div id=\"change_password_form_message\"></div>" +
      "<div id=\"change_password_form_contents\">" + 
      "<input type=hidden name=cmd value=\"changepass\">" +
        "<input type=hidden name=\"continue_hostname\" value=\"" + ((document.location.hostname) ? document.location.hostname : "www.streetprices.com") + "\">" +
      "<input type=hidden name=user value=\"" + user + "\">" +
      "<label class=\"tabular\" for=\"change_password_form_pass_field\" style=\"font-weight: bold; white-space: nowrap;\">current password</label> <input class=\"tabular\" id=\"change_password_form_pass_field\" type=password name=pass size=20><br>" +
      "<label class=\"tabular\" for=\"change_password_form_newpass_field_1\" style=\"font-weight: bold; white-space: nowrap;\">new password</label> <input class=\"tabular\" id=\"change_password_form_newpass_field_1\" type=password name=newpass1 size=20 onBlur=\"page.checkPassword($F('change_password_form_newpass_field_1'),$F('change_password_form_newpass_field_2'),$('change_password_form_message'));\"><br>" +
      "<label class=\"tabular\" for=\"change_password_form_newpass_field_2\" style=\"font-weight: bold; white-space: nowrap;\">confirm password</label> <input class=\"tabular\" id=\"change_password_form_newpass_field_2\" type=password name=newpass2 size=20 onBlur=\"page.checkPassword($F('change_password_form_newpass_field_1'),$F('change_password_form_newpass_field_2'),$('change_password_form_message'));\"><br>" +
      "<label class=\"tabular\"</label><input class=\"tabular\" type=submit value=\"change\">" +
      "</div>" +
      "<iframe id=\"change_password_form_secure_frame\" name=\"change_password_form_secure_frame\" style=\"width:1px; height:1px; border:0\" src=\"about:blank\"></iframe>" +
      "</form>";
   }
}

page.form_info = {
   'login_form': {
      focus: (page.getCookie && page.getCookie('user')) ? 'login_form_password_field' : 'login_form_username_field',
      create: page.createLoginForm,
      reset: function(form) {
           if ($('login_form_username_section')) {
              $('login_form_username_section').show();
           }
           if ($('login_form_contents')) {
              $('login_form_contents').show();
           }
           if ($('reset_password_form_contents')) {
              $('reset_password_form_contents').hide();
           }
           if ($('login_form_message_div')) {
              $('login_form_message_div').innerHTML = "";
           }
           if (form) {
              form.style.position = 'absolute';
              form.style.top = '30px';
              form.style.right = '10px';
           }
        }
   },
   'create_account_form': {
      focus: "create_account_form_username_field",
      create: page.createAccountForm,
      reset: function(form) {
                   page.refreshTuring('create_account_form_rand_field','create_account_form_turing_img');
             }
   },
   'product_review_form': {
      focus: "product_review_form_rating_field",
      create: page.createReviewForm
   },
   'price_alert_form': {
      focus: (page.getCookie && page.getCookie('user')) ? 'price_alert_form_price_field' : 'price_alert_form_email_field'
   },
   'exit_feedback_form': {
      focus: 'exit_feedback_form_feedback_field',
      create: page.createExitFeedbackForm
   },
   'flag_feedback_form': {
      focus: 'flag_feedback_form_problem_field_specs',
      create: page.createFlagFeedbackForm,
      reset: function(form) {
	        var contents = $('flag_feedback_form_contents');
		if (contents) { contents.show(); }
	        var message = $('flag_feedback_form_message_div');
		if (message) { message.innerHTML = ''; }
             }
   },
   'feedback_form': {
      focus: 'feedback_form_feedback_field',
      create: page.createFeedbackForm
   },
   'zip_code_form': {
      focus: 'zip_code_form_zip_field',
      create: page.createZipcodeForm
   },
   'change_email_form': {
      focus: 'change_email_form_email_field',
      create: page.createChangeEmailForm,
      reset: function(form) {
         var div = $('change_email_form_contents');
         if (div) { div.show(); }

         div = $('change_email_form_message');
         if (div) { div.innerHTML = ""; }
      }
   },
   'change_password_form': {
      focus: 'change_password_form_pass_field',
      create: page.createChangePasswordForm,
      reset: function(form) {
         var div = $('change_password_form_contents');
         if (div) { div.show(); }

         div = $('change_password_form_message');
         if (div) { div.innerHTML = ""; }

         var input = $('change_password_form_pass_field');
         if (input) { input.value = ""; }
             input = $('change_password_form_newpass_field_1');
         if (input) { input.value = ""; }
             input = $('change_password_form_newpass_field_2');
         if (input) { input.value = ""; }
      }
   },
   'shipping_form': {
      focus: 'shipping_form_shipping_method_field'
   }
};

page.toggleForm = function page_toggleForm(form_id,greyOut)
{
   if (form_id) {
      var form_container = $(form_id + '_container');

      // Get a handle to the form, creating it if necessary
      var form = $(form_id);
      if (!form) {
         if (page.form_info[form_id] && page.form_info[form_id].create) {
            if (form_container) {
               form_container.style.display = 'none';
               page.form_info[form_id].create(form_container);
               form = $(form_id);
            }
         }
      }

      if (form && form_container && form_container.style) {
         if (form.id != "login_form" && 
             form.id != "create_account_form" &&
             form.id != "zip_code_form" &&
             form.id != "exit_feedback_form" &&
             form.id != "feedback_form" &&
             form.id != "flag_feedback_form" &&
             form.id != "shipping_form" &&
             page.userNeedsToLogIn()) {
            // Looks like we know them, but they're not logged in.
            // Make them log in first.
            page.forceLogin(form);
         } else {
            // Show or hide the form
            var visible = 0;
            if (form_container.visible()) {
               page.hideForm(form_container);
            } else {
              // Show form
      
              if (page.form_info[form_id] && page.form_info[form_id].reset)
              {
                 page.form_info[form_id].reset(form);
              }
      
               var focus = ((page.form_info[form_id]) ? 
	                     page.form_info[form_id].focus : 
			     undefined);
               page.showForm(form_container, focus, greyOut);
               visible = 1;
            }
      
            if (page.form_info[form_id] && page.form_info[form_id].onComplete)
            {
               page.form_info[form_id].onComplete(form, visible);
            }
         }
      }
   }
   return false;
}


page.cullEnterKey = function page_cullEnterKey(e)
{
   var key = (window.event) ? window.event.keyCode : e.which;
   if (key == 13 || key == 10) {
      return false;
   }
   return true;
}

page.removeZipFromCookie = function page_removeZipFromCookie(id)
{
  var node = document.getElementById(id);
  if(node)
  {
    page.deleteCookie('zip', { domain: page.cookieDomain });
    page.setCookie('nation', 840, { domain: page.cookieDomain });
    page.updatePrices();
    var link = $('zip_code_form_link');
    if (link) { link.hide(); }
    link = $('zip_code_form_link_body');
    if (link) { link.innerHTML = '95054'; }
  }
}

page.submitZipToCookie = function page_submitZipToCookie(id,reload_tabs)
{
  var node = $(id);

  if(node && $F(node))
  {
    var zip = $F(node);

    page.setCookie('zip', zip, { domain: page.cookieDomain });  // setCookie always escapes the values
    page.setCookie('nation', 840, { domain: page.cookieDomain });
    if (reload_tabs)
    {
      page.updatePrices();

     var input_field = $('zip_code_form_zip_field');
     if (input_field) { input_field.value = zip; }

     var link = $('zip_code_form_link');  // in header
     if (link) { link.innerHTML = zip; link.show(); }
     link = $('zip_code_form_link_body');
     if (link) { link.innerHTML = zip; }
   }
   else
   {
     $('zip_code_form').innerHTML = "Loading...";
     window.location.reload(true);
   }
  }
  else 
  {
     $('zip_code_form').innerHTML = "Loading...";
     page.deleteCookie('zip', { domain: page.cookieDomain });
     window.location.reload(true);
  }
}


page.icon_on = {
   star:'/pic/paw_red_trans_20x20.gif',
   pawprint:'/pic/paw_red_trans_20x20.gif',
   wishlist:'/pic/wishlist_icon_red_20x20.gif',
   pricealert:'/pic/email_icon_blue_trans_20x20.gif',
   tags:'/pic/list_icon_yellow_trans_20x20.gif'
};
page.icon_off = {
   star:'/pic/paw_white_trans_20x20.gif',
   pawprint:'/pic/paw_white_trans_20x20.gif',
   wishlist:'/pic/wishlist_icon.gif',
   pricealert:'/pic/email_icon_white_trans_20x20.gif',
   tags:'/pic/list_icon_white_trans_20x20.gif'
};
page.showIcon = function page_showIcon(what, spid)
{
   if (page.icon_on[what]) {
      var icon = $('spid_' + spid + '_' + what + '_icon');
      if (icon) {
         try {
            icon.parentNode.style.opacity = 1.0;
            icon.parentNode.style.filter = 'alpha(opacity=100)';
            icon.src=page.icon_on[what];
            icon.blur();
         } catch(e) {}
      }
   }
}
page.hideIcon = function page_hideIcon(what, spid)
{
   if (page.icon_off[what]) {
      var icon = $('spid_' + spid + '_' + what + '_icon');
      if (icon) {
         try {
            icon.parentNode.style.opacity = '';
            icon.parentNode.style.filter = '';
            icon.src=page.icon_off[what];
            icon.blur();
         } catch(e) {}
      }
   }
}

page.finishDeletePriceAlert = function page_finishDeletePriceAlert(req,spid,id) 
{
   if (spid && id) {

      // delete it from the local page.products
      var pricealerts = page.products[spid].pricealerts;
      if (pricealerts) {
         var i=0;
         var found = 0;
         for (i=0; i< pricealerts.length && !found; i++) {
            if (pricealerts[i].id && pricealerts[i].id == id) {
               found=1;
               pricealerts.splice(i, 1);
            }
         }
      }

      // remove this price alert from the UI
      var node = $('pricealert_' + id);
      if (node) {
         if (node.remove) { node.remove();                     }
         else             { node.parentNode.removeChild(node); }
      }
      node = $('pricealert_' + id + '_secondary');
      if (node) {
         if (node.remove) { node.remove();                     }
         else             { node.parentNode.removeChild(node); }
      }

      // if it was the last one, do Special Things
      if (pricealerts.length == 0) {
         if (dashboard) {
            page.hideIcon('pricealert',spid);
            dashboard.hidePriceAlertArea('pricealert',spid);
         } else { 
            page.unColorPricealert($('pricealert_chunk_' + spid), spid);
         }
      }
   }
}
page.deletePriceAlertFailure = function page_deletePriceAlertFailure(req)
{
   if (req && req.responseText) {
      alert(req.responseText);
   }
}

page.deletePriceAlert = function page_deletePriceAlert(spid,id)
{
   // remove it from the database and pref system
   new Ajax.Request('/ajax/delete_pricealert.cgi', {
      method: 'post', 
      postBody: "id=" + id + "&spid=" + spid,
      onSuccess: new Function("req", "page.finishDeletePriceAlert(req,'" + spid + "','" + id + "')"),
      onFailure: page.deletePriceAlertFailure
      }
      );
}


// add/edit price alert
page.finishSubmitPriceAlert = function page_finishSubmitPriceAlert(req,spid,id) 
{
   // Replace with formatted pricealert
   // BUG: this also resets stickynotes
   if (dashboard && dashboard.updatePriceAlerts) {
      // it's a myStreetprices page
      dashboard.updatePriceAlerts(spid);
   } else {
      if (page.getCookie && page.getCookie('SID') && (spid == page.currentSpid)) {
         page.initItems();
      } else {
         $('price_alert_form_pricealerts_container').innerHTML="<p style=\"color: green; white-space: normal\">Got it!  We'll email you when a seller meets your price.</p>";
	 if (!page.getCookie || !page.getCookie('SID')) { $('price_alert_form_pricealerts_container').innerHTML+="<p style=\"white-space: normal\">Did you know you can track your future price alerts by creating an account?<br>  Just click &quot;create account&quot; at the top of this page.</p>"; }
	 $('price_alert_form_pricealerts_container').show();
         if (page.products[spid] && 
             page.products[spid].pricealerts &&
             page.products[spid].pricealerts.length > 0) {
            page.colorPricealert($('pricealert_chunk_' + spid));
         } else {
            page.unColorPricealert($('pricealert_chunk_' + spid), spid);
         }
      }
     // We successfully submitted the form -- hide it.
      $(id + '_button').disabled = false;
      page.toggleForm(id,0);
   }
}
page.submitPriceAlertFailure = function page_submitPriceAlertFailure(req,id) {
   if (req && req.responseText) {
      alert("Hmm, I couldn't save your price alert.  Check the form for more details.");
      var button = $(id + '_button');
      if (button) { button.disabled = false; }
   }
}

page.submitPriceAlert = function page_submitPriceAlert(id) {
   var form = $(id);
   if (form) {
      var button = $(id + '_button');
      if (button) { button.disabled = true; }
      var response_div = $(id + '_response');
      if (response_div) { response_div.innerHTML = ''; }

      // save it in the DB
      new Ajax.Updater(id + '_response','/ajax/add_pricealert.cgi', { 
            method: "post",
            postBody: Form.serialize(form),
            onSuccess: new Function("req","page.finishSubmitPriceAlert(req,$F('" + id + "_spid_field'),'" + id  + "');"),
            onFailure: new Function("req","page.submitPriceAlertFailure(req,'" + id + "');")
         });

      return false;
   }
   return true;
}

page.updatePrices = function page_updatePrices()
{
   var i = 0;

   // do the currrent tab first
   for (i in page.spids) {
      if (page.spids[i] == page.currentSpid)
      {
         page.updateTabPrices(i);
      }
   }
   // ...then all the other tabs
   for (i in page.spids) {
      if (page.spids[i] != page.currentSpid)
      {
         page.updateTabPrices(i);
      }
   }
}

page.getCategoryTree = function page_getCategoryTree()
{
   var container = 'category_tree'
   var url = '/a/category_tree.cgi';
   new Ajax.Updater(container, url, { method: 'get' });
}

page.updateTabPrices = function page_updateTabPrices(i)
{
   if (i == undefined) { i=0; }
   page.iteminfo[i] = undefined;

   var container = 'tab_table_wrapper_' + i;
   var url = '/a/wheretobuytable.cgi';
   new Ajax.Updater(container, url, { 
                    method: 'get',
                    parameters: 'pk_spid=' + encodeURIComponent(page.spids[i]) + 
                   '&pk_flavor=' + encodeURIComponent(page.flavors[i]) + 
                   '&i_tab=' + i,
                   evalScripts: true,
                   onComplete: function(req) { setTimeout('page.changeSort(page.currentPriceType, undefined)', 20); } 
               });
}


// Comparison functions for use on pricing page
page.cmpDefault = function page_cmpDefault(a,b)
{
   return (a.i < b.i);
}
page.cmpBasePrice = function page_cmpBasePrice(a,b)
{
   return (a.basePriceUSD - b.basePriceUSD);
}
page.cmpGroundPrice = function page_cmpGroundPrice(a,b)
{
   if (a.hasGroundInfo != b.hasGroundInfo) { 
      return (b.hasGroundInfo - a.hasGroundInfo);
   }
   if (a.hasTaxInfo != b.hasTaxInfo) { 
      return (b.hasTaxInfo - a.hasTaxInfo);
   }
   if (a.hasGroundInfo) {
      var a_price = a.groundPrice;
      var b_price = b.groundPrice;
      return (a_price - b_price);
   }
   else {
      return page.cmpBasePrice(a,b);
   }
}
page.cmpTwoDayPrice = function page_cmpTwoDayPrice(a,b)
{
   if (a.hasTwoDayInfo != b.hasTwoDayInfo) { 
      return (b.hasTwoDayInfo - a.hasTwoDayInfo);
   }
   if (a.hasTaxInfo != b.hasTaxInfo) { 
      return (b.hasTaxInfo - a.hasTaxInfo);
   }
   if (a.hasTwoDayInfo) {
      var a_price = a.twoDayPrice;
      var b_price = b.twoDayPrice;
      return (a_price - b_price);
   }
   else {
      return page.cmpBasePrice(a,b);
   }
}
page.cmpOvernightPrice = function page_cmpOvernightPrice(a,b)
{
   if (a.hasOvernightInfo != b.hasOvernightInfo) { 
      return (b.hasOvernightInfo - a.hasOvernightInfo);
   }
   if (a.hasTaxInfo != b.hasTaxInfo) { 
      return (b.hasTaxInfo - a.hasTaxInfo);
   }
   if (a.hasOvernightInfo) {
      var a_price = a.overnightPrice;
      var b_price = b.overnightPrice;
      return (a_price - b_price);
   }
   else {
      return page.cmpBasePrice(a,b);
   }
}
page.cmpRating = function page_cmpRating(a,b)
{
   if (a.rating.length || b.rating.length) {

      // no grade?  go to the bottom
      if (!a.rating.length) { return  1; }
      if (!b.rating.length) { return -1; }
   
      // compare the letter grade (without modifiers)
      if (a.rating.substring(0,1) < b.rating.substring(0,1)) { return -1; }
      if (a.rating.substring(0,1) > b.rating.substring(0,1)) { return  1; }
   
      // letter matches?  compare modifiers
      var lmod = 0;
      if (a.rating.substring(1,2) == "+") { lmod++; }
      if (a.rating.substring(1,2) == "-") { lmod--; }
      var rmod = 0;
      if (b.rating.substring(1,2) == "+") { rmod++; }
      if (b.rating.substring(1,2) == "-") { rmod--; }
   
      if (lmod<rmod){ return  1; }
      if (lmod>rmod){ return -1; }
   }

   return page.cmpGroundPrice(a,b);
}
page.cmpInStock = function page_cmpInStock(a,b)
{
   if (a.inventory < b.inventory) { return 1; }
   if (a.inventory > b.inventory) { return -1; }

   return page.cmpGroundPrice(a,b);
}



page.cmp_function = {
 "default": page.cmpDefault,
 "base": page.cmpBasePrice,
 "ground": page.cmpGroundPrice,
 "2day": page.cmpTwoDayPrice,
 "overnight": page.cmpOvernightPrice,
 "rating": page.cmpRating,
 "stock": page.cmpInStock
};
page.changeSort = function page_changeSort(sort_type, tab)
{
   if (page.cmp_function[ sort_type ])
   {
      if (tab == undefined)
      {
         // sort the current tab only
         var i = 0;
         var found = 0;
         for (i in page.spids) {
            if (page.spids[i] == page.currentSpid)
            {
               found = 1;
               page.changeSort(sort_type,i);
               break;
            }
            if (!found) { page.changeSort(sort_type,0); }
         }
      }
      else if (page.iteminfo[tab]) 
      {
         // sort a single tab

         // first, sort the model of the data
         page.iteminfo[tab].sort( page.cmp_function[sort_type] );


         // second, make the HTML reflect the model
         var newOrder = new Array;
         var i=0;
         for (i=0; i< page.iteminfo[tab].length; i++)
         {
            if (page.iteminfo[tab][i])
            {
               newOrder.push( page.iteminfo[tab][i].row_id );
            }
         }
         page.reorder(newOrder, "sellers_" + tab );


         // third, tell the user what we sorted by
         var old_sort = page.currentSort;
         page.currentSort = sort_type; 
         var old_price_type = page.currentPriceType ? 
                          page.currentPriceType : 
                          "ground";
         if (sort_type == 'base' || 
             sort_type == '2day'      || 
             sort_type == 'ground'     || 
             sort_type == 'overnight')
         {
            page.currentPriceType = sort_type;
         }

         var shipping_link = $('shipping_link');
         if (shipping_link)
         {
            shipping_link.innerHTML = 
               (page.currentPriceType == "base") ?
                   "base price, without shipping" :
                    page.currentPriceType + " shipping";
         }
         
   
         var old_sort_link = $('sort_link_' + old_sort + '_' + tab);
         if (old_sort_link) { old_sort_link.removeClassName("selected_sort_option"); }
         else if (old_sort == 'base' || 
                  old_sort == 'ground' || 
                  old_sort == '2day' || 
                  old_sort == 'overnight')
         {
            old_sort_link = $('sort_link_price_' + tab);
            if (old_sort_link) { old_sort_link.removeClassName("selected_sort_option"); }
         }
         
         var sort_link = $('sort_link_' + sort_type + '_' + tab);
         if (sort_link) { 
            sort_link.blur(); 
            sort_link.addClassName("selected_sort_option");
         }
         else if (sort_type == 'base' || 
              sort_type == 'ground' || 
              sort_type == '2day' || 
              sort_type == 'overnight')
         {
            sort_link = $('sort_link_price_' + tab);
            if (sort_link) {
               sort_link.innerHTML = sort_type + '  price';
               sort_link.blur(); 
               sort_link.addClassName("selected_sort_option");
            }
         }
      
         // Finally, if we're sorting by price, bring the totals up to date.
         if (sort_type == 'base' || 
              sort_type == 'ground' || 
              sort_type == '2day' || 
              sort_type == 'overnight')
         {
            // We only sort one tab at a time, so sort it even if 
            // page.currentSort hasn't changed -- this may be a different tab.
            for (i=0; i < page.iteminfo[tab].length; i++)
            {
               var iteminfo = page.iteminfo[tab][i];
               var span = $('price_' + tab + '_' + iteminfo.i);
               if (span)
               {
                  // calculate the new "total price"

		  var new_formatted_price = "<a class=\"price\" href=\"" + iteminfo.url + "\">" + iteminfo.currency + iteminfo.basePrice + "</a><span style=\"font-size: x-small; white-space: nowrap;\">";

                  if (page.currentPriceType == '2day')
                  {
                     new_formatted_price +=
                    ((iteminfo.hasTwoDayInfo) ?
		       ((iteminfo.twoDayShippingCost == 0) ?
		       "<br><span style=\"color: green\">FREE shipping</span>" :
		    "<br>plus " + iteminfo.currency + iteminfo.twoDayShippingCost + " shipping")
		    :
		    "<br>plus shipping"
		    );
                  }
                  else if (page.currentPriceType == 'overnight')
                  {
                     new_formatted_price +=
                    ((iteminfo.hasOvernightInfo) ?
		       ((iteminfo.overnightShippingCost == 0) ?
		       "<br><span style=\"color: green\">FREE shipping</span>" :
		    "<br>plus " + iteminfo.currency + iteminfo.overnightShippingCost + " shipping")
		    :
		    "<br>plus shipping"
		    );
                  }
                  else
                  {
                     new_formatted_price +=
                    ((iteminfo.hasGroundInfo) ?
		       ((iteminfo.groundShippingCost == 0) ?
		       "<br><span style=\"color: green\">FREE shipping</span>" :
		    "<br>plus " + iteminfo.currency + iteminfo.groundShippingCost + " shipping")
		    :
		    "<br>plus shipping"
		    );
                  }
                  new_formatted_price += 
		     ((iteminfo.hasTaxInfo) ?  
		         ((iteminfo.tax == 0) ? 
			 "<br><span style=\"color: green\">FREE tax</span>" : 
			 "<br>plus " + iteminfo.currency + iteminfo.tax + " tax") :
		     "<br>plus tax") +
		     "</span>";
		  span.innerHTML = new_formatted_price;
               }
            }
         }
      } else {
//      alert("no iteminfo for tab " + tab);
      }
   }
   return false;
}


// functions for product search results
page.disableButtons = function page_disableButtons() 
{
   if ($('actions_selectbox_top')) {
      $('actions_selectbox_top').disabled = true;
      $('actions_selectbox_bottom').disabled = true;
      $('compare_button_top').disabled = true;
      $('compare_button_bottom').disabled = true;
      $('wishlist_button_top').disabled = true;
      $('wishlist_button_bottom').disabled = true;
   }
}

page.enableButtons = function page_enableButtons() 
{
   if ($('actions_selectbox_top')) {
      $('actions_selectbox_top').disabled = false;
      $('actions_selectbox_bottom').disabled = false;
      $('compare_button_top').disabled = false;
      $('compare_button_bottom').disabled = false;
      $('wishlist_button_top').disabled = false;
      $('wishlist_button_bottom').disabled = false;
   }
}

page.disableButtonsIfNoneChecked = function page_disableButtonsIfNoneChecked() 
{
   for (var i in page.products) {
      if (page.products[i].checked) { return 0; }
   }
   page.disableButtons();
   return 1;
}
page.checkProduct = function page_checkProduct(product_id, checkbox) 
{
   page.products[product_id].checked = checkbox.checked;

   var container;
   if ((container = $('container_' + product_id))) {
      container.style.backgroundColor = (checkbox.checked) ? "#FFFFCC" : "#FFFFFF";
   }
   if ((container = $('grid_' + product_id))) {
      container.style.backgroundColor = (checkbox.checked) ? "#FFFFCC" : "#FFFFFF";
   }

   // keep grid/normal checkboxes in sync
   if (checkbox.id.match(/grid/)) {
      var box = $('compare_' + product_id);
      if (box) { box.checked = checkbox.checked; }
   } else {
      var box = $('compare_grid_' + product_id);
      if (box) { box.checked = checkbox.checked; }
   }

   if (checkbox.checked == false) {
      page.disableButtonsIfNoneChecked();
   } else {
      page.enableButtons();
   }
}
page.checkAll = function page_checkAll() 
{
   for (var i in page.products) {
      var node = $('compare_' + i);
      if (!node) { node = $('compare_grid_' + i); }
      if (node) {
         node.checked = true;
         page.checkProduct(i, node);
      }
   }
}
page.checkNone = function page_checkNone() 
{
   for (var i in page.products) {
      var node = $('compare_' + i);
      if (!node) { node = $('compare_grid_' + i); }
      if (node) {
         node.checked = false;
         page.checkProduct(i, node);
      }
   }
}
page.showOnlySavedItems = function page_showOnlySavedItems() 
{
   for (var i in page.products) {
      var node = $('container_' + i);
      if (node && !page.products[i].star) { node.hide(); }

          node = $('grid_' + i);
      if (node && !page.products[i].star) { node.hide(); }
   }
   var link = $('show_saved_link_top');
   if (link) { link.hide(); }
       link = $('show_saved_link_bottom');
   if (link) { link.hide(); }
       link = $('show_all_link_top');
   if (link) { link.show(); }
       link = $('show_all_link_bottom');
   if (link) { link.show(); }
}
page.showAllItems = function page_showAllItems() 
{
   for (var i in page.products) {
      var node = $('container_' + i);
      if (node) { node.show(); }

      node = $('grid_' + i);
      if (node) { node.show(); }
   }
   var link = $('show_saved_link_top');
   if (link) { link.show(); }
       link = $('show_saved_link_bottom');
   if (link) { link.show(); }
       link = $('show_all_link_top');
   if (link) { link.hide(); }
       link = $('show_all_link_bottom');
   if (link) { link.hide(); }
}

// star functions
// save the star to the server
page.addStar = function page_addStar(spid, show) 
{
   new Ajax.Request(page.prefURL,{
      method: 'post', 
      postBody: 'type=data&cmd=setkey&key=star&objtype=literal&val=1&grp=spid&id=' + spid, 
      onSuccess: (show) ? new Function("req", "page.showStar(" + spid + ");") : undefined });
}

// ...show the added star in the UI
// (we call this when the Ajax call returns success)
page.showStar = function page_showStar(spid) 
{
   if (page.products[spid]) {
      page.products[spid].star = 1;
   }

   var icon = $('star_' + spid);
   var span = $('star_chunk_' + spid);
   if (page.products[spid] && icon && span) {
      page.colorStar(span); span.blur();
   }
   else {
      var img = $('save_icon_' + spid);
      if (img) { img.src = page.icon_on['star']; img.parentNode.blur(); }
   }
}

// remove the star on the server
page.removeStar = function page_removeStar(spid,show) 
{
   new Ajax.Request(page.prefURL,{
      method: 'post', 
      postBody: 'type=data&cmd=setkey&key=star&grp=spid&id=' + spid, 
      onSuccess: (show) ? new Function("req", "page.hideStar(" + spid + ");") : undefined });
}
// ... and reflect the change in the UI
page.hideStar = function page_hideStar(spid) 
{
   if (page.products[spid]) {
      page.products[spid].star = 0;

      var icon = $('star_' + spid);
      if (icon) {
         icon.style.display = 'none';
         icon.blur();
      }
      var span = $('star_chunk_' + spid);
      if (span) { span.blur(); }
   }

   var img = $('save_icon_' + spid);
   if (img) { img.src=page.icon_off['star']; img.parentNode.blur(); }
}

// toggle the wishlist
page.toggleWishlist = function page_toggleWishlist(product_id) 
{
   if (page.products && page.products[product_id]) {
      if (page.products[product_id].wishlist) {
         return page.removeWishlist(product_id);
      } else {
         return page.addWishlist(product_id,1);
      }
   }
   return 0;
}
// toggle the star (and the server setting, and the local copy of the list)
page.toggleStar = function page_toggleStar(product_id) 
{
   if (page.products && page.products[product_id]) {
      if (page.products[product_id].star) {
         return page.removeStar(product_id,1);
      } else {
         return page.addStar(product_id,1);
      }
   }
   return 0;
}

// get the starred objects from the _local_ copy of the list
// (don't make a server call)
// (this is used in search results, to check boxes next to all starred 
//  products... so we always want to use the local copy, which reflects
//  what the UI is showing)
page.getStarred = function page_getStarred() 
{
   var starred = new Array;
   for (var i in page.products) {
      if (page.products[i].star) {
         starred.push(i);
      }
   }
   return starred;
}


page.textToHTML = function page_textToHTML(text) 
{
   if (text.replace) {
      text = text.replace(/^\s+/, '');
      text = text.replace(/\s+$/, '');
      text = text.replace(/[ \t]+\n/g, '\n');
      text = text.replace(/\n/g, '<br>');
   }
   return text;
}
page.htmlToText = function page_htmlToText(html) 
{
   if (html.replace) {
      html = html.replace(/<br>/g, '\n');
   }
   return html;
}

page.createStickynote = function page_createStickynote(type,id,default_text,args)
{
   if (!args) { args = new Object; }
   var stickynote_div = 'stickynote_' + type + '_' + id;

   if ($(stickynote_div) && !page.editors[stickynote_div])
   {
      var stickynote_text_div = stickynote_div + '_text';
      var stickynote_outer_div = stickynote_div + '_outer';
      var stickynote_min_div = stickynote_div + '_minimized';
   
      // set it up for in-place editing
      if (page.userNeedsToLogIn()) {
   
         default_text = "You need to log in before saving a note.";
         var listener = new Function("evt", "page.forceLogin('" + stickynote_div + "');");
         listener = listener.bindAsEventListener( $(stickynote_text_div) );
         Event.observe($(stickynote_text_div), 'click', listener);
   
      } else {
         // submitOnBlur doesn't work with cancelControl
         // this function will 'post' by default; no need to set it explicitly
         var editor = new Ajax.InPlaceEditor(stickynote_text_div, page.prefURL,
            {submitOnBlur: true, 
             cancelControl: false,
	     okText: "save note",
             onEnterHover: function(e) { return false; },
             onLeaveHover: function(e) { return false; },
             highlightColor: '#FFFF99', 
             highlightEndColor: '#FFFF99', 
             callback: new Function("form", "value", "return 'type=data&cmd=setkey&grp=" + encodeURIComponent(type) + "&id=" + encodeURIComponent(id) + "&key=note&objtype=literal" + "&val=' + encodeURIComponent(value);"),
             rows: args['rows'] ? args['rows'] : 2, 
             cols: args['cols'] ? args['cols'] : 20, 

             htmlResponse: true,
             onEnterEditMode: new Function("req", "var e = page.editors['" + stickynote_div + "']; if (e) { var text = e.getText(); var div = $('" + stickynote_text_div + "'); if (div && (text == '" + default_text.substitute(/'/,"\\'") + "')) { div.innerHTML = ''; } else { e.element.innerHTML = page.htmlToText(text); } }"),

             onComplete: new Function("response", "elem", 
                "var div = document.getElementById('" + stickynote_text_div + "');\
                if (div && response && response.responseText && response.responseText.match(/\\S/) && (response.status >= 200 && response.status < 300))\
                {\
                   div.innerHTML = page.textToHTML(response.responseText);\
                } else if (div) {\
                   div.innerHTML = \"" + default_text + "\";\
                }")

            });
         page.editors[stickynote_div] = editor;
      }
   
   
   
      if (args['initialize'])
      {
         // initialize it
         if (args['note_text'] != undefined) {
             var text = page.textToHTML(args['note_text']);

             if (text) {
                $(stickynote_text_div).innerHTML = text;
                $(stickynote_outer_div).style.display='';
                $(stickynote_min_div).style.display='none';
             } else {
                $(stickynote_text_div).innerHTML = default_text;
                $(stickynote_outer_div).style.display='none';
                $(stickynote_min_div).style.display='';
             }
          } 
          else 
          {
   
            // one note: the Updater ALWAYS updates the div with the response
            // onSuccess and onFailure let you do stuff BEFORE the update
            // onComplete lets you do stuff AFTER the update
            // So... if you want default text upon failure, you need to 
            // call onComplete and NOT onFailure
            new Ajax.Updater(stickynote_text_div, page.prefURL, 
               { method: "get",
                 parameters:'type=data&cmd=getkey&grp=' + encodeURIComponent(type) + '&id=' + encodeURIComponent(id) + '&key=note&objtype=literal', 
                 onComplete: 
               (args['force_open'] ?
                  new Function("response", "\
                   $('" + stickynote_outer_div + "').style.display='';\
                   $('" + stickynote_min_div + "').style.display='none';\
                   var div = $('" + stickynote_text_div + "');\
                   if (div && response && response.responseText && response.responseText.match(/\\S/) && (response.status >= 200 && response.status < 300)){\
                      var text = page.textToHTML(response.responseText);\
                      div.innerHTML = text;\
                   } else if (div) {\
                      div.innerHTML = \"" + default_text + "\";\
               }\
               ")
            :
                new Function("response", 
                "var div = document.getElementById('" + stickynote_text_div + "');\
                if (div && response && response.responseText && response.responseText.match(/\\S/) && (response.status >= 200 && response.status < 300)){\
                   var text = page.textToHTML(response.responseText);\
                   div.innerHTML = text;\
                   $('" +stickynote_outer_div+ "').style.display='';\
                   $('" +stickynote_min_div+ "').style.display='none';\
                } else if (div) {\
                   div.innerHTML = \"" + default_text + "\";\
                   $('" +stickynote_outer_div+ "').style.display='none';\
                   $('" +stickynote_min_div+ "').style.display='';\
                }")
                )
         });
      }
   }
   else
   {
      $(stickynote_text_div).innerHTML = default_text;
      if (args['force_open']) {
         $(stickynote_outer_div).style.display='';
         $(stickynote_min_div).style.display='none';
	 // page.editors[stickynote_div].enterEditMode('click');
      } else {
         $(stickynote_outer_div).style.display = 'none';
      }
   }

   // make it moveable, if desired
   if (args['draggable'])
   {
     new Draggable(stickynote_outer_div,{});
   }

   }
   return page.editors[stickynote_div];
}


page.initStickynote = function page_initStickynote(result)
{
   if (result.note && result.id) {
      if (!page.editors[stickynote_id]) {
         var parts = result.id.split(/_/);
         page.createStickynote(parts[0],parts[1], "Click to save a searchable note.", {rows: 2, cols: 20, force_open: 1, draggable: 0});
      }

      var div = $('stickynote_' + result.id + '_text');

      var text = page.textToHTML(result.note);
       div.innerHTML = text;

      var stickynote_id = 'stickynote_' + result.id;
      var toggle = $(stickynote_id + '_minimized');
      if (toggle) {
         toggle.style.display = 'none';
      }
      var outer = $(stickynote_id + '_outer');
      if (outer) {
         outer.style.display = '';
      }
   }
}

//-----------------------------------------------------------------------------
// Tips widget 
//-----------------------------------------------------------------------------


page.tips = [
   "<p style=\"margin-top: 0\"><b>Search by specs</b> with the <a href=\"/x/pfinder.cgi?pk_cat=1\">Digital Camera Finder</a>.</p>",

   "<p>You can <b>read reviews of any seller</b> by clicking on their letter grade.  (You can also write reviews there, to help out other users.)</p>",

   "<p>Compare prices from anywhere! Send <b>StreetPricesBot</b> an <b>AIM</b> with the name of your product.</p>",

   "<p><b>Search by part number</b> to find an exact match quickly.</p>",

   "<p>Our <b>common-sense product pages</b> let you see all of a digital camera's kits on one page.</p>",

   "<p><b>Stickynotes</b> let you keep your own secret notes on an item.  They'll even show up in your searches!</p>",

   "<p>We <b>graph prices</b> on every item.</p>",

   "<p>Click on the price graph to get <b>more price history</b>.</p>",

   "<p>We search <b>over 100 sellers</b> to help you find the best price on <b>hundreds of thousands of items</b>.</p>",

   "<p>Our <b>accurate product specs</b> are made in the USA by our dedicated in-house staff.</p>",

   "<p>Waiting until it's cheap?  Set a <b>price alert</b> on any item, and we'll tell you when it hits your price.</p>"

];

page.tipsLinkString = function page_tipsLinkString(className)
{
   return "<a id=\"motd_link\"" + (className ? " class=" + className : "") + " href=\"javascript:void(null);\" onclick=\"$('motd').style.display = ''; return false;\">show message of the day</a>";
}
page.tipsWidgetString = function page_tipsWidgetString(className)
{
   page.current_tip = Math.floor(Math.random() * (page.tips.length));

   return " <div id=\"motd\"" + (className ? " class=" + className : "") + ">" +
      "<a class=\"x_toggle\" style=\"font-size: x-small; color: black; float: right;\" href=\"\" onclick=\"$('motd').style.display = 'none'; return false;\">X</a>" +
      "<div id=\"tip_arrows\" style=\"text-align: center;\">" +
      "  <a style=\"text-decoration: none;\" href=\"javascript:void(null);\" onclick=\"page.lastTip();\">&larr;</a>" +
      "  <a style=\"text-decoration: none;\" href=\"javascript:void(null);\" onclick=\"page.nextTip();\">&rarr;</a>" +
      "</div>" +
      "<img style=\"float: left; margin-right: 6px;\" src=\"/pic/paw_black_transparent_20x20.gif\">" +
      "<span id=\"motd_message\">" + 
      page.tips[ page.current_tip ] +
      "</span>" +
   "</div>";
}

page.nextTip = function page_nextTip() {

   // this.blur() isn't working -- do the next best thing
   var search_query = $('search_query');
   if (search_query) { search_query.focus(); }

   var div = $('motd_message');
   if (div) {
      page.current_tip = (page.current_tip + 1) % page.tips.length;
      div.innerHTML = page.tips[page.current_tip];
   }
}
page.lastTip = function page_lastTip() {

   // this.blur() isn't working -- do the next best thing
   var search_query = $('search_query');
   if (search_query) { search_query.focus(); }

   var div = $('motd_message');
   if (div) {
      page.current_tip = (page.current_tip + (page.tips.length-1)) % page.tips.length;
      div.innerHTML = page.tips[page.current_tip];
   }
}

page.letterGrade = function page_letterGrade(n) {
   if        (n >= 990000) {
      return "A<sup>+</sup>";
   } else if (n >= 930000) {
      return "A";
   } else if (n >= 900000) {
      return "A<sup>-</sup>";
   } else if (n >= 870000) {
      return "B<sup>+</sup>";
   } else if (n >= 830000) {
      return "B";
   } else if (n >= 800000) {
      return "B<sup>-</sup>";
   } else if (n >= 770000) {
      return "C<sup>+</sup>";
   } else if (n >= 730000) {
      return "C";
   } else if (n >= 700000) {
      return "C<sup>-</sup>";
   } else if (n >= 0) {
      return "F";
   }
   return "";
}

page.formatPriceAlert = function page_formatPriceAlert(spid,pricealert)
{
   if (pricealert && pricealert.price) {
      var grade = pricealert.rating ? page.letterGrade(pricealert.rating) : "";
      var b_show_generic_setting = (page.could_be_generic && 
                                     page.could_be_generic[spid] && 
                                     !pricealert.b_brandname);
      return "<div id=\"pricealert_" + pricealert.id + "\" style=\"padding-left: 30px;\">" +
             ((pricealert.state == 1) ? "<span class=\"price_alert_triggered\">" : "") +
             "<img src=\"/pic/alert_icon_" + 
             ((pricealert.state == 1) ? "gray" : "black") +
             "_20x20.gif\" height=20 width=20 class=\"icon\" style=\"margin-left: -30px; vertical-align: middle\" alt=\"\"> " +
             "<b>price alert</b>: " + 
             "<span class=\"price\">" + pricealert.price + "</span>" +
             "," +
             (grade ?
                "&nbsp;<span class=\"merchant_rating_small\">" +
                grade +
                "</span>" 
                :
                ""
             ) +
             ((pricealert.state == 1) ? "</span>" : "") +
             " <a style=\"font-size: x-small; margin-left: 10px;\" href=\"javascript:void(null);\" onclick=\"if(confirm('Remove this price alert?')) { javascript:page.deletePriceAlert('" + spid + "','" + pricealert.id + "'); } return false;\">delete</a>" + 
             ((pricealert.b_new || b_show_generic_setting) ? "<div style=\"padding-right: 30px; margin-top: -4px;\">" : "") +
             ((pricealert.b_new) ? " <span class=\"pricealert_cond\">new</span>" : "") +
             ((pricealert.b_new && b_show_generic_setting) ? ", " : "") +
             ((b_show_generic_setting) ?  " <span class=\"pricealert_cond\">generic&nbsp;ok</span>" : "") +
             ((pricealert.b_new || b_show_generic_setting) ? "</div>" : "") +
             "</div>";
   }
   return "";
}

// finish item initialization when the Ajax call returns
page.finishInitItems = function page_finishInitItems(t) 
{
   if (t && t.responseText) {
      var results = eval(t.responseText);  // this should be a JS array
      if (results.length) {
         for (var i=0; i<results.length; i++) {
            if (results[i].id) {
               page.initStickynote(results[i]);
               var result = results[i];
   
               var tmp = result.id.split('_');
               result.grp  = tmp[0];
               if (result.grp == "spid") {
                  result.spid = tmp[1];
                  page.products[ result.spid ] = result;
   
                  if (result.wishlist == 1) {
                     page.showIcon('wishlist',result.spid);
                  }
                  if (result.tags) {
                     page.showTags(result.spid);
                  }
                  if (result.star == 1) {
                     page.showStar(result.spid);
                  }
               }
            }
         }
      }
   }
   if (page.products[ page.currentSpid ].pricealerts && 
       page.products[ page.currentSpid ].pricealerts.length > 0) 
    {
      page.refreshPriceAlertForm( page.products[ page.currentSpid ]);
      page.colorPricealert($('pricealert_chunk_' + page.currentSpid));
   } else {
      page.unColorPricealert($('pricealert_chunk_' + page.currentSpid), page.currentSpid);
   }
}
page.refreshPriceAlertForm = function page_refreshPriceAlertForm(item)
{
   var container = $('price_alert_form_container');
   var pricealerts_container = $('price_alert_form_pricealerts_container');
   if (container && pricealerts_container) {
      if (item.pricealerts && item.pricealerts.length) {
         var html = "";
         for (var j=0; j<item.pricealerts.length; j++) {
            html += page.formatPriceAlert(item.spid,item.pricealerts[j]);
         }
   
         pricealerts_container.innerHTML = html;
	 pricealerts_container.show();
   
         $('price_alert_form_response').innerHTML = '';
      } else {
         pricealerts_container.hide();
      }
   }
}
// Kick off an Ajax request to initialize the page
// - checks page.spid, page.hier for the main pawprint/stickynote
// - checks page.products for the rest
//
page.initItems = function page_initItems() 
{
   if (page.hier) {
      new Ajax.Request(page.prefURL, {
         method: 'get', 
         parameters: 'type=data&cmd=get&key=star&key=note&key=tags&grp=hier&id=' + 
                      page.hier,
         onSuccess: page.finishInitItems });
   }
   if (page.products) {

      var spids = "";
      for (var i in page.products) {
        if (page.products[i].id) {
           if (spids) { spids += '&id='; }
           spids += page.products[i].id;
        }
      }

      if (spids) {
         new Ajax.Request(page.prefURL, {
            method: 'get', 
            parameters: 'type=data&cmd=get&key=star&key=note&key=tags&key=review&key=alert&key=pricealerts&key=wishlist'+
                        '&id=' + spids, 
            onSuccess: page.finishInitItems });
      }
   }
};

page.prefIdsToSpids = function page_prefIdsToSpids(ids)
{
   if (ids[0] && ids[0].match && ids[0].match(/^spid_/))  {
      var i=0;
      var spids = new Array;
      for (i=0; i<ids.length; i++) {
         if (ids[i].match && ids[i].match(/^spid_/) && ids[i].replace) {
            spids.push(ids[i].replace('spid_', ''));
         }
      }
      return spids;
   }
   return ids;
}
page.collectItemInfo = function page_collectItemInfo(spids,fields,onSuccess)
{
   if (spids.length && fields.length && onSuccess) {

     new Ajax.Request('/a/p',
        { method: "get",
          parameters: 'spid=' + spids.join('&spid=') + 
                      '&get=' + fields.join('&get='),
          onSuccess: onSuccess
        });
  }
}


page.addToTrash = function page_addToTrash(product_id) {
   if (product_id) {
      new Ajax.Request('/pref/',{method: 'post', postBody: 'type=list&namespace=trash&name=trash&grp=spid&cmd=set&id=' + product_id });
   }
}
page.addToRecentProducts = function page_addToRecentProducts(product_id) {
   if (product_id) {
      new Ajax.Request('/pref/',{method: 'post', postBody: 'type=list&namespace=history&name=spid&grp=spid&cmd=set&max=' + page.MAX_SPID_HISTORY + '&id=' + product_id });
   }
}
page.removeFromRecentProducts = function page_removeFromRecentProducts(product_id) {
   if (product_id) {
      page.addToTrash(product_id);
      new Ajax.Request('/pref/',{method: 'post', postBody: 'type=list&namespace=history&name=spid&grp=spid&cmd=del&id=' + product_id });
   }
}
page.finishRecentProducts = function page_finishRecentProducts(req) 
{
   var div = $('recent_products');
   if (!div) { div = $('recent_products_horizontal'); }
   if (req && req.responseText && div) {
      
      var items = eval(req.responseText);  // this should be a JS array

      if (items && items.length) {

         var b_horizontal = (div.id == 'recent_products_horizontal');
         var image_style = (b_horizontal) ? " style=\"float: left; margin-right: 4px\"" : "";

         var html = "";
         var i=0;
         for (i=0; i<items.length; i++) {

            var spid = items[i].id.replace('spid_','');

            if (!page.products || !page.products[spid]) {

               var name = (items[i].name ? 
                           items[i].name : 
                           items[i].make + " " + items[i].model);
               var part = (items[i].name && (items[i].name != items[i].model)) ?
                          items[i].model : "";
               var split_name = (items[i].name ? 
                                 items[i].name : 
                                 items[i].make + "<br>" +
                                 items[i].model);

               html += 
                  "<li style=\"" + 
		  ((b_horizontal) ? "width: 250px; overflow: hidden;" : "margin-bottom: 24px") + 
		  "\">" + 
                  "<a class=\"big_red_x\" href=\"javascript:void(null)\" style=\"float: right; border: 0;\" title=\"remove this from your history\" onclick=\"if (confirm('Permanently remove this item from your history?')) { page.removeFromRecentProducts(" + spid + "); page.showRecentProducts(); } return false;\">X</a>" +
                   "<a href=\"" + items[i].path + "SP" + spid + ".html\">" + 
                   (items[i].img ?
                   "<img src=\"http://img.streetprices.com/pr/" + items[i].img + "/90/90/img.jpg\" height=\"90\" width=\"90\" border=\"0\" alt=\"" + name + "\"" + image_style + ">" :
                   "<img src=\"/pic/no_image_90x90.gif\" height=\"90\" width=\"90\" border=\"0\" alt=\"" + name + "\"" + image_style + ">") + 
                   "</a><br>" + 
                  "<a href=\"" + items[i].path + "SP" + spid + ".html\">" + 
                   ((name.length > 18) ? split_name : name) + "</a>" +
		   ((b_horizontal && part) ? "<br><span class=\"stats\">" + items[i].make + " " + part + "</span>" : "");
            }
         }
         div.innerHTML = "<a name=\"recent\"></a><h" + ((b_horizontal) ? "3" : "4") + ">You just looked at...</h"  + ((b_horizontal) ? "3" : "4") + ">" +
			 ((b_horizontal) ? "<div class=\"subhead_bar\"><div style=\"float: right\">Tip: to <i>permanently remove</i> an item from your history, click the X.</div>The most recent products you saw at StreetPrices.</div>" : "") + 
                         "<ul " + 
			 ((b_horizontal) ? "class=\"related_list\"" : "") + 
			 ">" + 
                           html +
                         "</ul>" +
			 ((b_horizontal) ? 
			 "<div style=\"clear: both; padding-left: 100px;\"><a href=\"/my/?list=recent\">see more history...</a></div>" :
			 "");
      }
   }
}
page.populateRecentProducts = function page_populateRecentProducts(req) 
{
   var ids = eval(req.responseText);
   var spids = page.prefIdsToSpids(ids);

   var fields = ['path','makemodel','name','img'];

   page.collectItemInfo(spids, fields, page.finishRecentProducts);
}
page.showRecentProducts = function page_showRecentProducts(max) 
{
   if (!max) { max = 5; }

   max++;  /* we won't show the current product, so +1 to compensate */

   if ($('recent_products') || $('recent_products_horizontal')) {
      new Ajax.Request(page.prefURL, { 
        method: "post", 
        postBody: "type=list&namespace=history&name=spid&grp=spid&cmd=all&max=" + max,
        onSuccess: page.populateRecentProducts
      });
   }
}

page.sendFlagFeedback = function page_sendFlagFeedback() 
{
   var form = $('flag_feedback_form');
   var message   = $F('flag_feedback_form_feedback_field');
   var problem = 0;
   if (form && form.problem) {
      for (var i=0; i<form.problem.length; i++) {
         if (form.problem[i].checked) {
	   problem = form.problem[i].value;
	 }
      }
   }
   
   if (message && problem) {
      new Ajax.Updater('flag_feedback_form_message_div','/ajax/send_feedback.cgi', { 
        method: 'post', 
        postBody: 'url=' + encodeURIComponent(window.location.href) + 
                  '&problem=' + encodeURIComponent(problem) + 
                  '&feedback=' + encodeURIComponent(message),
        onComplete: new function() {
                       var contents = $('flag_feedback_form_contents');
                       if (contents) { contents.hide(); }
                    }
      });
   }
}

page.sendExitFeedback = function page_sendExitFeedback() 
{
   var message   = $F('exit_feedback_form_feedback_field');
   var exit_beta = $F('exit_feedback_form_exit_sneak_preview_field');
   if (message) {
      new Ajax.Updater('exit_feedback_form_message_div','/ajax/send_feedback.cgi', { 
        method: 'post', 
        postBody: 'url=' + encodeURIComponent(window.location.href) + 
                  '&exit_sneak_preview=' + encodeURIComponent(exit_beta) + 
                  '&feedback=' + encodeURIComponent(message),
        onComplete: new function() {
                       var contents = $('exit_feedback_form_contents');
                       if (contents) { contents.hide(); }

                       if ($F('exit_feedback_form_exit_sneak_preview_field')) {
                          var div = $('exit_feedback_form_escape_div');
                          if (div) {
                             div.innerHTML = "<a href=\"javascript:void(null);\" title=\"exit new look and feel, for real\" style=\"cursor:pointer;\" onclick=\"page.setCookie('beta'," + page.beta_left_beta + ", { domain: page.cookieDomain }); window.location.reload(true); return false;\">now let me out of here!</a>";
                          }
                       }
                    }
      });
   }
}
page.sendFeedback = function page_sendFeedback() 
{
   var message   = $F('feedback_form_feedback_field');
   var exit_beta = $F('feedback_form_exit_sneak_preview_field');
   if (message) {
      new Ajax.Updater('feedback_form_message_div','/ajax/send_feedback.cgi', { 
        method: 'post', 
        postBody: 'url=' + encodeURIComponent(window.location.href) + 
                  '&exit_sneak_preview=' + encodeURIComponent(exit_beta) + 
                  '&feedback=' + encodeURIComponent(message),
        onComplete: new function() {
                       var contents = $('feedback_form_contents');
                       if (contents) { contents.hide(); }

                       if ($F('feedback_form_exit_sneak_preview_field')) {
                          var div = $('feedback_form_escape_div');
                          if (div) {
                             div.innerHTML = "<a href=\"javascript:void(null);\" title=\"exit new look and feel, for real\" style=\"cursor:pointer;\" onclick=\"page.setCookie('beta'," + page.beta_left_beta + ", { domain: page.cookieDomain }); window.location.reload(true); return false;\">now let me out of here!</a>";
                          }
                       }
                    }
      });
   }
}

//thumbnail navigation code -- start
var navPointLeft = 0;
var navPointRight = 1;
var navLength = 1;
var navStart = 0;
var navEnd = 0;

function navDisplay(iStart, iEnd)
{
  for(var j = navPointLeft; j < navPointRight; j++)
  {
    if($('nav_thumbnail_img_grp_' + j))
    {
      $('nav_thumbnail_img_grp_' + j).style.display = 'none';
    }
  }

  for(var i = iStart; i < iEnd; i++)
  {
    if($('nav_thumbnail_img_grp_' + i))
    {
      $('nav_thumbnail_img_grp_' + i).style.display = 'inline';
    }
  }

  navPointLeft = iStart;
  navPointRight = iEnd;
}

function navLeft()
{
  var iStart = ((navPointLeft - navLength) > 0) ? (navPointLeft - navLength) : navStart;
  var iEnd = iStart + navLength;
  
  navDisplay(iStart, iEnd);

  if($('nav_right_arrow_0'))
  {
    $('nav_right_arrow_0').style.visibility = 'visible';
  }

  if($('nav_left_arrow_0'))
  {
    if(iStart == navStart)
    {
      $('nav_left_arrow_0').style.visibility = 'hidden';
    }
    else
    {
      $('nav_left_arrow_0').style.visibility = 'visible';
    }
  }
}

function navRight()
{
  var iStart = navPointRight;
  var iEnd = ((navPointRight + navLength) < navEnd) ? (navPointRight + navLength) : navEnd;

  navDisplay(iStart, iEnd);

  if($('nav_left_arrow_0'))
  {
    $('nav_left_arrow_0').style.visibility = 'visible';
  }

  if($('nav_right_arrow_0'))
  {
    if(iEnd == navEnd)
    {
      $('nav_right_arrow_0').style.visibility = 'hidden';
    }
    else
    {
      $('nav_right_arrow_0').style.visibility = 'visible';
    }
  }
}

function navInitialize(nEnd)
{
  navEnd = nEnd;
  if($('nav_right_arrow_0') && (navLength < navEnd))
  {
    $('nav_right_arrow_0').style.visibility = 'visible';
  }
}
//thumbnail navigation code -- end

page.closeStickynote = function page_closeStickynote(type,id)
{
   Try.these( 
      function() { 
         new Effect.BlindUp('stickynote_' + type + '_' + id + '_outer', 
                            { afterFinish: 
                                function(obj) { 
                                   $('stickynote_' + type + '_' + id + '_minimized').show(); 
                                } 
                            }); 
      } 
   );
   return false;
}

page.openStickynote = function page_openStickynote(type,id,rows,cols,force_open,draggable)
{
   var stickynote_id = 'stickynote_' + type + '_' + id;

   // create the stickynote, if needed
   if (!page.editors[stickynote_id]) {
      var div = $(stickynote_id + '_text');
      var default_text = ((div) ? div.innerHTML : "Click here to save a note.");
      page.createStickynote(type,id,default_text,{rows: rows, cols: cols, force_open: force_open, draggable: draggable });
   }

   $(stickynote_id + '_minimized').style.display = 'none'; 
   $(stickynote_id + '_outer').style.display = ''; 
   return false;
}

page.colorStar =  function page_colorStar(node) 
{
   node.childNodes[1].style.display='inline';
   node.style.opacity = 1.0;
   node.style.filter = 'alpha(opacity=100)';
}
page.unColorStar =  function page_unColorStar(node,id) 
{
   if (page.products[id].star == 1) { 
      node.childNodes[1].style.display='inline'; 
      node.style.opacity = 1.0;
      node.style.filter = 'alpha(opacity=100)';
   } else { 
      node.childNodes[1].style.display='none'; 
      node.style.opacity = '';
      node.style.filter = '';
   }
}

page.colorList =  function page_colorList(node) 
{
   if (node) {
      node.childNodes[1].style.display='inline';
      node.style.opacity = 1.0;
      node.style.filter = 'alpha(opacity=100)';
   }
}
page.unColorList =  function page_unColorList(node,id) 
{
   if (page.products[id].tags && page.products[id].tags.length) { 
      node.childNodes[1].style.display='inline'; 
      node.style.opacity = 1.0;
      node.style.filter = 'alpha(opacity=100)';
   } else if (node) { 
      node.childNodes[1].style.display='none'; 
      node.style.opacity = '';
      node.style.filter = '';
   }
}

page.colorPricealert =  function page_colorPricealert(node) 
{
   node.childNodes[1].style.display='inline';
   node.style.opacity = 1.0;
   node.style.filter = 'alpha(opacity=100)';
}
page.unColorPricealert =  function page_unColorPricealert(node,id) 
{
   if (page.products[id].pricealerts && page.products[id].pricealerts.length > 0) { 
      node.childNodes[1].style.display='inline'; 
      node.style.opacity = 1.0;
      node.style.filter = 'alpha(opacity=100)';
   } else { 
      node.childNodes[1].style.display='none'; 
      node.style.opacity = '';
      node.style.filter = '';
   }
}

var currency;
if (!currency) { 
   currency = new Object(); 

   currency.in_dollars = function currency_in_dollars(pennies) {
      pennies = pennies - 0;  // Force to a number (if it's a string)
      var dollars = Math.floor((pennies + .5)/100);
      var cents = Math.floor(pennies % 100);
      return "$" + dollars + "." + ((cents < 10) ? "0" + cents : cents);
   }
}


page.colorWishlist =  function page_colorWishlist(node) 
{
   node.childNodes[1].style.display='inline';
}
page.unColorWishlist =  function page_unColorWishlist(node,id) 
{
   if (page.products[id].wishlist == 1) { 
      node.childNodes[1].style.display='inline'; 
   } else { 
      node.childNodes[1].style.display='none'; 
   }
}


// add the product to the "wishlist" list on the server
page.addWishlist = function page_addWishlist(spid, show) {
   new Ajax.Request('/pref/',{
            method: 'post', 
            postBody: 'type=xlst&namespace=tags&name=wishlist&cmd=add&id=spid_' + spid,
           onSuccess: (show) ? 
                      new Function("req", "page.products[" + spid + "].wishlist = 1; page.showIcon('wishlist'," + spid + ");") : 
                      undefined 
         });
}


//get the entire "wishlist" list from the server
page.getWishlist = function page_getWishlist() {
   new Ajax.Request('/pref/',{method: 'post', postBody: 'type=list&namespace=tags&name=wishlist&grp=spid&cmd=all', onSuccess: page.loadWishlist });
}

// remove the product from the "wishlist" list on the server
page.removeWishlist = function page_removeWishlist(spid) {
   new Ajax.Request('/pref/',{
            method: 'post', 
            postBody: 'type=xlst&namespace=tags&name=wishlist&cmd=del&id=spid_' + spid,
            onSuccess: new Function("req", "page.products[" + spid + "].wishlist = 0; page.hideIcon('wishlist'," + spid + ");")
         });
}

page.loadWishlist = function page_loadWishlist(t) 
{
  var wishlist_local = eval(t.responseText);  // this should be a JS array

  page.undisplayWishlist();

  if (wishlist_local.length) 
  {
    for (var i=0; i<wishlist_local.length; i++) 
    {
      page.wishlist_array.push(wishlist_local[i]);
    }

    page.displayWishlist();
  }
}

page.addCheckedToWishlist = function page_addCheckedToWishlist()
{
  for (var i in page.products)
  {
    if($('compare_' + i).checked)
    {
      page.addWishlist(i);
    }
  }
} 

page.showWishlist = function page_showWishlist(t)
{
  var wisharray = eval(t.responseText);
  var wishnode = document.getElementById('wishlist_viewer');

  if(wisharray.length && wishnode)
  {
    for(var k = 0; k < wisharray.length; k++)
    {
      if(wisharray[k].id && wisharray[k].make && wisharray[k].name && wisharray[k].path)
      {
        var id_parts = wisharray[k].id.split("_");
        if(id_parts.length > 0)
        {
          var wishitem = document.createElement('div');
          wishitem.id = 'wishitem_' + wisharray[k].id;
          wishitem.innerHTML = "<span>" + 
                         "<a target=\"_blank\" href=\"" + wisharray[k].path + "SI" + id_parts[id_parts.length - 1] + ".html" + "\">" + wisharray[k].make + " " + wisharray[k].model + "</a>" + "&nbsp;" +
                         "<a style=\"font-size: 10px; text-decoration: none; color: #000000\" href=\"#\" onclick=\"page.removeWishlist(" + id_parts[id_parts.length - 1] + "); page.getWishlist(); return false;\">[remove]</a>" + 
                         "</span>";
          wishnode.appendChild(wishitem);
        }
      }
    }
  }
}

page.displayWishlist = function page_displayWishlist()
{
  var wishnode = document.getElementById('wishlist_viewer');
  if(page.wishlist_array.length && wishnode)
  {
    var query = "get=makemodel&get=name&get=path";

    for(var i_wish=0; i_wish < page.wishlist_array.length; i_wish++)
    {
      var id_split = page.wishlist_array[i_wish].split("_");
      if(id_split.length > 0)
      {
        query = query + "&" + "spid=" + id_split[id_split.length - 1];
      }
    }

    new Ajax.Request('/a/p?' + query, {method: 'get', onSuccess: page.showWishlist });

    wishnode.style.display = 'block';
  }
}

page.undisplayWishlist = function page_undisplayWishlist()
{
  var wishnode = document.getElementById('wishlist_viewer');
  if(page.wishlist_array.length && wishnode)
  {
    for(var i_wish=0; i_wish < page.wishlist_array.length; i_wish++)
    {
      var wishitem = document.getElementById('wishitem_' + page.wishlist_array[i_wish]);
      
      if(wishitem)
      {
        wishnode.removeChild(wishitem);
      }
    }
  }

  page.wishlist_array = [];
}

page.closeWishlist = function page_closeWishlist()
{
  var wishnode = document.getElementById('wishlist_viewer');
  if(wishnode)
  {
    wishnode.style.display = "none";
  }
}

page.showTags = function page_showTags(spid) {
   var tags = page.products[spid].tags;
   target = $('tags_area_' + spid);
   if (!target) { target = $('tags_area'); }
   if (target) {
      if (tags && tags.length > 0) {
         var hyperlinked_tags = new Array;
         for (var i=0; i<tags.length; i++) {
            if (tags[i] && tags[i].length) {
	       hyperlinked_tags.push("<a href=\"/my/?list=tags_" + encodeURIComponent(tags[i]) + "\">" + tags[i] + "</a>");
	    }
         }
         target.innerHTML = hyperlinked_tags.join(', ');
      }
      else { target.innerHTML = ''; }

   }
   if (tags && tags.length > 0) {
      var span = $('tag_chunk_' + spid);
      if (span) { page.colorList(span); }
      else {
         var img = $('tag_icon_' + spid);
	 if (img) { img.src = page.icon_on['tags']; img.parentNode.blur(); }
      }
   } else {
      var span = $('tag_chunk_' + spid);
      if (span) { page.unColorList(span, spid); }
      else {
         var img = $('tag_icon_' + spid);
	 if (img) { img.src = page.icon_off['tags']; img.parentNode.blur(); }
      }
   }
   var span = $('star_chunk_' + spid);
   if (span) { span.blur(); }
}

// add the product to the "tags" list on the server
page.saveTags = function page_saveTags(spid, tags_string) {
   if (spid) {
      var tags = (tags_string && tags_string.split) ? tags_string.split(/,\s*/) : new Array;

      // clean up tags
      for (var i=0; i<tags.length; i++) {
	 if (tags[i].match(/^\"/)) {
            tags[i] = tags[i].substitute(/^\"/g, '');
            tags[i] = tags[i].substitute(/\"$/g, '');
	 }
         tags[i] = tags[i].substitute(/\"/g, '&quot;');
         tags[i] = tags[i].substitute(/[\r\n]/g, ' ');
         tags[i] = tags[i].substitute(/\s+/g, ' ');
      }

      var old_tags = page.products[spid].tags;
      if (!old_tags || !old_tags.indexOf) { old_tags = new Array; }

      page.products[spid].tags = tags;

      var tags_cgi_string = '';
      for (var i=0; i<tags.length; i++) {
         tags_cgi_string += '&name=' + encodeURIComponent(tags[i]);
      }

      // Update the product's list of tags, and the tags' lists of products
      new Ajax.Request('/pref/',{
            method: 'post',
            postBody: 'type=xlst&cmd=set&namespace=tags' + ((tags.length > 0) ? tags_cgi_string : '') + '&id=spid_' + spid + '&noempty=1',
            onSuccess: new Function("page.showTags(" + spid + ");" )
         });
   }
}


page.updateTags = function page_updateTags(spid) {
   var current_tags = page.products[spid].tags;
   if (current_tags) {
      current_tags = current_tags.join(',');
      current_tags = current_tags.replace(/\&quot;/g, '"');
   }
   var tags = prompt("Tags for this item (comma-separated):", (current_tags ? current_tags : ''));
   if (tags == null) { }
   else { 
      if (dashboard) {
         dashboard.prettySaveTags(spid,tags); 
      } else {
         page.saveTags(spid,tags); 
      }
   }
}

page.setView = function page_setView(view)
{
   if (page.setCookie && (view == 'grid' || view == 'horizontal')) {
      var domain = page.cookieDomain ? page.cookieDomain : document.domain;
      page.setCookie('search_view',view, {domain: domain});
   }
}

page.getCheckedSpids = function page_getCheckedSpids()
{
  var checkedSpids = new Array;
  for (var i in page.products)
  {
    if($('compare_' + i).checked)
    {
      checkedSpids.push(i);
    }
  }
  return checkedSpids;
}

page.getStickynoteNode = function page_getStickynoteNode(type,id,default_text,force_open,rows,cols,right)
{
  return '<a rel="nofollow" id="stickynote_'+type+'_'+id+'_minimized" class="stickynote_minimized" href="javascript:void(null)" onclick="page.openStickynote(\''+type+'\','+id+','+rows+','+cols+','+force_open+',0)" style="'+(right?' float: right':'')+'"><img src="/pic/corner-small.png" width=10 height=10 alt="add a note" title="add a note"></a><div id="stickynote_'+type+'_'+id+'_outer" class="stickynote_outer" style="display: none;'+(right?' float: right; width: 220px;':' width: 230px;')+'"><div id="stickynote_'+type+'_'+id+'" class="stickynote small_corner"'+(right?' style="width: 200px;"':' style="width=288px;"')+'><a rel="nofollow" href="javascript:void(null)" class="x_toggle brown" onclick="page.closeStickynote(\''+type+'\','+id+');" title="hide stickynote">X</a><div id="stickynote_'+type+'_'+id+'_text" class="stickynote_text">'+(default_text?default_text:'Click to save a searchable note')+'</div></div></div>';
}

page.getToolboxNode = function page_getToolboxNode(id)
{
  return '<div class="toolbox" style="position: relative; top: -10px; margin-bottom: -10px;"><a id="star_chunk_'+id+'" rel="nofollow" href="javascript:void(null);" onMouseOver="page.colorStar(this)" onMouseOut="page.unColorStar(this,'+id+')" onClick="page.toggleStar(\''+id+'\'); return false;"><img id="star_ghost_'+id+'" src="/pic/paw_white_trans_20x20.gif" height=20 width=20 alt="save" title="save it" class="star_ghost"><img id="star_'+id+'" src="/pic/paw_red_trans_20x20.gif" height=20 width=20 alt="" class="star"></a><a id="tag_chunk_'+id+'" rel="nofollow" href="javascript:void(null);" onMouseOver="page.colorList(this)" onMouseOut="page.unColorList(this,'+id+')" onClick="page.updateTags('+id+'); return false;"><img id="tag_ghost_'+id+'" src="/pic/list_icon_white_trans_20x20.gif" height=20 width=20 alt="edit tags" title="edit tags" class="star_ghost"><img id="tag_'+id+'" src="/pic/list_icon_yellow_trans_20x20.gif" height=20 width=20 alt="" class="star"></a></div>';
}

page.getPriceRangeNode = function page_getPriceRangeNode(id)
{
  var node = '';
  var info = page.products[id];

  if (info.items <= 0)
  {
    node += '<p><b>Sold out!</b>  We can\'t find any online sellers for this item.<br>'
    if (info.ebay && info.ebayq)
    {
      node += '<a target="_blank" rel="nofollow" href="';
      node += info.ebay;
      node += '">Search ebay for <i>';
      node += info.ebayq;
      node += '</i></a>';
    }
    node += '</p>';
  } else {
    node += '<span style="white-space: nowrap">';
    node += '<a class="product_result_price" href="'+info.url+'">';
    node += info.low_price;

    if (info.items > 1 && info.low_price != info.high_price)
    {
      node += '<span class="highprice">&nbsp;&ndash;&nbsp;';
      node += info.high_price;
      node += '</span>';
    }

    node += '</a>';

    if (info.items == 1)
    {
      node += ' at 1 seller';

      if (info.merchant != undefined)
      {
        node += ' ('+info.merchant+')';
      }

      node += '</span>';

      if (info.rd != undefined)
      {
        node += '<a href="'+info.rd+'" class="link_with_icon" style="margin-left: 2em; white-space: nowrap;"><span>See it at '+(info.merchant!=undefined?info.merchant:'this seller')+'</span> <img src="/pic/outside_page.png" alt=""/></a>';
      }
    } else {
      node += '</span>';
      node += '<a class="link_with_icon" style="margin-left: 2em" href="'+info.url+'">';
      node += '<span>Compare prices at '+info.items+' stores</span> <img src="/pic/graph_red_20x20.gif" style="vertical-align: middle" alt="and see price graph"/>';
      node += '</a>';
    }
 
    node += '</span>';
  }

  return node;
}
