var LPL = function()
{

    var valid = true, popContentLoaded = false, inPreview = false;
    
    /*
     * Ensure that a user agrees to the sites terms of service
     */
    function tos()
    {
        $tos = $('#LessonTosAgreement');
        $submit = $("input[type='submit']");
        
        $tos.click(function()
        {
            if ($(this)[0].checked == true) {
                $submit.attr('disabled', '');
            }
            else {
                $submit.attr('disabled', 'disabled');
                alert('You must agree to our terms of service before you can submit this lesson');
            }
        });
    }
    
    /*
     * add features to add/remove upload
     */
    function upload()
    {
        //in edit mode uncheck these boxes
        $("input[name='data[Lesson][LessonsUpload][]']").attr('checked', '');
        
        //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('');
        });
        
        //Remove an upload node
        $('a.removeUpload').click(function()
        {
            $(this).parent().remove();
            $('div.uploadMaster:eq(1)').addClass('uploadResourceHighlight');
        });
        
        //make sure that the displayed upload files are links
        $("input[name='data[Lesson][CurrentUploads][]']+label").each(function(i)
        {
            $(this).after('<a href="' + $(this).text() + '" target="_blank">' + $(this).text() + '</a>').remove();
        });

        $("input[name='data[TeachingTip][CurrentUploads][]']+label").each(function(i)
        {
            $(this).after('<a href="' + $(this).text() + '" target="_blank">' + $(this).text() + '</a>').remove();
        });
        
        //make sure that the displayed resources are links
        $("input[name='data[Lesson][CurrentResources][]']+label").each(function(i)
        {
            $(this).after('<a href="' + $(this).text() + '" target="_blank">' + $(this).text() + '</a>').remove();
        });
    }
    
    /*
     * add features to add/remove resources
     */
    function resources()
    {
        //in edit mode uncheck these boxes
        $("input[name='data[Lesson][LessonsSupplementalResource][]']").attr('checked', '');
        
        //master represents a default upload box
        //this acts as a template
        var $master = $('div.resourceMaster:eq(0)');
        
        //hide the template if in javascript mode
        $master.hide();
        
        $master.clone(true).insertAfter($master).show();
        $('div.resourceMaster:eq(1) input').val('http://');
        
        //Add an additional resource node
        $('a.addResource').click(function()
        {
            $master.clone(true).insertAfter($master).show();
            $('div.resourceMaster').removeClass('uploadResourceHighlight');
            $('div.resourceMaster:eq(1)').addClass('uploadResourceHighlight');
            $('div.resourceMaster:eq(1) input').val('http://');
        });
        
        //Remove the resource node
        $('a.removeResource').click(function()
        {
            $(this).parent().remove();
            $('div.resourceMaster:eq(1)').addClass('uploadResourceHighlight');
        });
    }
    
    /*
     * request removal of a lesson
     */
    function requestRemove()
    {
        setupAjaxFeedback();
        
        $('a.requestRemove').click(function(e)
        {
        
            var c = confirm("Are you sure you want to request the removal of this lesson?");
            
            if (c == false) {
                $("#popShowRemove").slideUp("slow");
                return false;
            }
            
            //submit the remove request via ajax
            $.ajax({
                type: "POST",
                url: $(this).attr("href"),
                timeout: 5000,
                error: function(r)
                {
                    $(".succ").empty();
                    $(".warn").empty();
                    $(".err").html("<p>We were unable to submit your request.  Please try again.");
                },
                success: function(r)
                {
                    $(".err").empty();
                    $(".warn").empty();
                    $(".succ").html("<p>Your request has been successfully sent.");
                }
            });
            
            return false;
        });
    }
    
    /*
     * report inappropriate lesson 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 lesson plan fields
     */
    function validateLessonFields()
    {
        //validate fields for add/edit lessons
        $('form#LessonAddForm, form#LessonEditForm').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 Lesson');
            
            //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('LessonTitle', 'Please enter a valid title.', 'text');
            validateText('LessonOriginalAuthor', 'Please enter the original author.', 'text');
            validateText('LessonDescription', 'Please enter a description.', 'tinymce');
            validateText('LessonObjectives', 'Please enter your lesson objectives.', 'tinymce');
            validateText('LessonPriorKnowledge', 'Please enter the required prior knowledge.', 'tinymce');
            validateText('LessonMaterials', 'Please enter the lesson materials.', 'tinymce');
            validateText('LessonProcedures', 'Please enter the lesson procedures.', 'tinymce');
            validateCheckBoxSelected('GradeLevel', 'Please select at least one grade level.');
            validateCheckBoxSelected('ContentCategory', 'Please select at least one grade level.');
            validateCheckBoxSelected('Standard', 'Please select at least one lesson standard.');
            
            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;
        });
    }
    
    /*
     * javascript validation for various lesson plan fields
     */
    function validateTeachingTipFields()
    {
        //validate fields for add/edit lessons
        $('form#TeachingTipAddForm, form#TeachingTipEditForm').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 Teaching Tip');
            
            //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('TeachingTipTitle', 'Please enter a valid teaching tip.', 'text');
            validateText('TeachingTipAuthor', 'Please enter the author.', 'text');
            validateText('TeachingTipDescription', 'Please enter a description.', 'tinymce');
            validateCheckBoxSelected('GradeLevel', 'Please select at least one grade level.');
            validateCheckBoxSelected('ContentCategory', 'Please select at least one grade level.');
            
            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").remove();
        
        if (content == '') {
            $('div.submit span.formError').remove();
            $("label[for='" + el + "']").after('<span class="formError">' + error + '</span>');
            //$('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 $mmcSearch = $('form#mmcSearch');
        
        //if we are on the mmc search page
        if ($mmcSearch.length > 0) {
        
            $mmcSearch.submit(function()
            {
            
                var query = $('input#query').val();
                query = $.trim(query);
                
                if (query == "" && !atLeastOnceSearchCheckboxSelected('mmcSearch')) {
                    alert('You must enter a valid search term, or select at least one content category and/or grade level, 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('My Music Class');
            
            //Lesson/tip Title
            if ($('#LessonTitle').length > 0) {
                $('h3.add_title').text($('#LessonTitle').attr('value'));
            } else {
                $('h3.add_title').text($('#TeachingTipTitle').attr('value'));
            }
                        
            //Grade Levels
            var gradeLevels = '';
            $('input:checked[id^=GradeLevel]').each(function(i)
            {
                gradeLevels += $(this).next().text() + '<br>';
            });
            $('div.GradeLevel').html(gradeLevels);
            
            //Content Categories
            var contentCategories = '';
            $('input:checked[id^=ContentCategory]').each(function(i)
            {
                contentCategories += $(this).next().text() + '<br>';
            });
            $('div.ContentCategory').html(contentCategories);
            
            //Description text
            if ($('#LessonDescription').length > 0) {
                $('div.add_description').html(tinyMCE.get('LessonDescription').getContent());
            } else {
                $('div.add_description').html(tinyMCE.get('TeachingTipDescription').getContent());
            }
            
            //only perform these actions if we are on the lesson preview page
            if ($('#LessonDescription').length > 0) {
                //Standards
                var standards = '';
                $('input:checked[id^=Standard]').each(function(i)
                {
                    standards += '<li>' + $(this).next().text() + '</li>';
                });
                $('ul.add_standards').html(standards);
                
                //Objectives
                $('div.add_objectives').html(tinyMCE.get('LessonObjectives').getContent());
                
                //Prior Knowledge
                $('div.add_prior_knowledge').html(tinyMCE.get('LessonPriorKnowledge').getContent());
                
                //Materials
                $('div.add_materials').html(tinyMCE.get('LessonMaterials').getContent());
                
                //Procedures
                $('div.add_procedures').html(tinyMCE.get('LessonProcedures').getContent());
                
                //Extensions
                var extensions = $.trim(tinyMCE.get('LessonExtensions').getContent());
                if (extensions != "") {
                    $('div.add_extensions').html(extensions);
                    $('h4.add_extensions').show();
                } else {
                    $('h4.add_extensions').hide();
                    $('div.add_extensions').html('');
                }
                
                //Assessment
                var assessment = $.trim(tinyMCE.get('LessonAssessmentNotes').getContent());
                if (assessment != "") {
                    $('div.add_assessment').html(assessment);
                    $('h4.add_assessment').show();
                } else {
                    $('h4.add_assessment').hide();
                    $('div.add_assessment').html('');
                }
                
                //Sources
                var sources = $.trim(tinyMCE.get('LessonSources').getContent());
                if (sources != "") {
                    $('div.add_sources').html(sources);
                    $('h4.add_sources').show();
                } else {
                    $('h4.add_sources').hide();
                    $('div.add_sources').html('');
                }
            }
            
            //Resources   
            //12/29/08 - Resources have been removed per instructions from MENC
            //however this code has been left in place in the event we are asked
            //to add support for resources back into the application     
            var resources = '';
            if ($('#TeachingTipResources').length > 0) {
                resources = $.trim(tinyMCE.get('TeachingTipResources').getContent());
            } else if($('#LessonLessonPlanResources').length > 0) {
                resources = $.trim(tinyMCE.get('LessonLessonPlanResources').getContent());
            }
            
            if (resources != "") {
                $('div.add_resources').html(resources);
                $('h4.add_resources').show();
            } else {
                $('h4.add_resources').hide();
                $('div.add_resources').html('');
            }
            
            //Author Information
            $('ul.add_author_information').html($('ul.sidebar_list').html());
            if ($('#TeachingTipAuthor').length > 0) {
                $('ul.add_author_information').prepend('<li><strong>Author</strong>: ' + $('#TeachingTipAuthor').attr('value') + '</li>');
            } else {
                $('ul.add_author_information').prepend('<li><strong>Original Author</strong>: ' + $('#LessonOriginalAuthor').attr('value') + '</li>');
            }
            
            return false;
        }, function()
        {
            inPreview = false;
            
            if ($('#TeachingTipTitle').length > 0) {
                $(this).text('Preview This Teaching Tip');
            } else {
                $(this).text('Preview This Lesson');
            }
            
            $('.preview').hide();
            $('.add').show();
            $('div.err p').remove();
            
            //Lesson/tip Title
            if ($('#TeachingTipTitle').length > 0) {
                $('h2').text('Add a Teaching Tip');
            } else {
                $('h2').text('Add a Lesson');
            }
            
            return false;
        });
        
        $('#preview').bind('click', function()
        {
            $('html, body').animate({
                scrollTop: 0
            }, 'slow');
        });
    }
    
    return {
        init: function()
        {
            //Lesson Uploads
            upload();
            
            //Lesson Resources
            resources();
            
            if ($('#LessonTitle').length > 0) {
                ///Validate lesson add/edit
                validateLessonFields();
            }
            
            if ($('#TeachingTipTitle').length > 0) {
                ///Validate teachingtip add/edit
                validateTeachingTipFields();
            }
            
            //Terms of service
            tos();
            
            //User Nav Popup
            authPopups();
            
            //request the removal of a lesson.
            requestRemove();
            
            //Set up lpl help
            help();
            
            search();
            
            preview();
        }
        
    };
    
}();



/*
 * For use with integration of 3rd party service (video storage) Sesame Vault
 */
var Uploader = function()
{

    var upload_key = '', $submit;
    
    function submit_file()
    {
    
        // Get just the name of the file, leaving out its path
        var file_name = $('#sesame_file').val();
        
        if (file_name.indexOf("\\") != -1) 
            file_name = file_name.match(/\\*([^\\]*)$/)[1];
        else 
            file_name = file_name.match(/\/*([^\/]*)$/)[1];
        
        $('#message').html('Uploading...');
        
        $.ajax({
            type: "POST",
            url: '/js/upload_info.php?file_name=' + encodeURIComponent(file_name),
            error: function(r)
            {
                alert("<p>We were unable to submit your upload request.  Please try again.");
            },
            success: function(r)
            {
            
                var results = eval('(' + r + ')');
                
                var upload_key = results.upload_key;
                var sig = results.sig;
                var time = results.time;
                
                Uploader.upload_key = upload_key;
                
                var url = 'http://www.sesamevault.com/upload/new/file?upload_key=' + upload_key + '&_sig=' + sig + '&_date=' + time;
                
                $('#sesame_upload_form').attr('action', url);
                $('#sesame_upload_form').submit();
                
                progress();
            }
        });
    }
    
    function progress()
    {
    
        if (!Uploader.upload_key) 
            return false;
        
        $('#progressContainer').css('display', 'block');
        
        var url = '/js/upload_info.php?upload_key=' + Uploader.upload_key;
        
        $.ajax({
            type: "POST",
            url: url,
            error: function(r)
            {
                alert("<p>We were unable to submit your upload request.  Please try again.");
            },
            success: function(r)
            {
                var response = null;
                response = eval('(' + r + ')');
                
                response.message = response.message ||
                {};
                
                if (!response.message) 
                    setTimeout(progress, 1000);
                
                if (response.message.video_id) {
                    completed(response.message.video_id);
                    
                    //because we are having the user add a link to their video as a 
                    //resource, the need to tag a video isn't necessary
                    //tag_video(response.message.video_id);
                }
                else 
                    if (response.message.status) {
                        inProgress(response.message.status.received, response.message.status.size);
                    }
                    else {
                        setTimeout(progress, 1000);
                    }
            }
        });
    }
    
    function inProgress(bytes_transfered, bytes_total)
    {
        var percent = Math.round(100 * bytes_transfered / bytes_total);
        
        $('#message').html(percent + '% complete...');
        $('#progressBar').css('width', percent + '%');
        setTimeout(progress, 1000);
    }
    
    function completed(video_id)
    {
        $('#progressBar').css('width', 0);
        $('#progressContainer').css('display', 'none');
        
        
        var url = location.protocol + '//' + location.host + '/lessons/media/' + video_id;
        
        var message = '<div id="sesame_alert"><p>Your upload is complete!  In order to associate this upload with your lesson, please' +
        ' copy/paste or type the following url into the resources box located on the lesson upload page, and select the appropriate resource type: <p><strong>' +
        url +
        '</strong></p></div>';
        
        $('#message').html(message);
        $('#sesame_submit').removeAttr("disabled");
    }
    
    function tag_video(video_id)
    {
        var tagUrl = "/js/upload_tag.php";
        
        $.ajax({
            type: "POST",
            url: tagUrl,
            data: {
                video_id: video_id
            },
            error: function(r)
            {
                alert("We were unable to associate this upload with your lesson.  Please try to upload the file again.  If this problem persists, please contact the site administrator.");
            },
            success: function(r)
            {
            }
        });
    }
    
    return {
    
        'init' : function()
        {
            var $sesame = $('#sesame_submit');
            
            //if we are on the MMC add/edit lesson page
            if ($sesame.length > 0) {
                $sesame.bind('click', function(e)
                {
                
                    $submit = $(this);
                    var file = $('input#sesame_file').val();
                    file = $.trim(file);
                    
                    if (file != '') {
                        $sesame.attr("disabled", "true");
                        submit_file();
                        
                    }
                    else {
                        alert('Please browse for a valid file before attempting to upload.');
                    }
                    
                    return false;
                });
            }
            
        }
        
    };
}();

$(document).ready(function()
{
    LPL.init();
    Uploader.init();
});
