/***
 * Sydney Symphony Event Search Module
 * 
 * Author: Chris Bellman
 * 
 * Search by keyword with predictive text, or between two dates
 */

var EventSearch = base2.Base.extend({
    constructor: function(options) {
        this.SetOptions(options);
        this.SetDefaults();
        this.SetEvents();
    },

    Options: {},

    SetOptions: function(options) {
        this.Defaults = {
            ContainerSelector: ".event-search",
            SearchSelector: ".keyword-search",
            DateFromSelector: ".from-date input",
            DateToSelector: ".to-date input",
            DatepickerIcon: "/assets/img/btn/calendar.gif"
        }

        this.Options = jQuery.extend({}, this.Defaults, options);
    },

    SetDefaults: function() {
        this.Container = jQuery(this.Options.ContainerSelector);
        this.SearchBox = this.Container.find(this.Options.SearchSelector);
        this.FromDateBox = this.Container.find(this.Options.DateFromSelector);
        this.ToDateBox = this.Container.find(this.Options.DateToSelector);

        //set default states of input fields
        this.SearchBox.val(this.SearchBox.attr("title")).addClass("default");
        this.FromDateBox.val(this.FromDateBox.attr("title")).addClass("default");
        this.ToDateBox.val(this.ToDateBox.attr("title")).addClass("default");
    },

    SetEvents: function() {
        //bind date picker to from and to date
        jQuery(this.Options.ContainerSelector + " " + this.Options.DateFromSelector + ", " + this.Options.ContainerSelector + " " + this.Options.DateToSelector).datepicker({
            showOn: "button",
            buttonImage: this.Options.DatepickerIcon,
            buttonImageOnly: true,
            dateFormat: 'dd/mm/yy',
            minDate: new Date()
        });

        this.Container.find("input").bind("focus", function() {
            if (jQuery(this).hasClass("default")) {
                jQuery(this).val("").removeClass("default");
            }
        });

        this.Container.find("input").bind("blur", function() {
            var obj = jQuery(this);
            
            // Invalid if its nothing, not a date, or a date before today
            if (obj.val().length == 0 || !Date.parse(obj.val()) || Date.parse(obj.val()).getDate() < new Date().getDate()) {
                obj.addClass("default");
                obj.val(obj.attr("title"));
            }
        });

        var obj = this;

        this.Container.find("#searchBtn").click(function() {
            var keywordTerm = obj.Container.find(".keyword-search").val();

            var redirectURL = '/EventSearch/Default.aspx?t='; //d&sd=1-2-2011&ed=1-1-2030

            if (keywordTerm.length > 0 && keywordTerm != 'Enter keywords') {
                //it's a keyword search
                redirectURL = redirectURL + "k&s=" + keywordTerm;
            }
            else {
                //it's a date search
                var fromDate = obj.Container.find(".from-date input").val();
                var toDate = obj.Container.find(".to-date input").val();

                if (fromDate != '' && fromDate != 'Select date' && toDate != '' && toDate != 'Select date')
                    redirectURL = redirectURL + 'd&sd=' + fromDate + '&ed=' + toDate;
            }

            if (redirectURL != '/EventSearch/Default.aspx?t=') {
                window.location.href = redirectURL;
            }

            return false;
        });

        jQuery(document).click(function(e) {
            if ($(e.target).closest('.predictions').length === 0) {
                obj.Container.find(".predictions").hide();
            }
        });

        jQuery('body').keydown(function(e) {
            if (e.keyCode == 27)
                obj.Container.find(".predictions").hide();
        });



        this.Container.find(".keyword-search").keyup(function(e) {
            if (e.keyCode == 27)
                return;

            if (e.keyCode == 13) {
                //enter was pressed, submit the search
                jQuery("#searchBtn").click();
                return false;
            }

            var term = jQuery(this).val();
            var predictionsDiv = obj.Container.find(".predictions");

            if (term.length > 2) {
                //get the result
                obj.GetPredictions(term, function(data) {
                    //clear the DOM of previous predictions
                    predictionsDiv.empty();

                    //write to the DOM
                    if (data && data.length > 0) {
                        obj.Predictions = data;

                        for (i = 0; i < data.length; i++) {
                            var url = data[i].Value;
                            var title = data[i].Key;
                            var resultHtml = '<div class="result"><a href="' + url + '">' + title + '</a></div>';

                            predictionsDiv.append(resultHtml);
                        }
                    }
                    else {
                        predictionsDiv.hide();
                    }

                    //show the predictions
                    predictionsDiv.show();
                });
            }
            else {
                //predictionsDiv.hide();
            }
        });
    },

    /* Properties, Member Variables  */
    Container: null,
    SearchBox: null,
    FromDateBox: null,
    ToDateBox: null,
    Predictions: [],


    /* Class Methods */
    GetPredictions: function(term, callback) {
        var data = {
            s: term
        }

        jQuery.ajax({
            url: '/EventSearch/services/predictSearch.ashx',
            data: data,
            type: "POST",
            async: true,
            success: jQuery.proxy(callback, this)
        });
    }
});
