(function(){if(!this.Form){this.Form={}}var a=("placeholder" in document.createElement("input"));if(!("supportsPlaceholder" in this)&&this.supportsPlaceholder!==false&&a){this.Form.Placeholder=new Class({});return}this.Form.Placeholder=new Class({Implements:Options,options:{color:"#A9A9A9",clearOnSubmit:true},initialize:function(c,b){this.setOptions(b);this.element=$(c);this.placeholder=this.element.get("placeholder");this.original_color=this.element.getStyle("color");if(this.element.get("value")==""){this.element.setStyle("color",this.options.color);this.element.set("value",this.placeholder)}this.element.addEvents({focus:function(){if(this.element.get("value")==this.placeholder){this.element.set("value","");this.element.setStyle("color",this.original_color)}}.bind(this),blur:function(){if(this.element.get("value")==""){this.element.setStyle("color",this.options.color);this.element.set("value",this.placeholder)}}.bind(this)});if(this.element.getParent("form")&&this.options.clearOnSubmit){this.element.getParent("form").addEvent("submit",function(d){if(this.element.get("value")==this.placeholder){this.element.set("value","")}}.bind(this))}}})})();

window.addEvent('domready', function(){

	// placeholder
	$('container').getElements('input[placeholder], textarea[placeholder]').each(function(el){
		new Form.Placeholder(el);
	});

	// scripts loaded?
	SCRIPTSLOADED = 0;
	SCRIPTSARRAY = [];
	
	// css loaded
	CSSARRAY = [];
	
	if (location.hash == ''){
		location.href = 'index.php#!/home.php';
	}

	if (root = document.id('container')){
	
		// set up cache
		cache = new Cache();
		
		hash = '';
		
		// native anchor or page?
		nativeAnchor = function(hash){
			return (hash.indexOf('!') == -1);
		};
		
		// page title
		pageTitle = function(s){
			document.title = s + ' | Rend Collective Experiment';
		};
		
		// page error
		pageError = function(){
			
			// set page title
			pageTitle('Error');
			
			// load in error page
			changePage('!/error.php');
			
		};
		
		// change selected link
		changeLink = function(l){
				
			// which one is selected
			if (!l) l = root.getElement('.slides > div.selected a');
			if (!l) l = 'home';
						
			// coordinates
			var coords = root.getCoordinates();
		
			// not home page
			if (l != 'home'){
						
				// open close these
				root.getElement('.slides').getElements('> div')
				.each(function(el){
				
					(function(){
				
						if (el != l.getParent('div')){
							el.removeClass('selected');
							el.get('tween').cancel().start('left', coords.left-window.getSize().x);						
						} else {
							el.addClass('selected');
							el.get('tween').cancel().start('left', coords.right-window.getSize().x-180);
						}
					
					}.delay(Math.random() * 1000));
					
				});	
			
			} else {
			
				// open close these
				root.getElement('.slides').getElements('> div')
				.each(function(el){
				
					(function(){
					
						amt = (el.hasClass('shop') || el.hasClass('portraits')) ? 600 : 750;
						el.removeClass('selected').get('tween').cancel().start('left', coords.left-window.getSize().x+amt);
					
					}.delay(Math.random() * 1000));
					
				});	
			
			}
				
		};
		
		// replace paths
		replacePaths = function(el){
		
			// replace links
			el.getElements('a')
			.each(function(a){
				if (a.getProperty('href').indexOf('http://') == -1 && a.getProperty('href').indexOf('#') == -1){
					a.addEvent('click', function(ev){
					
						if (ev) ev.stop();
						location.href = 'index.php#!/' + this.getProperty('href');
						
					});
				}
			});
			
			// replace forms
			el.getElements('form')
			.each(function(f){
			
				if (f.getParent('div.search')) return;
			
				f.set('send', { method: 'post', onSuccess: function(j){ pageLoaderSuccess(JSON.decode(j)); }, headers: { 'HTTP_ACCEPT' : 'application/json' } });
				f.addEvent('valid', function(){
					f.send();
				})
				f.addEvent('submit', function(ev){
					ev.stop();
				});
			
			});
		
		};
		
		// store last hash
		lastHash = [];
		
		// change page
		changePage = function(hash2){
		
			// replace !/ from start
			hash = hash2.replace('!/', '');
			
			// add to last hash
			lastHash.push(hash);
			
			// no page
			if (hash == ''){
				hash == 'home.php';
			}
								
			// hash to array
			hashArray = hash.split('/');
										
			if (c = cache.get(hash)){
				pageLoaderSuccess(c);
			} else {
				pageLoader.setOptions({ 'url': hash + '?' + new Date().getTime() + (lastHash.length > 0 ? '&lh=' + lastHash[lastHash.length - 2] : '') }).send('');
			}
			
			
		};
		
		// called on json receipt
		pageLoaderSuccess = function(j){
							
			if (j){
						
				// are we on a main link now?
				root.getElement('.slides').getElements('a')
				.each(function(el){
				
					var myparts = el.getProperty('href').split('/');
					var hashparts = hash.split('/');
					
					if (el.getProperty('href') == hash || myparts[0] == hashparts[0]){
						changeLink(el);
					}
				
				});
				
				if (['error.php', 'home.php', 'contact.php'].contains(hash)){
					changeLink('home');
				}
				
				// clear form check
				try { fc.reset(); } catch(e){ };
								
				// page title
				if (j.title) pageTitle(j.title);
				
				actualscripts = 0;

				// scripts?
				if (j.scripts){
				
					j.scripts.each(function(s){
					
						if (!SCRIPTSARRAY.contains(s)){
				
							// load in js
							Asset.javascript('js/' + s, {
							    events: {
							        load: function(){
							            SCRIPTSLOADED++;
							            if (SCRIPTSARRAY.length == SCRIPTSLOADED){
							            	window.fireEvent('scriptsloaded');
							            }
							        }
							    }
							});
						
							actualscripts++;
							
							// add to scripts array
							SCRIPTSARRAY.push(s);
						
						}
					
					});
				
				}
	
				// content
				if (j.content){
				
					root.getElement('.content .ontop').tween('opacity', 0);
				
					(function(){
					
						// home page
						if (['error.php', 'home.php', 'contact.php'].contains(hash)){
							root.getElement('.content .ontop').setStyle('margin-left', 20);
							root.getElement('.content .ontop').setStyle('width', 550);
						} else if (hash.indexOf('gatherings/') != -1) {
							root.getElement('.content .ontop').setStyle('margin-left', 170);
							root.getElement('.content .ontop').setStyle('width', 730);
						} else if (hash.indexOf('hymns/') != -1) {
							root.getElement('.content .ontop').setStyle('margin-left', 190);
							root.getElement('.content .ontop').setStyle('width', 730);
						} else if (hash.indexOf('scrapbook/') != -1) {
							root.getElement('.content .ontop').setStyle('margin-left', 170);
							root.getElement('.content .ontop').setStyle('width', 720);
						} else if (hash.indexOf('shop/') != -1) {
							root.getElement('.content .ontop').setStyle('margin-left', 170);
							root.getElement('.content .ontop').setStyle('width', 720);
						} else if (hash.indexOf('portraits/') != -1) {
							root.getElement('.content .ontop').setStyle('margin-left', 180);
							root.getElement('.content .ontop').setStyle('width', 708);
						} else {
							root.getElement('.content .ontop').setStyle('margin-left', 280);
							root.getElement('.content .ontop').setStyle('width', 550);
						}
					
						root.getElement('.content .ontop').set('html', j.content).tween('opacity', 1);
						// .content .home is set to display: none
						// need to set to display: block
						// prevents load in of home page on page load
						if (root.getElement('.home')) {
							root.getElement('.home').setStyle('display','block');		
						}
						
					}.delay(1000));
				
				}
	
			
			// css
			if (j.css){
			
				j.css.each(function(s){
				
					if (!CSSARRAY.contains(s)){

						new Asset.css('css/' + s);
						
						// add to css array
						CSSARRAY.push(s);
						
					};
				
				});
			
			}
				// js
				if (j.js){
				
	            	window.removeEvents('scriptsloaded');
				
					window.addEvent('scriptsloaded', function(){
						window.f = new Function('ryan', j.js);
						window.f.delay(1300);
					});
				
					if (actualscripts == 0){
						window.fireEvent('scriptsloaded');
					}
				
				}
	
			}
	
		};
		
		// Returns the version of Internet Explorer or a -1
		// (indicating the use of another browser).
		getInternetExplorerVersion = function(){
		  var rv = -1; // Return value assumes failure.
		  if (navigator.appName == 'Microsoft Internet Explorer')
		  {
		    var ua = navigator.userAgent;
		    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
		    if (re.exec(ua) != null)
		      rv = parseFloat( RegExp.$1 );
		  }
		  return rv;
		};
			
		// set up json request
		pageLoader = new Request.JSON({ url: '/json.php', method: 'get' }).addEvent('success', pageLoaderSuccess).addEvent('failure', pageError);

		// get slides and manage
		if (slide = root.getElement('.slides')){
			
			// replace paths
			replacePaths(document.id(document.body));
		
			// set tween
			slide.getElements('> div').set('tween', { duration: 900, transition: Fx.Transitions.Back.easeInOut });
			
			// set initial left
			slide.getElements('> div').setStyle('left', document.id('container').getCoordinates().left-window.getSize().x);
			
			// resize events
			window.addEvent('resize', function(){
				changeLink();
				//slide.getElements('> div').each(function(el){
				//	if (!el.hasClass('selected')){
				//		el.setStyle('left', document.id('container').getCoordinates().left-window.getSize().x);
				//	}
				//});
			});
			
		};	
	
		// setup parallax effect
		new MooParallax($(document.body).getElements('.parallax'));
		
		// add hash change event
		window.addEvent('hashchange', function(hash){
		
			// native anchor, so scroll to it
			if (nativeAnchor(hash)){
				//alert('scroll to: ' + hash);
			} else {
				changePage(hash);
			}
		
		})
		.fireEvent('hashchange', location.hash.replace('#', ''));
	
	};

	if ($('frm-join-the-family')) {
		form = $('frm-join-the-family');
		form.getElement('p.submit input').addEvent('click', function(c){
			c.stop();
			new Request.JSON({
			  url: 'jointhefamily.php',
			  data: {
			    	method: 'post',
			        email: form.getElement('.email').get('value'),
			        name: form.getElement('.name').get('value')
			  }
			})
			.addEvent('success', function(j){
				if (j){
									
					if (j.Result) {
					
						switch (j.Result.Code) {
						
							case 1:
								message = '<p>There seems to have been a wee error.  Try again!</p>'
								form.getPrevious('.error').set('html',message);
							break;
							
							default :
								message = '<p>Thanks for joining the family! Download some treats below!</p>';
								message += '<ul>';
								message += '<li><a href="cmsfiles/downloads/who-are-rend.zip" target="_blank">Who we are Rend? Video</a></li>';
								message += '<li><a href="cmsfiles/downloads/you-bled-video.zip" target="_blank">Offical You Bled Video</a></li>';
								message += '<li><a href="cmsfiles/downloads/you-bled-chords.zip" target="_blank">Offical You Bled Chords</a></li>';
								form.getParent('.message').set('html',message);
							break;
						
						}
					
					}
				}
			})
			.send();
		});
	}
	
	if (root.getElement('.handle')) {
		root.getElement('.handle').addEvent('click', function(e){
			e.stop();
			
			root.getElement('.handle')
			.set({duration: 1000, transition: Fx.Transitions.Sine.easeOut}).morph({
				'background-position' : '0 -300',
				'height' : 500
			});


			root.getElement('.close').morph({
				'top': 20
			});
			root.getElement('.video-list').morph({
				'top': 30
			});
		});

		root.getElement('.close').addEvent('click', function(e){
			e.stop();
			
			root.getElement('.handle').morph({
				'background-position' : '0 -579',
				'height' : 215
			});
			
			root.getElement('.close').morph({
				'top': -307
			});
			
			root.getElement('.video-list').morph({
				'top': -307
			});
		});
		
		root.getElements('div.video-list ul li').addEvent('click', function(){
			root.getElements('div.video-list ul li').each(function(c) {
				if (c.hasClass('chosen')) {
					c.removeClass('chosen');
				}	
			});
			
			root.getElements('div.video-show').each(function(s){
				if (s.hasClass('chosen')) {
					s.removeClass('chosen');
				}
			});

			this.addClass('chosen');
			root.getElements('div.video-show')[this.getAllPrevious('li').length].addClass('chosen');
			
		});
		
		if (BOTTOMPLAYLIST = JSON.decode(BOTTOMPLAYLIST)){
				
			currentIndex = 0;

/*
			new MooPlayer('mp3playerbottom-player')
			.addEvent('loaded', function(){ 
				console.log(this);
				this.setFile.delay(100, this, ['/cmsfiles/siteclips/come-on.mp3']); 
				this.play.delay(500, this);
				this.stop.delay(600, this);
			});
*/
			// mp3 player
			var meeeee = new MooPlayer('mp3playerbottom-player')
			.addEvent('loaded', function(){ 
				this.setFile.delay(100, this, ['http://www.rendcollectiveexperiment.com/' + BOTTOMPLAYLIST[currentIndex]]); 
				this.play.delay(500, this);
				this.stop.delay(600, this);

				$('mp3playerbottom-player').getElements('.mooplayer-playlist ul li').each(function(t,i){
					if (i != 0) {
						t.setStyle('display', 'none');
					}
				});

			}); 
			
			meeeee.onSoundCompleteCustom = function(){
					
					goto = ++currentIndex % BOTTOMPLAYLIST.length;
								
					this.clearFile();
					this.setFile.delay(100, this, ['http://www.rendcollectiveexperiment.com/' + BOTTOMPLAYLIST[goto]]);
					this.play.delay(100, this);

					$('mp3playerbottom-player').getElements('.mooplayer-playlist ul li')
					.each(function(t, i){
						if (i != goto){
							t.setStyle('display', 'none');
						} else {
							t.setStyle('display', 'block');
						}
					});
	 		};
	 		
	 		// go forward
			$('mp3playerbottom-player').getElement('a.mooplayer-next')
			.addEvent('click', function(p){
				
				p.stop();

				goto = ++currentIndex % BOTTOMPLAYLIST.length;
						
				meeeee.clearFile();
				meeeee.setFile.delay(100, meeeee, ['http://www.rendcollectiveexperiment.com/' + BOTTOMPLAYLIST[goto]]);
				meeeee.play.delay(100, meeeee);

				$('mp3playerbottom-player').getElements('.mooplayer-playlist ul li')
				.each(function(t, i){
					if (i != goto){
						t.setStyle('display', 'none');
					} else {
						t.setStyle('display', 'block');
					}
				});

			});	

	 		// go back
			$('mp3playerbottom-player').getElement('a.mooplayer-previous')
			.addEvent('click', function(p){
				
				p.stop();

				goto = --currentIndex % BOTTOMPLAYLIST.length;
				
				if (goto < 0){
					goto = BOTTOMPLAYLIST.length - 1;
				}
						
				meeeee.clearFile();
				meeeee.setFile.delay(100, meeeee, ['http://www.rendcollectiveexperiment.com/' + BOTTOMPLAYLIST[goto]]);
				meeeee.play.delay(100, meeeee);

				$('mp3playerbottom-player').getElements('.mooplayer-playlist ul li')
				.each(function(t, i){
					if (i != goto){
						t.setStyle('display', 'none');
					} else {
						t.setStyle('display', 'block');
					}
				});

			});	
						
		}
		
	}

});
