var egl;
var titleBase = " | Krug Mind Share";
var contentBase = "";//"<p class='clear'>&nbsp;</p>";

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function fixMindHeight () {
	if ($('#mind-header').length == 0)
		return;
	
	var delta = $('#mind-header').height() - 40;
	$('#mind-content').height(460-delta);
}

function updatePageAjax ( link, quick ) {
	var ready = false;
	var dataCont;
	var updateCont = function () {
		document.title = dataCont.title + titleBase;
		$("#content").html (dataCont.content + contentBase);
		$("#full-content-wrap").slideDown('slow', function () {
			$("#mind-content").css('position','relative');
		});
		$('a.selected').removeClass ('selected');
		//if (link.match("^/minds?/") !== null) link = '/minds';
		if (typeof dataCont.past_mind != "undefined")
			if (dataCont.past_mind=="True")
				link = '/past_minds';
			else
				link = '/minds';
		egl = dataCont;
		$('a[href='+link+']').addClass ('selected');
		
		if (typeof FB =="object" && typeof FB.Share == "object")
			FB.Share.renderAll();
		
		fixMindHeight();
		
		var subBlocks = $(".other-minds .other-mind-el").length; 
        if (subBlocks > 6)
        {
            $('#back-slide-but').show();
            $('#front-slide-but').show();
            $('.other-minds .wrapper').slider({
                left_btn_id: 'back-slide-but',
                right_btn_id: 'front-slide-but',
                slide_width: 61,
                slides_count: subBlocks            
            }); 
        }
	};

	$("#mind-content").css('position','static');
	$("a[name=fb_share]").hide();
	if (!quick) {
		if (link == '/minds' || link == '/past_minds')
			$('#content').css('overflow-y', 'hidden');
		else
			$('#content').css('overflow-y', 'auto');
		$("#full-content-wrap").slideUp ('slow', function (){
			if (ready)
				updateCont();
			else
				ready = true;
		});
	}
	else {
		ready = true;
	}
	
	$.ajax ({
		url : link,
		dataType : 'json',
		success : function (data) {
			dataCont = data;
			if (ready)
					updateCont();
			else
				ready = true;
		},
		error : function (request, status, error) {
			if (status == "parsererror") {
					window.location = link;
			}
			else $("#content-wrap").slideDown('slow');

		}
	});
	/**/
}

function sendPostForm ( formid ){
	var contactForm = $(formid);
	
	$.post (contactForm.attr('action'), contactForm.serialize(), function (data){
		document.title = data.title + titleBase;
		$("#content").html (data.content + contentBase);
	}, 'json');
	
	return false;
}

$(document).ready( function () {
	
	//$('#content').wrap("<div id='full-content-wrap'></div>")

	fixMindHeight();
	$("#mind-content").css('position','relative');
	//$('#content').height(maxPosibleHeight > 600 ? 600: maxPosibleHeight);
	//$('#content').height(580);
	
	if (location.hash) {
		updatePageAjax(location.hash.substr(1));
	}
	
	$('#mind-block-sel').change(function (event) {
		var year = $(this).val();
		
		$.get ('/get_mind_block/'+year, '', function (data) {
			$('#mind-block').html(data);
		},'html')
	})
	
	$('a.local').live ("click", function (event) {
		event.preventDefault();
		var link = $(this).attr('href')
		location.hash = link;
		
		updatePageAjax (link, $(this).hasClass('quick-change'));
		
		return false;
	});
	if (readCookie('age-pass') != 'passed')
	{
		var enterFunc = function () {
			$("p#entry-error").text("");
			if ($('#dialog select[name=country]').val() == 0 || $('#dialog select[name=day]').val() == 0 ||
					$('#dialog select[name=month]').val() == 0 || $('#dialog select[name=year]').val() == 0)
			{
				$("p#entry-error").text ("please fill the fields below");
				return;
			}
			var cur = new Date();
			var old = new Date(
					parseInt($('#dialog select[name=year]').val()),
					parseInt($('#dialog select[name=month]').val()),
					parseInt($('#dialog select[name=day]').val())
			);
			var age = cur.getFullYear() - old.getFullYear();
			old.setFullYear (cur.getFullYear());
			if (old > cur) age--;
			
			var minAge = 18
			/* US and Sri Lanka*/
			if ($('#dialog select[name=country]').val() == 234 || $('#dialog select[name=country]').val() == 208 )
			    minAge = 21
			/* Japan */
			if ($('#dialog select[name=country]').val() == 111)
			    minAge = 20

			if (age > minAge) 
			{
				createCookie ('age-pass', 'passed', 7);
				$("#dialog").dialog("close");
			}
			else
				$("p#entry-error").text ("you are not allowed to visit this site");
		}
		
		var list = $('select[name=year]')
		var year = (new Date()).getFullYear();
		for (var i = year-5; i > year-100; i--)
		{
			list.append ( $("<option value='"+i+"'>"+i+"</option>") )
		}
		list = $('select[name=day]')
		for (i=1; i <= 31; i++)
			list.append ( $("<option value='"+i+"'>"+i+"</option>") )
		
		$('#dialog').dialog({
				title: "Welcome to Krug Mind Share",
				width: 700,
				height: 450, 
				modal: true,
				closeOnEscape: false
				/*buttons: {
					Enter: enterFunc, 
				}*/
		});
		$('#enter-but').click ( enterFunc )
		$('.ui-widget-content').css('background-color', 'white');
		$('.ui-dialog-titlebar-close').hide();
		$('.ui-dialog-titlebar').hide();
		$('.ui-widget-overlay').css('opacity','0.8')
		$('.ui-widget-overlay').css('background','#5c0002')
		//$('.ui-widget-overlay').css('background','#666')
		
	}
	else
		createCookie ('age-pass', 'passed', 7);
});

