function supports_canvas() {
	  return !!document.createElement('canvas').getContext;
}


/*----------------- LOGIN FORM FUNCTIONS -----------------*/
function login( url, user, pswd, successHandler, errorHandler ){
	
	$.ajax({
		   type: "POST",
		   url: url,
		   data: "u="+user+"&p="+pswd,
		   success: function(msg){
				if( msg === "" ){
					errorHandler();
				}
				else
					successHandler(msg);
			}
		 });
}

var formtoggle;
function initLoginForm( url ){
	
	$("#login-tab").click( function(){
		toggleLoginForm(!formtoggle);
	});
	
	$("#login-form-submit").click( function(){
		$("#error").css('color', '#FFFFFF');
		$("#error").html( "LOGGING IN...");
		
		login( url, $("#username", "#login-form-container").val(), 
				$("#passwd", "#login-form-container").val(),
				function( ret ){
					var url = unescape(ret);
					document.location.href = url;
				},
				function( error ){
					$("#error").css('color', '#FF0000');
					$("#error").html( "INCORRECT LOGIN");
				}
				);
	});
}

function toggleLoginForm( bopen ){
	
	if(bopen){
		$("#passwd").val("");
		$("#username").val("");
		$("#login-form-container").stop();
		$("#login-form-container").animate({top:20}, 250, function(){
			$("#login-form-container").css('z-index', '100');
		});
		$("#login-tab").addClass("login-tab-over");
		$("#error").html("");
		
	}
	else{
		$("#login-form-container").css('z-index', '-1');
		$("#login-form-container").stop();
		$("#login-form-container").animate({top:-120}, 250, null, function(){
			$("#login-tab").removeClass("login-tab-over");
		});
		
	}
	formtoggle = bopen;
}

/*----------------- HERO FUNCTIONS -----------------*/
var heroitems;
var herocnt;
var t;
var timeout = 10000;
var flashvideo;
var imgdir;

function initHero( imagedir, swfplayer, items ){
	herocnt = 0;
	flashvideo = swfplayer;
	heroitems = items;
	imgdir = imagedir;
	
	//init buttons
	buttonHTML = "";
	for( i = 0; i < heroitems.length; i++ )
		buttonHTML += "<a id='btn"+i+"' href='javascript:showHeroItemIndex("+i+");'><img src='"+imgdir+"/"+(i+1)+"-off.gif'></img></a><span class='button-spacer'>&nbsp;</span>";
	
	$("#button-holder", "#panel", "#hero").html(buttonHTML);
	
	showHeroItemIndex(0);
	
}
function showHeroItemIndex( i ){
	var item = heroitems[i];
	
	if( item['is_video'] == 0 )
	{
		var div = $("#media", "#hero");
		var img = new Image();
		$(img).hide();
		$(img).bind("load",function(){ 
			$(this).fadeIn();
			//preload the next one
			var next_img = new Image();
			var next_item = heroitems[(i+1)%heroitems.length];
			$(next_img).hide();
			$(next_img).attr('src',next_item["img_url"]);
			
			//set timer
			clearTimeout( t );
			t = setTimeout( function(){
			herocnt = (i+1)%heroitems.length;
			showHeroItemIndex( herocnt );
					}, timeout );
			
		});
		$(img).attr('src',item["img_url"]);
		div.html($(img));
		
	}else{
		
		var div = $("#media", "#hero");
		var name = item['img_url'].substring(0, item['img_url'].length-4 );
		var html = '<div class="video-js-box vim-css">';
		html += '<video class="video-js vim-css" width="950" height="466" controls="controls" preload="auto" poster="'+item['img_url']+'" >';
		html += '<source src="'+name+'.mp4" type="video/mp4; codecs=\'avc1.42E01E, mp4a.40.2\'" />';
		html += '<source src="'+name+'.ogv" type="video/ogg; codecs=\'theora, vorbis\'" />';
		html += '<source src="'+name+'.webm" type="video/webm; codecs=\'vp8, vorbis\'" />';
		html += '<object id="flash_fallback_1" class="vjs-flash-fallback" width="950" height="466" type="application/x-shockwave-flash"';
		html += 'data="'+flashvideo+'">';
		html += '<param name="movie" value="r" />';
		html += '<param name="allowfullscreen" value="true" />';
		html += '<param name="flashvars" value="config={\'playlist\':[\'' +item['img_url']+ '\', {\'url\': ' +name+'.mp4\',\'autoPlay\':false,\'autoBuffering\':true}]}" />';
		html += '</object>';
		html += '</video></div>';
		div.html(html);
	}
	
	for( var j = 0; j < heroitems.length; j++){
		$("#btn"+j, "#button-holder").hover(
			function(){ $("img", $(this)).attr("src",imgdir+"/"+(parseInt($(this).attr('id').substr(3,1))+1)+"-on.gif") },
			function(){ $("img", $(this)).attr("src",imgdir+"/"+(parseInt($(this).attr('id').substr(3,1))+1)+"-off.gif")}
		);
		$("img", "#btn"+j, "#panel").attr("src",imgdir+"/"+(j+1)+"-off.gif");
	}
	
	$( "#btn"+i, "#panel").unbind('mouseenter mouseleave');
	$("img", "#btn"+i, "#panel").attr("src",imgdir+"/"+(i+1)+"-on.gif");
	
	$("#headline", "#panel").html(item['headline']);
	$("#body", "#panel").html(item['body']);
	$("#comments", "#panel").html(item['comments']);
	$("#read-more", "#panel").attr('href',item['url']);
}

/*----------------- CLOCK FUNCTIONS -----------------*/
function initClocks( flash_clock ){

	//use HTML5 canvas
	if( supports_canvas() ){ 
		clockifyTimeZonez();
		setInterval ( "clockifyTimeZonez()", 1000 );
	} 
	else{ //embed flash clocks
		swfobject.embedSWF(
				flash_clock, "ny_clock", 
				"64", "64",
				"9.0.0", "", 
				{ offset:5 }, {}, {});
		swfobject.embedSWF(
				flash_clock, "sh_clock", 
				"64", "64",
				"9.0.0", "", 
				{ offset:6 }, {}, {});
		swfobject.embedSWF(
				flash_clock, "hk_clock", 
				"64", "64",
				"9.0.0", "", 
				{ offset:6 }, {}, {});
	}
}

function clockifyTimeZonez(){
	drawTime( $("#ny_clock", "#newyork")[0], 8 );
	drawTime( $("#sh_clock", "#shanghai")[0], 9 );
	drawTime( $("#hk_clock", "#hongkong")[0], 9 );
}

function drawTime( canvas, offset ){	
	
	var x,y;
	var cxt = canvas.getContext("2d");
	var dt = new Date();
	var mr = 2*Math.PI/60*dt.getMinutes()+Math.PI/2;
	var hr = 2*Math.PI/12*((dt.getHours()-dt.getTimezoneOffset()+offset)+dt.getMinutes()/60);
	
	clearCanvas( cxt, canvas );
	
	//canvas.width = canvas.width;
	cxt.strokeStyle = "#333333";
	
	x = 16 * Math.cos( hr );
	y = 16 * Math.sin( hr );
	cxt.moveTo( 31, 30 );
	cxt.lineTo( 31+x, 30+y );
	
	x = 25 * Math.cos( mr );
	y = 25 * Math.sin( mr );
	cxt.moveTo( 31, 30 );
	cxt.lineTo( 31-x, 30-y );
	
	cxt.arc(30.5,30.5,1,0,Math.PI*2,true);
	
	cxt.stroke();
}


function clearCanvas(context, canvas) {
	  context.clearRect(0, 0, canvas.width, canvas.height);
	  var w = canvas.width;
	  canvas.width = 1;
	  canvas.width = w;
	}

function showPost( link ){
	location.href = link;
}
