/*-------------------------------------------------------
   Javascript for 623
   Design Engine v3.0 - (Default)
-------------------------------------------------------*/

$(".headerText").fitText(1, { minFontSize: '15px', maxFontSize: '12px' });

function site_url(uri)
{
	return base_url+uri
}


function showCaption() {
	$('.bg_caption').css("display", "block");
	$('#background').addClass( 'showCaption' );
	$('#caption').html('<a href="#" onclick="hideCaption()"><i class="fa fa-camera"></i></a>');
}
function hideCaption() {
	$('.bg_caption').hide();
	$('#background').removeClass( 'showCaption' );
	$('#caption').html('<a href="#" onclick="showCaption()"><i class="fa fa-camera"></i></a>');
}

$(document).ready(function()
{

    $('.fb-share').click(function(e) {
        e.preventDefault();
        window.open($(this).attr('href'), 'fbShareWindow', 'height=450, width=550, top=' + ($(window).height() / 2 - 275) + ', left=' + ($(window).width() / 2 - 225) + ', toolbar=0, location=0, menubar=0, directories=0, scrollbars=0');
        return false;
    });

	$("#popup-modal").fadeIn(500);
	$("#popup-modal-full").fadeIn(500);
		
	$('a[data-toggle=modal]').click(function(e) {
		e.preventDefault();
	  $("#" + $(this).data("target")).fadeIn(500);
	})
	
	$('.modal-close').click(function (e) {
		e.preventDefault();
		$('.modal').fadeOut(500);
	});

	$('#popup-modal-full').click(function (e) {
		e.preventDefault();
		$('.modal').fadeOut(500);
	});
	
	var url = window.location.href;
	if(url.indexOf('#watch') != -1) {
    	$('#watch-modal').fadeIn(500);
	}
		
	$(document).keyup(function(ev){
		if(ev.keyCode == 27)
			$('.modal').fadeOut(500);
	});

	$('a[data-toggle=dropdown]').click(function(e) {
		e.preventDefault();
	  $("#" + $(this).data("target")).slideToggle(100);
	})
		
	var width = $(".square").width();
	$('.square').css('height', width);

	// for the window resize
	$(window).resize(function() {
	    var width = $(".square").width();
	    $('.square').css('height', width);
	});

	var width = $(".sixteenNine").width()/16;
	$('.sixteenNine').css('height', width*9);

	// for the window resize
	$(window).resize(function() {
	    var width = $(".sixteenNine").width()/16;
	    $('.sixteenNine').css('height', width*9);
	});

	//Keeps the video background proportions
	var v_height = $(".vimeo_bg_iframe").height()/9;
	$('.vimeo_bg_iframe').css('width', v_height*16);

	// for the window resize
	$(window).resize(function() {
	    var v_height = $(".vimeo_bg_iframe").height()/9;
	    $('.vimeo_bg_iframe').css('width', v_height*16);
	});
		
	$('a.switch').on('click', function(e) {
	e.preventDefault();
	var body = $('body');
	if(body.hasClass('menuOn')) {
		var offset = -parseInt(body.css('top'));
		body.removeClass('menuOn').css('top', 0).scrollTop(offset);
	} else {
		body.css('top', -window.pageYOffset+'px').addClass('menuOn');
		}
	});
		
	/* Slider */
	
	var settings = { time: 7000, pausefor: 1000 };
	
	settings.slides = $(".slideshow li");
	settings.timer = setInterval(nextSlide, settings.time);
	settings.timeout = null;
	settings.current = 0;

	settings.slides.eq(0).addClass("current");
	settings.slides.eq(1).addClass("next");

	var n = 0;	

	settings.slides.each(function(){
		var slide = this,
			img = $(slide).find("img"),
			sh = slide.offsetHeight;
		
		img.on("load", function(){
			var tih = event.target.height,
				dy =  ((sh-tih)/2);
				if(tih>sh) {
					img.css({"margin-top": dy+"px"});
					}
			});

		$(slide).addClass("slide");
		$(slide).attr("id", "slide-" + n);
		n++;
	});
			
    	 
	function nextSlide() {

		settings.slides.removeClass("current next prev");

		if(settings.current+1 < settings.slides.length){
			settings.current++;
		} else { settings.current = 0; }
		
		settings.slides.eq(settings.current).addClass("current");
		settings.slides.eq(settings.current+1).addClass("next");
		if(!settings.slides.filter("next").length>0){
			settings.slides.eq(0).addClass("next");
		}
		
		settings.slides.eq(settings.current-1).addClass("prev");

	}


	$('form.signup label[for]+input[type="text"]')
	.wrap('<div class=\"hover-wrap\" style=\"position:relative;float:left\"><\/div>')
	.focus(function(){$(this).prev().hide();})
	.blur(function(){if ( !this.value ) $(this).prev().show()})
	.each(function(){$(this).before( $(this).parent().prev() );
	if ( this.value ) $(this).prev().hide();});
	
	
	/* if($("table.screenings").length>0){
		var table = $("table.screenings"),
			rows = table.find("tr");
			
		rows.each(function(){
			$(this).find("td:last-child").append('<a href="#more" class="watch-More btn btn-small"><i class="fa fa-caret-down" aria-hidden="true"></i> Details</a>');
			$(this).find("a[href=#more]").click(function(){
				var row = $(this).parent("td").parent("tr"),
					screening = row.data("screening");
					
					if(row.next(".details").length<1){
					
						row.after('<tr class="details"><td colspan="4"></td></tr>');
						details = row.next().find("td");
					
						$.ajax({
							  url: "/screenings/ajax_details/"+screening,
							  context: document.body
							}).done(function(response) {
							  details.html(response);
							});
						
						$(this).html("<i class='fa fa-caret-up'></i> Hide");
						
					} else {
						if($(this).text().toLowerCase().indexOf("hide") !== -1){
							details = row.next(".details");
							details.hide();
							$(this).html("<i class='fa fa-caret-down'></i> Details");
						}
					}
				
				});
		});
	} */
	
	// confirm that images are loaded prior to masonry running
	$('.masonry').imagesLoaded(function() {
	  
	  $('.masonry').each(function() {
	    $(this).masonry({
	        itemSelector: 'li'
	      });
	  });
	  
	});
	
	$(function() { 

		// Mobile Nav switcher
		$('a.switch').on('click', function(e) { 
			e.preventDefault();
			var body = $('body');
			if(body.hasClass('showNav')) {
				var offset = -parseInt(body.css('top'));
				body.removeClass('showNav').css('top', 0).scrollTop(offset);
			} else {
				body.css('top', -window.pageYOffset+'px').addClass('showNav');
			}
		});

		// Contact Form
		$('.site-contact-form select[name="reason"]').on('change', function(e) {
			// Redirect to screening request page
			if($(this).val() == 'request_screening'){
				var host = $(this).data('host');
				window.location.replace(host + "screenings/organise_a_screening");
			}
		});

	});

});

var user_profile = {
	initialized: false,
	id: '#user_profile', //i.e. #audience_segment_control
	auth_id: '',

	// Initialize class
	init: function(){
		var self = this;
		if(!this.initialized){
			self.init_triggers();
			self.initialized = true;
		}
		return self;
	},

	// Initialize triggers
	init_triggers: function(){
		var self = this;

		// Authorize btn
		$(self.id).on('click', 'a[data-action="authorize"]', function(e){
			self.authorize($(this).data('provider'));
			return false;
		});
		// Deauthorize btn
		$(self.id).on('click', 'a[data-action="deauthorize"]', function(e){
			self.deauthorize($(this).data('provider'), false);
			return false;
		});
		// Deauthorize and logout btn
		$(self.id).on('click', 'a[data-action="deauthorize-logout"]', function(e){
			self.deauthorize($(this).data('provider'), true);
			return false;
		});
		// Logout btn
		$(self.id).on('click', 'a[data-action="logout"]', function(e){
			self.logout();
			return false;
		});
		// Login btn
		$(self.id).on('click', 'a[data-action="login-open"]', function(e){
			self.open('.login');
			return false;
		});
		// Login form
		$(self.id).on('submit', '#user_login_form', function(e){
			self.login();
			return false;
		});
		// Signup btn
		$(self.id).on('click', 'a[data-action="signup-open"]', function(e){
			self.open('.signup', {height: 480});
			return false;
		});

	},

	// Check for authorization
	checkAuth: function(provider, sid){
		var self = this;
		var url = '/users/checkAuth/'+provider;
		if(sid) url = url+'?sid='+self.auth_id;
		
		$.ajax({
			dataType: 'json',
			url: url,
			cache: false,
			success: function(result)
			{
				if (result) self.authSuccess(provider, result);
				else self.authFail(provider);
			},
			error:function(xhr, ajaxOptions, thrownError)
			{
				trace('ERROR: '+thrownError);
				trace('STATUS: '+xhr.status);
			}
		});
	},

	// Authorize a provider
	authorize: function(provider){
		var self = this;
		self.auth_id = Math.random().toString(36).substr(2, 16);
		url = '/users/authorize/'+provider+'?sid='+self.auth_id;
		window.user_profile = self;
		installPopup = window.open(url, 'authorize', 'width=600,height=600');
		
		var pollTimer = window.setInterval(function() {
			if (installPopup.closed !== false) { // !== is required for compatibility with Opera
				window.clearInterval(pollTimer);
				self.checkAuth(provider, self.auth_id);
			}
		}, 200);
	},

	// Executed on authorization success
	authSuccess: function(provider, result){
		var self = this;

		if(result.email.search(/@assemble-vimeo_user.com/i) == -1){
			location.reload(); // Reload page
		} else{ 
			// New vimeo connect. Prompt user for email
			var screen = $('.user_profile_view .update', self.id);
			$.ajax({
				url: '/users/profile_ajax', 
 				//dataType: 'json', 
				success: function(result){ 
					screen.html(result);
					self.open('.update');
				},
				error:function(xhr, ajaxOptions, thrownError)
				{
					trace('ERROR: '+thrownError);
					trace('STATUS: '+xhr.status);
				}		
			})
			
		}		
	},

	// Executed on authorization fail
	authFail: function(provider){
		var self = this;
		//console.log("Auth Failed!");
		$('#user_login_form .usr_msg').html("Sorry, your account was not authorized.");
	},

	// Display a message to user.
	userMsg: function(msg){
		var self = this;
		$('.user_profile_msg', self.id).html('<span class="txt">' + msg + '</span>');
		$('.user_profile_msg .txt', self.id).delay(4000).fadeOut('slow');
	},

	// Deauthorizes a provider
	deauthorize: function(provider, logout){
		var url = '/users/deauthorize/'+provider;
		if(logout)
			url += '?logout=1'
		$.ajax({
			url: url,
			success: function()
			{
				//setPluginNotInstalled(provider);
				location.reload(); // Reload page
			},
			error:function(xhr, ajaxOptions, thrownError)
			{
				trace('ERROR: '+thrownError);
				trace('STATUS: '+xhr.status);
			}
		});
	},

	// Update user info
	update: function(){
		$.ajax({
			url: '/users/profile_ajax/',
			data: { // serialize doesn't work with shadowbox
				'email': $('#user_update_form input[name="email"]').last().val(),
				'first_name': $('#user_update_form input[name="first_name"]').last().val()
			},
			type: 'POST',
			success: function(result)
			{
				if(result == 'saved')
					location.reload(); // Reload page
				else
					$('.user_profile_screen', self.id).html(result);
			},
			error:function(xhr, ajaxOptions, thrownError)
			{
				trace('ERROR: '+thrownError);
				trace('STATUS: '+xhr.status);
			}
		});
	},

	// Logs the user out
	logout: function(){
		$.ajax({
			url: '/users/logout/',
			success: function()
			{
				location.reload(); // Reload page
			},
			error:function(xhr, ajaxOptions, thrownError)
			{
				trace('ERROR: '+thrownError);
				trace('STATUS: '+xhr.status);
			}
		});
	},

	// Opens a screen
	open: function(screenClass, extraParams){
		var self = this;
		var html = $('.user_profile_view ' + screenClass, self.id).html();
        var params = $.extend({}, extraParams);

		// If box is already open
		if(Shadowbox.isOpen()){
			$('.user_profile_screen').html(html);
		} else {
			html = '<div class="user_profile_screen">' + html + '</div>';
			Shadowbox.open({
				content: html,
				player: "html",
				height: params.height || 400,
				width: params.width || 600
			});
		}
	},

	// Closes a screen
	close: function(screenClass){
		var self = this;
		$('.user_profile_view ' + screenClass, self.id).slideUp();
	},

	// Login form submit
	login: function(){
		var self = this;
		$('#user_login_form .usr_msg').addClass('loading').html('');
		$.ajax({
			url: '/users/login/',
			type: 'POST',
			dataType: 'json',
			data: { // serialize doesn't work with shadowbox
				'email': $('#user_login_form input[name="email"]').last().val(),
				'password': $('#user_login_form input[name="password"]').last().val()
			},
			success: function(result)
			{
				if (result){ 
					location.reload(); // Reload page
				} else {
					$('#user_login_form .usr_msg').removeClass('loading').html("Sorry, that user or password was incorrect.");
				}
			},
			error:function(xhr, ajaxOptions, thrownError)
			{
				trace('ERROR: '+thrownError);
				trace('STATUS: '+xhr.status);
			}
		});
	},

	// Signup form submit
	signup: function(){
		var self = this;
		$('#user_signup_form .usr_msg').addClass('loading').html('');
		$.ajax({
			url: '/users/signup/',
			type: 'POST',
			dataType: 'json',
			data: { // serialize doesn't work with shadowbox
				'first_name': $('#user_signup_form input[name="first_name"]').last().val(),
                'email': $('#user_signup_form input[name="email"]').last().val(),
				'password': $('#user_signup_form input[name="password"]').last().val(),
				'username': $('#user_signup_form input[name="username"]').last().val(),
				'humanVerification': $('#user_signup_form input[name="humanVerification"]').last().val(),
			},
			success: function(data)
			{
				if (data.result){ 
					location.reload(); // Reload page
				} else {
					$('#user_signup_form .usr_msg').removeClass('loading').html(data.msg);
				}
			},
			error:function(xhr, ajaxOptions, thrownError)
			{
				trace('ERROR: '+thrownError);
				trace('STATUS: '+xhr.status);
			}
		});
	},

	// Login form submit
	forgot: function(){
		var self = this;
		$('#user_forgot_form .forgot_usr_msg').empty().addClass('loading');
		var url = '/users/forgot/?email=' + $('#user_forgot_form input[name="email"]').last().val();
		$.ajax({
			url: url,
			type: 'GET',
			dataType: 'json',
			success: function(result)
			{
				if (result){ 
					$('#user_forgot_form .forgot_usr_msg').removeClass('loading').html("Please check your email for password reset instructions.");
				} else {
					$('#user_forgot_form .forgot_usr_msg').removeClass('loading').html("Sorry, there is no user with that email.");
				}
			},
			error:function(xhr, ajaxOptions, thrownError)
			{
				trace('ERROR: '+thrownError);
				trace('STATUS: '+xhr.status);
			}
		});
	},

};

/* Sticky-kit v1.1.2 | WTFPL | Leaf Corcoran 2015 | http://leafo.net */

(function(){var b,f;b=this.jQuery||window.jQuery;f=b(window);b.fn.stick_in_parent=function(d){var A,w,J,n,B,K,p,q,k,E,t;null==d&&(d={});t=d.sticky_class;B=d.inner_scrolling;E=d.recalc_every;k=d.parent;q=d.offset_top;p=d.spacer;w=d.bottoming;null==q&&(q=0);null==k&&(k=void 0);null==B&&(B=!0);null==t&&(t="is_stuck");A=b(document);null==w&&(w=!0);J=function(a,d,n,C,F,u,r,G){var v,H,m,D,I,c,g,x,y,z,h,l;if(!a.data("sticky_kit")){a.data("sticky_kit",!0);I=A.height();g=a.parent();null!=k&&(g=g.closest(k));
if(!g.length)throw"failed to find stick parent";v=m=!1;(h=null!=p?p&&a.closest(p):b("<div />"))&&h.css("position",a.css("position"));x=function(){var c,f,e;if(!G&&(I=A.height(),c=parseInt(g.css("border-top-width"),10),f=parseInt(g.css("padding-top"),10),d=parseInt(g.css("padding-bottom"),10),n=g.offset().top+c+f,C=g.height(),m&&(v=m=!1,null==p&&(a.insertAfter(h),h.detach()),a.css({position:"",top:"",width:"",bottom:""}).removeClass(t),e=!0),F=a.offset().top-(parseInt(a.css("margin-top"),10)||0)-q,
u=a.outerHeight(!0),r=a.css("float"),h&&h.css({width:a.outerWidth(!0),height:u,display:a.css("display"),"vertical-align":a.css("vertical-align"),"float":r}),e))return l()};x();if(u!==C)return D=void 0,c=q,z=E,l=function(){var b,l,e,k;if(!G&&(e=!1,null!=z&&(--z,0>=z&&(z=E,x(),e=!0)),e||A.height()===I||x(),e=f.scrollTop(),null!=D&&(l=e-D),D=e,m?(w&&(k=e+u+c>C+n,v&&!k&&(v=!1,a.css({position:"fixed",bottom:"",top:c}).trigger("sticky_kit:unbottom"))),e<F&&(m=!1,c=q,null==p&&("left"!==r&&"right"!==r||a.insertAfter(h),
h.detach()),b={position:"",width:"",top:""},a.css(b).removeClass(t).trigger("sticky_kit:unstick")),B&&(b=f.height(),u+q>b&&!v&&(c-=l,c=Math.max(b-u,c),c=Math.min(q,c),m&&a.css({top:c+"px"})))):e>F&&(m=!0,b={position:"fixed",top:c},b.width="border-box"===a.css("box-sizing")?a.outerWidth()+"px":a.width()+"px",a.css(b).addClass(t),null==p&&(a.after(h),"left"!==r&&"right"!==r||h.append(a)),a.trigger("sticky_kit:stick")),m&&w&&(null==k&&(k=e+u+c>C+n),!v&&k)))return v=!0,"static"===g.css("position")&&g.css({position:"relative"}),
a.css({position:"absolute",bottom:d,top:"auto"}).trigger("sticky_kit:bottom")},y=function(){x();return l()},H=function(){G=!0;f.off("touchmove",l);f.off("scroll",l);f.off("resize",y);b(document.body).off("sticky_kit:recalc",y);a.off("sticky_kit:detach",H);a.removeData("sticky_kit");a.css({position:"",bottom:"",top:"",width:""});g.position("position","");if(m)return null==p&&("left"!==r&&"right"!==r||a.insertAfter(h),h.remove()),a.removeClass(t)},f.on("touchmove",l),f.on("scroll",l),f.on("resize",
y),b(document.body).on("sticky_kit:recalc",y),a.on("sticky_kit:detach",H),setTimeout(l,0)}};n=0;for(K=this.length;n<K;n++)d=this[n],J(b(d));return this}}).call(this);

$(".sticky").stick_in_parent({recalc_every: 1});

$('.sticky')
.on('sticky_kit:bottom', function(e) {
    $(this).parent().css('position', 'static');
})
.on('sticky_kit:unbottom', function(e) {
    $(this).parent().css('position', 'relative');
})

$('#Home #row-4 h2.take-action').parents('.inner-section').insertBefore('#Home #row-5 .inner-section');
	
	
	