var the_form = new Object();
var easy_options = new Object();

$(document).ready(function() {
	the_form = $("#beta_signup_form");
	
	/* Set your options*/
	easy_options = {
		debug:false,
		onkeyup: false,
		showErrors: function(errorMap, errorList) {
			var clicked = the_form.find("#signup").attr("clicked");
			this.defaultShowErrors();
			
			if (clicked == "true" || clicked == true) {
				var msg = "<h1>Oops!</h1><p>There were a few (" + this.numberOfInvalids() + ") problems with your form submission (highlighted in red). Just close out this dialog, make your changes, and re-submit.</p>";

				//The timeout is for Chrome
				window.setTimeout(show_dialog, 50, msg);
				toggle_submit(false);
			}
		},
		submitHandler: function() {
			//Submit form
			//Get industry, and stick it in the hidden input
			$("#Industry").val(get_industry());
			
			//Let user know something is going on
			msg = get_spinner() + "<h1>You're almost done!</h1><p>" +
				"Your information is now being submitted to our signup server. Once that's complete, you'll be redirected to a confirmation page.</p><p>Please don't hit the back button, or refresh this page.</p>";
				
			//Show user message
			window.setTimeout(show_dialog, 50, msg, "valid");
			window.setTimeout(post, 75);
		},
		success: function(label) {
		  l = label.attr("for");
		  t = "*";
		  if (l == "url_ok") t = "* This URL is available";
		  label.addClass("valid").text(t);
		},
		rules: {
			"industry_other_input": {
				required: {
					depends: function(element) {
						return $("#Industry_").val() == "other";
					}
				}
			}
		}//end rules
	};//end options
	
	
	/* -----------------------------------------------
	Style the error handler
	----------------------------------------------- */
	var err = $("#error_handler");
	var closebox = $("#error_closebox");
	var err_msg = $("#error_message");
	closebox.find("a").bind("click", function() {
		$("#error_handler").dialog("close");
		return false;
	});
	
	/* -----------------------------------------------
	Get all required inputs
	----------------------------------------------- */
	var inputs = the_form.find("input.required:not(.checkbox), select.required");
	
	//Attach default required behavior to all required inputs
	var t = 0;
	inputs.each(function() {
		var ths = $(this);
		var v = ths.val();
		//ths.css("background-color","yellow");
		ths.attr("title", "* Required");

		var n = ths.attr("name");
		if (ths.attr("id")) {
			n = ths.attr("id");
		}
		var s = "<label class='error valid' for='" + n +  "' generated='true'>*</label>";
		ths.after(s);

		//Make the input validate on change, not just submit
		ths.bind("change blur", function() {
			b = the_form.validate().element(ths);
		});
	});
	//Trap the enter key
	trap_enter_key();
	
	//Call the function that attaches the options to the validator object
	var f = the_form.validate(easy_options);
	
});

function toggle_submit(t) {
	b = the_form.find("#signup");
	b.attr("clicked", t);
	if (t==true) {
		submit_form();
	}
	return false;
}

//Helper function that suppresses the enter key for URL
function trap_enter_key() {
	var inputs = $("input[type='text']");
	inputs.bind("keypress", function(e) {
		var code=e.charCode || e.keyCode;
  		return (code==13)?false:true;
	});
}

//Helper function for toggling the industry to 'other'
function toggle_industry(v) {
	v = $.trim(v);
	var industry = v;
	var other = the_form.find("#industry_other_input").parent().parent().parent();
	
	switch(v) {
		case "":
			other.hide();
			break;
			
		case "other":
			//unstow the other input
			other.show();
			break;
			
		default:
			//youre good
			other.hide();
			break;
	}
}

//Helper function for live-checking URL
//Calls is_url function first
function check_url_availability(u) {
	var a = is_url(u)["pass"];
	var cb_url_ok = the_form.find("#url_ok")
	if(a) {
		
		var post_url = "/accounts/validations/check_url";
		var params = {
			url: u
		};
		
		$.ajax({
			type: "POST",
			url: post_url,
			data: params,
			dataType: "text",
			timeout:5000,
			error: function(data) {
				cb_url_ok.removeAttr("checked");
				single_validate(cb_url_ok);
			},
			success: function(data) {
				switch (data) {
					case true:
					case "TRUE":
					case "true":
						cb_url_ok.attr("checked","checked");	
						single_validate(cb_url_ok);

						break;
					
					default:
						cb_url_ok.attr("title", "* Required<br/><span class='valid'>" +
						"Unavailable. Please try again and then <a href=\"#\" onclick=\"check_url_availability(document.getElementById('URL').value);return false;\">click here</a> to check availability</span>");
						cb_url_ok.removeAttr("checked");
						single_validate(cb_url_ok);
						break;
				}
			}
		});
	}//end if a
	else {
		//The URL was not well-formed
		var default_title = cb_url_ok.attr("title");
		var help_msg = "[<a href='#' onclick='show_example_urls();return false;' style='color:red;text-decoration:underline'>Disallowed URL</a>]";
		cb_url_ok.removeAttr("checked");
		cb_url_ok.attr("title", help_msg);
		single_validate(cb_url_ok);
		
		//Set the title back to default
		cb_url_ok.attr("title", default_title);
	}
	
}

//Helper function for onchange validations (when quickly tabbing thru fields)
function single_validate(obj) {
	the_form.validate().element(obj);
}

//Helper function for concatenating the 'possibly' other industry
function get_industry() {
	var a = $.trim(the_form.find("#Industry_").val());
	var b = $.trim(the_form.find("#industry_other_input").val());
	
	if (a == "other") {
		return a + " - " + b;
	}
	else {
		return a;
	}
}

//Helper function for showing allowed urls
function show_example_urls() {
	allowed_urls = new Array("URL's must follow this pattern:", "- Can only contain letters, numbers, and dashes");
	alert(allowed_urls.join("\n"));
}

//Helper function for testing
function submit_form() {		
	the_form.submit();
}

//Helper function for determining if an URL is well-formed
function is_url(url) {
	//Set up some expressions to test for
	var not_alphanumeric = /[^0-9a-zA-Z\-]/;
	var is_alpha = /(^[0-9a-zA-Z]+)(\-*)([a-zA-Z0-9]+)$/;
	var ends_with_dash = /\-$/;
	
	var msg = "";
	var pass = false;
	
	if (null == url | "" == url) {
		//It's empty
		msg = "url is empty";
	}
	else if (ends_with_dash.test(url)) {
		//It ends with a dash
		msg = "ends with a dash";
	}
	else if (not_alphanumeric.test(url)) {
		//It contains 1 or more illegal chars
		var replacement = url.replace(not_alphanumeric,"X" )
		msg = "not alphanumeric";
	}
	else if (is_alpha.test(url)) {
		//It's good!
		pass = true;
		msg = "Your URL looks good!";
	}
	else {
		//Be paranoid
		msg = "'s can only contain letters, dashes, and numbers.  They must begin with a letter, and can not end with a dash. Please fix and submti again";
	}
	
	return {
		"pass": pass,
		"msg": msg
	};
}

//Helper function for showing modal dialog messages
function show_dialog(msg, className) {
	$("#error_message").html(msg);		
    		
	//Modal dialog
	var dialogOptions = {
		title: "",
		autoOpen: false,
		position: "top",
		modal: true,
		overlay: {
		  backgroundColor: "#000000",
		  opacity: .5
		  },
		draggable: false,
		resizable: false,
		width: 750,
		height:500
	};
		
	var div = $("#error_handler");
    div.dialog(dialogOptions);
    
    //Style the handler
    var ec = $("#error_container");
    switch (className) {
    	case "valid":
    		className = "valid";
    		//Don't prepend spinner
    		break;
    	case "neutral":
    		className = "neutral";
    		break;
    	default:
    		className = "";
    		ec.removeAttr("class");
    		break;
    }
    
    if (className !== "") {
    	ec.attr("class", className);
    }
    
    //now open
    div.dialog("open");
    
    //Remove the closebar
    link = $("a.ui-dialog-titlebar-close");
	link.remove();
}

//Helper ajax loading spinner graphic
function get_spinner() {
	var spinner = "<div style='float:left;margin:10px 25px 75px 0px;display:block;'><img src='/img/forms/ajax-loader.gif'/></div>";
	return spinner;
}

//Helper function to get terms & conditions
function get_terms() {
	var options = {
		url: "terms",
		dataType: "html",
		success: function(data) {
			var print = "<p class='print'><a href='terms' target='_blank'>Print-friendly version</a></p>";
			var html = $($(data).find("div.copyBox:first").html());
			html.find(":header").css("color","#222222");
			html.find("li").css("margin-bottom","15px");
			html = "<div style='height:250px;overflow-y:scroll;'>" + html.html() + "</div><br/>" + print;
			show_dialog(html, "neutral");
			
		}
	};
	$.ajax(options);
}

function post() {
	//Submit all vars
	var params = the_form.serialize();
	$.ajax({
		type: "POST",
		url: "includes/store_eval_data.php",
		data: params,
		dataType: "json",
		contentType: "application/x-www-form-urlencoded",
		error: function(data) {
			//There was a problem, but don't show it
			show_dialog("<h1>You're all set</h1><p>You'll be momentarily redirected to the <a href='thanks'>confirmation page</a>.</p>", "neutral");
			
			//Now redirect after a 2 second delay
			window.setTimeout(redirect, 2000, "thanks");
		},
		success: function(data){
			if (data.success !== true && data.success !== "true") {
				//Something happened
				var blurb = String(data.reason);
				var m = "The URL you selected is not available";
				if (blurb.indexOf(m) > -1) {
					blurb = "<h1>The URL you chose is taken</h1><p>We're sorry about that. Just close out this dialog, choose another URL, and re-submit this form.";
				}
				else {
					blurb = "<h1>Oops!</h1><p>We're really sorry about this, but there was a small problem. Details have been logged and sent to our <a href='mailto:support@shotgunsoftware.com;'>support team</a> - who will be contacing your shortly.</p><p style='margin-left:25px;'>" + String(data.reason) + "</p>";
				}
				
				show_dialog(blurb);
			}
			else {
				show_dialog("<h1>You're all set</h1><p>You'll be momentarily redirected to the <a href='thanks'>confirmation page</a>.</p>", "neutral");
				
				//Now redirect after a 2 second delay
				window.setTimeout(redirect, 2000, "thanks");
			}
			
		}//end success func
	});//end ajax call
}

function redirect(url) {
	top.location = url;
	//adding comment
}