var BoardSearch = Class.create();
BoardSearch.prototype = {
    initialize: function(boardSearch) {
        if (boardSearch) {
            this.name = boardSearch.name;
            this.path = boardSearch.path;
            this.sortBy = boardSearch.sortBy;
            this.sortOrder = boardSearch.sortOrder;
            this.options = boardSearch.options;
            this.searchType = boardSearch.searchType;
            this.blogsOnly = boardSearch.blogsOnly;	
	} else {
            this.name = "";
            this.path = "";
            this.sortBy = "";
            this.sortOrder = "";
            this.options = "";
            this.searchType = "";
	    	this.blogsOnly = "";
        }
    },
    getValuesFromForm: function(formName) {
        var input;
        var form = $(formName);
        if (form) {
            input = form['name'];
            if (input) {
                this.name = $(input).getValue();
            }
            input = form['path'];
            if (input) {
                this.path = $(input).getValue();
            }
            input = form['sortBy'];
            if (input) {
                this.sortBy = $(input).getValue();
            }
            input = form['sortOrder'];
            if (input) {
                this.sortOrder = $(input).getValue();
            }
            input = form['options'];
            if (input) {
                this.options = $(input).getValue();
            }
            input = form['searchType'];
            if (input) {
                this.searchType = $(input).getValue();
            }
		    input = form['blogsOnly'];
		    if(input){
		    	this.blogsOnly = $(input).getValue();
		    }
        }
    },
    getPathLabel: function(formName) {
        var input;
        var label = '';
        var form = $(formName);
        if (form) {
            input = $(form['path']);
            if (input) {
                label = input.getValue();
                var options = input.options;
                for (var i = 0; i < options.length; i++) {
                    var option = $(options[i]);
                    if (label == option.value) {
                        label = option.text;
                        break;
                    }
                }
            }
        }
        return label;
    },
    getValuesFromOptions: function(opts) {
        var value;
        if (opts) {
            value = opts['name'];
            if (value) {
                this.name = value;
            }
            value = opts['path'];
            if (value) {
                this.path = value;
            }
            value = opts['sortBy'];
            if (value) {
                this.sortBy = value;
            }
            value = opts['sortOrder'];
            if (value) {
                this.sortOrder = value;
            }
            value = opts['options'];
            if (value) {
                this.options = value;
            }
            value = opts['searchType'];
            if (value) {
                this.searchType = value;
            }
	    value = opts['blogsOnly'];
	    if(value){
	    	this.blogsOnly = value;
	    }
        }
    }
};

var BoardSearchResource = Class.create();
BoardSearchResource.prototype = {
    initialize: function(opts) {
        opts = opts ? opts : {};
        var prefix = opts['prefix'];
        this.prefix = prefix ? prefix : "boards";
        var formName = opts['formName'];
        this.formName = formName ? formName : this.prefix + 'Form';
        this.pager = new NumberListPager(this.prefix, this);
        this.boardSearch = new BoardSearch();
        this.boardSearch.getValuesFromOptions(opts);
        this.boards = new Array();
        this.boardGroups = new Array();
	this.urlPrefix = "/search";
    },
// fetch
    fetch: function() {
        var myAjax = new Ajax.Request(
                this.urlPrefix, {
            method: 'get',
            parameters: this.getParams(),
            requestHeaders: ['Accept', 'application/json'],
            onSuccess: this.fetchSuccess.bind(this)});
        return true;
    },
    fetchSuccess: function(response) {
        var boardSearchResource = eval('(' + response.responseText + ')');
        this.pager = new NumberListPager(this.prefix, this, boardSearchResource.pager);
        this.boardSearch = new BoardSearch(boardSearchResource.boardSearch);
        this.boards = boardSearchResource.boards;
	this.boardGroups = boardSearchResource.boardGroups;
        this.fetchCallback();
    },
    fetchCallback: function() {
        this.doRender();
    },
// doUpdate & doRender
    doUpdate: function(e) {
        this.boardSearch.getValuesFromForm(this.formName);
        if (this.boardSearch.name.length != 1) {
            this.beforeUpdateCallback();
            this.fetch();
            if (e) {
                if (e.preventDefault) {
                    e.preventDefault();
                }
                e.returnValue = false;
            }
        }
        return false;
    },
    doRender: function() {
        this.pager.doRender();
        var boardItem;
        var boardItemLink;
        //var boardItemCreated;
        var text;
        var boardsListContainer = $(this.prefix + 'ListContainer');
        var oldBoardsList = $(this.prefix + 'List');
        var newBoardsList = $(document.createElement("ul"));
        newBoardsList.setAttribute("id", this.prefix + "List");
	var group;
	if(this.boardSearch.blogsOnly=='true'){
		group = this.boardGroups;
	}else{
		group = this.boards;
	}
        group.each(function(board) {
        boardItem = $(document.createElement('li'));
        boardItemLink = $(document.createElement('a'));
        boardItemLink.setAttribute("href", "/" + board.path);
        boardItemLink.appendChild(document.createTextNode(board.name));
        /*if(this.boardSearch.blogsOnly){
	        boardItemCreated = $(document.createElement('span'));
	        boardItemCreated.appendChild(document.createTextNode(board.created));
	        boardItemLink.appendChild(boardItemCreated);
		}*/
        boardItem.appendChild(boardItemLink);
        newBoardsList.appendChild(boardItem);
        });

        boardsListContainer.replaceChild(newBoardsList, oldBoardsList);
        this.afterUpdateCallback();
    },
    beforeUpdateCallback: function() {
        var resultsIntro = $('resultsIntro');
        if (resultsIntro) {
            resultsIntro.innerHTML = '<img src="/images/icons/updating.gif" width="16" height="16" alt="updating" />' + resultsIntro.innerHTML;
        }
    },
    afterUpdateCallback: function() {
        var resultsIntro = $('resultsIntro');
        if (resultsIntro) {
            resultsIntro.removeClassName("jelResultsIntroUpdating");
            var content = '<strong>Your results</strong> - ';
            if (this.boardSearch.searchType == 'POPULARITY') {
                content += '<strong>popular</strong> search ';
            } else {
                content += '<strong>simple</strong> search ';
            }
            if (this.boardSearch.searchType == 'POPULARITY') {
                if (this.boardSearch.options == 'today') {
                    content += '<strong>today</strong> ';
                } else {
                    content += 'in the past <strong>';
                    if (this.boardSearch.options == '7Days') {
                        content += '7 days';
                    } else if (this.boardSearch.options == '30Days') {
                        content += '30 days';
                    }
                    content += '</strong> '
                }
            }
            content += 'for ';
            if (this.boardSearch.name != '') {
            	if (this.boardSearch.blogsOnly) {
            		content += 'blogs matching, or containing entries matching <strong>&quot;';
            	} else {
            		content += 'boards matching <strong>&quot;';
            	}
                content += this.boardSearch.name + '&quot;</strong> ';
            } else {
                content += '<strong>all</strong> boards ';
            }
            content += 'within ';
            if (this.boardSearch.path != '') {
                content += 'the <strong>' + this.boardSearch.getPathLabel(this.formName) + '</strong> topic:';
            } else {
                content += '<strong>all</strong> topics:';
            }
            resultsIntro.innerHTML = content;
        }
    },
// assignments
    setPagerFromJSON: function(s) {
        var pager = eval('(' + s + ')');
        this.pager = new NumberListPager(this.prefix, this, pager);
    },
    setBoardSearchFromJSON: function(s) {
        var boardSearch = eval('(' + s + ')');
        this.boardSearch = new BoardSearch(boardSearch);
    },
    addBoardFromJSON: function(s) {
        this.boards.push(eval('(' + s + ')'));
    },
    addBoardGroupFromJSON: function(s){
    	this.boardGroups.push(eval('(' + s + ')'));
    },
// misc.
    getUrl: function(page) {
        page = page ? page : this.pager.requestedPage;
        return this.urlPrefix + "?" + this.getParams(page);
    },
    getParams: function(page) {
        page = page ? page : this.pager.requestedPage;
        return "page=" + page +
               "&name=" + this.boardSearch.name +
               "&path=" + this.boardSearch.path +
               "&sortBy=" + this.boardSearch.sortBy +
               "&sortOrder=" + this.boardSearch.sortOrder +
               "&options=" + this.boardSearch.options +
               "&searchType=" + this.boardSearch.searchType +
	       "&blogsOnly=" + this.boardSearch.blogsOnly;
    },
// navigation
    goPrevious: function(e) {
        return this.pager.goPrevious(e);
    },
    goNext: function(e) {
        return this.pager.goNext(e);
    },
// observation
    observePager: function() {
        var prevPageLinkElem = $(this.prefix + 'PrevPageLink');
        if (prevPageLinkElem) {
            Event.observe(prevPageLinkElem, 'click', this.goPrevious.bindAsEventListener(this));
        }
        var nextPageLinkElem = $(this.prefix + 'NextPageLink');
        if (nextPageLinkElem) {
            Event.observe(nextPageLinkElem, 'click', this.goNext.bindAsEventListener(this));
        }
    },
    observeForm: function() {
        var form = $(this.formName);
        if (form) {
            this.observeFormElement(form, 'name');
            this.observeFormElement(form, 'path');
            this.observeFormElement(form, 'sortBy');
            this.observeFormElement(form, 'sortOrder');
            this.observeFormElement(form, 'options');
            this.observeFormElement(form, 'searchType');
	    this.observeFormElement(form, 'blogsOnly');
        }
    },
    observeFormElement: function(form, id) {
        var input = form[id];
        if (input) {
            if (input.type == 'text') {
                new Form.Element.DelayedObserver(input, 0.5, this.doUpdate.bind(this));
            } else if (input.type == 'select-one') {
                Event.observe(input, 'change', this.doUpdate.bind(this));
            }
        }
    }
};

// wraps a BoardSearchResource
var BoardSearchController = Class.create();
BoardSearchController.prototype = {
    initialize: function(opts) {
        opts = opts ? opts : {};
        var prefix = opts['prefix'];
        this.prefix = prefix ? prefix : "boards";
        this.boardSearchResource = new BoardSearchResource(opts);
        this.pagerHtmlLoaded = false;
    },
    start: function() {
        this.insertBoardsListHtml();
        this.insertPagerHtml();
    },
    startBoardSearchResource: function() {
        this.boardSearchResource.observePager();
        this.boardSearchResource.observeForm();
        this.boardSearchResource.doUpdate();
    },
    insertBoardsListHtml: function() {
        var listContainer = $(this.prefix + 'ListContainer');
        var list = $(document.createElement("ul"));
        list.setAttribute("id", this.prefix + "List");
        listContainer.appendChild(list);
    },
    insertPagerHtml: function() {
        new Ajax.Updater({success: this.prefix + 'PagerContainer'}, '/pager', {
            parameters: 'pagerPrefix=' + this.prefix,
            method: 'get',
            onComplete: this.setPagerHtmlLoaded.bindAsEventListener(this)
        });
        this.onPagerHtmlLoaded();
    },
    setPagerHtmlLoaded: function() {
        this.pagerHtmlLoaded = true;
    },
    onPagerHtmlLoaded: function() {
        if (this.pagerHtmlLoaded) {
            this.startBoardSearchResource();
        } else {
            setTimeout(this.onPagerHtmlLoaded.bind(this), 50);
        }
    }
};

// Borrowed from script.aculo.us controls.js v1.7.1_beta3
//
// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//           (c) 2005-2007 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
//           (c) 2005-2007 Jon Tirsen (http://www.tirsen.com)
// Contributors:
//  Richard Livsey
//  Rahul Bhargava
//  Rob Wills
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/

Form.Element.DelayedObserver = Class.create();
Form.Element.DelayedObserver.prototype = {
    initialize: function(element, delay, callback) {
        this.delay = delay || 0.5;
        this.element = $(element);
        this.callback = callback;
        this.timer = null;
        this.lastValue = $F(this.element);
        Event.observe(this.element, 'keyup', this.delayedListener.bindAsEventListener(this));
    },
    delayedListener: function(event) {
        if (this.lastValue == $F(this.element)) return;
        if (this.timer) clearTimeout(this.timer);
        this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
        this.lastValue = $F(this.element);
    },
    onTimerEvent: function() {
        this.timer = null;
        this.callback(this.element, $F(this.element));
    }
};

if (window.setBoardSearchLoaded) {
    setBoardSearchLoaded();
}
