/*
requires:
    jQuery
    jQuery BlockUI plugin

arguments:
    contentType, string, defaults to "content"
    formContainer, element, defaults to form element
    messagesContainer, element, defaults to new element prepended to form
*/
function doUserContent(e)
{
    // content type
    if(typeof(e.data) != "undefined" && typeof(e.data.contentType) != "undefined")
    {
        var gotContentType = e.data.contentType;
    }
    else
    {
        var gotContentType = "content";
    }

    // form
    if(typeof(e) != "undefined")
    {
        var gotForm = e;
    }
    else
    {
        return false;
    }

    /*
    if($(e.currentTarget).is("form"))
    {
        var gotForm = e.currentTarget;
    }
    else
    {
        return false;
    }
    */

    // form container
    if(typeof(e.data) != "undefined" && typeof(e.data.formContainer) != "undefined")
    {
        var gotFormContainer = e.data.formContainer;
    }
    else
    {
        var gotFormContainer = gotForm;
    }

    // messages container
    if(typeof(e.data) != "undefined" && typeof(e.data.messagesContainer) != "undefined")
    {
        var gotMessagesContainer = e.data.messagesContainer;
    }
    else // create default messages container
    {
        // default messages container id
        var gotMessagesContainerId = $(gotForm).attr("id") + "-messages";

        var gotMessagesContainer = $("#" + gotMessagesContainerId);

        if($(gotMessagesContainer).length == 0) // default messages container does not exist
        {
            // prepend messages container
            $(gotFormContainer).prepend("<div id=\"" + gotMessagesContainerId + "\"></div>");

            gotMessagesContainer = $("#" + gotMessagesContainerId);
        }
    }

    // return URL
    if($(gotForm).find("[name=rurl]"))
    {
        var gotRURL = $(gotForm).find("[name=rurl]").val();
    }
    else
    {
        var gotRURL = location.href;
    }

    // file path
    if($("input[type=file]").length > 0)
    {        
        var gotFilePath = $("input[type=file]").val();
    }
    else
    {
        var gotFilePath = "";
    }

    var gotMsgUGCContainer = $("#msgUGC");
   
    if($(gotForm).find("input[name=editContent]").val() == "Y") // edit
    {
        editUserContent(gotForm,true,function(obj){
            // debug
            //alert("editing");
            //alert("success: " + obj.success);
            //alert("contentID: " + obj.contentID);
            //alert("contentType: " + obj.contentType);
            //alert("title: " + obj.title);
            //alert("error: " + obj.error);
            //alert("messages: " + obj.messages);

            if(obj.error)
            {
                switch(obj.error)
                {
                    case("Content Type only support editing UGC created by user."):
                        // message
                        $(gotMessagesContainer).html("<p class=\"confirmationwarning\">Sorry, you can only edit your own " + $('<div/>').text(gotContentType).html() + ".</p>");

                        break;
                    case("Unable to verify user information so discussion cannot be posted"):
                        // message
                        $(gotMessagesContainer).html("<p class=\"confirmationwarning\"><a href=\"/s?action=login&amp;rurl=" + encodeURIComponent(location.href) + "\">Please login to edit this " + $('<div/>').text(gotContentType).html() + ".</a></p>");

                        break;
                    default:
                        // message
                        //$(gotMessagesContainer).html("<p class=\"confirmationerror\">" + obj.error + "</p>");

                        // even with error, content updates, manually supressing error message, further debug needed ~ Leo D 03.18.10
                        //displayUGCErrorMessage(gotMsgUGCContainer, obj.messages);
                        
                        // disable form
                        $.blockUI({
                            message: "<p class=\"confirmationwarning\">Please wait&hellip;</p>",
                            css: {
                                backgroundColor: "transparent",
                                border: "0"
                            },
                            overlayCSS: {
                                backgroundColor: "white"
                            }
                        });

                        // redirect
                        window.setTimeout(function(){
                            
                               if(gotRURL.indexOf("?") > 0){
                                    var redirectURL = gotRURL + "&r=" + 1*new Date();
                                }else{
                                    var redirectURL = gotRURL + "?r=" + 1*new Date();
                                }
                                
                                if(gotFilePath != ""){
                                    return resubmitFormForUpload(false, gotMsgUGCContainer, gotForm, obj.contentID, redirectURL, "");                                    
                                }   
                                
                                window.location = redirectURL;                                              
                            }
                            ,4000
                        );
                } // end of obj.error switch
            }
            else // no error
            {
                // disable form
                $.blockUI({
                    message: "<p class=\"confirmationwarning\">Please wait&hellip;</p>",
                    css: {
                        backgroundColor: "transparent",
                        border: "0"
                    },
                    overlayCSS: {
                        backgroundColor: "white"
                    }
                });

                switch(obj.status)
                {
                    case("Ready"):
                    
                        // redirect
                        window.setTimeout(function(){
                                                            
                                if(gotRURL.indexOf("?") > 0){
                                    var redirectURL = gotRURL + "&r=" + 1*new Date();
                                }else{
                                    var redirectURL = gotRURL + "?r=" + 1*new Date();
                                }                                   
                                    
                                if(gotFilePath != ""){
                                    return resubmitFormForUpload(false, gotMsgUGCContainer, gotForm, obj.contentID, redirectURL, "");  
                                }  
                                         
                                window.location = redirectURL;
                            }
                            ,4000
                        );

                        break;
                    case("In Progress"):
                    
                        if(gotFilePath != ""){
                            return resubmitFormForUpload(false, gotMsgUGCContainer, gotForm, obj.contentID, gotRURL, ""); 
                        }
                    
                        // redirect
                        window.location = gotRURL;

                        break;
                    default:
                         
                        $(gotMessagesContainer).html("<p class=\"confirmationquestion\">" + obj.status + "</p>");
                        //displayUGCErrorMessage(gotMsgUGCContainer, obj.messages); 
                        
                        $.unblockUI();
                } // end of obj.status switch
            } // end of obj.error check
        }); // end of editUserContent()
    }
    else // new
    {
        insertUserContent(gotForm,true,function(obj){
            // debug
            //alert("new");
            //alert("success: " + obj.success);
            //alert("contentID: " + obj.contentID);
            //alert("contentType: " + obj.contentType);
            //alert("title: " + obj.title);
            //alert("error: " + obj.error);
            //alert("messages: " + obj.messages);

            if(obj.error)
            {
                switch(obj.error)
                {
                    case("Unable to verify user information so discussion cannot be posted"):
                        // message
                        $(gotMessagesContainer).html("<p class=\"confirmationwarning\"><a href=\"/s?action=login&amp;rurl=" + encodeURIComponent(location.href) + "\">Please login to create a new " + $('<div/>').text(gotContentType).html() + ".</a></p>");

                        break;
                    default:
                        // message
                        $(gotMessagesContainer).html("<p class=\"confirmationerror\">" + obj.error + "</p>");
                        //displayUGCErrorMessage(gotMsgUGCContainer, obj.messages); 
                        
                } // end of obj.error switch
            }
            else // no error
            {
                // disable form
                $.blockUI({
                    message: "<p class=\"confirmationwarning\">Please wait&hellip;</p>",
                    css: {
                        backgroundColor: "transparent",
                        border: "0"
                    },
                    overlayCSS: {
                        backgroundColor: "white"
                    }
                });

                var objStatusSwitch = function(){ //private helper func
                    switch(obj.status)
                    {
                        case("Ready"):
                        
                           if($(gotForm).find("input[name=goToNewContent]").val() == "N"){
                                var redirectURL = gotRURL;
                            }else{
                                var redirectURL = gotRURL + obj.contentID + ".html";
                            }  
                        
                            if(gotFilePath != ""){   
                                return resubmitFormForUpload(true, gotMsgUGCContainer, gotForm, obj.contentID, redirectURL, "Ready");
                            }
                                                
                            // redirect                                                         
                            window.location = redirectURL;
    
                            break;
                        case("In Progress"):
                        
                            if(gotFilePath != ""){
                                return resubmitFormForUpload(true, gotMsgUGCContainer, gotForm, obj.contentID, gotRURL, "In Progress");
                            }
                            
                            // redirect
                            window.location = gotRURL;
    
                            break;
                        case("Unable to verify user information so discussion cannot be posted"):
                            // message
                            $(gotMessagesContainer).html("<p class=\"confirmationwarning\"><a href=\"/s?action=login&amp;rurl=" + encodeURIComponent(location.href) + "\">Please login to create a new " + $('<div/>').text(gotContentType).html() + ".</a></p>");
    
                            break;
                        default:
                            $(gotMessagesContainer).html("<p class=\"confirmationquestion\">" + obj.status + "</p>");
                            //displayUGCErrorMessage(gotMsgUGCContainer, obj.messages); 
                            
                    } // end of obj.status switch

                }

                if(obj.contentType == "JI.Event" && $("input[name='event.type']").val() == "ONCE" && $("#eventStartDate").val() != $("#eventEndDate").val()){

                    var url = "http://www.waupacanow.com/templates/API.FormProcess?command=return_date_range&start_date="+$('#eventStartDate').val()+"&end_date="+$('#eventEndDate').val();    
                    $(gotForm).find("input[name=contentID]").val(obj.contentID);
                    $(gotForm).find("input[name=editContent]").val("Y");
                                        $.getJSON(url,function(dates){
                        dates.splice(0,1);
                        var timeOutLength = 1000;
                        if(dates.length > 3){timeOutLength = 3000;}
                        $.each(dates,function(index,date){
                            window.setTimeout(function(){
                                var d = date;
                                $("#eventStartDate").val(d);
                                $("#eventEndDate").val(d);
                                    editUserContent(gotForm,true,function(obj){
                                        // debug
                                        //alert(d);
                                        //alert("contentID: " + obj.contentID);
                                        if(index + 1 == dates.length){
                                            objStatusSwitch(obj);
                                        }
                                    })
                                }
                                ,timeOutLength);                      
                        }); 
                    });           
                }else{
                    objStatusSwitch(obj);
                }
            } // end of obj.error check
        }); // end of insertUserContent()
    } // end of editContent check
} // end of doUserContent()

function resubmitFormForUpload(reset, gotMsgUGCContainer, gotForm, gotContentID, gotRURL, gotStatus)
{
    if (reset == true)
    {
        $(gotForm).find("input[name=contentID]").val(gotContentID);
        $(gotForm).find("input[name=editContent]").val("Y");
    }
    
    if (gotRURL.indexOf("http") > -1)
    {
        var root = "http://www.waupacanow.com";
        gotRURL = gotRURL.replace(root,"");
    }
    
    $(gotForm).find("[name='rurl']").val(gotRURL);
    $(gotForm).find("[id='groupEventTime']").remove();

    return editUserContent($(gotForm)[0]);
}

function displayUGCErrorMessage(gotMsgUGCContainer, message)
{
    if(typeof(message) != "undefined" && typeof(message.GLOBAL) != "undefined")
    {
        $(gotMsgUGCContainer).append("<div style='border:1px solid blue;padding:2px;color:red;'>");
        $(gotMsgUGCContainer).append("<br>ugc.messageDefault: " + message.GLOBAL[0].messageDefault);
        $(gotMsgUGCContainer).append("<br>ugc.messageKey: " + message.GLOBAL[0].messageKey);
        $(gotMsgUGCContainer).append("<br>ugc.messageType: " + message.GLOBAL[0].messageType);
        $(gotMsgUGCContainer).append("<br>ugc.messageParams[0]: " + message.GLOBAL[0].messageParams[0]);
        $(gotMsgUGCContainer).append("</div>");
    }
}
