//global variables
var longestcolumn = 0;
var items = new Array();
var filters = new Array();
var cache = [];
var loadingstate = 0;
var currentlocation = -1;

//classes
function offset(left,top){
	this.left = left;
	this.top = top;
}

function Item(type,title,text,article,width,height,wall,gallery,issue,miniexperiences,artists,brands,events,buy){
	this.type = type; //0:image-1:gallery-2:youtube-3:vimeo
    this.title = title;
	this.text = text;
	this.images = new Array();
	this.images[0] = article;
	this.width = width;
	this.height = height;
	this.images[1] = wall;
	for(var i=0; i<gallery.length; i++) this.images[i+2] = gallery[i];
	this.tags = new Array();
	this.tags[0] = miniexperiences;
	this.tags[1] = artists;
	this.tags[2] = brands;
	this.tags[3] = events;
	this.tags[4] = buy;
	this.issue = issue;
}

//functions
function max(a,b){
	var ret = a;
	if (a < b) ret = b;
	return ret;
}

function min(a,b){
	var ret = a;
	if (a > b) ret = b;
	return ret;
}

function getMax(cols){
	var mx = 0;
	for(i=0;i<cols.length;i++) if(mx < cols[i]) mx = cols[i];
	return mx;
}

function getMaxIndex(cols){
	var mx = cols[0];
	var ret = 0;
	for(i=0;i<cols.length;i++){
		if(mx < cols[i]){
			mx = cols[i];
			ret = i;
		}
	}
	return ret;
}

function getMinIndex(cols){
	var mn = cols[0];
	var ret = 0;
	for(i=0;i<cols.length;i++){
		if(mn > cols[i]){
			mn = cols[i];
			ret = i;
		}
	}
	return ret;
}

function getId(id){
	return id.substring(4,id.length);
}

function getFilter(filter){
	return filter.substring(6,filter.length);
}

function getArticle(article){
	return article.substring(8,article.length);
}

function getGallery(gallery){
	var ret = parseInt(gallery.substring(3,gallery.length));
	return ret--;
}

function getIcon(icon){
	return icon.substring(4,icon.length);	
}

function getColoricon(coloricon){
	return coloricon.substring(9,coloricon.length);	
}

function swapArrowColor(){
	/*
	if($('#arrow1').hasClass('yellow')){
		
		$('#arrow1').removeClass('yellow');
		$('#arrow1').addClass('highlight');
	
	}
	
	else{
		
		$('#arrow1').removeClass('highlight');
		$('#arrow1').addClass('yellow');
	}
	*/
}

/*TODO: Load Progressiu */
function loadXML(){
	var toload = 0;
    $.ajax({
		type: "GET",
		url: "xml/items.xml",
		dataType: "xml",
		success: function(xml) {
			var i = 0;
            toload = $(xml).find('item').size();
			$(xml).find('item').each(function(){
				var type = 0;
				var width = 0;
				var height = 0;
				var gallery = new Array();
				if($(this).find('images').find('article').attr('type') == 'image') type = 0;
				else if($(this).find('images').find('article').attr('type') == 'gallery'){
					type = 1;
					$(this).find('images').find('article').find('gallery').each(function(){ gallery[gallery.length] = $(this).text(); });
				}
				else if($(this).find('images').find('article').attr('type') == 'video'){
					if($(this).find('images').find('article').attr('source') == 'youtube'){
						type = 2;
						width = $(this).find('images').find('article').attr('width');
						height = $(this).find('images').find('article').attr('height');
					}
					else if($(this).find('images').find('article').attr('source') == 'vimeo'){
						type = 3;
						width = $(this).find('images').find('article').attr('width');
						height = $(this).find('images').find('article').attr('height');
					}
				}
				items[i] = new Item(type,
									$(this).find('title').text(),
									$(this).find('text').text(),
									$(this).find('images').find('article').text(),
									width,
									height,
									$(this).find('images').find('wall').text(),
									gallery,
									$(this).find('issue').text(),
									$(this).find('tags').find('miniexperiences').text(),
									$(this).find('tags').find('artists').text(),
									$(this).find('tags').find('brands').text(),
									$(this).find('tags').find('events').text(),
									$(this).find('tags').find('buy').text());
				i++;
                toload--;
                if(toload == 0) $('#wall').trigger({type:'xml'});
			});
		}
	});
}


function loadImages(){
	
	var toload = items.length;
	/*for(var i=0;i<items.length;i++){
		if(items[i].type == 0) toload = toload + 1;
		else if(items[i].type == 1)  toload = toload + (items[i].images.length - 1);
	}*/
	
	
	//Carreguem Thumbnails
	for(var i=0;i<items.length;i++){
		
		var img = new Image();
		$(img).load(function(){
					toload--;
					if(toload == 0) $('#wall').trigger({type:'loaded'});
		}).attr('src', items[i].images[1]);
		
		
	}
	
	//Carreguem fotos interiors
	for(var i=0;i<items.length;i++){
		switch (items[i].type){
			
			case 0:
				var img = new Image();
				$(img).load(function(){
					/*toload--;
					if(toload == 0) $('#wall').trigger({type:'loaded'});*/
				}).attr('src', items[i].images[0]);
				
			break;
			
			case 1:
				for(var x=2;x<items[i].images.length;x++){
					var img = new Image();
					$(img).load(function(){
						/*toload--;
						if(toload == 0) $('#wall').trigger({type:'loaded'});*/
					}).attr('src', items[i].images[x]);
				}
			break;
		}
	}
}


function initHeader(){
	$('#bgheader').width($(window).width()-15);
	$('#bgheader').stop().fadeTo(0,0.6);
}

function resetAll(){
	
	fadeInFlash();
	
	//Si tenim l'article obert.
	if($('#article').size() != 0){
	
		//Si el wall ja està alineat a 0
		if($('#wallframe').scrollTop() == $('#article').height()){
			
			
			
			document.location.hash = "";
			var articleHeight = $('#article').height();
			
			$('#article').remove();
			$('#selection').remove();
			$('#arrow').remove();
			$('#close').remove();
			
			
			
			$('.item').each(function(){
				$(this).offset(new offset($(this).offset().left,$(this).offset().top - articleHeight));
			});
			
			$('#wallframe').scrollTo(0,0,{duration:0,onAfter:function(){
				
			//resetFilters();
			initWall();
			initItems();	
				
			}});
			
			
		} else {
			
			
		
			
			$('#wallframe').scrollTo($('#article').height(),{duration:1000,onAfter:function(){
				document.location.hash = "";
				var articleHeight = $('#article').height();
				$('#article').remove();
				$('#selection').remove();
				$('#arrow').remove();
				$('#close').remove();
				
				
				$('.item').each(function(){
					$(this).offset(new offset($(this).offset().left,$(this).offset().top - articleHeight));
				});
				
				$('#wallframe').scrollTo(0,0,{duration:0,onAfter:function(){
					//resetFilters();
					initWall();
					initItems();
				}});
				
			}});
		}
	}else{
		if($('#wallframe').scrollTop() == 0){
			
			
			
			//resetFilters();
			initWall();
			initItems();
		} else {
			
			
			
			
			$('#wallframe').scrollTo(0,0,{duration:1000,onAfter:function(){
				//resetFilters();
				initWall();
				initItems();
				
				
			}});
		}
	}
}

function initLogo(){
    $("#logo").hover(function() {
     	$(this).html('');
   	},function(){
     	$(this).html('<img src="img/logo.jpg" alt="" />');
   	});
	$('#logo').click(function() { resetAll(); });
}

function orderWallItems(){
	for(i=0;i<items.length;i++) if($('#items #item'+i).size() != 0) $('#items').append($('#items #item'+i).remove());
}

function initWall(){
	
	
	//window.alert("InitWall");
	
	//init items
	var eachline = Math.floor(($(window).width() - 430)/210);
	if(eachline <= 2) eachline = 3;
	if(eachline > 6) eachline = 6;
	var cols = new Array(eachline);
	for(i=0;i<eachline;i++) cols[i] = 0;
	orderWallItems();
	
	$('.item').each(function() {
        i = getId($(this).attr('id'));
        if($(this).parent().attr('id') != 'invisible'){
			shortestcol = getMinIndex(cols);
            if($('#article').size() == 0) $(this).offset(new offset(410 + (shortestcol)*210, 60 + cols[shortestcol]));
			else $(this).offset(new offset(410 + (shortestcol)*210, cols[shortestcol] + $('#article').height() + $('#article').offset().top));
            cols[shortestcol] = cols[shortestcol] + $(this).height() + 10;
            $(this).stop().fadeTo(0,0.4);
        }
	});
	
	//set wall height and width
	var longestcolumn = getMax(cols);
	if($('#article').size() == 0) $('#wall').height(longestcolumn + 60);
	//TODO: tamany de l'article varia amb la càrrega de la foto!
	else $('#wall').height(longestcolumn + $('#article').height() + 60);
	if(($(window).width() - 430) > 420) $('#wall').width($(window).width() - 430);
	else $('#wall').width(420);
	
	//set wallframe height and width
	$('#wallframe').height($(window).height());
	if(($(window).width() - 410) > 420) $('#wallframe').width($(window).width() - 410);
	else $('#wallframe').width(420);
	
}

function overItem(){
	$(this).siblings().each(function() {
		if($(this).parent().attr('id') != 'invisible'){
            $(this).find('#itemtext').remove();	
			$(this).stop().fadeTo(500,0.4);			 
        }
    });
	var h = $(this).height();
	$(this).append('<div id="itemtext" class="itemtextselected"><h1>'+items[getId($(this).attr('id'))].title+'</h1></div>');
	$(this).find('#itemtext').width($(this).find('#itemtext').width()+1);
	$(this).find('#itemtext').offset(new offset($(this).offset().left + $(this).width() - $(this).find('#itemtext').width() - 8,$(this).offset().top + $(this).height() - 31 - ($(this).find('#itemtext').height()-12)));
	$(this).stop().fadeTo(200,1.0);
}

function outItem(){
	if($(this).parent().attr('id') != 'invisible'){
        $(this).find('#itemtext').remove();
        $(this).stop().fadeTo(500,0.4);
    }
}

function clickItem(){
	
	updateFlash(items[getId($(this).attr('id'))].issue);
	fadeInFlash();
	
	var previousHeight = $('#wallframe').scrollTop();
	
	//remove previous article
	if($('#article').size() != 0){
		previousHeight -= $('#wall').find('#article').height();
		$('#wall').find('#article').remove();
		$('#selection').remove();
		$('#arrow').remove();
		$('#close').remove();
	}
	
	//update menu
	$('#filters').html($('#filters').html() + '<span id="arrow" class ="yellow"> > </span><span id="selection" class="currentarticle">'+items[getId($(this).attr('id'))].title.toUpperCase()+'</span><a id="close" class="closearticle">&nbsp;&times;</a>');
	
	//place article
	placeArticle(getId($(this).attr('id')));
	
	//recalculate wall
	$('#wall').find('#article').offset(new offset($('#wall').find('#article').offset().left,$('#wall').offset().top + 60));
	
	initWall();
	
	//animate and set hash
	currentlocation = getId($(this).attr('id'));
	
	$('#wallframe').scrollTo($('#wall').find('#article').height() + previousHeight,{axis:'y',duration:0,onAfter:function(){ 
		
		$('#wallframe').scrollTo(0,0,{duration:1000,onAfter:function(){ 
			document.location.hash = 'article'+currentlocation; initItems(); 
			fadeOutFlash();
		}}); 
		initFilters();
	}});
}

function placeArticle(id){
	
	$('#wall').html('<div id="article">'+$('#invisible').find('#art'+id).html()+'</div>'+$('#wall').html());
	
	if(items[id].type == 1){
		
		if($('.articleimg').height()==0){
			
			$('.articleimglabel').hide();
			
			$(this).oneTime(500, function() {
				$('.articleimglabel').show();
    	 		$('#wall').find('.articleimglabel').offset(new offset($('.articleimg').offset().left + $('.articleimg').width() - $('.articleimglabel').width() - 8,$('.articleimg').offset().top + $('.articleimg').height() - 31));
				
				if($('.articleimg').height()==0){
						
					$(this).oneTime(2000, function() {
												   $('.articleimglabel').show();
    	 				$('#wall').find('.articleimglabel').offset(new offset($('.articleimg').offset().left + $('.articleimg').width() - $('.articleimglabel').width() - 8,$('.articleimg').offset().top + $('.articleimg').height() - 31));
					
  					});
				}
				
				else {
					
					$('.articleimglabel').show();
					
					
				}
  			});
			
			
		
		}
		else{
			$('#wall').find('.articleimglabel').offset(new offset($('.articleimg').offset().left + $('.articleimg').width() - $('.articleimglabel').width() - 8,$('.articleimg').offset().top + $('.articleimg').height() - 31));
		}
		
		initGallery(id);
	}
	
	initArticles();
}

function initGallery(id){
	
	$('#wall').find('.articleimglabel').children().each(function(){
		$(this).click(function(){
			if($(this).attr('class') != 'selected') {
				$('#wall').find('.articleimg').html('');
				$('#wall').find('.articleimg').html('<img src="'+items[id].images[getGallery($(this).attr('id'))+1]+'" alt="" /><div class="articleimglabel"></div></div>');
				var label = '';
				for(var i=2; i<items[id].images.length; i++){ 
					if(getGallery($(this).attr('id'))+1 == i) label += '<a id="gal'+(i-1)+'" class="selected">'+(i-1)+'</a>&nbsp;';
					else label += '<a id="gal'+(i-1)+'">'+(i-1)+'</a>&nbsp;';
				}
				$('#wall').find('.articleimglabel').html(label);
				
				
				
				$('#wall').find('.articleimglabel').offset(new offset($('.articleimg').offset().left + $('.articleimg').width() - $('.articleimglabel').width() - 8,$('.articleimg').offset().top + $('.articleimg').height() - 31));
				
				initGallery(id);
			}
		});						
	});
}

function initItems(){
	$('.item').hover(overItem,outItem);
	$('.item').click(clickItem);
}

function setAvailableFilters(){
	for(i=0;i<5;i++){
		var active = false;
		$('#items').find('.item').each(function(){ if(items[getId($(this).attr('id'))].tags[i] != 'false') active = true; });
		if($('#filter'+i).attr('class') == 'regular'){
			if(!active){
				$('#filter'+i).attr('class','disabled');
				$('#filter'+i).unbind('click');
				$('#filter'+i).unbind('hover');
			}
		} else if($('#filter'+i).attr('class') == 'disabled'){
			if(active){
				$('#filter'+i).attr('class','regular');
				$('#filter'+i).hover(function() { highlightFiltering(getFilter($(this).attr('id'))); }, function(){ unhighlightFiltering() });
    			$('#filter'+i).click(function() { clickFilter(getFilter($(this).attr('id'))); });
			} 
		}
	}
}

function clickFilter(filter){
	if($('#article').size() != 0){
		$('#wallframe').scrollTo($('#article').height(),{duration:1000,onAfter:function(){
			document.location.hash = "";
			var articleHeight = $('#article').height();
			$('#article').remove();
			$('#selection').remove();
			$('#arrow').remove();
			$('#close').remove();
			initWall();
			$('.item').each(function(){
				$(this).offset(new offset($(this).offset().left,$(this).offset().top - articleHeight));
			});
			$('#wallframe').scrollTo(0,0,{duration:0,onAfter:function(){ applyFilter(filter); }});
		}});
		fadeInFlash();
	}else{
		if($('#wallframe').scrollTop() == 0) applyFilter(filter);
		else $('#wallframe').scrollTo(0,0,{duration:1000,onAfter:function(){ applyFilter(filter); }});
	}
}

function applyFilter(filter){
	if(filters[filter] == false){
		filters[filter] = true;
		$('.item').each(function() { if(items[getId($(this).attr('id'))].tags[filter] == 'false') $('#invisible').append($(this).remove()); });
		initWall();
		initItems();
		$('#filter'+filter).attr('class','selected');
	}else{
		filters[filter] = false;
		checkFilters();
		initWall();
		initItems();
		$('#filter'+filter).attr('class','regular');
	}
	setAvailableFilters();
	highlightFiltering(filter);
}

function initFilters(){
    if(filters.length == 0) for(i=0;i<5;i++) filters[i] = false;
	$('#filters a').hover(function() { highlightFiltering(getFilter($(this).attr('id'))); }, function(){ unhighlightFiltering() });
    $('#filters a').click(function() { clickFilter(getFilter($(this).attr('id'))); });
	setAvailableFilters();
}

function highlightFiltering(filter){
	$('.item').each(function() {
		if(items[getId($(this).attr('id'))].tags[filter] == 'true'){
			$(this).stop().fadeTo(200,1.0);
			$(this).append('<div id="itemtext" class="itemtext"><h1>'+items[getId($(this).attr('id'))].title+'</h1></div>');
			$(this).find('#itemtext').width($(this).find('#itemtext').width()+1);
			$(this).find('#itemtext').offset(new offset($(this).offset().left + $(this).width() - $(this).find('#itemtext').width() - 8,$(this).offset().top + $(this).height() - 31 - ($(this).find('#itemtext').height()-12)));
		}else{
			$(this).stop().fadeTo(500,0.4);
			if($(this).find('#itemtext').size() != 0) $(this).find('#itemtext').remove();
		}
	});
}

function unhighlightFiltering(){
	$('.item').each(function() {
		if($(this).find('#itemtext').size() != 0){
			$(this).find('#itemtext').remove();
			$(this).stop().fadeTo(500,0.4);
		}
	});
}

function resetFilters(){
	for(i=0;i<5;i++){
		filters[i] = false;
		$('#filter'+i).attr('class','regular');
	}
	checkFilters();
	initWall();
}

function checkFilters(){
	$('.item').each(function() {
		var move = true;
		for(i=0;i<5;i++) if(items[getId($(this).attr('id'))].tags[i] == 'false' && filters[i] == true){
			move = false;
			break;
		}
		if(move){
			items[getId($(this).attr('id'))].visible = true;
			$('#items').append($(this).remove());
		}
	});	
}

function initAWButton () {
	$("#reset").click(function() { resetAll(); });
}

function initArticle () {
	
		updateFlash(items[getArticle(document.location.hash)].issue);
		fadeOutFlash();
		
		var previousHeight = $('#wallframe').scrollTop();
	
		//remove previous article
		if($('#article').size() != 0){
			previousHeight -= $('#wall').find('#article').height();
			$('#wall').find('#article').remove();
			$('#selection').remove();
			$('#arrow').remove();
			$('#close').remove();
		}
		
		//update menu
		$('#filters').html($('#filters').html() + '<span id="arrow" class="yellow"> > </span><span id="selection" class="currentarticle">'+items[getArticle(document.location.hash)].title.toUpperCase()+'</span><a id="close" class="closearticle">&nbsp;&times</a>');
		
		$("#close").click(function() { resetAll(); });
		
		//place article
		placeArticle(getArticle(document.location.hash));
		initWall();
		//recalculate wall
		$('#article').offset(new offset($('#article').offset().left,$('#wall').offset().top + 60));
		
		//reset items interaction
		initItems();
		
		//reset filters
		//initFilters();
		
		$(this).oneTime(300, function() {
    	 	initWall();
		 	initItems();
  		});
	
		$(this).oneTime(1600, function() {
    	 	initWall();
		 	initItems();
  		});
		
		
	
}

function initArticles(){
	$('.articleclose').click(function (){ resetAll(); });
	$('.articlecrossclose').click(function (){ resetAll();});
}

function initIcons(){
	$('#icons').offset(new offset($('#icons').offset().left,max( $(window).height() - $('#icons').height() - 20 , $('#flash').offset().top + $('#flash').height() + 10 )));
	//alert(($('#flash').offset().top + $('#flash').height() + 10)+" ? "+($(window).height() - $('#icons').height() - 20));
	$('.icon').each(function(){
		$(this).offset(new offset(20 + 20*getIcon($(this).attr('id')), $(this).offset().top - 18));
	});
	$('.iconcolor').each(function(){
		$(this).offset(new offset(20 + 20*getColoricon($(this).attr('id')), $(this).offset().top - 18));
	});
	
}

function activateIcons(){
	$('.icon').hover(function(){
		$(this).stop().fadeTo(0,0);			   
	},function(){
		$(this).stop().fadeTo(0,1);		
	});	
}

function animateLoading () {
	if(loadingstate == 0){
		$('#loadingbottom').stop().fadeTo(1000, 0.5);
		loadingstate = 1;
	}else{
		$('#loadingbottom').stop().fadeTo(1000, 0.9);
		loadingstate = 0;
	}
	setTimeout(function () {animateLoading();}, 1100);
}

function setLoading(){
	$('body').css('overflow', 'hidden');
	$('#loadingtext').offset(new offset(0,$(window).height()/2 - $('#loadingtext').height()/2));
    //setTimeout(function () {an	imateLoading();}, 1100);
}

function removeLoading(){
	$('body').css('overflow', 'visible');
	$('#loading').remove();
}

function xml(){
    $('#wall').bind('xml',function(){load();});
	loadXML();
}

function load(){
    $('#wall').bind('loaded',function(){setup();});
	//setup();
	loadImages();
}

function setup(){
	initHeader();
	initLogo();
	if(document.location.hash) {
		initArticle();
	}
	else{
		initWall();
		initItems();
	}
	//initFilters();
	initAWButton();
	initIcons();
	activateIcons();
	removeLoading();
	initCopy();
}


function initCopy(){
	
	$("#copy").offset({ top: $(window).height()-$("#copy").height() - 15, left:$('#copy').offset().left });
	
}

//ready
$(document).ready(function(){
	setLoading();
    xml();
	
});

//resize
$(window).resize(function() {
	$('#wallframe').scrollTop(0);
	initHeader();
	initCopy();
	initWall();
	initItems();
	//initFilters();
	initIcons();
});
