var $vidW = 704
var $vidH = 392
var $swfFile = 'siteplayer.swf'
var $swfDivId = 'swf'
var $videoTagId = 'vplayer'
var $useSwfObject = true
var $currentVideo
var $prevVideo
var $nextVideo

var HandleVideo = {

	setupVideo : function (department, video_id){
	
		$prevVideo = null
		$nextVideo = null
		$currentVideo = null
		
		var oggExists = false
		var mp4Exists = true
		
		if (department == 'showreel'){
		
			$currentVideo = HandleThumbs.create_ppc_showreel()
			consolelog(' showreel video needed  ' + department)
		}else{
			var departments = $xmlprojects[department]
			
			for ($x in departments)
			{
				var $sections = departments[$x];
				var $sectionsLength = Object.size($sections) //-->prototype count function as you cant get object length in JS
				for ($y in $sections)
				{
					var $video = $sections[$y];
					
					if ($video['id'] == video_id) {
						$currentVideo = $video
						var $nextNum = parseInt($y) + 1
						var $prevNum = $y - 1
						
						if ($prevNum > 0) {
							//$prevNum = $sectionsLength
							$prevVideo = $sections[$prevNum]
						}
						
						if ($prevNum < $sectionsLength){
							//$nextNum = 1
							$nextVideo = $sections[$nextNum]
						}
						
						//consolelog('$currentVideo index[' + $y + '] total[' + $sectionsLength + '] nextIndex[' + $nextNum + '] prevIndex[' + $prevNum + ']')
						break
					}
				}
			}
			openAndHighlightMenu(department, HandleVideo.xmlname_to_subpage($currentVideo['menu_name']))
		}
		
		if (!$currentVideo) {
			consolelog('WARNING!!!!!!!!!!! no video found!! ' + ' department[' + department + ']  video_id[' + video_id + ']')
			return
		}else{
			//consolelog('$currentVideo == ' + $currentVideo + ' department[' + department + ']  video_id[' + video_id + ']')
		}
		
		HandleVideo.updateVideoInfo()
		//HandleVideo.updatePrevNextInfo()//--not needed at the mo
		
		//---ADDING FLASH
		var videosupport = HandleVideo.detectVideoSupport();
		if (!oggExists && videosupport.ogg && !videosupport.mp4) HandleVideo.replaceVideoWithObject() //FOR FIREFOX
		if (!videosupport.ogg && !videosupport.mp4) HandleVideo.replaceVideoWithObject() //FOR IE
		if (videosupport.mp4) $('#videoArea').html(HandleVideo.createVideoTag())
		
		//---EVENTS
		$('#' + $videoTagId).bind("ended", function(evt){
			//can use: play, playing, ended, pause, progress
			//HandleVideo.closeVideo()
			$('#' + $videoTagId).trigger('play')
			$('#' + $videoTagId).trigger('pause')
			//alert('video ended play pause')
		});
	},
	
	showVideoPlayer : function ()
	{
		consolelog('showVideoPlayer called!')
		
		$("#mainpages").fadeIn(0)
		$("#thumbs").fadeOut(0)
		
		changeContentHeight()
		
		//var w = $(".hpages_wrapper").css('width')
		//var h = $(".hpages_wrapper").css('height')
		//$(".hpages_wrapper").css('width', '0')
		//$(".hpages_wrapper").css('height', '0')
		//$(".videoAreaWrapper").css('display', 'none')
		//$("#video_closebutton").css('display', 'visible')
		//$('.hpages_wrapper').delay(500).animate({width: w, height: h}); //width: 712px;//height: 524px;
		//$(".videoAreaWrapper").delay(1000).fadeIn('slow');
		
		HandleVideo.setupVideo($currentpage, $currentsubpage)
		
		$("#videopage").delay(100).fadeIn('slow', function()
		{
			HandleVideo.playVideo()
		})
	},
	
	createVideoTag : function()
	{
		var videoTag = '';
		videoTag += '<video id="' + $videoTagId + '" width="' + $vidW + '" height="' + $vidH + '" controls preload poster="' + $currentVideo['img_name'] + '">'
		videoTag += '<source type="video/mp4" src="' + $currentVideo['file_name'] + '" />'
		videoTag += '<p>Your user agent does not support the HTML5 Video element.</p>'
		videoTag += '</video>'
		return videoTag
	},
	
	createVideoObjectFallBack : function ()
	{
		var objectTag = '';
		objectTag += '<object id="vidswf" width="' + $vidW + '" height="' + $vidH + '" type="application/x-shockwave-flash" data="' + $swfFile + '">'
		objectTag += '<param name="movie" value="' + $swfFile + '" />'
		objectTag += '<param id="vidswf"/>'
		objectTag += '<param name="flashvars" value="img=' + $currentVideo['img_name'] + '&amp;file=' + $currentVideo['file_name'] + '" />'
		objectTag += '</object>'
		return objectTag
	},
	
	createSwfObjectFallBack : function ()
	{
		var newdiv = document.createElement( $swfDivId );
		newdiv.setAttribute('id', $swfDivId);
		$('#videoArea').html(newdiv);
		
		var params = {
			allowfullscreen: "true", 
			allowscriptaccess: "always"
		};
		
		var flashvars = {
			file: $currentVideo['file_name'],
			img: $currentVideo['img_name']
		};
		
		swfobject.embedSWF($swfFile, $swfDivId, $vidW, $vidH, "9", "expressInstall.swf", flashvars, params);
	},
	
	detectVideoSupport : function ()
	{
		var detect = document.createElement('video') || false;
		this.html5 = detect && typeof detect.canPlayType !== "undefined";
		this.mp4 = this.html5 && (detect.canPlayType("video/mp4") === "maybe" || detect.canPlayType("video/mp4") === "probably");
		this.ogg = this.html5 && (detect.canPlayType("video/ogg") === "maybe" || detect.canPlayType("video/ogg") === "probably");
		return this;
	},
	
	replaceVideoWithObject : function ()
	{
		var flashHtml
		
		if (!$useSwfObject){
			flashHtml = HandleVideo.createVideoObjectFallBack()
			$('#videoArea').html(flashHtml)
		}else{
			flashHtml = HandleVideo.createSwfObjectFallBack()
			$('#videoArea').html(flashHtml)
		}
	},
	
	playVideo : function ()
	{
		if ($('#' + $videoTagId))
		{
			setTimeout(function(){$('#' + $videoTagId).trigger('play')}, 500)
			//$('#' + videoTagId).attr("muted", true);
		}else{
			//tell flash to play video , if needed
		}
	},
	
	closeVideo : function ()
	{
		//var bname = navigator.appName;
		
		//if (bname == "Microsoft Internet Explorer") {
			$('#videoArea').html('');
		//}
		
		if ($('#' + $videoTagId)){
			$('#' + $videoTagId).trigger('stop')
		}else{
			//tell flash to play video , if needed
		}
		
		
	},
	
	updateVideoInfo : function()
	{
	
		//this numbers need to be based on the width of the div ---now 94% was 86%
		var safecount =  90//84
		var titlelimit =  36
		var projectlimit =  34
		var clientlimit =  26

		if ($currentVideo['link']) {
			safecount =  80//76
			titlelimit =  32
			projectlimit =  24
			clientlimit =  22
		}
		
		//consolelog('updateVideoInfo called -- safecount=' + safecount)
		
		var title = $currentVideo['title']
		var project = $currentVideo['project']
		var client = $currentVideo['client']
		
		if ( (title.length + project.length + client.length) > safecount) {
			//consolelog('WARNING!! too many letters to handle!! ' + (title.length + project.length + client.length))
			var title = truncate($currentVideo['title'], titlelimit)

			var project = truncate($currentVideo['project'], projectlimit)
			var client = truncate($currentVideo['client'], clientlimit)
		}
		
		$('.videoTitle').html(title)
		
		if(project && project != '') {
			$('.videoProject').append(" ").html(' - ' + project)
		}else{
			$('.videoProject').html('')
		}
		
		if(client && client != '') {
			$('.videoClient').html('Client: ' + client)
		}else{
			$('.videoClient').html('')
		}
		
		var linkhtml = ''
		
		if($currentVideo['link']) {
			var linkname = $xmltext['open_link']['copy']
			if( $currentVideo['linkname'] ) linkname = $currentVideo['linkname']
			linkhtml += '<a href="http://' + $currentVideo['link'] + '" target="_blank" style="text-decoration: none;">' + linkname + '</a>'
			
			if( $currentVideo['link2'] ) { 
				var link2name = $xmltext['open_link']['copy']
				if( $currentVideo['link2name'] ) link2name = $currentVideo['link2name']
				linkhtml += ' | <a href="http://' + $currentVideo['link2'] + '" target="_blank" style="text-decoration: none;">' + link2name + '</a>'
			}
			
			if( $currentVideo['link3'] ) { 
				var link3name = $xmltext['open_link']['copy']
				if( $currentVideo['link3name'] ) link3name = $currentVideo['link3name']
				linkhtml += ' | <a href="http://' + $currentVideo['link3'] + '" target="_blank" style="text-decoration: none;">' + link3name + '</a>'
			}
			
		}
		
		$('.videoLink').html( linkhtml )
		
		//var $short_par = truncate($currentVideo['par'], 100)
		$('.videoPar').html($currentVideo['par'])
		
		//consolelog('$currentVideo[par].length == ' + $currentVideo['par'].length)
		
		if ($currentVideo['par'].length > 100)
		{
			$("#videoInfoArea").delay(0).animate({'height': 0 + 'px'}, "slow", function(){})
			$(".hpages_videowrapper").delay(0).animate({'height': 410 + 'px'}, "slow", function(){})
			
			//$('.readmore_button').animate('fast')
			//$('.readmore_button').fadeIn('fast')
		}else{
			$("#videoInfoArea").delay(100).animate({'height': 42 + 'px'}, "fast", function(){})
			$(".hpages_videowrapper").delay(100).animate({'height': 410 + 'px'}, "fast", function(){})
			//$('.readmore_button').fadeOut('fast')
		}
	},
	
	updatePrevNextInfo : function()
	{
		var $prevdiv = $('.videoAreaWrapper').find('.prevText')
		
		if ($prevVideo){
			$prevdiv.find('a').html('&lt;&lt; ' + truncate($prevVideo['title'], 30))
			$prevdiv.find('a').attr('name', $prevVideo['department'] + '/' + $prevVideo['id'] + '/' + $prevVideo['tag_name'])
			$prevdiv.find('a').attr('href', '#/' + $prevVideo['department'] + '/' + $prevVideo['id'] + '/' + $prevVideo['tag_name'])
		}else{
			$prevdiv.find('a').html(' ')
		}
		
		var $nextdiv = $('.videoAreaWrapper').find('.nextText')
		
		if($nextVideo){
			$nextdiv.find('a').html(truncate($nextVideo['title'], 30) + ' &gt;&gt;')
			$nextdiv.find('a').attr('name', $nextVideo['department'] + '/' + $nextVideo['id'] + '/' + $nextVideo['tag_name'])
			$nextdiv.find('a').attr('href', '#/' + $nextVideo['department'] + '/' + $nextVideo['id'] + '/' + $nextVideo['tag_name'])
		}else{
			$nextdiv.find('a').html(' ')
		}
	},
	
	clickReadMore : function (evt)
	{
		var $target = $(evt.currentTarget);
		var $targetText = $target.find('a')
		var $targetPar = $('.videoPar')
		$targetPar.fadeOut(0)
		var $closedHeight = 42
		var $openHeight = 98
		var $text = $xmltext['read_less']['copy']
		var $par = $currentVideo['par']
		if ($("#videoInfoArea").css('height').replace("px", "") > $closedHeight){
			$openHeight = $closedHeight
			$opacity = 1
			$text = $xmltext['read_more']['copy']
			$par = truncate($par, 100)
		}
		$targetPar.delay(100).html($par)
		$targetText.delay(100).html($text)
		$("#videoInfoArea").delay(250).animate({'height': $openHeight + 'px'}, "slow", function(){})
		$targetPar.delay(1000).fadeIn('fast')
	},
	onClickClose : function (evt)
	{
		if ($currentVideo['department'] == 'showreel'){
			window.location.hash = ''
		}else{
			window.location.hash = "#/" + $currentVideo['department'] + "/" + HandleVideo.xmlname_to_subpage($currentVideo['menu_name']) + "/"
		}
	},
	onOverClose : function (evt){
		$('#video_closebutton').css("background-position", "top")
	},
	onOutClose : function (evt){
		$('#video_closebutton').css("background-position", "bottom")
	},
	
	
	
	xmlname_to_subpage : function (str){
		var newstr = str
		//XML node names (in case these a difference between hash sub page)
		switch(str){
			case 'dateone':
				newstr = '2012'
			break;
			case 'datetwo':
				newstr = '2011'
			break;
			case 'datethree':
				newstr = '2010'
			break;
		}
		//newstr = newstr.replace('-','')
		return newstr
	}
}
