﻿
(function($) {
    $.fn.ECfavorites = function(options) {
        var defaults = {
            path: document.location.pathname, //the path to pass to the services
            servicepath: "/Services/AJAXService.asmx",
            imgID: "imgFav",
            type: 1, // Favorite
            devPath: "/EducationCents.Site",
            addImgSrc: "/App_Themes/EducationCents/images/common/", //"~/App_Themes/EducationCents/images/common/AddFav.gif",
            removeImgSrc: "/App_Themes/EducationCents/images/common/", //"~/App_Themes/EducationCents/images/common/RemoveFav.gif"
            favAddImgName: "AddFav.gif",
            favRemoveImgName: "RemoveFav.gif",
            toolboxAddImgName: "AddToolbox.gif",
            toolboxRemoveImgName: "RemoveToolbox.gif"
        };

        var options = $.extend(defaults, options);

        return this.each(function() {

            //Global references
            var $original = $(this);
            var $servicepath = options.servicepath; //options.devPath + 
            var $img;
            var $add_imgpath = options.addImgSrc + ((options.type == 1) ? options.favAddImgName : options.toolboxAddImgName); //options.devPath +
            var $remove_imgpath = options.removeImgSrc + ((options.type == 1) ? options.favRemoveImgName : options.toolboxRemoveImgName);

            var $tool_name = "";
            var $anchor = "";

            //For more then one item on a page having a favorite link
            var index = $("." + options.imgID).length;
            var $imgID = options.imgID + index;

            //Initialize our plugin
            function init() {

                if (options.type >= 2) {
                    $anchor = $original.attr("name");
                    $tool_name = $original.attr("title");
                }
                else if (options.type == 1) {
                    $tool_name = $original.text();
                }

                if ($(".courseNav").size() > 0 && options.type == 1) {
                    $(".courseNav:first").after("<div style=\"float: right;\"><img style=\"display:none;\" id=\"" + $imgID + "\" class=\"" + options.imgID + "\" /></div>");
                }
                else {
                    if (options.type == 1) {
                        $original.after("<div style=\"float: right;\"><img style=\"display:none;\" id=\"" + $imgID + "\" class=\"" + options.imgID + "\" /></div>");
                    } else if (options.type > 1) {
                        $original.after("<div style=\"height:29px; text-align: right; padding-top: 10px;\" align=\"right\"><img style=\"display:none;\" id=\"" + $imgID + "\" class=\"" + options.imgID + "\" /></div>");
                    }
                }

                try {
                    jQuery('#dialog').jqm();
                }
                catch (ex) {
                    alert("install jqm");
                }

                var path = options.path;
                if (options.type >= 2) {
                    path += "#" + $anchor;
                }

                //Check to see if current path is a Favorite
                //This will have to be different for toolboxes
                $.ajax({
                    type: 'POST',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    url: $servicepath + '/IsFavorite',
                    data: "{'path':'" + path + "'}",
                    success: onIsFavorite,
                    error: onError
                });

                //IE shows empty box for a split second
                $img = $("#" + $imgID);
                $img.show();

                //Attach click event to the previsouly inserted image
                $img.click(function() {
                    //add or subtract depending on the state that we are in
                    if ($img.attr("favID") == null || $img.attr("favID") == -1) {
                        addingFavorite();
                    }
                    else {
                        removingFavorite();
                    }
                });
            }

            //Call web service to add path to favorites
            function addingFavorite() {
                var path = options.path;
                if (options.type >= 2) {
                    path += "#" + $anchor;
                }
                $.ajax({
                    type: 'POST',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    url: $servicepath + '/AddFavorite',
                    data: "{'path':'" + path + "', 'name': '" + $tool_name + "', 'type' : '" + options.type + "'}",
                    success: onAddFavorite,
                    error: onError
                });
            }


            //Call web service to remove path from favorites
            function removingFavorite() {
                $.ajax({
                    type: 'POST',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    url: $servicepath + '/RemoveFavorite',
                    data: "{'favID':'" + $img.attr("favID") + "'}",
                    success: onRemoveFavorite,
                    error: onError
                });
            }

            /*************************
            Ajax response Functions
            *************************/
            function onRemoveFavorite(data, textStatus) {
                set_image(-1, $add_imgpath);
                addImgeAlt(false);
            }

            function onAddFavorite(data, textStatus) {
                if (data.d != -1) {
                    set_image(data.d, $remove_imgpath);
                }
                else {
                    jQuery('#dialog').jqmShow(); //alert("popup modal");
                }

                addImgeAlt(true);
            }

            function onIsFavorite(data, textStatus) {

                if (data.d != null) {
                    set_image(data.d.ItemID, $remove_imgpath);
                    addImgeAlt(true);
                }
                else {
                    set_image(-1, $add_imgpath);
                    addImgeAlt(false);
                }
            }

            function addImgeAlt(isAdding) {
                if (isAdding) {
                    if (options.type == 1) {
                        $img.attr("alt", "Remove from Favorites");
                        $img.attr("title", "Remove from Favorites");
                    }
                    else {
                        $img.attr("alt", "Remove from Toolbox");
                        $img.attr("title", "Remove from Toolbox");
                    }
                }
                else {
                    if (options.type == 1) {
                        $img.attr("alt", "Add to Favorites");
                        $img.attr("title", "Add to Favorites");
                    }
                    else {
                        $img.attr("alt", "Add to Toolbox");
                        $img.attr("title", "Add to Toolbox");
                    }
                }
            }

            function set_image(favID, src) {
                $img.attr("favID", favID).attr("src", src);
            }

            function onError(XMLHttpRequest, textStatus, errorThrown) {
                //debugger;
                //var error = eval("(" + XMLHttpRequest.responseText + ")");
                //if (error.Message == 'No email addresses found')

                alert("error: " + XMLHttpRequest.responseText);
            }

            //Start the jquery!
            init();
        });
    };
})(jQuery); 