$(document).ready(function() {
    $(".social .mail a").click(function(evt) {
        evt.preventDefault();
        $("#subscribe-form").fadeIn();
    });

    $("#subscribe-form img").click(function() {
        $("#subscribe-form").fadeOut();
    });

    $("#subscribe-form").submit(function(evt) {
        evt.preventDefault();
        var email = $.trim($("#subscribe-email").val());
        var name = $.trim($("#subscribe-name").val());
        if (email.match(/\S+@\S+\.[a-zA-Z]+/) && name != "") {
            var url = $(this).attr("action") + "?name=" + encodeURIComponent(name) + "&email=" + encodeURIComponent(email);
            getJson(url, function(data) {
                if (data.result == "OK") {
                    $("#subscribe-form").addClass("done");
                    window.setTimeout(function() {
                        $("#subscribe-form").fadeOut();
                        window.setTimeout(function() {
                            $("#subscribe-form input").val("");
                            $("#subscribe-form").removeClass("done");
                        }, 1000);
                    }, 1000);
                } else {
                    alert("Error: " + data.result);
                }
            })
        } else {
            alert("Please fill in all fields correctly");
        }
    });

    placeHolderFallback();
});


function getJson(url, callback) {
    $.ajax({
      url: url,
      dataType: "json",
        success: function(data) {
            // log(data);
            if (callback != null) callback(data);
        },
        error: function(data) {
          log("Error: ");
          log(data);
            alert("Error: " + data);
        }
    });

}

function log(str) {
    try {
        if (window.console != null && window.console.log != null) {
            console.log(str);
            return true;
        }
    } catch (e) {
        // Ignore
    }
    return false;
}


function placeHolderFallback() {
		if(!('placeholder' in document.createElement("input"))) { //don't do any work if we don't have to!
			var inputs = $("input[type='text']"),
				origColour = inputs.eq(0).css("color");

			inputs
				.each(function(i) {
					var $t = $(this);
					$t.val($t.attr("placeholder")).addClass("placeholder");
				})
				.focus(function() {
					var $t = $(this);
					if($t.val() === $t.attr("placeholder")) $t.val('').removeClass("placeholder");
				})
				.blur(function() {
					var $t = $(this);
					if($t.val() === '') {
						$t.val($t.attr("placeholder")).addClass("placeholder");
					}
				})
		}

}
