 /* Text CFG
 */
(function($){
	var setLang = $.createSetUnsetFunction('aperto.text');
	setLang({
		mFilterAfterLink: '<ul class="add-more"><li><a href="#">weitere Kategorie hinzuf&uuml;gen</a></li></ul>'
	});
})(jQuery);


/**
 * @author alexander.farkas
 */
var playerOpen = function(playerID, status){
	var parent = $('#mp3_player'+playerID).parent();
	if(status){
		parent.css({'height': '45px'});
	} else {
		parent.css({'height': '22px'});
	}
};
	
	
var flashIsRunning = function(playerID){
	flashPlayer.stopAllExcept(playerID);
};
var flashPlayer = (function(){
	var playerLength = 0;
	function findeFlash(flash) {
		if (document.all) {
		  if (document.all[flash]) {
		    return document.all[flash];
		  }
		  if (window.opera) {
		    var movie = eval(window.document + flash);
		    if (movie.SetVariable) {
		      return movie;
		    }
		  }
		  return;
		}
		if(document.layers) {
		  if(document.embeds) {
		    var movie = document.embeds[flash];
		    if (movie.SetVariable) {
		      return movie;
		    }
		  }
		  return;
		}
		if (!document.getElementById) {
		  return;
		}
		var movie = document.getElementById(flash);
		if (movie.SetVariable) {
		  return movie;
		}
		var movies = movie.getElementsByTagName('embed');
		if (!movies || !movies.length) {
		  return;
		}
		movie = movies[0];
		if (movie.SetVariable){
		  return movie;
		}
		return;
	}
	return {
		init: function(){
			var link, so;
			$('div.player-container').each(function(i){
				link = $('a',this);
				
				so = new SWFObject(g_FlashPlayerPath.small, "mp3_player"+i, "128", "43", "7", "#FFFFFF");
				so.addParam("quality", "best");
				so.addParam("menu", "true");
				so.addParam("play", "true");
				so.addParam("wmode", "transparent");
				//
				so.addVariable("externLink", $(link[1]).attr('href'));
				so.addVariable("musik_path", $(link[0]).attr('href'));
				so.addVariable("playerID", i);
				//
				so.write(this);
				playerLength++;
			});
			$('div.swf:not(.player-container)').each(function(i){
				link = $('a',this);
				so = new SWFObject(g_FlashPlayerPath.big, "mp3_player"+i, "271", "20", "7", "#FFFFFF");
				so.addParam("quality", "best");
				so.addParam("menu", "true");
				so.addParam("play", "true");
				so.addParam("wmode", "transparent");
				so.addVariable("playerID", i);
				so.addVariable("musik_path", link.attr('href'));
				so.write(this);
				playerLength++;
			});
			playerLength++;
		},
		stopAllExcept: function(id){
			for(var i = 0; i<playerLength;i++){
				if(i != id){
					findeFlash('mp3_player'+i).stopWithPlaying();
				}
			}
		}
	};
})();
(function($){
	var arrayRemove = function(array, from, to) {
	  var rest = array.slice((to || from) + 1 || array.length);
	  array.length = from < 0 ? array.length + from : from;
	  return array.push.apply(array, rest);
	};
	(function($){
		$.userMode = (function(){
			var userBg, timer, testDiv;
			function testBg(){
				testDiv.css({backgroundColor: '#000000'});
				var black = jQuery.curCSS( testDiv[0], 'backgroundColor', true);
				testDiv.css({backgroundColor: '#ffffff'});
				var white = jQuery.curCSS( testDiv[0], 'backgroundColor', true);
				var newBgStatus = (black === white || white === 'transparent')?true:false;
				if(newBgStatus != userBg){
					userBg = newBgStatus;
					$.event.trigger('usermode',[{'usermode': userBg}]);
				}
			}
			return {
				get: function(){
					testBg();
					return userBg;
				},
				init: function(){
					testDiv = $('<div></div>').css({position: 'absolute', left: '-999em', top: '-999px', width: '0px', height: '0px'}).appendTo('body');
					timer = setInterval(testBg, 999);
				},
				stop: function(){
					clearInterval(timer);
					testDiv.remove();
				}
			};
		})();
		$($.userMode.init());
	})(jQuery);
	(function($){
		$.ui = $.ui ||
	    {};
		$.fn.extend({
	        checkBox: function(options){
	            var args = Array.prototype.slice.call(arguments, 1);
	            return this.each(function(){
	                if (typeof options == "string") {
	                    var selectTable = $.data(this, "ui-checkBox");
	                    selectTable[options].apply(selectTable, args);
	                }
	                else 
	                    if (!$.data(this, "ui-checkBox")) {
	                        $.data(this, "ui-checkBox", new $.ui.checkBox(this, options));
	                    }
	            });
	        }
	    });
		$.ui.checkBox = function(elm, o){
			this.o = $.extend({
					focusClass: 'focus',
					checkedClass: 'checked',
					disabledClass: 'disabled',
					hideInput: true
			}, o);
			var that = this;
			this.status = {};
			this.elm = $(elm);
			this.labels = $('label[for='+this.elm.attr('id')+']');
			this.status = false;
			
			this.update();
			var usermode = ($.userMode && $.userMode.get)?$.userMode.get():false;
			
			if(!usermode && this.o.hideInput){
				
				this.elm.css(
					{position: 'absolute', left: '-999em', width: '0px', overflow: 'hidden'}
				).bind('usermode', function(e, o){
					if(o.usermode){
						that.destroy.call(that, false);
					}
				});
			}
			this.elm.bind('click.checkBox', function(e){
					that.update.call(that,e);
				}).bind('change.checkBox', function(e){
					that.update.call(that,e);
				}).bind('focus.checkBox', function(){
					that.labels.addClass(that.o.focusClass);
				}).bind('blur.checkBox', function(){
					that.labels.removeClass(that.o.focusClass);
				});
		};
		$.extend($.ui.checkBox.prototype,{
			destroy: function(onlyCss){
				this.elm.css({position: '', left: '', width: '', overflow: ''});
					if(!onlyCss){
						this.elm.unbind('.checkBox');
					}
			},
			ui: function(){
            return {
	                instance: this,
	                options: this.o,
	                status: this.status
	            };
	        },
	        propagate: function(n){
	            var args = [this.ui()];
	            this.elm.triggerHandler("checkBox" + n, args);
	        },
			update: function(e){
				if((!this.status || this.status == 'unchecked') && this.elm.is(':checked')){
					this.labels.addClass(this.o.checkedClass);
					this.status = 'checked';
					this.propagate('change');
				} else if((!this.status || this.status == 'checked') && !this.elm.is(':checked')){
					this.labels.removeClass(this.o.checkedClass);
					this.status = 'unchecked';
					this.propagate('change');
				}
				if(this.elm.is(':disabled')){
					this.labels.addClass(this.o.disabledClass);
				} else {
					this.labels.removeClass(this.o.disabledClass);
				}
			}
		});
	})(jQuery);
	$.ui = $.ui ||
    {};
    $.fn.extend({
        selectTable: function(options){
            var args = Array.prototype.slice.call(arguments, 1);
            return this.each(function(){
                if (typeof options == "string") {
                    var selectTable = $.data(this, "ui-selectTabel");
                    selectTable[options].apply(selectTable, args);
                }
                else 
                    if (!$.data(this, "ui-selectTabel")) {
                        $.data(this, "ui-selectTabel", new $.ui.SelectTable(this, options));
                    }
            });
        },
		showSubform: function(options){
            var args = Array.prototype.slice.call(arguments, 1);
            return this.each(function(){
                if (typeof options == "string") {
                    var showSubform = $.data(this, "ui-showSubform");
                    showSubform[options].apply(showSubform, args);
                }
                else 
                    if (!$.data(this, "ui-showSubform")) {
                        $.data(this, "ui-showSubform", new $.ui.showSubform(this, options));
                    }
            });
        },
		multipleSelect: function(options){
			var args = Array.prototype.slice.call(arguments, 1);
            return this.each(function(){
                if (typeof options == "string") {
                    var multipleSelect = $.data(this, "ui-multipleSelect");
                    multipleSelect[options].apply(multipleSelect, args);
                }
                else 
                    if (!$.data(this, "ui-multipleSelect")) {
                        $.data(this, "ui-multipleSelect", new $.ui.multipleSelect(this, options));
                    }
            });
       	},
		filterMedia: function(options){
			var args = Array.prototype.slice.call(arguments, 1);
            return this.each(function(){
                if (typeof options == "string") {
                    var filtermedia = $.data(this, "ui-filtermedia");
                    filtermedia[options].apply(filtermedia, args);
                }
                else 
                    if (!$.data(this, "ui-filtermedia")) {
                        $.data(this, "ui-filtermedia", new $.ui.filterMedia(this, options));
                    }
            });
       	}
    });
	$.ui.filterMedia = function(elm, o){
		this.elm = $(elm);
		var that = this;
		var html = '<fieldset><div class="form-row"><select id="pod-webradio-filter" name="pod-webradio-filter">';
		html += '<option value="both">Podcasts und Webradios</option><option value="podcast">nur Podcasts</option><option value="webradio">nur Webradios</option>';
	    html += '</select><a class="button" href="#"><span><span><span><span>anzeigen</span></span></span></span></a></div></fieldset>';                     
		//this.select = $(html).insertBefore(elm).find('a').bind('click', function(){
		//	that.filter.call(that);
		//	return false;
		//}).end().find('select');

        // edited by cnolan, new target element #filter, template: Medienauswahl -> Filterbox
		this.select = $('#filter').find('a').bind('click', function(){
			that.filter.call(that);
			return false;
		}).end().find('select');
		this.filter();
	};
	$.extend($.ui.filterMedia.prototype, {
		filter: function(){
			
			switch(this.select.val()){
				case "podcast": 
					this.elm.find('li.podcast').css({'display': 'block'}).end()
						.find('li.webradio').css({'display': 'none'});
				break;
				case "webradio":
					this.elm.find('li.webradio').css({'display': 'block'}).end()
						.find('li.podcast').css({'display': 'none'});
				break;
				default: 
					this.elm.find('li.webradio, li.podcast').css({'display': 'block'});
				break;
				
			}
		}
	});
	$.ui.multipleSelect = function(elm, o){
		this.o = $.extend({
			afterLink: aperto.text.mFilterAfterLink,
			wrapper: '<div class="form-row"></div>',
			delFirst: true,
			removeLink: '<a href="#" class="close"><img alt="Spot entfernen" src="/img/icons/close.png"/></a>',
			removeLinkSel: 'a.close'
		}, o);
		var that = this;
		this.elm = $(elm);
		this.select = $('select', elm);
		var val = this.select.val();
		var tmpHtml = $('<div></div>').html(this.elm.clone());
		$('select', tmpHtml[0]).removeAttr('multiple')
			.find('option').removeAttr('selected').end();
		tmpHtml.find('select:first')	
			.after(this.o.removeLink);
		$('h2,p,label',tmpHtml[0]).remove();
		this.addStructure = tmpHtml.html();
		this.i = 0;
		this.afterLink = $(this.o.afterLink).insertAfter(elm).bind('click.multipleSelect', function(){
			that.add.call(that);
			return false;
		});
		if(val && val.length > 1){
			var found = false;
			$.each(val, function(i, item){
				if(found){
					that.add.call(that, item);
				} else {
					found = true;
					that.select.find('option').removeAttr('selected')
						.end().val(item);
				}
			});
		}
		this.select.removeAttr('multiple');
		if(this.o.delFirst){
			tmpHtml.find('option:first-child').remove();
			this.addStructure = tmpHtml.html();
		}
		
		
		
	};
	$.extend($.ui.multipleSelect.prototype, {
		add: function(val){
			var addElm = $(this.o.wrapper).html(this.addStructure);
			if(this.o.delFirst && !this.i){
				addElm.find('option:first-child');
			}
			var that = this;
			$(this.addStructure).insertBefore(this.afterLink[0]).find(this.o.removeLinkSel)
				.bind('click.multipleSelect', function(){
					that.remove.call(that, this);
					return false;
				}).end().find('select').each(function(){
					var jElm = $(this), 
						name = jElm.attr('name'), 
						id = jElm.attr('id');
					name = (name.indexOf('[]') === -1) ? name+'[]' : name;
					jElm.attr({'name': name, 'id': id+that.i});
					if(val){
						jElm.val(val);
					}
				});
			
			this.i++;
		},
		remove: function(elm){
			$(elm).parent().remove();
		}
	});
	$.ui.showSubform = function(elm, o) {
		this.o = $.extend({
			closeAppendTo: ':header:first',
			closeButton: '<a href="#"><img alt="Schlie&szlig;en" src="/img/icons/close.png"/></a>',
			disableInput: false
		}, o);
		var that = this;
		function handleClick(){
			that.handleClick.call(that);
			return false;
		}
		this.elm = $(elm).bind('click.showSubForm', handleClick).css({position: 'absolute', left: '-9999px'});
		this.elmParentUl = this.elm.parents('ul:first');
		this.hidden = true;
		var colappseId = '#'+this.elm.val();
		this.collapsElm = $(colappseId);
		this.disableInput = $(this.o.disableInput);
		
		if(!this.elm.is(':checked')){
			this.collapsElm.css({display: 'none'});
		} else {
			this.elmParentUl.css({display: 'none'});
		}
		$(this.o.closeButton).appendTo(colappseId+' '+this.o.closeAppendTo).bind('click.showSubForm', handleClick);
	};
	$.extend($.ui.showSubform.prototype, {
		handleClick: function(){
			
			this.elmParentUl.slideToggle(300);
			/*this.collapsElm.slideToggle(300);*/
			this.collapsElm.animate({opacity: 'toggle', height: 'toggle'},{duration: 300});
			
			this.disableInput[0].disabled = (this.disableInput[0].disabled)?false:true;

		}
	});
	$.ui.SelectTable = function(elm){
		var that = this, jElm, attrId;
		this.elm = $(elm);
		
		this.startTd = null;
		this.lastNewTd = null;
		this.curSelect = [];
		this.focusElm = null;
		this.holdStrg = false;
		
		this.MouseDrag = function(){
            this.element = that.elm;
            this.options = $.extend({}, $.ui.mouse.defaults, {cancel: 'th', distance: 1});
        };
        $.extend(this.MouseDrag.prototype, $.ui.mouse, {
			mouseDrag: function(){that.drag.apply(that, arguments);},
			mouseStop: function(){that.stop.apply(that, arguments);}

        });
		
		this.elm
			.bind('mousedown.selectTable',function(e){
				that.start.call(that, e.target);
			}).bind('mouseup.selectTable',function(){
				that.stop.call(that);
			})
			.attr({tabindex: '0'}).bind('focus.selectTable', function(e){
				var jElm = (e.explicitOriginalTarget)?$(e.explicitOriginalTarget):$(e.target);
				if(jElm.is('table')){
					that.onfocus.call(that);
				}
			}).bind('blur.selectTable', function(e){
				if(that.focusElm && $(e.target).is('table')){
					that.focusElm.removeClass('over');
					that.stop.call(that);
					$(document).unbind('keydown.selectTable').unbind('keyup.selectTable');
				}
				that.focusElm = null;
			}).addClass('js');
			var id = this.elm.attr('id');
			$('<a href="#'+id+'" class="sr-enable">Bitte klicken Sie, um nachfolgende Auswahltabelle f&uuml;r Sprachausgabe oder Braille-Zeile zu optimieren</a>')
				.insertBefore(this.elm[0]).bind('click.selectTable',function(){
					that.elm.unbind('.selectTable').removeClass('js');
				});
			this.tds = $('td[headers]', elm).each(function(){
				if(this.getElementsByTagName('input')[0].checked){
					this.className = 'selected';
				}
			});
		
		this.mouseDrag = new this.MouseDrag();
        this.mouseDrag.mouseInit();
	};
	$.extend($.ui.SelectTable.prototype, {
		onfocus: function(){
			var that = this;
			this.focusElm = this.tds.slice(0,1).addClass('over');
			if(this.focusElm[0].scrollIntoView){
				this.focusElm[0].scrollIntoView(false);
			}
			$(document).bind('keydown.selectTable',function(e){
				if(that.onkeydown.call(that,e)){
					return false;
				}
			}).bind('keyup.selectTable',function(e){
				that.onkeyup.call(that,e);
			});
			
		},
		onkeydown: function(e){
			var keyUp = 38, keyDown = 40, keyLeft = 37, keyRight = 39, keyStrg = 17, preventDefault = false, next = [], curHeaders, nextRow, curCol;
			switch(e.keyCode){
				case keyUp:
					curHeaders = this.focusElm.attr('headers');
					nextRow = parseInt(curHeaders.match(/row_(\d+)/)[1], 10)-1;
					curCol  = parseInt(curHeaders.match(/col_(\d+)/)[1], 10);
					next = this.tds.filter('[headers=row_'+nextRow+' col_'+curCol+']').addClass('over');
				break;
				case keyDown:
					curHeaders = this.focusElm.attr('headers');
					nextRow = parseInt(curHeaders.match(/row_(\d+)/)[1], 10)+1;
					curCol  = parseInt(curHeaders.match(/col_(\d+)/)[1], 10);
					next = this.tds.filter('[headers=row_'+nextRow+' col_'+curCol+']').addClass('over');
				break;
				case keyLeft:
					next = this.focusElm.prev('td').addClass('over');
				break;
				case keyRight:
					next = this.focusElm.next('td').addClass('over');
				break;
				case keyStrg:
					this.holdStrg = true;
					if(this.focusElm[0] && !this.startTd){
						this.start(this.focusElm[0]);
					}
				break;
			}
			if(next[0]){
				this.focusElm.removeClass('over');
				this.focusElm = next;
				next[0].scrollIntoView(false);
				preventDefault = true;
				if(this.holdStrg){
					this.drag({target: this.focusElm[0]});
				}
			}
			return preventDefault;
		},
		onkeyup: function(e){
			if(e.keyCode == 17){
				this.stop();
			}
		},
		start: function(elm){
			var jElm = $(elm), checkbox;
			if(jElm.is('td')){
				jElm.toggleClass('selected');
				checkbox = elm.getElementsByTagName('input')[0];
				checkbox.checked = (checkbox.checked)?false:true;
				this.startTd = jElm.attr('headers');
				this.lastNewTd = this.startTd;
				this.curSelect.push(this.startTd);
			}
		},
		drag: function(e){
			var jElm = $(e.target),
			curHeader = jElm.attr('headers');
			if(curHeader && curHeader != this.lastNewTd){
				this.lastNewTd = curHeader;
				this.getNewTds();
			}
		},
		getNewTds: function(){
			function getNums(row_colA,row_colB){
				var start, end, retVal = [];
				if(row_colA == row_colB){
					return [row_colA];
				}
				if(row_colA < row_colB){
					start = row_colA;
					end = row_colB;
				} else {
					start = row_colB;
					end = row_colA;
				}
				for(var i = start; i <= end; i++){
					retVal.push(i);
				}
				return retVal;
			}
			
			var lastRow = parseInt(this.lastNewTd.match(/row_(\d+)/)[1], 10),
			lastCol  = parseInt(this.lastNewTd.match(/col_(\d+)/)[1], 10),
			firstRow = parseInt(this.startTd.match(/row_(\d+)/)[1], 10),
			firstCol  = parseInt(this.startTd.match(/col_(\d+)/)[1], 10),
			rows = getNums(firstRow,lastRow),
			cols = getNums(firstCol,lastCol),
			deSelected = this.curSelect.concat([]),
			newSel = [],
			slected = [],
			selAtom,
			found,
			checkbox;
			
			for(var i = 0, lenA = rows.length; i<lenA;i++ ){
				for(var j = 0, lenB = cols.length; j<lenB;j++ ){
					selAtom = 'row_'+rows[i]+' col_'+cols[j];
					found = $.inArray(selAtom, deSelected);
					slected.push(selAtom);
					if(found == -1){
						newSel.push(selAtom);
						this.tds.filter('[headers='+selAtom+']').each(function(){
							$(this).toggleClass('selected');
							checkbox = this.getElementsByTagName('input')[0];
							checkbox.checked = (checkbox.checked)?false:true;
						});
					} else {
						arrayRemove(deSelected,found);
					}
				}
			}
			this.curSelect = slected;
			for(var k = 0, len = deSelected.length;k<len; k++){
				this.tds.filter('[headers='+deSelected[k]+']').each(function(){
					$(this).toggleClass('selected');
					checkbox = this.getElementsByTagName('input')[0];
					checkbox.checked = (checkbox.checked)?false:true;
				});
			}
		},
		stop: function(){
			this.startTd = null;
			this.lastNewTd = null;
			this.curSelect = [];
			this.holdStrg = false;
		}
	});
	$.fn.deleteLi = function(){
		var link =  '<a href="#" title="Löschen" class="delete">Löschen</a>';
		function delLi(){
			$(this).parent().animate({height: 0, opacity: 0}, {complete: function(){
				$(this).remove();
			}});
			return false;
		}
		return this.each(function(){
			$(link).appendTo(this).bind('click', delLi);
		});
	};
	function sliderVerteilung(){
		/* slider */
		function sliderChange(e,so, sa){
			so = so || sa;
			var rest = 100-so.value;
			rest += '/'+so.value;
			$('#verteilung').val(rest);
			$('#verteilung-slider span').html(rest);
		}
		function slideEnd(e,so, sa){
			so = so || sa;
			var rest = 100-so.value;
			if(!rest && $('#webradio-checkbox').is(':checked')){
				$('#webradio-checkbox').attr({checked: false});
				$('#webradio-content').slideUp(300);
			} else if(rest && !$('#webradio-checkbox').is(':checked')){
				$('#webradio-checkbox').attr({checked: true});
				$('#webradio-content').slideDown(300);
			}
			if(rest == 100 && $('#podcast-checkbox').is(':checked')){
				$('#podcast-checkbox').attr({checked: false});
				$('#podcast-content').slideUp(300);
			} else if(rest != 100 && !$('#podcast-checkbox').is(':checked')){

				$('#podcast-checkbox').attr({checked: true});
				$('#podcast-content').slideDown(300);
			}
			sliderChange(e,so, sa);
		}
		function sliderStart(){
			var startVal = parseInt($('#verteilung').val(), 10);
			if(startVal != 50){
				startVal = 100 - startVal;
				$("#verteilung-slider").slider('moveTo', startVal);
				if(!startVal){
					$('#podcast-checkbox').attr({checked: false});
					$('#podcast-content').slideUp(300);
					
				} else if(startVal == 100){
					$('#webradio-checkbox').attr({checked: false});
					$('#webradio-content').css({display: 'none'});
				}
			}
		}
		function checkBoxClick(){
			var jElm = $(this);
			if(!jElm.is(':checked')){
				if(jElm.is('#podcast-checkbox')){
					$('#podcast-content').slideUp(300, function(){
						$('#verteilung-slider').slider('moveTo', ''+0);
					});
				} else {
					$('#webradio-content').slideUp(300, function(){
						$('#verteilung-slider').slider('moveTo', 100);
					});
				}
			} else {
				if(jElm.is('#podcast-checkbox')){
					$('#podcast-content').slideDown(300);
				} else {
					$('#webradio-content').slideDown(300);
				}
			}
		}
        $('#verteilung').after('<div class="verteilung-wrapper"><div class="verteilung-box"><div id="verteilung-slider"><div class="ui-slider-handle"><span>50/50</span></div></div></div></div>');
		$('#verteilung').css({display: 'none'});
		$("#verteilung-slider").slider({stepping: 10})
			.bind('slidechange', slideEnd).bind('slide', sliderChange);
		if($('#verteilung')[0]){
			sliderStart();
		}
		$('#webradio-checkbox').bind('click', checkBoxClick);
		$('#podcast-checkbox').bind('click', checkBoxClick);
	}
	function editTable(){
		function close(elm){
			elm.each(function(){
				var jElm = $(this);
				id = jElm.attr('href');
				$(id+' a.close').bind('click', function(){
					jElm.click();
					return false;
				});
			});
		}
		function completeCallback(elmClick, conClick, otherElm){
			var img = $('img:first', elmClick[0]), 
			imgSrc = img.attr('src');
			
			if(elmClick.is('.on')){
				elmClick.parent().addClass('active');
				img.attr('src', imgSrc.replace('.png', '-active.png'));
			} else {
				elmClick.parent().removeClass('active');
				img.attr('src',imgSrc.replace('-active.png', '.png'));
			}
			if(otherElm[0]){
				img = $('img:first', otherElm[0]); 
				imgSrc = img.attr('src');
				if(otherElm.is('.on')){
					otherElm.parent().addClass('active');
					img.attr('src',imgSrc.replace('.png', '-active.png'));
				} else {
					otherElm.parent().removeClass('active');
					img.attr('src',imgSrc.replace('-active.png', '.png'));
				}
			}
		}
		$('#edit-table ul').each(function(){
			var tabLink = $('a', this).tab({closeOnClick: true, complete: completeCallback});
			close(tabLink);
		});
	}
	$.tablesorter.addParser({ 
        // set a unique id 
        id: 'custom_webradio', 
        is: function(s) { 
            // return false so this parser is not auto detected 
            return false; 
        }, 
        format: function(s, r, c) {
			
            return $(c).is('.webradio')?1:0; 
        }, 
        // set type, either numeric or text 
        type: 'numeric' 
    }); 
	$.tablesorter.addParser({ 
        // set a unique id 
        id: 'custom_podcast', 
        is: function(s) { 
            // return false so this parser is not auto detected 
            return false; 
        }, 
        format: function(s, r, c) {
			// format your data for normalization 
			
            return $(c).is('.webradio')?0:1; 
        }, 
        // set type, either numeric or text 
        type: 'numeric' 
    });
	$.tablesorter.addParser({ 
        // set a unique id 
        id: 'custom_podcast', 
        is: function(s) { 
            // return false so this parser is not auto detected 
            return false; 
        }, 
        format: function(s, r, c) {
			// format your data for normalization 
			
            return $(c).is('.webradio')?0:1; 
        }, 
        // set type, either numeric or text 
        type: 'numeric' 
    }); 
	
	$.tablesorter.addParser({ 
        // set a unique id 
        id: 'custom_buchungsdatum', 
        is: function(s) { 
            // return false so this parser is not auto detected 
            return false; 
        }, 
        format: function(s, r, c) {
			s = $('span.book-time',c).text();
			s = s.replace(/(\d{1,2})[\.\-](\d{1,2})[\.\-](\d{2})/, "$2/$1/$3");
            return $.tablesorter.formatFloat(new Date(s).getTime()); 
        }, 
        // set type, either numeric or text 
        type: 'numeric' 
    });
	$.tablesorter.addParser({ 
        // set a unique id 
        id: 'custom_startdate', 
        is: function(s) { 
            // return false so this parser is not auto detected 
            return false; 
        }, 
        format: function(s, r, c) {
			s = $('span.broadcast-start',c).text();
			s = s.replace(/(\d{1,2})[\.\-](\d{1,2})[\.\-](\d{2})/, "$2/$1/$3");
            return $.tablesorter.formatFloat(new Date(s).getTime()); 
        }, 
        // set type, either numeric or text 
        type: 'numeric' 
    });
	$.tablesorter.addParser({ 
        // set a unique id 
        id: 'custom_enddate', 
        is: function(s) { 
            // return false so this parser is not auto detected 
            return false; 
        }, 
        format: function(s, r, c) {
			s = $('span.broadcast-end',c).text();
			s = s.replace(/(\d{1,2})[\.\-](\d{1,2})[\.\-](\d{2})/, "$2/$1/$3");
            return $.tablesorter.formatFloat(new Date(s).getTime()); 
        }, 
        // set type, either numeric or text 
        type: 'numeric' 
    });
	function tableSort(){
		var val;
		function submitAction(e){
			val = $('#sort-control select').val();
			var confHeaders = table[0].config.headers;
			if(table.is('#edit-table') || table.is('.multi-sort')){
				$("table").trigger("update"); 
				if(val.indexOf('custom_') != -1 && (!confHeaders[0] || confHeaders[0].sorter == val)){
					table[0].config.headers[0] = { 
	                    sorter: val
	                };
					val = 'media';
					table.trigger('update');
				} else if(confHeaders && confHeaders[0] && confHeaders[0].sorter){
					table[0].config.headers[0] = null;
					table.trigger('update');
					val = 'media';
					table[0].config.sortList = [];
				}
			}
			table.each(function(){
				$('th',this).removeClass('active');
				$('th.'+val, this).click().addClass('active');
			});
			return false;
		}
		$('#sort-control a.button').click(submitAction);
		
		var table = $("#sort, #edit-table, table.multi-sort").tablesorter({ widgetZebra: {css: ["odd","even"]}, widgets: ['zebra']});

	}
	function hideValidBox() {
			function doHide() {
				var jElm = $(this).parent();
				var marginHeight = jElm.outerHeight() * -1;
				jElm.animate({'marginTop': marginHeight, 'opacity': 0.5},{duration: 350});
				
				return false;
			}
			$('a.valid-close').bind('click',doHide);
	}
	function fakeFile(){
		var jElm = $('input.upload').css({'opacity': 0});
		function fakeFileChange(){
			var jElm = $(this);
			jElm.next('input.fakefile').val(jElm.val());
		}
		if(jElm.css('opacity') === 0 || jElm.css('opacity') === '0'){
			jElm.after('<input type="text" class="fakefile" /><img src="img/buttons/button_select.gif" alt="Ausw&auml;hlen" />');
			jElm.bind('change', fakeFileChange);
		} else {
			jElm.css({'opacity': 1});
		}
	}
	function checkUpload () {
			function toggleUpload () {
					var td = $(this).parents('td:first');
					td[(this.checked)?'addClass':'removeClass']('inactive');
					td.find('a.button')[(this.checked)?'addClass':'removeClass']('btn-inactive');
					$(this).parents('form:first').submit();
			}
			$('#uploadcheck a.button').each(function (i){
				var jElm = $(this);
				jElm.after('\n<input name="aussetzen" id="aussetzen-'+i+'" type="checkbox" class="checkbox" /><label class="inline" for="aussetzen-'+i+'">Folge aussetzen</label>')
					.next().bind('click', toggleUpload);
			});
	}
	$.fn.resetInput  = function(){
		function enterInput(){
			var jElm = $(this);
			if(this.defaultValue == jElm.val()){
				jElm.val('');
			}
		}
		function leaveInput(){
			var jElm = $(this);
			if(jElm.val() === ''){
				jElm.val(this.defaultValue);
			}
		}
		return this.bind('focus',enterInput).bind('blur', leaveInput);
	};
	function tandemTrippleSwitcher(){
		
		function switcher(){
			var jElm = $(this),
				name = (jElm.attr('id') == 'werbeform-webradio') ?
					'webradiospot-length' :
					'podcastspot-length',
				value = parseInt(jElm.val(), 10);
			//if(jElm)
			for(var i = 1; i < 4; i++){
				if(i > value){
					$('#'+name+i+', label[for='+name+i+']').css({display: 'none'});
				} else {
					$('#'+name+i+', label[for='+name+i+']').css({display: ''});
				}
			}
		}
		
		$('#werbeform-webradio, #werbeform-podcast').bind('uaagchange', switcher).each(function(){
			switcher.call(this);
		});
	}
    function callOnDomReady(){
    	$('#amount,#budget').resetInput();
		$('body').addClass('js-enabled');
		$('a.tip').tooltip({'rePos': false});
		$('table.pick').selectTable();
		
		//fakeFile();
		
		$('#open-project').showSubform({disableInput: '#produkt'});
		$('#open-customer').showSubform({disableInput: '#kunde'});
        $('#open-timeofday, #open-rotation, #open-day').showSubform();

		tandemTrippleSwitcher();

        hideValidBox();
		sliderVerteilung();
		
		
		editTable();
		$('a.s-tab').tab();
		$('#tab a').tab();
		/* date */
		function customRange(input) {
			return {minDate: (input.id == 'to' ? $('#form').datepicker('getDate') : null),
				maxDate: (input.id == 'form' ? $('#to').datepicker('getDate') : null)};
		}
//		function customRange2(input) {
//			return {minDate: (input.id == 'ckto' ? $('#ckfrom').datepicker('getDate') : null),
//				maxDate: (input.id == 'ckfrom' ? $('#ckto').datepicker('getDate') : null)};
//		}
		
		$('#form').datepicker({beforeShow: customRange, closeAtTop: false});
		$('#to').datepicker({beforeShow: customRange,closeAtTop: false});
		
		
		// Kampagnebuchen Kriterien, Datumsauswahl
		year = $('#jahr').val();
		now     = new Date();
		
		if((year - now.getFullYear()) == 0) // 1 or 0, z.B. 2009-2008
		{
	        fromdate = new Date(year, now.getMonth(), now.getDate()+3);
	        todate   = new Date(year, now.getMonth(), now.getDate()+3);
			
			mdateFrom = new Date(year, 11, 27, 0, 0, 0);
			mdateTo   = new Date(year, 11, 31, 0, 0, 0);
			
	        $('#ckfrom').datepicker({minDate: fromdate, maxDate: mdateFrom});
	        $('#ckto').datepicker({minDate: todate, maxDate: mdateTo});
			
			
//	        $("#ckfrom,#ckto").datepicker({ 
//	            beforeShow: customRange2
//	        });			
		}
		else
		{
            fromdate = new Date(year, 0, 1, 0, 0, 0);
            todate   = new Date(year, 0, 1, 0, 0, 0);
            
            mdateFrom = new Date(year, 11, 27, 0, 0, 0);
            mdateTo   = new Date(year, 11, 31, 0, 0, 0);
            
            $('#ckfrom').datepicker({minDate: fromdate, maxDate: mdateFrom});
            $('#ckto').datepicker({minDate: todate, maxDate: mdateTo});
		}
		
		$('#datum').datepicker({closeAtTop: false});
		$('#media-list.sort').filterMedia();
		$('#media-list.delete li').deleteLi();
		
		$('div.multiple').multipleSelect();
		$('div.multiple-mod').multipleSelect({delFirst: false});
		$('div.timeday-overview input').checkBox();
		
		flashPlayer.init();
		
		$('input.button').createLinkButton({innerLink: '<span><span><span><span>$value</span></span></span></span>'});
		
		checkUpload();
		
		/* table sorter muss nach button kommen! */
		tableSort();
		/*
		$('table.pick tbody tr').each(function(i){
			var m = ['<abbr>Mo</abbr>','<abbr>Di</abbr>','<abbr>Mi</abbr>','<abbr>Do</abbr>','<abbr>Fr</abbr>','<abbr>Sa</abbr>','<abbr>So</abbr>'],
			u = [' 00:00',' 01:00',' 02:00',' 03:00',' 04:00',' 05:00',' 06:00',' 07:00',' 08:00',' 09:00',' 10:00',' 11:00',' 12:00',' 13:00',' 14:00',' 15:00',' 16:00',' 17:00',' 18:00',' 19:00',' 20:00',' 21:00',' 22:00'];
			$('td',this).each(function(j){
				var name = $(this).attr('headers').replace(' ','_');
				$(this).html('<label><input type="checkbox" name="'+name+'">'+m[j]+u[i]+'</label>');
			});
		});
		*/
		
		if(typeof opencustomer == 'function') {
		  
		  opencustomer();
		}		
		if(typeof openproduct == 'function') {
		  
		  openproduct();
		}
		
		$('#to-mediaselect').bind('click', function(e){
              e.stopPropagation();
              e.preventDefault();			
		      $('#campagne-book').attr({action: '/meinrbc/kampagnebuchenmedienauswahl/sync/true'});
			  $('#campagne-book').submit();
			  return false;
        });
		
		$('a.letter').bind('click', function(e){ 
		      e.stopPropagation();
		      e.preventDefault();
		      $('#campagne-media').attr({action: this});
			  $('#campagne-media').submit();
			  return false;
        });
    }
	
    $(callOnDomReady);
	
})(jQuery);
