﻿// 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._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:document.getElementById("sector_label").value,ID:'filter_sector'},{Name:document.getElementById("catagory_label").value,ID:'filter_category'},{Name:document.getElementById("cancelfilter_label").value,ID:'filter_disable'}];
          this._filters = [{Name:document.getElementById("sector_label").value,ID:'filter_sector'}]//,{Name:document.getElementById("catagory_label").value,ID:'filter_category'}];
        this._searchResults = null;
        this._currentPage = 0;
        this._itemsPerPage = 36;
        
        Array.prototype.isIn = function(element){
            var result = false;
            for(var c=0;c<this.length;c++)
                if(this[c]==element) result=true;
            
            return(result);
        }
        
        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.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.visiblity = "none";
                }

                this.CommitSearch();


            }
        }
        
        this.Select = function(id){
       
            document.getElementById("search_panel").style.display = "block";
            this.SelectFilter(this._filters[id].Control);
        }

        this.CommitSearch = function() {
           
            var keyword = document.getElementById("filter_keyword").value;
            if (keyword == null) keyword = "";
            keyword = keyword.replace(/[ ]/g, '%');
            var selectedValues = this.GetSelected();
            var backRef = this;
            if (document.getElementById("sectors_display") != null) {
                document.getElementById("sectors_display").innerHTML = this.GetSelectedString(this._sectors, selectedValues.Sectors);
            }
            if (document.getElementById("keywords_display") != null) {
                if (keyword == "") {
                    document.getElementById("keywords_display").innerHTML = "לא נבחרו";
                } else {
                    document.getElementById("keywords_display").innerHTML = keyword;
                }
            }
           

            if (this._firstTime) {
                this._communicator.StartRefresh("...ןעוט"); this._firstTime = false;
            } else {
                this._communicator.StartRefresh("...שופיח תואצות ןנסמ");
            }

            if (document.getElementById("topRanked")) {

                this._communicator.Execute("getTopRanked", { sLanguage: document.getElementById("sLanguage").value }, function(obj) { backRef.ProcessResults.call(backRef, obj); });
            } else {

                this._communicator.Execute("getSearchResults2", { Randomize: true, 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); });
            }
        }
        
         
        this.ProcessResults = function(obj){
            
            this._searchResults = obj;
            this._communicator.Refresh(this._searchResults.Results);
            var backRef = this;
            var panel = document.getElementById("paging_panel");
            panel.innerHTML = "";
            
            var nextLink = document.createElement("A");
            nextLink.innerHTML = document.getElementById("next_label").value;
            nextLink.href = "javascript:void(0);";
            nextLink.onclick = function() {
                backRef._currentPage++;
                backRef.CommitSearch();
            }
            
            var previousLink = document.createElement("A");
            previousLink.innerHTML = document.getElementById("prev_label").value;
            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 = "<span>" +c + "</span>";
                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);
            
            panel = document.getElementById("flipping_panel");
            panel.innerHTML = "";
            
            var previousImg = document.createElement("IMG");
            previousImg.src = "Images/Previous.gif";
            previousImg.align = "absmiddle";
            previousImg.style.cursor = "pointer";
            previousImg.onclick = function(){
                backRef._currentPage--;
                backRef.CommitSearch();
            }
            
            var nextImg = document.createElement("IMG");
            nextImg.src = "Images/Next.gif";
            nextImg.align = "absmiddle";
            nextImg.style.cursor = "pointer";
            nextImg.onclick = function(){
                backRef._currentPage++;
                backRef.CommitSearch();
            }
            
           // 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 = document.getElementById("values_label").value + "&nbsp;" + "<span class='big'>"+(Math.min(this._searchResults.Rows,(this._currentPage+1) * this._itemsPerPage)) + "-" + (this._currentPage * this._itemsPerPage + 1) +"</span>&nbsp" + document.getElementById("mitoch_label").value + " " + this._searchResults.Rows;
            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);
            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.checked = selectedArray.isIn(source[c].ID.toString())
                    //checkBox.setAttribute("Checked", selectedArray.isIn(source[c].ID.toString()));
                } else {
                checkBox.checked = true
                    //checkBox.setAttribute("Checked", false);
                }
            }

        }
        
        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 "cancel_filter2":
                    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";
                    return
                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){ 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("filter_by_sector").onclick = function() { backRef.Select(0); }
            
            document.getElementById("filter_by_category").onclick = function() { backRef.Select(1); }
            
            document.getElementById("mark_all").onclick = function() { backRef.CheckAll(1); }
            document.getElementById("mark_none").onclick = function() { backRef.CheckAll(0); }
            document.getElementById("cancel_filter2").onclick = function() { backRef.SelectFilter(document.getElementById('cancel_filter2')); };
            
        }
        
        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.GetSelectedString = function(nameArray, selArray) {

            var returnString = ""
            if (selArray.length == nameArray.length) return "כל הקטגוריות"
            for (var i = 0; i < selArray.length; i++) {
                returnString += nameArray[selArray[i] - 1].Name + ","
            }
            returnString = returnString.substr(0, returnString.length - 1);
            return returnString;
        }
        
        this.Initialize();
       
    }
    
    