Array.prototype.getUniqueValues = function () {
	var hash = new Object();
	for (j = 0; j < this.length; j++) {hash[this[j]] = false}
	var array = new Array();
	for (value in hash) {array.push(value)};
	return array;
}

Array.prototype.intersect =
  function() {
    if (!arguments.length)
      return [];
    var a1 = this;
    var a = a2 = null;
    var n = 0;
    while(n < arguments.length) {
      a = [];
      a2 = arguments[n];
      var l = a1.length;
      var l2 = a2.length;
      for(var i=0; i<l; i++) {
        for(var j=0; j<l2; j++) {
          if (a1[i] === a2[j])
            a.push(a1[i]);
        }
      }
      a1 = a;
      n++;
    }
    return a.unique();
  };

// Return new array with duplicate values removed
Array.prototype.unique =
  function() {
    var a = [];
    var l = this.length;
    for(var i=0; i<l; i++) {
      for(var j=i+1; j<l; j++) {
        // If this[i] is found later in the array
        if (this[i] === this[j])
          j = ++i;
      }
      a.push(this[i]);
    }
    return a;
  };

$.fn.reverse = [].reverse; 

var filterCalibers = [];
var filterStatus = [];
var filterKind = [];
var filterYear = [];
	
var filterArr = [];
var arrays = [];
var allElements = [];

var bcgs = [];


var loaderControll = 1;

var historyControll = 1;

var projectDetail;
//////////////////////////////////////////////////////////////////////////////////////////////////
// FUNKCE
//////////////////////////////////////////////////////////////////////////////////////////////////
function languageSwitch(){
	$('#languages a').click(function(){
		var href = window.location.href;
		window.location.href = href.replace(/(\/+)[a-zA-Z]{2}(\/+)/, $(this).attr('href'));
		return false;
	})
}

function preloader(){
	$('.main-list a').each(function(){
		var img = new Image();
		img.src = $(this).attr('rel');
		$(this).mouseover(function(){
			if($(this).hasClass('g') == false){
				if($(this).attr('rel')){
					$('#hoverImg').attr('src',img.src);
					$('#hoverImg').appendTo($(this)).show();
				}
			}
		})
		.click(function(){
			$('.main-list a').removeClass('selected');
			$(this).addClass('selected');
			$('#hoverImg').hide();
		})
		.mouseleave(function(){
			$('#hoverImg').hide();
		})
	})
}

// FILTER EFFECTS
function hideElement(elem){
	$(elem).animate({ 
		'width': "0px"
		// opacity: "hide"
		}, 500, function(){
			$(elem).hide();
		}).hide();
}

function showElement(elem){
	$(elem).animate({ 
		'width': "180px"
		// opacity: "show"
		}, 300, function(){
			$(elem).show();
		}).show();
}

// posouvá projekt s oknem nahoru
function scrollProject(){
	$(window).scroll(function(){
		if($('#fixer').offset().top < $('#project').offset().top)
			$('#project').css('top',$('#fixer').offset().top)
	})
}
function startLoading(){
	loaderControll = 1;
	function loading(){
		$('#calibers a').addClass('no-bcg');
		$('#caliber_xl').delay(500).queue(function(){$(this).removeClass('no-bcg').dequeue()});
		$('#caliber_l').delay(400).queue(function(){$(this).removeClass('no-bcg').dequeue()});
		$('#caliber_m').delay(300).queue(function(){$(this).removeClass('no-bcg').dequeue()});
		$('#caliber_s').delay(200).queue(function(){$(this).removeClass('no-bcg').dequeue()});
				
		if(loaderControll == 0){
			clearInterval(loading);
			$('#calibers a').removeClass('no-bcg');
		}
	}
	
	loading();
	
	if(loaderControll == 1) loading = setInterval(loading, 700);
	
}
function stopLoading(){
	loaderControll = 0;
}
// VYLISTOVÁNÍ GALERIE
function gallery(){
	$('#main-thumbnail').click(function(){
		var project = $(this).parent();
		var gallery = project.find('#gallery');
		var thumbnails = gallery.find('.thumbnail');
				
		if(thumbnails.length > 1){
			
			$('.text_cs').animate({
				'margin-top': $('#main-thumbnail img').height()*-1 + Math.ceil(thumbnails.length / 3)*130 + 'px'
			})
			
			$(this).addClass('invisible');
			gallery.show(0);
			// time = 0;
			
			thumbnails.map(function(i){
				if(i == 0) $(this).addClass('current_thumb');

				$(this).delay(++i*100).show(0);

				$(this).click(function(){
					$('.thumbnail').each(function(){
						$(this).removeClass('current_thumb');
					})
					$(this).addClass('current_thumb');					
					mainImage($(this));	
					lastNext();				
					return false;
				});
								
			})
			
		}
		return false;
	})
	.click(function(){
		mainImage($(this));
		if($(this).parents('#project').hasClass('setup')==false){
			$(this).parents('#project').addClass('setup');
			nextPrev();
		}
		lastNext();	
		return false;
	})
	
}

function lastNext(){
	if($('.thumbnail').length > 1){
		$('#navigation').removeClass('invisible');
	}else{
		$('#navigation').addClass('invisible');
	}
	if($('.current_thumb').next('.thumbnail').length > 0){
		$('#next').removeClass('invisible')
	}else{
		$('#next').addClass('invisible');
	}
	if($('.current_thumb').prev('.thumbnail').length > 0){
		$('#prev').removeClass('invisible')
	}else{
		$('#prev').addClass('invisible');
	}
}
function nextPrev(){
	// lastNext()
	// $('#next, #prev').removeClass('invisible')
	$('#next').click(function(){
		// $('.thumb_selected').next('a').trigger('click');
		var elem = $('.current_thumb:first').next('.thumbnail');
		elem.trigger('click');
		return false;
	})
	$('#prev').click(function(){
		// $('.thumb_selected').prev('a').trigger('click');
		var elem = $('.current_thumb:first').prev('.thumbnail');
		elem.trigger('click')
		return false;
	})
}

function nextPrevArea(){
	$('#next-area').live('click',function(){
		$('#next').trigger('click');
	}).live('mouseenter', function(){
		$('#next').addClass('hover')
	}).live('mouseleave', function(){
		$('#next').removeClass('hover')
	})
	
	$('#prev-area').live('click',function(){
		$('#prev').trigger('click');
	}).live('mouseenter', function(){
		$('#prev').addClass('hover')
	}).live('mouseleave', function(){
		$('#prev').removeClass('hover')
	})
}

function hideHeader(){
	$('#header').hide(); 
	$('#left').css('margin-top',$('#header').height() + 20);
}
function showHeader(){
	$('#header').show(); 
	$('#left').css('margin-top','170px');
}

function mainImage(elem){	
	var image = new Image;
	var container = $('#image-container');
	var description = $('#description');
	var src = elem.attr('href');
		
	var vimeoId = src.replace('http://vimeo.com/', '')
		
	startLoading();
	
	// Title Galerie
	var gallery_title = $('#gallery_title_content').html($("#project h1").html());
	
	if(elem.hasClass('vimeo')){
		$('.main-list a').addClass('invisible');
		// startLoading();
		
		hideHeader();
		
		container.css({'top' : $('#filter').position().top + 'px'}).show()
		container.find('img').remove();
		
		// Title fotky
		var des = elem.attr('title').split(" | ");
		var text = "";
		for (var i=0; i < des.length; i++) {
			if(des[i] != "") text += des[i]+"<br />";
		}
		description.html(text);
		
		$('#close').click(function(){
			resetGallery();
		})
		
		$('#vimeo_object').attr('value', 'http://vimeo.com/moogaloop.swf?clip_id='+vimeoId+'&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=0&amp;show_portrait=0&amp;color=ff9933&amp;fullscreen=1"')
		$('#vimeo_embed').attr('src', 'http://vimeo.com/moogaloop.swf?clip_id='+vimeoId+'&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=0&amp;show_portrait=0&amp;color=ff9933&amp;fullscreen=1"')
		
		$('#vimeo').appendTo(container).removeClass('hidden');
		stopLoading();
	}else{
		$(image)
			.load(function(){
				$('.main-list a').addClass('invisible');
				$('#vimeo').addClass('hidden')
				
				hideHeader();
				
				container.css({'top' : $('#filter').position().top + 'px'}).show();
				container.find('img').remove();
				$(this).appendTo(container.find('a#main-image'));
				
				var des = elem.attr('title').split(" | ");
				var text = "";
				for (var i=0; i < des.length; i++) {
					if(des[i] != "") text += des[i]+"<br />";
				}
				description.html(text);
				
				$('#close').click(function(){
					resetGallery();
					return false;
				})
				stopLoading();

			})
			.attr('src', src)
	}

	return false;
}

function resetGallery(){
	
	var thumbnails = $('.thumbnail');//.reverse();
	
	showHeader();
	
	$('.main-list a, #main-thumbnail').removeClass('invisible');
	$('.text_cs').animate({ 'margin-top': 0 });
	$('#image-container').hide();
	
	$('.current_thumb').each(function(i){
		$(this).removeClass('current_thumb');
	})
	thumbnails.hide();

}

function prask(){
	$('#projektil_white').show().delay(50).queue(function(){$(this).hide().dequeue()});
}

$.address.change(function(c){
	if(historyControll == 1){
		if($('a[name_='+c.value+']')) $('a[name=_'+c.value+']').trigger('click');
		resetGallery();
	}
});

function credits(){
	// $('#fixer').animate({
	// 	'width' : 110,
	// 	'height' : 30
	// }, 300, function(){
	// 	$('#fixer').delay('100').animate({
	// 		'width' : 3,
	// 		'height' : 3
	// 	},300)
	// })
	$('#fixer').hover(function(){
		$(this).animate({
			'width' : 110,
			'height' : 30
		})
	},function(){
		$(this).stop().animate({
			'width' : 3,
			'height' : 3
		})
	})
}

function setup(){
	setupAjax()
	gallery();
	scrollProject();
	prask();
	languageSwitch();
	nextPrevArea();
	preloader();
	credits();
	filterItems();
}
function filterItems(){
	$('a.filter').click(function(){
		
		if($(this).hasClass('selected')){
			$(this).removeClass('selected');
			$('.main-list a').not(elem).show();
		}else{
			$('.filter').removeClass('selected');
			$(this).addClass('selected');//.parent().siblings('li').children().removeClass('selected').parents('ul').siblings('ul').find('a').removeClass('selected')

			elem = '.'+$(this).attr('id').toString();

			// hideElement($('.main-list a').not(elem));
			// showElement(elem);

			$('.main-list a').not(elem).hide();
			$(elem).show();
		}
	});

}

$(document).ready(function() {
		
	setup();
	
	// seznam všech projektů
	$('.main-list a').map(function(){
		allElements.push($(this).attr('id'));
		bcgs[$(this).attr('id')] = $(this).css('background-image');
	})
	
	// zobrazí pouze použité tagy v menu
	$('#status a, #kind a, #year a, #calibers a').map(function(){
		var elem = '.'+$(this).attr('id').toString();
		
		if($(elem).length >= 0) $(this).parent().show();
		
		$(this).click(function(){resetGallery()});
	})
	
	//Ochrana e/mailu
	$('a.em').each(function(){
		e = this.rel.replace('/','@');
		this.href = 'mailto:' + e;
	});
	$('span.em').each(function(){
		e = $(this).text().replace('/','@');
		$(this).text(e);
	});
	$('a.em2').map(function(){
		$(this).attr('href','mailto:' + $(this).attr('href').replace('/','@'))
	})
	
	//////////////////////////////////////////////////////////////////////////////////////////////////
	// FILTER
	//////////////////////////////////////////////////////////////////////////////////////////////////
	// $('#status a, #kind a, #year a, #calibers a').toggle(function(){
	// 	
	// 	var elem = '.'+$(this).attr('id').toString();
	// 	
	// 	if($(this).parent().parent().attr('id') == 'status'){
	// 		$(elem).each(function(){
	// 			filterStatus.push($(this).attr('id'));
	// 		})
	// 	}
	// 	if($(this).parent().parent().attr('id') == 'kind'){
	// 		$(elem).each(function(){
	// 			filterKind.push($(this).attr('id'));
	// 		})
	// 	}
	// 	if($(this).parent().parent().attr('id') == 'year'){
	// 		$(elem).each(function(){
	// 			filterYear.push($(this).attr('id'));
	// 		})
	// 	}
	// 	if($(this).parent().attr('id') == 'calibers'){
	// 		$(elem).each(function(){
	// 			filterCalibers.push($(this).attr('id'));
	// 		})
	// 	}
	// 	
	// 	$(this).addClass('selected');
	// 	
	// 	filterAll();
	// 	
	// },function(){
	// 	
	// 	var elem = '.'+$(this).attr('id').toString();
	// 	
	// 	if($(this).parent().parent().attr('id') == 'status'){
	// 		$(elem).each(function(){
	// 			filterStatus.shift($(this).attr('id'));
	// 		})
	// 	}
	// 	if($(this).parent().parent().attr('id') == 'kind'){
	// 		$(elem).each(function(){
	// 			filterKind.shift($(this).attr('id'));
	// 		})
	// 	}
	// 	if($(this).parent().parent().attr('id') == 'year'){
	// 		$(elem).each(function(){
	// 			filterYear.shift($(this).attr('id'));
	// 		})
	// 	}
	// 	if($(this).parent().attr('id') == 'calibers'){
	// 		$(elem).each(function(){
	// 			filterCalibers.shift($(this).attr('id'));
	// 		})
	// 	}
	// 	
	// 	$(this).removeClass('selected');
	// 	
	// 	filterAll();
	// 	
	// })
	// 
	// function filterAll(){
	// 	//reset polí
	// 	arrays = [];
	// 	filterArr = [];
	// 	
	// 	//je třeba nastavit kvůli délce pole arrays
	// 	if(filterStatus.length > 0) arrays.push(filterStatus);
	// 	if(filterKind.length > 0) arrays.push(filterKind);
	// 	if(filterYear.length > 0) arrays.push(filterYear);
	// 	if(filterCalibers.length > 0) arrays.push(filterCalibers);
	// 	
	// 	if(arrays.length > 0){
	// 		for (var i=0; i < arrays.length; i++) {
	// 			arrays[i].getUniqueValues();
	// 			if(filterArr.length > 0){
	// 				if(arrays[i].length > 0) filterArr = filterArr.intersect(arrays[i]);
	// 			}else{
	// 				if(arrays[i].length > 0) filterArr = arrays[i];
	// 			}
	// 			filterArr.getUniqueValues();
	// 		}
	// 	}else{
	// 		// pokud není nastaven žádný filtr, zobrazí se všechny projekty
	// 		if($('#calibres a.selected, #filter a.selected').length < 1) filterArr = allElements;
	// 	}
	// 
	// 			
	// 	$('.main-list a').addClass('inactive');
	// 
	// 	filterArr.map(function(index) {
	// 		if(index != ""){
	// 			var elem = "#"+index;
	// 			$(elem).removeClass('inactive')
	// 			showElement(elem);
	// 		}
	// 	});
	// 	
	// 	$('.main-list a.inactive').map(function(){
	// 		hideElement(this);
	// 	})
	// }
	

	//////////////////////////////////////////////////////////////////////////////////////////////////
	// FILTER — ZOBRAZIT / SKRÝT
	//////////////////////////////////////////////////////////////////////////////////////////////////
	
	// var test = 0;
	// if($('#filter a').length > 0){
	// 	$('#header').hover(
	// 		function(){
	// 			$('#filter').slideDown(150,	changeMargin($('#filter').height()) );
	// 			test = 1;
	// 		},
	// 		function(){
	// 			test = 0;
	// 			setTimeout(function(){
	// 				if(test == 0 && $('#filter a.selected').length < 1)
	// 					$('#filter').slideUp(200, changeMargin(0) );
	// 		}, 700)
	// 		
	// 	})
	// }
	changeMargin($('#filter').height())
	//odsadí id main-list po najetí zvětšení filtru
	function changeMargin(margin){
		$('.main-list, #image-container').css({
			marginTop : margin + "px"
		}, 500)
	}	
	
	//////////////////////////////////////////////////////////////////////////////////////////////////
	// AJAX 
	//////////////////////////////////////////////////////////////////////////////////////////////////
	
	$( '.main-list a' ).click(function() {
		historyControll = 0;
		if(section != 'contact'){				
			$('#loader').appendTo($(this)).fadeIn("slow");
		
			loc = $(this).attr('name').replace(/_/,'');
		
			if(list_page == false){
				window.location.href = "/"+section+"s#"+loc;
			}
		
			window.location.hash = loc;
		
			animateContent("/_/"+section+"/"+loc);
		
			return false;
		}else{
			return true;
		}
		
	});
		
});

//////////////////////////////////////////////////////////////////////////////////////////////////
// AJAX FUNCTIONS
//////////////////////////////////////////////////////////////////////////////////////////////////
function setupAjax(){
	if(typeof(window['projectSlug']) != 'undefined'){
		var name = projectSlug.replace(/#/,'');
		if(list_page == true){
			var hash = (window.location.hash == '') ? projectSlug : window.location.hash;
			window.location.hash = hash;
			$( '#project' ).hide();		
			loadContent("/_/"+section+"/"+name);
		}else{
			$("a[name='_"+name+"']").addClass('selected');
		}
	}
}


function animateContent(target){
	historyControll = 0;
	$( '#project' )
		.animate({
			top : $('#fixer').offset().top + "px"
		}, 'fast')
		.slideUp("slow", function(){ loadContent(target) });
}

function loadContent(target){
	$( '#project' ).html( '&nbsp;' ).load("/"+language_code+target,showContent);
}

function showContent(){
	$( '#project' )
		.css({
			"top" : $('#fixer').offset().top + "px",
			"position" : "absolute"
		})
		.slideDown("slow");
		$('#loader').fadeOut("normal");
		prask();
		gallery();
		historyControll = 1;
}


function openGlallery(){
	if(projectDetail == true) $('#main-thumbnail').trigger('click');
}

$(window).load(function(){
	openGlallery();
})













