
/**
 [!file-evolution-number: 81]
 Quicklist for VisWiki (previously VisualWikipedia)
 Last modified: 2009-02-21 [00:46]
 Author: T. Hoshi
 Copyright (c) T. Hoshi 2008, 2009 All rights reserved.

Note that this module uses suerfish:
 * Superfish v1.4.8 - jQuery menu widget
 * Copyright (c) 2008 Joel Birch
 *
 * Dual licensed under the MIT and GPL licenses:
 * 	http://www.opensource.org/licenses/mit-license.php
 * 	http://www.gnu.org/licenses/gpl.html
 *

How it works:
 * it stores {{ title }} contained in
 <title>{{ title }} - Some arbitrary string</title>
 into cookie name specified by `quicklist.cookie_name'.

 Elements used:
 * id=my-quicklist-component
 * id=my-quicklist
 * id=my-quicklist-add  (if added, "added" text will be the content.)
 * cookie named
 
 EXAMPLE:
 <div id="my-quicklist-add" class="hidden"></div>
 <div id="my-quicklist-add"><span style=\"font-size:90%; color:#00a000;\" class=\"added-to-quicklist\">Added :)</span></div>
 <div id="my-quicklist-component" class="hidden"><h3>My QuickList</h3><div id="my-quicklist"></div></div>
*/

// **. Vars

var Quicklist = function(custom_quicklist) {
/// Customizable variables
    // this.cookie_name = "vw_quicklist";
    this.cookie_name = "vw_quicklist_en";
    this.add_page_message = "Add this page to QuickList!";
    this.added_message = "Added :)";
    this.remove_message = "Click here to remove this entry.";
    this.quicklist_limit = 20;
    this.show_limit = true;    /// e.g. "My QuickList 7/20" instead of "My QuickList 7". If you change it to false, you need to change width in .css.

    for (var p in custom_quicklist) {
        this[p] = custom_quicklist[p];
    }
};

// **. Fun

Quicklist.prototype.escapeTitleCookie = function(value) {
    return escape(strip(value)).replace(/%20/g, ' ').replace(/%7C/g, '|');    /// repls just to save up some space.
}

Quicklist.prototype.removeThisTitle = function(element) {
    var title = $($(element).parent().children()[0]).text();
    var quicklist_s = this.removeTitle(title);
    this.updateQuicklist(quicklist_s);
}

Quicklist.prototype.removeTitle = function(title) {    /// from quicklist cookie
    var c = getCookie( this.cookie_name );
    if (c) { c = unescape(c); }
    var quicklist_s = '';
    if (c && (c.length > 0)) {
        var titles = c.split( "|" );
        /// filter out the same title
        var validTitles = $.grep(titles, function(t) {
            return ((t.length > 0) &&  (title != t));
        });
        quicklist_s = validTitles.join( "|" );
        setCookie( this.cookie_name, this.escapeTitleCookie(quicklist_s), 300);
    }
    return quicklist_s;
}

Quicklist.prototype.prependTitle = function(title) {    /// prepend title to quicklist cookie, no dups.
    var c = getCookie( this.cookie_name );
    if (c) { c = unescape(c); }
    var quicklist_s;
    if (c==title) {
        return c;
    }
    else if (c) {
        var titles = c.split( "|" );
        /// filter out the same title
        var validTitles = $.grep(titles, function(t) {
            return ((t.length > 0) &&  (title != t));
        });
        quicklist_s = title+"|"+validTitles.join( "|" );
    }
    else
        quicklist_s = title;    /// prepend
    setCookie( this.cookie_name, this.escapeTitleCookie(quicklist_s), 300);
    return quicklist_s;
}

Quicklist.prototype.titleInQuicklist = function(title) {    /// true if title is in quicklist.
    var c = getCookie( this.cookie_name );
    if (!c || (c.length < 1)) { return false; }
    var titles = unescape(c).split( "|" );
	for(var i=0; i < titles.length; i++) {
        if (title == titles[i])
            return true;
    }
    return false;
}

Quicklist.prototype.quicklistLength = function() {
    var c = getCookie( this.cookie_name );
    if (!c || (c.length < 1)) { return 0; }
    var titles = unescape(c).split( "|" );
    return titles.length;
}

Quicklist.prototype.makeQuicklistLi = function(title) {
    return "<li><a href=\"" +
    escape(toutf8(title).replace(/ /g, '_')) +
    "\" class=\"quicklist-title\">" + htmlspecialchars(title) + "</a>" ;  /* +
    // " <a href=\"javascript:void(0)\" onclick=\"quicklist.removeThisTitle(this);return false\" class=\"quicklist-remove\">" +
    " <a style=\"display: none; visibility: hidden;\" href=\"javascript:void(0)\" onclick=\"quicklist.removeThisTitle(this);return false\" class=\"quicklist-remove\">" +    /// !!this is necessary for layout reasons for now....
    "<img src=\"/media/vw/remove.gif\" alt=\""+ this.remove_message + "\" title=\"" + this.remove_message +
    "\" align=\"absmiddle\" style=\"border: 0px;\"/></a>" + "</li>" ;
    */
}

Quicklist.prototype.updateQuicklist = function(quicklist_s) {
    var li_elements = [ ];
    var L = quicklist_s.split("|");
	for(var i=0; i < L.length; i++) {
        if (L[i].length > 0) {
            /// Remove the title from cookie if quicklist exceeds quicklist_limit; push ow.
            if (li_elements.length >= this.quicklist_limit)
                this.removeTitle(unescape(L[i]));
            else
                li_elements.push( this.makeQuicklistLi(L[i]) );
        }
    }
    var li_html = li_elements.join( "\n");
    
    // $("#my-quicklist-component").removeClass('hidden');
    $("#my-quicklist-ul").empty();
    $("#my-quicklist-ul").append(li_html);
    $("#my-quicklist-count").empty();

    // if (li_elements.length == this.quicklist_limit)
    if (this.show_limit)
        $("#my-quicklist-count").append('('+li_elements.length+'/'+this.quicklist_limit+')');
    else
        $("#my-quicklist-count").append('('+li_elements.length+')');
}

Quicklist.prototype.getThisPageTitle = function() {
    var title = $('title')[0].innerHTML;
    var index = rfind(title, ' - ');
    if (index < 0)
        return false;
    title = title.substring(0, index);     /// get only the article title.
    return title;
}

Quicklist.prototype.addThisPageToQuicklist = function() {
    var title = this.getThisPageTitle();
    if (title) {
        var quicklist_s = this.prependTitle(title);
        this.updateQuicklist(quicklist_s);
    }
    $("#my-quicklist-add").empty();    /// empty <div id="my-quicklist-add">...</div>
    $("#my-quicklist-add").append("<span style=\"font-size:90%; color:#00a000;\" class=\"added-to-quicklist\">" + this.added_message + "</span>");    /// empty <div id="my-quicklist-add">...</div>
}

// **. Execution

var custom_quicklist = custom_quicklist || { };
var quicklist = new Quicklist(custom_quicklist);    /// main Quicklist object
$(document).ready(function() {

    /// Inject "Add this page to quicklist" into "<div id="my-quicklist-add"></div>" if current page is not in ql yet.
    if (!quicklist.titleInQuicklist(quicklist.getThisPageTitle())) {
        $("#my-quicklist-add").empty();    /// empty <div id="my-quicklist-add">...</div>
        $("#my-quicklist-add").append("<a href=\"javascript:void(0)\" onclick=\"quicklist.addThisPageToQuicklist();return false\">"+ quicklist.add_page_message +"</a>").removeClass('hidden');
    }
    /// Inject Quicklist contents into "<div id="my-quicklist"><ul></ul></div>"
    var c = getCookie( quicklist.cookie_name );
    // alert( c );
    if (c)
        quicklist.updateQuicklist(unescape(c));
    else {
        $("#my-quicklist-count").empty();
        if (this.show_limit)
            $("#my-quicklist-count").append('(0/'+this.quicklist_limit+')');
        else
            $("#my-quicklist-count").append('(0)');
    }
        
});


// **. Superfish v1.4.8 - jQuery menu widget
// 2009-02-15 (15:11)

/// EXTRACTED on 2009-02-15

/*
 * Superfish v1.4.8 - jQuery menu widget
 * Copyright (c) 2008 Joel Birch
 *
 * Dual licensed under the MIT and GPL licenses:
 * 	http://www.opensource.org/licenses/mit-license.php
 * 	http://www.gnu.org/licenses/gpl.html
 *
 * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
 */

;(function($){
	$.fn.superfish = function(op){

		var sf = $.fn.superfish,
			c = sf.c,
			$arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')),
			over = function(){
				var $$ = $(this), menu = getMenu($$);
				clearTimeout(menu.sfTimer);
				$$.showSuperfishUl().siblings().hideSuperfishUl();
			},
			out = function(){
				var $$ = $(this), menu = getMenu($$), o = sf.op;
				clearTimeout(menu.sfTimer);
				menu.sfTimer=setTimeout(function(){
					o.retainPath=($.inArray($$[0],o.$path)>-1);
					$$.hideSuperfishUl();
					if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);}
				},o.delay);	
			},
			getMenu = function($menu){
				var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
				sf.op = sf.o[menu.serial];
				return menu;
			},
			addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };
			
		return this.each(function() {
			var s = this.serial = sf.o.length;
			var o = $.extend({},sf.defaults,op);
			o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){
				$(this).addClass([o.hoverClass,c.bcClass].join(' '))
					.filter('li:has(ul)').removeClass(o.pathClass);
			});
			sf.o[s] = sf.op = o;
			
			$('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
				if (o.autoArrows) addArrow( $('>a:first-child',this) );
			})
			.not('.'+c.bcClass)
				.hideSuperfishUl();
			
			var $a = $('a',this);
			$a.each(function(i){
				var $li = $a.eq(i).parents('li');
				$a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});
			});
			o.onInit.call(this);
			
		}).each(function() {
			var menuClasses = [c.menuClass];
			if (sf.op.dropShadows  && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass);
			$(this).addClass(menuClasses.join(' '));
		});
	};

	var sf = $.fn.superfish;
	sf.o = [];
	sf.op = {};
	sf.IE7fix = function(){
		var o = sf.op;
		if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined)
			this.toggleClass(sf.c.shadowClass+'-off');
		};
	sf.c = {
		bcClass     : 'sf-breadcrumb',
		menuClass   : 'sf-js-enabled',
		anchorClass : 'sf-with-ul',
		arrowClass  : 'sf-sub-indicator',
		shadowClass : 'sf-shadow'
	};
	sf.defaults = {
		hoverClass	: 'sfHover',
		pathClass	: 'overideThisToUse',
		pathLevels	: 1,
		delay		: 800,
		animation	: {opacity:'show'},
		speed		: 'normal',
		autoArrows	: true,
		dropShadows : true,
		disableHI	: false,		// true disables hoverIntent detection
		onInit		: function(){}, // callback functions
		onBeforeShow: function(){},
		onShow		: function(){},
		onHide		: function(){}
	};
	$.fn.extend({
		hideSuperfishUl : function(){
			var o = sf.op,
				not = (o.retainPath===true) ? o.$path : '';
			o.retainPath = false;
			var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
					.find('>ul').hide().css('visibility','hidden');
			o.onHide.call($ul);
			return this;
		},
		showSuperfishUl : function(){
			var o = sf.op,
				sh = sf.c.shadowClass+'-off',
				$ul = this.addClass(o.hoverClass)
					.find('>ul:hidden').css('visibility','visible');
			sf.IE7fix.call($ul);
			o.onBeforeShow.call($ul);
			$ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); });
			return this;
		}
	});

})(jQuery);

$(document).ready(function() {
    /// Superfish Menu initialization.
    $("ul.sf-menu").superfish( { delay: 300 } );
});

