/////////////////////////
// Help functions
/////////////////////////

Array.prototype.inArray = function (element) 
{
  var retur = false;
  for (var values in this) 
  {
    if (this[values] == element) 
    {
      retur = true;
      break;
    }  
  }
  return retur;
};

String.prototype.trim = function()
{ 
	str = this.match(/\S+(?:\s+\S+)*/);
	return str ? str[0] : '';
}

function clearInput(obj, color)
{
	if( !obj.hasClass('bind') )
	{
		obj.addClass('bind');
		var default_value = obj.val();
		if( color ) var default_color = obj.css('color');
		obj.focus(function(){
			if (obj.val() == default_value) obj.val("");
			if( color ) obj.css( 'color', color );
		});
		obj.blur(function(){
			if (obj.val() == "") obj.val(default_value);
			if( color ) obj.css( 'color', default_color );
		});
		obj.focus();
	}
}

// Check if < internet explorer 8
var ie = false;
$( function() { ie = $.browser.msie && parseFloat($.browser.version) < 8; } );

/////////////////////////
// Add enter click to input/forms
/////////////////////////

$( function() {
	$('input').keyup(function(e) 
	{
		if(e.keyCode == 13) 
		{
			if($(this).parent('form').size()) $(this).parent('form').submit();
			if($(this).attr('onchange')) $(this).change();
		}
	});
});

/////////////////////////
// Social medi buttons hover
/////////////////////////

$( function() {
	$('.social-hover').hover(function() {
		$(this).attr('src', $(this).attr('src').replace('.jpg', '')+'-hover.jpg');
	}, function () {
		$(this).attr('src', $(this).attr('src').replace('-hover', ''));
	});
});

/////////////////////////
// Top menu in header dropdown
/////////////////////////

$( function () {
	// IE z-index fix for dynamic menus
	if( ie )
	{
		var i = 1000;
		var blocks = $('div, ul');
		$.each(blocks, function() { 
		      $(this).css('z-index', i--);
		});
	}
	
	$('#menu ul>li').hover( function() {
		$(this).find('div').show();
	}, function() {
		$(this).find('div').hide();
	});
	
});

/////////////////////////
// Hide instrument when not a member
/////////////////////////

function hide_is_member(show)
{
	if( show )
		$('#is_member').slideDown();
	else
		$('#is_member').slideUp();
}

/////////////////////////
// Featured bands
/////////////////////////

$(function() {
	var childN = 1;
	update();
	function update()
	{
		if(childN > 1)
			$('#featured_bands span:nth-child('+childN+') span').fadeIn().removeClass('last').click(
				function() {
					$('#featured_bands div').animate( {marginLeft:'+=98px'}, 400 );
					$(this).unbind('click').fadeOut();
					childN--;
					update();
				}
			);
		if(childN+5 != $('#featured_bands img').size())
			$('#featured_bands span:nth-child('+(childN+5)+') span').fadeIn().addClass('last').click(
				function() {
					$('#featured_bands div').animate( {marginLeft:'-=98px'}, 400 );
					$(this).unbind('click').fadeOut();
					childN++;
					update();
				}
			);
	}
	$('#featured_bands span').hover( function() {
		$('.bands-pointer').stop(true, false).animate({ paddingLeft: $(this).position().left + 30 });
		if( $('.bands-pointer img').is(':hidden') ) $('.bands-pointer img').fadeIn();
		if( !$(this).find('span').is(':hidden') )
		{
			$('#featured_bands span').removeClass('featured-band-hover');
			$('.bands-pointer img').fadeOut();
			$('.bands-hover div.default').show();
			$('.bands-hover div.hover').hide();
		}
		else
		{
			$('#featured_bands span').removeClass('featured-band-hover');
			$(this).addClass('featured-band-hover');
			$('.bands-hover span').html( $(this).find('b').html() );
			$('.bands-hover div.default').hide();
			$('.bands-hover div.hover').show();
			$('#band-link').attr('href', $(this).find('a').attr('href') );
		}
	});
});

/////////////////////////
// MP3 Player
/////////////////////////

var toPlay;
var paused = true;

function player()
{
	if (ie) return window['fl']; 
	else return document['fl'];
}

function mp3play( str )
{
	toPlay = str;
	player().mp3play( toPlay );
	pause( false );
}

// update buttons
function pause( bool )
{
	paused = bool;
	if( paused )
	{
		$('#playbtn img').attr('src', '/images/site/track_play.png');
		$('.mp3playing').css('background-image', 'url(/images/site/track_bg.png)');
	}
	else
	{
		$('#playbtn img').attr('src', '/images/site/track_pause.png');
		$('.mp3playing').css('background-image', 'url(/images/site/track_bg_pause.png)');
	}
}

$(function() {
	if( $('.track').size() )
	{
		// load track content
		$('.track a').click( function() {
			if( $(this).parent().hasClass('mp3playing') )
			{
				player().mp3play( toPlay );
				pause( !paused );
			}
			else
			{
				$('.scr').width( 0 );
				pause(true);
				$('.mp3playing').removeClass('mp3playing');
				$('#music-display-container').html('').load( $(this).attr('href'), function() {
					$(this).show();
				});
				$(this).parent().addClass('mp3playing');
			}
			return false;
		});
		// scrubber functionality
		$('.track span.scrubber').click( function(e) {
	     	var offset = $(this).offset();
	   	 	var x = e.pageX - (offset.left);
			$(this).find('span').width( x );
			player().skipTo( x/260 );
			pause( false );
		});
	}
});

function scrubProgress( perc )
{
	if( perc > 0 )
	{
		if( perc > 99 )
		{
			pause( true );
			$('.scr').width( 0 );
		}
		else
		{
			//pause( false );
			$('.mp3playing span.scr').width( Math.round( (perc/100)*260 ) );
		}
	}
}

// Debug function
function jsalert( a )
{
	alert( a );
}

/////////////////////////
// Form functions
/////////////////////////

var currentInput;
$(function() {
	$('.checkbox').click( function() {
		try
		{
			if( $(this).attr('class') != 'checkbox single' )
			{
				if( $(this).attr('name') )
				{
					$('[name='+$(this).attr('name')+']').css('background', '#C9C9CA');
					$('#'+$(this).attr('name')).val($(this).attr('title'));
					$(this).css('background', 'url(/images/site/checkbox_selected.jpg)');
				}
				else if( $(this).attr('id').substr(0,1) == 'l' )
				{
					if( $(this).attr('id').substr(2,1) != currentInput && $(this).attr('title') == 'selected'  )
					{
						$(this).css('background', '#C9C9CA');
						$(this).attr('title', '');
						$('#l'+$(this).attr('id').substr(2,1)).css('border', '1px solid #A7A9AA').val('').blur();
						
					}
					else
					{
						$(this).css('background', 'url(/images/site/checkbox_selected.jpg)');
						$(this).attr('title', 'selected');
						$('#l'+$(this).attr('id').substr(2,1)).css('border', '1px solid #404040');
					}
				}
			}
			else
			{
				if( $('[name='+$(this).attr('name')+']').val() )
				{
					$(this).css('background', '#C9C9CA');
					$('[name='+$(this).attr('name')+']').val( '' );
				}
				else
				{
					$(this).css('background', 'url(/images/site/checkbox_selected.jpg)');	
					$('[name='+$(this).attr('name')+']').val( '1' );
				}
			}
			
		}
		catch( err ) { }
		return false;
	});
	$('.link')
	.focus( function() {
		currentInput = $(this).attr('id').substr(1,1);
		$('#lb'+$(this).attr('id').substr(1,1)).click();
	})
	.blur( function() {
		currentInput = null;
		var allLinks = '';
		$('.link').each(function() {
			if( $(this).val() )
				allLinks = allLinks + $(this).val() + '|';
		});
		$('#link-collector').val( allLinks );
	});
	$('.big').click( function () {
		if( $(this).attr('href') == '#' )
		{
			var form = $(this).parents('form:first');
			form.submit();
		}
	});
});

/////////////////////////
// Country change
/////////////////////////

function changeCountry( country_lang ) 
{
	window.location.href = window.location.href.replace('int-en', country_lang);
	return false;
}

/////////////////////////
// Newsletter
/////////////////////////

$(function () {
	if( $('#email').val() )
	{
		$('#newsletter .submit').click(function() { 
			$.post('http://imaginefestival.net/int-en/process/newsletter', { mail: $('#email').val() },
			   function(data){
			     alert(data);
			   });
		    return false; 
		});
    }
});

/////////////////////////
// Like button
/////////////////////////

function likeBand( bandId, obj )
{
	$.post('http://imaginefestival.net/int-en/process/like_band', { band_id: bandId },
		   function(data){
				if( data == '1' )
				{
					if( !obj ) $('.like-band').html('Thank you!');
					else obj.html('Thank you!');
				}
				else
					alert( 'You need to be logged in.' );
	});
	return false;
}

function likeComment( bandId, obj )
{
	$.post('http://imaginefestival.net/int-en/process/like_comment', { comment_id: bandId },
		   function(data){
				if( data == '1' )
				{
					obj.parent().prepend('<span>You like this!</span>');
					obj.remove();
				}
				else
					alert( 'You need to be logged in.' );
	});
	return false;
}


/////////////////////////
// Featured images on homepage
/////////////////////////

var interval = null;

$(function () {
	$('#ft-images a').click( function () {
		
		if( $('#b'+$(this).attr('name').substring(1)+'').is(':hidden') )
		{
			var bigimg = $('#b'+$(this).attr('name').substring(1)+'');
			$('#ft-big-image').remove('#b'+$(this).attr('name').substring(1)+'');
			$('#ft-big-image').prepend(bigimg);
			bigimg.slideDown(400, function() {
				$('#ft-big-image div.ft-big:visible:last').hide();
			});
			$('#ft-images a.selected').removeClass('selected');
			$(this).addClass('selected');
			return false;
		}
		
	}).hover( function() {
		
		if( $('#b'+$(this).attr('name').substring(1)+'').is(':hidden') )
		{
			interval = window.clearInterval(interval);
			$(this).click();
		}
		
	});
	if( $('#ft-images a').size() )
	{
		interval = window.setInterval(function() {
 			var current = $('#ft-big-image div.ft-big:visible').attr('id').substring(1);
 			if( current == '5' ) current = '0';
 			$('[name=f'+(parseInt(current)+1).toString()+']').click();
		}, 5000);
	}
});

/////////////////////////
// Event calender
/////////////////////////

var m_names = new Array(
							"january", "february", "march", 
							"april", "may", "june", "july", "august", "september", 
							"october", "november", "december"
						);
var currentEvent;
var currentMonth;
var currentYear;
						
// Year is 0: vorig jaar, 1: dit jaar, 2: volgend jaar
// Na huidige dag: laatste parameter true

function focusMonth( month, year, month_nr, curr_day )
{	
	if( month == 'next' )
		$('.m a.selected').nextAll('a.event-day:first').click();
	else if( month == 'prev' )
		$('.m a.selected').prevAll('a.event-day:first').click();
	else if( $('#'+month+year).hasClass('event-day') )
	{
		try
		{
			var date = new Date( );
			var thisYear = date.getFullYear();
			
			currentMonth = month_nr;
			currentYear = thisYear+(year-1);
			
			el = $('#'+month+year);
			
			pos = el.position().top - 76;
			
			$('.m div').animate({ marginTop: -pos });
			$('.m a.selected').removeClass('selected');
			el.addClass('selected');
			
			// Get the dates for the events and focus days
			$('.day').addClass('no-event-day').removeClass('event-day')
					 .removeClass('hidden-day').removeClass('selected')
					 .die();
			
			$.get('http://'+location.hostname+'/int-en/ajax/calendar_days/'+currentYear+'/'+currentMonth, function(data) {
				var total = parseInt(data.substring(0,2));
				if( data.substring(3) )
				{
					var dates = data.substring(3).split(',');
					for( e in dates )
					{
						$('#day'+dates[e]).addClass('event-day');
					}
					if( !curr_day )
						focusDay( $('.d a.event-day:first') );
					else
						focusDay( $('.d a.#day'+curr_day) );
				}
				for( var x = total+1; x <=31; x++ )
				{
					$('#day'+x).addClass('hidden-day');
				}
				$('.d a.event-day').click(function() {
					focusDay($(this));
				});
			});
		}
		catch(e) { }
	
		return true;
	}
	
	return false;
}

function focusDay( day )
{
	try
	{
		if( day == 'next' )
			el = $('.d a.selected').nextAll('a.event-day:first');
		else if( day == 'prev' )
			el = $('.d a.selected').prevAll('a.event-day:first');
		else
		{
			el = day;
			if( !el.hasClass('event-day') )
			{
				el = el.nextAll('a.event-day:first');
				if( !el.size() )
					focusMonth('next');
			}
		}
			
		pos = el.position().top - 76;
		
		$('.d div').animate({ marginTop: -pos });
		$('.d a.selected').removeClass('selected');
		el.addClass('selected');
		$('.event-info').load('http://'+location.hostname+'/int-en/ajax/calendar_event_info/'+currentYear+'/'+currentMonth+'/'+el.attr('id').substring(3), function() {
			currentEvent = 1;
			$('#rsvp').attr( 'href', 'http://www.facebook.com/event.php?eid='+$('#fbid1').val() );
			eventInfoButtons();
		});
	}
	catch(e) { }
	return false;
}

// Update classes
function eventInfoButtons()
{
	if( currentEvent>1 ) $('a.left').addClass('selected');
	else $('a.left').removeClass('selected');
	if( currentEvent<window.totalEvents ) $('a.right').addClass('selected');
	else $('a.right').removeClass('selected');
}

// Set current date in calendar
$( function() {
	
	if( $('.cal-links').size() )
	{	
		var date = new Date( );
		var month = date.getMonth();
		var thisYear = date.getFullYear();
		var day = date.getDate();
		$('.month').addClass('no-event-day');
		$.get('http://'+location.hostname+'/int-en/ajax/calendar_months/'+thisYear, function(data) {
			if( data )
			{
				var months = data.split(',');
				$('.month').each( function() {
					var id = $(this).attr('id');
					if( months.inArray( id.substring(0, id.length-1)+(thisYear+parseInt(id.substring(id.length-1)-1)) ) )
					{
						$(this).removeClass('no-event-day').addClass('event-day');
					}
				});
				if( !focusMonth( m_names[month], 1, month+1, day ) )
				{
					$('.m a.cal-link:nth-child('+(month+12)+')').nextAll('a.event-day:first').click();
				}
			}
		});
	}
	
});

// Scroll to the next/prev event
function eventScrollInfo()
{
	$('#rsvp').attr( 'href', 'http://www.facebook.com/event.php?eid='+$('#fbid'+currentEvent).val() );
	$('#event-info-container').animate( { marginLeft: -(327*(currentEvent-1)) } );
	eventInfoButtons();	
	$('.events-pagination span').html(currentEvent);
}

// Event arrow functionality
$( function() {	
	$('a.left').live('click', function () {
		if( currentEvent>1 )
		{
			currentEvent--;
			eventScrollInfo();
		}
	});	
	
	$('a.right').live('click', function () {
		if( currentEvent<totalEvents )
		{
			currentEvent++;
			eventScrollInfo();
		}
	});		
});

/////////////////////////
// Loop through fan stream
/////////////////////////

var fanStreamInterval;
var totalStreams;
var x = 1;

$( function() {
	if( totalStreams = $('.comment').size() )
	{
		fanStreamInterval = window.setInterval(function() {
			if( x == totalStreams-1 )
			{
				$('#fanstream-container').animate({marginTop:0});
				x=0;
			}
  			else
  			{
	  			if( !ie )
	  			{
	  				$('#fanstream-container').animate({marginTop:parseInt($('#fanstream-container').css('margin-top'))-100});
	  			}
	  			else // IE7 problems
	  				$('#fanstream-container').css('margin-top', (parseInt($('#fanstream-container').css('margin-top'))-100).toString()+'px');
  			}
  			x++;
		}, 5000); 
	}
});

/////////////////////////
// Band search
/////////////////////////

var lastSearch;

function searchBands()
{
	var extraPath = '';
	var term = ($('#search-field input').val()).toString().trim().replace(/\//g, '');
	if( term == '' || term == "Know the band you&#39;re after?".replace('&#39;','\'') ) term = '_';
	
	extraPath = term+'/';
	var rest = ['genre', 'venue', 'region','edition'];
	for( var i = 0; i<rest.length; i++ )
	{
		var v = $('#'+rest[i]+'-filter').val();
		if(v != null && v != 'undefined' && v != 'Know the band you\'re after?') {
			extraPath += $('#'+rest[i]+'-filter').val()+'/';
		} else {
			extraPath += '_/';
		}
	}
	if( extraPath == lastSearch ) return false;
	lastSearch = extraPath;
	if( !ie ) $('.bands-results').fadeOut();
	else $('.bands-results').hide();
	$('.bands-results').load('http://'+location.hostname+'/int-en/ajax/band_search/'+extraPath, function() {
			if( !ie ) $('.bands-results').fadeIn();
			else $('.bands-results').show();
	});
}


/////////////////////////
// Remove pagination when empty quick fix
/////////////////////////

$( function() {
	if( $('#news-paginate').size() && !$('#news-paginate a').size() )
		$('#news-paginate').hide();
});

/////////////////////////
// FAQ functionality
/////////////////////////

$( function() {
	if( $('.faq').size() )
	{
		$('.faq-question').click( function() {
			
			if( $(this).hasClass('down') )
			{
				$(this).removeClass('down');
				$(this).next().slideUp();
			}
			else
			{
				$('.faq-question.down').removeClass('down').next().slideUp();
				$(this).addClass('down');
				$(this).next().slideDown();
			}
		});
	}
});


/////////////////////////
// Slide down top menu to show countries/regions
/////////////////////////


function slideCountries()
{
	if( $('#top-container').height() < 300 )
	{
		$('#top-container').animate({height: 395});
		$('a.down img').attr('src', '/images/site/slide_up.png');
	}
	else
	{
		$('#top-container').animate({height: 50});
		$('a.down img').attr('src', '/images/site/slide_down.png');	
	}
}

/////////////////////////
// Video thumbnails
/////////////////////////

$(function() {
	if( $('div.video-thumbs span.thmb').size() )
	{
		if( $('div.video-thumbs span.thmb').size() > 3 )
		{
			$('div.video-thumbs span.thmb:last').prependTo('.video-thumbs-container');
			$('div.video-thumbs span.thmb').eq(1).find('a').click();
			function set_vid_nav()
			{
				if(document.selection != null) {
					document.selection.empty();
				} else if(window.getSelection) {
					window.getSelection().removeAllRanges();
				}
				$('div.video-thumbs span.over').unbind('click').hide();
				$('div.video-thumbs span.over:first')
											.removeClass('last')
											.show()
											.click( function() 
											{
												$('div.video-thumbs span.thmb:last').prependTo('div.video-thumbs-container');
												set_vid_nav();
											}
											);
				$('div.video-thumbs span.over:eq(3)')
											.addClass('last')
											.show()
											.click( function() 
											{
												$('div.video-thumbs span.thmb:first').appendTo('div.video-thumbs-container');
												set_vid_nav();
											}
											);
				
			}
			set_vid_nav();

		}
		else
		{
			$('.video-thumbs span:first a').click();
			$('.video-thumbs div').css('margin-left', '0px');
		}
			
		$('.video-thumbs span').hover( function() {
			if( $(this).find('span').is(':hidden') )
			{
				$('.video-thumbs span').removeClass('featured-band-hover');
				$(this).addClass('featured-band-hover');
				$('.video-hover span').html( $(this).find('b').html() );
				$('.video-hover').show();
			}
			else
				$('.video-thumbs span').removeClass('featured-band-hover');
				$('.video-hover span').html( $(this).find('b').html() );
				$('.video-hover').show();
				//$('.video-hover').hide();
		});
	}	
});

function showVid( vidType, vidId )
{
	if( vidType == 'yt' )
	{
		$('.video-frame').html( '<iframe class="youtube-player" type="text/html" width="337" height="238" src="http://www.youtube.com/embed/'+vidId+'" frameborder="0">' );	
	}
}

/////////////////////////
// Flickr gallery
/////////////////////////

$(function() {
	if( $('#flickr-gallery').size() )
	{
		var childN = 1;
		
		function update3()
		{
			if(childN > 1)
				$('#flickr-gallery span:nth-child('+childN+') span').fadeIn().removeClass('last').click(
					function() {
						$('#flickr-gallery div').animate( {marginLeft:'+=98px'}, 400 );
						$('#flickr-gallery span span').unbind('click').fadeOut();
						childN--;
						update3();
					}
				);
			if(childN+5 != $('#flickr-gallery img').size())
				$('#flickr-gallery span:nth-child('+(childN+5)+') span').fadeIn().addClass('last').click(
					function() {
						$('#flickr-gallery div').animate( {marginLeft:'-=98px'}, 400 );
						$('#flickr-gallery span span').unbind('click').fadeOut();
						childN++;
						update3();
					}
				);
		}
		
		update3();
		
		/*$('#flickr-gallery span').hover( function() {
			
			if( !$(this).find('span').is(':hidden') )
			{
				$('#flickr-gallery span').removeClass('featured-band-hover');
			}
			else
			{
				$('#flickr-gallery span').removeClass('featured-band-hover');
				$(this).addClass('featured-band-hover');
				$('#flickr-big').attr('src', $(this).find('a').attr('href'));
			}
		});
		$('#flickr-gallery span:first').hover();*/
	}
});

/////////////////////////
// Remove artist
/////////////////////////

function removeArtist(id)
{
	$.get('http://imaginefestival.net/int-en/process/remove_artist/'+id);
}

/////////////////////////
// My profile dropdown
/////////////////////////

var checkInterval = null;
var hover = false;

$( function() {
	$('a.mp').hover( function() {
			hover = true;
			clearInterval( checkInterval );
			$(this).addClass('over');
			$('#my-profile').show()
							.css('left', $('a.mp').offset().left)
							.css('top', $('a.mp').offset().top+38 );
		}, function() { 
			checkInterval = setInterval(checkDropDown, 1000); hover = false; 
	});
	$('#my-profile').hover( function() { hover = true; }, function() { hover = false; } );
});

function checkDropDown()
{
	if( !hover )
	{
		$('#my-profile').hide();
		$('a.mp').removeClass('over');
	}
}
