$(document).ready(function()
{
	/**
	 * Preload images
	 */
	function preload_images()
	{
		var images = new Array(
			_root + 'assets/img/ajax-loader.gif',
			_root + 'assets/img/balloon.png'
		);

		var now_at 	= 0;
		var done_at	= images.length;

		for(var i in images)
		{
			var a = new Image();
			a.src = images[i];
		}
	}



	/**
	 * Set blank targets
	 */
	$('a.blank').each(function(){
		$(this).attr('target', '_blank');
	});


	/**
	 * Clear certain inputs on focus
	 */
	$('.emptyme').each(function()
	{
		$(this).attr('original_value', $(this).val());

		$(this).focus(function()
		{
			var my_original_value = this.getAttribute('original_value');
			if(this.value == my_original_value)
			{
				this.value = '';
			}
		});

		$(this).blur(function()
		{
			var my_original_value = this.getAttribute('original_value');
			if(this.value == '')
			{
				this.value = my_original_value;
			}
		});
	});



	/**
	 * Scroll to the middle div
	 */
	function scroll_home()
	{
		var middle = $('#level_2').offset().top;
		window.scrollTo(0, middle);
		
		// If age verification is in place...
		$('#va_modal').center();
	}
	scroll_home();



	/**
	 * Scroller links
	 */
	$('a.scroller_link').click(function(e)
	{
		e.preventDefault();
		var target_div 			= $(this).attr('rel');
		var target_segment 		= $(this).attr('href').split('#')[1];
		window.location.href 	= window.location.href.split('#')[0] + '#' + target_segment;

		if($(this).attr('id') == 'kilpailu_link')
		{
			ew_ajax('level_1', 'ajax/kilpailu');
		}

		var my_top = document.getElementById(target_div).offsetTop;

		var new_title_segment = '';

		switch(target_segment)
		{
			case 'kilpailu':
			new_title_segment = 'Kilpailu';
			ga_hook('kilpailu');
			break;

			case 'alku':
			new_title_segment = '';
			break;

			case 'tuotetiedot':
			new_title_segment = 'Nyt maistuu elo!';
			ga_hook('tuotetiedot');
			break;
		}

		change_title(new_title_segment);

		$('#footer').fadeOut(100);

		$('html, body').animate({scrollTop: my_top}, 1000, function(){ $('#footer').fadeIn(1500); });
	});



	/**
	 * Check for a deep link and "go there"
	 */
	if(window.location.href.indexOf('#') > -1)
	{
		var my_segment = window.location.href.split('#')[1];
		var segments = my_segment.split('/');

		switch(segments[0])
		{
			case 'kilpailu':
				$('html, body').animate({scrollTop: document.getElementById('level_1').offsetTop}, 1000, function(){ $('#footer').fadeIn(1500); $('#va_modal').center(); });
				open_kilpailu_subnav();
				change_title('Kilpailu');
				// Deeper?
				if(segments[1] != '')
				{
					switch(segments[1])
					{
						case 'osallistu':
							ew_ajax('level_1', 'ajax/osallistu');
						break;

						case 'galleria':
							ew_ajax('level_1', 'ajax/galleria/1');
							// TODO: Deep link picture viewing also by ID segment?
						break;

						case 'palkinnot':
							ew_ajax('level_1', 'ajax/palkinnot');
						break;

						case 'saannot':
							ew_ajax('level_1', 'ajax/saannot');
						break;

						case 'raati':
							ew_ajax('level_1', 'ajax/raati');
						break;
					}
				}
				else
				{
					ew_ajax('level_1', 'ajax/kilpailu');
				}
			break;

			case 'tuotetiedot':
				$('html, body').animate({scrollTop: document.getElementById('level_3').offsetTop}, 1000, function(){ $('#footer').fadeIn(1500); $('#va_modal').center(); });
				close_kilpailu_subnav();
				change_title('Nyt maistuu elo!');
			break;
		}
	}



	// Call init functions
	place_preloader();
	setTimeout(page_has_loaded, 4000);
	preload_images();
	place_navigation();
	hot_air_balloon();
	hide_footer_cans();
	refresh();
});

/**
 * Center elements
 */
jQuery.fn.center = function()
{
    this.css('position', 'absolute');
    this.css('top', ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + 'px');
    this.css('left', ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + 'px');
    return this;
}

// ---------------------------------------- 8< ----------------------------------------

var ajax_busy = false;



/**
 * Position the navigation
 */
function place_navigation()
{
	var my_left = ($('.center').offset().left - 20);
	$('#navigation').css({left: my_left + 'px'});
}



/**
 * Call this function whenever something needs to be "refreshed"
 */
function refresh()
{
	attach_fancybox();

	// Hijack all links with ajax_link class
	$('.ajax_link').click(function(e)
	{
		e.preventDefault();

		$('.ajax_link').removeClass('active');
		$(this).addClass('active');

		if(ajax_busy) return;

		ajax_busy = true;

		var my_rel = $(this).attr('rel');
		if(my_rel == '')
		{
			var my_level = $(this).parents('.level');
			my_level = my_level.attr('id');
		}
		else
		{
			my_level = my_rel;
		}
		var my_href = $(this).attr('href');
		ew_ajax(my_level, my_href);
	});



	// Attach ajax upload to file field
	new AjaxUpload('upload_button', {
			action: _root + 'picture/upload',
			name: 'image',
			onComplete: function(file, response)
			{
				if(response)
				{
					eval(response);
				}
			}
		});

	attach_fancybox();
	hijack_upload_form();

} // End of refresh



/**
 * Hijack the upload form
 */
var upload_form_busy = false;
function hijack_upload_form()
{
	if( ! document.getElementById('ew_upload_form')) return;

	document.getElementById('ew_upload_form').onsubmit = function()
	{
		if(upload_form_busy) return;

		upload_form_busy = true;

		$('#upload_submit_button').fadeOut(100);

		$.post(_root + 'picture/save', $('#ew_upload_form').serialize(), function(response)
		{
			if(response == 'ok')
			{
				ew_ajax('level_1', _root + 'ajax/upload_successful')
				upload_form_busy = false;
			}
			else
			{
				eval(response);
				$('#upload_submit_button').fadeIn(100);
				upload_form_busy = false;
			}
		});
		return false;
	}
}



/**
 * Function that should take care of all inline AJAX page loads
 */
function ew_ajax(my_level, my_href)
{
	var my_el = '#' + my_level + '_content_ajax';

	$('a').each(function()
	{
		if($(this).attr('href') == my_href)
		{
			$(this).addClass('active');
		}
	});

	$(my_el).fadeOut(200);
	$(my_el).html('<img src="' + _root + 'assets/img/ajax-loader.gif" alt="Loading..." id="ajax_loader_gif" />');
	$(my_el).fadeIn(200);

	if(window.location.href.indexOf('/kuva/') < 0)
	{
		window.location.href = '#' + my_href.replace('ajax', 'kilpailu').replace(_root, '');
	}
	else
	{
		// This is a redirect from a single image URL
		var segments = window.location.href.split('/')
		var image_id = segments[segments.length - 1];
		$(window).load(function(){ open_single_picture(image_id); });
		window.location.href = _root + '#kilpailu/galleria/1';
	}

	$.ajax({
		url: my_href,
		success: function(data)
		{
			ajax_busy = false;

			ga_hook(my_href);

			$(my_el).hide();
			$(my_el).fadeIn(500);

			$(my_el).html(data);
			refresh();
		}
	});
}



/**
 * Hide the file input and show user that upload is complete
 */
function upload_complete()
{
	document.getElementById('upload_message').innerHTML = '<div id="image_upload_div_wrapper"><img src="' + _root  + 'assets/img/image_uploaded.gif" alt="" /> <span class="image_uploaded">Kuva ladattu</span></div>';
	$('#upload_message').hide();
	$('#image_field_para').fadeOut(150, function(){ $('#upload_message').fadeIn(150); });
}



/**
 * Open and close the subnav
 */
function open_kilpailu_subnav()
{
	$('#kilpailu_subnav').show('slow');
	$('#kilpailu_link').addClass('active');
}
function close_kilpailu_subnav()
{
	//$('#kilpailu_subnav').fadeOut(150);
	$('#kilpailu_subnav').hide('slow');
	$('#kilpailu_link').removeClass('active');
}



/**
 * Title stuff
 */
function change_title(seg)
{
	var pipe = seg == '' ? '' : ' | ';
	document.title = seg  + pipe + _title;
}



/**
 * Hot air balloon
 */
function hot_air_balloon()
{
	if(document.getElementById('balloon'))
	{
		document.body.removeChild(document.getElementById('balloon'));
	}
	var b = document.createElement('div');
		b.id 	= 'balloon';
		b.title	= 'Katso mahtavat palkinnot!';
	document.body.appendChild(b);

	b.style.top = ($('body').height() - 250) + 'px';
	var my_left = 50;
	$('#balloon').css({left: my_left + 'px'});
	$("#balloon").animate({"marginTop": "-=" + ($('body').height() + 150) + "px"}, 100000, function(){ hot_air_balloon(); });
	$("#balloon").click(function()
	{
		ew_ajax('level_1', 'ajax/palkinnot');
		$('html, body').animate({scrollTop: $('#level_1').offset().top}, 1000, function(){ $('#footer').fadeIn(1500); });
	});
}



/**
 * Hide the footer ornament in case of a small height viewport
 */
function hide_footer_cans()
{
	var h = $(window).height();
	if(h < 830)
	{
		$('#slogan').hide();
	}
	else
	{
		$('#slogan').show();
	}
}



/**
 * Attach fancybox
 */
function attach_fancybox()
{
	$('.fb').fancybox({
		'autoScale': false,
		'autoDimensions': true,
		'modal': false,
		//'width': 900,
		'overlayOpacity' : 0.5,
		'overlayColor': '#000',
		'onComplete': function(){ $.fancybox.resize(); }
	});
}



/**
 * Keep the navigation in place even on resize
 */
$(window).resize(function()
{
	place_navigation();
	hide_footer_cans();
});



/**
 * Make navigation behave according to scroll position
 */
window.onscroll = function()
{
	var edge = $('#level_1').height() - 250;
	var my_top = $(window).scrollTop();

	if(my_top < edge)
	{
		open_kilpailu_subnav();
		$('#nav_2').removeClass('active');
		$('#nav_3').removeClass('active');
	}
	else
	{
		close_kilpailu_subnav();

		if(my_top < ($('#level_3').offset().top - 250))
		{
			$('#nav_3').removeClass('active');
			$('#nav_2').addClass('active');
		}
		else
		{
			$('#nav_2').removeClass('active');
			$('#nav_3').addClass('active');
		}
	}
}



/**
 * Liking functionalities
 */
function ew_like(id)
{
	$.ajax({
		url: _root + 'picture/like/' + id,
		success: function(data)
		{
			if(isNaN(data)) // The server should return the new points amount, so if it isn't a number, something went wrong
			{
				if(data == 'cookies')
				{
					document.getElementById('like_div').innerHTML = 'Sinun tulee hyväksyä evästeet tykätäksesi';
				}
				else
				{
					document.getElementById('like_div').innerHTML = 'Tykkäät jo tästä kuvasta';
				}
			}
			else
			{
				document.getElementById('like_div').innerHTML 			= '<strong>kiitos!</strong>';
				$('#amount_of_likes').hide();
				$('#amount_of_likes').html(data);
				$('#amount_of_likes').fadeIn(450);
				setTimeout("document.getElementById('like_div').innerHTML = '" + data + "';", 2000);
				ga_hook('liked');
			}
		}
	});
}



/**
 * Add the addthis-button
 * This is done separately due to this being an external service with possible hang-ups at loadup
 */
function add_addthis()
{
	var c = '<a class="addthis_button" href="http://addthis.com/bookmark.php?v=250&amp;username=xa-4bd836ce65f49183"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=xa-4bd836ce65f49183"></script>';
	$('#addthis').html(c);
}



/**
 * Place the preloading overlay, covering the whole site before elements have loaded
 */
function place_preloader()
{
	var pr 				= document.createElement('div');
		pr.id 			= 'preloader';
		pr.innerHTML 	= 'Ladataan sivua...';

	document.body.appendChild(pr);
}



/**
 * Remove the preloading overlay
 */
function remove_preloader()
{
	$('#preloader').fadeOut(350);
}



function page_has_loaded()
{
	remove_preloader();
	add_addthis();
}



/**
 * All elements have loaded
 */
$(window).load(function()
{
	page_has_loaded();
});



/**
 * Google Analytics hook
 */
function ga_hook(l)
{
	pageTracker._trackPageview(l);
}



/**
 * Force a modal with single picture (externally shared link on Facebook)
 */
function open_single_picture(image_id)
{
	$.ajax({
		cache	: false,
		url		: _root + "picture/view/" + image_id,
		success: function(data)
		{
			$.fancybox(data, {
				'autoScale': false,
				'autoDimensions': true,
				'modal': false,
				//'width': 900,
				'overlayOpacity' : 0.5,
				'overlayColor': '#000',
				'onComplete': function(){ $.fancybox.resize(); }
				}
			);
			refresh();
			setTimeout(resize_damnit, 5000);
		}
	});

}


//setInterval(resize_damnit, 1000);
function resize_damnit()
{
	$.fancybox.resize();
}



/**
 * Previous picture, clicked from the modal window
 */
function ew_previous_picture()
{
	now_at --;
	var new_id = pics[now_at];
	$.ajax({
		url: _root + 'picture/view/' + new_id,
		success: function(data)
		{
			ajax_busy = false;
			$('#fancybox-inner').html(data);
			refresh();
			$.fancybox.resize();
		}
	});
}



/**
 * Next picture, clicked from the modal window
 */
function ew_next_picture()
{
	now_at ++;
	var new_id = pics[now_at];
	$.ajax({
		url: _root + 'picture/view/' + new_id,
		success: function(data)
		{
			ajax_busy = false;
			$('#fancybox-inner').html(data);
			refresh();
			setTimeout(resize_damnit, 600);
		}
	});
}


// EOF
