$j = jQuery;

if (self.RatingManager) { // DEBUG
    alert("The generic.js is included into this page twice. Please remove the duplicate from the template (probably {% block extrahead %}{% endblock %}).");
}

self.RatingManager = {
    init: function() {
    },
    destruct: function() {
        self.RatingManager = null;
    },
    rate: function(iCounter, iCTId, oObjId, iPoints) {
        $j("#star_rating_" + iCounter).addClass("progress").css({
            cursor: "wait"
        });
        $j.get(
            "/helper/rating/" + iCTId + "/" + oObjId + "/" + iPoints + "/",
            new Function("sData", "self.RatingManager.showResults(sData, '" + iCounter + "')")
        );
        return false;
    },
    showResults: function(sData, iCounter) {
        eval("oData = " + sData);
        var $oEl = $j("#star_rating_" + iCounter);
        if (oData) {
            width = oData['average_points_rounded'] * 20
            $oEl.html(
                '<div class="star-rating-results-background"><div class="star-rating-results-progress" style="width: ' + width + 'px"></div></div>'
            );
            $j("#star_rating_count_" + iCounter).html(
                oData['rating_count']
            );
            $j("#star_rating_average_" + iCounter).html(
                oData['average_points']
            );
        }
        $oEl.removeClass("progress").css({cursor: "pointer"});
    }
};

self.FavoriteManager = {
    sContextItemType: "",
    sSlug: "",
    sInnerTextToAdd: gettext("Add to favorites"),
    sTitleToAdd: gettext("Add to favorites"),
    sInnerTextToRemove: gettext("It's your favorite"),
    sTitleToRemove: gettext("Remove from favorites"),
    init: function() {
        var oSelf = self.FavoriteManager; 
        var aUrlBits = document.location.pathname.substr(1).split("/");
        // person|institution|event|document|group
        oSelf.sContextItemType = aUrlBits[0];
        var sLang = window.settings.lang;
        if (settings.URL_ID_INSTITUTION == oSelf.sContextItemType) {
            oSelf.sSlug = aUrlBits[1];
            $j(
                "#activity_" + sLang + " .navi_add-institution-to-favorites_" + sLang + ",#activity_" + sLang + " .navi_remove-institution-from-favorites_" + sLang
            ).click(function() {
                $j("#adding_to_favorites_0").click();
                return false;
            });
        } else if (settings.URL_ID_DOCUMENT == oSelf.sContextItemType) {
            oSelf.sSlug = aUrlBits[1];
            var sLang = window.settings.lang;
            $j(
                "#activity_" + sLang + " .navi_add-document-to-favorites_" + sLang + ",#activity_" + sLang + " .navi_remove-document-from-favorites_" + sLang
            ).click(function() {
                $j("#adding_to_favorites_0").click();
                return false;
            });
        }
    },
    destruct: function() {
        self.FavoriteManager = null;
    },
    toggle: function(iCounter, iCTId, oObjId) {
        $j("#adding_to_favorites_" + iCounter).addClass("progress").css({
            cursor: "wait"
        });
        $j.get(
            "/helper/favorite/" + iCTId + "/" + oObjId + "/",
            new Function("sData", "self.FavoriteManager.showResults(sData, '" + iCounter + "')")
        );
        return false;
    },
    showResults: function(sData, iCounter) {
        eval("oData = " + sData);
        var oSelf = self.FavoriteManager;
        var $oEl = $j("#adding_to_favorites_" + iCounter);
        if (oData) {
            $oSpan = $oEl.children("span:first");
            if (oData["action"] == "added") {
                $oEl.attr({
                    title: oSelf.sTitleToRemove
                }).addClass("active");
                $oSpan.html(oSelf.sInnerTextToRemove);
            } else {
                $oEl.attr({
                    title: oSelf.sTitleToAdd
                }).removeClass("active");
                $oSpan.html(oSelf.sInnerTextToAdd);
            }
            if (oData["count"] != undefined) {
                $oEl.children(".favorites_count").text(oData["count"]);
            }
        }
        $oEl.removeClass("progress").css({cursor: "pointer"});
        var sLang = window.settings.lang;
        $j("#activity_" + sLang).load(
            document.location.pathname + " #activity_" + sLang,
            oSelf.init
        );
    }
};

self.FavoriteContactManager = {
    sInnerTextToAdd: gettext("Add to contacts"),
    sTitleToAdd: gettext("Add to contacts"),
    sInnerTextToRemove: gettext("It's your contact"),
    sTitleToRemove: gettext("Remove from contacts"),
    init: function() {
    },
    destruct: function() {
        self.FavoriteContactManager = null;
    },
    toggle: function(iCounter, iCTId, oObjId) {
        $j("#adding_to_favorites_" + iCounter).addClass("progress").css({
            cursor: "wait"
        });
        $j.get(
            "/helper/favorite/" + iCTId + "/" + oObjId + "/",
            new Function("sData", "self.FavoriteContactManager.showResults(sData, '" + iCounter + "')")
        );
        return false;
    },
    showResults: function(sData, iCounter) {
        eval("oData = " + sData);
        var oSelf = self.FavoriteContactManager;
        var $oEl = $j("#adding_to_favorites_" + iCounter);
        if (oData) {
            $oSpan = $oEl.children("span:first");
            if (oData["action"] == "added") {
                $oEl.attr({
                    title: oSelf.sTitleToRemove
                }).addClass("active");
                $oSpan.html(oSelf.sInnerTextToRemove);
            } else {
                $oEl.attr({
                    title: oSelf.sTitleToAdd
                }).removeClass("active");
                $oSpan.html(oSelf.sInnerTextToAdd);
            }
        }
        $oEl.removeClass("progress").css({cursor: "pointer"});
    }
};

self.MemoManager = {
    sInnerTextToAdd: gettext("Add to Memo"),
    sTitleToAdd: gettext("Add to Memo"),
    sInnerTextToRemove: gettext("Remove Memo"),
    sTitleToRemove: gettext("Remove Memo"),
    init: function() {
    },
    destruct: function() {
        self.MemoManager = null;
    },
    toggle: function(iCounter, iCTId, oObjId) {
        $j("#adding_to_memos_" + iCounter).addClass("progress").css({
            cursor:"wait"
        });
        $j.get(
            "/helper/memo/" + iCTId + "/" + oObjId + "/",
            new Function("sData", "self.MemoManager.showResults(sData, '" + iCounter + "')")
        );
        return false;
    },
    showResults: function(sData, iCounter) {
        var oSelf = self.MemoManager;
        eval("oData = " + sData);
        $oEl = $j("#adding_to_memos_" + iCounter);
        if (oData) {
            $j("ul.toolbar .memos .item_count").text(oData.memo_count);
            if (oData.memo_count == 0) {
                $j("ul.toolbar .memos").addClass("hidden");
            } else {
                $j("ul.toolbar .memos").removeClass("hidden");
            }
            $oSpan = $oEl.children("span:first");
            if (oData["action"] == "added") {
                $oEl.attr({
                    title: oSelf.sTitleToRemove
                }).addClass("active");
                $oSpan.html(oSelf.sInnerTextToRemove);
            } else {
                $oEl.attr({
                    title: oSelf.sTitleToAdd
                }).removeClass("active");
                $oSpan.html(oSelf.sInnerTextToAdd);
                if (-1 != document.location.pathname.indexOf("/memos/")) {
                    $oSpan.parents(".info:first").fadeOut("normal").slideUp("normal", function() {
                        $j(this).remove();
                        $j(".info:odd").removeClass("odd even").addClass("odd");
                        $j(".info:even").removeClass("odd even").addClass("even");
                    });
                }
            }
        }
        $oEl.removeClass("progress").css({cursor: "pointer"});
    }
};

self.ListManager = {
    init: function() {
     	var oSelf = self.ListManager;
     	
     	$j("#id_list_pagination").change(function () {
        	oSelf.paginate_by($j(this).val());
        });
     	
     	$j("#id_list_sorting").change(function () {
        	oSelf.order_by($j(this).val());
        });
        
        $j(".abc_filter a").click(function () {
        	oSelf.filter_by_abc($j(this).attr("id"));
        });

     	$j("#id_list_view").change(function () {
        	oSelf.view_by($j(this).val());
        });
     	
    },
    
    paginate_by: function(iItems) {
    	if (iItems) {
            append_to_get({page: null, paginate_by: iItems});
	    }
    },
    
    order_by:  function(sVal) {
    	if (sVal) {
            append_to_get({page: null, order_by: sVal});
	    }
    },
    
    view_by:  function(sVal) {
        if (sVal == "gallery") {
            alert(gettext("Gallery view is not yet implemented!"));
        }
    },
    
    filter_by_abc:  function(iId) {
        var aM = iId.match(/id_abc_filter_(.+)$/);
        var sFilter = aM[1];
    	if (sFilter) {
	        var sLink = document.location.href.replace(/[&/?]?by-abc=[^&]+/gim, "").replace(/\/[&\?]/gim, "/?");
	        sLink = sLink.replace(/&?\bpage=\d+/gim, "");
	        sSep = (-1 == sLink.indexOf("?"))? "?": "&";
	        
	        if (sFilter == "all") 
	        	document.location.href = sLink;
	        else
	        	document.location.href = sLink + sSep + "by-abc=" + sFilter;
	    }
    },
    
    destruct: function() {
        self.ListManager = null;
    }
};


$j(document).ready(function(){
    self.RatingManager.init();
    self.FavoriteManager.init();
    self.FavoriteContactManager.init();
    self.MemoManager.init();
    self.ListManager.init();
});

$j(window).unload(function() {
    self.RatingManager.destruct();
    self.FavoriteManager.destruct();
    self.FavoriteContactManager.destruct();
    self.MemoManager.destruct();
    self.ListManager.destruct();
});
