$(document).ready(function() {
	PageSetup.init();
	Results.init();
	Query.init();
})

Results = {
	VIDEO_THUMB_PREFIX: "http://i.adultswim.com/asfix/repository",
	VIDEO_URL_PREFIX: "http://video.adultswim.com/",
	SITE_GENERIC_THUMB: "http://i.cdn.turner.com/adultswim/tools/img/search_generic_tn.jpg",
	
	itemCount: 0,			//the count of the current search results
	sitesTotal: 0,			//the total of sites found
	videosTotal: 0,			//the total of videos found
	thumbnail: [],			//the array holding all the thumbnails of the current search results
	icon: [],				//the array holding all the icons of the current search results
	collection: [],			//the array holding all the collections of the current search results
	title: [],				//the array holding all the titles of the current search results
	description: [],		//the array holding all the descriptions of the current search results
	url: [],				//the array holding all the urls of the current search results
	dateTime: [],			//the array holding all the dates of the current search results
	date: "",				//the date of the current result in the array
	time: "",				//the time of the current result in the array
	rating: [],				//the array holding all the ratings of the current search results
	currentPage: 1,			//the current page of the search results
	totalPages: 1,			//the total number of pages in the query results
	noSiteResults: false,	//for if there are no results found in a site search
	noVideoResults: false, 	//for if there are no results found in a video search
	error: false,			//for if there's an error with the query

	init: function(){
		Results.setupResultsHover();
	},
	
	setupResultsHover: function(){
		$(".hover").hover(
			function() {
				$(this).children(".resultsText").addClass('resultsTextHover');
				$(this).children(".icon").addClass('iconHover');
			},
			
			function() {
				$(this).children(".resultsTextHover").removeClass('resultsTextHover');
				$(this).children(".iconHover").removeClass('iconHover');
			}
		)
	},
	
	setupClick: function() {
		$(".hover").each(function (i) {
			$(this).click(function(e) {
				if(e.ctrlKey) {
					//console.log("Ctrl+Click");
					window.open(Results.url[i], "_blank");
				} 
				else {
					//console.log('Click')
					window.open(Results.url[i], "_self");
				}
			}); 
		})
	},
	
	setupResults: function() {
		var BASE_HTML_STR = '<li class="result hover clearfix"><div class="thumbnail"></div><div class="icon"></div><div class="resultsText"><div class="bottomRow clearfix"><div class="date"><span class="dateDate"></span> <span class="dateTime"></span></div><div class="rating"></div></div></div><div class="resultBgImg"></div></li>';
		var BASE_HTML_STR_NO_RESULTS = '<li class="result noHandCursor clearfix"><div class="thumbnail"></div><div class="icon"></div><div class="resultsText"><div class="bottomRow clearfix"><div class="date"><span class="dateDate"></span> <span class="dateTime"></span></div><div class="rating"></div></div></div><div class="resultBgImg"></div></li>'
		
		$("#resultsList").empty();
		$("#noResults").remove();
		
		//results found
		if ((Results.noSiteResults == false) && (Results.noVideoResults == false) && (Results.error == false)) {
			
			//append base html
			for (var i = 0; i < Results.itemCount; i++) {
				$("#resultsList").append(BASE_HTML_STR);
			}
			
			/* load in thumbnails */
			var thumbnails = $(".thumbnail");
			
			$(".thumbnail").each(function(i){
				var img = new Image();
				
				$(img).load(function(){
					$(thumbnails[i]).append(img);
					
				}).attr('src', Results.thumbnail[i]).attr('title', Results.title[i]);
			});
			
			/* load in icons with results */
			Results.loadIcons(true);
			
			/*load in results text bg classes*/
			Results.loadTextBgs();
			
			/*load in BGs */
			Results.loadBgImgs();
			
			Results.appendDescriptions();
			
			Results.appendTitles();
			
			if (Query.type == "video") {
				/*load in dates */
				$(".date").each(function(i){
					var dateTimeArr = Utilities.parseDateTime(Results.dateTime[i])
					
					$(this).children(".dateDate").text(dateTimeArr[0])
				});
			}
			
			if (Query.type == "video") {
				/*load in ratings */
				$(".rating").each(function(i){
					$(this).text(Results.rating[i]);
				});
			}
			
			//if there were less than 10 results add blank remainders
			if (Results.itemCount < 10) {
				for (var i = 0; i < (10 - Results.itemCount); i++) {
					$("#resultsList").append(BASE_HTML_STR_NO_RESULTS);
				}
				
				$(".thumbnail").each(function(i){
					if (i % 2 == 0) {
						$(this).addClass('noThumbBg1');
					}
					else if (i % 2 != 0) {
						$(this).addClass('noThumbBg2');
					}
				});
				
				/* load in icons w/out results */
				Results.loadIcons(false);
				
				/*load in results text bg classes*/
				Results.loadTextBgs();
				
				/*load in BGs */
				Results.loadBgImgs();
			}
			
			Results.setupResultsHover();
			Results.setupClick();
		}
		//no results found
		else if ((Results.noSiteResults == true) || (Results.noVideoResults == true) || (Results.error == true)) {
			$("#results").prepend('<div id="noResults"></div>');
			
			//append base html
			for (var i = 0; i < 10; i++) {
				$("#resultsList").append(BASE_HTML_STR_NO_RESULTS);
			}
			
			
			$(".thumbnail").each(function(i){
				if (i % 2 == 0) {
					$(this).addClass('noThumbBg1');
				}
				else if (i % 2 != 0) {
					$(this).addClass('noThumbBg2');
				}
			});
			
			/* load in icons w/out results */
			Results.loadIcons(false);
			
			/*load in results text bg classes*/
			Results.loadTextBgs();
			
			/*load in BGs */
			Results.loadBgImgs();
		}
		
		PageSetup.positionZoomImg();
	},
	
	loadIcons: function(appendResults){
		$(".icon").each(function(i){
			if (i % 2 == 0) {
				$(this).addClass('iconBg1');
			}
			else if (i % 2 != 0) {
				$(this).addClass('iconBg2');
			}
			
			if (appendResults) {
				$(this).addClass(Results.icon[i]);
				
				if (Results.icon[i] == "TVE") {
					$(this).parent().find('.thumbnail').after('<div class="TVE-sash sash"></div>');
				}
			}
		});
	},
	
	loadBgImgs: function(){
		$(".resultBgImg").each(function(i){
			if (i < 10) {
				$(this).addClass('bg' + (i + 1));
			}
			
			if ((i % 2 == 0) && (i >= 10)) {
				$(this).addClass('blankBg1');
			}
			else if ((i % 2 != 0) && (i >= 10)) {
				$(this).addClass('blankBg2');
			}
		});
	},
	
	loadTextBgs: function(){
		$(".resultsText").each(function(i){
			if (i % 2 == 0) {
				$(this).addClass('resultsTextBg1');
			}
			else if (i % 2 != 0) {
				$(this).addClass('resultsTextBg2');
			}
		});
	},
	
	appendTitles: function(){
		if (Query.type == "site") {
			$(".resultsText").each(function(i) {
				$(this).prepend('<div class="siteTitle"></div>');
			})
			
			$(".siteTitle").each(function(i){
				$(this).text(Results.title[i]);
			});
		}
		else if (Query.type == "video") {
			$(".resultsText").each(function(i) {
				$(this).prepend('<div class="videoTitle"></div>');
			})
			
			$(".resultsText").each(function(i) {
				$(this).prepend('<div class="collection"></div>');
			})
			
			$(".collection").each(function(i){
				$(this).text(Results.collection[i]);
			});
			
			$(".videoTitle").each(function(i){
				$(this).text(Results.title[i]);
			});
			
			//fixes box model irregularity in ie6
			$(".bottomRow").css('padding-bottom', '6px')
		}
	},
	
	appendDescriptions: function(){
		if (Query.type == "site") {
			$(".resultsText").each(function(i) {
				$(this).prepend('<div class="siteDescription"></div>');
			})
			
			$(".siteDescription").each(function(i){
				$(this).text(Results.description[i]);
			});
		}
		else if (Query.type == "video") {
			$(".resultsText").each(function(i) {
				$(this).prepend('<div class="videoDescription"></div>');
			})
			
			$(".videoDescription").each(function(i){
				$(this).text(Results.description[i]);
			});
		}
	},
	
	tracking: function(){
		try {
				trackMetrics({
					type: "adu-search",
					data: {
						search_result_count_site:           Results.sitesTotal,        //number of search results for site
						search_result_count_video:        Results.videosTotal,      //number of search results for video
						search_result_page:                  Results.currentPage          //search page number
					}
				});
				try{
					console.log('|-o-| trackMetrics',Results.sitesTotal,Results.videosTotal,Results.currentPage);
				} catch(e){}
		} catch(e){
			try{
				console.log('|-o-| tracking error!',e.name,e.message);
			} catch(e){}
		}
	}
}

Query = {
	SEARCH_URL: "/as-search/search.jsp?",
	type: "video",
	text: "",
	length: 20,
	order: "relevance",
	start: 1,
	numEpisodes: 0,
	
	init: function(){
		var urlReg = /(\w+):\/\/(\w+)\.(\w+)\.(\w+)\/(search)\/(|index.html)(\?queryText=)(.*)/;
		var address = document.URL;
		var urlResult = address.match(urlReg);
		
		//console.log('urlResult: ' + urlResult);
		//console.log('bigSearch: ' + $("#bigSearch").val())
		
		//if the url does have ?queryText and bigSearch is empty
		if ((urlResult != null) && $("#bigSearch").val() == "") {
			//console.log('if')
			//if ?queryText is not blank, set Query.text to what's there
			if (urlResult[8] != "") {
				Query.text = urlResult[8];
				//console.log("Query.text: " + Query.text);
			}
			else {
				
			}
			
			//if the value of the big search field is not equal to what was just retrieved from the url
			//then set the query text as what in the big search field 
			//this is to handle page backs by the user
			if ($("#bigSearch").val() == "") {
				PageSetup.setupInputFields(true);
				//console.log('if')
			}
			else if ($("#bigSearch").val() != Query.text) {
				Query.text = $("#bigSearch").val();
				
				PageSetup.setupInputFields(false);
				//console.log('else if')
			}
			else {
				PageSetup.setupInputFields(true);
				//console.log('else')
			}
		}
		//if the url does have ?queryText and the bigSearch has something in it
		else if ((urlResult != null) && ($("#bigSearch").val() != "")) {
			//console.log('else if 1')
			Query.text = $("#bigSearch").val();
				
			PageSetup.setupInputFields(true);
		}
		//if the url doesn't have ?queryText and bigSearch is not empty AND the bigsearch value is not the initial text
		else if (((urlResult == null) && ($("#bigSearch").val() != "")) && ($("#bigSearch").val() != PageSetup.INITIAL_TEXT)) {
			//console.log('else if 2')
			Query.text = $("#bigSearch").val();
				
			PageSetup.setupInputFields(true);
			//console.log('else if')
		}
		//catch all
		else {
			//console.log('else')
			PageSetup.setupInputFields(true);
		}
		
		Query.callSearch();
	},
	
	callSearch: function(){
		if (isNaN(Query.start)) {
			Query.start = 1;
		}
		
		xmlUrl = Query.SEARCH_URL + "queryText=" + Query.text + "&queryType=" + Query.type + "&sortOrder=" + Query.order + "&start=" + Query.start + "&length=" + Query.length;
		//xmlUrl = "tve-test.xml"
		
		Query.query(xmlUrl)
	},
	
	query: function(xmlUrl) {
		$.ajax({
			url: xmlUrl,
			dataType: "xml",
			//contentType: "text/xml",
			error: function(xhr, desc, exceptionobj){
				//var xml = (new DOMParser()).parseFromString( xhr.responseText, "text/xml");
				//alert('Error: ' + desc + '\n');
			},
			success: function(xml){
				//alert('success')
				if (Query.checkError(xml)) {
					//alert('error!')
					return;
				};
				
				if (Query.storeTotals(xml)) {
					//alert('no results!')
					return;
				};
				
				Query.storeResults(xml);
				
				if (Query.type == "video" && Query.order == "relevance") {
					Query.moveUpEpisodes();
				}
			},
			complete: function(){
				PageSetup.setupSearchTabs();
				PageSetup.setupAmount();
				PageSetup.setupSort();
				PageSetup.setupNextPrevBtns();
				PageSetup.setupPagination();
				PageSetup.setupPageAmount();
				Results.setupResults();
				
				Results.tracking();
			}
		});
	},
	
	checkError: function(xml){
		if (xml.getElementsByTagName("results")[0].getAttribute("error") == "true") {
			Results.error = true;
			
			return true;
		}
		else {
			Results.error = false;
			
			return false;
		}
	},
	
	storeTotals: function(xml){
		Results.sitesTotal = xml.getElementsByTagName("sites")[0].getAttribute("total");
		Results.videosTotal = xml.getElementsByTagName("videos")[0].getAttribute("total");
		
		Results.currentPage = Math.ceil(Query.start / Query.length);
		
		if (Query.type == "site") {
			if (Results.sitesTotal == 0) {
				Results.noSiteResults = true;
				
				return true;
			}
			else {
				Results.totalPages = Math.ceil(Results.sitesTotal / Query.length);
				
				Results.noVideoResults = false;
				Results.noSiteResults = false;
			}
			
			Results.itemCount = xml.getElementsByTagName("sites")[0].getAttribute("itemCount");
		}
		else if (Query.type == "video")  {
			if (Results.videosTotal == 0) {
				Results.noVideoResults = true;
				
				return true;
			}
			else {
				Results.totalPages = Math.ceil(Results.videosTotal / Query.length);
				
				Results.noSiteResults = false;
				Results.noVideoResults = false;
			}
			
			Results.itemCount = xml.getElementsByTagName("videos")[0].getAttribute("itemCount");
		}
		
		return false;
	},
	
	storeResults: function(xml) {
		/*for (var i = 0; i < Results.itemCount; i++) {
			jXML.getNodeValue(xml, i, Results.title, "title");
			jXML.getNodeValue(xml, i, Results.description, "description");
			jXML.getNodeValue(xml, i, Results.url, "url");
			jXML.getNodeValue(xml, i, Results.thumbnail, "thumbnail");
			
			if (Query.type == "site") {
				Results.icon[i] = "pageIcon";
				
				if (Results.thumbnail[i] == "[object Window]" || Results.thumbnail[i] == "[object]" || Results.thumbnail[i] == "[object Object]" || Results.thumbnail[i] == "[object DOMWindow]" ) {
					Results.thumbnail[i] = Results.SITE_GENERIC_THUMB;
					//console.log(Results.thumbnail[i])
				}
			}
			
			if (Query.type == "video") {
				jXML.getNodeValue(xml, i, Results.dateTime, "date");
				
				jXML.getNodeValue(xml, i, Results.collection, "collection");
				
				jXML.getNodeValue(xml, i, Results.rating, "rating");
				
				jXML.getNodeValue(xml, i, Results.icon, "type");
				
				Results.thumbnail[i] = Results.VIDEO_THUMB_PREFIX + Results.thumbnail[i];
				Results.url[i] = Results.VIDEO_URL_PREFIX + Utilities.formatLink(Results.collection[i]) + "/" + Utilities.formatLink(Results.title[i]) + ".html";
			}
		}*/
		if (Query.type == "site") {
			var siteContent = $(xml).find('site');
			
			$(siteContent).each(function(i) {
				Results.title[i] = $(this).find('title').text();
				Results.description[i] = $(this).find('description').text();
				Results.url[i] = $(this).find('url').text();
				Results.thumbnail[i] = $(this).find('thumbnail').text();
				
				Results.icon[i] = "pageIcon";
				
				if (Results.thumbnail[i] == "[object Window]" || Results.thumbnail[i] == "[object]" || Results.thumbnail[i] == "[object Object]" || Results.thumbnail[i] == "[object DOMWindow]" ) {
					Results.thumbnail[i] = Results.SITE_GENERIC_THUMB;
				}
			})
		}
		
		if (Query.type == "video") {
			var videoContent = $(xml).find('video');
			
			$(videoContent).each(function(i) {
				Results.title[i] = $(this).find('title').text();
				Results.description[i] = $(this).find('description').text();
				Results.url[i] = $(this).find('url').text();
				Results.thumbnail[i] = $(this).find('thumbnail').text();
				
				Results.dateTime[i] = $(this).find('date').text();
				Results.collection[i] = $(this).find('collection').text();
				Results.rating[i] = $(this).find('rating').text();
				Results.icon[i] = $(this).find('type').text();
				
				if (Results.icon[i] != "TVE") {
					Results.thumbnail[i] = Results.VIDEO_THUMB_PREFIX + Results.thumbnail[i];
				}
				
				Results.url[i] = Results.VIDEO_URL_PREFIX + Utilities.formatLink(Results.collection[i]) + "/" + Utilities.formatLink(Results.title[i]) + ".html";
			})
		}
	},
	
	moveUpEpisodes: function(){
		Query.numEpisodes = 0;
					
		for (var i = 0; i < Results.itemCount; i++) {
			if (Results.icon[i] == "EPI" || Results.icon[i] == "PRE" || Results.icon[i] == "TVE") {
				Query.numEpisodes++;
				//console.log(Query.numEpisodes)
			}
		}
		
		//shifts all episodes to the top
		for (var j = 0; j < Query.numEpisodes; j++) {
			for (var i = 0; i < Results.itemCount; i++) {
				if (Results.icon[i+j] == "EPI" || Results.icon[i+j] == "PRE" || Results.icon[i] == "TVE") {
					Results.collection.unshift(Results.collection[i+j]);
					Results.title.unshift(Results.title[i+j]);
					Results.description.unshift(Results.description[i+j]);
					Results.url.unshift(Results.url[i+j]);
					Results.dateTime.unshift(Results.dateTime[i+j]);
					Results.thumbnail.unshift(Results.thumbnail[i+j]);
					Results.rating.unshift(Results.rating[i+j]);
					Results.icon.unshift(Results.icon[i+j]);
					
					Results.collection.splice(i+j + 1, 1);
					Results.title.splice(i+j + 1, 1);
					Results.description.splice(i+j + 1, 1);
					Results.url.splice(i+j + 1, 1);
					Results.dateTime.splice(i+j + 1, 1);
					Results.thumbnail.splice(i+j + 1, 1);
					Results.rating.splice(i+j + 1, 1);
					Results.icon.splice(i+j + 1, 1);
					break;
				}
			}
		}
	}
}

PageSetup = {
	INITIAL_TEXT: "Enter Search Text, Buddy",
		
	init: function(){
		PageSetup.addZoomImage();
	},
	
	addZoomImage: function(){
		$("body").append('<div id="zoomImg"></div>');
		PageSetup.positionZoomImg();
		
		$(window).resize(function(){
			PageSetup.positionZoomImg();
		});
	},
	
	positionZoomImg: function(){
		var pos = $("#searchfield").position();
		var searchfieldHeight = $("#searchfield").height();
		
		$("#zoomImg").css('left', pos.left - 96);
		
		if (jQuery.support.opacity) {
			$("#zoomImg").css('top', (pos.top + searchfieldHeight) + 1);
		}
		else {
			$("#zoomImg").css('top', (pos.top + searchfieldHeight + 5));
		}
	},
	
	setupSearchTabs: function(){
		if (Results.error == true) {
			$("#sitesTotal").text("0");
			$("#videosTotal").text("0");
		}
		else {
			if (Results.noSiteResults == true) {
				$("#sitesTotal").text("0");
			}
			else {
				$("#sitesTotal").text(Results.sitesTotal);
			}
			
			if (Results.noVideoResults == true) {
				$("#videosTotal").text("0");
			}
			else {
				$("#videosTotal").text(Results.videosTotal);
			}
		}
		
		if (Query.type == "site") {
			$("#siteTab").removeClass('inactive');
			$("#siteTab").addClass('active');
			
			$("#videoTab").removeClass('active');
			$("#videoTab").addClass('inactive');
		}
		else if (Query.type == "video") {
			$("#siteTab").removeClass('active');
			$("#siteTab").addClass('inactive');
			
			$("#videoTab").removeClass('inactive');
			$("#videoTab").addClass('active');
		}
		
		$("#siteTab").unbind();
		$("#videoTab").unbind();
		$(".active").css('color', '#000000');
		$(".inactive").css('background-position', 'left bottom');
		$(".inactive").css('color', '#ffec83');
		
		$(".inactive").hover(
			function() {
				$(this).css('background-position', 'right bottom');
				//$(this).css('color', '#c03b00');
			},
			
			function() {
				$(this).css('background-position', 'left bottom');
				//$(this).css('color', '#ffec83');
			}
		)
		
		$("#siteTab").click(function() {
			Query.type = "site";
			Query.start = 1;
			
			Query.callSearch();
		})
		
		$("#videoTab").click(function() {
			Query.type = "video";
			Query.start = 1;
			
			Query.callSearch();
		})
	},
	
	setupAmount: function(){
		//if ((Results.noSiteResults == false) && (Results.noVideoResults == false)) {
		if ((Results.noSiteResults == false) && (Results.noVideoResults == false) && (Results.error == false)) {
			//console.log('results found')
			$(".resultsStart").text(Query.start);
			$(".resultsCount").text((parseInt(Query.start) + parseInt(Results.itemCount)) - 1);
			
			if (Query.type == "site") {
				$(".resultsTotal").text(Results.sitesTotal);
			}
			else if (Query.type == "video") {
				$(".resultsTotal").text(Results.videosTotal);
			}
		}
		else if ((Results.noSiteResults == true) || (Results.noVideoResults == true) || (Results.error == true)) {
			//console.log('no results found')
			//console.log('Results.noSiteResults: ' + Results.noSiteResults)
			//console.log('Results.noVideoResults: ' + Results.noVideoResults)
			$(".resultsStart").text('0');
			$(".resultsCount").text('0');
			$(".resultsTotal").text('0');
		}
		
		$(".queryText").text(Query.text);
	},
	
	setupSort: function(){
		if (Query.order == "date") {
			$("#sortDate").removeClass('sortBy');
			$("#sortDate").addClass('sortedBy');
			
			$("#sortRelevance").removeClass('sortedBy');
			$("#sortRelevance").addClass('sortBy');
			
			$("#sortRelevance").css('color', '#a37b01');
			
			PageSetup.setupTextHover($("#sortRelevance"));
			
			$("#sortRelevance").click(function() {
				Query.order = "relevance";
				
				Query.callSearch();
				
				$(this).unbind();
			})
		}
		else if (Query.order == "relevance") {
			$("#sortRelevance").removeClass('sortBy');
			$("#sortRelevance").addClass('sortedBy');
			
			$("#sortDate").removeClass('sortedBy');
			$("#sortDate").addClass('sortBy');
			
			$("#sortDate").css('color', '#a37b01');
			
			PageSetup.setupTextHover($("#sortDate"));
			
			$("#sortDate").click(function() {
				Query.order = "date";
				
				Query.callSearch();
				
				$(this).unbind();
			})
		}
	},
	
	setupNextPrevBtns: function(){		
		if (Results.currentPage == 1) {
			$(".previousPage").addClass('pageInactive');
		}
		else {
			$(".previousPage").removeClass('pageInactive');
		}
		
		if (Results.currentPage == Results.totalPages) {
			$(".nextPage").addClass('pageInactive');
		}
		else {
			$(".nextPage").removeClass('pageInactive');
		}
		
		PageSetup.setupTextHover($(".previousPage:not(.pageInactive)"));
		$(".nextPage:not(.pageInactive)").css('color', '#a37b01');
		
		$(".previousPage:not(.pageInactive)").click(function() {
			Query.start = Query.start - Query.length;
			
			Query.callSearch();
						
			$(this).unbind();
		})
		
		PageSetup.setupTextHover($(".nextPage:not(.pageInactive)"));
		$(".previousPage:not(.pageInactive)").css('color', '#a37b01');
		
		$(".nextPage:not(.pageInactive)").click(function() {
			Query.start = Query.start + Query.length;

			Query.callSearch();
							
			$(this).unbind();
		})
	},
	
	setupPagination: function(){
		$(".pages").empty();
		
		if ((Results.noSiteResults == false) && (Results.noVideoResults == false) && (Results.error == false)) {
			//total number of divs that can be in the pagination area including ... and pages
			var numOfDivsInPages = 9;
			//the halfway point for the current page to go.  ceiling makes it go up for odd total div numbers
			var middleDivInPages  = Math.ceil(numOfDivsInPages / 2)
			
			//if the current page is less than or equal to the halfway point
			if (Results.currentPage <= middleDivInPages) {
				//page to be added is 1
				var pageAdded = 1;
				//the number of divs added so far
				var numDivsAdded = 0;
				
				//while the number of divs added is less than the total number of divs that can be added 
				//AND the page to be added is less than or equal to the total number of pages in the results
				while ((numDivsAdded < numOfDivsInPages) && (pageAdded <= Results.totalPages)) {
					//if the total number of results pages is greater than the number of divs that can be added to the pagination area
					//AND the number of divs added so far is less than the total that can be added minus the number added so far
					if ((Results.totalPages > numOfDivsInPages) && (numDivsAdded < (numOfDivsInPages - 2))) {
						//add the page to be added
						$(".pages").append('<span class="page page' + pageAdded + '">' + pageAdded + '</span>');
						
						PageSetup.setupTextHover($(".page" + pageAdded));
						PageSetup.setupPageClick($(".page" + pageAdded));
						
						//console.log('page' + pageAdded + ' appended');
						pageAdded++;
						numDivsAdded++;
					}
					
					else if (Results.totalPages > numOfDivsInPages && (numDivsAdded >= (numOfDivsInPages - 2))) {
						//add ... to separate the pages near the current page and the last page
						$(".pages").append('<span class="dotdotdot">...</span>');
						numDivsAdded++;
						//add the last page div
						$(".pages").append('<span class="page page' + Results.totalPages + '">' + Results.totalPages + '</span>');
						
						PageSetup.setupTextHover($(".page" + Results.totalPages));
						PageSetup.setupPageClick($(".page" + Results.totalPages));
						
						numDivsAdded++;
						//console.log('page' + Results.totalPages + ' appended');
					}
					
					else {
						$(".pages").append('<span class="page page' + pageAdded + '">' + pageAdded + '</span>')
						
						PageSetup.setupTextHover($(".page" + pageAdded));
						PageSetup.setupPageClick($(".page" + pageAdded));
						
						//console.log('page' + pageAdded + ' appended');
						pageAdded++;
						numDivsAdded++;
					}
				}
			}
			//if the current page is more than the halfway point
			else if (Results.currentPage > middleDivInPages) {
				//page to be added is the current page minus the number of divs before the halfway point 
				//- 3 because of the first two divs added for padding right below
				var pageAdded = Results.currentPage - (middleDivInPages - 3);
				//the number of divs added so far
				var numDivsAdded = 0;
				
				//add the first page div
				$(".pages").append('<span class="page page1">1</span>')
				
				PageSetup.setupTextHover($(".page1"));
				PageSetup.setupPageClick($(".page1"));
				
				numDivsAdded++;
				
				//add ... to separate first page and the pages near the current page
				$(".pages").append('<span class="dotdotdot">...</span>')
				
				numDivsAdded++;
				
				//while the number of divs added is less than the total number of divs that can be added 
				//AND the page to be added is less than or equal to the total number of pages in the results
				while (numDivsAdded < numOfDivsInPages && (pageAdded <= Results.totalPages)) {
					//if the total number of results pages is greater than the number of divs that can be added to the pagination area
					//AND the number of divs added so far is less than the total that can be added minus the number added so far
					if ((Results.totalPages > numOfDivsInPages) && (numDivsAdded < (numOfDivsInPages - 2)) && (Results.currentPage < (Results.totalPages - 3))) {
						//console.log('if fired')
						//add the page to be added
						$(".pages").append('<span class="page page' + pageAdded + '">' + pageAdded + '</span>')
						
						PageSetup.setupTextHover($(".page" + pageAdded));
						PageSetup.setupPageClick($(".page" + pageAdded));
						
						//console.log('page' + pageAdded + ' appended')
						pageAdded++;
						numDivsAdded++;
					}
					
					else if (Results.totalPages > numOfDivsInPages && (numDivsAdded >= (numOfDivsInPages - 2)) && (Results.currentPage < (Results.totalPages - 3))) {
						//console.log('else if fired')
						//add ... to separate the pages near the current page and the last page
						$(".pages").append('<span class="dotdotdot">...</span>')
						numDivsAdded++;
						//add the last page div
						$(".pages").append('<span class="page page' + Results.totalPages + '">' + Results.totalPages + '</span>')
						
						PageSetup.setupTextHover($(".page" + Results.totalPages));
						PageSetup.setupPageClick($(".page" + Results.totalPages));
						
						numDivsAdded++;
						//console.log('page' + Results.totalPages + ' appended')
					}
					
					else {
						//console.log('else fired')
						$(".pages").append('<span class="page page' + pageAdded + '">' + pageAdded + '</span>')
						
						PageSetup.setupTextHover($(".page" + pageAdded));
						PageSetup.setupPageClick($(".page" + pageAdded));
						
						//console.log('page' + pageAdded + ' appended');
						pageAdded++;
						numDivsAdded++;
					}
				}
			}
			
			$(".page" + Results.currentPage).addClass("currentPage");
			$(".page" + Results.currentPage).removeClass("page");
			$(".page" + Results.currentPage).unbind();
			
			$("#resultsDetailsBottom .page" + Results.currentPage).addClass("currentPage");
			$("#resultsDetailsBottom .page" + Results.currentPage).removeClass("page");
			$("#resultsDetailsBottom .page" + Results.currentPage).unbind();
		}
		
		else if ((Results.noSiteResults == true) || (Results.noVideoResults == true) || (Results.error == true)) {
			//console.log('no results found... adding page')
			$(".pages").append('<span class="currentPage">1</span>')
		}
	},
	
	setupPageClick: function(page){
		page.click(function() {
			var pageNum = $(this).attr('class').substr(9);
							
			Query.start = (((parseInt(pageNum) * Query.length) + 1)) - Query.length;
			//console.log('((parseInt(pageNum) * Query.length) + 1): ' + ((parseInt(pageNum) * Query.length) + 1))		
			//console.log('start: ' + Query.start)					
			Query.callSearch();
							
			$(this).unbind();
		})
	},
	
	setupPageAmount: function(){
		if (Query.length == 20) {
			$("#twenty").removeClass('length');
			$("#twenty").addClass('lengthed');
			
			$("#fifty").removeClass('lengthed');
			$("#fifty").addClass('length');
			
			$("#fifty").css('color', '#a37b01');
			
			PageSetup.setupTextHover($("#fifty"));
			
			$("#fifty").click(function() {
				Query.length = 50;
				
				var modulo = Query.start % Query.length;
				Query.start = Query.start - (modulo - 1);
				
				Query.callSearch();
				
				$(this).unbind();
			})
		}
		else if (Query.length == 50) {
			$("#fifty").removeClass('length');
			$("#fifty").addClass('lengthed');
			
			$("#twenty").removeClass('lengthed');
			$("#twenty").addClass('length');
			
			$("#twenty").css('color', '#a37b01');
			
			PageSetup.setupTextHover($("#twenty"));
			
			$("#twenty").click(function() {
				Query.length = 20;
				
				var modulo = Query.start % Query.length;
				Query.start = Query.start - (modulo - 1);
				
				Query.callSearch();
				
				$(this).unbind();
			})
		}
	},
	
	setupInputFields: function(changeText){
		if (changeText) {
			if (Query.text == "") {
				$("#bigSearch").val(PageSetup.INITIAL_TEXT);
			}
			else {
				$("#bigSearch").val(Query.text);
			}
			//console.log('change text ran')
		}
		else {
			$("#bigSearch").val(PageSetup.INITIAL_TEXT);
		}
		
		$("#bigSearch").focus();
		
		$("#searchfield").val($("#bigSearch").attr('value'));
	
		PageSetup.addInputEvents();
	},
	
	addInputEvents: function(){
		$("#bigSearch").blur(function() {
			$("#searchfield").val($(this).attr('value'));
		});
		
		$("#bigSearch").keyup(function(event) {
			$("#searchfield").val($(this).attr('value'));
		});
		
		$("#bigSearch").keydown(function(event) {
			if ($(this).val() == PageSetup.INITIAL_TEXT) {
				$(this).val("");
			}
		});
		
		$("#bigSearch").focus(function() {
			$("#searchfield").val($(this).attr('value'));
		});
		
		$("#bigSearch").click(function() {
			if ($(this).val() == PageSetup.INITIAL_TEXT) {
				$(this).val("");
			}
			
			$("#searchfield").val($(this).attr('value'));
		})
		
		$("#bigSearch").keypress(function(e) {
			if (e.which == 13) {
				Query.text = $("#bigSearch").attr('value')
				Query.start = 1;
			
				Query.callSearch();
			}
		})
		
		$("#bigSearchButton").click(function() {
			Query.text = $("#bigSearch").attr('value')
			Query.start = 1;
			
			Query.callSearch();
		})
	},
	
	setupTextHover: function(div){
		div.hover(
			function() {
				$(this).css('color', '#000000');
				$(this).css('cursor', 'hand');
				$(this).css('cursor', 'pointer');
			},
			
			function() {
				$(this).css('color', '#a37b01');
				$(this).css('cursor', 'auto');
			}
		)
	}
}

var jXML = {
    getAttribute: function(xml,nodes) {
        var response = {};
        for (var node in nodes) {
            if (nodes[node][2] == null) {
                response[node] = $(nodes[node][0] + "[" + nodes[node][1] + "]",xml);
            } else {
                if ($(nodes[node][0],xml).attr(nodes[node][1]) == nodes[node][2]) {
                    response[node] = $(nodes[node][0],xml);
                }
            }
        }
        return response;
    },
	getAttributeValue: function(xml, array, tagName, attributeName) {
		array = xml.getElementsByTagName(tagName)[0].getAttribute(attributeName);
		//console.log(attributeName + ': ' + array)
	},
	getNodeValue: function(xml, num, array, name) {
		try {
			array[num] = xml.getElementsByTagName(name)[num].childNodes[0].nodeValue;
			//console.log(name + " " + num + ": " + array[num])
		}
		catch (e) {
			array[num] = toString(e);
		}
	}
};

var Utilities = {
	regexChars: new RegExp(/[~`!@#\$\%\^\&*\(\)_\+=\{\}\[\]\|\\;:\'\"<>,\.\?\/]/g),
	
	parseDateTime: function(dateTime) {
		var dateTimeSplit = dateTime.split(" ");
		
		var newDateTime = [];
		
		newDateTime[0] = Utilities.formatDate(dateTimeSplit[0]);
		newDateTime[1] = Utilities.formatTime(dateTimeSplit[1]);
		
		return newDateTime;
	},
	
	formatDate: function(date) {
		var dateSplit = date.split("/");
		
		var day = dateSplit[2];
		var month = dateSplit[1];
		var year = dateSplit[0];
		
		switch(month) {
			case "01":
				month = "Jan";
				break;
			case "02":
				month = "Feb";
				break;
			case "03":
				month = "Mar";
				break;
			case "04":
				month = "Apr";
				break;
			case "05":
				month = "May";
				break;
			case "06":
				month = "Jun";
				break;
			case "07":
				month = "Jul";
				break;
			case "08":
				month = "Aug";
				break;
			case "09":
				month = "Sep";
				break;
			case "10":
				month = "Oct";
				break;
			case "11":
				month = "Nov";
				break;
			case "12":
				month = "Dec";
				break;
			default:
				break;
		} 
		
		if (day.substring(0, 1) == "0") {
			day = day.substring(1, 2);
		}
		
		var newDate = "Added " + month + " " + day + ", " + year;
		
		return newDate;
	},
	
	formatTime: function(time) {
		var timeSplit = time.split(":");
		
		var minute = timeSplit[1];
		var hour = timeSplit[0];
		var meridiem;
		
		if (hour < 12) {
			meridiem = "am";
		}
		else if (hour >= 12) {
			meridiem = "pm";
		}
		
		if ((meridiem == "pm") && (hour > 12)) {
			hour = hour - 12;
		}
		
		if (hour == 00) {
			hour = 12;
		}
		
		var newTime = hour + ":" + minute + meridiem;
		
		return newTime;
	},
	
	formatLink: function(str) {
		return $.trim(str.toLowerCase().replace(Utilities.regexChars, '')).replace(/ /g, '-').replace(/-{2,}/g,'-').replace(/-$/g,'');
	}
}

