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,selectedGallery,selectedGalleryItem,type='image';

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

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);
}

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) });
}

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 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);
}


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

function setUpAll (n) {
	if (n) {
		if (thisPage != 'bio') {
		var a=$$('form');
		a.each(function(n){
			$(n.id).reset();
		});
		}
	}
	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 sc1 = scTop.split('/');
	createSCPlayer (490, 18, sc1[0], sc1[1], 'soundcloud-player', null, 'tiny', 'FFFFFF');
	Event.observe('twitterText', 'keypress',twitterCharsLeft);
	Event.observe('twitterText', 'keydown',twitterCharsLeft);
	Event.observe('twitterText', 'keyup',twitterCharsLeft);
	Event.observe('twitter', 'click',function(){twitterPost(1)} );
	twitterPost();
}

function checkCookie(n) {
	var c = getCookie(n);
	if (c!=null && c!="") return true
	else return false;
}

function getCookie(c_name) {
	if (document.cookie.length>0)
	  {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1)
		{
		c_start=c_start + c_name.length+1;
		c_end=document.cookie.indexOf(";",c_start);
		if (c_end==-1) c_end=document.cookie.length;
		return unescape(document.cookie.substring(c_start,c_end));
		}
	  }
	return "";
}

function setCookie(c_name,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}



function twitterPost (m) {
	if (checkCookie('oauth_token') && checkCookie('oauth_token_secret')) {
		if ($('twitterText').present()) {
			var allNodes = Form.serialize('twitterForm');
			var aj = new Ajax.Request(baseURL+'ajaxStuff.php', {method: 'post', parameters: 'twitterPost=1&'+allNodes,onComplete: function(response) {
				$('twitterText').value='';
				twitterCharsLeft ();
				getTweets ();
				setCookie('twitterPost','',0);
				messageBox('Your text has been tweeted.',3);
			}});
		}
	}
	else {
		if ($('twitterText').present()) setCookie('twitterPost',$F('twitterText'),2);
		if (m){
			setCookie('twitterRedirectURL',window.location,2);
			var aj = new Ajax.Request(baseURL+'ajaxStuff.php', {method: 'post', parameters: 'getAuthoriseURL=1',onComplete: function(response) {
				var url = response.responseText;
				window.location = url;
			}});
		}
	}
}

function getTweets () {
	//clearTimeout(twitTime)
	var aj = new Ajax.Updater('twitterMentions',baseURL+'ajaxStuff.php', {method: 'post', parameters: 'loadTwitter=1&type=mentions'});
	var aj2 = new Ajax.Updater('johnsTwitterFeed',baseURL+'ajaxStuff.php', {method: 'post', parameters: 'loadTwitter=1&type=user'});
	//twitTime = setTimeout(getTweets,300000);
}

function twitterCharsLeft () {
	$('twitChars').update((twitterCharMax-$F('twitterText').length));
	if ($F('twitterText').length>twitterCharMax) $('twitterText').value = $F('twitterText').substring(0,twitterCharMax);
}

/********************** LIVE DATES ************************/

function setUpLiveDates() {
	
	if ($('eventsList') != null) $('mainContainer').observe('mousemove', getcords);
	
}

function loadDateOV(i) {
	if ($('event-details') != null) $('event-details').remove();
	new Ajax.Updater('liveMain', baseURL+'ajaxStuff.php', {
	  parameters: 'getDate='+i ,
	  onComplete: function () { $('event-details').appear(); },
	  insertion: 'bottom'
	});
}

var scrollLeft,scrollRight;
function getcords(e){
	var mainCont = 'eventsList', wrapper = 'eventsCont';
	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');
		}
	}
}

/********************** GALLERY ************************/

function setUpGallery () {
	if ($('vids') != null) type = 'Vimeo,YouTube';
	$('scrollLeft').observe('click', function () {
		if (working<1 && galleryCurrentPage>1) {
			working=1;
			new Effect.Move('content', { x: 596, y: 0, mode: 'relative', transition: Effect.Transitions.spring, afterFinish: function(){ working=0; --galleryCurrentPage; }});
		}
	});
	$('scrollRight').observe('click', function () {
		if (working<1 && galleryCurrentPage<galleryPages) {
			working=1;
			new Effect.Move('content', { x: -596, y: 0, mode: 'relative', transition: Effect.Transitions.spring, afterFinish: function(){ working=0; ++galleryCurrentPage; }});
		}
	});
	setupGalleryObserves();
	setupGalleryPageObserves ();
	selectPage(pageNum,'galleryPages');
}

function setupGalleryObserves () {
	var a=$$('#galleryAlbums li a img'),i=1;
	if (a.length<1) {
		resetGalleryContent ();
		$('content').update('No Results');
		selectedGallery = null;
	}
	a.each(function(n){
		//$(n.id).setOpacity('0.5');
		if (i<2) {
			//$(n.id).setOpacity('1.0');
			loadGallery (n.id);
		}
		$(n.id).stopObserving('mouseout');
		$(n.id).stopObserving('mouseover');
		//Event.observe(n.id, 'mouseover',function () { $(n.id).setOpacity('1.0'); });
		//Event.observe(n.id, 'mouseout',function () { if ('gal_'+selectedGallery != n.id) $(n.id).setOpacity('0.5'); });
		Event.observe(n.id, 'click',function () { loadGallery (n.id); });
		++i;
	});
}

function setupGalleryItemObserves (l) {
	var a=$$('ul#content li a img'),t,r,i=1;
	galleryPages = Math.ceil(a.length/4);
	$('content').setStyle({ width:(a.length*149)+'px'});
	a.each(function(n){
		//$(n.id).setOpacity('0.5');
		if (i<2) loadGalleryItem(n.id);
		$(n.id).stopObserving('mouseout');
		$(n.id).stopObserving('mouseover');
		//Event.observe(n.id, 'mouseover',function () { $(n.id).setOpacity('1.0'); });
		//Event.observe(n.id, 'mouseout',function () { if (selectedGalleryItem != n.id)  $(n.id).setOpacity('0.5'); });
		Event.observe(n.id, 'click',function () { if (selectedGalleryItem != n.id) loadGalleryItem(n.id,1); });
		++i;
	});
}

function setupGalleryPageObserves () {
	var a=$$('#galleryPages li a'),r;
	a.each(function(n){
		$(n.id).observe('click',function(){showGalleryPage(n.id)});
	});
}

function resetGalleryContent () {
	if (selectedGalleryItem) {
		if ((selectedGalleryItem.search('Vimeo')>=0) || (selectedGalleryItem.search('YouTube')>=0)) {
			swfobject.removeSWF('mainContent');
			$('mainContentContainer').update('<div id="mainContent"></div>');
		}
		else $('mainContent').update();
	}
	$('imageTitle').update('');
	$('imageText').update('');
}

function loadGalleryItem(i,a) {
	resetGalleryContent ();
	//$(i).setOpacity('1.0');
	selectedGalleryItem = i;
	if (a == null) a=0;
	var v,r;
	$('mainContent').setStyle({paddingLeft: '0px'});
	if (i.search('image')>=0) {
		v = i.split('_');
		//var pad = Math.ceil(($('mainContent').getWidth()-v[2])/2);
		//$('mainContent').setStyle({paddingLeft: pad+'px'});
		r = $(i).src.replace('thumbnail','main');
		$('mainContent').update('<img src="'+r+'" width="'+v[2]+'" height="'+v[3]+'" />');
	}
	if (i.search('Vimeo')>=0) {
		v = i.replace('Vimeo_','').split('||');
		showVimeo (v[0], 637, 357, 'mainContent', 'ff0000',a);
	}
	if (i.search('YouTube')>=0) {
		v = i.replace('YouTube_','').split('||');
		showYouTube (v[0], 637, 357, 'mainContent',a);
	}
	loadGalleryItemText (v[1]);
}

function loadGalleryItemText (i) {
	$('imageTitle').update();
	$('imageText').update();
	var aj1 = new Ajax.Request(baseURL+'ajaxStuff.php', {method: 'post', parameters: 'getGalleryItemInfo='+i,onComplete: function(response) {
		var reply = response.responseText.split('||message||');
		$('imageTitle').update(reply[1]);
		$('imageText').update(reply[3]);
	}});
}

function loadGallery (i) {
	var galID = i.replace('gal_',''),m=0;
	if (galID != selectedGallery || selectedGallery == null) {
		//if (selectedGallery && $('gal_'+selectedGallery) != null) $('gal_'+selectedGallery).setOpacity('0.5');
		selectedGallery = galID;
		//$(i).setOpacity('1.0');
		if (galleryCurrentPage>1) {
			--galleryCurrentPage;
			m = galleryCurrentPage * 596;
			galleryCurrentPage=1;
		}
		var aj1 = new Ajax.Updater('content',baseURL+'ajaxStuff.php', {method: 'post', parameters: 'getGalleryItems='+galID+'&type='+type,onComplete: function(response) {
			new Effect.Move('content', { x: m, y: 0, mode: 'relative', transition: Effect.Transitions.full});
			setupGalleryItemObserves (1);
		}});
	}
}

function showGalleries (p) {
	var aj1 = new Ajax.Updater('galleryAlbums',baseURL+'ajaxStuff.php', {method: 'post', parameters: 'getGalleries='+p+'&type='+type,onComplete: function(response) {
		setupGalleryObserves ();
	}});
}

function selectPage(i,ulID) {
	var a=$$('#'+ulID+' li a');
	a.each(function(n){
		if ($(n.id).hasClassName('active')) $(n.id).removeClassName('active');
	});
	if ($('page'+i)) $('page'+i).addClassName('active');
}

function showGalleryPage (p) {
	if ($(p) != null) {
		p=p.replace('page','');
		if (p != pageNum) {
			pageNum = p;
			selectPage(p,'galleryPages');
			showGalleries (p);
		}
	}
}
function galleryPageBack () {
	var f = parseInt(pageNum) -1;
	showGalleryPage ('page'+f)
}
function galleryPageNext () {
	var f = parseInt(pageNum) +1;
	showGalleryPage ('page'+f)
}

/********************** LISTEN ************************/

function setupListen () {
	var a=$$('.paging ul li a'),z;
	a.each(function(n){
		z = n.id.replace('p','');
		if ($(n.id).hasClassName('active')) pageNum=z;
	});
	Event.observe( 'pBack', 'click',function (e) { Event.stop(e); listenPageMove ('-'); });
	Event.observe( 'pNext', 'click',function (e) { Event.stop(e); listenPageMove ('+'); });
}

function loadListenPage (pg) {
	if (parseInt(pg) != parseInt(pageNum)) {
		var a=$$('.paging ul li a'),b;
		a.each(function(n){
			$(n.id).removeClassName('active');
		});
		pageNum=pg;
		$('p'+pg).addClassName('active');
		var aj1 = new Ajax.Updater('scTracks',baseURL+'ajaxStuff.php', {method: 'post', parameters: 'getListen='+pg});
	}
	else (parseInt(pg) +'---'+ parseInt(pageNum));
}

function listenPageMove (type) {
	var i;
	pageNum = parseInt(pageNum);
	if (type=='+') {
		i = pageNum + 1;
		if ($('p'+i) != null) loadListenPage (i)
	}
	else {
		if (pageNum>1) {
			i = pageNum - 1;
			loadListenPage (i)
		}
	}
	
}

/********************** VAULT ************************/

function setupVault () {
	var f = 'signupform1';
	Event.observe( 'signupform1', 'submit', function (e) {
		Event.stop(e);
		if (badField (f)) {
			messageBox('Please enter all fields');
		}
		else if (isValidEmail($F('email'))) {
			var vars = 'signup=1&'+$(f).serialize();
			if ($('notify').checked==true) vars = vars +'&notify=1';
			var aj1 = new Ajax.Request(baseURL+'ajaxStuff.php', {method: 'post', parameters: vars, onComplete: function (r) {
				$(f).reset();
				messageBox(r.responseText);
			}});
		}
		else messageBox('Please enter a valid email address');
	});
	
}

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

Event.observe( window, 'load',function () { 
	setUpAll(1)
	switch(thisPage) {
	case 'live':
	  setUpLiveDates();
	  break;
	case 'gallery':
	  setUpGallery ();
	  break;
	case 'gallery video':
	  setUpGallery ();
	  break;
	case 'listen':
	  setupListen ();
	  break;
	case 'vault':
	  setupVault ();
	  break;
	}
});
