function openRssItem(id) {
	var rssItem = $('#rss-item-'+id);
	rssItem.children('.rss-item-maincontent').removeClass('hidden');
	rssItem.children('.rss-item-teaser').hide();
	rssItem.addClass('active');
	rssItem.removeAttr('onclick');
}

function checkTime() {
	$.ajax({
		async: false,
		cache: false,
		type: 'get',
		url: '/getajax/getTime/',
		success: function(time) {
			if(time) {
				serverdate = time;
				clientdate = new Date().getTime()/1000;
			}
		}
	});
	
	diff = clientdate - serverdate;
	if(diff > 3600*24) {
		alert("The time on your computer's clock is not what we expected.\nAre you sure it's set to the current date and time?\n\nPlease correct this and restart your browser to avoid any login troubles :)");
		return false;
	}
	return true;
}

//this file includes all the document.ready functions for better caching

function requestUsername(rmPageId, form) {
	var requestedShortUrl = $('#request-form-username-'+rmPageId).val();
	//validate short url
	requestedShortUrl = requestedShortUrl.replace(/^\s+|\s+$/g,""); //trim
	if(!requestedShortUrl.match(/^[a-z0-9A-Z]+$/)) {
		alert("Your username can only contain alphanumeric characters");
		return false;
	} else {
		var message = $('#request-form-message-'+rmPageId).val();
		if(!message) {
			alert("Please give us a motivation to why you want to change your username");
		} else {
			$.ajax({
				type: 'post',
				url: '/saveajax/requestShortUrl/',
				dataType: 'json',
				data: { rmPageId:rmPageId, message:message, requestedShortUrl:requestedShortUrl },
				success: function(data, txtstatus) {
					if(data.returnStatus.status < 0) {
						alert('Request new username, something went wrong: '+data.returnStatus.description);
					} else {
						$(form).parent().slideUp().next().fadeIn(); 
					}
				},
				error: function(data, txtstatus) {
					alert('Request new username, something went wrong. Please send your request to support@rootmusic.com ');
				}
			});
		} 
	}
}

function isset(variable) {
	return (typeof(window[variable]) != 'undefined');
}

function showError(error) {
	if(error) {
		alert(error);
		try { console.log(error); } catch (err) {}
	}
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

var rm_debug = false;
// IE compatibility
$.ready(function() {
	if (!isset(console) || !isset(console.log)) {
		var console = { log: function(message) {
			if($('#rm-console').length == 0) {
				var domStr = '<div id="rm-console"></div>';
				$('body').append($(domStr));
			}
			$('#rm-console').append('<p>'+message+'</p>').scrollTop(100000000); // ridiculous
		}};
	}
});
function debug(message) {
	if(rm_debug) {
		try{
			if(typeof(message) == 'string') {
				var timestamp = ''+(new Date());
				message = timestamp+'> '+message;
			}
			console.log(message); 
		} catch(err) {
			
		}
	}
}


//function loadFacebook() {
//	 var e = document.createElement('script');
//	 e.setAttribute('language', 'javascript');
//     e.setAttribute('type', 'text/javascript');
//     e.setAttribute('async', 'true');
//	 e.setAttribute('src', document.location.protocol + '//connect.facebook.net/en_US/all.js');
//	 document.body.appendChild(e);
//}

function loadGoogleAnalytics() {
	var e = document.createElement('script'); 
	e.setAttribute('language', 'javascript');
    e.setAttribute('type', 'text/javascript');
    e.setAttribute('async', 'true');
    e.setAttribute('src',
    		(('https:' == document.location.protocol) ? 'https://ssl' : 'http://www') + 
    		'.google-analytics.com/ga.js');
    document.body.appendChild(e);
}

function loadChartbeat() {
    window._sf_endpt=(new Date()).getTime();
    var e = document.createElement('script');
    e.setAttribute('language', 'javascript');
    e.setAttribute('type', 'text/javascript');
    e.setAttribute('async', 'true');
    e.setAttribute('src',
       (("https:" == document.location.protocol) ? "https://s3.amazonaws.com/" : "http://") +
       "static.chartbeat.com/js/chartbeat.js");
    document.body.appendChild(e);
}

function loadFanbox(host) {
	try {
		var domTarget = document.getElementById("like-box");
		FB.XFBML.parse(domTarget);
	} catch (err) {}
}

//function dump(arr,level) {
//	var dumped_text = "";
//	if(!level) level = 0;
//	
//	//The padding given at the beginning of the line.
//	var level_padding = "";
//	for(var j=0;j<level+1;j++) level_padding += "    ";
//	
//	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
//		for(var item in arr) {
//			var value = arr[item];
//			
//			if(typeof(value) == 'object') { //If it is an array,
//				dumped_text += level_padding + "'" + item + "' ...\n";
//				dumped_text += dump(value,level+1);
//			} else {
//				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
//			}
//		}
//	} else { //Stings/Chars/Numbers etc.
//		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
//	}
//	return dumped_text;
//}

function checkLoginStatus() {
	FB.getLoginStatus(function(response) {
		if (response.session) {
			// facebook has errord on us again
		} else {
			alert("You have been logged out. If you did not log out of Facebook, you probably have third-party cookies disabled.\n\nPlease enable third party cookies in your web browser in order for RootMusic to be able to communicate with Facebook.");
			window.location = "/logout";
		}
	});
}

function editTemplateReady(isLocal, level, pageLoaded, ga, showIntro, showVisualIntro, fbKey, host, sc_init_needed, use_sc_connect, currentTime) {
	
	$('.hidden').hide().removeClass('hidden');
	
	if(!isLocal) {
		try {
			FB.init({appId: fbKey, status: true, cookie: true, xfbml: true, channelUrl: 'http://'+host+'/channel.html' });
			FB.Event.subscribe('auth.logout', function(response) {
				checkLoginStatus();
			});
//			FB.Event.subscribe('auth.sessionChange', function(response) {
//				if(response.session) {
//					updateFacebookSession(response.session);
//				} else {
//					window.location = "/logout"; 
//				}
//			});
		} catch (err) {
			showError("We couldn't establish a connection to Facebook for verifying your account, please try reloading the page."+err);
			try {console.log('edit/ready '+err);} catch(err) {}
		}
	}
	
	if(pageLoaded) {
	
		// Editor-specific content
		
		try {
			if(BrowserDetect.browser == "MSIE" || BrowserDetect.browser == "Explorer") {
				displayIEMessage();
			}
		} catch(e) {}
	
		// Launch widget handler
		var controller = new RMUIController({
			level: level, 
			scConnect: use_sc_connect,
			scInit: sc_init_needed, 
			currentTime : currentTime
		});
	
		// Fire up tutorial videos
		if(showIntro) {
			loadTutorialVideo('editor');
		}
		if(showVisualIntro && level > 0) {
			$('#rm-css-launch').one('click', function(e) {
				if(!flowplayers['css']) {
					loadTutorialVideo('css');
				}
				else {
					showTutorialVideo('css');
				}
				return false;
			});
		}
		
		// Fb instruction pane JS
		$('#fb-instructions-button').bind('click', function(event) {
			controller.showFacebookModal();
			
			$('#autoshare-activate-button').data('fbPageId', $('#autoshare-fbPageId').val()).data('rmPageId', $('#autoshare-rmPageId').val());
			RMFBAutoshare.init($('#autoshare-activate-button'), function() {
				$(this).bind('click', function(e) {
					RMFBAutoshare.request($(e.currentTarget));
				});
			});
								
			event.stopImmediatePropagation();
			return false;
		});
		$('#open-fb-export-video').bind('click', function(e) {
			if(!flowplayers['fb-export']) {
				loadTutorialVideo('fb-export');
			}
			else {
				showTutorialVideo('fb-export');
			}
			return false;
		});
		$('.fb-nav-step','#rm-fb-instructions').bind('click', function(event) {
			var idTokens = $(event.currentTarget).attr('id').split('-');
			var id = idTokens[idTokens.length-1];
			if($('#fb-install-step-'+id).is(':hidden')) {
				$('.fb-nav-step','#rm-fb-instructions').removeClass('active');
				$(event.currentTarget).addClass('active');
				$('#fb-install-step-'+id).siblings().hide().end().fadeIn();
			}
			return false;
		});
		$('.fb-install-next-link','#rm-fb-instructions').bind('click', function(event) {
			var hrefTokens = $(event.currentTarget).attr('href').split('-');
			var id = hrefTokens[hrefTokens.length-1];
			if($('#fb-install-step-'+id).is(':hidden')) {
				$('.fb-nav-step','#rm-fb-instructions').removeClass('active');
				$('#fb-nav-step-'+id).addClass('active');
				$('#fb-install-step-'+id).siblings().hide().end().fadeIn();
			}
			return false;
		});
		
		// Sidebar show/hide JS
		$('#editor-fb-sidebar-overlay').bind('mouseenter mouseleave', function(event) {
			var message = $('#editor-fb-sidebar-description');
			var shade = $('#editor-fb-sidebar-shade');
			switch(event.type) {
				case 'mouseenter':
					shade.stop().animate({opacity: 0.75}, 250);
					message.fadeIn('fast');
					break;
				case 'mouseleave':
					shade.stop().animate({opacity: 0.2}, 250);
					message.fadeOut('fast');
					break;
				default:
					break;
			}
		});
		
		// Add-ons JS
		$('#listn-to-addon').bind('click', function(event) {
			var linkDisplay = $(event.currentTarget).find('.listn-to-link');
			if(linkDisplay && (!$(event.target).hasClass('help') || linkDisplay.is(':hidden'))) {
				linkDisplay.slideToggle();
			}
		});
	}
	
	// GENERIC UI INITS
	// Help boxes
	$('a.help').live('click', function(event) {
		var msg = $(event.currentTarget).siblings('.help-message');
		debug($(event.currentTarget).position());
		var offset = msg.hasClass('right') ? ($(event.currentTarget).position().left - 215) : ($(event.currentTarget).position().left - 100);
		msg.css({left: offset+'px', top: ($(event.currentTarget).position().top+30)+'px'});
		if(msg.is(':hidden')) {
			msg.slideDown();
		} else msg.slideUp();
		return false;
	});
	$('em.help-message > p > a').live('click', function(event) {
		var msg = $(event.currentTarget);
		msg.preventDefault();
	});
	// Generic UI functions - move to own file, load with all pages?
	$('em.help-message').live('click', function(event) {
		var msg = $(event.currentTarget);
		debug($(event.currentTarget).position());
		if(!msg.is(':hidden')) {
			msg.slideUp();
		}
		return false;
	});
	$(document).click(function (event) {
		$(event.currentTarget).find('.help-message').slideUp();
	});

	// Hover tips
	$('.hover-tip').live('mouseover mouseout mousemove', function(event) {
		switch(event.type) {
			case 'mouseover':
				$(event.currentTarget).data('hovering',true);
				var helpWindow = $(event.currentTarget).siblings('.hover-tip-window');
				helpWindow.css({top: (event.clientY+15)+'px', left: (event.clientX+15)+'px'});
				setTimeout(function() {
					if($(event.currentTarget).data('hovering')) {
						helpWindow.fadeIn('fast');
						/*if((event.pageY-event.screenY)>0){
							$('.hover-tip-content').css({position: fixed, top: 0});
						}*/
					}
				}, 350);
				break;
			case 'mouseout':
				$(event.currentTarget).data('hovering',false);
				var helpWindow = $(event.currentTarget).siblings('.hover-tip-window');
				helpWindow.fadeOut('fast');
				break;
			case 'mousemove':
				var helpWindow = $(event.currentTarget).siblings('.hover-tip-window');
				helpWindow.css({top: (event.clientY+15)+'px', left: (event.clientX+15)+'px'});
				break;
			default:
				break;
		}
	}); 
	
	// Logout buttons
	$("#logout-button").css({height: 0, paddingTop: 0, paddingBottom: 0});
	$("#user-login").bind('mouseenter', function(event) {
		$(event.currentTarget).data("hovering", true);
		setTimeout( function() {
			if($(event.currentTarget).data("hovering")) $("#logout-button").stop().animate({height: '1em', paddingTop: '8px', paddingBottom: '8px'}, 250);
		}, 500);
	}).bind('mouseleave', function(event) {
		var login_pane = $(event.currentTarget);
		login_pane.data("hovering", false);
		setTimeout( function() {
			if(!login_pane.data("hovering")) $("#logout-button").stop().animate({height: 0, paddingTop: 0, paddingBottom: 0}, 250);
		}, 500);
	});

	//IT IS IMPORTANT THAT THESE ARE LAST
	
	//Chartbeat
	if(!isLocal) {
		loadChartbeat();
	}

	//Google Analytics
	if(ga) {
		loadGoogleAnalytics();
	}
	
	//DONT ADD MORE STUFF HERE
}

var RMFBAutoshare = {
	init: function(targetButton, callback) {
		if(targetButton && !targetButton.data('hasInstalledApp')) {
		
			targetButton.attr('disabled','disabled').addClass('loading').addClass('disabled').text('Checking status...');
			
			RMFBAutoshare.checkHasAppInstalled(targetButton.data('fbPageId'), function(installed) {
//				alert("hasInstalledApp="+installed);
				targetButton.data('hasInstalledApp',installed);
				if(installed === true) {
					targetButton.text('Verifying with FB...');
					
					RMFBAutoshare.checkHasSharePermission(targetButton.data('fbPageId'), function(share) {
	//					alert("HasSharePermission="+share);
						targetButton.data('hasSharePermissions',share);
						if(share === true) {
							targetButton.removeAttr('disabled').removeClass('disabled').removeClass('loading').text('Enable Autoshare');
						} else {
							RMFBAutoshare.revokeSharePermission(function(revoked) {
	//							alert("PermissionRevoked="+revoked);
								targetButton.removeAttr('disabled').removeClass('disabled').removeClass('loading').text('Enable Autoshare');
							});
						}
						
						if(callback && typeof(callback) == 'function') {
							debug('calling callback.');
							callback.call(targetButton);
						} else {
							debug(callback);
						}
					});
				} else {
					targetButton.removeClass('loading').removeAttr('href').text('BandPage not installed');
				}
			});
		} else {
			debug('RMFBAutoshare::init: no source button, or init already ran');
		}
	},
	request: function(targetButton, callback) {
		if(targetButton && targetButton.data('hasInstalledApp') === true) {
			if(targetButton.data('hasSharePermissions') === true) {
//			    alert("request//   installed="+targetButton.data('hasInstalledApp')+"      sharePerm="+targetButton.data('hasSharePermissions'));
				RMFBAutoshare.enableAutoshare(targetButton, callback);
			} else {
				FB.login(function(response) {
					if (response.session && response.perms && response.perms.indexOf('publish_stream') != -1) {
						//ok, we got it!
						RMFBAutoshare.enableAutoshare(targetButton, callback);
					} else {
						debug('AutoSharePerms::enable: user cancelled.');
					}
				}, {perms:'publish_stream', profile_selector_ids: targetButton.data('fbPageId')});
			}
		} else {
			debug('RMFBAutoshare::requestAutoshare: no source button, hasInstalledApp not set or false');
		}
	},
	checkHasAppInstalled: function(fbPageId, callback) {
		$.ajax({
			type: "get",
			dataType: "json",
			cache: false,
			url: "/getajax/isAppInstalled/"+fbPageId,
			success: function(data, txtstatus) {
				callback.call(this, data);
			}
		});
	},
	checkHasSharePermission: function(fbPageId, callback) {
		$.ajax({
			type: "get",
			dataType: "json",
			cache: false,
			url: "/getajax/hasSharePermission/"+fbPageId,
			success: function(data, txtstatus) {
				callback.call(this, data);
			}
		});
	},
	revokeSharePermission: function(callback) {
		$.ajax({
			type: "get",
			dataType: "json",
			cache: false,
			url: "/getajax/revokeSharePermission/",
			success: function(data, txtstatus) {
			callback.call(this, data);
		}
		});
	},
	enableAutoshare: function(targetButton, callback) {
		if(targetButton && targetButton.data('rmPageId')) {
			targetButton.attr('disabled', 'disabled').animate({opacity: 0.5}, 250, function() {
				$(this).addClass('disabled');
			});
			$.ajax({
				type: "post",
				url: "/saveajax/updateUseAutoshare/",
				data: { autoshare:true, rmPageId: parseInt(targetButton.data('rmPageId')) },
				dataType: "json",
				success: function(data, txtstatus) {
					if(data.returnStatus.status < 0) {
						alert("Save autoshare settings, something went wrong: "+data.returnStatus.description);
						if(targetButton) {
							targetButton.css({opacity: 1}).removeAttr('disabled').removeClass('disabled');
						}
					}
					// hide button, etc
					if(callback) {
						callback.call(this, data);
					} else {
						if(targetButton) {
							targetButton.fadeOut(function() {
								$(this).parent().append('<p class="message info">Autoshare activated! You can now edit your Autoshare settings from the <a href="/settings" title="BandPage Settings">settings</a> page.</p>');
							});
						}
					}
				},
				error: function(data, txtstatus) {
					// display error message
					if(targetButton) {
						targetButton.css({opacity: 1}).removeAttr('disabled').removeClass('disabled');
					}
				}
			});
		} else {
			debug('RMFBAutoshare::enableAutoshare: an error occurred: rm id missing from button');
		}
	}
}

function updateFacebookSession(session) {
	//alert("session changed!! "+session);
}

function upgradeTemplateReady(isLocal, isDev, pageLoaded, ga, fbKey, host, multi) {
	if(!isLocal) {
		FB.init({appId: fbKey, status: true, cookie: true, xfbml: true, channelUrl: 'http://'+host+'/channel.html' });
		FB.Event.subscribe('auth.logout', function(response) {
			checkLoginStatus();
		});
//		FB.Event.subscribe('auth.sessionChange', function(response) {
//			if(response.session) {
//				updateFacebookSession(response.session);
//			} else {
//				window.location = "/logout";
//			}
//		});
	}
	$('.hidden').hide().removeClass('hidden');

	if(pageLoaded) {
		// install new helper functions
		if(!Array.prototype.indexOf) {
			Array.prototype.indexOf = function(value) {
				for(var i=0; i<this.length; i++) {
					if(this[i] == value) return i;
				}
				return -1;
			};
		}
		if(!Array.prototype.findProp) {
			Array.prototype.findProp = function(propName, value) {
				for(var i=0; i<this.length; i++) {
					if(this[i] && this[i][''+propName]) {
						if(typeof(value) == 'number') {
							if(parseInt(this[i][''+propName]) == value) return i;
						} else if(this[i][''+propName] == value) return i;
					}
				}
				return -1;
			};
		}
		
		// Launch cart handler
		var _Cart = new RM_Upgrade_Cart(PAGE_DATA.bands, PAGE_DATA.upgrades);
	}
	
	if(multi) {
		$('li.page','#user-pages').hover(function(me) {
			$(me.currentTarget).css({marginBottom: '9px',backgroundColor: '#F6FAFE', borderBottom: '1px solid #A5CBEB'});
		}, function(me) {
			$(me.currentTarget).css({marginBottom: '10px', backgroundColor: '', borderBottom: ''});
		});
	}
	
	$("#logout-button").css({height: 0, paddingTop: 0, paddingBottom: 0});
	$("#user-login").bind('mouseenter', function(event) {
		$(event.currentTarget).data("hovering", true);
		setTimeout( function() {
			if($(event.currentTarget).data("hovering")) $("#logout-button").stop().animate({height: '1em', paddingTop: '8px', paddingBottom: '8px'}, 250);
		}, 500);
	}).bind('mouseleave', function(event) {
		var login_pane = $(event.currentTarget);
		login_pane.data("hovering", false);
		setTimeout( function() {
			if(!login_pane.data("hovering")) $("#logout-button").stop().animate({height: 0, paddingTop: 0, paddingBottom: 0}, 250);
		}, 500);
	});
	
	//IT IS IMPORTANT THAT THESE ARE LAST
	
	//Chartbeat
	if(!isLocal) {
		loadChartbeat();
	}

	//Google Analytics
	if(ga) {
		loadGoogleAnalytics();
	}
	
	//DONT ADD MORE STUFF HERE
}

function infoTemplateReady(isLocal, fbAppId, ga, registration, host) {
	if(!isLocal) {
		try {
			FB.init({appId: fbAppId, status: true, cookie: true, xfbml: false, channelUrl: 'http://'+host+'/channel.html' });
			FB.Event.subscribe('auth.logout', function(response) {
				checkLoginStatus();
			});
//			FB.Event.subscribe('auth.sessionChange', function(response) {
//				if(response.session) {
//					updateFacebookSession(response.session);
//				} else {
//					window.location = "/logout";
//				}
//			});
		} catch (err) {
			showError("We couldn't establish a connection to Facebook for verifying your account, please try reloading the page"+err);
			try {console.log('register/ready '+err);} catch(err) {}
		}
	}
	
	if(!isLocal) {
		$("#fb-email-perm").click(function(e) {
			if($('#tos-checkbox').is(':checked')) {
				try {
					FB.login(function(response) {
				    	if(response.session && response.perms && response.perms.indexOf("email")!=-1) {
							try {
//								var query = FB.Data.query('select email from user where uid='+ response.session.uid);
//								query.wait(function(users) {
//									 if(users && users.length == 1 && users[0].email) {
			                    		$("#fb-email-perm").animate({left: '+=100px', opacity: 0}, 250, function() {
			                    			$(this).css({
			                    				opacity: 0, 
			                    				backgroundImage: 'none',
												color: '#666',
												fontSize: '1.6em',
												textIndent: '60px',
												lineHeight: '82px'
											}).html('Loading <img style="margin-left:5px;" src="http://b.ak.static-rootmusic.com/images/common/ajax-loader-trans.gif">');
										});
										$("#fbemail").val("email@facebook.com");
										$("#fb-form").submit();
//									} else {
//										showError("We couldn't verify your email with Facebook, please enter an email instead.");
//									}
//								 });
							} catch (err) {
								showError("We couldn't verify your email with Facebook, please enter an email instead."+err);
							}
						} else {
							showError("We couldn't verify your email with Facebook, please enter an email instead.");
						}
					}, {perms:'email'});
				} catch (err) {
					showError("We couldn't verify your email with Facebook, please enter an email instead."+err);
				}
			} else {
				alert("You have to agree to the terms.");
			}
			return false;
		});
	}
	$('.hidden').hide().removeClass('hidden');
		
	if(isLocal) {
		$("#mainnav-sign-in").click(function() {
			$("#mainnav-sign-in").html('loading').addClass('loading').css({
				color: '#666',
				background: 'transparent'
			}).unbind('click');
			window.location = "/edit";
			return false;
		});
	} else {
		FB.getLoginStatus(function(response) {
			if (response.session) {
			    // logged in and connected user, someone you know
				$("#mainnav-sign-in").click(function() {
					if(checkTime()) {
						  //this shows the facebook connect dialog or logs you in automatically
						$("#mainnav-sign-in").html('loading').addClass('loading').css({
							color: '#666',
							background: 'transparent'
						}).unbind('click');
						$('#teaser-sign-up').animate({ top: '+=50px', opacity: 0 }, 500, function() {
							$(this).parent().text('I can do fancy stuff k?');
						});
						  window.location = "/edit";
					}
				  return false;
				  });
			  } else {
			    // no user session available, someone you dont know
				  $("#mainnav-sign-in").click(function() {
						//this shows the facebook connect dialog or logs you in automatically
						fblogin();
						return false;
				  });
			  }
		});
	}
	
	if(registration) {
		$("#view-tos").click(function(e) {
			if($("#terms-of-service-container").is(":hidden")) {
				$("#tos-agreement").css('height', 'auto');
				$("#terms-of-service-container").slideDown();
			} else {
				$("#terms-of-service-container").slideUp();
			}
			return false;
		});
		$("#tos-checkbox").change(function(e) {
			$("input[name='tos']").val($("#tos-checkbox").is(":checked"));
		});
	}
	
	var validator = $("#contact-form").validate({
		rules: {
			name: { required: true },
			comments: { required: true },
			email: { required: true, email: true }
		},
		messages: {
			name: "Please enter your name.",
			comments: "Please enter a comment.",
			email: {
				required: "We need your email address to contact you.",
				email: "Your email address must be in the format of name@domain.com."
			}
		},
		errorContainer: "#errorMessages",
		errorLabelContainer: "#errorMessages",
		wrapper: "li"
	});
	$('#submit-form-button').click(function(event) {
		if(validator.form()) {
			$('#contact-form').submit();
		} else {
			$('#errorMessages').addClass('error message big');
		}
	});

	//Fanbox
	if(!isLocal) {
		loadFanbox(host);
	}
	
	//Chartbeat
	if(!isLocal) {
		loadChartbeat();
	}
	
	//Google Analytics
	if(ga) {
		loadGoogleAnalytics();
	}
}

function fblogin() {
	try {
		if(checkTime()) {
			FB.login(function(response) {
				//this is called on successful connect
				if(response.session) {
					try {
						$("#mainnav-sign-in").html('loading').addClass('loading').css({
							color: '#666',
							background: 'transparent'
						}).unbind('click');
						/*$('#teaser-sign-up').animate({ top: '+=50px', opacity: 0 }, 500, function() {
							$(this).parent().text('I can do fancy stuff k?');
						});*/
						$('#teaser-sign-up').animate({ top: '+=50px', opacity: 0 }, 500, function() {
							$(this).parent().text('Connecting to your Facebook data...');
						});
						window.location = "/edit";
					} catch(err) {
						alert(err);
					}
				} else {
					//alert("user canceled");
				}
			});
		}
	} catch (err) {
		showError("We couldn't establish a connection to Facebook for verifying your account, please try reloading the page."+err);
	}
	return false;
}

function landingTemplateReady(isLocal, fbAppId, autoShowIntro, ga, host) {
	if(!isLocal) {
		try {
			FB.init({appId: fbAppId, status: true, cookie: true, xfbml: false, channelUrl: 'http://'+host+'/channel.html' });
			FB.Event.subscribe('auth.logout', function(response) {
				checkLoginStatus();
			});
//			FB.Event.subscribe('auth.sessionChange', function(response) {
//				if(response.session) {
//					updateFacebookSession(response.session);
//				} else {
//					window.location = "/logout"; 
//				}
//			});
			FB.getLoginStatus(function(response) {
				  if (response.session) {
				    // logged in and connected user, someone you know
					  $("#teaser-sign-up, #mainnav-sign-in, #home-musician-link").click(function() {
						  if(checkTime()) {
							  $("#mainnav-sign-in").html('loading').addClass('loading').css({
									color: '#666',
									background: 'transparent'
								}).unbind('click');
								$('#teaser-sign-up').animate({ top: '+=50px', opacity: 0 }, 500, function() {
									$(this).parent().addClass('loading').text('Contacting Facebook');
								});
							  //this shows the facebook connect dialog or logs you in automatically
							  window.location = "/edit";
						  }
						  return false;
					  });
				  } else {
				    // no user session available, someone you dont know
					  $("#teaser-sign-up, #mainnav-sign-in, #home-musician-link").click(function() {
						  //this shows the facebook connect dialog or logs you in automatically
						  fblogin();
						  return false;
					  });
				  }
			});
		} catch (err) {
			showError("We couldn't establish a connection to Facebook for verifying your account, please try reloading the page"+err);
		}
	}

	$('.hidden').hide().removeClass('hidden');
	
	// automatically show intro if we're on /intro
	if(autoShowIntro) {
		loadVideo('fan');
	}
	
	if(isLocal) {
		$("#teaser-sign-up, #mainnav-sign-in, #home-musician-link").click(function() {
			$("#mainnav-sign-in").html('loading <img style="position:relative;top:3px;margin-left:5px;" src="http://b.ak.static-rootmusic.com/images/common/ajax-loader-trans.gif">').css({
				color: '#666',
				background: 'transparent'
			}).unbind('click');
			$('#teaser-sign-up').animate({ top: '+=50px', opacity: 0 }, 500, function() {
				$(this).parent().addClass('loading').text('I can do fancy stuff k?');
			});
			window.location = "/edit";
			return false;
		});
	} 
	
	// fan video
	$('#home-fan-link').click(function(event) {
		if($('#fan-video').data('loaded')) {
			showVideo('fan');
		} else loadVideo('fan');
		return false;
	});
	$('#home-musician-link').parent().hover(function(event) {
		$(event.currentTarget).children('.hover-content').slideDown('fast');
	}, function(event) {
		$(event.currentTarget).children('.hover-content').slideUp('fast');
	});
	$('.bandpage-product').hover(function(event) {
		$(event.currentTarget).find('.header-link').css({color: '#555555'}).end().children('.hover-content').fadeIn('fast');
	}, function(event) {
		$(event.currentTarget).find('.header-link').css({color: ''}).end().children('.hover-content').fadeOut('fast');
	}).click(function(event) {
		location.href = $('.header-link',event.currentTarget).attr('href');
		return true;
	});
	$('#watch-intro-button').click(function(event) {
		if($('#watch-intro-button').data('loaded')) {
			showVideo('intro');
		} else loadVideo('intro');
		return false;
	});
	
	// start visual slideshow
	// load all images, then start slideshow
	debug('starting slideshow...');
	var imgLoader = $('<img />');
	var imgsLoaded = 0;
	imgLoader.load(function(event) {
		
		imgsLoaded++;
		debug('loaded image '+imgs[imgsLoaded-1].src);
		if(imgsLoaded == imgs.length) {
			setTimeout(function() {
				runSlideshow();
			}, 2250);
		}
		else {
			imgLoader.attr('src',imgs[imgsLoaded].src);
		}
	}).attr('src', imgs[imgsLoaded].src);
	
	//Fanbox
	if(!isLocal) {
		loadFanbox(host);
	}
	
	//Chartbeat
	if(!isLocal) {
		loadChartbeat();
	}
	
	// Google Analytics
	if(ga) {
		loadGoogleAnalytics();
//		$.geekGaTrackPage(ga);
	}
}

function loggedinTemplateReady(isLocal, pageLoaded, fbKey, host, crowdsoundLink) {
	$('.hidden').hide().removeClass('hidden');
	
	if(!isLocal) {
		try {
			FB.init({appId: fbKey, status: true, cookie: true, xfbml: true, channelUrl: 'http://'+host+'/channel.html' });
			FB.Event.subscribe('auth.logout', function(response) {
				checkLoginStatus();
			});
//			FB.Event.subscribe('auth.sessionChange', function(response) {
//				if(response.session) {
//					updateFacebookSession(response.session);
//				} else {
//					window.location = "/logout";
//				}
//			});
		} catch (err) {
			showError("We couldn't establish a connection to Facebook for verifying your account, please try reloading the page."+err);
		}
	}
	
	$('.sc-disconnect').bind('click', function(e) {
		e.stopPropagation();
		if(confirm("This will remove all your SoundCloud tracks from your BandPage playlist... Are you sure you want to disconnect SoundCloud from this account?")) {
			var rmPageId = $(e.target).attr('id').substr(4);
			$(e.currentTarget).animate({opacity: 0.5},500);
			$.ajax({
				type: "post",
				url: "/saveajax/removeSoundcloud/",
				data: { rmPageId:rmPageId },
				dataType: "json",
				success: function(data, txtstatus) {
					if(data.status < 0) {
						alert("Disconnect from Soundcloud, something went wrong: "+data.description);
					} else {
						$(e.currentTarget).fadeOut();
					}
				},
				error: function(txtStatus) {
					try{ console.log(txtStatus); } catch(e) {}
				}
			});
		}
		return false;
	});
	$('.ad-disconnect').live('click', function(e) {
		e.stopPropagation();
		if(confirm("Are you sure you want to disconnect ArtistData sync from this account? You will still be able to edit your existing shows, they just won\'t get synced with any other social sites.")) {
			var idTokens = $(e.currentTarget).attr('id').split('-');
			var bandId = idTokens[idTokens.length-1];
			$(e.currentTarget).addClass('loading').text('Disconnecting...');
			$.ajax({
				type: 'post',
				url: '/saveajax/clearArtistDataKey/',
				data: { bandId: parseInt(bandId)},
				dataType: 'json',
				success: function(data, status, response) {
					if(data.returnStatus.status >= 0) {
						$(e.currentTarget).fadeOut('fast', function() {
							$(this).siblings('h3, .key-display').remove();
							$(this).parent().append('<p><strong class="artistdata">ArtistData</strong> successfully disconnected</p>');
						});
					} else {
						alert("Disconnect from ArtistData, something went wrong: "+data.description);
					}
				},
				error: function(status) {
					try{ console.log(status); } catch(err) {}
				}
			});
		}
		return false;
	});
	$('.rm-reset-style').bind('click', function(e) {
		if(confirm('WARNING: This will get rid of any custom styles you have on your BandPage. Reseting cannot be undone! Are you sure you want to do this?')) {
			var idTokens = $(e.currentTarget).attr('id').split('-');
			var rmPageId = idTokens[idTokens.length-1];
			$(e.currentTarget).attr('disabled','disabled').addClass('loading').addClass('disabled').text('Clearing styles...');
			$.ajax({
				type: 'post',
				url: '/saveajax/resetAllStyles/',
				data: {rmPageId: rmPageId},
				dataType: 'json',
				success: function(data, status, response) {
					if(data.returnStatus && data.returnStatus.status >= 0) {
						$(e.currentTarget).text('Styles cleared!').removeClass('loading');
						setTimeout(function() {
							$(e.currentTarget).closest('.settings-suboptions').slideUp();
						}, 1000);
					} else {
						alert('Clear all Plus styles, something went wrong: '+data.error);
					}
				},
				error: function(status) {
					debug('clearAllStyles::error: '+status);
				}
			});
		}
		return false;
	});
	
	$('.show-request-form-button').bind('click', function(e) {
		$(e.currentTarget).hide().parent().siblings('.help-message').slideUp();
		$(e.currentTarget).hide().siblings('.request-form').slideDown();
		return false;
	});
	
	$("#logout-button").css({height: 0, paddingTop: 0, paddingBottom: 0});
	$("#user-login").bind('mouseenter', function(event) {
		$(event.currentTarget).data("hovering", true);
		setTimeout( function() {
			if($(event.currentTarget).data("hovering")) $("#logout-button").stop().animate({height: '1em', paddingTop: '8px', paddingBottom: '8px'}, 250);
		}, 500);
	}).bind('mouseleave', function(event) {
		var login_pane = $(event.currentTarget);
		login_pane.data("hovering", false);
		setTimeout( function() {
			if(!login_pane.data("hovering")) $("#logout-button").stop().animate({height: 0, paddingTop: 0, paddingBottom: 0}, 250);
		}, 500);
	});
	
	/** Settings-specific JS **/
	$('.bandpage-bar').click(function(event) {
		var target = $(event.currentTarget);
		var settingsPane = target.siblings('.settings-pane');
		if(settingsPane.is(':hidden')) { settingsPane.slideDown(); }
		else { settingsPane.slideUp(); }
		
		// set up autoshare button on click
		var autoshareButton = settingsPane.find('.autoshare-activate-button');
		autoshareButton.data('fbPageId', settingsPane.find('input[name="fbPageId"]').val());
		autoshareButton.data('rmPageId', settingsPane.find('input[name="rmPageId"]').val());
		RMFBAutoshare.init(autoshareButton, function() {
			// set up click handler for autosharing if app added
			$(this).bind('click', function(e) {
				RMFBAutoshare.request($(e.currentTarget), function() {
					// on success, fade in autoshare settings
					$(e.currentTarget).closest('.fb-autoshare-disabled').hide().siblings('.fb-autoshare-enabled').fadeIn();
				});
				return false;
			});
		});
		
		return false;
	}).find('a').click(function(event) {
		event.stopPropagation();
		return true;
	});
	
	$('.plan-option-help-text').fadeOut(1);
	$('.billing-icon').hover(function(event) {
		var target = $(event.currentTarget);
		$('.plan-option-help-text',target.closest('.billing-options')).css({left: target.position().left});
		$('.plan-option-help-text',target.closest('.billing-options')).stop().text(target.val()).fadeTo(250, 1);	
	}, function(event) {
		var target = $(event.currentTarget);
		$('.plan-option-help-text',target.closest('.billing-options')).stop().fadeOut(250);		
	});
	
	/** Help-specific JS **/
	
	$('.faq-question-header','#faq .faq-question.collapsed').bind('click',function(event) {
		var linked_p = $(this).parent().siblings('.faq-question-answer');
		if(linked_p.length > 0) {
			if(linked_p.is(':hidden')) linked_p.slideDown();
			else linked_p.slideUp();
		}
	});

	if(crowdsoundLink) {
		try{ console.log('loading crowdsound... url='+crowdsoundLink); } catch(err) {}
		$.ajax({
			dataType: 'script',
			url: crowdsoundLink,
			success: function() {
				//$('#crowdsound-feedback').append($('.iframe.crowdsound'));
				var crowdsoundCleanup = setInterval(function() {
					if($('iframe.crowdsound').length) {
						$('#crowdsound-feedback').append($('iframe.crowdsound'));
						$('iframe.crowdsound').hide().load(function() {
							$('#crowdsound-feedback').children('p.loading').remove();
							$('iframe.crowdsound').fadeIn();
						});
						clearInterval(crowdsoundCleanup);
					}
				}, 100);
			},
			error: function() {
				try{ console.log('dammit'); } catch(e) {}
			}
		});
	}
	
	$('.video-tutorial','#video-tutorial-list').bind('click', function(event) {
		var idTokens = $(event.currentTarget).attr('id').split('-');
		var id = idTokens[idTokens.length-1];
		loadVideo(id);
		return false;
	});
	
	$('.hover-tip').live('mouseover mouseout mousemove', function(event) {
		switch(event.type) {
			case 'mouseover':
				$(event.currentTarget).data('hovering',true);
				setTimeout(function() {
					if($(event.currentTarget).data('hovering')) {
						var helpWindow = $(event.currentTarget).siblings('.hover-tip-window');
						helpWindow.fadeIn('fast');
					}
				}, 350);
				break;
			case 'mouseout':
				$(event.currentTarget).data('hovering',false);
				var helpWindow = $(event.currentTarget).siblings('.hover-tip-window');
				helpWindow.fadeOut('fast');
				break;
			case 'mousemove':
				var helpWindow = $(event.currentTarget).siblings('.hover-tip-window');
				helpWindow.css({top: (event.clientY-helpWindow.outerHeight()-15)+'px', left: (event.clientX+15)+'px'});
				break;
			default:
				break;
		}
		try { console.log(event.type); } catch(e) {}
	});
	
	$('.autoshare-deactivate-button').bind('click', function(event) {
		if(confirm('Are you sure? BandPage only sends out messages about new material so your fans will be more likely to come back to get the latest news.')) {
			var settingsPane = $(event.currentTarget).closest('.bandpage-settings-pane');
			$.ajax({
				type: 'post',
				url: '/saveajax/updateUseAutoshare/',
				data: { 
					autoshare:false,
					rmPageId: parseInt(settingsPane.find('input[name="rmPageId"]').val())
				},
				dataType: 'json',
				success: function(data, response) {
					if(data.returnStatus.status >= 0) {
						var old_msg = $(event.currentTarget).text();
						$(event.currentTarget).text('Autoshare disabled.').attr('disabled','disabled').removeAttr('href').addClass('disabled');
						setTimeout(function() {
							settingsPane.find('.fb-autoshare-enabled').hide();
							settingsPane.find('.fb-autoshare-disabled').fadeIn();
							$(event.currentTarget).text(old_msg).removeAttr('disabled').removeClass('disabled');
							
							RMFBAutoshare.init(settingsPane.find('.autoshare-activate-button'));
						}, 500);
					}
				}
			});
			
		}
		return false;
	});
	$('input[type="checkbox"]', '.fb-autoshare-options').bind('change', function(event) {
		SaveHelper.save($(event.currentTarget).attr('name'), {
			shareShows: $('.fb-autoshare-options input[name="autoShareShows"]',$(event.currentTarget).closest('.bandpage-settings-pane')).is(':checked'),
			shareSongs: $('.fb-autoshare-options input[name="autoShareSongs"]',$(event.currentTarget).closest('.bandpage-settings-pane')).is(':checked'),
			shareVideos: $('.fb-autoshare-options input[name="autoShareVideos"]',$(event.currentTarget).closest('.bandpage-settings-pane')).is(':checked'),
			rmPageId: parseInt($(event.currentTarget).closest('.bandpage-settings-pane').find('input[name="rmPageId"]').val())
		});
	});
	
	$('.rm-inline-edit').each(function() {
		if(!$(this).hasClass('date') && !$(this).hasClass('autocomplete')) {
			if(TextInlineEditWidget) { 
				var inlineWidget = new TextInlineEditWidget($(this), {/* options */}, $(this).hasClass('multiline'));
				inlineWidget.enable();
			}
		}
	});
	
	$('.settings-pane').not('.hidden').each(function() {
		// set up autoshare button on click
		var autoshareButton = $(this).find('.autoshare-activate-button');
		autoshareButton.data('fbPageId', $(this).siblings('input[name="fbPageId"]').val());
		autoshareButton.data('rmPageId', $(this).siblings('input[name="rmPageId"]').val());
		if($('.fb-autoshare-disabled', $(this)).is(':visible')) {
			RMFBAutoshare.init(autoshareButton, function() {
				// set up click handler for autosharing if app added
				$(this).bind('click', function(e) {
					RMFBAutoshare.request($(e.currentTarget), function() {
						// on success, fade in autoshare settings
						$(e.currentTarget).closest('.fb-autoshare-disabled').hide().siblings('.fb-autoshare-enabled').fadeIn();
					});
					return false;
				});
			});
		}
	});
	
	// "Hold On!" prevent cancel form
	$('input[value="Cancel"]').click(function(event) {
		$('div#preventCancel').fadeIn().animate({top: $(window).scrollTop() + 'px'}, 250);
		$('#content').prepend('<div id="shade-overlay"></div>');
		$(window).bind('scroll', function() {
			var newPos = $(window).scrollTop() - 50;
			$('div#preventCancel').stop().animate({top: newPos + 'px'}, 250);
		});
		// Save input id in case user really wants to cancel.
		$('input.reallyCancel[name="userId"]').val($(this).siblings('input[name="userId"]').val());
		$('input.reallyCancel[name="bandId"]').val($(this).siblings('input[name="bandId"]').val());
		$(this).parent().submit(function() {
			return false;
		});
		event.stopPropagation();
	});
	$('a[name="reallyCancel"]').click(function() {
		$('form[name="reallyCancelForm"]').submit();
		$('#shade-overlay').remove();
	});
	$('body').bind('click', function(event) {
		var eTarget = event.target.toString();
		if($('#preventCancel').is(':visible')) {
			$('#preventCancel').fadeOut();
			$('#shade-overlay').remove();
			$(window).unbind('scroll');
		}
		if (eTarget.substring(eTarget.length - 15) != 'generate-ad-key') {
			if ($('#artistdata-setup-modal').is(':visible')) {
				$('#artistdata-setup-modal').fadeOut();
				$('#shade-overlay').remove();
				$(window).unbind('scroll');
			}
		}
	});
	$('#preventCancel').bind('click', function(event) {
		event.stopPropagation();
	});
	
	// ArtistData connect in settings
	$('.action-artistdata-connect-settings').live('click', function(event) {
		// If the bandId changes, reshow the Generate button.
		// We're sharing one modal box for multiple bands.
		var oldBandId = $('#artistdata-store-bandId').text();
		var newBandId = $(this).parents('.bandpage-settings-pane').attr('id').substring(14);
		if (oldBandId != newBandId) {
			$('#artistdata-store-bandId').text(newBandId);
			$('p.key-display').replaceWith('<a href="#generate-ad-key" class="rc-m rm-ui-button dark" id="action-generate-key" title="Generate your unique ArtistData key">Generate</a>');
		}
		// Reorienting the window on the page before scrolling magic.
		$('#artistdata-setup-modal').fadeIn().animate({top: $(window).scrollTop() + 'px'}, 250);
		$('#content').prepend('<div id="shade-overlay"></div>');
		// Scrolling magic!
		$(window).bind('scroll', function() {
			var newPos = $(window).scrollTop() - 50;
			$('#artistdata-setup-modal').stop().animate({top: newPos + 'px'}, 250);
		});
	});
	$('a.modal-settings-close').click(function() {
		$(this).parent().fadeOut();
		$('#shade-overlay').remove();
		$(window).unbind('scroll');
	});
	$('a#action-generate-key').live('click', function(event) {
		$(this).text('Generating key...');
		$(this).addClass('disabled loading');
		$.ajax({
			url: '/saveajax/getArtistDataKey',
			data: { 
				bandId: $('#artistdata-store-bandId').text()
			},
			dataType: 'json',
			type: 'POST',
			success: function(data, response) {
				if(data.returnStatus && data.returnStatus.status >= 0) {
					var key = data.artistDataBandKey;
					$(event.currentTarget).fadeOut('fast',function() {
						$(this).after('<p class="key-display">Your key is <strong>'+key+'</strong></p>');
						$(this).remove();
					});
					SaveHelper.saveSuccessCallbacks();
					var bandId = $('#artistdata-store-bandId').text();
					var adSettings = $('#bandpage-band-'+bandId).children('.settings-pane').children('.page-options').children('.artistdata-settings');
					adSettings.children().not('h4').remove();
					adSettings.children('h4').after('<a id="disconnect-artistdata-'+bandId+'" class="rm-ui-button rc-m small ad-disconnect" href="#artistdata-disconnect">Disconnect from <strong class="artistdata">ArtistData</strong></a><br /><br /><h3>Your <strong class="artistdata">ArtistData</strong> key is</h3><div class="key-display">'+key+'</div>');
				} else {
					SaveHelper.errorCallbacks(data.error);
				}
			}
		});
		return false;
	});
	$('#artistdata-setup-modal').bind('click', function(event) {
		var eTarget = event.target.toString();
		if (eTarget.length < 15 || eTarget.substring(eTarget.length - 15) != 'generate-ad-key') {
			event.stopPropagation();
		}
	});
	
	//only important on /help
	FB.getLoginStatus(function(response) {
		if (response.session) {
		    // logged in and connected user, someone you know
			$("#mainnav-sign-in").click(function() {
				if(checkTime()) {
						$("#mainnav-sign-in").html('loading').addClass('loading').css({
							color: '#666',
							background: 'transparent'
						}).unbind('click');
					  //this shows the facebook connect dialog or logs you in automatically
					  window.location = "/edit";
				}
				return false;
			  });
		  } else {
		    // no user session available, someone you dont know
			  $("#mainnav-sign-in").click(function() {
					//this shows the facebook connect dialog or logs you in automatically
					fblogin();
					return false;
			  });
		  }
	});
	
	var validator = $("#contact-form").validate({
		rules: {
			name: { required: true },
			comments: { required: true },
			email: { required: true, email: true }
		},
		messages: {
			name: "Please enter your name.",
			comments: "Please enter a comment.",
			email: {
				required: "We need your email address to contact you.",
				email: "Your email address must be in the format of name@domain.com."
			}
		},
		errorContainer: "#errorMessages",
		errorLabelContainer: "#errorMessages",
		wrapper: "li"
	});
	$('#submit-form-button').click(function(event) {
		if(validator.form()) {
			$('#contact-form').submit();
		} else {
			$('#errorMessages').addClass('error message big');
		}
	});
	
	//IT IS IMPORTANT THAT THESE ARE LAST
	
	//Chartbeat
	if(!isLocal) {
		loadChartbeat();
	}

	//Google Analytics
	if(ga) {
		loadGoogleAnalytics();
	}
	
	//DONT ADD MORE STUFF HERE
}

function tourTemplateReady(isLocal, tourVideo, ga, fbKey, host) {
	if(!isLocal) {
		try {
			FB.init({appId: fbKey, status: true, cookie: true, xfbml: false, channelUrl: 'http://'+host+'/channel.html' });
			FB.Event.subscribe('auth.logout', function(response) {
				checkLoginStatus();
			});
//			FB.Event.subscribe('auth.sessionChange', function(response) {
//				if(response.session) {
//					updateFacebookSession(response.session);
//				} else {
//					window.location = "/logout";
//				}
//			});
			FB.getLoginStatus(function(response) {
				  if (response.session) {
				    // logged in and connected user, someone you know
						  $("#tour-final-step, #tour-final-step2").click(function() {
							  if(checkTime()) {
								  //this shows the facebook connect dialog or logs you in automatically
								  $("#mainnav-sign-in").html('loading').addClass('loading').css({
										color: '#666',
										background: 'transparent'
									}).unbind('click');
									  window.location = "/edit";
							  }
							  return false;
						  });
				  } else {
				    // no user session available, someone you dont know
					  $("#tour-final-step, #tour-final-step2").click(function() {
							//this shows the facebook connect dialog or logs you in automatically
							fblogin();
							return false;
					  });
				  }
			});
		} catch (err) {
			showError("We couldn't establish a connection to Facebook for verifying your account, please try reloading the page."+err);
			try {console.log('tour/ready '+err);} catch(err) {}
		}
	}
	$('.hidden').hide().removeClass('hidden');
	
	if(isLocal) {
		$("#tour-final-step, #tour-final-step2").click(function() {
			window.location = "/edit";
			return false;
		});
	}

	if(tourVideo) {
		flowplayer('tour-video-flv', '/flash/flowplayer/flowplayer-3.1.5.swf', {
			clip: {
				autoPlay: false,
				autoBuffering: true,
				url: $('#tour-video-flv','#tour').data('url')
			}
		});
	}
	
	if(isLocal) {
		$("#mainnav-sign-in").click(function() {
			$("#mainnav-sign-in").html('loading <img style="position:relative;top:3px;margin-left:5px;" src="http://b.ak.static-rootmusic.com/images/common/ajax-loader-trans.gif">').css({
				color: '#666',
				background: 'transparent'
			}).unbind('click');
			window.location = "/edit";
			return false;
		});
	} else {
		FB.getLoginStatus(function(response) {
			if (response.session) {
			    // logged in and connected user, someone you know
				$("#mainnav-sign-in").click(function() {
					if(checkTime()) {
						$("#mainnav-sign-in").html('loading <img style="position:relative;top:3px;margin-left:5px;" src="http://b.ak.static-rootmusic.com/images/common/ajax-loader-trans.gif">').css({
							color: '#666',
							background: 'transparent'
						}).unbind('click');
					  //this shows the facebook connect dialog or logs you in automatically
					  window.location = "/edit";
					}
				  return false;
				});
			  } else {
			    // no user session available, someone you dont know
				  $("#mainnav-sign-in").click(function() {
						//this shows the facebook connect dialog or logs you in automatically
						fblogin();
						return false;
				  });
			  }
		});
	}
	
	var accomp_img;	
	$("#tour-copy li").each(function() {
		accomp_img = $("img[rev='"+$(this).attr("rel")+"']");
		$(this).css({ position: 'relative', top: (accomp_img.position().top+20) + "px" });
	});
	
	$(".tour-overview-button").bind('mouseover',function(me) {
		$(me.currentTarget).animate({opacity: 1}, 250).siblings().animate({opacity: 0.5}, 250);
	});
	$("#tour-overview-buttons").bind('mouseleave', function(me) {
		$(".tour-overview-button").animate({opacity: 1}, 250);
	});
	
	//Fanbox
	if(!isLocal) {
		loadFanbox(host);
	}
	
	//Chartbeat
	if(!isLocal) {
		loadChartbeat();
	}

	//Google Analytics
	if(ga) {
		loadGoogleAnalytics();
	}
}

//from landing
function runSlideshow() {
	var active = $('a','#bandpage-viewer-slideshow');
	var indx = active.data('index') ? active.data('index') : 0;
	var next_indx = (indx+1) % imgs.length;
	// create new image before it
	var next = $('<a href="'+imgs[next_indx].href+'" target="_blank" title="'+imgs[next_indx].title+'"><img src="'+imgs[next_indx].src+'" alt="'+imgs[next_indx].title+'" /></a>');
	next.data('index',next_indx);
	$('#bandpage-viewer-slideshow').prepend(next);
	
	// animate front image out and remove
	$('a:last-child','#bandpage-viewer-slideshow').animate({opacity: 0},500,function() {
		var current = $(this).siblings('a');
		$(this).remove();
		current.children('img').animate({opacity: 1},2250, function() {
			runSlideshow();
		});
	});
}

function loadVideo(id) {
	if(!id) id = 'fan';
	var video_container = false;
	var flv_content_container = false;
	var flv_path = false;
	switch(id) {
		case 'fan':
			video_container = $('#fan-video');
			flv_content_id = 'fan-video-flowplayer';
			flv_path = 'http://a.ak.static-rootmusic.com/video/rm_fan_intro_v2.flv';
			break;
		case 'intro':
			video_container = $('#intro-video');
			flv_content_id = 'intro-video-flowplayer';
			flv_path = 'http://a.ak.static-rootmusic.com/video/rm_homepage_visual_intro_v2.flv';
			break;
		case 'signin':
			video_container = $('#signin-video');
			flv_content_id = 'signin-video-flowplayer';
			flv_path = 'http://b.ak.static-rootmusic.com/video/tutorial_signin_v2.flv';
			break;
		case 'content':
			video_container = $('#content-video');
			flv_content_id = 'content-video-flowplayer';
			flv_path = 'http://c.ak.static-rootmusic.com/video/tutorial_content_v4.flv';
			break;
		case 'appearance':
			video_container = $('#appearance-video');
			flv_content_id = 'appearance-video-flowplayer';
			flv_path = 'http://c.ak.static-rootmusic.com/video/tutorial_visual_v3.flv';
			break;
		case 'exporting':
			video_container = $('#exporting-video');
			flv_content_id = 'exporting-video-flowplayer';
			flv_path = 'http://d.ak.static-rootmusic.com/video/tutorial_export_v2.flv';
			break;
		case 'sharing':
			video_container = $('#sharing-video');
			flv_content_id = 'sharing-video-flowplayer';
			flv_path = 'http://c.ak.static-rootmusic.com/video/tutorial_sharing.flv';
			break;
		case 'musicplayer':
			video_container = $('#musicplayer-video');
			flv_content_id = 'musicplayer-video-flowplayer';
			flv_path = 'http://a.ak.static-rootmusic.com/video/tutorial_musicplayer.flv';
			break;
		default:
			break;
	}
	// install 'skip' handler
	$('.video-control-link.cancel', video_container).bind('click',function(e) {
		if(flowplayers[id] && flowplayers[id].isPlaying()) {
			flowplayers[id].stop();
		} else {
			var cancel_cleanup = setInterval(function() {
				if(flowplayers[id] && flowplayers[id].isPlaying()) {
					flowplayers[id].stop();
					clearInterval(cancel_cleanup);
				}
			}, 3000);
		}
		hideVideo(id,true);
		if(id=='fan') { shareRootMusic(); }
		return false;
	});
	$('.video-control-link.pause', video_container).bind('click', function(e) {
		if(flowplayers[id] && flowplayers[id].isPlaying()) {
			flowplayers[id].pause();
		} else {
			var pause_cleanup = setInterval(function() {
				if(flowplayers[id] && flowplayers[id].isPlaying()) {
					flowplayers[id].pause();
					clearInterval(pause_cleanup);
				}
			}, 3000);
		}
		hideVideo(id);
		if(id=='fan') { shareRootMusic(); }
		return false;
	});
	
	showVideo(id);
	
	$('#'+flv_content_id).flowplayer('/flash/flowplayer/flowplayer-3.1.5.swf', {
		clip: {
			autoPlay: true,
			autoBuffering: true,
			url: flv_path,
			onFinish: function() {
				hideVideo(id,true);
				if(id == 'fan') {
					shareRootMusic();
				}
			}
		},
		onLoad: function() {
			flowplayers[id] = $f(flv_content_id);
			video_container.data('loaded',true);
		},
		onError: function(errCode, errMsg) {
			try{ console.log(errMsg); } catch(e) {}
		}
	});
}

function hideVideo(id, reset) {
	if(!id) id = 'fan';
	var video_container = false;
	switch(id) {
		case 'fan':
			video_container = $('#fan-video');
			break;
		case 'intro':
			video_container = $('#intro-video');
			break;
		case 'signin':
			video_container = $('#signin-video');
			break;
		case 'content':
			video_container = $('#content-video');
			break;
		case 'appearance':
			video_container = $('#appearance-video');
			break;
		case 'exporting':
			video_container = $('#exporting-video');
			break;
		case 'sharing':
			video_container = $('#sharing-video');
			break;
		case 'musicplayer':
			video_container = $('#musicplayer-video');
			break;
		default:
			break;
	}
	$('.modal-video-controls', video_container).slideUp(function() {
		if(video_container) {
			video_container.animate({opacity: 0}, function() {
				$(this).css({top: '-4000px'});
				$('#modal-shade').fadeOut();
			});
		}
	});
}

function showVideo(id) {
	try{ console.log('showVideo('+id+')'); } catch(e) {}
	if(!id) id = 'signin';
	var video_container = false;
	switch(id) {
		case 'fan':
			video_container = $('#fan-video');
			break;
		case 'intro':
			video_container = $('#intro-video');
			break;
		case 'signin':
			video_container = $('#signin-video');
			break;
		case 'content':
			video_container = $('#content-video');
			break;
		case 'appearance':
			video_container = $('#appearance-video');
			break;
		case 'exporting':
			video_container = $('#exporting-video');
			break;
		case 'sharing':
			video_container = $('#sharing-video');
			break;
		case 'musicplayer':
			video_container = $('#musicplayer-video');
			break;
		default:
			break;
	}
	$('#modal-shade').fadeIn(function() {
		if(video_container) {
			video_container.css({top: '-60px', opacity: 0, display: 'block'}).animate({opacity: 1}, function() {
				$('.modal-video-controls',$(this)).slideDown();
				$('#modal-shade').css({height: $('body').outerHeight()+'px'});
				if(flowplayers[id] && !flowplayers[id].isPlaying()) flowplayers[id].play();
			});
		}
	});
}

function shareRootMusic() {
	var attachment = {
	     name:'RootMusic | BandPages on Facebook',
	     href: host+'/intro',
	     caption:'Attention musicians everywhere: Facebook now has BandPages. Watch the video!',
//	     description:'Check out band pages on facebook...',
	     media:[{
	       type:'image',
	       src: imgs[Math.round(Math.random()*imgs.length)].src,
	       href: host+'/intro'
		}]
	};

	var message = ''; 
	//message = 'Attention musicians everywhere: Facebook now has BandPages. Watch the video!'; /* FB POLICY */
    FB.ui({ 
	    method: 'stream.publish',
	    message: message,
	    attachment: attachment,
	    user_message_prompt: 'Let your friends know about RootMusic!'
	}, function(response) {
//		if(response && response.post_id) {
//			alert('Post was published');
//		} else {
//			alert('Post was not published');
//		}
	});
}
