if($.browser.mozilla||$.browser.opera ){document.removeEventListener("DOMContentLoaded",$.ready,false);document.addEventListener("DOMContentLoaded",function(){$.ready()},false)}
if (!console) {
	var console = {
		log: function (){}
	}
}
jQuery.event.remove( window, "load", jQuery.ready );
jQuery.event.add( window, "load", function(){ jQuery.ready(); } );
jQuery.extend({
	includeStates:{},
	include:function(url,callback,dependency){
		if ( typeof callback!='function'&&!dependency){
			dependency = callback;
			callback = null;
		}
		url = url.replace('\n', '');
		jQuery.includeStates[url] = false;
		var script = document.createElement('script');
		script.type = 'text/javascript';
		script.onload = function () {
			jQuery.includeStates[url] = true;
			if ( callback )
				callback.call(script);
		};
		script.onreadystatechange = function () {
			if ( this.readyState != "complete" && this.readyState != "loaded" ) return;
			jQuery.includeStates[url] = true;
			if ( callback )
				callback.call(script);
		};
		script.src = url;
		if ( dependency ) {
			if ( dependency.constructor != Array )
				dependency = [dependency];
			setTimeout(function(){
				var valid = true;
				$.each(dependency, function(k, v){
					if (! v() ) {
						valid = false;
						return false;
					}
				})
				if ( valid )
					document.getElementsByTagName('head')[0].appendChild(script);
				else
					setTimeout(arguments.callee, 10);
			}, 10);
		}
		else
			document.getElementsByTagName('head')[0].appendChild(script);
		return function(){
			return jQuery.includeStates[url];
		}
	},
	readyOld: jQuery.ready,
	ready: function () {
		if (jQuery.isReady) return;
		imReady = true;
		$.each(jQuery.includeStates, function(url, state) {
			if (! state)
				return imReady = false;
		});
		if (imReady) {
			jQuery.readyOld.apply(jQuery, arguments);
		} else {
			setTimeout(arguments.callee, 10);
		}
	},
	videoThumbOver: function () {
		$('.video-thumb').mouseenter (
			function(e) {
				var t = this
				var $t = $(this)
				//$('#debug').html($('#debug').html() + '<br />' + $t.attr('videoName'))
				var el = $('#video-thumb-play')
				el.unbind('click') 
				el.click(function(event) {
					playVideo(event, $t.attr('videoName'), $t.attr('videoId'))
				})
				var thisOff = $t.offset()
				el.css('top', thisOff.top)
				el.css('left', thisOff.left)
				el.fadeIn(400)
			}
		)
	},
	ceRollover: function() {
		this.src = this.src.replace("_off","_on");
	},
	ceRollout: function() {
		this.src = this.src.replace("_on","_off");
	}

	
});
///// include js files ////////////
$.include('js/coin-slider.js');
$.include('js/superfish.js');
$.include('js/tag-cloud.js');
$.include('js/jquery.quicksand.1.2.2.js');
$.include('json/ceData.js');

if (typeof JSON === 'undefined') {
	$.include('js/json2.js');
}

$(document).ready(function() {
	var that = this
	,	ting = new buzz.sound("sounds/ting", { formats: ['ogg', 'mp3'] } )
	,	shhh = new buzz.sound("sounds/shhh", { formats: ['ogg', 'mp3'] } )

	// set up the dynamic data
	if (ceData) {
	
		// set up the tag cloud
		var a2 = [], aStatic = [], t
		a2.push('<ul>')
		for (var i=0; i<ceData.tags.length; ++i) {
			a2.push('<li><div>' + ceData.tags[i].name + '</div></li>')
			aStatic.push('<a onclick="resortVideos(\'' + ceData.tags[i].name + '\')">[' + ceData.tags[i].name.replace(/ /g, '&nbsp;') + ']</a> ')
		}
		a2.push('</ul>')
		$('#tag-cloud').html(a2.join(''))
		$('#tag-cloud-static').html(aStatic.join(''))		
	
		// set up the videos
		var a = [], v
		a.push('<ul id="vidSource" class="shuffler">')
		for (var i=0; i<ceData.videos.length; ++i) {
			renderVideo(ceData.videos[i], a)
		}
		a.push('</ul>')
		$('#shuffler').html(a.join(''))
		$.videoThumbOver()
	}
	
	
	// coin slider
	if ($("#coin-slider").length) {
		$('#coin-slider').coinslider({
			width: 934, // width of slider panel
			height: 348, // height of slider panel
			links: true,
			titleSpeed: 500
		});
	}	
	if ($("#tag-cloud").length) {
		$('#tag-cloud').tagCloud({
			height: 150,
			width: 250,
			xOffset: 110,
			zSpread: 1,
			initialStepping: 1
		});
	}

	$('#video-thumb-play').mouseleave (
		function(e) {
			$(this).hide()
		}
	)

	
	//superfish menu init
	jQuery('ul.sf-menu').superfish();				


	$("#ceLinkButton img").hover($.ceRollover, $.ceRollout)
	$("#chat_submit").hover($.ceRollover, $.ceRollout).click(function() {
		sendChat()
	})
	
	var soc = $.fn.ceSocket(ceSocketUrl + '?cePid=' + cePid)
	//var soc = $.fn.ceSocket()
	
	soc.on('outgoing', function (data) {
		if (!that.chat_tab_is_open) {
			openChatTab(function () {
				//printChatMessage(data)
				window.setTimeout(function () {printChatMessage(data)}, 500)
			})
		} else {
			printChatMessage(data)
		}
	});

	soc.on('incomming', function (data) {
		if (!that.chat_tab_is_open) {
			openChatTab(function () {
				//printChatMessage(data)
				window.setTimeout(function () {printChatMessage(data, 'me')}, 500)
			})
		} else {
			printChatMessage(data, 'me')
		}
	});

	var printChatMessage = function (data, who) {
		var $ct = $('#chat_text')
		if (who == 'me') {
			$ct.append('<br /><span class="me_text">(me): ' + data.text + '</span>')
		} else {
			$ct.append('<br /><span class="ce_text">(craft-e): ' + data.text + '</span>')
		}
		$ct.scrollTop($ct.scrollTop() + 100)
		ting.play()
	}
	
	soc.on('enableChat', function (enabled, callback) {
		console.log('enableChat: ' + enabled)
		ceIsChatEnabled = enabled
		enableChat()
	})
	
	var enableChat = function() {
		var $cc = $('#chat_container')
		var l
		if (ceIsChatEnabled) {
			l = -265
		} else {
			that.chat_tab_is_open = false
			l = -350
		}
		if (l != $cc.css('left')) {
			shhh.play()
			$cc.animate({
				'left': l
			}, function () {
				shhh.stop()
				shhh.load()
			})
		}
	}
	
	// after the page loads, wait a second before enabling chat (if availiable)
	setTimeout(enableChat, 1000)
	
	$('#chat_input').keypress(function(e){
		if(e.which == 13){
			e.preventDefault()
			e.stopPropagation()
			sendChat()
		}
	});	
	
	var sendChat = function () {
		//alert($('#chat_input').val())
		var $ci = $('#chat_input'),
			$ct = $('#chat_text')

		var text = $ci.val()
		soc.emit('incomming', {"text": text, "cookie": document.cookie}, function () {
			console.log('emit receipt: ' + JSON.stringify(arguments))
		})
		$ct.append('<br /><span class="me_text">(me): ' + text + '</span>')
		$ct.scrollTop($ct.scrollTop() + 100)
		$ci.val('')
	}	
	
	
	$("#chat_tab").click(function() {
		if (that.chat_tab_is_open) {
			closeChatTab()
		} else {
			openChatTab()
		}
	
	})
	
	var openChatTab = function (callback) {
		var $cc = $('#chat_container')
		this.tab_original = $cc.css('left')
		shhh.play()
		$cc.animate({
			'left': 0
		}, function () {
			shhh.stop()
			shhh.load()
			if (callback) {
				callback()
			}
			that.chat_tab_is_open = true
		})
	}
	var closeChatTab = function () {
		var $cc = $('#chat_container')
		shhh.play()
		$cc.animate({
			'left': this.tab_original
		}, function() {
			shhh.stop()
			shhh.load()
		})
		that.chat_tab_is_open = false
	}
});			

function onAfter(curr, next, opts, fwd) {
	//get the height of the current slide
	var $ht = $(this).height();
	//set the container's height to that of the current slide
	$(this).parent().animate({height: $ht});
};			

$(window).load(function(){
});

var resortVideos = function(tag) {
	//alert('starting')
	if (ceData.videos) {

		$('#shuffler-title').html(tag)
		for (var i=0; i < ceData.tags.length; ++i) {
			if (ceData.tags[i].name == tag) {
				$('#shuffler-desc').html(ceData.tags[i].desc + '<br /><br />')
			}
		}

		var a = [], v, t
		a.push('<ul id="vidDestination" class="shuffler">')
		for (var i=0; i<ceData.videos.length; ++i) {
			v = ceData.videos[i]
			if (v.tags[tag]) {
				renderVideo(v, a, tag)
			}
		}
		a.push('</ul>')
		$('#shuffler-hidden').html(a.join(''))
		$("#vidSource").quicksand($("#vidDestination > li"), 
		  {
		    duration: 1000
		  }, function() { // callback function
		  	$.videoThumbOver()
		  }
		);
	}
}

var renderVideo = function (v, a, tag) {
	var id = v.name.replace(/ /g, '_')
	a.push('<li data-id="' + id + '">')
	a.push('<img id="video-thumb-' + id + '" src="' + v.src + '" videoName="' + v.name + '" videoId="' + v.videoId + '" class="video-thumb" /><br />')
	a.push('<div class="video-thumb-text"><strong>' + v.name + '</strong><br />')
	if (tag) {
		a.push(v.tags[tag])
	}
	a.push('</div></li>')
}

var playVideo = function (e, videoName, videoId) {
	//alert(tag)
	var available = {
		  "agent submission": true
		, "get your energy back": true
		, "agent review": true
		, "learner return": true
		, "funding forecast": true
		, "care home finder": true
	}
	if (!available[videoName]) {
		var aMsg = ['Unfortunately this video is not available yet (this site is still being developed).\n\The available videos are:\n\n']
		for (var key in available) {
			aMsg.push(key + '\n')
		}
		alert(aMsg.join(''))
		return
	}


	var id = 'video-thumb-' + videoName.replace(/ /g, '_')
	var a = [], $he = $('#' + id), pos = $he.offset(), duration = 500, $body = $('body')
	a.push('<div id="click-trap" style="height:' + $(document).height() + 'px; width:' + $(document).width() + 'px;left:0px;top:0px;position:absolute; z-index: 900; opacity:.50; filter: alpha(opacity=50); background-color: #ccc;"></div>')
	a.push('<div id="vid-transition-container-div" style="height:' + $he.height() + 'px; width:' + $he.width() + 'px;left:' + pos.left + 'px;top:' + pos.top + 'px;">')
	a.push('  <div style="height: 100%; width: 100%"; border: 1px solid #009be3>')
	a.push('    <img id="vid-transition-img" src="' + $he.attr('src') + '" />')
//	a.push('    <div id="vid-transition-controls" style="height: 2px; overflow:hidden">')
//	a.push('      <img src="images/vPlayerControls.jpg" style="width: 100%; height: 100%;" />')
//	a.push('    </div>')
	a.push('</div></div>')
	$('#scratch').html(a.join(''))
	
	// move and expand the video container
	var wWidth = document.documentElement.clientWidth
	var wHeight = document.documentElement.clientHeight
	var vidW = 640
	var vidH = 360
	var targetW = vidW + 15
	var targetH = vidH + 38
	var scrolled = $(window).scrollTop()
	var targetTop = scrolled + (wHeight - targetH) / 2
	var targetLeft = (wWidth - targetW) / 2
	
	$('#vid-transition-container-div').animate({
			top: targetTop,
			left: targetLeft,
			height: targetH,
			width: targetW
		}, duration, function () {
			var a = []

			a.push('<table cellpadding="0" cellspacing="0">')
			a.push(' <tr><td class="pop-all pop-top pop-left pop-tl"><img src="images/1x1.png" width="1px" height="1px" /></td>')
			a.push('   <td class="pop-all pop-top pop-ttl"><img src="images/video-icon.png" width="30px" height="28px" />&nbsp;<span class="pop-title">' + videoName + '</span></td>')
			a.push('   <td class="pop-all pop-top pop-ttr"><img id="pop-close" src="images/skins/w7/pop-close_off.png"/></td>')
			a.push('   <td class="pop-all pop-top pop-right pop-tr"><img src="images/1x1.png" width="1px" height="1px" /></td></tr>')
			a.push(' <tr><td class="pop-all pop-left pop-l"><img src="images/1x1.png" width="1px" height="1px" /></td><td colspan="2"class="pop-all pop-c">')

			a.push(' <iframe src="http://player.vimeo.com/video/' + videoId + '?title=' + videoName + '&amp;byline=0&amp;portrait=0&amp;autoplay=1" width="' + vidW +  '" height="' + vidH +  '" frameborder="0"></iframe>')	
		  //a.push(' <iframe src="http://player.vimeo.com/video/26769802?title=0&amp;byline=0&amp;portrait=0" width="400" height="300" frameborder="0"></iframe><p><a href="http://vimeo.com/26769802">Untitled</a> from <a href="http://vimeo.com/user7863557">craft-e com</a> on <a href="http://vimeo.com">Vimeo</a>.</p>
			a.push(' </td><td class="pop-all pop-right pop-r"><img src="images/1x1.png" width="1px" height="1px" /></td></tr>')
			a.push(' <tr><td class="pop-all pop-bottom pop-left pop-bl"><img src="images/1x1.png" width="1px" height="1px" /></td><td colspan="2" class="pop-all pop-bottom pop-b"><img src="images/1x1.png" width="1px" height="1px" /></td><td class="pop-all pop-bottom pop-right pop-br"><img src="images/1x1.png" width="1px" height="1px" /></td></tr>')
			a.push('</table>')
		
			$('#vid-transition-container-div').html(a.join(''))
			
//			$("#jquery_jplayer_1").jPlayer({
//				ready: function () {
//					$(this).jPlayer("setMedia", {  // video paths need to be relative to where the swfPath for flash to work.
//						m4v: "videos/" + tag + ".mp4",
//						ogv: "videos/" + tag + ".ogg",
//						poster: "videos/" + tag + ".jpg"
//						//m4v: "videos/" + 'learner return' + ".mp4",
//						//ogv: "videos/" + 'learner return' + ".ogg",
//						//poster: "videos/" + 'learner return' + ".jpg"
//					});
//				},
//				ended: function (event) {
//					$(this).jPlayer("play");
//				},
//				swfPath: "",
//				supplied: "m4v, ogv"
//			});
			
			$("#pop-close").hover($.ceRollover, $.ceRollout).click(function(){
				$('#scratch').html('')
			})
			
		}
	)
	$('#vid-transition-img').animate({
			height: 360,
			width: 640
		}, duration
	)
	
	$('#vid-transition-controls').animate({
			height: 93,
			width: 640
		}, duration
	)
	


}
