/*
 Provides jQuery functions for rendering facets and other Dieselpoint UI objects
 Copyright 2010, Dieselpoint, Inc.
 */

/**
 * This code styles a listfacet. Example:
 * 
 *  $(".listfacet").listFacet({baseURL: "http://myhost.com?uq=foo", plusImageName: "img/myplus.gif"});
 * 
 * Options:
 *
 * baseURL: override the baseURL supplied in the data-baseurl attribute of the facet. default: ""
 * plusImageName: path to image containing a plus sign. default: "images/plus.gif"
 * minusImageName: path to image containing a minus sign. default: "images/minus.gif"
 * blankImageName: path to image containing an empty box. default: "images/blank.gif"
 *
 * @param {Object} options
 */
jQuery.fn.listFacet = function(options){

    var defaults = {
        baseURL: null,
        titleClass: "facettitle",
        plusImageName: "images/plus.gif",
        minusImageName: "images/minus.gif",
        blankImageName: "images/blank.gif",
		moreLinkText: "more..."
    };
    var options = $.extend(defaults, options);
    
    // roll through each top-level <div> that has the "listfacet" class
    return this.each(function(){
        var div = $(this);
        
        var title = div.attr("data-title")
        var attrId = div.attr("data-attr");
		var hasMore = div.attr("data-more");
        var baseURL = getBaseURL(div);
        
        // the div should have only one root ul tag
        var ul = div.children("ul:first-child");
        
        if (title != null) {
            ul.before("<span class='" + options.titleClass + "'>" + title + "</span>")
        }
        
        // check to see if this list is hierarchical
        var isHierarchy = (ul.find("ul").length > 0);
        
        handleMenu(ul, true);
        
		// once the menu is built, add a more... link as the last li
		if (hasMore === "Y") {
			var href = baseURL + "&more=" + escape(attrId);
			ul.append("<li><a href='" + href + "'>" + defaults.moreLinkText + "</a></li>");
		}
		
        // recursive function that styles each submenu, starting with the root
        function handleMenu(ul, isOpen){
        
            // iterate over each child li
            ul.children().each(function(){
                var li = $(this);
                
                // get text of this menu element
                var text = this.childNodes[0];
                text.data = jQuery.trim(text.data);
                
                // create the link
                var value = li.attr("data-value");
                if (!value) {
                    value = text.data;
                }
				value = escapeQuotes(value);

				var clause;
				
				var value2 = li.attr("data-value2");
				if (value2) { // if range
					value2 = escapeQuotes(value2);
				
					if (value && value.length > 0 && !(value == "undefined")) {
						clause = "[" + attrId + "]>=\"" + value + "\"";
					}
					if (clause) {
						clause += " AND ";
					} else {
						clause = "";
					}
					clause += "[" + attrId + "]<\"" + value2 + "\"";
					
				} else { // not a range
					clause = "[" + attrId + "]=\"" + value + "\"";
				}
				
	            var lastChar = baseURL.substr(baseURL.length - 1, 1);
				var connector = (lastChar == "=" ? "" : " AND ");
                var href = "<a href='" + baseURL + connector + escape(clause) + "'></a>";
				
				$(text).wrap(href);
                
                if (isHierarchy) {
                    // create an image, either plus or blank
                    var img = $(new Image());
                    
                    var childMenus = li.children("ul");
                    if (childMenus.length > 0) {
                        var childMenu = $(childMenus[0]);
                        
                        // if there is a childmenu
                        img.attr("src", defaults.plusImageName);
                        img.click(function(){
                            toggleBranch(img, childMenu);
                        })
                        
                        // recurse
                        handleMenu(childMenu, false);
                    }
                    else {
                        // no submenu
                        img.attr("src", defaults.blankImageName);
                    }
                    
                    li.prepend(img);
                }
            })
            
            if (!isOpen) {
                ul.hide();
            }
        }
        
        /**
         * Toggle a branch of the tree on or off
         */
        function toggleBranch(img, childMenu){
            if (childMenu.is(':visible')) {
                img.attr("src", defaults.plusImageName);
                childMenu.hide();
            }
            else {
                img.attr("src", defaults.minusImageName);
                childMenu.show();
            }
        }
        
        function getBaseURL(div){
            var baseURL = defaults.baseURL;
            if (baseURL == null) {
                baseURL = div.attr("data-baseurl");
                if (!baseURL) {
                    baseURL = window.location.href;
                }
            }
			if (baseURL.indexOf("&c=") == -1 && baseURL.indexOf("?c=") == -1) {
				if (baseURL.indexOf("?") == -1) {
					baseURL += "?c=";
				} else {
					baseURL += "&c=";
				}
			}  
            return baseURL;
        }
    });
};

/**
 * Escape double quotes in a string by adding a backslash before each.
 */
function escapeQuotes(str) {
	return str.replace(/"/gi, '\\"');
}

/**
 * dieselAutoComplete widget is an extension of jQuery UI AutoComplete widget.
 * By default, dieselAutoComplete widget consumes "value" & "label" fields 
 * defined in the JSON data.
 * 
 * Example 1:
 * 
 * var entries = [
 * 				{ 	
 * 					"value" : "teddy bears",
 * 					"label" : "<span><b>teddy</b> bears</span>"
 * 				}, 
 * 				{ 
 * 					"value" : "teddy roosevelt",
 * 					"label" : "<span><b>teddy</b> roosevelt</span>"
 * 				}
 * 			];
 * 
 * $("#search").dieselAutoComplete({
 * 		source :  entries
 * });
 * 
 * <input id="search">
 * 
 * Example 2:
 *  
 * $("#search").dieselAutoComplete({
 * 		source :  "autocomplete.jsp?ind=acmecraft&attrid=title",
 * });
 * 
 * 	@see http://jqueryui.com/demos/autocomplete/
 */
$.widget('ui.dieselAutoComplete',
		$.ui.autocomplete, {

			// On selection, copies "value" field into the input box.
			select:		function(event, ui){
							this.element.val(ui.item.value);
							return false;
						},
			
			// Renders well-formed HTML provided by the "label" field.
			_renderItem: function(ul, item) {
							return $( "<li></li>" )
							.data( "item.autocomplete", item )
							.append("<a>" + item.label +"</a>")
							.appendTo( ul );
						}
});

