var flashvars = {};
var params = {};
var attributes = {};

var theCat = '';
var theProj = '';
var theTab = '';
var theAsset = 0;
var headerOverride = '';
var months = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
var today = new Date();

var relatedProjectIds = new Array();
var searchResults = {};

var rooturl = "" + window.location;


function doTest(str) {
	alert(str);
}

function toggleAudioDropdown() {
	$('#player').toggleClass('on');
}

function getHomeUrl(arg) {
	// arg = "/lifestyle/scionmagazine/index.html"
	var gourl = rooturl.split('.com');
	if(arg.indexOf('#') > 0) {
		var spli = arg.split('#');
		arg = '/' + betterlink(spli[0]) + '#' + spli[1]; // make project name all lowercase with no spaces
	} else {
		arg = betterlink(arg); // make project name all lowercase with no spaces
	}
	gourl = gourl[0] +  '.com' + arg;
	window.location = gourl;
	return false;
}

function loadRelatedPrograms() {
	// dynamic Related Programming javascript
	var theURL = "";// + "/xml/";
	if(tabs == false) { theURL = theCat+"RelatedPrograms.xml"; }
	else { theURL = "relatedPrograms.xml"; }
	$.ajax({
		type: "GET",
		url: theURL,
		dataType: "xml",
		success: function(xml) {
		$('project',xml).each(function(i) {
			$('#rp').append('<a href="'+$(this).children('projectUrl').text()+'" class="'+((i%2 == 0) ? '' : 'two')+'"><img src="'+$(this).children('projectLogoSmall').text()+'" />'+$(this).children('projectName').text()+'<span></span></a>');
			relatedProjectIds.push( $(this).children('vmixProjectCollectionID').text() );
		});
		
		// now that we have relatedProjects data, we can load the relatedContent Flash module, as well...
		var relatedProjectIdsString = "";
		jQuery.each(relatedProjectIds, function() {
			relatedProjectIdsString += this + ",";
		});
		// add related content flash module
		//$('#related').append('<div id="relatedContentFlashModule"></div>');
		//$('#related').after('<div id="relatedPlaceholder">&nbsp;</div>');
		relatedProjectIdsString = relatedProjectIdsString.substring(0,relatedProjectIdsString.length-1);
		var relatedContentFlashVars = {collectionID: relatedProjectIdsString};
		//swfobject.embedSWF("/flash/relatedContent.swf", "relatedContentFlashModule", "205", "994","9.0.0","expressInstall.swf",relatedContentFlashVars, params, {id:"",name:""});
		swfobject.embedSWF("/flash/relatedContent.swf", "related", "205", "994","9.0.0","expressInstall.swf",relatedContentFlashVars, params, {id:"related",name:""});
		
		$('#rp a')
			.bind('mouseenter',function() { $(this).siblings('.on').removeClass('on'); $(this).addClass('on'); })
			.filter(':last').addClass('last').parent().children('a:first').addClass('first on');
		}
	});
}

function markNavCat() {
	$('#nav li a:contains('+theCat+')').parent().addClass('on').siblings('.on').removeClass('on');
}

function goHome() {
	rooturl = rooturl.substring(0,rooturl.indexOf('.com')) + '.com';
	attributes.id = "home";
	attributes.name = "home";
	flashvars.xmlUrl = "/xml/homepage.xml";
	swfobject.embedSWF("/flash/homepage.swf", "home", "565", "319","9.0.0","expressInstall.swf",flashvars, params, attributes);
}

function makeCollapsible() {
	$('#more ul').children('li').each(function() {
		if($(this).children().size() > 1) {
			$(this).children('a:first-child').click(function() { 
				$(this).parent().toggleClass('on');
				if(theTab.indexOf('image') >= 0) {
					if($(this).parent().hasClass('on')) {
						flashvars.collectionID = $(this).siblings('div').attr('id');
						attributes.id = flashvars.collectionID;
						attributes.name = flashvars.collectionID;
						swfobject.embedSWF("/flash/imagesThumbnails.swf", flashvars.collectionID,"544", "143","9.0.0","expressInstall.swf",flashvars, params, attributes);
					} else {
						var newid = $(this).siblings('object').attr('id');
						$(this).siblings('object').remove();
						$(this).after('<div id="'+newid+'" />');
					}
				}
				return false;
			});
		} //else {
		//	$(this).hide();
		//}
	});
	if(theTab.indexOf('image') >= 0) {
		$('#more ul li.on').removeClass('on').children('a').click();
	}
	if(theTab.indexOf('vid') >= 0) {
		var theli = $('#more ul.videos').children('li');
		if(theli.size() == 1) { theli.addClass('one').children('a').hide(); }
	}
}

function whatsHot() {
	attributes.id = "whatshot";
	attributes.name = "whatshot";
	var noflashvars = {};
	swfobject.embedSWF("/flash/whatsHot.swf", "whatshot", "546", "220","9.0.0","expressInstall.swf",noflashvars, params, attributes);	
}

function betterlink(lnk) {
	var mobetter = lnk.toLowerCase();
	mobetter = mobetter.replace(/ /g,'');
	mobetter = mobetter.replace(/\/scionav\//g,'/');
	return mobetter;
}

function deepLink(lnk) {
	// error check
	lnk = betterlink(lnk);
	var curl = "" + window.location;
	curl = curl.substr(0,curl.indexOf("/index.html"));
	var newurl = rooturl + ((lnk.substr(0,1) == '/') ? '' : '/') + lnk;
	var newSection = lnk.substr( 0, lnk.indexOf("/") );
	
	/*
	lnk = music/scionavremix/index.html#video,4286420
	curl = http://sciondev.ninthlink-proofing.com/music/scionavremix
	newurl = http://sciondev.ninthlink-proofing.com/music/scionavremix/index.html#video,4286420
	*/
	if( ($('#home').size()<1) && ($('#fourohfour').size()<1) && (newurl.indexOf(curl)!=-1) ) 
	{ // not on home or 404 , so check if TABS are set.
		if(tabs != false) {
			var tstart = lnk.indexOf("#");
			var tend = lnk.indexOf(",");
			
			if(tend == -1)
			{
				// there is no ',' in the string
				tend = lnk.length;
			}
			
			var gotab = lnk.substring((tstart+1),tend);
			theAsset = lnk.substr(tend+1);
			
			searchBye();
			$('#content, #related, #tabs li').show();
			
			if($('#li'+gotab+' a').size() > 0) { $('#li'+gotab+' a').click(); }
			// assuming bad tab link, like "video", recaps the first letter...
			gotab = (gotab.substring(0,1)).toUpperCase() + gotab.substr(1);
			$('#tabs a:contains('+gotab+')').click();
			
			return;
		}
	} // else
	window.location = newurl;
}

function searchBye() {
	if($('#title span').size() > 0) $('#title').html($('#title span').html());
	$('#main .results').remove();
}

function updateHash(asset) {
	var whash = "" + window.location.hash;
	whash = whash.split(',');
	window.location.hash = whash[0] + ',' + asset;
}

function prepareSearchResults() {
	if($('#home,#fourohfour').size() > 0) {
		$('#home,#fourohfour').remove();
		$('#wrap').append('<div id="left" /><div id="main"><ul id="tabs" /><h1 id="title" class="txt">Home</h1><div id="footer" /></div>');
	} else {
		$('#content, #related, #tabs li').hide();
	}
	if($('#searchtab').size() == 0) {
		$('#tabs').prepend('<li id="searchtab" class="on last"><a href="">Search</a></li>').find('#searchtab a').click(function() { return false; });
	}
	//$('#relatedPlaceholder').hide();
}

function searchReults(videoArray,imagesArray,audioArray,articlesArray,searchStr) {
	if($('#searchtab').size() > 0) {
		searchBye();
	} else {
		prepareSearchResults();
	}
	if((videoArray.length + imagesArray.length + audioArray.length + articlesArray.length) == 0) { searchNoResult(searchStr); return false; }
	$('#title').wrapInner('<span />').children('span').hide().after('Search Results for "' + searchStr + '"');
	var searchHeaders = new Array("Videos","Images","Audio","Articles");
	searchResults = new Array(videoArray, imagesArray, audioArray, articlesArray);
	var theURL = "/xml/projectManifest.xml";
	$.ajax({
		type: "GET",
		url: theURL,
		dataType: "xml",
		success: function(xml) {
			//alert(searchResults.toSource());
			for(var i=0; i<searchResults.length; i++) {
				if(searchResults[i].length > 0) {
					$('#footer').before('<div class="results ' + searchStr+ '"><h2>'+searchHeaders[i]+'</h2></div>');
					for(var j=0; j<searchResults[i].length; j++) {
						desctxt = searchResults[i][j].description.displayText;
						var href = "";
						var proj = "Project";
						$('vmixProjectCollectionID:contains("'+ searchResults[i][j].description.projectCollectionId +'")',xml).each(function() {
							href = '/' + $(this).siblings('projectCategory').text();
							href += '/'+ $(this).parent().parent().attr('name') + "/index.html" + "#" + searchResults[i][j].description.tab;
							/*
							var tname = $(this).siblings('tabName').text();
							$(this).parent().parent().children('tab').each(function(i) {
								if($(this).children('tabName').text() == tname) href += (i+1);
							});
							*/
							href += ',' + searchResults[i][j].id;
							proj = $(this).siblings('projectName').text()
						});//searchResults[i][j].description.categoryCollectionId
						$('#main .results:last').append('<a href="'+ href+ ((j<6) ? '' : '" class="bye') +'"><img src="'+ searchResults[i][j].thumbnailSmall+'" width="96" height="56" /><strong>'+proj+'</strong><em>'+searchResults[i][j].title+'</em>'+((desctxt.length > 86) ? (desctxt.substr(0,86)+'...') : desctxt) + '</a>');
					}
					if(searchResults[i].length > 6) { $('#main .results:last').append('<a href="" class="more">More</a>'); }
				}
			}
			$('#main .results a.more').click(function() {
				$(this).hide().siblings('.bye').removeClass('bye');
				$(this).parent().siblings('.results').remove();
				// paginate search results after MORE link is clicked right here
				return false;
			});
		}
	});
	return false;
}

function searchNoResult(str) {
	searchResults = {};
	prepareSearchResults();
	$('#title').wrapInner('<span />').children('span').hide().after('Search Results for "' + str + '"');
	$('#title').after('<div class="results"><h2>No results found. Please try again, or <a href="" class="back">go back</a>.</h2></div>');
	$('#main a.back').click(function() {
		$('#tabs li#searchtab, .results').remove();
		$('#tabs li, #content, #related').show();
		//$('#relatedPlaceholder').show();
		$('#title').html($('#title span').html());
		return false;
	});
	return false;
}

function handleEvents() {
	$('#content .events').attr('id','more').wrapInner('<ul class="text"><li class="on"></li></ul>');
	
	var eventMonth;
	var eventYear;
	var eventDate;
	var eventDateString = "";
	var eventEndDateString = "";
	var eventEndDateDisplayString = "";
	var eventMonth0;
	var eventD;
	var eventEndD;
	var eventSplit;
	var eventLocation = "";
	
	today.setDate(today.getDate() - 1); // adjust "today" to show events with the current date
	
	$('#content #more .event').each(function(i) {
		//for each .event
		$(this).children('p').after('<div class="dates">Event Dates</div>').siblings('.date').each(function(i) {
			if($.trim($(this).children('.hideEvent').text()) != '0') { 
				eventEndDateString = $.trim($(this).children('.eventEndDate').text());
				eventDateString = $.trim($(this).children('.eventStartDate').text());
				eventEndDateString = dateSlashToDotString(eventEndDateString);
				eventDateString = dateSlashToDotString(eventDateString);
				
				if(eventEndDateString != eventDateString)
				{
					eventEndDateDisplayString = " - " + eventEndDateString;
				} else {
					eventEndDateDisplayString = " ";
				}
				$(this).children('.eventEndDate').html(eventEndDateDisplayString + "<br />");
				$(this).children('.eventStartDate').html(eventDateString);
				eventSplit = eventEndDateString.split('.');
				eventD = new Date(eventSplit[2],eventSplit[0]-1,eventSplit[1]);
				if(eventD > today) {
					eventLocation = $.trim($(this).children('.eventCity').text());
					$(this).children('.eventCity').html(eventLocation);
					$(this).siblings('.dates').append('<br /><a href="">'+ eventDateString  + eventEndDateDisplayString + "<br />" +$(this).children('.eventCity').html() +'</a>');
				} else {
					//alert(eventD + ' is in the past!');
					$(this).remove();
				}
			}
			if($.trim($(this).children('.showUrl').text()) == '1') {
				$(this).append('<a href="'+$.trim($(this).children('.eventRsvpUrl').text())+'">Click to RSVP</a>');
			}
		});
		$(this).children('.dates').children('a').each(function(i) {
			$(this).click(function() {
				$(this).addClass('on').siblings('.on').removeClass('on');
				var thedate = $(this).parent().siblings('.date:eq('+i+')');
				thedate.addClass('on').siblings('.date.on').removeClass('on');
				var theevent = $(this).parent().parent();
				theevent.children('img').remove();
				var theimg = $.trim(thedate.children('.eventThumbnailImage').text());
				if(theimg == '') { theevent.addClass('noimg'); } else {
					theevent.prepend('<img src="'+ theimg +'" />');
				}
				return false;
			});
			if(i==0) { $(this).click(); }
		});
		if($(this).children('.date').size() > 0) {
			
			eventDate = $.trim($(this).children('.date:first').children('.eventStartDate').text());
			eventDate = eventDate.split('.');
			eventYear = eventDate[2];
			eventMonth = eventDate[0];
			eventMonth = parseInt(eventMonth,10) - 1;
			eventMonth0 = ((eventMonth < 10) ? '0' + eventMonth : '' + eventMonth);
			if($('#m'+eventYear+eventMonth0).size() <= 0) {
				if(i==0) {
				$('#content #more .text').prepend('<li id="m'+eventYear+eventMonth0+'" class="on"><a href="">'+months[eventMonth]+'</a></li>');
				} else {
					// and what about some sort of sorting?
					var insertdone = false;
					var compareli = $('#content #more .text li:first-child');
					while(!insertdone) {
						var liid = compareli.attr('id');
						if(liid < ("m"+eventYear+eventMonth0)) {
							compareli.before('<li id="m'+eventYear+eventMonth0+'" class="on"><a href="">'+months[eventMonth]+'</a></li>');
							insertdone = true;
						} else {
							if(compareli.next().size() <= 0) {
								compareli.after('<li id="m'+eventYear+eventMonth0+'" class="on"><a href="">'+months[eventMonth]+'</a></li>');
								insertdone = true;
							} else {
								compareli = compareli.next();	
							}
						}
					}
				}
			}
			$(this).appendTo($('#m'+eventYear+eventMonth0));
		} else {
			$(this).remove();
		}
	});
	makeCollapsible();
	var _eventsContent = $('#more ul').children('li');
	var _firstChildClean = _eventsContent[0].innerHTML.replace(/\s/g, "");
	if((_eventsContent.size()==1) && (_firstChildClean == '')) defaultEventsContent();
}

function defaultEventsContent(){
	var _insertString = "<div id='defaultEvents'>";
	_insertString+=     "<p>CHECK BACK SOON FOR MORE UPCOMING EVENTS!</p>";
	_insertString+=     "<p>Navigate to:<br>";
	_insertString+=     "<a href='/art/index.html'>ART</a><br>";
	_insertString+=     "<a href='/film/index.html'>FILM</a><br>";
	_insertString+=     "<a href='/lifestyle/index.html'>LIFESTYLE</a><br>";
	_insertString+=     "<a href='/music/index.html'>MUSIC</a><br>";
	_insertString+=     "</p>";
	_insertString+=     "</div>";
	$('#more').html(_insertString);
}

/**
*	Utility.  Converts a date string of format MM/DD/YY to MM.DD.YY for display purposes
**/
function dateSlashToDotString(dateString)
{
	var token = /\//g;
	dateString = dateString.replace(token,".");
	return dateString;
}

function scrollPageUp() {
	window.scrollTo(0,0);
}

function gomedia(i,j,asset) {
	var objid = $('#content object:eq(0)').attr('id');
	var mainapp = document.getElementById(objid);
	mainapp.newMediaItem(i,j);
	updateHash(asset);
	scrollPageUp();
	return false;
}

function connectionMessage() {
	var player = document.getElementById('player');
	player.connectionMessage();
	return false;
}

function importAudio(obj) {
	var player = document.getElementById('player');
	player.importAudio(obj);
	return false;
}

/** obj is the data object
*	isStream is a boolean indicating whether or not the track is streaming or a static file (like an MP3)
**/
function playTrackCouldBeStation(obj, isStream) {
	var player = document.getElementById('player');
	player.playTrackCouldBeStation(obj, isStream);
	return false;
}

function parseDur(durr) {
	var dM = Math.floor(durr/60);
	var dS = durr%60;
	
	var ret = ((dM < 10) ? '0' + dM : dM) + ':' + ((dS < 10) ? '0' + dS : dS);
	
	return ret;
}

function parseNestedCollections(nColl) {
	var tident = "" + window.location.hash;
	tident = (tident.split(','))[0];
	var numInside = nColl.length;
	var pageType = theTab.substr(0,3); // Abo, Vid, Ima, Aud, Bio, Cha, Art, Eve, Cus
	var id = '';
	switch (pageType) {
		case "ima":
			for(var i=0; i<numInside; i++) {
				if(nColl[i].theCollection.length > 0) {
					$('#more .images').append('<li'+ ((i==0) ? ' class="on"' : '') + '><a href="">' + nColl[i].title +' <span>('+ nColl[i].theCollection.length +' Images)</span></a><div id="'+ nColl[i].id +'"></div></li>');
				}
			}
			break;
		case "vid":
			for(var i=0; i<numInside; i++) {
				temp = $('#more .videos').append('<li'+ ((i==0) ? ' class="on"' : '') + '><a href="" rel="'+ nColl[i].id+'">' + nColl[i].title + '</a><ul /></li>').children('li:last-child').children('ul');
				for(var j=0; j<nColl[i].theCollection.length; j++) {
					rDate = new Date(nColl[i].theCollection[j].creationDate);
					dur = parseInt(nColl[i].theCollection[j].duration,10);
					sdur = parseDur(dur);
					id = nColl[i].theCollection[j].id;
					temp.append('<li><span class="title"><a href="'+tident+'" rel="' + id + '" onclick="gomedia('+i+','+ j+',' + id + '); return false;">' + nColl[i].theCollection[j].title + '</a></span><span class="runtime">' + sdur + '</span><span class="release">'+(rDate.getMonth() + 1) + '.'+ rDate.getDate() + '.' + rDate.getFullYear()+'</span><span class="rating"><img src="../../images/stars5.gif" alt="' + nColl[i].theCollection[j].rating + '" /></span></li>');
				}
			}
			break;
		case "cha":
			for(var i=0; i<nColl[0].theCollection.length; i++) {
				$('#more').append('<div class="channel"><a href="" onclick="gomedia(0,'+ i+',' + nColl[0].theCollection[i].id + '); return false;" rel="' + nColl[0].theCollection[i].id + '"><img src="' + nColl[0].theCollection[i].filePath + '" /></a><strong>' + nColl[0].theCollection[i].title + '</strong><br /><em>' + nColl[0].theCollection[i].description.displayText + '</em><br /></div>');
			}
			break;
		case "bio":
			$('#content').append('<div id="more"><ul class="text" /></div>');
			var bioCollectionLength = nColl[0].theCollection.length;
			if(bioCollectionLength == 1)
			{
				//only one node
				$('#more').addClass('soloBio');
			}
			for(var i=0; i<numInside; i++) {
				temp = $('#more .text').append('<li'+ ((i==0) ? ' class="on"' : '') + '>' + ((numInside > 1) ? ('<a href="">' + nColl[i].title + '</a>') : '' )+ '</li>').children('li:last');
				for(var j=0; j<nColl[i].theCollection.length; j++) {
					var dsptxt = nColl[i].theCollection[j].description.displayText;
					dsptxt = dsptxt.replace(/\n/g,'<br />');
					temp.append('<div><img src="'+nColl[i].theCollection[j].filePath+'" /><h2>'+nColl[i].theCollection[j].title+'</h2><p><span>'+dsptxt+'</span></p></div>');
					dsptxt = temp.children('div:last').find('span');
					if(dsptxt.height() > 66) { dsptxt.addClass('off').after('<a href="">Read More</a>'); }
				}
			}
			$('#more ul.text li.on div p a').click(function() {
				if($(this).prev().hasClass('off')) {
					$(this).html('Read Less').prev().removeClass('off');
				} else {
					$(this).html('Read More').prev().addClass('off');
				}
				return false;
			});
			break;
		case "art":
			$('#content').append('<div id="more"><ul class="text"><li class="on" /></ul></div>');
			// get the issue Cover (nColl[0])
			//exception case for scion mag article 15
			if (theTab == "articles2") {
				$('#content #more ul.text li:last-child').append('<div class="first"><a href="'+$.trim($('#content .interactivePdf').text())+'" target="_blank" class="strippedLinks"><img src="'+nColl[0].theCollection[0].filePath+'"/></a><h2>'+nColl[0].theCollection[0].title+'</h2><p>'+nColl[0].theCollection[0].description.displayText+'</p><div class="articleLinks"><a class="downloadArticle strippedLinks" href="'+$.trim($('#content .interactivePdf').text())+'" target="_blank">View Interactive Version</a>&nbsp;&nbsp<span style="color: #B0D3EA; display: inline; float: none;">|</span>&nbsp;&nbsp;<a class="downloadArticle strippedLinks" href="'+$.trim($('#content .issuePdf').text())+'">Download File</a></div></div>');
			}
			else {
				$('#content #more ul.text li:last-child').append('<div class="first"><img src="'+nColl[0].theCollection[0].filePath+'"/><h2>'+nColl[0].theCollection[0].title+'</h2><p>'+nColl[0].theCollection[0].description.displayText+'</p><a class="pdf" href="'+$.trim($('#content .issuePdf').text())+'">View Entire PDF</a></div>');
			}
			// get the issue other articles (nColl[1])
			for(var i=0; i<nColl[1].theCollection.length; i++) {
				//exception case for scion mag article 15
				if (theTab == "articles2") {
					$('#content #more ul.text li:last-child').append('<div><a href="'+$.trim($('#content .interactivePdf').text())+'" target="_blank" class="strippedLinks"><img src="'+nColl[1].theCollection[i].filePath+'"/></a><h2>'+nColl[1].theCollection[i].title+'</h2><p class="stars">'+nColl[1].theCollection[i].description.displayText+'</p></div>');
				}
				else {
					$('#content #more ul.text li:last-child').append('<div><img src="'+nColl[1].theCollection[i].filePath+'"/><h2>'+nColl[1].theCollection[i].title+'</h2><p class="stars">'+nColl[1].theCollection[i].description.displayText+'</p></div>');
				}
			}
			break;
	}
	
	makeCollapsible();
}

function biohelp() {
	var vmixCollection = $('#content').attr('class');
	var cntrl = document.getElementById('control');
	cntrl.getCollections(vmixCollection);
}

function helperFunctions() { // functions for elements on the various tab pages

	if($('#content .headerTitle').size() > 0) { //override header
		headerOverride = $('#title').html();
		$('#title').html($('#content .headerTitle').html());		
	}

	var vmixCollection = 0;
	if(tabs == false) {
		vmixCollection = theProj;
	} else {
		vmixCollection = $.trim($('#content .vmixGalleryId').html());		
	}
	if(theTab.indexOf('general') > -1) { theTab = $('#content .tabName').html(); theTab = ($.trim(theTab)).toLowerCase(); }
	if(theTab == "exhibitions") { theTab = 'bios'; }
	flashvars = {
		tab: theTab,
		collectionID: vmixCollection,
		assetID: theAsset
	};
	params = {
		wmode: "transparent"
	};
	//theTab = what type of page we are currently on, soooo ...
	var pageType = theTab.substr(0,3); // ab, vi, im, au, bi, ch, ar, ev, cu
	var eID = '';
	switch (pageType) {
		case "abo":
			eID = "mainapp";
			attributes.id = eID;
			attributes.name = eID;
			swfobject.embedSWF("/flash/aboutImageGallery.swf", eID, "547", "303","9.0.0","expressInstall.swf",flashvars, params, attributes);
			break;
		case "vid":
			eID = "mainappVid";
			attributes.id = eID;
			attributes.name = eID;
			params.allowFullScreen = 'true';
			$('#content').append('<div id="'+eID+'" /><div class="hr" /><div id="whatshot" /><div class="hr" /><div id="more"><div class="hdr"><span class="title" /><span class="runtime" /><span class="release" /><span class="rating" /></div><ul class="videos"></ul></div>')
			swfobject.embedSWF("/flash/videoPlayer.swf", eID, "547", "568","9.0.0","expressInstall.swf",flashvars, params, attributes);
			break;
		case "ima":
			eID = "mainappIma";
			attributes.id = eID;
			attributes.name = eID;
			$('#content').append('<div id="'+eID+'" /><div class="hr" /><div id="whatshot" /><div class="hr" /><div id="more"><ul class="images" /></div>');
			swfobject.embedSWF("/flash/imagesBrowser.swf", eID, "547", "358","9.0.0","expressInstall.swf",flashvars, params, attributes);
			break;
		case "aud":
			eID = "mainappAud";
			attributes.id = eID;
			attributes.name = eID;
			$('#content').append('<div id="'+eID+'" /><div class="hr" /><div id="whatshot" /><div class="hr" /><div id="more" />');
			swfobject.embedSWF("/flash/audioDetail.swf", eID, "547", "330","9.0.0","expressInstall.swf",flashvars, params, attributes);
			attributes.id = 'more'; attributes.name = 'more';
			swfobject.embedSWF("/flash/audioBrowser.swf", "more", "547", "248","9.0.0","expressInstall.swf",flashvars, params, attributes);
			break;
		case "bio":
			$('#content').attr("class", vmixCollection);
			//$('#content').addClass(vmixCollection);
			setTimeout("biohelp(); ",500); // not sure why this one needs a delay...
			break;
		case "cha":
			eID = "mainappCha";
			attributes.id = eID;
			attributes.name = eID;
			$('#content').append('<div id="'+eID+'" /><div class="hr" /><div id="more" />');
			swfobject.embedSWF("/flash/channels.swf", eID, "532", "337","9.0.0","expressInstall.swf",flashvars, params, attributes);
			break;
		case "art":
			// until Allen gets VMIX calls working, fake the content
			$('#content').attr("class", vmixCollection);
			//$('#content').addClass(vmixCollection);
			setTimeout("biohelp(); ",500); // not sure why this one needs a delay...
			break;
		case "eve":
			//fix events formatting
			handleEvents();
			break;
		default:
			//do not draw any flash, we are cool
			break;
	}
	
	// add whatsHot flash
	if($('#whatshot').size() > 0) {
		whatsHot();
	}
}

function processTabs() {
	if($('#tabs li a:empty').size() == 0) {
		$('#tabs li a .tabName').each(function(i) {
			var txt = $.trim($(this).text());
			$(this).html(txt);
			if(theTab.toLowerCase() == txt.toLowerCase()) {
				theTab = tabs[i+1];
				var whash = "" + window.location.hash;
				if(whash.indexOf(',') > -1) { whash = whash.split(','); whash = ',' + whash[1]; }
				else { whash = ''; }
				window.location.hash = theTab + whash;
				$(this).parent().parent().addClass('on').children('a:first-child').click();
			}
		});
	}
}

function loadPage() {
	// always call Omniture
	callOmniture();
	//draw the controller, search bar, and audio player flash, as these 3 will be on all pages
	flashvars = {};
	params = {
		wmode: "transparent"
	};
	attributes = {};
	$('body').append('<div id="control" />');
	attributes.id = "control";
	attributes.name = "control";
	swfobject.embedSWF("/flash/controller.swf", "control", "1", "1","9.0.0","expressInstall.swf",flashvars, params, attributes);
	attributes.id = "search";
	attributes.name = "search";
	swfobject.embedSWF("/flash/searchbar.swf", "search", "205", "29","9.0.0","expressInstall.swf",flashvars, params, attributes);
	attributes.id = "player";
	attributes.name = "player";
	swfobject.embedSWF("/flash/audioPlayer.swf", "player", "199", "415","9.0.0","expressInstall.swf",flashvars, params, attributes);
	
	attributes.id = "events";
	attributes.name = "events";
	flashvars.xmlUrl = "/xml/eventsManifest.xml";
	swfobject.embedSWF("/flash/events.swf", "events", "191", "221","9.0.0","expressInstall.swf",flashvars, params, attributes);
	
	
	attributes = {
		id: "",
		name: ""
	};
	
	$('#player').blur(function() { /*alert('ok!');*/ });
	
	if($('#home').size() > 0) { // home page
		goHome();
		return false;
	}
	if($('#fourohfour').size() > 0) { // 404 page
		rooturl = rooturl.substring(0,rooturl.indexOf('/')) + '/';
		return false;
	}
	
	//otherwise, on category landing page (page has no Tabs) or project page (has Tabs)
	theCat = category.toLowerCase();
	$('#nav li a[href="/'+theCat+'/index.html"]').parent().addClass('on');
	
	rooturl = rooturl.substr(0,(rooturl.indexOf(theCat)-1));
	
	var locA = "" + window.location.hash;
	theAsset = locA.indexOf(',');
	if(theAsset > -1) { theAsset = locA.substr(theAsset + 1); }
	
	flashvars = {
		collectionID: vmixProjectId
	};
	params = {
		wmode: "transparent"
	};
	attributes = {
		id: "related",
		name: "related"
	};
	
	// tabfix for IE6 ...
	
	$('#tabs').addClass('beforemain').insertBefore('#main');
	$('#main').addClass('aftertabs');
	
	// alright
	loadRelatedPrograms();	

	if(tabs == false) {
		// we are on a cat landing page, so ... do something ...
		//flashvars = { collectionID: relatedContentId };
		//loadRelatedPrograms();
		//swfobject.embedSWF("/flash/relatedContent.swf", "related", "205", "994","9.0.0","expressInstall.swf",flashvars, params, attributes);
		
		theTab = "about";
		theProj = vmixProjectId;
		$('#tabs').append('<li class="on last"><a href="">About</a></li>');
		
		helperFunctions();
		return false;
	} // else { on project page
	
	theProj = $('#title').text();
	theProj = theProj.split(' ').join('').toLowerCase();
	//loadRelatedPrograms();
	
	var tabLoc = "" + window.location.hash;
	if(tabLoc != "") {
		theTab = tabLoc.substr(1);
		theTab = theTab.split(',');
		theTab = theTab[0];
		// error correct for deep linking, so theTab = "general2" and not "Video" ?
		
	} else {
		theTab = tabs[1];
	}

	
	flashvars = {
		tab: theTab,
		collectionID: vmixProjectId,
		assetID: theAsset
	};
	params = {
		wmode: "transparent"
	};
	attributes = {
		id: "",
		name: ""
	};
	// so now lets get the tab names!
	var theUrl = '';
	for(var i=1; i < tabs.length; i++) {
		theUrl = tabs[i]+'.incl .tabName';
		//theUrl = '/includes/'+theCat+'/'+theProj+tabs[i]+'.incl .tabName';
		$('#tabs').append('<li id="li'+tabs[i]+'"><a href="#'+tabs[i]+'"></a></li>').children('li:last').children('a').load(theUrl,processTabs);
		
		if(tabs[i].indexOf('vents') > -1) { // for Events, hide tab if hideEventsTab == 1
			//theUrl = '/includes/'+theCat+'/'+theProj+tabs[i]+'.incl .hideEventsTab';	
			theUrl = tabs[i]+'.incl .hideEventsTab';		
			$('#tabs li:last').append('<div class="hideEventsTab" />').children('.hideEventsTab').load(theUrl,function() {
				var hidecheck = $('#tabs .hideEventsTab .hideEventsTab');
				if(hidecheck.html() == '1') {
					hidecheck.parent().parent().hide().children('.hideEventsTab').remove();
				}
			});
		} 
	}
	$('#tabs li:last').addClass('last');
	$('#tabs li a[href*='+theTab+']').parent().addClass('on');
	if(!window.location.hash) { window.location.hash = '#' + theTab; }
	
	$('#tabs a').each(function(i) {
		$(this).click(function () {
			var tabLoc = ($(this).attr('href')).split('#');
			theTab = tabLoc[1];
			if($(this).parent().hasClass('on') == false) {
				$(this).parent().addClass('on').siblings('.on').removeClass('on');
				window.location.hash = '#' + theTab;
				// go omniture?
				s_pageName = "sci: scionav: " + theCat + ": " + theProj + ": " + theTab;
				//s.tl(true,'o','tab change');
			}
			var theUrl = theTab+'.incl';
			//un-override the header?
			if(headerOverride != '') { $('#title').html(headerOverride); headerOverride = ''; }
			$('#content').empty().load(theUrl,helperFunctions);
			return false;
		});
		if($(this).parent().hasClass('on')) { $(this).click(); }
	});
	
}

/**
* callOmniture() sets the value for a campaign code when appropriate, and makes a standard call to the Omniture service.
* All other standard Omniture object values are set on a page-by-page basis, but this function must be called after they are
* set, in order to actually make the call to Omniture.
*
*/
function callOmniture()
{
	// look for the campaignCode ('scid') in the query string 
	// if it exists, and hasn't already been set earlier in the session, set it
	var qs = document.location.search.substring(1);
	
	var vars = qs.split("&"); 
	var campaignCode = "";
	
	// Look in the query string
	for (var i=0; i<vars.length; i++) 
	{
		var pair = vars[i].split("="); 
		if (pair[0] == 'scid') 
		{
			campaignCode = pair[1]; 
		} 
	}
	if(campaignCode == "")
	{
		// some redirects set prior query string params in a hash element, so we need to inspect that as well
		var hashElements = window.location.hash;
		hashElements = hashElements.substring( hashElements.indexOf('?')+1, hashElements.length );
		vars = hashElements.split("&"); 
		for (var j=0; j<vars.length; j++) 
		{
			pair = vars[j].split("="); 
			if (pair[0] == 'scid') 
			{
				campaignCode = pair[1]; 
			} 
		}
	}
	
	
	// check cookies to see if the campaign code was already set this session
	var presetCampaignCode = Get_Cookie('omnitureCampaignCode');
	
	if(presetCampaignCode == null && campaignCode != "")
	{
		// campaign code wasn't already set, but was passed in the query string, so we need to set it and store it as a cookie so we won't set it more than once
		
		// These are the possible parameters for Set_Cookie:
		// name, value, expires, path, domain, secure
		Set_Cookie( 'omnitureCampaignCode', campaignCode, '', '/', '', '' );
		s.campaign = campaignCode;
	} else {
		// campaign code was already set, or no code was passed, so set the omniture campaign code to an empty string
		s.campaign = "";
	}
	
	// all values are set so make the call to Omniture's server
	s.t();
}

function Set_Cookie( name, value, expires, path, domain, secure ) 
{
		// set time, it's in milliseconds
		var today = new Date();
		today.setTime( today.getTime() );
		
		/*
		if the expires variable is set, make the correct 
		expires time, the current script below will set 
		it for x number of days, to make it for hours, 
		delete * 24, for minutes, delete * 60 * 24
		*/
		if ( expires )
		{
			expires = expires * 1000 * 60 * 60 * 24;
		}
		var expires_date = new Date( today.getTime() + (expires) );
		var cookieString = name + "=" + value  +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
		
		document.cookie = cookieString;
}

// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}			

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) 
{
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
		( ( path ) ? ";path=" + path : "") +
		( ( domain ) ? ";domain=" + domain : "" ) +
		";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function Check_Cookie(name) 
{
	var cookie_val = Get_Cookie(name);
	//trace(name + " Cookie: " + cookie_val);
}


function clearPage() {
	$('#left,#main,#home').remove();
}

$(function() {	
	loadPage();
	$('#nav li').bind('mouseenter',function() { $(this).addClass('ov'); }).bind('mouseleave',function() { $(this).removeClass('ov'); });
});