(function($) {
  $.update_search_inputs = function() {
    var url_parameters = {};

    document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function() {
      function decode(s) {
        return decodeURIComponent(s.split("+").join(" "));
      }

      url_parameters[decode(arguments[1])] = decode(arguments[2]);
    });

    if($.cookie('scholastic_rls') == "100" || $.cookie('scholastic_rls') == "101" ||
       $.cookie('scholastic_rls') == "102" || $.cookie('scholastic_rls') == "103") {
      $('#RLS select[name="RLS_system"]').val($.cookie('scholastic_rls'));
    }

    if(-1 != window.location.pathname.indexOf('bookAlikeSearch.do')) {
      $(function(){
        if($('#search_bar_term').size() > 0) {
          jQuery('#bookAlikeForm .as-input').val($('#search_bar_term').val());
          NttBookAlikeEntered = true;
        }
      });
      $('.tabs li a').filter(':last').click();
    }else{
      $(function(){
        if($('#search_bar_term').length && $('#search_bar_term').val().length > 0) {
          $('#quickSearchHeaderForm .as-input').val($('#search_bar_term').val());
          NttQuicksSearchHeaderEntered = true;
        }

        if(typeof url_parameters["N"] != 'undefined' && -1 != url_parameters["N"].indexOf("1650")) {
          $('#quickSearch input#only_available_for_purchase').attr('checked','checked');
        }
      });
      $('.tabs li a').filter(':first').click();

    }
  }

})(jQuery);

(function($) {
  $.cookie = function(name, value, options) {
    if (typeof value != 'undefined') {
      options = options || {};
      if (value === null) {
        value = '';
        options.expires = -1;
      }
      var expires = '';
      if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
        var date;
        if (typeof options.expires == 'number') {
          date = new Date();
          date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
        } else {
          date = options.expires;
        }
        expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
      }
      var path = options.path ? '; path=' + (options.path) : '';
      var domain = options.domain ? '; domain=' + (options.domain) : '';
      var secure = options.secure ? '; secure' : '';
      document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
      var cookieValue = null;
      if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
          var cookie = jQuery.trim(cookies[i]);
          if (cookie.substring(0, name.length + 1) == (name + '=')) {
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
            break;
          }
        }
      }
      return cookieValue;
    }
  }
})(jQuery);

(function($) {
  $.show_advanced_search = function() {
    $("body").append($("#advanced_search_popup").remove());
    $("#advanced_search_popup #advanced_search .in .content").load("/tbw/viewCustomSearchForm.do",
      function() {
        var defaultValue = "Enter a title, author, or keyword";
        var advancedSearchKeyword = $('#custom_search_form .as-input');

        if (!advancedSearchKeyword.val() || advancedSearchKeyword.val().trim() == '' || advancedSearchKeyword.val() == defaultValue) {
          var quickSearchKeywords = $('#quickSearchHeaderForm .as-input').val();
          advancedSearchKeyword.val(quickSearchKeywords && quickSearchKeywords.trim().length > 0
                                                    ? quickSearchKeywords
                                                    : defaultValue );
        }

        $('#custom_search_formm .as-input').focus(function () {
          if($(this).attr("value")==defaultValue) {
            $(this).attr("value","");
          }
        });

        $('#custom_search_form').submit(function() {
          if(advancedSearchKeyword.val() == defaultValue) {
            advancedSearchKeyword.val("");
          }
        });

        advancedSearchKeyword.blur(function() {
          if ($(this).attr("value").trim() == '') {
            $(this).attr("value", defaultValue);
          }
        });

        if($.cookie('scholastic_rls') == "100" || $.cookie('scholastic_rls') == "101" ||
           $.cookie('scholastic_rls') == "102" || $.cookie('scholastic_rls') == "103") {
          $('#custom_search_form #reading_level_opts').val($.cookie('scholastic_rls'));
        }

        $('#advanced_search_popup').show();
      }
    );
  }
})(jQuery);

function NttSubmit() {
  var localNttBookAlikeInput = jQuery('#bookAlikeForm .as-input');
  if(!NttBookAlikeEntered || localNttBookAlikeInput.val().trim()=='') {
    jQuery('#NttBookAlikeInputWrapper').addClass('error');
    localNttBookAlikeInput.addClass('error');
    return false;
  } else {
    return submitSearchFormAndGradeOffset(localNttBookAlikeInput.attr('id'), 'bookAlikeForm', 'N=0&Ntk=TBW_TitleSearch_SI&Ntx=mode+matchallpartial&Ne=1314', slider.getValue() / slider.getThumb().tickSize );
  }
}

function removeErrorClasses(input){
  jQuery(input).parent().andSelf().removeClass('error')
}

function NttQuicksSearchHeaderSubmit(formId){
  if( !formId ) formId = 'quickSearchHeaderForm';
  var inputElement = jQuery('#' + formId + ' .as-input');
  var inputId = inputElement.attr('id');

  if(inputElement == null || inputElement.val().trim()=='' || !NttQuicksSearchHeaderEntered){
    jQuery('#NttQuicksSearchInputWrapper').addClass('error');
    inputElement.addClass('error');
    return false;
  } else {
    if ($('#only_available_for_purchase')[0].checked) {
      return quickSearchFormAction(inputId, 'Ntx=mode+matchallpartial&Ntk=TBW_QuickSearch_SI&Ne=1314&N=0+1650');
    } else {
      return quickSearchFormAction(inputId, 'N=0&Ntk=TBW_QuickSearch_SI&Ntx=mode+matchallpartial&Ne=1314');
    }
  }
}

function quickSearchFormAction(inputId, queryString){
  var searchParam = document.getElementById(inputId);
  window.location = document.quickSearchHeaderForm.action
    + queryString
    + "&" + document.getElementById(inputId).name
    + "=" + encodeURIComponent(searchParam.value);

  return false;
}

function RLSset(level, dontReloadDoc)
{
  $.cookie('scholastic_rls', level, {path: '/', domain: '.scholastic.com'});
  var httpRequest = createRequest();
  var randReq = parseInt(Math.random()*99999999);
  var url = "/tbw/RLSSet.do";
  httpRequest.onreadystatechange = function() { alertContents(httpRequest, dontReloadDoc); };
  httpRequest.open('GET', url + "?rls_value=" + level + "&rand=" + randReq, true);
  httpRequest.send(null);
}

function RLS_change_refresh(formName) {
  rls = document.forms[formName].RLS_system;
  RLSset(rls.options[rls.selectedIndex].value, false);
}

function alertContents(httpRequest, dontReloadDoc) {
  if (httpRequest.readyState == 4) {
    if (httpRequest.status == 200) {
      RLSresponse = httpRequest.responseText.replace(/^\s+|\s+$/g,"");
      switch(RLSresponse) {
      case "removed":
        document.getElementById("TBWheader_unset").style.display="block";
        document.getElementById("TBWheader_set").style.display="none";
        break;
      case "set_error":
        //do something
        alert("Error setting RLS");
        break;
      case "unset_error":
        //do something
        alert("Error removing RLS");
        break;
      default:
        //if the reading level was just set, then refresh
        if (!dontReloadDoc) {
          window.location.reload();
        }
      }
    } else {
      alert('There was a problem with the request.');
    }
  }
}

function getOffsetFromUrl(){
  var regexS = "[\\?&]gradeOffset=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function submitSearchForm(inputId, formId, queryString){
  var searchForm = jQuery('#' + formId);
  var searchParam =  searchForm.find('#' + inputId );

  window.location = searchForm.attr('action')
    + queryString
    +  "&" + searchParam.attr('name')
    + "=" + encodeURIComponent(searchParam.val());



  return false;
}

function submitSearchFormAndGradeOffset(inputId, formId, queryString,gradeOffset ){
  var searchForm =  jQuery('#' + formId);
  var searchParam = searchForm.find('#' + inputId );

  window.location =  searchForm.attr('action')
    + queryString
    +  "&" + searchParam.attr('name')
    + "=" + encodeURIComponent(searchParam.val())
    + "&"
    + "gradeOffset="
    + gradeOffset;

  return false;
}

// While we're using jQuery 1.3.2 we need this
if (typeof($.parseJSON) == "undefined") {
  $.extend({
    parseJSON: function( data ) {
      if ( typeof data !== "string" || !data ) {
        return null;
      }
      data = jQuery.trim( data );
      if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
                                .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
                                .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {
        return window.JSON && window.JSON.parse ?
          window.JSON.parse( data ) :
          (new Function("return " + data))();
      } else {
        jQuery.error( "Invalid JSON: " + data );
      }
    }
  });
}


function initScholasticAutosuggest( type, formId ) {
  var optsHash = {
    quickSearch: {
      suggest_url : "/solr/tbw_autocomplete/suggest_quick",
      startText : "Enter a title, author, or keyword"
    },
    bookAlikeSearch: {
      suggest_url : "/solr/tbw_autocomplete/suggest_bookalike",
      startText : "Enter a title to find similar books"
    }
  };

  var opts = optsHash[type];
  opts['form_id'] = formId;

  ScholasticAutosuggest.init(opts);
}

jQuery(function() {
  initScholasticAutosuggest('quickSearch', "quickSearchHeaderForm");

  initScholasticAutosuggest('bookAlikeSearch', "bookAlikeForm");

  jQuery.update_search_inputs();
});

