var quicksite = 
{
	show_sidebar : true,
	sidebar_start : 'open',
	username : null,
	password : null, 
	userid : null,
	image_path : null,
	thumbnail_path : null,
	thumbnail_url : null,
	image_url : null,
	fb_appID : '273184636025267',
	helpers : {
		validateName : function(name)
		{
			return name != 'undefined' && name != '' && name != null && name != 'Full Name' && name != 'Your Name';
		},
		validateEmail : function(email)
		{
			var regex = /^[^@]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$/gi;
			
			return regex.test(email) && email != 'your@email.com';
		},
		validatePassword : function(password)
		{
			var regex = /[a-zA-Z0-9!@#\$]{6,12}/gi;
			
			return regex.test(password);
		},
		validateUsername : function(username)
		{
			var regex = /^[A-Za-z0-9]{3,20}$/gi;
						
			return regex.test(username) && username != "Username" && username != "URL";
		},
		validateInvite : function(invite)
		{
			var regex = /[a-zA-Z0-9]*/gi;
			
			return regex.test(invite);
		},
		validateCity : function(city)
		{
			var regex = /[a-zA-Z0-9'\-\s]*/gi;
			
			return regex.test(city) && city != 'Your City';
		},
		validateZip : function(zip)
		{
			var regex = /[0-9]{5}(\-|\s)?[0-9]{0,5}/gi;
			
			return regex.test(zip) && zip != '11111';
		},
		validateCc : function(cc)
		{
			var regex = /[0-9]{13,19}/gi;
			
			return regex.test(cc);
		},
		validateCVV : function(cvv)
		{
			var regex = /[0-9]{3,6}/gi;
			
			return regex.test(cvv);
		},
		validateTitle : function(title)
		{
			return title != '' && title != 'Post Title';	
		},
		validateText : function(text)
		{
			return text != '';	
		},
		validateURL : function(url)
		{
			return url != '';	
		},
		validateEmbed : function(embed)
		{
			return embed != '' && embed != 'Paste embed code or a video url';
		}
	},
	validate : function(data)
	{
		// data will be an array of objects of input values
		// example:  { obj : $username, type : 'username' }
		
		for (var i in data)
		{
			switch(data[i].type)
			{
				case 'email':
					if (!quicksite.helpers.validateEmail(data[i].obj.val())) {
						alert("Please use a valid email address.");
						data[i].obj.focus();
						return false;
					}
					break;
				case 'password':
					if (!quicksite.helpers.validatePassword(data[i].obj.val())) {
						alert("Password must be between 6-12 characters and contain only letters, numbers, and !@#$");
						data[i].obj.focus();
						return false;
					}
					break;
				case 'username':
					if (!quicksite.helpers.validateUsername(data[i].obj.val())) {
						alert("Please enter a subdomain.");
						data[i].obj.focus();
						return false;	
					}
					break;
				case 'username2':
					if (quicksite.usernameObj.proceed == false) {
						alert("Please enter a valid subdomain.");
						data[i].obj.focus();
						return false;
					}
					break;
				case 'title':
					if (!quicksite.helpers.validateTitle(data[i].obj.val())) {
						alert("Please set a page title.");
						data[i].obj.focus();
						return false;	
					}
					break;
				default:
					break;
			}
		}
		
		// If we get this far then we are good to go
		return true;
			
	},
	getSessionData : function()
	{
		$.post('/_api/session_info',{},function(data){
			if (!data.error) {
				quicksite.username = data.data.UNAME;
				quicksite.userid = data.data.USERID;
			}
		},'json');
	},
	getUsername : function()
	{
		return quicksite.username;
	},
	categories : 
	{
		getCategories : function(callback)
		{
			var postdata = {};
			
			$.post('/_api/getCategories',postdata,function(data){
				if (data.error == false) {
					// Fill in categories
					if (callback) callback(data.data);
				}
			},'json');
		},
		getSelectedCategories : function(blockid,callback)
		{
			var postdata = {
				blockid : blockid
			}
			
			$.post('/_api/getSelectedCategories',postdata,function(data){
				if (data.error == false && callback) {
					callback(data.data);
				}
			},'json');
		},
		populate : function(cats,$ele)
		{
			html = '';
			for(var i = 0; i <= cats.length -1; i++) {
				html += '<div id="uccode-'+cats[i].name.replace(/\s/g, "")+'"><input class="category-input" type="checkbox" name="categories[]" value="'+cats[i].name+'"></input>&nbsp;'+cats[i].name+'</div>'
			}
			
			$ele.html(html);
		},
		check : function(cats)
		{
			if (cats == null) return;
			
			for (var i=0; i<=cats.length-1; i++) {
				$("#uccode-"+cats[i].replace(/\s/g, "")+" input").attr('checked',true);
			}
		},
		removeCategories : function(cat_arr)
		{
			var postdata = {
				"categories[]" : cat_arr
			}
			
			$.post('/_api/removeCategories',postdata,function(data){
				//alert(data);
			},'json');
		}
	},
	facebook : 
	{
		me_res : null,
		auth_res : null,
		logged : null,
		fbinit : function()
		{
			FB.init({ 
				appId:quicksite.fb_appID, cookie:true,
				status:true, xfbml:true, oauth:true
			});
													
			if (quicksite.facebook.fbIsLoggedIn() == true) {
				// Stuff that needs to happen if user is already logged in
				$("#connect-facebook").val("Connected");
				$("#connect-facebook").attr("disabled","disabled"); 
			} else {
				// Stuff that should happen if user is not logged in	
			}
		},
		fbIsLoggedIn : function() 
		{
			FB.getLoginStatus(function(response) {
				if (response.authResponse) {
					// logged in and connected user, someone you know
					return true;
				} else {
					// no user session available, someone you dont know
					return false;
				}
			});
		},
		fblogin : function(callback) 
		{ 
			FB.login(function(response) {
				//var accessToken = response.authResponse.accessToken;
				quicksite.facebook.auth_res = response.authResponse;
				if (response.authResponse) {
					console.log('Welcome!  Fetching your information.... ');
					FB.api('/me', function(response) {
						//var userName = response.username;
						console.log('Good to see you, ' + response.id + '.');
						quicksite.facebook.me_res = response;
						//var text = '';
						//for(var i in response){ text += i+':'+response[i]+' '; }
						//alert(text);
						if (callback != null) callback();
					});
				} else {
					console.log('User cancelled login or did not fully authorize.');
				}
			}, {scope: 'publish_stream,offline_access,email'});
		},
		fbMainLogin : function()
		{

			var handler = function()
			{
				var postdata = 
				{
					email : quicksite.facebook.me_res.email,
					access_token : quicksite.facebook.auth_res.accessToken,
					facebook_username : quicksite.facebook.me_res.username,
					facebook_id : quicksite.facebook.me_res.id
				}
				
				$.post('/_api/facebookLogin',postdata,function(data) {
					if (!data.error) {
						window.location = 'http://www.rollr.com/customize';
					} else {
						switch(data.error)
						{
							case '1':
							case 1:
								alert("Sorry, we could not log you in with facebook at this time.");
								break;
							case '2':
							case 2:
								quicksite.deployLightbox('/includes/chooseUsername',580,305,false);
								break;
							default:
								break;
						}
					}
				},'json');
			}
			
			quicksite.facebook.fblogin(handler);
		},
		fbNewUser : function(callback)
		{
			//if (quicksite.facebook.fbIsLoggedIn()) return false;
									
			var handler = function()
			{
				
				var postdata = 
				{
					userid : quicksite.userid,
					access_token : quicksite.facebook.auth_res.accessToken,
					facebook_username : quicksite.facebook.me_res.username,
					facebook_id : quicksite.facebook.me_res.id
				}
								
				$.post('/_api/addFBUser',postdata,function(data){
					if (data.error != true) {
						// Do nothing
						//$("#connect-facebook").val("Connected");
						if (callback != null) callback();	
					} else {
						alert("Sorry we could not make the connection with facebook at this time.");
					}
				},'json');
			}
			
			quicksite.facebook.fblogin(handler);
		},
		fbRegister : function()
		{
			// Fill in hidden form values
			$("#fb-reg-username").val(quicksite.username);
			$("#fb-reg-password").val(quicksite.password);
			$("#fb-reg-email").val(quicksite.facebook.me_res.email);
			$("#fb-a-t").val(quicksite.facebook.auth_res.accessToken);
			$("#fb-reg-fb-username").val(quicksite.facebook.me_res.username);
			$("#fb-reg-fb-id").val(quicksite.facebook.me_res.id);
						
			// Submit the form	
			$("#fb-reg-form").submit();
		}
	},
	uploadProfilePic : function()
	{
		{
			//starting setting some animation when the ajax starts and completes
			$("#loading")
			.ajaxStart(function(){
				$(this).show();
				$('#submit-setup').attr("disabled","disabled");
			})
			.ajaxComplete(function() {
				$(this).hide();
			});
		   
			$.ajaxFileUpload
			(
				{
					url:'/_api/uploadProfilePic',
					secureuri:false,
					fileElementId:'profile-pic',
					dataType: 'json',
					success: function (data, status)
					{
						if(typeof(data.error) != 'undefined')
						{
							if(data.error != '')
							{
								alert(data.error);
							}else
							{
								$small_url = data.small_url;
								$small_path = data.small_path;
								$med_path = data.med_path;
								$med_url = data.med_url;
								$large_path = data.large_path;
								$large_url = data.large_url;
																
								$("#profile-pic-img").attr('src',$med_url);
																
								$('#submit-setup').removeAttr("disabled");
							}
						}
					},
					error: function (data, status, e)
					{
						alert(e);
					}
				}
			)
		   
			return false;
	
		}
	},
	deployLightbox : function(which, width, height, bar)
	{
		// Set height and width
		var $h, $w;

		if (which != null) {
			which = which;	
		} else {
			which = '';	
		}
		if (height != null) {
			$h = height;
		} else { 
			$h = 600;
		}	
		if (width != null) {
			$w = width;
		} else { 
			$w = 800;
		}
	
		if (bar != null && bar == true) {
			// Append lightbox with menu code to bottom of the <body>
			$('body').prepend(
				'<div id="shield" style="display:none;">'
				+ '</div><!-- #shield -->'
				+ '<div id="outer" style="display:none;">'
				+ '<div id="lightbox-bar"><a id="lightbox-exit"></a></div>'
				+ '<iframe id="include" frameborder="0" src="" height="100%" width="100%"></iframe>'
				+ '</div><!-- #outer -->'
			);
		} else {
			// Append lightbox code to bottom of the <body>
			$('body').prepend(
				'<div id="shield" style="display:none;">'
				+ '</div><!-- #shield -->'
				+ '<div id="outer" style="display:none;">'
				+ '<iframe id="include" name="include" frameborder="0" src="" height="100%" width="100%"></iframe>'
				+ '</div><!-- #outer -->'
			);
		}
		
		// Determine left positioning
		var $left = (( $(window).width() - $w) / 2);
		
		// Set the CSS that positions the lightbox
		$('#outer').css('top','100px');
		$('#outer').css('width',$w + 'px');
		$('#outer').css('height',$h + 'px');
		$('#outer').css('left',($left-5) + "px"); // again, -5 for padding
		$('#outer iframe').attr('src',which);
			
		// Show the lightbox
		$("#shield").show('fast',function() {
			$("#outer").show('fast',function() {
				// If the shield is clicked, close the lightbox
				$("#shield").click(function() {
					quicksite.closeLightbox();
				});
			});
		});
		$("HTML").css("overflow", "hidden");
	},
	deployThemeLightbox : function(which)
	{
		// Append lightbox with menu code to bottom of the <body>
		$('body').prepend(
			'<div id="theme_shield" style="display:none;">'
			+ '</div><!-- #shield -->'
			+ '<div id="theme_outer" style="display:none;">'
			+ '<div id="lightbox-bar"><a id="themebox-exit"></a></div>'
			+ '<iframe id="include" frameborder="0" src="" height="100%" width="100%"></iframe>'
			+ '</div><!-- #outer -->'
		);
		
		var window_width = self.innerWidth || (document.documentElement.clientWidth || document.body.clientWidth);
		var window_height = self.innerHeight || (document.documentElement.clientHeight || document.body.clientHeight);
		
		// Determine height and width
		var w = ( window_width - 60 );
		var h = ( window_height - 60 );
		
		// Determine left and top positioning
		var left = (( window_width - w) / 2);
		var top = (( window_height - h) / 2);
		
		// Set the CSS that positions the lightbox
		$('#theme_outer').css('z-index','9999');
		$('#theme_outer').css('top',(top) + "px");  
		$('#theme_outer').css('left',(left) + "px");
		$('#theme_outer').css('width',w + 'px');
		$('#theme_outer').css('height',h + 'px');
		$('#theme_shield').css('z-index','9998');
		$('#theme_outer iframe').attr('src',which);
			
		// Show the lightbox
		$("#theme_shield").show('fast',function() {
			$("#theme_outer").show('fast',function() {
				// If the shield is clicked, close the lightbox
				$("#theme_shield").click(function() {
					quicksite.closeThemeLightbox();
				});
			});
		});
		$("HTML").css("overflow", "hidden");
	},
	resizeLightbox : function(width, height, callback)
	{	
		// Determine left positioning
		var $left = (( $(window).width() - width) / 2);
		
		if (callback != null) callback();
		
		// Set the CSS that positions the lightbox
		$('#outer').css({'left':($left-5) + "px"}); // again, -5 for padding
		$('#outer').animate({'height':height,'width':width},100);
	},
	closeLightbox : function() 
	{
		// Hide lightbox HTML
		$("#shield").hide('fast');
		$("#outer").hide('fast');
				
		// Remove HTML
		$("#shield").remove();
		$("#outer").remove();
		$("HTML").css("overflow","visible" );
	},
	closeThemeLightbox : function() 
	{	
		// Hide lightbox HTML
		$("#theme_shield").hide('fast');
		$("#theme_outer").hide('fast');
				
		// Remove HTML
		$("#theme_shield").remove();
		$("#theme_outer").remove();
	},
	formatYoutube : function()
	{
		// resize .block-vid iframes (Youtbe embeds) and make them transparent
		$(".block-vid iframe").width(320).height(270);
		$('.block-vid iframe').each(function() {
			var url = $(this).attr("src");
			$(this).attr("src",url+"?wmode=transparent");
		});
	},
	newUser : 
	{
		// Step 1: choose theme
		stepOne : function()
		{
			quicksite.deployLightbox('/includes/chooseTheme',770,450);	
		},
		// Step 2: choose a site title
		stepTwo : function()
		{
			$("#include").hide();
			// Adjust the size of the iframe
			quicksite.resizeLightbox(600,230,function(){
				$("#include").attr('src','/includes/siteTitle').show();
			});
		},
		// Step 3: choose post type
		stepThree : function()
		{
			// Adjust the size of the iframe
			quicksite.resizeLightbox(770,450,function(){
				$("#include").attr('src','/includes/firstPost');
			});	
		},
		stepFour : function(type)
		{
			$("#include").attr('src','/includes/newPost/' + type);	
		},
		stepFive : function()
		{
			quicksite.closeLightbox();	
		}
	},
	removeBlock : function(id)
	{
		var postdata = {
			blockid		:	id
		};
				
		$.post('/_api/removeBlock',postdata,function(data){
			if (data.error) alert(data.message);
		},'json');
	},
	removePage : function(id)
	{
		var postdata = {
			mongoid		:	id
		};
				
		$.post('/_api/removePage',postdata,function(data){
			if (data.error) alert(data.message);
		},'json');
	},
	showBlockMessage : function(message)
	{
		$(".message-div").remove();
		
		$("#admin-main").prepend(
			'<div class="block message-div" style="background-color:#f8f8f8; display:none;">'
			+ '<div class="block-message">'
			+ message
			+ '</div>'
			+ '</div>'
		);
		
		$(".message-div").slideDown();		
	},
	hideLoading : function()
	{
		$('#loading-box').remove();	
	},
	showLoading : function() 
	{
		// Create a loading box
		$('body').append(
			'<div id="loading-box" style="display:none;"><img src="/_img/ajax-loader.gif" /></div>'
		);
		
		$("#loading-box").css({
			'position'	:	'absolute',
			'top'		:	'50%',
			'left'		:	'50%',
			'z-index'	:	'9999999'
		}).show();
	},
	changeTheme : function(selected, theme_name)
	{
		var postdata =
		{
			mongoid : selected,
			theme_name : theme_name	
		}

		$.post('/_api/updateTheme', postdata, function(data) {
			if (data.error != "false") {
				quicksite.showBlockMessage("Could not select theme, please try again later.");
			} else {
				quicksite.showBlockMessage("You've successfully updated your theme!");
			}
		},'json')	
	},
	shareNew : 
	{
		facebook : false,
		twitter : false,
		toggleLock : false,
		toggleFacebook : function(pos)
		{
			if (quicksite.shareNew.toggleLock == true) return;
			
			if (pos) {
				if (pos == 'on') {
					//$('#fb-share').attr('src','/_img/fb-share-checked.png');
					$('#can-post-fb').attr('CHECKED',true);
					quicksite.shareNew.facebook = true; 
				} else {
					//$('#fb-share').attr('src','/_img/fb-share-unchecked.png');
					$('#can-post-fb').attr('CHECKED',false);
					quicksite.shareNew.facebook = false;
				}
			} else {
				if (quicksite.shareNew.facebook == false) {
					//$('#fb-share').attr('src','/_img/fb-share-checked.png');
					$('#can-post-fb').attr('CHECKED',true);
					quicksite.shareNew.facebook = true; 
				} else {
					//$('#fb-share').attr('src','/_img/fb-share-unchecked.png');
					$('#can-post-fb').attr('CHECKED',false);
					quicksite.shareNew.facebook = false;
				}
			}
		},
		toggleTwitter : function(pos)
		{	
			if (quicksite.shareNew.toggleLock == true) return;
			
			if (pos) {
				if (pos == 'on') {
					//$('#twitter-tweet').attr('src','/_img/tweet-checked.png');
					$('#can-tweet').attr('CHECKED',true);
					quicksite.shareNew.twitter = true; 
				} else {
					//$('#twitter-tweet').attr('src','/_img/tweet-unchecked.png');
					$('#can-tweet').attr('CHECKED',false);
					quicksite.shareNew.twitter = false;
				}
			} else {
				if (quicksite.shareNew.twitter == false) {
					//$('#twitter-tweet').attr('src','/_img/tweet-checked.png');
					$('#can-tweet').attr('CHECKED',true);
					quicksite.shareNew.twitter = true; 
				} else {
					//$('#twitter-tweet').attr('src','/_img/tweet-unchecked.png');
					$('#can-tweet').attr('CHECKED',false);
					quicksite.shareNew.twitter = false;
				}
			}
		},
		lockToggle : function(l)
		{
			quicksite.shareNew.toggleLock = l;
		},
		privatize : function(checked)
		{
			if (checked == true) {
				quicksite.shareNew.toggleFacebook('off');
				quicksite.shareNew.toggleTwitter('off');
				quicksite.shareNew.lockToggle(true);
				$("#sharing-div").slideUp();
			} else {
				quicksite.shareNew.lockToggle(false);
				quicksite.shareNew.toggleFacebook('on');
				quicksite.shareNew.toggleTwitter('on');
				$("#sharing-div").slideDown();
			}
		}
	},
	showMoreFeed : 
	{
		have : null,
		showMoreLink : function()
		{
			$("#admin-main").append(
				'<div class="block show-more-block" style="background-color:#f8f8f8; display:none;">'
				+ '<div class="show-more-div">'
				+ '<a id="show-more">Show More</a>'
				+ '</div>'
				+ '</div>'
			);
			
			// Show it
			$(".show-more-block").show();
		},
		getFeed : function(callback)
		{
			var postdata = 
			{
				userid 	:	quicksite.userid,
				type 	:	'all',
				limit	:	15,
				have	:	quicksite.showMoreFeed.have	
			}
			
			var formFeed = '';
			
			$.post('/_api/getMoreFeed', postdata, function(data) {
				quicksite.showMoreFeed.have = parseInt(quicksite.showMoreFeed.have) + parseInt(data.count);
				callback(data.feed,data.more); // The formatted feed
			},'json');
		},
		showFeed : function()
		{
			var handler = function(the_feed,more)
			{
				// Remove existing "show more" buttons
				$(".show-more-block").remove();
					
				// Append the feed
				$("#admin-main").append(the_feed);
				
				// Format the youtube videos
				quicksite.formatYoutube();
				
				if (more != false) {
					// Append the "show more" buttons
					quicksite.showMoreFeed.showMoreLink();
				}
			};
		
			quicksite.showMoreFeed.getFeed(handler);		
		}
	},
	usernameObj : 
	{
		proceed : false,
		checkUsername : function(username)
		{		
			function hideall() {
				$("#uname-unavailable").hide();
				$("#uname-available").hide();
				$("#uname-invalid").hide();
			}
			
			if (username.length < 3) {
				hideall();
				parent.quicksite.usernameObj.proceed = false;
				return false;
			}
			
			if (username.length > 20) {
				hideall();
				parent.quicksite.usernameObj.proceed = false;
				$("#uname-invalid").show();
				return false;
			}
			
			if (!quicksite.helpers.validateUsername(username)) {
				hideall();
				$("#uname-invalid").show();
				parent.quicksite.usernameObj.proceed = false;
				return false;	
			}
			
			var postdata = {
				username : username	
			}
			
			$.post('/_api/usernameAvailable',postdata,function(data) {
				if (data.available == true)	{
					// Show the 'not available' stuff
					hideall();
					$("#uname-available").show();
					parent.quicksite.usernameObj.proceed = true;
					return true;
				} else {
					// Show the 'available' stuff
					hideall();
					$("#uname-unavailable").show();
					parent.quicksite.usernameObj.proceed = false;
					return false;
				}
			},'json');
			
		},
		checkUsername2 : function(username)
		{		
			if (username.length < 3) {
				$("#username-msg").html('');
				parent.quicksite.usernameObj.proceed = false;
			}
		
			if (!quicksite.helpers.validateUsername(username)) {
				if (username != '') $("#username-msg").html('<span class="username-invalid">This username is invalid.</span>');
				else $("#username-msg").html('');
				parent.quicksite.usernameObj.proceed = false;
				return false;	
			}
			
			var postdata = {
				username : username	
			}
			
			$.post('/_api/usernameAvailable',postdata,function(data) {
				if (data.available == true)	{
					// Show the available stuff
					$("#username-msg").html('<span class="username-available">' + username + '</span>.rollr.com is available.');
					parent.quicksite.usernameObj.proceed = true;
					return true;
				} else {
					// Show the 'available' stuff
					$("#username-msg").html('<span class="username-unavailable">' + username + '</span>.rollr.com is unavailable.');
					parent.quicksite.usernameObj.proceed = false;
					return false;
				}
			},'json');
		},
		checkUsername3 : function(username)
		{
			if (username.length < 3) {
				$("#username-msg").html('');
				parent.quicksite.usernameObj.proceed = false;
			}
		
			if (!quicksite.helpers.validateUsername(username)) {
				if (username != '') $("#username-msg").html('<span class="username-invalid">' + username + '.rollr.com is invalid.</span>');
				else $("#username-msg").html('');
				parent.quicksite.usernameObj.proceed = false;
				return false;	
			}
			
			var postdata = {
				username : username	
			}
			
			$.post('/api/usernameAvailable',postdata,function(data) {
				if (data.available == true)	{
					// Show the available stuff
					$("#username-msg").html('<span class="username-available">' + username + '</span>.rollr.com is available!');
					parent.quicksite.usernameObj.proceed = true;
					return true;
				} else {
					// Show the 'available' stuff
					$("#username-msg").html('<span class="username-unavailable">' + username + '</span>.rollr.com is not available.');
					parent.quicksite.usernameObj.proceed = false;
					return false;
				}
			},'json');
		}
	}
}

$(document).ready(function(){

	if (quicksite.show_sidebar == true && typeof sidebar != "undefined" && typeof sidebar.show_sidebar != "undefined") {
		sidebar.show_sidebar(quicksite.sidebar_start);
	}

	var $image_path = false;
	var $image_url = false;
	var $thumbnail_url = false;
	var $thumbnail_path = false;
	
	var $edit_toggle = false;
	
	quicksite.formatYoutube();
	
	// Populate username, userid, and position
	quicksite.username = $("#username").val();
	quicksite.showMoreFeed.have = $("#have").val();
	quicksite.userid = $("#userid").val();	
	
	/*  ON CLICK  */
	$(document).click(function(e){
		$this = $(e.target);
				
		//$(".options-box").remove();
		
		//alert($this.attr("id"));
				
		switch($this.attr("id"))
		{
			case 'submit-text':
				$("#text-title-error").empty();
				// Validate the title and content
				if (!quicksite.helpers.validateTitle($('#text-title').val())) {
					$("#text-title-error").append('<span class="validate-error">Title is required</span>').show();
					e.preventDefault();	
				}
				break;
			case 'submit-image':
				var proceed = true;
				$("#image-title-error").empty();
				$("#image-file-error").empty();
				// Validate image url
				if ($("#file").val() == '') {
					$("#image-file-error").append('<span class="validate-error">Image is required</span>');
					e.preventDefault();
					proceed = false;
				}
			 	// Validate the title
				if (!quicksite.helpers.validateTitle($('#image-title').val())) {
					$("#image-title-error").append('<span class="validate-error">Title is required</span>');
					e.preventDefault();
					proceed = false;
				}
				
				if (proceed == false) return false;
				
				$("#image-filter").val(imageuploader.filter);
				$("#original-name").val(imageuploader.original_name);
																									 	
			 	// Last, submit form
			 	$("#add-image").submit();
			 	break;
			case 'submit-embed':
				e.preventDefault();
				var proceed = true;
				$("#embed-title-error").empty();
				$("#embed-code-error").empty();
				
				if (!quicksite.helpers.validateTitle($('#embed-title').val())) {
					$("#embed-title-error").append('<span class="validate-error">Title is required</span>');
					e.preventDefault();
					proceed = false;
				}
				
				if (!quicksite.helpers.validateEmbed($('#embed-code').val())) {
					$("#embed-code-error").append('<span class="validate-error">Embed code is require</span>');
					e.preventDefault();
					proceed = false;
				}
				
				if (proceed == false) return false;
				
				$("#add-embed").submit();
				break;
			/*
			case 'submit-video':
				// Validate the title and content
				$("#video-title-error").empty();
				$("#video-url-error").empty();
				if (!quicksite.helpers.validateTitle($('#video-title').val())) {
					$("#video-title-error").append('<span class="validate-error">Title is required</span>');
					e.preventDefault();	
				}
				if (!quicksite.helpers.validateURL($('#video-url').val())) {
					$("#video-url-error").append('<span class="validate-error">Video URL is required</span>');
					e.preventDefault();	
				}
				break;
			case 'submit-link':
				// Validate url
				$("#link-url-error").empty();
				if (!quicksite.helpers.validateTitle($('#link-url').val())) {
					$("#link-url-error").append('<span class="validate-error">URL is required</span>');
					e.preventDefault();	
				}
				break;
			*/
			/*case 'go-home':
				// Hmm....go home?
				window.location = '/customize';
				break;*/
			case 'connect-facebook':
				quicksite.facebook.fbNewUser();
				break;
			case 'main-signup':
				// Validate email, password, and username
				// Check to see if email address is valid
				var data = [
					{ type : 'email', obj : $('#main-email') },
					{ type : 'password', obj : $('#main-password') },
					{ type : 'username2', obj : $('#main-username') }
				];
				if (!quicksite.validate(data)) e.preventDefault();
				else $("#signupform").submit();
				break;
			case 'submit-page':
				// Validate the data and submit the page
				var data = [
					{ type : 'title', obj : $('#page-title') }
				];
				if (quicksite.ate(data)) $('#add-page-form').submit();
				break;
			case 'main-fb-signup-button':
			case 'main-facebook-login':
				quicksite.facebook.fbMainLogin();
				break;
			case 'continue-username':
				// final validation on username
				if (parent.quicksite.usernameObj.proceed == false) {
					alert("Please choose a valid username.");
				} else if (!quicksite.helpers.validatePassword($("#choose-password").val())) {
					alert("Please choose a valid password.");
				} else {
					parent.quicksite.username = $("#choose-username").val();
					parent.quicksite.password = $("#choose-password").val();
					parent.quicksite.facebook.fbRegister();
				}
				break;
			case 'cancel-username':
				parent.quicksite.closeLightbox();
				break;
			case 'go-home':
				window.location = '/customize';
				break;
			case 'main-login-button':
				window.location = '/admin/login';
				break;
			case 'main-signup-button':
				window.location = '/admin/signup';
				break;
			case 'fb-share':
			case 'can-post-fb':
				if (user.connectedFacebook == false) {
					// Prompt to connect to facebook
					quicksite.facebook.fbNewUser(function(){
						quicksite.shareNew.toggleFacebook();
						user.connectedFacebook = true;
					});
				} else {
					quicksite.shareNew.toggleFacebook();
				}
				break;
			case 'twitter-tweet':
			case 'can-tweet':
				if (user.connectedTwitter == false) {
					// Prompt to connect to twitter
					window.open('/twitter/redirecter','',"height=800,width=800,modal=yes,alwaysRaised=yes");
					quicksite.shareNew.toggleTwitter();
				} else {
					quicksite.shareNew.toggleTwitter();
				}
				break;
			case 'ps-private':
				quicksite.shareNew.privatize(true);
				break;
			case 'ps-public':
				quicksite.shareNew.privatize(false);
				break;
			case 'remove-cat':
				if (confirm("Are you sure you want to remove the selected category(s)?")) {
					var cat_arr = [];
					$("input[class=category-input]:checked").each(function(i){
						cat_arr.push(this.value);
						$("#uccode-"+this.value.replace(/\s/g, "")).remove();
					});
					quicksite.categories.removeCategories(cat_arr);
				}
				break;
			case 'show-register':
				$("#facebook-register-div").hide();
				$("#register").fadeIn(1500);
				break;
			case 'show-facebook-reg-div':
				$("#register").hide();
				$("#facebook-register-div").fadeIn(1500);
				break;
			default:
			 	break;
		}
		
		switch($this.attr('class'))
		{
			case 'post-title':
				if ($this.val() == 'Post Title') {
					$this.val('');
				}
				break;
			default:
				break;
		}
	});
	
	/*  ON KEYUP  */
	$(document).keyup(function(e){
		$this = $(e.target);
		
		switch($this.attr("id"))
		{
			case 'choose-username':
				quicksite.usernameObj.checkUsername($this.val());
				break;
			case 'main-username':
				quicksite.usernameObj.checkUsername2($this.val());
				break;
			case 'community-username':
				quicksite.usernameObj.checkUsername3($this.val());
				break;
			default:
				break;
		}
	});
	
	/* ON KEYPRESS */
	$('#new-cat').keypress(function(e){
		if (e.which == 13) { // They pressed enter
			e.preventDefault();
			
			var cat = $(e.target).val();
			if (cat == '' || cat == 'New Category') {
				$('#new-cat').val('New Category');
				return;
			}
			
			var postdata = {
				userid		: user.userid,
				category	: cat  
			}
			
			$('#new-cat').val('');
			
			$.post('/_api/createCategory',postdata,function(data){
				if (data.error == false) {
					$('#selected-categories').append(
						'<div id="uccode-'+cat.replace(/\s/g, "")+'"><input type="checkbox" name="categories[]" value="'+cat+'" CHECKED></input>&nbsp;'+cat+'</div>'
					);
					$("#remove-cat").show();
				} else {
					alert("Could not create category or category already exists.");
				}
			},'json');
		}
	});
		
	/*  ON CHANGE  */
	$(document).change(function(e){
		$this = $(e.target);
		
		switch($this.attr("id"))
		{
			case 'image-file':
				if ($thumbnail_path != false) {
					removeImage($thumbnail_path);
				}
				ajaxFileUpload();
				break;
			default:
				break;
		}
	});	
	
	/*  ON BLUR  */
	$('input').blur(function(e){
		$this = $(e.target);
		
		switch($this.attr("ID"))
		{
			case 'main-email':
				if ($this.val() == '') {
					$this.val('Email Address');
					$this.css('color','#999');
				}
				break;
			case 'main-password':
				if ($this.val() == '') {
					$('#main-password').hide();
					$('#main-text-password').show();
					$('#main-text-password').css('color','#999');
				}
				break;
			case 'main-username':
				if ($this.val() == '') {
					$this.val('Username');
					$this.css('color','#999');
					$("#username-msg").text('');
				}
				break;
			case 'community-username':
				if ($this.val() == '') {
					$this.val('Username');
					$this.css('color','#999');
					$("#username-msg").text('');
				}
				break;
			case 'new-cat':
				if ($this.val() == '') {
					$this.val('New Category');
				}
				break;
			default:
				break;
		}
		
		switch($this.attr('class'))
		{
			case 'post-title':
				if ($this.val() == '') {
					$this.val('Post Title');
				}
				break;
			default:
				break;
		}
	});
	$('#embed-code').blur(function(){
		if ($(this).val() == '') {
			$(this).val('Paste embed code or a video url');
		}
	});
	
	/*   ON FOCUS   */
	$('input').focus(function(e){
		$this = $(e.target);
		
		switch($this.attr("id"))
		{
			case 'main-email':
				if ($('#main-email').val() == 'Email Address')
					$('#main-email').val('');
					$this.css('color','#333');
				break;
			case 'main-text-password':
				$("#main-text-password").hide();
				$('#main-password').show().focus().css('color','#333');
				break;
			case 'main-username':
				if ($('#main-username').val() == 'Username')
					$('#main-username').val('');
					$this.css('color','#333');
				break;
			case 'community-username':
				if ($('#main-username').val() == 'Username')
					$('#main-username').val('');
					$this.css('color','#333');
				break;
			case 'new-cat':
				if ($this.val() == 'New Category') {
					$this.val('');
				}
				break;
			default:
				break;
		}
	});
	$('#embed-code').focus(function(){
		if ($(this).val() == 'Paste embed code or a video url') {
			$(this).val('');
		}
	});
	
	/*  ON HOVER  */
	$('.btn-blue').hover(
		function(){
			$(this).removeClass('btn-blue');
			$(this).addClass('btn-blue-hover');
		},
		function() {
			$(this).removeClass('btn-blue-hover');
			$(this).addClass('btn-blue');
		}
	);
	$('.btn-red').hover(
		function(){
			$(this).removeClass('btn-red');
			$(this).addClass('btn-red-hover');
		},
		function() {
			$(this).removeClass('btn-red-hover');
			$(this).addClass('btn-red');
		}
	);
	$('.btn-green').hover(
		function(){
			$(this).removeClass('btn-green');
			$(this).addClass('btn-green-hover');
		},
		function() {
			$(this).removeClass('btn-green-hover');
			$(this).addClass('btn-green');
		}
	);
	
	function ajaxFileUpload()
    {
        //starting setting some animation when the ajax starts and completes
        $("#loading").show();
		$('#submit-image').attr("disabled","disabled");
       
        $.ajaxFileUpload
        (
            {
                url:'/_api/uploadImage',
                secureuri:false,
                fileElementId:'image-file',
                dataType: 'json',
                success: function (data, status)
                {
                    if(typeof(data.error) != 'undefined')
                    {
                        if(data.error != '')
                        {
                            alert(data.error);
							$('#loading').hide();
                        }else
                        {
                            // alert(data.msg);
                            $("#image_preview").empty();
                            $("#image_preview").append('<img src="' + data.thumbnail_url + '" />');
                            
                            $("#image-caption-div").show('fast');
							
							$('#loading').hide();
							$('#submit-image').removeAttr("disabled");
                            
                            quicksite.image_path = data.image_path;
                            quicksite.image_url = data.image_url;
                            quicksite.thumbnail_url = data.thumbnail_url;
                            quicksite.thumbnail_path = data.thumbnail_path;
                         
                        }
                    }
                },
                error: function (data, status, e)
                {
                    alert(e);
					$('#loading').hide();
                }
            }
        )
        return false;
    }
    
    function removeImage(path)
    {
    	var postdata = {
    		image_path	:	path
    	};
    
    	$.post('/_api/removeImage',postdata,function(data){
    		$thumbnail_url = false;
    		$thumbnail_path = false;
    	},'json');
    }

	// On window resize
	$(window).resize(function(){		
		// calculate workspace, sidebar width
		// determine sidebar stuff
		if (quicksite.show_sidebar == true && typeof sidebar.resize != "undefined") {
			sidebar.resize($("#outer-wrapper"));
		}
	});
    
});

$(window).load(function(){
	// calculate workspace, sidebar width
	// determine sidebar stuff
	/*if (quicksite.show_sidebar == true) {
		sidebar.resize($("#outer-wrapper"));
	}*/
});


