var SM = function()
{

    var valid = true, popContentLoaded = false, inPreview = false;
    
    /*
     * add features to add/remove upload
     */
    function upload()
    {
        //master represents a default upload box
        //this acts as a template
        var $master = $('div.uploadMaster:eq(0)');
        
        //hide the template if in javascript mode
        $master.hide();
        
        $master.clone(true).insertAfter($master).show();
        $('div.uploadMaster:eq(1) input').val('');
        
        //Add an additional upload node when requested
        $('a.addUpload').click(function() {
            $master.clone(true).insertAfter($master).show();
            $('div.uploadMaster').removeClass('uploadResourceHighlight');
            $('div.uploadMaster:eq(1)').addClass('uploadResourceHighlight');
            $('div.uploadMaster:eq(1) input').val('');
            return false;
        });
        
        //Remove an upload node
        $('a.removeUpload').click(function()
        {
            $(this).parent().remove();
            $('div.uploadMaster:eq(1)').addClass('uploadResourceHighlight');
            return false;
        });
        
        //make sure that the displayed upload files are links
        $("input[name='data[SupportmusicUpload][CurrentUploads][]']+label").each(function(i)
        {
            $(this).after('<a href="' + $(this).text() + '" target="_blank">' + $(this).text() + '</a>').remove();
        });
        
    }
    
    /*
     * report inappropriate case content
     */
    function reportInappropriateContent()
    {
        setupAjaxFeedback();
        
        //report inappropriate content
        $('form#report').submit(function(e)
        {
            $.ajax({
                data: {
                    notes: $('textarea#notes').val()
                },
                type: "POST",
                url: this.action,
                timeout: 5000,
                error: function(r)
                {
                    $("#popNotes").slideUp("slow");
                    $(".succ").empty();
                    $(".warn").empty();
                    $(".err").html("<p>We were unable to process your request.  Please try again.</p>");
                },
                success: function(r)
                {
                    $("#popNotes").slideUp("slow");
                    $(".err").empty();
                    $(".warn").empty();
                    $(".succ").html("<p>Your message has been successfully sent.</p>");
                }
            });
            return false;
        });
        
        $('textarea#notes').click(function(e)
        {
            $(this).val('');
        });
    }
    
    /*
     * provide visual feedback to the user
     */
    function setupAjaxFeedback()
    {
        $(".submit").ajaxStart(function()
        {
            $(this).addClass('submitr');
        });
        
        $(".submit").ajaxStop(function()
        {
            $(this).removeClass('submitr');
        });
    }
    
    /*
     * setup authenticated popups for various actions
     */
    function authPopups()
    {
        //hide all javascript div popups
        var $popup = $('.viewPopup + div');
        $popup.hide();
        
        //toggle the div which contains our popup html
        $('a.viewPopup').click(function(e)
        {
            $(this).next('div').slideToggle("medium");
            return false;
        });
        
        //setup the reporting of inappropriate content
        reportInappropriateContent();
    }
    
    /*
     * javascript validation for various case plan fields
     */
    function validateCaseFields()
    {
        //validate fields for add/edit cases
        $('form#SupportmusicCaseAddForm').submit(function(e)
        {
            valid = true;
            $('div.err').empty();
            
            //just in case we're in preview mode, show the elements and hide the preview
            $('.add').show();
            $('.preview').hide();
            $('h2').text('Add a Support Music Entry');
            
            //force the click of the preview button if we are in preview mode to return to 
            //regular add mode
            if (inPreview == true) {
                $('#preview').click();
            }
            
            validateText('SupportmusicCaseTitle', 'Please enter a valid title.', 'text');
            validateText('SupportmusicCaseSubmittersName', 'Please enter your name.', 'text');
            validateText('SupportmusicCaseSubmittersEmail', 'Please enter your email.', 'text');
            validateText('SupportmusicCaseItemText', 'Please enter a description of your entry.', 'tinymce');
            /*validateCheckBoxSelected('SupportmusicCategory', 'Please select at least one grade level.');*/
            validateCheckBoxSelected('SupportmusicRelevance', 'Please select at least one issue.');
            validateText('SupportmusicCaseSpamPrevention', 'Please enter the valid spam prevention answer.', 'text');
            
            if (!valid) {
                $('div.err').append('<p>All required fields must be filled out prior to submission.</p>');
                $('html, body').animate({
                    scrollTop: 0
                }, 'slow');
            }
            
            return valid;
        });
    }
    
    /*
     * validate text fields (input or textarea)
     */
    function validateText(el, error, type)
    {
        var content = '';
        
        if (type == 'text') {
            content = $('#' + el).val();
        }
        else 
            if (type == 'tinymce') {
                content = tinyMCE.get(el).getContent();
            }
            else {
                alert('An unexpected error has been encountered.  Please try again.  If you continue to have problems, please contact a site administrator.')
                return false;
            }
        
        //remove any error feedback that might have previously been added
        $("label[for='" + el + "'] + span.formError, div.error-message").remove();
        
        if (content == '') {
            $('div.submit span.formError').remove();
            $("label[for='" + el + "']").after('<span class="formError">' + error + '</span><br>');
            //$('div.submit').append('<span class="formError">Error: All required form fields must be filled out.  Please see above for details.</span>');
            valid = false;
        }
    }
    
    /*
     * validate checkboxes
     */
    function validateCheckBoxSelected(el, error)
    {
        //remove any error feedback that might have previously been added
        $("label[for='" + el + el + "'] + span.formError").remove();
        
        var atLeastOneChecked = false;
        
        $checkBoxSet = $("input[id^='" + el + "']");
        
        $checkBoxSet.each(function(i)
        {
            if (this.checked) {
                atLeastOneChecked = true;
            }
        });
        
        if (!atLeastOneChecked) {
            $('div.submit span.formError').remove();
            //$('div.submit').append('<span class="formError">Error: All required form fields must be filled out.  Please see above for details.</span>');
            $("label[for='" + el + el + "']").after('<span class="formError">' + error + '</span>');
            valid = false;
        }
    }
    
    /*
     * setup site help
     *    -the application makes the assumption that help markup will take the form
     *    <div><a href="/gp/menc-help#nameOfHelpSection" class="help nameOfHelpSection">Link Title</a></div>
     *    -therefore, a corresponding help section will be located at /gp/menc-help
     */
    function help()
    {
        $('a.help').each(function(i)
        {
            $help = $(this).after('<div class="help-block"></div>').next('div');
            var className = $(this).attr('class').split(' ');
            $help.hide().load($(this).attr("href") + ' div.' + className[1]);
        });
        
        //help resources
        $('a.help').click(function()
        {
            $(this).next('div').slideToggle("medium");
            return false;
        });
    }
    
    function search()
    {
        var $smSearch = $('form#smSearch');
        
        //if we are on the mmc search page
        if ($smSearch.length > 0) {
        
            $smSearch.submit(function()
            {
            
                var query = $('input#query').val();
                query = $.trim(query);
                
                if (query == "" && !atLeastOnceSearchCheckboxSelected('smSearch')) {
                    alert('You must enter a valid search term, or select at least one content category and/or relevance, prior to submitting your search request.');
                    return false;
                }
                
                return true;
                
            });
        }
    }
    
    /*
     * validate checkboxes
     */
    function atLeastOnceSearchCheckboxSelected(el)
    {
        var atLeastOneChecked = false;
        
        $checkBoxSet = $("#" + el + " input[type='checkbox']");
        
        $checkBoxSet.each(function(i)
        {
            if (this.checked) {
                atLeastOneChecked = true;
            }
        });
        
        return atLeastOneChecked;
    }
    
    function preview()
    {
        $('#preview').toggle(function()
        {
            inPreview = true;
            
            $(this).text('Continue Editing');
            $('.preview').show();
            $('.add').hide();
            $('div.err').html("<p>You are currently in preview mode.  This item needs to be submitted in order to be saved.</p>");
            
            $('h2').text('Support Music');
            
            $('h3.add_title').text($('#SupportmusicCaseTitle').attr('value')).show();
            
            //Attribution
            var attribution = $.trim(tinyMCE.get('SupportmusicCaseAttribution').getContent());
            if (attribution != "") {
                $('div.SupportmusicCaseAttribution').html(attribution);
            }
            
            //Content Categories
            var contentCategories = '';
            $('div.SupportmusicCategorySupportmusicCategory').html($('#SupportmusicCategorySupportmusicCategory :selected').text());
                        
            //Relevance
            var relevance = '';
            $('input:checked[id*=SupportmusicRelevance]').each(function(i)
            {
                relevance += $(this).next().text() + '<br>';
            });
            $('div.SupportmusicRelevance').html(relevance);
            
            //name and email
            $('.submitters_name').text($('#SupportmusicCaseSubmittersName').attr('value'));
            $('.submitters_email').text($('#SupportmusicCaseSubmittersEmail').attr('value'));
                        
            //Description text
            $('div.item_text').html(tinyMCE.get('SupportmusicCaseItemText').getContent());
            
            //Links text
            $('div.links').html(tinyMCE.get('SupportmusicCaseLinks').getContent());
                        
            
            return false;
        }, function()
        {
            inPreview = false;
            $(this).text('Preview');
            $('h2').text('Preview this Support Music Case');
            
            $('.preview').hide();
            $('.add').show();
            $('div.err p').remove();
            
            //case/tip Title
            $('h2').text('Add a Support Music Entry');
            
            return false;
        });
        
        $('#preview').bind('click', function()
        {
            $('html, body').animate({
                scrollTop: 0
            }, 'slow');
            return false;
        });
    }
    
    return {
        init: function()
        {            
            if ($('#SupportmusicCaseTitle').length > 0) {
                ///Validate case add/edit
                validateCaseFields();
            }
            authPopups();
            help();
            search();
            upload();
            preview();
        }
        
    };
    
}();

$(document).ready(function()
{
    SM.init();
});

