/* Author: Nate VanderEnde
   For: Outside Line
*/

// Check if we can use the History API
var historyAPI = false;
	if (typeof history.pushState === "function") historyAPI = true;

// Set an isMobile var and update when the browser is resized so we can determine how to animate later
var siteURL = $('body').data('site-url'),
	threshold = 768,
	isMobile = true,
	contentScroll = false,
	panelScroll = false,
	windowWidth = window.innerWidth;

	// IE doesn't support window.innerWidth properly, so: 
	if (windowWidth == undefined) {
		windowWidth = document.documentElement.clientWidth;
	};
	
	if(windowWidth >= threshold) {
		isMobile = false;
		positionHeaders();
		initPanelScroll();
	}
	
	$(window).resize(function() {

		newWidth = window.innerWidth;

		if (newWidth == undefined) {
		newWidth = document.documentElement.clientWidth;
		};
		if(windowWidth >= threshold) {
			// changed from desktop...
			if(newWidth >= threshold) {
				// to desktop
				windowWidth = newWidth;
				positionHeaders();
			} else {
				// to mobile
				windowWidth = newWidth;
				isMobile = true;
				resetDrawers();
				initPanelScroll();
				var overlay = document.getElementById('overlay');
				overlay.parentNode.removeChild(overlay);
			}
		} else {
			// changed from mobile...
			if(newWidth >= threshold) {
				// to desktop
				windowWidth = newWidth;
				isMobile = false;
				resetDrawers();
				positionHeaders();
				initPanelScroll();
			} else {
				// to mobile
				windowWidth = newWidth;
			}
		}

		toggleRainbowLink();

	});	
	
// On document ready	

$(document).ready(function(){

	// Close overlay
	$('#instructions').live('click', function(){ $(this).fadeOut(150, function(){ $(this).remove(); }); });
	$('#overlay a.close').live('click', function(){ $('#overlay').fadeOut(150, function(){ $(this).remove(); }); });
	$('#overlay').live('click', function(e){
		if(e.target == this) $('#overlay').fadeOut(150, function(){ $(this).remove(); return false; });
	});

	toggleRainbowLink();

	// External links in new window
	$("a").each(function(){
		if (this.href.indexOf(location.hostname) == -1) { $(this).attr('target', '_blank'); } 
	});
	
	// Open active drawer
	if($('.box.active').length > 0) { setTimeout(function(){ openDrawer($('.box.active')) }, 400); }
	
	/*
	// Shrink logo panel on scroll
	$('.content-wrap').scroll(function(){
		var position = $(this).scrollLeft()/2,
			maxAdjust = 40,
			base = -212,
			$banner = $('#banner'),
			$logo = $('#logo');
		if(position <= maxAdjust) {
			$logo.css({ marginLeft:(base-position), marginRight:(base-position) });
		} else if(position > maxAdjust) {
			$logo.css({ marginLeft:(base-maxAdjust), marginRight:(base-maxAdjust) });
		}
	});
	*/
	
	// Header Drop Downs
	$('header nav.links a.handle').click(function(){
		var $allHandles = $('header nav.links a.handle'),
			$handle = $(this),
			$allDrawers = $('header nav.drop-down'),
			$drawer = $(this).siblings('nav.drop-down');
		console.log($drawer);
		if($drawer.is(':visible')) {
			$allDrawers.hide();
			$allHandles.removeClass('active');
		} else {
			$allDrawers.hide();
			$allHandles.removeClass('active');
			$drawer.show();
			$handle.addClass('active');
		}
		return false;
	});
	
	// Nice form inputs
	$('input[type=text]').focus(function(){
		var value = $(this).val(),
			placeholder = $(this).attr('placeholder'),
			$input = $(this);
		if(value == placeholder) {
			$input.val('');
		}
	}).blur(function(){
		var value = $(this).val(),
			placeholder = $(this).attr('placeholder'),
			$input = $(this);
		if(value == '') {
			$input.val(placeholder).removeClass('complete');
		} else {
			$input.addClass('complete');
		}
	});
	
	// Sign-up ajax
	$('form.subscribe').submit(function(){
		var $form = $(this)
			action = $form.attr('action'),
			request = $form.serialize(),
			$popup = $(document.createElement('div')).addClass('popup');
		$.post(action, request, function(data){
			$form.children().css({opacity:0});
			$popup.html(data.message).appendTo($form);
			setTimeout(function(){
				$form.children().css({opacity:1});
				$popup.remove();
			}, 4000);
		}, 'json');
		return false;
	});
	
	// Expanding Drawers & History State
	$('.box:not(.disabled) .handle').live('click', function() {
		
		var permalink = $(this).find('a.permalink').attr('href');

		if(historyAPI) {
			history.pushState('', '', permalink);
			setState($(this));
		} else {
			window.location = permalink;
		}
		return false;
		
	});
	$('.box:not(.disabled) .handle a.permalink').live('click', function(){
		
		var permalink = $(this).attr('href');
		if(historyAPI) {
			history.pushState('', '', permalink);
			setState($(this).parents('.handle'));
		} else {
			window.location = permalink;
		}
		return false;
		
	});
	$('.box .drawer a.close').live('click', function(){
		
		var permalink = $(this).attr('href');
		if(historyAPI) {
			history.pushState('', '', permalink);
			$('title').html('Lurpak');
			var $parent = $(this).parents('.box'),
				$handle = $parent.find('.handle'),
				$drawer = $parent.find('.drawer')
				speed = 300;
			$drawer.animate({ width:'0px' }, speed, function(){
	    		$(this).empty();
	    	});
			//$handle.animate({ width:'78px' }, speed);
			$parent.animate({ marginRight:'1px' }, speed).removeClass('active');
		} else {
			window.location = permalink;
		}
		return false;
	});
	
	// YouTube videos loaded in only on-click
	$('div.yt-thumb').live('click', function(){
		var $thumbnail = $(this),
			$parent = $thumbnail.parent('.video'),
			videoID = $parent.data('video-ID');
		$thumbnail.remove();
		$parent.html("<iframe width='100%' height='100%' src='http://www.youtube.com/embed/"+videoID+"?autohide=1&modestbranding=1&origin="+siteURL.replace('http://', '')+"&rel=0&showinfo=0&autoplay=1' frameborder='0' allowfullscreen></iframe>");
	});
	
	// Social articles clickable
	$('.social article, .related article').live('click', function(){
		var destination = $(this).find('a.permalink').attr('href');
		console.log(destination);
		if(destination) {
			window.open(destination);
			return false;
		}
	});
	
});

function toggleRainbowLink(){

	if ($('html').hasClass('oldie')) {

		if (document.documentElement.clientHeight < 640) {
		$('#rainbow-link').addClass('hidden');
		} else if (document.documentElement.clientHeight > 640 && $('#rainbow-link').hasClass('hidden')) {
			$('#rainbow-link').removeClass('hidden');	
		} else if (document.documentElement.clientHeight < 720) {
			$('#rainbow-link').addClass('static');
		} else if (document.documentElement.clientHeight > 720 && $('#rainbow-link').hasClass('static')) {
			$('#rainbow-link').removeClass('static');	
		};
	};	
}

function setState($handle) {

	var $parent = $handle.parent('.box'),
	    $activeParent = $('article.box.active'),
	    $handle = $handle,
	    $activeHandle = $activeParent.find('.handle'),
	    $drawer = $handle.siblings('.drawer'),
	    $activeDrawer = $activeParent.find('.drawer'),
	    speed = 300,
	    permalink = $handle.find('a.permalink').attr('href');
	
	$('title').html('Week of the ' + $handle.find('h1 span').html() + ' &mdash; Lurpak');    
		    
	if(isMobile) {
	    if($parent.hasClass('active')) {
	    	// Just close all drawers
	    	$activeDrawer.find('iframe').remove();
	    	$activeDrawer.slideUp(speed, function(){
	    		$(this).empty();
	    	});
	    	$activeParent.removeClass('active');
	    } else {
	    	// Close all drawers and open a new one
	    	if($activeDrawer.length > 0) {
	    		$activeDrawer.find('iframe').remove();
	    		$activeDrawer.slideUp(speed, function(){
	    			$(this).empty();
	    			$('<div/>').load(permalink + ' .box.active .drawer', function(){
	    				var $newContent = $(this).find('.drawer').children();
	    				$drawer.append($newContent);
	    				setTimeout(function(){
	    					$drawer.slideDown(speed);
	    					$parent.addClass('active');
	    				}, speed/3);
	    			});
	    		});
	    		$activeParent.removeClass('active');
	    	} else {
	    		$('<div/>').load(permalink + ' .box.active .drawer', function(){
	    			var $newContent = $(this).find('.drawer').children();
	    		    $drawer.append($newContent);
	    		    setTimeout(function(){
	    		    	$drawer.slideDown(speed);
	    		    	$parent.addClass('active');
	    		    }, speed/3);
	    		});
	    	}
	    }
	} else {
	    if($parent.hasClass('active')) {
	    	// Just close all drawers
	    	$activeDrawer.find('iframe').remove();
	    	$activeDrawer.animate({ width:'0px' }, speed, function(){
	    		$(this).empty();
	    	});
	    	//$activeHandle.animate({ width:'78px' }, speed);
	    	$activeParent.animate({ marginRight:'1px' }, speed).removeClass('active');
	    } else {
	    	// Close all drawers and open a new one
	    	if($activeDrawer.length > 0) {
	    		$activeDrawer.find('iframe').remove();
	    		$activeDrawer.animate({ width:'0px' }, speed, function(){
	    			$(this).empty();
	    			$('<div/>').delay(speed).load(permalink + ' article.active', function(){
	    				var $newContent = $(this).find('.drawer').children();
	    				$drawer.append($newContent);
	    				initPanelScroll();
	    				setTimeout(function(){
	    					$drawer.animate({ width:'320px' }, speed);
	    					//$handle.animate({ width:'10px' }, speed);
	    					$parent.animate({ marginRight:'0px' }, speed).addClass('active');
	    				}, speed/3);
	    			});
	    		});
	    		//$activeHandle.animate({ width:'78px' }, speed);
	    		$activeParent.animate({ marginRight:'1px' }, speed).removeClass('active');
	    	} else {
	    		$('<div/>').delay(speed).load(permalink + ' article.active', function(){
	    			var $newContent = $(this).find('.drawer').children();
	    		    $drawer.append($newContent);
	    		    initPanelScroll();
	    		    setTimeout(function(){
	    		    	$drawer.animate({ width:'320px' }, speed);
	    		    	//$handle.animate({ width:'10px' }, speed);
	    		    	$parent.animate({ marginRight:'0px' }, speed).addClass('active');
	    		    }, speed/3);
	    		});
	    	}
	    }
	}
}

function toggleRainbowLink(){

	if ($('html').hasClass('oldie')) {

		if (document.documentElement.clientHeight < 640) {
		$('#rainbow-link').addClass('hidden');
		} else if (document.documentElement.clientHeight > 640 && $('#rainbow-link').hasClass('hidden')) {
			$('#rainbow-link').removeClass('hidden');	
		} else if (document.documentElement.clientHeight < 720) {
			$('#rainbow-link').addClass('static');
		} else if (document.documentElement.clientHeight > 720 && $('#rainbow-link').hasClass('static')) {
			$('#rainbow-link').removeClass('static');	
		};
	};	
}

function openDrawer($parent) {

	var $handle = $parent.find('.handle'),
	    $drawer = $parent.find('.drawer'),
	    speed = 200;
			    
	if(isMobile) {
	    $drawer.slideDown(speed);
	} else {
	    $drawer.animate({ width:'320px' }, speed);
	    //$handle.animate({ width:'10px' }, speed);
	    $parent.animate({ marginRight:'0px' }, speed, function(){
	    	setTimeout(function(){
	    		contentScroll.scrollToElement($parent, false, true);
	    	}, speed*2);
	    });
	}
}

function toggleBanner() {
	var $banner = $('#banner'),
		$logo = $('#logo');
	if($banner.hasClass('open')) {
		$banner.animate({ width:'0px', marginRight:'0px' }, 400).removeClass('open');
		$logo.animate({ marginLeft:'-252px', marginRight:'-252px' }, 400);
	} else {
		$banner.animate({ width:'316px', marginRight:'1px' }, 400).addClass('open');
		$logo.animate({ marginLeft:'-212px', marginRight:'-212px' }, 400);
	}
	return true;
}

function positionHeaders() {
	var $allHeaders = $('.box .handle h1'),
		padding = 18,
		leftPadding = 70,
		width = window.innerHeight,
		height = 78,
		bottom = (width-height)/2,
		right = -1*bottom;

		if (width == undefined) {
			width =  document.documentElement.clientHeight;
		};

	$allHeaders.css({
		width:(width-leftPadding-padding),
		height:(height-(padding*2)),
		padding:padding,
		paddingLeft:leftPadding,
		right:right,
		bottom:bottom
	});
	//$('#banner').css({ height:width });
}

function resetDrawers() {

	var $allHandles = $('.box .handle'),
		$allHeaders = $('.box .handle h1'),
		$allDrawers = $('.box .drawer'),
		$allParents = $('article.box');
	
	if(isMobile) {
		$allHandles.attr('style', '');
		$allHeaders.attr('style', '');
		$allDrawers.attr('style', '');
		$allParents.attr('style', '').removeClass('active');
	} else {
		$allHandles.css({ width:'78px' });
		$allDrawers.css({ width:'0px', display:'block' });
		$allParents.css({ marginRight:'1px' }).removeClass('active');
	}
}

function initPanelScroll() {
	
	if(contentScroll) {
		contentScroll.destroy();
	}
	
	contentScroll = false;
	
	if(panelScroll) {
		panelScroll.destroy();
	}
	
	panelScroll = false;
		
	if(!isMobile) {
		contentScroll = $('div.content-wrap').jScrollPane({
			autoReinitialise: true,
			hideFocus: true,
			stickToRight: false
		}).data('jsp');
		
		panelScroll = $('.box .drawer .articles').jScrollPane({
			autoReinitialise: true,
			hideFocus: true,
			contentWidth: 320,
			verticalDragMaxHeight: 200,
			verticalDragMinHeight: 30,
			verticalGutter: -6
		}).data('jsp');
	}
}


