function validateEmail(str) {
	var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]){2,}\.)+[a-zA-Z0-9]{2,4}$/;
	if(str.match(emailRegEx)){
		return true;
	} else {
		return false;
	}
}


function initialize() {	
	var centerLatLng = new google.maps.LatLng(41.203166, 16.558971);
	var markerLatLng = new google.maps.LatLng(41.199496, 16.558938);
	var myOptions = {
		zoom: 15,
		center: centerLatLng,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		mapTypeControlOptions: {
		style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
		}
	};
	var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

	var marker = new google.maps.Marker({
		position: markerLatLng, 
		map:      map, 
		title:    'Piping Technique s.r.l.'
	}); 
}

function loadScript() {
	if(!document.getElementById('map_canvas')) return;

	var script = document.createElement("script");
	script.type = "text/javascript";
	script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
	document.body.appendChild(script);
}
  
window.onload = loadScript;

//window.onload = function () { initialize(); }


jQuery(document).ready(function($){
	var search = $('#search-id').val();
	
	$('#search-id').focus(function() {
		if($(this).val() == search) {
			$(this).val('');
		}
	});
	
	$('#search-id').blur(function() {
		if($(this).val() == '') {
			$(this).val(search);
		}
	});
	
	$('#search').submit(function() {
		if($('#search-id').val() == search || $('#search-id').val() == '') {
			return false;
		}
	});
 	
	/*$("ul.topnav li a").click(function() {
		$(this).parent('li').find("ul.subnav").slideDown('fast').show();

		$(this).parent('li').hover(function() {
		}, function(){
			$(this).parent().find("ul.subnav").slideUp('normal'); 
		});

	}).hover(function() {
		$(this).trigger('click');
	}, function(){
	});*/
	
	$("ul.topnav").superfish({
		autoArrows:  false,
		delay:       800,                             // one second delay on mouseout 
		animation:   {opacity:'show',height:'show'},  // fade-in and slide-down animation 
		speed:       'fast',                          // faster animation speed 
		autoArrows:  false,                           // disable generation of arrow mark-up 
		dropShadows: false                            // disable drop shadows 			
	});
	
	$('.eml').html(function(i, html) {
		return '<a href="mailto:' + html + decodeURIComponent('%40') + 'pipingtechnique.it">' + html + decodeURIComponent('%40') + 'pipingtechnique.it</a>';
	});
	
	$('a.target-blank').attr('target', '_blank');
	
	var cache = [];
	
	// Arguments are image paths relative to the current page.
	$.preLoadImages = function() {
		var args_len = arguments.length;
		
		for (var i = args_len; i--;) {
			var cacheImage = document.createElement('img');
			cacheImage.src = arguments[i];
			cache.push(cacheImage);
		}
	}
	
	if($('a.iframe').length) {
		jQuery.preLoadImages(//'img/logo-background-small-loading.png',
		'img/logo-background-small-loading-it.png',
		'img/logo-background-small-loading-en.png');
	}
	
	$('a.iframe').fancybox({
		'width'				: '75%',
		'height'			: '75%',
        'autoScale'     	: false,
        'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'				: 'iframe'
	});
	
	
	/* Scroll product-summary */
	if($('#product-summary').scrollLeft() == 0) {
		$('#product-summary-scroll-left').addClass('hidden');
	}
	
	
	function checkAndscroll($this, sc, side) {
		var slBefore = $('#product-summary').scrollLeft()
		
		$('#product-summary').scrollLeft($('#product-summary').scrollLeft() + sc);
		
		var slAfter = $('#product-summary').scrollLeft();
		
		if(slBefore == slAfter) {
			$this.addClass('hidden');
		}
		
		$('#product-summary-scroll-' + side).removeClass('hidden');
	}
	
	
	$('#product-summary-scroll-left').click(function() {
		checkAndscroll($(this), -50, 'right');		
		return false;
	});
	
	
	$('#product-summary-scroll-right').click(function() {
		checkAndscroll($(this), 50, 'left');
		return false;
	});
	
	
	/* Contacts */
	$('#invia-id').removeClass('none');
	
	
	$('#invia-id').click(function() {
		$('#contacts label, #contacts .mandatory-fields').removeClass('bold');
		
		var error = 0;
		
		$('#contacts .mandatory').find('input, select').each(function(i) {
			if($(this).val() == '' || 
				$(this).is(':checkbox') && !$(this).is(':checked') || 
				$(this).attr('id') == 'email-id' && !validateEmail($(this).val())) {
				$('label[for="' + $(this).attr('id') + '"]').addClass('bold');
				$('.mandatory-fields').addClass('bold');
				error++;
			}
		});
		
		if(error) {
			$('#alert-msg').text(completeFields);
			$('#alert').dialog('open');
			return false;
		} else {
			$('#invia-id').attr('disabled', 'disabled');
		
			var messaggioInviato = 0;
			
			$('#contacts').ajaxSubmit({
				type: 'POST',
				url: pathPT + 'send-request.php',
				dataType: 'json',
				timeout: 90000,
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					$('#alert-msg').text(textStatus + ': ' + errorThrown);
					$('#alert').dialog('open');
					return false;
				},
				beforeSubmit: function(a,f,o) {
					$('#invia-id').hide();
					$('#wait-message').show();
					$('body').css('cursor', 'wait');
				},
				complete: function(XMLHttpRequest, textStatus) {
					$('#wait-message').fadeOut('slow', function() {
						$('#invia-id').show();
						
						if(messaggioInviato) {
							$('#contacts').find(':text, :file, textarea').val('').end().find('textarea').text('').end().find(':checkbox').attr('checked', '');
						} else {
							$('#invia-id').removeAttr('disabled');
						}
						$('body').css('cursor', 'default');
					});
				},
				success: function(data) {
					if(data.ok) {
						$('#alert-msg').text(requestSent);
						$('#alert').dialog('open');
						messaggioInviato = 1;
					} else {
						$('#alert-msg').text(data.error);
						$('#alert').dialog('open');
					}
				}
			});
		}
	});
	
	
	$('input').keyup(function(e) {
		checkFields();
	});	
	
	$('select').change(function() {
		checkFields();
	});
	
	$(':checkbox').click(function() {
		checkFields();
	});
	

	function checkFields() {		
		var error = 0;
		
		$('#contacts .mandatory').find('input, checkbox, select').each(function(i) {
			if($(this).val() == '' || $(this).is(':checkbox') && !$(this).is(':checked') || $(this).attr('id') == 'email-id' && !validateEmail($(this).val())) {
				error++;
			}
		});
		
		if(!error) {
			$('#invia-id').removeAttr('disabled');
		} else {
			$('#invia-id').attr('disabled', 'disabled');
		}
	}
	
	
	$('#alert').dialog({
		minWidth:  480,
		autoOpen:  false,
		modal:     true,
		draggable: true,
		resizable: false,
		buttons: {
			OK: function() {
				$(this).dialog('close');
			}
		}
	});
});
