var formSubmitSuccess = "Thank you for submitting information. We will contact you as soon as possible.";
var formSubmitFailure = "Failure: Unable to submit the Form.";

var EXPAND_ANIM_DURATION = 100;
var CAROUSEL_ANIM_DURATION = 200;
var VISIBLE_LAYER = { hide: function() {} };

var addthis_config = {
     ui_offset_top: 40,
     ui_offset_left: 60,
	 ui_click: true
}

/**
 * Global flag to enable/disable javascript logging.
 */
var logEnabled = false;


function setFormSubmitMessages(msgs){
	formSubmitSuccess = msgs[0];
	formSubmitFailure = msgs[1];
	}

function alertFormSubmitSuccess(){
	alert(formSubmitSuccess);
}

// added to display message when mail sent successfully.
function alertSendSubmitSuccess(tr_text_success){
	alert(tr_text_success);
}
function alertSubmitFailure(tr_text_err){
	alert(tr_text_err);
}

function alertFormSubmitFailure(){
	alert(formSubmitFailure);
}


/**
 * Logs a message to the console.
 *
 * @param params The first parameter is the message (eg. "Error {0} happened at {1}"), subsequent parameters are the message arguments.
 */
function log() {
	if (logEnabled && typeof(console) !== 'undefined' && console != null) {
		var message = arguments[0];
		var length = arguments.length;
		for (var i = 1; i < length; i++) {
			message = message.replace("{" + i + "}", arguments[i]);
		}
		console.log(message);
	}
}

/**
 * Returns an associative array with the parameters from the query string.
 *
 * @return The parameters from the query string.
 */
function parseUrlParameters() {
	var params = {};
	var e;
	var decode = function (s) {
		return decodeURIComponent(s.replace(/\+/g, " "));
	};
	var queryString = window.location.search.substring(1);
	var r = /([^&=]+)=?([^&]*)/g;

	while (e = r.exec(queryString)) {
		params[decode(e[1])] = decode(e[2]);
	}

	return params;
}

typeof $ == 'function' && $(function() {

	// Extends jQuery functionality
	jQuery.fn.extend({

		/**
		 * Loads a fatwire page and places the returned HTML into the matched element.
		 * It will automatically add to all the matched elements the attribute "data-page" containing the page name to avoid reloading it unnecessarily (only if no params where provided).
		 *
		 * @param page The name of the page to load. Eg. WCom/Contact/ContactForm.
		 * @param params The request parameters.
		 * @param loaded A callback function that is executed when the page is loaded.
		 * @param init A callback function that is executed when page is loaded the first time.
		 */
		loadPage: function(page, params, loaded, init) {
			// If the second parameter was provided
			if (params) {
				// If it's a function
				if (jQuery.isFunction(params)) {
					// We assume that it's the callback
					loaded = params;
					params = null;

				// Otherwise, build a param string
				} else if (typeof params === "object") {
					params = jQuery.param(params, jQuery.ajaxSettings.traditional);
				}
			}

			// If the given page was already loaded into the matched element avoid loading it again
			if (page == this.attr("data-page") && !params) {
				log("Page '{1}' was already loaded.", page);
				if (loaded) this.each(loaded);
				return this;
			}

			// Loads the page into the matched element
			log("Loading page '{1}'.", page);

			var url = baseAjaxUrl + page;

			var self = this;
			this.load(url, params, function(res, status) {
				if (status === "success" || status === "notmodified") {

					self.attr("data-page", page);
					self.html(res.responseText);

					log("Page '{1}' loaded.", page);
					if (init) self.each(init);
					if (loaded) self.each(loaded);
				}
			});
			
			
			var hashParams = location.hash.split('_');
			
			// If the browser is rendering the page from a bookmark or from pressing the Back Button
			// there will be hash params in the URL
			if((hashParams.length == 6) && hashParams[0] == '#') {

				// Need to parse out the parameters
				params = "?" + params;
				var pageIndex;
				
			    var vars = [], hash;
	            var hashes = params.slice(params.indexOf('?') + 1).split('&');
	            for (var i = 0; i < hashes.length; i++) {
	                hash = hashes[i].split('=');
	                vars.push(hash[0]);
	                vars[hash[0]] = hash[1];
	                
	                if(hash[0]=="pageIndex"){
	                	pageIndex = hash[1];
	                }
	            }
		 					

				var contentType = hashParams[1];
				var contentYear = hashParams[2];
				var contentTypeEng = hashParams[4];
				var contentYearEng = hashParams[5];
				
				window.location.hash = "#_" + contentType + "_" + contentYear + "_" + pageIndex + "_" + contentTypeEng + "_" + contentYearEng;

				
			}
			
			

			return this;
		}
	});

	/* Search input focus on click

	$("#nav .input, #sitemap .input").focus(function() {
		$(this).attr("value", "");
	});
        */


	/* Entire block clickable */

		$('.products_grid .left, .products_grid .right').click(function() {
    	window.location = $(this).find('a').attr('href');
    	return false;
	});

	$(document.body).click(function(e) {
	    if (typeof VISIBLE_LAYER.offset == 'function') {
	        /* Hide layer when clicked outside */

	        var offset = VISIBLE_LAYER.offset();
	        var size = { width: VISIBLE_LAYER.outerWidth(), height: VISIBLE_LAYER.outerHeight() };

	        if (e.pageX < offset.left || e.pageX > offset.left + size.width || e.pageY < offset.top || e.pageY > offset.top + offset.height) {
	            VISIBLE_LAYER.fadeOut('fast');
	        }
	    }
	});

    /* Make My Wartsila and Global Sites in header openable and closeable */

    var myWartsilaContent = $('#my_wartsila_content');
	var selectLanguageContent = $('#select_language_content');
    var globalSitesContent = $('#wartsila_global_sites_content');

    $('#my_wartsila').click(function() {
        VISIBLE_LAYER.hide();

        globalSitesContent.hide();
		selectLanguageContent.hide();
        myWartsilaContent.fadeIn('fast');

        VISIBLE_LAYER = myWartsilaContent;
    });

    $('#wartsila_global_sites').click(function() {
        VISIBLE_LAYER.hide();

        myWartsilaContent.hide();
		selectLanguageContent.hide();
        globalSitesContent.fadeIn('fast');

        VISIBLE_LAYER = globalSitesContent;
    });

	$('#wartsila_global_sites_content h2 a').click(function() {
        VISIBLE_LAYER.hide();

        return false;
	});

    $('#select_language').click(function() {
        VISIBLE_LAYER.hide();

        myWartsilaContent.hide();
        globalSitesContent.hide();
		selectLanguageContent.fadeIn('fast');

        VISIBLE_LAYER = selectLanguageContent;
    });

	$('#select_language_content h2 a').click(function() {
        VISIBLE_LAYER.hide();

        return false;
	});

		$('.captcha_why').click(function() {

			if (!$('#captcha_help').is(':visible')) {
				$(this).closest('label').after($('#captcha_help'));
				$('#captcha_help').show();
			} else {
				$('#captcha_help').hide();
			};
			return false;
		});

	$('#button_contactus, .button_contactus').click(function() {
		showContactUs();
		return false;
	});
	

    /* Make expandable items expandable */
   //provchanges- expandable page modifications
 //   $('.expand_area > div').css('display', 'none');
    $('.expand_area > h3 > a').click(function() {
        var header = $(this).closest('h3');
        var block = header.next('div');

        header.toggleClass('expanded_header');

        if (block.is(':visible')) {
            block.hide(EXPAND_ANIM_DURATION);
        }
        else {
            block.show(EXPAND_ANIM_DURATION, function() {
                initCarousels(block);
            });
        }

        return false;
    });

    /* Make tab groups switchable */
	$('.tabs_nav li:first-child').addClass('first_current'); // first tab is selected by default with special class
	initTabsNavigators($(document));

    /* Make search results preview openable */

    $('#nav form input[type="text"]')
    	.focus(function() {
   	        VISIBLE_LAYER.hide();
    		$('#search_preview').fadeIn('fast');
	    })
	    .blur(function() {
    		$('#search_preview').hide();
	    });


    /* Make pulldowns openable */

    $('.dropdown').each(function() {

    	var content = $(this);
    	var wrapper = content.parents('.dropdowns');
    	var pulldown = wrapper.find('a[rel="' + $(this).attr('id') + '"]');

    	pulldown.click(function() {


   	        VISIBLE_LAYER.hide();

   	        var left = parseInt(pulldown.offset().left - wrapper.offset().left) - 1;

   	        pulldown.addClass('current');
   	        content.css('left', left + 'px');
    		content.fadeIn('fast');

    		VISIBLE_LAYER = {
    			'hide': function() {
    				pulldown.removeClass('current');
    				content.hide();
    			},
    			'offset': function() {
    				return content.offset();
    			},
    			'outerWidth': function() {
    				return content.outerWidth();
    			},
    			'outerHeight': function() {
    				return content.outerHeight();
    			},
    			'fadeOut': function(x) {
    				content.fadeOut(x);
    			}
    		};

    		return false;
    	});
    });


    /* Make carousels moveable */

    initCarousels(document.body);


    /* Make product finder dropdowns openable */

    $('.product_dropdown2').hide();

    $('.product_chooser .nav > li').click(function() {
    	VISIBLE_LAYER.hide();

        var ref = $(this).find('a[rel]');
    	var pulldown = $('#' + ref.attr('rel'));
    	var contoff = $('#container').offset();
        var off = ref.offset();

    	off.top -= contoff.top;
    	off.left -= contoff.left;

    	if (pulldown.hasClass('product_dropdown_3_columns')) {
    		off.left = $('#container').width() - pulldown.width() + 15;
    	}

        pulldown.remove().appendTo('#container');
        pulldown.css({
            'position': 'absolute',
            'top': (off.top - 30) + 'px',
            'left': (off.left - 15) + 'px',
            'z-index': 999
        });
    	pulldown.fadeIn('fast');
    	VISIBLE_LAYER = pulldown;

    	return false;
    });

    /* Make glossary openeable */

    $('<div class="glossary_content"> <div class="text"></div> <div class="bottom"></div> </div>').insertAfter('.glossary:first');
    $('.glossary_content').hide();
    $('.glossary').mouseover(function() {
    	VISIBLE_LAYER.hide();

    	var term = $(this);
        var tooltip = $('.glossary_content');

        tooltip.remove().appendTo(document.body);

    	var contoff = $('#container').offset();
        var off = term.offset();

    	tooltip.find('.text').text(term.attr('tooltip'));
    	tooltip.css({
    	    'position': 'absolute',
    	    'z-index': 10,
    	    'top': off.top + term.height() + 2 + 'px',
    	    'left': off.left + 'px'
    	});

    	term.mouseout(function() {
    	    tooltip.hide();
    	});

    	tooltip.fadeIn('fast');
    	VISIBLE_LAYER = tooltip;

        return false;
    }).each(function() {
        var item = $(this);

        item.attr('tooltip', item.attr('title'));
        item.removeAttr('title');
    });
    
    /* Ensure the search boxes have autocomplete turned off*/
    $(document).ready(function() {
    	$("#q").attr("autocomplete", "off");
    	$("#qf").attr("autocomplete", "off");
    	});
    
});

/**
 * Initializes all the tabs navigators under the given root element.
 *
 * @param $root The root element.
 */
function initTabsNavigators($root) {
	log("Initializing tabs navigators.");

	$root.find('.tabs_nav').next('.tabs_wrapper').each(function() {	
		$(this).children(':not(:first)').css('display', 'none');
	});

	$root.find('.tabs_nav li a').click(function() {
		var tab = $(this).closest('li');
		var tabsWrapper = tab.parent();
		
		var url_parts = $(this).attr('href').split('#');
		var target;
		var listSize = 0;
		var arcEvents;
		
		if (url_parts.length == 1) {
					target = url_parts;
		};

		if (url_parts.length == 3) {
			listSize = url_parts[1];
			arcEvents = url_parts[0];
			target = url_parts[2];
		};
		
		if (url_parts.length == 2) {
			listSize = url_parts[0];
			target = url_parts.pop();
		};
		
		
		
		var contentWrapper = $('div#'+target);

		VISIBLE_LAYER.hide();

		tab.siblings().removeClass('current first_current current_service24h');
		tab.addClass(tab.prev('li').length == 1 ? 'current' : 'current');
		
		//document.getElementById('li#'+target).className = 'current';

		if (tab.hasClass('service24h')) {
			/* Special case for contact dialog */
			tab.removeClass('current');
			tab.addClass('current_service24h');
		}

		contentWrapper.siblings('div').css('display', 'none');
		contentWrapper.css('display', 'block');
		initCarousels(contentWrapper);
		
		var nextLinkIndex = $('div#'+target+' div.carousel_footer a.right').attr('title');
		var previousLinkIndex = $('div#'+target+' div.carousel_footer a.left').attr('title');
		var index=0;
		if(arcEvents != undefined)
		{
			if(arcEvents.length > 4)
			{
				arcEvents = arcEvents.substring(arcEvents.length-4, arcEvents.length)
			}
		}
		if(arcEvents == "true")
		{
			
			if(nextLinkIndex == undefined && previousLinkIndex == undefined)
			{
				index=0;
			}
			
			if(nextLinkIndex != undefined)
			{
				index = nextLinkIndex-5;
			}
			else if(nextLinkIndex == undefined && previousLinkIndex != undefined )
			{
				index = previousLinkIndex-5;
			}
			
			if(isNaN(index))
			{
				var hashParams = location.hash.split('_');
				window.location.hash = "#_0_" + target + "_" + listSize +"_"+hashParams[4]+"_1";
			}
			else
			{
				var hashParams = location.hash.split('_');
				window.location.hash = "#_" + index + "_" + target + "_" + listSize +"_"+hashParams[4]+"_1";
			}
		}
		else
		{
			if(nextLinkIndex == undefined && previousLinkIndex == undefined)
			{
				index=0;
			}
			
			if(nextLinkIndex != undefined)
			{
				index = nextLinkIndex-5;
			}
			else if(nextLinkIndex == undefined && previousLinkIndex != undefined )
			{
				index = previousLinkIndex-5;
			}
			
			if(isNaN(index))
			{
				var hashParams = location.hash.split('_');
				window.location.hash = "#_0_" + target + "_" + listSize +"_"+hashParams[4];
			}
			else
			{
				var hashParams = location.hash.split('_');
				window.location.hash = "#_" + index + "_" + target + "_" + listSize +"_"+hashParams[4];
			}
			
		}
		return false;
	});
}

function callDivTab(tabId)
{	
	var contentWrapper = $('div.'+tabId);
	
	document.getElementById("tab"+tabId).className = 'current';

	contentWrapper.siblings('div').css('display', 'none');
	contentWrapper.css('display', 'block');	
	
}

function showGlobalAddressBook(){
	var globallink = $('#globalAddressLink');
	globallink.click();
}


function initCarousels(root) {

	/* Frontpage carousel special */
	$(".liftup_frontpage img:first").addClass('background');
	$(".liftup_frontpage .carousel a").css('display','block');
	$(".liftup_frontpage .carousel a:first").addClass('previous');
	$(".liftup_frontpage .carousel a:first").next('a').addClass('next');


    $('.carousel', root).each(function() {
        var carousel = $(this);
        var prevButton = carousel.find('a.previous');
        var nextButton = carousel.find('a.next');
        var footer = carousel.next('.carousel_footer');
        var wrapper = carousel.find('div.content');
        var content = wrapper.children();
        var indexLabel = footer.find('.current');
        var isAnimating = false;
        var pageIndex = 0;
        var totalWidth = 0;

        content.children().each(function() {
            totalWidth += $(this).outerWidth();
        });

        wrapper.children().css({
            'width': totalWidth + 'px',
            'margin-left': 0
        });

        var pageCount = Math.ceil(content.innerWidth() / parseInt(wrapper.innerWidth())) ||Â 1;

        footer.find('.total').text(pageCount);


        function onAnimationDone() {
             isAnimating = false;
             indexLabel.text(pageIndex + 1);

            if (pageIndex == 0)
                prevButton.addClass('disabled');
            else
                prevButton.removeClass('disabled');

            if (pageIndex >= pageCount - 1)
                nextButton.addClass('disabled');
            else
                nextButton.removeClass('disabled');
        }


        prevButton.addClass('disabled').click(function() {
            if (isAnimating || pageIndex <= 0)
                return false;

            pageIndex--;
            isAnimating = true;

            var pos = parseInt(content.css('margin-left'));
            var width = wrapper.innerWidth();

            content.animate({
                marginLeft: (pos + width) + 'px'
            }, CAROUSEL_ANIM_DURATION, 'linear', onAnimationDone);

            return false;
        });


        nextButton.click(function() {
            if (isAnimating || pageIndex >= pageCount - 1)
                return false;

            pageIndex++;
            isAnimating = true;

            var pos = parseInt(content.css('margin-left'));
            var width = wrapper.innerWidth();

            content.animate({
                marginLeft: (0, pos - width) + 'px'
            }, CAROUSEL_ANIM_DURATION, 'linear', onAnimationDone);

            return false;
        });

        onAnimationDone();
    });


    /* Bookmarks */

	// add a "rel" attrib if Opera 7+
	if(window.opera) {
		if ($(".link_bookmark a").attr("rel") != ""){ // don't overwrite the rel attrib if already set
			$(".link_bookmark a").attr("rel","sidebar");
		}
	}

	$(".link_bookmark a").click(function(event){
		event.preventDefault(); // prevent the anchor tag from sending the user off to the link
		var url = this.href;
		var title = this.title;

		if (window.sidebar) { // Mozilla Firefox Bookmark
			window.sidebar.addPanel(title, url,"");
		} else if( window.external ) { // IE Favorite
			window.external.AddFavorite( url, title);
		} else if(window.opera) { // Opera 7+
			return false; // do nothing - the rel="sidebar" should do the trick
		} else { // for Safari, Konq etc - browsers who do not support bookmarking scripts (that i could find anyway)
			 alert('Unfortunately, this browser does not support the requested action,'
			 + ' please bookmark this page manually.');
		}

	});


	/* Print page */

	$('.link_print a').click(function() {
		window.print();
		s.eVar14=s.pageName; 
		s.events = "event7";	
		s.t();		
		return false;
	});

    /* Video 
	
	$('div#videos').delegate('a.play_control','click', function(event) {
					   
		var clickedLink = $(event.currentTarget);
		var videoHref = clickedLink.attr("href");
		var videoTitle = clickedLink.attr("title");
		var videoId = videoHref.replace("http://www.youtube.com/watch?v=","");
		$(".video_popup").remove();			
		$("<div class='video_popup'><div class='video_container'><h2><span>"+videoTitle+"</span><a href='#'>Close</a></h2><iframe title='"+videoTitle+"' width='425' height='349' src='http://www.youtube.com/embed/"+videoId+"' frameborder='0' allowfullscreen class='youtube'></iframe></div></div>").insertAfter("#footer");
		
		var dialog = $('.video_popup');
		var overlay = getOverlay();
    	
		overlay.fadeIn('fast');
		dialog.css('margin-top', $(window).scrollTop() + 'px');
		dialog.fadeIn('fast');


		$("#overlay").click(function() {
			$(this).hide();
			$(".video_popup").hide();
			return false;
		});
		
		$(".video_popup h2 a").click(function() {
				$(".video_popup").hide();
				$("#overlay").hide();
				return false;
		});
		
	return false;
	});
*/
// Material List page.  Select a material type.

	 $('div#material_list div#type_content ul li').click(function() {

		var getid = $(this).attr('id');
		var selectvalue = $(this).children('a').text();
		var childpagename = $(this).children('a').attr('name');
		var replaceVal = $(this).children('a').attr('rel');
		var yearVal = $('div.dropdowns ul li.width_narrow p a span').attr('id');
		
		var hashParams = location.hash.split('_');
		
		var yearValLocalisedLang = $('div.dropdowns ul li.width_narrow p a span').text();
		
		$('div.dropdowns div#type_content').hide();
		$('div.dropdowns ul li.width_wide p a span').replaceWith('<span id="'+replaceVal+'">'+selectvalue+'</span>');
		
		
		//Simon Whelan: added if statement to cope with the new financial materials page
		if(childpagename == "WMedia_C/FinancialMaterialListView")
		{
			$("#materialsContent").loadPage(childpagename, { pageIndex:"1", pageSize:"15", financialfileType:replaceVal, year:yearVal});
		}
		else
		{
			$("#materialsContent").loadPage(childpagename, { pageIndex:"1", pageSize:"15", fileType:replaceVal, year:yearVal});
		}
		

		var hashParams = location.hash.split('_');
		var pageIndex = hashParams[3];
		
		if(pageIndex > 1){
			pageIndex = 1;
		}
		
		window.location.hash = "#_" + selectvalue + "_" + yearValLocalisedLang + "_" + pageIndex + "_" + replaceVal + "_" + yearVal;
				
        return false;
    });

	//Material List page.  Select a year.

	 $('div#material_list div#year_content ul li').click(function() {
		var getid = $(this).attr('id');
		var childpagename = $(this).children('a').attr('name');
		var contentVal = $('div.dropdowns ul li.width_wide p a span').attr('id');
		var replaceVal = $(this).text();
		
		
		var yearValLocalisedLang = $(this).children('a').text();;
		

		$('div.dropdowns div#year_content').hide();
		$('div.dropdowns ul li.width_narrow p a span').replaceWith('<span id="'+getid+'">'+replaceVal+'</span>');

		//Simon Whelan: added if statement to cope with the new financial materials page
		if(childpagename == "WMedia_C/FinancialMaterialListView")
		{
			$("#materialsContent").loadPage(childpagename, { pageIndex:"1", pageSize:"15", financialfileType:contentVal, year:getid});
		}
		else
		{
			$("#materialsContent").loadPage(childpagename, { pageIndex:"1", pageSize:"15", fileType:contentVal, year:getid});
		}


		var hashParams = location.hash.split('_');
		
		var pageIndex = hashParams[3];
		var contentType = hashParams[1];

		if(pageIndex > 1){
			pageIndex = 1;
		}
		
		window.location.hash = "#_" + contentType + "_" + yearValLocalisedLang + "_" + pageIndex + "_" + contentVal + "_" + getid;
		
        return false;
    });


}


//opens pop window which will explain about why captcha needed
function captchaExplain(captchatitle, captchaText){
	//1321 - get handle to window if open already and close
    explainWindow= window.open ("", "test", "location=0,status=0,scrollbars=0,width=350,height=270,top=400,left=350");
    explainWindow.close();	
      
	explainWindow= window.open ("", "test", "location=0,status=0,scrollbars=0,width=350,height=270,top=400,left=350");
	explainWindow.document.write ('<html><head><title>');	
	explainWindow.document.write (captchatitle);
	explainWindow.document.write ('</title></head>');
	explainWindow.document.write ('<body>');
	explainWindow.document.write ('<font size="2" face="Tahoma, Verdana, Helvetica, Arial, sans-serif">');
	explainWindow.document.write (captchaText);
	explainWindow.document.write('</font></body>');
	explainWindow.document.write('</html>');

}

//email validation
function emailcheck(str) {
		 var at="@"
		 var dot="."
		 var lat=str.indexOf(at)
		 var lstr=str.length
		 var ldot=str.indexOf(dot)
		 if (str.indexOf(at)==-1){
		   return false;
		 }

		 if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){

		   return false;
		 }

		 if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){

		    return false;
		 }

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false;
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false;
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false;
		 }

		 if (str.indexOf(" ")!=-1){
		    return false;
		 }

 		 return true;
	}

//validating footer send form
function validateSendForm(url, tr_text_success, tr_text_err) {

		$('#add_your_error').hide();
		$('#send_this_error').hide();
		$('#your_message_error').hide();
		$('#invalid_toemail').hide();
		$('#invalid_youremail').hide();
		$('#send_mail_success').hide();
		$('#send_capthcha_error').hide();
		
		 var toemail=$('#send_this').val();
		 var sendmessage=$('#your_message').val();
		 var fromemail=$('#add_your').val();
		 
		 var recaptcha_response_field=$('#recaptcha_response_field').val();

		//check for to email
		 if (toemail == "")
		 {

			$('#send_this_error').show();
			return false;
		 }
		else {
			if (!emailcheck(toemail))
			{
				$('#invalid_toemail').show();
				return false;
			}
		 }


		//check for message
		  if (sendmessage == "")
		 {

			$('#your_message_error').show();
			return false;
		 }

		//check for your email

		if (fromemail == "")
		 {

			$('#add_your_error').show();
			return false;
		 }
		else {
			if (!emailcheck(fromemail))
			{
				$('#invalid_youremail').show();
				return false;
			}
		 }
		 
		 
		 if (recaptcha_response_field == "") {
		 			$('#send_capthcha_error').show();
		 			return false;
		 		}
	
		  		  
		  s.events = "event14";
		  s.eVar6 = s.pageName;
		  s.t();	  
	sendMailAjax(url, tr_text_success, tr_text_err);

}

function registerShareHit()
{
	s.events = "event14";
	s.eVar6 = s.pageName;
	s.t();
	return true;
}

function getOverlay() {
	var overlay = $('#overlay');
	var styles = {
		'display': 'none',
		'position': 'fixed',
		'z-index': 10,
		'top': 0,
		'left': 0,
		'right': 0,
		'bottom': 0,
		'opacity': 0.75,
		'background-color': '#000000'
	};
	var ie6styles = {
		'display': 'block',
		'position': 'absolute',
		'z-index': 10,
		'top': '0px',
		'left': '0px',
		'opacity': 0.75,
		'background-color': '#000000'
	};

	if (overlay.length == 0) {
		overlay = $('<div id="overlay"></div>');
		overlay.css(isIE6() ? ie6styles : styles);

		$(document.body).append(overlay);
	}

	if (isIE6()) {
		overlay.css({
			'width': document.body.clientWidth + 'px',
			'height': document.body.clientHeight + 'px'
		});

		if (!window.resizeAdded) {
			$(window).resize(function() {
				overlay.css({
					'width': document.body.clientWidth + 'px',
					'height': document.body.clientHeight + 'px'
				});
			});

			window.resizeAdded = true;
		}
	}

	return overlay;
}


function isIE6() {
	var ua = navigator.userAgent;
	return ua.indexOf('MSIE 6') >= 0 && ua.indexOf('Opera') == -1;
}


/* font replace by cufon */
//Cufon.replace('.liftup_frontpage h2.heading a', { hover: true, fontFamily: 'helvetica' });
//Cufon.replace('.liftup_frontpage div.carousel div.content ul li h2 a', { hover: true, fontFamily: 'helveticabold' });




//sending mail using footer send form by calling ajax call
function sendMailAjax(sendurl , tr_text_success, tr_text_err) {

	var dataString = $('#footer_send').serialize();
	var host = window.location.host;
        var protocol = window.location.protocol;
	$.ajax({type: "POST",
			 url:protocol+'//'+host+sendurl,
			 data: dataString,
			 dataType: "text",
			 success: function(data) {
			 	if(trim(data).indexOf("recaptcha_error") != -1){
			 					// display error message
			 					$('#send_capthcha_error').show();
			 					Recaptcha.reload();
			 					return false;
				} else if(trim(data).indexOf("success") != -1){
					alertSendSubmitSuccess(tr_text_success);
					hideSendForm();
				} else {
					alertSubmitFailure(tr_text_err);
					return false;
				}

			 }
	});
    return false;
}

//getting footer send form using ajax call
function getSendForm(sendurl,replaceval) {

		var protocol = window.document.location.protocol+'//';
		var host = window.location.host;
		var url=protocol+host+sendurl;

	 	var xmlhttp=null;
		try
		{
			xmlhttp=new XMLHttpRequest();
		}
		catch(B)
		{
			try
			{
				xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
			}catch(B)
			{
				xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
		}
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{

				$('div#'+replaceval).replaceWith(xmlhttp.responseText);
				var dialog = $('.send_link');
				var overlay = getOverlay();

				overlay.fadeIn('fast');
				dialog.css('margin-top', $(window).scrollTop() + 'px');
				dialog.fadeIn('fast');

				$('#add_your_error').hide();
				$('#send_this_error').hide();
				$('#your_message_error').hide();
				$('#invalid_toemail').hide();
				$('#invalid_youremail').hide();
				$('#send_capthcha_error').hide();
				$('span#invalid_­send_capthcha').hide();
				$('#send_mail_success').hide();
				$('span#send_mail_success').hide();
				showRecaptcha('recaptcha_div');

			}
		}
		xmlhttp.open("GET",url,true);
		xmlhttp.send(null);

}

var overlayOpened;

function showOverlay() {
	var overlay = getOverlay();
	overlay.fadeIn('fast');
	overlay.click(hideOverlay);
	overlayOpened = true;
}

function hideOverlay() {
	$('#overlay').hide();
	overlayOpened = false;
}

function isOverlayOpen() {
	// Check using a variable instead of the CSS visibility because of the asynchronous effects
	return overlayOpened;
}


var chooseOption;
var howOption;

/**
 * Loads the content for the contact us dialog and shows it.
 */
function showContactUs() {	
	chooseOption = null;
	howOption = null;
	showOverlay();
	$('#contact').loadPage('WCom/Contact/ContactForm', showContactUsDialog);
}

/**
 * Loads the content for the contact us dialog and shows it based on coming from a link asset.
 */
function showContactUsLink(chooseValue, howValue) {
	chooseOption = chooseValue;
	howOption = howValue;
	
	showOverlay();
	$('#contact').loadPage('WCom/Contact/ContactForm', showContactUsDialogDirect);
}


/**
 * Shows the contact us dialog.
 */
function showContactUsDialogDirect() {
	
	var choose = chooseOption;
	var how = howOption;
	
	if (!isOverlayOpen()) {
		return;
	}

	// Removes the click handler to prevent closing the popup window accidentally
	$('#overlay').unbind('click');
	$('#contact h2 a').click(hideContactUs);

	// Initializes the dialog box
	if (!window.contactSetUp) {
		initContactUsDialog();
	}

	// Resets the contact us form fields and links
	var dialog = $('#contact');
	dialog.find('#fill input, #fill textarea').attr('value', '');
	dialog.find('.buttons a').removeClass('clicked');
	dialog.find('#how, #fill').hide();
	dialog.css('margin-top', $(window).scrollTop() + 'px');
	dialog.fadeIn('fast');

	if(choose != undefined) {
		$('#choose .content ul.buttons li a#topic_'+choose).click();
		if(how != undefined) {
			$('#how #topic_'+choose+'_step2 ul.buttons li a#topic_'+choose+'_step2_'+how).click();
		}
	}
}

function showContactUsDialog() {
	if (!isOverlayOpen()) {
		return;
	}

	// Removes the click handler to prevent closing the popup window accidentally
	$('#overlay').unbind('click');
	$('#contact h2 a').click(hideContactUs);

	// Initializes the dialog box
	if (!window.contactSetUp) {
		initContactUsDialog();
	}

	// Resets the contact us form fields and links
	var dialog = $('#contact');
	dialog.find('#fill input, #fill textarea').attr('value', '');
	dialog.find('.buttons a').removeClass('clicked');
	dialog.find('#how, #fill').hide();
	dialog.css('margin-top', $(window).scrollTop() + 'px');
	dialog.fadeIn('fast');
}


function setCRMInterest(el){
		var container = el;
		var captcha = container.find(".captcha");
		Recaptcha.create(captcha.attr("publickey"), captcha.attr("id"), { theme: "clean" });
		$('#fill').show();
		container.find("form").show();
								
		$('#crm_interest').change(function() {
			if ($('#crm_interest').val() !== 'Power Plants') {
				$('#crm_interest_energy_wrapper').hide();
			} else {
				$('#crm_interest_energy_wrapper').show();
			};
	});
	
		var interest = $('#choose .buttons a.clicked').attr('id').split('_').pop();
		if (interest === 'energy') {
			$('#crm_interest').val('Power Plants');
		};
		if (interest === 'marine') {
			$('#crm_interest').val('Ship Power');
		};
		if (interest === 'services') {
			$('#crm_interest').val('Services');
		};
		$('#crm_interest_energy_wrapper').hide();
		if (interest === 'energy') {
			$('#crm_interest_energy_wrapper').show();
	};
}


/**
 * Initializes the contact us dialog.
 */
function initContactUsDialog() {
	var dialog = $('#contact');

	initTabsNavigators(dialog);
	
	dialog.find('#choose .buttons a').click(function() {
		dialog.find('#choose .buttons a').removeClass('clicked');
		$(this).addClass('clicked');
		$('#captcha_help').hide();

		if ($(this).attr('id') === 'topic_find') {
			return true;
		}

		dialog.find('#how .content, #fill').hide();
		dialog.find('#how .content#'+$(this).attr('id')+'_step2, #how').show();
		dialog.find('#how .buttons a ').removeClass('clicked');

		return false;
	});

	dialog.find('#how .buttons a').click(function() {
		dialog.find('#how .buttons a').removeClass('clicked');
		$(this).addClass('clicked');

		$('#captcha_help').hide();

		/* handle links */
		//if ($(this).attr('href') !== '#') {
			//return true;
		//};

		$('#fill').hide();
		$('#fill form').hide();

		var showForm = function() {
			var container = $(this);
			var captcha = container.find(".captcha");
			Recaptcha.create(captcha.attr("publickey"), captcha.attr("id"), { theme: "clean" });
			$('#fill').show();
			container.find("form").show();
		}
		
		var destination = $(this).attr('id').split('_').pop();
		switch (destination) {
			case 'research':
			case 'innovations':
			case 'power':
			case 'marine':
			case 'send':
			case 'inquiry':
			case 'responsibility':
			case 'enviromental':
			case 'feedback2':
				$('#form_general_container').loadPage('WCom/Contact/DisplayEmailForms', showForm);
				break;
			case 'contact':
			$('#form_crm_container').loadPage('WCom/Contact/DisplayCRMForm', function() {
							setCRMInterest($(this));
			}); 
				break;
			case 'supplier':
				$('#form_supplier_container').loadPage('WCom/Contact/DisplaySupplierForm', showForm);
				break;
			default:
				$('#fill').hide();
				return false;
				break;
		};

					
		/* pre-select interest */
		if (destination === 'contact') {
			var interest = $('#choose .buttons a.clicked').attr('id').split('_').pop();
			if (interest === 'energy') {
				$('#crm_interest').val('Power Plants');
			};
			if (interest === 'marine') {
				$('#crm_interest').val('Ship Power');
			};
			if (interest === 'services') {
				$('#crm_interest').val('Services');
			};
			$('#crm_interest_energy_wrapper').hide();
			if (interest === 'energy') {
				$('#crm_interest_energy_wrapper').show();
			};
		};

		return false;
	});

	window.contactSetUp = true;
}

/**
 * Hides the contact us popup window.
 */
function hideContactUs() {
	getOverlay().hide();
	$('#contact').hide();

	return false;
}

//hiding footer send form
function hideSendForm(){

    	getOverlay().hide();
    	$('.send_link').replaceWith('<div id="footer_send_form" style="display: none"></div>');

}
//generating captcha in send form
function showRecaptcha(element) {

	var publickeyval = $('#send_publickey').val();
	 Recaptcha.create(publickeyval, element, {
		theme: "clean",
		callback: Recaptcha.focus_response_field});
}

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}
//validates and submits supplier form
function validateSupplierFormOnSubmit(currentSupForm,supUrl,errList)
{

	var curSupForm = document.getElementById(currentSupForm);
	var formUrl = "";
	var emailError ="";
	var productvals = "";
	var envcertvals ="";
	var cname = trim(curSupForm.supplier_companyname.value);
	var cperson = trim(curSupForm.supplier_contactperson.value);
 	var email = trimAll(curSupForm.supplier_email.value);
	var zipcode = trim(curSupForm.supplier_zipcode.value);
        var city = trim(curSupForm.supplier_city.value);
	var country = curSupForm.supplier_country.value;
	var telephone = trim(curSupForm.supplier_telephone.value);
	var fax = curSupForm.supplier_fax.value;
	var doe = curSupForm.supplier_establishment.value;
	var numofemp = curSupForm.supplier_numberofemployees.value;
	var yrturnover = curSupForm.supplier_yearlyturnover.value;
  var currency = curSupForm.currency.value;
	var street = trim(curSupForm.supplier_street.value);
	var pobox =  trim(curSupForm.supplier_pobox.value);
	var website =  trim(curSupForm.supplier_website.value);
	var dun = trim(curSupForm.supplier_dun.value);
	var vatcode = trim(curSupForm.supplier_vatcode.value);
	var ownership = trim(curSupForm.supplier_ownership.value);
	var describe = trim(curSupForm.supplier_describe.value);
	var references = trim(curSupForm.supplier_references.value);
	var jventure = trim(curSupForm.supplier_jointventures.value);
	var othercerts = trim(curSupForm.supplier_certother.value);
	var otherprod = trim(curSupForm.sup_otherproducts.value);
	var recaptcha_response_field = trim(curSupForm.recaptcha_response_field.value);
	var recaptcha_challenge_field = trim(curSupForm.recaptcha_challenge_field.value);
	
	var htmlValue="";
        document.getElementById("SPFormReg").style.fontWeight = "bold";
        document.getElementById("SPFormReg").style.color = "red";
        var isError = new Boolean(false);


	var key;
	var errobject = new Object();
	var vallist;
	var maplist;
	maplist = 	errList.split("*=*");
	for(i=0;i<maplist.length-1;i++)
	{
		vallist = maplist[i].split("$=$");
		key = vallist[0];
		errobject[key] = vallist[1];
	}


if (curSupForm.recaptcha_response_field.value == "") {
			$('#sup_invalid_send_contact_recaptcha').show();
			isError = true;
			htmlValue+=errobject["recaptcha_response_field"]+"<br />";
		} else {
			document.getElementById("sup_invalid_send_contact_recaptcha").innerHTML = "";
			$('#sup_invalid_send_contact_recaptcha').hide();
	}
	document.getElementById("sup_invalid_send_contact_recaptcha").innerHTML = errobject["recaptcha_response_field"];
	
	
	if(errobject.size!=0)
	{

           if  (cname == '' || cname == null)
              {
                htmlValue+=errobject["supplier_companyname"]+"<br />";
                isError = true;
            }

		   if  (cperson == '' || cperson == null)
              {
                htmlValue+=errobject["supplier_contactperson"]+"<br />";

                isError = true;
            }

		   if  (zipcode == '' || zipcode == null)
              {
                htmlValue+=errobject["supplier_zipcode"]+"<br />";

                isError = true;
            }

		   if  (city == '' || city == null)
              {
                htmlValue+=errobject["supplier_city"]+"<br />";

                isError = true;
            }

			if (isNaN(numofemp))
              {
                htmlValue+=errobject["supplier_numberofemployees"]+"<br />";

                isError = true;
            }

			if (isNaN(yrturnover))
			{
				htmlValue+=errobject["supplier_yearlyturnover"]+"<br />";

		                isError = true;
			}

		//	if (((!yrturnover == '') || (!yrturnover == null)) && (currency == "CUR"))
		//     {
        //        htmlValue+="Please select the currency<br />";
        //        alert("yrturnover:"+htmlValue);
        //        isError = true;
        //    }

		   if  (country == '' || country == null || country == '-1')
              {
                htmlValue+=errobject["supplier_country"]+"<br />";

                isError = true;
            }

            var telephoneNo = trimAll(telephone);
	    if  (telephoneNo == '' || telephoneNo == null || isNaN(telephoneNo) )
            {
                htmlValue+=errobject["supplier_telephone"]+"<br />";
                 isError = true;
            }

	    var faxNo = trimAll(fax);
	    if(isNaN(faxNo))
		{
				htmlValue+=errobject["supplier_fax"]+"<br />";
				isError = true;
		}



	    if(email == "" || email == null)
            {
                htmlValue+=errobject["supplier_email"]+"<br />";
                isError = true;
            }
            else

            {
		if(!emailcheck(email)){
                	htmlValue+=errobject["supplier_email"]+"<br />";
                   	isError = true;
		}
            }

	    if(isNaN(doe))
		{
			htmlValue+=errobject["supplier_establishment"]+"<br />";
			isError = true;
		}
	}

	     if(isError == true)
	            {
				document.getElementById("SPFormReg").innerHTML=htmlValue+"<br /><br />";
				window.scrollTo(1,1);

	            }

	   if (isError == false)
           {
        	document.getElementById("SPFormReg").innerHTML="";
       		for (i=0; i<curSupForm.supplier_certificate.length; i++){
			if (curSupForm.supplier_certificate[i].checked==true)
					envcertvals += curSupForm.supplier_certificate[i].value+",";
				}

		 for (i=0; i<curSupForm.sup_products.length; i++){
			if (curSupForm.sup_products[i].checked==true)
				productvals += curSupForm.sup_products[i].value+",";
			}

			  formUrl = "companyname="+encodeURIComponent(cname);
			  formUrl += "&street="+encodeURIComponent(street);
			  formUrl += "&contactperson="+encodeURIComponent(cperson);
			  formUrl += "&zipcode="+encodeURIComponent(zipcode);
			  formUrl += "&telephone="+encodeURIComponent(telephone);
			  formUrl += "&city="+encodeURIComponent(city);
			  formUrl += "&country="+country;
			  formUrl += "&email="+encodeURIComponent(email);
			  formUrl += "&fax="+encodeURIComponent(fax);
			  formUrl += "&doe="+encodeURIComponent(doe);
			  formUrl += "&numofemp="+encodeURIComponent(numofemp);
			  formUrl += "&yrturnover="+encodeURIComponent(yrturnover);
			  formUrl += "&currency="+currency;
			  formUrl += "&pobox="+encodeURIComponent(pobox);
			  formUrl += "&website="+encodeURIComponent(website);
			  formUrl += "&dun="+encodeURIComponent(dun);
			  formUrl += "&vatcode="+encodeURIComponent(vatcode);

			  formUrl += "&ownership="+encodeURIComponent(ownership);
			  formUrl += "&describe="+encodeURIComponent(describe);
			  formUrl += "&references="+encodeURIComponent(references);
			  formUrl += "&jventure="+encodeURIComponent(jventure);

			  formUrl += "&selectedcerts="+envcertvals;
			  formUrl += "&othercerts="+encodeURIComponent(othercerts);

			  formUrl += "&selectedproducts="+productvals;
			  formUrl += "&otherprod="+encodeURIComponent(otherprod);
			  
			  formUrl += "&recaptcha_challenge_field="+recaptcha_challenge_field;
				formUrl += "&recaptcha_response_field="+recaptcha_response_field;

			  var url = supUrl+'&'+formUrl;
			  submitSupplierFormByAjax(url);

           }
         else
          {
          //alert("error");
			//return false;
		   }
}


//trims leading spaces
function trimAll(str){
	while(str.indexOf(" ") != -1)
		str = str.replace(" ","");
		return str;
}

//invokes supplier submit form

function submitSupplierFormByAjax(url)
{
	var xmlhttp=null;
	try
	{
		xmlhttp=new XMLHttpRequest();
	}
	catch(B)
	{
		try
		{
			xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
		}catch(B)
		{
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	xmlhttp.onreadystatechange=function()
	{
		if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{
			var restext = xmlhttp.responseText;
			var tokentxt = restext.split('\n');
			
			if(trim(restext).indexOf("recaptcha_error") != -1){
						// display error message
						$('#sup_invalid_send_contact_recaptcha').show();
						Recaptcha.reload();
						return false;
				} else if(trim(restext).indexOf("Failure") != -1){
					Recaptcha.reload();
					alertFormFailure();
					return false;
				} else {	
					alertFormSubmitSuccess();
					document.getElementById("form_supplier").reset();
					hideContactUs();
			}
		}
	}
	xmlhttp.open("GET",url,true);
	xmlhttp.send(null);
}


// calender popup in form builder
function showPopupCalendar(inputFieldId)
{
	doc = '<html><head><title>Calendar</title>';
	doc += '<link rel="stylesheet" type="text/css" href="/cs/static/zpcal/themes/aqua.css" title="Aqua"/>';
	doc += '<script type="text/javascript" src="/cs/static/zpcal/src/calendar.js"><\/script>';
	doc += '<script type="text/javascript" src="/cs/static/zpcal/lang/calendar-en.js"><\/script>';
	doc += '<script type="text/javascript">';
	doc += 'function parseDate(){';
	doc += 'var d = opener.document.getElementById("'+inputFieldId+'").value;';
	doc += 'var date = new Date();';
	doc += 'if (d.length == 16) d += ":00";';
	doc += 'if (d.length == 19) {';
	doc += 'date.setFullYear(d.substring(0,4));';
	doc += 'var firstCharMonth = parseInt(d.substring(5,6));';
	doc += 'if (firstCharMonth==0) date.setMonth(parseInt(d.substring(6,7))-1);';
	doc += 'else date.setMonth(parseInt(d.substring(5,7))-1);';
	doc += 'date.setDate(d.substring(8,10));';
	doc += 'date.setHours(d.substring(11,13));';
	doc += 'date.setMinutes(d.substring(14,16));';
	doc += 'date.setSeconds(d.substring(17,19));';
	doc += '}'; //end if
	doc += 'return date;';
	doc += '}'
	doc += 'function dateChanged(cal) {';
	doc += 'if (cal.dateClicked) {';
	doc += 'opener.document.getElementById("'+inputFieldId+'").value= cal.currentDate.print("%Y-%m-%d %H:%M:%S");';
	doc += 'window.close();}  }';
	doc += 'window.onload = function(){';
	doc += 'Zapatec.Calendar.setup({';
	doc += 'flat : "calendar-container",';
	doc += 'showsTime      : "seconds",';
	doc += 'date      : parseDate(),';
	doc += 'singleClick    : true,';
	doc += 'weekNumbers    : false,';
	doc += 'noHelp         : true,';
	doc += 'step           : 1,';
	doc += 'timeInterval   : 1,';
	doc += 'disableFdowChange : true,';
	doc += 'flatCallback   : dateChanged';
	doc += '});';
	doc += '}<\/script>';
	doc += '</head><body><div style="float: left; margin-right: 1em; margin-bottom: 1em;" id="calendar-container"><\/div>';
	doc += '<a href="javascript:self.close();"><img align="right" src="/cs/Xcelerate/graphics/en_US/button/content/images/close_window_small.gif" border="0" alt="Close Window"\><\/a>';
	doc += '<\/body><\/html>';
	calWindow = window.open("", 'Calendar', "width=240,height=270,status=no,resizable=no,left=450,top=300");
	calWindow.document.write(doc);
	calWindow.document.close();
}

// validating form on form builder funtionality
function validateForm(required,validate,errmsg,mapobj, postUrl)
{
	$('div#form_error_msg').hide();
	$('#recaptcha_error').hide();
	if(checkRequired(required,errmsg,mapobj)&& valiateFields(validate,errmsg,mapobj))
	{
			// now validate recaptcha
			if ($('#recaptcha_response_field').val() == "") {
					$('#recaptcha_error').show();
					return false;
				} else {
					$('#recaptcha_error').hide();
			}
			// Submits the form
			var form = $('#form_builder');
				jQuery.ajax({
					type: "post",
					url: postUrl,
					data: form.serialize(),
					success: function(data) {
						if(trim(data).indexOf("recaptcha_error") != -1){
							// display error message
							$('#recaptcha_error').show();
							Recaptcha.reload();
							return false;
						} else if(trim(data).indexOf("success") != -1){
							$('.form_bulder_area').replaceWith("<div>"+ formSubmitSuccess +"</div>");
							hideContactUs();
						} else {
							Recaptcha.reload();
							alertFormSubmitFailure();
							return false;
						}
					}
		});
	}
	else {
		document.getElementById('form_builder').focus();
		return false;
	}
}


//check required fields on form builder
function checkRequired(required,errmsg,mapobj)
{
	var list;
	var checkString="";
	list = 	required.split("*=*");
	var pass =true;
	var i=0;
	var missing= errmsg+'<br/>';
	var dropDown;
	var dropDownvalue;
	var key;
	var someobject = new Object()
	var vallist;
	var maplist;
	maplist = 	mapobj.split("*=*");
	for(i=0;i<maplist.length-1;i++)
	{
		vallist = maplist[i].split("$=$");
		key = vallist[0];
		someobject[key] = vallist[1];
	}
	for(i=0;i<list.length-1;i++)
	{
		var inputObj = document.getElementById(list[i]);

		if (inputObj.type=="select")
		{
			checkString=inputObj.options[inputObj.selectedIndex].value;
		}
		else
		{
			if (inputObj.type=="radio")
			{
				var getname=inputObj.name;
				var radioval =  document.getElementsByName(getname);
				var str;
				var bool = new Boolean(false);
				for(x=0;x<radioval.length;x++){
					if(radioval[x].checked) {
						str=radioval[x].value;
						bool=true;
					}
				}
				if(bool) {
					checkString=str;
				}
			}
			else
			{
				checkString=inputObj.value.trim();
			}
		}

		if((checkString==null)||(checkString==""))
		{
			pass=false;
			if(someobject.size!=0)
			{
				key = list[i];
				missing+="*"+someobject[key]+"<br/>";
			}
			//missing+="*"+document.getElementById(list[i]).name+"<br/>";
		}
	}

	/* Commented out by JF.  Uncomment when Recaptcha is working
	var capval = Recaptcha.get_response();
	if(capval==null || capval=="")
	{
		pass=false;
		missing+="*Captcha Text <br/>";
	}*/
	if(!pass)
	{
		$('div#form_error_msg').replaceWith('<div id="form_error_msg" style="color:red;">'+missing+'</div>');
	}
	return pass;
}


// validating fields on form builder
function valiateFields(validate,errmsg,mapobj)
{
	var list;
	list = 	validate.split("*=*");
	var message= errmsg+"<br/>";
	var invalidList="";
	var i=0;
	var par;
	var key;
	var pass=true;
	var someobject = new Object()
	var vallist;
	var maplist;
	maplist = 	mapobj.split("*=*");
	for(i=0;i<maplist.length-1;i++)
	{
		vallist = maplist[i].split("$=$");
		key = vallist[0];
		someobject[key] = vallist[1];
	}

	for(i=0;i<list.length-1;i++)
	{
		list[i]=list[i].trim();
		par=list[i].split("$=$");
		if(par[1]=="Email Address")
		{
			var str = document.getElementById(par[0]).value;
			if(str!=null && str!="" && !valiateEmail(par[0]))
			{
				key = par[0];
				invalidList+=someobject[key]+'<br/>';
			}
		}


	}


	if(invalidList!="")
	{
		pass=false;
		$('div#form_error_msg').replaceWith('<div id="form_error_msg" style="color:red;">'+message+invalidList+'</div>');
		return pass;
	}
// Commented out by JF.  Uncomment when Recaptcha is working, and remove the document.formbuilder.submit()
//	validateCaptcha(ipAddr,privatekey,message);
//	document.formbuilder.submit();
return true;
}

//email validation
function valiateEmail(id)
{

	var str=document.getElementById(id).value;
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	return	filter.test(str);
}

//captcha validation on form builder
function validateCaptcha(ipAddr,privatekey,message)
{
	var url="http://www.google.com/recaptcha/api/verify?privatekey="+privatekey+"&challenge="+Recaptcha.get_challenge()+"&response="+Recaptcha.get_response()+"&remoteip="+ipAddr;
	var xmlhttp=null;
	try
	{
		xmlhttp=new XMLHttpRequest();
	}
	catch(B)
	{
		try
		{
			xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
		}catch(B)
		{
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	xmlhttp.onreadystatechange=function()
	{

		if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{
			var restext = xmlhttp.responseText;
			var tokentxt = restext.split('\n');
			if(tokentxt[0]=='true'&& tokentxt[1]=='success')
			  {
				document.formbuilder.submit();
				return true;
			  }
			  else
			  {
				var msg='Catptch Text <br/>';
				Recaptcha.reload();
				$('div#form_error_msg').replaceWith('<div id="form_error_msg" style="color:red;">'+message+msg+'</div>');
				return false;
			  }

		}
	}

	xmlhttp.open("POST",url,true);
	xmlhttp.send();
	sleep(3000);
}

// restricts max length of text areas
function ismaxlength(obj){
	var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
	if (obj.getAttribute && obj.value.length>mlength)
	obj.value=obj.value.substring(0,mlength)
}




