rl.work = (function() {
	
	var sliderLoaded=false,
		pageType=null,
		filter=null,		
		filterCategory=null,
		parsedEntries=null,
		peCount=null,
		topGalleryCount=null,
		botGalleryCount=null,
		galleryWidth=0,
		sliderWidth=0;	
	
	// determines page type and sets the data to be loaded - is the first item loaded
	var parseXml = function() {		
		var i,items,item,l=0,filter;				
		var entries = $(rl.csData).find("entry");
		var entryCount = $(entries).length;		
		
		loadEntries=[];
		
		// hide/remeove all elements before building
		$(".listGallery").hide();		
		$(".miniList").hide();
		$("#miniCs").hide();		
		$("#indCs").hide();
		$("#workCs").remove();
		$("#galleryShell").hide();  // for IE 7, parent div's must be hidden last		
		$("#titleLoader").show();		
		$("#workDropdown").show();
		
		filter=null;		
		// determine if this is a filter
		if (rl.filterOptions["industry"][rl.secPageName]) {
			filter= rl.filterOptions["industry"][rl.secPageName];
			filterCategory="industry";
		}
		if (rl.filterOptions["offerings"][rl.secPageName]) {
			filter= rl.filterOptions["offerings"][rl.secPageName];
			filterCategory="offerings";
		}		
		
		// this section does the actual parsing, and storage of entries and loadEntries		
		if (rl.secPageName==null) { // full list
			pageType="fullList";					
			loadEntries = $(entries).find('small_img');
			parsedEntries=entries;	
		} else if (rl.secPageName=="brands-of-fame") {						
			pageType="brands-of-fame";
			items = $("#brands-of-famePage .thirdCol").children();
			for (i=0;i<$(items).length;i++) {
				item = $(items)[i];
				loadEntries.push(item);
			}
			parsedEntries=items;
		} else if (filter!=null ) {  // listing filter
			pageType="listFilter";
			parsedEntries=[];
			peCount=0;
			
			if (filterCategory=="industry") {
				items = $(entries).find("industry");
				for(i=0;i<$(items).length;i++) {
					item = $(items)[i];					
					if ( $(item).text()==filter) {
						parsedEntries.push($(item).parent());
						loadEntries.push($(item).parent().find("small_img"));
					}
				} 
			}									
			if (filterCategory=="offerings") {
				items=$(entries).find("offerings").find("item");				
				for(i=0;i<items.length;i++) {					
					item = $(items)[i];					
					if ( $(item).text()==filter) {
						parsedEntries.push($(item).parent().parent());
						loadEntries.push($(item).parent().parent().find("small_img"));
					}
				} 
			}
			
		} else { // individual case study or error
			$("#workDropdown").hide();
			
			parsedEntries = $(rl.csData).find('entry[id='+rl.secPageName+']');
			
			if (parsedEntries.text()=="") {
				pageType="error";
			} else {
				pageType="individualCS";
				loadEntries.push($(parsedEntries).find("bg_img"));			
				// grab the item images
				items=$(parsedEntries).find("media").find("item");
				for(i=0;i<items.length;i++) {
					if ($(items[i]).attr("type") == "Image") {
						loadEntries.push($(items)[i]);
					}
				}
			}
		}
		
		peCount=parsedEntries.length;
		if(peCount==0 || pageType=="error") {
			console.log(peCount +" "+pageType);
			$("#titleLoader").hide();
			throw new Exception("404");
		}

		rl.model.loadAssets(loadEntries, buildFactory);
		
		return;
	}
	
	// puts together different builds to set up the different types of pages
	var buildFactory = function() {
		var bgSrc;
		galleryWidth=0,
		sliderWidth=0;		
		
		if(pageType=="fullList" || pageType=="listFilter") {			
			topGalleryCount = (peCount%2==0) ? peCount/2 : Math.ceil(peCount/2);
			botGalleryCount = (peCount%2==0) ? peCount/2 : Math.floor(peCount/2);
			
			buildListGallery($("#listGallery1"),topGalleryCount,0);
			buildListSlider($("#miniList1"),topGalleryCount);
			
			buildListGallery($("#listGallery2"),botGalleryCount,topGalleryCount);
			buildListSlider($("#miniList2"),botGalleryCount);
			
			dragListHandler($("#listGallery1"),$("#listGallery2"));
			// when build is finished show the content
			
			$("#workDropdown").show();
			$(".listGallery").show();
			$(".miniList").show();			
		} else if (pageType=="brands-of-fame") {
			
			buildBrandsGallery("#brands1");
			buildBrandsGallery("#brands2");
			buildBrandsGallery("#brands3");
			
			$("#workDropdown").show();
		} else {			
			var items = $(parsedEntries).find("media").find("item");
			var itemCount = $(parsedEntries).find("media").find("item").length;			
			var overviewPos = (itemCount%2==0) ? itemCount/2 : Math.ceil(itemCount/2);
						
			buildCsGallery(items,itemCount,overviewPos);			
			buildCsSlider(itemCount,overviewPos);
			dragCsHandler();
			
			// when build is finished show the content
			// background image change
			bgSrc = $(parsedEntries).find("bg_img").attr("src");
			$("#pageBGholder").css("background-image",$("#pageBG").css("background-image")).show();
			$("#pageBG").css("background-image","url("+bgSrc+")");
			$("#pageBGholder").fadeOut();
			
			$("#indCs").show();
			$("#miniCs").show();
		}
		
		// get rid of loader and show the master shell
		$("#titleLoader").hide();
		$("#galleryShell").show();
		$(window).resize();
	}
	
	var buildBrandsGallery = function(brandsId) {
		var i=0,imgSrc,data="",items,item;
		
		items=$("#brands-of-famePage "+brandsId).children();
		
		for (i=0;i<$(items).length;i++) {
			item = $(items)[i];
			data += "<img src='"+$(item).attr("src")+"' />";
		}
		$("#brands-of-famePage "+brandsId).html(data);
	}
	
	var buildCsGallery = function(items,itemCount,overviewPos) {
		var i=0,
		imgSrc,
		vimSrc,
		vid,
		data="",titleData="";
				
		for(i=0;i<itemCount;i++) {			
			if(i==overviewPos) {
				data += "<li class='csOverview'>"
				data += "<div class='csData'>";
				data += "<h3>Overview</h3>";
				data += parsedEntries.find("bigidea").text()!="" ? "<p class='headline'>"+parsedEntries.find("bigidea").text()+"</p>" : "";
				data += parsedEntries.find("business").text()!="" ? "<h4>Business</h4><p>"+parsedEntries.find("business").text()+"</p>" : "";
				data += parsedEntries.find("audience").text()!="" ? "<h4>Target Audiences</h4><p>"+parsedEntries.find("audience").text()+"</p>" : "";
				data += parsedEntries.find("assignment").text()!="" ? "<h4>Assignment</h4><p>"+parsedEntries.find("assignment").text()+"</p>" : "";
				data += parsedEntries.find("goal").text()!="" ? "<h4>Goal</h4><p>"+parsedEntries.find("goal").text()+"</p>" : "";				
				data += "</div>";
				data += "<div class='csMeta'>";
				var metaIndustryLink = [];
				var metaOfferingLinks = [];
				metaIndustryLink.push("<a href='/#work/" + parsedEntries.find("industry").text().toLowerCase() + "' class='industryLink'>" + parsedEntries.find("industry").text() + "</a>");
				parsedEntries.find("offerings item").each(function(ind, item) {
					if ($(item).text() != "Corey Classic") {
						metaOfferingLinks.push("<a href='/#work/" + $(item).text().toLowerCase() + "' class='offeringLink'>" + $(item).text() + "</a>");
					}
				});
				data += metaIndustryLink + " | ";
				data += metaOfferingLinks.join(",&nbsp;");
				data += "</div>";
				data +=	"</li>";
			}
			
			switch ($(items[i]).attr('type')) {
				case "Image":
					imgSrc = $(items[i]).attr('src');
					cap = $(items[i]).attr('caption');
					subcap = $(items[i]).attr('subcap');
					imglink = $(items[i]).attr('link');
					data += "<li>";
					if (imglink != "" && imglink != undefined) data += "<a target='_blank' href='"+imglink+"'>";
					data += "<img class='csImg csTT' src='"+imgSrc+"' alt='"+(cap != "" && cap != undefined ? cap : "")+"' data-subcap='"+(subcap != "" && subcap != undefined ? subcap : "")+"'/>";
					if (imglink != "" && imglink != undefined) data += "</a>";
					data += "</li>";
					break;
				case "Vimeo":
					vimSrc = $(items[i]).attr('src');
					vid = vimSrc.substr(vimSrc.lastIndexOf("/") + 1);
					data += "<li><div class='vimeoEmbed'><iframe src=\"http://player.vimeo.com/video/"+vid+"?title=0&amp;byline=0&amp;portrait=0\" width=\"545\" height=\"363\" frameborder=\"0\"></iframe></div></li>";
					break;
			}
		}
		
		titleData="<div id='workCs'><a href='/#work' class='solo'>View All Featured Projects</a><h2>"+parsedEntries.find("title").text()+"</h2></div>";
		
		$("#workPage .titleBar").append(titleData);
		$("#indCs").html(data);
		
		$("#indCs .csTT").unbind("mouseover mouseout mousemove mouseenter mouseleave", rl.work.handleTooltip);
		$("#indCs .csTT").bind("mouseover mouseout mousemove mouseenter mouseleave", rl.work.handleTooltip);
		
		galleryWidth = (547*itemCount)+393+200;
		
		return;
	}	
	
	var handleTooltip = function(evt) {
		//move the tooltip to the ideal position
		$("#tooltip").css({"left":(evt.pageX + 16)+"px", "top":(evt.pageY - 30) + "px"}).removeClass("dispLeft").addClass("dispRight");
		//get the far right of the tooltip
		var ttright = evt.pageX + 16 + $("#tooltip").outerWidth();
		//hide the tooltip so it doesn't show up as efp
		$("#tooltip").css({"display": "none"});
		//adjust position if the tooltip goes past the right side of the document
		if (ttright > $(document).width()) {
			$("#tooltip").css({"left": evt.pageX - 16 - $("#tooltip").outerWidth() + "px" }).removeClass("dispRight").addClass("dispLeft");
		}
		
		//get the element underneath the mouse
		var efp = $(document.elementFromPoint(evt.pageX, evt.pageY));
		
		if ($(this).hasClass("csTT")) {
			var ihtml;
			if ($(this).attr("alt") != "") {
				ihtml = "<div class='caption'>" + $(this).attr("alt") + "</div><div class='subcap'>" + $(this).attr("data-subcap") + "</div>";
				if (efp.hasClass("csTT") && efp.attr("alt") != "") {
					$("#tooltip").css({"display":"block"});
				}
			} else {
				ihtml = "";
			}
			$("#tooltipContent").html(ihtml);
		} else {
			if (efp.hasClass("csTT") && efp.attr("alt") != "") {
				$("#tooltip").css({"display":"block"});
			}
		}
	}
	
	var tooltipPassthrough = function(evt) {
		evt.type = "mouseover";
		handleTooltip.call($(document.elementFromPoint(evt.pageX, evt.pageY)), evt);
	}
	
	var buildListGallery = function(galleryId,entryCount,startIndex) {
		var tags = "",
			tagItems = "",
			tagCount=0,
			tagHtml="",
			i=0,t=0,
			imgSrc="",
			data="",
			prevGalleryWidth=0,currGalleryWidth=0;
		
		for (i=startIndex;i<entryCount+startIndex;i++) {			
			tags = $(parsedEntries[i]).find("offerings");			
			tagCount = ($(tags).find("item").length==0) ? 0 : $(tags).find("item").length;
						
			if (tagCount!=0) {
				tagHtml = "";
				for (t=0;t<tagCount;t++) {					
					tagItems = $(tags[0]).find("item");					
					if ( t==(tagCount-1) )
						tagHtml += $(tagItems[t]).text();
					else
						tagHtml += $(tagItems[t]).text() +  ", ";					
				}				
			}			
			imgSrc = $(parsedEntries[i]).find('small_img').attr('src');
			link = "/#work/"+$(parsedEntries[i]).attr("id");
			
			data += "<li><h4><a href='"+link+"'>"+$(parsedEntries[i]).find('title').text()+"</a></h4>";
			data += "<div class='tags'><span class='industry'>"+$(parsedEntries[i]).find('industry').text()+"</span> | "+tagHtml+"</div>";
			data += "<a href='"+link+"' class='dim'><img src='"+imgSrc+"' /></a></li>";			
		}		
		$(galleryId).html(data);
		
		// grab the largest of the two different gallerywidths
		prevGalleryWidth = galleryWidth;
		currGalleryWidth = (302*entryCount)+200;
		galleryWidth = (currGalleryWidth>prevGalleryWidth) ? currGalleryWidth : prevGalleryWidth;
		
		return;
	}
	
	var buildCsSlider = function(galleryCount,overviewPos) {
		var sliderLiWidth = 42,			
			data = "";
				
		sliderWidth = (sliderLiWidth*(galleryCount))+27+42;

		for(var i=0;i<galleryCount;i++) {
			if (i==overviewPos) {
				data += "<li class='csText'></li>";
			}
			data += "<li></li>";			
		}
		
		$("#miniCs").html(data);		
		// set the slider width
		$("#slider").css("width",sliderWidth+"px");		
		// default handle to center
		$("#handle").css("left",(sliderWidth/2)-52);
	}
	
	var buildListSlider = function(miniGalleryId,galleryCount) {
		var sliderLiWidth = 28,
			currWidth=0,prevWidth=0,
			data = "";
		
		prevWidth=sliderWidth;
		currWidth=(sliderLiWidth*galleryCount)+42;  // 42 for margins
		sliderWidth = (currWidth>prevWidth) ? currWidth : prevWidth;
		
		for(var i=0;i<galleryCount;i++) {
			data += "<li></li>";
		}
		
		$(miniGalleryId).html(data);		
		// set the slider width
		$("#slider").css("width",sliderWidth+"px");		
		// default handle to center
		$("#handle").css("left",(sliderWidth/2)-52);	
	}
	
	var dragCsHandler = function() {		
		var moveMultiplier = (galleryWidth/(sliderWidth));		
		var centerAdjust = ((sliderWidth/2)-52)*moveMultiplier;
		
		// set the width and left position here as moveMultiplier is established here		
		$("#indCs").css({"width":galleryWidth,"left":-(centerAdjust)}); //-(galleryWidth/2)-100}
		
		// listen for dragging
		$('#handle').draggable({  // is this a memory leak?
			axis: "x",
			containment: "#slider",
			drag: function(e,ui) {
				leftPos = (ui.position.left)*-(moveMultiplier);				
				$("#indCs").css("left",leftPos+"px");
			}
		});
			
	}
	
	var dragListHandler = function(galleryId1,galleryId2) {		
		var moveMultiplier = (galleryWidth/(sliderWidth));		
		var centerAdjust = ((sliderWidth/2)-52)*moveMultiplier;
		
		// set the width and left position here as moveMultiplier is established here 
		$(galleryId1).css({"width":galleryWidth,"left":-(centerAdjust)}); //-(galleryWidth/2)-100}
		$(galleryId2).css({"width":galleryWidth,"left":-(centerAdjust)});
		
		// listen for dragging
		$('#handle').draggable({  // is this a memory leak?
			axis: "x",
			containment: "#slider",
			drag: function(e,ui) {
				leftPos = (ui.position.left)*-(moveMultiplier);				
				$(galleryId1).css("left",leftPos+"px");
				$(galleryId2).css("left",leftPos+"px");
			}
		});
			
	}
	
	return {
		parseXml : parseXml,
		handleTooltip: handleTooltip,
		load : function() {
			if (!sliderLoaded) {
				rl.model.loadCsFeed();  // grab model data				
				sliderLoaded=true;
			} else {							
				parseXml();
			}
			
			return;
		},
		init : function() {
			$("#tooltip").bind("mouseover mouseout mouseenter mouseleave mousemove", rl.work.handleTooltip);
			return;
		}
	};
	
}());
