/**
 * Init
 */

var aMenuActiveStates = new Array();
aMenuActiveStates['year'] = 0;
aMenuActiveStates['customer'] = 0;
aMenuActiveStates['design'] = 0;

var bAllowCar = true;
var oCarousel = false;


/**
 * Perform on DOM ready
 */	
	
$(document).ready( function() {
	

	$('img.hoverable').each(function()
			   {
			      $(this).qtip({
			    	  content: {
			    	  	prerender: false,
			    	  	text:'<a href="'+$(this).parent().attr('href')+'"><img src="'+jQuery(this).attr('rel')+'" /></a>'
			      		},
			    	   position: {
			    	      target: 'mouse',
			    	      adjust: {
			      			resize: true,
			      			screen: true
			      		},
			              corner: {
			               target: 'topRight',
			               tooltip: 'bottomLeft'
			            }
			    	      
			    	   },
			           hide: {
			               fixed: true, 
				           	effect: {
				           		type: 'show',
				           		length: 0
				           	}               
			            },
			           style: {
			                tip: {
			                corner: 'bottom left',
			                size: {
			            		x: 1,
			            		y: 1
			            	
			            	},
			                border: 1,
			                width: 300,
			                height: 300
			             },

		                name: 'light',            	
		            	width: '300px',
		            	height: '300px'
			            	
			            },
			           show: {
			            	delay: 0,            	
			            	solo: true,
			            	effect: {
			            		type: 'hide',
			            		length: 0
			            	}
			            }
			           
			         
			      });
			   });	
	
	
	if(bDoReload) {
		initCarousel();
		buildPortfolioNav(true);
		reloadForResolution();		
	} else {
		
	
		// Clean HTML
		$('div.col_600 span.usergenerated').each( function() {
			var sHtml = $(this).html();
			var sClean = $.htmlClean(sHtml,{allowedClasses: ["portfolio_props","allowclick"]});
			$(this).html(sClean);
		});
	
		$('div.col_300 span.usergenerated').each( function() {
			var sHtml = $(this).html();
			var sClean = $.htmlClean(sHtml,{allowedClasses: ["portfolio_props","allowclick"]});
			$(this).html(sClean);
		});
	
		
		// Init portfolio thumbnail carousel
		initCarousel();
		
		// Init portfolio menus
		if(!bNoPfNav) { 
			buildPortfolioNav(true);
		} else {
			buildPortfolioNav(false);
		}
		
		// Set window to max available screen size
		self.moveTo(0,0)
		self.resizeTo(screen.availWidth,screen.availHeight)
	
		// Regifure img on load
		refigure();
		
		// Send resolution
		sendResolution(false);
		
		// Reinitialise some stuff when the window is resized
		$(window).resize( function() { 
			refigure(); // Bg image
			setCarousel(false); // thumbscroller
			resetSlider(); // Slider
			sendResolution(false); // New resoltion
		});
			
		// Navigate through images (bg)
		$('#img_prev').click( function() {
			navBgImage(1,'back');
		});
	
		$('#img_next').click( function() {
			navBgImage(1,'forward');
		});	
		
		// Go to thumbnail overview
		$('#thumboverview').click( function() {
			
	//		if($('#content').hasClass('thumbs')) {
	//			var iWidth = $('#content').innerWidth() - 100 ;
	//		} else {
	//			var iWidth = $('#content').width() - 200 ;
	//		}
	//		var iHeight = $(window).height() - 28 - 60;
	//		
	//		
	//		if(!$.browser.mozilla) {
	//			//iHeight = iHeight-30;
	//		}
	//		document.location.replace(LINKROOT+'/view/portfolio/thumbs/'+iWidth+'x'+iHeight);
			document.location.replace(LINKROOT+'/view/portfolio/thumbs/');
			
		});
		
		// Show menu when mouse enters trigger
		$('a.nav').mouseover(function() {		
			sTrigger = $(this).attr('id').replace('nav_','');
			setActiveMenu(sTrigger);
			showMenu( $(this).attr('id').replace('nav_',''),false );
		})
		
		// Remove menu when mouse leaves trigger
		$('a.nav').mouseout(function() {
			sTrigger = $(this).attr('id').replace('nav_','');
			unsetActiveMenu(sTrigger);
			hideMenu( sTrigger,500,false );
		})	
		
		// Keep menu open when mouse on
		$('div.popupmenu').mousemove(function() {
			setActiveMenu( $(this).attr('id').replace('menu_',''),false );
		});
		$('a.nav').mousemove(function() {
			setActiveMenu( $(this).attr('id').replace('nav_',''),false );
		});	
		
		// Remove menu when mouse leaves
		$('div.popupmenu').mouseout(function(e) {
			 
			if ( $(e.target).hasClass("popupmenu")) { 
				var that = this;
				unsetActiveMenu( $(that).attr('id').replace('menu_','') );
				setTimeout( function() {				
					hideMenu( $(that).attr('id').replace('menu_',''),200,false );
				},200);
			}
	
		});
		
		// Add event to show slider
		$('div.slider').mouseover(function() {
			// Show slider
			if($(this).hasClass('slider_hidden')) {
				var that = this;
				var iWindowWidth = $(window).width();
				var iMargin = iWindowWidth-610;
			      $(this).animate({ 
			          marginLeft: iMargin
			        }, 500, function() {
			        	$(that).removeClass('slider_hidden');
			        	$(that).addClass('slider_visible');
			        } );
				
			} 
		})
		
		// Hide intro mov
		$('div#modal').click(closeIntro);
		
		// Add event to hide slide
		$('div.slider').click( function (e) {
			
			bAllow = true;
			// Safari bubbles onclick event all the way to the video..
			
			if(	!$(e.target).hasClass('allowclick')) {
				console.log(e.target);
				bAllow = false;
			}
		
			if($(this).hasClass('slider_visible') && bAllow) {
				var that = this;
			      $(this).animate({ 
			          marginLeft: '90%'
			        }, 500, function() {
			        	$(that).addClass('slider_hidden');
			        	$(that).removeClass('slider_visible');
			        } );			
			}
		})
		}
});


function setActiveMenu(sTrigger) {		
	aMenuActiveStates[sTrigger] = 1;
}

function unsetActiveMenu(sTrigger) {
	aMenuActiveStates[sTrigger] = 0;
}


/**
 * Function to scale background image
 */
var resizer = function() {
	 
	 
	var iWindowWidth = $(window).width();
	var iWindowHeight = $(window).height();

	var iImageWidth = $('#scaleimg').width();
	var iImageHeight = $('#scaleimg').height();
	var iOver = iImageWidth / iImageHeight;
	var iUnder = iImageHeight / iImageWidth;
	
	
	// Apply height to liquid height block
	var iLiquidHeight = iWindowHeight - 240;
	$('div.liquidheight').animate({maxHeight: iLiquidHeight});
	
	
	$('#scale').css({width: iWindowWidth, height: iWindowHeight});

	if( (iWindowWidth / iWindowHeight) >= iOver) {
		var iNewImgWidth = iWindowWidth;
		var iNewImgHeight = iUnder*iWindowWidth;
	} else {
		var iNewImgWidth = iOver*iWindowHeight;
		var iNewImgHeight = iWindowHeight;
	}
	
	
		
	
	$('#scaleimg').css({width: iNewImgWidth, height: iNewImgHeight});
	
	
	// Flash
	if(sYoutube != '') {
		
		var iFlashWidth = iWindowWidth;
		var iFlashHeight = iWindowHeight - 130;
		var iFlashDivHeight = iFlashHeight - 40;
		
		 $('div#youtube').flash(
			        { wmode : "transparent", allowfullscreen: true, width: iFlashWidth, height: iFlashHeight, flashvars: { autoplay:1, rel:0, fs:1, color1: '0x000000', color2: '0x000000', border: 0, loop:0} },
			        { version: 8, expressInstall: true , wmode: 'transparent' },
			        
			        function(htmlOptions) {
			            $this = $(this);
			            htmlOptions.src = 'http://www.youtube.com/v/'+$(this).attr('title')+'&ap=%2526fmt%3D22'; 
			            $this.html($.fn.flash.transform(htmlOptions));						
			        }
			    );	
		 
		 $('div#youtube').css({height: iFlashDivHeight, width:iFlashWidth });
		 $('div#scale').css({backgroundColor: '#000' });
		
	}	
	
	setTimeout( function() {
		// Diff
		iDiffWidth = (iNewImgWidth - iWindowWidth)/2;
		iDiffHeight = (iNewImgHeight - iWindowHeight)/2;
		
		iMarginLeft = iDiffWidth * -1;
		iMarginTop = iDiffHeight * -1;
	
		
		if(iMarginLeft < 0) {
			$('#scaleimg').css({marginLeft: iMarginLeft});	
		}
	
		if(iMarginTop < 0) {
			$('#scaleimg').css({marginTop: iMarginTop});	
		}	
		$('#scaleimg').show();
	},100);


	// Thumb flag
	var oThumbOffset = $('#thumbbutton').offset();
	$('#thumbflag').css({left: oThumbOffset.left , top: oThumbOffset.top-100 });
	if(!$('#thumbflag').hasClass('hidden')) {
		$('#thumbflag').show();
	}

	// Remove loading
	$('#wrapper').addClass('notloading');
}



/**
 * Refigures the div containing our BG image
 */
function refigure() {
	
	setTimeout(resizer,400);
	
}          




 /**
  * Hide menu
  */
function hideMenu(sTrigger,iTimeout,bForce) {
	// Hide
	setTimeout(function() {
		if(aMenuActiveStates[sTrigger] == 0 || bForce == true) {
			$('#menu_'+sTrigger).slideUp(250,function() {	
			});			
		}
	},iTimeout);
}




/**
 * Show menu
 */
function showMenu(sTrigger) {

	if(sTrigger == 'home') {
		return true;
	}
	
	// Find position for menu
	var oPos = $('#navpos_'+sTrigger).position();

	
	
	if(sTrigger != 'info' && sTrigger != 'news' ) {	
		var iLeft = oPos.left + 15;
	} else {
		var iLeft = oPos.left;
	}
	
	var iLeft = oPos.left + 15;
	
	
	// Tweak positioning
	
	var iWidth = $(window).width();
	
	switch(sTrigger) {
	case 'info':
		iLeft = iLeft + 15;
		break;
		
	case 'news':
		if(iWidth > 1400) {
			iLeft = iLeft + 30;
		} else {
			iLeft = iLeft + 20;
		}
		break;
		
	case 'year':
		if(iWidth > 1400) {
			iLeft = iLeft + 40;
		} else {
			iLeft = iLeft + 10;
		}
		break;
	}


	// Set menu in right postion
	$('#menu_'+sTrigger).css({left: iLeft});			

	if(sTrigger != 'info' && sTrigger != 'news') {
		setMenuMargin(sTrigger);
	} else {
		$('#menu_'+sTrigger+' div.popupitem').css({marginLeft: 5});
	}
	$('#menu_'+sTrigger).slideDown(500);
}

function setMenuMargin(sTrigger) {
	// Find margin for menu
	iMargin = $('#navpos_'+sTrigger).width()+5;
	
	$('#menu_'+sTrigger+' div.popupitem').css({marginLeft: iMargin});
	
	
}

function setPortfolioNavValue(sTrigger,sValue,oThat) {
	$('#nav_'+sTrigger).html ( $(oThat).html() );
	//if(sValue != 0) {
		$('#nav_'+sTrigger).addClass('active');
	//}
	
	setMenuMargin(sTrigger);
	
}

function hideCarousel() {

		$('#menu_nav_thumbs_wrap').animate({width: "1px"}, function() {
			

	});
}

 
function setPortfolio(sTrigger,sValue,oThat) {
	
	//hideCarousel();
	//hideMenu(sTrigger,10,true);
	setPortfolioNavValue(sTrigger,sValue,oThat);
	aPortfolioFilters[sTrigger] = sValue;
	
	if($(oThat).hasClass('faded')) {
		switch(sTrigger) {
		case 'customer':
			aPortfolioFilters['year'] = 0;
			aPortfolioFilters['design'] = 0;
			break;
		case 'year':
			aPortfolioFilters['customer'] = 0;
			aPortfolioFilters['design'] = 0;
			break;
			
		case 'design':
			aPortfolioFilters['year'] = 0;
			aPortfolioFilters['customer'] = 0;
			break;
		}
	}
	
	
	// Set new filters
	var sFilterString = 'year='+aPortfolioFilters['year']+'&customer='+aPortfolioFilters['customer']+'&design='+aPortfolioFilters['design'];
	
	document.location.href = LINKROOT+'/view/portfolio/detail/?'+sFilterString;
	//$.getScript(LINKROOT+'/do/portfolio/setfilters?'+sFilterString, function() { setCarousel(true); });
	
}


/**
 * Init the portfolio navigation (onload)
 * @return
 */
function buildPortfolioNav(bChangeValues) {
	
//	if(bIsCampain) {
//		sUrl = LINKROOT+'/do/portfolio/navigation/campain';
//	} else {
//		sUrl = LINKROOT+'/do/portfolio/navigation/';
//	}
//	 
//	$.getScript(sUrl, function() {
//	
		if(bChangeValues) {
		
			if(aPortfolioFilters['year'] != '') {
				setPortfolioNavValue('year',aPortfolioFilters['year'],$('#portfolio_year_'+aPortfolioFilters['year']));
			}
		
			if(aPortfolioFilters['customer'] != '') {
				setPortfolioNavValue('customer',aPortfolioFilters['customer'],$('#portfolio_customer_'+aPortfolioFilters['customer']));
			}
		
			if(aPortfolioFilters['design'] != '') {
				setPortfolioNavValue('design',aPortfolioFilters['design'],$('#portfolio_design_'+aPortfolioFilters['design']));
			}

			setCarousel(true);
			
		}
		
		setMenuMargin('year');
		setMenuMargin('design');
		setMenuMargin('customer');
		
		$('a.nav').show();
//	});	
	
}
 
 
 /**
  * Inits our carrousel (use just once)
  * @return
  */
function initCarousel() {
	$('#menu_nav_thumbs_right').mouseover( function () {
		clearInterval(oCarousel);
		oCarousel = setInterval( function() {
			var iPos = $('#menu_nav_thumbs_wrap').scrollLeft();
			iPos = iPos+10;		
			$('#menu_nav_thumbs_wrap').scrollLeft(iPos);
		},60);
	})
	
	$('#menu_nav_thumbs_left').mouseover( function () {
		clearInterval(oCarousel);
		oCarousel = setInterval( function() {
			var iPos = $('#menu_nav_thumbs_wrap').scrollLeft();
			iPos = iPos-10;		
			$('#menu_nav_thumbs_wrap').scrollLeft(iPos);
		},60);
	})
	
	$('#menu_nav_thumbs_left').mouseout( function () {
		clearInterval(oCarousel);
	});
	
	$('#menu_nav_thumbs_right').mouseout( function () {
		clearInterval(oCarousel);
	
	});	
	
}
 
 
/**
 * (Re)sets our thumbscroller
 * @return
 */
function setCarousel(bNoAnim) {
		
	if(bFirstView) {
		iTimeout = 1500;
	} else {
		iTimeout = 0;
	}
	
	
	setTimeout( function() {
		
		// Get width of containing td
		var iWidth = $('#nav_thumbs').width();
		
		
		// Substract width of left/right thingy
		iWidth = iWidth - $('#menu_nav_thumbs_left').width();
		iWidth = iWidth - $('#menu_nav_thumbs_right').width();
		
	
		
		
		if(!bNoAnim) {
			
			$('#menu_nav_thumbs_wrap').css({width: iWidth});
		} else {
			// Set container
			$('#menu_nav_thumbs_wrap').animate({width: iWidth}, function() {
				moveThumbnailSlider(iPos);
		 	});
		}
	
	},iTimeout);	
	
	
	
}
 
 
function resetSlider() {
	$('div.slider').each(function() {
		// Reset slider?
		if($(this).hasClass('slider_visible')) {
			var that = this;
			var iWindowWidth = $(window).width();
			var iMargin = iWindowWidth-600;
		      $(this).css({ 
		          marginLeft: iMargin
		        });
			
		} 
	})
	
}


function navBgImage(iSteps,sDirection) {
	switch(sDirection) {
		case 'back':
			iNextImage = iImageActive-1;
			iPos = iPos - 1;
			
			break
			
		case 'forward':
			iNextImage = iImageActive+1;
			iPos++;
			break;
	}
	
	if(iNextImage > iMaxImages) {
		
		// End of portfolio item reached, go to next (if any)
		if(sNextPf) {
			document.location.replace(sNextPf);
			return true;
		} else {
			return false;
		}
	} else if(iNextImage < 0) {
		
		// Beginning of portfolio item reached, go to previous (if any)
		if(sPrevPf) {
			document.location.replace(sPrevPf);
			return true;
		} else {
			return false;	
		}
	
		
	}
	
	
	
	iImageActive = iNextImage;
	
	// Set image
	var sImage = LINKROOT + '/' + aImages[ iNextImage ];
	
	// Set active thumb
	$('.thumblink').removeClass('active');
	$('#thumblink_'+iPos).addClass('active');
	
	$('#scaleimg').attr({src: sImage});
	refigure();
	
	
}


function moveThumbnailSlider(iPos) {
	
	iOffset = (32*iPos);
	$('#menu_nav_thumbs_wrap').scrollLeft(iOffset);
}


function showMovie(sMovie) {
	if (AC_FL_RunContent == 0) {
		alert("This page requires AC_RunActiveContent.js.");
	} else {
		AC_FL_RunContent(
			'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
			'width', '570',
			'height', '326',
			'src', LINKROOT+'/assets/default/flash/AFC_EmbedPlayer',
			'quality', 'high',
			'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
			'align', 'middle',
			'play', 'true',
			'loop', 'true',
			'scale', 'showall',
			'wmode', 'window',
			'devicefont', 'false',
			'id', 'AFC_EmbedPlayer',
			'bgcolor', '#ffffff',
			'name', 'AFC_EmbedPlayer',
			'menu', 'true',
			'allowFullScreen', 'true',
			'allowScriptAccess','sameDomain',
			'customSkinUrl',LINKROOT,
			
			'salign', '',
			'FlashVars', 'flvURL='+ LINKROOT+'/'+sMovie+'&customSkinURL='+LINKROOT+'/&autoStart=false&bufferSeconds=1&showBigPlayButton=true&showBufferingIndicator=true&showReplayButton=true&autoHideControls=true'
			); //end AC code
	}
	
}


function showIntroMovie(sMovie) {
	
	var iHeight = $(window).height();
	var iTop = (iHeight-500)/2;
	
	$('#intro_movie').css({marginTop: iTop+'px'});
	
	if (AC_FL_RunContent == 0) {
		alert("This page requires AC_RunActiveContent.js.");
	} else {
		AC_FL_RunContent(
			'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
			'width', '720',
			'height', '480',
			'src', LINKROOT+'/assets/default/flash/AFC_EmbedPlayer',
			'quality', 'high',
			'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
			'align', 'middle',
			'play', 'true',
			'loop', 'true',
			'scale', 'showall',
			'wmode', 'window',
			'devicefont', 'false',
			'id', 'AFC_EmbedPlayer',
			'bgcolor', '#ffffff',
			'name', 'AFC_EmbedPlayer',
			'menu', 'true',
			'allowFullScreen', 'true',
			'allowScriptAccess','sameDomain',
			'customSkinUrl',LINKROOT,
			'salign', '',
			'FlashVars', 'flvURL='+ LINKROOT+'/'+sMovie+'&customSkinURL='+LINKROOT+'/&autoStart=true&bufferSeconds=1&showBigPlayButton=true&showBufferingIndicator=true&showReplayButton=true&autoHideControls=true'
			); //end AC code
	}
	
}


function preLoad() {
	setTimeout(function() {
		var sHtml = '';
		$(aImages).each( function() {
			
			sHtml += '<img src="'+LINKROOT+'/'+this+'" />';
		});
		
		$('#preloader').html(sHtml);
	},500);
}


function sendResolution(bReload) {
	if(bNoPfNav) {
		return false;
	}

	if($('#content').hasClass('thumbs')) {
		var iWidth = $('#content').innerWidth() - 100 ;
	} else {
		var iWidth = $('#content').width() - 200 ;
	}
	var iHeight = $(window).height() - 28 - 60;
	
	
	
	
	if(!$.browser.mozilla) {
		//iHeight = iHeight-30;
	}
	
	if(bReload) {
		$.post(LINKROOT+'/do/frontend/setresolution',{width: iWidth, height: iHeight}, function() {
			window.location.reload(true);	
		});
		
	} else {
		$.post(LINKROOT+'/do/frontend/setresolution',{width: iWidth, height: iHeight});
	}
}



function reloadForResolution() {
	setTimeout(function() {
		
		sendResolution(true);
	},500);
}


function closeIntro() {
	$('#intro').html('&nbsp;');
	$('#intro').hide();
	$('#modal').fadeOut();
}


function homepageThumbs() {
	
	setTimeout( function() {
		var iWindowWidth = $(window).width();
		var iWindowHeight = $(window).height();
		
		
		// Just wrappers homepage
		if(iWindowWidth <= 1024) {
			var iMargin = (iWindowWidth/100)*12;
		} else if(iWindowWidth <= 1280) {
			var iMargin = (iWindowWidth/100)*10;
		} else {
			var iMargin = (iWindowWidth/100)*9;
		}
		var iJustWidth = (iWindowWidth - iMargin)/4;
		var iJustHeight = ((iWindowHeight)-230)/2;
		$('.just_wrapper').animate({width: iJustWidth+'px', height: iJustHeight+'px'}, function() {
			// Images for homepage
			$('div.just_wrapper').each( function() {
				var iWidth = iJustWidth-10;
				var iHeight = iJustHeight-30;
				
				$(this).find('.justmeta').each( function() {
					iThisHeight = $(this).height();
					iHeight = iHeight - iThisHeight;
				});
				
				$(this).find('img.justthumb').each( function() {
					var sSrc = $(this).attr('rel');
					
					
					
					var iImgWidth = Math.round( iWidth / 100)*100;
					var iImgHeight = Math.round( iHeight / 10)*10;
					
					
					var iMarginLeft = (iImgWidth - iWidth)/2;
					
					
					sSrc += '/'+iImgWidth+'/'+iImgHeight;
					$(this).attr({src: sSrc, height: iImgHeight, width: iJustWidth});
					
					// Set in center
					var iMarginLeft = iWidth
					
					// Set wrapper
					$(this).find('div.homepage_thumb').each( function() {
							$(this).attr({width: iWidth, height: iHeight});	
					});
				});
			});			
		});
		
		
	},700);
}
