var mT, inputV = new Array (),pageNum=1,pageTotal=1, isIE6 = false, working=0, working2 = new Array (), mem = new Array (), mem2 = new Array (), uploadedFile = new Array (), missingList = new Array(), errorList = new Array(),timer,timer2,timer3,time;

if (navigator.userAgent.toLowerCase().indexOf('msie 6') != -1) isIE6 = true;

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


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 tinyMCEStuff (i,t) {
	if (t == 'focus') {
		tinyMCE.execCommand('mceAddControl', false, i);
		tinyMCE.execInstanceCommand("mceFocus",false,i);	
	}
	if (t == 'remove') {
		tinyMCE.execCommand('mceRemoveControl', false, i);	
	}
	if (t == 'get') {
		return tinyMCE.get(i).getContent();	
	}
}

function ajaxText (f) {
	var c = '', h = 'hiddenField', r, i,dd;
	
	r = f.split(',');
	r.each(function(i){
		
		var t = $(i).tagName.toLowerCase()
		
		if (t=='form') {
			
			var fi = $$('#'+f+' input[type="email"]', '#'+f+' input[type="text"]', '#'+f+' input[type="password"]', '#'+f+' textarea', '#'+f+' select').uniq().compact(),ff = new Array();
			
			fi.each(function(n){
				if (n.id.blank()==false) ff.push(n.id);
			});
			if (ff.length>0) c = c + ajaxText (ff.join());
			
		}
		else {
			var p = $(i).getOffsetParent();
			$(p).insert('<input type="hidden" id="'+p+'_'+h+'" name="'+i+'_2" />');
			if ($(i).hasClassName('tinyMCE')) {
				
				$(p+'_'+h).setValue(tinyMCE.get(i).getContent());
				
			}
			else if (t=='textarea' || (t=='input' && ($(i).type=='text' || $(i).type=='password' || $(i).type=='email'))) {
				
				$(p+'_'+h).setValue($F(i).replace("‘","'").replace("’","'"));
				if (($(i).type=='text' && $(i).hasClassName('email')==false && $(i).hasClassName('noEnt')==false) || ($(i).type =='textarea' && $(i).hasClassName('noEnt')==false)) $(p+'_'+h).setValue(htmlentities($F(p+'_'+h)));
				if (t=='textarea' && $(i).hasClassName('noBR')==false) $(p+'_'+h).setValue(nl2br($F(p+'_'+h),true));
			}
			else if (t=='select') {
				$(p+'_'+h).setValue($F(i));
			}
			c = c+'&'+$(p+'_'+h).serialize();
			$(p+'_'+h).remove();
				
		}
	});
	return c;
}

function nl2br (str, is_xhtml) {
    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';

    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}

function br2nl (str) {
    return str.replace(/<br\s*\/?>/mg,"\n");
}


function errorMessage (errTtl,missTtl) {
	
	if (errTtl == null) errTtl = 'Please rectify the following errors:';
	if (missTtl == null) missTtl = 'The following fields are missing:';
	
	var t='';
	
	if (missingList.length>0) {
		
		t = t + missTtl+'<br /><br />';
		
		missingList.each(function(n){
		
			t = t + n+'<br />';
		
   		});
		
	}
	if (errorList.length>0) {
		
		if (t != '') t = '<br />'+t;
		
		t = t + errTtl+'<br /><br />';
		
		errorList.each(function(n){
		
			t = t + n+'<br />';
		
   		});
		
	}
	missingList.clear();
	errorList.clear();
	messageBox(t);
}

// f = a comma seperated string of form ID's, exFl = a comma seperated string of field ID's to exclude
function validateForm (q,exFl) {
	if (exFl != null) exFl = exFl.split(',');
	else exFl = new Array();
	var form = q.split(',');
	form.each(function(f){
		
		$$('#'+f+' input[type="text"]').each(function(n){

			if (inputV[n.id]==null) inputV[n.id] = '';
			if ( ($F(n.id)=='' || $F(n.id)==inputV[n.id]) && (exFl.lastIndexOf(n.id)<0) && $(n.id).hasClassName('mandatory') ) {
				
				if ($$('label[for="'+n.id+'"]')[0] != null) missingList.push($$('label[for="'+n.id+'"]')[0].innerHTML);
				
			}
			else if ( ($(n.id).hasClassName('email')) && (isValidEmail($F(n.id))==false) ) {
				
				if ($$('label[for="'+n.id+'"]')[0] != null) errorList.push($$('label[for="'+n.id+'"]')[0].innerHTML +' - the email doesn\'t appear to be correct');
				
			}
			
		});
		
		$$('#'+f+' input[type="email"]').each(function(n){
			if (inputV[n.id]==null) inputV[n.id] = '';
			if (exFl.lastIndexOf(n.id)<0 && $(n.id).hasClassName('mandatory')) {
			
				if ($F(n.id)=='' || $F(n.id)==inputV[n.id]) {
					
					if ($$('label[for="'+n.id+'"]')[0] != null) missingList.push($$('label[for="'+n.id+'"]')[0].innerHTML);
					
				}
				else if (isValidEmail($F(n.id))==false) {
					
					if ($$('label[for="'+n.id+'"]')[0] != null) errorList.push($$('label[for="'+n.id+'"]')[0].innerHTML +' - the email doesn\'t appear to be correct');
					
				}
			
			}
			
		});
		
		$$('#'+f+' input[type="password"]').each(function(n){
			if (inputV[n.id]==null) inputV[n.id] = '';
			if (exFl.lastIndexOf(n.id)<0 && $(n.id).hasClassName('mandatory')) {
			
				if ($F(n.id)=='' || $F(n.id)==inputV[n.id]) {
					
					if ($$('label[for="'+n.id+'"]')[0] != null) missingList.push($$('label[for="'+n.id+'"]')[0].innerHTML);
					
				}
			
			}
			
		});
		
		$$('#'+f+' select').each(function(n){
			
			if (exFl.lastIndexOf(n.id)<0 && $(n.id).hasClassName('mandatory')) {
				
				if ($F(n.id)=='0') {
					
					if ($$('label[for="'+n.id+'"]')[0] != null) missingList.push($$('label[for="'+n.id+'"]')[0].innerHTML);
					else alert(n.id);
					
				}
			
			}
			
		});
		
		$$('#'+f+' textarea').each(function(n){
			if (inputV[n.id]==null) inputV[n.id] = '';
			if (exFl.lastIndexOf(n.id)<0 && $(n.id).hasClassName('mandatory')) {
			
				var c = $F(n.id);
			
				if ($(n.id).hasClassName('tinyMCE')) {
					c = tinyMCE.get(n.id).getContent().stripScripts().stripTags();
				}
				if (c=='' || c==inputV[n.id]) {
					
					missingList.push($$('label[for="'+n.id+'"]')[0].innerHTML);
					
				}
			
			}
			
		});
	});
	if (missingList.length < 1 && errorList.length < 1) return true; else return false;
}

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 html_entity_decode(str) {
    var  tarea=document.createElement('textarea');
    tarea.innerHTML = str; return tarea.value;
    tarea.parentNode.removeChild(tarea);
}

var cc=0;
function replaceT(i,newType,value){
	++cc;
	var theID = 'inID_'+cc;
	var newO=document.createElement('input');
	newO.setAttribute('type',newType);
	newO.setAttribute('name',$(i).getAttribute('name'));
	//newO.setAttribute('id',theID);
	newO.setAttribute('id',$(i).getAttribute('id'));
	$(i).parentNode.replaceChild(newO,$(i));
	theID = $(i).getAttribute('id')
	$(theID).addClassName('text');
	setTimeout(function() {
		if (newType=='text') $(theID).value = value;
		else $(theID).activate();
		$(theID).addClassName('text');
	}, 10);
	if (newType=='password') Event.observe(theID, 'blur',function () { if ($F(theID)=='' || $F(theID)==null) replaceT(theID,'text',value) });
	else Event.observe(theID, 'focus',function () { replaceT(theID,'password',value) });
}


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

function setUpAll (n) {
	var doIt;
	if (n) {
		var a=$$('form');
		a.each(function(n){
			$(n.id).reset();
		});
	}
	var a=$$('input[type="text"]','textarea','input[type="password"]','input[type="email"]');
	a.each(function(n){
		if (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 f1 = 'newsletterForm';
	if ($(f1) != null) {
		Event.observe(f1, 'submit',function (e) {
			Event.stop(e);
			if (working==0) {
				if (validateForm (f1)) {
					working=1;
					var aj1 = new Ajax.Request(baseURL+'ajaxStuff.php', {method: 'post', parameters: 'newsletter=1'+ajaxText (f1),onComplete: function(resp) {
						working=0;
						messageBox(resp.responseText);
						$(f1).reset();
					}});
				}
				else errorMessage ();
			}
		});
		
	}
	var a=$$('a.share[id^=share-]');
	a.each(function(n){
		addthis.button("#"+n.id, {}, {url: $(n.id).href, title: $(n.id).title, data_track_clickback: true, ui_click: true, addthis_button_tweet: true });		
	});
}


function setupHome () {
	
	getSliderPics ('pageHome');
	
}

function setUpContact () {
	var f3 = 'contactForm';
	
	if ($(f3) != null) {
		
		Event.observe(f3, 'submit',function (e) {
			Event.stop(e);
			if (working==0) {
				
				if (validateForm (f3)) {
					working=1;
					var aj1 = new Ajax.Request(baseURL+'ajaxStuff.php', {method: 'post', parameters: 'contact=1'+ajaxText(f3),onComplete: function(resp) {
						working=0;
						messageBox(resp.responseText);
						$(f3).reset();
					}});
				}
				else errorMessage ();
			}
		});
		
	}
}

function setUpServices () {
	var t;
	if ($('body').hasClassname('apps')) t = 'apps';
	if ($('body').hasClassname('web')) t = 'web';
	if ($('body').hasClassname('media')) t = 'apps';
	getSliderPics (t);
}

function getSliderPics (t) {
	
	var aj1 = new Ajax.Updater('slider',baseURL+'ajaxStuff.php', {method: 'post', insertion: Insertion.Bottom, parameters: 'sliderPics='+t,onComplete: function(resp) {
		
		var banners = $$('ul#slider li'),i=1;
		pageTotal = banners.length;
		var f = Math.floor(Math.random()*4);
		banners.each(function (n) {
			var tt = n.id.replace('bannerBox','');
			$('textBox_1_'+tt).setOpacity(0);
			$('textBox_2_'+tt).setOpacity(0);
			$('textBox_1_'+tt).show();
			$('textBox_2_'+tt).show();
		} );
		$('textBox_1_'+pageNum).addClassName(bgTranPos[f]);
		$('textBox_2_'+pageNum).addClassName(bgTranPos[f]);
		var f1 = new Effect.Fade('textBox_1_'+pageNum, { duration: 1.0, from: 0, to: 0.7 });
		var f2 = new Effect.Fade('textBox_2_'+pageNum, { duration: 1.0, from: 0, to: 1 });
		if (pageTotal>1) {
			
			$('sc').insert('<ul id="pages" style="display:none"></ul>');
			var iii=1;
			while (iii<=pageTotal) {
				$('pages').insert('<li><a href="#" onclick="doBanner ('+iii+'); return false;" id="page'+iii+'"></a></li>');
				++iii;
			}
			$('pages').appear();
			$('page1').addClassName('active');
			banners.each(function (n) {
			
				if (i==1) {
					
					$(n.id).setStyle({ position: 'absolute', left:'0px', top:'0px' });
					
				}
				else {
					
					$(n.id).setStyle({ position: 'absolute', left:'974px', top:'0px' });
					
				}
				++i;
			} );
			
			slideTime=setInterval(function () { doBanner (); },5000);
		}
		
	}});
	
}
var bgTranPos = new Array('bottom-left','bottom-left','bottom-left','bottom-left'),slideTime;

function doBanner (ii) {
	
	var resetIt=false;
	if (ii==null) {
		if (pageNum==pageTotal) ii=1; else ii=pageNum+1;
	}
	else resetIt=true;
	
	if (working==0 && ii != pageNum) {
		$('page'+pageNum).removeClassName('active');
		if (resetIt==true) clearInterval(slideTime);
		working=1;
		$$('ul#slider li').each( function (n) { $(n.id).setStyle({zIndex:3}); });
		var eff = new Array(),old,b='bannerBox',i=1;
		old=pageNum;
		$(b+old).setStyle({zIndex:2});
		eff[i] = new Effect.Move(b+ii, { x: -974, y: 0, mode: 'relative', afterFinish: function(){
			$('textBox_1_'+old).setOpacity(0);
			$('textBox_2_'+old).setOpacity(0);
			removeAllCssClasses('textBox_1_'+old);
			removeAllCssClasses('textBox_2_'+old);
			$('textBox_1_'+old).addClassName('background-transparency');
			$('textBox_2_'+old).addClassName('transparency-content');
			var f = Math.floor(Math.random()*4);
			$('textBox_1_'+ii).addClassName(bgTranPos[f]);
			$('textBox_2_'+ii).addClassName(bgTranPos[f]);
			var f1 = new Effect.Fade('textBox_1_'+ii, { duration: 1.0, from: 0, to: 0.7 });
			var f2 = new Effect.Fade('textBox_2_'+ii, { duration: 1.0, from: 0, to: 1 });
			working=0;
			$('page'+ii).addClassName('active');
			pageNum=ii;
		}});
		++i;
		eff[i] = new Effect.Move(b+old, { x: -974, y: 0, mode: 'relative', afterFinish: function(){ $(b+old).setStyle({ left:'974px' }); }});
		++i;
		
		if (resetIt==true) slideTime=setInterval(function () { doBanner (); },8000);
		
	}
	
}

//////// WORK ///////////

function blastImage (num) {
	$('colour'+num).setStyle({opacity: 0.0 });
	new Effect.Tween('colour'+num, 0, 100, { duration: 0.8} , function(p) { this.setStyle({opacity : (p/100) }) } );
	new Effect.Tween('bw'+num, 100, 0, { duration: 0.8} , function(p) { this.setStyle({opacity : (p/100) }) } );
}

function blastImageOff (num) {
	new Effect.Tween('bw'+num, 0, 100, { duration: 0.8} , function(p) { this.setStyle({opacity : (p/100) }) } );
	new Effect.Tween('colour'+num, 100, 0, { duration: 0.8} , function(p) { this.setStyle({opacity : (p/100) }) } );
}

function doImages () {
	blastImage(box);
	++box;
	if (box > boxes ) {
		if (timer) clearInterval(timer);
	}
}

function unDoImages () {
	blastImageOff(box2);
	++box2;
	if (box2 > boxes ) {
		if (timer2) clearInterval(timer2);
	}
}

function doIt () {
	box=1;
	box2=1;
	if ( Prototype.Browser.IE ) time=7800
	else time=6800
	if (timer2) clearInterval(timer2);
	if (timer) clearInterval(timer);
	timer = setInterval("doImages()",100);
  	setTimeout( function () { timer2 = setInterval("unDoImages ()",100); },2000);
}


function removeAllCssClasses(el) {
	$w($(el).className).each(function(c){$(el).removeClassName(c);})
}

Event.observe( window, 'load',function () { 
	
	setUpAll(1) 

	switch (thisPage) {
		case 'home':
			setupHome ();
			break;
		case 'contact':
			setUpContact ();
			break;
		case 'work':
			doIt (); timer3 = setInterval(doIt,time);
			break;
		  
	}
});
