$(document).ready(function () {
    // constants, initialize variables
    var STEP_PREFIX = 'forumquestion_form_step_'
        , NUMSTEPS = 4
        , STEP_TITLES= [
              'Ask a new question: Step 1 of 4'
            , 'Ask a new question: Step 2 of 4'
            , 'Ask a new question: Step 3 of 4'
            , 'Ask a new question: Step 4 of 4'
            , 'Success!'
        ]
        , TIKIROOT = $('#tikiroot').text()
        , LOCALE   = $('#locale').text()
        , DEFAULT_ASK_A_QUESTION_TEXT = 'Type your question here'
        , askAQuestionOptions = getAskAQuestionData()
        , results_max_height = 0
        , steps = $('#forumquestion_form_form').children()
        , stepnum  = 0, gotostepnum = 0, selectedId = -1
        , STEP_NEXT_TITLE = 'Next step'
        , STEP_FINAL_TITLE = 'Submit your question'
        , QUESTION_MINLENGTH = 5
        , os = $('#os')
        , fxVersion = $('#version')
        , pluginE = $('#plugins')
        , captcha_img_src = $('#forumquestion_form_step_4 .captcha img').attr('src')
        // generate the fields for last step?
        , generateFields = true
        , stopFocusSelector;
    ;
    // END initialize variables
    // initialize CSS for various elements
    $('#forumquestion_question').css('color', '#c7c7c7');

    /**
     * Resizes the 'Ask a question' form, most importantly
     * adjusting max-height and max-width
     */
    function resizeForm() {
        results_max_height = ($(window).height() - 300);
        if (results_max_height <= 0) results_max_height = 200;
        $('#forumquestion_results').css('max-height', results_max_height + 'px');
        $('.forumquestion_form').dialog('option', 'maxHeight', ($(window).height() - 100));
        $('.forumquestion_form').dialog('option', 'maxWidth', ($(window).width()));
    }
    /**
     * Resizes warning form
     */
    function resizeWarningForm() {
        $('#forumquestion_warning').dialog('option', 'maxHeight', ($(window).height() - 100));
    }

    $(window).bind('resize', function() {
        resizeForm();
    });
    /**
     * Helper function, returns int for the step number of the multi-step
     * ask a question form
     */
    function getStepNumber() {
        var stepnum = -1;
        steps.each(function () {
            if ($(this).is(':visible')) {
                var num = $(this).attr('id').toString();
                num = num.substring(num.length-1);
                stepnum = parseInt(num);
            }
        });
        return stepnum;
    }

    /**
     * Helper function. Checks that a question was entered.
     * Disables the Next>> button if not
     */
    function checkQuestionEntered() {
        if (DEFAULT_ASK_A_QUESTION_TEXT == $('#forumquestion_question').val()
            || ($('#forumquestion_question').val().length < QUESTION_MINLENGTH)) {
            $('.forumquestion_askaq button:eq(0)').removeClass('enabled');
            return false;
        }
        return true;
    }

    /**
     * Helper function, show step number
     */
    function showStep(stepnum, steptitlenum) {
        if (steptitlenum == undefined) {
            steptitlenum = stepnum;
        }
        $('.forumquestion_form').dialog('option', 'title', STEP_TITLES[steptitlenum-1]);
        $('#forumquestion_form_form').children().hide();
        $('#forumquestion_form_step_5').hide();
        $('#' + STEP_PREFIX + (stepnum)).show();
        // focus the question input for search step
        if (stepnum == 3) {
            $('#forumquestion_question').focus();
            checkQuestionEntered();
        }
        // no <<Prev button for first step
        if (stepnum == 1) {
            $('.forumquestion_askaq button:eq(1)').hide();
            if (gotostepnum > 0) $('.forumquestion_askaq button:eq(0)').addClass('enabled');
        }
        else if (stepnum == 5) {
            $('.forumquestion_askaq button:eq(1)').hide();
        }
        else {
            $('.forumquestion_askaq button:eq(1)').show();
        }
        // no Next>> button for last step if skipped
        if (steptitlenum == NUMSTEPS && gotostepnum == NUMSTEPS) {
            $('.forumquestion_askaq button:eq(0)').hide();
        }
        else if (stepnum == 5) {
            $('.forumquestion_askaq button:eq(0)').hide();
        }
        else {
            if (stepnum == NUMSTEPS) {
                $('.forumquestion_askaq button:eq(0)').val(STEP_FINAL_TITLE).html(STEP_FINAL_TITLE);
            }
            else {
                $('.forumquestion_askaq button:eq(0)').val(STEP_NEXT_TITLE).html(STEP_NEXT_TITLE);
            }
            $('.forumquestion_askaq button:eq(0)').show();
        }
    }

    // for "close this window" button in step 5
    $('.close_forumquestion').click(function () {
        $('.forumquestion_form').dialog('close');
        return false;
    });

    /**
     * Resets the ask a question dialog.
     * This is useful, for example, when reopening it.
     */
    function resetAskAQuestionDialog() {
        // hide all steps
        $('#forumquestion_options input').attr('checked', false);
        showStep(1);

        // reset search step
        $('#forumquestion_question').val(DEFAULT_ASK_A_QUESTION_TEXT).blur();
        $('#forumquestion_results').hide();
        $('#forumquestion_prefix').hide();
        $('#forumquestion_results_after').hide();
        $('#forumquestion_results_loading').hide();
        $('#forumquestion_tips').show();
        $('#forumquestion_ask').val('Ask this »');

        // reset warnings
        $('#forumquestion_form_step_4 input').removeAttr('continue');
        $('#forumquestion_form_step_4 textarea').removeAttr('continue');

        // reload the captcha and reset the input
        $('#forumquestion_captcha_reload').click();
        $('.captcha input').val('');
    }
    $('.forumquestion').click(function () {
        resetAskAQuestionDialog();
        $('.forumquestion_form').dialog('open');
        return false;
    });

    /**
     * Creates the ask a question form/dialog
     */
    $('.forumquestion_form').dialog({
        closeOnEscape: false
        , autoOpen: false
        , width: 720
        , maxHeight: ($(window).height() - 100)
        , maxWidth: ($(window).width())
        , minHeight: 150
        , minWidth: 400
        , modal: true
        , draggable: false
        , resizable: false
        , dialogClass: 'forumquestion_askaq'
        , position: ['center', 60]
        , open: function(event, ui) {
            resizeForm();
            gotostepnum = 0;
            if (isUsingFirefox()) fillInfo();
            fillUserAgent();
            $('.forumquestion_askaq button:eq(1)').hide();
        }
        , buttons: {
            'Next step': function() {
                stepnum = getStepNumber();
                switch(stepnum) {
                    case 1:
                        if (gotostepnum > 0) {
                            // gotostepnum is set on clicking a radio option from first step
                            var showstepnum = gotostepnum;
                            if (gotostepnum == NUMSTEPS) {
                                // no allow_continue requires description
                                if (askAQuestionOptions[selectedId].description == '') {
                                    $('#forumquestion_description').html('Required option description goes here. ' +
                                        'See <a href="' + TIKIROOT + 'tiki-admin-ask_a_question.php">tiki-admin-ask_a_question.php</a>.');
                                }
                                else {
                                    $('#forumquestion_description').html(askAQuestionOptions[selectedId].description);
                                }
                                showstepnum = 2;
                            }
                            else if (gotostepnum == 2) {
                                $('#forumquestion_description').html(askAQuestionOptions[selectedId].description);
                            }
                            // show search step
                            else {
                                checkQuestionEntered();
                            }
                            // step 4 can be description step. we use the id from step_2 to show it, though
                            showStep(showstepnum, gotostepnum);
                        }
                        return false;
                    case 2:
                        // step 2 is description step, go to step 3
                        showStep(3);
                        // allow through to disable search button
                        checkQuestionEntered();
                        return false;
                    case 3:
                        // checks a question has been entered and proceeds to last step
                        if (checkQuestionEntered() == true) {
                            showStep(4);
                            // smart: generate fields only when option in step 1 changes
                            if (generateFields == true) generateFormFields();
                            generateFields = false;
                        }
                        return false;
                    case 4:
                        // this is the only step that allows submit
                        $('#forumquestion_form_form').submit();
                        break;
                    default:
                        return false;
                }
                return false;
            }
            , 'Previous step': function() {
                var stepnum = getStepNumber();
                var showstepnum = stepnum - 1;
                // if we skipped step 2 on Next>>, go back to first step
                if (stepnum == 3 && gotostepnum == 3) {
                    showstepnum = 1;
                }
                showStep(showstepnum);
            }
        }
        , close: function() {
            $('#forumquestion_warning').dialog('close');
        }
    });
    // after dialog is generated, update close button caption
    $('.ui-icon-closethick').html('Cancel and close');

    $('#forumquestion_warning').dialog({
        autoOpen: false
        , width: 350
        , maxHeight: ($(window).height() - 100)
        , minHeight: 100
        , draggable: false
        , dialogClass: 'forumquestion_warning'
        , position: 'center'
        , resizable: false
        , open: function(event, ui) {
            resizeWarningForm();
        }
        , buttons: {
            'Yes': function() {
                $(stopFocusSelector).attr('continue', '1');
                $(this).dialog('close');
                $('#forumquestion_form_form').submit();
            },
            "No, I'll fix this": function() {
                if (($(this).html().indexOf('email address') > -1)
                    && ($('.emailme_toggle input').is(':hidden'))) {
                    $('#emailme_check input').click();
                }
                $(this).dialog('close');
                $(stopFocusSelector).focus();
            }
        }
    });

    /**
     * Helper function for generating the warning
     */
    function questionWarn(messageCode, threadId) {
        switch(messageCode) {
            case 'description':
                $('#forumquestion_warning .warning_title')
                    .html('You left the <strong>Description</strong> field blank');
                $('#forumquestion_warning .warning_content')
                    .html('Please provide a more detailed description.');
                $('#forumquestion_warning .warning_suffix')
                    .html('');
                stopFocusSelector = '#description';
                $('.forumquestion_warning button:eq(0)').hide();
                $('.forumquestion_warning button:eq(1)').val("OK").html("OK");
                break;
            case 'extensions':
                $('#forumquestion_warning .warning_title')
                    .html('You left the <span>Installed extensions</span> field blank');
                $('#forumquestion_warning .warning_content')
                    .html('Knowing what extensions you have installed is valuable troubleshooting information.<br/>To find your extensions, go to the the <strong>Tools</strong> menu, select <strong>Add-ons</strong> and select the <strong>Extensions</strong> tab.');
                $('#forumquestion_warning .warning_suffix')
                    .html('Are you sure you want to proceed?');
                stopFocusSelector = '#extensions textarea';
                $('.forumquestion_warning button:eq(0)').show();
                $('.forumquestion_warning button:eq(1)').val("No, I'll fix this").html("No, I'll fix this");
                break;
            case 'email':
                $('#forumquestion_warning .warning_title')
                    .html('You left the <span>Email</span> field blank');
                $('#forumquestion_warning .warning_content')
                    .html('Providing your email address makes it easier for you to know when your question receives support.');
                $('#forumquestion_warning .warning_suffix')
                    .html('Are you sure you want to proceed?');
                stopFocusSelector = '.emailme_toggle input';
                $('.forumquestion_warning button:eq(0)').show();
                $('.forumquestion_warning button:eq(1)').val("No, I'll fix this").html("No, I'll fix this");
                break;
            case 'duplicatethread':
                $('#forumquestion_warning .warning_title')
                    .html('Oops! <span>A similar thread already exists!</span>');
                $('#forumquestion_warning .warning_content')
                    .html('<a href="' + TIKIROOT + 'tiki-view_forum_thread.php?forumId=1&comments_parentId=' + threadId + '" target="_blank">Click here to see it</a> or click <b>Try again</b> below to update your question.');
                $('#forumquestion_warning .warning_suffix')
                    .html('');
                $('.forumquestion_warning button:eq(0)').hide();
                $('.forumquestion_warning button:eq(1)').val('Try again').html('Try again');
                stopFocusSelector = '#extensions textarea';
                break;
            case 'antibotcode':
            default:
                $('#forumquestion_warning .warning_title')
                    .html('You have mistyped the <span>spam prevention code</span>');
                $('#forumquestion_warning .warning_content')
                    .html("You must provide this code to post your question. If you're having trouble, try clicking \"Reload\" below the image.");
                $('#forumquestion_warning .warning_suffix')
                    .html('');
                $('.forumquestion_warning button:eq(0)').hide();
                $('.forumquestion_warning button:eq(1)').val('Try again').html('Try again');
                stopFocusSelector = '.captcha input';
                $('.captcha input').val('');
                $('#forumquestion_captcha_reload').click();
        }
        $('#forumquestion_warning').dialog('open');
    }

    /**
     * This is where all the submission stuff happens.
     * This function takes care of:
     * -- search results
     * -- question submission
     * -- errors in either of the above two
     */
    $('#forumquestion_form_form').submit( function () {
        if (($('#forumquestion_question').val() == DEFAULT_ASK_A_QUESTION_TEXT)
            || ($('#forumquestion_question').val() == '')) {
            return false;
        }
        var stepnum = getStepNumber();
        if (stepnum == 3) {
            // search step
            // hide Tips
            $('#forumquestion_tips').hide();
            $('#forumquestion_results').hide();
            $('#forumquestion_prefix').hide();
            $('#forumquestion_results_after').hide();
            $('#forumquestion_results_loading').show();
            // populate results
            $.getJSON(TIKIROOT + 'tiki-newsearch.php?q=' + escape($('#forumquestion_question').val()) +
                '&locale=' + LOCALE + '&format=json',
            function (data) {
                $('#forumquestion_results').remove('.result');
                if (data.results == null) {
                    $('#forumquestion_results').html(data.message)
                }
                else {
                    $.each(data.results, function(i,item){
                        var result = $('#forumquestion_result_template .result').clone();
                        result.children('a').attr('href', TIKIROOT + item.path).html(item.title);
                        result.children('p').html(item.description);
                        result.appendTo('#forumquestion_results');
                    });
                    $('#forumquestion_results').append('<a id="forumquestion_moreresults" target="_blank" href="' + TIKIROOT +
                        'tiki-newsearch.php?q=' + escape($('#forumquestion_question').val()) +
                        '&locale=' + LOCALE + '">More results</a>');
                }
                $('#forumquestion_results_loading').hide();
                $('#forumquestion_results').show();
                $('#forumquestion_prefix').show();
                $('#forumquestion_results_after').show();
                $('#forumquestion_ask').val('Ask again »');
            });
        }
        else if (stepnum == NUMSTEPS) {
            // question submission step
            // validate description
            if ($('#description').val().replace(/^\s+|\s+$/g,"")  == '') {
                questionWarn('description');
                return false;
            }
            // validate extensions
            if ($('#extensions textarea').val() == '') {
                if ($('#extensions textarea').attr('continue') == null) {
                    questionWarn('extensions');
                    return false;
                }
            }
            // warn email for anonymous users
            if ((!$('#emailme_username').is(':visible')) &&
                   ( ($('.emailme_toggle input').val() == '')
                    || ($('#emailme_check input').is(':checked') == false))
                ) {
                if ($('.emailme_toggle input').attr('continue') == null) {
                    questionWarn('email');
                    return false;
                }
            }
            // validate captcha
            if ($('.captcha').html() !== null) {
                var antibotcode = $('.captcha input').val();
                // simple regex makes sure 5 digits are entered to help user quickly
                var antibotregex = /^\d{5}$/;
                if (!antibotregex.test(antibotcode)) {
                    questionWarn('antibotcode');
                    return false;
                }
            }
            $('.forumquestion_askaq button:eq(0)')
                .after('<img id="forumquestion_ask_loading" src="' + TIKIROOT + 'images/search/wait.gif" alt="Loading..." />');
            $.ajax({
                url: TIKIROOT + 'tiki-ask_a_question.php',
                type: 'POST',
                async: false,
                data: $(this).serialize(),
                cache: false,
                dataType: 'text',
                timeout: 3000,
                global: false,
                error: function() {
                    // the only alert() issued by this code explicitly :)
                    $('#forumquestion_ask_loading').remove();
                    alert('Error submitting form, please try again.');
                },
                success: function(data, textStatus) {
                    // check if antibotcode was mistyped
                    if (data.indexOf('anti-bot') > -1) {
                        questionWarn('antibotcode');
                        return false;
                    }
                    // success! link to thread id
                    var dataSplit = data.split('\n');
                    var threadId = dataSplit[0];
                    if (data.indexOf('duplicate')!=-1) {
                        // duplicate thread
                        questionWarn('duplicatethread', threadId);
                        return false;
                    }
                    var viewquestion = $('#viewquestion').attr('href');
                    viewquestion = viewquestion.replace(/000000/, threadId)
                    $('#viewquestion').attr('href', viewquestion);
                    $('#bookmarkquestion').attr('href', viewquestion);
                    // done! show success step!
                    showStep(5);
                    $('#forumquestion_ask_loading').remove();
                }
            });
        }
        // always return false to keep the form visible
        return false;
    });

    // generate radio options for first step
    $.each(askAQuestionOptions, function(i,item){
        var option = $('#forumquestion_option_template label').clone();
        option.children('input').attr('value', i);
        option.append(' ' + item.label)
            .appendTo('#forumquestion_options');
    });

    // auto change text to default value for question
    $('#forumquestion_question').focus(function() {
        if ($(this).val() == DEFAULT_ASK_A_QUESTION_TEXT)
            $(this).css('color', '#000').val('');
    }).blur(function() {
        $(this).keyup();
        if ($(this).val() == '')
            $(this).css('color', '#c7c7c7').val(DEFAULT_ASK_A_QUESTION_TEXT);
    });

    /**
     * Allows generateFormFields() to be called on step 4
     * Sets which step follows
     */
    $('#forumquestion_options input').click(function () {
        generateFields = true;
        $('.forumquestion_askaq button:eq(0)').addClass('enabled');
        selectedId = $(this).val();
        $('#choice_id').val(askAQuestionOptions[selectedId].id);
        if (askAQuestionOptions[selectedId].allow_continue == true) {
            if (askAQuestionOptions[selectedId].description == '') {
                gotostepnum = 3;
            }
            else {
                gotostepnum = 2;
            }
        }
        else {
            gotostepnum = 4;
        }
    });

    // email toggle
    $('#emailme_check input').click(function () {
        $('.emailme_toggle').toggle();
    });

    // captcha reload on step 4
    $('#forumquestion_captcha_reload').click(function () {
        var timestamp = new Date().getTime();
        $('#forumquestion_form_step_4 .captcha img').attr('src', captcha_img_src + '?' + timestamp);
        return false;
    });

    // show/hide details on step 4
    $('#show_details').click(function () {
        $('#details').toggle();
        if ($('#details').is(':visible')) {
            $('#show_details').html('Hide details');
        }
        else {
            $('#show_details').html('Show details');
        }
    });

    // enable/disable next button on search step, step 3
    $('#forumquestion_question').keyup(function () {
        var val = $(this).val().replace(/^\s+|\s+$/g,"");
        if (val.length >= QUESTION_MINLENGTH &&
            val != DEFAULT_ASK_A_QUESTION_TEXT) {
            $('.forumquestion_askaq button:eq(0)').addClass('enabled');
        }
        else {
            $('.forumquestion_askaq button:eq(0)').removeClass('enabled');
        }
    });

    // generate form fields for step 4
    function generateFormFields() {
        $('#forumquestion_form_step_4_fields_custom').html('');
        $.each(askAQuestionOptions[selectedId].fields, function(i,item) {
            var field = $('#forumquestion_fields_custom_template .' + item.type).clone();
            // this is the cool part, all the attributes set in the admin are set first
            field.attr(item.attributes);
            // then they are overwritten for each form element. also helps create valid HTML
            switch (item.type) {
                //case 'hidden':
                    //break;
                case 'checkbox':
                case 'radio':
                    field.append(' ' + item.label);
                    break;
                case 'text':
                    field.prepend(item.label + ' ');
                    break;
                case 'select':
                    field.prepend(item.label + ' ');
                    var selectField = field.children('select').attr('name', item.name);
                    var option = selectField.children('option');
                    $.each(item.options, function(optname,optlabel) {
                        option.attr('value', optname)
                              .text(optlabel);
                        option = option.clone();
                        selectField.append(option);
                    });
                    // remove the extra clone at the end
                    option.remove();
                    break;
                case 'textarea':
                    field.prepend(item.label + ' ');
                    field.children('textarea').attr('name', item.name);
                    break;
                case 'textblock':
                    field.html(item.description);
                    break;
                default:
                    field.html('');
                    if (item.label) {
                        field.html('<div class="textblock_label">' + item.label + '</div>');
                    }
                    field.append(item.description);
            }
            switch (item.type) {
                case 'text':
                case 'hidden':
                case 'checkbox':
                case 'radio':
                    field.children('input').attr({ 
                        name: item.name,
                        value: item.value
                    });
            }
            // finally add the field
            field.appendTo('#forumquestion_form_step_4_fields_custom');
        });
    }

    // bookmark this question button, cross browser
    // should work on IE4+, Gecko-based browsers, Opera
    $('#bookmarkquestion').click(function () {
        if (window.sidebar) {
            window.sidebar.addPanel(this.title, this.href, '');
        }
        else if (window.external) {
            window.external.AddFavorite(this.href, this.title);
        }
        return false;
    });

    //effect for blur/focus on inputs
    $('.forumquestion_askaq input[type="text"]').focus(function () {
        $(this).css('background', '#e7f7f8');
    }).blur(function () {
        $(this).css('background', '#ffffff');
    });
    //effect for blur/focus on textarea
    $('.forumquestion_askaq textarea').focus(function () {
        $(this).css('background', '#e7f7f8');
    }).blur(function () {
        $(this).css('background', '#ffffff');
    });

    /**
     * The three functions below are taken from forum_advanced_post.tpl r51406
     * Modified for use with jQuery
     */
    function isUsingFirefox() {
        try {
            return (-1 != navigator.userAgent.indexOf('Firefox'));
        } catch (ex) {
            return false;
        }
    }

    function getFirefoxVersion() {
        var version = /Firefox\/(\S+)/i.exec(navigator.userAgent);
        return version[1];
    }

    function getOS() {
        var oscpu = navigator.oscpu;
        switch (oscpu) {
            case "Windows NT 5.1":
                return "Windows XP";
            case "Windows NT 6.0":
                return "Windows Vista";
            case "Windows NT 6.1":
                return "Windows 7";
            case "Linux i686":
                return "Linux";
            default:
                return oscpu;
        }
    }

    function fillInfo() {
        os.val(getOS());
        fxVersion.val(getFirefoxVersion());

        var plugins = [];
        for (var i = 0; i < navigator.plugins.length; i++) {
            var d = navigator.plugins[i].description.replace(/<[^>]+>/ig,'');
            if (plugins.indexOf(d) == -1) {
                plugins.push(d);
            }
        }
        if (plugins.length > 0) {
            pluginE.val("*-" + plugins.join("\n*"));
        }
    }

    function fillUserAgent() {
        $('#user_agent').val(navigator.userAgent);
    }

    // Bug 518445: Open the form automatically
    if(window.location.href.indexOf('openpost')!=-1 && $('input[name="comments_threadId"]').val() <= 0){
        resetAskAQuestionDialog();
        $('.forumquestion_form').dialog('open');
    }
    
    // Bug 518424
    window.aaqLoaded = true;
});
