/* Runs when the DOM is loaded. */
$(document).ready(function() {

	initSelectVote();
	initVotingForm();
	initGenres();

	$('nav').has('ul.sub').addClass("with_sub");

	$('li.award').each(function() {
		var width = $(this).width();
		$(this).width(width + 2);
	})

	$('nav .sub li').each(function() {
		var width = $(this).width();
		$(this).width((width + 2));
	})

	$('nav li.inactive a img').each(function() {
		var no = $(this).attr("src");
		var noSplit = no.split(".");
		var act = "" + noSplit[0] + "_active." + noSplit[1] + "";

		$(this).attr("mover", act);

		$(this).mouseover(function() {
			$(this).attr("src", $(this).attr("mover"));
		});

		$(this).mouseout(function() {
			$(this).attr("src", no);
		});
	})

	$('a#imagelink').each(function() {
		$(this).removeAttr("class");
	})
	// TODO fix it in typo3
	// just a temporary solution

	$("h2").each(function() {
		if($(this).html() == "") {
			$(this).remove();
		}
	})

	$(".pdflists a").each(function() {
		$(this).attr("target", "_blank");
	})
	// refresh captcha
	$('a#refresh').click(function() {
		change_captcha();
	});
	// Countdown
	// $("#countdown").countdown({
		// date : "january 20, 2012", //Counting to a date
		// offset : 1,
		// hoursOnly : false,
		// onComplete : function(event) {
			// $(".notice").remove();
			// $("a.button:contains('Jetzt voten!')").remove();
			// $("a.button:contains('Jetzt Voten!')").remove();
		// },
		// onPause : function(event, timer) {
			// $(this).html("Pause");
		// },
		// onResume : function(event) {
			// $(this).html("Resumed");
		// },
		// leadingZero : false,
		// htmlTemplate : "%{d}"
	// });
// 
	// var cd = $("#countdown").text();
	// if(cd == "1"){
	 // $("#dayOrDays").text("Tag");
	// } else {
	  // $("#dayOrDays").text("Tage");
	// }
// 
	// if(parseInt(cd) <= 0){
		// $(".notice").remove();
		// $("a.button:contains('Jetzt voten!')").remove();
		// $("a.button:contains('Jetzt Voten!')").remove();
	// }
		$("a.button:contains('Jetzt voten!')").remove();
		$("a.button:contains('Jetzt Voten!')").remove();
		
	// order top items alphabetical
	$('ul.listing li').sortElements(function(a, b) {
		return $(a).attr("title") > $(b).attr("title") ? 1 : -1;
	});
	
	// remove double items from overwiew-all list
	var listmap = {};
	$("ul.opts li").each(function(){
	    var value = $(this).attr("title");
	    if (listmap[value] == null){
	        listmap[value] = true;
	    } else {
	        $(this).remove();
	    }
	});
	
	// remove double items from voting list
	var votemap = {};
	$("div#form_box ul#votings > li").each(function(){
	    var value = $(this).attr("title");
	    if (votemap[value] == null){
	        votemap[value] = true;
	    } else {
	        $(this).remove();
	    }
	});
	
	$("p.bodytext").each(function() {
		if($(this).html() == "&nbsp;") {
			$(this).remove();
		}
	});
	$("#vintro").html($("#votingintro").html())
	$("#ftext").html($("#formtext").html())
	
	initFixedScroll();
});
// Bind to scroll, for positioning of the voting form heading & sidebar.
function initFixedScroll() {
	var voting_aside = $('#voting_aside');
	var voting_head = $('#form_box');

	if(voting_aside.length) {
		var elementAsideOffset = (voting_aside.offset().top) - 25;
		var elementHeadOffset = (voting_head.offset().top) - 25;

		$(window).scroll(function() {
			var scrollOffset = $(window).scrollTop();

			if(scrollOffset >= elementAsideOffset) {
				voting_aside.addClass('fixed');
			} else {
				voting_aside.removeClass('fixed');
			}

			if(scrollOffset >= elementHeadOffset) {
				voting_head.addClass('fixed');
			} else {
				voting_head.removeClass('fixed');
			}
		});
	}
}

// Initialize voting form (where stars can be selected).
function initSelectVote() {
	var voting_block = $('.voting_block');

	if(!voting_block.length) {
		return false;
	}

	$('.error_msg').hide();
	$('.error_add').hide();

	voting_block.find('li').each(function() {
		var label = $(this).find('h3').html();
		//var label = $(this).find('h3 a').text();
		var rate_show = $(this).find('.rate_show');

		for(var i = 0; i <= 5; i++) {
			var li = $('<li></li>').appendTo(rate_show);
			var a = $('<a href="#" class="' + (i == 0 ? 'active' : '') + ' stars_' + i + '" data-rating="' + i + '">' + i + ' Stern</a>').appendTo(li);

			a.click(function() {
				var rating = $(this).data('rating');
				var cur_rating = rate_show.find('.active').data('rating');

				if(cur_rating > 0) {
					$('.voting_block .stars_' + cur_rating).removeClass('active').show();
				}
				$('.star_box .s' + cur_rating).removeAttr('style');
				if(cur_rating == 1){
					$('.star_box .s' + cur_rating).html('Bitte '+ cur_rating +' Stern vergeben');
				} else {
					$('.star_box .s' + cur_rating).html('Bitte '+ cur_rating +' Sterne vergeben');
				}
				$('.star_box .star_' + cur_rating).removeClass('active');
				//$('#voting_form input[name="stars_' + cur_rating + '"]').val('');
				$('#voting_form input[vote="' + cur_rating + '"]').val('');

				if(rating != 0) {
					rate_show.find('a').removeClass('active');
					$('.voting_block .stars_' + rating).removeClass('active').hide();
					//$('.star_box .s' + rating).html(label).attr("style","color:#3AB8FF");
					$('.star_box .s' + rating).html(label);
					$('.star_box .star_' + rating).addClass('active');
					//$('#voting_form input[name="stars_' + rating + '"]').val(rate_show.closest('li').data('show-id'));
					$('#voting_form input[vote="' + rating + '"]').attr('name', 'tx_skymiraawardwebvoting_channelvoting[channel][id][' + rate_show.closest('li').data('show-id') + '][votes]').val(rating);
				}

				$(this).addClass('active').show();

				return false;
			});
		}
	});
}

function submitVotes() {
	var has_errors = false;

	$('#voting_form input').each(function() {
		if(!$(this).val() || $(this).val() == '') {
			$('.error_msg').show();
			has_errors = true;
			return false;
		}
	});
	if(!has_errors) {
		$('#form_1').hide();
		$('.error_msg').hide();
		$('#voting_user_data').show();
	}
}

function initVotingForm() {
	$('#voting_user_data .error_msg').hide();

	// Custom radio's
	var radios = $('#voting_user_data .field.radio input');
	radios.each(function() {
		var input = $(this);
		var radio = $(this).hide();
		var link = $('<a href="#" class="faux_radio ' + ($(this).is(':checked') ? 'active' : '') + '"></a>').insertAfter($(this));
		link.click(function() {
			$('#voting_user_data .field.radio .faux_radio').removeClass('active');
			$('#voting_user_data .field.radio input').attr('checked', false);
			$(this).addClass('active');
			input.attr('checked', true);
			return false;
		});
	});
	// Custom checkboxes
	var checkboxes = $('#voting_user_data .field.checkbox .field input');
	checkboxes.each(function() {
		var input = $(this);
		var checkbox = $(this).hide();
		var link = $('<a href="#" class="faux_checkbox ' + ($(this).is(':checked') ? 'active' : '') + '"></a>').insertAfter($(this));
		link.click(function() {
			if(input.is(':checked')) {
				$(this).removeClass('active');
				input.attr('checked', false);
			} else {
				$(this).addClass('active');
				input.attr('checked', true);
			}
			return false;
		});
	});

	$('#submit_button').click(function() {
		var has_errors = false;

		$('#voting_user_data input[type="text"]').each(function() {
			if($(this).val() == '') {
				has_errors = true;
				$(this).closest('.field').addClass('error');
			} else {
				$(this).closest('.field').removeClass('error');
			}
		});
		var terms = $('#voting_user_data input[name="tx_skymiraawardwebvoting_channelvoting[users][tac]"]');
		if(terms.is(':checked')) {
			terms.closest('.field').removeClass('error');
		} else {
			has_errors = true;
			terms.closest('.field').addClass('error');
		}

		if(!has_errors) {
			$('#voting_user_data .error_msg').hide();
			$(".ajax-loader").fadeIn('slow');
			$(".ajax-loader").ajaxStop(function() {
				$(this).fadeOut('slow');
			});
			var postaction = $("#voting_user_data").attr("action");
			$.post(postaction + "&type=99", $("#voting_user_data").serialize(), function(data) {

				var thiserrorcount = 0;
				var errormessages = [];
				for(i in data) {
					if(data[i].errorcount == 1) {
						thiserrorcount = thiserrorcount + 1
						errormessages.push(data[i].message)
					}
				}

				if(thiserrorcount > 0) {
					$(".error_add").show();
					$.each(errormessages, function() {
						//alert(this +" - "+ thiserrorcount);
						$(".error_add").html("");
						$(".error_add").append('<p>' + this + '</p>');
					});
				} else {
					document.getElementById('captcha').src = "/captcha/get_captcha.php?rnd=" + Math.random();
					window.location = "/voten-gewinnen/lieblingsender-waehlen/teilnahmebestaetigung/"
					$(".error_add").hide();
					$(".error_add").html("");
				}

			});
			return true;
		}
		$(".error_add").html("");
		$('#voting_user_data .error_msg').show();

		return false;
	});

	$('.navi_category a').click(function() {
		var id = $(this).attr('href');
		var el = $(id);

		if(el.length) {
			$(window).scrollTop(el.offset().top - 80);
		}

		return false;
	});

	$('#backbutton').click(function() {
		$('#voting_user_data').hide();
		$('.error_msg').hide();
		$('#form_1').show();
		return false;
	});
}

function change_captcha() {
	document.getElementById('captcha').src = "/captcha/get_captcha.php?rnd=" + Math.random();
}

function initGenres() {
	var el = $('#vote_favorite');

	if(!el.length) {
		return false;
	}

	var programs = el.find('.opts li');

	el.find('.navigation a').click(function() {
		var genre = $(this).data('genre');
		el.find('.navigation li').removeClass('active');
		$(this).parent().addClass('active');

		if(!genre) {
			programs.show();
		} else {
			programs.hide().filter('[data-genre="' + genre + '"]').show();
		}

		return false;
	});
}

