$(function(){

/**
 * Global AJAX
 *
 */
	$.ajaxSetup({
	  beforeSend: function(){
			$('body').css( 'cursor', 'progress' );
		}, 
		complete : function () {
			$('body').css( 'cursor', 'auto' );
		}
	});
	

	
/**
 * JWPlayer. Load content if video src was defined
 *
 */
 	$('#video-tint').click(function() {
		$(this).hide();
		jwplayer().play();
	});
 
	if( typeof video_src != 'undefined' ) {
		// Reels
		var is_reel = false;
		if( typeof reel_playlist_pages != 'undefined' && reel_playlist_pages.length > 1 ) {
			is_reel = true;
			var player_skin_name = $('html').attr('id') + '_nav';
			var player_autostart = 'true';
			var player_videolist = [];
			var playlist_clicked = 0;
			// Fake navigation (2 - previous, 1 - next, 0 - current)
			for( i = 0; i < 3; i++ ) {
				player_videolist.push( { 'file': video_src.file, 'image': video_src.image } );
			}
			// Next & Previous links
			var reel_current = 0;
			for( i in reel_playlist_pages ) {
				if( reel_playlist_pages[i] == window.location.href ) {
					reel_current = parseInt( i );
					break;
				}
			}
			// Next
			var reel_next = 0;
			if( reel_current < ( reel_playlist_pages.length - 1 ) ) {
				reel_next = ( reel_current + 1 );
			}
			// Previous
			var reel_previous = reel_current - 1;
			if( reel_current == 0 ) {
				reel_previous = reel_playlist_pages.length - 1;
			}
		// Single video
		} else {
			var player_skin_name = $('html').attr('id');
			var player_autostart = 'false';
			var player_videolist = [ { 'file': video_src.file, 'image': video_src.image } ];
		}
		//console.log("player_autostart = "+player_autostart);
		//console.log('/js/jwplayer/' + player_skin_name + '/jwplayer_' + player_skin_name + '.zip?7');
		jwplayer('video-player').setup({
			'file': video_src.file,
			'image': video_src.image,
			'width': '640',
			'height': '399',
			'autostart': player_autostart,
			'skin': '/js/jwplayer/' + player_skin_name + '/jwplayer_' + player_skin_name + '.zip?814334',
			'controlbar': 'bottom',
			'modes': [
			        {type: 'flash', src: '/js/jwplayer/player.swf'},
			        {type: 'html5'}
			    ],
			'playlist': player_videolist,
			'events': {
					'onComplete': function() {
						if (is_reel)
							location.href = reel_playlist_pages[ reel_next ];
						//console.log( reel_playlist_pages[ reel_next ] );
					},
					'onPause': function() {
						$('#video-tint').hide();
					},
					'onPlay': function() {
						$('#video-tint').show();
					},
				}
		});
		// Reels playlist handling
		jwplayer().onPlaylistItem( function( obj ) {
			// Run only once
			if( playlist_clicked == 0 ) {
				playlist_clicked = 1;
			} else if ( playlist_clicked == 1 ) {
				playlist_clicked = 2;
				// Next
				if( obj.index == 1 ) {
					jwplayer().stop();
					window.location.href = reel_playlist_pages[ reel_next ];
				// Previous
				} else if ( obj.index == 2 ) {
					jwplayer().stop();
					window.location.href = reel_playlist_pages[ reel_previous ];
				}
			} else {
				jwplayer().stop();
			}
			return false;
		} );

	}

/**
 * Nexus logo anim
 *
 */
	var nexus_logo_anim = 0;
	$('#contactDetails').hover( function(){
		if( nexus_logo_anim == 0 ) {
			nexus_logo_anim = setTimeout( function() { $('#contactDetails').stop().animate( { marginLeft: 0 }, 250 ); }, 300 );
		}
	}, function(){
		clearTimeout( nexus_logo_anim );
		nexus_logo_anim = 0;
		$(this).stop().animate( { marginLeft: -230 }, 250 );	
	});	

/**
 * Homepage content reload
 *
 */
	if( typeof player_playlist != 'undefined' && typeof video_src != 'undefined' ) {
		// loader animation
		$('#loadAnother').hover( 
			function() {
				$(this).css('background', 'url(../img/load_another_arrows-cycle.gif?'+1+') 93% 47% no-repeat');
			}, function() {
				$(this).css('background', 'url(/img/load_another_arrows-start.gif) 93% 47% no-repeat');
			}
		);
		// load file
		$('#loadAnother').bind( 'click', function() {
			load_video();
		//	console.log(video_src,video_id,video_src.file,video_src.image)
			jwplayer().load({ file: video_src.file, image: video_src.image } );
		//jwplayer().resize(200, 300)
			
			return false;
		});
		// Find first video in the random array
			for( i in player_playlist ) {
				if( player_playlist[ i ].file == video_src.file ) {
					var video_id = i;
					break;
				}
			}
		// Load next video
			function load_video() {
				video_id = video_id == (player_playlist.length - 1) ? 1 : parseInt(video_id) + 1;
				video_src = { file: player_playlist[ video_id ].file, image: player_playlist[ video_id ].image };
				$('#video h1').html( player_playlist[ video_id ].heading );
			}
		}

/**
 * News Show more items
 *
 */
	if( $('body').attr('id') == 'news' ) {
			var news_page = 1; // Init page
			$('.viewAll').bind( 'click', function() {
				if( news_page != false ) {
					$('.viewAll').fadeTo( 'fast', 0.3 ); // Fade out a link
					$.ajax( {
					  url: '/news',
						type: 'POST',
						data: {page: news_page++, ajax: true},
					  context: $('#nxNews'),
					  success: function( data ) {
							// count result
							var news_needle = '<article';
							var news_count = 0; 
							for( var i=0; i < data.length; i++ ) { 
								if ( news_needle == data.substr( i, news_needle.length ) ) 
									news_count++; 
							}
							if( news_count < 10 ) {
								news_page = false; // Do not try to load more content
								$('.viewAll').addClass('hidden');
							}
						  $(this).find('article:last').after( data ); // Append content
							$('.viewAll').fadeTo( 'fast', 1 ); // Fade in a link
					  },
						error: function() {
							$('.viewAll').addClass('hidden');
							news_page = false; // Do not try to load more content
						}
					});
				}
				return false;
			});
	}
	
/**
 * Log In Popup
 *
 */
	$('#siteBar .login').bind('click', function() {
		if ($(this).hasClass('selected')) {
			$(this).removeClass('selected');
			}
		else {
			$(this).addClass('selected');
			}
		$('#loginForm').toggle();
		return false;
	});

/**
 * Email favourites Popup
 *
 */
	$('#emailFaves').bind('click', function() {
		$('#mailForm').fadeToggle(150);
		$(this).toggleClass('active');
		return false;
	});

/**
 * Display Favourites Count
 *
 */
	function display_favourites_count( count ) {
		if( typeof nexus_fav_uid != 'undefined' ) {
			if( typeof count == 'undefined' ) {
				$.ajax( {
				  url: '/favourites/crossDomain/get/' + nexus_fav_uid + '/' + nexus_fav_uid,
					dataType: 'json',
				  success: function( data ) {
						display_favourites_count( data.count );
				  }
				});	
			} else {
				if( count > 0 ) {
					$('#siteBar .favourites span:eq(1)').html( ' (' + count + ')' );
					$('#siteBar .favourites').attr( 'href', '/favourites/' + nexus_fav_uid );
				} else {
					$('#siteBar .favourites span:eq(1)').html( '' );
					$('#siteBar .favourites').attr( 'href', 'javascript:void();' );
				}
			}
		}
	}
	display_favourites_count();
	
/**
 * Add To Favourites
 *
 */
	$('#favouritesNav a').bind('click', function(){
		if( typeof nexus_fav_uid != 'undefined' && ( typeof video_src != 'undefined' || img_src != 'undefined' || project_src != 'undefined' ) ) {
				if( typeof project_src != 'undefined' ) {
					var entry_id = project_src.id;
				} else if ( typeof video_src != 'undefined' ) {
					var entry_id = video_src.id;
				} else if( typeof img_src != 'undefined' ) {
					var entry_id = img_src.id;
				}
				$.ajax( {
				  url: '/favourites/crossDomain/add/' + nexus_fav_uid + '/' + entry_id,
					dataType: 'json',
				  success: function( data ) {
						// Effect
							$('#newFavouriteItem').remove();
							var tmpl = '<img src="/img/favorites.png" id="newFavouriteItem" width="2" height="2" alt="" />';
							$('#siteBar .favourites').append( tmpl );
							$('#newFavouriteItem').animate( { width: 50, height: 50, right: -15, top: -10, opacity: 0 }, 500, function(){ display_favourites_count( data.count ); } );
				  }
				});
		}
		return false;
	});

/**
 * Remove From Favourites
 *
 */
	$('#items .remove').bind('click', function() {
		if( typeof nexus_fav_uid != 'undefined' ) {
			var entry_id = $(this).attr('data-id');
			$.ajax( {
			  url: '/favourites/crossDomain/delete/' + nexus_fav_uid + '/' + entry_id,
				dataType: 'json',
			  success: function( data ) {
					display_favourites_count( data.count );
			  }
			});
		}
		$(this).parent().remove();
		add_fake_items( $('#items'), 6 );
		return false;
	});
	
/**
 * Sharing
 *
 */
	$('#shareBar .twitter, #shareBar .facebook, #shareNav .twitter, #shareNav .facebook').bind('click', function(){
		var new_window = window.open( $(this).attr('href'), $(this).attr('class'), 'height=250,width=450,left=200,top=200' );
		return false;
	});
	
/**
 * Google Map
 *
 */
	if(	$('#contact-gmap').length > 0 ) {
		$('#contact-gmap').gMap({ markers: [{ latitude: 51.526308, longitude: -0.077645, popup: false, icon: { image: "/img/contact-map-marker.png", iconsize: [50, 51], iconanchor: [18,45] } }], latitude: 51.526308, longitude: -0.077645, controls: ["GSmallMapControl"], zoom: 15 });
	}

/**
 * Work page entry description
 *
 */
	if( $('#mediaDescription p').length > 0 ) {
		var text_description = [];
				text_description['wrapper'] = $('#mediaDescription div');
				text_description['forward'] = '<span class="descriptionToggle forward">Read More &gt;</span>';
				text_description['back'] = '<span class="descriptionToggle back">&lt; Back</span>';
				text_description['max'] = 288 - $('#mediaPlayer hgroup').height();
				text_description['height'] = text_description['wrapper'].height();
				$('#mediaDescription div').height( text_description['max'] );
				if( text_description['height'] > ( text_description['max'] + 20 ) ) {
			text_description['wrapper'].css('height', text_description['max'] + 'px');
			$('#mediaDescription div').append( text_description['forward'] );
			$('#mediaDescription div .descriptionToggle').live( 'click', function(){
				text_description['active'] = $('.descriptionToggle').hasClass( 'forward' ) ? 'back' : 'forward';
				$('#mediaDescription div .descriptionToggle').remove();
				$('#mediaDescription div').append( text_description[ text_description['active'] ] );
				text_description['wrapper'].css({ 'margin-top': ( text_description['active'] == 'back' ? '-'+(text_description['max'])+'px' : 0), 'height': ( text_description['active'] == 'back' ? 'auto' :  text_description['max'] + 'px') });
				//console.log( text_description['max'] );
			});
		}
		$('#mediaDescription div p').css('opacity', '1');
	}
	
/**
 * Items fake list items
 *
 */
	function add_fake_items( elem, num, min ) {
		var work_items_length = elem.find('li').length;
		var fake_items = work_items_length < min ? min : work_items_length%num;
		if( fake_items != 0 ) {
			fake_items = num < fake_items ? min - work_items_length : num - fake_items;
			for( i = 0; i < fake_items; i++ ) {
				elem.append('<li></li>');
			}
		}
	}
	if( $('#items').length > 0 || $('#projectContent ul').length > 0 ) {
		switch( $('body').attr('id') ) {
			case 'work':
				if( window.location.pathname.split('/')[1] == 'directors' ) {
					add_fake_items( $('#projectContent ul'), 6, 12 );
				} else {
					if( $('#items').length > 0 ) {
						add_fake_items( $('#items'), 6, 18 );	
					} else if ( $('#projectContent ul').length > 0 ) {
						add_fake_items( $('#projectContent ul'), 2, 12 );	
					}
				}
			break;
			case 'directors':
				if( $('html').attr('id') == 'nexus' ) {
					if ($('#directors-list').hasClass('row5')) {
						add_fake_items( $('#items'), 5, 5 );	
					}
					
					else {
						add_fake_items( $('#items'), 6, 6 );	
					}
				}
			break;
			case 'directors-sub':
				add_fake_items( $('#items'), 3, 9 );
			break;
		}
	}
	
/**
 * Email to a friend form
 *
 */		
	$('#freeform').bind( 'submit', function(){
		// Validation
			var valid = true;
			var email_regex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
			$('label').removeClass('invalid');
			if( $('#name').val().length < 2 ) {
				$('label[for=name]').addClass('invalid');
				var valid = false;
			} 
			if( ! $('#email').val().match( email_regex ) ) {
				$('label[for=email]').addClass('invalid');
				var valid = false;
			} 
			if( ! $('#recipient_email').val().match( email_regex ) ) {
				$('label[for=recipient_email]').addClass('invalid');
				var valid = false;
			} 
	
		// Submission
			if( valid ) {
				if( typeof nexus_fav_uid == 'undefined' ) {
					return false;
				}
				$.ajax( {
				  url: '/favourites/crossDomain/get/' + nexus_fav_uid + '/' + nexus_fav_uid,
					dataType: 'json',
				  success: function( data ) {
						$('#entries').val( data.entries );
						var recepient_emails = $('#recipient_email').val();
								recepient_emails += $('#email2').val().match( email_regex ) ? ', ' + $('#email2').val() : '';
								recepient_emails += $('#email3').val().match( email_regex ) ? ', ' + $('#email3').val() : '';
								recepient_emails += $('#email4').val().match( email_regex ) ? ', ' + $('#email4').val() : '';
								recepient_emails += $('#email5').val().match( email_regex ) ? ', ' + $('#email5').val() : '';
						$('#recipient_email').val( recepient_emails );
						$.ajax( {
							url: "/favourites",
							type: 'POST',
							data: $('#freeform').serialize(),
							success: function( data ) {
								if( data == 'success' ) {
									$('#emailFaves').trigger('click');
									$('#freeform')[0].reset();
								}
							}, error: function(jqXHR, textStatus, errorThrown) {
								if (errorThrown == '') {
									$('#emailFaves').trigger('click');
									$('#freeform')[0].reset();
								} else {
									alert('There was an error with your submission. Please try again later.');
								}
							}
						});
					}
				});
			}
		return false;
	});

/**
 * Image gallery
 *
 */
	if( typeof image_gallery != 'undefined' && typeof img_src != 'undefined' && image_gallery.length > 0 ) {
		// Show Enlarge for the current image
		for( i in image_gallery ) {
			if( img_src['id'] == image_gallery[i]['id'] ) {
				
				$('#project .extraLines').addClass('imgExt');
				$('#imageGalleryEnlarge').append('<a href="javascript:void();">enlarge</a>');
				break;
			}
		}
		$('#project img:first').after( '<ul id="imageGallery"></ul>');
		for( i in image_gallery ) {
			$('#imageGallery').append('<li><a href="' + image_gallery[i]['image'] + '" rel="imageGallery" class="image-'+i+'" title="' + image_gallery[i]['caption'] + '"></a></li>');	
		}
		$("a[rel='imageGallery']").colorbox();
		$('#imageGalleryEnlarge a').live('click', function(){
			$('#cboxContent').before('<h1 id="cboxHeader">' + $('#projectDetails hgroup h1:first').html() + '<br /><span>' + $('#projectDetails hgroup h2:first').html() + '</span></h1>');
			var index = 0;
			for( i in image_gallery ) {
				if( img_src['id'] == image_gallery[i]['id'] ) {
					index = i;
					break;
				}
			}
			$("a[rel='imageGallery'].image-"+index).trigger('click');
			return false;
		});
		$('#project img:first').bind('click', function() {
			$('#imageGalleryEnlarge a').trigger('click');
		});
/**
 * Single image enlarge
 *
 */
	} else if ( typeof img_src != 'undefined' && img_src['large_image'] != '' ) {
		$('#image .extraLines').addClass('imgExt');
		$('#imageGalleryEnlarge').append('<a href="javascript:void();">enlarge</a>');
		$('#image img:first').after( '<ul id="imageGallery"></ul>');
		$('#imageGallery').append('<li><a href="' + img_src['large_image'] + '" rel="imageGallery" title="' + img_src['caption'] + '"></a></li>');
		$("a[rel='imageGallery']").colorbox();
		$('#imageGalleryEnlarge a').live('click', function(){
			$('#cboxContent').before('<h1 id="cboxHeader">' + $('#mediaInfo hgroup h1:first').html() + '<br /><span>' + $('#mediaInfo hgroup h2:first').html() + '</span></h1>');
			$("a[rel='imageGallery']:eq(0)").trigger('click');
			return false;
		});
		$('#image img:first').bind('click', function() {
			$('#imageGalleryEnlarge a').trigger('click');
		});
	}
	
/**
 * Selected filter
 *
 */
	if( $('body').attr('id') == 'work' ) {
		if( $('#filters ul li.selected').length > 0 ) {
			var selected_filter = $('#filters ul li.selected:first a').html();
			$('#filtersShow').after( '<a href="/work/filter:page-1-show-all" id="filtersSelected">' + selected_filter + '</a>' );	
		}
	}
	
});

