/**
 * @author		Angelo Dini
 * @copyright	http://www.divio.ch
 */

// check if console.log is available
if (window['console'] === undefined) window.console = { log: function(){} };
var log = (window.ActiveXObject) ? console.debug : console.log;

// allow jQuery to chain .log
if('jQuery' in window) jQuery.fn.log = function(msg) { console.log("%s: %o", msg, this); return this; };

// set namespace
var BASE = {};

/**
 * MODULES
 * ##################################################|
 * private scope - do it the moo way
 */
jQuery(document).ready(function ($) {
    
    $('.noactionform').submit(function(){
        $('#search_songs').click();
        return false;
    });
    
	BASE = {
		init: function() {
			// reflection auto startup
			if($('.reflection').length) $('.reflection').reflect({ 'height': 0.25 });

			// font-family auto startup
			//try{Typekit.load();}catch(e){}
			
			// ie6 fixes
			$.fn.fix_pseudos = function(options){
				this.filter(":first-child").addClass("first-child");
				this.filter(":last-child").addClass("last-child");
			}
			$('.tbl_default tbody td, .tbl_default tfoot td, .tbl_programm tbody tr td, .tbl_programm thead tr td, .tbl_default th').fix_pseudos();
			$('.tabnav li, .subnav li').fix_pseudos();
		}
	};
	BASE.init();

	/* toolbar */
	BASE.toolbar = {
		init: function () {
			this.toolbar = $('#topbar');
			this.triggerShow = $('.open_toolbar');
			this.triggerShow.bind('click', $.proxy(BASE.toolbar, 'show'));

			this.triggerHide = $('.close_toolbar');
			this.triggerHide.bind('click', $.proxy(BASE.toolbar, 'hide'));

			this.header = $('#header');
			this.logo = $('#mainlogo a');
		},
		show: function (event) {
			event.preventDefault();
			this.triggerShow.fadeOut();
			this.toolbar.slideDown();
			this.header.animate({ 'padding-top': '40px' });

			this.logo.animate({ 'margin-top': '25px' });
			$(document.body).animate({ 'background-position': '50% 255px' });
		},
		hide: function (event) {
			event.preventDefault();
			this.triggerShow.fadeIn();
			this.toolbar.hide();
			this.header.animate({ 'padding-top': '1px' });

			this.logo.animate({ 'margin-top': '40px' });
			$(document.body).animate({ 'background-position': '50% 215px' });
		}
	};
	BASE.toolbar.init();
	
	/* feature */
	BASE.feature = {
		init: function () {
			this.container = $('#feature .feature-container');
			this.container.css('display', 'block');
			this.state = 0;

			this.trigger = $('#feature .feature-closer');
			this.trigger.css('display', 'block');
			this.trigger.bind('click', $.proxy(BASE.feature, 'toggle'));

			if(this.container.hasClass('hidden')) {
				this.toggle();
			}
		},
		toggle: function (event) {
			if(event) event.preventDefault();

			this.container.stop().slideToggle();
			this.trigger.toggleClass('feature-active');
		}
	};
	BASE.feature.init();

	/* radio player */
	BASE.player = {
		init: function(obj) {
			var container = $('.feature-container');

			var tracklist = container.find('.track-item');
			var playing = container.find('.track-current');
			var moderator = container.find('.track-profile');

			//onload
			var request = function () {
				$.ajax({
					url: obj.data_url,
					dataType: "json",
					success: update
				});
			}
			// init
			//setTimeout(request, 500);
			
			//relpace player popup link with iPhone app download
			if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i)) ) {
				$("#btn_webradio")
					.unbind('click')
					.removeAttr("rel")
					.attr("href","http://clk.tradedoubler.com/click?p=24372&a=1646143&url=http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=328024679&mt=8")
					.find("span").text("Download iPhone App");
			}

			// interval
			setInterval(request, 30000);

			// refresh function
			var update = function refresh(data) {
				var data = data.results;
				if (data != null) {
					// update: track-list
					$(data.history).each(function(index){
						$(tracklist[index]).find('.title strong').html(data.history[index].artist).end().find('.title .track').html(data.history[index].title).end().find('.time').html(data.history[index].played_at).end().find('.img img').attr('src', data.history[index].cover).end().find('.buy a').attr('href', data.history[index].buy_link);
					});
					
					// update: playing now
					playing.find('.img img').attr('src', data.now_playing.cover).end().find('.track .title').html(data.now_playing.artist).end().find('.track strong').html(data.now_playing.title).end().find('.buy a').attr('href', data.now_playing.buy_link);
					
					// update: moderator
					moderator.find('.moderator a').attr("href", data.moderator.profile_url).end()
							.find('.moderator a strong').html(data.moderator.name).end()
							.find('.right a').attr("href", data.moderator.profile_url).end()
							.find('.right a img').attr('src', data.moderator.photo).end()
							.find('.shoutout').html(data.moderator.shoutout);
					if (data.moderator.name == '') {
						moderator.find('.moderator span').hide();
					}else {
						moderator.find('.moderator span').show();
					}
					$('.reflected').reflect({ 'height': 0.25 });
				}
				// update reflection
				setTimeout(function () {
					$('.reflected').reflect({ 'height': 0.25 });
				}, 1000);
			};
		}
	};

	/* tabbing */
	BASE.tabs = {
		init: function () {
			this.triggers = $('.tabnav li a');
			this.triggers.bind('click', $.proxy(BASE.tabs, 'change'));
			
			var index = 0;
			// check if an element is selected
			var activeIndex = 0;
			this.triggers.each(function (index, item) {
				if($(item).parent().hasClass('active')) activeIndex = index;
			});
			
			$(this.triggers[activeIndex]).parent().addClass('active');

			this.containers = $('.tabcontainer');
			this.containers.css('display', 'none');
			$(this.containers[activeIndex]).css('display', 'block');
		},
		change: function (e) {
			e.preventDefault();
			var index = this.triggers.index(e.target);

			// set new tab
			$(this.triggers).parent().removeClass('active');
			$(this.triggers[index]).parent().addClass('active');

			this.containers.css('display', 'none');
			$(this.containers[index]).css('display', 'block');
		}
	};
	if($('.tabnav li').length) BASE.tabs.init();

	/* music archive */
	BASE.musicarchive = {
		init: function (urls) {
			this.urls = urls;
			this.container = $('#data_table tbody');

			// date (calendar) events
			$.datepicker.setDefaults($.datepicker.regional['fr']);
			
			this.date = {
				from: $("#date_from input"),
				to: $("#date_to input")
			};
			this.date.from.bind('click', function (e) { e.preventDefault(); });
			this.date.from.datepicker();
			this.date.to.datepicker();
			this.date.to.bind('click', function (e) { e.preventDefault(); });

			// time events
			this.time = {
				fromUp: $('#time_from .time-up'),
				fromDown: $('#time_from .time-down'),
				toUp: $('#time_to .time-up'),
				toDown: $('#time_to .time-down')
			};
			this.time.fromUp.bind('click', { dir: 'up', type: 'from' }, $.proxy(BASE.musicarchive, 'changeTime'));
			this.time.fromDown.bind('click', { dir: 'down', type: 'from' }, $.proxy(BASE.musicarchive, 'changeTime'));
			this.time.toUp.bind('click', { dir: 'up', type: 'to' }, $.proxy(BASE.musicarchive, 'changeTime'));
			this.time.toDown.bind('click', { dir: 'down', type: 'to' }, $.proxy(BASE.musicarchive, 'changeTime'));

			// attach ajax events
			this.triggers = {
				latest: $('#latest_songs'),
				search: $('#search_songs'),
				filter: $('#filter_songs')
			};
			this.triggers.latest.bind('click', $.proxy(BASE.musicarchive, 'filterByLatest'));
			this.triggers.search.bind('click', $.proxy(BASE.musicarchive, 'filterBySearch'));
			this.triggers.filter.bind('click', $.proxy(BASE.musicarchive, 'filterByFilter'));
			
			// update script
			this.buildNav();
		},
		changeTime: function (obj) {
			obj.preventDefault();

			var el = $(obj.currentTarget).parent().find('span');
			var time = el.html();

			var tmp = time.split(':')[0];
				tmp = (tmp < 10) ? parseInt(tmp.replace('0', '')) : parseInt(tmp);

			// increment/decrement
			if(obj.data.dir == 'up') {
				if(tmp >= 23) tmp = -1;
				tmp++;
			} else {
				if(tmp == 0) tmp = 24;
				tmp--;
			}
			// add leading zero
			if(tmp < 10) tmp = '0' + tmp;

			// crosscheck items (todo)

			el.html(tmp + ':00');
		},
		filterByLatest: function (obj) {
			obj.preventDefault();
			var that = this;
			$('.small_loder').removeClass('hidden');

			// request
			$.get(this.urls.latest, function (data) {
				$('#data_table tbody').html(data);
				// rebuild nav
				that.buildNav();
				$('.small_loder').addClass('hidden');
			});
		},
		filterBySearch: function (obj) {
			obj.preventDefault();
			var that = this;
			$('.small_loder').removeClass('hidden');

			var term = $('#field_topsearch').val();
			if(term == 'Suche...') term = '';

			// request
			$.get(this.urls.search, { 
				term: term
			}, function (data) {
				$('#data_table tbody').html(data);
				// rebuild nav
				that.buildNav();
				$('.small_loder').addClass('hidden');
			});
		},
		filterByFilter: function (obj) {
			obj.preventDefault();
			var that = this;
			$('.small_loder').removeClass('hidden');

			var startStr = $('#date_from input').val().replace('.', '_').replace('.', '_') + '_' + $('#time_from span').text().replace(':', '_');
			var endStr = $('#date_to input').val().replace('.', '_').replace('.', '_') + '_' + $('#time_to span').text().replace(':', '_');

			// request
			$.get(this.urls.filter, {
				'start': startStr,
				'end': endStr
			}, function (data) {
				$('#data_table tbody').html(data);
				// rebuild nav
				that.buildNav();
				$('.small_loder').addClass('hidden');
			});
		},
		buildNav: function () {
			$('#data_table').css({'top': 0});
			// calc bound
			var bound = (Math.ceil(this.container.find('tr').length/5));

			// generate anchors
			var els = '';
			for(var i=0; i < bound; i++) {
				els += '<a href="#">' + (i+1) + '</a>';
			}

			// get them every time
			$('.tablenav').html(els);
			$('.tablenav').find('a:first-child').addClass('active');
			$('.tablenav').find('a').bind('click', $.proxy(BASE.musicarchive, 'changeTo'));

			// audio testing
			this.audio();
		},
		changeTo: function (obj) {
			obj.preventDefault();
			var index = $($(obj.currentTarget).parent().find('a')).index($(obj.currentTarget));
			// change active state
			$('.tablenav a').removeClass('active');
			$($($('.tablenav')[0]).find('a')[index]).addClass('active');
			$($($('.tablenav')[1]).find('a')[index]).addClass('active');

			// animation
			$('#data_table').animate({'top': -(index*($('#data_table').find('tr:first-child').height()*5))+'px'}, { duration: 750 });
		},
		audio: function () {
			// only webkit or chrome
			if($.browser.webkit) {
				$('.itunes_player').removeClass('hidden');

				$('.itunes_player').bind('click', function (e) {
					e.preventDefault();
                    var audio = $(this).parent().find('audio')[0];
					$('audio').each(function(){
					    var other = $(this)[0];
					    if (!other.paused && audio.src != other.src){
					        other.pause();
	                        $(this).parent().find('a').css('background-position', 'left -180px');
					    }
					});
					if (audio.paused) {
						$(this).find('a').css('background-position', 'left -300px');
						audio.play();
					} else {
					    audio.pause();
						$(this).find('a').css('background-position', 'left -180px');
					}
				});
			}
		}
	};

	/**
	 * Auto input fill-in module
	 * @param: label (if true than labeltext on parent else rel attribut on this)
	 * @param: strip (replacement text)
	 */
	$.fn.fieldLabel = function (options) {
		//var $this = this;
		var options = $.extend({
			label: true,
			strip: '',
			add: ''
		}, options);

		// store label element and use replacement
		var label = (options.label == true) ? $(this).parent().find('label').text() : label = $(this).attr('rel');
		label = label.replace(options.strip, '');
		label += options.add;

		// initialize
		if(this.attr('value') == '') this.attr('value', label);
		
		// attach event
		this.bind('click blur', function (e) {
			($(this).attr('value') == label) ? hide($(this), e) : show($(this), e);
		})

		// show functionality
		function show(el, e) {
			if(el.attr('value') != '') return false;
			el.attr('value', label);
		};

		// hide functionality
		function hide(el, e) {
			if(e.type == 'blur' && el.attr('value') == label) return false;
			el.attr('value', '');
		};

		// keep chaining
		return this;
	};
	$('#field_topsearch').fieldLabel({ strip: ': ', add: '...' });
	$('#field_freqcity').fieldLabel({ strip: ': ', add: '...' });
	//$('#field_searchmusic').fieldLabel({ strip: ': ', add: '...' });

	/**
	 * Target modifier
	 * @param: pattern (property:initialClass:target)
	 */
	$.fn.defineTarget = function (options) {
		var options = $.extend({
			pattern: 'rel:target:blank'
		}, options);
		var opt = options.pattern.split(':');

		return this.each(function () {
			if(($(this).attr(opt[0]) == (opt[1]+':'+opt[2]))) $(this).attr('target', opt[2]);
		});
	};
	$('a').defineTarget();

	/**
	 * E-Mail encrypter
	 */
	$.fn.encrypter = function (options) {
		var options = $.extend({
			/* none defined */
		}, options);
		var mailto = 'mailto:' + this.attr('rel') + '@' + this.text();

		this.attr('href', mailto);
		this.html(mailto.replace('mailto:', ''));
	};
	$('.encrypte').encrypter();

	/**
	 * POP-UPer
	 */
	$.fn.popup = function (options) {
		var options = $.extend({
			trigger: 'open',
			width: 200,
			height: 50
		}, options);

		// set vars
		var url = this.attr('href');
		var size = {
			'x': this.attr('rel').split(':')[1],
			'y': this.attr('rel').split(':')[2]
		};

		// attach event
		this.bind('click', open_window);

		// some function
		function open_window(e) {
			e.preventDefault();

			window.open(url, '_blank', 'width=' + size.x + ',height=' + size.y + ',status=yes,scrollbars=yes,resizable=yes');
		};

		// keep chaining
		return this;
	};
	if($('.feature-container p .button').length) $('.feature-container p .button').popup();

});
//jQuery(document).ready(function ($) { /* when js in head */ });