// ----------------------------------------------------
// ------ jquery.relationshipManagement Version 2 -----
// ----------------------------------------------------
// Controls the editing of the relationships
// ----------------------------------------------------

; (function ($, window, document, undefined) {

	var pluginName = "relationshipManagement";

	function relationshipManagement(options) {
		this._name = pluginName;
		this._defaults = $.fn.relationshipManagement.defaults;
		this.options = $.extend({}, this._defaults, options);

		this.init();
	};

	function stateChanged(plugin, $this) {

		var id = $this.data("id");

		var $editButton = $("#entry" + id + "Btn");
		var $buttonText = $("#entry" + id + "Text");

		var selected = false;
		var tempVal = parseInt($this.data("selected"));

		if (isNaN(tempVal) || tempVal === 0) {
			selected = false;
		} else {
			selected = true;
		}

	    $buttonText.empty();
	    $buttonText.show();

	    var remove = selected;

	    selected = !selected;

	    plugin.save(id, remove, function () {

            var message = "";
	        var buttonMessage = "";
            var cssClass = "";
	        var removeCssClass = "";
	        var $span = null;
	        var $divImage = null;
	        var $messageDiv = null;

	        if (selected === true) {
                message = plugin.options.addMessage;
                buttonMessage = plugin.options.toRemoveMessage;

                cssClass = plugin.options.addCssClass;
	            removeCssClass = plugin.options.removeCssClass;
	        } else {
                message = plugin.options.removeMessage;
                buttonMessage = plugin.options.toAddMessage;

                cssClass = plugin.options.removeCssClass;
                removeCssClass = plugin.options.addCssClass;
	        }

	        if (selected) {

	            $editButton.removeClass(plugin.options.notSelectedClass).addClass(plugin.options.selectedClass);

	            $this.data("selected", "1");

	        } else {

                $editButton.removeClass(plugin.options.selectedClass).addClass(plugin.options.notSelectedClass);

	            $this.data("selected", "0");
	        }

	        $this.addClass("animated once shake");
	        $this.closest(".ribbonWrap").toggleClass("animated once shake");

	        if (plugin.options.placeMessageInImage === false) {
	            setTimeout(function () {
	                $editButton.find(".fadeOut").hide("slow");
	            }, 2500);

	            $buttonText.html(message);

                $buttonText.removeClass(removeCssClass).addClass(cssClass);
                $buttonText.css("visibility", "visible");
	            $buttonText.show();

	            setTimeout(function () {
                    $buttonText.hide();
	                $buttonText.css("visibility", "hidden");
	            }, 3000);

	        } else {
	            $divImage = $this.find(".trigger-card-image");

	            $divImage.empty();

	            $messageDiv = $("<div class='fadeOut'><p class='trigger-card-hoverText rs_skip'><span class='callout " + cssClass + "'>" + message + "</span></p><div class='trigger-card-tint'></div></div>");

	            $divImage.append($messageDiv);

	            setTimeout(function () {
	                $divImage.find(".fadeOut").hide("slow");
                }, 2500);

	            setTimeout(function () {
	                $messageDiv.hide();
	            }, 3000);
	        }

	        $span = $editButton.find("span");

            $span.html(buttonMessage);

	    });
	};

	$.extend(relationshipManagement.prototype, {

		init: function () {
			this.buildCache();

			this.bindEvents();
		},

		destroy: function () {
			this.unbindEvents();
		},

		buildCache: function () {

			this.$entries = $(this.options.entrySelector);
			this.$saveButton = $(this.options.saveButtonId);

			this.$errorMessageContainer = $(this.options.errorMessageContainerId);
			this.$errorMessage = $(this.options.errorMessageId);

			this.$alertBoxCloseLink = $(this.options.alertCloseLinkSelector);

		},

		bindEvents: function () {
			var plugin = this;

			plugin.$entries.on("click", function (e) {
				e.preventDefault();

				var $this = $(this);

				stateChanged(plugin, $this);
			});

			plugin.$alertBoxCloseLink.on("click", function (e) {
				e.preventDefault();

				plugin.clearError();
			});
		},

		unbindEvents: function () {
			var plugin = this;

			plugin.$entries.off("click");
			plugin.$alertBoxCloseLink.off("click");

		},

		clearError: function() {

			var plugin = this;

			plugin.$errorMessageContainer.hide();
			plugin.$errorMessage.text("");
		},

		setError: function (errorMessage) {
			var plugin = this;

			plugin.$errorMessageContainer.show();
			plugin.$errorMessage.text(errorMessage);

		},

		save: function (id, remove, successFnc) {

		    var plugin = this;

		    plugin.clearError();

            if (plugin.options.entriesUpdateUrl == null) {
		        plugin.setError("No save url has been set");
		        return;
		    }

		    var saveData = {
		        Id: id,
		        Remove: remove
		    };

		    $.ajax({
		        type: "POST",
                url: plugin.options.entriesUpdateUrl,
		        data: JSON.stringify(saveData),
		        dataType: "json",
		        contentType: "application/json; charset=utf-8",
		        cache: false,
		        success: function (data) {
		            if (data == null) {
		                plugin.setError("An error has occurred during the save.");
		                return;
		            }

		            successFnc();
		        },
		        error: function (jqXHR, textStatus, errorThrown) {
		            plugin.setError("A problem prevented the changes from being saved: " + textStatus);
		        },
		        complete: function () {

		        }
		    });
		}

	});

	$.fn.relationshipManagement = function (options) {

		var self = new relationshipManagement(options);

		return this;
	};

	$.fn.relationshipManagement.defaults = {
		entrySelector: ".editState",
		errorMessageContainerId: "#errorRow",
		errorMessageId: "#errorMessage",
		alertCloseLinkSelector: "a.close",
		addMessage: "Added",
        removeMessage: "Removed",
        toAddMessage: "Add",
        toRemoveMessage: "Remove",
        notSelectedClass: "toAdd",
        selectedClass: "isActive",
        addCssClass: "success",
        removeCssClass: "alert",
		entriesUpdateUrl: null,
		placeMessageInImage: false
    };

})(jQuery, window, document);
