$(document).ready(function() {

	function printpage()
	{
		window.print();
	}
	
	// NAVIGATION
	$('a.main-nav').mouseover(function(){
		$('ul.sub-nav').hide();
		show = $(this).attr('title');
		$('#sub-' + show).show();
	});
	
	$('ul.sub-nav').mouseleave(function(){
		$(this).hide();
		show = $('ul.main-nav a.current').attr('title');
		$('#sub-' + show).show();
	});
	
	$('div.main-nav').mouseleave(function(){
		$('ul.sub-nav').hide();
		show = $('ul.main-nav a.current').attr('title');
		$('#sub-' + show).show();	
	});
	
	// TEAM BIO MASONRY

	if($('.team-bio').is('ul'))
	{
		var $containerbio = $('.team-bio');
		$containerbio.imagesLoaded(function(){
		  $containerbio.masonry({
		    itemSelector : 'li'
		  });
		});
	}

	if($('.explore-related').is('ul'))
	{
		var $container = $('.explore-related');
		$container.imagesLoaded(function(){
		  $container.masonry({
		    itemSelector : 'li'
		  });
		});	
	}


	$('#basket').load('/shop/ p.basket', null, function(){
		$('p.basket').find('a').attr('href', $('p.basket').find('a').attr('href'));
	});
	
	$('a.ajax').click(function(){
		history.pushState({ path: this.path }, '', this.href)

		el = $(this);
		h1 = el.text();
		$('#xpage').load($(this).attr('href'), {'format' : 'html'}, function(){
			$('h1').text(h1);
			$('a.ajax').removeClass('current');
			el.addClass('current');
			
			var $container = $('.team-bio');
			$container.imagesLoaded(function(){
			  $container.masonry({
			    itemSelector : 'li'
			  });
			});
			
		});
		
		return false;
	});
	
	var landingPath = location.pathname;
	
	$(window).bind('popstate', function() {
		if($('#xpage').is('div') && landingPath != location.pathname)
		{
			$('#xpage').load(location.pathname, {'format' : 'html'}, function(response){
				h1 = $($(response)[0]).text();
				$('h1').text(h1);
				$('a.ajax').removeClass('current');
				$('a[href="' + location.pathname + '"]').addClass('current');
			})			
		}
	});
	
	if($('a[rel="fancybox"]').length > 0)
	{
		$('a[rel="fancybox"]').fancybox({
			titlePosition: 'inside',
		//	titleFormat: formatTitle,
			onStart: function(){
				$('#fancybox-title').html($(this).find('img').attr('alt'))
			}
		});
	}
	
	if($('a[rel="flickr"]').length > 0)
	{
		$('a[rel="flickr"]').fancybox({
			titlePosition: 'inside',
			titleFormat: formatTitle
		});
	}
	
	if($('a[rel="fancyvideo"]').length > 0)
	{
		$('a[rel="fancyvideo"]').click(function() {
			$.fancybox({
					'padding'		: 0,
					'autoScale'		: false,
					'transitionIn'	: 'none',
					'transitionOut'	: 'none',
					'title'			: this.title,
					'width'			: 680,
					'height'		: 495,
					'href' 			: this.href.replace(new RegExp('/([0-9])', 'i'), '/moogaloop.swf?clip_id=$1'),
					'type'			: 'swf',
					'swf'				: {
					  'wmode'		: 'transparent',
						'allowfullscreen'	: 'true'
					}
				});

			return false;
		});
	}
	
	function formatTitle(title, currentArray, currentIndex, currentOpts)
	{
		parts = title.split('|');
		html = '<span>' + parts[0] + '</span>';
		if(parts[1])
		{
			html += ' <a href="http://www.flickr.com/photos/' + parts[2] + '" target="_blank" class="fancytitle">' + parts[1] + '</a>';
		}
		
		return html;
	}
	
	
	$('#timeframe').change(function(){
		location.href = $('#timeframe').val();
	});
	
	$('#newsletters').change(function(){
		window.open($(this).val(), '_blank');
	});
	
	$('#year').change(function(){
		url = $('#year').attr('name');
		if($('#year').val() != '')	url += '/archive/' + $('#year').val();
		location.href = url;
	});
	
	$('#issue').change(function(){
		url = $('#issue').attr('name');
		if($('#issue').val() != '')	url += '/issue/' + $('#issue').val();
		location.href = url;
	});
	
	$('#artist').change(function(){
		url = $('#artist').attr('name');
		if($('#artist').val() != '')	url += '/artist/' + $('#artist').val();
		location.href = url;
	});
	
	$('#author').change(function(){
		url = $('#author').attr('name');
		if($('#author').val() != '')	url += '/author/' + $('#author').val();
		location.href = url;
	});
	
	$('#artists').change(function(){
		location.href = $('#artists').val();
	});
	
	$('.artist-az a').click(function(){
		if(!$(this).hasClass('az'))
		{
			return false;			
		}
	});
	
	function scrollPage() 
	{
			$(document).scrollTo($('div.pagination'), 800,  {offset: {top:-45, left:0} });
	}
	
	function onAfter(curr, next, opts, fwd) {
	 var $ht = $(this).height();

	 //set the container's height to that of the current slide
	 $(this).parent().animate({height: $ht});
	}

		$('.pagination').cycle({
	   	height: 'auto',
	    timeout: 0, 
	    pager:  '#pagination-nav',
	    next:   '#next-page', 
	    prev:   '#prev-page',
			onPrevNextEvent: scrollPage,
			onPagerEvent: scrollPage,
			after: onAfter
		});


// SLIDESHOW
  $('.slideshow').cycle({
	// fx:     'fade', 
	// speed:  'normal', 
	  timeout: 5000, 
  	speed:   1000, 
    pager:  '#nav',
    next:   '#next2', 
    prev:   '#prev2'     	 
	});


  $('.videos').cycle({
    timeout: 0, 
    speed:   1000, 
    pager:  '#nav',
    next:   '#next2', 
    prev:   '#prev2'     	 
	});

//RESOURCES SLIDESHOW

  $('.resources-ss').cycle({
			fx:     'fade', 
	    speed:   1000, 
		  timeout: 5000, 
	    pager:  '#nav',
	    next:   '#next2', 
	    prev:   '#prev2'     	 
	});
		
// PUBLICATIONS SLIDER

  $('.publications-slider').cycle({
		fx:     'scrollHorz', 
    speed:   1000, 
	  timeout: 5000, 
    pager:  '#nav',
    next:   '#next2', 
    prev:   '#prev2'     	 
	});

	if($('.events-ss').is('ul'))
	{
		$('.events-ss').after('<ul id="nav-thumbs"></ul>');
	}

// EVENTS-ss SLIDESHOW
  $('.events-ss').cycle({
		fx:     'fade', 
    speed:   1000, 
    timeout: 0, 
    pager:  '#nav-thumbs',
    next:   '#next2', 
    prev:   '#prev2',
    // callback fn that creates a thumbnail to use as pager anchor 
   	pagerAnchorBuilder: function(i, slideobj) { 
       return '<li><a href="#"><img src="' + $(slideobj).find('img').attr('src') + '" /></a></li>'; 
   }
});


	
// MAGAZINE_SS SLIDESHOW

  $('.magazine-ss').cycle({
			// fx:     'fade',
		   timeout: 5000, 
			 speed:  1000, 
		   pager:  '#nav',
		   next:   '#next2', 
		   prev:   '#prev2'     	 
 });

// A-Z Artists

	$('a.az').each(function(i){
		
		$(this).click(function(){

			if($('.pagination').is('div'))
			{
				$('#pagination-controls').hide();
				
				t = ($(this).attr('href').match(/artist/))?	'Artists ' : 'Showcase ';
				t += $(this).text();
				$('h1').text(t);
						
				parts = $(this).attr('href').split('#');
				
				exp = '^[' + parts[1] + ']';
				regex = new RegExp(exp, 'gi');
				
				if(!$('#' + parts[1]).is('ul'))
				{
					$('.pagination').append('<ul class="artist-list" id="' + parts[1] + '"></ul>');					
				}
				$('ul.artist-list').hide();
				
				$('#main-list li').each(function(){
					if($(this).attr('title').match(regex))
					{
						$('#' + parts[1]).append($(this));
					}
				});

				$('#' + parts[1]).fadeIn('slow');

				$('div.pagination').css({'height': 'auto'});;
				
				return false;
			}
		});
		
		parts = location.href.split('#');
		
		if(parts[1] && parts[1] == $(this).text())
		{
			t = ($(this).attr('href').match(/artist/))?	'Artists ' : 'Showcase ';
			t += $(this).text();
			$('h1').text(t);
			$('#pagination-controls').hide();
			
			$(this).trigger('click');
		}
		
	});

//ACCORDIAN

	//Hide (Collapse) the toggle containers on load
	
	//uncomment use this  to collapse content
	// collapse $("div.sh_collapse").hide(); 
	
	//Switch the "Open" and "Close" state per click then slide up/down (depending on open/close state)
	$("h3.expand").click(function(){
		$(this).toggleClass("active").nextAll().slideToggle("fast");
	});
	
	$('h3.switch').click(function(){
		$(this).next().toggle('fast');
	});

// CAPTION SLIDERS

	//To switch directions up/down and left/right just place a "-" in front of the top/left attribute

	//Full Caption Sliding (Hidden to Visible)
	$('.boxgrid.captionfull').hover(function(){
		$(".cover", this).stop().animate({top:'130px'},{queue:false,duration:160});
	}, function() {
		$(".cover", this).stop().animate({top:'260px'},{queue:false,duration:160});
	});
	//Caption Sliding (Partially Hidden to Visible)
	$('.boxgrid.caption').hover(function(){
		$(".cover", this).stop().animate({top:'160px'},{queue:false,duration:160});
	}, function() {
		$(".cover", this).stop().animate({top:'220px'},{queue:false,duration:160});
	});
	
	$('#nav-thumbs').easyPaginate({
		step: 6,
		nextprev: true
	});
	
	$('form').submit(function(){
	        var response = true;
	        var msg = '';

	        $(this).find('input.required[type="text"]').each(function(){
	            if(!$(this).val())
	            {
	                msg += 'Please enter your ' + $(this).attr('title') + "\n";
	                response = false;
	            }
	        });

	        $(this).find('input.required[type="checkbox"], input.policy').each(function(){
	            if($(this).attr('checked') == false)
	            {
	                msg += $(this).attr('title') + "\n";
	                response = false;
	            }
	        });

	        if(msg != '')
	        {
	            alert(msg);
	        }

	        return response;
	    });
	
	// CHANNEL 
	$('#switch_channel').change(function(){
		location.href = $(this).val();
	});
	
	// VIDEO 
	$('a[rel="video"]').click(function(){
		dest = $(this).attr('name');
		$('#' + dest).load($(this).attr('href'), {'format' : 'html'}, function(){});
		return false;
	});
	

	// AUDIO
	
	// JW Audio Player
	$('div.player').each(function(){
		id = $(this).attr('id');
		path = "/media/audio/" + $(this).attr('title');
		jwplayer(id).setup({
		'flashplayer': "/javascript/JWplayer-5.7/player.swf", 
		'file': path, 
		'height': 24, 
		'width': 300,
		'controlbar': 'bottom',
		'skin': '/javascript/JWplayer-5.7/skins/five.zip'
		});
	});
	
	if(!$('#audio-player').is('div'))
	{
			
		$("#audio").jPlayer({
			ready: function() {
			  $("#audio").jPlayer( "setMedia", {
					mp3: $('a.play:first').attr('href')
				});
			},
			solution: "flash, html",
			swfPath: "/skin/sprites",
			supplied: "mp3"
		});
		
		
		$('a.play').click(function(){	
						
			var audiofile = $(this).attr('href');
		//	$("#audio").jPlayer('clearMedia');
			$("#audio").jPlayer("setMedia", {
				mp3: audiofile
			}).jPlayer("play");
			
			src = $('#audio').data("jPlayer").status.src;
			desc = $(this).attr('desc').replace(/\n/g, "<br />");
			
			$('#episode_title').text($(this).text());			
			$('#episode_desc').html(desc);
			$('#episode_download').attr('href', $(this).attr('href'));
			
			//console.log(src);
			
			return false;
		});
	}
	
	$('a[rel="audio"]').click(function(){
		dest = $(this).attr('name');
		$('#' + dest).load($(this).attr('href'), {'format' : 'html'}, function(){});
		return false;
	});
	
	// BLOG
	
	$('div.post .entry-content img').each(function(){
		imgtitle = $(this).attr('title');
		imgstyle = $(this).attr('style');
		$(this).wrap('<div class="inline-image" style="' + imgstyle + '"></div>');
		
		imgstyle = 'width: ' + $(this).attr('width') + 'px';
		$(this).after('<div class="caption" style="' + imgstyle + '">' + imgtitle + '</div');
	});
	
	
	// SUBMIT 

	if($('#showcase_upload').is('input'))
	{
		$.getScript('/javascript/jQuery/jquery.uploadify/swfobject-2.js', function(){
			flash_version = swfobject.getFlashPlayerVersion();
			if(flash_version.major < 10)
			{
				$('#showcase_upload').prev().html('You need <a href="http://get.adobe.com/flashplayer/" target="_blank">Flash Player</a> version 10 or above to submit your images');
			}
			$.getScript('/javascript/jQuery/jquery.uploadify/jquery.uploadify.v2.1.4.min.js', function(){
				sessId = $('#showcase_upload').attr('desc');
				if(!sessId)
				{
					alert('Please allow photoworks.org.uk to set cookies and reload this page');
				}
				$('#showcase_upload').uploadify({
					'uploader'       : '/javascript/jQuery/jquery.uploadify/uploadify.swf',
					'script'         : '/media/uploadify',
					'cancelImg'      : '/skin/sprites/cancel-x.png',
					'folder'         : '/tmp/' + sessId,
					'multi'          : true,
					'auto'			 		 : true,
					'expressInstall' : '/skin/sprites/expressInstall.swf',
					'queueSizeLimit' : 12,
					'scriptData'     : {'PHPSESSID' : sessId},
					'buttonText'	 	 : 'SELECT FILES',
					'fileExt'				 : '*.jpg;*.JPG',
					'fileDesc'			 : 'JPEG only are allowed',
					'simUploadLimit' : 1,
					'sizeLimit'			 : 10000000,
					'onComplete': function(event, queueID, fileObj, response, speed)
					{
						if(window.console)
						{
							console.log(fileObj);			
							console.log(response);			
						}
					
						if($('#showcase_upload-label').find('div.imagelibrary').length < 12)
						{
							$('#showcase_upload-label').append(response);
						}
						else
						{
							$('#showcase_upload').uploadifyClearQueue();
							alert('You reached the limit of 12 images');
							return;
						}
					
					},
					'onSelect': function()
					{
						if($('#showcase_upload-label').find('div.imagelibrary').length >= 12)
						{
								$('#showcase_upload').uploadifyClearQueue();
								alert('You reached the limit of 12 images');
								return;
						}
					},
					'onSelectOnce': function()
					{
						if($('#showcase_upload-label').find('div.imagelibrary').length >= 12)
						{
								$('#showcase_upload').uploadifyClearQueue();
								alert('You reached the limit of 12 images');
								return;
						}
					},
					'onError': function(event, queueID, fileObj, errorObj)
					{
						$('#showcase_upload-label').before('<span id="uploadifyError" class="error">Error uploading file `' + fileObj.name + '`</span>');
						if(window.console)
						{
							console.log(fileObj);			
							console.log(errorObj);			
						}
				
					},
					'onCancel': function(event, queueID, fileObj, data)
					{
						if($('#uploadifyError').is('span'))
						{
							$('#uploadifyError').remove();
						}
					},
					'onAllComplete': function()
					{
						$('a.remove').click(function(){
							if(confirm('Do you wish to remove the selected file?'))
							{
								$(this).parent().parent().remove();
							}
							return false;
						});
					}
				});
			});
		});
	}
	
	
}); // End

