function initPageHeight() {
	// Clear css attribute "height" of related containers so that they will have auto height
	// before applying new calculated heights to them
	$(".left_nav").css("height", "");
	$(".body_wrap").css("height", "");
	$(".right_nav").css("height", "");
	$(".fill-height").each(function() {
		$(this).css("height", "");
	});

	var lch = $(".left_nav").height(); //lch - left column height
	var pbh = $(".body_wrap").height(); //pbh = page body height
	var rch = $(".right_nav").height(); //rch = right column height

	if (lch > rch && lch > pbh){
		$(".body_wrap").css("height", lch + "px");
		$(".right_nav").css("height", lch + "px");
	} else if (rch > lch && rch > pbh){
		$(".body_wrap").css("height", rch + "px");
		$(".left_nav").css("height", rch + "px");
	} else if (pbh > rch && pbh > lch){
		$(".left_nav").css("height", pbh + "px");
		$(".right_nav").css("height", pbh + "px");
	}

	$(".fill-height").each(function() {
		var regex = new RegExp("\\D", "g");

   		$(this).height($(this).parent().height() -
   				( $(this).offset().top - $(this).parent().offset().top ) +
   				$(this).parent().css("border-top-width").replace(regex,"") * 1  +
   				( $(this).parent().css("padding-top").replace(regex,"")  * 1 +
   				  $(this).parent().css("padding-bottom").replace(regex,"")  * 1 ) -
   				( $(this).css("padding-top").replace(regex,"")  * 1   +
   				  $(this).css("padding-bottom").replace(regex,"")  * 1  ) -
   				( $(this).css("border-top-width").replace(regex,"")  * 1  +
   				  $(this).css("border-bottom-width").replace(regex,"")  * 1)
   		);
	  });

}

$(function(){
	$(".button").assignMouseEvents();
	//initPageHeight();
});


function submitSearchForm(theForm) {
	   if(doSearchValidation (theForm)) theForm.submit();
}

function doSearchFocus(component) {
    var searchVal = component.value;
    if (searchVal == searchInstructions) {
        component.value = "";
    }
}

function doSearchBlur(component) {
    var searchVal = component.value;
    if (strTrim(searchVal) == '') {
        component.value = searchInstructions;
    }
}

function doSearchValidation (theForm) {
	var searchVal = theForm.keyword.value ;
	if (searchVal == "" || searchVal == searchInstructions) {
		alert (searchErrorText) ;
		return false ;
	}
	return true ;
}

function doControlFocus(component,defaultMessage) {
    var controlVal = component.value;
    if (controlVal == defaultMessage) {
        component.value = "";
    }
}

function doControlBlur(component,defaultMessage) {
    var controlVal = component.value;
    if (strTrim(controlVal) == '') {
        component.value = defaultMessage;
    }
}

function strTrim(s) {
    // Remove leading spaces and carriage returns
    while (s.substring(0,1) == ' ') {
        s = s.substring(1, s.length);
    }
    // Remove trailing spaces and carriage returns
    while (s.substring(s.length-1, s.length) == ' ') {
        s = s.substring(0, s.length-1);
    }
    return s;
}

/*
 * This function launches a new web browser window to a specified width, height and features.
 * Features string is a comma separated window's feature needed for this new window. For Instance
 * If a new window needs a toolbar the feature string must be "toolbar" like needs scroll bar and
 * and toolbar then it must be "toolbar,scrollbar". Note that the order of the feature is not required.
 * Also it's case insensitive. Therefore, "scrollbar,toolbar" is identical to "Toolbar,ScrollBar".
 *
 * If the features string is ommitted then all the features are turned off. To turn all the features on
 * use the word "all" for features instead of specifying each feature.
 */

function openWindow(address, width, height,features)
{
	/* Find out what features need to be enable
	 *
   */
	if(features)
		features = features.toLowerCase();
	else
		features = "";

	var toolbar = (features == "all" ? 1 : 0);
	var menubar = (features == "all" ? 1 : 0);
	var location = (features == "all" ? 1 : 0);
	var directories = (features == "all" ? 1 : 0);
	var status = (features == "all" ? 1 : 0);
	var scrollbars = (features == "all" ? 1 : 0);
	var resizable = (features == "all" ? 1 : 0);


	if(features != "all")
	{
		//split features
		var feature = features.split(",");
		for(i = 0; i < feature.length; i++)
		{
		 	if(feature[i] == "toolbar")
			   toolbar = 1;
			else if(feature[i] == "menubar")
			   menubar = 1;
			else if(feature[i] == "location")
			   location = 1;
			else if(feature[i] == "directories")
			   directories = 1;
			else if(feature[i] == "status")
			   status = 1;
			else if(feature[i] == "scrollbars")
			   scrollbars = 1;
			else if(feature[i] == "resizable")
			   resizable = 1;
		}

	}
	features = "toolbar=" + toolbar + ",";
	features += "menubar=" + menubar + ",";
	features += "location=" + location + ",";
	features += "directories=" + directories + ",";
	features += "status=" + status + ",";
	features += "scrollbars=" + scrollbars + ",";
	features += "resizable=" + resizable;

	var newWindow = window.open(address, 'Popup_Window', 'width=' + width + ',height=' + height + ',"' + features + '"');
	newWindow.focus();
}

function trim(s)
{
	// Remove leading spaces and carriage returns
	while (s.substring(0,1) == ' '){
		s = s.substring(1,s.length);
	}
	// Remove trailing spaces and carriage returns
	while (s.substring(s.length-1,s.length) == ' '){
		s = s.substring(0,s.length-1);
	}
	return s;
}
/**
 * Check if the zip code is a US or APO/FPO or Canadian zip code
 */
function isZipCode(s) {
	return isUnitedStateZipCode(s) || isFPOorAPOZipCode(s) || isCanadianZipCode(s);
}

/**
 * Check if the zip code is a US zip code
 */
function isUnitedStateZipCode(s) {

	var reUSZip = new RegExp(/(^\d{5}$)|(^\d{5}(\-|\ )\d{4}$)/);

    if (!reUSZip.test(s)) {
         return false;
    }

    return true;
}

/**
 * Check if the zip code is a Canadian zip code
 */
function isCanadianZipCode(s) {

	var reCanZip = new RegExp(/(^[a-zA-Z]\d{1}[a-zA-Z](\-|\ )\d{1}[a-zA-Z]\d{1}$)/);

    if (!reCanZip.test(s)) {
         return false;
    }

    return true;
}

/**
 * Check if the zip code is a FPO or APO zip code
 */
function isFPOorAPOZipCode(s) {

	var reFPOorAPOZip = new RegExp(/(^[a-zA-Z]{3}(\-|\ )?[a-zA-Z]{2}(\-|\ )?\d{5}$)/);

    if (!reFPOorAPOZip.test(s)) {
         return false;
    }

    return true;
}

/*************************
	Form Field Background Color
*************************/
/*$(function(){
	$("input[type=text]").focus(function(){
		makeCurrent(this);
	});
	$("input[type=text]").blur(function(){
		makeNormal(this);
	});
	$("input[type=password]").focus(function(){
		makeCurrent(this);
	});
	$("input[type=password]").blur(function(){
		makeNormal(this);
	});
	$("textarea").focus(function(){
		makeCurrent(this);
	});
	$("textarea").blur(function(){
		makeNormal(this);
	});
});
function makeCurrent(elem){
	$(elem).css("background-color", "yellow");
}
function makeNormal(elem){
	$(elem).css("background-color", "white");
}*/

/*************************
	Footer Javascript
*************************/

function callEmailSignup() {

	//var formAction = $("#subscribeForm").attr("action");
	//$("#emailSignUp").html("Saving...").load(formAction, {"userEmail":$("#subscribeForm input[name=userEmail]").val()});
	
	//$("#subscribeForm").submit();
	
	var mail=$("#subscribeForm input[name=userEmail]").val();
	
	location.href="/user/subscribe.jsp?email="+$("#subscribeForm input[name=userEmail]").val();

}

$(function() {
	$("#subscribeForm input[name=userEmail]").keydown(function(event) {
		if (event.keyCode == 13)
		{
			callEmailSignup();
			return false;
		}
	});

	$(".email-signup-container .signup-button").click(function(){
		callEmailSignup();
	});
});

/* Create cookie */

function createCookie(name, value, domain, secs, path) {
	if (secs) {
		var date = new Date();
		date.setTime(date.getTime()+(secs*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";

	document.cookie = name+"="+value+expires+"; path=" + ((path) ? path : "/") + ((domain) ? "; domain=" + domain : "");
}



/*************************
	Required for Popup to Layer conversion
*************************/

/*
The default action for writing the response to the active popup layer.
Use this global function so the popup plugin can be changed easily
 */
var writeDataIntoLayer = function(data) {
	//used for jmpopups
	//$("#popupLayerScreenLocker").next().html(data);
	//used for openDOMWindow
	//$("#DOMWindow").html(data);
	//used for ColorBox
	$("#cboxLoadedContent").html(data);
	$.colorbox.resize();
};

jQuery.fn.closeLayer = function(){
	/* use closeLayer() for all close layer events so that the interface with the plugin is only in one spot */
	$.colorbox.close();
};

jQuery.fn.softSlideDown = function(callback){
	this.css("opacity", 0).slideDown(300).fadeTo(150, 1, function() {
		if (callback && typeof callback == "function")
			callback();
	});
	return this;
};

jQuery.fn.softSlideUp = function(callback){
	this.fadeTo(150, 0).slideUp(300, function() {
		if (callback && typeof callback == "function")
			callback();
	}).css("opacity", 1);
	return this;
};

jQuery.fn.hilight = function(callback){
	var me = this;
	if (me.hasClass("animating")) {
		var t = setTimeout(function(){
			me.hilight(callback);
		},200);
	} else {
		var hiliteColor = "#BDE8FF";
		var defaultStart = "#FFFFFF";
		var currentColor = jQuery(this).css('background-color');
		if (currentColor && currentColor != 'transparent' && currentColor.indexOf("rgba(") == -1)
			defaultStart = currentColor;

		me.addClass("animating").css("background-color",defaultStart).animate({ backgroundColor:hiliteColor }, 300, function() {
			me.animate({ backgroundColor:defaultStart }, 1000, function() {
				me.css("background-color",currentColor).removeClass("animating");
				if (callback && typeof callback == "function")
					callback();
			});
		});
		return this;
	}
};


$(function() {
	$(".openAjaxLayer").live("click", function(e) {
		e.preventDefault();
		var layerWidth = 400;//the default layer width, can be overridden by setting a class of layerWidth700 on each anchor 
		var maxLayerWidth = 500;//the max width of the layer
		var path = $(this).attr("href");
		var tagsLayerWidth = $(this).attr('data-layerWidth');
		var tagsMaxLayerWidth = $(this).attr('data-maxLayerWidth');

		if( tagsMaxLayerWidth != undefined  )
		 	maxLayerWidth = tagsMaxLayerWidth;

		if ( tagsLayerWidth != undefined )
			layerWidth = tagsLayerWidth;

		/* we need to cache bust GET requests for IE */
		var paramSep = (path.indexOf("?") > 0) ? "&" : "?";
		var d = new Date();
		path = path + paramSep + "time=" + d.getTime();

		$.colorbox({
			scrolling:false,
			href:path,
			width:layerWidth,
			opacity:.6
		});
		return false;
	});

	$(".closePopupLayer").live("click", function(e){
		e.preventDefault();
		$(this).closeLayer();
		return false;
	});
});

(function($){  
	$.fn.popup = function(options) {
		var checking=0;
		var popupDefaults = {
			    message: 'Warning',
			    dismiss: 'Cancel',
				accept: 'OK',
				acceptURL: '#'
			};
		var opts = $.extend({}, $.fn.popup.defaults, options);
	    $(this).click(function(){
			var linkPosition = $(this).offset();
			var path = $(this).attr("href");
			if (path != undefined) {opts.acceptURL=path;}
			if ($('#popup')){$('#popup').remove();}
			if ($('#screen')){$('#screen').remove();}
			$('<div/>',{
				'id':'screen',
				'css':{
					'background-color':'rgb(0,0,0)',
					'position':'absolute',
					'top':0,
					'left':0,
					'width':$(window).width()+'px',
					'height':$(window).height()+'px',
					'display':'none',
					'visibility':'visible'
				}
			}).appendTo('body').fadeTo('fast',0.7);
			
			$(window).resize(function(){
				$('#screen').css('width',$(this).width());
				$('#screen').css('height',$(this).height());
				$('#popup').css({
					left:($(this).width() / 2) - ($('#popup').width() / 2)+$(this).scrollLeft(),
					top:($(this).height() / 2) - ($('#popup').height() / 2)+$(this).scrollTop()-100
				});
			});
			
			$(window).scroll(function(){
				$('#screen').css('left',$(this).scrollLeft());
				$('#screen').css('top',$(this).scrollTop());
				$('#popup').css({
					left:($(this).width() / 2) - ($('#popup').width() / 2)+$(this).scrollLeft(),
					top:($(this).height() / 2) - ($('#popup').height() / 2)+$(this).scrollTop()-100
				});
			});
			
			var	$popup = $('<div/>',{'id':'popup',css:{'display':'none'}}).appendTo('body');
			
			var $popContents = $('<div/>',{
				'id':'popContents',
				'html': opts.message
			}).appendTo($popup);
			
			var popButtons = $('<div/>',{
				'id':'popButtons',
				'html': '<a href="javascript:void(0);" id="popDismiss" class="btnRed">'+ opts.dismiss+'</a><a href="'+opts.acceptURL+'" id="popAccept" class="btnGreen">'+ opts.accept + '</a>'
			}).appendTo($popContents);

			$("#popup").css({
				left:($(window).width() / 2) - ($("#popup").width() / 2),
				top:($(window).height() / 2) - ($("#popup").height() / 2)-100
			}).fadeIn('slow');

			checking = setInterval(function() {
			    var currHeight = $('#popContents').height();
			    if ($('#popup').height() != currHeight) {
				 $('#popup').animate({height:currHeight+'px'});
				 newHeight = currHeight;
			    }
			  },100);
			
			$('<img/>',{'src':'/starter/assets/images/common/loadinfo-horiz.gif','css':{'display':'none'}}).appendTo('body');
			
			return false;
		});
		
		$("#screen").live("click", function(){
			clearInterval(checking);
			$("#screen").fadeOut();
			$("#popup").fadeOut();
		});

		$("#popDismiss").live("click", function(){
			clearInterval(checking);
			$("#screen").fadeOut();
			$("#popup").fadeOut();
		});

		$("#popAccept").live("click", function(){
			clearInterval(checking);
			$("#popContents").html('<div class="poploading"><img src="/starter/assets/images/common/loadinfo-horiz.gif" alt="Loading..."/></div>');
		});

	};
})(jQuery);

 ////////////////////////////////////////////////
// JS added by Snow Valley

var common_js = {
	init : function(){
	
		// Initialise custom dropdowns
		//$( '.use_msdropdown' ).msDropDown({showIcon:true});

		$( "form#subscribeForm" ).unbind("submit").submit(function( e ){  
			e.preventDefault();			
		});
	
		// Use customInput.jquery.js to create custom checkbox elements (added 09/08/2011)
		//$('.body_wrap').find('input[type="checkbox"]').ezMark();
	}
};


$(function() {

	common_js.init();

});

// Micros Italia functions

// Simple function to pre-load images
function preloadImages(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
    });
}

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function blockUiOnNavigate(message, imageUrl) {
	$.blockUI({
		overlayCSS: { backgroundColor: '#FFF', opacity: 0.7 }, 
		css: { backgroundColor: '#FFF', borderWidth:'2px', textAlign:'center', padding:'10px' },
		message: '<p style="margin-bottom: 5px;">' + message + '</p><p><img src="' + imageUrl +'" /></p>'
	});
}
