/**
 * @author dchiu
 */
var imagePath='/cdc_content_elements/humannetwork/hn3/images';
var jsPath='/web/about/humannetwork/js';


function renderPage(jQuery, page) {
	if (page != 'home') {
		jQuery('<script type="text/javascript" src="' + jsPath + '/jquery.localscroll-1.2.6-min.js"></script>').appendTo('head');
		jQuery('<script type="text/javascript" src="' + jsPath + '/jquery.scrollTo-1.3.3-min.js"></script>').appendTo('head');
		jQuery('<script type="text/javascript" src="' + jsPath + '/jquery.serialScroll-1.2.1-min.js"></script>').appendTo('head');
	}
	
	if (page == 'home') {
		//load media content
		jQuery.get("home.xml",function(xml){
			var text = jQuery("channel>item",xml).each(
				function(idx){
					//display main video
					if (idx==getVideo()) {
						renderDartTag(this);
						renderVideoPlayer(this, "home-video");
												
						jQuery('div#home-video-entry').html('<h2>'+jQuery('title',this).text()+'</h2>');
						jQuery('div#home-video-entry').append('<p>'+jQuery('description',this).text()+'</p>');
					}

					//display thumbnails
					jQuery('div#thumb-entry-'+idx+' .thumb-photo').append(
						'<img src="'+getMediaThumbnail(this).attr('url')+'" class="home-thumbnail" border="0" id="thumb'+idx+'">'+
						'<a href="?videoid='+idx+'">'+
						'<img src="'+imagePath+'/home_thumb_clipping_mask_'+idx+'.gif" class="thumb-clipping-mask" border="0"></a>'
						);
					jQuery('div#thumb-entry-'+idx).append(
						'<h3>'+jQuery('title',this).text()+'</h3>'+
						'<p>'+jQuery('description',this).text()+'</p>'
						);
				})
			});
	}
	
	if (page == 'work') {
		jQuery('h2.category-title').html('in the workplace');
		renderThumbnailPage(jQuery, page);
	}
	
	if (page == 'community') {
		jQuery('h2.category-title').html('in the community');
		renderThumbnailPage(jQuery, page);
	}
	
	if (page == 'entertainment') {
		jQuery('h2.category-title').html('in entertainment');
		renderThumbnailPage(jQuery, page);
	}
	
	if (page == 'sports') {
		jQuery('h2.category-title').html('in sports');
		renderThumbnailPage(jQuery, page);
	}
	
	if (page == 'videoplayer') {
		var key=getUrlVars();
		renderVideoPage(jQuery, key['category']);
	}
}

function renderDartTag(xmlObj) {
	var type=jQuery('DARTtag>type',xmlObj).text();
	var cat=jQuery('DARTtag>cat',xmlObj).text();
	var axel = Math.random()+"";
	var a = axel * 10000000000000;
	if (type.length > 1 && cat.length > 1) {
		jQuery('BODY').append('<IMG SRC="http://ad.doubleclick.net/activity;src=1165127;type='+type+';cat='+cat+';ord=1;num='+ a + '?" WIDTH=1 HEIGHT=1 BORDER=0>');	
	}
}

function renderVideoPage(jQuery, category){
	jQuery('UL LI#'+category+' A img').css('visibility','hidden');
	jQuery('UL LI#'+category).css('background','url('+imagePath+'/'+category+'_highlite.gif) no-repeat');
	jQuery('UL LI#'+category).css('margin-left','-4px');

	jQuery.get(category+".xml", function(xml){	
		jQuery('div#related-links').html('<h3>Related Links</h3>');
		
		jQuery('div#videoplayer-bottom h3').html('Related Stories');
		
		var thumbnails = jQuery("channel>item", xml).each(function(idx){
			//display main video
			if (getCiscoVideoID(this).replace('.flv','') == getVideo()) {
				renderDartTag(this);
				renderVideoPlayer(this, "video");
				jQuery('div#catgory-description').html('<h3>'+jQuery("title:first", this).text()+'</h3>');
				jQuery('div#catgory-description').append('<p>'+jQuery("description:first", this).text()+'</p>');
				var related = jQuery("related>item", this).each(function(idx){
					jQuery('#related-links').append('<a href="'+jQuery('link',this).text()+'" target="_blank">'+jQuery('title',this).text()+'</a>')
					});			
			}

			if (idx%4==0 && idx!==0) {
				var panelNum=jQuery('div.panel').length+1;
				jQuery('div.scrollContainer').append('<div class="panel" id="panel'+panelNum+'"></div>');
			}

			jQuery('div.panel:last').append(
				'<div class="medium-thumb">'+
				'	<div class="thumb">'+
				'		<img src="' +imagePath+'/thumbnails/'+category+'/'+
						getCiscoVideoID(this).replace('.flv','') +'/93x61.jpg'+'" />'+
				'	</div>'+
				'	<a href="#" onclick="return showVideo(\''+category+'\',\''+getCiscoVideoID(this).replace('.flv','')+'\')"><img src="'+imagePath+'/medium_thumb_clipping_mask.gif" class="clipping-mask" border="0"></a>'+
				'	<div class="thumb-title">'+
						jQuery('title:first',this).text()+
				'	</div>'+
				'</div>'
				);				
		})
		
		try { 
			jQuery(document).ready(initCategorySlider());	
		} catch (e) {}
		jQuery('#slider .scroll').after('<div id="viewall"><a href="'+category+'.html">View all</a></div><div id="displaying">Displaying <span>1-4</span> of '+jQuery("channel>item", xml).length+'</div>');		
	})		

}

function renderThumbnailPage(jQuery, category) {
		jQuery.get(category+".xml",function(xml){
			//display page description
			jQuery('div#col2 #category-description').html(jQuery('channel>description',xml).text());
			
			//display thumbnails
			var text = jQuery("channel>item",xml).each(
				function(idx){
					var maskType='png';
					
					if (jQuery.browser.msie &&  jQuery.browser.version < 7) {
						maskType='gif';
					}

					if (idx%9==0 && idx!=0) {
						var panelNum=jQuery('div.panel').length+1;
						jQuery('div#slider ul.navigation').append('<li><a href="#panel'+panelNum+'">&nbsp;</a></li>');
						jQuery('div.scrollContainer').append('<div class="panel" id="panel'+panelNum+'"></div>');
					}
					
					jQuery('div.panel:last').append('<div class="large-thumb">' +
						'<div class="thumb"><img src="' +imagePath+'/thumbnails/'+category+'/'+
						getCiscoVideoID(this).replace('.flv','') +'/154x67.jpg'+
						'"></div>' +
						'<div class="thumb-caption thumb'+idx+'title">' +
						jQuery('title:first', this).text() +
						'</div>' +
						'<a href="videoplayer.html?videoid=' +
						getCiscoVideoID(this).replace('.flv','') +
						'&category='+category+'"><img src="' +
						imagePath +
						'/thumb_frame.'+maskType+'" class="clipping-mask" id="thumb'+idx+'" border="0"></a>' +
						'</div>');

				});
				//this try catch is a hack to suppress the "'undefined' is null or not an object" problem in IE7
				try { 
					jQuery(document).ready(initCategorySlider());	
					jQuery(document).ready(jQuery('ul.navigation a:first').click());
				} catch (e) {}
				jQuery('.clipping-mask').hover(function(){
					var thumbId='.'+jQuery(this).attr('id')+'title';
					jQuery(thumbId).css('color','#fff');
					jQuery(thumbId).css('background','#4f6e7e url('+imagePath+'/thumb_caption_bg.gif) no-repeat');
				},function() {
					var thumbId='.'+jQuery(this).attr('id')+'title';
					jQuery(thumbId).css('color','#3F5F72');
					jQuery(thumbId).css('background','#e1e1e1');
				})
			});	
	
}

function getCiscoVideoID(xmlObj) {
	
	var url=getMediaContent(xmlObj).attr('url').split('/');
	var flv=url[url.length-1];
	return flv;
}

function getCiscoVideoPath(xmlObj) {
	
	var fileId=getCiscoVideoID(xmlObj);
	var path=getMediaContent(xmlObj).attr('url').substr(0,(getMediaContent(xmlObj).attr('url').length)-(fileId.length+1));
	return path;
}

function getUrlVars() {
	var vars = [], hash;
	var hashes = location.href.slice(location.href.indexOf('?') + 1).split('&');
	 
	for(var i = 0; i < hashes.length; i++) {
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
		}
	
	return vars;
}

function getVideo() {
	var key=getUrlVars();

	if (!key['videoid'])
		return 0;
	else
		return key['videoid'];
}

function showVideo(category, videoId) {
	jQuery.get(category+".xml",function(xml){
		var text = jQuery("channel>item", xml).each(function(idx){
			if (getCiscoVideoID(this).replace('.flv','') == videoId) {
				jQuery('#jwFLVplayer').remove();
				renderDartTag(this);
				renderVideoPlayer(this, "video");
				jQuery('div#catgory-description').html('<h3>'+jQuery("title:first", this).text()+'</h3>');
				jQuery('div#catgory-description').append('<p>'+jQuery("description:first", this).text()+'</p>');
				jQuery('div#related-links').html('<h3>Related Links</h3>');
				var related = jQuery("related>item", this).each(function(idx){
					jQuery('#related-links').append('<a href="'+jQuery('link',this).text()+'" target="_blank">'+jQuery('title',this).text()+'</a>')
					});				
				
			}
		});
	});
	return false
}

function renderVideoPlayer(xmlObj, divId) {
	var width=379;
	var height=252;
	var autostart='true';
	var key=getUrlVars();
	var category=key['category'];	
	var videoImage=getMediaImage(xmlObj).attr('url');
		
	if (divId!='home-video') {
		width=384;
		height=218;		
	}
	
	if (divId=='home-video' && getVideo()==0) {
		autostart='false';
	}
	if (videoImage==undefined)
		videoImage=imagePath+'/thumbnails/'+category+'/'+getCiscoVideoID(xmlObj).replace('.flv', '')+'/384x216.jpg';
	
	var sVid = new SWFObject(cdc_cache_bust("/cdc_content_elements/flash/video-player/mediaplayer.swf"),"jwFLVplayer",width,height,"8");
	sVid.addParam("allowfullscreen","true");
	sVid.addParam("wmode","transparent");
	sVid.addVariable("width",width);
	sVid.addVariable("height",height);
	sVid.addVariable("shownavigation","true");
	sVid.addVariable("autostart",autostart);	
	sVid.addVariable("callback","true");
	sVid.addVariable("file",getCiscoVideoPath(xmlObj));
	sVid.addVariable("id",getCiscoVideoID(xmlObj).replace('.flv', ''));
	sVid.addVariable("image",videoImage);
	sVid.addVariable("pagename","The Human Network");
	sVid.addVariable("videoname",jQuery('title',xmlObj).text());
	sVid.addVariable("countrycode","US");
	sVid.addVariable("bufferlength",1);
	sVid.write(divId);
}

//help jquery retrieve <media:image> element based on browser type
function getMediaImage(obj) {
	if (jQuery('media\\:image', obj).length==1) {
		return jQuery('media\\:image', obj);
	}
	else {
		return jQuery(obj).find('image');
	}
}	

//help jquery retrieve <media:content> element based on browser type
function getMediaContent(obj) {
	if (jQuery('media\\:content', obj).length==1) {
		return jQuery('media\\:content', obj);
	}
	else {
		return jQuery(obj).find('content');
	}
}	

//help jquery retrieve <media:thumbnail> element based on browser type	
function getMediaThumbnail(obj) {
	if (jQuery('media\\:thumbnail', obj).length==1) {
		return jQuery('media\\:thumbnail', obj);
	}
	else {
		return jQuery(obj).find('thumbnail');
	}
}	

function initCategorySlider() {
		var jQuerypanels = jQuery('#slider .scrollContainer > div');
		var jQuerycontainer = jQuery('#slider .scrollContainer');
		
		// if false, we'll float all the panels left and fix the width 
		// of the container
		var horizontal = true;
		
		// float the panels left if we're going horizontal
		if (horizontal) {
		  jQuerypanels.css({
		    'float' : 'left',
		    'position' : 'relative' // IE fix to ensure overflow is hidden
		  });
		  
		  // calculate a new width for the container (so it holds all panels)
		  jQuerycontainer.css('width', jQuerypanels[0].offsetWidth * jQuerypanels.length);
		}

		// collect the scroll object, at the same time apply the hidden overflow
		// to remove the default scrollbars that will appear
		var jQueryscroll = jQuery('#slider .scroll').css('overflow', 'hidden');
		
		// apply our left + right buttons
		if (jQuery('.panel').length > 1) {
			//if (jQuery('body').attr('id') != 'human-network-videoplayer') {
			if (jQuery('div#content-container').attr('class') != 'human-network-videoplayer') {
				jQueryscroll.after('<img src="' + imagePath + '/nav-previous.gif" border="0" class="scrollButtons left"><img src="' + imagePath + '/nav-viewall.gif" border="0" class="scrollButtons viewall"><img src="' + imagePath + '/nav-next.gif" border="0" class="scrollButtons right">');
			}
			else {
				jQueryscroll.after('<img src="' + imagePath + '/arrow_right.gif" border="0" class="scrollButtons right">');
				jQueryscroll.before('<img src="' + imagePath + '/arrow_left.gif" border="0" class="scrollButtons left">');
			}
		}
		else {
			jQuery('div#slider ul.navigation').html('');
		}
		
		// handle nav selection
		function selectNav() {
		  jQuery(this)
		    .parents('ul:first')
		      .find('a')
		        .removeClass('selected')
		      .end()
		    .end()
		    .addClass('selected');
		}
		
		jQuery('img.viewall').bind("click", function() {
			jQuery('ul.navigation a:first').click();
			jQuerypanels.css('float','none');
			jQuery('#slider .scroll').css('height','auto');
			jQuery('#slider').css('height','auto');
			jQuery('#content-container').css('height','auto');
			jQuery('ul.navigation').css('display', 'none');
			jQuery('img.scrollButtons').css('display', 'none');
			if (jQuery.browser.msie &&  jQuery.browser.version < 7) {
				jQuerypanels.css('padding',0);	
			}
			});
		jQuery('#slider .navigation').find('a').click(selectNav);
		
		// go find the navigation link that has this target and select the nav
		function trigger(data) {
		  var el = jQuery('#slider .navigation').find('a[href$="' + data.id + '"]').get(0);
		  selectNav.call(el);
		  var set=(data.id.replace('panel','')*4-4)+1;
		  jQuery('#displaying>span').html(set+'-'+((set+jQuery('#'+data.id+' .medium-thumb').length)-1));
		}
		
		if (window.location.hash) {
		  trigger({ id : window.location.hash.substr(1) });
		} else {
		  jQuery('ul.navigation a:first').click();
		}
		
		var offset = parseInt((horizontal ? 
		  jQuerycontainer.css('paddingTop') : 
		  jQuerycontainer.css('paddingLeft')) 
		  || 0) * -1;
		
		
		var scrollOptions = {
		  target: jQueryscroll, // the element that has the overflow
		  
		  // can be a selector which will be relative to the target
		  items: jQuerypanels,
		  
		  navigation: '.navigation a',
		  
		  // selectors are NOT relative to document, i.e. make sure they're unique
		  prev: 'img.left', 
		  next: 'img.right',
		  
		  // allow the scroll effect to run both directions
		  axis: 'xy',
		  
		  onAfter: trigger, // our final callback
		  
		  offset: offset,
		  
		  cycle: false,
		  
		  // duration of the sliding effect
		  duration: 500,
		  
		  // easing - can be used with the easing plugin: 
		  // http://gsgd.co.uk/sandbox/jquery/easing/
		  easing: 'swing'
		};
		
		// apply serialScroll to the slider - we chose this plugin because it 
		// supports// the indexed next and previous scroll along with hooking 
		// in to our navigation.
		jQuery('#slider').serialScroll(scrollOptions);
		
		// now apply localScroll to hook any other arbitrary links to trigger 
		// the effect
		jQuery.localScroll(scrollOptions);
		
		// finally, if the URL has a hash, move the slider in to position, 
		// setting the duration to 1 because I don't want it to scroll in the
		// very first page load.  We don't always need this, but it ensures
		// the positioning is absolutely spot on when the pages loads.
		scrollOptions.duration = 1;
		jQuery.localScroll.hash(scrollOptions);	
}
