var mT, inputV = new Array (),pageNum=1, shareThisObject = new Array (), isIE6, notIE, notChrome, notSafari, working=0, working2 = new Array (), mem = new Array (), mem2 = new Array (), uploadedFile = new Array (),galleryPages,galleryCurrentPage=1;

if (navigator.userAgent.toLowerCase().indexOf('msie 6') == -1) notIE6 = true; else notIE6 = false;
if (navigator.userAgent.toLowerCase().indexOf('msie') == -1) notIE = true; else notIE = false;
if (navigator.userAgent.toLowerCase().indexOf('chrome') == -1) notChrome = true; else notChrome = false;
if (navigator.userAgent.toLowerCase().indexOf('safari') == -1) notSafari = true; else notSafari = false;

function messageBox(message,secondsOut,container,action,noP) {
	
	var m=message;
	if (action =='close') {
		closeBox('messageBox',0.6,1)
	}
	else if (action =='update') {
		$('messageBox').update(m);
	}
	else {
		if (container==null) container='mainContainer';
		$(container).setStyle({position:'relative'});
		m='<div id="messageBox" style="display:none;">'+m+'</div>';
		$(container).insert(m);
		centreElement ('messageBox',1,container);
		if (mT) clearTimeout(mT);
		mT=null;
		$('messageBox').appear({ duration: 0.3, delay:0.2 });
		var s = message.split(' ');
		secondsOut = Math.ceil(s.length/3);
		mT = setTimeout(function () { 
			messageBox(null,null,null,'close',noP)
		}
		,(secondsOut*1000));
	}
}

function loadingBox(onOff,container,delOL) {
	if (onOff==1) {
		if (container==null) container='mainWrapper';
		$(container).setStyle({position:'relative'});
		var m='<div id="loadingBox" style="display:none;"></div>',o;
		
		$(container).insert(m);
		if ($('pageOverlay') == null) {
			o='<div id="pageOverlay" style="display:none;"></div>';
			$(container).insert(o);
			$('pageOverlay').setStyle({height:$(container).getHeight()+'px',width:$(container).getWidth()+'px'});
		}
		if ($('pageOverlay') != null && $('pageOverlay').visible() == false) {
			$('pageOverlay').appear({ duration: 0.3, from:0, to:0.5 });
		}
		centreElement ('loadingBox',1,container);
		$('loadingBox').appear({ duration: 0.3, delay:0.2 });
	}
	else {
		if (delOL != null) closeBox('pageOverlay',0.5,1)
		closeBox('loadingBox',0.5,1)
	}
}

function pageOverlay (c) {
	var i = 'pageOverlay';
	if ($(i)!=null) $(i).remove();
	if (c==null) c='mainWrapper';
	$(c).setStyle({position:'relative'});
	$(c).insert('<div id="'+i+'" style="display:none;"></div>');
	$(i).setStyle({height:$(c).getHeight()+'px',width:$(c).getWidth()+'px'});
	$(i).appear({ duration: 0.3, from:0, to:0.5 });
}

function showBox(i,c,ov) {
	if (c==null) c='mainWrapper';
	if (ov) pageOverlay(c)
	centreElement (i, 1, c)
	$(i).appear({ duration: 0.5, delay:0.2 });
}

function centreElement (e, vert, c) {
	var a = document.viewport.getWidth(),b = document.viewport.getHeight(),theScrolls = document.viewport.getScrollOffsets();
	theScrolls = document.viewport.getScrollOffsets();
	if (c) {
		theScrolls[0]=0
		a = $(c).getWidth()
	}
	theLeft = Math.floor(((a)-($(e).getWidth()))/2) + theScrolls[0];
	theTop = Math.floor(((b)-($(e).getHeight()))/2) + theScrolls[1];
	if (theTop < 0) theTop = 0;
	if (vert==1)  {
		$(e).setStyle({ top: '0px' });
		$(e).setStyle({ top: theTop+'px' });
	}
	$(e).setStyle({ left: theLeft+'px' });
	
}

function closeBox(i,d,r) {
	$(i).fade({ duration: d, afterFinish:function () {
		if (r != null) $(i).remove();
	}});
}

function ajaxText (i,t,n) {
	if (t == 'form') {
		return Form.serialize(i);	
	}
	if (t == 'ent') {
		return htmlentities(i);	
	}
	if (t == 'ready') {
		i = i.replace("‘","'");
		i = i.replace("’","'");
		if (n != null) escape(i);
		else return encodeURI(escape(i));
	}
	if (t == 'ent-ready') {
		i = ajaxText (i,'ent');
		return ajaxText (i,'ready');
	}
	if (t == 'encode_utf8') {
		return encodeURIComponent( escape( s ) );
	}
	if (t == 'decode_utf8') {
		return decodeURIComponent( escape( s ) );
	}
}

function clearInputBox(i,t,o,c) {
	if (o==1) {
		if ($F(i) == t) $(i).value='';
	}
	else if (o==2) {
		$(i).stopObserving('focus');
		$(i).stopObserving('blur');
		$(i).observe('focus', function () { clearInputBox(i,t,1,c); });
		$(i).observe('blur', function () { clearInputBox(i,t,0,c); });
	}
	else {
		if ($F(i) == '') $(i).value=t;	
	}
	if (c) { $(i).setStyle({ color: c }); }
}

function isValidEmail(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1) return false;
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) return false;
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) return false;
	if (str.indexOf(at,(lat+1))!=-1) return false;
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) return false;
	if (str.indexOf(dot,(lat+2))==-1) return false;
	if (str.indexOf(" ")!=-1) return false;
	return true;			
}

function handleEnter (event, func, v) {
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	if (keyCode == 13) {
		event.stop()
		if (func) func (v);
		return false;
	}
	else return true;
}

function badField (f,t) {
	var b = false;
	if (t==1) {
		f.each(function(n){
			if ($F(n)=='' || $F(n)==inputV[n]) b = true;
		});
	}
	else if ($(f).tagName == 'FORM' || $(f).tagName == 'form') {
		var a=$$('#'+f+' input[type="text"]');
		a.each(function(n){
			if ($F(n.id)=='' || $F(n.id)==inputV[n.id]) b = true;
		});
		var a=$$('#'+f+' textarea');
		a.each(function(n){
			if ($F(n.id)=='' || $F(n.id)==inputV[n.id]) b = true;
		});
	}
	else if ($F(f)=='' || $F(f)==inputV[f]) b = true;
	return b;
}

function html_entity_decode(str) {
    var  tarea=document.createElement('textarea');
    tarea.innerHTML = str; return tarea.value;
    tarea.parentNode.removeChild(tarea);
}

function showVimeo (vidID, width, height, divID, colour,auto) {
	var flashvars = {clip_id: vidID,server: "vimeo.com",show_title: "0",show_byline: "0",show_portrait: "0",fullscreen: "1",color: colour,autoplay:auto};
	var params = {allowfullscreen: "true",allowscriptaccess: "always",movie: "http://vimeo.com/moogaloop.swf",wmode: "transparent"};
	var attributes = {clip_id: vidID};
	swfobject.embedSWF("http://vimeo.com/moogaloop.swf", divID, width, height, "9.0.0","expressInstall.swf", flashvars, params, attributes);
}

function showYouTube (vidID, width, height, divID, auto) {
	var flashvars = {};
	var params = {allowfullscreen: "true",allowscriptaccess: "always",wmode: "transparent"};
	var attributes = {id: "vid"};
	swfobject.embedSWF("http://www.youtube.com/v/"+vidID+"&hl=en&fs=1&rel=0&color1=0x000000&color2=0xdddddd&autoplay="+auto, divID, width, height, "9.0.0","expressInstall.swf", flashvars, params, attributes);
}


/********************** ALL ************************/

function setUpAll (n) {
	var doIt;
	if (n) {
		var a=$$('form');
		a.each(function(n){
			$(n.id).reset();
		});
	}
	var a=$$('input[type="text"]');
	a.each(function(n){
		if ($F(n.id) != null && n.id != null) {
			clearInputBox($(n.id),$F(n.id),2);
			inputV[n.id]=$F(n.id);
		}
   	});
	var a=$$('textarea');
	a.each(function(n){
		if ($F(n.id) != null && n.id != null) {
			clearInputBox($(n.id),$F(n.id),2);
			inputV[n.id]=$F(n.id);
		}
   	});
	var a=$$('input[type="radio"]');
	a.each(function(n){
		if (n.id != null) {
			Event.observe(n.id, 'dblclick',function (e) {
				$(n.id).checked = false;
			});
		}
   	});
	var f = 'signUpForm';
	if ($('signup_submit') != null) {
		Event.observe('signup_submit', 'click',function (e) {
			Event.stop(e);
			if (badField (f)) {
				messageBox('Please enter your name and email');
			}
			else if (isValidEmail($F('signup_email'))) {
				var aj = new Ajax.Request(baseURL+'ajaxStuff.php', {method: 'post', parameters: 'signUp=1&'+ajaxText (f,'form'),onComplete: function(response) {
					$(f).reset();
					messageBox(response.responseText,3);
				}});
			}
			else {
				messageBox('Please enter a valid email address');
			}
		});
	}
}

var imageSRC = new Array(), imageText = new Array(), imageID = new Array(), imagNum=0, imageTimer;
function pageImageTrans () {

	var a=$$('div#imageWrapper img[id^="mainImage_"]'),b,imID,txID,w='imageWrapper';
	a.each(function(n){
		b = n.id.split('_');
		imID = n.id;
		pageNum = b[1]+'_'+b[2];
		txID = 'mainImageText_'+pageNum;
   	});
	new Effect.BlindDown(txID, { duration: 0.7, delay:0.4 });
	if (b[2]=='1') {
		var aj = new Ajax.Request(baseURL+'ajaxStuff.php', {method: 'post', parameters: 'getMainImages='+b[1]+'&p='+thisPage,onComplete: function(response) {
			var r = response.responseText.split('|||mmm|||'),s;
			r.each(function(n){
				b = n.split('||mm||');
				imageSRC.push(b[0]);
				imageText.push(b[1]);
				imageID.push(b[2]);
			});
			imageSRC.push($(imID).src.substring($(imID).src.lastIndexOf('/')+1));
			imageText.push($(txID).innerHTML);
			imageID.push(imID);
		}});
		imageTimer = setInterval(function () {
			if (imageText.length>1) {
				if (imagNum > (imageText.length-1)) imagNum=0;
				$(w).insert('<img src="'+baseURL+'images/page_image/main/'+imageSRC[imagNum]+'" width="963" height="346" alt="Image" id="mainImage_'+imageID[imagNum]+'" style="display:none;" /><p style="display:none" id="mainImageText_'+imageID[imagNum]+'">'+imageText[imagNum]+'</p>');
				var e1 = new Effect.BlindUp('mainImageText_'+pageNum, { duration: 0.5 });
				var e2 = new Effect.Fade('mainImage_'+pageNum, { duration: 0.8, delay:0.5, afterFinish: function () { $('mainImage_'+pageNum).remove(); $('mainImageText_'+pageNum).remove(); pageNum = imageID[imagNum]; } });
				var e3 = new Effect.Appear('mainImage_'+imageID[imagNum], { duration: 0.8, delay:0.5 });
				var e4 = new Effect.BlindDown('mainImageText_'+imageID[imagNum], { duration: 0.7, delay:1.0, afterFinish: function () { ++imagNum; } });
			}
		}, 8000);
		
	}
	
}

/********************** HOME ************************/

function setUpHome() {
	
	pageImageTrans ()
	
}

/********************** BLOG ************************/

function setUpBlog() {
	
	pageImageTrans ()
	
}

/********************** CONTACT ************************/

function setUpContact() {
	var f = 'contact_form';
	Event.observe('contact_submit', 'click',function (e) {
		Event.stop(e);
		if (badField (f)) {
			messageBox('Please enter your name, email &amp; enquiry.');
		}
		else if (isValidEmail($F('contact_email'))) {
			var aj = new Ajax.Request(baseURL+'ajaxStuff.php', {method: 'post', parameters: 'contact=1&'+ajaxText (f,'form'),onComplete: function(response) {
				$(f).reset();
				messageBox(response.responseText,3);
			}});
		}
		else {
			messageBox('Please enter a valid email address');
		}
	});
	
}

/********************** COMMUNICATIONS ************************/

function setupCommunications () {
	
	setupCaseStudies ()
	$('mainContainer').observe('mousemove', getcords);
	workedWithRolls ()
}

/********************** DIGITAL ************************/

function setupDigital () {
	
	setupCaseStudies ()
	
	workedWithRolls ()
	
}

/********************** ABOUT ************************/

function setupAbout () {
	
	$('mainContainer').observe('mousemove', getcords);
	workedWithRolls ()
	
}

function workedWithRolls () {
	var a=$$('div#partnersCont ul li img');
	a.each(function(n){
		//$(n.id).observe('mouseover', function () { $(n.id).addClassName('over'); });
		//$(n.id).observe('mouseout', function () { $(n.id).removeClassName('over'); });
		$(n.id).addClassName('over');
   	});
}

/********************** TALENT ************************/

function setupTalent () {
	
	$('mainContainer').observe('mousemove', getcords);
	
}

function setupTalent () {
	
	var a=$$('div#talentContent div.study a');
	a.each(function(n){
		$(n.id).observe('click', function (e) { Event.stop(e); getTalent ($(n.id).href.substring($(n.id).href.lastIndexOf("/")+1)) });
   	});
	
}

function getTalentInfo (p,t) {
	var aj = new Ajax.Updater('talentRightContent',baseURL+'ajaxStuff.php', {method: 'post', parameters: 'loadTalentSection='+p+'&t='+t, onComplete: function () {
		if (t=='book') {
			setUpAll ();
		}
	}});
	var a=$$('div.focus_left ul li a');
	a.each(function(n){
		$(n.id).removeClassName('active');
	});
	$(t).addClassName('active');
}

function getTalent (id) {
	var adH = 0,contentBox = 'talentContent',h2,ov = 'focusOverlay',con='talentFocus',pars,timed=1;
	
	var h = createOverlay (contentBox,'#ffffff',0,0,2,adH,0),pars='getTalent='+id;
	new Ajax.Updater({ success: 'focusOverlay' },baseURL+'ajaxStuff.php', {
		parameters: pars,
		insertion: 'top',
		onComplete:function (response) { 
			$(con).setStyle({left:$(con).getWidth()+'px'});
			$(con).show();
			h2 = $(con).getHeight();
			if (h2 > h) {
				$(ov).setStyle({height:h2+'px'});
				$(contentBox).setStyle({height:(h2-adH)+'px'});
			}
			if ($('vidBox') != null) $('vidBox').removeClassName('unHideIt');
			new Effect.Move(con, { x: 0, y: 0, mode: 'absolute', transition: Effect.Transitions.sinoidal,duration:0.7, afterFinish: function(){
				var rt = 'rosterTitle';
				$(rt).removeClassName('roster');
				$(rt).addClassName('back_roster');
				$(rt).update('<a href="#" id="closeRoster">Back to the Roster</a>');
				
				if ($('vidBox') != null) {
					
					$('vidBox').addClassName('unHideIt');
					var l = $('vidLink').href,w=381,h=212;
					if (l.search('vimeo') > 0) {
						l = l.substring(l.lastIndexOf("/")+1);
						showVimeo (l, w, h, 'vidBox', 'ff0078');
					}
					else if (l.search('youtube') > 0) {
						l = l.split('watch?v=');
						showYouTube (l[1], w, h, 'vidBox');
					}
					else $('vidBox').removeClassName('unHideIt');
				
				}
				
				$('closeRoster').observe('click', function (e) {
					Event.stop(e);
					closeContentBox (contentBox,con,ov)
					$('closeRoster').stopObserving();
					$(rt).removeClassName('back_roster');
					$(rt).addClassName('roster');
					$(rt).update('Roster');
				});
			}});
		}
	});

}

function createOverlay (i,bg,topP,leftP,z,aH,aW,ov) {
	if (ov==null) ov = 'focusOverlay';
	var w=$(i).getWidth(),h=$(i).getHeight();
	if (aH) h = h + aH;
	if (aW) w = w + aW;
	if (z==null) z=2;
	if (topP==null) topP=0;
	if (leftP==null) leftP=0;
	if ($(ov)==null) $(i).insert('<div id="'+ov+'" class="focusOverlay"><div></div></div>');
	$(ov).hide();
	$(ov).setStyle({width:w+'px',height:h+'px',backgroundColor:bg,zIndex:z,left:leftP+'px',top:topP+'px'});
	new Effect.Appear(ov, { duration: 0.5 });
	return h;
}

function closeContentBox (contentBox,con,ov) {
	if ($(ov) != null) new Effect.Fade(ov, { duration: 0.5, afterFinish: function(){ $(contentBox).writeAttribute('style', ''); }});
	new Effect.Move(con, { x: $(con).getWidth(), y: 0, duration:0.5, mode: 'absolute', transition: Effect.Transitions.sinoidal, afterFinish: function(){
		$(con).remove();
		if ($(ov) != null) $(ov).remove();
	}});
}

function sendBookingEnquiry (id) {
	if (badField ('bookForm')) {
		messageBox('Please enter your name, email and enquiry');
	}
	else if (isValidEmail($F('email'))) {
		var vars = ajaxText ('bookForm','form');
		var aj = new Ajax.Request(baseURL+'ajaxStuff.php', {method: 'post', parameters: 'sendTalentEmail='+id+'&'+vars,onComplete: function(response) {
			var r = response.responseText;
			if (r=='Your enquiry has been sent.') $('bookForm').reset();
			messageBox(r);
		}});
	}
	else {
		messageBox('Please enter a valid email address');
	}
}

/********************** Brand Partnerships ************************/

function setupBrandPartnerships () {
	
	setupCaseStudies ()
	$('mainContainer').observe('mousemove', getcords);
	workedWithRolls ()
	
}

var scrollLeft,scrollRight;
function getcords(e){
	var mainCont = 'partners', wrapper = 'partnersCont';
	if ($(mainCont).getWidth()>$(wrapper).getWidth()) {
		var mouseX=parseInt(Event.pointerX(e)),mouseY=parseInt(Event.pointerY(e)),i=$(wrapper),l=$(i).viewportOffset(),w=$(i).getWidth(),h=$(i).getHeight(),d=150,a1,fI,s = document.viewport.getScrollOffsets();
		if (mouseX < (l[0]+s[0]+d) && mouseX > (l[0]+s[0]) && mouseY > (l[1]+s[1]) && mouseY < ((l[1]+s[1])+h)) {
			if (working != 1) {
				working=1;
				a1 = parseInt($(mainCont).getStyle('left').replace('px',''));
				d = (a1-(a1*2))/500;
				scrollRight = new Effect.Tween(mainCont, a1, 0, { duration: d} , function(p) { this.setStyle({left : p+'px' }) } );
				if ($('logoLeft') != null) $('logoLeft').addClassName('over');
			}
		}
		else if (mouseX > ((l[0]+s[0]+w)-d) && mouseX < (l[0]+s[0]+w) && mouseY > (l[1]+s[1]) && mouseY < ((l[1]+s[1])+h)) {
			if (working != 1) {
				working=1;
				a1 = parseInt($(mainCont).getStyle('left').replace('px',''));
				fI = $(mainCont).getWidth() - w;
				d = (fI+a1)/500;
				fI = fI-(fI*2)-8;
				scrollLeft = new Effect.Tween(mainCont, a1, fI, { duration: d} , function(p) { this.setStyle({left : p+'px' }) } );
				
				if ($('logoRight') != null) $('logoRight').addClassName('over');
			}
		}
		else {
			working = 0;
			if (scrollLeft) scrollLeft.cancel();
			if (scrollRight) scrollRight.cancel();
			if ($('logoLeft') != null) $('logoLeft').removeClassName('over');
			if ($('logoRight') != null) $('logoRight').removeClassName('over');
		}
	}
}

/********************** Brand Activation ************************/

function setupBrandActivation () {
	
	setupCaseStudies ()
	
}

/********************** CASE STUDIES ************************/

function setupCaseStudies () {
	
	workCaseStudies ('setup')
	workCaseStudies ('pages')
	if ($('caseStudyLeft') != null) {
		
			$('caseStudyLeft').observe('click', function (e) {
				Event.stop(e);
				if (working<1 && galleryCurrentPage>1) {
					working=1;
					new Effect.Move('case-studies', { x:972, y: 0, mode: 'relative', transition: Effect.Transitions.spring, afterFinish: function(){ working=0; --galleryCurrentPage; }});
				}
			});
			$('caseStudyRight').observe('click', function (e) {
				Event.stop(e);
				if (working<1 && galleryCurrentPage<galleryPages) {
					working=1;
					new Effect.Move('case-studies', { x: -972, y: 0, mode: 'relative', transition: Effect.Transitions.spring, afterFinish: function(){ working=0; ++galleryCurrentPage; }});
				}
			});
		
	}
	loadCaseStudyVideo ();
	
}

function loadCaseStudyVideo () {
	if ($('vidBox') != null) {
					
		$('vidBox').addClassName('unHideIt');
		var l = $('vidLink').href,w=565,h=345;
		if (l.search('vimeo') > 0) {
			l = l.substring(l.lastIndexOf("/")+1);
			showVimeo (l, w, h, 'vidBox', 'ff0078');
		}
		else if (l.search('youtube') > 0) {
			l = l.split('watch?v=');
			showYouTube (l[1], w, h, 'vidBox');
		}
		else $('vidBox').removeClassName('unHideIt');
	
	}
}

function workCaseStudies (t) {
	var a=$$('ul#case-studies li div a[id^="caseStudy_"]');
	a.each(function(n){
		switch(t) {
		case 'setup':
			var b = n.id.split('_');
			Event.observe(n.id, 'click',function (e) {
				Event.stop(e);
				loadCaseStudy (b[1])
			});
			break;
		case 'removeActive':
			$(n.id).removeClassName('active');
			break;
		case 'pages':
			galleryPages = Math.ceil(a.length/3);
			break;
		}
   	});
}

function loadCaseStudy (id) {
	var aj = new Ajax.Request(baseURL+'ajaxStuff.php', {method: 'post', parameters: 'getCaseStudy='+id,onComplete: function(response) {
		var c = response.responseText.split('|||mmm|||');
		$('case_study_content').update(c[0]);
		$('case_study_images').update(c[1]);
		workCaseStudies ('removeActive')
		$('caseStudy_'+id).addClassName('active');
		loadCaseStudyVideo ();
	}});
}


/********************** ONLOAD ************************/

Event.observe( window, 'load',function () { 
	setUpAll(1)
	switch(thisPage) {
	case 'home':
	  setUpHome();
	  break;
	case 'blog':
	  setUpBlog();
	  break;
	case 'contact':
	  setUpContact();
	  break;
	case 'communications':
	  setupCommunications();
	  break;
	case 'digital':
	  setupDigital();
	  break;
	case 'brand-partnerships':
	  setupBrandPartnerships();
	  break;
	case 'brand-activation':
	  setupBrandActivation();
	  break;
	case 'about':
	  setupAbout();
	  break;
	case 'talent':
	  setupTalent();
	  break;
	}
});



