﻿// SitePartFilter enumeration
function SitePartFilter(value) {
    this._value = value;
}

SitePartFilter.prototype.toString = function() {
    return this._value;
};

SitePartFilter.ALL = new SitePartFilter(0);
SitePartFilter.LOKET = new SitePartFilter(1);
SitePartFilter.ORGANISATIE = new SitePartFilter(2);
SitePartFilter.PLAYGROUND = new SitePartFilter(3);


function SearchHelper() {
    this.SLHost = null;
}

// Members
SearchHelper.STATE_COOKIE = "TrudoSearchState";
SearchHelper._instance = null; // Will contain singleton instance to this class
SearchHelper.prototype._SLHost = null;
SearchHelper.prototype._searchInput = null;
SearchHelper.prototype._infoLabel = null;
SearchHelper.prototype._prevLink = null;
SearchHelper.prototype._nextLink = null;
SearchHelper.prototype._filterId = "";
SearchHelper.prototype._currentPage = 0;
SearchHelper.prototype._numResults = 0;
SearchHelper.prototype._totalResults = 0;
SearchHelper.prototype._filter = SitePartFilter.ALL;

// Returns a singleton instance for this class
SearchHelper.getInstance = function() {
    if (SearchHelper._instance == null) {
        SearchHelper._instance = new SearchHelper();
    }

    return SearchHelper._instance;
}

// Does the actual initilization, params is a JS object containing all variables
// and their values needed by the SearchHelper.
SearchHelper.prototype.init = function(params) {
    for (var param in params) {
        var value = params[param];
        switch (param) {
            case "SLHostClientId":
                this._SLHost = document.getElementById(value);
                break;
            case "SearchInputClientId":
                this._searchInput = document.getElementById(value);
                break;
            case "FilterClientId":
                this._filterId = value;
                break;
            case "InfoLabelClientId":
                this._infoLabel = document.getElementById(value);
                break;
            case "PrevLinkClientId":
                this._prevLink = document.getElementById(value);
                break;
            case "NextLinkClientId":
                this._nextLink = document.getElementById(value);
                break;
            case "TotalResults":
                this._totalResults = value;
                break;
            case "ResultsPerPage":
                this._numResults = value;
                break;
            case "CurrentFilter":
                this._filter = value;
                break;
            case "CurrentPage":
                this._currentPage = value;
                break;
        }
    }

    for (var i = 0; document.getElementById(this._filterId + "_" + i) != null; i++) {
        var input = document.getElementById(this._filterId + "_" + i);

        if (input == null) {
            // Should not be possible
            continue;
        }

        // Create holder for pretty checkbox images
        var repl = document.createElement("div");
		var label = input.parentNode.getElementsByTagName("label")[0];
		
        repl.className = input.checked ? "state-checked" : "state-unchecked";

        input.className += " radio-replaced"

        // Set pointers
        input.replaceNode = repl;
        repl.inputNode = input;
		label.inputNode = input;

        Event.attach(repl, "click", this.clickFilter);
        Event.attach(label, "click", this.clickFilter);

        // Insert before real input
        input.parentNode.insertBefore(repl, input);
    }

    // Hook up onchange events to filter
    for (var i = 0; document.getElementById(this._filterId + "_" + i) != null; i++) {
        Event.attach(document.getElementById(this._filterId + "_" + i), "click", function() {
            SearchHelper.getInstance().updateFilter(); 
        });
    }

    //    if (this._searchInput != null) {
    //        new AutoCompleteTextField(this._searchInput, new SlideAnim());
    //    }
}

SearchHelper.prototype.clickFilter = function(e) {

            if (!e) var e = window.event;
            var target = null;
            if (e.target) target = e.target;
            else if (e.srcElement) target = e.srcElement;

            if (target && target.inputNode) {
                if (!target.inputNode.checked) {
                    target.inputNode.checked = !target.inputNode.checked;
                    SearchHelper.getInstance().updateFilter();
                }
                //                target.className = target.inputNode.checked ? "state-checked" : "state-unchecked";
            }
}


// This function is called whenever the user changes the filter settings. The
// ApplyFilter on the SilverLight search object is called such that it can update
// which results are visible.
SearchHelper.prototype.updateFilter = function() {
    if ((this._SLHost == null) || (this._SLHost.Content == null)) {
        return;
    }

    for (var i = 0; document.getElementById(this._filterId + "_" + i) != null; i++) {
        var input = document.getElementById(this._filterId + "_" + i);
        if (input.checked) {
            var status = this._SLHost.Content.navObj.ApplyFilter(i);
            this._currentPage = status.CurrentPage;
            this._totalResults = status.TotalResults;
            this._filter = i;
            this.refreshInfo();
            this.updateCookie();
        }

        // Maintain pretty radio button state
        var replaceCheck = input.replaceNode;
        if (replaceCheck) {
            replaceCheck.className = input.checked ? "state-checked" : "state-unchecked";
        }
    }
}

// Tells the SilverLight search object to navigate to the previous page
SearchHelper.prototype.gotoPreviousPage = function() {
    if ((this._SLHost != null) && (this._SLHost.Content != null)
        && (this._currentPage > 0)) {
        this._currentPage--;
        this._SLHost.Content.navObj.SetPage(this._currentPage);

        this.refreshInfo();
        this.updateCookie();

    }
}

// Tells the SilverLight search object to navigate to the next page
SearchHelper.prototype.gotoNextPage = function() {
    if ((this._SLHost != null) && (this._SLHost.Content != null) && 
        (this._currentPage < this.getLastPage())) {
        this._currentPage++;
        this._SLHost.Content.navObj.SetPage(this._currentPage);

        this.refreshInfo();
        this.updateCookie();
    }
}

// Returns the last page of the search results (calculated based on the total
// number of results and amount of results displayed per page).
SearchHelper.prototype.getLastPage = function() {
    return Math.floor((this._totalResults - 1) / this._numResults);
}

// Refreshes the info displayed in the header (like number of results, current page,
// etc..).
SearchHelper.prototype.refreshInfo = function() {
    if (this._infoLabel == null) {
        return;
    }

    var resultsLabel = document.getElementById("trudo-searchheader-resultslbl");
    var noResultsLabel = document.getElementById("trudo-searchheader-noresultslbl");

    if (resultsLabel != null) {
        resultsLabel.style.display = this._totalResults > 1 ? 'block' : 'none';
    }

    if (noResultsLabel != null) {
        noResultsLabel.style.display = this._totalResults > 0 ? 'none' : 'block';
    }

    if (this._totalResults > 0) {
        var firstResult = document.getElementById("trudo-searchheader-fres");
        var lastResult = document.getElementById("trudo-searchheader-lres");
        var totalResult = document.getElementById("trudo-searchheader-total");

        // Disable/enable previous and next links depending on current page
        if (firstResult != null) {
            firstResult.innerHTML = this._currentPage * this._numResults + 1;
        }

        if (lastResult != null) {
            lastResult.innerHTML = Math.min((this._currentPage + 1) * this._numResults, this._totalResults);
        }

        if (totalResult != null) {
            totalResult.innerHTML = this._totalResults;
        }
    }

    // Disable/enable previous and next links depending on current page
    if (this._prevLink != null) {
        var className = this._prevLink.className.replace("asf-disabled", "")
        if ((this._currentPage == 0) || (this._totalResults == 0)) {
            className += " asf-disabled";
        }

        this._prevLink.className = className;
    }

    if (this._nextLink != null) {
        var className = this._nextLink.className.replace("asf-disabled", "")
        if ((this._currentPage == this.getLastPage()) || (this._totalResults == 0)) {
            className += " asf-disabled";
        }

        this._nextLink.className = className;
    }
}

// Resets the cookie using current values
SearchHelper.prototype.updateCookie = function() {
    var value = "{\"CurrentPage\": " + this._currentPage + ", \"TotalResults\": " +
        this._totalResults + ", \"CurrentFilter\": " + this._filter  + "}";
    document.cookie = SearchHelper.STATE_COOKIE + "=" + value + "; path=/";
}

// Returns the reference to the search button
SearchHelper.prototype.getSearchButton = function() {
    return this._searchButton;
}

// Small helper class which provides a cross-browser compatible function to
// attach events to dom elements.
function Event() {
}

Event.attach = function(obj, evType, fn, scope) {
    var scopedEventHandler = scope ? function(e) { fn.apply(scope, [e]); } : fn;

    if (obj.addEventListener) {
        obj.addEventListener(evType, scopedEventHandler, false);
        return true;
    } else if (obj.attachEvent) {
        var r = obj.attachEvent('on' + evType, scopedEventHandler);
        return r;
    } else {
        return false;
    }
}


// Handles OnClientDropDownOpening of the main search field.
// The dropdown should only be visible if the input size is at least 2.
function MinInputTest(sender, args) {
    if (sender.get_text().length < 2) {
        var ev = args.get_domEvent();
        if (ev == null || args.get_domEvent().target.className == "rcbInput") {
            args.set_cancel(true);
        }
    }
}


function ReApplyFilter(sender, args) {
    if (sender) {
        RefreshMatches(sender);
    }
}

function RefreshMatches(comboBox) {
    comboBox.get_items().forEach(function(item) {
        var match = item.get_comboBox().get_text().toLowerCase();
        if (item.get_text().toLowerCase().indexOf(match) == 0) {
            item.set_text("<em>" + item.get_text().substring(0, match.length) +
                "</em>" + item.get_text().substring(match.length));
        }
        else {
            item.hide();
        }
    });
}

// Handles the OnClientLoad of the main search field.
// Attaches an event handler to the keyup event of the input element. This handler
// will force the dropdown to close whenever the input size < 2.
function AttachMinInputTest(sender, args) {
    trudoSearchCombo = sender;
    trudoSearchInput = sender.get_inputDomElement();

    trudoSearchCombo.set_enableTextSelection(false);

    Event.attach(sender.get_inputDomElement(), "keyup", function(e) {
        if (e.keyCode == 13) {
            var idv = trudoSearchCombo.get_id();
            __doPostBack(idv.substr(0, idv.lastIndexOf('_')).replace(/_/g, '$'), "");
        }

        if (trudoSearchInput.value.length > 1) {
            if (!trudoSearchCombo.get_dropDownVisible()) {
                trudoSearchCombo.showDropDown();
            }

            //trudoSearchNoResults.style.display = trudoSearchCombo.get_visibleItems().length == 0 ? "block" : "none";

            if (trudoSearchCombo.get_visibleItems().length == 0) {
                trudoSearchCombo.hideDropDown();
                //trudoSearchCombo._getAnimationContainer().style.display = "none";
            }
        }
        else {
            if (trudoSearchCombo.get_dropDownVisible()) {
                trudoSearchCombo.hideDropDown();
            }
        }
    });
}

//function AutoCompleteTextField(textField, anim) {
//    this._field = textField;
//    this._listHolder = document.createElement("div");
//    this._list = document.createElement("ul");
//    this._listHolder.appendChild(this._list);

//    document.body.appendChild(this._listHolder);

//    // temp style
//    this._field.style.marginLeft = "100px"
//    this._list.style.border = "1px solid #323232";

//    var pos = GetPos(this._field);
//    var dim = GetDim(this._field);


//    with (this._listHolder.style) {
//        background = "white";

//        position = "absolute";
//        top = (pos.y + dim.height) + "px";
//        left = pos.x + "px";
//        width = dim.width + "px";
//        display = "none";
//    }
//    
//    

//    this._anim = anim;
//    if (anim == null) {
//        this._anim = new InstantShowAnim();
//    }

//    this._anim.setObject(this._listHolder);

//    this.attachEvents();
//}

//AutoCompleteTextField.prototype._field = null;
//AutoCompleteTextField.prototype._anim = null;
//AutoCompleteTextField.prototype._list = null;
//AutoCompleteTextField.prototype._listHolder = null;
//AutoCompleteTextField.MIN_CHARS = 2;
//AutoCompleteTextField.AUTOCOMPLETE_VALUES = ["Huren", "Huur", "Huurovereenkomst",
//    "Huuba", "Huuuuuuuuuuuurrrrr"];


//AutoCompleteTextField.prototype.attachEvents = function() {
//    Event.attach(this._field, "keyup", function() {
//        if (this._field.value.length >= AutoCompleteTextField.MIN_CHARS) {
//            this.filterResults();

//            if (this._list.childNodes.length == 0) {
//                this.addItem("Geen resultaten");
//            }

//            this._anim.show();
//        }
//    }, this);
//}

//AutoCompleteTextField.prototype.filterResults = function() {
//    // Clear the list
//    this.clearList();

//    var values = AutoCompleteTextField.AUTOCOMPLETE_VALUES;
//    var re = new RegExp("^" + this._field.value, "i");
//    for (var i = 0; i < values.length; i++) {
//        var value = values[i];
//        if (value.match(re)) {
//            this.addItem(value);
//        }
//    }
//}

//AutoCompleteTextField.prototype.clearList = function() {
//    while (this._list.hasChildNodes()) {
//        this._list.removeChild(this._list.firstChild);
//    }
//}

//AutoCompleteTextField.prototype.addItem = function(value) {
//    var item = document.createElement("li");
//    item.appendChild(document.createTextNode(value));
//    this._list.appendChild(item);

//    item.style.height = "20px";
//}

//function GetPos(obj) {
//    var p = { x: 0, y: 0 };
//    if (obj == null) return p;

//    for (; obj != null; obj = obj.offsetParent) {
//        p.x += obj.offsetLeft;
//        p.y += obj.offsetTop;
//    }

//    return p;
//}

//function GetDim(obj) {
//    if (obj == null) {
//        return { width: 0, height: 0 };
//    }

//    // Todo most likely wont work in all browsers
//    return { width: obj.offsetWidth, height: obj.offsetHeight };
//}

//function ShowAnim() {
//}

//ShowAnim.HIDE_DELAY = 1000; // Numer of ms after which to hide the shown container
//ShowAnim._timeout = null;
//ShowAnim._isVisible = null;

//ShowAnim.prototype.show = function() {
//    var scope = this;

//    if (this._timeout != null) {
//        clearTimeout(this._timeout);
//    }

//    this._isVisible = true;
//    this._timeout = setTimeout(function(scope) { scope.hide() }, ShowAnim.HIDE_DELAY, scope);
//}

//ShowAnim.prototype.hide = function() {
//    this._isVisible = false;
//    this._timeout = null;
//}

//ShowAnim.prototype.setObject = function(obj) {
//    this._obj = obj;
//}

//function InstantShowAnim() {
//    InstantShowAnim.baseConstructor.call();
//}

//extend(InstantShowAnim, ShowAnim);

//InstantShowAnim.prototype.show = function() {
//    InstantShowAnim.superClass.show.apply(this);
//    this._obj.style.display = "block";
//}

//InstantShowAnim.prototype.hide = function() {
//    InstantShowAnim.superClass.hide.apply(this);
//    this._obj.style.display = "none";
//}

//function SlideAnim() {
//    SlideAnim.baseConstructor.call();
//}

//SlideAnim.SLIDE_DURATION = 100;
//SlideAnim.SLIDE_STEPS = 10;
//SlideAnim.prototype.currentHeight = 0;
//SlideAnim.prototype.targetHeight = 0;
//SlideAnim.prototype._interval = null;
//SlideAnim.prototype._currentStep = 0;
//SlideAnim.prototype._isSliding = false;


//extend(SlideAnim, ShowAnim);

//SlideAnim.prototype.show = function() {
//    //var dim = GetDim(this._obj);
//    // TODO betere manier om height the krijgen

//    this.targetHeight = this._obj.firstChild.childNodes.length * 20;

//    if (this._isVisible) {
//        // If current height is larger than target height -> adjust
//        this._obj.style.height = this.targetHeight + "px";
//    } else {
//        // Start sliding
//        this.currentHeight = 0;
//        this._obj.style.height = "0px";
//        this._obj.style.display = "block";
//        this._isSliding = true;
//        this._currentStep = 0;
//        var scope = this;

//        this._interval = setInterval(function(scope) { scope.slideStep() }, SlideAnim.SLIDE_DURATION / SlideAnim.SLIDE_STEPS, scope);
//    }

//    SlideAnim.superClass.show.apply(this);
//}

//SlideAnim.prototype.hide = function() {
//    InstantShowAnim.superClass.hide.apply(this);
//    this._obj.style.display = "none";
//    this.currentHeight = 0;
//    this.targetHeight = 0;
//}

//SlideAnim.prototype.slideStep = function() {
//    this.currentHeight += this.targetHeight / Math.pow(2, this._currentStep + 1);
//    
//    // Last step set to full height
//    if (this._currentStep == SlideAnim.SLIDE_STEPS - 1) this.currentHeight = this.targetHeight;

//    this._obj.style.height = this.currentHeight + "px";

//    this._currentStep++;

//    if (this._currentStep >= SlideAnim.SLIDE_STEPS) {
//        clearInterval(this._interval);
//        this._isSliding = false;
//    }
//}


//function extend(subClass, baseClass) {
//    function inheritance() { }
//    inheritance.prototype = baseClass.prototype;

//    subClass.prototype = new inheritance();
//    subClass.prototype.constructor = subClass;
//    subClass.baseConstructor = baseClass;
//    subClass.superClass = baseClass.prototype;
//}


    
