/**
 * Cassiopeia
 */

// preload
var img=new Image();
	img.src= "http://payload.cargocollective.com/1/0/2995/194087/MUNKSTERBATE_mini.gif";

var Design = {
	keybindings: function() {
		// Remove previous bindings
		Cargo.Core.KeyboardShortcut.Remove("Left");
		Cargo.Core.KeyboardShortcut.Remove("Right");

		Cargo.Core.KeyboardShortcut.Add("Left", 37, function() {
			Action.Project.Prev();
			return false;
		});

		Cargo.Core.KeyboardShortcut.Add("Right", 39, function() {
			Action.Project.Next();
			return false;
		});
	},

	resizeSlideshow: function(el, obj, state) {
		if (state == "resize") {
			el.find("> *").css({
				"-webkit-transition": "margin 0s ease",
				"-moz-transition": "margin 0s ease",
				"transition": "margin 0s ease"
			});
		} else {
			el.find("> *").css({
				"-webkit-transition": "margin " + obj.options.transition_duration + "s ease",
				"-moz-transition": "margin " + obj.options.transition_duration + "s ease",
				"transition": "margin " + obj.options.transition_duration + "s ease"
			});
		}

		// Resize and position the containing element
		obj.resizeContainer();
		Cargo.Plugins.elementResizer.refresh();
	},

	groupNavigation: function() {
		var navGroups = [],
			filterLinkContainer = $('.filter_links');

		$(".navigation div[data-type]").each(function() {
			var type = this.getAttribute("data-type");

			if ($.inArray(type, navGroups) == -1) {
				// first unwrap if already wrapped
				if ($(this).parent().hasClass("group")) {
					$(this).unwrap();
				}

				if (type == "link" || type == "page") {
					var items = $(".navigation div[data-type='link'], .navigation div[data-type='page']");
					navGroups.push("link", "page");
				} else {
					var items = $(".navigation div[data-type='" + type + "']");
					navGroups.push(type);
				}

				items.wrapAll("<span class='group' />");
			}

			// move filter links into their own container
			if(type === "link" && filterLinkContainer.length > 0) {

				var link = $(this).find('a');
				
				// only ignore the selects filter url
				if(link.length > 0 && link.attr('href').toLowerCase().indexOf('filter/') !== -1 && link.attr('href').toLowerCase().indexOf('filter/select') === -1) {
					filterLinkContainer.append(this);
				}

			}

			
		});
	},

	resizeLegacyImages: function(){

		function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {

			var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);

			return { width: Math.round(srcWidth*ratio), height: Math.round(srcHeight*ratio) };

		}

		Cargo.View.ProjectDetail.$el.find('img[width="670"]').each(function(){

			var srcParts = this.src.split('.');

			if(srcParts.length > 1) {
				srcParts[srcParts.length - 2] = srcParts[srcParts.length - 2] + '_o';

				var srcWidth = parseInt(this.getAttribute('width_o')),
					srcHeight = parseInt(this.getAttribute('height_o')),
					maxWidth = Math.min(srcWidth, 905),
					newDimensions = calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, 9e9);

				this.src = srcParts.join('.');
				this.width = newDimensions.width;
				this.height = newDimensions.height;
			}

		});

	},

	formatThumbnails: function() {
		 $(".thumbnail[data-formatted!='true']").each(function() {

			var imgSrc = $(this).find(".thumb_image img").attr("src");

			if (imgSrc == "/_gfx/thumb_custom.gif") {
				$(this).addClass("default_thumb");
			}

			$(this).find(".thumb_image img").attr('data-o-src', imgSrc);

			$(this).attr("data-formatted", "true");
		});
	},

	easterEgg: function(){

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

		$('.thumb_image img').each(function(){

			if( ! $(this).hasClass('munked')){
				//$(this).attr('src', 'http://media.gmunk.com/2011/MUNKSTERBATE_mini.gif').addClass('munked');
			}
		});

		$('.thumb_excerpt:not(.clone)').each(function(){

			$(this).parent().find('.thumb_excerpt.clone').remove();

			var clone = this.cloneNode(true);
			this.style.display = "none";
			this.parentNode.insertBefore(clone, this);

			$(clone).addClass('clone blacked-out');

			clone.style.display = "";

			$(clone).blast({
				delimiter: "word",
				stripHTMLTags: true,
				aria: false
			});

		});

		var audio_player = document.getElementById('audio_player');

		if(audio_player !== null) {

			audio_player.src = "http://media.gmunk.com/2011/audio/MUNKSTERBATE_0" + Math.round((Math.random() * 7) + 1) + "_audio.mp3";
			audio_player.volume = 0.5;
			audio_player.load();
			audio_player.play();

		}

	},

	unEasterEgg: function(){

		if(audio_player !== null) {

			audio_player.src = "";
			audio_player.pause();

		}

		$('body').removeClass('munked');

		$('.thumb_image img').each(function(){

			if($(this).hasClass('munked')){
				//$(this).attr('src', $(this).attr('data-o-src')).removeClass('munked');
			} 
		});

		$('.thumb_excerpt:not(.clone)').each(function(){
			$(this).parent().find('.thumb_excerpt.clone').remove();
		});
	},

	 mobileIcons: function() {
		if (navigator.userAgent.match(/i(Phone|Pod|Pad)|windows/gi)) {
			$(".goto.prev").text("▲");
			$(".goto.next").text("▼");
			$(".project_nav .previous").text("◀");
			$(".project_nav .next").text("◀");
		}
	}
};

/**
 * Events
 */

// overwrite the slideshow init method so we can fuck things up!!!
var initSlideshowMethod = Cargo.Core.Slideshow.InitSlideshow;

Cargo.Core.Slideshow.InitSlideshow = function(){

	// Resize images before the slideshow initializes
	Design.resizeLegacyImages();

	var slideshows = $(".slideshow").not('[data-slideshow-initialized]');

	initSlideshowMethod.apply(Cargo.Core.Slideshow, arguments);

	slideshows.each(function() {

		var container = $('.slideshow_container', this),
			slideshowObj = Cargo.Core.Slideshow.SlideshowObjects[this.getAttribute('data-id')];

		if(slideshowObj === undefined) {
			return;
		}

		$.each( slideshowObj.slides, function(i, $slide) {
			if ( $(this).is("img") ) {
				$(this).off("click");
			}
		});

		var next = $('<div class="slideshow-nav-overlay next" />'),
			prev = $('<div class="slideshow-nav-overlay prev" />');

		next.on('click', slideshowObj.setNext);
		prev.on('click', slideshowObj.setPrev);
		
		container.prepend(next);
		container.prepend(prev);
		

	});

}

$(function() {

	Design.mobileIcons();
	Design.keybindings();
	Design.formatThumbnails();

	if (Cargo.Helper.IsOnSet() && Cargo.Model.Project.GetType() != "page") {
		$(".show_index").show();
	}

	// divide the nav in groups
	Design.groupNavigation();

	var nav = $('.navigation'),
		right = $('.right', nav),
		left = $('.left', nav),
		resizeCallback = function(){
			left.width( (nav.width() - right.width()) - 20 );
		}

	$(window).resize(resizeCallback);
	Cargo.Event.on("project_load_complete", resizeCallback);
	resizeCallback();


	function strip_tags (input, allowed) {
		allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('');
		
		var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
			commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
		
		return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
			return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
		});
	}

	function html_substr( str, count ) {
		
		var div = document.createElement('div');
		div.innerHTML = str;
		
		walk( div, track );
		
		function track( el ) {
			if( count > 0 ) {
				var len = el.data.length;
				count -= len;
				if( count <= 0 ) {
					el.data = el.substringData( 0, el.data.length + count );
				}
			} else {
				el.data = '';
			}
		}
		
		function walk( el, fn ) {
			var node = el.firstChild, oldNode;
			do {
				if( node.nodeType === 3 ) {
					fn(node);
				} else if( node.nodeType === 1 ) {
					walk( node, fn );
				}
			} while( (node = node.nextSibling) && (count>0));
			//remove remaining nodes
			while(node){
				oldNode = node;
				node = node.nextSibling;
				el.removeChild(oldNode);
			}
			
		}
		return div.innerHTML;
	}

	Cargo.Collection.Projects.each(function(projectModel){
		console.log(projectModel);
	});

	Cargo.Collection.Projects.on('add', function(model){
		
		$('[name="' + model.get('id') + '"] .thumb_excerpt').html(
			html_substr(strip_tags(model.get('content'), '<a><span><font>'), 250) + '...'
		);

	});

});

Cargo.Event.on("element_resizer_init", function(plugin) {
	plugin.setOptions({
		adjustElementsToWindowHeight: Cargo.Model.DisplayOptions.attributes.image_scale_vertical
	});
});

Cargo.Event.on("slideshow_resize", function(el, obj) {
	Design.resizeSlideshow(el, obj, "resize");
});

Cargo.Event.on("slideshow_transition_start", function(el, obj) {
	Design.resizeSlideshow(el, obj);
});

Cargo.Event.on("fullscreen_destroy_hotkeys", function() {
	Design.keybindings();
});

Cargo.Event.on("project_collection_reset", function(){
	if(Design.currPID === 194087){
		Design.easterEgg();
	} else {
		Design.unEasterEgg();
	}
});	

Cargo.Event.on("show_index_complete", Design.unEasterEgg);

Cargo.Event.on("project_load_complete", function(pid) {

	Design.resizeLegacyImages();

	if(Cargo.Model.Project.get('type') === "page") {
		$('.site_header').insertBefore('.container');
	} else {
		$('.site_header').insertAfter('.container');
	}

	Design.currPID = pid;

	if(Design.currPID === 194087){
		Design.easterEgg();
	} else {
		Design.unEasterEgg();
	}

	Design.mobileIcons();

	var next,
		nodesInBetween;

	// remove crud from in between columns
	$('.project_content column').each(function(i, column){

		nodesInBetween = [];
		next = column;
		
		while((next = next.nextSibling) !== null) {
			
			nodesInBetween.push(next);

			if(next.nodeType === Node.ELEMENT_NODE && next.nodeName !== "BR") {
				break;
			}
		}

		if(next !== null && next.nodeName === "COLUMN"){
			for(i = 0; i < nodesInBetween.length - 1; i++){
				nodesInBetween[i].parentNode.removeChild(nodesInBetween[i]);
			}
		} else {
			nodesInBetween = null;
		}

	});

	if (Cargo.Model.Project.GetType() == "project") {
		if (!Cargo.Model.DisplayOptions.attributes.thumbs_below_projects || Cargo.Helper.IsOnSet()) {
			$(".show_index").show();
		}
	}
});

Cargo.Event.on("show_index_complete", function(pid) {
	if (Cargo.Plugins.hasOwnProperty("columnizer")) {
		Cargo.Plugins.columnizer.updateTargets();
	}

	$(".show_index").hide();
});

Cargo.Event.on("pagination_complete", function() {
	if (Cargo.Plugins.hasOwnProperty("columnizer")) {
		Cargo.Plugins.columnizer.updateTargets();
	}

	Design.formatThumbnails();
	Design.groupNavigation();
});

Cargo.Event.on("navigation_reset", function() {
	Design.groupNavigation();
});
