// http://www.caktux.ca/blog/suy-jquery-ui-based-ie6-outdated-notification-plugin
// IE6 outdated

jQuery.fn.delay = function(time,func){
	this.each(function(){
		setTimeout(func,time);
	});	
	return this;
};

 $(function () {
		// $('.wrapper').pngfix();
		// jQuery.each(jQuery.browser, function(i, val) {
		// 	if (val) {
		// 		$("<div style=\"color:green\">" + i + " : <span>" + val + "<\/span>")
		// 		.appendTo(document.body);
		// 	}else{
		// 		$("<div style=\"color:red\">" + i + " : <span>" + val + "<\/span>")
		// 		.appendTo(document.body);
		// 	}
		// });
	
		
		// ===============
		// = nieuwe menu =
		// ===============
		$('#firstpane p.menu_head').siblings("div.menu_body").slideUp("slow",function(){
			
			// =========================================
			// = Open menu wanneer we in subcat zitten =
			// =========================================
			if($('.menu_body a').filter('.item_active').parent().prev().attr('id') !== undefined){
				$('.menu_body a').filter('.item_active').parent().prev().css({backgroundImage:"url(http://www.boefjes.nu/images/menu/down.png)"}).next("div.menu_body").slideDown("slow");
			}
		});
		

		$("#firstpane p.menu_head").click(function()
		{
			if ($(this).css('background-image') == 'url(http://www.boefjes.nu/images/menu/down.png)') {
				$(this).css({backgroundImage:"url(http://www.boefjes.nu/images/menu/left.png)"});
			}else{
				$('#firstpane').find('p.menu_head').css({backgroundImage:"url(http://www.boefjes.nu/images/menu/left.png)"});
				$(this).css({backgroundImage:"url(http://www.boefjes.nu/images/menu/down.png)"});
			}
		    $(this).next("div.menu_body").slideToggle(800).siblings("div.menu_body").slideUp("slow");
			$("#firstpane").find('> p.menu_head:first').addClass('titlebarbegin').css({'padding':'5px',backgroundImage:'none'}).unbind();
			$("#firstpane").find('> p.menu_head:last').addClass('titlebarend').css({'padding':'5px',backgroundImage:'none'}).unbind();
		});
		$("#firstpane").find('> p.menu_head:first').addClass('titlebarbegin').css({'padding':'5px',backgroundImage:'none'}).unbind();
		$("#firstpane").find('> p.menu_head:last').addClass('titlebarend').css({'padding':'5px',backgroundImage:'none'}).unbind();
		
		scrolltotop();
		// =====================
		// = einde nieuwe menu =
		// =====================

		// ====================
		// = Setup the quotes =
		// ====================
		$('.quotes').innerfade({
			animationtype: 'slide',
			speed: 500,
			timeout: 5500,
			type: 'sequence'
		});
	
		$.post("/user/logincheck", {},function (json){check_login(json,77)},'json');

		// $('a').filter(':hash').not('.item_active,.item').click(function(event){
		// 		alert("linktext = "+$(this).text());
		// 		return false;
		// });

		//prepend all links with #topdata
		$('a').filter(':href').each(function(){
			if ($(this).attr('href') !="#") {
				$(this).attr('href',$(this).attr('href') + '#topdata');
			};
		});
		$("#register").click(function(){
			var url = '/register/';
			if ($('ol#listview').length == 1) {
				$("#listview").slideUp(1200,function () {
					$(this).load(url + ' #register_form',function(){
						$("#listview").slideDown(1200)
						activate_register_validation();
					});
				});
			}else{
				$('#main_content').slideUp(1200,function(){
					$('#main_content').html('<tr><td><ol id="listview"><li /></ol></td></tr>');
					$("ol#listview").hide().load(url + ' #register_form',function(){
						$("ol#listview").slideDown(1200);
						activate_register_validation();
					});
					$(this).show();
				});
			}
			return false;
		});
		
		// ==============
		// = Login form =
		// ==============
		$("#loginbutton").click(function(){
			user_login();
			return false;
		});
		// Zorg dat IE zonder submit toch wil inloggen zonder dubbele input on submit etc.
		$("#loginform_form input").keydown(function (e) {
			if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
				if(event.keyCode==13) user_login();
			}
		});
			
		$("#loginform_form").submit(function () {
			user_login();
		  	return false;
		});

		$("#login > .actionbar > #logout").click(function(){
			$.post("/user/logout/", {}, function() {
				show_login_form(77);
				$("#loginform").find(":input").val('');
			});	
		});
		$("#login > .actionbar > #resetlogin").click(function(){
			show_login_form(77);
		});
		$('input[type=text], input[type=password]').focus(function(){
			$(this).css({'background-color':'#FEF4D3','border':'1px solid #9bd0e8'});
		});
		$('input[type=text], input[type=password]').blur(function(){
			$(this).css({'background-color':'','border':'1px solid #d2bf7a'});
		});

		// =======================
		// = Menu met ajax laden =
		// =======================
		$('ol>li>a').live('click',function(e) {
			e.preventDefault();
			url = $(this).attr('href');
			$('html,body').animate({scrollTop: $('body').offset().top},'slow');
			$.ajax({
				url: url,
				beforeSend: function(){
					// $("#listview").stop().slideUp(700,function () {
					// 	// $("ol#listview").html($('#waiting').html()).slideDown('fast');
					// });
				},	
				success: function(data){
					// alert('success');
					$("#listview").stop().slideUp(1200,function () {
						html = $(data).find('#listview').html();
						$("ol#listview").html(html);
					});
					// $("ol#listview").slideUp('fast');
				},
				complete: function(){
					// $("ol#listview").hide().css({height: 'auto'}).slideDown(1200);
					$("ol#listview").slideDown(1200,function(){
						item_list();
						add_cart_links();
						scrolltotop();
						$('html,body').animate({scrollTop: $('ol#listview').offset().top -17},'slow');
					});
				}
			});
			
			return false;			
		})
		$('#firstpane').find('a').click(function(){
			$('.menu_body a').filter('.item_active').removeClass('item_active').addClass('item');
			$(this).removeClass('item').addClass('item_active');
			url = $(this).attr('href');
			if ($('ol#listview').length == 1) {
				$.ajax({
					url: url,
					beforeSend: function(){
						// $("#listview").stop().slideUp(1200,function () {
						// 	// $("ol#listview").html($('#waiting').html()).slideDown('fast');
						// });
					},	
					success: function(data){
						// alert('success');
						$("#listview").stop().slideUp(1200,function () {
							html = $(data).find('#listview').html();
							$("ol#listview").html(html);
						});
						// $("ol#listview").slideUp('fast');
					},
					complete: function(){
						// $("ol#listview").hide().css({height: 'auto'}).slideDown(1200);
						$("ol#listview").slideDown(1200,function(){
							item_list();
							add_cart_links();
							scrolltotop();
							$('html,body').animate({scrollTop: $('ol#listview').offset().top -17},'slow');
						});
					}
				});
					// $(this).load(url + ' #listview > li',function(){
					// 	item_list();
					// 	$("#listview").slideDown(1200)
					// 	add_cart_links();
					// });
			}else{
				$('#main_content').slideUp(1200,function(){
					$('#main_content').html('<tr><td><ol id="listview"><li /></ol></td></tr>');
					$.ajax({
						url: url,
						beforeSend: function(){
							// $("#listview").stop().slideUp(1200,function () {
							// 	// $("ol#listview").html($('#waiting').html()).slideDown('fast');
							// });
						},	
						success: function(data){
							// alert('success');
							$("#listview").stop().slideUp(1200,function () {
								html = $(data).find('#listview').html();
								$("ol#listview").html(html);
							});
							// $("ol#listview").slideUp('fast');
						},
						complete: function(){
							// $("ol#listview").hide().css({height: 'auto'}).slideDown(1200);
							$("ol#listview").slideDown(1200,function(){
								item_list();
								add_cart_links();
								scrolltotop();
								$('html,body').animate({scrollTop: $('ol#listview').offset().top -17},'slow');
							});
						}
					});
					// $("ol#listview").hide().load(url + ' #listview > li',function(){
					// 	item_list();
					// 	$("ol#listview").slideDown(1200);
					// 	add_cart_links();
					// });
					$(this).show();
				});
			}
			return false;
		});
		fotocart();
		item_list();
 });
function user_login () {
	$('input[name=username]').blur();
	$('input[name=password]').blur();
	$.post("/user/inloggen", {username: $('input[name=username]').val(),password: $('input[name=password]').val()},function (json){check_login(json,77)},'json');
	
	// return true;
}
// return;
function fotocart(){
	$("a[rel^='cartfoto[cart]']").each(function(i){
		$(this).unbind('click');
	});
	$("a[rel^='cartfoto[cart]']").prettyPhoto({
		animationSpeed: 'normal', /* fast/slow/normal */
		padding: 40, /* padding for each side of the picture */
		opacity: 0.75, /* Value betwee 0 and 1 */
		showTitle: true, /* true/false */
		allowresize: true, /* true/false */
		counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
		theme: 'dark_rounded' /* light_rounded / dark_rounded / light_square / dark_square */
	});	
}
function item_list(){
	$("a[rel^='itemlist']").each(function(i){
		$(this).unbind('click');
	});
	$("a[rel^='itemlist']").prettyPhoto({
		animationSpeed: 'normal', /* fast/slow/normal */
		padding: 40, /* padding for each side of the picture */
		opacity: 0.75, /* Value betwee 0 and 1 */
		showTitle: true, /* true/false */
		allowresize: true, /* true/false */
		counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
		theme: 'dark_rounded' /* light_rounded / dark_rounded / light_square / dark_square */
	});	
}

function show_login (status,height) {
	
	$('#login > .actionbar > .mid-button').animate({'opacity': 0}, 'fast',function(){
		$(this).hide();
	});
	if ($('#loginform').is(':visible')) {
//		console.log('animate error loginform');
		$('#loginform').animate({height: 0},300,function (){
			$(this).hide();
		});
		$('#loginstatus').show(function () {
			$(this).animate({'height': (height)},300);
//			console.log(status);
			if (status == 'success') {
				$('#login > .actionbar > #logout').animate({'opacity': 1}, 'fast',function(){
					$(this).show();
				});
			}else if (status == 'error') {
				$('#login > .actionbar > #resetlogin').animate({'opacity': 1}, 'fast',function(){
					$(this).show();
				});
			}else{
				$('#login > .actionbar > #logout').animate({'opacity': 1}, 'fast',function(){
					$(this).show();
				});
			}
		});
	}else{
//		console.log('animate error loginstatus');
		$('#loginstatus').animate({height: 0},300,function (){
			$(this).hide();
		});
		$('#loginform').show(function () {
			$(this).animate({'height': height},300);
		});
		$('#login > .actionbar > #logout').animate({'opacity': 1}, 'fast',function(){
			$(this).show();
		});
	}
}
function show_login_form (height) {
	$('#login > .actionbar > .mid-button').animate({'opacity': 0}, 'fast',function(){
		$(this).hide();
	});
	if ($('#loginform').not(':visible')) {
		$('#loginform').css({'height':0}).hide();
		$('#loginstatus').animate({height: 0},300,function (){
			$(this).hide();
			$('#loginform').animate({'height': height},300);
		});
		$('#login > .actionbar > #loginbutton').animate({'opacity': 1}, 'fast',function(){
			$(this).show();
		});
		$('#login > .actionbar > #register').animate({'opacity': 1}, 'fast',function(){
			$(this).show();
		});
	}
	$('#afreken_button').val('Inloggen').css({'color' : '#f00'}).unbind("click");
}
function check_login (json,height) {
		$('#afreken_button').val('Inloggen').css({'color' : '#f00'}).unbind("click");
		$loginform   = $('#loginform');
		$loginstatus = $('#loginstatus');
		$loginform.css({'height':height,'display': 'block'});
		if (typeof json.data != "undefined" && json.data.name.length > 0) {
			$loginstatus.html('<b>U bent ingelogd</b> (met de gebruikersnaam : ' + json.data.name + ')<br /><br />Binnenkort kan je ook je adres gegevens wijzigen.');
			show_login('success',height);
			$('#afreken_button').val('Afrekenen').css({'color' : '#009200'}).click(function(){
				show_afrekenen();
				return false;
			});
		}else{
			if (typeof json.debug != "undefined" && json.debug.length > 0) {
				$loginstatus.html(json.debug);
				//uitschakelen omdat anders er meteen een error getoond wordt
				// show_login('error',height);
			}else if (typeof json.error != "undefined" && json.error.length > 0) {
				$loginstatus.html(json.error);
				show_login('error',height);
			}else if (typeof json.logout != "undefined" && json.logout.length > 0) {
				$loginstatus.html(json.logout);
				show_login('error',height);
			}else{
				// console.log('do noting');
			}
		}
}

function show_afrekenen () {
	$('#cart_inhoud').load("/cart #cart_inhoud",function(){
		cart_height = $('#cart_overzicht').height();
		$('cart_overzicht').css({height:'0px'});
		$('#topdata').parent().animate({height:'0px'},function(){
			$(this).fadeOut().hide();
		});
		$('#global_content').animate({opacity: '0'},'fast').hide();
		$('#cart_overzicht').animate({height:cart_height}).fadeIn();
		$('.footer').parent().hide();
	});
	return false;
}
function hide_afrekenen () {
	$('#topdata').parent().animate({height: '210px'});
	$('#global_content').animate({opacity: 1},'fast').show();
	cart_height = $('#cart_overzicht').height();
	$('#cart_overzicht').animate({height:'0px'},function(){ 
		$(this).css({height:cart_height}).hide();
	});
	$('.footer').parent().show();
	return false;
}
function submit_cart () {
	$('#cart >.sc_menu > li').each(function(){ $(this).remove()});
	check_empty_cart();
	$.post('/check/send_cart/',{'opmerking': $('#opmerking').val()});
	hide_afrekenen();
	return false;
}
function activate_register_validation () {
	$('#signup #username').focus();
	$('#signup #username').blur(function() {
		$.ajax({url:'/check/username',type: 'post', dataType: 'script', data:$('#signup').serialize()});
	});
	$('#signup #email').blur(function() {
		$.ajax({url:'/check/email',type: 'post', dataType: 'script', data:$('#signup').serialize()});
	});
	$('#signup #passwd1').blur(function() {
		$.ajax({url:'/check/passwd',type: 'post', dataType: 'script', data:$('#signup').serialize()});
	});
	$('#signup #voornaam').blur(function() {
		$.ajax({url:'/check/naam/'+ this.name,type: 'post', dataType: 'script', data:$('#signup').serialize()});
	});
	$('#signup #achternaam').blur(function() {
		$.ajax({url:'/check/naam/'+ this.name,type: 'post', dataType: 'script', data:$('#signup').serialize()});
	});
	$('#signup #postcodel').blur(function() {
		$.ajax({url:'/check/postcode',type: 'post', dataType: 'script', data:$('#signup').serialize()});
	});
	$('#signup #straat').blur(function() {
		$.ajax({url:'/check/naam/'+ this.name,type: 'post', dataType: 'script', data:$('#signup').serialize()});
	});
	$('#signup #plaats').blur(function() {
		$.ajax({url:'/check/naam/'+ this.name,type: 'post', dataType: 'script', data:$('#signup').serialize()});
	});
	$('#signup').submit(function(){
		if (($('#signup .okay').length/2) == 9) {
			$.ajax({url:'/check/enter_data',type: 'post', dataType: 'script', data:$('#signup').serialize()});
		}else{
			alert('Je hebt nog fouten in het formulier.');
		}
		return false;
	});
}
function scrolltotop () {
	$items = $('ol#listview li:gt(2)');
	$items.find('div:first').before('<div style="float:right;font-size:14px;cursor:pointer" class="totop">&nbsp;&#8593;&nbsp;</div>');
	$items.find('.totop').click(function(){
		// offset = $('ol#listview').offset().top - 17;
		// $('html,body').animate({scrollTop: offset},'slow');
		$('html,body').animate({scrollTop: $('body').offset().top},'slow');
	});
}
