// JavaScript Document
$(document).ready(function() {

	//$('#navigation ul.leftside li:first').addClass('first');
	$('#navigation ul.leftside li:last').addClass('last');

	$('.t-clickable').click(function() {
		var parent = $(this).parent();
		if(parent.hasClass('open')) {
			parent.removeClass('open').addClass('close');
		} else {
			parent.removeClass('close').addClass('open');
		}
	});

	$(".colorbox").colorbox({width:"100%", height:"100%", iframe:true});
	
	$(".colorbox_geo").colorbox();
	$(".colorbox_inline").colorbox({inline: true});

	$(".videocontrol").click(function() {
		var player = $(this).nextAll('.videoplayer').children('video');
		$(this).hide();
		$(player).parent().show();
		$(player).mediaelementplayer({
			success: function(mediaElement, domObject) {
				mediaElement.play();
			}
		});
		return false;
	});



    $(".audioprobe").click(function(){
		audioprobeClick();
		return false;
    });

	/*
	$('.checkbox_alle_faecher').change(function(){
		if($(this).is(':checked')) {
			$('.checkbox_fach').attr('checked', 'checked');
		} else {
			$('.checkbox_fach').attr('checked', '');
		}
	});

	$('.checkbox_fach').change(function(){
		if(!$(this).is(':checked')) {
			$('.checkbox_alle_faecher').attr('checked', '');
		}
	});
	*/
	$('a.twitter').click(function() {
		open($(this).attr('href'), "_blank", "innerHeight=370, innerWidth=550, resizable=no, menubar=no, location=no");
		return false;
	});

	$('a.facebook').click(function() {
		open($(this).attr('href'), "_blank", "innerHeight=370, innerWidth=550, resizable=no, menubar=no, location=no");
		return false;
	});

    /* Lernorte JS - Filter */
    if($("#filter1-custom").get(0)){
        $("#filter1-custom").live("change", function(){
            $("#filter2-custom").children("option[value!='']").remove();
            var _value = $(this).get(0).value;
			
			// Setzen der Überschrift abhängig vom Kriterium
			var _headline;
			if (_value == '') {
				_headline = 'Ergebnisse deutschlandweit';
			} else {
				_headline = 'Ergebnisse in ' + $(':selected', this).text();
			}
			$('.lernorte-headline').text(_headline);
			// Ende

            if(_value != null && _value.length > 0){
                url = "/lernorte/filter/";
                _filterinputvalue = $("#filterinput").attr("value");
                params = {type:$(this).attr("class"), value:_value,filterinputvalue:_filterinputvalue}

                $.getJSON(url,params,
    			  function(data){
    			      if(data != null){
				  if (data['content'].length > 1) {
				      $("#filter2-custom").empty().append("<option value=\"\">bitte ausw&auml;hlen...</option>");
				  } else {
				      $("#filter2-custom").empty();
				  }
				  $(data['content']).each(function(){
				      $("#filter2-custom").append("<option value=\""+this['value']+"\">"+this['content']+"</option>");
				  });
				  $("#filter2-container").css('display', 'inline');
                              } else {
				  $("#filter2-container").hide();
				  $("#filter2-custom").empty();
				  //$("#filter2-custom").empty().append("<option selected value=\"\">Kein Thema</option>");
			      }
			  });
            } else {
		$("#filter2-container").hide();
	    }
        });

        $("#filter1-custom").live("change", function(){
            var _value = $(this).get(0).value;
            var _name = "inp"+$(this).attr("name");
            $("input[name='"+_name+"']").parent().show();
            if(_value.length > 0 && _value != ''){
                $("input[name='"+_name+"'][value!='"+_value+"']").parent().hide();
            }
        });

        $("#filter2-custom").live("change", function(){
            var _value = $(this).get(0).value;
            var _name = "inp"+$(this).attr("name");
			var _parent = $("select#filter1-custom option:selected").val();
			if(_value.length == 0 && _value == ''){
				$("input[name='"+_name+"']").parent().hide();
					$("input[name='inpfilter1'][value='"+_parent+"']").parent().show();
			} else {
				$("input[name='"+_name+"']").parent().show();
				if(_value.length > 0 && _value != ''){
					$("input[name='"+_name+"'][value!='"+_value+"']").parent().hide();
				}
			}
			
			// Setzen der Überschrift abhängig vom Kriterium
			var _headline;
			if (_value == '') {
				_headline = 'Ergebnisse in ' + $('#filter1-custom :selected').text();
			} else {
				_headline = 'Ergebnisse in ' + $(':selected', this).text();
			}
			$('.lernorte-headline').text(_headline);
			// Ende
		});
    }

	/* FINDE Premium Abo Fachzeitschrift-Filter */
    if($("#fachzeitschrift").get(0)){
        $("#fachzeitschrift").live("change", function(){
            $("#abotype").children("option[value!='0']").remove();
			$('strong.aboswitchitems').remove();
			$("#praemie").children("option[value!='0']").remove();
			$('div.aboswitchitems').remove();

            var _value = $('#fachzeitschrift > option:selected').attr('site');
            
            var zielgruppen_AIM_abos = new Array();
            zielgruppen_AIM_abos['Lehrerinnen und Lehrer']      = 'OAEN2080';
            zielgruppen_AIM_abos['Studierende und Referendare'] = 'OAEN2080';
            zielgruppen_AIM_abos['Schulen und Institutionen']   = 'OASN2080';
            
			$("#loading").ajaxStart(function(){
			   	$(this).show();
			 }).ajaxStop(function(){
			 	$(this).hide();
			 });

			if(_value != null && _value.length > 0){
                url = "/abo/get.Ajax.Abo.Zielgruppe.From.Site/";
                params = {site:_value};

                $.getJSON(url,params,
    			  function(data){
    			      if(data != null){
						  $(data).each(function(i, e){
							  item_nr = i;
							  item_nr++;
							  $("#abotype").append('<option rel="'+zielgruppen_AIM_abos[e.zielgruppe]+'" title="item'+item_nr+'" value="'+e.zielgruppe+'">'+e.zielgruppe+'</option>');
							  $('#versandkosten').text(e.versandkosten);
							  _strong =  '<strong rel="item'+item_nr+'" preis_euro_de="'+e.preis_euro_de+'" preis_euro_at="'+e.preis_euro_at+'" preis_chf_ch="'+e.preis_chf_ch+'" class="aboswitchitems item'+item_nr+'" style="display: none;">'+e.preis_euro_de+' € (D), '+e.preis_euro_at+' € (A), '+e.preis_chf_ch+' CHF</strong>';
							  $(_strong).insertAfter($('#abotype_br'));
						  });
                  	  /* Jetzt haben wie die Zielgruppen ermittelt und angezeigt, jetzt fehlen noch die Prämien */
					  render_praemienoptions(_value);
					  }
			  });
            }
        });
		function render_praemienoptions(_site) {
			if(_site != null && _site.length > 0){
				url = "/abo/get.Ajax.Abo.Praemien.From.Site/";
                params = {site:_site};

                $.getJSON(url,params,
    			  function(data){
    			      if(data != null){
						  $(data).each(function(i, e){
							  console.log(e);
							  item_nr = i;
							  item_nr++;
							  titel = e.titel != '' ? e.titel : '';
							  beschreibung = (e.beschreibung) ? e.beschreibung : '';
							  imgsrc = getPraemienBild(e.praemie_artID, 110);
							  $("#praemie").append('<option title="item'+item_nr+'" rel="'+e.artID+'" value="'+e.titel+'">'+e.titel+'</option>');
							  _div =  '<div class="aboswitchitems item'+item_nr+'" style="display: none;">\
											<h4>'+titel+'</h4>\
											<img class="" alt="" src="'+ imgsrc +'" />\
											<p>\
												'+beschreibung+'\
											</p>\
										</div>';
							  $(_div).insertAfter($('#praemie'));
						  });

					  }
			  });
            }
		}

		function getPraemienBild(artID, breite) {
			if(artID != null){
				url = "/abo/get.Ajax.Praemien.Cover/";
                params = {artID:artID, breite:breite, site:$('#site').val()};

				$.ajax({
				  type: "GET",
				  async: false,
				  url: url,
				  data: params,
				  success: function(data){
					imgsrc=data;
				  }
				});
				return imgsrc;
			}
		}
    }
	
	/* Kombi-Abo Zeitschrift-Auswahl */
	
	if ($('#abotype option:selected').val() != '0' && $('#kombi_fz').length > 0) print_kombi_fz_pulldown();
	
	function print_kombi_fz_pulldown() {
		$("#kombi_fz").children("option[value!='0']").remove();
		$('strong.kombiaboswitchitems').remove();
		var _kombityp = $("#kombityp").val();
        var _value = $('#abotype option:selected').val();
		var _sessionvalue = $('#kombi_fz_name').val();
		url = '/abo/get.Ajax.Kombi.Fz/';
		params = {zielgruppe:_value, site:$('#site').val(), kombityp: _kombityp};
		$.getJSON(url,params,
			  function(data){
				  if(data != null){
					  $(data).each(function(i, e){
						  
                          if (e.titel == _sessionvalue && 1==2) { _selected = 'selected'; } else _selected = '';
						  item_nr = i;
						  item_nr++;
						  $("#kombi_fz").append('<option '+_selected+' reiheID="'+$('#site').val()+'" title="item'+item_nr+'" value="'+e.fachzeitschrift_reiheID+'">'+e.titel+'</option>');
						  _strong =  '<strong rel="item'+item_nr+'" preis_kombi_euro_de="'+e.preis_euro_de+'" preis_kombi_euro_at="'+e.preis_euro_at+'" preis_kombi_chf_ch="'+e.preis_chf_ch+'" class="kombiaboswitchitems item'+item_nr+'" style="display: none;">€ '+formatPrice(e.preis_euro_de)+' (D), € '+formatPrice(e.preis_euro_at)+' (A), CHF '+formatPrice(e.preis_chf_ch)+' (CH)</strong>';
						  $(_strong).insertAfter($('#kombiabo_br'));
					  });
				  }
		  });
	}
	
	if($("#kombi_fz").get(0)){
		$("#loading").ajaxStart(function(){
			$(this).show();
		 }).ajaxStop(function(){
			$(this).hide();
		 });
		
		$('#abotype').live('change', function() {
			print_kombi_fz_pulldown();
		});
	}
    
    $("#kombi_fz").live('change', function() {    
       kombi_reiheid = $('#kombi_fz option:selected').attr('reiheid');
       //alert(kombi_reiheid);
       $("#kombi_reiheid").val(kombi_reiheid);
    });
    
    
	/*Abo Bestellübersicht drucken */
	
	$('.printer').click(function() {
		form = $('#aboFormular').clone();
		form.find('a').remove();
		//$('<br>').insertAfter(form.find('span.rightside'));
		form.printElement();
	});	
	

	/*
	if($("select.switch").get(0)){
        $("select.switch").each(function(){
           $(this).nextAll(".aboswitchitems").hide();
           var item = $(this).children("option:selected").get(0).title;
           if(item.length > 0){
               $(this).nextAll("."+item).show();
               var id = $(this).attr("id");
               $("h3."+id).html("").html($(this).children("option:selected").text());
               if(id == 'abotype'){
                     var text = $(this).nextAll("."+item).text();
                    $("h2."+id).html("").html(text);
               }
           }
        });

        $("select.switch").live('change', function(){

           $(this).nextAll(".aboswitchitems").hide();
            var item = $(this).children("option:selected").get(0).title;
			console.log(item);
           if(item.length > 0){
                $(this).nextAll("."+item).show();
                var id = $(this).attr("id");
               $("h3."+id).html("").html($(this).children("option:selected").text());
               if(id == 'abotype'){
                    var text = $(this).nextAll("."+item).text();
                    $("h2."+id).html("").html(text);

               }
           }
        });
     }
	*/

	$('.togglejivz').click(function(){
		$(this).hide();
		if($(this).attr('rel') == 'collapse'){
			$(this).parent().find(".togglejivz[rel='close']").show();
			$(this).parent().find('.threadblockjivz').show();
		} else {
			$(this).parent().find(".togglejivz[rel='collapse']").show();
			$(this).parent().find('.threadblockjivz').hide();
		}
		return false;
	});

	$('.change-submit').change(function() {
		$(this).closest('form').submit();
	});
	
	/** Neues Toggling */
	$('.toggle-both').click(function() {
		var container = $(this).closest('.toggle-container');
		if(container.hasClass('toggle-opened')) {
			container.find('.toggle-long').hide();
			container.find('.toggle-short').show();
			container.addClass('toggle-closed').removeClass('toggle-opened');
		} else {
			container.find('.toggle-short').hide();
			container.find('.toggle-long').show();
			container.addClass('toggle-opened').removeClass('toggle-closed');		
		}
		return false;
	});
	
	$('.toggle-more').click(function() {
		var container = $(this).closest('.toggle-container');
		container.find('.toggle-short').hide();
		container.find('.toggle-long').show();
		container.addClass('toggle-opened').removeClass('toggle-closed');
		return false;
	});
	
	$('.toggle-less').click(function() {
		var container = $(this).closest('.toggle-container');
		container.find('.toggle-long').hide();
		container.find('.toggle-short').show();
		container.addClass('toggle-closed').removeClass('toggle-opened');
		return false;
	});

	//$("select.switch").die('change');
    $("#abotype.switch, #kombi_fz.switch").live('change', function(){
		change_prices($(this));
	});
    
    /*
    $("#praemie").change(function(){
       alert('ok');
       $(this).nextAll(".aboswitchitems").hide();
        var item = $(this).children("option:selected").get(0).title;
       if(item.length > 0){
            $(this).nextAll("."+item).show();
            var id = $(this).attr("id");
           $("h3."+id).html("").html($(this).children("option:selected").text());
           if(id == 'abotype'){
                var text = $(this).nextAll("."+item).text();
                $("h2."+id).html("").html(text);

           }
       }
    });
    */
    
    function change_prices(select) {
        select.nextAll(".kombiaboswitchitems").hide();
        select.nextAll(".aboswitchitems").hide();
		var main_item = $('#abotype').children("option:selected").get(0).title;
		var item = select.children("option:selected").get(0).title;
        select.nextAll("."+item).show();
		var id = select.attr("id");
		var $preis_kombi_euro_de = 0;
		var $preis_kombi_euro_at = 0;
		var $preis_kombi_chf_ch = 0;
		var $preis_gesamt_euro_de = 0;
		var $preis_gesamt_euro_at = 0;
		var $preis_gesamt_chf_ch = 0;
		if (id == 'abotype' || id == 'kombi_fz') {
			preis_item = $('strong.aboswitchitems.'+main_item);
			$preis_euro_de = parseFloat($(preis_item).attr("preis_euro_de"));
			$preis_euro_at = parseFloat($(preis_item).attr("preis_euro_at"));
			$preis_chf_ch = parseFloat($(preis_item).attr("preis_chf_ch"));
			$('#preis_haupt_euro_de').val($preis_euro_de);
			$('#preis_haupt_euro_at').val($preis_euro_at);
			$('#preis_haupt_chf_ch').val($preis_chf_ch);
			if ($('#kombi_fz').length == 1 && $('#kombi_fz').is(':visible')) {
				preis_kombi_item = $('strong.kombiaboswitchitems.'+item);
				$preis_kombi_euro_de = parseFloat($(preis_kombi_item).attr("preis_kombi_euro_de"));
				$preis_kombi_euro_at = parseFloat($(preis_kombi_item).attr("preis_kombi_euro_at"));
				$preis_kombi_chf_ch = parseFloat($(preis_kombi_item).attr("preis_kombi_chf_ch"));
				$('#preis_kombi_euro_de').val($preis_kombi_euro_de);
				$('#preis_kombi_euro_at').val($preis_kombi_euro_at);
				$('#preis_kombi_chf_ch').val($preis_kombi_chf_ch);
			}
			$preis_gesamt_euro_de = parseFloat($preis_euro_de) + parseFloat($preis_kombi_euro_de);
			$preis_gesamt_euro_at = parseFloat($preis_euro_at) + parseFloat($preis_kombi_euro_at);
			$preis_gesamt_chf_ch = parseFloat($preis_chf_ch) + parseFloat($preis_kombi_chf_ch);
			$('#preis_gesamt_euro_de').val($preis_gesamt_euro_de);
			$('#preis_gesamt_euro_at').val($preis_gesamt_euro_at);
			$('#preis_gesamt_chf_ch').val($preis_gesamt_chf_ch);
			//alert($preis_euro_de + ' + ' + $preis_kombi_euro_de + ' = ' + $preis_gesamt_euro_de);
		if (!isNaN($preis_gesamt_euro_de)) $('h2.abotype').text('€ '+formatPrice($preis_gesamt_euro_de) + ' (D), € ' + formatPrice($preis_gesamt_euro_at) + ' (A), CHF ' + formatPrice($preis_gesamt_chf_ch) + ' (CH)');
		}
    }
    
    
    if ($('#abotype').length > 0 && $('#abotyp_hidden_input').val() == 'einfach') {
        $("#abotype").attr('selectedIndex', 1);
        $('h3.abotype').text($("#abotype").val());
        change_prices($('#abotype'));
        print_kombi_fz_pulldown();
    }
    
    
    function generate_aim_link() {
        var p_id = $('#abotype > option:selected').attr('rel');
        var reiheID = $('#fachzeitschrift').length > 0 ? $('#fachzeitschrift > option:selected').attr('site') : $('#site').val();
        var artID = $('#praemie > option:selected').attr('rel');
        var aim_kauf_baselink = 'https://secure.schulbuchzentrum-online.de/aim/pda/buy.php?';
        $('#btn-step').attr('href', aim_kauf_baselink+'p[p_id]='+p_id+'&p[salesp]='+reiheID+'-'+artID).removeAttr('onclick');
    }
    
    function clear_all_prices() {
        $('#preis_haupt_euro_de').val("");
        $('#preis_haupt_euro_at').val("");
		$('#preis_haupt_chf_ch').val("");
        $('#preis_gesamt_euro_de').val("");
        $('#preis_gesamt_euro_at').val("");
	    $('#preis_gesamt_chf_ch').val("");
        $('h2.abotype').text("");
        $('h3.kombi_fz').text("Abonnement bereits vorhanden");
    }
    
    if ($('#abotyp_hidden_input').length > 0 && $('#abotyp_hidden_input').val() == 'premium') {
        generate_aim_link();
        $("select.switch").live('change', function(){
            generate_aim_link();    
        });
    }
    
    $('#user_has_abo, #user_has_no_abo').change(function() {
        refreshKombiPulldown();
        $("#abotype").attr('selectedIndex', 0);
    });
    
    
    if ($('#user_already_has_abo').val() == 1) {
        $('#user_has_abo').attr('checked', 'checked');
        refreshKombiPulldown();
    }
    
    function refreshKombiPulldown() {
        
        $('h3.kombi_fz').text("");
        $('#kombi_fz').toggleClass('required').toggle();
        $('#kombi_fz').prev().toggle();
        
        var site = getUrlVars()["site"];
        var _schulkombi = $('#schulkombi').val();
        
        if (_schulkombi == 1) {
            _kombiabotyp = 'schulkombi';
            _einfachabotyp = 'einfach';
        } else {
            _kombiabotyp = 'kombi';
            _einfachabotyp = 'aboplus';
        }

        var url = '/abo/get.Ajax.Typ.Abo/';
        var params = {};
        formcheck('.required');
        if ($('#user_has_abo').is(':checked')) {
            params = { abotyp: _kombiabotyp, site: site, kombityp: _kombiabotyp};
            $('.kombiaboswitchitems').hide();
            $('.pruefhinweis').show(); 
        } else {
            params = { abotyp: _einfachabotyp, site: site, kombityp: _kombiabotyp};
            $('.pruefhinweis').hide();
        }
        $('#abotyp_box').load(url, params);
        clear_all_prices();
    }

});

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function formatPrice(value) {

	arr = String(value).split(".");
	
	if (arr.length == 2) {
		euro = arr[0];
		cent = String(arr[1]);
		if (cent.length == 1) {
			cent += '0';
		}
	} else {
		euro = arr;
		cent = '00';
	}
	if (cent.length > 2) {
	   cent = cent.substring(0, 2);
	}
    value = euro+','+cent;
    
return value;
}

function loadWeitersagenCode() {
	Recaptcha.create("6LeBccQSAAAAAO5ArfHkPMqhYoGU6LnFTjsGbsJk","weitersagen_code", {theme: "clean", lang: "de", callback: Recaptcha.focus_response_field});
}

function submitWeitersagen() {
	var url = $('#supporterFormular').attr("action");
	var params = $('#supporterFormular').serialize();
	
	params += "&url=" + $(location).attr('href');
	
	$('#supporterFormular_error').hide();
	$.postJSON(url, params,
		function(data) {
			if(data['sent'] == 'OK'){
			   $("#supporterFormular").hide();
			   $("#weitersagen_success").show();
			} else {
				if(data['sent'] == 'DATA_FAIL') {
					$('#supporterFormular_error').text('Bitte füllen Sie alle benötigten Felder aus und geben Sie den Sicherheits-Code erneut ein.');
					loadWeitersagenCode();
				} else if(data['sent'] == 'MAIL_FAIL') {
					$('#supporterFormular_error').text('Bitte versuchen Sie es später erneut.');	
					loadWeitersagenCode();
				} else {
					$('#supporterFormular_error').text('Allgemeiner Fehler.');	
				}
				$('#supporterFormular_error').show();
			}
	});
	return false;
}

var audioPlayer = new Array();
var audioPlayerControl = new Array();

function audioprobePauseAll() {
	for(var index in audioPlayer) {
		audioPlayer[index].pause();
		$(audioPlayerControl[index]).removeClass('paused').addClass('play');
	}
}

function audioprobeClick() {
	audioPlayer = new Array();
	audioPlayerControl = new Array();
	$('#fancybox .playercontrol').each(function() {
		var control = this;
		$(this).parent().find('audio').mediaelementplayer({
			audioWidth: 0,
			audioHeight: 0,
			features: [],
			success: function(mediaElement, domObject) {
				audioPlayer.push(mediaElement);
				audioPlayerControl.push(control);
				$(control).click(function(){
					if(mediaElement.paused) {
						audioprobePauseAll();
						$(control).removeClass('play').addClass('paused');
						mediaElement.play();
					} else {
						$(control).removeClass('paused').addClass('play');
						mediaElement.pause();
					}
				});
				mediaElement.addEventListener('timeupdate', function(e) {
					var time = Math.round(mediaElement.currentTime);
					var duration = Math.round(mediaElement.duration);
					$(control).nextAll('.played').html(formatAudioTime(time));
				}, false);

			}
		})
	});
}

function formatAudioTime(secs) {
	var minutes = Math.floor(secs / 60);
	var seconds = secs - minutes * 60;
	var pad = seconds < 10 ? '0' : '';
	return minutes + ":" + pad + seconds;
}
