//Grab a handle to the form
var the_form = new Object();

	
//Set up a flds array
var flds = new Array();

//Setup cookies array
var cookies = new Array();
	
	
$(document).ready(function() {
	the_form = $("#beta_signup_form");
	
	//style the inputs
	var inputs = the_form.find("input[type='text']");
	inputs.css({
		"background-color":"#CCCCCC",
		"border":"1px solid #CCCCCC",
		"width":"450px",
		"height":"16px"
    });
	
	//style the labels
	the_form.find("label").css("margin-top","2px");
	
	//Populate fields array
	//flds["name"] = $("input[name='cm-name']");
	flds["firstname"] = $("#FirstName");
	flds["lastname"] = $("#LastName");
	flds["email"] = $("#idirdt-idirdt");
	flds["company"] = $("#Company");
	flds["country"] = $("#Country");
	flds["size"] = $("*[name='cm-fo-yuljjh']");
	flds["industry"] = $("#Industry_");
	//flds["terms"] = $("#TermsandConditions");
	
	//Set up the industries array 
	var industries = new Array();
	industries["Animation"] = "Animation";
	industries["FX"] = "FX";
	industries["Video Games"] = "Video Games";
	industries["Other"] = "other";
	
	//Redo all 2-letter country codes
	var countries = flds["country"].find("option");
	countries.each(function() {
		var ths = $(this);
		var val = ths.attr("value");
		var txt = $.trim(ths.text());
		if (val.length == 2) {
			//replace with text
			ths.val(txt);
		}
	});
	
	//Populate the Industry dropdown
	populate_industry_dropdown(industries);
	
	//Activate the submit button
	var submit_btn = the_form.find("input[type='button']");
	submit_btn.click(function() {
		//Do stuff here	
		validate_signup_form();
	});
	
	//Prep the form labels
	prepare_form_labels();
	
	//Populate broser info
	var browser_info = $.browser.name + "::" + $.browser.version + "::" + $.os.name;
	$("#BrowserName").val (browser_info);
	//$("#BrowserVersion").val($.browser.version);
	//$("#OS").val($.os.name);
});

function populate_industry_dropdown(arr) {
	//Get jquery handle for dropdown
	var sel = flds["industry"];
	for (i in arr) {
		addOption(i,arr[i],sel);
	}	
	
	//Now allow the user to specify "other"
	var other_dropdown_html = "" +
		"<div style='display:none;padding-top:5px;' id='industry_other'>" +
		"<span style='line-height:150%;color:#666666;font-size:11px;-top:5px;'>Please type in your industry:" +
		"<span/><br/><input type='text' id='industry_other_input'><" + "/div>";
		

	//Insert the other input after the industry dropdown
	sel.after(other_dropdown_html);
	
	//Grab a handle
	var industry_other = $("#industry_other");
	
	
	//Now bind the Industry dropdown to the "other"

	sel.bind("change",function() {
		var ths = $(this);
		var v = jQuery.trim(ths.val());
		
		
		if (v == "other" || v == "Other") {
			industry_other.show();
		}
		else {
			industry_other.find("input").val("");
			industry_other.hide();
		}
		
		//Set the value of the real industry
		$("#Industry").val(v);
	});
}

function validate_signup_form() {
	var errors = new Array();
	
	for (i in flds) {
		var proceed = true;
		fld = flds[i];
		if (!fld.attr("id")) {
			field_id = "";
		}
		else {
			field_id = fld.attr("id").toLowerCase();
		}
		
		//get the error
		error_msg = "- " + getLabel(fld);
		
		switch (field_id) {
			case "idirdt-idirdt":
				v = jQuery.trim(fld.val());
				if (! isValidEmail(v)) {
					proceed = false;
				}
				else {
					cookies["email"] = v;
				}
				break;
			
			case "country":
				
				v = jQuery.trim(fld.val());
				if (v.length < 1) {
					proceed = false;
				}
				else {
					cookies["country"] = v;
				}
				break;
			
			case "termsandconditions":
				if (!fld.attr("checked") == true) {
					proceed = false;
				}
				break;
			case "industry_":
				v = jQuery.trim(fld.val());
				if (v == "other") {
					//Make sure other is filled out
					var other_industry = jQuery.trim($("#industry_other_input").val());
					if (other_industry == "") {
						alert("you must fill out other industry");
						proceed = false;
					}
					else {
						new_value = v + " - " + other_industry;
						$("#Industry").val(new_value);
						cookies["industry"] = new_value;
					}
					
				}
				else if (v=="") {
					proceed = false;
				}
				else {
					//user selected a dropdown menu	
					cookies["industry"] = v;
				}
				break;
			
			default:
				//In the case of an unknown field id such as: studio size
				v = jQuery.trim(fld.val());
				if (i != "size") {
					cookies[i] = v;
				}
				else {
					var s = fld.get(0);
					cookies[i] = s.options[s.selectedIndex].text;
				}
				if (v == "") {
					proceed = false;	
				}
				break;
		}//end switch
		
		//now highlight the warning msg (if any)
		highlight(fld,proceed);
		
		if (proceed == false) {
			//add the error
			errors.push(error_msg);
		}
		
	}//end for fld in flds
	
	//if (proceed == true) {
	if (errors.length == 0) {
		//Set some cookies
		setCookies();
		
		//First disable the button
		var btn = the_form.find("input[type='button']");
		btn.attr("disabled","disabled");
		
		//Before submitting the form, call ajax
		var params = $("#beta_signup_form").serialize();
		
		//Change the url of this script in production
		$.ajax({
			type: "POST",
			url: "includes/store_eval_data.php",
			data: params,
			dataType: "json",
			success: function(data){
				//DO NOT SUBMIT THE FORM
				if (data.success !== true) {
				 alert("Oops, there was a problem\n" + data.reason.join("\n"));
				 //re-enable the submit button
				 btn.removeAttr("disabled");
				 //top.location = "thanks";
				}
				else {
					//everything was good - user was created, and 
					top.location = "thanks";
					//alert("Everything ok\n" + data.reason.join("\n"));
					//btn.removeAttr("disabled");
				}
				
			}//end success func
		});//end ajax call
	}
	
	else {
		//display all errors
		msg = "Oops! We need a little bit more information from you to get started on your eval server:\n" + errors.join("\n");
		
		alert(msg);
	
	}
}

function isValidEmail(email) {
if (email == "") {
	return false;
}
else if (email.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) {
	return true;
}
else {
	return false;
}
}


function getLabel(obj) {
	var label = obj;
	if (label.attr("error")) {
		return label.attr("error");
	}
	else {
		return "label not found";
	}
}

function highlight(fld,status) {
	if (fld.attr("error") == "Country") {
		//alert("highlighting country now");
	}
	
	var msg_style = "warning";
	var other_style = "muted";
	if (status == true) {
		msg_style = "muted";
		other_style = "warning";
	}
	
	//apply the msg
	var msg = fld.parent().find("span");
	msg.removeClass(other_style);
	if (! msg.hasClass(msg_style)) {
		msg.addClass(msg_style);	
	}
}
function prepare_form_labels() {
	for (i in flds) {
		fld = flds[i];
		if (fld.attr("id") == "name") {
			fld.after("<span class='muted'>* Mandatory</span>");
		}
		else {
			fld.after("<span class='muted'>*</span>");
		}
	}
	
	/*
	
	terms = flds["terms"].parent().find("span");
	//terms.wrap("<div style='position:relative;'></div>");
	terms.css({
		"position":"absolute",
		"top":"7px",
		"left":"245px",
		"width":"220px"
   });
   */
}

//other functions
function addOption(text,val,obj) {
	if (typeof(obj) == "object" && obj.length > 0) {
		var html = obj.html();
		new_option = "<option value=\"" + val + "\">" + text + "<" + "/option>";
		html += new_option;
		obj.html(html);
		return obj.find("option[value='" + val + "']");	
	}
}

function selectOption(text, obj) {
	var dropdown = obj.get(0);
	var my_index = -1;
	
	for (var i=0; i<dropdown.options.length;i++) {
		j = dropdown.options[i].value;
		if (j == text) {
			my_index = i;
			found_value = j;
		}
	}
	
	if (my_index > -1) {
		dropdown.options.selectedIndex = my_index;
	}
}

function setCookies() {
	var today = new Date();
	var expire = new Date();
	var nDays = 1;
	expire.setTime(today.getTime() + 3600000*24*nDays);
	
	for (cookie in cookies) {
		var cookieName = cookie;
		cookieValue = cookies[cookie];
		document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
	}
	
	/* Now tack on for the nonrequired fields:
		referral: ReferralSource
	  comments: Comments
	  browser_info: browser_info */
	  
	var referral = $("#ReferralSource").val();
	document.cookie = "referral"+"="+escape(referral) + ";expires="+expire.toGMTString();
	
	var comments = $("#Comments").val();
	document.cookie = "comments"+"="+escape(comments) + ";expires="+expire.toGMTString();
	
	//Now tack on the browser info
	var browser_info = $.browser.name + " " + $.browser.version + " " + $.os.name;
	//Set the browser_info cookie
	document.cookie = "browser_info"+"="+escape(cookieValue) + ";expires="+expire.toGMTString();

}