var modal = { //Global vars
	speed:500,
	selector: '#modal_wrapper',
	close: '.close',
	inner: '#modal_inner'
}
var url = {
	imgs: 'http://www.unsigneddesign.com/pattern/',
	cdn: 'http://kneedeepincode.com/cdn/patternfall/',
	suffix: 'pattern'
}

function windowCenter(x){ //the center of the screen. Used for the loader
	if(x=='y'){
		return $(window).height()/2+'px';
	}
	else{
		return $(window).width()/2+'px';
	}
}

function centerThis(selector){ //Will center the selector in the dead center of the screen. Used for the modal
	var x_center = ($(window).width()/2-$(selector).width()/2)+'px';
	var y_center = ($(window).height()/2-$(selector).height()/2)+'px';
	$(selector).css({left:x_center,top:y_center});
	$(window).resize(function(){
		centerThis(selector);
	})
}

$(function() {
	$('body').addClass('home_page');
	var download_btn = '.download_btn';
	$('body')
	//modal HTML
	.prepend('\
		<div id="modal_wrapper">\
			<div id="modal_top">\
				<a title="Close" class="close" href="#">\
					<img src="http://kneedeepincode.com/cdn/patternfall/images/close_x.png" alt="Close" />\
				</a>\
			</div>\
			<div id="modal_inner"></div>\
			<div id="modal_bottom"></div>\
		</div>\
	')
	//Adds the hide/show cardboard button, loader gif, and preloads the download modal box
	.append('\
		<a id="hide_cardboard">Hide Cardboard</a>\
		<div class="loader"></div>\
		<img src="'+url.cdn+'images/modal_box.png" style="display:none" />\
	')
	.css({
		margin:'0',
		padding:'0',
		background: 'url('+url.cdn+'loader.gif) no-repeat center '+windowCenter('y')+' #fff'
	});
	
	/* Start cardboard hide/show script */
	function cardboard_animation(selector,the_text){
		$(selector).animate({bottom:'-='+($(selector).height()+100)+'px'},300,'easeInBack',function(){
			$(selector).text(the_text).animate({bottom:'20px'},250);
		});
	}
	
	$('#hide_cardboard').toggle(
		function(){
			$('#header').animate({top:'-='+($('#header').height())+'px'});
			$('#ad_sidebar').animate({right:'-='+($('#ad_sidebar').width()-75)+'px'});
			cardboard_animation($(this),'Show Cardboard');
			return false;
		},
		function(){
			$('#header').animate({top:'0px'});
			$('#ad_sidebar').animate({right:'0px'});
			cardboard_animation($(this),'Hide Cardboard');
			return false;
		}
	);
	/* ...end... */
	/* Generate Sidebar Height */
	function ad_sidebar_height(){
		$('#ad_sidebar').css('height',$(window).height()+20+'px');
	}
	ad_sidebar_height();
	$(window).resize(function(){
		ad_sidebar_height();
	});
	/* ...end... */
	
	/* Add Patterns */
    var container = $('#wrapper');
    x = 100;
    y = 1;
    n = 100;
    function addPatterns() {
        for (i = y; i <= x; i++) {
				if(!$('body').hasClass('nomore')){
					$(container).append('<a href="' + url.imgs + i + '.jpg"><img src="' + url.imgs + i + 's.jpg" class="pattern" alt="pattern'+i+'" /></a>');
					$('img[alt=pattern'+i+']').error(function(){
						$(this).addClass('error');
						$('body').attr('class','nomore');
					});
				}
			}
        y = x + 1;
        x = x + n;
			$(window).load(function(){
				$('#the_patterns').fadeIn(function(){
					if(window.location.hash.indexOf(url.suffix) >= 0){
						change_location();
					}
				});
			});
    }

	addPatterns();
	make_patterns_clickable();
    $(window).scroll(function() {
		if(!$('body').hasClass('nomore')){
			if ($(window).scrollTop() == $('html').height() - $(window).height()) {
 					addPatterns();
					make_patterns_clickable();
			}
		}
    });
	/* ...end... */
	/*
	setInterval(check_broken, 1000);
	function check_broken(){

	}
	*/
	/* Modal Start */
   $(modal.close).click(function() {
		current_content = $(modal.inner).html();
		if(!$('body').hasClass('noback')){
			$('body').addClass('home_page');
			$('#the_patterns').fadeTo(1,1);
			$('#the_patterns').fadeOut(0);
				$(modal.selector).fadeOut(modal.speed,function(){
					$('#the_patterns').fadeIn(function() {
					    $('body').css({
					        background: 'url('+url.cdn+'loader.gif) no-repeat center '+windowCenter('y')+' #fff',
					        height: 'auto'
					    });
					});
				});
			return false;
		}
		else if($('body').hasClass('home_page')){
			$(modal.selector).fadeOut(modal.speed);
		}
		else{
			$('body').removeClass('noback');
			$(modal.inner).empty().append('<a title="Download" href="'+url.cdn+'download.php?src='+url.imgs+get_pattern_id()+'.jpg" class="download_btn"><img src="http://kneedeepincode.com/cdn/patternfall/images/download.png" alt="Download" /></a>');
			centerThis(modal.selector);
			return false;
		}
	});

	$('.modal a').click(function(){ //Add content from on the page hidden
		$('body').addClass('noback');
		the_content = $(this).attr('href');
		$(modal.inner).empty().append($(the_content).html()).parent().fadeIn(modal.speed);
		centerThis(modal.selector);
		return false;
	});
	/* ...end... */
	
	/* URL code */
	function get_pattern_id(selector){
		if(selector){
			return $(selector).parent().attr('href').split('/')[4].split('.')[0];
		}
		else{
			return window.location.hash.split('/')[1];
		}
	}
	function url_rewrite(selector){
		window.location.hash = url.suffix+'/'+get_pattern_id(selector);
	}
	function change_location(){
		if(window.location.hash.indexOf(url.suffix) >= 0){
			$('img[src='+url.imgs+get_pattern_id()+'s.jpg]').click();
		}
		else if(window.location.hash.indexOf('home') >= 0) {
			$(modal.close).click();
		}
		else{
			$(modal.close).click();
		}
	}
	setInterval(location_check, 1000);
	var last_url = "";
	function location_check() {
		if (window.location.hash==last_url) {
			return;
		}
			last_url = window.location.hash;
			change_location();
   }
	/* ...end... */

	/* Everytime you click on a pattern */
	function make_patterns_clickable(){
	    $('.pattern').click(function() {
			$('body').removeClass('home_page');
			$('.loader').css({top:windowCenter('y'),left:windowCenter('x')}).fadeIn(250);
			$('.the_load_img').remove();
	        var the_background = $(this).parent().attr('href');
	        $('body').css({
	            background: 'url(' + the_background + ')',
	            height: $('body').height()+'px'
	        });
			
				$('#the_patterns').fadeTo(250,0.5);
				$('body').append('<img src="'+the_background+'" class="the_load_img">');
				$('.the_load_img').load(function(){
					$('#the_patterns').fadeOut(function(){
						$('.loader').css({display:'none'});
						centerThis(modal.selector);
						$(modal.selector).fadeIn(modal.speed);
					});
				});
				$(modal.inner).empty().append('<a title="Download" href="#download" class="download_btn"><img src="http://kneedeepincode.com/cdn/patternfall/images/download.png" alt="Download" /></a>');
				$(download_btn).attr('href',url.cdn+'download.php?src='+the_background);
				url_rewrite($(this));
			return false;
	    });
	}
	/* ...end... */
});