
$( function() {
	
	var promo_callout = $("#promo_callout")
	
	promo_callout.jqm()
	
	$("#address_address").inputLabel("phone # or email")
	
	
	$(".promo").mouseenter( function() {
		$(this).append("<div class=\"mo\">click for details</div>")
		$(this).addClass("promo_hover")
	});
	
	
	$(".promo").mouseleave( function() {
		$(".mo").remove()
		$(this).removeClass("promo_hover")
	})
	
	var req_id = 0
	
	$(".promo").click( function() {
		var promo_id = $(this).attr("promo_id")
		
		$("#load_wrapper").hide()
		promo_callout.jqmShow()
		
		$.getJSON("/promos/details/" + promo_id, {}, function(data) {
			promo = data
			
			// fill into details of promotion
			$("h1#pc_name").text(promo.vendor.name)
			
			$("#description").text(promo.description)
			
			if (!promo.expires) {
				$("#expiration").text("")
			}
			else {
				$("#expiration").text("Expires " + promo.expires)
			}
			
			$("#websites li").remove()
			
			if (promo.vendor.site_link.id) {
				$("#websites").append("<li><a href=\"/vendors/site/" + promo.vendor.id + "\" target=\"_blank\">" + promo.vendor.site_link.label + "</a></li>");
			}
			if (promo.vendor.alt_link.id) {
				$("#websites").append("<li><a href=\"/vendors/alt/" + promo.vendor.id + "\" target=\"_blank\">" + promo.vendor.alt_link.label + "</a></li>");
			}
			
			status_text.removeClass("error").text("Send this to your email")
            
            $("#subscribe").attr("name", "subscribe[" + promo.vendor.id + "]")
			
            $("#promo_id").val(promo.id)
            
			$(".status").css("display", "none")
			sendit.show()
			
			$(".promo_checkbox").removeAttr("checked")
			$("#twitter_link").attr("href", "/promos/twitter/" + promo_id)
			$("#facebook_link").attr("href", "/promos/facebook/" + promo_id)
			
			$(".promo_form").attr("action", "/promos/send")

			$("#load_wrapper").show()
		})

	})
	
	
	var sendit = $("#sendit")
	var loading = $("#loading")
	var success = $("#success")
	var pending = $("#pending")
	var error = $("#error")
	
	var status_text = $("#status_text")
	
	function send_callback(data) {

		$(".status:visible").hide()

		switch (data.status) {
		
			case "no_format":
				status_text.addClass("error").text("Please enter an email address")
				sendit.show()
			break;
			
			case "email_success":
			case "text_success":
				success.show()
				$(document).oneTime("3s", function() {
					promo_callout.jqmHide()
				})
				
			break
			
			case "text_pending":
			case "text_invited":
				pending.show()
			break
			
			default:
				error.show()
			
		}
	}
	
	$(".promo_form").submit( function() {
		$(".status:visible").hide()
		loading.show()
		$.post($(this).attr("action"), $(this).serialize(), send_callback, "json")
		return false
	})

})

