var JI = JI || {};

JI.getJSON = function(options){
	if(options['callback'] == null){
		options['callback'] = function(data){
			return true;
		}
	}
	this.cb = 'jsonp_request_' + Math.floor(Math.random()*1000);
	window[this.cb] = function(data){
		options.callback(data);
	}
	var head = document.getElementsByTagName("head")[0];
	this.inject = function(url){
		this.url = url.replace(/(\{|%7B)(callback)(\}|%7D)/,this.cb);
		var script = document.createElement("script");
		script.setAttribute("type","text/javascript");
		script.setAttribute("src",this.url);
		var done = false;
		script.onload = script.onreadystatechange = function(){
			if ( !done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") ) {
				done = true;
				script.onload = script.onreadystatechange = null;
				head.removeChild(script);
				try{ delete script;} catch(e){}
			}
		};
		head.appendChild(script);
	}
	this.inject(options.url);
} // JI.getJSON

JI.querystring = function(base){
	this.base = base;

	this.params = {};
	this.add = function(qs){
		if(typeof qs == 'object'){
			for(var p in qs){
				this.params[p] = qs[p];
			}
		}
		else{
				var b = qs.split('?');
				if(b.length==2){
					this.base = b[0];
					qs = b[1];
				}
			qs = qs.replace(/\+/g, ' ');
			var args = qs.split('&');

			for (var i = 0; i < args.length; i++) {
				var pair = args[i].split('=');
				var name = decodeURIComponent(pair[0]);

				var value = (pair.length==2)
					? decodeURIComponent(pair[1])
					: name;
				this.params[name] = value;
			}
		}
	}

	this.get = function(key, default_) {
		var value = this.params[key];
		return (value != null) ? value : default_;
	}

	this.contains = function(key) {
		var value = this.params[key];
		return (value != null);
	}

	this.getUrl = function(){
		var u = '';
		for(var p in this.params){
			u += '&'+p+'='+this.params[p];
		}
		u = this.base+'?'+u.substring(1,u.length);
		return u;

	}


	this.getQuery = function(){
		var u = '';
		for(var p in this.params){
			u += '&'+p+'='+this.params[p];
		}
		u = u.substring(1,u.length);
		return u;
	}

	this.remove = function(key){
		if(this.contains(key)){
			var value = this.params[key];
			delete this.params[key];
			return value;
		}
		else{
			return false;
		}
	}

	this.append = function(d,qs){
		if(typeof qs == 'object'){

			for(var p in qs){

				var value = this.params[p];
				if(value != null){
						var prm = value+d+qs[p];
						this.params[p] = prm;
				}
				else{
					for(var p in qs){
						this.params[p] = qs[p];
					}
				}

			}
		}
		else{

			var b = qs.split('?');
				if(b.length==2){
					this.base = b[0];
					qs = b[1];
				}

			qs = qs.replace(/\+/g, ' ');
			var args = qs.split('&');
			for (var i = 0; i < args.length; i++) {

				var pair = args[i].split('=');
				var name = decodeURIComponent(pair[0]);

				var value = (pair.length==2)
					? decodeURIComponent(pair[1])
					: name;
				var oldvalue = this.params[name];
				if(oldvalue != null){
						var prm = oldvalue+d+value;
						this.params[name] = prm;

				}
				else{
					this.params[name] = value;
				}
			}
		}
	}
} // JI.querystring

JI.renderPageComponent = function(options){
	Object.keys = Object.keys || function(o) {
	    var result = [];
	    for(var name in o) {
	        if (o.hasOwnProperty(name))
	          result.push(name);
	    }
	    return result;
	};

	if(options == null){
		options = {};
	}

	if(options["url"] == null){
		options["url"] = "http://www.jsonline.com/";
	}

	if(options["start"] == null){
		options["start"] = "";
	}

	if(options["end"] == null){
		options["end"] = "";
	}

	if(options["yld_mgr"] == null){
		options["yld_mgr"] = "";
	}

	if(options["styleSheets"] == null){
		options["styleSheets"] = new Array();
	}

	if(options["containerId"] == null){
		return false;
	}
	else
	{
		if (!document.getElementById(options.containerId)) return false;
		var container = document.getElementById(options.containerId);
	}

	if(options["containerPrepend"] == null)
	{
		options["containerPrepend"] = "";
	}

	if(options["containerAppend"] == null){
		options["containerAppend"] = "";
	}

	if(options["secureAdServer"] == null){
		options["secureAdServer"] = "";
	}	

	if(options["debug"] == null){
		options["debug"] = false;
	}

	var tempUrl = new JI.querystring("http://www.jsonline.com/templates/API.Json");
	tempUrl.add({"action": "get_html"});

	var slots = Object.keys(options.yld_mgr.slots);
	for (var i = 0; i < slots.length; i++)
	{
		var slotProps = Object.keys(options.yld_mgr.slots[slots[i]]);

		for (var j = 0; j < slotProps.length; j++)
		{
			temp = {};
	    	temp[slots[i] + "." + slotProps[j]] = options.yld_mgr.slots[slots[i]][slotProps[j]];

			tempUrl.add(temp);
		}
	}

	// duplicate url construction to prevent double encoding of parameter values
	if(options.baseAssetUrl == null)
	{
		tempUrl.add({"callback": encodeURIComponent("{callback}")});
		tempUrl.add({"url": encodeURIComponent(options["url"])});
		tempUrl.add({"start": encodeURIComponent(options["start"])});
		tempUrl.add({"end": encodeURIComponent(options["end"])});
		tempUrl.add({"secureAdServer": encodeURIComponent(options["secureAdServer"])});
		tempUrl.add({"pubId": encodeURIComponent(options.yld_mgr.pub_id)});
		tempUrl.add({"site": encodeURIComponent(options.yld_mgr.site_name)});
		tempUrl.add({"cTopId": encodeURIComponent(options.yld_mgr.content_topic_id_list)});

		var jsonUrl = tempUrl;
	}
	else
	{
		tempUrl.add({"callback": "{callback}"});
		tempUrl.add({"url": options["url"]});
		tempUrl.add({"start": options["start"]});
		tempUrl.add({"end": options["end"]});
		tempUrl.add({"secureAdServer": options["secureAdServer"]});
		tempUrl.add({"pubId": options.yld_mgr.pub_id});
		tempUrl.add({"site": options.yld_mgr.site_name});
		tempUrl.add({"cTopId": options.yld_mgr.content_topic_id_list});

		if(options["secureAdServer"] == true) 
		{
			var jsonUrl = new JI.querystring("https://secure.jsonline.com/branding/");
		} 
		else 
		{
			var jsonUrl = new JI.querystring("http://secure.jsonline.com/branding/");
		}
		jsonUrl.add({"url": encodeURIComponent(tempUrl.getUrl())});
		jsonUrl.add({"baseAssetUrl": encodeURIComponent(options["baseAssetUrl"])});
	}

	if(options["debug"] == true)
	{
		alert(jsonUrl.getUrl());
	}

	var req = new JI.getJSON({
		url: jsonUrl.getUrl(),
		callback:function(data){
			for (var i = 0, len = options["styleSheets"].length; i < len; ++i){
				var styleSheetElement = document.createElement("link");
				styleSheetElement.setAttribute("type","text/css");
				styleSheetElement.setAttribute("rel","stylesheet");

				if(options.baseAssetUrl == null)
				{
					var styleSheetHref = options["styleSheets"][i];
				}
				else
				{
					if(options["secureAdServer"] == true) 
					{
						var styleSheetHref = new JI.querystring("https://secure.jsonline.com/branding/");
					}
					else
					{
						var styleSheetHref = new JI.querystring("http://secure.jsonline.com/branding/");
					}
					styleSheetHref.add({"url": encodeURIComponent(options["styleSheets"][i])});
					styleSheetHref.add({"baseAssetUrl": encodeURIComponent(options["baseAssetUrl"])});
					styleSheetHref = styleSheetHref.getUrl();
				}

				styleSheetElement.setAttribute("href",styleSheetHref);
				document.getElementsByTagName("head")[0].appendChild(styleSheetElement);
			}

			container.innerHTML = container.innerHTML + options.containerPrepend + data.html + options.containerAppend;
		}
	});
} // JI.renderPageComponent

function renderPagePart2(styleSheets,url,start,end,pubId,siteName,cTopId,sz,dlv,width,height,containerId,containerPrepend,containerAppend,secureAdServer){
	for (var i = 0, len = styleSheets.length; i < len; ++i){
		document.write("<link type=\"text/css\" rel=\"stylesheet\" href=\"" + styleSheets[i] + "\" />");
	}

	var req = new JI.getJSON({
		url:"http://www.jsonline.com/templates/API.Json?action=getPagePartJSON&callback={callback}&url=" + encodeURIComponent(url) + "&start=" + encodeURIComponent(start) + "&end=" + encodeURIComponent(end) + "&pubId=" + encodeURIComponent(pubId) + "&site=" + encodeURIComponent(siteName) + "&secureAdServer=" + encodeURIComponent(secureAdServer) + "&cTopId=" + encodeURIComponent(cTopId) + "&dlv=" + encodeURIComponent(dlv) + "&sz=" + encodeURIComponent(sz) + "&width=" + encodeURIComponent(width) + "&height=" + encodeURIComponent(height),
		callback:function(data){
			document.getElementById(containerId).innerHTML = containerPrepend + data.html + containerAppend;
		}
	});
} // renderPagePart2

/*
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.todaystmj4.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.todaystmj4.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>");
    }
}

