$(function(){	
	var MG = {
		
		params: '',
		uri: '',

		bindEvents:function(){
			$('input[type="text"]').live('blur', function(){
				if($(this).val() == '') $(this).val($(this).attr('alt'));
			});
			$('input[type="text"]').live('focus', function(){
				$(this).removeClass('error').val(($(this).val() == $(this).attr('alt') ? '' : $(this).val()));	
			});
			$('a').live('click', function(){
				if(($(this).attr('href')).match('http')){
					window.open($(this).attr('href'));
					return false;
				}
				if(($(this).attr('href')).match('mailto')){
					return true;
				}	
				MG.params = $(this).attr('alt');
				MG.processRequest($(this).attr('href'), MG.handleResponse);								
				return false;		
			});	
			$('a#about').unbind().click(function(){
				if($('#overlay:visible').length){
					$('#overlay').fadeOut(500, function(){
						var x = Math.abs(($('#content').css('top')).replace('px', ''));
						$('#content').css({top: 0}).removeClass('fixed');
						$(window).scrollTop(x);
						$('a#about').trigger('click');
					});
				}else{
					$('#overlay').find('#blog, #purchase, #typewriter').addClass('hidden');
					$('#overlay #blog').removeClass('hidden');
					window.setTimeout(function(){
						MG.resize();
					}, 10);
					$('#content').css({top: -$(window).scrollTop()}).addClass('fixed');								
					$('#overlay').fadeIn(500);
				}
				return false;
			});
			$(window).resize(function(){
				MG.resize();
			});
			$('#overlay').click(function(e){
				if($(e.target).attr('id') == $(this).attr('id')){
					$(this).fadeOut(500, function(){	
						var x = Math.abs(($('#content').css('top')).replace('px', ''));
						$('#content').css({top: 0}).removeClass('fixed');
						$(window).scrollTop(x);
						// Typewriter Clear All
						$('#overlay #typewriter #canvas').html('<div id="sample"></div><ol></ol>');
					});
				}
			});
			$('#header select').change(function(){
				if($(this).attr('id') == 'categories'){
					MG.processRequest($(this).val(), MG.handleResponse);					
				}else{
					if($(this).val() != '-'){
						var value = '^([0-9]+)-([^\-]+)-'+($(this).val()).replace(' ', '-')+'$';
						$('#content ol li').addClass('hidden').parent().find('li').filter(function(){
							return ($(this).attr('id')).match(new RegExp(value, 'i'));
						}).removeClass('hidden');						
					}else{
						/* Show All */
						$('#content ol li').removeClass('hidden');
					}
				}
			});
			$('.hover').live('click', function(){
				$(this).parent().find('a:first').trigger('click');
			});
			// Typewriter Events 
			$('#overlay #typewriter ol li a').click(function(){
				if($(this).html() == '<span>Clear All</span>'){
					if($('#sample:visible').length > 0){
						$('#sample').fadeOut(250, function(){
							$('#overlay #typewriter ol li a:eq(2)').trigger('click');
						});
					}else{
						$('#canvas ol li').fadeOut(250, function(){
							$(this).remove();
						});				
					}
				}else{
					if($(this).find('span').html() == 'Textsample'){
						$(this).parents('ol').find('a').eq(2).trigger('click');
						$('#overlay #typewriter form input').val('The quick brown fox jumps over the lazy dog. Victor jagt zw&ouml;lf Boxk&auml;mpfer quer &uuml;ber den gro&szlig;en Sylter Deich. Portez ce vieux whisky au juge blond qui fume. Quel fez sghembo copre davanti. Quizdeltagerne spiste jordb&aelig;r med fl&oslash;de, mens cirkusklovnen Walther spillede p&aring; xylofon. Flygande b&auml;ckasiner s&ouml;ka hwila p&aring; mjuka tuvor. K&aelig;mi n&yacute; &ouml;xi h&eacute;r ykist &thorn;j&oacute;fum n&uacute; b&aelig;&eth;i v&iacute;l og. Sexy qua lijf, doch bang voor&rsquo;t zwempak. V&aring;r s&aelig;re Zulu fra bade&oslash;ya spilte jo whist og quickstep i min taxi. El veloz murci&eacute;lago hind&uacute; com&iacute;a feliz cardillo y kiwi. La cig&uuml;e&ntilde;a tocaba el saxof&oacute;n detr&aacute;s del palenque de paja. &Agrave; noite, vov&ocirc; Kowalsky v&ecirc; o &iacute;m&atilde; cair no p&eacute; do ping&uuml;im queixoso e vov&oacute; p&otilde;e a&ccedil;&uacute;car no ch&aacute; de t&acirc;maras do jabuti feliz.');						
						$('#overlay #typewriter #canvas ol').prepend('<li><img src="'+MG.uri+'typewriter/'+$('#typewriter form').find('input').val()+'/'+$('select#typeface').val()+'-'+$('select#style').val()+'/16/" class="loading" /></li>');
						$('#overlay #typewriter form input').val('').trigger('blur');						
					}else{
						var name = '00_'+$(this).find('span').html()+'_'+Utility.uppercaseFirstLetter($('select#style').val())+'.png';
						$('#overlay #typewriter #canvas #sample').empty().append('<img src="'+MG.uri+'assets/purchase/typefaces/'+$('select#typeface').val()+'/'+name+'" />').fadeIn(250);											
					}
				}
				return false;
			});
			$('#overlay #typewriter select').change(function(){
				if($(this).attr('id') == 'typeface'){
					MG.processRequest(MG.uri+'purchase/typefaces/'+$(this).val()+'/', function(response){
						$('#overlay #typewriter select#style').empty();
						$.each(response.leaves, function(){
							$('#overlay #typewriter select#style').append('<option value="'+this.name+'">'+this.title+'</option>');
						});
						if($('#overlay #typewriter select#style').find('[value="regular"]').length > 0){
							$('#overlay #typewriter select#style').val('regular');
						}
						if(($('#overlay #typewriter #canvas ol li').length == 0) && ($('select#style').val())){
							$('#overlay #typewriter form').trigger('submit');	
						}
					});
				}
			}).parents('form').submit(function(){
				if($('#sample:visible').length > 0){
					$('#sample').fadeOut(250, function(){
						$('#overlay #typewriter form').trigger('submit');
					});
				}else{
					$('#overlay #typewriter #canvas ol').prepend('<li><img src="'+MG.uri+'typewriter/'+encodeURIComponent($(this).find('input').val())+'/'+$('select#typeface').val()+'-'+$('select#style').val()+'/'+$('select#size').val()+'/" class="loading"></li>');
				}
				return false;
			});
			// Newsletter
			$('form#newsletterSubscribeForm').live('submit', function(){
				$.post(MG.uri+'subscribe.php', $(this).serialize(), function(r){
					if(r.status == 'ok'){
						alert("Thanks for subscribing!");
					}else{						
						alert("This Address already exists!");
					}
				}, 'json');
				return false;
			});
			Purchase.bindEvents();
			return MG;
		},
		handleResponse:function(response){
			/* Send Location Hash to Google Analytics */
			var pageTracker = _gat._getTracker("UA-15937344-1");
			pageTracker._trackPageview(response.permalink);
			if((response.permalink).match('^(/purchase/(.+)/|/)$')){
				if($('#overlay:visible').length){
					$('#overlay').fadeOut(500, function(){
						var x = Math.abs(($('#content').css('top')).replace('px', ''));
						$('#content').css({top: 0}).removeClass('fixed');
						$(window).scrollTop(x);
						// Typewriter Clear All
						$('#overlay #typewriter #canvas').html('<div id="sample"></div><ol></ol>');
						MG.handleResponse(response);
					});
				}else{
					$('#content ol').empty();
					if(response.level > 2){
						$(response.images).each(function(i){
							if(!this.match('00_')){
								var src = this;
								$('#content ol').append('<li class="hidden" id="'+(src.substr(src.lastIndexOf('/')+1, src.lastIndexOf('.')-src.lastIndexOf('/')-1)).replace(/_/g,'-').toLowerCase()+'"><img src="" /></li><li class="eoi"></li>').find('img').load(function(){
									$(this).parent().fadeIn(500, function(){
										$(this).removeClass('hidden');
									});
								});			
								$('#content ol li.hidden:last img').attr('src', src);									
							}
						});	
						$('#header #information select').empty().append('<option value="-" selected="selected">Show All</option>');
						$(response.leaves).each(function(){
							$('#header #information select').append('<option value="'+this.name+'">'+this.title+'</option>');											
						});
						$('#overlay #blog ol').empty().append('<li class="entry"><div class="headline"><h3><span>About</span></h3></div><span>'+(response.description).replace(/([^>])\n/g, '$1<br />')+'</span><div><img src="'+MG.uri+'assets/'+response.permalink+'00_About.png" class="noresize"/></div></li><li class="eoi"></li>')
						$('#overlay #blog').removeClass('hidden');
						$('#information').find('ul a').attr('alt', response.name);
						if(response.permalink.match('/typefaces/')){
							$('#information').find('ul li:eq(1)').removeClass('hidden');
							$('#information').find('#filter').removeClass('hidden');
						}else{
							$('#information').find('ul li:eq(1)').addClass('hidden');							
							$('#information').find('#filter').addClass('hidden');
						}
						$('#information').removeClass('hidden').find('h3 span').html(Utility.uppercaseFirstLetter(response.name)).parents('.headline:first').find('h2 span').html(((response.permalink).match('product') ? 'Product' : 'Typeface')).parents('#information:first').animate({left: 35}, 500, function(){
							$(this).data('hidden', false);
						});
						
					}else{
						$(response.children).each(function(i,o){
							$('#content ol').append('<li class="hidden loading"><a href="'+(o.attributes.permalink)+'"></a><img src="" /><div class="hover"></div></li><li class="eoi"></li>').find('img:last').load(function(){
								$(this).parent().fadeIn(500, function(){
									$(this).removeClass('hidden').removeClass('loading');
									$(this).find('.hover:last').width(($(this).find('img').width()-2)).height(($(this).find('img').height()-2));
									if($('#content ol li.loading').length == 0){
										MG.resize();
									}
								});
							});	
							$('#content ol li.hidden:last img').attr('src', MG.uri+'assets'+o.attributes.permalink+'00_Teaser.png');		
						});
						$('#information').animate({left: -170}, 500, function(){
							$(this).data('hidden', true).addClass('hidden');
						});	
					}
				}
			}else{
				if(!$('#overlay:visible').length){
					$('#overlay').find('#blog, #purchase, #typewriter').addClass('hidden');
					if(response.name != 'purchase'){
						if(response.leaves.length > 0){
							$('#overlay #blog ol').empty();
							$(response.leaves).each(function(){
								var name = this.name;
								$('#overlay #blog ol').append('<li class="entry" id="entry-'+this.id+'"><div class="headline"><h3><span>'+this.title+'</span></h3></div><span>'+(this.text).replace(/([^>])\n/g, '$1<br />')+'</span><img src="" class="hidden" /></li><li class="eoi"></li>');
								if(response.images){
									$(response.images).each(function(){
										var f = this.substring(this.lastIndexOf('/')+1, this.lastIndexOf('.'));
										$('#overlay #blog ol li#entry-'+f+' img:last').attr('src', this).removeClass('hidden');														
									});
								}
								if(name == 'newsletter'){
									$('#blog ol li.entry:last').append('<form action="" id="newsletterSubscribeForm"><input type="text" id="email" name="email" alt="Your E-Mail Address" value="Your E-Mail Address" /><button type="submit"><span>&#x2714;</span></button></form>');
								}
							});
						}
						window.setTimeout(function(){
							MG.resize();
						}, 10);
						if(MG.params){
							$('#overlay #typewriter select#typeface').val(MG.params).trigger('change');	
						}else{
							$('#overlay #typewriter select#typeface').val('maison').trigger('change');	
							$('#overlay #typewriter select#style').val('Regular').trigger('change');	
						}
					}else{
						if(MG.params) $('.'+MG.params).find('a:first').trigger({force: 'open', type: 'click'});
						MG.resize();
					}
					$('#content').css({top: -$(window).scrollTop()}).addClass('fixed');
					$('#overlay').find('.'+response.name).removeClass('hidden').parent().parent().fadeIn(500);		
					MG.resize();		
				}else{					
					$('#overlay').fadeOut(500, function(){
						var x = Math.abs(($('#content').css('top')).replace('px', ''));
						$('#content').css({top: 0}).removeClass('fixed');
						$(window).scrollTop(x);
						$('#overlay #typewriter #canvas').html('<div id="sample"></div><ol></ol>');
						MG.handleResponse(response);
					});
				}	
			}
			return true;
		},
		location:function(){
			return (window.location.hash).replace('#', '');
		},
		processRequest:function(request, responseHandler){
			jQuery.getJSON(request, {}, function(response){
				if(responseHandler(response)){
					window.location.hash = request;					
				}
			});	
			return true;
		},
		resize:function(){
			$('#overlay').find('.content').width($(window).width()-180);
			
			var x = Math.floor(($(window).width()- 195) / 325);
			$('#blog').find('li.eoi').removeClass('clear').filter(function(i){
				return (i == $('#blog li.entry').length-1) || (((i+1)%x == 0) && (i > 0)) || (x == 1);
			}).addClass('clear');
			/* Products */
			var r = 0;
			$('#content').find('ol > li.eoi').removeClass('clear');
			$('#content').find('ol > li:not(.eoi)').each(function(i){
				r = r + $(this).width()+15;				
				if(r > ($('#content ol').width()-50)){
					r = $(this).width()+15;
					$('#content .eoi').eq(i-1).addClass('clear');
				}
			});
			$('#overlay').height(($('#overlay .content').height() > $(window).height() ? ($('#overlay .content').height()+85) : $(window).height()));
		}
	}
	
	var Utility = {
		uppercaseFirstLetter:function(s){
			return (s.replace('-', ' ') + '').replace(/^(.)|\s(.)/g, function ($1) {
				return $1.toUpperCase();
			}).replace('- ', '-');
		}
	}
	
	var Purchase = {
		bindEvents:function(){
			$('#purchaseForm').submit(function(){
				if($(this).find('#terms-of-licensing').attr('checked')){
					var form = $(this);
					$.post(MG.uri, $(this).serialize(), function(r){
						if(r.status == 'ok'){
							if(r.redirect != ''){
								window.location.href = r.redirect;								
							}else{
								alert("Thank you for ordering!");
							}
						}else{
							$.each(r.error, function(property, error){
								if($('#purchaseForm #'+property).length){
									$('#purchaseForm #'+property).addClass('error');
								}
							});
						}
						$(form).find('button').removeAttr('disabled').removeClass('disabled');
					}, 'json');
					$(form).find('button').attr('disabled', true).addClass('disabled');					
				}else{
					alert("Please agree with our Terms of Licensing!");
				}
				return false;
			});
			$('#purchase a').click(function(e){
				if(($(this).attr('href')).match('http')){
					window.open($(this).attr('href'));
					return false;
				}
				if($(this).html() == 'User Licenses'){
					alert("A MilieuGrotesque Single-User License permits the installation of our fonts on up to three computers - within one company or institutional entity and at a single location. Should you wish to install or use our font(s) on more than three computers or if you would like to make it available to more than three users via a local network in an in-house font library, please purchase a corresponding Multi-User License. If you require more than 25 licenses of any particular font, please contact us via e-mail. Please also read our EULA for more detailed information.");
					return false;
				}
				$(this).parent().find('.inner').toggleClass('hidden');
				if((e.force == 'open') && $(this).parent().find('.inner').hasClass('hidden')){
					$(this).trigger('click');
				}
				MG.resize();	
				return false;
			});
			$('#purchase ol input').click(function(){
				if($(this).attr('checked')){
					$(this).parent().parent().find('ol li input[type="checkbox"]').attr('checked', true).not(this).trigger('change');
				}else{
					$(this).parent().parent().find('ol li input[type="checkbox"]').removeAttr('checked').not(this).trigger('change');
				}
			}).change(function(){
				if(!$(this).hasClass('collection')){
					$('.collection').each(function(){
						var all = $(this).parent().parent().find('input[type="checkbox"]').not('.collection').length;
						var checked = $(this).parent().parent().find('input[type="checkbox"]:checked').not('.collection').length;
						if((checked == all) && (all > 0)){
							$(this).attr('checked', true);
						}else{
							$(this).removeAttr('checked');
						}
					});					
				}
				var total = Purchase.calculatePrice();
				$('#total-price .price').html(total+'.&ndash; CHF');
				$('#total-price input').val(total);
			});
			$('#purchase select').unbind().change(function(){
				$(this).parents('.top').find('.q').html($(this).hasClass('shipping') ? 10 : $(this).val());
				$(this).parents('.top').find('.x').val($(this).hasClass('shipping') ? 1 : $(this).val());
				
				var total = Purchase.calculatePrice();
				$('#total-price .price').html(total+'.&ndash; CHF');
				$('#total-price input').val(total);
				
			});
			$('.shipping').change(function(){
				$(this).parents('form:first').find('.shipping').val($(this).val()).parents('form:first').find('#shipping').val($(this).val());
				var total = Purchase.calculatePrice();
				$('#total-price .price').html(total+'.&ndash; CHF');
				$('#total-price input').val(total);
			});
			$('#purchase ol li a').not('.exception').trigger('click');
		},
		calculatePrice:function(){
			var price = 0;
			$('.p').html(0);
			$('.priced').removeClass('priced');
			$('#purchase input.collection:checked').each(function(){
				if(!$(this).hasClass('priced')){
					var q = ($(this).parents('.top').find('.q').html() / 10);
					var p = parseFloat($(this).parent().find('.price').attr('alt'));
					$(this).parent().parent().find('input[type="checkbox"]').addClass('priced');					
					$(this).parents('.top').find('.p').html((parseFloat($(this).parents('.top').find('.p').html()) + p));
				}
			});
			$('#purchase input[type="checkbox"]:checked').not('.priced').each(function(){
				var p = parseFloat($(this).parent().find('.price').attr('alt'));
				$(this).parents('.top').find('.p').html((parseFloat($(this).parents('.top').find('.p').html()) + p));
			});
			$('.p').each(function(){
				price = price + parseFloat($(this).html()) * parseFloat($(this).parent().find('.q').html() / 10);
			});
			$('.shipping').each(function(){
				if($(this).parents('li:first').find('input[type="checkbox"]:checked').length > 0){
					price = price + parseFloat($(this).val());
				}
			});
			return Math.round(price*100)/100;
		}
	}
	/* Load Settings */
	$('meta[name^="milieugrotesque."]').each(function(){
		MG.uri = $(this).attr('content');
	});
	/* Set Location Hash */
	if(MG.location() == ''){
		window.location.hash = MG.uri;
	}
	MG.bindEvents().processRequest(MG.location(), function(response){
		$('#header').animate({left: '0px'}, 500, function(){
			MG.handleResponse(response);			
		});
	});
});