/* Author: Luke Penza
 * Version: 1.0
*/
;(function($){
	var _old = $.unique;
 
    $.unique = function(arr){
 
        // do the default behavior only if we got an array of elements
        if (!!arr[0].nodeType){
            return _old.apply(this,arguments);
        } else {
            // reduce the array to contain no dupes via grep/inArray
            return $.grep(arr,function(v,k){
                return $.inArray(v,arr) === k;
            });
        }
    };
	
	var methods = {};
	
	methods = {
		init : function() {
			var $this = $(this),
				data = $this.data('catsDiv');
				
         // If the plugin hasn't been initialized yet
         if ( ! data ) {
         
			$(this).data('catsDiv',methods.convertCategories($(this)));

         }				
		},		
		setToClientHeight : function(wrap,data){
			var obj = $(this);
			
			if (obj.length===0 || $(data).length===0 || $(wrap).length===0){
				return this;
			}

			obj.css('min-height',function(){
				var totalHeight = 0;
				
				$.each(data,function(key,id){
					var elem = $(id);
					if (elem.length!==0){
						totalHeight += elem.outerHeight();
					}
				});
				
				var extraHeight = (obj.outerHeight() - obj.height());
				
				
				return $(wrap).height() - (totalHeight + extraHeight);
			});
		},
		
		queryCategory : function() {
            
			return this.each(function() {
				var el$=$(this),
					webappid=el$.data("webapp-id"),
					catid=el$.data("cat-id"),
					fid=el$.data("fid"),
					maincat=el$.data("main-cat"),
					result=el$.data("resultset"), // item-group or parent
					url=el$.data("result-url"),
					claArr,catsArr=[],claID='',cla$,cats$,params,
					isOnlyCla = function(value,arr) {
						var uarr = $.unique(arr);
						return (uarr.length===1 && uarr[0]===value);
					},
					fallback = function(){
						if (catid.length){
							if (isNaN(catid)){
								claID=cats$.find('div').andSelf().filter(function() {return $(this).data('CAT_Name')===catid;}).attr('id');
								
								if (typeof claID !== 'undefined'){
									catsArr.push(claID);									
								}else{
									catsArr.push(cats$.attr('id'));
								}

							}else{
								catsArr.push(catid);
							}
							
						}else{
							catsArr.push(cats$.attr('id'));
						}
					};
				
				cla$ = $('#cla');
				cats$ = $('#CAT_Category').data('catsDiv').find('.level-0').filter(function(){return $(this).data('CAT_Name')===maincat;});
				claArr = cla$.length ? cla$.text().split(',') : null;
				
				if (claArr !== null && !isOnlyCla(maincat,claArr)){
					var len = claArr.length,i,
					cmpName = function() {return $(this).data('CAT_Name')===claArr[i];};
					
					for(i=len;i--;){
						if (result==="parent"){
							claID=cats$.find('div').andSelf().filter(cmpName).parent().attr('id');
							//if it has no parent then fallback on item-group
							
							if (claID===cats$.attr('id')){
								fallback();
							}
							
						}else{
							claID=cats$.find('div').andSelf().filter(cmpName).attr('id');
						}

						catsArr.push(claID);
					}
				}else{
					//if it doesn't exist fallback to catid if not present fallback to main group main-cat
					fallback();					
				}
					
				params = $.param({CAT_Category: catsArr},true);

				$.post( '/Default.aspx?CCID='+webappid+'&FID='+fid+'&ExcludeBoolFalse=True&ID=/'+url, 
						params ,
						function( data ) {
							var $div = $('<div></div>').hide().addClass('resultsTmp').appendTo("body").html(data);
							
							$div.find("#webapp"+webappid+"pagination").remove();
							
							// find a node tree within reponse HTML
							var innerData = $div.find('#webappsearchresults'+webappid).html();
							
							$div.find('#webappsearchresults'+webappid).remove();
							// insert data into dom
							$(innerData).appendTo(el$);
							
						}
						,'html'
				);				 
             
            });
		},
		
		convertCategories: function(id$){
			var mainDiv = $("<div></div>").attr("id","CAT_set"),
				currentDiv = mainDiv,
				currLen = -1,
				prevLen,currLevel,prevLevel,parentDiv,i;
			
			//#CAT_Category must exist on the page albeit hidden
			id$.find("option").filter(function(){return parseInt($(this).attr("value"),10)>0;}).each(function(){
				if ($(this).len===0){
					return null;
				}
				//create new div for option
				prevLen = currLen;
				currLen = $(this).text().match(/^-*/)[0].length;
				currLevel = Math.floor(currLen/3);
				prevLevel = Math.floor(prevLen/3);
				//create new div with catid as id
				var newDiv = $("<div></div>").attr("id",$(this).attr("value")).attr("class","level-"+currLevel).data('CAT_Name',$(this).text().substr(currLevel*3));
				
				if (prevLevel<currLevel) {
					//new level insert newdiv into current div and make newdiv current
					newDiv.appendTo(currentDiv);
				}else if (prevLevel>currLevel){
					//level finished append new div to current divs parent
					//get parent dir prevLevel-currLevels up
					var len = prevLevel-currLevel+1;
					for (i=len;i--;){
						parentDiv = currentDiv.parent();
						currentDiv=parentDiv;
					}
					newDiv.appendTo(parentDiv);
				}else{
					//same level append new div to current
					newDiv.appendTo(currentDiv.parent());
				}
				currentDiv=newDiv;
				
			});
			
			return mainDiv;				
		}
	};
	
	$.fn.gdcc = function( method ) {
	
		// Method calling logic
		if ( methods[method] ) {
			return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		} else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
		}    
	
	};	
	
	$(function(){
		$("#CAT_Category").gdcc();//init
		$(".query-items").gdcc('queryCategory');
	});	

}(jQuery));
