// pulsate plugin:
(function($) { $.fn.pulsate = function(options, callback) { options = $.extend({repeats: 3, duration: 210}, options); return this.each(function() { var duration = options.duration/options.repeats; for(var i=0;i<options.repeats;i++) { $(this).fadeOut(duration).fadeIn(duration);} $(this).queue(function() { $(this).dequeue(); if (callback) callback();});});}; })(jQuery);

// Core
jQuery(function($) {
	// All slideshows should modify image url's to request a size to fit their container. 
	$.fn.slideshow.defaults.beforeLoad = function(src) {
		var size = {width:$(this).width(), height: $(this).height()};
		src = src.replace(/(width=)(\d*)/, '$1'+size.width);
		src = src.replace(/(height=)(\d*)/, '$1'+size.height);
		return src;
	}
	Application.transitions = true;
	
	$.trace = function(message) {
		if (window.console && window.console.log) {
			window.console.log(message);
		} else {
			$('#debug').prepend(message+'<br/>');
		}
	}
	function init() {
		$(window).afterResize(function() {
			//@do something
			Application.resizeActiveImage();
		});
	
		// After logo is loaded the height should be set to auto. 
		$('#menu1_vol_img').load(function() { $(this).css({height: 'auto'});});	
		
		// Initiate tooltips. 
		$('#menu1 a[title!=""]').tooltip({width: '400px', delay: 1000,anchor: {left: 0, top: 0}, position: {left: 4, top: 1}, timeout: 10, style: {letterSpacing:0,textTransform:'none'}});
		$('.imgcontrol').not('#download_bttn').tooltip();
		$('#download_bttn').tooltip({filter:function() { return $('#downloadMenu').hide().html(); }});		
		$('.tooltip-content a').hover(function(){$(this).addClass('hover');}, function() {$(this).removeClass('hover');});
		
		// mode2 slideshow arrows
		$('#mode2-slideshow').each(function() {
			var s = $(this);
			var sl = $('#mode2-slideshow-left');
			var sr = $('#mode2-slideshow-right');
			var offset = 32;
			var arrowHover=false;
			var side=0;
			var timer;
			function positionArrows() {
				//if (Application.IE7)
				//	return;
				var sp = s.position();
				sl.css({left: s.width()/2-s.find('.current').width()/2-offset+'px'});
				sr.css({left: s.width()/2+s.find('.current').width()/2+offset+'px'});
				sl.css({top: s.height()/2-sl.height()/2+'px'});
				sr.css({top: s.height()/2-sr.height()/2+'px'});
			}
			function determineSide(ev) {
				//if (Application.IE7)s.css({border: 'solid 1px #fff'});
				var sp = s.position();
				if ((ev.pageX -  sp.left) < s.width()/2) {
					if (side != -1) {
						side = -1;
						//if (Application.IE7) return;
						sl.fadeIn(300);
						sr.fadeOut(300);
					}
				} else {
					if (side != 1) {
						side = 1;
						//if (Application.IE7) return;
						sr.fadeIn(300);
						sl.fadeOut(300);
					}
				}
			}

			s.mouseenter(function(ev) {
				if (arrowHover || Application.mode == 1)
					return;
				positionArrows();
				determineSide(ev);
				sl.add(sr).hover(function() {
					arrowHover=true;
				}, function() {
					arrowHover=false;
				});
				s.mousemove(function(ev) {
					positionArrows();// It seems in IE, we should reposition. 
					determineSide(ev);
				});
				s.mouseleave(function() {
					setTimeout(function() {
						if (arrowHover) 
							return;
						sl.fadeOut(300);
						sr.fadeOut(300);
						s.unbind('mousemove mouseleave slideshow:beginTransition.arrows slideshow:endTransition.arrows');
						sl.unbind('hover');
						sr.unbind('hover');
				//		if (Application.IE7) s.css({border: 'none 0px'});
					}, 100);
				});
				s.bind('slideshow:beginTransition.arrows', function() {
					sl.fadeOut(300);
					sr.fadeOut(300);
				});
				s.bind('slideshow:endTransition.arrows', function() {
					positionArrows();
					if (side == -1) {
						sl.fadeIn(300);
					} else if(side == 1) {
						sr.fadeIn(300);
					}
				});
			});
			s.add(sl).add(sr).click(function(ev) {
				if (activeImage && activeImage.get(0).__type == 'movie') {
					var pos = activeImage.offset();
					if (ev.pageX > pos.left && ev.pageX < pos.left + activeImage.width() &&
						ev.pageY > pos.top && ev.pageY < pos.top + activeImage.height() ) {
						return;
					}
				} 
				if (side == -1) {
					s.trigger('slideshow:stop');
					s.trigger('slideshow:prev');
				} else if (side == 1) {
					s.trigger('slideshow:stop');
					s.trigger('slideshow:next');
				}
			});
		});
		
		// Handle image download (tmp solution)
		$('.download-current-image').live('click', function(ev) {
			ev.preventDefault();
			var url = $('#menu2-image-download-url').val();
			$(document.body).trigger('tooltip:hide');
			if (url) { $(this).pulsate(); location.href = url;}
		});
		// Handle portfolio download (tmp solution)
		$('.download-current-portfolio').live('click', function(ev) {
			ev.preventDefault();
			var url = $('#menu2-pdf-download-url').val();
			$(document.body).trigger('tooltip:hide');
			if (url) {$(this).pulsate();location.href = url;}
		});
		
		// Listen to the maximize link
		$('#maximizeLink').click(function(ev) {
			Application.changeMode(3); 
		});
		$('#minimizeLink').click(function(ev) {
			Application.changeMode(2); 
		});
			
		// Listen to the favorites links
		$('#addToFavoritesLink').click(function(ev) {
			var image = Application.getCurrentThumbnailImageId();
			if (!Application.isFavorite(image)) {
				Application.addToFavorites(image);
				$('#addToFavoritesLink').hide();
				$('#removeFromFavoritesLink').show();
			}
		});
		// Listen to the favorites links
		$('#removeFromFavoritesLink').click(function(ev) {
			var image = Application.getCurrentThumbnailImageId();
			if (Application.isFavorite(image)) {
				Application.removeFromFavorites(image);
				$('#addToFavoritesLink').show();
				$('#removeFromFavoritesLink').hide();
			}
		});
		
		// Handle history pop
	    $(window).history(function(e, currentHash, previousHash) {
	    	handleLink(currentHash, previousHash);
	    });
	    
	    // Handle histrory push	
	    $(window).historyadd(function(e, currentHash, previousHash) {
			location.hash = '#'+currentHash;
	    	handleLink(currentHash, previousHash);
	    });

		// Listen to all links
		$('a.ajax, span.ajax a').live('click', function(ev) {
			var href=this.href;
			if ($(this).hasClass('external') || 'javascript:void(0)' == href || ev.button!=0 || ev.metaKey)
				return;
								
			var base = $('base').attr('href').replace(/(.*\/\/.*?\/)(.*)/, '$1');
			var path = href.replace(base, '');
			if (Application.initialLink && Application.mode ==1) {
				location.href = (Application.hrefPrefix ? Application.hrefPrefix : '/') + '#'+path;
			}
			ev.preventDefault();
			
			$('#mode2-slideshow-left').add('#mode2-slideshow-right').fadeOut(300);
			
			if (Application.mode==3) {
				Application.changeMode(2);
				return;
			}
			
			
			$('#transition').queue(function() {
				$(this).dequeue();
				$('#divContentHeader').fadeOut(300);	
/*				if (path.substr(0, 4) == 'news' && path != 'news-signup') {
					var current = $.history.getCurrent();
					if (current.substr(0, 4) == 'news' && current != 'news-signup') {
						var id = path.replace(new RegExp('/', 'g'), '-');
						var pos = $('#'+id).position();
						if (pos) {
							$('#divContent').scrollTo($('#'+id), {duration:800, axis:'y'});
							handleLink(path, current, true);
							return;
						} 
					}
				}*/
				$.history.add(path);
			});
		});

		// Check the initial link
		var path = $.history.getCurrent();
		
		if (!path && Application.initialLink) {
			Application.mode = 1;
			handleLink(Application.initialLink);
			
			//location.href=$('base').attr('href')+'/'+'#'+Application.initialLink;
		}else if (path && path != 'index') {
			Application.transitions = false;
			Application.mode = 1;
			$.history.add(path);
			handleLink(path);
			$('#menu1').show();
		} else {
			Application.changeMode(1);
			path = 'index';
			handleLink(path);
			$.history.add(path);
		}
	}
	    
    function handleLink(path, additionalData, noajax) {
    	try {
		if (!path) 
			path = 'index';
		var link = $('a[href="/'+path+'"]');
		
		var data = 'ajax=1&test2=1';
		if (typeof additionalData == 'object') {
			data += '&'+$.param(additionalData);
		}else if (typeof additionalData == 'string') {
			data += '&' + additionalData;
		}
		if (link.length) {
			var speed = 500 * Application.transitions;
			Application.transitions = true;
			
			if (path=='index') {
				link.nextAll('ul').find('li').removeClass('open').children('ul').slideUp(speed);
			} else {
				var li = $(link).parents('li').eq(0);
				li.addClass('open').siblings().removeClass('open').children('ul').slideUp(speed);
				li.parents('li').addClass('open').siblings().removeClass('open').children('ul').slideUp(speed);
				li.children('ul').slideDown(speed).find('ul').removeClass('open').slideUp();
				li.parents('li').children('ul').slideDown(speed);
			}
		}
		if (noajax) return;
		} catch(e) {
			alert(e);
			debugger;
		}
		
		
		$.ajax({url: $('base').attr('href')+Application.hrefPrefix + path+'/', type: 'POST', data: data, complete: function(t) {
			try {
				var response = eval('('+t.responseText+')');
				$(response).each(function() {
					switch(this.type) {
						case 'update': 
							switch (this.selector) {
								case 'title':
									document.title = this.data;
									break;
								default:
									var elem = $(this.selector);
									var data = this.data;
									if (this.fade) {
										elem.fadeOut(300, function() {
											elem.html(data).fadeIn(300);
										});
									} else {
										elem.html(data);
									}
									break;
							}
							break;
						case 'eval':
							try {
								eval(this.data);
							} catch(e) {alert(e);}
							break;
						case 'pauseMainSlideshow': 
							$('#mainSlideshow').trigger('slideshow:pause').fadeOut();
							break;
						case 'continueMainSlideshow': 
							$('#mainSlideshow').trigger('slideshow:continue');
							break;
						case 'mode1content':
							var elem = $('#divContent');
							var data = this.data;
							elem.fadeOut(300, function() {
								elem.html(data).fadeIn(300);
							});
							break;
						case 'artistpreviews':
							Application.artistPreviews(this.images);
							break;
						case 'error':
							alert(this.data);
							break;
						case 'mode':
							Application.changeMode(this.data);
							break;
						default:
							alert('System error - Unknown response type: '+this.type);
							break;
					}
				});
				/*Google analytics pagetracker. */
				Application.pageTracker._trackPageview('/'+path)
			} catch(e) {
				alert(e);
				alert('An unknown system error occured\n\n'+t.responseText);
			}
		}});
    }
    Application.ajax = handleLink;
    
    Application.loadImage=function(src, onLoaded) {
    	var img = new Image();
   		var onload = function() { onLoaded(img); };
 		try {
			img.onload = onload;
 		} catch(e) {
			img.onLoad = onload;
 		}
    	img.src = src;
    };
    
    
	
	Application.getCurrentThumbnailImageId = function() {
		var image = 0;
		if (Application.mode == 2) {
			var img = $('#menu2-thumbs img.selected');
			if (img.length == 1) {
				var src = img.attr('src');
				image = parseInt(src.replace(/.*vol_(\d+)_tn.*/, '$1'));
			}
		}
		return image;
	};
	
	Application.isFavorite = function(image) {
		var favorites = $.cookie('jsfavorites');
		favorites = favorites || '';
		favorites = "|"+favorites+"|";
		var inFavorites = new RegExp('\\|'+image+'\\|');
		return inFavorites.test(favorites);
	}
	Application.addToFavorites = function(image) {
		var favorites = $.cookie('jsfavorites');
		favorites = favorites || '';
		favorites += !favorites ? image : '|'+image;
		$.cookie('jsfavorites', favorites, { expires: 999, path: '/'});
	}
	Application.removeFromFavorites = function(image) {
		var favorites = $.cookie('jsfavorites');
		favorites = favorites || '';
		favorites = favorites.split('|');
		for (var i in favorites) {
			if (favorites[i] == image) {
/*				$('#mode2-slideshow img').eq(i).fadeOut(300, function() {
					$(this).remove();
				});*/
				favorites.splice(i, 1);
				break;
			}
		}
		favorites = favorites.join('|');
		$.cookie('jsfavorites', favorites, { expires: 999, path: '/'});
		
		if ($('#menu2top a[href=/favorites]').hasClass('selected')) {
			var img = $('#menu2-thumbs img.selected');
			$('#mode2-slideshow .current').fadeOut(300).addClass('deleted');
			img.addClass('deleted').fadeOut(300).addClass('deleted');
			$('#mode2-slideshow').trigger('slideshow:next');
		};
	}
	var activeImage=null;
	var resizing=false;
	var resizeSeqNr = 0;
	Application.setActiveImage = function(img) {
		activeImage = $(img);
		if (resizing) {
			resizing = false;
		}
	}
	Application.resizeActiveImage = function(options, callback) {
		options = options || {};
		callback = callback || function(){};
		if (activeImage) {
			var img = activeImage;
			if (img.get(0).__type == 'movie') {
				var containerSize = {width:img.parent().width(), height: img.parent().height()};
				var height = options.height ? options.height-32 : containerSize.height; 
				var width = options.width ? options.width : containerSize.width; 
				img.attr('height', height); 
				img.attr('width', width); 
				img.children('embed').attr('height', height); 
				img.children('embed').attr('width', width); 
				img.css({width: width+'px', height: height+'px'});
				callback(true);
				return;
			}
			
		
			try {
				var seqNr = ++resizeSeqNr;
				var src = img.attr('src');
				var pos = img.position();
				var size = {width:img.width(), height: img.height()};
				var containerSize = {width:img.parent().width(), height: img.parent().height()};
	//			var hAlign = (containerSize.width-size.width-pos.left) / (containerSize.width -size.width);
	//			var vAlign = (containerSize.height-size.height-pos.top) / (containerSize.height -size.height);
				var hAlign= 0.5;
				var vAlign= 0;
				if (img.parent().attr('id') == 'mode2-slideshow')
					vAlign = 0.5; 
					
			//	alert(size.width+', '+size.height+': '+src);
				img.css({
					top:pos.top+'px', 
					left:pos.left+'px', 
					width: size.width+'px', height: size.height+'px'
				});
				
				var height = options.height ? options.height : containerSize.height; 
				var width = options.width ? options.width : containerSize.width; 
				var newSrc = src.replace(/width=\d+/, 'width='+width)
					.replace(/height=\d+/, 'height='+height);
				
				Application.loadImage(newSrc, function(newImg) {
					if (activeImage && img.attr('src') == src && seqNr == resizeSeqNr) {
						var queue = $(this);
						img.attr('src', newImg.src);
						img.animate({
							top:vAlign*(height-newImg.height), 
							left:hAlign*(width-newImg.width), 
							width: newImg.width, height: newImg.height
						}, {duration: 300, complete:function() {
							callback(true);
							img.css({width: 'auto', height: 'auto'});
						}});
					} else {
						callback(false);
						img.css({width: 'auto', height: 'auto'});
					}
				});
			} catch(e) {
				callback(false);
			}
		}
	}
	Application.clearQueue = function(queueName) {
		$(document).queue(queueName, []);
	}
	Application.queueImageLoad = function(queueName, src, callback) {
		$(document).queue(queueName, function() {
			Application.loadImage(src, function() {
				if (callback) {
					callback.apply(this, arguments);
				}
				$(document).dequeue(queueName);
			});
		});
	}
	
	
	var bioEnabled = false;
	var bioVisible = false;
	Application.enableBio = function(enable) {
		var enabled = bioEnabled;
		bioEnabled = enable === 'undefined' ? true : enable;
		
		$('#menu2-biolink').css({visibility:'visible', opacity:0});		
		
		if (enabled && !bioEnabled) {
			$('#menu2-artistblock').unbind('mouseenter').unbind('mouseleave');
		} else if (!enabled && bioEnabled) {
			$('#menu2-artistblock').hover(function() {

				$('#menu2-biolink').stop(true).css({visibility:'visible'}).fadeTo(300, 1);
				
				}, function() {
					$('#menu2-biolink').stop(true).fadeTo(300, 0);
				}
			);
		}
	}
	Application.showBio = function() {
		var w = $('#mode2-slideshow').width();
		var h = $('#mode2-slideshow').height();
		$('#divContent .height-100').css({height: h+'px'});
		$('#divContent .width-100').css({width: w+'px'});
		$('#divContent .width-50').css({width: w*0.5+'px'});
		$('#divContent .width-40').css({width: w*0.4+'px'});
		$('#divContent .width-25').css({width: w*0.25+'px'});
		$('#divContent .margin-left-10').css({marginLeft: w*0.1+'px'});		
		$('#divContent .margin-left-25').css({marginLeft: w*0.25+'px'});		
		
		if ($('#bioimage').length) {
			$('#bioimage').one('load', function() {
					$(this).fadeIn(500);
				}
			).attr('src', $('#bioimage').attr('src').replace(/(width=)\d*(.*?height=)\d*/, '$1'+w*0.4+'$2'+h) )
			 .hide();
		}
		
		$('#divContent').css({width: w+'px', height: h+'px', left: '32px', top: '32px'}).fadeIn(500);
		$('#mode2-slideshow').fadeOut(500).trigger('slideshow:stop');
		bioVisible = true;
	}
	Application.hideBio = function() {
		if (bioVisible) {
			$('#divContent').fadeOut(500);
			$('#mode2-slideshow').fadeIn(500);
			bioVisible = false;
		}
	}
	
	
	init();	
});