$(function(){
	targetBlank();
	searchInput();
	
	initialGroupSize();
	
	hoverId();
	imageCycle();
	
	if($('#archive').size()>0) {
		adjustArchiveMenu();
	}

	if($('#artists').size()>0) {
		adjustArtistsMenu();
		masonParticipants();
	}
	
	if(1 | $('#archive').size()==0) {
		createBackgrounds();
	}
	
	var ws = $('body').attr('workspace');
	$('#menu').append('<div id="white-bg"><img src="' + ws + '/bg/white.png"/></div>');

	$(window).bind('resize load', function() {
		boxLayout($('#home.boxes'), $('#content').width());

		$('#archive .boxes').each(function() {
			boxLayout($(this), $(this).parent().width());
		});
		
		fitImages();
		columnizeSubArticles();
		
		if(1 | $('#archive').size()==0) {
			placeBackgrounds();
		}
	});

	
	collapseMenuOnScrollResize();
	bottomMenuOnScrollResize();

	$(window).trigger('resize');	
	//////////////////////////////////////
	//////////////////////////////////////
	//$('body').css('visibility', 'visible');
	//////////////////////////////////////
	//////////////////////////////////////

	archiveArtistJumpmenuOnClick();
	
});

function createBackgrounds() {
	var cnt=0;
	var cur=0;
	var max=3;
	if($('#archive').size()>0) {
		max = 7;
	}

	if($('#article').size()>0) {
		max = 0;
	}
	
	var base = $('body').attr('workspace');
	
	$('body').append('<div id="backgrounds"></div>');
	$('#backgrounds').css('overflow','hidden');	
	$('.glow').each(function() {

		$(this).attr('sync-id', cnt);
		
		var path = 'bg';
		if($('#archive').size()>0) {
			path = 'bgi';
		}
		
		var bg = $('<div><img src="'+base+'/'+path+'/'+cur+'.png"</div>');
		bg.attr('id', 'bg-sync-'+cnt );
		bg.css('position', 'absolute');		
		$('#backgrounds').append(bg);

		
		cnt++;
		cur++;
		
		if (cur>max) { 
			cur = 0;
		}
	})
}

function placeBackgrounds() {
	var cnt = 0;
	$('#backgrounds').width($(window).width());
	$('#backgrounds').height($(document).height());
	
	$('.glow').each(function() {

		var dt = $(this).offset().top;
		var dl = $(this).offset().left;
		var dw = $(this).outerWidth();
		var dh = $(this).outerHeight();

		var syncId = $(this).attr('sync-id');
		var bg = $('#bg-sync-'+syncId);
		var bgimg = bg.find('img');
		var bgw = dw*1.8;
		var bgh = dh*1.8;

		if($('#archive').size()>0) {
			bgw = dw*1.6;
			bgh = dh*1.6;
		}

		if($('#article').size()>0) {
			bgw = dw*1.7+100;
			bgh = dh*1.8+100;
		}


		bgimg.width(bgw);
		bgimg.height(bgh-30);
		
		var deltaw = Math.round((bgw - dw) /2)
		var deltah = Math.round((bgh - dh) /2)

		bg.css('top', (dt-deltah)+'px');
		bg.css('left', (dl-deltaw)+'px');
		
	});
}

function archiveArtistJumpmenuOnClick() {
	if($('#archive').size()>0) {
		$(window).hashchange( function(){
			var h = window.location.hash.substr(1);
			if(h!='') {
				//$('#archive-menu .shorthand a').removeClass('selected');
				//$('#shorthand-menu-'+h+ ' a').addClass('selected');
				$.scrollTo('#shorthand-'+h, 400);
			}
		});

		$(window).bind('load', function() {
			var h = window.location.hash.substr(1);
			if(h != '') {
				$.scrollTo('#shorthand-'+h, 400);
			}
		})	
		/*
		$('#archive-menu .shorthand a').bind('click', function(e) {
			e.preventDefault();
			var u = $(this).attr('href').substr(1);

			$.scrollTo('#shorthand-'+u, 400);
		})
		
		$(window).bind('scroll resize', function() {
			$('#archive .year h1:in-viewport').each(function(){
				window.location.hash = $(this).text();
			});
		});
		*/
	}
	
	if($('#jumpmenu').size()>0) {
		$('#jumpmenu a').bind('click', function(e) {
			e.preventDefault();
			var i = $(this).parent().index();
			$.scrollTo($('#article .body h2').eq(i-1),300);
		});
	}

	if($('#artists').size()>0) {
		$(window).hashchange( function(){
			h = window.location.hash.substr(1);
			if(h!='') {
				$.scrollTo('#shorthand-'+h, 400)
			}
		});
		$(window).bind('load', function() {
			$(window).hashchange();	
		})		
	}
}

function columnizeSubArticles() {
	$('.group').each(function() {
		if($(this).outerWidth()>500) {
			$(this).find('.sub.intro-article').css('width', '50%');
			$(this).find('.sub.intro-article').css('float', 'left');
		} else {
			$(this).find('.sub.intro-article').css('width', 'auto');
			$(this).find('.sub.intro-article').css('float', 'none');
		}
	});
}

function bottomMenuOnScrollResize() {

	$(window).bind('scroll resize load', function() {
		var wb = $('#white-bg');		
		if($(window).width()>600) {
			var t = $(window).height() - $('#menu-snap-to-bottom').height();
			$('#menu-snap-to-bottom').css('top', t-7);			
			$('#menu-snap-to-bottom').css('left', 0);	

			wb.show();
			wb.css('top', t-30);
			wb.css('left', -100);			
			wb.find('img').width(350);
			wb.find('img').height(120);

		} else {
			wb.hide();			
			//var t = $(window).height() - $('#menu-snap-to-bottom').height();
			//$('#menu-snap-to-bottom').css('top', 0);			
			//$('#menu-snap-to-bottom').css('left', Math.round($(window).width()/2)-5);
		}
		
				
	});
}

function collapseMenuOnScrollResize() {
	var navTotalHeight = $('#nav').outerHeight();
	var homeTotalHeight = $('#logo').outerHeight();
	var menuTotalHeight = $('#menu').outerHeight();
	var collapsed = false;
	var calendarHeight = $('#calendar').height();
	var btBarHeight = $('#menu-snap-to-bottom').height();

	$(window).bind('scroll resize load', function() {
		if($(window).width()>600) {
			if(navTotalHeight>$(window).height()) {
				$('#nav').css('position', 'absolute');
				$('#nav').css('top', '0')
				d = ( menuTotalHeight - homeTotalHeight - $(window).scrollTop() );
				
				if (d<=0) {					
					$('#calendar').css('position', 'fixed').css('top', homeTotalHeight+'px');				
										
					$('#logo').css('position', 'fixed');
					$('#logo').css('top', '0');

					if(!collapsed) {
						collapsed = true;					
//						$('#home').hide();
//						$('#home').fadeIn(200);

					}
				} else {
					collapsed = false;
					$('#calendar').css('position', 'static');
					$('#logo').css('position', 'static');
					
				}
			} else {
				collapsed = false;
				$('#nav').css('position', 'fixed');
				$('#calendar').css('position', 'static');
				//$('#calendar').css('position', 'fixed').css('top', ($(window).height()-calendarHeight-btBarHeight)+'px');
				$('#logo').css('position', 'static');
				
			}
		} else {//mobile
			collapsed = false;
			$('#nav').css('position', 'relative');
			$('#calendar').css('position', 'static');
			$('#logo').css('position', 'static');
			//$('#calendar').css('left', Math.round($(window).width()/2)-5);
			//$('#calendar').css('top', $('#menu-snap-to-bottom').height()+'px');
			

		}

	})

}

function adjustArtistsMenu() {
	$(window).bind('load resize', function() {
		$('#artists-menu').css('left', ($('#content').width()+130)+'px');
		$('#artists-menu').css('top', '5px');
	});
}

function masonParticipants() {
	$('#artists .participant').each(function() {
		var ih = $(this).find('.inner').outerHeight();
		var h = $(this).height();
		if(ih>h) {
			$(this).height(120);
			
		} else {
			
		}
	});

	$('#artists-list .participants').each(function() {
		$(this).masonry({
			itemSelector: '.participant',
			isFitWidth: true
		});			
	})
}

function adjustArchiveMenu() {
	$(window).bind('load resize', function() {
		$('#archive-menu').css('left', ($('#content').width()+130)+'px');
		$('#archive-menu').css('top', '5px');
	});
}

function initialGroupSize() {
	/* Initial size */
	var extraMargin = 90;
	var sizeFactor = 1.4;
	if($('#archive').size()>0) {
		extraMargin = 30;
		sizeFactor = 0.6;
	}
	$('.group').each(function() {
		var i = $(this).find('.intro-article:first img:first');

		if(i.size()<1) { //no image
			var weight = parseInt($(this).attr('weight'));
			var w = (weight*sizeFactor*100)+60;
			$(this).attr('origwidth', w);
			$(this).width(w);		

		} else {
			w = Math.round((i.width())+extraMargin);
			
			$(this).width(w);	
			$(this).attr('origwidth', w);
			
		}
	})
}

function hoverId() {
	// hover id
	$('.mhover').bind('mouseover', function() {
		id = $(this).attr('hoverid');
		$('.hoverid-'+id).addClass('hover');
	});
	
	$('.mhover').bind('mouseout', function() {
		$('.mhover').removeClass('hover');
	});
}

function searchInput() {
	$('#search-input').bind('focus', function() {
		if($(this).val() == 'Search...' || $(this).val() == 'Zoek...') {
			$(this).val('')
		}
	})

	$('#search-input').bind('blur', function() {
		if($(this).val() == '') {
			if($('body').attr('url-language') == 'en') {
				$(this).val('Search...')
			} else {
				$(this).val('Zoek...')
			}			
		}
	})
	$('#search-input').trigger('blur');
	
}

function fitImages() {
	$('img').each(function() {
		pw = $(this).parent().width();		

		if($(this).parent().is('a')) {

			pw = $(this).parent().parent().width();	
		}

		ow = parseInt($(this).attr('origwidth'));				
		if(ow > pw) {			
			r = ow/parseInt($(this).attr('origheight'));
			$(this).width(pw);
			$(this).height(pw/r);
			
		} else {
			$(this).width(ow);
			$(this).height($(this).attr('origheight'));			
		}
	})
	
	//image cycle
	var maxH =0;
	$('#image-cycle-inner img').each(function(){
		if($(this).height()>maxH) maxH = $(this).height();
	});
	$('#image-cycle-inner').height(maxH);
	var w = $('#image-cycle-inner').width();
	$('#image-cycle-inner img').each(function(){
		var d = Math.round((maxH-$(this).height())/2);
		$(this).css('top', d);
		var wd = Math.round((w-$(this).width())/2);
		$(this).css('left', wd);
	});
	
}

function zboundaries(els) {
	var l = parseInt(els.find('img:first').css('z-index'));
	var h = l;
	var topobj = els.find('img:first');
	var botobj = topobj;

	els.find('img').each(function(){
		z = parseInt($(this).css('z-index'));

		if(z<l) { 
			botobj = $(this);
			l=z;
		}
		if(z>h) {
			topobj = $(this);
			h=z;
		}
	});
	r = {'lowest': l, 'highest':h, 'topobj':topobj, 'botobj':botobj}
	return r;
}

function imageCycle() {
	
	/* Image cycle */
	var numImages = $('#image-cycle img').size();
	var imageZ = numImages+1000;
	$('#image-cycle img').each(function() {
		$(this).css('z-index', imageZ--)
	})
	
	$('#image-cycle img').hide();
	$('#image-cycle img:first').show();
	
	////setup
	$('#image-total').text(numImages);
	if(numImages<2) {
		$('#image-navigation').hide();
	}
	if(numImages<1) {
		$('#image-cycle-container').hide();
	}
	$('#image-previous').bind('click', function(e) {
		e.preventDefault();
		var b = zboundaries($('#image-cycle'));
		b.botobj.css('z-index', b.highest+1);
		
		b = zboundaries($('#image-cycle'));
		$('#image-cycle img').hide();
		b.topobj.show();

		$('#image-current').text(b.topobj.index()+1);
	});
	$('#image-next').bind('click', function(e) {
		e.preventDefault();
		var b = zboundaries($('#image-cycle'));
		b.topobj.css('z-index', b.lowest-1);

		b = zboundaries($('#image-cycle'));
		
		
		$('#image-cycle img').hide();
		b.topobj.show();
		$('#image-current').text(b.topobj.index()+1);			
	});
	////
	
	$('#image-cycle img').bind('click', function(e) {
		$('#image-next').trigger('click');
		
	});

	
	/* *********** */

}

function targetBlank() {
	$('a[href^="http://"]').each(function(){
		t = $(this);
		if(t.attr('href').search(/w139.nl/i) == -1 && t.attr('href').search(/localhost/i) == -1 && t.attr('href').search(/webtic.com/i) == -1 && t.attr('href').search(/10.37.129.2/i) == -1) {
			$(this).attr("target", "_blank");
		}
	});
}


function boxLayout(container, containerwidth) {


    c = 0;
    boxes = [];
	container.css('position', 'relative');
	
	var firstRowPackWidth = 0;
	var firstRowPackWidthLess = 0;	
	var toBePacked = [];
	
	var cnt = 1;
	container.find('> .box').each(function() {    
		var origwidth = parseInt($(this).attr('origwidth'));
		$(this).attr('packedwidth', origwidth);

		if(firstRowPackWidth<containerwidth) {
			firstRowPackWidthLess = firstRowPackWidth;
			firstRowPackWidth+=parseInt(origwidth) +(20*cnt);
			toBePacked.push($(this));
			cnt++;
		}
    });
//	console.log('firstRowPackWidthLess  ' + firstRowPackWidthLess);
//	console.log('firstRowPackWidth      ' + firstRowPackWidth);
//	console.log('containerwidth         ' + containerwidth);


	var percentWhiteSpace = (containerwidth - firstRowPackWidthLess  )/containerwidth;
	if(percentWhiteSpace > 0.28) {
		var excessPixels = firstRowPackWidth - containerwidth;
		var factor = firstRowPackWidth / containerwidth
		if(excessPixels>0) {
			$(toBePacked).each(function() {
				var ow = parseInt($(this).attr('origwidth'));

	//			console.log('dP' + dP)
//				$(this).attr('packedwidth', (ow/factor)-(16*$(toBePacked).size()));
				$(this).attr('packedwidth', (ow/factor));
			});

			
		}


	}

		
    container.find('> .box').each(function() {    
	
		var packedwidth = parseInt($(this).attr('packedwidth'));

		if(packedwidth > containerwidth-20) {
			$(this).width(containerwidth-20);
		} else {
			$(this).width(packedwidth);
		}

        boxes.push({ w: $(this).outerWidth(), h: $(this).outerHeight(), x:0, y:0, o: $(this) });
		$(this).css('position','absolute');

		safety = 1;
    });

    x = 0;
    y = 0;

    prevrow = null;
    row = null;

    while( boxes[c] != null ) {
        row = new Array();
        while( boxes[c] != null && (x + boxes[c].w) < containerwidth ) {

            row.push(boxes[c]);

            boxes[c].x = x;
            boxes[c].y = y;
            x += boxes[c].w;

            c++;
        };

        remaining = containerwidth - x;
        insert = Math.floor(remaining / (row.length+1));

		var maxrowheight = 0;
		var maxy=0;
        for(i=0; i<row.length; i++) {
            tx = row[i].x;
            ty = row[i].y;

			if(row[i].h > maxrowheight) {
				maxrowheight = row[i].h;
			}
			/*
			var overlap = 0;
			if(i>0) {
				overlap = 8;
			}*/

            //row[i].x = (remaining/2) + tx + ((i+1)*(insert*0)) - overlap*i;
			row[i].x = tx + ((i+1)*(insert*1));

            maxy = 0;
            if(prevrow != null) {
                found = false;
                for(p=0; p<prevrow.length; p++) {
                    if(prevrow[p].y + prevrow[p].h > maxy) {
                        maxy = prevrow[p].y + prevrow[p].h;
                    }

                    px1 = prevrow[p].x;
                    px2 = prevrow[p].x + prevrow[p].w;
                    tx1 = row[i].x;
                    tx2 = row[i].x + row[i].w;

                    if((px1 > tx1 && px1 < tx2) || (px2 > tx1 && px2 < tx2) || (px1 < tx1 && px2 > tx2)) {
                        h = prevrow[p].y+prevrow[p].h;
                        if(h > ty) {
                            ty = h;
                            found = true;
                        }
                    }
                }
                if(found) {
                   row[i].y = ty;
                } else {
                   row[i].y = maxy;
                }
            }
        }

        prevrow = row;
        
        y += 10;
        x = 0;

    }
    
	container.height(maxy + maxrowheight);
	container.width(containerwidth);
    //place
    for(i=0; i<boxes.length; i++) {
	
        boxes[i].o.css('left', boxes[i].x);
        boxes[i].o.css('top', boxes[i].y);
//        boxes[i].o.find('.txt').text(i);
    }
}


var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-10382711-5']);
_gaq.push(['_trackPageview']);

(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
