﻿// JScript File

    function Pager(pagesPerDivision, totalNumberOfPages, currentPage){
            
        
        this.currentPage = currentPage
        this.pagesPerDivision = pagesPerDivision;
        this.totalNumberOfPages = totalNumberOfPages;
        this.currentDivision = Math.floor(currentPage / pagesPerDivision);
        
        this.firstPageNum = this.currentDivision * this.pagesPerDivision;
        this.lastPageNum = Math.min((this.currentDivision+1) * this.pagesPerDivision,this.totalNumberOfPages);
        
        this.firstPageOnNextDivision = function(){
            Math.min(this.totalNumberOfPages,this.lastPageNum+1);
        }
        
        this.lastPageOnPreviousDivision = function(){
            Math.max(0,this.firstPageNum-1);
        }
        
        
    }
    
    function VisualSearch(){
    
        
        this._firstTime = true;
        this._communicator =  new Communicator();
        this._communicator._vsearch = this;
        this._sectors = null;
        this._categories = null;
        this._subjects = null;
        //this._filters = [{Name:'מגזר',ID:'filter_sector'},{Name:'קטגוריה',ID:'filter_category'},{Name:'נושא',ID:'filter_subject'}];
        this._filters = [{Name:'מגזר',ID:'filter_sector'},{Name:'קטגוריה',ID:'filter_category'},{Name:'בטל סינון',ID:'filter_disable'}];
        this._searchResults = null;
        this._currentPage = 0;
        this._itemsPerPage = 36;
        this._firstPage = null;
        
        Array.prototype.isIn = function(element){
            var result = false;
            for(var c=0;c<this.length;c++)
                if(this[c]==element) result=true;
            
            return(result);
        }
        
        function itemsPerPage() {
            return (this._itemsPerPage);
        }
        
        this.CheckAll = function(checkState){
        
            var controls = [document.getElementById("section_items"),document.getElementById("category_items")];
            var inputElements = document.getElementsByTagName("INPUT");
            var selectedFilter;
            
            for(var c=0;c<controls.length;c++)
                if(controls[c].style.display=="block"){
                    selectedFilter=controls[c].id;
                    for(i=0;i<inputElements.length;i++)
                        if(inputElements[i].getAttribute("group")==selectedFilter) inputElements[i].checked = (checkState==1);
                }
            
        }
        
        this.FinishInitialization = function(){
           if(this._sectors!=null && this._categories!=null){
              
                var selectedCategories = [];
                var selectedSectors = [];
                var selectedSubjects = [];
                
                if(window._defaults){
                    selectedCategories = window._defaults.categories;
                    selectedSectors = window._defaults.sectors;
                    selectedSubjects = window._defaults.subjects;
                    document.getElementById("filter_keyword").value = decodeURI(window._defaults.keyword).replace(/[%]/g,' ');
                    this._currentPage = window._defaults.pageId;
                    //this._totalPages = this._searchResults.Pages;
                    
                }
              
              this.BindList(document.getElementById("section_items"),this._sectors,selectedSectors);
              this.BindList(document.getElementById("category_items"),this._categories,selectedCategories);
              //this.BindList(document.getElementById("subject_items"),this._subjects,selectedSubjects);
              
              var backRef = this;
              document.getElementById("apply_filter").onclick = function(){
                backRef._currentPage = 0;
                backRef.CommitSearch.call(backRef);
                document.getElementById("search_panel").style.display = "none";
                document.getElementById("category_selection_container").style.display = "none";
              }
              
              this.CommitSearch();
           }
        }
        
        this.Select = function(id){
            document.getElementById("comment_panel").style.display = "block";
            this.SelectFilter(this._filters[id].Control);
        }
      
        this.CommitSearch = function(dir,flip){
        this.ProcessResults(getSearchResultsObj(),false,0)
            // alert(this._firstPage);
             //panel = document.getElementById("flipping_panel").style.display = "none";
             var keyword = document.getElementById("filter_keyword").value;
             if (keyword == null) keyword = "";
             keyword=keyword.replace(/[ ]/g,'%');
             var selectedValues = this.GetSelected();
             var backRef = this;
             
             if(this._firstTime)   
                { 
                    this._communicator.StartRefresh("...ןעוט"); 
                  this._firstPage = this._currentPage;  
                }
             else              
                this._communicator.StartRefresh("...שופיח תואצות ןנסמ");
             this._communicator.Execute("getSearchResults",{Randomize:selectedValues.AllSelected, ItemsPerPage:this._itemsPerPage,PageID: this._currentPage,Keyword:keyword,Subjects:selectedValues.Subjects.join(","), Categories:selectedValues.Categories.join(","), Sectors:selectedValues.Sectors.join(",") },function(obj){ backRef.ProcessResults.call(backRef,obj,flip,dir);});
        }
        
         
        this.ProcessResults = function(obj,flip,dir){
            panel = document.getElementById("flipping_panel").style.display = "block";
            this._searchResults = obj;
            this._currentPage=this._searchResults.CurrentPage
            //this._communicator.Refresh(this._searchResults.Results);
            var backRef = this;
            var panel = document.getElementById("paging_panel");
            panel.innerHTML = "";
            panel.style.display = "none";
            
            var nextLink = document.createElement("A");
            nextLink.innerHTML = "הבא";
            nextLink.href = "javascript:void(0);";
            nextLink.onclick = function() {
                backRef._currentPage++;
                backRef.CommitSearch();
            }
            
            var previousLink = document.createElement("A");
            previousLink.innerHTML = "הקודם";
            previousLink.href = "javascript:void(0);";
            previousLink.onclick = function() {
                backRef._currentPage--;
                backRef.CommitSearch();
            }

            var pager = new Pager(10,this._searchResults.Pages,this._searchResults.CurrentPage);
            
            if(this._searchResults.Pages>1 && this._currentPage!=0) panel.appendChild(previousLink);
            var spanElement = document.createElement("SPAN");
            spanElement.className = "pageNumbers"
            //for(var c=this._searchResults.Pages;c>0;c--){
            for(var c=pager.firstPageNum+1;c<=pager.lastPageNum;c++){
                var newLink = document.createElement("A");
                newLink.innerHTML = c;
                newLink.href = "javascript:void(0);";
                newLink.setAttribute("pageid",c);
                newLink.onclick = function() {
                    backRef._currentPage = this.getAttribute("pageid")-1;
                    backRef.CommitSearch();
                }
                
                if((c-1)==this._currentPage) newLink.className="selected";
                
                spanElement.appendChild(newLink);
            }
           
            panel.appendChild(spanElement);
            if(this._searchResults.Pages>1 && this._currentPage!=(this._searchResults.Pages-1)) panel.appendChild(nextLink);
             // flipping panel
            panel = document.getElementById("flipping_panel");
            panel.innerHTML = "";
            
            var previousImg = document.createElement("IMG");
            previousImg.src = "Images/Previous_inv.gif";
            previousImg.align = "absmiddle";
            previousImg.style.cursor = "pointer";
            previousImg.onclick = function(){
                backRef._currentPage--;
                backRef.CommitSearch();
                getFlashObject("Results_Grid").getCurrentValues(backRef._currentPage, backRef._searchResults.Rows);
            }
            
            var nextImg = document.createElement("IMG");
            nextImg.src = "Images/Next_inv.gif";
            nextImg.align = "absmiddle";
            nextImg.style.cursor = "pointer";
            nextImg.onclick = function(){
                backRef._currentPage++;
                backRef.CommitSearch();
                getFlashObject("Results_Grid").getCurrentValues(backRef._currentPage, backRef._searchResults.Rows);
            }
            
            if(this._searchResults.Pages>1 && this._currentPage!=0) panel.appendChild(previousImg);
            //panel.insertData(0,"<span>"+(this._currentPage * this._itemsPerPage + 1) + "-" + (Math.min(this._searchResults.Rows,(this._currentPage+1) * this._itemsPerPage))+"</span> מתוך "+this._searchResults.Rows);
            var element = document.createElement("SPAN");
         
            element.innerHTML = "&nbsp;" + document.getElementById("values_label").value + "&nbsp;" + (Math.min(this._searchResults.Rows,(this._currentPage+1) * this._itemsPerPage)) + "-" + (this._currentPage * this._itemsPerPage + 1) + " " + document.getElementById("mitoch_label").value+ " "+this._searchResults.Rows + "&nbsp;";
            panel.appendChild(element);
            //panel.innerHTML = "<span>"+(this._currentPage * this._itemsPerPage + 1) + "-" + (Math.min(this._searchResults.Rows,(this._currentPage+1) * this._itemsPerPage))+"</span> מתוך "+this._searchResults.Rows;
            if(this._searchResults.Pages>1 && this._currentPage!=(this._searchResults.Pages-1))  panel.appendChild(nextImg);
            if (flip != undefined) {this._communicator.itemNav(dir,flip);}
            this.setIndex();
            this._firstTime=false;
            setFooter()
        }
        
        this.BindList = function(panel, source, selectedArray){
            
            panel.innerHTML = "";
            
            for(var c=0;c<source.length;c++){
                var newItem = document.createElement("DIV");
                newItem.className = "searchPropertyDiv";
                var newItemCheck = document.createElement("DIV");
                var checkBox = document.createElement("INPUT");
                checkBox.type = "checkbox";
                checkBox.setAttribute("group",panel.id);
                checkBox.value = source[c].ID;
                if(source[c].CategoryID) checkBox.setAttribute("CategoryID",source[c].CategoryID);
                //checkBox.onclick = function() {  }
                //checkBox.checked = true;
                newItemCheck.appendChild(checkBox);
                newItemCheck.className = "searchPropertyCheckBoxDiv";
                var newItemCaption = document.createElement("DIV");
                newItemCaption.className = "searchPropertyCaptionDiv";
                newItemCaption.innerHTML = source[c].Name;
                newItem.appendChild(newItemCheck);
                newItem.appendChild(newItemCaption);
                panel.appendChild(newItem);
                if(selectedArray.length>0) 
                    checkBox.setAttribute("checked",selectedArray.isIn(source[c].ID.toString()));
                else
                    checkBox.setAttribute("checked",true);
            }
            
        }
        
        this.PopulateFilters = function(panel){
            
            var backRef = this;
            for(var c=0;c<this._filters.length;c++){
                var newFilter = document.createElement("DIV");
                newFilter.className = "searchFilterCaptionDiv";
                newFilter.innerHTML = this._filters[c].Name;
                newFilter.id = this._filters[c].ID;
                newFilter.onclick = function() { backRef.SelectFilter(this); }
                this._filters[c].Control = newFilter;
                var newSeparator = document.createElement("DIV");
                newSeparator.className = "searchFilterSeperatorDiv";
                //newSeparator.innerHTML = ">";
                panel.appendChild(newFilter);
                if(c<this._filters.length-1) panel.appendChild(newSeparator);
            } 
        }
        
        this.SelectFilter = function(obj){
            
            switch(obj.id){
                case "filter_sector":
                    document.getElementById("category_selection_container").style.display = "none";
                    document.getElementById("category_items").style.display = "none";
                    document.getElementById("section_items").style.display = "block";
                    document.getElementById("subject_items").style.display = "none";
                break;
                case "filter_category":
                    document.getElementById("category_selection_container").style.display = "none";
                    document.getElementById("category_items").style.display = "block";
                    document.getElementById("section_items").style.display = "none";
                    document.getElementById("subject_items").style.display = "none";
                break;
                case "filter_disable":
                    document.getElementById("category_items").style.display = "block";
                    document.getElementById("section_items").style.display = "block";             
                    document.getElementById("filter_keyword").value = "";
                    this.CheckAll(1);
                    this.CommitSearch();
                    document.getElementById("search_panel").style.display = "none";
                break;
                case "filter_subject":
                    ///alert(document.getElementById("subject_items").innerHTML);
                    var selectedValues = this.GetSelected();
                    
                    //var selectedSections = selectedValues.Sectors;
                    var selectedCategories = selectedValues.Categories;
                    //var selectedSubjects = selectedValues.Subjects;
                    
                    if(selectedCategories.length==0) return("false");
                    
                    var backRef = this;
                    var cs = document.getElementById("category_selection")
                    cs.innerHTML = "";
                    //document.getElementById("subject_items").innerHTML = "";

                    for (c=0;c<this._categories.length;c++){
                        
                        if(selectedCategories.isIn(this._categories[c].ID)){
                            var newOption = document.createElement("OPTION");
                            newOption.value = this._categories[c].ID;
                            newOption.innerText = this._categories[c].Name;
                            cs.appendChild(newOption);
                        }
                    }
                    
                    cs.onchange = function() {
                        var trayElements = document.getElementById("subject_items").children;
                        for(var c=0;c<trayElements.length;c++){
                            if(trayElements[c].firstChild.firstChild.getAttribute("CategoryID")==cs[cs.selectedIndex].value) 
                                trayElements[c].style.display="block";
                            else
                                trayElements[c].style.display="none";
                        }
                    }
                    
                    //this._communicator.Execute("getSubjects", {Categories:selectedCategories.join(","),Sectors:selectedSections.join(",")},function(obj){ obj.pop(); backRef.BindList(document.getElementById("subject_items"),obj,selectedSubjects); cs.onchange.call();});
                    cs.onchange.call();
                    
                    document.getElementById("category_selection_container").style.display = "block";
                    document.getElementById("category_items").style.display = "none";
                    document.getElementById("section_items").style.display = "none";
                    document.getElementById("subject_items").style.display = "block";
                
                break;

            }
            
            for(var c=0;c<this._filters.length;c++)
                this._filters[c].Control.className = "searchFilterCaptionDiv";
            
            obj.className = "searchFilterCaptionSelectedDiv";
        }

        this.Initialize = function() {
            var backRef = this;
             
                        
            if(window._sectors && window._categories){
                this._sectors = window._sectors;
                this._categories = window._categories;
                this.FinishInitialization();
            } else {
                this._communicator.Execute("getSectors",{},function(obj,status){ obj.pop(); backRef._sectors = obj; backRef.FinishInitialization(); });
                this._communicator.Execute("getCategories",{},function(obj){ obj.pop(); backRef._categories = obj; backRef.FinishInitialization(); });
            }
            //this._communicator.Execute("getSubjects2",{},function(obj){ obj.pop(); backRef._subjects = obj; backRef.FinishInitialization(); });
           
            //backRef._sectors = [{ID:1, Name:'ניסיון' },{ID:2, Name:'שנית'},{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' },{ID:3, Name:'ניסיון' }];
            //backRef._categories = [{ID:1, Name:'ניסיון' },{ID:2, Name:'שנית'},{ID:3, Name:'ניסיון' }];
                        
            this.PopulateFilters(document.getElementById("filter_selection"));
            this.SelectFilter(this._filters[0].Control);
            document.getElementById("command_panel").setAttribute("ref",this);
            document.getElementById("filter_bar").setAttribute("ref",this);
            document.getElementById("close_btn").onclick = function(){ document.getElementById("search_panel").style.display = "none"; };
            document.getElementById("add_comment").onclick = function() { backRef.Select(0); }
                     
        }
        
        this.setIndex = function() {
           var backref = this;
           var num = document.getElementById("index").value * 1;
           var currEntry = num + (this._currentPage * 36);
           var totalEntries = this._searchResults.Rows;
           if (this._firstTime) {
                panel = document.getElementById("pageNavMin");
                panel.innerHTML = "";
           
                var previousImg = document.createElement("IMG");
                previousImg.src = "images/subject/prev.gif";
                previousImg.align = "absmiddle";
                previousImg.style.cursor = "pointer";
                previousImg.onclick = function(){
                    if (num == 1) {
                      backref._currentPage = backref._firstPage-1;
                      backref.CommitSearch("p",true);
                    }
                    else if (backref._firstPage != backref._currentPage) {
                      backref._currentPage = backref._firstPage;
                      backref.CommitSearch("p",false);
                    }
                    else{
                      backref._communicator.itemNav("p",false);
                    }
                }
                
                var nextImg = document.createElement("IMG");
                nextImg.src = "images/subject/next.gif";
                nextImg.align = "absmiddle";
                nextImg.style.cursor = "pointer";
                nextImg.onclick = function(){
                    if (num == 36) {
                          backref._currentPage = backref._firstPage+1;
                          backref.CommitSearch("n",true);
                    }
                    else if (backref._firstPage != backref._currentPage) {
                      backref._currentPage = backref._firstPage;
                      backref.CommitSearch("n",false);
                    }else{
                        backref._communicator.itemNav("n",false);
                    }
                }
                
                if(currEntry>1) panel.appendChild(previousImg);
                var element = document.createElement("a");
                element.innerHTML = "&nbsp;&nbsp;" + document.getElementById("item_label").value + " " + currEntry + " " + document.getElementById("mitoch_label").value + " " + totalEntries + "&nbsp;&nbsp;";
                element.setAttribute("id","pageNavLabel");
                panel.appendChild(element);
                if(currEntry<totalEntries)  panel.appendChild(nextImg);
                getFlashObject("Results_Grid").getItemID(document.getElementById("itemID").value);
                getFlashObject("Results_Grid").getCurrentValues(this._currentPage, totalEntries);
           }
        }
        
        this.GetSelected = function() {
            
            var inputElements = document.getElementsByTagName("INPUT");
            var selectedSections = new Array();
            var selectedCategories = new Array();
            var selectedSubjects = new Array();
            var selectedCounter = 0;
            var validControls = 0;
            
            for (var c=0;c<inputElements.length;c++){
                if(inputElements[c].getAttribute("group")=="section_items") { validControls++; if(inputElements[c].checked) { selectedSections.push(inputElements[c].value); selectedCounter++ }}
                if(inputElements[c].getAttribute("group")=="category_items") { validControls++; if(inputElements[c].checked) { selectedCategories.push(inputElements[c].value); selectedCounter++ }}
                if(inputElements[c].getAttribute("group")=="subject_items") { validControls++; if(inputElements[c].checked) { selectedSubjects.push(inputElements[c].value); selectedCounter++ }}
            }
            
            return({AllSelected:(selectedCounter==validControls), Sectors:selectedSections,Categories:selectedCategories,Subjects:selectedSubjects});
        }
        
        this.Initialize();
    }
    
function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
  alert('Query Variable ' + variable + ' not found');
}
function getSearchResults(){

   var s=document.getElementById("searchResults").value
   
   return eval("["+s+"]")[0].Results
    
}
function getSearchResultsObj(){
var s=document.getElementById("searchResults").value
    return eval("["+s+"]")[0]
}
    