var mod;
var loginIsOpen=false;
var footerIsOpen=false;
var loginBlockHeight;
var loginFlag = false; 				//if user details/password are incorrect login stays open

var bodyid;
var hashparams;

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

var setHashParams = function()
{
	hashparams = {};
	if(window.location.hash.length)
	{
		var tmp = window.location.hash.split('#')[1];
		var arr = tmp.split('&');
		arr.each( function(param)
		{
			if(param.indexOf('=') != -1)
			{
				var params = param.split('=');
				hashparams[params[0]] = params[1];
			}
		});
	}
}

var appscripts = function()
{
	bodyid = $$('body').first().id;
	setHashParams();
	
	viewPortSizing();

	peopleObserve();
	
	Event.observe( document.onresize ? document : window, "resize", function() {
		footerMarginFix();
		viewPortSizing();
	});
	
	if($$('.moodboard-lightwindow').length)
	{
		moodboard_lw_links_init();
	}
	
	if ($$('.case-studies-switchimg').length) 
	{
		loadCaseStudyImageSwitching();
	}
	
	if($('flashcontents'))
	{
		$$('body').first().style.backgroundPosition = 'center -1000px';
	}

	$$('#login-block .form-error' ).each(function(e){ 
		loginFlag = true;
	});

	if ($('login-block') && !loginFlag) {
		$('login-block').down('div.body').hide();   // hide login block		
	}
	
	$$('#login-block.open').each( function()
	{
		openLoginBlock();
	});
	
	if ($('xauth_login-credential'))
	{
		loginBlockInit();
	}

	if ($('archive-list'))
	{
		initiliseBlogArchive();
	}
	
	// if ($('gallery_view')) {
	// 	gal_window_factory();
	// };
	
	if($('xauth_register-company_type') && $('xauth_register-company_type-input'))
	{
		$('xauth_register-company_type-input').hide();
		$('xauth_register-company_type').observe('change', function() {
			if($F('xauth_register-company_type').indexOf('Other') != -1)
			{
				$('xauth_register-company_type-input').show();
			}
			else
			{
				$('xauth_register-company_type-input').value = '';
				$('xauth_register-company_type-input').hide();
			}
			
		}, false);
	}
		
	if ($('popup-heads'))
	{
		var puh = $('popup-heads');		
		puh.setStyle({'position':'relative'});
	}
	
	if ($('popup'))
	{
		var pu = $('popup');						// set popup/down + overlay
		var pud = pu.getDimensions();
		pu.setStyle({display:'none', height:'auto', 'overflow':'hidden', 'position':'relative', 'z-index':'2001'});
		initPopup();
	}			 

	if($('replaybtn'))
	{
		$('replaybtn').observe('click', function(e) {
			$('replaybtn').hide();
			eraseCookie( bodyid+'_flash' );
			hideCopy();
			e.stop();
		}, false);
	}
	
	if($('skipbtn'))
	{
		$('skipbtn').observe('click', function(e) {
			$('skipbtn').hide();
			document.fire('animation:complete');
			e.stop();
		}, false);
	}

	hideMain(false);									// function for hiding main content block

	initlw();									// init gallery popups
	
	gallery_hover();							// gal hovers setup
	galleries_hover();							// Title Hovers
	
	footerMarginFix();
};

var footerMarginFix = function()
{
	if ($('sticky'))
	{
		//viewport height
	  	var myHeight = 0;
	  	if( typeof( window.innerHeight ) == 'number' ) {
	    	//Non-IE
	    	myHeight = window.innerHeight;
	  	} else if( document.documentElement && document.documentElement.clientHeight ) {
	    	//IE 6+ in 'standards compliant mode'
   			myHeight = document.documentElement.clientHeight;
  		} else if( document.body && document.body.clientHeight ) {
			//IE 4 compatible
		    myHeight = document.body.clientHeight;
		}
		// window.alert( 'Height = ' + myHeight );
		
		//page height
		if (window.innerHeight && window.scrollMaxY) {// Firefox
			yWithScroll = window.innerHeight + window.scrollMaxY;
			xWithScroll = window.innerWidth + window.scrollMaxX;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			yWithScroll = document.body.scrollHeight;
			xWithScroll = document.body.scrollWidth;
		} else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
			yWithScroll = document.body.offsetHeight;
			xWithScroll = document.body.offsetWidth;
	  	}
		arrayPageSizeWithScroll = new Array(xWithScroll,yWithScroll);
		// alert( 'The viewport height is ' + myHeight + ' and the document height is' + yWithScroll );

		//compare
		if (myHeight >= yWithScroll || $('flashcontent-home') || $('flashcontents')) {
			$('sticky').style.marginTop = '-79px';
		} else {
			$('sticky').style.marginTop = '-60px';
		}
	}	
};

var peopleObserve = function()
{
	var elems = $$('a.people-hover');

	//to store z-index value of the element before it's replaced
	var tmp_ZI = elems.length + 21;

	elems.each(function(el) {
		el.observe('mouseover', function(e) {
			//give ever-decreasing z-index values to each li - for IE. - put here for robust-ness. . . 
			var zi = elems.length + 21;
			var polar = $$('li.polaroid');
			polar.each(function(ziel) 
			{
				ziel.style.zIndex = zi--;
			});

			elems.each(function(ele){
				ele.next().hide();
				if (ele.next().hasClassName('to-front')) {
					ele.next().removeClassName('to-front');
				}
			});
			//store the z-index for later and replace it with 99
			tmp_ZI = el.up('li.polaroid').getStyle('z-index');
			el.up('li.polaroid').style.zIndex = elems.length + 22;

			el.next().addClassName('to-front');
			el.next().show();
			e.stop();
		});
	});
	
	$$('a.overlay').each(function(el) {
		el.observe('mouseout', function(e) {
			el.hide();
			if (el.hasClassName('to-front')) {
				el.removeClassName('to-front');
			}
			//replace original z-index value
			el.up('li.polaroid').style.zIndex = tmp_ZI;
			e.stop();	
		});
	});
};

var initiliseBlogArchive = function()
{
	$$('#archive-list div.archive-content').each(function(el)
	{
		el.hide();
	});
	
	addClickEvents();
};

var addClickEvents = function()
{
	var arrDowns = 	$$('#archive-list span.arr-down');
	arrDowns.each(function(el)
	{
		el.observe('click', function(e)
		{
			e.stop();
			var elm = e.element();
			elm.next('.archive-content').toggle();
		});
	});
};

var removePWbg = function()
{
	$('xauth_login-credential').setStyle({
		backgroundImage:'none'
	});
};

var loginBlockInit = function()
{
	$('xauth_login-credential').observe('blur', function()
	{
		if ($F('xauth_login-credential').length > 0)
		{
			removePWbg();
		} else {
			$('xauth_login-credential').setStyle({
				background:'#787878 url(/staticfiles/img/password-field-bg.gif) no-repeat 3px 0'
			});
		}
	});
	
	$('xauth_login-credential').observe('focus', function()
	{
		if ($F('xauth_login-credential').length == 0)
		{
			removePWbg();
		}
	});

	if ($('xauth_login-email')) 
	{
		$('xauth_login-email').observe('change', function()
		{
			if ($F('xauth_login-email') != 'Email' && $F('xauth_login-email').lenght > 0)
			{
				removePWbg();
			}
		});	

		$('xauth_login-email').observe('focus', function()
		{
			if ($F('xauth_login-email') == 'Email')
			{
				$('xauth_login-email').value = '';
			}
		});

		$('xauth_login-email').observe('blur', function()
		{
			if ($F('xauth_login-email').length == 0)
			{
				$('xauth_login-email').value = 'Email';
			}
		});
	}
};

var getDocumentHeight = function() 
{
	var body = document.body;
	var innerHeight =	((self.innerHeight != undefined)&&!isNaN(self.innerHeight))?self.innerHeight:0;

	if ( ! document.compatMode || document.compatMode=="CSS1Compat")
	{
		return Math.max(body.offsetHeight,
		document.documentElement.clientHeight,
		document.documentElement.scrollHeight);
	}
	
	return Math.max(body.scrollHeight, body.clientHeight);
};

var initPopup = function()
{
	// alert('login = '+loginIsOpen);
	// alert('footer = '+footerIsOpen);
	if ($('popup-footer-overlay'))
	{
		if (loginIsOpen==false && footerIsOpen==false)
		{
			closeOverLay(); 
		}
	}
	
	if (loginIsOpen==true && footerIsOpen==true)   					// if for some reason both login and footer are open, on next pass through initPopup, all will reset 
	{
		appscripts(); closeLogin(); closeFooter();	closeOverLay();
	}

	// setup - 3 arguments to be carried through functions
		// not to be passed on
		var footer = $('footer').getHeight();
		var pageHeight = getDocumentHeight(); // (document.height !== undefined) ? document.height : document.body.offsetHeight; 
	var mc = $('main-content');
	var headerH = ($('header').getHeight())+($('logo-head').getHeight());
	var oh = pageHeight-(headerH+footer);	
	// end setup

	if ($('login-block')) 
	{
		var la = $('login-block');

		if (la.hasClassName('closed') && loginIsOpen==false) 
		{
			var larr = $('login-arrow');
			la.observe('click', function(e) 
			{
				if (window.scrollbars) 
				{
					window.scrollbars.visible = (window.scrollbars.visible)? false:true;
				}

				Event.stopObserving(la, 'click');
				e.stop();

				if (footerIsOpen==true)  													// close other or place overlay 
				{
					closeFooter();
				} else {
					overLay(mc, headerH, oh);
				}

				expandPopup(mc, headerH, oh, true);											// open

				if (loginIsOpen==false) { loginIsOpen=true; }

				initPopup();
			}, false);
		}
	}

	var sticky = $('sticky');

	if (sticky.hasClassName('closed') && footerIsOpen==false)
	{
		var pu = $('popup');															// footer('sticky')
		var puh = $('popup-heads');	

		$('popup-heads-trigger').observe('click', function(e)
		{
			if (window.scrollbars) 
			{
				window.scrollbars.visible = (window.scrollbars.visible)? false:true;
			}
			
			Event.stopObserving('popup-heads-trigger', 'click');
			e.stop();

			if (loginIsOpen==true)			 											// close other or place overlay 
			{
				closeLogin();	
			} else { 
				overLay(mc, headerH, oh); 
			}
			
			expandPopup(mc, headerH, oh, false);										// open
			if (footerIsOpen==false) { footerIsOpen=true; }
			
			sticky.removeClassName('closed');											// some classes
			pu.addClassName('open');
			puh.addClassName('open');			
			
			addClickObserver();															// add 'close' observer	
			initPopup();
		}, false);
	}
};

var overLay = function(mc, headerH, oh)
{
	// alert('func overLay');	
	if (window.scrollbars) {
		window.scrollbars.visible = (window.scrollbars.visible)? false:true;
	}

	var overlay = Builder.node('div', { id : 'popup-footer-overlay', 'class' : 'popup-footer-close','style' : 'position: absolute; background: rgba(0,0,0, 0.7); opacity: 0.7; filter: alpha(opacity=70); z-index: 1001' });
	// overlay.clonePosition(mc, {setLeft:true, setTop:true, setWidth:false, setHeight:false});
	overlay.setStyle({ 'width': 100 + '%', 'top' : headerH + 'px' });

	mc.insert(overlay);
	new Effect.Morph(overlay, 
		{style:'height:' + oh + 'px;', // 'top': header,
		duration:0.3
	});
};

var closeOverLay = function()
{
	// alert('func closeOverLay');	
	var overlay = $('popup-footer-overlay');
	new Effect.Morph(overlay, 
		{style:'height:0;',
		duration:0.4,
		afterFinish: function()
		{	
			if (window.scrollbars) {
				window.scrollbars.visible = true;
			}
			
			overlay.remove();
			// initPopup();
		}
	});
};

function expandPopup(mc, headerH, oh, arg)
{
	// alert('func expandPopup');
	if (window.scrollbars) {
		window.scrollbars.visible = (window.scrollbars.visible)? false:true;
	}

	if (arg==false)																	// if arg == 0 - open footer
	{
		var pu = $('popup');
		var puh = $('popup-heads');
		var pud = pu.getDimensions();
		var puhd = puh.getDimensions();
		var mch = mc.getHeight() - mc.getStyle('padding-bottom').replace('px', '');  
		pu.setStyle({display:'block', height:0, 'position':'absolute', 'width':'940px'});
		
		new Effect.Morph(pu, 
			{style:'height: 180px; margin-top: -180px ;',
			duration:0.3
		});
		new Effect.Morph(puh, 
			{style:'top: -180px;',
			duration:0.3,
			afterFinish: function()
			{
				if (window.scrollbars) {
					window.scrollbars.visible = true;
				}
			}	
		});
	}

	if (arg==true) 									 								// if arg == 1 - open login
	{
		openLoginBlock();
	}
}

var openLoginBlock = function()
{
	var login = $('login-block').down('div.body');	
	var loginConts = login.down('div.appear');									// hides child elements, shows after morph. 

	var ld = login.getDimensions();
	var login_height = ld.height;
	loginConts.hide();
	login.setStyle({height:0, display:'block', width: '160px'});

	new Effect.Morph(login,{
		style: 'height: '+ login_height + 'px;',// background-color:#3c3c3c',
		duration: 0.3,
		afterFinish: function()
		{
			loginConts.show();				
		}
	});
	
	new Effect.Morph($('login-block').down('div.head'),{
		style: 'top: '+ login_height + 'px; ',//background-color:#3c3c3c',
		duration: 0.3,
		afterFinish: function()
		{
			$('login-block').down('div.head').addClassName('head-open');
			loginIsOpen=true;	
			footerIsOpen=false;
			$('login-block').removeClassName('closed');
			var la = $('login-arrow');
			la.addClassName('arr-up');
			la.removeClassName('arr-down');			
			addClickObserver();															// add 'close' observer			
		}
	});	
};

function addClickObserver()
{
	// alert('func addClickObserver');	
	if (window.scrollbars)
	{
		window.scrollbars.visible = (window.scrollbars.visible)? false:true;
	}

	$$('.popup-footer-close').each(function(el)
	{
		el.observe('click', function(e) 
		{
			el.stopObserving('click');
			if (loginIsOpen==true) {closeLogin();}
			if (footerIsOpen==true) {closeFooter();}
			initPopup();
			e.stop();
		});
	});

	if (footerIsOpen==true)
	{
		$('popup-heads-trigger').observe('click', function(e)
		{
			$('popup-heads-trigger').stopObserving('click');
			closeFooter();	
			initPopup();
			e.stop();
		});
	}

	if (loginIsOpen==true || $$('.arr-up'))
	{
		$$('div.head').each(function(el) {
			el.observe('click', function(e)
			{
				el.stopObserving('click');
				closeLogin();
				initPopup(); 
				e.stop();
			});
		});
	}
}

function closeLogin()
{
	// alert('func closeLogin');	
	var block = $('login-block');
	if (!block.hasClassName('closed')) 
	{
		var la = $('login-arrow');
		lb = block.down('div.body');
		var ld = lb.getDimensions();
		var login_height = ld.height;
		
		loginIsOpen=false;
		la.removeClassName('arr-up');
		la.addClassName('arr-down');
		block.addClassName('closed');
		
		lb.down('div.appear').setStyle({display: 'none'});
		new Effect.Morph(lb, 
			{style:'height: 0;',
			duration:0.3,
			afterFinish: function()
			{
				lb.setStyle({display:'none', height:login_height - 32 +'px'});
			}
		});
		var lh=block.down('div.head');
		new Effect.Morph(lh, 
			{style:'top: 0; background-color:none;',
			duration:0.3,
			afterFinish: function()
			{
				lh.removeClassName('head-open');
			}
		});
	}
}

function closeFooter()
{
	// alert('func closeFooter');	
	if (!$('sticky').hasClassName('closed')) {						// 'sticky' is the div surrounding both popup elements (popup & popup-heads)
		var la = $('login-arrow');
		var pu = $('popup');
		var puh = $('popup-heads');
		var pud = pu.getDimensions();
		var puhd = puh.getDimensions();	
		pu.setStyle({'z-index':'1010'});
		puh.setStyle({'z-index':'1010'});

		footerIsOpen=false;	
		$('sticky').addClassName('closed');
		pu.removeClassName('open');

		new Effect.Morph(pu, 
			{style:'height: 0px; margin-top: 0px;',
			duration:0.3
		});
		new Effect.Morph(puh, 
			{style:'top:0px',
			duration:0.3,
			afterFinish: function()
			{
				// if (footerIsOpen==false && loginIsOpen==false) { initPopup(); };
				puh.removeClassName('open');
			}
		}, false);
	}
}

var hideMain = function(fade) 
{
	if(fade === undefined ) { fade = true; }

	if($('hide') || bodyid == 'what-we-do' || bodyid == 'how-we-do-it')
	{
		if($('hide'))
		{
			var hide = $('hide').down('a.hidebtn');
			if(hide)
			{
				hide.observe('click', function(e) {
					hideCopy(true, false);
					e.stop();
				}, false);
			}
		}
		
		if ($('flashwrapper') && $('flashcontents') && $('flashcontents').tagName == 'DIV') 
		{
			hideCopy(fade);
		}
	}
};

var showCopy = function()
{
	$('flashwrapper').show();
	if($('flashcontents'))
	{
		$$('body').first().style.backgroundPosition = 'center -1000px';
	}
	
	viewPortSizing();
	var showanim = ((hashparams.anim != undefined) && (hashparams.anim == 1));
	if((swfobject.hasFlashPlayerVersion("9.0.115")) && (((readCookie( bodyid+'_flash' ) == null) && ((hashparams.anim == undefined) || (hashparams.anim != 0))) || showanim))
	{
		if($('skipbtn')) { $('skipbtn').show(); }
		showFlashContent();
	}
	else
	{
		document.fire('animation:complete');
	}
}

var hideCopy = function(fade, show)
{
	if(show === undefined ) { show = true; }
	if(fade === undefined ) { fade = true; }
	
	if(fade)
	{
		$('page-content-surround').fade( {
			style: 'height: 0px;',
			duration:0.5,
			afterFinish:function()
			{
				if(show) { showCopy(); }
			}
		});
	}
	else
	{
		$('page-content-surround').hide();
		if(show) { showCopy(); }
	}
};

var showMain = function()
{
	if(swfobject.hasFlashPlayerVersion("9.0.115"))
	{
		if($('skipbtn')) { $('skipbtn').hide(); }
		if($('replaybtn')) { $('replaybtn').show(); }		
	}
	
	if($('flashwrapper')) { $('flashwrapper').hide(); }

	if($('flashcontents'))
	{
		$$('body').first().style.backgroundPosition = 'center top';
	}
	
	if($('page-content-surround'))
	{	
		$('page-content-surround').appear({
			style: 'height: 0px',
			duration: 0.5
		});
	}
	
	createCookie( bodyid+'_flash', 'true', 365 );
};

var initlw = function()
{
	$$('.lightwindow').each( function(el) {
		el.stopObserving('click');
		el.observe('click', function( e ) {
			
			e.stop();
			var a = e.findElement('a');
			var dims = a.rel.split(',');
			var w = parseInt(dims[0], 10) + 112;
			var h = parseInt(dims[1], 10) + 170;
			var idn = parseInt(dims[2], 10);
			mod = gal_window_factory( el, {iframe: true, className: 'modal-gallery', height:h, width:w, g_id:idn} );
			mod.open();
			
		}, false);
	});
};

var closelw = function()
{
	Control.Modal.close();
};
var mbcloselw = function()
{
	if($('moodboards-lhs-options'))
	{
		var cont = $('moodboards-lhs-options').up();
		$('moodboards-lhs-options').replace('<img src="/cache/global/img/ajax-loading.gif" style="width:20px;" /> <span class="white">Please wait while this page updates.</span>');
	}	
	Control.Modal.close();	
	document.fire('page:reload')
}

var prevLWClicked = function(e)
{
	var frame = $('modal-window-iframe');
	var prevLink = null;
	var currentImage = 'lw-img-'+e.memo.currentImage;
	
	if($(currentImage))
	{
		prevLink = $(currentImage).up('div.item').previous().down('a.lightwindow');
	}
	
	if(prevLink == null) { prevLink = $$('a.lightwindow').last(); }

	if (prevLink != null) {
		Control.Modal.close();
		
		var dims = prevLink.rel.split(',');
		var w = parseInt(dims[0], 10) + 112;
		var h = parseInt(dims[1], 10) + 170;
		idpr = parseInt(dims[2], 10);
	
		mod = gal_window_factory( prevLink, {iframe: true, className: 'modal-gallery', height:h, width:w, g_id:idpr} );
		mod.open();
	}
};

var nextLWClicked = function(e)	
{
	var frame = $('modal-window-iframe');
	var nextLink = null;

	var currentImage = 'lw-img-'+e.memo.currentImage;
	if($(currentImage))
	{
		nextLink = $(currentImage).up('div.item').next().down('a.lightwindow');
	}
	
	if(nextLink == null) { nextLink = $$('a.lightwindow').first(); }

	if (nextLink != null) {
		Control.Modal.close();
		
		var dims = nextLink.rel.split(',');
		var w = parseInt(dims[0], 10) + 112;
		var h = parseInt(dims[1], 10) + 170;
		idpr = parseInt(dims[2], 10);
	
		mod = gal_window_factory( nextLink, {iframe: true, className: 'modal-gallery', height:h, width:w, g_id:idpr} );
		mod.open();
	}
};

var gal_window_factory = function(container,options) {  

	// if (!$('gallery_view')) {
		var h = options.height;
	
		var ftw = options.width + 10;
		var ww = options.width  - 73;
	
		var bgtop = (options.height/2) - 12;

	    var w = new Control.Modal(container,Object.extend({  
	        className: 'modal-gallery',
	  		fade: (!Prototype.Browser.IE),
			overlayOpacity: 0.75,
	   		closeOnClick: $('control_overlay'),
	        // insertRemoteContentAt: window_contents,
			onRemoteContentLoaded: function() {
				// $('control_overlay').setStyle({height:($('control_overlay').getHeight() - 140) + 'px'});
				document.fire('modal:loaded', {g_id:options.g_id});
			},
	  		afterClose: function() { 
				var id = this.container.id;
				this.destroy();
				$(id).remove();
				// if (!$('modal-window-iframe')) {
				// 	$('control_overlay').hide();
				// };
				if (window.scrollbars) {
					window.scrollbars.visible = (window.scrollbars.visible)? false:true;
				}
			}
			// indicator: window_loading
	    },options || {}));  

	    return w;  
	// } else {
	// 	  	$('close').down('a').observe('click', function(e){
	//     parent.Control.Modal.close();
	// 	e.stop();
	// }, false);
	// };
};

var gallery_hover = function()
{
	var gals = $$('a.gal-pic');
	
	//to store z-index value of the element before it's replaced
	var tmp_ZI = gals.length;
	
	gals.each(function(el){
		el.observe('mouseover', function(e){
			
			//give ever-decreasing z-index values to each li - for IE. - put here for robust-ness. . . 
			var zi = gals.length;
			var galItem = $$('.gallery .item');
			galItem.each(function(ziel) 
			{
				ziel.style.zIndex = zi--;
			});
			
			gals.each(function(ele){
				ele.next().hide();
				ele.next().removeClassName('to-front');
			});
			//store the z-index for later and replace it with 99
			tmp_ZI = el.up('.gallery .item').getStyle('z-index');
			el.up('.gallery .item').hasClassName(tmp_ZI);
			el.up('.gallery .item').style.zIndex = gals.length + 1;
			
			el.next().addClassName('to-front');
			el.next().show();
			e.stop();
		});
	});
	
	$$('a.gal-overlay').each(function(el) {
		el.observe('mouseout', function(e) {
			el.hide();
			if (el.hasClassName('to-front')) {
				el.removeClassName('to-front');
			}
			//replace original z-index value
			el.up('.gallery .item').style.zIndex = tmp_ZI;
			e.stop();
		});
	});
};

var galleries_hover = function()
{
	var gals = $$('a.gal-pic');
	gals.each(function(el){
		el.observe('mouseover', function(e){
			gals.each(function(ele){
				ele.next().hide();
				ele.next().removeClassName('to-front');
			});
			el.next().addClassName('to-front');
			el.next().show();
		});
	});
	
	$$('a.gal-title-hover').each(function(el) {
		el.observe('mouseout', function(e) {
			el.hide();
			if (el.next() && el.next().hasClassName('to-front')) {
				el.next().removeClassName('to-front');
			}
		});
	});
};

var manageMoodboardItems = function()
{
	// hide_mb_its_overlay();
	// $$('a.open-moodboard-list').each( function(el)
	// {
	// 	el.next().hide();
	// 	initMoodboardItemLinks();
	// });
	// alert('809');
};

var initMoodboardItemLinks = function()
{

	$$('a.open-moodboard-list').each( function(el)
	{
		el.observe('click', function(e){
			e.stop();
			$$('a.open-moodboard-list').each( function(elm)
			{
				elm.next().hide();
				elm.removeClassName('mb-link-white');
			});			
			el.next('ul.moodboard-items').toggle();
			var ndims = el.up('ul').getDimensions();
			var h = ndims.height + 85;
			// alert(h);
			el.up('div.body').setStyle({height:h +'px'});
			el.up('div.body').next('div.head').setStyle({top:h +'px'});
		
			el.toggleClassName('mb-link-white');
		});
	});
	
	removeMoodboardLinks();
};

var removeMoodboardLinks = function()
{
	var rmlnks = $$('a.remove-from-moodboard');

	rmlnks.each(function(remBtn){
		remBtn.observe('mouseover', function(e){
			e.stop();
			remBtn.previous().show();
			remBtn.next('span').show();			
			remBtn.previous().style.zIndex = 5;
			remBtn.next('span').style.zIndex = 8;
		});		
	});

	rmlnks.each(function(remBtn)
	{
		remBtn.observe('click', function(e)
		{
			var btnClicked = e.findElement('a');
			deleteFromMoodboard(btnClicked);
			e.stop();
		});
			
		remBtn.observe('mouseout', function(e)
		{
			e.stop();
			hide_mb_its_overlay();
		});		
	});
	
};

var deleteFromMoodboard = function(remButton)
{
	if( ! confirm('Are you sure you wish to delete this moodboard item?'))
	{
		return;
	}
	if (remButton.tagName == 'IMG')
	{
		remButton = remButton.up();
	}
	
	new Ajax.Request('/moodboards/delete_item', {
		parameters:{moodboard_item_id:remButton.rel},
	  	onSuccess: function(transport) 
		{
	    	if (transport.responseText == 1)
			{
				if ($('moodboard-items'))
				{
					remButton.up('div.item').remove();
				}
				else
				{
					remButton.up('li').remove();
				}
			}
	  	}
	});
};

var hide_mb_its_overlay = function()
{
	$$('div.mb-img-item-overlay').each(function(el)
	{
		el.hide();
		el.style.zIndex = 0;
	});
	
	$$('span.remove-indicator').each( function(el)
	{
		el.hide();
		el.style.zIndex = 0;
	});	
};

var load_mbs = function()
{
	new Ajax.Updater($('gals-mbs'), '/moodboards/login_block_moodboards_display', 
	{
		onComplete:function()
		{		
			manageMoodboardItems();
		} 
	});
};

var removeMoodboardLinksEditPage = function()
{
	if($('delete-moodboard-form'))
	{
		$('delete-moodboard-form').observe('submit', function(e)
		{
			if( ! confirm('Are you sure you want to delete this moodboard?'))
			{
				e.stop();
			}
		});
	}
	
	hide_mb_its_overlay();
	var rmlnks = $$('a.remove-from-moodboard');

	rmlnks.each(function(remBtn){
		remBtn.observe('mouseover', function(e)
		{
			e.stop();
			remBtn.previous('div.mb-img-item-overlay').show();
			remBtn.previous('span').show();
		});		
	});
	
	rmlnks.each(function(remBtn)
	{
		remBtn.observe('click', function(e)
		{
				var btnClicked = e.element();
				deleteFromMoodboard(btnClicked);
				e.stop();
			});
			
		remBtn.observe('mouseout', function(e)
		{
			e.stop();
			hide_mb_its_overlay();
		});
	});
};

var moodboard_items_edit = function()
{
	removeMoodboardLinksEditPage();
};

function flashcomms( msg )
{
	document.fire(msg);
}

function flashskip()
{
	if ($('flashcontent-home'))
	{
		$('flashcontent-home').remove();
	}
	else
	{
		document.fire('animation:complete');
	}
}

var viewPortSizing = function()
{
	// accomodating 1024 x 768 was an afterthought - this alters #flashwrapper's parent div if viewport < #flashwrapper, and alters margins accordingly
	
	var tmpWidth = document.viewport.getWidth();
	var tmpHalf = tmpWidth / 2;

	var tmpHeight = document.viewport.getHeight();

	var portHeight = tmpHeight - 200;
	var divHeight = 469;

	// find home-page flash content
	if ($('flashcontent-home'))
	{
		var flCont = $('flashcontent-home');
		var mainCpBk = $('main-copy-block')
		var mainBlk = mainCpBk;
	} else {
		if ($('flashcontents')) 
		{ 
			var flCont = $('flashcontents');
			var portHeight = 600; // tmpHeight - 232;
			var divHeight = 410;
			var mainBlk = $('main-flash-block');
		}
	}

	if (flCont) 
	{
		// For homepage animations #main-copy-block on the homepage has a -ve left margin of 129.
		// Find it. Set it to 0 in the if, reset it in the else
		
		var parDiv = flCont.up('div');
		
		// WIDTH
		if (tmpWidth < 1201)
		{		
			parDiv.hasClassName('surround');

			if (tmpWidth < 945) {
				mainBlk.setStyle({ 'margin-left' : 0 });
				flCont.setStyle({ 'margin-left' : '-130px', width : '1076px'});
				parDiv.setStyle({ width : '945px', overflow : 'hidden' });
				// hold the background image in place
				// document.body.setStyle({ 'background-position' : '-129px 100px' });
			} else {
				parDiv.setStyle({ width : tmpWidth + 'px', overflow : 'hidden' }); 
				flCont.setStyle({ 'margin-left' : '-' + ( (1200 - tmpWidth) / 2 ) + 'px', width : (tmpWidth + ((1200 - tmpWidth) / 2)) + 'px' })
				// centre the background image again
				// document.body.setStyle({ 'background-position' : '50% 100px' });
				if ($('flashcontent-home')) {
					mainBlk.setStyle({ 'margin-left' : '-' + ( (document.viewport.getWidth() - 940) / 2 ) + 'px' });
				}
			}
		} else {
			parDiv.setStyle({ width : 1200 + 'px' });
			flCont.setStyle({ 'margin-left' : 0 });
			if ($('flashcontent-home')) {
				mainBlk.setStyle({ 'margin-left' : '-129px' });	
			};
		}

		// HEIGHT
		if (tmpHeight < 830 && flCont) 
		{
			if (tmpHeight > 640) {
				parDiv.setStyle({ height : portHeight + 'px', overflow : 'hidden' });
			} else {
				parDiv.setStyle({ height : divHeight + 'px', overflow : 'hidden' });
				$('main-content').setStyle({ 'min-height' : divHeight + 'px' });
			}
		}
	}
};

//Moodboad lightwindows - send email/add image
var moodboard_lw_links_init = function()
{
	$$('.moodboard-lightwindow').each( function(el) {
		el.stopObserving('click');
		el.observe('click', function( e ) {
			
			e.stop();
			var a = e.findElement('a');
			mod = moodboard_window_factory( el, {iframe: true, className: 'modal-moodboard'} );
			mod.open();
			
		}, false);
	});	
}

var moodboard_window_factory = function(container, options)
{
	var window_contents = new Element('div',{  
        className: 'window_contents'
    });
	var window_header = new Element('div',{  
        className: 'window_header'
    });
    var window_close = new Element('div',{  
        className: 'window_close'  
    }).update('Close');
	
	 var w = new Control.Modal(container,Object.extend({  
	        className: 'modal-moodboard',
	  		fade: true,
			overlayOpacity: 0.75,
	   		closeOnClick: $('control_overlay'),
			insertRemoteContentAt: window_contents,	
			onRemoteContentLoaded: function() {
				document.fire('modal:loaded');
			},
	  		afterClose: function() { 
				var id = this.container.id;
				this.destroy();
				$(id).remove();
				$('control_overlay').hide();
			}
	    },options || {}));  
		
		w.container.insert(window_contents);
		
		$('control_overlay').observe('click', function(e){
		    Control.Modal.close();
			document.fire('page:reload');
			e.stop();
		}, false);
		
	    return w;	
}

//Case studies
var loadCaseStudyImageSwitching = function()
{
	$$('.case-studies-switchimg').each(function(el)
	{
		el.observe('click', function(e)
		{
			var lnk = e.findElement('a');
			$('case-studies-main-img').src = lnk.href;
			e.stop();
		});
	});
}

// General page reload function called by page:reload event
var page_reload = function()
{
 	window.location.href = window.location.href;
}


document.observe('moodboards:loaded', load_mbs);
document.observe('moodboard-items:loaded', moodboard_items_edit);

document.observe('gallery:next', nextLWClicked);
document.observe('gallery:previous', prevLWClicked);

function externalLinks() { $$('a').each( function(el) { if(el.getAttribute("href") && el.getAttribute("rel") == "external") { el.target="_blank"; } } ); }
function internalLinks() { $$('a').each( function(el) { if(el.getAttribute("href") && el.getAttribute("rel") == "internal") { el.target="_self"; } } ); }

document.observe('dom:loaded', appscripts, false);
document.observe('dom:loaded', externalLinks, false);

document.observe('lw:init', initlw);
document.observe('lw:close', closelw);
document.observe('mblw:close', mbcloselw);

document.observe('quicksearch:complete', gallery_hover);
document.observe('quicksearch:complete', initlw);
document.observe('quicksearch:complete', footerMarginFix);

document.observe('animation:complete', showMain);

document.observe('page:reload', page_reload);