﻿/// <reference path="../Global.js" />
/// <reference path="../extJs/util.js" />

// JScript File
/*
Author: Alivya Zhang
Create: 2010-04-07
*/

/*
TypeofMaterial = 0,
Subjects = 1,
Authors = 2,
Series = 3,
DatePublished = 4,
TargetAudience = 5
*/
function SimpleSearch() {
}

SimpleSearch.prototype = {
   CustomSettingShowCollectionType: true,
   Decentralized: null,
   SearchMinChar: 0,
   DoReadingCountSearch: false,
   clientMsg: "",
   BrowseIndex: true,
   ShowOtherConditions: true,

   Initial: function(callback, isFocusInSearch) {
      /// <summary>
      /// The Initialize of simple
      /// </summary>
      window.searchLoadMask.show();

      var parent = this;
      var isShowCboSearch = false;
      var isShowOneLibrary = false;
      AjaxSimpleSearch.AjaxInitialSimple(
         function(res) {
            if (res.length = 17) {
               if (res.containsKey("isUseGoogleSuggestions"))
                  isShowCboSearch = res.getValue("isUseGoogleSuggestions") == "1" ? true : false;
               if (res.containsKey("showOneLibrary"))
                  isShowOneLibrary = res.getValue("showOneLibrary") == "1" ? true : false;
               if (res.containsKey("clientMsg1"))
                  parent.clientMsg = res.getValue("clientMsg1");
               if (res.containsKey("bCustomsettingShowCollectionType"))
                  parent.CustomSettingShowCollectionType = res.getValue("bCustomsettingShowCollectionType") == "1" ? true : false;
               if (res.containsKey("Decentralized"))
                  parent.Decentralized = res.getValue("Decentralized");
               if (res.containsKey("iSearchMinChar"))
                  parent.SearchMinChar = parseInt(res.getValue("iSearchMinChar"));
               if (res.containsKey("BrowseIndex"))
                  parent.BrowseIndex = res.getValue("BrowseIndex") == "1" ? true : false;
               if (res.containsKey("isNewAdvanced"))
                  window.isNewAdvancedSearch = res.getValue("isNewAdvanced") == "1" ? true : false;
               //               window.isNewAdvancedSearch = parent.isNewAdvanced;

               var defaultSearchBy = res.getValue("WebOpacDefaultSearch");
               var lexileList = eval(res.getValue("lexileDatas"));
               var arInterestLevelList = eval(res.getValue("arInterestLevelDatas"));
               var rcInterestLevelList = eval(res.getValue("arInterestLevelDatas"));
               var bookAdventureList = eval(res.getValue("bookAdventureDatas"));

               BindLibraries();
               if (res.containsKey("sDefaultLibraryID"))
                  Util.searchLibraryid = res.getValue("sDefaultLibraryID");
               Util.set_LibraryIDsOfSelectedItems($("cboLibraries"), Util.searchLibraryid);
               SelectItemByValue($("cboSearchBy"), defaultSearchBy);
               if (res.containsKey("defaultSort"))
                  SelectItemByValue($("cboSort"), res.getValue("defaultSort"));
               BindCBDataSource("cboLexile", lexileList);
               BindCBDataSource("cboARInterestLevel", arInterestLevelList);
               BindCBDataSource("cboRCInterestLevel", rcInterestLevelList);
               BindCBDataSource("cboBA", bookAdventureList);

               var keydown = function(e) {
                  Util.keyDown(e, "Util.search_Simple()");
               };
               $("txtSearch").onkeydown = keydown;
               $("txtLexFrom").onkeydown = keydown;
               $("txtLexTo").onkeydown = keydown;
               $("txtBAFrom").onkeydown = keydown;
               $("txtBATo").onkeydown = keydown;
               $("txtARTestNoFrom").onkeydown = keydown;
               $("txtARTestNoTo").onkeydown = keydown;
               $("txtARPointsFrom").onkeydown = keydown;
               $("txtARPointsTo").onkeydown = keydown;
               $("txtReadingLevelFrom").onkeydown = keydown;
               $("txtReadingLevelTo").onkeydown = keydown;
               if (isShowCboSearch) {
                  LazyLoad.loadOnce("js/Logic/complete.js", function() {
                     oComplete = new Complete("txtSearch");
                     oComplete.keydowncallback = keydown;
                     oComplete.country = 'ca'; // ca is canada 
                     oComplete.onclick = Util.search_Simple;
                     oComplete.offset.w = 0;
                     oComplete.setpos();
                  }, this, true, true);
               }
               if (Util.isFocusInSearch()) {
                  if (isFocusInSearch) {
                     setTimeout(function() { $("txtSearch").focus() }, 500);
                  }
                  else if (isFocusInSearch == null) {
                     setTimeout(function() { $("txtSearch").focus() }, 500);
                  }
               }
               if (!parent.ShowOtherConditions)
                  parent.ShowOtherConditions = true;
               if ($("cboLibraries").options.length > 1) {
                  document.getElementById("txt2").style.display = "";
                  document.getElementById("txt8").style.display = "";
               }
               else {
                  document.getElementById("txt2").style.display = "none";
                  document.getElementById("txt8").style.display = "none";
               }
               SelectItemByText($("cboReading"), $("cboReading").text);
               //         		$("ResultMainDIV").style.display = "none";
               parent.cboLibraries_onchange();
               if (res.containsKey("OPACFeatureDescHTML")) {//Simon add for Display OPAC Feature Descrition,2011-03-18
                  if (res.getValue("OPACFeatureDescHTML") != "") {
                     var browserWindow = Util.getDocument();
                     var blankHeight = browserWindow.clientHeight;
                     $("OPACFeatureDescDIV").style.height = (blankHeight / 2 - 70) + "px";
                     $("OPACFeatureDesc").innerHTML = res.getValue("OPACFeatureDescHTML");
                     $("OPACFeatureDescDIV").style.display = "";
                  }
               }
               window.isSearching = false;
               if (callback != null)
                  callback();
            }
            return false;
         },
         function(error) {
            if (window.searchLoadMask) { window.searchLoadMask.hide(); } Util.showError(error);
         });

      function BindLibraries() {
         if (!isShowOneLibrary) {
            BindCBDataSource("cboLibraries", Util.libraries);
            if (Util.libraries != null && Util.libraries.length > 1)
               $("cboLibraries").options[$("cboLibraries").options.length] = new Option("All Libraries", "0");
         }
         else {
            $("cboLibraries").options.length = 1;
            if (Util.searchLibraryid.toLowerCase() != "all") {
               for (var i = 0; i < Util.libraries.length; i++) {
                  if (Util.searchLibraryid == Util.libraries[i][0]) {
                     $("cboLibraries").options[0] = new Option(Util.libraries[i][1], Util.libraries[i][0]);
                     break;
                  }
               }
            }
            else
               $("cboLibraries").options[0] = new Option("All Libraries", "0");
         }
      }

      function BindCBDataSource(oSelect, Source) {
         /// <summary>
         /// Binding Source to CommboBox(Select) 
         /// </summary>
         /// <param name="oSelect" type="String|Object" mayBeNull="false"/>
         /// <param name="Source" type="Array" mayBeNull="false">
         /// Example: [['0001',"Insignia"],['0002','LibraryName']]
         /// </param>
         /// <param name="defaultValue" type="Array" mayBeNull="true">
         /// Example: ['0001', '0002']
         /// </param>
         if (typeof oSelect == "string") {
            oSelect = $(oSelect);
         }
         oSelect.options.length = Source.length;
         for (var i = 0; i < Source.length; i++) {
            oSelect.options[i] = new Option(Source[i][1], Source[i][0]);
         }
      }

      //selected the first Item which text was assigned
      function SelectItemByText(obj, text) {
         var isExit = false;
         for (var i = 0; i < obj.options.length; i++) {
            if (obj.options[i].text == text) {
               obj.options[i].selected = true;
               return true;
            }
         }
         return false;
      }

      //selected the first Item which value was assigned
      function SelectItemByValue(obj, value) {
         var isExit = false;
         for (var i = 0; i < obj.options.length; i++) {
            if (obj.options[i].value == value) {
               obj.options[i].selected = true;
               return true;
            }
         }
         return false;
      }
   },
   search: function(callback, searchBy, searchValue, isLink, strCollection) {
      /// <summary>simple search</summary>
      /// <param name="callback" type="object" mayBeNull="false" >the callback function</param>
      /// <param name="searchBy" type="string" mayBeNull="true" ></param>
      /// <param name="searchValue" type="string" mayBeNull="true" ></param>
      /// <param name="isLink" type="Boolean" mayBeNull="true" ></param>
      /// <param name="strCollection" type="string" mayBeNull="true" ></param>
      /// <param name="strLibraryId" type="string" mayBeNull="true" ></param>

      var regN = new RegExp("%27", "g");
      if (searchValue != null) {
         searchValue = searchValue.replace(regN, "'");
         regN = new RegExp("%29", "g");
         searchValue = searchValue.replace(regN, "\"");
         regN = new RegExp("%20", "g");
      }
      if (isLink == null)
         isLink = false;
      var searchString = (searchValue == null ? $("txtSearch").value : searchValue.replace(regN, " "));
      $("txtSearch").value = searchString;
      if (searchBy != null) {
         if (searchBy.toLowerCase() == "seriestitle".toLowerCase())
            searchBy = "Series";
         var obj = $("cboSearchBy");
         for (var i = 0; i < obj.options.length; i++) {
            if (obj.options[i].value.toLowerCase() == searchBy.toLowerCase()) {
               obj.options[i].selected = true;
               break;
            }
         }
      }

      var parent = this;
      if (!window.isSearching) {
         window.isSearching = true;
         var sRef;
         var MinChar = Util.minChar;

         var sValue = $("txtSearch").value;

         AjaxSimpleSearch.AjaxNormalizeString(searchString, function(NormalizedValue) {
            var bShowNew = $("chkShowNew").checked;
            if (!bShowNew && ((searchString.length < MinChar || NormalizedValue.length < MinChar) && !parent.DoReadingCountSearch)) {
               $("trShowErrorMessage").style.display = "";
               $("lblErrorMessage").innerHTML = parent.clientMsg;
               window.isSearching = false;
               if (searchString.length < MinChar || NormalizedValue.length < MinChar) {
                  $("lblErrorMessage").innerHTML = Util.langMinChar;
               }

               if (callback != null)
                  callback(null);
               return;
            }
            else {
               if ($("cboSearchBy") == null) {
                  window.isSearching = false;
                  if (callback != null)
                     callback(null);
                  return;
               }
               if ($("cboLibraries").value == "") {
                  $("cboLibraries").selectedIndex = 0;
               }
               loadSearchData(parent, callback);
            }
         },
         function(error) {
            if (window.searchLoadMask) { window.searchLoadMask.hide(); } window.isSearching = false; Util.showError(error);
         });
      }
      else {
         return;
      }

      function loadSearchData(Owner, callback) {
         var strSearchBy = (searchBy == null ? $("cboSearchBy").value : searchBy);
         var strARSearchType = (searchBy == null ? $("cboReading").value : "");
         var strARTestNoFrom = (searchBy == null ? $("txtARTestNoFrom").value : "");
         var strARTestNoTo = (searchBy == null ? $("txtARTestNoTo").value : "");
         var strARPointsFrom = (searchBy == null ? $("txtARPointsFrom").value : "");
         var strARPointsTo = (searchBy == null ? $("txtARPointsTo").value : "");
         var strcboARInterestLevel = (searchBy == null ? $("cboARInterestLevel").value : "");
         var strRCInterestLevel = (searchBy == null ? $("cboRCInterestLevel").value : "");
         var strARReadingLevelFrom = (searchBy == null ? $("txtReadingLevelFrom").value : "");
         var strARReadingLevelTo = (searchBy == null ? $("txtReadingLevelTo").value : "");
         var strLexileType = (searchBy == null ? $("cboLexile").value : "");
         var strLexileFrom = (searchBy == null ? $("txtLexFrom").value : "");

         var strLexileTo = (searchBy == null ? $("txtLexTo").value : "");

         var strBAType = (searchBy == null ? $("cboBA").value : "");
         var strBAFrom = (searchBy == null ? $("txtBAFrom").value : "");
         var strBATo = (searchBy == null ? $("txtBATo").value : "");

         var strOrderBy = (searchBy == null ? $("cboSort").value : "");
         var bShowNew = (searchBy == null ? $("chkShowNew").checked : false);
         var strLibraryID = "";
         if (searchBy == null) {
            for (var i = 0; i < $("cboLibraries").options.length; i++) {
               if ($("cboLibraries").options[i].selected) {
                  if ($("cboLibraries").options[i].value == "0") {
                     strLibraryID = "0";
                     break;
                  }
                  if (strLibraryID.length > 0)
                     strLibraryID += "|";
                  strLibraryID += $("cboLibraries").options[i].value;
               }
            }
         }

         var strSelectCollection = strCollection;
         if (!isLink || strCollection == null || strCollection.length < 1) {
            strCollection = "";
            strSelectCollection = "";
            var isSelectedCol = false;
            for (var i = 0; i < $("cboCollection").options.length; i++) {
               if ($("cboCollection").options[i].selected) {
                  isSelectedCol = true;
                  if (strSelectCollection.length > 0)
                     strSelectCollection += "|";
                  strSelectCollection += $("cboCollection").options[i].value;
               }
               else {
                  if (strCollection.length > 0)
                     strCollection += "|";
                  strCollection += $("cboCollection").options[i].value;
               }
            }
            if (!isSelectedCol)
               strCollection = "";
            if (isLink)
               strSelectCollection = "";
         }

         var iSearchMethod = (searchBy == null ? parseInt($("cboMatch").value) : 29802);
         AjaxSimpleSearch.AjaxSearch(strARSearchType, strARTestNoFrom, strARTestNoTo, strARPointsFrom, strARPointsTo, strcboARInterestLevel
            , strRCInterestLevel, strARReadingLevelFrom, strARReadingLevelTo, strLexileType, strLexileFrom, strLexileTo
            , strBAType, strBAFrom, strBATo, "", iSearchMethod, strSearchBy, strOrderBy, strLibraryID, strCollection, searchString, bShowNew, isLink
            , $("chkRating0").checked, window.FilterBrate, strSelectCollection,
            function(res) {
               if (res != null && typeof (res) == "object") {
                  if (!res.bResult) {
                     window.isSearching = false;
                     if (res.strError != null && res.strError.length > 0) {
                        $("trShowErrorMessage").style.display = "";
                        $("lblErrorMessage").innerHTML = res.strError;
                        if (callback != null)
                           callback(null);
                     }
                     else {
                        if (callback != null)
                           callback(null, true);
                     }
                     return;
                  }
                  else {
                     window.isSearching = false;
                     $("trShowErrorMessage").style.display = "none";
                     $("lblErrorMessage").innerHTML = "";
                     if (callback != null)
                        callback(res.oResult, true);

                     return;
                  }
               }
               else {
                  window.isSearching = false;
                  if (callback != null)
                     callback(null, true);
                  return;
               }
            },
            function(error) {
               if (window.searchLoadMask) { window.searchLoadMask.hide(); } window.isSearching = false; Util.showError(error);
            });
      }
   },

   showReadingByType: function() {
      /// <summary>if reading program change, show defferent content below it</summary>

      var ReadingType = $("cboReading").options[$("cboReading").selectedIndex].value;
      switch (ReadingType) {
         case "All":
            $("trAcceleratedReader").style.display = "none";
            $("trLexile").style.display = "none";
            $("trBookAdventure").style.display = "none";
            this.DoReadingCountSearch = false;
            break;
         case "AcceleratedReader":
            $("trAcceleratedReader").style.display = "";
            $("trLexile").style.display = "none";
            $("tdcboARInterestLevel").style.display = "";
            $("tdcboRCInterestLevel").style.display = "none";
            $("trBookAdventure").style.display = "none";
            this.DoReadingCountSearch = true;
            break;
         case "ReadingCount":
            $("trAcceleratedReader").style.display = "";
            $("trLexile").style.display = "none";
            $("tdcboARInterestLevel").style.display = "none";
            $("trBookAdventure").style.display = "none";
            $("tdcboRCInterestLevel").style.display = "";
            this.DoReadingCountSearch = true;
            break;
         case "Lexile":
            $("trAcceleratedReader").style.display = "none";
            $("trBookAdventure").style.display = "none";
            $("trLexile").style.display = "";
            this.DoReadingCountSearch = true;
            break;
         case "BookAdventure":
            $("trBookAdventure").style.display = "";
            $("trAcceleratedReader").style.display = "none";
            $("trLexile").style.display = "none";
            this.DoReadingCountSearch = true;
            break;
      }
   },

   cboLibraries_onchange: function() {
      /// <summary>if libraries change, show or hide collection and reading program and change the collection type datas</summary>

      var cValue = true;
      var j = 0;
      var parent = this;
      var strLibraryID = "";
      HidenReadingProgam(this);
      for (var i = 0; i < $("cboLibraries").options.length; i++) {
         if ($("cboLibraries").options[i].selected) {
            if ($("cboLibraries").options[i].value == "0") {
               strLibraryID = "0";
               cValue = false;
               break;
            }
            if (strLibraryID.length > 0)
               strLibraryID += "|";
            strLibraryID += $("cboLibraries").options[i].value;
            j++;
         }
      }
      if (j > 1) {
         cValue = false;
      }
      if (window.searchLoadMask)
         window.searchLoadMask.hide();
      if (cValue == true) {
         AjaxSimpleSearch.hidebUseARRCLexile($("cboLibraries").value,
            function(response) {
               if (response) {
                  VisibleReading(false, parent);
               }
               else {
                  VisibleReading(true);
                  if ($("cboReading").options.length > 0)
                     $("cboReading").options[0].selected = true;
               }
               ChangeShowCollectionType(parent, $("cboLibraries").value);
            },
            function(error) {
               if (window.searchLoadMask) { window.searchLoadMask.hide(); } Util.showError(error);
               return;
            });
      }
      else {
         AjaxSimpleSearch.hidebUseARRCLexile2((strLibraryID == "0" ? "All" : strLibraryID),
            function(response) {
               if (response) {
                  VisibleReading(false, parent);
               }
               else {
                  VisibleReading(true);
                  if ($("cboReading").options.length > 0)
                     $("cboReading").options[0].selected = true;
               }
               ChangeShowCollectionType(parent, strLibraryID);
            },
            function(error) {
               if (window.searchLoadMask) { window.searchLoadMask.hide(); } Util.showError(error);
            });
      }

      function ChangeShowCollectionType(Owner, libraryID) {
         var K = 0;
         for (var i = 0; i < $("cboLibraries").options.length; i++) {
            if ($("cboLibraries").options[i].selected) {
               K++;
            }
         }
         var strLibraryID = "";
         strLibraryID = libraryID;
         AjaxSimpleSearch.AjaxHideAndGetCollectionType($("cboLibraries").value, strLibraryID,
            function(response) {
               if (K > 1) {
                  if (Owner.CustomSettingShowCollectionType) {
                     VisibleCollection(true);
                  }
                  else {
                     VisibleCollection(false);
                  }
               }
               else {
                  if (response.bResult) {
                     VisibleCollection(false);
                  }
                  else {
                     VisibleCollection(true);
                  }
               }
               $("cboCollection").options.length = 0; //clear all options
               if (strLibraryID.length > 0 && response.oResult != null && typeof (response.oResult) == "object" && $("tdlblCollection").style.display != "none") {
                  $("cboCollection").options.length = response.oResult.Rows.length;
                  for (var index = 0; index < response.oResult.Rows.length; index++) {
                     $("cboCollection").options[index] = new Option(response.oResult.Rows[index].t10Value, response.oResult.Rows[index].t10Value);
                     if (response.oResult.Rows[index].Selected == "True")
                        $("cboCollection").options[index].selected = true;
                  }
               }
            },
            function(error) {
               if (window.searchLoadMask) { window.searchLoadMask.hide(); } Util.showError(error);
               return;
            });
      }

      function VisibleReading(IsVisible, Owner) {
         if (IsVisible) {
            $("trReading").style.display = "";
         }
         else {
            $("trReading").style.display = "none";
            if ($("cboReading").options.length > 0)
               $("cboReading").options[0].selected = true;
            HidenReadingProgam(Owner);
         }
      }

      function HidenReadingProgam(Owner) {
         try {
            $("trLexile").style.display = "none";
            $("trAcceleratedReader").style.display = "none";
            Owner.DoReadingCountSearch = false;
         } catch (x) {

         }
      }

      function VisibleCollection(IsVisible) {
         if (IsVisible) {
            $("tdlblCollection").style.display = "";
            $("cboCollection").style.display = "";
         }
         else {
            $("tdlblCollection").style.display = "none";
            $("cboCollection").style.display = "none";
         }
      }
   }
}
