$(function(){
	/*
	 * Custom jQuery Functions
	 */
	// jQuery logging
	jQuery.fn.log = function (msg) {

		console.log("%s: %o", msg, this);
		return this;

	};
	// Superfish Navigation
	$('div#nav ul.sf-menu').superfish();

	/*
	 * Panel
	 */
	$('#slider #greeting,#slider .toggle').click(function(){
		if((!$('#reg_form').length && $(this).attr('id')!='greeting') || $(this).attr('id')=='login'){
			$.validationEngine.closePrompt(".formError",true);
			/*$("#reg_form,.login form").validationEngine('hideAll');*/
			if($('#panel_color').css('display')=='none'){
				$('#panel_color').slideDown("slow");
			} else if(!$('#userEmail').length) {
				$('#panel_color').slideUp("slow");
			}
			if(!$('#userEmail').length){
				$('#panel_color').css({height:'70px'});
			}
			$('#slider .toggle').toggle();
			$('#slider #close_reg').hide();
			$('#slider #reg').show();
			if((!$('#user').length && !$('#password').length && !$('#userEmail').length) || ($('#userEmail').length && $(this).attr('id')=='login')){
				/* login */
				$('#panel_color').addClass('loadingpanel').animate({height:'70px'});
				$('#panel_content').hide();
				$('#panel_content').load($('#login').attr('rel'),function(){
					console.log('login loaded');
					$(".login form").validationEngine({
						promptPosition: "bottomRight",
						ajaxSubmit: true,
						ajaxSubmitFile: $('.login form').attr('action'),
						ajaxSubmitMessage: "Login Successful!",
						ajaxSubmitExtraData: "submit=true",
						reload: true,
						success :  true,
						failure : function() {}
					});
				}).fadeIn('slow');
				$('#panel_color').removeClass('loadingpanel');
			}
		}
	});
	/* show user menu after login */
	if($('#panel_color').hasClass('justLoggedIn')){
		$('#panel_content').load($('#slider_user #menu').attr('rel'));
		$('#panel_color').css({height:'320px'});
		$('#panel_color').slideDown("slow");
		$('#slider_user .toggle_menu').toggle();
	}
	/* activate login form on first load */
	$(".login form").validationEngine({
		promptPosition: "bottomRight",
		ajaxSubmit: true,
		ajaxSubmitFile: $('.login form').attr('action'),
		ajaxSubmitMessage: "Login Successful!",
		ajaxSubmitExtraData: "submit=true",
		reload: true,
		success :  true,
		failure : function() {}
	});
	/*$('.login form').validationEngine({
		ajaxFormValidation: true,
		onValidationComplete: function(form,status){
			form.action = form.action + "&submit=true";
		},
        onAjaxFormComplete: function(status){
            if (status === true) {
                alert("the form is valid!");
                // uncomment these lines to submit the form to form.action
                location.reload(true);
                // or you may use AJAX again to submit the data
            }
        }
	});*/

	$('#slider .toggle_reg').click(function(){
		if($('#panel_color').css('display')=='none'){
			$('#panel_color').slideDown("slow");
		} else if(!$('#user').length && !$('#mailEmail').length) {
			$.validationEngine.closePrompt(".formError",true);
			/*$("#reg_form,.login form").validationEngine('hideAll');*/
			$('#panel_color').slideUp("slow");
		}
		$('#slider .toggle_reg').toggle();
		$('#slider #close').hide();
		$('#slider #login').show();
		/* register */
		if(!$('#reg_form').length){
			$('#panel_color').addClass('loadingpanel').animate({height:'250px'});
			$('#panel_content').hide();
			$('#panel_content').load($(this).attr('rel'),function(){
				$("#reg_form").validationEngine({
					promptPosition: "bottomRight",
					ajaxSubmit: true,
					ajaxSubmitFile: $('#reg_form').attr('action'),
					ajaxSubmitMessage: "Thank you, we received your inscription!",
					ajaxSubmitExtraData: "userSend="+$('userSend').val(),
					reload: true,
					success :  true,
					failure : function() {}
				});
				$('#panel_content').fadeIn('slow');
				$('#panel_color').removeClass('loadingpanel');
			});
		}
	});

	$('#slider_user .toggle_menu').click(function(){
			if($('#panel_color').css('display')=='none'){
				$('#panel_color').css({height:'320px'});
				$('#panel_color').slideDown("slow");
			} else {
				$.validationEngine.closePrompt(".formError",true);
				/*$("#reg_form,.login form").validationEngine('hideAll');*/
				$('#panel_color').slideUp("slow");
			}
			$('#slider_user .toggle_menu').toggle();
			$('#panel_content').load($(this).attr('rel'));
	});
	$('#slider_user #greeting').click(function(){
		if($('#panel_color').css('display')=='none'){
			$('#panel_color').css({height:'320px'});
			$('#panel_color').slideDown("slow");
		} else {
			$.validationEngine.closePrompt(".formError",true);
			/*$("#reg_form,.login form").validationEngine('hideAll');*/
			$('#panel_color').slideUp("slow");
		}
		$('#slider_user .toggle_menu').toggle();
		$('#panel_content').load($(this).attr('rel'));
	});

	$('a[rel=register]').live('click',function(){
		if($('#panel_color').css('display')=='none'){
			$('#panel_color').css({height:'320px'});
			$('#panel_color').slideDown("slow");
		} else {
			$.validationEngine.closePrompt(".formError",true);
			$('#panel_color').slideUp("slow");
		}
		$('#slider .toggle_reg').toggle();
		$('#panel_content').load($(this).attr('href'),function(){
			$("#reg_form").validationEngine({
				promptPosition: "bottomRight",
				ajaxSubmit: true,
				ajaxSubmitFile: $('#panel_content form').attr('action'),
				ajaxSubmitMessage: "Thank you, we received your inscription!",
				ajaxSubmitExtraData: "userSend="+$('userSend').val(),
				reload: true,
				success :  false,
				failure : function() {}
			});
			$('#panel_content').fadeIn('slow');
			$('#panel_color').removeClass('loadingpanel');
		});
		return false;
	});

	$('a[rel=sendpw]').live('click',function(){
		$('#panel_color').addClass('loadingpanel').animate({height:'100px'});
		$('#panel_content').hide();
		$('#panel_content').load($(this).attr('href'),function(){
			$(".passwordforgotten form").validationEngine({
				promptPosition: "bottomRight",
				ajaxSubmit: true,
				ajaxSubmitFile: $('.passwordforgotten form').attr('action'),
				ajaxSubmitMessage: "Password re-send!",
				ajaxSubmitExtraData: "passSend="+$('.passwordforgotten #submit').val(),
				success :  false,
				failure : function() {}
			});
			$('#panel_content').fadeIn('slow');
			$('#panel_color').removeClass('loadingpanel');
		});
		return false;
	});


	/* Plant Profile */
	$(".plant_image a").overlay({
		target: '#plant_image',
        effect: 'apple',
        oneInstance: true,
        closeOnClick: true
	});

	// avatar position fix
	$('.profile_avatar span.whitebg_shadow img').hide();
	if($('.profile_avatar span.whitebg_shadow img').length){
		$('.profile_avatar span.whitebg_shadow').css('background','url(' + $('.profile_avatar span.whitebg_shadow img').attr('src') + ') no-repeat 50% 50%');
	} else {
		$('.profile_avatar span.whitebg_shadow').css('background','url(/img/icons/user_64.png) no-repeat 50% 50%');
	}

	$('ul.tabs li a').each(function(index){
		var button = this;
		$(this).click(function(){
			$('div.plant_parts div.tab').each(function(tindex){
				if(index == tindex){
					$('div.tab:eq(' + tindex + ')').show();
				} else {
					$('div.tab:eq(' + tindex + ')').hide();
				}
			});
			$('ul.tabs li a:not('+ $(this) + '.inactive' +')' ).addClass('inactive');
			$(this).removeClass('inactive');
			return false;
		});
		$('div.plant_parts div.tab').each(function(index){
			if(index == 0){
				$('div.tab:eq(' + index + ')').show();
			} else {
				$('div.tab:eq(' + index + ')').hide();
			}
		});
	});
	
	$('ul.log_tabs li a').each(function(index){
		var button = this;
		$(this).click(function(){
			$('div.plant_parts div.log_tab').each(function(tindex){
				if(index == tindex){
					$('div.log_tab:eq(' + tindex + ')').show();
				} else {
					$('div.log_tab:eq(' + tindex + ')').hide();
				}
			});
			$('ul.tabs li a:not('+ $(this) + '.inactive' +')' ).addClass('inactive');
			$(this).removeClass('inactive');
			return false;
		});
		$('div.plant_parts div.log_tab').each(function(index){
			if(index == 0){
				$('div.log_tab:eq(' + index + ')').show();
			} else {
				$('div.log_tab:eq(' + index + ')').hide();
			}
		});
	});

	/*
	 * Sunflower rating
	 */
	if($('#rating1').length){
		$('#rating1').hover(function(){
			$('#rating1 li').click(function(){
				$(this).removeClass('.sunflower_off').addClass('sunflower_on');
				$(this).prevAll('.sunflower_off').removeClass('sunflower_off').addClass('sunflower_on');
				$(this).nextAll('.sunflower_on').removeClass('sunflower_on').addClass('sunflower_off');
				var thisid = $(this).attr('id').split("-");
				var thisid = $('#value1').val(thisid[0]);
				;	
			});
		});
	}	
	if($('#rating2').length){
		$('#rating2').hover(function(){
			$('#rating2 li').click(function(){
				$(this).removeClass('.sunflower_off').addClass('sunflower_on');
				$(this).prevAll('.sunflower_off').removeClass('sunflower_off').addClass('sunflower_on');
				$(this).nextAll('.sunflower_on').removeClass('sunflower_on').addClass('sunflower_off');
				var thisid = $(this).attr('id').split("-");
				var thisid = $('#value2').val(thisid[0]);
				;	
			});
		});
	}	
	if($('#rating3').length){
		$('#rating3').hover(function(){
			$('#rating3 li').click(function(){
				$(this).removeClass('.sunflower_off').addClass('sunflower_on');
				$(this).prevAll('.sunflower_off').removeClass('sunflower_off').addClass('sunflower_on');
				$(this).nextAll('.sunflower_on').removeClass('sunflower_on').addClass('sunflower_off');
				var thisid = $(this).attr('id').split("-");
				var thisid = $('#value3').val(thisid[0]);
				;	
			});
		});
	}	
	if($('#rating4').length){
		$('#rating4').hover(function(){
			$('#rating4 li').click(function(){
				$(this).removeClass('.sunflower_off').addClass('sunflower_on');
				$(this).prevAll('.sunflower_off').removeClass('sunflower_off').addClass('sunflower_on');
				$(this).nextAll('.sunflower_on').removeClass('sunflower_on').addClass('sunflower_off');
				var thisid = $(this).attr('id').split("-");
				var thisid = $('#value4').val(thisid[0]);
				;	
			});
		});
	}	
		
	$('ul.ctabs li a').each(function(index){
		var button = this;
		$(this).click(function(){
			$('div.plant_charts div.ctab').each(function(tindex){
				if(index == tindex){
					$('div.ctab:eq(' + tindex + ')').show();
				} else {
					$('div.ctab:eq(' + tindex + ')').hide();
				}
			});
			$('ul.ctabs li a:not('+ $(this) + '.inactive' +')' ).addClass('inactive');
			$(this).removeClass('inactive');
			return false;
		});
		$('div.plant_charts div.ctab').each(function(index){
			if(index == 0){
				$('div.ctab:eq(' + index + ')').show();
			} else {
				$('div.ctab:eq(' + index + ')').hide();
			}
		});
	});

	/*
	 * Language Menu
	 */
	$('#languages select').selectmenu({
			style:'dropdown',
			icons: [
				{find: '.de'},
				{find: '.en'},
				{find: '.es'},
				{find: '.be'},
				{find: '.fr'},
				{find: '.nl'},
				{find: '.pl'},
				{find: '.gr'},
				{find: '.it'},
				{find: '.cz'},
				{find: '.pt'},
				{find: '.jp'},
				{find: '.ru'},
				{find: '.ro'},
				{find: '.cn'},
				{find: '.bg'},
				{find: '.dk'},
				{find: '.fi'},
				{find: '.se'},
				{find: '.hu'}
			]}).change(function(){
				window.location.href = $(this).val();
			});

	/*
	 * Home - Welcome Text Columns
	 */
	if($.browser.ie){ // works only in IE since jQuery 1.6.x
		$('#welcome_text div').columnize({columns:2});
	}

	/*
	 * Plants view all (Tooltip)
	 */
	$("#view_all a").tooltip({
		bodyHandler: function() {
			return $($(this).attr("href")).html();
		},
		showURL: false
	});

	/*
	 * Ranking (Tooltip)
	 */
	$("#ranking a.tooltip").tooltip({
		bodyHandler: function() {
			return $($(this).attr("href")).html();
		},
		showURL: false
	});

	/*
	 * Plant details (Tooltip)
	 */
	$(".plant_parts a").tooltip({
		bodyHandler: function() {
			return $($(this).attr("href")).html();
		},
		showURL: false
	});

	/*
	 * Plants Map
	 */
	if($('.plant #map').length){
		if(!$('#my_stat').length){
			starte(8);
			$('#maplinks').click(function(){ return false; });
		}
	}

	/*
	 * Country Comparison
	 */
	if($('table.compare').length){
		$.tablesorter.defaults.widgets = ['zebra'];
		$('table.compare').tablesorter();

		$('#compare_dd select[name=year]').change(function(){
			var newhref = $('#compare_dd').attr('action');
			newhref = newhref.split('?');
			newhref = newhref[0] + '?year=' + $(this).val();
			if($('input[name=country]').length){
				newhref = newhref + '&country=' + $('input[name=country]').val();
			}
			window.location.href=newhref;
		});

		$('#compare_bl select[name=year]').change(function(){
			/*var newhref = $('#compare_bl').attr('action');
			newhref = newhref.split('?');
			newhref = newhref[0] + '?year=' + $(this).val();
			if($('input[name=bl]').length){
				newhref = newhref + '&bl=' + $('input[name=bl]').val();
			}
			if($('input[name=bz]').length){
				newhref = newhref + '&bz=' + $('input[name=bz]').val();
			}
			if($('input[name=lk]').length){
				newhref = newhref + '&lk=' + $('input[name=lk]').val();
			}*/

			var location = window.location.href.substring(0,window.location.href.length-9);
			var year = $('#compare_bl select option:selected').val();
			newhref = location + year + '.html';
			window.location.href=newhref;
		});
	}

	if($('#slider_home').length>0){
		$('#slider_home').easySlider({
			auto: true,
			continuous: true
		});
		$('.slider_image').each(function(){
			$(this)
			.css('background','url(' + $(this).find('img').attr('src') + ') no-repeat 50% 50%')
			.css('width', $(this).find('img').width())
			.css('height', $(this).find('img').height());

		});
		$('.slider_image img').hide();
	}
	
	/*
	 * Gallery
	 */
	if($('#gallery_home').length>0){
		/*$('#gallery_home').cycle('fade');*/
		$('#gallery_home').easySlider({
			auto: true,
			continuous: true
		});
	}

	/*
	 * ideas
	 */
	/* vote for an idea */
	$("#vote").live('click', function(){
		$.post( '/ajax/info/ideasvoting', {id:$('#id').val(), grade:$('#grade').val(), comment:$('#comment').val()},
		function(html) {
			$("#content_overlay div.contentWrap").html(html);
		});
	});

	/* comment for an idea */
	$("#save_comment").live('click', function(){
		$.post( '/ajax/info/ideascomment', {id:$('#id').val(),reload:$('#reload').val(), comment:$('#comment').val()},
		function(html) {
			$("#content_overlay div.contentWrap").html(html);
		});
	});

	if($('#ideas .ideas_list').length>0){
		$('.ideas_list').each(function(i, idea){
			var each_id = $(idea).attr('id').split('_');
			var id = each_id[1];

			$("#idea_" + id + ' .voting').live('mousedown', function(){
				$(this).overlay({
					target: '#content_overlay',
					effect: 'apple',
					oneInstance: true,
					closeOnClick: false,
					onBeforeLoad: function() {
						var wrap = this.getOverlay().find(".contentWrap");
						wrap.load('/ajax/info/ideasvoting/' + id);
					},
					onClose: function(html) {
						$.ajax({
							async: false,
							url:"/ajax/info/ideasvoting",
							type: "POST",
							data: ({id: id,voted:1}),
							dataType: "html",
							success: function(html){
							$('#idea_' + id + ' .box').replaceWith(html);
						}
						});
					}
				});
			});

			$("#idea_" + id + ' .comment').live('mousedown', function(){
				$(this).overlay({
					target: '#content_overlay',
					effect: 'apple',
					oneInstance: true,
					closeOnClick: false,
					onBeforeLoad: function() {
						var wrap = this.getOverlay().find(".contentWrap");
						wrap.load('/ajax/info/ideascomment/' + id);
					},
					onClose: function(html) {
						$.ajax({
							async: false,
							url:"/ajax/info/ideasvoting",
							type: "POST",
							data: ({id: id,comment:1}),
							dataType: "html",
							success: function(html){
							$('#idea_' + id + ' .comments').replaceWith(html);
						}
						});
					}
				});
			});

			/*$("#idea_" + id + " .show_details").live('mousedown', function() {
				$("#idea_" + id + " .show_details span").toggle();
				$("#details_" + id).slideToggle("slow");
			});*/

		});
	}

	/*
	 * incomplete plants
	 */
	if ($("#pp_incomplete").length > 0 ) {
		$("#pp_incomplete").overlay({
			target: '#content_overlay',
	        effect: 'apple',
	        oneInstance: true,
	        closeOnClick: true,
	        onBeforeLoad: function() {
				var wrap = this.getOverlay().find(".contentWrap");
				wrap.load('/ajax/plant/insertelements/info');
			}
		});
	}

	/* Surveys comments */
	$('.surveys .comment').live('mousedown', function(){
		var id_array = $('.surveys .comment').attr('id').split('_');
		var id = id_array[1];
		$(this).overlay({
			target: '#content_overlay',
			effect: 'apple',
			oneInstance: true,
			closeOnClick: false,
			onBeforeLoad: function() {
				var wrap = this.getOverlay().find(".contentWrap");
				wrap.load('/ajax/info/surveyscomment/'+id);
			},
			onClose: function(html) {
				$.ajax({
					async: false,
					url:"/ajax/info/surveyscomment",
					type: "POST",
					data: ({id: id,comment:1}),
					dataType: "html",
					success: function(html){
					$('#comments .comments').replaceWith(html);
				}
				});
			}
		});
	});

	/* Save comment for an survey */
	$("#save_survey_comment").live('click', function(){
		$.post( '/ajax/info/surveyscomment', {id:$('#id').val(),reload:$('#reload').val(), comment:$('#comment').val()},
		function(html) {
			$("#content_overlay div.contentWrap").html(html);
		});
	});

	/* News comments */
	$('.news .comment').live('mousedown', function(){
		var id_array = $('.news .comment').attr('id').split('_');
		var id = id_array[1];
		$(this).overlay({
			target: '#content_overlay',
			effect: 'apple',
			oneInstance: true,
			closeOnClick: false,
			onBeforeLoad: function() {
				var wrap = this.getOverlay().find(".contentWrap");
				wrap.load('/ajax/news/comment/'+id);
			},
			onClose: function(html) {
				$.ajax({
					async: false,
					url:"/ajax/news/comment",
					type: "POST",
					data: ({id: id,comment:1}),
					dataType: "html",
					success: function(html){
					$('.news .comments').replaceWith(html);
				}
				});
			}
		});
	});

	/* Save comment for news */
	$("#save_news_comment").live('click', function(){
		$.post( '/ajax/news/comment', {id:$('#id').val(),reload:$('#reload').val(), comment:$('#comment').val()},
		function(html) {
			$("#content_overlay div.contentWrap").html(html);
		});
	});

	/* Directory entry comments */
	$('.directory .comment').live('mousedown', function(){
		var id_array = $('.directory .comment').attr('id').split('_');
		var id = id_array[1];
		$(this).overlay({
			target: '#content_overlay',
			effect: 'apple',
			oneInstance: true,
			closeOnClick: false,
			onBeforeLoad: function() {
				var wrap = this.getOverlay().find(".contentWrap");
				wrap.load('/ajax/directory/entrycomment/'+id);
			},
			onClose: function(html) {
				$.ajax({
					async: false,
					url:"/ajax/directory/entrycomment",
					type: "POST",
					data: ({id: id,comment:1}),
					dataType: "html",
					success: function(html){
					$('.directory .comments').replaceWith(html);
				}
				});
			}
		});
	});

	/* Save comment for directory entry */
	$("#save_entry_comment").live('click', function(){
		$.post( '/ajax/directory/entrycomment', {id:$('#id').val(),reload:$('#reload').val(), comment:$('#comment').val()},
		function(html) {
			$("#content_overlay div.contentWrap").html(html);
		});
	});
	
	/* Ranking Search Options */
	$('#ranking_options_button').click(function(){
		if($('#ranking_search_options').css('display') == 'none'){
			$('#ranking_search_options').slideDown();
			$('#ranking_options_button').text($('#ranking_options_button').text().replace('[+]','[-]'));
		} else {
			$('#ranking_search_options').slideUp();
			$('#ranking_options_button').text($('#ranking_options_button').text().replace('[-]','[+]'));
		}
	});
	
	/* Print button */
	$("#print_button").click(function(){
    	$('#'+$(this).attr('name')).printArea({mode: "popup"});
	});
	
	/* Donations */
	if($('#addDonation').length){
		$( ".datepicker" ).datepicker({ dateFormat: 'dd.mm.yy' });
		$('#addDonation').validationEngine();
	}
	
	/*
	 * Plants Map
	 */
	if($('#directory_map #map').length){
			starte(8);
			$('#maplinks').click(function(){ return false; });
	}

});
