// Define some variables to be used by several of the functions.
var catalogVars = {
	selectedTags : [],								// When we started we were calling them tags, these are the filters
	currentCategory : "",							// The category currently selected from the left nav
	siteList : null,								// This will be the XML DOM (populated on page load)
	noCUIs : 'No CUIs were found in this category.'	// Message to display when no CUIs are in the selection
}

// Extend jQuery to do case insensitive :contains(text)
$.expr[":"].contains_ic = function(el, i, m) {
    var search = m[3];
    if (!search) return false;
    return eval("/" + search + "/i").test($(el).text());
};

$(document).ready(function() {
	// Populate the tags/filters with those that are checked in case the screen was refreshed
	$("#tags input:checked").each(function() {
		catalogVars.selectedTags.push($(this).val());
	});
	
	// Register events for the logo to go back to the home screen
	$('#header img').click(function(event){
		event.stopPropagation();
		$("#sitePreviews").fadeOut(350);
		$("#searchScope").fadeOut(350);
		$("#homePage").fadeIn(350);
	});
	
	getXML();
	
	if (isDev()) {
		$('#navColumn').html('<a href="form.asp?id=0" id="newSiteButton"><img src="images/newSiteButton.jpg"/></a><hr/>' + $('#navColumn').html());
		
		// Attach lightbox effect to any this link"
		$('#newSiteButton').bind('click', function(event) {
			event.stopPropagation();
			$.get(this.href+"&ts="+new Date().getTime(), function(data) {
		    	$.facebox(data);
			});
			return false;
		});
	}
	
		// Register events for tabs
	$(".tabs").click(function(event){
		var thisTab = $(event.target);
		if (thisTab.attr("rel")) {
			$(".tabs li").each(function() {
				var el = $(this);
				var currentTabID = el.children().attr("rel");
				if (currentTabID == thisTab.attr("rel")) {
					el.addClass("active");
					if (currentTabID) {
						$("#" + currentTabID).show();
						getTagList();
					}
				} else {
					el.removeClass("active");
					$("#" + currentTabID).hide();
				}
			});
		};
	});

}); // end document ready

// Get the XML DOM containing the site info
function getXML() {
	$.ajax({
		type: "GET",
     	url: "loadData.asp?ts="+new Date().getTime(),
     	dataType: "xml",
     	success: function(xml) {
			catalogVars.siteList = xml;
			// Register events for expand/collapse of categories
			$("#leftNavCategories").click(function(event) {
				event.stopPropagation();
				var clickedLink = $(event.target);
				if (clickedLink.attr("href")) {
					catalogVars.currentCategory = clickedLink.attr('rel');
					getSites(clickedLink);
					
					var target = clickedLink.parent();
					if (target.hasClass("collapsed")) {
						target.removeClass("collapsed");
						target.addClass("expanded");
					}
					else if (target.hasClass("expanded")) {
						target.removeClass("expanded");
						target.addClass("collapsed");
					}
					
					$('#leftNavCategories li').removeClass("active");
					target.addClass("active");
				}
				return false;
			});
		}
	});
}

//Get the XML DOM containing the site info like the getXML() function 
//except click events are not added to li's in the left pane.  
//Instead the active item (if present) is reloaded.  
function reloadXML(){
	$.ajax({
		type: "GET",
     	url: "loadData.asp?ts="+new Date().getTime(),
     	dataType: "xml",
     	success: function(xml) {
			catalogVars.siteList = xml;	
			$("#leftNavCategories li").each(function(){
				if($(this).hasClass("active")){
					getSites($(this).find("a"));
				}
			});
		}
	});
}

//Makes an ajax call to get the most up to date tag list from the database.
function getTagList(){
	$.ajax({
		type: "GET",
		url: "buildTagList.asp",
		dataType: "html", 
		success: function(list){
			$("#tags").html(list);
				
			// Register events for tags/filters
			$('#tags li').click(function(event){
				var thisTag = $(event.target);
				
				// Make sure that we're looking at the check box and not the label element
				if ($(thisTag).attr("for") != undefined) {
					thisTag = $(thisTag).parent();
				}
				var tagID = $(thisTag).attr("value");
				// Add/Remove the tagID from selectedTags and show the relevant sites
				if ($(thisTag).attr("type") == "checkbox") {
					if (!$(thisTag).attr("checked")) {
						catalogVars.selectedTags.splice(catalogVars.selectedTags.indexOf(tagID), 1);
						getSites();
					}
					else {
						catalogVars.selectedTags.push(tagID);
						getSites();
					}
				}
			});

		}
	});
}

// Build the breadcrumb trail, starting from obj and working backwards
function buildBreadCrumb(obj,breadCrumb) {
	var el = obj;
	if (breadCrumb == undefined) {
		breadCrumb = "";
	}
	if (obj.parent().parent().attr("id") != "leftNavCategories") {
		return buildBreadCrumb($(obj.parent().parent().parent().children()[0]),"<span> > " + obj.html() + "</span>")
	} else {
		return "<span>" + obj.html() + breadCrumb + "</span>";
	}
}

// Build the list of currently used tags to show the user
function buildEnabledTags() {
	var tagList = [];
	// Get the names for the selected tags/filters
	for (var i=0; i<catalogVars.selectedTags.length; i++ ) {
		// Get the value of the checkbox with the ID of the current tag in selectedTags
	    tagList.push($('#tags [@value='+catalogVars.selectedTags[i]+']').attr('id'));
	} 
	var tags = tagList.sort().join(", ");
	if (tags != "") {
		tags = "Filtering by: " + tags + " - <span>(<a href='#' onclick='clearTags(); return false;'>clear</a>)</span>";
	}
	return tags;
}

// Deselect any tags
function clearTags() {
	catalogVars.selectedTags = [];
	$("#enabledTags").html(buildEnabledTags());
	$("#tags input:checked").each(function() {
		$(this).attr("checked","");
	})
	getSites();
}

// Get all relevant sites from the XML data based on the current category and currently selected tags
function getSites(categoryObj) {
	$("#homePage").hide();
	$("#enabledTags").html(buildEnabledTags());
	if (categoryObj) {
		$("#breadCrumb").html(buildBreadCrumb(categoryObj));
	}
	$("#searchScope").show();
	// Fade out the current sites, and then grab the new ones
	$("#sitePreviews").fadeOut(150, function() {
		$("#siteList").html('');
		
		// Return true if a site has all of the currently selected tags
		var checkTags = function(thisSite) {
			var allTags = true;
		 	if (catalogVars.selectedTags.length != 0) {
		 		for (var i = catalogVars.selectedTags.length - 1; i >= 0; i--) {
		 			if ($(thisSite).find("[@id="+catalogVars.selectedTags[i]+"]").length == 0) {
		 				allTags = false;
						break;
		 			}
		 		}
		 	}
		 	return allTags;
	  	};
		var findSites;
		if (catalogVars.currentCategory == "") {
			catalogVars.currentCategory = "All Sites";
		}
		if (catalogVars.currentCategory == "All Sites") {
			// Find any site with a title
			findSites = 'title';
		} else {
			// Find sites by ID#
			findSites = 'category[@id='+catalogVars.currentCategory+']';
		}
		
		// Loop through all sites in the current category
		$(findSites,catalogVars.siteList).each(function() {
			var thisSite = $(this).parent();
			if (checkTags(thisSite)) {
				// Get site info from XML DOM
		    	var id = $(thisSite).find('id').text()	
				var title = $(thisSite).find('title').text();
		    	var url = $(thisSite).find('url').text()	
				var desc = $(thisSite).find('description').text();
				
				var editLink = "";
				var editClass = "";
				if (isDev()) {
					editLink = '<a class="editLink" href="form.asp?id=' + id + '" rel="facebox"><img src="images/edit.png"/ class="editIcon" alt="edit"></a>'
					editClass = ' class="edit" '
				}
				
				// If there is no form in the title
				if (desc.indexOf("<form") == -1) {
					desc = "<p>" + desc + "</p>";
				}
				$('<li></li>')
					.html(editLink+'<a href="/clients/catalog/' + url + '" target="_new"><h4><div' + editClass + '>' + title + '</div></h4><img src="/clients/catalog/' + url + '/images/catalogThumbnail.png" alt="' + title + '" title="' + title + '"/></a>' + desc)
					.appendTo('#siteList');
			}
			
			// This code is to handle the select box for the State CUIs
			$('#siteList select').change(function() {
				$(this).parent().attr('action','/clients/catalog/state' + this.value);
				$(this).parent().attr('target','_new');
				$(this).next().css('display','inline');
				if (this.value != "Select a State") {
					$(this).parent().prev().attr('href','/clients/catalog/state' + this.value);					
					$($(this).parent().prev().children()[1]).attr('src','/clients/catalog/state' + this.value + '/images/catalogThumbnail.png');				
				} else {
					$(this).parent().prev().removeAttr('href');			
				}
				$($(this).parent().prev().children()[0]).html('<div>State CUIs: ' + this.value + '</div>');
			});
		});
		if (!window.XMLHttpRequest) {
			replacePNG($('#siteList')[0]);
		}
		
		// Attach lightbox effect to any links with rel="facebox"
		$('a[rel*=facebox]').bind('click', function(event) {
			event.stopPropagation();
			$.get(this.href+"&ts="+new Date().getTime(), function(data) {
		    	$.facebox(data);
			});
			return false;
		});
	
		// Setup editing
		$('.editLink').click(function() {
			catalogVars.activeEditing = this.id;
		});

		// Display an error message if no CUIs were found in this category
		if ($('#siteList').children().length == 0) {
			$('<li class="error"></li>')
	        	.html(catalogVars.noCUIs)
	            .appendTo('#siteList');
		}
		$("#sitePreviews").fadeIn(250);
	});
}

// Microsoft forgot to add this to Explorer
if(!Array.indexOf){
	Array.prototype.indexOf = function(obj){
		for(var i=0; i<this.length; i++){
			if(this[i]==obj){
				return i;
			}
		}
		return -1;
	}
}