//urlencode stuff
$.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;
  while(x<c.length){var m=r.exec(c.substr(x));
    if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length;
    }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);
    o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},
URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;
  while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);
  t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}
});

(function($) {
    
    $.fn.filestyle = function(options) {
                
        /* TODO: This should not override CSS. */
        var settings = {
            width : 250
        };
                
        if(options) {
            $.extend(settings, options);
        };
                        
        return this.each(function() {
            
            var self = this;
            var wrapper = $("<div>")
                            .css({
                                "width": settings.imagewidth + "px",
                                "height": settings.imageheight + "px",
                                "background": "url(" + settings.image + ") 0 0 no-repeat",
                                "background-position": "right",
                                "display": "inline",
                                "position": "absolute",
                                "overflow": "hidden"
                            });
                            
            var filename = $('<input class="file-name">')
                             .addClass($(self).attr("class"))
                             .css({
                                 "display": "inline",
                                 "width": settings.width + "px",
                                 "margin-right": "5px"
                             });

            $(self).before(filename);
            $(self).wrap(wrapper);

            $(self).css({
                        "position": "relative",
                        "height": settings.imageheight + "px",
                        "width": settings.width + "px",
                        "display": "inline",
                        "cursor": "pointer",
                        "opacity": "0.0"
                    });

            if ($.browser.mozilla) {
                if (/Win/.test(navigator.platform)) {
                    $(self).css("margin-left", "-142px");                    
                } else {
                    $(self).css("margin-left", "-168px");                    
                };
            } else {
                $(self).css("margin-left", settings.imagewidth - settings.width + "px");                
            };

            $(self).bind("change", function() {
                filename.val($(self).val());
            });
      
        });
        

    };
    
})(jQuery);

$(document).ready(function()
{
	//prepare video thickbox links
	$('a.video-thumb').click(function(){
		var id = $(this).attr("id");
		id = id.substr(id.indexOf("_") + 1);
		tb_show(this.title, '/ajax/videos/show/' + id + '/?height=490&width=615', false);
		this.blur();
		return false; 
	});
	
 $('#vote-video-info').show();
 
 $('div.video-vote b').each(function() {
 	var id = $(this).attr("id");
 id = id.substr(id.indexOf("_") + 1);
 
 	$(this).wrap("<a class='button-link ajax' href='/videos/vote/" + id + "'></a>");
 });
 
	preview_images = new Array();
	settings = new Object({delay:1000, fadeDelay:250});

  $('a.video-thumb').hover(function(e) {
  	  	
  	var key = $(this).attr('id');
  	
  	//check for existing data
  	if(preview_images[key] == null)
  	{  		  		
  		preview_images[key] = new Object(
				{'container': this, 'maxindex': 100, 'counter': 0, 'active': false, 'thumbs': new Array() });
 		}
 		
 		if(preview_images[key].active == true) //prevent multiple loops
 			return false;
 		
 		preview_images[key].counter = 0;
 		preview_images[key].active = true;
 		loadNextImage(key);
  }, function(e){
  	//mouse out, stop preview
  	var key = $(this).attr('id');
  	preview_images[key].active = false;
  	loadNextImage(key); //hide all images
  });
   
  function loadNextImage(key)
  {  		
  	var ref = preview_images[key];
  	
  	if(!ref.active) //stop anim
  	{
  		for(var i = 0; i < ref.thumbs.length && i <= ref.maxindex; i++)
  			$(ref.thumbs[i]).hide();
  			
 			return;
 		}
  		
 		if(ref.counter > ref.maxindex) //reached end of the loop
 		{
 			$(ref.thumbs[0]).show(); //show first thumb
 			ref.counter = 1; //go on with the second thumb
 			var lastThumb = ref.thumbs[ref.maxindex];
			$(lastThumb)
			.hide()
			.animate({opacity: 1.0}, settings.delay, "", function() {
					loadNextImage(this.refkey);
				});
				
			return;
		}
 		
  	if(ref.thumbs[ref.counter] == undefined)
  	{
  		//create overlay
			var img = new Image();
			img.refkey = key;
			img.refindex = ref.counter;
			$(img).attr('style', 'display:none; position:absolute; left:0; top:0;');
			
			ref.thumbs[ref.counter] = img; //save reference
			
			$(img).load(function(){
				fadeIn(this);
			}).error(function() {
				var ref = preview_images[this.refkey];
				ref.maxindex = this.refindex - 1;
				loadNextImage(this.refkey);
			}).attr('src', "/images/videos/thumbnails/preview/" + key + "/" + ref.counter + ".jpg");
			
			$(ref.container).append(img);
	  }
	  else
	  {
	  	fadeIn(ref.thumbs[ref.counter]);
	  }
			  
		ref.counter++;
  }
  
  function fadeIn(img)
  {
  	var ref = preview_images[img.refkey];
  	
  	if(!ref.active)
  		return;
  	
  	//fade in
		$(img)
		.show()
		.animate({opacity: 1.0}, settings.delay, "", function() {
			loadNextImage(img.refkey)
		});
				
		//hide prev image	
		var ref = preview_images[img.refkey];
		var prevThumb = ref.thumbs[img.refindex - 1]; 
			
		if(prevThumb != undefined)
			$(prevThumb).hide();
  }
  
  $("a.ajax.confirmed").click(function(event) {
		
		if(!confirm('really?'))
			event.stopImmediatePropagation();

		return false;
	});
	
  $('a.ajax').click(function(){  	
  	$.get(this.href, function(ret){
		  eval(ret);
  	});
  	return false;
  });
  
  $('.video-vote a').click(function(){
  	var content = $(this).html();
 		$(this).parent().empty().append(content);
  });
  
  //$("#gallery").parent("#navigation").find("#nav-breadcrumb").hide();
   
  $("#category-form .dropdown").change(function() {
    $("#category-form").submit();
	});
	
	$("#category-form .submit").hide();

	//show gallery fullscreen button
	//$('#gallery .overlay .fullscreen-button').show();
		
  $("#gallery div.close-overlay a")
  .show()
	.toggle(function(){
		$(this).html("Menü ausklappen").css("background-image", "url(/css/gallery_show_menu_btn.gif)");
  	$("#gallery div.optional").hide();
  	return false;
  }, function(){
  	$(this).html("Menü einklappen").css("background-image", "url(/css/gallery_hide_menu_btn.gif)");
  	$("#gallery div.optional").show();
  	return false;
  })
  //.animate({opacity: 1.0}, 5000, "", function() {
  //		if($('#gallery div.optional').is(':visible'))
	//			$(this).click();
	//	});
  
  attachThumbListeners();
  
  function attachThumbListeners()
  {
  	$("#thumb-container a.thickbox")
		.unbind('click')
		.click(function(){
			var t = $(this).siblings("p").children("span").html();
			var a = this.href || this.alt;
			var g = this.rel || false;
			tb_show(t,a,g);
			this.blur();
			
  		//count views
  		this.href.match(/(\d+).jpg/);
  		var imageId = RegExp.$1;  	
  		$.get("/ajax/gallery/view_counter/" + imageId + '/');
  		
  		return false;
  	});
  
  	$("#thumb-container a.thickbox[title!='']").parent("div")
  	.unbind('hover')
  	.hover(function() {
	  	var $this = $(this).children("a.thickbox");
	  	if($this.siblings('p').length == 0)
	  	{
	  			$this.after("<p><span class='label'>" + $this.get(0).title + "</span></p>");
	  			//$this.removeAttr('title'); //prevent default tooltip
			}
	    		
	 		$this.siblings("p").show();
	  	return false;
		 		
  	}, function(){
	  	var $a = $(this).children("a.thickbox");
	  	var $p = $a.siblings("p");
	  	//var $span = $p.children("span");
			//$a.get(0).title = $span.html();
			$p.hide();
	  	return false;
  	});
  }
 
  thumbs_loading = false;
  no_more_thumbs = false;
  
  loading_delay = 1500;
  
  if($("#gallery").length > 0)
  {
	  $(window).scroll(function(){
			
			if(thumbs_loading || no_more_thumbs)
				return;
			
			if ($(window).scrollTop() >= $(document).height() - $(window).height() - 190)
			{
				thumbs_loading = true;
				
				$("#thumb-placeholder")
				.show()
				.animate({opacity: 1.0}, loading_delay, "", function() {
														
					loading_delay = Math.min(loading_delay + 500, 5000);
					
					var cat_id = $("#gallery-category").html() || 0;
					
					var url = "/gallery/loadnext/" + cat_id + "/" + $("#thumb-container div").length + '/' + $("#category-form input:hidden[name=sort_mode]").val();
					
			 		$.get(url, function(ret){
			 			$("#thumb-placeholder").hide();
			 			
			 			if(ret.length < 20)
			 			{
			 				no_more_thumbs = true;
		 				}
			 				
			  		$("#thumb-placeholder").before(ret);
			  		attachThumbListeners(); //hint: instead of reattaching this thing, use the live-function
			  		thumbs_loading = false;
			  		$(window).scroll();
	  			});
  			});
			}
		}); 
 	}
 	
 	$("a[target='_blank']").click(function(){
 		$.post("/ajax/links/click/", {url: this.href, referer: window.location.href}, function(ret){});
 	});

	$('#events-city-selector').show();
	$('#events-city-selector select').change(function(){
		$('#events-city-selector form').submit();
	});
	
	$('a.fullscreen-button').show().toggle(function() { 			
			var fullWidth = $('body').width();
			var neededWidth = Math.ceil(fullWidth / 160.0) * 160 + 1;
			
			var leftOffset = -1 * Math.floor((neededWidth - fullWidth) / 2); //align to even pixels
			
			$('#gallery')
			.addClass('fullscreen')
			.prependTo($('body'));
			
			$('#thumb-container').width(neededWidth)
			.css('margin-left', leftOffset + 'px');
			
			$('html').css('overflow-x', 'hidden');			
			$('#gallery').animate({opacity: 1.0}, 500, "", function() {
			$(window).scroll();});
				
			loading_delay = 500;
			
			return false;
		}, 
		function() {
			$('#gallery').removeClass('fullscreen');
			
			$('#gallery').prependTo($('#content .grid-triple-column'));
			
			$('html').css('overflow-x', 'auto');
			
			$('#thumb-container').css('width', 'auto')
			.css('margin-left', '0px');
			
			return false;
		}).click(	function() {
			$('#shadow-table').toggle();		
			$("#gallery div.close-overlay a").click();
		return false;
		});
	
	if($("div.calendar").length)
	{		
		function daysInMonth(iMonth, iYear)
		{
			return 32 - new Date(iYear, iMonth, 32).getDate();
		}
		
		today = new Date();
		
		current = null;
		
		function updateCalendar(year, month)
		{
			var monthLabels = new Array("Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember");
			
			$("p.month-label").html(monthLabels[month] + " " + year);
			
			$daycontainer = $("div.day-container");
		
			$daycontainer.empty();
			
			current = new Date(year, month, 1);
			
			var leftOffset = -1 * ((current.getDay() + 6) % 7) + 1;
			
			for(var i = leftOffset; i < 35 + leftOffset; i++)
			{
				var act = new Date(year, month, i);
				
				var key = act.getFullYear() + "-" + act.getMonth() + "-" + act.getDate();
				var daily_events = events[key];
				
				var dayClass = "";
				
				if(act.getFullYear() == today.getFullYear() && act.getMonth() == today.getMonth() && act.getDate() == today.getDate())
					dayClass += " future today";
				
				if(act - today >= 0)
					dayClass += " future";
										
				$newhtml = "<span>" + act.getDate() + "</span>";
				
				if(daily_events && daily_events.length >= 1)
				{
					var anchorclass = '';
					
					if(daily_events.length == 1)
						anchorclass += " single";
						
					if(daily_events.length > 1)
						anchorclass += " multiple";
						
					var anchor = act.getFullYear() + "-" + act.getMonth() + "-" + act.getDate();
					
					$newhtml = "<a class='" + anchorclass + "' href='#anchor-" + anchor + "'>" + $newhtml + "</a>";
				}
				
				$newhtml = "<div class='day" + dayClass + "'>" + $newhtml + "</div>";
				
				$daycontainer.append($newhtml);
			}
		}
		
		updateCalendar(today.getFullYear(), today.getMonth());
		
		$("div.calendar a.prev").click(function(){
			if(current > today)
			{
				var helper = new Date(current.getFullYear(), current.getMonth() - 1, 1);
				updateCalendar(helper.getFullYear(), helper.getMonth());
			}
			
			return false;
		});
		
		$("div.calendar a.next").click(function(){
			var helper = new Date(current.getFullYear(), current.getMonth() + 1, 1);
			updateCalendar(helper.getFullYear(), helper.getMonth());
			
			return false;
		});
		
		$("div.calendar").slideDown();
	}
	
	$('div.event-teaser a.button-details').click(function(){
		$teaser = $(this).parent().parent();
		$teaser.hide();
		$teaser.siblings('div.event-details').show();
		return false;
	});
	
	$("input[type=file]").filestyle({ 
     image: "/css/form_input_file_btn.gif",
     imageheight : 25,
     imagewidth : 130,
     width : 100
 });
 
 //clear default form fields on first focus
 $("input.default").focus(function(){
			this.value = '';
			$(this).unbind('focus');
			return false;
	});
	
	$("form.upload").submit(function() {
		$("form.upload input[type=submit]").hide();
		$("form.upload .loading-indicator").show();
	});
 
}); //$document.ready
