/* ****************************** SCRIPT LOGIC  ******************************** */

$(function(){
	
	
	/*==================== HOVER FADING ====================*/
	
	/*
	opacity: .7,						// 0 - 1. //
	animSpeedIn: 500,					// Anim time in milliseconds. //
	animSpeedOut: 200,					// Anim time in milliseconds. //
	delayIn: 0,							// Delay time in milliseconds. //
	delayOut: 0,						// Delay time in milliseconds. //
	childElement: null,					// Child to apply fade to. //
	easing: '',							// Easing to apply. //
	onAnimInStart: null,				// Additional function to peform when anim begins. //
	onAnimInEnd: null,					// Additional function to peform when anim ends. //
	onAnimOutStart: null,				// Additional function to peform when anim begins. //
	onAnimOutEnd: null,					// Additional function to peform when anim ends. //
	ieOpacityClass: 'ieOpacityFail'		// IE class that uses IE filters to change opacity. //
	*/
	
	_initQuicklinks = function( $elem ){
		/*$elem.find('.quickLink').hoverFade({
			opacity:0.7,
			childElement:'.quicklinkBg',
			easing:'easeOutCubic',
			animSpeedIn:300,
			animSpeedOut:200,
			onAnimInStart:function( $this ){
				// For article links. //
				$this.find('.articleInfoContainer').stop(true, true).animate({'bottom':0}, {duration:200, easing:'easeInOutQuad'});
				var $titles = $this.find('.articleInfoContainer .linkTitleContainer');
				$titles.find('.articleLinkTitle, ._jsArticleSubtitle').find('span').removeClass('hide');
				// For latest article links. //
				if( $titles.find('._jsArticleTags').size() ) $titles.find('._jsArticleSubtitle').hide().end().find('._jsArticleTags').show();
				
				// For pillar links. //
				$this.find('.titleBg, .linkTitle').stop(true, true).animate({height:46}, {duration:100, easing:'easeInOutQuad'});
			},
			onAnimOutStart:function( $this ){
				// For article links. //
				$this.find('.articleInfoContainer').stop(true, true).animate({'bottom':-80}, {duration:150, easing:'easeInOutQuad'});
				var $titles = $this.find('.articleInfoContainer .linkTitleContainer');
				$titles.find('.articleLinkTitle, ._jsArticleSubtitle').find('span').addClass('hide');
				// For latest article links. //
				if( $titles.find('._jsArticleTags').size() ) $titles.find('._jsArticleTags').hide().end().find('._jsArticleSubtitle').show();
				
				// For pillar links. //
				$this.find('.titleBg, .linkTitle').animate({height:36}, {duration:100, easing:'easeInOutQuad'});
			}
		});*/
		$elem.find('.quickLink').hoverFade({
			opacity:0.7,
			childElement:'.quicklinkBg',
			easing:'easeOutCubic',
			animSpeedIn:300,
			animSpeedOut:200,
			onAnimInStart:function( $this ){
				
				$this = $this.not('.miniSize');
				
				$this.find('.articleInfoContainer').stop(true, true).animate({'bottom':0}, {duration:200, easing:'easeInOutQuad'});
				var $titles = $this.find('.articleInfoContainer .linkTitleContainer');
				$titles.find('.articleLinkTitle, ._jsArticleSubtitle').find('span').removeClass('hide');
				// For latest article links. //
				if( $titles.find('._jsArticleTags').size() ) $titles.find('._jsArticleSubtitle').hide().end().find('._jsArticleTags').show();
				
				// For pillar links. //
				$this.find('.linkTitle').stop(true, true).animate({paddingLeft:15}, {duration:100, easing:'easeInOutQuad'});
				//$this.find('.titleBg, .linkTitle').stop(true, true).animate({height:46}, {duration:100, easing:'easeInOutQuad'});
			},
			onAnimOutStart:function( $this ){
				
				$this = $this.not('.miniSize');
				
				if( $this.hasClass('category') ) var bottomAmt = -20;
				else var bottomAmt = -80;
				
				$this.find('.articleInfoContainer').stop(true, true).animate({'bottom':bottomAmt}, {duration:150, easing:'easeInOutQuad'});
				var $titles = $this.find('.articleInfoContainer .linkTitleContainer');
				$titles.find('.articleLinkTitle, ._jsArticleSubtitle').find('span').addClass('hide');
				// For latest article links. //
				if( $titles.find('._jsArticleTags').size() ) $titles.find('._jsArticleTags').hide().end().find('._jsArticleSubtitle').show();
				
				// For pillar links. //
				//$this.find('.titleBg, .linkTitle').animate({height:36}, {duration:100, easing:'easeInOutQuad'});
				$this.find('.linkTitle').stop(true, true).animate({paddingLeft:10}, {duration:100, easing:'easeInOutQuad'});
			}
		});
	}
	_initQuicklinks($('body'));
	
	
	// Right panel hovering on articles page. //
	var regExpContainsArticles = /articles/i;
	var regExpContainsView = /view/i;
	if( regExpContainsArticles.test(location.search) && regExpContainsView.test(location.search) ){
		$('.panel.widget').addClass('rightPanelOpacity').hoverFade({
			opacity:1,
			easing:'easeOutCubic',
			animSpeedIn:300,
			animSpeedOut:200,
			delayOut:150,
			ieOpacityClass:'ieOpacityFailed100'
		});
	}
	
	
	// Right Panel artlice links. //
	if( $.support.opacity ) {
		$('.topArticleWrapperWeek a, .topPartiesWidget a.party').removeClass('noOpacitySupport').hoverFade({
			childElement:'.articleThumb',
			opacity:1,
			easing:'easeOutCubic',
			animSpeedIn:300,
			animSpeedOut:200,
			delayOut:150
		});
	}
	
	
	/*==================== NAVIGATION ====================*/
	
	/*
	mouseOutDelay:200, 					// Millisecs waiting for menu item to hide //
	animate:true,						// True to fade in / fade out on first item open, item closing //
	fadeTime:200 						// Fade animation speed //
	*/
	
	$('#_jsMenuNav').menu({
		mouseOutDelay:200,
		animate:true,
		fadeTime:200
	});
	
	
	/*==================== BACKGROUND CROSS EFFECT ====================*/
	
	/*
	nextElement:'',						// The next element to reveal during the effect //
	delayOnLoad:2000,					// Delay after loading if runOnLoad is true //
	animateMethod:'fade',				// Method of cross effect (fade, slide) //
	animateSpeed:1000,					// Animation speed //
	animateType:'over',					// 'over' 'outIn' - specifies whether the first object should remain in place
											or have the opposite effect applied to it
	runOnLoad:true,						// If this should run on load //
	listeners:[							// If externals listeners can trigger this effect //
		{'#selector' : 'click'}			// Selector and event listener //
	],
	preventAnimation:true				// True to prevent animatin (e.g. for ie)
	*/
	
	$('#initDynamicBG').crossEffect({
		nextElement:'#nextDynamicBG',
		animate:true,
		runOnLoad:true,
		animateMethod:'fade',
		animateType:'over',
		animateSpeed:500
		/*
		,
		listeners:[ {
			'#_jsMenuNav a' : 'click',
			'onEvent' : function( $a, event ){
				
				// Prevent nav and get back JSON from a tag //
				event.preventDefault();
				var json = $.parseJSON( $a.attr('rel') );
				
				// Switch background based on JSON //
				if(json){
					$('#nextDynamicBG').css({
						'background' : 'url(img/contextBg/' + json['cat_id'] + '.jpg) bottom center no-repeat'
					});
				}
				
				// On complete of event //
				return function(){
					location.href = $a.attr('href');
				}
			}
		}]*/
	});
	
	
	/*==================== DROPDOWN REPLACE ====================*/
	
	
	/*
	title:'Please make a selection',		// HTML of dropdown anchor //
	wrapperClass:'_jsDropdownWrapper',		// Wrapper div class. //
	containerClass:'_jsDropdownContainer',	// Container ul class. //
	initClass:'_jsInitDropdown',			// Init a class. //
	animate:true,							// Slide down & up. //
	easing:'',								// Slide down & up. //
	animSpeedIn:300,						// Slide in speed. //
	animSpeedOut:200,						// Slide out speed. //
	submitIfSingle:true						// Submits the form of it's the only form element in the form. //
	*/
	// Commented out for now, while Justin works on the styling etc. //
	$( '._jsDropDownReplace' ).replaceDropdown({
		easing:'easeInOutExpo',
		animSpeedIn:300,
		animSpeedOut:200,
		wrapperClass:'jsDropDown',
		initClass:'_jsDropDownInit',
		containerClass:'ulDropDown',
		submitIfSingle:true
	});
	
	
	/*==================== MORE OF THE SAME CATEGORY SHIFTER ====================*/
	
	
	$('.articlesLinkStage').shifter();
	
	
	/*==================== BANNER CYCLERS ====================*/
	
	/*
	type: 'fade',						// Sets the type of anim.  Possible values are : slide,fade,hard. //
	direction: 'right',					// Sets the direction of the anim  if type is 'slide'. Possible values are : up,down,left,right. //
	useNumbers: true,					// Sets to show numbers to navigate or not . Possible values are : true, false. //
	onAnimEnd: null,					// Additional function to peform when anim ends. //
	onAnimStart: null,					// Additional function to peform when anim begins. //
	animSpeed:500,						// Anim time in milliseconds. //
	easing: '',							// Easing to apply. //
	delayTime:5000						// Time in milliseconds between anims. //
	*/
	
	_runBanners = function(){
		$('._jsBannerCyclerMain').bannerCycler({
			delayTime:6000,
			animSpeed:800,
			easing:'easeInOutQuint',
			type:'slide',
			direction:'up',
			useNumbers:true,
			onAnimStart:function($this){
				$this.find('.bannerDesc').fadeOut(200);
			},onAnimEnd:function($this){
				$this.find('.bannerDesc').fadeIn(200);
			}
		});
		$('._jsBannerCyclerAdvert').bannerCycler({
			delayTime:5000,
			animSpeed:1000,
			type:'fade',
			useNumbers:false
		});
	}
	
	
	/*==================== POPUP ====================*/
	
	/*
	onPopupCreation: null,				// Additional function to peform when pop up is created (before it fades in - for content generation & adding classes). //
	onOpenAnimEnd: null,				// Additional function to peform when anim ends. //
	onCloseAnimEnd: null,				// Additional function to peform when anim ends. //
	delayBlanketIn: 200,				// Delay time in milliseconds. //
	delayContentIn: 200,				// Delay time in milliseconds. //
	animSpeedBlanketIn: 500,			// Anim time in milliseconds. //
	animSpeedContentIn: 500,			// Anim time in milliseconds. //
	animSpeedBlanketOut: 200,			// Anim time in milliseconds. //
	animSpeedContentOut: 300,			// Anim time in milliseconds. //
	closePopup:false					// Overwrite function & close popup //
	*/
	
	
	// Launch gallery popup. //
	$('.galleryWidgetWrapper').click(function(e){
		e.preventDefault();
		$.popup({
			onPopupCreation:function($this){
				var articleId = location.search.split('/')[3];
				
				$.ajax({
					url:'?/gallery',
					dataType:'html',
					type:'post',
					data:{
						ajax_on:true,
						article_id:articleId
					},
					success:function(newHtml){
						$this.find('.popupContainer').html(newHtml);
					},
					error:function(){
						alert('issue on ajax on popup');
					}
				});
			},onOpenAnimEnd:function($this){
				if( $.support.opacity ) $this.find('.moduleGallery').thumbsGallery();
				else{
					$.doTimeout('initGallery', 1000, function(){ 
						$this.find('.moduleGallery').thumbsGallery();
					});
				}
			}
		});
	});
	
	
	
	$('body').delegate('._jsPreviewImage', 'click', function( e ){
		e.preventDefault();
		
		var imgSrc = $(this).parents('.downloadItem').first().find('img').attr('src');
		var imgAlt = $(this).parents('.downloadItem').first().find('img').attr('alt');
		var downloadHref = $(this).siblings('a').attr('href');
		
		$.popup({
			onPopupCreation:function($this){
				$this.find('.popupClose').css({
					'marginTop':'-400px',
					'marginLeft':'435px'
				});
				$this.find('.popupContainer').css({
					'height':'768px',
					'marginTop':'-384px',
					'marginLeft':'-450px',
					'width':'900px'})
				.html('<img class="previewImg" src="'+imgSrc+'" alt="'+imgAlt+'" /><div class="previewLoading"></div><a href="'+downloadHref+'" class="previewDownload">Download</a>');
			},onOpenAnimEnd:function($this){
				var imgHeight =  Number( $this.find('.popupContainer .previewImg').height() );
				var imgWidth =  Number( $this.find('.popupContainer .previewImg').width() );
				
				$this.find('.popupContainer').hover(function(){
					$this.find('.previewDownload').fadeIn();
				},function(){
					$this.find('.previewDownload').fadeOut();
				});
				
				$this.find('.popupContainer').animate({
					'height':imgHeight+40,
					'width':imgWidth+40,
					'marginTop':(imgHeight+40)*-.5,
					'marginLeft':(imgWidth+40)*-.5},
				{duration:500, easing:'easeInOutQuint', complete:function(){
					$('.previewLoading').fadeOut();
				}});
				
				$this.find('.popupClose').animate({
					'marginTop':-(imgHeight+40)*.5-15,
					'marginLeft':(imgWidth+40)*.5-15},
				{duration:500, easing:'easeInOutQuint'});
			}
		});
		
	});
	
	
	/* ==================== FORMS ====================== */
	
	/*
	$.fn.formConfig.defaults = {
		listeners		: { 'click': '._jsTriggerFormSubmit' },			// Listeners (type, selector - relative to parent form) //
		disableListener	: true,											// Whether to disable listener on submit //
		ajaxSubmit		: false,										// Submit via AJAX POST request //
		ajaxDataType	: 'json',										// What kind of data response is expected //
		ajaxTimeout		: 20000, // Milisecond timeout //				// When to abandon AJAX call and throw error //
		ajaxKeyword		: 'ajax_on',										// What post var will be interpreted by PHP (to prevent normal output) //
		formElements	: 'input, select, textarea',					// What form elements to search for (jQuery selector) //
		formExceptions	: '._jsFormExp',								// What form elements to ignore //
		fnSuccess		: function( data, textStatus, xhr ){},			// What function to exec on success
		fnFailure		: function( data, textStatus, xhr ){},			// ... on failure //
		fnError			: function( xhr, textStatus, errorThrown ){},	// ... on error //
		validator		: {												// Optionally add validator to this form, and pass object as normal //
			...	
		}
	}; */
	
	// Search form //
	
	// General form behaviour //
	$('form._jsDefaultForm').formConfig({
		listeners: [
			{
				'click' : ['._jsTriggerFormSubmit' ]
			}
		],
		onBeforeSubmit: function( $form ){
		}
	});
	
	$('#header ._jsSearchHeaderForm').formConfig({
		listeners: [
			{
				'onKeyEnter' : ['input._jsOnKeyEnterSubmit'],
				'click' : ['._jsTriggerFormSubmit' ]
			}
		],
		validator: {
			inputTips:false
		},
		onBeforeSubmit: function( $form ){
			var searchTerm = $form.find('._jsSearchHeaderFormInput').val();
			$form.attr('action', '?/search/#for/'+searchTerm);
		}
	});
	
	// Contact form //
	
	$('#_jsContactForm').formConfig({
		listeners: [
			{
				'click' : ['._jsTriggerFormSubmit']
			}
		],
		ajaxSubmit : true,
		onBeforeSubmit: function( $form ){
			$form.find('._jsTriggerFormSubmit').addClass('disabled').find('span').html('SENDING MESSAGE...');
			$form.find(':input').attr('disabled','disabled');
			$form.find('.jsDropDown').addClass('disabled');
		},
		fnSuccess: function( $form, data, textStatus, xhr ){
			$form.find(':input').removeAttr('disabled');
			if( _supportsOpacity ){
				$form.find('.contactInputWrapper').fadeOut(500, function(){
					$(this).html("<p>Your message has been sent. Thanks for the chat, we'll be in touch.</p>").fadeIn();
				});
				$form.find('.contactTextareaWrapper').fadeOut(500);
				$form.find('h1').fadeTo(500, 0, function(){
					$(this).html('Thank You').fadeTo(500, 1);
				});
			}else{
				$form.find('.contactInputWrapper').html("<p>Your message has been sent. Thanks for the chat, we'll be in touch.</p>");
				$form.find('.contactTextareaWrapper').hide();
				$form.find('h1').html('Thank You');
			}
		},
		fnFailure: function( $form, errorThrown ){
			$form.find(':input').removeAttr('disabled');
			$form.find('.jsDropDown').removeClass('disabled');
			$form.find('._jsTriggerFormSubmit').removeClass('disabled').html('SEND MESSAGE');
			if(errorThrown){
				alert('Connection to internet failed');	
			}
		},
		ajaxKeyword:'ajax_on',
		validator: {
			inputTips:false,
			failureCls:'valFailed',
			successCls:'valPassed',
			useParent:true // Defines whether a parent should be used for class application // 
		},
		disableListener:true
	});
	
	
	/* ==================== GALLERY ====================== */
	
	/*
	animating : true,						// Use fading, sliding or hard cut. //
	extraSpace : true,						// Centre images on ends. //
	
	bigSlideSpeed : 700,					// Duration of big image slding. //
	bigSlideEasing : 'easeInOutQuint',		// Easing of big image slding. //
	
	thumbSlideSpeed : 400,					// Duration of thumbnail image slding. //
	thumbSlideEasing : 'easeInOutQuint',	// Easing of thumbnail image slding. //
	
	thumbHoverOpacity : .5,					// Opacity of thumbnail when hovering over it. Initial opacity is set by css. //
	thumbHoverSpeed : 300,					// Duration of thumbnail hover animation. //
	thumbHoverEasing : 'easeInOutQuad',		// Easing of thumbnail image slding. //
	
	bigFadeOpacity : .2,					// Opacity of big images when it's not in view. //
	bigFadeSpeed : 400,						// Duration of big image hover animation. //
	bigFadeEasing : 'easeInOutQuint',		// Easing of big image hover. //
	
	infoSlideSpeed : 300,					// Duration of info div image slding. //
	infoSlideEasing : 'easeInOutCirc',		// Easing of info div image slding. //
	
	minDraggerWidth : 200,					// Minimum dragger width. //
	maxDraggerWidth : 600,					// Maximum dragger width. //
	
	youTubeSupport : true					// Supports youtube videos in the gallery. //
	}; */
	
	$('.moduleGallery').thumbsGallery();
	
	
	/* ==================== CAROUSEL ====================== */
	
	
	$('.moduleCarousel .viewPort').carousel({carousel:'.carouselWrapper'});
	
	
	/*==================== DOWNLOADS AUDIO PLAYER ====================*/
	
	/*
	swfUrl: 'flash/flashSound.swf',		// SWF URL relative to root. //		
	onPause: null,						// Additional function to peform when sound gets paused. //
	onPlay: null,						// Additional function to peform when sound gets played after being paused. //
	onInit: null						// Additional function to peform when sound gets played first time around. //
	*/
	
	_initFlashSound = function(){
		var regExpContainsDownloads = /downloads/i;
		if( regExpContainsDownloads.test(location.search) ){
			$('._jsPlayAudio').flashSound({
				onPause:function( $this ){
					$this.html('Paused').removeClass('audioPlay').addClass('audioPause');
				},onPlay:function( $this ){
					$this.html('Playing').removeClass('audioPause').addClass('audioPlay');
				},onInit:function( $all ){
					$all.html('Preview').removeClass('audioPause audioPlay');
				}
			});
		}
	}
	_initFlashSound();
	
	/* ======================================= GLOBAL YOUTUBE ======================================= */
	
	$('div._jsYouTubeEmbed').each( function(){
		var $this = $(this);
		$this.youTubeEmbed({video:'http://www.youtube.com/watch?v='+vidId,overwrite:true, width:550, height:390});
	});
	
});
