//======================================================
//
// custom scripts for kkaarrlls-website
// 
// ======================================================


/**
 * farbspektakel für kkaarrlls-homepage
 * @author Martin Sprekelsen <martin@sprekelsen.de>
 */
function blinken(){
	/**
	 * durchsucht das dokument nach blinkenden elementen <tag class="blinker">...</tag>
	 */
	this.blinkers = getElementsByClassName('blinker');
	
	/**
	 * definiert die blinkfarben
	 */
	 this.f  = new Array('#FF4C4C','#FF9B04','#FF15FF');
	 
	/**
	 * definiert die blinkfrequenz
	 */
	this.interval = 200;
	
	/**
	 * internes farbindex-array
	 */
	this.fi = new Array();
	
	/**
	 * constructor
	 */
	this.initMe = function(){
		if(this.blinkers.length>0){
			var i;
			var j=0;
			for(i=0;i<this.blinkers.length;i++){
				if(j>=this.f.length){j=0;}
				this.fi[i] = j;
				this.blinkers[i].style.color = this.f[j];
				j++;
			}
			window.setInterval("this.blink()", this.interval);
		}
	};
	
	/**
	 * lässt die puppen tanzen
	 */
	this.blink = function(){
		var i;
		for(i=0;i<this.fi.length;i++){ 
			this.fi[i]++;
			if(this.fi[i]>=this.f.length){this.fi[i] = 0;}
			this.blinkers[i].style.color = this.f[this.fi[i]];
		}
	};
	
	/**
	 * constructor aufrufen
	 */
	this.initMe();
}

/**
 * bilder-gruppier-effekt für kkaarrlls-presse-seite
 * @author Martin Sprekelsen <martin@sprekelsen.de>
 */
function presse(){
	
	/**
	 * bilder werden quadratisch zentriert zugeschnitten
	 */
	function imagesFit(group){
		
		if(group == null){
			var subject = $('.imgGroup').find('.img>a>img');
			var speed = 0;
		} else {
			var subject = group.find('.img>a>img');
			var speed = 50;
		}

		subject.each(function(){
			
			var h  = $(this).height();
			var w  = $(this).width();
			var th = h; 
			var tw = w;
			var r  = w/h;
			
			if(r<1){
				th = Math.floor((1/r) * 130);
				tw = 130;
			}
			
			if(r>1){
				th = 130;			
			}
			
			var mL = Math.floor(-1*(tw-130)/2);
			var mT = Math.floor(-1*(th-130)/2);
		
			// besser aussteigen wenn dims nicht gelesen werden koennen
			if(h==0||w==0){
				return;
			}
			
			$(this).stop(true,true).animate({
				'marginTop':mT,
				'marginLeft':mL,
				'width':tw,
				'height':th
			},speed);
			
			$(this).parent().parent().css({
				'width':'130px',
				'paddingRight':'0'
			});
		});
	}
	
	/**
	 * bilder werden im originalverhältnis angezeigt
	 */
	function imagesUnfit(group){
		if(group == null){
			var subject = $('.imgGroup').find('.img>a>img');
		} else {
			var subject = group.find('.img>a>img');
		}
		
		subject.each(function(){
			var iw = $(this).width();
			var ih = $(this).height();
			var ir = iw/ih;
			var itw = 130;
			var ith = 130;
			
			if(ir>1){
				itw = iw;
			}
			
			if(ir<1){
				itw = Math.floor(ir * 130);
			}
			
			$(this).stop(true,true).animate({
				'marginTop':0,
				'marginLeft':0,
				'width':itw,
				'height':130
			},100);
			
			$(this).parent().parent().css({
				'width':itw,
				'paddingRight':'5px'
			});
			
		});
	}
	
	/**
	 * alle bilder einer gruppe werden gezeigt
	 */
	function imagesSlideOut(group){

		var totWidth = 0;
		
		// bilder auffaechern
		$(group.find('.img').get().reverse()).each(function(index) {
			var w = $(this).width();
			var width = $(this).outerWidth(true);
			$(this).stop(true,false).animate({
				'width':width,
				'left':Math.round(totWidth)
			},Math.round(100*(index+1)));		
			totWidth += width;
		});
		
		// textfeld addieren
		totWidth += 285;
		
		// nur animieren, wenn auffaecherung groesser als die ursprungsbreite ist
		if(totWidth>420){	
			size = Math.round(100 * group.find('.img').length);
			group.stop(true,false).animate({'width':totWidth},size);
		}
	}
	
	/**
	 * nur das coverbild einer gruppe wird gezeigt
	 */
	function imagesSlideIn(group){
		group.find('.img').stop(true,false).animate({'left':0,'width':'130px'},400);
		
		// jQuery 1.7-bug not animating percentage http://bugs.jquery.com/ticket/10669
		// unkommentieren und pixelbasierten workaround loeschen, wenn jQuery > 1.7 bzw. bugfix vorliegt
		// group.stop(true,false).animate({'width':'100%'},350);
		group.stop(true,false).animate({'width':'420px'},350);
	}
	
	// initiales fitting für die bilder
	imagesFit(null);
	
	// interaktion
	$('.imgGroup').hover(
		
		function(){
			imagesUnfit($(this));
			imagesSlideOut($(this));
		},
		function(){
			imagesFit($(this));
			imagesSlideIn($(this));
		}
	);
}

/**
 * filter-menu für kkaarrlls-presse-seite
 * @author Martin Sprekelsen <martin@sprekelsen.de>
 */
function zeitfilter(){
	// menu erzeugen
	function populateMenu(){
		years = [];
		$('.imgGroup, .kkPreviewBox').each(function(){
			var classes = $(this).attr('class').split(/\s+/);
			for(var i = 0; i < classes.length; i++){
				
				var myClass = classes[i].split('__');
				if(myClass[0]=='year'){
					var addMe = myClass[1];
				}
				
				if(!in_array(addMe,years)){
					if(typeof(addMe)!='undefined'){
						years.push(addMe);
					}
				}
			}
		});
		
		years.sort();

		for(var j=0;j<years.length;j++){
			var entry = $("<li class=\"zeitfilter\">/<a href=\"#\">" + years[j] + "</a></li>");
			entry.appendTo('#zeitfilter');
		}
		
		$('#zeitfilter li:first-child').find('a').css('textDecoration','underline');
	}
	populateMenu();
	
	function showGroup(group, speed){

		// set default speed	
		if(typeof speed == 'undefined') speed = 600;

		var groupClass = group.substr(1);

		// edition-preview-boxen
		$('.kkPreviewBox').not('.notFilterable').each(function(){
			var myName = $(this).find('a img').attr('alt');
			if(   $(this).hasClass(groupClass)
			   || group == "")
			{
				$(this).stop(true,false).kkSlideLeftShow(speed);
			} else {
				$(this).stop(true,false).kkSlideLeftHide(speed);
			}
		});
		
		// pressebereich
		$('.imgGroup,.file').each(function(){
			if(   $(this).hasClass(groupClass)
			   || group == "")
			{
				$(this).stop(true,true).slideDown(speed);
			} else {
				$(this).stop(true,true).slideUp(speed);
			}
		});
		
		// get year for link-highlighting
		var year = group.split('__');
		if(year[0]=='.year'){
			var myYear = year[1];
		} else {
			var myYear = 'all';
		}

		// highlight link
		$('#zeitfilter li').find('a').css('textDecoration','none');
		$('#zeitfilter li').each(function(){
			var target = $(this).find('a').html();
			if (target == myYear){
				$(this).find('a').css('textDecoration','underline');
			}
		});
	}
	
	$('#zeitfilter li').click(function(){

		// define filter
		var target = $(this).find('a').html();
		if(target.substring(0, 3) == 'all'){
			var filter = ""; 
		} else {
			var filter = ".year__" + target;
		}

		// set cookie so save filter state
		$.cookie('kkYearFilter', filter);
		
		showGroup(filter);
	});
	
	// onload-defaults
	var yearFilterIsSet = $.cookie('kkYearFilter');
	if(yearFilterIsSet!=null){
		showGroup(yearFilterIsSet,0);
	}
}

/**
 * korrigiert die hoehe der hintergrundbox in der 
 * kkaarrlls-editions-detail-seite, sodass die platzhalter-
 * kreuzkaesten nicht mehr halb verdeckt werden 
 * @author Martin Sprekelsen <martin@sprekelsen.de>
 */
function fixDetailBoxLayout(){
	var kreuzkastenHoehe = 145;
	var detailBoxHoehe   = $('.detailBox').innerHeight();
	var offset           = 30;
	var setHeight        = (Math.ceil(detailBoxHoehe/kreuzkastenHoehe)*kreuzkastenHoehe)-offset;
	$('.detailBox').css('height',setHeight);
}

/**
 * slide-left-effekt für den Zeitfilter in der edition-uebersicht.
 * Dank an vdboor (stackoverflow.com)
 */
// original-script macht probleme in webkit-browsern.
// jQuery.fn.slideLeftHide = function( speed, callback ) { this.animate( { width: "hide", paddingLeft: "hide", paddingRight: "hide", marginLeft: "hide", marginRight: "hide" }, speed, callback ); }
// jQuery.fn.slideLeftShow = function( speed, callback ) { this.animate( { width: "show", paddingLeft: "show", paddingRight: "show", marginLeft: "show", marginRight: "show" }, speed, callback ); }
// angepasstes script passt.
jQuery.fn.kkSlideLeftHide = function( speed, callback ) { this.animate( { width: 0, marginRight: 0 }, speed, callback ); }
jQuery.fn.kkSlideLeftShow = function( speed, callback ) { this.animate( { width: "130px", marginRight: "15px" }, speed, callback ); }


/**
 * in-array helper-function.
 * Danke an den unbekannten contributor (stackoverflow.com)
 */
function in_array(item,arr) {
	for(p=0;p<arr.length;p++) if (item == arr[p]) return true;
	return false;
}


/**
* jQuery Cookie plugin
*
* Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

/*
Developed by Robert Nyman, http://www.robertnyman.com
Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/      
var getElementsByClassName = function (className, tag, elm){
	if (document.getElementsByClassName) {
	        getElementsByClassName = function (className, tag, elm) {
	                elm = elm || document;
	                var elements = elm.getElementsByClassName(className),
	                        nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
	                        returnElements = [],
	                        current;
	                for(var i=0, il=elements.length; i<il; i+=1){
	                        current = elements[i];
	                        if(!nodeName || nodeName.test(current.nodeName)) {
	                                returnElements.push(current);
	                        }
	                }
	                return returnElements;
	        };
	}
	else if (document.evaluate) {
	        getElementsByClassName = function (className, tag, elm) {
	                tag = tag || "*";
	                elm = elm || document;
	                var classes = className.split(" "),
	                        classesToCheck = "",
	                        xhtmlNamespace = "http://www.w3.org/1999/xhtml",
	                        namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
	                        returnElements = [],
	                        elements,
	                        node;
	                for(var j=0, jl=classes.length; j<jl; j+=1){
	                        classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
	                }
	                try     {
	                        elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
	                }
	                catch (e) {
	                        elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
	                }
	                while ((node = elements.iterateNext())) {
	                        returnElements.push(node);
	                }
	                return returnElements;
	        };
	}
	else {
	        getElementsByClassName = function (className, tag, elm) {
	                tag = tag || "*";
	                elm = elm || document;
	                var classes = className.split(" "),
	                        classesToCheck = [],
	                        elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
	                        current,
	                        returnElements = [],
	                        match;
	                for(var k=0, kl=classes.length; k<kl; k+=1){
	                        classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
	                }
	                for(var l=0, ll=elements.length; l<ll; l+=1){
	                        current = elements[l];
	                        match = false;
	                        for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
	                                match = classesToCheck[m].test(current.className);
	                                if (!match) {
	                                        break;
	                                }
	                        }
	                        if (match) {
	                                returnElements.push(current);
	                        }
	                }
	                return returnElements;
	        };
	}
	return getElementsByClassName(className, tag, elm);
};




//======================================================
//
// DOM-ready
//
// ======================================================

$(document).ready(function (){
	
	blinken();

	zeitfilter();
	
	//fix overflow-prob when using tools
	$('.kkPreviewboxTools').on('click',function(){
		$(this).parent().css({overflow:"visible"});
	});
});


//======================================================
//
// Alles geladen
//
//======================================================

$(window).load(function () {
	presse(); //presse erst aufrufen, wenn alle bilder geladen sind!
	fixDetailBoxLayout();
});

















