﻿Tikal.Options = new function () {
    var _isCollapsed = true; // Internal variable, only used for UI
    this.tabName = "";      // Tab name to display later
    this.url = "";          // Url, maybe selected from the combo or typed in manually
    this.rssValue = "";     // The RSS value may be either pre-defined or added by the user

    var _hiddenElement = null;

    var _tabNameControl = $("#tabName"),
        _serviceURLControl = $("#serviceURL"),
        _serviceURLSelectControl = $("#serviceURLSelect"),
        _custonRSSFeedControl = $("#customRSSFeed"),
        _addRSSFeedCheckControl = $("#addRSSFeedCheck"),
    // Just prepare this one, we must attach it after the dialog has already been created
    // as this control is going to be changed
		_serviceURL = null,
		allFields = $([]).add(_tabNameControl).add(_serviceURL),
		tips = $(".validateTips");

    // Private Methods, used only internally
    function updateTips(t) {
        tips
			.text(t)
			.show()
			.addClass("ui-state-highlight");
        setTimeout(function () {
            tips.removeClass("ui-state-highlight", 1500);
        }, 500);
    }

    function resetTips() {
        if (tips.is(":visible")) {
            tips
			    .hide()
                .text('')
        }
    }

    function checkLength(o, n, min, max) {
        if (o.val().length > max || o.val().length < min) {
            o.addClass("ui-state-error");
            updateTips("Length of " + n + " must be between " +
					min + " and " + max + ".");
            setTimeout(function () { o.removeClass("ui-state-error"); resetTips(); }, 3500);
            return false;
        } else {
            return true;
        }
    }

    function checkRegexp(o, regexp, n) {
        if (!(regexp.test(o.val()))) {
            o.addClass("ui-state-error");
            updateTips(n);
            setTimeout(function () { o.removeClass("ui-state-error"); resetTips(); }, 3500);
            return false;
        } else {
            return true;
        }
    }

    /* Services Methods, handle external services but use dialog controls */
    // Handle saving a new service
    function saveService() {
        Tikal.Utils.Tabs.storeNewTab(Tikal.Options.tabName, Tikal.Options.url, Tikal.Options.rssValue);
        // Append the new tab
        Tikal.Utils.Tabs.appendTab(Tikal.Options.tabName);
    }

    function slideDialog(hideOrShow) {
        if (hideOrShow == 'hide') {
            $("#options-dialog").hide('fast');
            $('.' + _hiddenElement).show("fast");
        } else {
            $("#options-dialog").show('slow');
            $("#tabName").focus();
        }
    }

    // Reset all the input fields
    function resetInputFields() {
        _tabNameControl.val('');
        _serviceURLControl.val('');
        _serviceURLSelectControl.val($('option:first', _serviceURLSelectControl).val());
        _custonRSSFeedControl.val('');
        _addRSSFeedCheckControl.removeAttr('checked');
        resetTips();
    }

    /* End of private methods*/

    // Privileged Methods, accessible from the outside
    this.initOptionsDialog = function () {
        Tikal.Utils.CalculateCurrentWindowHeight();
        $("#options-dialog").height(Tikal.Utils.frameHeight + 'px');

        Tikal.Utils.LocalStore.reloadSavedServices();
        Tikal.Utils.LocalStore.reloadMorePreloadedOptions();
        Tikal.Utils.Tabs.loadPredefinedURLs();
    }

    this.showDialog = function (element) {
        resetInputFields();
        $('.' + element).hide("fast");
        _hiddenElement = element;
        slideDialog();
        return (false);
    }

    /* End of Privileged Methods */

    /* Event Handlers, binding */

    $("html").bind({
        'click': function (event) {   // Close options-dialog DIV if the user has clicked outside of it
            var evt = (evt) ? evt : ((event) ? event : null);
            if ((evt.srcElement.type != "button") && (evt.srcElement.type != "checkbox")) {
                if ((evt.clientX < $('#options-dialog').position().left) && (evt.clientY < $('#options-dialog').height())) {
                    slideDialog('hide');
                    $('.' + _hiddenElement).show("fast");
                }
            }
        }
    });

    $("#toggleUrl").bind({
        'click': function () {
            if (_isCollapsed) {
                _isCollapsed = false;
                $("#toggleUrl").find('span').removeClass('expand');
                $("#checkOption").hide();
                _serviceURLSelectControl.hide();

                $("#inputOption").show();
                _serviceURLControl.show().css("display", "block"); ;
                $("#toggleUrl").find('span').addClass('collapse');

            } else {
                _isCollapsed = true;
                $("#toggleUrl").find('span').removeClass('collapse');
                _serviceURLControl.hide().css("display", "none");
                $("#inputOption").hide();

                $("#checkOption").show();
                _serviceURLSelectControl.show();
                $("#toggleUrl").find('span').addClass('expand');
            }
        }
    });

    $("#close-dialog").bind({
        'click': function () {
            slideDialog('hide');
        }
    });

    $("#addService").bind({
        'click': function () {
            var bValid = true;
            allFields.removeClass("ui-state-error");

            bValid = bValid && checkLength(_tabNameControl, "tabName", 1, 32);
            bValid = bValid && checkRegexp(_tabNameControl, /^[a-z]([0-9a-z_])+$/i, "Tab name may consist of a-z, 0-9, underscores, begin with a letter.");

            Tikal.Options.tabName = $(_tabNameControl).val();

            if (!_isCollapsed) { // New manual add service, RSS isn't mandatory
                bValid = bValid && checkRegexp(_serviceURLControl, /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/, "Invalid URL");
                // Only test the custom RSS feed input if it's not empty
                if (_custonRSSFeedControl.val().length > 0) {
                    bValid = bValid && checkRegexp(_custonRSSFeedControl, /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/, "Invalid RSS URL");
                }

                Tikal.Options.url = _serviceURLControl.val();
                Tikal.Options.rssValue = _custonRSSFeedControl.val();
            } else {
                Tikal.Options.url = $("#serviceURLSelect option:selected").text();
                if ($('#addRSSFeedCheck:checked')) {
                    var preDefinedUrlsKey = $("#serviceURLSelect option:selected").val();
                    var element = Tikal.Utils.GetObjectByKeyJSON(Tikal.preDefinedUrls, preDefinedUrlsKey);
                    Tikal.Options.rssValue = element.rss;
                }
            }

            if (bValid) {
                saveService();
                slideDialog('hide');
            }
        },
        'focus': function () {
            $(this).addClass('ui-state-focus');
        },
        'blur': function () {
            $(this).removeClass('ui-state-focus');
        }
    });

    $(":button").bind({
        'mouseover': function () {
            $(this).addClass('ui-state-hover');
        },
        'mouseleave': function () {
            $(this).removeClass('ui-state-hover');
        }
    });

    /* End of Event Handlers*/
};
