//view controller for deal.jade

$(document).ready(function(){
	
	$('#facebook').click(function(e){
		//set up extra permissions
		disableLogins()
		
		FB.login(function(response){
			if (response.authResponse) 
			{
			     
				FB.api('/me', function(response) {
					console.log(response)
					
					var user = new mmd.models.User(response)
					user.save(function(){
						showDeal('facebook')
						
						
						
						//post to facebook
						var message = { 
								message: "I just saved $" + mmd.deal.savings +" at MyMovieDeals.com",
								picture: mmd.deal.image,
								link: "http://m.mymoviedeals.com/deal/"+mmd.deal.slug,
								name: mmd.deal.title,
								caption: mmd.deal.title,
								description: mmd.deal.description,
								type: "link"
								//TODO:add icon
						}
						
						//commented out for now
						// FB.api('/me/feed', 'post', message, function(response) {
						// 							console.log(response)
						// 						  if (!response || response.error) {
						// 						    //alert('Error occured');
						// 						  } else {
						// 						    //alert('Post ID: ' + response.id);
						// 						  }
						// 							// FB.logout(function(response){
						// 							// 								console.log("cleared")
						// 							// 							})
						// 						});
						
					})
					
		   });
		
		  } 
			else 
			{
				
	    	console.log('User cancelled login or did not fully authorize.');
	    }
		
		})
	})
	
	$('#email').click(function(e){	
	
		//disable login buttons
		disableLogins()
		
		$('#emailModal').reveal()
		$('#emailAddress').focus()
	})
	
	$('#go').click(function(e){
		//disable the buttons so submission can happen
		
		//validate the email

		if(validateEmail($('#emailAddress').val()) || $('#emailAddress').val().length != 0) {
			var user = new mmd.models.User({
																			email			: $('#emailAddress').val()
																		,	first_name: $('#fname').val()
																		,	last_name	: $('#lname').val()
																			})
																			
			user.save(function(){
				$('#emailModal').trigger('reveal:close')
				clearForm()
				enableLogins()
				showDeal("email")
			})																
			

		} else {
			//highlight the email as being lame
			$('#emailAddressLabel').addClass('red')
		}
		
		
	})
	
	$('#cancel').click(function(e){
		console.log("canceled deal")
		clearForm()
		enableLogins()
	})
	
	
	function showDeal(where)
	{
		
		//http://m.mymoviedeals.com/deal/free-popcorn-at-palm-dor/code/4f08887dd76a94024f000003
		
		enableLogins()
		
		//TODO simplify to a get
		$.ajax({
		  url: "/deal/"+mmd.deal.slug+"/code/"+mmd.user._id,
		  type: "GET",
		  complete: function() { //called when complete
				
		  },

		  success: function(data, status, xhr) { //called when successful
				console.log(data)
				
				var $map;
				if(data.success)
				{
					$(".response").show()
					
				}
				
				
				if(data.success == true && !data.rd)
				{
					$(".coupon").show()
									
					//in with the new
					$("#title").html('You Got It!  <br><small>We think you are <i>pretty</i> neat.</small>')
					$("#subtitle").html('<a href="http://m.mymoviedeals.com/user/' + mmd.user._id + '/deals/' + mmd.deal.slug + '?print=true"">Print the deal</a>  |  <a href="http://m.mymoviedeals.com/user/'+mmd.user._id+'/deals">View Your Deals Here</a>')
					
					$(".instructions").html('<h3>'+ mmd.deal.title + 
											'</h3>' + '<p>' + mmd.deal.redemption + '</p><p>' + 
											'<p><a href="http://m.mymoviedeals.com/user/' + mmd.user._id + '/deals/' + mmd.slug + '">View</a> | <a href="http://m.mymoviedeals.com/user/' + mmd.user._id + '/deals/' + mmd.deal.slug + '?print=true">Print</a></p>' + 
											'<p><a href="http://m.mymoviedeals.com/user/' + mmd.user._id + '/deals">View All Your Deals</a>' +
											'</p>')
					
					$(".qrcode").html('<h3>The Code</h3><img src="'+data.qrcode+'" height="200" width="200">')
					$(".map").html('<h3>The Venue</h3><img src="http://maps.google.com/maps/api/staticmap?center='+mmd.deal.lat+','+mmd.deal.lon+'&zoom=13&markers=label:$|'+mmd.deal.lat+','+mmd.deal.lon+'&size=320x200&sensor=false">' +
												 '<p><a href="">Get Directions</a></p>' +
													'<div class="venue">' +
														'<ul>' +
															'<li>' +
																'<b>'+ mmd.deal.venue +'</b>' +
															'</li>' +
															'<li>' + mmd.deal.address + '</li>' +
															'<li>' + mmd.deal.city + ' ' + mmd.deal.state + ' ' + mmd.deal.postal + '</li>' +
														'</ul>' +
													'</div>'	)
										
					 														
				}
				
				if(data.success && data.rd)
				{
					//clearElements()
					
					$("#title").html('You Already Got It! <small>(We still think highly of you.)</small>')
					$("#subtitle").html('It looks like you already signed up for this one.  <a href="http://m.mymoviedeals.com/'+data.rd+'">View Your Deals Here</a>')
					
				}
				
		 	},

		  error: function() {
		    //called when there is an error
				console.log("error")
			
		  }
		
		});
	}
	
	
	function disableLogins()
	{
		$("button#email").attr('disabled','disabled')
		$("button#facebook").attr('disabled','disabled')
	}
	
	function enableLogins()
	{

		$("button#email").removeAttr('disabled')
		$("button#facebook").removeAttr('disabled')
	}
	
	
	function clearForm() 
	{
		$("#emailAddress").val('')
		$("#fname").val('')
		$("#lname").val('')
	}
	
	//thanks to jim gaudet http://thejimgaudet.com/articles/jquery-e-mail-validation-without-a-plugin/
	function validateEmail($email) {
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		if( !emailReg.test( $email ) ) {
			return false;
		} else {
			return true;
		}
	}
	
	
	
})
