/*
 * Globals
 */
//This has been moved to a global to support multiple paginated objects per DOM
var cc_startPage = 1;
var cc_pageBottom = 0;

function CollapsedContent(){
	this.parent = ".sortable";
	this.collapse = ".collapse";
	this.trigger = ".trigger";
	this.backText = 'Back to Index';
	
	this.setBehaviors = cc_setBehaviors;
	this.setSlide = cc_setSlide;
	this.setFade = cc_setFade;
	this.setTabs = cc_setTabs;
	this.setPagination = cc_setPagination;
	this.setPaginationControls = cc_setPaginationControls;
	this.setSortable = cc_setSortable;
	
	this.animation = "Fade";
	this.doSlide = cc_doSlide;
	this.doFade = cc_doFade;
	this.doTabs = cc_doTabs;
	
	this.tabs = {
		match: false,
		current: false
	};
	
	this.paginate = {
			enabled: false,
			includeNumbers: true,
			container: $('.paginate'),
			height: 300,
			target: 1,
			forcePageHeights: false,
			showParent: false,  //used by the accordions to get height calcs
			controlParent: $('.paginate'),
			flexLastHeight: false
	};
	
	this.sortable = {
		enabled: false,	
		categories: new Array(),
		uniqueCategories: new Array(),
		node: '.category',
		container: '.sortable',
		filters: false,
		splitChar: ';'
	};	
	
	this.__construct = function(){
		var obj = this;
		$("body").ready(function(){
			obj.setBehaviors();
		});
	};
	
}

function cc_setBehaviors(){
	var obj = this;
	
	eval('obj.set'+obj.animation+'();');
	
	$(obj.parent+" "+obj.collapse).hide();
	
	$(obj.parent+" "+obj.trigger).click(function(){
		eval('obj.do'+obj.animation+'(this);');
	});	
	
	$(obj.parent+" "+obj.trigger).hover(
	  function(){
	    $(this).css("text-decoration","underline");
	  },function(){
	    $(this).css("text-decoration","none");
	  }
	);
	$(obj.parent+" "+obj.trigger).css("cursor","pointer");
	
	if(obj.paginate.enabled){
		obj.setPagination();
	}	
	
	if(obj.sortable.enabled){
		$(obj.sortable.container).ready(function(){
			obj.setSortable();
		});
	}
	
	if(obj.animation == "Tabs"){
		//$(obj.collapse).filter(":first").show();
		$(obj.parent).each(function(){
			$(this).find(obj.collapse).filter(":first").show();
		});	
	}	
	
	
}

function cc_setSlide(){
	var obj = this;
	
	$(obj.parent+" "+obj.trigger).addClass("collapsible");
	$(obj.parent+" "+obj.collapse).css("padding-left", "20px");
}

function cc_doSlide(clicked){
	var obj = this;
	
	var target = $(clicked).parent().find(obj.collapse);
	
	if(target.is(":visible")){
		target.slideUp();
		$(clicked).removeClass("expanded");
    }
    else{ 
		$(clicked).addClass("expanded");
        target.slideDown(500, function(){
	        //show the first tab if it is there
	        if(target.children('.tab').length > 0){
	        	target.children('.tabMenu').children('li:first').trigger('click');
	        }
        });    
    }
}

function cc_setFade(){
	var obj = this;
}	
function cc_doFade(clicked){
	var obj = this;
	
	$(clicked).parent().nextAll().hide();
	$(clicked).parent().prevAll().hide();
	$(clicked).parent().find(obj.collapse).fadeIn();
	
	$(obj.parent+":first").before('<div class="back tiny right">'+obj.backText+'</div>');
	$(obj.parent+":first").parent().find('.back').click(function(){
		$(obj.parent+':visible').fadeOut('normal', function(){
			$(obj.parent+" "+obj.collapse).hide();
			$(obj.parent).parent().children(':not(script)').fadeIn();
			$(obj.parent+":first").parent().find('.back').remove();
		});	
		obj.setBehaviors();
	});	
	
	$(clicked).unbind();
	$(clicked).css("text-decoration","none");
	$(clicked).css("cursor","auto");
}

function cc_setPagination(){
	//this version does not support table chunking. Use jquery-pagination.js for that.
	var obj = this;
	
	obj.paginate.target = cc_startPage;
	if( (obj.paginate.showParent == true) && (obj.paginate.container.parent().is(":not(:visible)")) ){
		var myParent = obj.paginate.container.parent();
		myParent.show();
	}	
	
	var localBottom = 0;
	obj.paginate.container.children().each(function(){	 
		var localHeight = 0;
		
		if(jQuery.support.cssFloat == true){
			cc_pageBottom += $(this).outerHeight(true); 
			localBottom += $(this).outerHeight(true); 
			localHeight = $(this).outerHeight(true);
		}	
		else{
			/*
			 * IE already adds margins and padding to objects' heights, so don't use outerHeight
			 * and also seems to be messing up with the heights of floated children.
			 */
			cc_pageBottom += $(this).height();
			localBottom += $(this).height();
			localHeight = $(this).height();
			if(($(this).children(':first').css('float') == 'left') || ($(this).children(':first').css('float') == 'right')){
				$(this).children(':not(:first)').each(function(){
					cc_pageBottom -= $(this).height();
					localBottom += $(this).height();
					localHeight += $(this).height();
				});
			}	
		}
		
		/*
	    if(Math.ceil( (cc_pageBottom)/obj.paginate.target) >= obj.paginate.height){
	    	obj.paginate.target++;
	    }
		 */
		
		if(localBottom >= obj.paginate.height){
			obj.paginate.target++;
			localBottom = localHeight;
		}	
		
		$(this).attr("bottom", localBottom);
	    $(this).attr("target",obj.paginate.target);  
	   
	
	}); 
	if( (obj.paginate.showParent == true) && (typeof(myParent) != 'undefined') ){
		myParent.hide();
	}	
     
	//Chunk the copy content based on position values
	for(var n=obj.paginate.target; n>=cc_startPage; n--){
	  obj.paginate.container.children(":first").before('<div id="page'+n+'" class="page" style="display: none;"></div>');	  
	}
  
  obj.paginate.container.children(":not(.page)").each(function(){
	$("#page"+$(this).attr("target")).append($(this));
  });
  
/*
 * find the tallest page and set all heights equal to that one. This stops the bouncing effect.
 * if this.forPageHeight is set, use that instead (accordions use this)
 */
  if(obj.paginate.forcePageHeights == false){
	  var pageHeight = 0;
  
	  obj.paginate.container.find(".page").each(function(){
		  $(this).show();
		  if($(this).height() > pageHeight){
			  pageHeight = $(this).height();
		  }
		  $(this).hide();
	  });
  }
  else{
	  var pageHeight = obj.paginate.forcePageHeights;
  }

  obj.paginate.container.find(".page").height(pageHeight);
 
  obj.paginate.container.find(".page:first").show();

  obj.setPaginationControls();
  
  //let the last page height flex if true:
  if(obj.paginate.flexLastHeight == true){
	  obj.paginate.container.find(".page:last").css('height','auto');
  }
}

function cc_setPaginationControls(){
	//if(cc_startPage != 0){
		//If the startPage counter is not zero, this means there are other objects paginated, and we need a new page
		//cc_startPage++;
	//}
	
	var obj = this;
	
	//if there is more than one page, add the pagination controls
	if(obj.paginate.target != cc_startPage){
	  obj.paginate.controlParent.append('<div class="paginationControls"><div class="right"></div><div class="controls"></div><div class="left"></div><div class="clear"></div></div><div class="clear"></div>');
	  
	  var controls = obj.paginate.controlParent.find(".paginationControls");
	  
	  controls.children(".left").hide();

	  controls.children(".right").click(function(){
			if(typeof(siteTracker) != 'undefined'){
					siteTracker._trackEvent('GeneralPaginationToggle', $(this).attr('class'));
			}
			controls.children(".left").show();
		    var currentPage = obj.paginate.container.find(".page:visible");
		    var nextPage = currentPage.next();
		    if(nextPage.attr("class") == 'page'){
		        nextPage.fadeIn();
		        currentPage.hide();
		    }
		    if(nextPage.html() == obj.paginate.container.find(".page:last").html() ){
		    	controls.children(".right").hide();
		    }
		    else controls.children(".right").show();
		    
		    controls.children(".controls").children("span").removeClass('selected');
		    controls.children(".controls").children("span[name='"+nextPage.attr('id').substr(4)+"']").addClass('selected');
	  });
	  controls.children(".left").click(function(){
			if(typeof(siteTracker) != 'undefined'){
					siteTracker._trackEvent('GeneralPaginationToggle', $(this).attr('class'));
			}
			controls.children(".right").show();
		    var currentPage = obj.paginate.container.find(".page:visible");
		    var nextPage = currentPage.prev();
		    if(nextPage.attr("class") == 'page'){
		    	nextPage.fadeIn();
		    	currentPage.hide();
		    }
		    if(nextPage.html() == obj.paginate.container.find(".page:first").html() ){
		    	controls.children(".left").hide();
		    }
		    else controls.children(".left").show();
		    
		    controls.children(".controls").children("span").removeClass('selected');
		    controls.children(".controls").children("span[name='"+nextPage.attr('id').substr(4)+"']").addClass('selected');
	  });
	 
	  if(obj.paginate.includeNumbers == true){
		  //if more than 10 pages, show 1 - 10, then every tenth page and the last one
		  for(var n=obj.paginate.target; n>=cc_startPage; n--){
			  var visibleNum = n-cc_startPage+1;
			  	if((visibleNum<=10) || (visibleNum%10 == 0) ){
			  		controls.children(".controls").prepend('<span class="number" name="'+n+'">'+visibleNum+'</span> ');
			  		if( (visibleNum%10 == 0) && (visibleNum!=obj.paginate.target) ){
			  			controls.find(".controls > span[name='"+n+"']").after('<span class="continuation" displayStart="'+(visibleNum+1)+'" start="'+(n+1)+'"> ... </span>');
			  		}
			  	}
		  }  
		  controls.children(".controls").children("span:first").addClass('selected');
	  }
	  $('.paginationControls > .controls > .continuation').live('click', function(){
		  //add the next 9 spans:
		  for(var n=0; n<9; n++){
			  var start = parseInt($(this).attr('start'))+n;
			  var displayStart = parseInt($(this).attr('displayStart'))+n;
			  if(start < cc_startPage){
				  controls.find(".controls span[name='"+(start-1)+"']").after('<span class="number" name="'+start+'">'+displayStart+'</span> ');
			  }  
		  }
		  $(this).remove();
	  });
	  
	  $('.paginationControls > .controls > .number').live('click', function(){
		  if($("#page"+$(this).attr('name')).html() != obj.paginate.container.find(".page:visible").html()){
			  if(typeof(siteTracker) != 'undefined'){
					siteTracker._trackEvent('GeneralPaginationToggle', $(this).attr('name'));
			  }
			  controls.children(".controls").children("span").removeClass('selected');
			  var current = obj.paginate.container.find(".page:visible");
			  
			  obj.paginate.container.find("#page"+$(this).attr('name')).fadeIn();
			  current.hide();

			  if( obj.paginate.container.find("#page"+$(this).attr('name')).prevAll('.page').length == 0 ){
				  $(".paginationControls .left").hide();
			  }
			  else{
				  controls.children(".left").show();
			  }
			  if( obj.paginate.container.find("#page"+$(this).attr('name')).nextAll('.page').length == 0 ){
				  controls.children(".right").hide();
			  }
			  else{
				  controls.children(".right").show();
			  }
			  $(this).addClass('selected');
		  }
		  else return true;
	  });
	  $('.paginationControls, .paginationControls > .controls, .paginationControls > .controls > span').live('dbclick', function(){
		  return false;
	  });
	}  
	 
	//set the globals for a new call to this object (for accordions)
	 cc_startPage = obj.paginate.target + 1;
	 cc_pageBottom = obj.paginate.target*obj.paginate.height;
}

function cc_setTabs(){
	var obj = this;
	
	$(obj.parent).each(function(){
		var parentNode = $(this);
		parentNode.prepend('<ul class="tabMenu"></ul>');
		
		parentNode.children(obj.collapse).each(function(){
			parentNode.find(".tabMenu").append('<li>'+$(this).find(obj.trigger).text()+'</li>');
		});
		
		parentNode.find(".tabMenu li:first").addClass("selected");
		parentNode.children(obj.collapse).find(obj.trigger).filter(":first").addClass("selected");
		//obj.tabs.current = parentNode.children(obj.collapse).find(obj.trigger).filter(":first").text();
	});	
	
	obj.tabs.match = obj.trigger;
	obj.trigger = ".tabMenu li";
	
	//if mobile, run the mobile ui function:
	if( (typeof(detect) != 'undefined') && (detect.test(navigator.userAgent))){
		var wt;
		$('#content').ready(function(){
			waitForMui();
		});
		
		function waitForMui(){
			$(".tabMenu").height('40px');
			
			if(typeof(mobileReady) != 'undefined'){
				mobileReady.setTabs();
				clearTimeout(wt);
				
				
			}
			else{
				wt = setTimeout(function(){
					waitForMui();
				},50);
			}
		}
	}
}

function cc_doTabs(clicked){
	var obj = this;
	var needle = $(clicked).text();
	
	//var parentNode = $(clicked).parent().parent();
	
	//if(obj.tabs.current != needle){
		//obj.tabs.current = needle;
		$(clicked).prevAll().removeClass("selected");
		$(clicked).nextAll().removeClass("selected");
		$(clicked).addClass("selected");
		
		var currentNode = $('.tabMenu').nextAll(obj.collapse+":visible");
		/*
		 * set the parent .tabs to the height of the current .tab plus the height of the menu; 
		 * this prevents the page from "bouncing" when the .tab elements show/hide
		 */
		var parentNode = currentNode.parents(obj.parent);
		var h = parentNode.height();
		parentNode.height(h);	
		currentNode.hide();
		
		parentNode.find(obj.tabs.match).each(function(){
			if(needle == $(this).text()){
				$(this).parents(obj.collapse+":hidden").fadeIn();
				parentNode.height('auto');
			}	
		});
			
}

function cc_setSortable(){
	var obj = this;

	//trim whitespace from a string
	String.prototype.trim = function() {
		return this.replace(/^\s+|\s+$/g,"");
	}
	
	if($('#switchContainer').length == 0){
		$(obj.sortable.container).prepend('<div id="switchContainer" style="margin-bottom: 10px;background-color: #cccccc;padding: 8px;">Filter by category: </div>');
	}
	
	//obj.sortable.node can be a string or an array; if it is an array, we will need multiple drop downs
	if(typeof(obj.sortable.node) == 'object'){
		for(var n=0; n<obj.sortable.node.length; n++){
			if($(obj.sortable.node[n]).length > 0){
				createFilter(obj.sortable.node[n]);
			}	
		}
	}
	else{
		if($(obj.sortable.node).length > 0){
			createFilter(obj.sortable.node);
		}	
	}	
	
	
	function createFilter(node){
		if($(node).attr('title').length > 0){
			var defaultText = '-- '+$(node).attr('title')+' --';
		}
		else{
			var defaultText = '-- View all --';
		}	
		
		
		$('#switchContainer').append('<select class="switch" target="'+node+'" style="margin: 0px 4px;"><option value="">'+defaultText+'</option></select>');		
		var thisSwitch = $('#switchContainer select.switch[target="'+node+'"]');
		
		//add another View all option is title was defined:
		if($(node).attr('title').length > 0){
			thisSwitch.append('<option value="">View all</option>');
		}
		
		
		
		obj.sortable.categories = new Array();
		obj.sortable.uniqueCategories = new Array();
	
		$(obj.sortable.container).find(node).each(function(){ 
			//Split on semicolons, trim white space, and then push all values.
			var cat = $(this).text();
			//obj.sortable.categories.push(cat.trim());
			var cats = cat.split(obj.sortable.splitChar);
			
			for(var n=0; n<cats.length; n++){
				cats[n] = cats[n].trim();
				obj.sortable.categories.push(cats[n]);
			}
			
		});
		obj.sortable.categories.sort();

		for(var n=0;n<obj.sortable.categories.length;n++){
		  if(obj.sortable.categories[n] != obj.sortable.categories[n+1]){
			  obj.sortable.uniqueCategories.push(obj.sortable.categories[n]);
		  }
		}
		for(var n=0;n<obj.sortable.uniqueCategories.length;n++){
			thisSwitch.append('<option value="'+obj.sortable.uniqueCategories[n]+'">'+obj.sortable.uniqueCategories[n]+'</option>');
		}
	
		/*
		 * turn on all of the items;
		 * take them away if they don't match the search criteria
		 */
		thisSwitch.change(function(){
			$(obj.sortable.container).find(node).parents(obj.parent).show();
			
			$('#switchContainer select.switch').each(function(){
				var val = $(this).val();
				var targetSet = $(this).attr('target');
				var removeSet = $(targetSet).filter(function(){
					if($(this).text().indexOf(val) == -1){
						return true;
					}
				});
		
				removeSet.parents(obj.parent).hide();

			});
			
			var displaySet = $(obj.sortable.container).find(node).parents(obj.parent).filter(':visible');
			displaySet.hide();
			displaySet.fadeIn();
			
			/*
			 * This needs to be more sophisticated with multiple selects.
			 * We need to do an AND lookup
			 * 
			 * so track the globally selected values, and always match against that set, 
			 * not just the value of the changed select object.
			 */
		});	
	}	
}
