/**
 * RAF polyfill
 */

(function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
                                   || window[vendors[x]+'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); },
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());

/**
 * Global namespace
 */
var submitTime = 0,
	submitLoop = 0,
	docReady, bgvideo, deruLoop;

// Mobile dev optimizaitons
var dev = false;

/**
 * Deru
 */
var deru = deru || {

	setup : function() {

		docReady = true;

		deru.gallery.setup();
		deru.background.setup();
		deru.social.setup();
		deru.transition.setup($('.transition'));

	},

	setSize : function() {
		// $('.project_content').css({
		// 	height : $(window).height()
		// })
	},

  centerThis : function($this) {

  	$this
	  	.removeClass('centered')
	  	.css({
	  		marginTop : '',
			opacity : '1'
	  	});

  	if ( $this.outerHeight() < $(window).height() ) {

  		$this
  			.addClass('centered')
	  		.css({
		      marginTop : ($(window).height() - $this.outerHeight() ) / 2,
		    });

  	}

  }

};

/**
 * Setup
 */
$(function() {

	deru.setup();

	$(window).resize(function() {
		deru.setSize();
	}).resize();

});

/**
 * Navigation
 */

deru.navigation = {

	active : function(pid) {

		// Reset active states
		$('.navigation')
			.find('a')
			.removeClass('active')
			.end()
			.find('a[data-id="' + pid + '"]')
			.addClass('active');

	}

}

/**
 * Gallery w/ Tumblr
 */

deru.gallery = {

	template : null,
	scroll   : null,
	newpage  : false,
	finished : false,

	data : {
		pagination : 10,
	},

	setup : function() {

		// Handlebarz
		deru.gallery.template = Handlebars.compile( $("#gallery-template").html() );

		// Scroll for paginate
		// $(window).on('scroll', function() {
		// 	clearTimeout(deru.gallery.scroll);
		// 	deru.gallery.scroll = setTimeout(function() {
		// 		deru.gallery.checkPagination();
		// 	}, 10);
		// });

	},

	checkPagination : function() {

		var top        = $(window).scrollTop();
		var breakpoint = $(document).height() - ($(window).height() * 2);

		if ( top > ( breakpoint ) && deru.gallery.newpage == false &&  deru.gallery.finished == false) {

			deru.gallery.paginate($('.gallery_container'));

			deru.gallery.newpage = true;
			setTimeout(function() {
				deru.gallery.newpage = false;
			}, 500);
		}
	},

	unload : function() {

	},

	paginate : function( $container ) {

		// Get the offset
		var page   = parseInt( $container.attr("data-page") ),
			offset = page * deru.gallery.data.pagination;

		// Show loading
		// $(".loading").show();

		// if ( data.response.total_posts == $('.gallery_post').length ) {
		// 	deru.gallery.finished = true;
		// 	$(".loading").hide();
		// 	return false;
		// }

		// Get the new data passed through Handlebars
		var formattedResponse = deru.gallery.template(posts);
		console.log(formattedResponse);

		// Add it to the container
  		$container.append(formattedResponse);

  		// Format the unformatted posts
  		$(".gallery_post:not([data-formatted])").each(function() {

	        var permalink = $(this).attr('data-permalink');

  			var $title = $(this).find('.caption_holder b, .caption_holder strong');
  			var $description = $(this).find('.caption_holder i, .caption_holder em');

  			// Remove redundant images
  			$(this).find('.hidden_img').first().remove();

  			// Format the title
  			$title.clone().appendTo($(this).find('.gallery_title'));
	  		$description.clone().appendTo($(this).find('.gallery_title'));

	  		// Format video URL
	  		if ( $(this).is('.video') ) {

		        var id, url;

	  			var $video = $(this).find('a.gallery_img');
	  			id = $video.attr('href').split("/").pop();
	  			url = 'http://player.vimeo.com/video/' + id;
	  			$video.attr('href', url);


		  		$(this).find('a.gallery_img').colorbox({
	  				transition: "none",
	  				speed : 0,
	  				fadeOut : 0,
	  				// maxWidth:"75%",
	  				// maxHeight:"75%",
	  				reposition : true,
	  				scalePhotos: true,
	  				scrolling : false,
	  				iframe:true,
	  				innerWidth: 800,
	  				innerHeight: 450
	  			});

	  		} else if ( $(this).is('.photo') ) {

	  			$(this).find('a.gallery_img').colorbox({
	  				rel: 'gallery-' + $(this).attr('data-id'),
	  				transition: "none",
	  				speed : 0,
	  				fadeOut : 0,
	  				maxWidth:"75%",
	  				maxHeight:"75%",
	  				reposition : true,
	  				scalePhotos: true,
	  				scrolling : false,
	  				current : "{current} of {total}"
	  			});

	  		}

  			// Yea we good
  			$(this).attr("data-formatted", "true");

  		});

		deru.gallery.layout();

	    setTimeout(function() {
	      deru.gallery.layout();
	    }, 1000);

  		// Update the data
  		$container.attr("data-page", page + 1);

	},

  layout : function($container) {

    var resizeTimeout;

    $(window).resize(function() {
		clearTimeout(resizeTimeout);
		resizeTimeout = setTimeout(function() {
			$('.gallery_container').removeWhitespace().collagePlus({
				'targetHeight'  : 500,
				'fadeSpeed' : "fast",
				'effect' : 'effect-1',
				'allowPartialLastRow' : true
			});
		},5);
    }).resize();

  },

};

$(document).on('cbox_open', function(){


 	$('body').addClass('lbox_open');

   $('#cboxWrapper .social_container').remove();

 	// Make the social shit
   setTimeout(function() {

     $('div.social_container')
       .clone()
       .removeAttr('id')
       .appendTo($('#cboxWrapper'));

    setTimeout(function() {

       var permalink = $('#cboxTitle .custompermalink').attr('data-link');
       var fblike = '<iframe class="facebooklike" src="//www.facebook.com/plugins/like.php?href=' + encodeURIComponent(permalink) + '&amp;width&amp;layout=button&amp;action=like&amp;show_faces=true&amp;share=false&amp;height=20&amp;appId=265799803451765&amp;colorscheme=dark" scrolling="no" frameborder="0" style="border:none; overflow:hidden; height:20px; width: 48px;" allowTransparency="true" data-colorscheme"dark"></iframe>';
       var tweetshit = '<a href="https://twitter.com/share" class="twitter-share-button" data-text="Deru 1979" data-url="' + permalink + '" data-count="none" data-dnt="true">Tweet</a>';

       $('#cboxWrapper').find('.facebooklike').after(fblike);
       $('#cboxWrapper').find('.facebooklike').first().remove();

       $('#cboxWrapper').find('.twitter-share-button').after(tweetshit);
       $('#cboxWrapper').find('.twitter-share-button').first().remove();

       twttr.widgets.load();

      }, 2000);


   }, 100);

});

 $(document).on('cbox_closed', function(){
 	$('body').removeClass('lbox_open');
 });

/**
 * Page
 */
deru.page = {

	setup : function() {

		var $container = $('.entry');
		var title = '';

		deru.setSize();

		// Project title
		if ( $container.attr('data-title') != undefined ) {
			title = 'section_' + $container.attr('data-title').replace(' ', '_');
		}

		// Reset the media related stuff
		deru.background.reset();
		$(window).off('scroll', history_scroll);

		$('body').attr('id', title);

	},

	center : function( $this ) {

		$this.css({
			marginTop : ($this.outerHeight() / 2) * -1,
			marginLeft : ($this.outerWidth() / 2) * -1
		})

	},

	extend : function() {

		// Check for doc ready
		if ( docReady ) {

			// If there are functions we should call
			if ( $('.project_content [data-event]').length > 0) {

				// Grab the event name
				var event_name = $('.project_content [data-event]').attr('data-event');

				// If it's a function which exists, call it
		    	if (typeof window[event_name] == 'function') {
					window[event_name]();
				}

			}

		}
		else {
			setTimeout(function() {
				deru.page.extend();
			}, 25);
		}

	},

	reset : function() {

	}

};

/**
 * Video
 */

deru.videos = {
	'boy_digging' : 'http://assets.1979.la/video/BoyDigging.mp4',
	'boy_digging_2' : 'http://assets.1979.la/video/BoyDigging2.mp4',
	'stone_throw' : 'http://assets.1979.la/video/StoneThrow.mp4'
};

deru.images = {
	'rain' : 'http://assets.1979.la/img/textures/grain.jpg',
	'grain' : 'http://assets.1979.la/img/textures/grain2.jpg',
	'noise' : 'http://assets.1979.la/img/textures/noisebg2.jpg',
	'hist1' : 'http://assets.1979.la/img/textures/hist_bg1.jpg',
	'hist2' : 'http://assets.1979.la/img/textures/hist_bg3.jpg',
};

deru.background = {

	setup : function() {

		// Look for instances of the big video
		if ( !bgvideo ) {
			bgvideo = new $.BigVideo();
			bgvideo.init();
		}

	},

	random : function(type, tag) {

		var data = { };

		// Fail check
		if ( type != 'video' && type != 'image' && type != 'reset' ) {
			console.log('needs a type');
			return false;
		}

		// Dev
		if ( dev ) {
			return false;
		}

		var _checkType = function() {
			// Check for the type of media we're randomizing
			if ( type == 'video' ) {
				data.obj = deru.videos;
			} else if ( type == 'image' ) {
				data.obj = deru.images;
			}
		};

		var _setSize = function() {
			data.size = Object.size(data.obj);
		}

		var _getRandomValue = function() {
			var keys = Object.keys(data.obj)
		    data.url = data.obj[keys[ keys.length * Math.random() << 0]];
		};

		var _setMedia = function() {

			// Video
			if ( type == 'video' ) {

				// Plugin
				bgvideo.show(data.url, { ambient: true } );

				// Show or hide
				$('#big-video-wrap').show();
				$('#big-image-wrap').hide();

			} else if ( type == 'image' ) {

				// Add the image to the page
				$('#big-image-wrap').css({
					'background-image' : 'url(' + data.url + ')',
					'display' : 'block'
				});

				// Show or hide
				$('#big-video-wrap').hide();

			} else if ( type == 'reset' ) {
				$('#big-video-wrap').hide();
				$('#big-image-wrap').hide();
			}

		};

		// Construct
		_checkType();
		_setSize();
		_getRandomValue()
		_setMedia();

	},

	remove : function() {

	},

	getVideo : function(video, url) {
    // Dev
    if ( dev ) {
      return false;
    }
		$('#big-image-wrap').hide();
		$('#big-video-wrap').show();
		if ( url == undefined ) {
			bgvideo.show(deru.videos[video], { ambient: true } );
		} else {
			bgvideo.show(url, { ambient: true } );
		}
	},

	getImg : function(img) {

    // Dev
    if ( dev ) {
      return false;
    }

		// Add the image to the page
		$('#big-image-wrap').css({
			'background-image' : 'url(' + deru.images[img] + ')',
			'display' : 'block'
		});

		// Show or hide
		$('#big-video-wrap').hide();

	},

	jumpTo : function(time) {

		if ( bgvideo && time !== undefined) {
			bgvideo.getPlayer().currentTime(time + 0.1);
		}

	},

	loopTo : function(time) {

		deru.background.jumpTo(time);
		clearTimeout(deruLoop);
		deruLoop = setTimeout(function() {
			deru.background.loopTo(time);
		}, 2800);

	},

	hideVideo : function() {
		$('#big-video-wrap').hide();
		if ( bgvideo ) {
			bgvideo.getPlayer().pause();
		}
		$('#big-image-wrap').show();
	},

	reset : function() {

		// Video
		$('#big-video-wrap').hide();
		if ( bgvideo ) {
			bgvideo.getPlayer().pause();
		}

		// Images
		$('#big-image-wrap').hide();

	}

};

/**
 * Transitions
 */

deru.transition = {

	$el : {
		parent : null,
		svg    : '<svg width="100" height="10%" viewBox="0 0 100 10" version="1.1" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns"><title>scrollit</title><description>Created with Sketch (http://www.bohemiancoding.com/sketch)</description><defs></defs><g stroke="none" stroke-width="0" fill="none" sketch:type="MSPage"><path d="M0,5 L100,5" id="Line" stroke="#000" stroke-width="10" stroke-dasharray="1 5" stroke-dashoffset="0" sketch:type="MSShapeGroup"></path></g></svg>'
	},

	data : {
		active  : false,
		length  : 5,
		pause   : 5,
		timeout : 250
	},

	/**
	 * Create
	 * @param  {int} id Used to grab the element
	 */
	create : function(id) {

		$(this.$el.svg)
			.attr('id', id)
			.prependTo(this.$el.parent.find('.bars'));

	},

	/**
	 * Resize the elements to fill the height of the window
	 * @param  {element} $window The window element
	 */
	resize : function($window) {
		var height = $window.height() / 9.9;
		this.$el.parent.find('.bars svg').height(height);
	},

	/**
	 * Randomize the SVG
	 * @param {element} $element The SVG we're targeting
	 */
	randomize : function($element) {

		var self = this;

		var opacity = Math.random() * 1;
		var bgposx  = Math.floor(Math.random() * 1000);
		var bgposy  = Math.floor(Math.random() * 1000);

		$element
			.css({
				'background-position' : bgposx + 'px ' + bgposy + 'px',
			})
			.find('path').each(function() {
				var len = Math.floor(Math.random() * self.data.length) + 1;
				var pau = Math.floor(Math.random() * self.data.pause) + 1;
				$(this).attr('stroke-dasharray', len + ' ' + pau);
			});

	},

	/**
	 * Animation loop
	 */
	loop : function() {

		// Explicitly state the location of self
		var self = deru.transition;

		setTimeout(function() {

			if ( self.data.active ) {

				requestAnimationFrame(self.loop);

				// Do the bidness
				self.$el.parent.find('svg').each(function() {
					self.randomize($(this));
				});

			}

		}, 10);

	},

	/**
	 * Make it dance
	 */
	setParams : function() {

		var self = this;

		setTimeout(function() {

			// Randomize the data
			self.data.length  = Math.floor(Math.random() * 50) + 1;
			self.data.pause   = Math.floor(Math.random() * 99) + 30;
			self.data.timeout  = Math.floor(Math.random() * 500) + 50;

			self.$el.parent.find('svg').each(function() {

				var offset  = Math.floor(Math.random() * 500) + 500;

				$(this)
					.find('path')
					// .attr('stroke-dashoffset', offset);

			});

			self.setParams();

		}, self.data.timeout);

	},

	setup : function($parent) {

		var self = this;

		// Cache the parent
		self.$el.parent = $parent;

		// Create the elements
		for (var i = 10 - 1; i >= 0; i--) {
			this.create(i);
		};

		// Add the loading SVG
		// $parent.prepend('<div class="tone">' + loadingTone + '</div>');

		this.setParams();
		this.loop();
		this.events();

		$(window).resize(function() {
			self.resize($(this));
		}).resize();

	},

	/**
	 * Start the animation
	 */
	start : function() {
		this.data.active = true;
		this.loop();
		this.$el.parent.show();
	},

	/**
	 * Stop the animation
	 */
	stop : function() {
		var self = this;
		setTimeout(function() {
			self.data.active = false;
			self.$el.parent.hide();
		}, 500);
	},

	/**
	 * Event bindings
	 */
	events : function() {

		var self = this;

		// Show
		Cargo.Event.on('project_load_start', function( pid ) {
			self.start();
		});

		// Hide
		Cargo.Event.on('project_load_complete', function( pid ) {
			self.stop();
		});

	}

};

/**
 * Start page
 */
function page_start() {

	deru.background.random('video');

	// Hover to show
	$('.start_title')
		.on('mouseenter', function() {
			$('body').addClass('start_hover');
		})
		.on('mouseleave', function() {
			$('body').removeClass('start_hover');
		});

	// Animate
	setTimeout(function() {
		$('body').addClass('start_animate');
	}, 100);

}

/**
 * 1979
 */

function page_1979() {
	deru.background.getImg('noise');
}

function page_1979_two() {
	deru.background.getImg('noise');
}

function page_1979_three() {
	deru.background.random('image');
}

function page_1979_four() {
	deru.background.random('image');
}

function page_confirmation() {
	deru.background.getImg('noise');
}

function page_shop() {
	deru.background.getImg('noise');
}

/**
 * History
 */

function page_history() {

	var tones = 9;

	// Rest
	deru.background.getImg('reset');

	$content = $('.nine_pure_tones');

	// Loop through the tones
	for (var i = tones - 1; i >= 0; i--) {
		var tone = puretones[i];
		$('<div class="tone" id="tone_' + i + '"/>')
			.prepend('<div class="tone_num">' + tone.num + '</div><div class="tone_title">' + tone.title + '</div><div class="tone_tag">' + tone.tag + '</div>')
			.append(tone.svg)
			.prependTo($content);
	};

	$('div[data-section]').each(function() {
		$("#history_nav").append('<div data-target="' + $(this).attr('data-section') + '" data-navsec="' + $(this).attr('data-section') + '"></div>');
	});

	$("#history_nav > div:first-child").addClass('active');

	/**
	 * Navigation clicks
	 */

	$('[data-target]').on('click', function() {
		var section = $(this).attr('data-target');
		$('html, body').stop().animate({
			scrollTop : $('div[data-section="' + section + '"]').offset().top
		}, 250);
	});

	// Jump nav
	$(window).on('scroll', history_scroll);

};

var history_scroll_timeout;
var history_active;
var history_ios_fix;

function history_scroll() {
	clearTimeout(history_scroll_timeout);
	history_scroll_timeout = setTimeout(function() {
		hisscrolly();
	}, 15);

	clearTimeout(history_ios_fix);
	history_ios_fix = setTimeout(function() {
		hisscrolly();
	}, 250);
};

function hisscrolly() {
	// Data
	var scrollTop = $(window).scrollTop();

	$('div[data-section]').each(function() {
		if ( ($(this).position().top + $(this).height() ) > $(window).scrollTop() ) {

			// active
			if ( $(this).attr('data-section') !== history_active ) {

				$('div[data-navsec]').removeClass('active');

				// Mark as active
				history_active = $(this).attr('data-section');
				$('div[data-navsec="' + history_active + '"]').addClass('active');

			}

			return false;
		}
	});
}

function page_history_two() {
	deru.background.random('video');
};

/**
 * Gallery
 */
function page_gallery() {
	deru.gallery.paginate($('.gallery_container'));
	deru.background.getImg('noise');
};

/**
 * Gallery
 */
function page_submit() {
	deru.submit.setup();
    $('div.textarea').replaceWith('<textarea placeholder="describe the significance of this memory"/>');
};

/**
 * Project load
 */
Cargo.Event.on('project_load_complete', function( pid ) {

	deru.page.setup();
	deru.page.extend();
	deru.navigation.active(pid);

	var resizeTimeout;

	$(window).resize(function() {
		clearTimeout(resizeTimeout);
		var resizeTimeout = setTimeout(function() {
			$('.centerthis').each(function() {
		    deru.centerThis($(this));
		  });
		}, 100);
	}).resize();

});

/**
 * Social shit
 */

deru.social = {

	timeout : null,

	setup : function() {

		$('body')
			.on('click', '.social_button', function(event) {
				$(this).parent().addClass('active');
				event.stopPropagation();
			})
			.on('mouseenter', '.social_options', function() {
				clearTimeout(deru.social.timeout);
			})
			.on('mouseleave', '.social_options', function() {
				clearTimeout(deru.social.timeout);
				deru.social.timeout = setTimeout(function() {
					$('.social_container').removeClass('active');
				}, 500);
			});


	}

};

deru.submit = {

	template : { },

	setup : function() {

		// alert('yo');
		deru.submit.template = Handlebars.compile( $("#submit-template").html() );
		var formattedResponse = deru.submit.template('nope');

		deru.background.getVideo('nope', 'http://assets.1979.la/video/WebLoopSubmissionCards_2.mp4');

		// Add it to the container
  		$('.entry .centerthis').append(formattedResponse);

  		$('body').on('click', '#link_section_2', function() {
  			$('#section_2').show();
  			$('.form-all').hide();
  			$('html, body').scrollTop(0);
  		});

  		// Nine pure tones hovers
  		$('.submit_tone')
  			.on('mouseenter', function() {
				$('body').addClass('submit_vid_active');
				submitTime = $(this).index() * 3;
				deru.background.loopTo(submitTime);
  			})
  			.on('mouseleave', function() {
  				clearTimeout(deruLoop);
  				bgvideo.getPlayer().off('progress');
  				$('body').removeClass('submit_vid_active');
  			})
  			.on('click', function() {
  				$('#cid_13').find('input').removeAttr('checked');
  				$('.submit_tone').removeClass('active');
  				$(this).addClass('active');
  				$('#cid_13').find('input[value="' + $(this).attr('data-value') + '"]').attr('checked', 'checked');
  			})
  			.each(function(){
  				$(this)
            .append('<div class="toneytitle"/>');

          $(this).find('.toneytitle')
            .append('<div class="bigone">' + $(this).attr('data-value') + '</div>')
            .append('<div class="smallone">' + $(this).attr('data-second') + '</div>');
  			});

  		// Change notification
  		$('#input_1').change(function() {
  			var src = $(this).val();
  				src = src.replace(/^.*[\\\/]/, '');
  			$('#select_file_name').text(src);
  		});

      $('.jotform-form').on('submit', function() {
        $('div[data-loading="page"].loading').show();
      });
        
        // shuffleHeadline();
        // setTimeout(shuffleHeadline,6000);

	}

};

// var phrases = [
// 	"Phases In Shift Belong Here.",
// 	"Polarize Your Context.",
// 	"Disperse Waves Abroad.",
// 	"Refract The Past Onto The Wall.",
// 	"Reflect And Renew.",
// 	"Reverberating Visions Claim Space.",
// 	"Harmony Needs A Partner.",
// 	"Vibrations In Space and History Remain.",
// 	"Resonate Through Aether Waves."
// ];
// var numPhrases = phrases.length;
// var phraseIndex = 0;

//  function shuffleHeadline(){
// 	var tPhrase = String(phrases[phraseIndex]);
//     $(".submit-sub > span").shuffleText(tPhrase, {
// 	    frames : 30,
// 	    maxSpeed : 2000,
// 	    amount : 4,
// 	    complete : function(){
// 	       //killAnim();
// 	       if(phraseIndex==numPhrases-1){
// 		       phraseIndex = 0;
// 	       } else{
// 		       phraseIndex++;
// 	       }
	       
// 	    }
//     });	        
// }
// function killAnim(){
//     clearInterval(headlineAnimInit);
// }

/**
 * Extended
 */

Object.size = function(obj) {
  var size = 0, key;
  for (key in obj) {
    if (obj.hasOwnProperty(key)) size++;
  }
  return size;
};



/**
 *  Typography
 */

WebFontConfig = {
  google: { families: [ 'Inconsolata:400,700:latin' ] }
};

(function() {
  var wf = document.createElement('script');
  wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
    '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
  wf.type = 'text/javascript';
  wf.async = 'true';
  var s = document.getElementsByTagName('script')[0];
  s.parentNode.insertBefore(wf, s);
})();

/**
 * Anthony Videos
 */
(function($) {

    $.deruHover = function(options) {

        var dh = {

            options: $.extend({
                'element' : null,
                'video'   : null,
            }, options),

            showVideo: function( ) {
                deru.background.getVideo('nope', dh.options.video);
            },

            hideVideo : function() {
            	 deru.background.hideVideo();
            }

        };

        // Bind
        $('body')
        	.on('mouseenter', dh.options.element, function() {
        		dh.showVideo();
        	})
        	.on('mouseleave', dh.options.element, function() {
        		dh.hideVideo();
        	});
        
    };
})(jQuery);