/* Capture Widget */
var mmURL = '';
function submitIdeaAJAX() {
    var name = jQuery("#mmIdeaName").val();
    var des = jQuery("#mmIdeaDescription").val();
    var lctn = window.location.href;
    var prsn = jQuery("#mmPersonName").val();
    var email = jQuery("#mmPersonEmail").val();
    if (name == "" && des != "") {
        var length = 25;
        if (des.length < 25) {
            length = des.length;
        }
        name = des.substr(0, length);
    }
    if (name != "") {
        jQuery.ajax({
            dataType: 'jsonp',
            data: {name:name, des:des, location:lctn, person:prsn, email:email},
            url: mmURL
        });
        mmtoggleView();
    }
    else {
        jQuery(".mmIdeaName").css("border", "3px solid red");
    }
}

function mmtoggleView() {
    jQuery(".mmWF").children().toggle();
    jQuery(".mmWF").children(":input[type=text],textarea").val("");
    jQuery(".mmIdeaName").css("border", "1px #ccc solid");
}

function mmInjectWidget(url) {
    if(url) { mmURL = url; }
    jQuery("body").append("<div class='mmWidgetFlag' onclick='mmLoadPopup()'><span class='mmWidgetFlagText'>Feedback</span></div>");
    jQuery(".mmWidgetFlag").css("float", "right");
}

function mmClosePopup() {
    jQuery(".mmWidgetPopup").remove();
    jQuery(".mmWidgetBackground").remove();
}

function mmLoadPopup() {
    //var top = 80;
    var width = ((jQuery(window).width()) / 2) - 175; //originally "jQuery(document)"
    var text = "<div class='mmWidgetPopup'>" +
            "<fieldset class='mmWF'>" +
            "<div onclick='mmClosePopup()' class='mmClose' style='display:none'>Close</div>" +
            "<div class='mmMessage' onclick='mmtoggleView()' style='display:none;'>Thanks for your input! Click here to submit another idea.</div>" +
            "<div class='mmIdeaSubmit'></div>" +
            "<div onclick='mmClosePopup()' class='mmClose'>Close</div>" +
            "<label>Idea:</label>" +
            "<input type='text' id='mmIdeaName' class='mmIdeaName' name='ideaName' title='Submit an idea' />" +
            "<label>Description:</label>" +
            "<textarea id='mmIdeaDescription' class='mmIdeaDescription' name='ideaDescription' title='Add a description'></textarea>" +
            "<label>Name (optional):</label>" +
            "<input type='text' id='mmPersonName' class='mmPersonName' name='personName' title='Enter your name' />" +
            "<label>Email (optional):</label>" +
            "<input type='text' id='mmPersonEmail' class='mmPersonEmail' name='personEmail' title='Enter your email' />" +
            "<br/>" +
            "<input type='button' value='Submit Feedback!' onclick='submitIdeaAJAX()' class='mmSubmit' name='mmSubmit' />" +
            "<br/>" +
            "<a href='http://getmilemarker.com' class='mmPoweredBy'>Powered by MileMarker</a>" +
            "</fieldset>" +
            "</div>";
    var background = "<div class='mmWidgetBackground'></div>";
    jQuery("body").append(background);
    jQuery("body").append(text);
    jQuery(".mmWidgetPopup").css("top", top)
            .css("left", width);
}

/* /Capture Widget */

/* List Widget */

//var serverURL = 'http://app.getmilemarker.com';
//var mmToken = '0c346fc6-48f6-4dc9-9f61-98caad3b7b7d';
//var serverURL = 'http://localhost:8080/milemarker';

function mmGetIdeaList() {
    var intv = '';
    if (!jQuery("input:focus").hasClass("mmComment")) {
        jQuery.ajax({
            dataType: 'jsonp',
            data: {location:window.location.href},
            url: serverURL + '/widget/ideaListWidget/' + mmToken,
            success: function(response) {
                var text = "<div id='mmIdeaList' class='mmWF'>";
                jQuery.each(response, function(j, set) {
                    intv = set.interval;
                    jQuery.each(set.ideas, function(index, item) {
                        text += "<div class='mmIdea'>";

								if(mmCanVote(item.id)) {
            	    			    text += "<div class='voteBot'>";
                                } else {
                                    text += "<div class='voteBot " + mmVoteType(item.id) + "'>";
                                }
						text += "<div class='voteBotButtons'>" +
								"<span class='voteBotButton up' onclick='mmVoteForIdea(" + item.id + ",\"voteUp\")'>" +
								"<a href='javascript://'>+</a>" +
								"</span>" +
								"<span class='voteBotButton down' onclick='mmVoteForIdea(" + item.id + ",\"voteDown\")'>" +
								"<a href='javascript://'>-</a>" +
                                "</span>" +
								"</div><!-- / voteBotButtons -->" +
								"<div class='voteTotal'>" + item.totalVotes + "</div>" +
								"<ul class='voteSpark'>" +
							    "<li style='width: " + item.downVotePercentage + "%;background-color: #e88c8c'> </li>" +
								"<li style='width: " + item.upVotePercentage + "%; margin-left: -1px; background-color: #a3d18c; border-right: 1px solid #fff'> </li>" +
								"</ul>" +
								"</div><!-- / voteBot -->";

                        text +=       "<div class='mmIdeaTitle'><strong>" + item.title + "</strong></div>";

                        
                        text += "<div class='mmIdeaCreator'><label><em>Posted by " + item.creator + " on " + item.date + "</em></label></div>" +
                                "<div class='mmIdeaDescription'>" + (item.description ? item.description : '') + "</div>" +
                                "<div class='mmIdeaCommentCount' onclick='toggleComments(event)'><label>Comments (" + item.comments.length + ") <a class='mmCommentToggle' style='text-decoration:none;' href='javascript:'>[+]</a></label></div>" +
                                "<div class='mmIdeaComments'>";
                                jQuery.each(item.comments, function(i, comment) {
                                    text += "<div class='mmIdeaComment'>" +
                                            "<div class='mmIdeaCommentCreator'><label><em>Posted by " + comment.creator + " on " + comment.date + "</em></label></div>" +
                                            "<div class='mmIdeaCommentTitle'>" + comment.title + "</div></div>";
                                });
                        text += "<a href='javascript:' class='mmToggleAddComment' onclick='toggleAddComment(event)'>Add a Comment</a>" +
                                "</div><div class='mmAddComment' ><label>Name</label><input class='mmCommenter' id='mmAddCommentName" + item.id + "' type='text'><br /><label>Comment</label><textarea class='mmComment' id='mmAddCommentText" + item.id + "' type='text'></textarea>" +
                                "<br /><input type='button' class='mmSubmit' onClick='mmAddComment(" + item.id + ")' value='Add comment'/>" +
                                "<a href='javascript:' class='mmCancel' onclick='toggleAddComment(event);'>cancel</a></div>" +
                                "</div>";
                    });
                });
                text += "</div>";
                window.clearInterval(mmIntv);
                mmIntv = "";
                if (intv) {
                    mmIntv = window.setInterval(mmGetIdeaList, intv);
                }
                jQuery('#mmIdeaList').replaceWith(text);
            }
        });
    }
}

function mmAddComment(id) {
    var comment = jQuery("#mmAddCommentText" + id).val();
    var name = jQuery("#mmAddCommentName" + id).val();
    jQuery.ajax({
        dataType: 'jsonp',
        data: {ideaId:id, name:name, comment:comment, location:window.location.href},
        url: serverURL + '/widget/postComment/' + mmToken,
        success: function(response) {
            mmGetIdeaList();
        }
    });
}

function mmCanVote(ideaId) {
    var canVote = true;
    var cookie = jQuery.cookie('mmVC_5348_9372_'+ideaId);
    if(cookie == 'voteUp' || cookie == 'voteDown') {
        canVote = false;
    }
    return canVote
}

function mmVoteType(ideaId) {
    return jQuery.cookie('mmVC_5348_9372_'+ideaId);
}

function mmBuildCookie(ideaId, type) {
    var array = new Object();
    array['mmVC_5348_9372_'+ideaId] = type;
    jQuery.cookie(array, {expires:1});
}

function mmVoteForIdea(id, type) {
    if(mmCanVote(id)) {
        jQuery.ajax({
            dataType: 'jsonp',
            data: {ideaId:id, type:type, location:window.location.href},
            url: serverURL + '/widget/voteForIdea/' + mmToken,
            success: function(response) {
                mmBuildCookie(id, type);
                mmGetIdeaList();
            }
        });
    }
}

function toggleComments(event) {
    var idea = jQuery(event.target).closest(".mmIdea");
    var comments = idea.find(".mmIdeaComments");
    var clickedInCommentsSection = (jQuery(event.target).closest(".mmIdeaComments").size() > 0);
    var clickedInAddCommentSection = (jQuery(event.target).closest(".mmAddComment").size() > 0);
    var addCommentButton = idea.find(".mmToggleAddComment");
    var addComment = idea.find(".mmAddComment");
    var commentToggle = idea.find(".mmCommentToggle");

    if (!clickedInCommentsSection && !clickedInAddCommentSection) {
        if (comments.is(':visible') && addComment.is(':hidden')) {
            comments.hide();
            addCommentButton.show();
            addComment.hide();
            commentToggle.text("[+]");
        }
        else {
            comments.show();
            commentToggle.text("[-]");
        }
    }
}

function toggleAddComment(event) {
    var idea = jQuery(event.target).closest(".mmIdea");
    var addComment = idea.find(".mmAddComment");
    var addCommentButton = idea.find(".mmToggleAddComment");
    var cancelButton = idea.find(".mmCancel");


    if (addComment.is(":hidden")) {
        addCommentButton.hide();
        addComment.show();
        cancelButton.show();
    }
    else {
        addComment.hide();
        addCommentButton.show();
        cancelButton.show();
    }
}

/* /List Widget */

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Create multiple cookies at once stored in an object, with optional parameters affecting them all.
 *
 * @example $.cookie({ 'the_cookie' : 'the_value' });
 * @desc Set/delete multiple cookies at once.
 * @example $.cookie({ 'the_cookie' : 'the_value' }, { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Set/delete multiple cookies with options.
 *
 * @param Object name An object with multiple cookie name-value pairs.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the names and values of all cookies for the page.
 *
 * @example $.cookie();
 * @desc Get all the cookies for the page
 *
 * @return an object with the name-value pairs of all available cookies.
 * @type Object
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */


jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined'  ||  (name  &&  typeof name != 'string')) { // name and value given, set cookie
        if (typeof name == 'string') {
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            // CAUTION: Needed to parenthesize options.path and options.domain
            // in the following expressions, otherwise they evaluate to undefined
            // in the packed version for some reason...
            var path = options.path ? '; path=' + (options.path) : '';
            var domain = options.domain ? '; domain=' + (options.domain) : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = name + '=' + encodeURIComponent(value) + expires + path + domain + secure;
        } else { // `name` is really an object of multiple cookies to be set.
          for (var n in name) { jQuery.cookie(n, name[n], value||options); }
        }
    } else { // get cookie (or all cookies if name is not provided)
        var returnValue = {};
        if (document.cookie) {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (!name) {
                    var nameLength = cookie.indexOf('=');
                    returnValue[ cookie.substr(0, nameLength)] = decodeURIComponent(cookie.substr(nameLength+1));
                } else if (cookie.substr(0, name.length + 1) == (name + '=')) {
                    returnValue = decodeURIComponent(cookie.substr(name.length + 1));
                    break;
                }
            }
        }
        return returnValue;
    }
};

