﻿var popupTipAFriendStatus = 0;

function loadTipAFriendPopup() {
	if (popupStatus == 0) {
		$("#tipAFriendBackground").css({
			"opacity": "0.7"
		});
		$("#tipAFriendBackground").fadeIn("fast");
		$("#tipAFriendContainer").fadeIn("normal");
		popupTipAFriendStatus = 1;
	}
}

function disableTipAFriendPopup() {
	if (popupTipAFriendStatus == 1) {
		$("#tipAFriendContainer").fadeOut("fast");
		$("#tipAFriendBackground").fadeOut("normal");
		popupTipAFriendStatus = 0;
	}
}

function centerTipAFriendPopup() {
	var windowHeight = document.documentElement.clientHeight;
	var windowWidth = document.documentElement.clientWidth;
	var popupHeight = $("#tipAFriendContainer").height();
	var popupWidth = $("#tipAFriendContainer").width();
	$("#tipAFriendContainer").css({
		"position": "absolute",
		"top": ($(document).scrollTop() + ((windowHeight / 2) - (popupHeight / 2) - 50)),
		"left": ((windowWidth / 2) - (popupWidth / 2))
	});
	$("#tipAFriendBackground").css({
		"height": $(document).height()
	});
}

function openTipAFriend() {
	$("#tipAFriendToEmail").val("");
	$("#tipAFriendToName").val("");
	$("#tipAFriendOutput").html("");
	$("#tipAFriendContent").show();
	centerTipAFriendPopup();
	loadTipAFriendPopup();
}

$(document).ready(function() {
	$("#tipAFriendBackground").click(function() { disableTipAFriendPopup(); });
	$(document).keypress(function(e) {
		if (e.keyCode == 27 && popupStatus == 1)
			disableTipAFriendPopup();
	});
});

function tipAFriend() {
	var from_email = $("#tipAFriendFromEmail").val();
	var from_name = $("#tipAFriendFromName").val();
	var to_email = $("#tipAFriendToEmail").val();
	var to_message = $("#tipAFriendToMessage").val();
	var art_id = $("#tipAFriendArticleId").val();
	var msg = '';
	var page_url = location.href;

	if (!validateEmail(from_email)) { msg += 'Din e-postadress är inte giltig.'; }
	if (from_name === '') { msg += 'Du har inte skrivit in ditt namn.'; }
	if (!validateEmail(to_email)) { msg += 'Mottagarens e-postadress är inte giltig.'; }
	if (to_email === '') { msg += 'Du har inte skrivit in mottagares namn.'; }

	if (msg != '') {
		alert(msg);
	} else {
		$("#tipAFriendToEmail").val("");
		$("#tipAFriendToMessage").val("");

		$("#tipAFriendContent").hide();
		$("#tipAFriendOutput").show();
		$("#tipAFriendOutput").html("Skickar...");

		$.ajax({
			url: "/Site/Services/Article.asmx/TipAFriend",
			type: "post",
			contentType: "application/json",
			data: $.toJSON({ fromEmail: from_email, fromName: from_name, toEmail: to_email, toMessage: to_message, articleId: art_id }),
			dataType: "json",
			processData: false,
			success: function(data, textStatus) { $("#tipAFriendOutput").html(data.d); },
			error: function(XMLHttpRequest, textStatus, errorThrown) { var jsonError = $("#tipAFriendOutput").html(XMLHttpRequest.responseText); }
		});
	}
}
