var booth = false;
var Snapped = false;

$( function () {
		booth = new PhotoBooth( $('#booth' ) );

		$('<div id="legal"><p>Disclaimer: The Prepare Yourself website and all associated correspondence has been created for promotional purposes only. The content and materials are not factually accurate and do not reflect actual happenings.</p><p>&copy; Copyright Discovery Communications 2010.</p></div>').appendTo('#content');

	});


function playVideo() {

	var s = '';
	s += '<div id="blocker"></div>';

	s += '<div id="blocker-panel" class="media-player">';
	s += '<div id="blocker-inner">';
	s += '<a href="javascript:void(0);"><span>Close</span></a>';
	s += '<div id="blocker-media-screen"></div>';
	s += '</div>';
	s += '</div>';

 	$('body').prepend(s);

	$('#blocker').css('height', screen.height);

   	$('#blocker').click ( function () {
			unblock();
		});

	$('#blocker-panel a').click ( function () {
			unblock();
		});

	var div = $( '#blocker-panel' );
	div.css("top", ($(window).height() - div.height())/3  + 'px');
	div.css("left", ($(window).width() - div.width())/2  + 'px');

	$('#blocker-media-screen').html('<div id="player-screen-swf"></div>');

	swfobject.embedSWF(
					   "/flash/AjaxPlayer.swf", 
					   "player-screen-swf", 
					   "640", 
					   "424", 
					   "9.0.0", 
					   false, 
					   { 'mediaURL': '/tvc.flv' },
					   { 'wmode': 'window' }
					   );

	return false;


}

function MediaPlayerReceiver ( message, val )
{
	if ( message == 'complete' ) {
		unblock();
	}
}

function MediaPlayerSender(msg, val) {
	if (document.getElementById("player-screen-swf")) { 
		document.getElementById("player-screen-swf").MediaPlayerControl(msg, val);
	}
}

function resizeHandler() {
	var div = $( '#blocker-panel' );
	if ( undefined != div ) {
		div.css("top", ($(window).height() - div.height())/3  + 'px');
		div.css("left", ($(window).width() - div.width())/2  + 'px');
	}
};

var resizeTimer = null;
$(window).bind('resize', function() {
		if (resizeTimer) {
			clearTimeout(resizeTimer);
		}
		resizeTimer = setTimeout(resizeHandler, 100);
	});
 


function unblock() {
	$('#blocker').hide();
	$('#blocker-panel').fadeOut(450, function() {
			$('#blocker-panel').remove();
			$('#blocker').remove();
		});
}


function PhotoBooth( el ) {

	var self = this;
	var e = el;

	var session_id = $('input[name=q]').val();

	var tools = false;
	var composition = false;
	var controls = false;

	// empty headshot to fill
	var mask = false;
	var face = false;

	// user's picture
	var image = false;
	var imageLoaded = false;

	var imageWidthDefault = 368;
	var imageHeightDefault = 448;

	var imageWidth = 368;
	var imageHeight = 448;
	var imageScale = 1.0;
	var imageRotation = 0;
	var imageFlip = false;

	var maskWidth = 0;
	var maskHeight = 0;
	var imagePos = false;

	var nameHint = 'Enter your name';

	var disableMove = false;

	var selectedMask = false;
	var cache = [];
	// overlay for upload and webcam
	var win = false;

	var hardeners = false;
	var selectedCrewman = false;

	var facials = {};

	facials.captain = {
		'eyebrowleft':{'index': 0, 'slug':'eyebrowleft', 'width':116, 'height':64},
		'eyebrowright':{'index': 1, 'slug':'eyebrowright', 'width':116, 'height':64},
		'scar':{'index': 2, 'slug':'scar', 'width':128, 'height':64},

		'nose':{'index': 3, 'slug':'nose', 'width':84, 'height':64},
		'darkeyeleft':{'index': 4, 'slug':'darkeyeleft', 'width':116, 'height':80},
		'darkeyeright':{'index': 5, 'slug':'darkeyeright', 'width':116, 'height':80},

		'showbeard':{'index': 6, 'slug':'showbeard', 'width':168, 'height':90},
		'tash':{'index': 7, 'slug':'tash', 'width':180, 'height':128},
		'fluff':{'index': 8, 'slug':'fluff', 'width':80, 'height':86},

		'sutures':{'index': 9, 'slug':'sutures', 'width':56, 'height':64},
		'lips':{'index': 10, 'slug':'lips', 'width':116, 'height':60},
		'goatee':{'index': 11, 'slug':'goatee', 'width':192, 'height':124}
	};

	facials.deckhand = {
		'eyebrowleft':{'index': 0, 'slug':'eyebrowleft', 'width':116, 'height':64},
		'eyebrowright':{'index': 1, 'slug':'eyebrowright', 'width':108, 'height':64},
		'scar':{'index': 2, 'slug':'scar', 'width':112, 'height':72},

		'scab':{'index': 3, 'slug':'scab', 'width':72, 'height':56},
		'darkeyeleft':{'index': 4, 'slug':'darkeyeleft', 'width':116, 'height':64 },
		'darkeyeright':{'index': 5, 'slug':'darkeyeright', 'width':108, 'height':64},

		'showbeard':{'index': 6, 'slug':'showbeard', 'width':164, 'height':80},
		'tash':{'index': 7, 'slug':'tash', 'width':180, 'height':104},
		'fluff':{'index': 8, 'slug':'fluff', 'width':108, 'height':108},

		'sutures':{'index': 9, 'slug':'sutures', 'width':56, 'height':72},
		'wisp':{'index': 10, 'slug':'wisp', 'width':116, 'height':54},
		'goatee':{'index': 11, 'slug':'goatee', 'width':204, 'height':100}
	};

	facials.greenhorn = {
		'eyebrowleft':{'index': 0, 'slug':'eyebrowleft', 'width':120, 'height':64},
		'eyebrowright':{'index': 1, 'slug':'eyebrowright', 'width':116, 'height':84},
		'scar':{'index': 2, 'slug':'scar', 'width':128, 'height':64},

		'nose':{'index': 3, 'slug':'nose', 'width':72, 'height':64},
		'darkeyeleft':{'index': 4, 'slug':'darkeyeleft', 'width':116, 'height':80},
		'darkeyeright':{'index': 5, 'slug':'darkeyeright', 'width':120, 'height':80},

		'showbeard':{'index': 6, 'slug':'showbeard', 'width':160, 'height':90},
		'tash':{'index': 7, 'slug':'tash', 'width':180, 'height':120},
		'fluff':{'index': 8, 'slug':'fluff', 'width':100, 'height':86},

		'sutures':{'index': 9, 'slug':'sutures', 'width':64, 'height':60},
		'wisp':{'index': 10, 'slug':'wisp', 'width':104, 'height':60},
		'goatee':{'index': 11, 'slug':'goatee', 'width':192, 'height':124}
	};

	var crew = [ "deckhand", "captain", "greenhorn" ];

	// preload
	for ( var i in crew ) {
		var cacheImage = document.createElement('img');
		cacheImage.src = '/images/facials-' + crew[i] + '.png';
		cache.push(cacheImage);
	}

	this.crewSelect = function ( crewman ) {

		mask.css( 'background', 'url(/images/mask-' + crewman + '.png) center no-repeat' );

		$('.facial').remove();

		self.selectedCrewman = crewman;
		var s = '';
		var x = 0;
		for ( var i in facials[crewman] ) {
			var h = facials[crewman][i];
			s += '<li><a href="javascript:;" class="hardener" style="background:url(/images/hard-icons-' + crewman + '.jpg) -' + ( h.index * 48 + 1) + 'px 0 no-repeat;" rel="' + i + '"></a></li>';
		}
		
		$('#hardeners ul').html(s);

		$("#hardeners ul li a").draggable({ 
				revert: 'invalid',
					revertDuration: 250,
					containment: e,
					start: function ( event, ui ) {
					self.disableMove = true;
					$("#tip-harden").remove();
				},
					helper: function(event) {
					var h = facials[crewman][$(event.target).attr('rel')];
					return $('<div id="proxy" rel="' + h.slug + '" class="ui-widget-header hardness"></div>').css({'width':h.width,'height':h.height,'background':'url(/images/facials-' + crewman + '.png) -' + ( h.index * 256 ) + 'px 0 no-repeat'});
				},
				stop: function(event, ui) {
					var h = facials[crewman][$(event.target).attr('rel')];
					// var h = hardeners[$('#proxy').attr('rel')];
					var q = $('#proxy').offset();
					var v = $('#mask').offset();
					var x = q.left - v.left;
					var y = q.top - v.top;
					$('<div class="facial" rel="' + h.slug + '"></div>').css({'width':h.width,'height':h.height,'background':'url(/images/facials-' + crewman + '.png) -' + ( h.index * 256 ) + 'px 0 no-repeat'}).appendTo('#mask').css({'left':x,'top':y});
				}
			});

		$('.facial').live('mouseover', function () {
				$('<a class="facial-remover" href="javascript:;"></a>').appendTo(this);
				$(this).addClass('facial-hover')
			});

		$('.facial').live('mouseout', function () {
				$(this).removeClass('facial-hover')
				$(this).find('.facial-remover').remove();
			});

		$('.facial-remover').live('click', function () {
				$(this).parent().remove();
			});

		$('.facial').live('click', function () {
				$(this).remove();
			});

		$("#hardeners ul li a").css({cursor: 'move'});
		self.selectedMask = crewman;

	}

	this.init = function() {
		// app container
		// var boothdiv = $('#booth');

		$('<a href="#video" id="play-video"><span>Play Video</span></a>').appendTo(e).click( function () {
				playVideo();
				return false;
			});

		// compositing area
		$('<div id="composition" />').appendTo(e); //.dropShadow({left: 0, top: 0, opacity: .75, blur: 4});
		composition = $('#composition');

		// user's face
		$('<div id="face" />').appendTo(composition);
		face = $('#face');

		// overlay of crewmember
		$('<div id="mask"></div>').appendTo(composition);
		mask = $('#mask');

		// tools down side

		$('<div id="tools" />').appendTo(e);
		tools = $('#tools');

	   // $('<h3 rel="upload">Upload Image</h3>').appendTo(tools);

		// image upload / snap
		var s = '<ul id="image-tools">';
		s += '<li><a href="javascript:;" rel="upload-image" class="tools-upload"><span>Upload Image</span></a></li>';
		s += '<li><a href="javascript:;" rel="take-photo" class="tools-webcam"><span>Take Photo</span></a></li>';
		s += '</ul>';

		$(s)
		.appendTo(tools)
		.bind('click', function ( e ) {
				if ( e.target.tagName == 'UL' ) {
					return false;
				}
				if ( e.target.tagName == 'LI' ) {
					var target = $(e.target).child('a:first');
				} else if ( e.target.tagName != 'A' ) {
					var target = $(e.target).parent();
				} else {
					var target = $(e.target);
				}
				var call = target.attr('rel');
				switch ( call ) {
				case 'take-photo' :
					self.snap();
					break;
				case 'upload-image' :
					self.upload();
					break;
				}
				return false;
			});

		// $('<h3 rel="crew">Select Crewman</h3>').appendTo(tools);

		var s = '<div id="crewmen">';
		s += '<ul>';
		for ( var i in crew ) {
			slug = crew[i];
			s += '<li><a href="javascript:;" style="background:url(/images/thumb-' + slug + '.jpg) center no-repeat;" rel="' + slug + '" class="crewmen-select"><span>' + slug + '</span></a></li>';
		}
		s += '</ul></div>';

		$(s).appendTo(tools);

		// currently viewed
		$('#crewmen ul li').hide();
		$('#crewmen ul li:first').show().addClass('current');

		$('#crewmen .crewmen-select').bind ( 'click', function ( e ) { 
				if ( e.target.tagName != 'A' ) {
					var target = $(e.target).parent();
				} else {
					var target = $(e.target);
				}
				var slug = target.attr('rel');
				self.crewSelect( slug );
				// remove the tip here so user click causes removal,
				$("#tip-crew").fadeOut(250, function () { $("#tip-crew").remove(); } );
				return false;
			});

		$('<a href="javascript:;" class="crewmen-select-prev"><span>&larr;</span></a>').appendTo('#crewmen').bind('click', function () {
				var e = $('#crewmen ul li.current').prev();
				if ( e.length == 0 ) {
				e = $('#crewmen ul li:last-child');
				}
				$('#crewmen ul li.current').hide().removeClass('current');
				e.show().addClass('current');
			});

		$('<a href="javascript:;" class="crewmen-select-next"><span>&rarr;</span></a>').appendTo('#crewmen').bind('click', function () {
				var e = $('#crewmen ul li.current').next();
				if ( e.length == 0 ) {
				e = $('#crewmen ul li:first-child');
				}
				$('#crewmen ul li.current').hide().removeClass('current');
				e.show().addClass('current');
			});


		// $('<h3 rel="harden">Harden Your Face</h3>').appendTo(tools);
		
		$('<div id="hardeners-wrap"><div id="hardeners"><ul></ul></div></div>').appendTo(tools);

		self.crewSelect('deckhand');

		$( "#mask" ).droppable({ 
				accept: '.hardener',
					drop: function(event, ui) {
					// ui.draggable.addClass('hard');
				}
			});

		$( "#hardeners" ).droppable({ 
				accept: '.hardener',
					drop: function(event, ui) {
					ui.draggable.removeClass('hard');
				}
			});
		

		// $('<div class="tip" id="tip-upload"><span>Upload an image or use your webcam to take a picture of your face</span></div>').appendTo(composition);
		// $('<div class="tip" id="tip-crew"><span>Click on a Crewman to put your face in. Use the mouse to position your face.</span></div>').appendTo(composition);
		// $('<div class="tip" id="tip-harden"><span>Drag hardness on to your face to make it look like you\'ve spent a month in the North Sea</span></div>').appendTo(composition);

		$('#tools').bind( 'mouseover', function () {
				// if ( ! imageLoaded ) {
				// 	return false;
				// }
				// var tip = $('#tip-' + $(this).attr('rel') );
				// var tip = $('#tip-' + $(this).attr('rel') );
				// if ( ! tip.is('visible') ) {
				// 	tip.fadeIn(250);
				// }
				$('.tip').show();

			});

		$('#tools').bind( 'mouseout', function () {
				$('.tip').hide();
				// if ( ! imageLoaded ) {
				// 	return false;
				// }
				// var tip = $('#tip-' + $(this).attr('rel') );
				// if ( tip.is('visible') ) {
				// 	tip.fadeOut(250);
				// }
			});

		// $(document).bind('keypress', function (event) {
		// 		var key = event.which;

		// 		if ( key == 105 ) {
		// 			self.move('up');
		// 		}

		// 		if ( key == 107 ) {
		// 			self.move('down');
		// 		}

		// 		if ( key == 106 ) {
		// 			self.move('left');
		// 		}

		// 		if ( key == 108 ) {
		// 			self.move('right');
		// 		}

		// 		if ( key == 45 ) {
		// 			self.zoom('dec');
		// 		}

		// 		if ( key == 61 ) {
		// 			self.zoom('inc');
		// 		}

		// 	});


		$('<div id="controls" />').appendTo(e);
		controls = $('#controls');

		// move buttons
		// get rid of old one
		$('#rotate').remove();
		var s ='<ul id="rotate">';
		s += '<li><a href="javascript:;" id="rotate-left" rel="ccw"><span>L</span></a></li>';
		s += '<li><a href="javascript:;" id="rotate-right" rel="cw"><span>R</span></a></li>';
		s += '</ul>';

		$(s)
		.appendTo(controls)
		.bind ( 'click', function ( e ) { 
				if ( e.target.tagName == 'UL' ) {
					return false;
				}
				if ( e.target.tagName == 'LI' ) {
					var target = $(e.target).child('a:first');
				} else if ( e.target.tagName != 'A' ) {
					var target = $(e.target).parent();
				} else {
					var target = $(e.target);
				}
				var dir = target.attr('rel');
				self.rotate(dir);
				return false;
			});

		// move buttons
		// get rid of old one
		$('#move').remove();
		var s ='<ul id="move">';
		s += '<li id="move-up" ><a href="javascript:;" rel="up"><span>&uarr</span></a></li>';
		s += '<li id="move-left"><a href="javascript:;" rel="left"><span>&larr;</span></a></li>';
		s += '<li id="move-right"><a href="javascript:;" rel="right"><span>&rarr;</span></a></li>';
		s += '<li id="move-down"><a href="javascript:;" rel="down"><span>&darr;</span></a></li>';
		s += '</ul>';

		$(s)
		.appendTo(controls)
		.bind ( 'click', function ( e ) { 
				if ( e.target.tagName == 'UL' ) {
					return false;
				}
				if ( e.target.tagName == 'LI' ) {
					var target = $(e.target).child('a:first');
				} else if ( e.target.tagName != 'A' ) {
					var target = $(e.target).parent();
				} else {
					var target = $(e.target);
				}
				var dir = target.attr('rel');
				self.move(dir);
				return false;
			});


		// scale buttons
		$('#scale').remove();
		var s ='<ul id="scale">';
		s += '<li><a href="javascript:;" id="scale-up" rel="dec"><span>-</span></a></li>';
		s += '<li><a href="javascript:;" id="scale-down" rel="inc"><span>+</span></a></li>';
		s += '</ul>';
		$(s)
		.appendTo('#controls')
		.bind ( 'click', function ( e ) { 
				if ( e.target.tagName == 'UL' ) {
					return false;
				}
				if ( e.target.tagName == 'LI' ) {
					var target = $(e.target).child('a:first');
				} else if ( e.target.tagName != 'A' ) {
					var target = $(e.target).parent();
				} else {
					var target = $(e.target);
				}
				var dir = target.attr('rel');
				self.zoom(dir);
				return false;
			});


		// move buttons
		// get rid of old one
		$('#flip').remove();
		var s ='<ul id="flip">';
		s += '<li><a href="javascript:;"><span>&harr;</span></a></li>';
		s += '</ul>';

		$(s)
		.appendTo(controls)
		.bind ( 'click', function ( e ) { 
				if ( e.target.tagName == 'UL' ) {
					return false;
				}
				if ( e.target.tagName == 'LI' ) {
					var target = $(e.target).child('a:first');
				} else if ( e.target.tagName != 'A' ) {
					var target = $(e.target).parent();
				} else {
					var target = $(e.target);
				}
				self.flip();
				return false;
			});

		var s = '<div id="share"><a href="javascript:;"><span>Share</span></a></div>';
		$(s).appendTo(controls).bind('click', function () {
				self.share();
				return false;
			});

		var s = '<div id="name"><input type="text" name="name" value="' + nameHint + '" /></div>';
		$(s).appendTo(mask);
		$('#name input').bind('focus', function () { 
				$(this).removeClass('invalid').select(); 
			});

		tools.hide();
		controls.hide();
		composition.hide();

		var s = '<div id="splash"><div><p>Years of freezing temperatures,<br />raging seas and punishing labour leave <br />scars on the fishermens skin, and separate <br />the veterans from the greenhorns.</p></p>Now you can look as tough as a <br />Deadliest Catch fisherman without<br />braving the elements.</p><p>Prepare to harden yourself up for the all<br />new season of Deadliest Catch and get<br/>closer to the action than ever before.</p><p><a href="javascript:;"><span>Start</span></a></div></div>';
		$(s).appendTo(e).delay(500);
		$('#splash a').bind('click', function () {
				$('<div id="title"><a href="/"></a></div>').appendTo(e).hide().fadeIn(500);
				tools.fadeIn();
				controls.fadeIn();
				composition.fadeIn();
				$('#splash').fadeOut( 500, function() { 
						$('#splash').remove();

					});
			});
	

		$('<div id="sharethis"></div>').appendTo('#booth');
		var s = '';
		s += '<a id="ck_email" class="stbar chicklet" href="javascript:void(0);"><img src="http://w.sharethis.com/chicklets/email.gif" /></a>';
		s += '<a id="ck_facebook" class="stbar chicklet" href="javascript:void(0);"><img src="http://w.sharethis.com/chicklets/facebook.gif" /></a>';
		s += '<a id="ck_twitter" class="stbar chicklet" href="javascript:void(0);"><img src="http://w.sharethis.com/chicklets/twitter.gif" /></a>';
		s += '<a id="ck_sharethis" class="stbar chicklet" href="javascript:void(0);"><img src="http://w.sharethis.com/chicklets/sharethis.gif" />ShareThis</a>';
		$(s).appendTo('#sharethis');
		var shared_object = SHARETHIS.addEntry({ title: document.title, url: document.location.href });
		shared_object.attachButton(document.getElementById("ck_sharethis"));
		shared_object.attachChicklet("email", document.getElementById("ck_email"));
		shared_object.attachChicklet("facebook", document.getElementById("ck_facebook"));
		shared_object.attachChicklet("twitter", document.getElementById("ck_twitter"));


	}

	this.init();

	this.newWin = function ( id ) {
		self.closeWin();
		$('<div id="' + id + '" class="win"></div>').appendTo(e);
		win = $('#' + id );
	}

	this.closeWin = function () {
		if ( win ) {
			win.remove();
		}
	}

	// pull in user uploaded image from server (once image has been
	// uploaded via cam or uploader)

	this.loadImage = function () {
		
		var myDate = new Date();
		var buster = myDate.getHours() + '-' + myDate.getMinutes() + '-' + myDate.getSeconds();
		$('#image').remove();
		$('<img src="/prepare/image/' + session_id + '.jpg?rotate=' + imageRotation + '&flip=' + imageFlip + '&z=' + buster + '" id="image" style="width: ' + imageWidth + 'px; height: ' + imageHeight + 'px;" />').appendTo(face);
		image = $('#image');

		// $("#image").css({"width": imageWidth + 'px', "height": imageHeight + 'px' });		

		image.css({top: 0, left: 0});

		maskWidth = $("#mask").width();
		maskHeight = $("#mask").height();
		imagePos = $("#image").offset();
		
		var x1 = (imagePos.left) - imageWidth;
		var y1 = (imagePos.top) - imageHeight;

		var x2 = (imagePos.left + maskWidth) + imageWidth;
		var y2 = (imagePos.top + maskHeight) +  imageHeight;

		image.draggable( 'destroy' );
		image.draggable({ containment: [x1,y1,x2,y2] });

		// set up rollover behavour
		// // should be 640 x 480
		// imageWidth = $("#image").width();
		// imageHeight = $("#image").height();
		
		// $("#image").css({cursor: 'move'});
		// // these need to behave depending on action
		// $('#mask').unbind('mouseover');
		// $('#mask').bind('mouseover', function () {
		// 		if ( ! self.disableMove ) {
		// 			$('#mask').hide();
		// 			// $('#hardness').hide();
		// 		}
		// 		self.disableMove = false;
		// 	});

		// $('#face').unbind('mouseout');
		// $('#face').bind('mouseout', function () {
		// 		$('#mask').show();
		// 		// $('#hardness').show();
		// 		self.disableMove = false;
		// 	});

		// $("#tip-upload").remove();
	
	}

	this.zoom = function( dir ) {

		if ( dir != 'inc' && dir != 'dec' ) {
			return false;
		}

		var pw = parseInt ( $("#image").width() );
		var ph = parseInt ( $("#image").height() );

		imageScale = parseFloat(imageScale);

		imageScale += ( dir == 'inc' ) ? 0.1 : -0.1;

		if ( imageScale < 0.1 ) {
			imageScale = 0.1;
		}

		if ( imageScale > 5 ) {
			imageScale = 5;
		}

		imageScale = imageScale.toFixed(1);

		imageWidth = parseInt ( imageWidthDefault * imageScale );
		imageHeight = parseInt ( imageHeightDefault * imageScale );

		// var top = parseInt( $("#image").css('top') ) + ( ph - imageHeight / 2 );
		var left = parseInt( $("#image").css('left') ) + ( ( pw - imageWidth ) / 2 );
		var top = parseInt( $("#image").css('top') ) + ( ( ph - imageHeight ) / 2 );
		
		$("#image").css( { "width": imageWidth + 'px', "height": imageHeight + 'px', "top": top + 'px', "left": left + 'px' });		

		var f = image.offset();
		var p = mask.offset();

		// $("#image").css({top: 0, left: 0});

		// var maskWidth  = $("#mask").width();
		// var maskHeight = $("#mask").height();

		// var imagePos     = $("#image").offset();
		// var maskPos     = $("#mask").offset();

		// imageWidth   = $("#image").width();
		// imageHeight  = $("#image").height();
		
		// var x1 = maskPos.left - (w / 2);
		// var x2 = maskPos.left + maskWidth - (w / 2);

		// var y1 = maskPos.top - (h / 2);
		// var y2 = maskPos.top + maskHeight - (h / 2);

		// $("#image").draggable('destroy');
		// $("#image").draggable({ containment: [x1,y1,x2,y2] });
		
	}

	this.rotate = function( dir ) {

		if ( dir != 'cw' && dir != 'ccw' ) {
			return false;
		}

		imageRotation += ( dir == 'cw' ) ? 5 : -5;

		imageRotation = imageRotation % 360;

		if ( imageRotation < 0 ) {
			imageRotation += 360;
		}

		var left = parseInt( $("#image").css('left') );
		var top = parseInt( $("#image").css('top') );
		
		self.loadImage();
		$("#image").css( { "top": top + 'px', "left": left + 'px' });		

	}

	this.flip = function( dir ) {
		imageFlip = ! imageFlip;
		self.loadImage();
	}

	this.move = function( dir ) {

		var top = parseInt($("#image").css('top'));
		var left = parseInt($("#image").css('left'));

		switch ( dir ) {

		case 'up':
			top -= 16;
			break;
		case 'down':
			top += 16;
			break;
		case 'left':
			left -= 16;	
		break;
		case 'right':
			left += 16;
			break;
		}

		$("#image").css({"top": top+'px', "left": left+'px' });		

		// image of user
		var f = image.offset();
		var p = mask.offset();

	}

	// grab image from webcam
	this.snap = function () {
		self.newWin('snapper');

		$('<a href="javascript:;" class="close"><span>Cancel</span></a>')
		.appendTo(win)
		.bind('click',function () {
				win.fadeOut(250, function () { win.remove(); } );
			});


		$('<div id="camcap">').appendTo(win);
		var myDate = new Date();
		var buster = myDate.getHours() + '-' + myDate.getMinutes() + '-' + myDate.getSeconds();
		$('#camcap').flash({ src: '/snapper.swf?' + buster, width: 368, height: 448,flashvars: { session_id: session_id } });
	}

	this.snapped = function () {
		$('#camcap').remove();
		self.closeWin();
		imageScale = 1.0;
		imageRotation = 0;
		imageFlip = false;
		self.loadImage();
	}

	Snapped = function () {
		self.snapped();
	}

	// user upload image with progress bar
	this.upload = function () {

		var sid = session_id;

		var s = '';
		s += "\n";
		s += '<div class="upload-input upload-vacant">';
		// s += '<div class="upload-thumb"></div>';

		s += "\n";
		s += '<form method="post" enctype="multipart/form-data" action="submit.cgi?sid=' + sid + '" target="form' + sid + '_iframe">';
		s += '<input type="file" name="file" />';
		s += '<input type="hidden" name="sid" value="' + sid + '" />';
		s += '<input type="hidden" name="filename" value="" />';
		s += '<p>Select a JPEG image of your face up to 200KB. Best size is 640x480 pixels.</p>';
		s += '</form>';

		s += '<div class="upload-status">';
		s += '<div class="upload-progress-bar"><div class="upload-progress-indicator"></div></div>';
		s += '<a href="javascript:;" class="upload-cancel"><span>Cancel</span></a>';
		s += '</div>';

		s += "\n";
		s += '<iframe name="form' + sid + '_iframe" id="form' + sid + '_iframe" src="about:blank"></iframe> ';

		s += '</div>';

		self.newWin('uploader');
		$('<a href="javascript:;" class="close"><span>Cancel</span></a>')
		.appendTo(win)
		.bind('click',function () {
				win.fadeOut(250, function () { win.remove(); } );
			});
		$(s).appendTo(win);

		win.find('.upload-input input[type=file]').bind ( 'change', function () {
				var form = $(this).parent();
				var slot = form.parent();
				
				var sid = form.find('input[name=sid]').val();
				var filename = form.find('input[name=file]').val();

				// IE bastard son ov the devil gives full path as filename
				filename = filename.replace(/^.*\\/, '');
				if ( filename.replace ( '/\s/', '' ).toString() === '' ) {
					return false;
				}
				form.find('input[name=filename]').val( filename );
				form.submit();

				form.find('input[name=file]').remove();
				form.find('p').remove();
				slot.find('.upload-status').show();
				var progressIndicator = slot.find('.upload-progress-indicator');

				form.progress = function () {
					// cachebuster for IE
					var myDate = new Date();
					var buster = myDate.getHours() + '-' + myDate.getMinutes() + '-' + myDate.getSeconds();
					$.getJSON( '/prepare/progress', { 'sid': sid, 'nocache': buster }, function ( json ) {
							if ( json.error == 'oversize' ) {
								// uploaded file was too big
								slot.find('.upload-status').fadeOut ( 250 );
								clearInterval ( interval );
								slot.append('Sorry, that file is too large to upload. Maximum size permitted is 1 Megabyte.' );
								// after 5 seconds fade out and remove - use animate opacity from 100% to 100% over 5 seconds to achieve delay
								slot.animate({opacity: 1.0}, 5000).fadeOut( 'slow', function() { slot.remove(); });
							} else if ( json.error == 'type_not_permitted' ) {
								// illegal file type ( not in $permitted list )
								clearInterval ( interval );
								slot.find('.upload-status').fadeOut ( 250 );
								slot.append( 'Sorry, that file type is not suitable. Please upload a JPEG image.');
								// // after 5 seconds fade out and remove - use animate opacity from 100% to 100% over 5 seconds to achieve delay
								slot.animate({opacity: 1.0}, 5000).fadeOut( 'slow', function() { slot.remove(); });
							} else if ( json.progress >= 100 || json.progress == 'done' ) {
								clearInterval ( interval );
								self.closeWin();
								imageScale = 1.0;
								imageRotation = 0;
								imageFlip = false;
								self.loadImage();
							} else {
								// still uploading - show % completed
								progressIndicator.css('width', json.progress + '%' );
							}
						});
				}

				var interval = setInterval( form.progress, 1000 );
				form.data( 'interval', interval );

				slot.find('a.upload-cancel').click ( function () {
						clearInterval ( interval );
						slot.fadeOut( 250, function() { self.closeWin() });
						return false;
					});
				
			});

		// var that = this;
		// $('.upload-remove').live ( 'click', function () {	
		// 		var slot = $(this).parent();
		// 		slot.fadeOut( 250, function() { slot.remove(); that.update(); });
		// 		return false;
		// 	});

	}

	this.layout = function () {

		var caption = $('#name input').val();

		if ( caption == nameHint ) {
			caption = 'Meet the new';
			// $('#name input').addClass('invalid').select();
			// return false;
		}

		if ( ! image ) {
			return false;
		}

		var p = mask.offset();
		var hards = [];

		e.find('.facial').each ( function () {
				var q = $(this).offset();
				slug = $(this).attr('rel');
				hards.push ({ 
						'x': q.left - p.left, 
							'y': q.top - p.top, 
							'index': facials[self.selectedCrewman][slug].index
					});
			});

		// image of user
		var f = image.offset();

		var i = {
			x: f.left - p.left,
			y: f.top - p.top,
			w: imageWidth,
			h: imageHeight
		};

		return { "session_id": session_id, "hards": hards, "image": i, "rotate": imageRotation, "flip": imageFlip, "mask": self.selectedMask, "caption": caption };

	}

	this.share = function () {
		
		var layout = self.layout();

		if ( ! layout ) {
			return false;
		}
		
		$('#tools').fadeOut();
		// $('#share').fadeOut();
		$('<div id="rendering"></div>').appendTo(e);
		
		// post layout
		$.post ( '/prepare/render', layout, function ( data ) {
				window.location.href='/poster/' + session_id + '.html';
			});

	}

}

function S4() {
	return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}

function guid() {
	return (S4()+S4()+S4()+S4()+S4()+S4()+S4()+S4());
}

function getCookie ( c_name )
{
	if ( ! document.cookie.length > 0 ) {
		return '';
	}

	c_start=document.cookie.indexOf ( c_name + '=' );

	if ( c_start == -1 ) {
		return '';
	}

	c_start = c_start + c_name.length + 1;
	c_end=document.cookie.indexOf ( ';', c_start );

	if ( c_end == -1 ) {
		c_end=document.cookie.length;
	}

	return unescape ( document.cookie.substring ( c_start, c_end ) );

}

function setCookie ( c_name, value, expiredays )
{
	
	var exdate = new Date();
	exdate.setDate ( exdate.getDate() + expiredays );

	document.cookie = c_name +  "=" + escape ( value ) + ( ( expiredays == null) ? "" : ";expires=" + exdate.toGMTString () );

}


