var liveloom= function(){
	
	//startup code
	this.busy = true;
	this.lastCommand = "";
	this.canSave = false;
	this.currentLoomName="";
	this.adRefreshes=0;
	this.isFullScreen = false;
	this.loadedTabs=false;
	this.newAmazonHtml = "";
	this.secondFeatureLoad =false;
	this.lastLoadTime = new Date();
	this.loaded=false;
	
	setInterval("ll.refreshAd();",3*60*1000);
	
	this.lastPing=new Date().getTime();
	
	this.liveloomReady = function(){
		if (ll.loaded) return;
		ll.loaded = true;
		this.loadPopular();
		this.busy=false;
	};
	this.loadPopular = function(){
		if (! this.isFacebook){
			$.ajax({
				  url: "/lib/popular.php",
				  cache: false,
				  success: function(html){
					$("#featured").empty();
				    $("#featured").append(html);
				  }
				});
		}
		else{
			$.ajax({
				  url:  "/lib/popularFB.php",
				  cache: false,
				  success: function(html){
					if (!ll.secondFeatureLoad){
						$("#featured").empty();
						$("#featured").append(html);
					}
					else{
						ll.newAmazonHtml = html;
						$("#featured").hide("slide",{ direction: "left" }, 3000,ll.showNewAmazonHtml);
					}
				  }
				});
		}	
	};
	this.loadRecent = function(){
		if (! this.isFacebook){
			$.ajax({
				  url: "/lib/recent.php",
				  cache: false,
				  success: function(html){
				$("#featured").empty();
				    $("#featured").append(html);
				  }
				});
		}
		else{
			$.ajax({
				  url:  "/lib/recentFB.php",
				  cache: false,
				  success: function(html){
					if (!ll.secondFeatureLoad){
						$("#featured").empty();
						$("#featured").append(html);
					}
					else{
						ll.newAmazonHtml = html;
						$("#featured").hide("slide",{ direction: "left" }, 3000,ll.showNewAmazonHtml);
					}
				  }
				});
		}	
	};
	this.loadSaved = function(){
		if (! this.isFacebook){
			$.ajax({
				  url: "/lib/getUserStates.php",
				  cache: false,
				  success: function(html){
					$("#featured").empty();
				    $("#featured").append(html);
				  }
				});
		}
		else{
			$.ajax({
				  url:  "/lib/getUserStatesFB.php",
				  cache: false,
				  success: function(html){
					if (!ll.secondFeatureLoad){
						$("#featured").empty();
						$("#featured").append(html);
					}
					else{
						ll.newAmazonHtml = html;
						$("#featured").hide("slide",{ direction: "left" }, 3000,ll.showNewAmazonHtml);
					}
				  }
				});
		}	
	};
	
	
	this.loadState = function(state, name, owner){
		var now = new Date();
		var i = now - ll.lastLoadTime;
		if (i>1500){
			ll.lastLoadTime = now;
		}
		else{
			return false;
		}
		try{
			if (!this.busy){
				thisMovie("liveloom").loadState(state, name, owner);
				googleTracker("looms/"+state);
			}
			
			return false;
		}
		catch (Exception){
			return false;
		}
	};
	
	this.loadedState = function (state, name, owner){
		if (!ll.isFacebook){
			document.title = "liveloom - " + name + (owner.length  > 0 ? " - " + owner : "");
		}
		
		$("#liveloomtitle").hide("slide",{ direction: ll.isFacebook ?"right": "left" }, 1000,ll.showNewTitle);
		
		ll.newTitle = "<a href='" + 
				(ll.isFacebook ? "http://www.liveloom.com/":"") + "/looms/" + state +"' onclick='return false;'>" + name + 
				(owner ? " - " + owner : "") +"</a>";
		ll.setEmbedCode(state);
		if (ll.isFacebook){
			ll.showNewEmbedLink();
		}
		else{
			$("#embedlink").hide("slide",{ direction:"left" }, 1000,ll.showNewEmbedLink);
		}
	};
	
	this.showNewTitle = function(){
		$("#liveloomtitle").empty();
		$("#liveloomtitle").append(ll.newTitle);
		$("#liveloomtitle").show("slide",{ direction: ll.isFacebook ? "right": "left" },1000);

	};
	
	this.saveState =  function(){
			thisMovie("liveloom").saveState();
	};
	
	this.savedState =function(stateId){
		//todo
	};

	this.shareOnFacebook = function(url,name){
		var e = document.getElementById("swfsharer");
		if (e !=null){
			addthis_open(e, '', url, name);
		}
		else{
			window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(url)+'&t='+encodeURIComponent(name),'sharer','toolbar=0,status=0,width=626,height=436');
		}
		return false;		
	};
	this.loadFbConnect = function(){
		window.location =  "http://www.liveloom.com/fbconnect.php?redirect=http://www.liveloom.com/";
	};
	
	this.toggleFullScreen = function(isFullScreen){
		this.isFullScreen  = isFullScreen;
	};
	
	this.googleTracker = function(text) {
		pageTracker._trackPageview(text ); 
   	};

	this.refreshAd= function(){
		if (this.isFullScreen) { 
			return;
		}
		if (this.adRefreshes<20){
			//only on facebook app.
			if (document.getElementById("ad")){
				document.getElementById("ad").innerHTML="<iframe frameborder='0' scrolling='no'	marginheight='0' marginwidth='0' width='645' height='75' src='http://www.adparlor.com/serveIFrameAd.aspx?appId=4025891&adtype=6&network=facebook&adTBG=000000&adTColor=FFFFFF&adCntColor=000000&adBG=FFFFFF' id='AdParlorAd'></iframe>";	
				this.adRefreshes++;
			}
		}
	};
	
	
	
	this.embedFlash = function(w,h,st){
			var flashvars = {
				state: (st==null) ? "" : st ,
		  		stagewidth: w,
		  		stageheight: h,
		  		showcontrols: "true",
		  		allowfullscreen:"true"
			};
			var params = {
		  		menu: "false",
		  		bgcolor:"0x000000",
		  		allowfullscreen:"true",
		  		quality:"high",
		  		wmode:"opaque"
			};
			var attributes = {
		  		styleclass:"liveloomcontainer"
			};
		
			swfobject.embedSWF("/liveloom.swf", "liveloom", w, h, "9.0.0", "expressInstall.swf", flashvars,params,attributes);
		
	};
	
	this.facebookInvite= function(url){
		window.open("/invite.php");
	};
	
	this.redirect = function(url){
		window.open(url);
		thisMovie("liveloom").trackRedirect(url);		
	};
	
	this.loadAlbum = function(artist,album){
		
		$.ajax({
			  url: "/lib/amazonstore.php?artist=" + artist + "&album=" +album,
			  cache: false,
			  success: function(html){
				if (html.length > 0 ){
					ll.newAmazonHtml = html;
					if (ll.isFacebook){
						$("#sponsors").hide("slide",{ direction: "left" }, 3000,ll.showNewAmazonHtml);
					}
					else{
						$("#albums").hide("slide",{ direction: "up" }, 3000,ll.showNewAmazonHtml);
					}
					
				}
			  }
			});
	};
	this.showNewAmazonHtml = function(){
		if (ll.isFacebook){
			$("#sponsors").empty();
			$("#sponsors").append(ll.newAmazonHtml);
			$("#sponsors").show("slide",{ direction: "right" }, 3000);
			if (!ll.secondFeatureLoad){
				ll.secondFeatureLoad = true;
				ll.reloadFbFeatured = setTimeout('ll.loadFeatured();',90000);
			}
			else{
				ll.secondFeatureLoad = false;
			}
		}
		else{
			$("#albums").empty();
			$("#albums").append(ll.newAmazonHtml);
			$("#albums").show("slide",{ direction: "down" }, 3000);
		}
	};

	this.setEmbedCode = function(state){
		ll.embedCode='<object width="399" height="299"><param name="movie" value="http://www.liveloom.com/liveloom.swf"></param>'+
		'<param name="flashvars" value="state=' + state + '&stagewidth=399&stageheight=299&autoplay=false&embedmode=true&allowfullscreen=true"></param>'+
		'<param name="autoplay" value="false"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>'+
		'<embed src="http://www.liveloom.com/liveloom.swf"  flashvars="state=' + state + '&autoplay=false&stagewidth=399&stageheight=299&embedmode=true&allowfullscreen=true" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="399" height="299"></embed></object>';
	
	};
	this.showNewEmbedLink = function(){
		document.getElementById("embedcode").value=ll.embedCode;
		document.getElementById("embedanchor").style.visibility="visible";
		$("#embedlink").show("slide",{ direction: "left" }, 1000);
	};
	
	this.signOut = function(){
		$.ajax({
			  url:  "/signOut.php",
			  cache: false,
			  success: function(html){
				document.location.href="http://www.liveloom.com";
			  }
			});
	};
	this.signIn = function(){
		userId = document.getElementById("userId").value;
		password = document.getElementById("password").value;
		if (userId.length===0 || password.length==0){
			document.getElementById("signInError").innerHTML = "Please enter a username and password";
			return;
		}
		document.getElementById("signInError").innerHTML = "";
		$.ajax({
			  url:  "/login.php?userId="+userId+"&password="+password,
			  cache: false,
			  success: function(text){
				if (text==="false"){
					document.getElementById("signInError").innerHTML = "Incorrect username or password";
				}
				else{
					$.ajax({
						  url:  "/header.php",
						  cache: false,
						  success: function(text){
							document.getElementById("signinel").innerHTML = text;
						}
					});
					if (document.getElementById("loginButton")){
						document.getElementById("userId").disabled="disabled";
						document.getElementById("password").disabled="disabled";
						
						document.getElementById("signInError").innerHTML = "Signed in as " + document.getElementById("userId").value;
						document.getElementById("loginButton").disabled="disabled";
						var bits = text.split(",");
						var fb = bits[1].split("=");
						switch (fb[1]){
							case "noaccount":
								document.getElementById("fbsignin").style.visibility="hidden";
								document.getElementById("addFacebook").style.visibility="visible";
								break;
							case "signedin":
								document.getElementById("fbsignin").innerHTML="You are signed in to Facebook";
								break;
							case "signedout":
								document.getElementById("fbsignin").style.visibility="hidden";
								document.getElementById("signinFacebook").style.visibility="visible";
								break;
						}
					}
				}
			  }
			});
	};
	
	this.register = function(){
		userId = document.getElementById("userId").value;
		password = document.getElementById("password").value;
		password2 = document.getElementById("password2").value;
		email = document.getElementById("email").value;
		accepted = document.getElementById("acceptTerms").checked;
		if (userId.length===0 || password.length==0 || email.length==0){
			document.getElementById("signInError").innerHTML = "Please enter an email, username and password";
			return;
		}
		if (password !== password2){
			document.getElementById("signInError").innerHTML = "Your passwords don't match";
			return;
		}
		document.getElementById("signInError").innerHTML = "";
		if (!checkEmail(email)){
			document.getElementById("signInError").innerHTML = "Please enter a valid email address";
			return;
		}
		if (!accepted){
			document.getElementById("signInError").innerHTML = "Please accept our Terms and Conditions";
			return;
		}
		$.ajax({
			  url:  "/doRegister.php?userId="+userId+"&password="+password+"&email="+email +"&challenge="+Recaptcha.get_challenge()+"&response="+Recaptcha.get_response(),
			  cache: false,
			  success: function(result){
				Recaptcha.destroy();
				switch (result){
					case "true":
						ll.signIn();
						document.getElementById("signInError").innerHTML = "You have been successfully registered!";
						break;
					case "duplicateuserid":
						document.getElementById("signInError").innerHTML = "User id "+ userid +" is already in use";
						break;
					case "duplicateemail":
						document.getElementById("signInError").innerHTML = "Email "+ email +" is already registered";
						break;
					case "badcaptcha":
						Recaptcha.create("6LcxVAgAAAAAABXFP--7IjeozWgcrrsTR9t27h1t",
								"recapt", {
								   theme: "black",
								   callback: Recaptcha.focus_response_field
								});
						break;
				}
			  }
		});
	};
	
	this.showPasswordReset = function(){
		document.getElementById("loginDiv").style.visibility="hidden";
		document.getElementById("resetPasswordDiv").style.visibility="visible";
	};
	this.resetPassword = function(){
		var userId = document.getElementById("resetUserId").value;
		if (userId.length ===0){
			document.getElementById("resetPasswordError").innerHTML="Please enter your username or password";
			return;
		}
		document.getElementById("resetPasswordError").innerHTML="";
		$.ajax({
			  url:  "/resetPassword.php?userId="+userId,
			  cache: false,
			  success: function(result){
				Recaptcha.destroy();
				switch (result){
					case "true":
						document.getElementById("resetPasswordError").innerHTML = "A new password has been sent to your registered email address";
						break;
					default:
						document.getElementById("resetPasswordError").innerHTML = "We could not find your username or password";
						break;
				}
			  }
		});
	};
	
	this.showUserDetails = function(){
		$.nyroModalManual({
		      url: '/userDetails.php'
		    });

	};
	
	this.updateUser = function(){
		document.getElementById("updateError").innerHTML="";
		var userId=document.getElementById("updateUserId").value;
		var firstName=document.getElementById("updateFirstName").value;
		var surname=document.getElementById("updateLastName").value;
		var email=document.getElementById("updateEmail").value;
		var password=document.getElementById("updatePassword").value;
		var password2=document.getElementById("updatePassword2").value;
		if (password.length >0 && password != password2){
			document.getElementById("updateError").innerHTML="The passwords don't match";
			return;
		}
		if (email.length==0){
			document.getElementById("updateError").innerHTML="Please enter an email address";
			return;
		}
		if (!checkEmail(email)){
			document.getElementById("updateError").innerHTML=email +" is not a valid email address";
			return;
		}
		if (userId.length==0){
			document.getElementById("updateError").innerHTML="Please choose a user name";
			return;
		}
		$.ajax({
			  url:  "/updateUserDetails.php?userId="+userId+"&email="+email+"&firstName="+firstName+"&surname="+surname+(password.length>0 ? "&password="+password:"") ,
			  cache: false,
			  success: function(result){
				document.getElementById("updateError").innerHTML=result;
			  }
		});
		
	};
	
	
};

function checkEmail(email) {
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return filter.test(email);
}