(function($){ 
	$.fn.defaultValueActsAsHint = function() {
		return this.each(function() {
			var self = $(this);
			self.attr('_default', self.attr('value'))
			self.addClass('hint');

			self.bind('focus', function(event) {
				var self = $(this);
				if (self.attr('_default') == self.attr('value'))
					self.removeClass('hint').attr('value', '');
			});

			self.blur(function() {
				var self = $(this);
				if ($.trim(self.attr('value')) == '')
					self.addClass('hint').attr('value', self.attr('_default'));
			});

		});
	};
})(jQuery);
jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} 
});
function centre_nav() {
	$('.navi').css({'width': $('.navi > a').length * 15, 'margin-left':  (872 - ($('.navi > a').length * 14)) / 2});
};
function start_workshop_slideshow() {
	$('a.prev , a.next').addClass('hide_nav')
	$('a.playstop').addClass('playing');
	$('a.playstop').attr("title", "pause slideshow");
	$('div.scrollable').scrollable({api:true}).getConf().slideshow = window.setInterval(function() {
		var my_scroll = $('div.scrollable').scrollable({api:true});
		if (active_index() + 1>= my_scroll.getSize()) {
			$('div.scrollable div.items div.active').removeClass('active').siblings('.item:first').addClass('active');	
			my_scroll.begin();
		} else {
			$('div.scrollable div.items div.active').removeClass('active').next().addClass('active');	
			my_scroll.next();
		}
	}, 7000);
};
function stop_workshop_slideshow() {
	$('a.prev , a.next').removeClass('hide_nav')
	$('a.playstop').removeClass('playing');
	$('a.playstop').attr("title", "play slideshow");
	window.clearInterval($('div.scrollable').scrollable({api:true}).getConf().slideshow);
};
function active_index() {
	return $.inArray($('.active').get(0),$('div.items div.item'));
}
function flashPutHref(href) { location.href = href; }
function siteDate(theDate) {
  var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
  var dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
  var today = new Date();
  var ord = '';
  switch (theDate.getDate()) {
    case 1:
    case 21:
    case 31:
      ord = 'st';
      break;
    case 2:
    case 22:
      ord = 'nd';
      break;
    case 3:
    case 23:
      ord = 'rd';
      break;
    default:
      ord = 'th'
  }
  return dayNames[theDate.getDay()] + ' ' + theDate.getDate() + ord + ' ' + monthNames[theDate.getMonth()] + ' ' + theDate.getFullYear();
}
$(document).ready(function(){
  $('#dvDateTime').html(siteDate(new Date()));
	$(".next").click(function() {
		if (active_index() + 1 >= $('div.scrollable').scrollable({api:true}).getSize()) { return false; }
    // if ($('.active').next('.dummy').length) { return false; }
		$('div.scrollable div.items div.active').removeClass('active').next().addClass('active');	
	});
	$(".prev").click(function() {
		if (active_index() <= 0) { return false; }
		$('div.scrollable div.items div.active').removeClass('active').prev().addClass('active');	
	});
	$("div.scrollable").scrollable({
		size: 7,
		prev: '#scroll_prev',
		next: '#scroll_next',
		onSeek: function(index) {
			// centre the naviagtor
			centre_nav();
			var workshop_id = $('div.scrollable div.items div.active').get(0).id.match(/\w+_(\d+)/)[1];
			var selected_id = $('div.alldetails').get(0).id.match(/\w+_(\d+)/)[1];
			if (workshop_id != selected_id) {
			  $('#workshop_main_wait').show();
				$.getScript('/pages/workshops/' + workshop_id);			  
			}
		}
	}).navigator('.navi');
	$("div.scrollable div.item").click(function(){
		stop_workshop_slideshow();
	});
	if ($('.navi').length) {
    centre_nav();
	};
	if ($('a.playstop').length && !location.href.match(/noslideshow/)) {
		window.setTimeout("start_workshop_slideshow()", 4000);
	};
	$("a.playstop").click(function() {
		if ($(this).hasClass('playing')) {
			stop_workshop_slideshow();
		} else {
			start_workshop_slideshow();
			$('div.scrollable div.items div.active').removeClass('active').next().addClass('active');	
			$('div.scrollable').scrollable({api:true}).next();
		}
	});
	$('select#filter').change(function() {
	  $('#ws_spinner').show();
		$.ajax({type: 'GET', url: '/pages', data: {filter: this.value}, dataType: 'script'});
	});
	$('#ws_searchbox').bind('submit ' + ($.browser.msie ? 'click' : 'change'), function(e) {
    var el = e.target;
		if (el.id === 'ws_filter' && ($.browser.msie && e.type === 'click')) {
			el.blur();
			el.focus();
		}
	  if (el.id === 'ws_filter' && e.type === 'change') {
  		$('#ws_spinner').show();
  		$.ajax({type: 'GET', url: el.form.action, data: {filter: el.value}, dataType: 'script'});
  	}
  	if (el.id === 'workshop_search_form' && e.type === 'submit') {
  		var field = $(el).children('[name=search]').get(0);
  		if (field.value.match(/search workshops/)) {
  			field.value = '';
  		}
  		$('#ws_spinner').show();
  		$.ajax({type: 'GET', url: el.action, data: $(el).serialize(), dataType: 'script'});
  		return false;
	  }
  	if (el.id === 'reset_search' && e.type === 'click') {	  
	    $('#ws_spinner').show();
  		$.ajax({type: 'GET', url: $('#ws_search_field').get(0).form.action, data: 'search=&filter=', dataType: 'script'});
  	  return false;  	  
	  }
	});
	$('a.workshop_filter').live('click', function() {
	  if ($('#selected_workshop').length) {
  		$.ajax({type: 'GET', url: this.href, dataType: 'script'});
  		$('html,body').animate({scrollTop: $('a[name=main]').offset().top-12}, 200)
  		return false;	    
	  }
	});
	$('#cal_searchbox').live('submit click change', function(e) {
    var el = e.target;
	  if (el.id === 'cal_filter' && (e.type === 'change' || ($.browser.msie && e.type === 'click'))) {
  		$('#ws_spinner').show();
  		$.ajax({type: 'GET', url: el.form.action, data: {tag: el.value}, dataType: 'script'});
  	}
	});
	$('#workshops_list a').live('click', function(e){
	  if ($('#workshops_scroll').length > 0) {
  		var el = $(this).parents('li');
  		var selected = $('#workshops_list li.selected');
  		if (el.get(0) === selected.get(0)) {
  			return false;
  		}
  		selected.removeClass('selected');
  		el.addClass('selected');
  		var target_scroll = $('div#workshops_scroll div.items #' + el.get(0).id);
  		$("div.scrollable").scrollable().click($('#workshops_scroll .items div.item').index(target_scroll[0]));
  		return false;
		}
	});
	$("a.player[rel]").overlay({
	  effect: 'apple',
	  expose: '#777',
		onLoad: function(content) {
			this.getOverlay().find("a.standard_player").flowplayer(0).load();
		},
		onClose: function(content) {
			$f().unload();
		}	
	});
	$('a.standard_player').flowplayer("/site/swf/flowplayer-3.1.3.swf", {
    clip: { scaling: 'fit' },
    canvas: { backgroundGradient: 'none'},
    plugins: {
       controls: {
         all: false,
         play: true,
         stop: true,
         scrubber: true,
         fullscreen: true,
          durationColor: '#ffffff',
          tooltipColor: '#5F747C',
          progressColor: '#000000',
          bufferColor: '#5c5c5c',
          backgroundColor: '#303030',
          buttonColor: '#636363',
          progressGradient: 'medium',
          timeBgColor: '#555555',
          timeColor: '#262626',
          buttonOverColor: '#728B94',
          sliderColor: '#454545',
          borderRadius: '0px',
          bufferGradient: 'none',
          backgroundGradient: 'none',
          volumeSliderGradient: 'none',
          tooltipTextColor: '#ffffff',
          sliderGradient: 'none',
          volumeSliderColor: '#000000',
          height: 24,
          opacity: 1.0
       }
    }
  });
	$("div.getInTouch input, div.getInTouchSmall input, div.getInTouch textarea, div.booking_form input[type=text], div.booking_form textarea").defaultValueActsAsHint();
	if ($('div#top_right div.search input').length && !window.location.href.match(/global_search/)) {
		$('div#top_right div.search input').defaultValueActsAsHint();
	};
	if ($('div#ws_searchbox div.search input').length && !window.location.href.match(/search/)) {
		$('div#ws_searchbox div.search input').defaultValueActsAsHint();
	};
	$(".date_input").datepicker({ dateFormat: 'dd/mm/yy' });
	if ($('#gmap_sidebar').length) {
		if (GBrowserIsCompatible()) {
      var map = new GMap2(document.getElementById("gmap_sidebar"));
			var eastside = new GLatLng(51.527865,-0.076554); 
      map.setCenter(eastside, 13);
			map.addOverlay(new GMarker(eastside));
      map.setUIToDefault();
    }
  };
  $('a.map_link').click(function() {
		var _win = window.open(this.href, 'gmap_popup_window', 'width=520,height=520,menubar,toolbar,status,resizable,scrollbars');
		return false;
	});
	$('#cal_box').show();
	var cal_match = window.location.href.match(/calendar\/(\d+\/\d+)/)
  $('#cultural_picker').datepicker({
    defaultDate: (cal_match ? new Date(cal_match[1]+ '/01') : null),
      onChangeMonthYear: function(year, month, inst) {
        if ($('#cultural_picker').data('run_once')) {
          $('.spinner').show();
         $.getScript('/pages/' + cal_name + '/' + year + '/' + month);
        } else {
          $('#cultural_picker').data('run_once', 'true');
        }
      },
      beforeShowDay: function(date) {
        var today = new Date();
        if (date.getYear() === today.getYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate()) {
          return [true, 'ui-datepicker-today'];
        }
        if (cal_days[$.datepicker.formatDate('yymmdd',date)]) {
          return [true, 'marked']
        }
        return [false, '']
      },
      onSelect: function(dateText, inst) {
        var ymd = dateText.replace(/((\d+)\/(\d+)\/(\d+))/,"$4$2$3");
        $('html,body').animate({scrollTop: $('a[name=' + ymd + ']').offset().top-12}, 200)
      }
  });
	$('#cal_pag a').live('click', function(e) {
	  $('.spinner').show();
	  $('#cultural_picker').datepicker('setDate', new Date(this.href.match(/pages\/.+\/(\d+\/\d+)/)[1]+ '/01'));
	  //$.getScript(this.href);
	  return false;
	});
	$('.show_album').next().hide();
	$('.show_album').click(function(){
		$(this).next().slideToggle(300);
	});
	var gallery_api = $('a.load_album[rel]').overlay({
		api: true,
	  expose: '#777',
    onLoad: function(content) {
      if (location.href.match(/\#.*id=/)) {
        // let slideshow do the business
      } else {
        swfobject.getObjectById('swf_gallery').sspLoadAlbum(this.getTrigger().get(0).id, 0);        
      }
    },
		onClose: function(content) {
			location.href = location.href.replace(/#.*/, '#');
		}
	});
  if (gallery_api && document.location.href.match(/\#.*id=/)) {
    gallery_api.load();
  }
  $('a.load_movie_album').click(function(){
    swfobject.getObjectById('swf_movie_gallery').sspLoadAlbum(this.id, 0);
    return false;
  });
  $('a.load_movie_direct').click(function(){
    var index = this.id.match(/content_(\d+)/)[1];
    var gal = $(this).parents('.album_links').get(0).id;
    swfobject.getObjectById('swf_movie_gallery').sspLoadAlbum(gal, index);
    return false;
  });
  $('#full_width :last-child.bottom_borderBox,#left_col :last-child.bottom_borderBox').removeClass('bottom_borderBox').css({'padding-bottom':'20px'});
  $('#full_width :last-child.bottom_line').removeClass('bottom_line').css({'padding-bottom':'20px'});
  $('ul.tabs').tabs('div.form_tabs > div.tab', {
    onClick: function() {
      $('ul.tabs li:has(a.current)').prevAll().children('a').addClass('done');
      $('ul.tabs li:has(a.current)').nextAll().children('a').removeClass('done');
    }
  });
  var tab_api = $("ul.tabs").tabs(0); 
  $("div.form_tabs button.next_tab").click(function() { tab_api.next(); return false; }); 
  $("div.form_tabs button.prev_tab").click(function() { tab_api.prev(); return false; });
  $('.show_extra[checked]').parent().next().children('.extra').show();
  $('select.change_extra').each(function(e) { if (this.value === 'other') { $(this).parent().next().children('.extra').show(); }})
	$('.show_extra').click(function() {$(this).parent().next().children('.extra').show(); })
	$('.hide_extra').click(function() {$(this).parent().next().children('.extra').hide(); })
	$('.change_extra').change(function() {
		if(this.value === 'other') {
			$(this).parent().next().children('.extra').show();
		} else {
			$(this).parent().next().children('.extra').hide();
		}
	});
	$('div.intro_panel > div:last-child').addClass('clearmargin');
	$('.show_calendar_item').live('click', function() {
    $(this).prev().slideToggle();
    if ($(this).html().match(/show/)) {
      $(this).html('hide details...');
    } else {
      $(this).html('show details...');      
    }
    return false;
	});
	if ($('#form_container #notice_div, #form_container #error_div').length) {
    $('html,body').animate({scrollTop: $('#form_container #notice_div, #form_container #error_div').offset().top-12}, 600);
	};
	$('.small_pics, div.movie').mouseenter(function() {$(this).find('img.float').css({'top':'0', 'left':'0'})});
	$('.small_pics, div.movie').mouseleave(function() {$(this).find('img.float').css({'top':'-9999px', 'left':'-9999px'})});
	$('a.edit_comment').live('click', function(){
	  $(this).prevAll('.spinner').show();
	  var _div = $(this).parents('div.news_comment');
	  $.get(this.href, function(data){
	    _div.html(data);
	  });
	  return false;
	});
	$('div#comments').bind('submit click', function(e){
	  var el = e.target;
	  var _div = $(el).parents('div.news_comment');
	  if (e.type === 'submit') {
  	  $(el).children('.spinner').show();
	    $.post(el.action, $(el).serialize(), function(data){
  	    _div.replaceWith(data);
  	  });
	    return false;
	  } else if (e.type === 'click' && $(el).hasClass('cancel_edit')) {
  	  $(el).next('.spinner').show();
	    $.get(el.href, function(data){
  	    _div.replaceWith(data);
  	  });
	    return false;
	  }
	});
});