var mT,inputV = new Array (),working=0,pageNum=1,isIE6,posMinHieght = 940;

if (navigator.userAgent.toLowerCase().indexOf('msie 6') == -1) notIE6 = true; else notIE6 = false;

function messageBox(message,secondsOut) {
	i='messageBox';
	if (mT) clearTimeout(mT);
	mT=null;
	if ($(i) != null) {
		$(i).update(message);
		centreElement (i,1);
		$(i).show();
		mT = setTimeout(function () { $(i).hide(); }, (secondsOut*1000));
	}
	else {
		alert('Message box doesn\'t exist');	
	}
}

function centreElement (e, vert) {
	var theScrolls = document.viewport.getScrollOffsets();
	theLeft = Math.floor(((document.viewport.getWidth())-($(e).getWidth()))/2) + theScrolls[0];
	theTop = Math.floor(((document.viewport.getHeight())-($(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(id,overlay) {
	var ov=1;
	if (overlay != null) {
		ov=0;
		$('pageOverlay').setStyle({ zIndex: overlay });
	}
	if (ov==1) $('pageOverlay').hide();
	$(id).hide();
}

function Select_Value_Set(SelectName, Value) {
  eval('SelectObject = document.' + 
    SelectName + ';');
  for(index = 0; 
    index < SelectObject.length; 
    index++) {
   if(SelectObject[index].value == Value)
     SelectObject.selectedIndex = index;
   }
}

function logInOut(l) {
	if (l==1) {
		if ($('user').present && $('pw').present) {
			var allNodes = Form.serialize('homeForm');
			var aj = new Ajax.Request(baseURL+'ajaxStuffAdmin.php', {method: 'post', parameters: 'logInOut=in&'+allNodes,onComplete: function(response) {
				var r = response.responseText;
				if (r=='You have been logged in') window.location.href = baseURL+'admin.php';
				messageBox(r,3)
			}});
		}
		else {
			messageBox('Please enter your username &amp; password',3)
		}
	}
	else {
		if (confirm("Are you sure?")) {
			var aj = new Ajax.Request(baseURL+'ajaxStuffAdmin.php', {method: 'post', parameters: 'logInOut=out',onComplete: function(response) {
				var r = response.responseText;
				if (r=='You have been logged out' && thisPage.search('admin') != -1) window.location.href = baseURL;
				else if (r=='You have been logged out') $('loginBoxOptions').hide();
			}});
		}
	}
}

function pageOverlay() {
	var theScrolls = document.viewport.getScrollOffsets();
	pageWidth = document.viewport.getWidth() + theScrolls[0]; pageHeight = document.viewport.getHeight() + theScrolls[1];
	if (pageWidth < $('mainContainer').getWidth()) pageWidth = $('mainContainer').getWidth();
	if (pageHeight < ($('mainContainer').getHeight()+127)) pageHeight = ($('mainContainer').getHeight()+127);
	$('pageOverlay').setStyle({ opacity: '0.5', display: 'block', width:pageWidth+'px', height:pageHeight+'px' });
	$('pageOverlay').show();
}

function showBox(id,noDrag) {
	pageOverlay();
	centreElement (id,1);
	$(id).show();
	if (noDrag==null) new Draggable(id, { scroll: window });
}

function readyForPost(t) {
	t = t.replace("‘","'");
	t = t.replace("’","'");
	return escape(t);
}

function encode_utf8(s) {
	return unescape( encodeURIComponent( s ) );
}

function decode_utf8 (s) {
	return decodeURIComponent( escape( s ) );
}

function clearInputBox(i,t,o,c) {
	if (o==1) {
		if ($F(i) == t) $(i).value='';
	}
	else if (o==2) {
		$(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 adminLogout () {
	var aj = new Ajax.Request(baseURL+'ajaxStuff.php', {method: 'post', parameters: 'adminLogout=1&'+allNodes,onComplete: function() {
		window.location.href = baseURL+'login/logout';
		messageBox('You have been logged out',8);
	}});
}

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=0x2d2d2d&autoplay="+auto, divID, width, height, "9.0.0","expressInstall.swf", flashvars, params, attributes);
}

function showJWPlayer (id,w,t) {
	var flashvars = {file: baseURL+'tracks/'+t};
	var params = {allowfullscreen: "true",allowscriptaccess: "always",wmode: "transparent"};
	var attributes = {};
	swfobject.embedSWF(baseURL+'jw_player/player2.swf', id, w, 24, "9.0.0","expressInstall.swf", flashvars, params, attributes);
}

function createSCPlayer (width, height, user, permalink, divID, set, type, colour, play) {
	if (set) user = user + '/sets';
	if (colour == null) colour = '6cff00';
	if (play == null) play = 'false';
	if (type == null || type != 'tiny') type = 'main';
	var flashvars = { url: "http://soundcloud.com/"+user+"/"+permalink,color: colour,player_type:type, auto_play:play};
	var params = {allowscriptaccess: "always",wmode: "transparent"};
	var attributes = {name: 'player'};
	swfobject.embedSWF("http://player.soundcloud.com/player.swf", divID, width, height, "9.0.0","expressInstall.swf", flashvars, params, attributes);
}

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 doSIFR (s,oL,oT,aL,sC,sBg,sCase) {
	if(typeof sIFR == "function"){
		sIFR.replaceElement(named({sSelector:s, sFlashSrc:sifrFont, sColor:sC, sLinkColor:"#000000", sBgColor:sBg, sHoverColor:"#CCCCCC",sCase:sCase,sWmode:"opaque", nPaddingTop:0, nPaddingBottom:0, sFlashVars:"textalign="+aL+"&offsetTop="+oT+"&offsetLeft="+oL+""}));
	};
}

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

function setUpAll () {
	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=$$('a[id^=readMore]'),i=1,b;
	a.each(function(n){
		$(n.id).stopObserving('click');
		if (i==1) b = n.id;
		Event.observe(n.id, 'click',function () { showOverlay (n.id,dbName) });
		++i;
	});
	if (thisPage=='current_news') posMinHieght = 1190
	if ($('overlay') != null) {
		if ($('overlay').getStyle('top') != '-2000px') setOverlayPosition ('readMore'+current_record,0,setXtra (dbName));
		else {
			$('overlay').setStyle({top:'-2020px'});
			if (thisPage != 'what_turns_us_on') showOverlay (b,dbName)
		}
		if ($('closeOL') != null) Event.observe('closeOL', 'click',function () { showOverlay (null,dbName,1) });
	}
}

var gotContent=0;
function showOverlay (i,table,ci) {
	if (working!=1) {
		working=1;
		if ($('overlay').getStyle('top') != '-2000px') {
			if ($('splitter2') != null) $('splitter2').fade({duration:0.5});
			Effect.Shrink('overlay', { duration: 0.5,direction:'bottom-left',afterFinish: function () {
				$('overlay').setStyle({top:'-2000px'});
				$('overlay').show();
				$('left').setStyle({height:'auto'});
				setTheHeight ();
				working=0;
				if (ci == null) showOverlay (i,table);
			}});
		}
		else if (gotContent != 1) {
			var aj1 = new Ajax.Updater('content',baseURL+'ajaxStuff.php', {method: 'post', parameters: 'getTextRecord='+table+'&id='+i,onComplete: function(response) {
				working=0;
				gotContent=1;
				showOverlay (i,table);
			}});
		}
		else {
			setOverlayPosition (i,1,setXtra (table));
			Effect.Grow('overlay', { duration: 0.5,direction:'bottom-left',afterFinish:function() { working=0; gotContent=0; } });
		}
	}
}

function setXtra (t) {
	if (t==null) t='m';
	switch(t) {
		case 'services':
			return 36;
			break;
		case 'news':
			return 40;
			break;
		default:
			return 40;
	}
}

function setUpHome () {
	var aj1 = new Ajax.Updater('tweets',baseURL+'ajaxStuff.php', {method: 'post', parameters: 'loadTweets=1'});
}

function setTheHeight () {
	var b=parseInt($('left').getHeight()),c=parseInt(posMinHieght);
	if (b < c) $('left').setStyle({height:posMinHieght+'px'});
}

function setOverlayPosition (i,h,xtra) {
	var b = $('content').getHeight()-37-12,d = $(i).cumulativeOffset (),readMoreFromTop= d[1]+6,z=0;
	var ovTop = readMoreFromTop-b;
	if (xtra) ovTop = ovTop - xtra;
	if (ovTop<70) {
		z = 70-ovTop;
		ovTop = 70;
	}
	$('middle1').setStyle({height:(b-z)+'px'});
	$('point').setStyle({top:(b+6-z)+'px'});
	$('middle3').setStyle({height:(12+z)+'px'});
	$('overlay').setStyle({top:ovTop+'px'});
	if (h) $('overlay').hide();
	if ( ($('left').getHeight()-34) < ($('overlay').getHeight() +50) ) $('left').setStyle({height:($('overlay').getHeight() +50)+'px'});
	if (dbName=='services') {
		var d = $(i).cumulativeOffset (),readMoreFromTop= d[1]+10,f=$(i).getWidth();
		var e = 359 - f;
		readMoreFromLeft = f+18;
		$('splitter2').setStyle({ left:readMoreFromLeft+'px',top:readMoreFromTop+'px',width:(359-readMoreFromLeft+15)+'px' });
		$('splitter2').appear({duration:0.5});
	}
}

function setUpPositive () {
	setUpImages ()
	setTheHeight ();
}

function setUpNews () {
	setUpImages ()
	setTheHeight ();
}

function setUpImages () {
	var a=$$('a[id^=pic]');
	a.each(function(n){
		var p = n.id.split("_"),b=$$('a[id^=pic_'+p[1]+']');
		Event.observe(n.id, 'click',function () { loadImageBox (n.id,b.length) });
	});
}

function loadImageBox (i,n) {
	$('close').stopObserving('click');
	Event.observe('close', 'click',function () {
		$('imageBox2').update('');
		closeBox('imageBox');
	});
	var p = i.split("_"),im=$(i).href.split("?d="),im2=im[1].split("x"),a1,a2,id;
	$('imageBox').setStyle({ width:parseInt(im2[0])+'px',height:(parseInt(im2[1])+24)+'px' });
	$('imageBox2').setStyle({ width:im2[0]+'px',height:im2[1]+'px',marginBottom:'8px' });
	if (n>1) {
		p[2] = parseInt(p[2]);
		if (p[2]<n) id = 'pic_'+p[1]+'_'+(p[2]+1);
		else id = 'pic_'+p[1]+'_1';
		a1 = '<a href="#" onclick="loadImageBox (\''+id+'\','+n+'); return false;">',a2='</a>';
	}
	else a1='',a2='';
	$('imageTitle').update($(i).title);
	$('imageBox2').update(a1+'<img src="'+im[0]+'" alt="'+$(i).title+'" />'+a2);
	showBox('imageBox',1);
}

function setUpConnect () {
	$('close').stopObserving('click');
	Event.observe('close', 'click',function () {
		$('imageBox2').update('');
		closeBox('imageBox');
	});
	Event.observe('map', 'click',function () {
		var w=700,h=600;
		$('imageBox').setStyle({ width:w+'px',height:(h+24)+'px' });
		$('imageBox2').setStyle({ width:w+'px',height:h+'px',marginBottom:'8px' });
		showBox('imageBox',1);
		$('imageBox2').update('<iframe width="'+w+'" height="'+h+'" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.co.uk/maps?q=wired+events+EC4N+7AE&amp;hl=en&amp;cd=1&amp;ei=m3QGTKSWN5bUjAenqOHLCA&amp;sig2=AOQ7Syy2G9jTfFfK1oEXlg&amp;sll=51.511694,-0.086625&amp;sspn=0.011899,0.033023&amp;ie=UTF8&amp;view=map&amp;cid=14902450238414533669&amp;hq=wired+events+EC4N+7AE&amp;hnear=&amp;ll=51.511528,-0.086626&amp;spn=0.006295,0.006295&amp;t=h&amp;iwloc=A&amp;output=embed"></iframe>');
	});
	Event.observe('submit', 'click',function () {
		if ($F('name')=='' || $F('name')=='Name' || $F('email')=='' || $F('email')=='Email' || $F('enquiry')=='' || $F('enquiry')=='Enquiry') 
			messageBox('Please enter all fields',3);
		else if (isValidEmail($F('email'))) {
			var allNodes = Form.serialize('contactForm');
			var aj = new Ajax.Request(baseURL+'ajaxStuff.php', {method: 'post', parameters: 'contactUs=1&'+allNodes,onComplete: function(response) {
				messageBox(response.responseText,3);
				$('contactForm').reset();
			}});
		}
		else messageBox('Please enter a valid email address',3);
	});
}


Event.observe( window, 'load',setUpAll);
if (thisPage == 'home')
	Event.observe( window, 'load',setUpHome);
if (thisPage == 'positive')
	Event.observe( window, 'load',setUpPositive);
if (thisPage == 'current_news')
	Event.observe( window, 'load',setUpNews);
if (thisPage == 'connect')
	Event.observe( window, 'load',setUpConnect);