////////////////////////////////////////////////////////////////////////////////
//-- MISC NATIVE JS --//////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//deal with a missing console
if (!window.console) {
	var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

	window.console = {};
	for (var i = 0; i < names.length; ++i)
		window.console[names[i]] = function () { }
}

// clear form values
function clearDefault(el) {
	if (el.defaultValue == el.value) el.value = ""
}
////////////////////////////////////////////////////////////////////////////////
//-- JQUERY PLUGINS --//////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//Extend jQuery w/ GA Page & Event Tracker methods
(function ($) {
	var methods = {
		page: function (pg) {
			//default page - set it or use what's in the browser's address bar
			pg = pg || document.location.pathname;

			//add GET string (so we capture AdWords redirects)
			pg = pg + document.location.search;

			//send in page to GA
			_gaq.push(
                    ["_setAccount", "UA-2202549-4"],
                    ["_setDomainName", ".screamingcircuits.com"],
                    ["_trackPageview", pg],
                    ["_trackPageLoadTime"]
		        );

			//log it for testing
			console.log("The GA Page = " + pg);
			console.log(_gaq);
			(function gaIsLoaded() {
				if (typeof _gaq._getAsyncTracker == "function") {
					var timestamp = new Date();
					console.log("ga.js is active @ " + timestamp.getTime());
					console.log(_gaq);
					return;
				}
				var timestamp = new Date();
				console.log("not yet! @ " + timestamp.getTime());
				setTimeout(gaIsLoaded, 1);
			})();

			//maintain jQuery chainability
			return this;
		},
		event: function (ev) {
			//set default event data
			var event = {
				category: "Script Error",
				action: "Error",
				label: "Event Data Object Required"
			};

			//merge in new event data if available
			if (ev) {
				$.extend(event, ev);
			}

			//send GA Event
			//format: category, action, opt_label, opt_value
			//    ex: home, click, headerLogo
			_gaq.push(
                    ["_trackEvent", event.category, event.action, event.label]
                );

			//log it
			console.log(event.category + ", " + event.action + ", " + event.label);

			//maintain jQuery chainability
			return this;
		}
	};
	//plugin reference definition and method calling logic
	$.fn.screamingGA = function (method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else {
			$.error("Method " + method + " does not exist on screamingGA");
		}
	};
})(jQuery);
////////////////////////////////////////////////////////////////////////////////
//-- LEGACY STUFF --////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
function ConfigDialogs() {
	$(".thickbox").click(function () {
		var dialogId = $(this).attr("showid");
		$("#" + dialogId).dialog({
			autoOpen: false,
			draggable: false,
			modal: true,
			position: "center",
			resizable: false,
			title: "Glossary",
			width: 455
		});
		$("#" + dialogId).dialog("open");

		//send event data to GA
		$.fn.screamingGA("event", {
			category: "Help",
			action: "Click",
			label: dialogId
		});
	});
}
//Validation Setup
function runValidation($target) {
	//Capture original email address value (for edit profile)
	$("#EditUserForm").data("OriginalEmailAddress", $("#EmailAddress").val());

	//ADD ALL RULES HERE - SET DEFAULT MESSAGES APPROPRIATELY
	//
	//no spaces validation rule
	$.validator.addMethod("noSpaces", function (value, element) {
		var pattern = /\s/i;
		var test = pattern.test(value);
		return this.optional(element) || !test;
	}, "Spaces are not allowed");
	//alphanumberic only validation rule
	$.validator.addMethod("alphanumericwithbasicpunc", function (value, element) {
		var pattern = /[\=\[\]{}<>|\\^~`&*]/i;
		var test = pattern.test(value);
		return this.optional(element) || !test;
	}, "Basic punctuation only - = * ~ & < > { } [ ] | ` \ not allowed");

	//phone number validation rule
	$.validator.addMethod('phone', function (value, element) {
	    return this.optional(element) || (value.match(/^.{10,64}$/)); //Testing that there are at least 10 characters, less than 64
	}, "Please enter a valid Phone Number");

    //Note, previous value match was too restrictive: ^((\+){0,1}\d\s*)?\(?([0-9]{3})\)?\s*[\. -]?\s*([0-9]{3})\s*[\. -]?\s*([0-9]{4})\s?((ext|x)\s*\.?:?\s*([0-9]+))?$

	//email changed and unique validation rule (for edit profile)
	$.validator.addMethod("emailNewAvail", function (value, element) {
		var response = true;
		if ($("#EditUserForm").data("OriginalEmailAddress") === value) {
			return true;
		}
		else {
			$.ajax({
				async: false,
				url: "/User/EmailIsAvailable",
				type: "POST",
				dataType: "json",
				data: { "email": value },
				success: function (data) {
					response = data;
				}
			});
		}
		return response;
	}, 'This email address is already in use');

	//Is login available validation rule
	$.validator.addMethod("loginAvail", function (value, element) {

		var response = true;
		$.ajax({
			async: false,
			url: "/User/LoginNameIsAvailable",
			type: "POST",
			dataType: "json",
			data: { "loginName": value },
			success: function (data) {
				response = data;
			}
		});
		return response;
	}, "This username has been taken");

	//Is email available validation rule
	$.validator.addMethod("emailAvail", function (value, element) {
		var response = true;
		$.ajax({
			async: false,
			url: "/User/EmailIsAvailable",
			type: "POST",
			dataType: "json",
			data: { "email": value },
			success: function (data) {
				response = data;
			}
		});
		return response;
	}, "This username has been taken");

	//Item already in list validation rule (for Email Addresses) 
	$.validator.addMethod("itemInUse", function (value, element) {
		var currentEmails = $("#currentEmailsForm").serializeArray();
		var testArray = [];
		$.each(currentEmails, function (index) {
			testArray.push(currentEmails[index].value);
		});

		return ($.inArray($("#EmailAddress").val(), testArray) == -1);
	}, "This is already in use");

	//start validation and set error messages
	$($target).validate({
		messages: {
			FirstName: {
				required: "Required"
			},
			LastName: {
				required: "Required"
			},
			LoginName: {
				required: "Required",
				noSpaces: "Spaces are not allowed",
				minlength: "Must be at least 6 characters long",
				loginAvail: "This Username has already been used"
			},
			EmailAddress: {
				required: "A valid email address is required",
				noSpaces: "Spaces are not allowed",
				email: "A valid email address is required",
				emailAvail: "This email address has already been used",
				emailNewAvail: "This email address has already been used",
				itemInUse: "This email has already been added"
			},
			StreetAddress1: {
				required: "Please provide your shipping address"
			},
			City: {
				required: "Please provide your shipping city"
			},
			State: {
				required: "Please provide your shipping state"
			},
			PostalCode: {
				required: "Please provide your shipping postal code"
			},
			Country: {
				required: "Please provide your shipping country"
			},
			ContactPhone: {
				required: "Phone Number is required",
				phone: "Please enter a valid Phone Number"
			},
			HearAbout: {
				required: "Required"
			},
			//"PhoneNumber" is used on Contact Us page, "ContactPhone" on Registration & User Profile pages (let's unify!)
			PhoneNumber: {
				required: "Phone Number is required",
				phone: "Please enter a valid Phone Number"
			},
			PasswordUnencrypted: {
				required: "Password is required",
				noSpaces: "Spaces are not allowed",
				minlength: "Must be 6 characters or more"
			},
			PasswordUnencryptedConfirm: {
				required: "Password is required",
				noSpaces: "Spaces are not allowed",
				minlength: "Must be 6 characters or more",
				equalTo: "Passwords must match"
			},
			//Login page
			Password: {
				required: "Password is required",
				noSpaces: "Spaces are not allowed"
			},
			//Change Password page
			PasswordOld: {
				required: "Password is required",
				noSpaces: "Spaces are not allowed"
			},
			PasswordNew: {
				required: "Password is required",
				noSpaces: "Spaces are not allowed",
				minlength: "Must be 6 characters or more"
			},
			PasswordConf: {
				required: "Password is required",
				noSpaces: "Spaces are not allowed",
				minlength: "Must be 6 characters or more",
				equalTo: "Passwords must match"
			},
			//Contact Us page
			Name: {
				required: "Name is required",
				minlength: "Name must be 2 characters or more"
			},
			Message: {
				required: "A message is required",
				alphanumericwithbasicpunc: "= * ~ & < > { } [ ] | ` \ not allowed"
			}
		},
		onkeyup: false,
		errorClass: "Invalid",
		success: "Valid",
		//debug:true,
		errorElement: "span",
		errorPlacement: function (error, element) {
			element.parent("td").next("td").html(error);
		},
		//using this to track validation errors in GA
		showErrors: function (errorMap, errorList) {
			if (errorList[0]) {
				var formId = this.currentForm.id;
				$.each(errorMap, function (key, value) {

					//send event data to GA
					$.fn.screamingGA("event", {
						category: "Validation",
						action: formId,
						label: key + ":" + value
					});
				});
			}

			//resume default behavior
			this.defaultShowErrors();
		},
		//using this to track validation successes in GA
		submitHandler: function (form) {
			//send event data to GA
			$.fn.screamingGA("event", {
				category: "Validation",
				action: form.id,
				label: "Success"
			});

			//submit form (default behavior)
			form.submit();
		}
	});
}
////////////////////////////////////////////////////////////////////////////////
//-- DOM READY! --//////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
$(document).ready(function () {
	//check if we are on staging, if so show "staging" indicator in GUI
	var isStaging = (location.host === "staging.screamingcircuits.com" || location.host === "alpha.screamingcircuits.com") ? true : false;
	if (isStaging) {
		$("body").addClass("staging");
	}

	//Header Login Reset
	if ($("#GoBackToForm").length == 1) {
		$("#GoBackToForm").click(function () {
			$("#LoginError").fadeOut("normal", function () {
				$("#LoginForm").fadeIn("normal");
			});
			return false;
		});
	}

	//Setup Glossary dialogs (and any other modal dialog element)
	ConfigDialogs();

	//Fix to enable AJAX relative path
	var arr = location.href.split("/");
	if ($("#AuthForm").length == 1 || arr[0] == "https:") {
		if (arr[2].indexOf(".") > -1)
			$("#AuthForm").attr("action", "https://" + arr[2] + $("#AuthForm").attr("action"));
	}

	//hide / show "Hear About Us Detail"
	$(".HearAboutDescriptionContainer").hide();
	$("#HearAboutUs").change(function () {
		var test = $(this).val();
		if (test == "Email Send-Out" || test === "") {
			$(".HearAboutDescriptionContainer").hide();
		}
		else {
			$(".HearAboutDescriptionContainer").show();
		}
	});

    //Run validation if a qualifying form is on the page
    var $form = $("#main form").filter("[class!=noValidation]");
    if ($form.length) {
        runValidation($form);
        // If this is the registration form we want to force validation on any EmailAddress automatically filled by referral parameters as soon as the page is loaded...
        if ($form.context.location.pathname.toLowerCase() == "/user/register") {
            $("#EmailAddress").focusout();
            $("#FirstName").focus();
        }
    }
});
