// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

(function(){

$(function(){
  initCycle();
  initVideoRating();
  initCommentRating();
  initPolll();
  initCommenting();
  initResizeGmpPlayer();
  initAjaxCommentPagination();
  initBoxHover();
  initVignette();
  initTopTenImgHover();
  initLayoutSupport();
  initArchive();
});

// all the hacks and tunings css cannot do - "js will save us all" e. meyer

function initLayoutSupport(){
  $(".box.plain_header h2.post").each(function(){
      if($(this).find("small.invert_tag").length){
        var width = $(this).find("small.invert_tag")[0].clientWidth;
        width = width + 5;
        $(this).css("padding-right",width+"px");
      };
  });
};

// Top Ten Image Hover Border

function initTopTenImgHover(){
  var imgsrc;
  $("#top_ten_video_parts ol li a.image_link").each(function(){
    imgsrc = $(this).find("img:first")[0].src;
    $(this).find("img:first").remove(); 
    $(this).css("background-image","url("+imgsrc+")");
  });
};

// Vignette Effect

function initVignette() {
  $(".box.big_picture").each(function(){
    createVignette(this);
  });
}

function createVignette(object) {
  var left, top, href;
  left = $(object).css("padding-left");
  href = $(object).find("a.img_link:first")[0].href
  
  if(!$(object).find("a.vignette:first").length) $(object).append('<a class="vignette"></a>');
  
  if($(object).find("h4").length) {
    top = $(object).find("a.img_link img:first")[0].offsetTop + "px";
  } else {
    top = $(object).css("padding-top");
  }
  
  if($(object).find("a.vignette:first").length) {
    var $vignette = $(object).find("a.vignette:first");
    $vignette.css("top",top);
    $vignette.css("left",left);
    $vignette[0].href = href;
  }
}


// Box Hover Effect

function initBoxHover(){
  if(navigator.appVersion.indexOf("MSIE 6.") == -1) {
	    $(".box.big_picture").mouseover(function(element){
    		createVignette(this);
    		$(this).addClass("active");    		
    		/*
    		  var href = $(this).find("p.intro a:first")[0].href;
    		  $(this).find("*").click(function(){
          location.href = href;
    		  return false;
    		})*/
    	});
    	$(".box.big_picture").mouseout(function(element){
    	  createVignette(this);
    		$(this).removeClass("active");
    	});
  }
}

// image Cycling
function initCycle(){
  	$('#image_container').cycle({ 
      fx: 'scrollHorz',
      timeout: 0,
      speed: 250,
      before:  onBefore, 
      after:   onAfter,
      next: $(".next_page:eq(0), #image_container"),
      prev: $(".prev_page:eq(0)")
   });  
}

function onBefore(curr,next,opts) {
  var first = true;
  if (first) {
    var $slide = $(curr);
    $slide.hide()
    $slide.load(function(){
      var w = $slide.outerWidth();
      var h = $slide.outerHeight();
      $slide.css({
          marginTop: (419 - h) / 2,
          marginLeft: (742 - w) / 2
      });
    });
    first = false;
    $slide.show();
  };    
  $slide = $(next);
  w = $slide.outerWidth();
  h = $slide.outerHeight();
  $slide.css({
      marginTop: (419 - h) / 2,
      marginLeft: (742 - w) / 2
  });
};

function onAfter(currSlideElement, nextSlideElement, options, forwardFlag) {
  $('#img_caption').html(this.alt);
  var sts = this.id.split("_")[1] + "/" + $("#image_container img").length;
  $(".pag .invert_tag:eq(0)").html(sts);
  _reloadTracking();
}

function reloadIVW() {
  if( $("#ivw_pixel").length > 0){
    var IVW = $("#ivw_pixel").attr("src").split("?")[0];
    $("#ivw_pixel").remove();
    var t = "<img id=\"ivw_pixel\" src=\""+IVW+"?r="+escape(document.referrer)+"&d="+(Math.random()*100000)+"\" width=\"1\" height=\"1\" alt=\"szmtag\" />";
    $("body").append(t);
  }
};

function reloadOmniture(){
  if(typeof dispatcher != "undefined"){
    dispatcher.sendCall(); 
  }
}

function reloadGoogleAnalytics() {
  try {                       
    var pageTracker = _gat._getTracker("UA-9930738-4");
    pageTracker._trackPageview();
  } catch(err) {}
}  

// video rating
function initVideoRating(){
	if($('#video_rating').length > 0){
	  var initial_state = parseFloat( $("#video_rating").attr('rel') ).toFixed(1);
	  var url_path = jQuery.url.attr("path");	  
  	$('#video_rating').rater(url_path, {curvalue: initial_state });
  }
}

function initPolll() {
	if($(".box.survey a").attr("href") == undefined){return;}

  var poll_id   = $(".box.survey").attr("id");
  var poll_url  = $(".box.survey a").attr("href").split("&")[0];
  // return if not found
  if (typeof poll_url !== "string" & typeof poll_id !== "string"){return;};
    
  if (jQuery.cookie('voted') === poll_id) {
    $.ajax({
      type: "GET",
      url: poll_url,
      dataType: "json",
      success: function(json){ showResults(json); }
     });      
  };
  
  $(".box.survey a").bind("click", function(event){
    var url = $(this).attr("href");
    var el = this;
	
    $.ajax({
      type: "PUT",
      url: url,
      data: {},
      dataType: "json",
      success: function(json){
      var els = $(".box.survey a");
	    $.each(els, function(){
          var text = $(this).text();
          $(this).replaceWith("<span>" + text + "</span>");          
          $(".box.survey .result").css("background", "transparent");          
        });
        
        //$(".box.survey #choice_a_text .result p small").text(json.choice_a_count + " Stimmen für:");
        //$(".box.survey #choice_b_text .result p small").text(json.choice_b_count + " Stimmen für:");
        
        
        $("#choice_a_text .indicator").animate({"width": json.choice_a_percentage }, "slow");
        $("#choice_b_text .indicator").animate({"width": json.choice_b_percentage}, "slow");
        // IE6 doenst get height 100%
        if(navigator.appVersion.indexOf("MSIE 6.") != -1) $(".box.survey .indicator").each(function(){ $(this).height((this.parentNode.offsetHeight-6)+"px");});
        // find and save poll id
        jQuery.cookie('voted', poll_id);
      }       
     });     
    event.preventDefault();
  });
};

function showResults(json) {
  $(".box.survey a").each(function(){
    var text = $(this).text();
    $(this).replaceWith("<span>" + text + "</span>");          
    $(".box.survey .result").css("background", "transparent");          
  });
  
  $(".box.survey #choice_a_text .result p small").text(json.choice_a_percentage + $('.result p small')[0].innerHTML);
  $(".box.survey #choice_b_text .result p small").text(json.choice_b_percentage + $('.result p small')[1].innerHTML);
  
  $("#choice_a_text .indicator").animate({"width": json.choice_a_percentage }, "slow");
  $("#choice_b_text .indicator").animate({"width": json.choice_b_percentage}, "slow");
  // IE6 doenst get height 100%
  if(navigator.appVersion.indexOf("MSIE 6.") != -1) $(".box.survey .indicator").each(function(){ $(this).height((this.parentNode.offsetHeight-6)+"px");});
};

function initCommenting(){
	$(".commentform").bind("submit",function(event){
		var url = this.action;
		var form_data = $(this).serialize();
				
		$.ajax({
			type: "POST",
			url: $(this).attr('action'),
			data: form_data,
			dataType: "script",
			beforeSend: function(){
			  $(".commentform").addClass("loading");
			},
			success: function(){
			  _reloadTracking();
			  $(".commentform").removeClass("loading");
			},
			error: function(){
			  alert("Request failed, please reload the browser and try again.");
			}
		});
				
		event.preventDefault();
	});
}

function initCommentRating(){
  // einmal raten.
  // div ersetzen
  //
	$(".comment_box small a, a.missbrauch_melden").bind("click", function(event){
		var url = $(this).attr("href");
		var el = $(this);
		var link = this;
		$.ajax({
			type: "PUT",
			url: url,
			data: {},
			dataType:"json",
			beforeSend: function(){
			  el.parent("small").animate({"opacity":0});
			},
			success: function(json){			  
			  el.parent("small").animate({"opacity":1});
			  if(el[0].className == "missbrauch_melden"){
				  el.fadeOut("slow");
			    link.innerHTML = $(".rating_result span")[1].innerHTML;
			  }else{
			    el.parent("small")[0].innerHTML = $(".rating_result span")[0].innerHTML;
			  }
			},
			error: function(){
			  alert("Request failed, please reload the browser and try again.");
			}
		});
		event.preventDefault();
	});	
}

function initResizeGmpPlayer(){
	if($(".uma_player").children()[0] == undefined){return;}
	var url = location.toString();
	if(url.match(/posts/)){
	  $(".uma_player")[0].style.width = "593px";
		$(".uma_player").children()[0].style.width = "593px";
	}
}

function initAjaxCommentPagination(){
	$(".comment_pagination a").click(function(event){
		var el = this;
			$.ajax({
				type: "GET",
				url: el.href,
				data: {},
				dataType:"script",
				beforeSend: function(){
				  $(".comments").addClass("loading");
				},
				success: function(){
				  $(".comments").removeClass("loading");
				  initAjaxCommentPagination();
				  initCommentRating();
				  _reloadTracking();  
				  $('html,body').animate({ scrollTop:$('.comment_box').offset().top }, 'fast');
				}
			});
		event.preventDefault();
	});
};

function _reloadTracking() {
  reloadIVW();
  reloadOmniture();
  reloadGoogleAnalytics();
}

})();

function initArchive(){
  $(".archive_months").hide();
  $(".archive_months:first").show();
  $('.archive_year').click( function(event){
    $(".archive_months").hide();
    $( '#' + $(this).attr("id") + '_content' ).show();
    return false;
  });
};