/**
 * @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://zuerisee.mp3.green.ch/listen.pls")
					.find("span").text("Webradio starten");
			}

			// 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(':', '_');

			var term = $('#field_topsearch').val();
			if(term == 'Suche...') term = '';

			// request
			$.get(this.urls.filter, {
				'start': startStr,
				'end': endStr,
				'term': term
			}, 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');
					}
				});
			}
		}
	};

	/* team module */
	BASE.team = {
		init: function (cols, json) {
			this.canvas = $('.team');
			this.anchors = this.canvas.find('a');
			this.images = this.anchors.find('img');
			this.bound = this.anchors.length;
			this.imgUrl = '/media/img/team/';
			this.json = json;
			this.cols = cols;
			this.counter = 0;

			// preloader
			this.preloader();

			// attach events
			this.anchors.bind('mouseenter', $.proxy(BASE.team, 'setup'));
			this.anchors.bind('mouseleave', $.proxy(BASE.team, 'reset'));
		},
		setup: function (obj) {
			// save index
			this.selected = this.anchors.index($(obj.currentTarget));

			// loop
			this.images.each($.proxy(BASE.team, 'update'));
			this.counter = 0;
		},
		preloader: function () {
			var images = '';
			this.images.each(function (index, item) {
				// loop 8 times
				for(i=0; i<9; i++) {
					images += '"' + $(item).attr('src').replace('0', i) + '"';
					if(index != this.bound && i < 8) {
						images += ',';
					}
				}
			});
			// load preloader
			$.preLoadImages(images);
		},
		update: function (index, item) {
			// save prefix
			var prefix = $(item).attr('src').split('state_')[0].replace(this.imgUrl, '');

			// initial value
			var value = 0;
			var row = (Math.floor((index/this.cols))+1);

			// if index smaller than selected index
			if(index < this.selected) {
				// check if its cornered 4,6
				value = (this.counter == (row-1)) ? 4 : 6;
	
				// check if its vertical 5
				if((this.selected-index) % this.cols == 0) {
					value = 5;
					// increase counter
					this.counter++;
				}
				
				// check if its same wor 3,7
				if(row == (Math.floor(this.selected/this.cols)+1)) value = 3;
			}

			// if index equals selected index
			if(index == this.selected) value = 0;

			// if index greater than selected index
			if(index > this.selected) {
				// check if its cornered 4,6
				value = (this.counter == (row-1)) ? 8 : 2;

				// check if its vertical 1
				if((this.selected-index) % this.cols == 0) {
					value = 1;
					// increase counter
					this.counter++;
				}

				// check if its same wor 3,7
				if(row == (Math.floor(this.selected/this.cols)+1)) value = 7;
			}

			// render item compared to saved value
			$(item).attr('src', this.imgUrl + '' + prefix + 'state_' + value + '.jpg');
		},
		reset: function () {
			var imgUrl = this.imgUrl;
			
			this.images.each(function (index, item) {
				// get prefix
				var prefix = $(item).attr('src').split('state_')[0].replace(imgUrl, '');

				$(item).attr('src', imgUrl + prefix + 'state_0.jpg');
			});
		}
	};
	// need to define how many column
	BASE.team.init(4);

	/**
	 * 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
	 * @version: 0.3.0
	 * @param: property (target:blank)
	 * @example: <a href="#" rel="target:blank">Lorem Ipsum</a>
	 */
	$.fn.defineTarget = function (options) {
		var options = $.extend({ property: 'rel' }, options);
		return this.each(function () {
			$(this).attr('target', '_' + $(this).attr(options.property).split(':')[1]);
		});
	};
	if(!(navigator.userAgent.match(/iPhone/i)) || !(navigator.userAgent.match(/iPod/i)) || !(navigator.userAgent.match(/iPad/i)) ) {
		$('a[rel*="target:"]').defineTarget();
		$('a[class*="target:"]').defineTarget({ property: 'class' });
	}
	/**
	 * 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();

	/**
	 * Horizontal dropdown menu
	 * @version: 0.2
	 * @param: fx (transition effect: fade, slide or toggle)
	 * @example: $(element).dropdown();
	 */
	$.fn.dropDownMenu = function (options) {
		var $this = this;
		var timer;
		var options = $.extend({
			fx: 'toggle',
			delay: 0
		}, options);

		// autohide subtree
		$this.find('ul').hide();

		// mouseenter event
		$this.find('li').bind('mouseenter', function (e) {
			if($(this).find('ul').length) show($(this), $(this).find('ul'));
		});

		// mouseleave event
		$this.find('li').bind('mouseleave', function (e) {
			var el = $(this);
			if(el.find('ul').length) {
				timer = setTimeout(function () {
					hide(el, el.find('ul'));
					el.removeClass('hover');
				}, options.delay);
				el.find('ul').bind('mouseenter', function () {
					clearTimeout(timer);
				});
			}
		});

		// show menu
		function show(parent, child) {
			parent.addClass('hover');
			if(options.fx == 'toggle') child.css('display', 'block').stop().show();
			if(options.fx == 'slide') child.css('height', 'auto').stop().slideDown();
			if(options.fx == 'fade') child.css('opacity', 1).stop().fadeIn();
		}

		//hide menu
		function hide(parent, child) {
			if(options.fx == 'toggle') child.stop().hide();
			if(options.fx == 'slide') child.stop().slideUp();
			if(options.fx == 'fade') child.stop().fadeOut();
		}

		// keep chaining
		return this;
	};
	$('.ddmenu').dropDownMenu();

});
//jQuery(document).ready(function ($) { /* when js in head */ });
