function limitChars(textid, limit, infodiv)
{
	//var text = $('#'+textid).val(); 
	var text = $('#'+textid).val();
	var textlength = text.split(/\b[\s,\.-:;]*/).length;
	var imited;
	
	if(textlength > limit)
	{
		$('#' + infodiv).html('You cannot write more then '+limit+' words!');
		limited = $.trim(text).split(" ", limit);
		limited = limited.join(" ");
		$('#'+textid).val(limited);
		return false;
	} else {
		$('#' + infodiv).html('Words remaining: '+ (limit - textlength));
		return true;
	}
}
 
function add_map_tag(class_name, image, alt_text)
{
	$('div.image-map').append('<div class="' + class_name + ' map-label"><img src="/_assets/images/js-only/' + image + '" alt="' + alt_text + '" /></div>');
	$('div.' + class_name).hide();	
	
	$('.' + class_name).mouseenter(function(){ // When user rolls over the link
		$('div.' + class_name).fadeIn();
	}).mouseleave(function(){ // When user moves away from the link
			$('div.' + class_name).fadeOut();
	});
		
}

function video_overlay(title, webm, mp4, ogg, flv, youTube)
{

	if ($.browser.msie ) {
		return '<div id="videoOverlay">' +
			'<div>' +
				'<a class="close">Close</a>' +
				'<div class="videoFrame">' +
					 '<a href="' + flv + '" style="display:block;width:613px;height:345px" id="player"></a>' + 
				'</div>' +			
				'<h2>' + title + '</h2>' +
				'<a href="http://www.youtube.com/watch?v=' + youTube + '" target="_blank"><img src="/_assets/images/video/youtube.png" alt="Watch the view on YouTube" width="66" height="25" /></a>' +
			'</div>' +
		'</div>';				
	} else
	{
		return '<div id="videoOverlay">' +
		'<div>' +
			'<a class="close">Close</a>' +
			'<div class="videoFrame">' +
				webkit_video(webm, mp4, ogg) +
			'</div>' +			
			'<h2>' + title + '</h2>' +
			'<a href="http://www.youtube.com/watch?v=' + youTube + '" target="_blank"><img src="/_assets/images/video/youtube.png" alt="Watch the view on YouTube" width="66" height="25" /></a>' +
		'</div>' +
	'</div>';
	}
	
	

}

function webkit_video(webm, mp4, ogg)
{
	return '<video width="613" height="345" controls="controls"><source src="' + webm + '" type="video/webm" /><source src="' + mp4 + '" type="video/ogg" /><source src="' + ogg + '" type="video/mp4" />Sorry, your browser does not support this video format</video>';
}


// LOAD JAVASCRIPT
/* ALWAYS THE FIRST CALL */ $('html').removeClass('no-js').addClass('yes-js'); // Removes the no-js class and adds yes-js class to the document


if( $('div.video-pod').length > 0 )
{
	$('.video-player-container').remove();
}


/* PAGE LOADED
--------------------------------------------------------------------------------------------------------------------------- */

if( $('div.cp-image-large').length > 0 )	
{
	$('div.main-content').append('<div class="loading-graphic"><img src="/_assets/images/js-only/ajax-loader.gif" /></div>');
}

$(window).load(function() {
	
	$('.external-link a').attr('target','_blank'); $('a.external-link').attr('target','_blank'); // Amend external links with the _blank attribute
	$('div.cp-preview-square:first .item').addClass('first');
	$('div.cp-preview-square:last .item').addClass('last');
/*
	 $('div.secondary-navigation ul').hide();
	
*/
	$('div.secondary-navigation li.t3').hide();
	// Nabigation animation
	 $('div.secondary-navigation ul.t2').delay(100).fadeIn(400, 'easeInOutBounce', function() {
	 	$('div.secondary-navigation ul.t3').delay(100).fadeIn(400, function() {
	 		$('div.secondary-navigation li.t3').delay(100).slideDown(400);	
	 	});
	 });
	
	// Search 
	$('form.search input[name="query"]').focus(function(){ if( $(this).val() == "Search" ) { $(this).val(''); } });	
	$('form.search input[name="query"]').blur(function(){ if( $(this).val() == "" ) { $(this).val('Search'); } });
	
	// Home page only
	if( $('body.home div.cp-preview').length > 0 ) // If there is a preview content pod set on the home page
	{	
		
		var username='MediaCityUK'; // set user name
		var format='json'; // set format, you really don't have an option on this one
		var url='http://api.twitter.com/1/statuses/user_timeline/'+username+'.'+format+'?callback=?'; // make the url

		$.getJSON(url,function(tweet){ // get the tweets
							
			// loading-tweets
			$('.loading-tweets').remove();
												
			$.each(tweet, function(index) {
				var tweet_full_date = tweet[index].created_at;
				var tweet_day = tweet_full_date.substr(8, 3);
				var tweet_month = tweet_full_date.substr(4, 3);
				var tweet_time = tweet_full_date.substr(11, 5);
				var tweet_year = tweet_full_date.substr(26, 4);	
 				$('div.tweet-ticker ul').append('<li class="tweet news-item"><span>' + tweet[index].text + ' - ' + tweet_time + ' ' + tweet_day + ' ' + tweet_month + ' ' + tweet_year + '</span></li>');
			});
			
			$('#tweet-ticker').ticker();
		});
		
		
		
		image_slideshow('cp-preview');
		
		
		// Image map tag
		add_map_tag('map-theheart', 'tag-the-heart.png', 'TheHeart');
		add_map_tag('map-bbc-left', 'tag-bbc.png', 'BBC');
		add_map_tag('map-blue', 'tag-blue.png', 'Blue');
		add_map_tag('map-piazza', 'tag-piazza.png', 'Piaza');
		add_map_tag('map-the-studios', 'tag-the-studios.png', 'TheStudios');
		add_map_tag('map-open-centre', 'tag-the-open-centre.png', 'The Open Centre');
		add_map_tag('map-tram', 'tag-tram.png', 'Tram');
		add_map_tag('map-white', 'tag-white.png', 'White');
		add_map_tag('map-number-one', 'tag-number-one.png', 'NumberONE');
		add_map_tag('map-bbc-right', 'tag-bbc.png', 'BBC');
		add_map_tag('map-orange', 'tag-orange.png', 'Orange');
		add_map_tag('map-unviersity', 'tag-university-of-salford.png', 'University of Salford');

	}
	
	// Add a fading effect to the main navigation text colours
	$('.main-navigation a[class!="selected"]').animate({ color: '#fff'}, 0 ); // Reset base colour
	$('.main-navigation a[class!="selected"]').mouseenter(function(){ // When user rolls over the link
		$(this).animate({ color: '#95A3AB'}, 400 ); // change the colour
	}).mouseleave(function(){ // When user moves away from the link
  		$(this).animate({ color: '#fff'}, 400 ); // Return to base colour
	});
	
	if( $('div.latest-tweet').length == 1 )
	{
		
		var username='MediaCityUK'; // set user name
		var format='json'; // set format, you really don't have an option on this one
		var url='http://api.twitter.com/1/statuses/user_timeline/'+username+'.'+format+'?callback=?'; // make the url

		$.getJSON(url,function(tweet){ // get the tweets
			var tweet_full_date = tweet[0].created_at;
			var tweet_day = tweet_full_date.substr(8, 3);
			var tweet_month = tweet_full_date.substr(4, 3);
			var tweet_time = tweet_full_date.substr(11, 5);
			var tweet_year = tweet_full_date.substr(26, 4);			
			
			 $('div.latest-tweet span.date-posted').text( tweet_time + ' ' + tweet_day + ' ' + tweet_month + ' ' + tweet_year);
			 $('div.latest-tweet p.tweet').text(tweet[0].text);
			
			var tweet_full_date = tweet[1].created_at;
			var tweet_day = tweet_full_date.substr(8, 3);
			var tweet_month = tweet_full_date.substr(4, 3);
			var tweet_time = tweet_full_date.substr(11, 5);
			var tweet_year = tweet_full_date.substr(26, 4);		
			 
			 $('div.second-latest-tweet span.date-posted').text( tweet_time + ' ' + tweet_day + ' ' + tweet_month + ' ' + tweet_year);
			 $('div.second-latest-tweet p.tweet').text(tweet[1].text);
			 
		});
		
	}
	
	
	// Gallery
	if( $('div.cp-gallery').length > 0 )
	{	
		var imagesPerPage = 25;
		var totalNumberImages = $('div.cp-gallery img').length;
		// Gallery pagination
		if( totalNumberImages  > imagesPerPage ) // If number of images is greater than the number that should be displayed on each page
		{
			$('div.cp-gallery').after('<div class="pagination"></div>');
			var numPages = Math.round(totalNumberImages/imagesPerPage);
			
			//Create page links 
			for(i = 0; i<numPages;i++) {
				var pageNum = i + 1;				
				$('div.pagination').append('<span class="page"><a href="#" rel="'+i+'">'+ pageNum +'</a> </span>');				
			}
			
			//Hide all li
			$('div.gallery ul li').hide();
		
			//Show just first li
			$('div.gallery ul li:first').show();
			
			//Use slice to get 25 li to show at a time
			$('div.gallery ul li').slice(0, imagesPerPage).show();
	
			//Add a active class to current link
		$('div.pagination a:first').addClass('active');
		
		
			//Attach onclick event to fire page change
			$('div.pagination a').bind('click', function(){
			
				$('div.pagination a').removeClass('active');
				
				$(this).addClass('active');
				var currPage = $(this).attr('rel');
				var startItem = currPage * imagesPerPage;
				var endItem = startItem + imagesPerPage;
				$('div.gallery ul li').css('opacity', '0.0').hide().slice(startItem, endItem).css('display', 'table-row').animate({opacity:1}, 300);
				
				return false;
				
			});

			
		}
		
		
		// Light box effect
		var login_form = '<div id="download-container">' +
						  			'<form name="login-in">' +
						  			'	<p>To download this image you must login or, if not registered, email your image request to <a href="mailto">imagerequest@mediacityuk.co.uk</a></p>' +
						  			'	<div class="form-element">' +
						  			'		<label for="username">Username:</label>' +
						  			'		<span>' +
						  			'			<input type="text" name="username" id="username" />' +
						  			'		</span>' +
						  			'	</div>' +
						  			'	<div class="form-element">' +
						  			'		<label for="password">Password:</label>' +
						  			'		<span>' +
						  			'			<input type="password" name="password" id="password" />' +
						  			'		</span>' +
						  			'	</div>' +
						  			'	<div class="form-action">' +
						  			'		<button type="submit" name="login">Login</button>' +
						  			'	</div>' +
						  			'</form>' +
						  			'</div>';

		function display_download_box(LinkLowRes, linkHighRes, instructions)
		{
			return '<div id="download-container"><p>Download a JPEG of this imageL <a href="' + LinkLowRes + '" class="low-res">low resolution</a> <a href="' + linkHighRes + '" class="high-res">high resolution</a></p>' +
				  			'<div class="download-instructions"><p>' + instructions + '</p></div>' +
				  			'<span class="logout">Logout</span></div>';
		}
		
		function display_request_box()
		{
			return '<div id="download-container"><p>To request a copy of this image please email: <a href="mailto:press@mediacityuk.co.uk">press@mediacityuk.co.uk</a></p></div>';
		}
		
		function get_current_image_id()
		{
		
			var href_val = String($.colorbox.element().context);

			href_val = href_val.replace('http://local.mediacityuk.co.uk', '');
			href_val = href_val.replace('http://www.mediacityuk.co.uk', '');
			href_val = href_val.replace('http://mediacityuk.co.uk', '');				
	 		
	 		return $('li a[href="' + href_val + '"] img').attr('id');
			
		}
	
		function remove_download_comtainer()
		{
			if( $('div#download-container').length > 0 ) {
			 $('div#download-container').remove(); }
		}
	
		 $('div.cp-gallery a').colorbox({
		 	maxHeight: '80%',
		 	maxWidth: '80%',
		 	onLoad: function() {
		 		remove_download_comtainer();
		 		
		 		// Get rel id from the orignal li item
		 			// To do this grab the current selected image
		 		var current_image_id = get_current_image_id();
		 		
		 		$('#cboxContent').append(display_request_box());
			  	$('div#download-container').hide().delay(1000).slideDown();	 			 		
		 	}
		 });
		 
		 $('#download-container span.logout').live('click', function(){
		 	
		 	$.ajax({
		  		url: "/ajax/logout",
		  		dataType: 'JSON',
		 		success: function(data){
		  			
		  			alert(data.message);
		  			
		  			if( data.complete ) // If logged in
			  		{		  				
		  				remove_download_comtainer();
		  				$('#cboxContent').append(login_form);
		  			} 
		  			
		  		}
			});
		 	
		 });


		 $('#download-container button').live('click', function(){
			 	var submit_form = true;

			 	if(  $('#download-container #username').val()  == "" )
			 	{
			 		submit_form = false;
			 	}
			 	
			 	if(  $('#download-container #password').val()  == "" )
			 	{
			 		submit_form = false;
			 	}
			 
			 	if( submit_form )
			 	{
			 		
				 	$.ajax({
				  		url: "/ajax/login",
				  		data: "image_id=" +  get_current_image_id() + "&" + $('#download-container form').serialize(),
				  		dataType: 'JSON',
				  		type: 'POST',
				 		success: function(data){
				  			
				  			alert(data.message);
				  			
				  			if( data.complete ) // If logged in
					  		{		  				
				  				remove_download_comtainer();
				  				$('#cboxContent').append( display_download_box(data.LinkLowRes, data.linkHighRes, data.instructions) );
				  			} 
				  			
				  		}
					});
								
				} else {
					alert('Please enter a username and password');
				}
			

			return false;
		 	
		 });
		 
		 		
	}
		
	// FAQ's	
	if( $('div.cp-faq').length > 0 )
	{
		$('div.cp-faq dd').hide().addClass('closed');
		
		var faq_status = 'closed';
		$('div.cp-faq dt').click(function() {
			// Return all anwers to hiddens state
			$('dt').css('background', 'url(/_assets/images/styles/backgrounds/faq-arrow.png) no-repeat'); 
			$('dd').slideUp();
			// Slide down the current ansers
			$(this).next('dd').slideDown();
			$(this).css('background', 'url(/_assets/images/styles/backgrounds/faq-arrow-down.png) no-repeat 0 3px');

		});
		
	}	
	
	// Large images
	if( $('div.cp-image-large').length > 0 )
	{
	
		$('div.loading-graphic').fadeOut(function() { 
			$(this).remove();
		});
		
		$outer_container=$("div.cp-image-large");
		$imagePan_panning=$("div.cp-image-large img");
		$imagePan=$("div.cp-image-large div.item");
		$imagePan_container=$("div.cp-image-large div.item .img-wrap");
	
		$imagePan_panning.css("margin-top",($imagePan.height()-$imagePan_panning.height())/2+"px");
		containerWidth=$imagePan.width();
		containerHeight=$imagePan.height();
		totalContentW=$imagePan_panning.width();
		totalContentH=$imagePan_panning.height();
		$imagePan_container.css("width",totalContentW).css("height",totalContentH);
	
		function MouseMove(e){
			var mouseCoordsX=(e.pageX - $imagePan.offset().left);
			var mouseCoordsY=(e.pageY - $imagePan.offset().top);
		  	var mousePercentX=mouseCoordsX/containerWidth;
		  	var mousePercentY=mouseCoordsY/containerHeight;
		  	var destX=-(((totalContentW-(containerWidth))-containerWidth)*(mousePercentX));
		  	var destY=-(((totalContentH-(containerHeight))-containerHeight)*(mousePercentY));
		  	var thePosA=mouseCoordsX-destX;
		  	var thePosB=destX-mouseCoordsX;
		  	var thePosC=mouseCoordsY-destY;
		  	var thePosD=destY-mouseCoordsY;
		  	var marginL=$imagePan_panning.css("marginLeft").replace("px", "");
		  	var marginT=$imagePan_panning.css("marginTop").replace("px", "");
		  	var animSpeed=500; //ease amount
		  	var easeType="easeOutCirc";
		  	if(mouseCoordsX>destX || mouseCoordsY>destY){
			  	$imagePan_container.stop().animate({left: -thePosA-marginL, top: -thePosC-marginT}, animSpeed,easeType); //with easing
		  	} else if(mouseCoordsX<destX || mouseCoordsY<destY){
			  	$imagePan_container.stop().animate({left: thePosB-marginL, top: thePosD-marginT}, animSpeed,easeType); //with easing
		  	} else {
				$imagePan_container.stop();
		  	}	
		  	
		  	
		  		  	
		}
		
		// Centre the image
		$imagePan_panning.css("margin-left",($imagePan.width()-$imagePan_panning.width())/2).css("margin-top",($imagePan.height()-$imagePan_panning.height())/2);
	
		// Moved the bin into a mouse over so the mouse out can be trigged every time.		
		$("div.cp-image-large div.item").mouseover(function(){ // When user moves out of the div									
			
			$imagePan.bind("mousemove", function(event){
				MouseMove(event);									  
			});
			$("div.cp-image-large").mouseout(function(){ // When user moves out of the div									
				$("div.cp-image-large div.img-wrap").delay(500).animate({left: 0, top: 0}, 1000,"easeOutCirc"); // Return the image wrap to start		
			});		
		});		  	
	
		$('div.cp-image-large').append('<div class="hand"></div>');
	
		$(window).resize(function() {
			$imagePan.unbind("mousemove");
			$imagePan_container.css("top",0).css("left",0);
			$(window).load();

		});
		
		
		
				
	}
	
	// Slideshows
	if( $('div.cp-image-slideshow').length > 0 )
	{
		image_slideshow('cp-image-slideshow');
	}
	
	// Search occupiers
	if( $('form#searchOccupiers').length > 0 )
	{
		$('form#searchOccupiers select').change(function() {
			
			$('form#searchOccupiers select[name!="' + $(this).attr('name') + '"]').val('');
			$('form#searchOccupiers').submit();

		});
	}
	
	// New Occupier form
	if( $('form#newOccupierForm').length > 0 )
	{
	
		$('#newOccupierForm li.field label input:checked').each(function(index) {
    		$(this).parent().addClass('selected');
		});
	
		$('#newOccupierForm li.field label').click(function(){
			if( $(this).hasClass('selected') )
			{
				$(this).removeClass('selected');
				$(this).children('input').attr('checked', false);
			} else {
				$(this).addClass('selected');
				$(this).children('input').attr('checked', true);
			}
			return false;
		});
		
		$('#description').keyup(function(){
 			limitChars('description', 100, 'charlimitinfo');
 		})
		
	}

	
	
/* GLOBAL FUNCTIONS
	------------------------------
*/
	function image_slideshow(cp) // Pass the content pod type that will used to create the slideshow
	{
		
	
		$('div.' + cp + ' .item').each(function(index) { // For each item 			
				
			var num_images = $('div.' + cp + ' .item:eq(' + index + ') div.img-wrap img').length; // Count the number of image in the image wrap
			var container_width = $('div.' + cp + ' .item:eq(' + index + ') div.img-wrap').width(); // Get the width of the image wrap
			var progess_width = container_width / num_images; // Work the width of the each progress increaes
			
			$('div.' + cp + ' .item:eq(' + index + ') div.img-wrap').after('<div class="progress-bar"><div class="progress"></div></div>'); // Place the progress bar
			$('div.' + cp + ' .item:eq(' + index + ') div.progress').width(progess_width); // Set the progress width
			
			var started_slideshow = false; // Declare that the slideshow has not start yet
			
			if( $('div.' + cp + ' .item:eq(' + index + ') div.img-wrap img').length > 0 )
			{
							
				$('div.' + cp + ' .item:eq(' + index + ') div.img-wrap').cycle({ 
				   	timeout:       1000,
				   	before: function(currSlideElement, nextSlideElement, options, forwardFlag) { // Before the next slide is shown
				   		var slide_index = options.currSlide;
				   		var multiply_width_by = slide_index + 2;
				   		if( started_slideshow == false || (slide_index + 1) == $('div.' + cp + ' .item:eq(' + index + ') div.img-wrap img').length ) 
				   		{ // Rest the multiply variable to 1 if at the begining or the end of the slideshow
				   		  multiply_width_by = 1;
				   		  started_slideshow = true; // Set the slideshow to started
				   		}
				   		
				   		var item_id = $(this).parent().parent().parent('.item').attr('id'); // Get the item ID
				   		var wrap_width = $('#' + item_id + ' div.img-wrap').width(); // 
				   		var curr_num_images = $('#' + item_id + ' div.img-wrap img').length; // Count the number of image in the image wrap				   		
				   		var progess_width = wrap_width / curr_num_images; // Work the width of the each progress increaes
				   		
				   		
				   		$('#' + item_id + ' div.progress').animate({ width: progess_width * multiply_width_by }, 400 ); // Animate the progress bar
				   		
				   	}
			    });
			    
			  	$('div.' + cp + ' .item:eq(' + index + ') div.img-wrap').cycle('pause');	  
			    
			    $('div.' + cp + ' .item:eq(' + index + ')').mouseenter(function(){
			    	$('div.' + cp + ' .item:eq(' + index + ') div.img-wrap').cycle('resume');
			    }).mouseleave(function(){
			    	$('div.' + cp + ' .item:eq(' + index + ') div.img-wrap').cycle('pause');
			    });				
			} // Close if( $('div.' + cp + ' .item:eq(' + index + ') div.img-wrap img').length > 0 )
			
		
		}); // Close $('div.' + cp + ' .item').each
	} // Close image_slideshow(cp)
	
	
	// Video
	if( $('div.video-pod').length > 0 )
	{
		
/*
		if ($.browser.msie ) { // If in internet explorer
			var video_id = $('div.video-player').attr('id'); // Get the ID of the video player
			video_id = video_id.replace('video-', ''); // Strip the variable down to the number		
		
			$.ajax({
		  		url: "/ajax/get_video/" + video_id, // Get the video details from JSON file
		  		dataType: 'JSON',
		 		success: function(data){		  					  			
		  			if( data.id > 0 ) // If returned a video
			  		{		  											  			
			  			$('div.video-player').html('<a href="' + data.flv + '" style="display:block;width:613px;height:345px" id="player"></a>'); // Replace HTML5 video with the 
						flowplayer("player", "/_assets/flash/flowplayer-3.2.7.swf");
		  			} 		  			
		  		}
			});
		}
			
*/
		
		$('div.video-pod div.item').append('<img src="/_assets/images/styles/icons/play-video.png" alt="PLAY" width="300" height="171" class="play" />');
		
		$('div.video-pod div.item a').click(function(){
			
			var vid_id =  $(this).attr('rel');
	
			return false;
			
		});
		
		$('div.video-pod div.item img.play').click(function(){
			
			var vid_id =  $(this).prev().attr('rel');
			$('.play').remove();
			$.ajax({
		  		url: "/ajax/get_video/" + vid_id, // Get the video details from JSON file
		  		dataType: 'JSON',
		 		success: function(data){		  					  			
		  	  			
			  			// Add loading graphic							  			
			  			$('body').append('<div class="loading-video"><img src="/_assets/images/js-only/ajax-loader.gif" /><h3>Loading video</h3></div>');
			  			// Add overlay to the page
						$('body').append( video_overlay(data.title, data.webm, data.ogg, data.mp4, data.flv, data.youtube) );
						// Video
						$("#videoOverlay").overlay({
							top: 100,
							mask: {
								color: '#000',	
								loadSpeed: 200,
								opacity: 0.8
							},
							closeOnClick: true,
							onBeforeLoad: function() {
								$('div.loading-video').fadeOut(function() { // Remove loading graphic
									$('div.loading-video').remove();
									$('body').append('<div class="video-overlay"></div>');
									if ($.browser.msie ) {
										flowplayer("player", "/_assets/flash/flowplayer-3.2.7.swf");
									}
								});
							},
							onClose: function(){
								$('#videoOverlay').remove(); // overlay on close
								$('.video-overlay').fadeOut(function() {
									$('.video-overlay').remove();
								}); // overlay on close
							},
							load: true
						}).load();
		  			
		  		}
			});		
			
			
		});
	}
		
	
});
