// ALL TOGETHER NOW
	$(document).ready(function(){
		setHeights();  		// set heights upon page load
		initHomeLink();		// make home link slip out on hover
		initMainMenu();		// glow and init hover animations on main menu
		initNewsTicker();	// make news ticker slip out on hover
		initVidThumbs();	// randomly turn on thumbnails
		vidHover();			// slide the title upon hover
		gdayTest = $('h3.pagetitle').text(); // fetch the greeting
		if (gdayTest.indexOf('good day') !== -1) { localTimeGreeting(); } // if greeting is good day, convert to greeting for local time.
		emboldenh3();		// wrap ems around a char
		
		
		$(window).resize(function(){
			setHeights();	// remember to re-set heights upon window resize
		});
		
		initNanoScroller();	// initialize inner scrolls
		addSocialLinks();	// make the social links coordinate with social menu item
		switchToHD();
		prependmVideos();
	});

function prependmVideos(){
	$('div.vidcol.musicVideo ul li').each(function(){
		var data = $(this).data();
		var fart = data.artist[0] + " - ";
		
		$(this).find('h5.title').prepend(fart);
	});
}

function switchToHD(){
	var tog = $('ul.mainmenu a[title="HD is off"]');		// identify the menu item that inits the toggle

	function searchStringInArray (stringArray,needle) {
	    for (var j=0; j<stringArray.length; j++) {
	        if (stringArray[j].match (needle)) return j;
	    }
	    return null;
	}

	tog.click(function(){
		if (tog.attr('title') == 'HD is off') {				// if the switch is off
			tog.attr('title', 'HD is on');
			tog.html('Disable HD');
			
			$('a.vidlink h5.hd').show().parent('a').each(function(){ //in the process, show the HD Available tag
				// begin dissection of what the shadowbox width and height params are
				var sbox = $(this).attr('rel').split(';');
				
				var wi = searchStringInArray(sbox,'width');
				var hi = searchStringInArray(sbox,'height');
				
				var warr = sbox[wi].match(/\d/g);
				var harr = sbox[hi].match(/\d/g);
				
				var w = '';
				var h = '';
				for (var i in warr) { w += warr[i]; } 
				for (var i in harr) { h += harr[i]; } 
	
				if (w == 640 && h == 360) { hdw = w*2; hdh = h*2; } // what to do if the video is standard size (double the w and h)
				else if (w == 846 && h == 360) { hdw = 1280; hdh = 544;} // what to do if it's this special 2:35 thingy
				else { hdw = w; hdh = h;}
				
				// form the new rel attr and replace the href with _hd.mov, and finally, tell Shadowbox to redo it.
				var newSBox = 'shadowbox;height=' + hdh + ';width=' + hdw;
				
				$(this).attr('rel',newSBox);
				var ohref = $(this).attr('href');
				var nhref = ohref.substr(ohref, ohref.length-4) + '_hd.mov';
				$(this).attr('href',nhref);
			
				Shadowbox.setup($(this));
				$(this).children('h5.nsfw').addClass('share');
			});

			return true;
	  	}
		if (tog.attr('title') == 'HD is on')  {				// if the switch is on
			tog.attr('title', 'HD is off');
			tog.html('Enable HD');
			
			$('a.vidlink h5.hd').hide().parent('a').each(function(){ // hide it now
				// begin dissection of what the shadowbox width and height params are
				var sbox = $(this).attr('rel').split(';');
				
				var wi = searchStringInArray(sbox,'width');
				var hi = searchStringInArray(sbox,'height');
				
				var warr = sbox[wi].match(/\d/g);
				var harr = sbox[hi].match(/\d/g);
				
				var w = '';
				var h = '';
				for (var i in warr) { w += warr[i]; } 
				for (var i in harr) { h += harr[i]; } 
	
				if (w == 1280 && h == 720) { hdw = w/2; hdh = h/2; } // what to do if the video is 16:9 size (halve the w and h)
				else if (w == 1280 && h == 544) { hdw = 846; hdh = 360; } // what to do if it's this special 2:35 thingy
				
				else { hdw = w; hdh = h;}
				
				// form the new rel attr and replace the href with _hd.mov, and finally, tell Shadowbox to redo it.
				var newSBox = 'shadowbox;height=' + hdh + ';width=' + hdw;
				
				$(this).attr('rel',newSBox);
				var ohref = $(this).attr('href');
				var nhref = ohref.substr(ohref, ohref.length-7) + '.mov';
				$(this).attr('href',nhref);
			
				Shadowbox.setup($(this));
				$(this).children('h5.nsfw.share').removeClass('share');
			});
			
			return true;
		}
	});
}

// animate the main home link 'stick-out'
function initHomeLink(){  		
  		var ani = 17; //the animation increment, in pixels
  		var tar = $('a#main-home-link h2.dop');
  		
  		var lst = tar.css('left'); //the starting position for css left
  		var pst = tar.css('padding-right'); //the starting padding-right value
		var lfi = parseInt(lst) + ani + "px"; //final left value
		var pfi = parseInt(pst) + ani + "px"; //final padding value
		
			// actually do it
	  		tar.parent().hover(
	  			function(){tar.stop().animate({ "left" : lfi, "padding-right" : pfi }, "fast");},
	  			function(){tar.stop().animate({ "left" : lst, "padding-right" : pst }, "fast");}
				);
}
  	
// add roman numerals to the beginning of the menu, then add animatable underlines
function initMainMenu(){
		var width = $(window).width();
		var height = $(window).height();
		var tog = $('ul.mainmenu a[title="HD is off"]');
		if (width < 1300 || height < 740) {tog.parent('li').detach();}	// don't even show the HD option if the window is too small.
	
  		var e = $('ul.mainmenu li');
  		e.each(function(i){
  			var rnum = romanize(i+1);
  			var rstr = '<span class="roman">' + rnum + '.</span>';
  			$(this).prepend(rstr);
  			var str = '<li><div class="m_underline"></div></li>';
  			$(this).after(str);
  		});
  		
		// starter animation
  		var baseWait = 900;
  		var aniTime = 900;
  		$('div.m_underline').each(function(i){
  			var t = baseWait + i * 200;
  			$(this).delay(t).animate({width: "0px", opacity: 0}, aniTime);
  			$(this).delay(t).parent('li').prev('li').children('span.roman').animate({color: "black"}, t*2);
  		});
  		
		//animate upon hover
  		var hoverTime = aniTime/4;
  		e.children('a').hover(
  			function(){
  				$(this).parent('li').next('li').children('div.m_underline').stop(true).animate({width: "100%", opacity: 1}, hoverTime);
  				$(this).prev('span.roman').stop(true).animate({color: "white"}, hoverTime);
  				}, function() {
  				$(this).parent('li').next('li').children('div.m_underline').stop().animate({width: "0px", opacity: 0}, hoverTime);
  				$(this).prev('span.roman').stop().animate({color: "black"}, hoverTime);
  		});
}
  	
// animate & innerfade the newsticker
function initNewsTicker(){
		// starting fade-in
		var ticker = $('header div.posts');
		ticker.css('opacity', 0);
		ticker.animate({'opacity':1}, 850);
		
		// revolving door
		var ohei = ticker.height();
		ticker.innerfade({
			animationtype: 'slide',
			timeout: 7000,
			containerheight: ohei + 'px'
		});
		
		// hover
		var ani = 10; //the animation increment, in pixels
  		
  		var pst = ticker.css('padding-right'); //the starting padding-right value
		var pfi = parseInt(pst) + ani + "px"; //final padding value
		
		ticker.find('div.entry a').hover(
		function(){ticker.stop('news').animate({ "padding-right" : pfi }, { duration : "fast", queue: 'news'}).dequeue('news');},
		function(){ticker.stop('news').animate({ "padding-right" : pst }, { duration : "fast", queue: 'news'}).dequeue('news');}
		);

}

// resize height settings
function calcHeight(s){
	// gather stats
	var vHt = $(window).height();
	var wwid = $(window).width();
	var hHt = $('header').height();
	var hMt = parseInt($('header').css('margin-top'));
	var mCtp = parseInt($('div.maincontent').css('padding-top'));
	var vmTop = parseInt($('div.vidcol').css('margin-top'));
	var vmBot = parseInt($('div.vidcol').css('margin-bottom'));
	var iMain = parseInt($('ul.mainmenu').css('margin-top'));
	var iMw = $('ul.mainmenu').height();
	
	// run calcs
	if( s == 'vHt'){
		return vHt;
	}
	if( s == 'wwid') {
		return wwid;
	}
	
	if( s == 'max' ) {
		var MaxCol = vHt - hHt - hMt - mCtp - vmTop - vmBot;
		return MaxCol; 
	}
	
	if( s == 'main') {
		var mainHeight = vHt - hHt - hMt- mCtp;
		return mainHeight; 
	}
	
	if( s == 'menu') {
		var top = hHt + hMt + iMain + iMw + 40; 
		return top + 'px';
	}
	
}

function setHeights(){
	var maxHt = calcHeight('max');
	$('div.vidcol').each(function(){
		var minHt = $(this).find('ul').height();
		// minHt += parseInt($(this).find('ul li').css('margin-bottom'));
		if (minHt < maxHt) { $(this).height(minHt); }
		else { $(this).height(maxHt); }
	});

	var mHeight = calcHeight('main');
	$('div.maincontent').height(mHeight);
	
	if (!enoughSpace()) { $('div.vidinfo').addClass("left").css('top',calcHeight('menu')); }
	if (enoughSpace())  { $('div.vidinfo').removeClass("left"); }
}


// determine placement of div.vidinfo
function enoughSpace(){
	var conW = $('div.maincontent').width();
	var vidS = $('div.vidinfo').width();
	var colW = 0;
	$('div.vidcol').each(function(i){
		colW += $(this).width() + parseInt($(this).css('margin-right')) + parseInt($(this).css('padding-right')) + parseInt($(this).css('border-right-width')) 
		});
	var diff = conW - colW;
	if (vidS > diff) {return false;} else {return true;}
}

function initNanoScroller(){
	$('div.nano').each(function(){
		$(this).nanoScroller();
	});
}
function initVidThumbs(){
	function randsort(c) {
		var o = new Array();
		for (var i = 0; i < c; i++) {
			var n = Math.floor(Math.random()*c);
			if( jQuery.inArray(n, o) > 0 ) --i;
			else o.push(n);
		}
		return o;
	}
	
	var e = $('div.maincontent div.vidcol ul li');
	var c = e.size();
	var r = randsort(c);
	
	e.each(function(i) {
		var e = $(this);
		e.fadeTo(0, 0.03);
		setTimeout(function(){
			e.fadeTo(1000, 1);
		}, r[i]*111);
	});
}

// animate and populate data into the vidinfo div
function vidHover(){
	$('div.vidcol li a h5.title').slideToggle(0); //initalize the bottom title flag to be down
	$('div.vidcol li a h5.nsfw').slideToggle(0);
	
	$('div.vidcol li a').hover(
		function(){
			$(this).children('h5.title').stop(true,true).slideToggle('fast'); //animate the bottom flag
			$(this).children('h5.nsfw').stop(true,true).slideToggle('fast');  //animate the top flag
			
			// now, build the vidinfo area
				var hli = $(this); 
				var vidtitle = hli.children('h5.title,h6').text();
				var rawvidinfo = hli.parent('li').data();
			if (!jQuery.isEmptyObject(rawvidinfo)) { 
				var hvi = '<table><caption>' + vidtitle + '</caption><tbody>';
				
				// specify the orders that info is to be displayed, along with seperator flags
				var narOrd = ["director","producer","actor","company","sec_sep","genre","sec_sep","camera","format","aspect","runtime","distribution"];
				var mVideoOrd = ["artist","label","sec_sep","director","company","producer","sec_sep","genre","sec_sep","camera","format","aspect","runtime","distribution"];
				var comOrd = ["client","company","sec_sep","director","producer","sec_sep","genre","sec_sep","camera","format","aspect","runtime","distribution"];
				// figure out post_type
				if ( hli.parents('.narrative').length == 1) {var curtype = narOrd;}
				if ( hli.parents('.musicVideo').length == 1) {var curtype = mVideoOrd;}
				if ( hli.parents('.commercial').length == 1) {var curtype = comOrd;}
				
				// iterate over the type that we're in
					for(key in curtype){
						var key = curtype[key];
							if (rawvidinfo[key]){ //make sure it's not empty
								
								for(index in rawvidinfo[key]){
								var value = rawvidinfo[key][index];
								var single = rawvidinfo[key].length;
								
								if (index == 0) {
									hvi += '<tr><td class="key">';
									if (key == 'actor') { hvi += 'cast' } else { hvi += key; } 
										if (single == 1 || key == 'format' || key == 'actor') hvi += ':</td><td class="value">';
										if (single > 1 && key != 'format' && key != 'company' && key != 'actor') hvi += 's:</td><td class="value">';
										if (single > 1 && key == 'company') { hvi = hvi.substr(0, hvi.length-1); hvi +='ies:</td><td class="value">';} 
									hvi += value;
									hvi += '</td></tr>';
								}
									
								if (index > 0){
									hvi += '<tr><td></td><td class="value">';
									hvi += value;
									hvi += '</td></tr>';
								}
							}
						}
						var sep_row = '<tr class="seperator"><td></td><td></td></tr>';
						var tab_beg = '<tbody>';
						if (key == 'sec_sep' && hvi.substr(-sep_row.length,sep_row.length) != sep_row && hvi.substr(-tab_beg.length,tab_beg.length) != tab_beg) {hvi += sep_row;}	
					}
				hvi += '</tbody></table>';
				var current = $('div.vidinfo').html();
				if (current != hvi){
					$('div.vidinfo').stop(true,true).fadeOut(175, function(){ 
						$('div.vidinfo').html(hvi);
					}).fadeIn(175);
				}
		}},
		function(){
			$(this).children('h5.title').stop(true,true).slideToggle('fast');
			$(this).children('h5.nsfw').stop(true,true).slideToggle('fast');
		}
	);
}

function localTimeGreeting(){
	var now = moment();
	var ct = now.format('HHmm');
	
	var gmorn = 'good morning';
	var gaft = 'good afternoon';
	var geve = 'good evening';

	if (ct >= 1730 || ct >= 0) str = geve;	
	if (ct >= 600 && ct < 1200) str = gmorn;
	if (ct >= 1200 && ct < 1730) str = gaft;
	
	str += '.';
	
	$('h3.pagetitle').text(str);
}

function emboldenh3(){
	var t = $('div.main h3.pagetitle');
	var words = $(t).text()
	words = jQuery.trim(words);
	words = words.split(' ');
	$(words).each(function(i){ words[i] = words[i].trim(); });
	var rwi = Math.floor(Math.random()*words.length);

	$(words).each(function(i){
		if (i == rwi) words[i] = '<em>' + words[i].substr(0,1) + '</em>' + words[i].substr(1);
	});

	var newstring = '';
	$(words).each(function(i){
		word = words[i];
		if (i = 0) { newstring += word; }
		else { newstring += ' ' + word; }
	});
	
	$(t).html(newstring);
}

function addSocialLinks(){
	var sBox = '<li class="sociallinks"><a style="display: none;" class="facebook" href="http://www.facebook.com/bobbydp" target="_blank"><img src="/img/facebook.png" /></a><a style="display: none;" class="twitter" href="http://www.twitter.com/bobbydp" target="_blank"><img src="/img/twitter.png" /></a></li>';
	$('ul.mainmenu').append(sBox);
	
	$('a[title="Social"]').click(function(){ 
		$('ul.mainmenu li.sociallinks a').fadeToggle(175);
	});
}
