var mod;
var loginIsOpen = false;
var footerIsOpen = false;
var loginBlockHeight;
// var loginFlag = false; 				//if user details/password are incorrect login stays open
var	negMargin = '65';
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();
	});
	
	InputBoxesHighlight.init();

	if($$('.moodboard-lightwindow').length)
	{
		moodboard_lw_links_init();
	}
	
	if ($$('.case-studies-switchimg').length) 
	{
		loadCaseStudyImageSwitching();
	}
	
	if($('flashcontents'))
	{
		$$('body').first().style.backgroundPosition = 'center -1000px';
	}

	// CHECK LOGIN BLOCK DESIRED STATE
	if ($('login-block')) 
	{
		// IF .open OR .form-error EXIST THEN LEAVE OPEN AND SETUP THE LISTENER FOR CLOSING
		var login = $('login-block');
		if (login.hasClassName('open')) 
		{
			loginIsOpen = true;
			// setup 
			var footer = $('footer').getHeight();
			var pageHeight = getDocumentHeight(); // (document.height !== undefined) ? document.height : document.body.offsetHeight; 
			// 3 arguments to be carried through functions
			var mc = $('main-content');
			var headerH = ($('header').getHeight())+($('logo-head').getHeight());
			var oh = pageHeight-(headerH+footer);	
			// end setup
			expandPopup(mc, headerH, oh, true);											// open

			login.down('div.head').hide();
		}
		
		if (login.down('span.form-error')) 
		{
			loginIsOpen = true;
			login.down('div.head').down('span').hide();
			login.down('div.head').down('a').hide();

			if ($F('xauth_login-credential').length > 0)
			{
				removePWbg();
			}
			// initPopup();
		}

		// alert(login.hasClassName('open'));

		// ELSE CLOSE THE LOGIN BLOCK AND SETUP LISTENER FOR OPENING
		if ($('login-block') && !loginIsOpen) 
		{
			$('login-block').down('div.body').hide();   // hide login block
			// initPopup();
		}
	};
	
	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();
			new Effect.Fade($('login'), { style: 'display: none;', duration: 0.5 });
			new Effect.Fade($('sticky'), { 
				style: 'display: none;', 
				duration: 0.5,
				// neatest way of stoping the background changing before the animation starts
				afterFinish: function() { homepageCycleImage(); }
			});
			
			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(); 
	
	initPopup();
	
	if($('prefs-saved-notice')) {
		$('the-form-xauth_profile').observe('click', function(e) {
			new Effect.Fade($('prefs-saved-notice'), { style: 'display: none', duration: 0.5 });
		});
		
	}
};

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 viewport height is >= document height
		if ((myHeight + 18) >= yWithScroll ) {// || $('flashcontent-home') || $('flashcontents')
			$('sticky').style.marginTop = '-65px';
			negMargin = 65;
		} else {
			$('sticky').style.marginTop = '-40px';
			negMargin = 40;
		}
		
		popupJump();
	}
};

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 .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 = '';
			}
			
			// remove password on 'email' focus
			removePWbg();
		});

		$('xauth_login-email').observe('blur', function()
		{
			if ($F('xauth_login-email').length == 0)
			{
				$('xauth_login-email').value = 'Email';
			}
			
			// re-add 'password' if empty
			if ($F('xauth_login-credential').length == 0)
			{
				$('xauth_login-credential').setStyle({
					background:'#787878 url(/staticfiles/img/password-field-bg.gif) no-repeat 3px 0'
				});
			}
		});
	}
};

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()
{
	if ($('login-block') && $('login-block').down('span.form-error')) { 
		// if the login box has an error it will be open on page load. 
		// The 'else' here stops poor interaction with the Info Panel.
		
		// close-error is a cancel button that reloads the page via _closeError()
		if ( ! $('close-error')) {
			var closeError = new Element('div', { 'id': 'close-error'}).update('cancel');
			$('xauth_login-form_submit').up().insert(closeError);
			_closeError();
		};
	} else {
		$$('.sticky-close').each(function(el)
		{
			el.title = "Click to open or close footer";
		});
	
		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 
		if ($('footer')) {
			var footer = $('footer').getHeight();			
		};

		var pageHeight = getDocumentHeight(); // (document.height !== undefined) ? document.height : document.body.offsetHeight; 
		// 3 arguments to be carried through functions
		var mc = $('main-content');
		if ($('header')) {
			var headerH = ($('header').getHeight())+($('logo-head').getHeight());			
		};

		var oh = pageHeight-(headerH+footer);	
		// end setup

		var la = $('login-block');
		if (la) 
		{
			if (la.hasClassName('closed') && loginIsOpen==false) 
			{
				var larr = $('login-arrow');
				la.stopObserving('click');
				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

					loginIsOpen=true;

					initPopup();
				}, false);
			}
		}

		var sticky = $('sticky');
		var pu = $('popup');
		var puh = $('popup-heads');	

		if ($('popup-heads')) {
			$('popup-heads').stopObserving('mouseover');			
		};

		if (sticky && sticky.hasClassName('closed') && footerIsOpen === false)
		{
			$('popup-heads').observe('click', function(e)
			{
				resetPopup();

				if (window.scrollbars) 
				{
					window.scrollbars.visible = (window.scrollbars.visible)? false:true;
				}
			
				Event.stopObserving('popup-heads', '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 _closeError = function()
{
	if ($('close-error')) {
		$('close-error').observe('click', function(event) {
			window.location.reload();
		 });
	};
}

var popupJump = function()
{
	if ($('login-block') && !footerIsOpen && !$('login-block').down('span.form-error')) {
			var sticky = $('sticky');
			var pu = $('popup');
			var puh = $('popup-heads');
		
			$('popup-heads').observe('mouseover', function()
			{
				sticky.setStyle({ marginTop : '-' + (negMargin + 4) + 'px', 'height' : '69px' });
				puh.setStyle({ 'height' : '30px', 'background-color' : '#575757' });
			}, false);

			$('popup-heads').observe('mouseout', function()
			{
				resetPopup();
			}, false);
	};
};

var resetPopup = function()
{
	$('sticky').setStyle({ marginTop : '-' + negMargin + 'px', 'height' : '65px' });
	$('popup-heads').setStyle({ 'height' : '26px', 'background-color' : 'transparent' });
};

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 block = $('login-block');
	var 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.2,
		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');
			if (la.previous('span')) {
				la.previous('span').setStyle({ 'opacity' : '0.3', 'filter' : 'alpha(opacity=30)' });
			};
			addClickObserver();															// add 'close' observer
		}
	});
};

function 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(); 
				if($('login-arrow').previous('span'))
				{
					new Effect.Opacity($('login-arrow').previous('span'), { from: 0.3, to: 1.0, duration: 0.5 });
				}
				e.stop();
			});
		});
	}
}

function closeLogin()
{
	var block = $('login-block');
	if (block && !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');
			}
		});
		
		loginIsOpen = false;
	}
}

function 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(); }
		if(typeof(showFlashContent) == 'function')
		{
			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 );
	
	$('login').appear({ style: 'display: block', duration: 0.5 });
	$('sticky').appear({ style: 'display: block', duration: 0.5 });
};

var homepageCycleImage = function()
{
	if ($('home')) {
		// read cookie
		var ck = readCookie( 'homepageBackgroundPicker' );
		// add one
		var newCK = parseInt(ck)+1;
		// reset if too high
		if (newCK > 3) { newCK = 0 };
		// set cookie
		document.cookie = 'homepageBackgroundPicker='+newCK;
		// change bg image
		$('home').setStyle({ backgroundImage : 'url("/staticfiles/img/bg-home-'+newCK+'.jpg")' });
	};

	// if ($('home')) {
	// 	// generate a random number between 0-4
	// 	var randomFileNumber=Math.floor(Math.random()*4);
	// 	// randomly pick one of the files and add to the bg image
	// };
};

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) + 100; // was 112
			var h = parseInt(dims[1], 10) + 130; // was 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;

	// find the id of the current element (anchor in gallery, img in moodboards)
	var currentImage = 'lw-img-'+e.memo.currentImage;
	if($(currentImage))
	{
		// find the parent element .surround.item in moodboards, .item in gallery
		var parentElement = ($(currentImage).hasClassName('mbgallery-check')) ? 'div.surround.item' : 'div.item';
		// get previous image
		prevLink = $(currentImage).up(parentElement).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) + 100;
		var h = parseInt(dims[1], 10) + 130;
		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;

	// find the id of the current element (anchor in gallery, img in moodboards)
	var currentImage = 'lw-img-'+e.memo.currentImage;
	if($(currentImage))
	{
		// find the parent element .surround.item in moodboards, .item in gallery
		var parentElement = ($(currentImage).hasClassName('mbgallery-check')) ? 'div.surround.item' : 'div.item';
		// get next image
		nextLink = $(currentImage).up(parentElement).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) + 100;
		var h = parseInt(dims[1], 10) + 130;
		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();
	// });
};

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;

			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()
{
    var tmp = $('gals-mbs');
	if (tmp) {
		new Ajax.Updater(tmp, '/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 a design 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 - 108;

	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 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');
		var tmpSwitch = true;
		// WIDTH
		if (tmpWidth < 1201)
		{		
			parDiv.hasClassName('surround');

			if (tmpWidth < 945)		// at this res scrollbars are acceptable
			{
				mainBlk.setStyle({ marginLeft : 0 });
				// set the width and left align the surrounding div.
				parDiv.setStyle({ 
					width : '945px', 
					overflow : 'hidden', 
					marginLeft : '-' + tmpWidth / 2 + 'px'
				});
				// Give a -ve Lmargin to the flash to remove the feathered edging
				flCont.setStyle({ 
					marginLeft : '-70px', 
					width : '1075px'
				});
			} 
			else	// at this res scrollbars are not acceptable 
			{	
				// give correct width and centre align the flash
				parDiv.setStyle({
					width : tmpWidth + 'px',
					overflow : 'hidden',
					marginLeft : '-' + tmpHalf + 'px'
				});
				flCont.setStyle({ 
					marginLeft : '-' + ( (1200 - tmpWidth) / 2 ) + 'px',
					width : '1200px'
				});
				if ($('flashcontent-home'))
				{
					mainBlk.setStyle({ 
						marginLeft : '-' + ( (document.viewport.getWidth() - 940) / 2 ) + 'px'
					});
				}
			}
		} 
		else	// reset values to those originally declared by the css
		{
			parDiv.setStyle({
				width : '1200px',
				marginLeft : '-600px',
				overflow : 'visible'
			});
			flCont.setStyle({
				marginLeft : '0px',
				width : '1200px'
			});
			if ($('flashcontent-home')) {
				mainBlk.setStyle({ marginLeft : '-129px' });
			};
		}

		// HEIGHT
		if (tmpHeight < 830 && flCont) 
		{
			if (tmpHeight > 640) {
				parDiv.setStyle({ height : portHeight + 'px', overflow : 'hidden' });
			} else {
				parDiv.setStyle({ height : portHeight + 'px', overflow : 'hidden' });
				$('main-content').setStyle({ 'min-height' : portHeight + '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 ) {
			// HEIGHT SET FOR EMAIL A FRIEND WINDOW
			var h = 430;
			var w = 500;
		
			// IF HEIGHT VALUES NEED CHANGING ALSO CHANGE IN moodboard-lw-tpl.css
			if (el.hasClassName('email-rouge')) { h = 350; };
			if (el.hasClassName('add-images')) { h = 300; };
						
			e.stop();
			var a = e.findElement('a');
			mod = moodboard_window_factory( el, {iframe: true, className: 'modal-moodboard', height:h, width:w} );
			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;
};

var InputBoxesHighlight = 
{
	init: function()
	{
		$$('input').each(function(el) { el.observe('focus', InputBoxesHighlight.showHighlightListener); });
		$$('input').each(function(el) { el.observe('blur', InputBoxesHighlight.hideHighlightListener); });
		$$('select').each(function(el) { el.observe('focus', InputBoxesHighlight.showHighlightListener); });
		$$('select').each(function(el) { el.observe('blur', InputBoxesHighlight.hideHighlightListener); });
		$$('textarea').each(function(el) { el.observe('focus', InputBoxesHighlight.showHighlightListener); });
		$$('textarea').each(function(el) { el.observe('blur', InputBoxesHighlight.hideHighlightListener); });
	},
	
	showHighlightListener: function(event) { InputBoxesHighlight.showHighlight(this); },
	hideHighlightListener: function(event) { InputBoxesHighlight.hideHighlight(this); },

	showHighlight: function(link) { link.addClassName('focus'); },
	hideHighlight: function(link) { link.removeClassName('focus'); }
};

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('animation:complete', homepageCycleImage);
	
document.observe('page:reload', page_reload);

//window.onload = footerMarginFix;
document.observe('dom:loaded', footerMarginFix);
