var instructionChannel;
var currentEmailSending = {
	'emailNumber': 0
};

$(document).ready(function(){
	$("body").removeClass("noscript");
	$(".pulldown .top").remove();
	$(".top").click(function(){
		$.scrollTo(0,400);
		return false;
	});
	
	// Enable Email and Video Tabs
	$(".email").addClass("email-tab-selected").children("h2").click(function(){
		var p = $(this).parent(".email");
		if(p.hasClass("sending")){
			cancelSend(p);	
		}
		p.find(".thumbnail img").show();
		p.find(".thumbnail #video-replace").remove();
		p.get(0).className = "email " + (this.className.replace(" hover","")) + "-selected";
		p.find(".send-email").hide();
	});
	
	// Move helper content up top into the channel and hide the channel
	$(".pulldown").appendTo("#instruction-channel").removeClass("pulldown").addClass("content").hide();
	instructionChannel = $("#instruction-channel").hide();
	
	// Add the tabs and associated code
	$("#tabs .content").empty();
	addTab("faqs");
	addTab("instructions");
	
	// Enable the clipboard feature
	$.clipboardReady(function(){
		$( ".description span" ).click(function(){
			var clipText = $(this).parent().find(".video-path").text();
			$.clipboard(clipText);
			return false;
		});
	}, { swfpath: "js/jquery.clipboard.swf" } );
	
	
	// Temporarly open the faq tab
	//$("#tabs h2:eq(0)").click();
	
	
	$("#send-from-browser, #download-pdf, #download-source, #send-error, #send-success").dialog({ 
	    modal: true, 
	    overlay: { 
	        opacity: 0.5, 
	        background: "black" 
	    },
		buttons: {
			"Back to Email Center":function(){
				$(this).dialog("close");
			}
		},
		width: 400,
		height: 275,
		autoOpen: false
	});
	
	$("#requirements").dialog({
		modal: true,
		overlay: {
			opacity: 0.5,
			background: "black"
		},
		buttons: {
			"Yes, This Mailing Meets These Requirements":function(){
				$(this).dialog('close');
				sendActualEmails();
			},
			"No":function(){
				$(this).dialog('close');
			}
		},
		width: 800,
		height: 275,
		autoOpen:false
	});
	
	$("#ltci-requirements").dialog({
		modal: true,
		overlay: {
			opacity: 0.5,
			background: "black"
		},
		buttons: {
			"Yes, I Certify These Statements Are True":function(){
				$(this).dialog('close');
				sendActualEmails();
			},
			"No":function(){
				$(this).dialog('close');
			}
		},
		width: 750,
		height: 450,
		autoOpen:false
	});
	
	$(".send .help").click(function(){
		$("#send-from-browser").dialog("open");
	});
	
	$(".pdf .help").click(function(){
		$("#download-pdf").dialog("open");
	});
	
	$(".source .help").click(function(){
		$("#download-source").dialog("open");
	});
	
	$(".preview-video").click(function(){
		resetMedia();
		var videoName = this.rel;
		var thumb = $(this).parents("div.email").find(".video-email .thumbnail");
		thumb.find("img").hide();
		thumb.append("<div id='video-replace'>Replace with Video</div>");
		insertVideo(videoName);
		return false;
	});
	
	//$("#email-01-section > div").css("display","none");
	$("#send-mail-form").hide();
	//$("#send-mail-form").appendTo($("#email-01-section")).show();
	
	$(".email .video-email .send a").click(function(){
		var altClass = $(this).hasClass('ltci') ? "ltci" : "";
		sendEmail($(this).parents("div.email"),"video",parseInt(this.rel),altClass);
		return false;
	});
	
	$(".email .html-email .send a").click(function(){
		var altClass = $(this).hasClass('ltci') ? "ltci" : "";
		sendEmail($(this).parents("div.email"),"email",parseInt(this.rel),altClass);
		return false;
	});
	
	$(".send-email .cancel").click(function(){
		eC = $(this).parents("div.email");
		return cancelSend(eC);
	});
	
	$("label input, label textarea").blur(function(){
		if($(this).hasClass("validate-error")){
			validate();
		}
	});
	
	// $("#send-now").click(function(){
	// 	var validation = validate();
	// 	if(validation){
	// 		sendActualEmails();
	// 		return false;
	// 	} else {
	// 		return false;
	// 	}
	// });
	
	$("#send-now").click(function(){
		var validation = validate();
		if(validation){
			showRequirements();
			return false;
		} else {
			return false;
		}
	});
	
	$(".error, #validation-summary").hide();
});

function insertVideo(videoName){
	var flashvars = {
		'skinName':'http://emailcenter.berkshirelifetools.com/media/Clear_Skin_2',
		'streamName':'../videos/' + videoName,
		'autoPlay':'true',
		'autoRewind':'true'
		}
	
	swfobject.embedSWF("http://emailcenter.berkshirelifetools.com/media/FLVPlayer_Progressive.swf", "video-replace", "360", "276", "8.0.0", "",flashvars, {'wmode':'transparent'});
}

function resetMedia(){
	$(".thumbnail img").show();
	$(".thumbnail #video-replace").remove();
}

function cancelSend(eC){
	if(eC == null || eC == undefined) eC = $("#email-" + currentEmailSending.emailNumber + "-section");
	currentEmailSending.emailNumber = 0;
	currentEmailSending.emailType = "";
	currentEmailSending.emailTitle = "";
	
	eC.find(".send-email").hide();
	eC.removeClass("sending");
	$(".content-dim").fadeOut();
	return false;
}

function sendEmail(emailContainer,type,number,altReq) {
	if(type==undefined) type = "email";
	if(typeof(altReq) == "undefined") altReq = "";
	$("#send-mail-form h3").html(emailContainer.find((type=="email" ? ".html-email h3": ".video-email h3")).html());

	if(emailContainer.find((type=="email" ? ".html-email .ca-disclaimer": ".video-email .ca-disclaimer")).length != 0){
		$("#send-mail-form .ca-disclaimer").show();
	} else {
		$("#send-mail-form .ca-disclaimer").hide();
	}
	currentEmailSending.emailTitle = emailContainer.find((type=="email" ? ".html-email h3": ".video-email h3")).text();
	currentEmailSending.emailNumber = number;
	currentEmailSending.emailType = type;
	currentEmailSending.altReq = altReq;

	emailContainer.addClass("sending");
	$("#validation-summary, .error").hide();
	$(".validate-error").removeClass("validate-error");
	$(".content-dim").fadeIn();
	$("#send-mail-form").appendTo(emailContainer).show();
}

function sendActualEmails(){
	$("#email-" + currentEmailSending.emailNumber + "-section").addClass("sendingReal");
	var yourName = $("#your_name").get(0).value;
	var yourEmail = $("#your_email").get(0).value;
	var recipients = $("#recipient").get(0).value;
	var message = $("#message").get(0).value;
	$.post('sendmail.php',{
		'email_id':currentEmailSending.emailNumber,
		'email_type':currentEmailSending.emailType,
		'from_name': yourName, 
		'from_email': yourEmail,
		'recipients': recipients,
		'message': message},
		parseResponse,
		"json")
}

function parseResponse(data, textStatus){
	$("#email-" + currentEmailSending.emailNumber + "-section").removeClass("sendingReal");
	if(textStatus == "success"){
		if(data.type == "success"){
			cancelSend();
			showEmailSuccess(data);
		} else {
			showEmailError();
		}
	} else {
		showEmailError();
	}

}

function showEmailError(){
	$("#send-error").dialog("open")
}

function showEmailSuccess(data){
	$("#send-success").dialog("open")
}

function showRequirements(email){
	var id = "#requirements";
	if(currentEmailSending.altReq != "") id = "#" + currentEmailSending.altReq + "-requirements";
	var $id = $(id);
	$(".req_email_title", $id).text(currentEmailSending.emailTitle);
	var ct = $('#recipient').val().split(',').length;
	$(".req_email_count", $id).text( ct == 1 ? "1 recipient" : ct + " recipients");
	$id.dialog("open");
}

function reshowButtons(){
	
}

function addTab(tabName){
	$("#" + tabName + " h2").clone().append("<em>&nbsp;</em>").click(function(){
		togglePanel("#" + tabName,this);
	}).appendTo("#tabs .content");
}

function validate(){
	var yourName = $("#your_name_label");
	var yourEmail = $("#your_email_label");
	var recipients = $("#recipient_label");
	var iErrorCount = 0;
	
	
	iErrorCount += validateField(yourName,"name",iErrorCount,"required");
	iErrorCount += validateField(yourEmail,"email",iErrorCount,"email");
	iErrorCount += validateField(recipients,"recipient",iErrorCount,"array_email");
	
	
	if (iErrorCount > 0){
		$("#validation-summary").slideDown();
		return false;
	} else {
		$("#validation-summary").slideUp();
		return true;
	}

}

function validateField(label,labelText,errCount,type){
	var validEmail = /^(.+)@(.+)\.(.+)$/;
	var answer = false;
	var value = label.find("input, textarea").get(0).value;
	if(type=="required"){
		answer = value != "";
	} else if (type=="email") {
		answer = validEmail.test(value);
	} else if (type=="array_email") {
		answers = value.split(",");
		if(answers.length == 0){
			answer = false
		} else {
			answer = validEmail.test(answers[0]);
		}
	}
	
	if(answer) {
		label.find(".error").hide();
		$("#" + labelText + "_validation").hide();
		label.find("input, textarea").removeClass("validate-error");
		return 0;
	} else {
		label.find(".error").text(errCount + 1).show();
		$("#" + labelText + "_validation").show().find(".number").text(errCount + 1);
		label.find("input, textarea").addClass("validate-error");
		return 1;
	}
}

function togglePanel(panel,handle){
	
	if(instructionChannel.is(':visible') && !$(panel).is(':visible')){
		$("#tabs h2").removeClass("selected");
		$(handle).addClass("selected");
		$("#instruction-channel .content").hide().filter(panel).show();
		return;
		
	} else if (instructionChannel.is(':visible') && $(panel).is(':visible')) { 
		instructionChannel.slideUp(function(){
			$("#tabs h2").removeClass("selected");
		});
		return;
	}
	$("#tabs h2").removeClass("selected");
	$("#instruction-channel .content").hide().filter(panel).show();
	$(handle).addClass("selected");
	instructionChannel.slideDown();	
}