var request = null;
var timeout = null;

$(document).ready(function() {
    // clear any checked radio buttons
    $("input[name='template']:checked").attr("checked","");
    
    jQuery.validator.addMethod("domain2", function(value, element, param) {
		var check = value.match(/^[a-zA-Z0-9\-]+$/);
		if (check==null) {
			return false;
		} else {
			return true;
		};
	});
	$('#form1').validate({
		rules : {
			domain: {
				required: true,
				domain2: true
			},
			current_email: {
				required: true,
				email: true
			},
			template: {
				required: true
			}
		},
		messages: {
			domain: {
				required: "Please enter a website address",
				domain2: "Website addresses can only contain letters, numbers and hyphens (-)"
			},
			current_email: {
				required: "Please enter an email address so that we can contact you",
				email: "This email address is invalid. Please check and try again."
			},
			template: {
				required: "Please choose one of the templates. It will change colour once selected."
			}
		},
		success: function(label) {
			label.removeClass('error');
		}
	});
    
    $("#domain").keyup(function(){
        if (timeout) {
            clearTimeout(timeout);
        };
        timeout = setTimeout(function() {
			checkDomain();
		},800); 
    }).focus(function() {
        if ($(this).val()=="YourName") {
            $(this).val("");
        };
    });
    
    $("#extension").change(function() {
		checkDomain();
    });
    
    $('ul#templates li').hover(function() {
        $(this).addClass("hover");
    }, function() {
        $(this).removeClass("hover");
    });
    
    $('#btn_buynow').click(function() {
        $(this).hide();
        
        var error = false;
        if (!$("#domain_response").hasClass("available")) {
            error = true;
            alert("Please first make sure you've selected a website address that is available.");
        };
        
        if ($("input[name='template']:checked").length==0) {
            error = true;
            alert("Please choose a template first.");
        };
        
        if ($("#current_email").val()=="") {
            error = true;
            alert("Please enter your current email address");
        };
        
        if (error) {
            $(this).show();
            return false;
        } else {
            $("#popup_container").show();
            $.ajax({
                type: "POST",
                url: "domains/process",
                data: ({"domain":$("#domain").val()+$("#extension").val(),"template":$("input[name='template']:checked").val(),"email":$("#current_email").val(),"order_id":$("#order_id").val()}),
                success: function(data) {
                    if (data=="success") {
                        $("#btn_submit").trigger("click");
                        return true;
                    } else {
                        alert("There was a problem processing your order. Please email customer support at hello@bridgeinternet.co.uk. We're sorry for any inconvenience caused by this fault.");
                        return false;
                    };
                }
            })
        };
    });
    
    $('ul#templates li input').click(function() {
        $('ul#templates li.selected').removeClass("selected");
        $(this).parent().addClass("selected");
    });
});

function checkDomain() {
    if ($("#form1").validate().element('#domain')) {
        if (request) {
            request.abort();
        };
        $('#domain_spinner').show();
        $("#domain_response").attr("class","").html("checking . . . please wait");
        var domain_name = $("#domain").val()+$("#extension").val();
        //alert(domain_name);
        request = $.ajax({
           type:"GET",
           url:$("#domain_url").attr("href"),
           data:"domain_name="+domain_name,
           success: function(response) {
               $('#domain_spinner').hide();
               if (response=="available") {
                   $("#domain_response").html("Your chosen address is available").addClass("available");
               } else if(response=="registered") {
                   $("#domain_response").html("Sorry, your chosen address is unavailable. Please try another one.").addClass("unavailable");
               } else {
                   $("#domain_response").html("There has been an error: please contact customer support quoting the following: "+response).addClass("error");
               };
           } 
        });
    };
}

function fnGetDomain(url) {
   return url.match(/:\/\/(.[^/]+)/)[1];
};

// stores base url
var baseUrl = "http://"+fnGetDomain(window.location.href);
