/* 
 * Scape movement.
 */

jQuery(function($){

	$.fn.autosize = function(z){
		var t = $(this),
		s,
		d = {
			w: (winheight / theight) * twidth,
			h: (winwidth / twidth) * theight
		};
		if (d.h > winheight) {
			s = {
				width: winwidth + 'px',
				height: d.h + 'px'
			};
		} else {
			s = {
				width: d.w + 'px',
				height: winheight + 'px'
			};
		}
		if (z == 'init') {
			t.css(s);
			t.show('fade', 'slow', function(){
				popupi.dialog('open');
			});
		} else {
			s = $.extend({
				top: 0,
				left: 0
			}, s);
			t.animate(s);
		}
		return t;
	};

	$.fn.zoomToggle = function(e){
		var t = $(this);
		if (zoomed) {
			$('#zoom').unbind('click');
			t.unbind('click')
			.draggable('destroy')
			.autosize('zoomout')
			.click(function(e){
				$(this).zoomToggle(e);
			});
			zoomed = !zoomed;
		} else {
			t.unbind('click')
			.animate({
				width: twidth + 'px',
				height: theight + 'px',
				left: -e.pageX + 'px',
				top: -e.pageY + 'px'
			})
			.unbind('mousedown')
			.draggable({
				cursor: 'move',
				drag: function(e, ui){
					e.stopPropagation();
					var up = ui.position;
					if (up.left <= tc.x) {
						up.left = tc.x;
					}
					if (up.left >= 0) {
						up.left = 0;
					}
					if (up.top <= tc.y) {
						up.top = tc.y;
					}
					if (up.top >= 0) {
						up.top = 0;
					}
				}
			})
			.click(function(e){
				var tp = t.position();
				var map = {
					x: e.pageX - tp.left,
					y: e.pageY - tp.top
				};
				$.post('gridlocation.php', map, function(detailsflat){
					var details = detailsflat.split(','),
					akey = details[0],
					gptext = details[1];
					$('#artist-details').html(gptext);
					$('#akey').val(akey);
					$('#guess').val(guesses[akey]);
					popup.dialog('open')
					.dialog('option', {
						position: [
							e.pageX,
							e.pageY - popup.outerHeight()
						]
					});
				});
			});
			$('#zoom').click(function(e){
				t.zoomToggle(e);
			});
			zoomed = !zoomed;
		}
		return t;
	}

	var getGuesses = function(){
		var decoded,
		cookie = getCookie('answers');
		if (cookie) {
			try {
				decoded = JSON.parse(cookie);
			} catch (exception) {
				decoded = null;
			}
			if (decoded) {
				return decoded;
			} else {
				return {};
			}
		} else {
			return {};
		}
	}

	var twidth,
	theight,
	winwidth = $(window).width(),
	winheight = $(window).height(),
	tc,
	guesses = getGuesses(),
	zoomed = false,
	dOps = {
		autoOpen: false,
		modal: true,
		resizable: false,
		width: 472,
		height: 255
	},
	popup = $('#popup').dialog($.extend({}, dOps, {
		width: 269,
		height: 149,
		dialogClass: 'popup-dialog',
		open: function(){
			var qty = 0;
			$.each(guesses, function(){
				qty++;
			});
			$('#guess-qty').text(qty);
		}
	})),
	popupi = $('#popup-instructions').dialog($.extend({}, dOps, {
		open: function(){
			var dpp = $(this);
			$('.ui-widget-overlay').one('click', function(){
				dpp.dialog('close');
			});
		}
	}));

	$('#entry').dialog(dOps);

	$('.ui-dialog').removeClass('ui-corner-all');
	$('#enter, #zoom, #instructions, #s').button();
	$('#instructions').click(function(){
		popupi.dialog('open');
	});
	popupi.dialog('widget').click(function(){
		popupi.dialog('close');
	});

	$('#carry-on').click(function(e){
		e.preventDefault();
		$('#entry').dialog('close');
	})

	$('#guess-form').submit(function(e){
		e.preventDefault();
		if ($('#guess').val() != "" && $('#akey').val() != 0) {
			guesses[$('#akey').val()] = $('#guess').val();
			setCookie( 'answers' , JSON.stringify(guesses), 60);
			//setCookie( $('#akey').val() , $('#guess').val(), 60);
		}
		popup.dialog('close');
	});

	$('#e').click(function(e){
		e.preventDefault();
		$('.error').remove();
		$('#name, #email').removeClass('invalid');
		var optval = '';
		$('#optout:checked').each(function(){
			optval = 'on';
		});
		var data = {
			name: $('#name').val(),
			email: $('#email').val(),
			fbid: $('#fbid').val(),
			sinc: $('#sinc').val(),
			optout: optval,
			guesses: guesses
		};
		$.post('enter.php', data, function(result){
			if (result == 'invalid-n') {
				$('#name').addClass('invalid');
				$('#entry-form').append('<div class="error">Please enter your full name</div>');
			} else if (result == 'invalid-e') {
				$('#email').addClass('invalid');
				$('#entry-form').append('<div class="error">Please enter a valid email address</div>');
			} else if (result == 'invalid-ne') {
				$('#name, #email').addClass('invalid');
				$('#entry-form').append('<div class="error">Please enter your full name and a valid email address</div>');
			} else {
				$('#submit-content').hide();
				$('#correct').text(result);
				var qty = 0;
				$.each(guesses, function(){
					qty++;
				});
				//$('#guessed-qty').text($('#guess-qty').text());
				$('#guessed-qty').text(qty);
				var th = 'I just played EMI Christmas and spotted ' + result + ' out of 59 artists. Can you top it and win?';
				$('#tweet').attr('href', 'https://twitter.com/share?text=' + encodeURIComponent(th));
				$('#congrats').show();
				FB.getLoginStatus(function(response) {
					if (response.authResponse) {
						$('#share').click();
					}
				});
			}
		});
	});

	$(window).load(function(){
		var t = $('#scape');
		twidth = t.width();
		theight = t.height();
		tc = {
			x: winwidth - twidth,
			y: winheight - theight
		};
		$('#loading').remove();
		t.autosize('init')
		.mousedown(function(e){
			e.preventDefault();
		})
		.click(function(e){
			t.zoomToggle(e);
		});
	});

});

