/*
	Check validity of email string
	@param	aString	email string
*/
function isValidEmail(aString) {
	return /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(aString);
}

/*
	Check to see if user has chosen a contact type
	@return 	Boolean
*/
function checkContactTypeForContactForm() {
	return ($("#teambuilding").attr("checked") || $("#kursuspakker").attr("checked") || $("#dagmoder").attr("checked") || $("#temafester").attr("checked"));
}

/*
	Check validity of email string
	@param	formID	ID of form
	@param	condition	an array of object that has following format
					{
						name: "", // name of control in form
						valid:	"", // accept "number", "email", "required" and function
						alert: "", // text will be showed when this control is not valid
						minLength: "", // option - min length of content, not used with valid = "email"
						maxLength: "", // option - max length of content, not used with valid = "email"
					}
*/
function initAlertForm(formID, arrCondition) {
	// if alert box does not exist, do nothing
	if (!$("#alertBox")) {
		return;
	}
	
	var form = $("#" + formID);
	
	// cache the condition
	if (!initAlertForm.conditionCache) {
		initAlertForm.conditionCache = new Object();
	}
	initAlertForm.conditionCache[form] = arrCondition;
	
	// init for all inputs only accept number
	var inputNode;
	for (var i = 0; i < arrCondition.length; i++) {
		inputNode = $("#" + arrCondition[i].name);
		if (arrCondition[i].valid == "number") {
			inputNode.keypress(function(evt) {
				// fix for IE
				if (!evt.charCode) {
					evt.charCode = evt.keyCode;
				}
					
				// if user does not enter a digit, ignore that character (except system key)
				if (!(evt.charCode <= 57 && evt.charCode != 32)) {
					evt.preventDefault();
				}
			});
		} 
		
		// if this control has max length, handle it
		if (!isNaN(arrCondition[i].maxLength)) {
			// store this info
			inputNode.attr("maxLength", arrCondition[i].maxLength);
			
			// if its value exeeds max length, ignore new character
			inputNode.keyup(function(evt) {
				if (this.value.length > $(this).attr("maxLength")) {
					// trip out characters that are out of bound
					this.value = this.value.substr(0, $(this).attr("maxLength"));
				}
			});
		}
	}
	
	// validate form before submit
	form.submit(function(evt) {
		// get condition from cache
		var arrCondition = initAlertForm.conditionCache[$(this)];
		var isValid = true;
		var strTemp;

		// check all conditions
		for (var i = 0; i < arrCondition.length && isValid; i++) {
			
			strTemp = $("#" + arrCondition[i].name).attr("value");
			strTemp = jQuery.trim(strTemp);
			
			
			switch (arrCondition[i].valid) {
				case "required":
					if (strTemp.length == 0) {
						isValid = false;
					}
					break;
					
				case "email":
					isValid = isValidEmail(strTemp);
					break;
			}

			if (jQuery.isFunction(arrCondition[i].valid)) {
				isValid = arrCondition[i].valid();
			}
			
			// check min length 
			if (!isNaN(arrCondition[i].minLength)) {
				isValid = isValid && arrCondition[i].minLength <= strTemp.length;
			}
		}
		
		// if not valid, show alert box for corresponding control
		if (!isValid) {
			// stop submit
			evt.preventDefault();
						
			// set focus for error control
			$("#" + arrCondition[i - 1].name).focus();
			
			// show alert box
			showAlert($("#" + arrCondition[i - 1].name), arrCondition[i - 1].alert);
		}
	});
	
	/*
		Show alert box
		@param	aControl	an input tag
		@param	strAlert	an alert string		
	*/
	function showAlert(aControl, strAlert) {
		// get position of control
		var pos = aControl.offset();
		var height = aControl.outerHeight();
				
		// update alert string
		$("#alertBox").children("p")[0].innerHTML = strAlert;

		// show alert box next to control
		$("#alertBox").css({
			top: pos.top + height,
			left: pos.left,
			display: "block"
		});
		
		// clear previous timeout
		if (showAlert.timeoutID) {
			clearTimeout(showAlert.timeoutID);
			showAlert.timeoutID = null;
		}
		
		// only show alert box in 2 seconds
		showAlert.timeoutID = setTimeout(function() {
			$("#alertBox").css("display", "none");
			showAlert.timeoutID = null;
		}, 2000);
	}
}

function initContactForm() {
	// if this page does not contain contact form, do nothing
	var frmContact = $("#frmContact");
	if (!frmContact) {
		return;
	}
	
	// clear default content of textarea when it get focus
	
	var defaultText = $("#comments").attr("value");
	$("#comments").focus(function() {// clear text if it is default text
		if (this.value == defaultText) {
			this.value = "";
		}
	});
	
	$("#comments").blur(function() {
		// set clear text if user does not enter any characters
		if (this.value == "") {
			this.value = defaultText;
		}
	});
			
	// add event for contact type images 
	jQuery.each(frmContact.children("div").children("p"), function(aPNode) {
		var aPNode = $(this);
		aPNode.click(function(evt) {
			if (evt.target != this) {
				return;
			}
			
			$(this).children("input")[0].click();
		});
	});
	
	// config for contact form
	var frmContactCondition = [
		{
			name: "navn",
			valid: "required",
			alert: "Please enter your last name"
		},
		{
			name: "firmanavn",
			valid: "required",
			alert: "Please enter your first name"
		},
		{
			name: "vej",
			valid: "required",
			alert: "Please enter your address"
		},
		{
			name: "postnummer",
			valid: "number",
			minLength: "4",
			maxLength: "5",
			alert: "Please enter your post code"
		},
		{
			name: "postnummer_by",
			valid: "required",
			alert: "Please enter your city"
		},
		{
			name: "tlf",
			valid: "number",
			minLength: "10",
			maxLength: "10",
			alert: "Please enter your phone"
		},
		{
			name: "email",
			valid: "email",
			alert: "Please enter your email"
		},
		{
			name: "teambuilding",
			valid: checkContactTypeForContactForm,
			alert: "Please choose a contact type"
		}
	];	
	
	initAlertForm("frmContact", frmContactCondition);
}

/*
	Automatic change state of images
*/
function initImageHover() {
	jQuery.each($("img"), function() {
		var aImageNode = $(this);
		// determine if this image need to be handled or not
		var src = aImageNode.attr("src").toLowerCase();		
		if (src.indexOf("_n.") == -1) {
			return;				
		}
		
		// for special case - splash screen
		var parent = aImageNode.parents("div.navigate")[0];
		if (!parent) {
			parent = this;
		}
						
		// change image according to user's actions
		parent = $(parent);
		parent.mouseover(function() {
			aImageNode.attr("src", aImageNode.attr("src").replace(/_n./i, "_o."));
		});
		
		parent.mouseout(function() {
			aImageNode.attr("src", aImageNode.attr("src").replace(/_o./i, "_n."));
		});
	});
}

function setMainClass() {
	$('div#frontpageCampaigns').parent().addClass('front')
}

function setServiceClass()
{
	$('.service div:first').addClass('balance');
	$('.m3items > div').next().addClass('balance');
	$('.m3items').parent().addClass('mainColumCenterFront');
	$('.frontPageMainImage').next().next().next().addClass('mainColumCenterFront');
	$('img.toprightfloatingimage').prev().prev().addClass('balance');
	$('.rightColumnContainer').prev().addClass('mEditorContentSmall');
}

/*
	Init page when it finish load
*/
$(document).ready(function() {
	initImageHover();
	initContactForm();
	setMainClass();
	setServiceClass();
});
