/**
 * Luma JS library
 * 
 * @author	Devin Smith <devins@luma-pictures.com>
 * @date	2009.09.18
 *
 * This library was written exclusively for luma-pictures.com
 *
 */

if (typeof(console) == 'undefined') {
	console = {
		log: function() { return null; }
	};
}
var historyUnsuported = false;
if (typeof(history.pushState) == 'undefined') {
	history.pushState = function() { return null; }
	history.replaceState = function() { return null; }
	historyUnsuported = true;
}



var app = {
	els: {},
	toTop: function() {
		$('html, body').animate( { scrollTop: 0 }, 200 );
	},
	toBottom: function() {
		$('html, body').animate( { scrollTop: $($('.wrapper').get(0)).height() }, 200 );
	},
	/*
	cookie: {
		set: function(name,value) {
			var exdate = new Date();
			exdate.setDate(exdate.getDate() + 180);
			document.cookie = name + '=' + escape(value) + ';path=/;expires=' + exdate.toGMTString();
		},
		get: function(name) {
			if (document.cookie.length > 0) {
				c_start=document.cookie.indexOf(name + '=');
				if (c_start!=-1) {
					c_start=c_start + name.length + 1;
					c_end=document.cookie.indexOf(';',c_start);
					if (c_end==-1)  {
						c_end=document.cookie.length;
					}
	    			return unescape(document.cookie.substring(c_start,c_end));
				}
			}
			return null;
		}
	},
	*/
	fancyinit: function() {
		$('a[rel=fancybox]').each(function() {
			if ($(this).attr('ref')) {
				p = $(this).attr('ref');
				$(this).fancybox({
					type: 'inline',
					autoDimensions: true,
					onComplete: function() {
						eval('$.app.els.' + p + '.player.play();');
					},
					padding: 0,
					margin: 0
				});
			} else {
				$(this).fancybox({margin: 0, padding: 0});			
			}
		});
	},
	init: function() {
		$.app.ipad = navigator.userAgent.match(/iPad/i) != null;
		$.app.iphone = navigator.userAgent.match(/iPhone/i) != null;

		$('.tip').live('mouseover', function(event) {
		
			$(this).qtip({
				overwrite: false,
				show: {
					event: event.type,
					ready: true
				},
				style: {
					classes: 'ui-tooltip-dark'
				},
				position: {
					my: 'top left',
					at: 'bottom left'
				},
				show: {
					delay: 200
				}
			}, event);
		});

		$.app.fancyinit();
		
		$('a[rel=culturebox]').each(function() {

			$(this).fancybox({

				autoDimensions: true,
				onComplete: function() {
					if (!$.app._ignoreState) {
						history.pushState({}, document.title, (this.orig.parent()).attr('ref'));
					}
					$.app._ignoreState = false;
				},
				onClosed: function() {
					history.pushState({}, document.title, '/culture/album/' + $($('.culture-album').get(0)).attr('ref'));
				},
				titlePosition: 'over',
				padding: 0,
				margin: 20
			});
		});
		
		if ($('.news') && $('.news-item').get(0)) {
			$($('.news-item').get(0)).fadeIn();

			$(document).everyTime(10000, function(i) {
				var key = null;
				$('.news-item').each(function(k) {
					if ($(this).css('display') != 'none') {
						key = k;
					}
				});
				var next = key == $('.news-item').length-1 ? 0 : key+1;
				$($('.news-item').get(key)).fadeOut('fast',function() {
					$($('.news-item').get(next)).fadeIn('fast');
				});
			}, 50);
		}
				
		if (!$.app.ipad) {
			$('.buttonLink img, .subtool img, .article img, .projectImg, .buzz-featured-item')
				.live('mouseover',function(el, i){
					$(this).clearQueue().stop(true, false).animate(
						{opacity: .7}, {duration: 350, specialEasing: {opacity: 'easeOutQuart'}}
					)
				})
				.live('mouseout',function(el, i){
					$(this).clearQueue().stop(true, false).animate(
						{opacity: 1}, {duration: 350, specialEasing: {opacity: 'easeOutQuart'}}
					)
				});

			$('.positions a')
				.mouseover(function(el, i){
					$(this).clearQueue().stop(true, false).animate(
						{color: '#0057f7'}, {duration: 150, specialEasing: {color: 'easeOutQuart'}}
					)
				})
				.mouseout(function(el, i){
					$(this).clearQueue().stop(true, false).animate(
						{color: '#333333'}, {duration: 250, specialEasing: {color: 'easeOutQuart'}}
					)
				});

			
			$('.reelImg')
				.mouseover(function(el, i){


					$(this).find('.play-icon').clearQueue().stop(true, false).animate(
						{opacity: 1}, {duration: 350, specialEasing: {opacity: 'easeOutQuart'}}
					)
				})
				.mouseout(function(el, i){
					$(this).find('.play-icon').clearQueue().stop(true, false).animate(
						{opacity: 0}, {duration: 350, specialEasing: {opacity: 'easeOutQuart'}}
					)
				});

		}

		//has news feed 
		if ($('#newsFeed').get(0)) {
			$.app.feed.init('', $('#newsFeed').get(0));
		}
		
		//its the about page
		if ($('#aboutPics').get(0)) {
			$.app.about.init();
		}

		// its the jobs page
		if ($('#content_jobs').get(0)) {
			$.app.jobs.init();            
		}
		
		// its the project page
		if ($('#projectSlides').get(0)) {
			$.app.project.init();
		}
		
		// its the homepage
		if ($('#mainContentVid').get(0)) {
			$.app.reel.init();
		}

		$.app.hotkey.init();

	},
	
	
	hotkey: {
		keys: null,
		banned: false,
		actions: {
			ninja: {
				keys: [68],
				action: function() {
					$('.hidden_person').css('display', '');
					$.app.toBottom();
				}
			},
			next: {
				keys: [39],
				action: function() {
					if (!($('#projectSlidesContent').get(0))) {
						return;
					}
					k = null;
					$('#projectSlidesContent .slidesImg').each(function(i, v) {
						if ($(v).hasClass('img-active')) {
							k = i;
						}
						if (k != null && k+1 == i) {
							$(v).click();
						}
					});
					if (k == null) {
						k = 0;
						$($('#projectSlidesContent .slidesImg').get(1)).click();
					}

					page = Math.floor(($.app.project.current/5));
					pageitem = Math.floor((k+1)/5);
					if (pageitem > page) {
						$('#slidesDown a').click();
					}
				}
			},
			prev: {
				keys: [37],
				action: function() {
					if (!($('#projectSlidesContent').get(0))) {
						return;
					}
					k = null;
					$($('#projectSlidesContent .slidesImg').get().reverse()).each(function(i, v) {
						if ($(v).hasClass('img-active')) {
							k = i;
						}
						if (k != null && k+1 == i) {
							$(v).click();
							kv = v;
						}
					});
					
					$('#projectSlidesContent .slidesImg').each(function(i, v) {
						if (v == kv) {
							k = i;
						}
					});
					
					page = Math.floor(($.app.project.current/5));
					pageitem = Math.floor(k/5);
					if (pageitem < page) {
						$('#slidesUp a').click();
					}
				}
				
			}
		},
		active: false,

		init: function() {
			$(document).keyup(function(event) { $.app.hotkey.process(event); });

		},
		checkban: function(event) {
			if (event.which == 17) {
				return;
			}
			if (event.ctrlKey) {
				$.app.hotkey.banned = true;
				$(document).stopTime('bankeys').oneTime(500,'bankeys',$.app.hotkey.unban);
			}
		},
		unban: function() {
			$.app.hotkey.banned = false;
		},
		process: function(event) {
			if ($.app.hotkey.banned) {
				return false;
			}
			if (browser.name == 'MSIE') {
				return false;
			}
			if (!(event.target instanceof HTMLBodyElement)) {
				return;
			}
			if (event.which == 91 || event.which == 18) {
				return;
			}
			if ($.app.hotkey.keys == null) {
				$.app.hotkey.keys = [];
			}

			$.app.hotkey.keys[$.app.hotkey.keys.length] = event.which;
			
			if ($.app.hotkey.check()) {
				$.app.hotkey.finish();
			} else {
				$(document).stopTime('hotkeys').oneTime(2000,'hotkeys',$.app.hotkey.finish);
			}
		},
		check: function() {

			for (x in $.app.hotkey.actions) {
				match = null;
				for (var i = 0; i < $.app.hotkey.keys.length+1; i++) {
					if ($.app.hotkey.keys[i] != $.app.hotkey.actions[x]['keys'][i] && $.app.hotkey.actions[x]['keys'][i] != 0) {
						match = false;
						break;
					}
				}
				if ($.app.hotkey.keys.length != $.app.hotkey.actions[x]['keys'].length) {
					match = false;
				}
				if (match == null) {
					match = x;
					break;
				}
			}

			if (match != false && match != null) {
				$.app.hotkey.actions[match]['action']($.app.hotkey.keys);
			}
			return match;
		},
		finish: function() {
			//if ($.app.hotkey.active) {
				$(document).stopTime('hotkeys');
				$.app.hotkey.active = false;
				$.app.hotkey.keys = null;
			//}
		}
	},

	jobs: {
		populateEmail: function(jobId) {
			$.getJSON(baseUrl + 'jobs/email?id=' + jobId,{}, function(json) {
				location.href = json.content;
			});
		},
		scrollTo: function(jobId) {
			$.scrollTo($('.job_'+jobId).get(0), 350, {easing:'easeOutQuart'} );
		}
	},

	project: {
		slides: {},
		slideCollection: {},
		videos: {},
		currentVideo: null,
		current: 0,
		distance: 408,
		init: function() {
			eval($.app.project.initcmd);
			$('#projectSlides').scrollTo($('#projectSlidesContent div').first().get(0));
		},
		
		scroll: function(direction) {

			var items = $('#projectSlidesContent div');
			if (direction == 'back') {
				$.app.project.current -= 5;
			} else {
				$.app.project.current += 5;
			}
			if ($.app.project.current <= 0) {

				$('#projectSlides').scrollTo(items.first().get(0), 350, {easing:'easeOutQuart'} );
				$.app.project.current = 0;
				if ($('#slidesUp').get(0)) {
					$('#slidesUp').css('display','none');
				}
				if ($('#slidesDown').get(0)) {
					$('#slidesDown').css('display','');
				}
			} else if (items[$.app.project.current]) {
				var pos = items[$.app.project.current];

				$('#projectSlides').scrollTo(pos, 350, {easing:'easeOutQuart'} );
				if (items[$.app.project.current+5]) {
					if ($('#slidesDown').get(0)) {
						$('#slidesDown').css('display','');
					}
				} else {
					if ($('#slidesDown').get(0)) {
						$('#slidesDown').css('display','none');
					}
				}
				if ($('#slidesUp').get(0)) {
					$('#slidesUp').css('display','');
				}
			} else {

				$('#projectSlides').scrollTo(items.last().get(0), 350, {easing:'easeOutQuart'} );
				$.app.project.current = items.length-5;
				if ($('#slidesDown').get(0)) {
					$('#slidesDown').css('display','none');
				}
				if ($('#slidesUp').get(0)) {
					$('#slidesUp').css('display','');
				}
			}		

		},
		
		showVideo: function(movie) {
			if ($.app.project.movie) {
				$.app.project.movie.destruct();
			}
			$('#projectImage').html('');

			$.app.project.movie = new QuickControl(contentServer + 'assets/reel/' + $.app.project.videos[movie].video, {
				id: 'mainVid',
				width: 1024,
				height: $.app.project.videos[movie].height,
				style: 'mainContentVid',
				container: 'projectImage',
				attributes: {
					autoplay: 'true',
					enablejavascript: 'false'
				},
				onended: function() {
					$.app.project.nextVideo();
				}
			});
			$.app.project.currentVideo = movie;
			$('#projectImage').css('height',($.app.project.videos[movie].height+20) + 'px');
		},
		
		nextVideo: function() {
			var previous = '';
			
			for (x in $.app.project.videos) {
				if (previous == $.app.project.currentVideo) {
					$.app.project.showVideo(x);
					return;
				}
				previous = x;
			}
			
			for (x in $.app.project.videos) {
				//$.app.project.showVideo(x);	
				//return;
			}
		},
		
		showImage: function(img, sender) {
			if ($f()) {
				$f().stop();
				$('#projectImage object').remove();
			}
			$('#projectSlidesContent .slidesImg').removeClass('img-active');
			$(sender).addClass('img-active');

			if ($.app.project.movie) {
				$('#projectImage').html('');
				$.app.project.movie.destruct();
				$.app.project.movie = null;
			}
			
			if ($('#project_new').get(0)) {
				$('#project_new')
					.attr('id','project_old')
					.css('z-index','1');
			}

			$('#projectImage').prepend(
				$('<div></div>')
					.attr('id','project_new')
					.css({
				    	'z-index': 2,
				        'opacity': 0,
						'position': 'absolute',
				        'background': 'url(' + img + ') center center',
				        'height': '400px',
				        'width': '1024px',
				        'float': 'left',
				        'clear': 'none'
					})
			);
			$('#projectImage').css('height','400px');

			if ($('#project_old').get(0)) {
				$('#project_old').clearQueue().stop(true, false).animate(
					{opacity: 0}, 500, 'easeOutQuart', $(this).remove()
				);
			}
			$('#project_new').clearQueue().stop(true, false).animate(
				{opacity: 1}, 500, 'easeOutQuart'
			);

		}		
	},
	
	sidevid: {
		create: function(params) {
			$.app.sidevid.movie = $.media({
				width: params.width,
				height: params.height,
				poster: params.poster,
				file: contentServer + 'assets/reel/' + params.movie,
				id: 'mainVid',
				container: (typeof(params.container) == 'undefined' ? 'sideVid' : params.container),
				autoplay: (typeof(params.autoplay) == 'undefined' ? true : params.autoplay),
				properties: params,
			});
		},
		play: function(params, poster) {
			if ($.app.ipad || $.app.iphone || (browser.name == 'MSIE' && browser.version == '9.0')) {
				if ($.app.sidevid.current != params.video || !$.app.sidevid.movie) {
					$.app.sidevid.current = params.video;
					$.app.sidevid.movie.load({
						file: contentServer + 'assets/reel/' + params.video,
						height: params.video_height,
						width: params.video_width,
						poster: poster,
						properties: params,
					});
				}
			} else {
				$f().play(contentServer + 'assets/reel/' + params.video);
			}
		}	
	},

	reel: {
		movie: null,
		current: 0,
		updateLoc: function(create) {
			url = document.location.pathname.replace('/reel','').replace('/','');
			if (url) {
				$.app.reel.reels = reels;
				var complete = false;
				$.each($.app.reel.reels, function(k, v) {
					if (v) {
						if (v.permalink == url) {
							$.app.reel[create ? 'create' :  'play'](k);
							complete = true;
							return;
						}
					}
				});
			}
			if (complete) { return; }
			$.app.reel[create ? 'create' :  'play'](1);
			try {
				history.replaceState({}, document.title, '/');
			} catch(e) {}

		},
		init: function(movie) {

			$('#mainContentVid').css('display','');
			
			window.onpopstate = function (e) {
				//$.app.reel.updateLoc();
			}

			$.app.reel.reels = reels;

			var completed = false;
			
			i = 0;
			$.app.reel.map = {};
			for (x in $.app.reel.reels) {
				i++;
				$.app.reel.map[x] = i;
			}

			$.app.reel.updateLoc(true);
		},
		create: function(movie) {
			try {
				movie = movie.replace('reel-','');
			} catch(e) {}

			if ($.app.ipad || $.app.iphone || (browser.name == 'MSIE' && browser.version == '9.0')) {

				$.app.reel.current = movie;
				$.app.reel.movie = $.media({
					width: 1024,
					height: 400,
					file: contentServer + 'assets/reel/' + $.app.reel.reels['reel-' + movie].file,
					id: 'mainVid',
					properties: $.app.reel.reels['reel-' + movie],
					container: 'mainContentVid'
				});
			} else {
				files = [];
				for (x in $.app.reel.reels) {
					files[files.length] = {
						file: contentServer + 'assets/reel/' + $.app.reel.reels[x].file,
						properties: $.app.reel.reels[x],
					}
				}
				
				$.app.reel.current = movie;
				$.app.reel.movie = $.media({
					width: 1024,
					height: 400,
					file: contentServer + 'assets/reel/' + $.app.reel.reels['reel-' + movie].file,
					files: files,
					id: 'mainVid',
					properties: $.app.reel.reels['reel-' + movie],
					container: 'mainContentVid',
					onstart: function(clip) {
						id = $f().getClip().index;
						for (x in $.app.reel.map) {
							if ($.app.reel.map[x] == id) {
								movieId = x.replace('reel-','');
								break;
							}
						}


						if (clip.index != 0) {
							try {
								_tracker._trackEvent('Videos', 'Play', clip.url);
							} catch (e) {}
	
							$.app.reel.playExtras(movieId);
						}
						
						if (clip.index != 0 && clip.index != 1) {
							try {
								history.replaceState({}, document.title, '/reel/' + $.app.reel.reels['reel-' + movieId].permalink);
							} catch(e) {}
						}
					}
				});
				
				if (movie != 1) {
					$f().play($.app.reel.map['reel-' + movie]);
				}
			}
		},
		playExtras: function(movie) {
			if (parseInt($.app.reel.reels['reel-' + movie].montage)) {
				$('.slide-montage').fadeOut(150,function() {

					$('.slide-montageswap').fadeIn(300);
				});
				$('.just-released-wrap').fadeOut(200);
	
			} else if(parseInt($.app.reel.reels['reel-' + movie].montageswap)) {

				$('.slide-montageswap').fadeOut(150,function() {

					$('.slide-montage').fadeIn(300);
				});
				$('.just-released-wrap').fadeIn(200);
				
			} else {
				$('.just-released-wrap').fadeOut(200);
			}
		},
		next: function() {
			var previous = '';
			var completed = '';
			
			for (x in $.app.reel.reels) {
				if (previous == $.app.reel.current) {
					if (!$.app.reel.reels[x].active || $.app.reel.reels[x].active == '0') {
						previous = x;
					} else {
						$.app.reel.play(x);
						return;
					}	
				}
				previous = x;
			}

			// if we havent played anything yet play the first
			for (x in $.app.reel.reels) {
				$.app.reel.play(x);	
				return;
			}
			
		},
		play: function(movie) {

			if ($.app.ipad || $.app.iphone || (browser.name == 'MSIE' && browser.version == '9.0')) {
				if ($.app.reel.current != movie || !$.app.reel.movie) {

					$.app.reel.current = movie;
					$.app.reel.movie.load({
						file: contentServer + 'assets/reel/' + $.app.reel.reels['reel-' + movie].file,
						height: 400,
						width: 1024,
						properties: $.app.reel.reels['reel-' + movie],
					});
	
				}
			} else {
				$f().play($.app.reel.map['reel-' + movie]);
			}

			$.app.reel.playExtras(movie);
		}
	},
	
	history: {
		timer: null,
		hash: '',
		getHash: function () {
			var hash = location.hash;
			var hashReplace = /#(.*)/;
			hash = hashReplace.exec(hash);
			if (hash) {
				hash = hash[1];
			}
			return hash;

		},
		check: function() {
			var hash = this.history.getHash();
    		if (hash && hash != $.app.history.hash) {
        		$.app.history.hash = hash;
        		$.app.displayPage(hash);
    		} else {
	    		$.app.history.hash = 'home';
	        	$.app.displayPage($.app.history.hash);
	    	}
		}
	},
	buzz: {
		current: null,
		init: function() {
			window.onpopstate = function (e) {

				id_article = document.location.pathname.replace('/buzz/','');
				if (id_article != '/buzz' && id_article != $.app.buzz.current) {
					$.app.buzz.load(id_article, true);
				} else {
					$.app.buzz.load($.app.buzz.start, true);
				}
			}
		},
		load: function(id_article, ignoreHistory) {
			if (historyUnsuported)
				return true;

			if (id_article == $.app.buzz.current) 
				return false;

			$.getJSON(baseUrl + 'ajax/buzz/',{
				id_article: id_article
			}, function(json) {
				var obj = $('.fb-like').html('').clone().attr('data-href','http://' + location.host + '/buzz/' + json.link);
				$('.fb-like').replaceWith(obj);
				FB.XFBML.parse(document.getElementById('.fb-like'));

				$('.buzz-article').fadeOut(100,function() {
					$(this).remove();
					var newsItem = $(json.content);
					newsItem.css('display','none');
					$('.buzz-article-wrapper').append(newsItem);

					$.app.fancyinit();
					if (!ignoreHistory) {
						history.pushState({}, json.article.title, '/buzz/' + json.link);
					}
					$.app.buzz.current = json.link;
					
					newsItem.fadeIn('fast',function() {

					});
				});
			});
			
			return false;
		}
	},
	login: function(source) {
		var status = false;
		if (!$('#save-password').attr('hasevent')) {
			$('#save-password').bind('load',function(){
				location.href = '/jobs/apply';
			}).attr('hasevent',true);
		}
		
		$.app.postForm(source,null,function(json) {
			status = json.status;
		},false);

		return status;
	},
	
	applyContinue: function(source) {
		$.app.applyContinue = true;

		var parent = $(source).find('.parentFormWrapper');

		parent.find('.loader').css('display','').fadeIn(200);
		parent.find('.button').css('display','none');
		parent.find('.link-submit').css('display','none');
		parent.find('.formMessage')
			.empty()
			.fadeOut(400);

		try {
			$.uploader.start();
		} catch (e) {
			$.app.apply($('#apply-form'));
		}
	},
	
	apply: function(source) {
		$.ajax({
			url: $(source).attr('action'),
			dataType: 'json',
			type: 'post',
			data: $(source).serializeArray(),
			complete: function(json) {
				location.href = '/jobs/complete';
			}
		});
		return status;
	},


	postForm: function(source, destination, complete) {
		var async = arguments[3] == false ? false : true;
		var contentFormat = arguments[4] ? arguments[4] : false;
		var parent = $(source).find('.parentFormWrapper');

		parent.find('.loader').css('display','').fadeIn(200);
		parent.find('.button').css('display','none');
		parent.find('.link-submit').css('display','none');
		parent.find('.formMessage')
			.empty()
			.fadeOut(400);


		$.ajax({
			url: destination || source.attr('action'),
			dataType: 'json',
			type: 'post',
			data: $(source).serializeArray(),
			complete: function(json) {

				content = '';
				if (!json.status) {
					if (json.response) {
						content = '<div class="messageError ui-state-error ui-corner-all"><table cellpadding="1" cellspacing="0"><tr><td><span class="ui-icon ui-icon-alert"></span></td><td class="message">' + json.response + '</td></tr></table></div>';
						$('html,body').animate({scrollTop: 0}, 200);
					}
				} else {
					if (json.response) {
						content = '<div class="messageSuccess ui-state-highlight ui-corner-all"><table cellpadding="1" cellspacing="0"><tr><td><span class="ui-icon ui-icon-alert"></span></td><td class="message">' + json.response + '</td></tr></table></div>';
					}
				}

				parent.find('.loader').css('display','none');
				parent.find('.button').css('display','').fadeIn(200);

				parent.find('.formMessage')
					.clearQueue()
					.dequeue('fx')
					.stop(true, true)
					.html(content)
					.animate(
						{ height: 'toggle', opacity: '1'},
						{ duration: 300, specialEasing: { height: 'easeOutQuart' }}
					);
	
				if (complete) {

					complete(json);
				}
			}
		});

		return false;
	}
}

$(document).ready(function() {
	$.app.init();
});

$(document).ready(function() {
	$('a.minibutton').bind({
		mousedown: function() {
			$(this).addClass('mousedown');
		},
		blur: function() {
			$(this).removeClass('mousedown');
		},
		mouseup: function() {
			$(this).removeClass('mousedown');
		}
	});
});

function initScreen() {
	setTimeout('window.scrollTo(0,1);',100);
}
function updateOrientation() {
	initScreen();
}


(function($) {
    $.fn.sorted = function(customOptions) {
        var options = {
            reversed: false,
            by: function(a) {
                return a.text();
            }
        };
        $.extend(options, customOptions);
    
        $data = $(this);
        arr = $data.get();
        arr.sort(function(a, b) {
            
            var valA = options.by($(a));
            var valB = options.by($(b));
            if (options.reversed) {
                return (valA < valB) ? 1 : (valA > valB) ? -1 : 0;              
            } else {        
                return (valA < valB) ? -1 : (valA > valB) ? 1 : 0;  
            }
        });
        return $(arr);
    };

})(jQuery);

$(function() {

	$('img').not('.projects img').lazyload({
		placeholder : '/assets/images/white.gif',
		effect: 'lazyFadeIn'
	 });

	
	var read_button = function(class_names) {
		var r = {
			selected: false,
			type: 0
		};
		for (var i=0; i < class_names.length; i++) {
			if (class_names[i].indexOf('selected') == 0) {
				r.selected = true;
			}
			if (class_names[i].indexOf('segment') == 0) {
				//r.segment = class_names[i].split('-')[1];
			}
		};
		return r;
	};
	
	var determine_sort = function($buttons) {
		var $selected = $buttons.parent().filter('[class*="selected"]');
		return $selected.find('a').attr('data-value');
	};
	
	var determine_kind = function($buttons) {
		var $selected = $buttons.parent().filter('[class*="selected"]');
		return $selected.find('a').attr('data-value');
	};
	
	var $preferences = {
		duration: 400,
		easing: 'easeInOutQuad',
		adjustHeight: 'dynamic'
	};
	
	var $list = $('#list');
	var $data = $list.clone();
	
	var $controls = $('ul.splitter ul');
	
	$controls.each(function(i) {
		
		var $control = $(this);
		var $buttons = $control.find('a');
		
		$buttons.bind('click', function(e) {
			
			var $button = $(this);
			var $button_container = $button.parent();
			var button_properties = read_button($button_container.attr('class').split(' '));			
			var selected = button_properties.selected;
			var control_type = $control.parent().parent().attr('data-type');

			if (!selected) {

				$buttons.parent().removeClass('selected');
				$button_container.addClass('selected');
				
				var sorting_type = determine_sort($controls.eq(1).find('a'));
				var sorting_kind = determine_kind($controls.eq(0).find('a'));

				$.getJSON(baseUrl + 'ajax/setFilter',{
					kind: sorting_kind,
					type: sorting_type,
					data: control_type
				}, function(json) {});	
				
				if (sorting_kind == 'all') {
					var $filtered_data = $data.find('li');
				} else {
					var $filtered_data = $data.find('li.' + sorting_kind);
				}
				if (!sorting_type) {
					sorting_type = 'date';
				}
				if (sorting_type == 'date') {
					var $sorted_data = $filtered_data.sorted({
						by: function(v) {
							return parseFloat($(v).find('span[data-type="' + sorting_type + '"]').text());
						},
						reversed: true
					});
				} else {
					var $sorted_data = $filtered_data.sorted({
						by: function(v) {
							return $(v).find('span[data-type="' + sorting_type + '"]').text().toLowerCase();
						}
					});
				}

				
				$list.quicksand($sorted_data, $preferences);
				
			}


			e.preventDefault();
		});
		
	});
});

$.extend($, {values: function(o) {
	var q = o.serializeArray(), p = {};
	for (i in q) {
		p[q[i].name] = q[i].value;
	}
	return p;
}, app: app});



$.fn.extend({
	lazyFadeIn: function() {
		return $(this).fadeIn(100);
	}
});

