var animObject	= {
	exists:false
};

var objPortletClosed = {
	width:	171,
	height:	284
};

var objPortletOpened = {
	width:	511,
	height:	398
};

var objPortletContentClosed = {
	width:	153,
	height:	106
};

var objPortletEasing = {
	width:	'easeOutCirc',
	height:	'easeOutCirc'
};

var animating = 'no';

function debug (message) {
	if(console && console.log) {
		console.log(message);
	}
}

function portletOpenTrigger() {

	var container	= $('.column-container:not(.static)');
	var nextPortlet	= container.data('nextPortlet');

	container.data('nextPorlet',null);

	portletOpen(nextPortlet,container);

}

function portletOpen($portletClicked,$container) {

	if($portletClicked.hasClass('wallpaper')) {

		openWallpaperPortlet($portletClicked,$container);

	} else if($portletClicked.hasClass('blog')) {

		openBlogPortlet($portletClicked,$container);

	} else if($portletClicked.hasClass('video-portlet')) {

		openVideoPortlet($portletClicked,$container);

	} else if($portletClicked.hasClass('gallery')) {

		openGalleryPortlet($portletClicked,$container);

	} else if($portletClicked.hasClass('news')) {

		openNewsPortlet($portletClicked,$container);

	} else if($portletClicked.hasClass('fullbody')) {

		openQuestionnairePortlet($portletClicked,$container);

	} else if($portletClicked.hasClass('fullbodyabout')) {

		openAboutPortlet($portletClicked,$container);

	} else if($portletClicked.hasClass('competition')) {

		animating = 'no';
		window.open ($portletClicked.find('h2.opener a').eq(0).attr('href'),'win-'+Math.floor(Math.random()*100));

	} else if($portletClicked.hasClass('contact')) {

		animating = 'no';

		if($portletClicked.hasClass('openable')) {
			window.open ($portletClicked.find('h2.opener a').eq(0).attr('href'),'win-'+Math.floor(Math.random()*100));
		}

		return false;

	} else {

		openNormalPortlet($portletClicked,$container);

	}
}

function closeOpenPortlet($portletOpen,$container,$portletClicked) {

	if($portletOpen.hasClass('wallpaper')) {

		closeWallpaperPortlet($portletOpen,$container,$portletClicked);

	} else if($portletOpen.hasClass('blog')) {

		closeBlogPortlet($portletOpen,$container,$portletClicked);

	} else if($portletOpen.hasClass('video-portlet')) {

		closeVideoPortlet($portletOpen,$container,$portletClicked);

	} else if($portletOpen.hasClass('gallery')) {

		closeGalleryPortlet($portletOpen,$container,$portletClicked);

	} else if($portletOpen.hasClass('news')) {

		closeNewsPortlet($portletOpen,$container,$portletClicked);

	} else if($portletOpen.hasClass('fullbody')) {

		closeQuestionnairePortlet($portletOpen,$container,$portletClicked);

	} else if($portletOpen.hasClass('fullbodyabout')) {

		closeAboutPortlet($portletOpen,$container,$portletClicked);

	} else {

		closeNormalPortlet($portletOpen,$container,$portletClicked);

	}

}

function loadVideoYoutube (id,width,height) {

	if(!width) {
		width = 340;
	}

	if(!height) {
		//height = 231;
		height = 274;
	}

	var html = '<object width="'+width+'" height="'+height+'">';
		html+= '<param name="movie" value="http://www.youtube.com/v/'+id+'?fs=1&amp;hl=en_GB"></param>';
		html+= '<param name="allowFullScreen" value="true"></param>';
		html+= '<param name="allowscriptaccess" value="always"></param>';
		html+= '<embed ';
			html+='src="http://www.youtube.com/v/'+id+'?fs=1&amp;hl=en_GB" ';
			html+='type="application/x-shockwave-flash" ';
			html+= 'allowscriptaccess="always" ';
			html+= 'allowfullscreen="true" ';
			html+= 'width="'+width+'" ';
			html+= 'height="'+height+'"';
		html+= '></embed>';
		html+= '</object>'
	return html;
}

function loadSlideShow (arrUrls) {

	var html = '';

	html+='<div class="slideshow">';
		html+='<a class="prev browse left" id="slide-prev"></a>';
		html+='<a class="next browse right" id="slide-next"></a>';

		if(arrUrls && arrUrls.length > 0){
			var len = arrUrls.length;
			html+='<div class="slidetabs"'+(len==1 ? ' style="display:none;"' : '')+'><div class="inner"><div class="pre"></div><div class="mid">';
			for(var i=0;i<len;i++) {
				html+='<a href="#"></a>';
			}
			html+='</div><div class="post"></div></div></div>';
		}

		html+='<div class="scrollable-container">';
			html+='<div class="scrollable">';
				html+='<div class="items images">';
					if(arrUrls && arrUrls.length > 0) {
						var len = arrUrls.length;
						for(var i=0;i<len;i++) {
							html+='<div class="thumb">';
							html+='<p class="img"><img src="'+arrUrls[i].url+'" /></p>';
							html+='<p class="title" style="display:none;">'+arrUrls[i].title+'</p>';
							html+='</div>';
						}
					}
				html+='</div>';
			html+='</div>';
		html+='</div>';
	html+='</div>';

	return html;
}

$(function() {

	if($('.hidden-form').length > 0) {
		setTimeout(function(){
			$('.hidden-form form').css({opacity:0,'display':'block'});
			$('.hidden-form').animate({opacity:0},2500,function(){
				$('.hidden-form').css({'background-image':'none'}).find('form').css({opacity:1});
				$('.hidden-form').animate({opacity:1},2500);
				$('.hidden-form').removeClass('hidden-form');
				$('h2.block').text('Please enter your details below');
			});
		},1500);
	}

	var themes		= 'themeWhite themeBlack themeStone themeGrass themeSand themeWood themeSky themeCork themeStar themeMatrix';
	var $body		= $('body');
	var $column		= $('.column');
	var $portlets	= $('.portlet');
	var $filterLinks= $('.filter a:not(.add-wallpaper)');
	var $icon		= $('.icon');
	var $openers	= $('.opener');
	var $closers	= $('.close-news');
	var $container	= $('.column-container:not(.static)');
	var clsHidden	= 'invis';
	var speed		= 1200;
	var objMasonry	= {
		singleMode:		false,
		columnWidth:	objPortletClosed.width+8,
		itemSelector:	'.portlet:not(.'+clsHidden+')',
		resizeable:		true,
		animate:		true,
		animationOptions:	{
			duration:	speed,
			queue:		false,
			complete:	function () {
				//$(this).css({'position':'absolute'});
			}
		},
		saveOptions:	true
	};

	/**
	 * Bind Masonry to the portlet container
	 */
	if($container.length > 0) {
		$container.masonry(objMasonry,function() {
			// Optional callback.
			// 'this' will refer to the applicable elements Masonry just rearranged
		});
		objPortletLast	 = $('.portlet:last').offset();
	}

	/**
	 * Move image background position if hovering over the portlet.
	 */
	$portlets.bind({
		mouseover:	function(){
			$(this).addClass('over');
		},
		mouseout:	function(){
			$(this).removeClass('over');
		}
	});

	/**
	 * Bind Video Loader to video Porlets
	 */
	$('.youtube .portlet-header a').each(function(){
		$(this).parents('.portlet-header').html(loadVideoYoutube($(this).attr('rel')));
	});

	/**
	 * Bind Peronalisation options only if the controlling portlet exists
	 */
	if($icon.length > 0) {
		$icon.bind({
			click:		function(){
				var style	= $(this).attr('class').split(' ')[1];
				$body.removeClass(themes).addClass('theme'+style.substr(0, 1).toUpperCase()+style.substr(1));
				document.cookie='style='+style;
				$.data(document.body,'styleOn',style);
				return false;
			},
			mouseover:	function(){
				var style	= $(this).attr('class').split(' ')[1];
				$body.removeClass(themes).addClass('theme'+style.substr(0, 1).toUpperCase()+style.substr(1));
				return false;
			},
			mouseout:	function(){
				var style = $.data(document.body,'styleOn').replace('theme','');
				if(!style) {
					style = 'white';
				};
				$body.removeClass(themes).addClass('theme'+style.substr(0, 1).toUpperCase()+style.substr(1));
				return false;
			}
		});
	}

	/**
	 * Bind click events to the Links used to Shuffle the display
	 */
	if($filterLinks.length > 0) {
		$filterLinks.click(function(){

			$filterLinks.removeClass('selected');
			$(this).addClass('selected');

			var clsMatch = '.' + $(this).attr('rel');

			if(clsMatch=='.all') {
				// show all hidden boxes
				$container.children('.'+clsHidden).toggleClass(clsHidden).animate({opacity: 1},{duration: speed});
			} else {
				// hide visible boxes 

				var els = $container.children().not(clsMatch).not('.'+clsHidden);
				els.each(function(){
					var $this = $(this);
					if($this.hasClass('opened') && $this.hasClass('video-portlet')) {
						$this.find('.close-news').trigger('click');
					}
					$this.toggleClass(clsHidden).animate({opacity: 0},{duration:speed});
				});
				//$container.children().not(clsMatch).not('.'+clsHidden).toggleClass(clsHidden).animate({opacity: 0},{duration: speed});
				// show hidden boxes
				$container.children(clsMatch+'.'+clsHidden).toggleClass(clsHidden).animate({opacity: 1},{duration: speed});
			}
			$container.masonry();

			return false;
		});
	}

	if($openers.length > 0) {
		/**
		 * Close any open portlets and then open the portlet clicked
		 */
		$openers.bind('click',function(){

			if(animating=='no') {
				animating = 'yes';

				var $portletClicked	= $(this).parents('.portlet');

				/**
				 * Don't respond if the one you clicked on is already open
				 */
				if(!$portletClicked.hasClass('opened')) {

					if($portletClicked.find('.openlink').length > 0) {
						animating = 'no';
						return true;
					}

					var $portletOpen = $('div.opened');

					/**
					 * Close Anything open
					 * pass in the portletClicked to open it when finished closing
					 *
					 * or
					 *
					 * Open the portletClicked
					 */
					if($portletOpen.length > 0) {
						closeOpenPortlet($portletOpen,$container,$portletClicked);
					} else {
						portletOpen($portletClicked,$container);
					}

				} else {

					var $headerPopups = $portletClicked.find('.header-popups a');

					if($headerPopups.length < 1) {

						var $popups = $portletClicked.find('.popup');

						if($popups.length > 0) {
							/**
							 * Create a duplicate of the close span but completely hidden
							 */
							$portletClicked.find('.portlet-header').append('<div style="position:absolute;top:5px;width:519px;" class="header-popups">'+$portletClicked.find('.close').html()+'</div>');
							$portletClicked.find('.portlet-header').find('.close-news').remove();
							var $fancyBoxLinks = $portletClicked.find('.header-popups a');
							var $fancyLength = $fancyBoxLinks.length;
							var $fancyLinks = [];
							for(var i=0;i<$fancyLength;i++) {
								$fancyLinks[$fancyLinks.length] = {
									'href':$fancyBoxLinks[i].href,
									'title':$fancyBoxLinks[i].title
								};
							}
							$portletClicked.find('.header-popups a').eq(0).click(function(){
								$(this).css({'position':'absolute','top':'0px','width':'519px','height':'160px'});
								$.fancybox(
									$fancyLinks,
									{
										'transitionIn'	: 'fade',
										'transitionOut'	: 'fade',
										'easingIn'		: 'swing',
										'easingOut'		: 'swing',
										'titlePosition'	: 'inside',
										'type'			: 'image',
										'titleFormat'	: function(title, currentArray, currentIndex, currentOpts) {
											return '<span id="fancybox-title-over">' + title + '</span>';
										}
									}
								);
								return false;
							}).trigger('click');

							//$portletClicked.find('.header-popups a.popup').trigger('click');
							//$portletClicked.find('.close a.popup').unbind('click').bind({
							//	click:function(){
							//		$(this).parents('.portlet').find('.header-popups a')[0].trigger('click');
							//		return false;
							//	}
							//});
							$('#fancybox-close').html('Close');
						} else if($(this).hasClass('targetallowed')) { // allow popup links inline on the news page
							return true;
						}
					} else {
						$headerPopups.trigger('click');
					}

					animating = 'no';

				}
			}

			return false;
		});
	}
	if($closers.length > 0) {
		/**
		 * Only attempt to close the portlet if it's opened
		 */
		$closers.click(function(){

			var $portletOpen = $(this).parents('.portlet');

			if($portletOpen.hasClass('opened')) {
				closeOpenPortlet($portletOpen,$container,null);
			}

			return false;
		});
	}

	$('.next,.prev').live('mouseover', function() {
		var $this = $(this);
		$this.css({'background-position':($this.hasClass('next')?'right':'left')+' top'})
	});
	$('.next,.prev').live('mouseout', function(){
		var $this = $(this);
		$this.css({'background-position':($this.hasClass('next')?'left':'right')+' top'});
	});


	$portlets.each(function(){
		var $this = $(this);
		var $body = $this.find('.portlet-text .body');

		var videoMatches = /\[video code=([^\)]+)\]/.exec($body.html());

		if(videoMatches && videoMatches.length > 0) {
			var newContent = $body.html();
			var videoLink = videoMatches[0];
			var videoUrl = videoMatches[1];

			newContent = newContent.replace(
				videoLink,
				'<div class="video-link '+videoUrl+'"></div>'
			);
			$body.html(newContent);
		}
	});

	if($('#term').length > 0) {
		var $term = $('#term');
		$term.bind({
			click:function(){
				var $this = $(this);
				if($this.val()==$this.parent().find('.label').text()) {
					$this.val('');
				}
			},
			focus:function(){
				var $this = $(this);
				if($this.val()==$this.parent().find('.label').text()) {
					$this.val('');
				}
			},
			blur:function(){
				var $this = $(this);
				if($this.val()=='') {
					$this.val($this.parent().find('.label').text());
				}
			}
		});
		$term.val($term.parent().find('.label').text());
		$('#term-submit').bind({
			mouseover:function(){
				$(this).addClass('over');
			},
			mouseout:function(){
				$(this).removeClass('over');
			}
		});
	}

	if($('.entry-content').length > 0) {
		$('.entry-content').each(function(){
			var html = $(this).html();

			var videoMatches = /\[video code=([^\)]+)\]/.exec(html);

			if(videoMatches && videoMatches.length > 0) {
				var newContent = html;
				var videoLink = videoMatches[0];
				var videoUrl = videoMatches[1];

				var width = 320;
				var height = 240;
				var isDetailedView = false;

				if($('#comments').length > 0) {
					isDetailedView = true;
				}
				if(isDetailedView) {
					/*width = 460;
					height = 345;*/
					width = 380;
					height = 260;
				}

				newContent = newContent.replace(
					videoLink,
					'<div class="myvideo">'+loadVideoYoutube (videoUrl,width,height)+'</div>'
				);
				$(this).html(newContent);
			}
		});
	}

	if($('.fullbody').length > 0) {
		$('.fullbody .portlet-content').each(function(){
			$(this).bind({
				mouseover: function(){
					if(animating=='no' && !$(this).parents('.fullbody').hasClass('opened')) {
						$(this).css({'background-position':'left -274px'});
					}
				},
				mouseout: function(){
					if(animating=='no' && !$(this).parents('.fullbody').hasClass('opened')) {
						$(this).css({'background-position':'left 0px'});
					}
				}
			});
			//$(this).find('.question').css({'opacity':0.5});
		});
	}

	if($('#contact-submit').length > 0) {
		$('#contact-form-container .label').hide();
		$('#contact-submit').bind({
			mouseover:function(){
				$(this).addClass('over');
			},
			mouseout:function(){
				$(this).removeClass('over');
			}
		});
		$('#author,#email,#comment').unbind('click,focus,blur').bind({
			click:function(){
				var $this = $(this);
				if($this.val()==$this.parent().find('.label').text()) {
					$this.val('');
				}
			},
			focus:function(){
				var $this = $(this);
				if($this.val()==$this.parent().find('.label').text()) {
					$this.val('');
				}
			},
			blur:function(){
				var $this = $(this);
				if($this.val()=='') {
					$this.val($this.parent().find('.label').text());
				}
			}
		}).trigger('blur');
	} else {
		
	}

	$.data(document.body,'styleOn',$body.attr('class'));
});
