/// <reference path="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1-vsdoc.js" />
var agent = navigator.userAgent.toLowerCase();
var touchOS = ('ontouchstart' in document.documentElement) ? true : false;
var mobileOS = typeof orientation != 'undefined' ? true : false;
var otherBrowser = (agent.indexOf("series60") != -1) || (agent.indexOf("symbian") != -1) || (agent.indexOf("windows ce") != -1) || (agent.indexOf("blackberry") != -1);
var iOS = (navigator.platform.indexOf("iPhone") != -1) || (navigator.platform.indexOf("iPad") != -1) ? true : false;
var android = (agent.indexOf("android") != -1) || (!iOS && !otherBrowser && touchOS && mobileOS) ? true : false;

// main navigation:
function initMainNav() {
	var innermainnav = $("ul#innermainnav");
	innermainnav.find(" > li").addClass("widthover").removeClass("over");
	innermainnav.find(" > .mainitem").hoverIntent({
		interval: 300, // milliseconds delay before onMouseOver
		over: showSubnav,
		sensitivity: 4,
		timeout: 300, // milliseconds delay before onMouseOut
		out: hideSubnav
	});

	// dealer locator submit.
	$(function() {
		$("#clicksubmit").click(function() {

			var plist = $("form#frmlocator select#productslist");
			var inputsearch = $("form#frmlocator input.insearch");
			var retvalue = false;
			var ret2value = false;

			if (plist.val() != "-1") {
				ret2value = true;
			};

			if (inputsearch.attr("orgvalue") != undefined) {
				if (inputsearch.attr("orgvalue") != inputsearch.val()) {
					retvalue = true;
				}
			}
			else {
				if (ret2value) {
					inputsearch.val("");
					retvalue = false;
				}
			}

			var docLocation = document.getElementById("frmlocator").action + "#cc=" + countrycode + "&searchIndex=0&qs=" + escape(inputsearch.val()) + "&prod=" + plist.val() + "&gmap=true&search=true";

			if (retvalue && ret2value) {
				inputsearch.val(escape(inputsearch.val()));
				$("form#frmlocator").submit();
			}
			else if (retvalue && !ret2value) {
				inputsearch.val(escape(inputsearch.val()));
				$("form#frmlocator").submit();
			}
			else if (!retvalue && ret2value) {
				$("form#frmlocator div.insearchstart").addClass("error");
			}
			else {
				$("form#frmlocator div.insearchstart").addClass("error");
			}
		});

	});

	// Prevent dealersearch dropdown from collapsing in IE
	if (!jQuery.support.noCloneEvent) {
		$("#productslist").hover(function() {
			event.cancelBubble = true;
		},
		function() {
			event.cancelBubble = true;
		});
	};

}

// product navigation:
function initProductNav() {
	$(function() {
		$("div#productsnav").addClass("activenav");
		if (!touchOS && !iOS && !android) $("div#productsnav ul li:not(.active) img").bubbleup({ tooltips: true });
	});
}

function showSubnav() {
	$(this).addClass("over posover");
	$("#productsnav").css("visibility", "hidden");
	$("#content").addClass("over");
	// subnavigation will align centered in IE6/7
	$(".innersubnav").each(function() {
		//$(this).replaceWith("<span class=\"innersubnav\">" + $(this).html() + "</span>");
	})

	//commented out, because this will add additional click events to existing ones
	//initPopupWindow();
	
	Cufon.replace('.brandMainNavigation .innersubnav p', { fontFamily: 'gftya' });
}

function hideSubnav() {
	$(this).removeClass("over posover");
	$("#productsnav").css("visibility", "");
	$("#content").removeClass("over");
}

function initGeneral() {
	// Add print functionality
	$("#print").click(function() {
		window.print();
	});

	// Reload page from select > option.
	$("select.reloadfromoption").change(function() {
		if ($(this).val() != "-1") {
			if($("#dclanguage").length == 1)
			{
				var oURL = window.location.href.split('?')[1];
				location.href = $(this).val() + "?" + oURL;
			}
			else
			{
				location.href = $(this).val();
			}
		}
	});

	// Focus input text events (Ger, 07-12-2009):
	$("input.inputtext").blur(function() {
		var orgValue = storeValue(this);
		if ($(this).val() == "") {
			$(this).val(orgValue);
		}
	});

	$("input.inputtext").focus(function() {
		var orgValue = storeValue(this);
		if ($(this).val() == orgValue) {
			$(this).val("");
		}
	});
	
	//CSS certificate IT add
	var urlVar = document.location;
	if(urlVar.toString().match(/\/it\//)){
		$("#footer").css({"height":"50px"});
		$("#innerfooter").append("<img class='isologo' src='http://cdn.yamaha-motor.eu/static/img/local/it/certo_logo.jpg'/>");
		$("#footernav").addClass("footernav");
		$(".footernav").css({"float":"left","margin":"0px"});
		$(".isologo").css({"float":"right"," position":"relative","padding-left":"20px"});
		$("#productsnav #products2 li.last").css({"display":"none"});
	}
	
	if(urlVar.toString().match(/\/ee\//) || (urlVar.toString().match(/\/is\//))|| (urlVar.toString().match(/\/lv\//))|| (urlVar.toString().match(/\/lt\//))|| (urlVar.toString().match(/\/baltic\//))){
	 $("#productsnav #products2 li").css({"display":"none"});
	 $("#productsnav #products2 li.last").css({"display":"block"});
	}
	//var urlVarLink = document.location;
	//if(urlVar.toString().match(/\/ee\//)&& (urlVarLink.toString().match(/\/is\//))){
	//}
	
	
	if((urlVar.toString().match(/\/fr\//)) && (!urlVar.toString().match(/\/be\/fr\//)) && (!urlVar.toString().match(/\/ch\/fr\//))){
		$("#productsnav #products2").css({"display":"none"});
		$("ul#products1 li a").slice(4, 5).attr('href', 'http://www2.yamaha-motor.fr/2011/bateau/');
	}
	
	if(urlVar.toString().match(/\/baltic\//)){
	 $("#productsnav #products2 li").css({"display":"none"});
	 $("#productsnav #products2 li.last").css({"display":"block"});
	}
	
	if(urlVar.toString().match(/\/hyper-modified\//)){
		$("a[href*='view=techspecs']").css({'display':'none'});
	}
	
	if(urlVar.toString().match(/\/designcafe\//)){
		$(".contentinnerwrap").css({"background":"url('http://cdn.yamaha-motor.eu/static/img/dcbackground.png') no-repeat scroll 101% 40px transparent"});
		$(".rightbar").css({"position":"relative","margin-top":"200px"});
		$(".content #content").css({"margin-top":"0"});
	}
	// Styles for active cufon links in galnav
	if ($("#innergalnav li").length) {
		$('#innergalnav li a').bind('click', function() {
			$(this).parent().addClass('active').siblings('li').removeClass('active');
			Cufon.refresh('#innergalnav li a');		
		}); 
	}
}

function initGallerybrowsing() {
	// homepage scrollable:	
	if ($(".home div.browsable0").length > 0) {
		if ($(".home div.browsable0").children().children('li').size() > 3) {
			// do some custom actions when scrolling occurs 
			var api = $(".home div.browsable0").scrollable({ size: 3, speed: 800, item: 'li', clickable: false }).circular().navigator().autoscroll({ api: true, autoplay: true, steps: 3, interval: 10000 });
			// we scroll 1 items forward 
			api.move(1);
			// scroll to the beginning in 1000 milliseconds 
			api.begin(1000);
		}
		else {
			$(".home div.browsable0").find(".gallerywrapper").find("> a.browse").addClass("disabled");
		}
	}
	if ($("div.browsable2").length > 0) {
		if ($("div.browsable2").children().children('li').size() > 2) {
			// do some custom actions when scrolling occurs 
			var api = $("div.browsable2").scrollable({ size: 2, speed: 800, item: 'li', clickable: false }).circular().navigator().autoscroll({ api: true, autoplay: false, steps: 2 });	
			// we scroll 1 items forward 
			api.move(1);
			// scroll to the beginning in 1000 milliseconds 
			api.begin(1000);		
		}
			else {
			$("div.browsable2").find(".gallerywrapper").find("> a.browse").addClass("disabled");
		}	
	}	
	if ($("div.browsable3").length > 0) {
		if ($("div.browsable3").children().children('li').size() > 1) {
			// do some custom actions when scrolling occurs 
			var api = $("div.browsable3").scrollable({ size: 1, speed: 800, item: 'li', clickable: false }).circular().navigator().autoscroll({ api: true, autoplay: false, steps: 1 });
			// we scroll 1 items forward 
			api.move(1);
			// scroll to the beginning in 1000 milliseconds 
			api.begin(1000);
		}
		else {
			$("div.imagegalleryWrapper").find(".gallerywrapper").find("> a.browse").addClass("disabled");
		}	
	}
	if ($("div.browsable4").length > 0) {
		var $browsable4 = $("div.browsable4");
		if (typeof TourLocator == "undefined") {
			if($browsable4.find("ul").children().length <= 5){
				var pixels = ( 5 - $browsable4.find("ul").children().length) * 42 ;
				$(".gallerywrapper").find("> a.browse").addClass("disabled");
				$browsable4.find("ul").css("margin-left",pixels + "px");
			}
			else
			{
				$browsable4.scrollable({ size: 1, speed: 800, item: 'li', clickable: false }).navigator();
			}

			$(".gallerywrapper a.browse").click(function()
				{
					var browser = $(this).parent().find("div.browsable4").data("scrollable");
					var amount = browser.getPageAmount();
					var ind = browser.getIndex();
					if(amount - ind <= 5)
					{
						$(this).parent().find("a.nextPage").addClass("disabled");
					}
					else
					{
						$(this).parent().find("a.nextPage").removeClass("disabled");
					}
				}
			)
		}	
	}
	else {
	    // default scrollable:
	    if ($("div.browsable").length > 0) {
	        var isProductPage = $("#localnav").length > 0;
	        $("div.browsable").each(function () {
	            // when product page (full width gallery) thumbs shown is max 7, else 5
	            // disable navigation when less than that
	            //var thumbCount = isProductPage == true ? 7 : 5;
	            if ($(this).find("ul").children().length <= 7) {
	                var pixels = (7 - $(this).find("ul").children().length) * 40;
	                $(this).parent().find("a.browse").addClass("disabled");
	                $(this).find("ul").css("margin-left", pixels + "px");
	            }
	            else {
	                $(this).scrollable({ size: 7, speed: 800, item: 'li', clickable: false }).navigator();
	            }
	        }
			)
	    }
	}

	// grid view scrollable:
	if ($("div#browsable1").length > 0) {
		$("div#browsable1").scrollable({ size: 1, speed: 800, item: 'li', clickable: false }).navigator();
	}

	// vertical scrollable:
	if ($("div#vrtcalbrowsable").length > 0) {
		$("div#vrtcalbrowsable").scrollable({ vertical: true, size: 1, speed: 800, item: 'li', clickable: false }).navigator();
	}

	// fix for slider when there are an uneven # of banners
	// add row2 class to second row for uneven amounts of banner items
	$('div.panelproduct div.gallerywrapper').children('div.scrollable:even').addClass('row2');

	// add empty li tag to 2nd row to even it up
	$('div.panelproduct div.gallerywrapper').each(function() {
		// if there are 2 rows
		if ($(this).children('div.scrollable').size() == 2) {
			// if li count is not the same then add an empty li tag to the 2nd div scrollable
			var firstRowLength = $(this).children('div.scrollable:eq(0)').children('.items').children('li').size();
			var secondRowLength = $(this).children('div.scrollable:eq(1)').children('.items').children('li').size();

			if (firstRowLength != secondRowLength) {
				$(this).children('div.scrollable:eq(1)').children('.items').append('<li></li>');
			}
		}
		// if there are 6 items
		if ($(this).children().children().children('li').size() == 6) {
			$(this).find("> a.right").addClass("disabled");
		}
	});
}

function storeValue(element) {
	if (typeof ($(element).attr("orgvalue")) == "undefined") {
		$(element).attr("orgvalue", $(element).val());
	};
	return $(element).attr("orgvalue");
}

function initSwapImg() {
	$(".bookmarks img.add")
		.mouseover(function() {
			var src = $(this).attr("src").match(/.*(?=\.)/) + "-over.png";
			$(this).attr("src", src);
		})
		.mouseout(function() {
			var src = $(this).attr("src").replace("-over", "");
			$(this).attr("src", src);
		});
}

function initTooltip() {
	$(".addproducts .category").hoverIntent({
		interval: 200, // milliseconds delay before onMouseOver
		over: showTooltip,
		sensitivity: 4,
		timeout: 200, // milliseconds delay before onMouseOut
		out: hideTooltip
	});

	$(".addproducts .selectedcategory").hover(function() {
		$(this).removeClass("over");
	});

	$(".bookmarks .bookmark").hoverIntent({
		interval: 100, // milliseconds delay before onMouseOver
		over: showTooltip,
		sensitivity: 4,
		timeout: 100,
		out: hideTooltip
	});
	
	$(".accesoriesList .tip").hoverIntent({
		interval: 50, // milliseconds delay before onMouseOver
		over: showTooltip,
		sensitivity: 4,
		timeout: 50,
		out: hideTooltip
	});

	$("ul.innerLocalNav>li:last-child").addClass("lastitem");

	$("ul.innerLocalNav>li.lastitem").hoverIntent({
		interval: 100,
		over: showTooltip,
		sensitivity: 4,
		timeout: 100,
		out: hideTooltip
	});
}

function showTooltip() {
	$(this).addClass("over");
}

function hideTooltip() {
	$(this).removeClass("over");
}

function initTabs() {
	if (document.getElementById("sitemap")) {
		// Sitemap navigation
		var tabs = $("#tabsnav li");
		var tabpages = $("#sitemap div.columns");
		var headings = $(tabpages).find("h2.min");

		// Close all pages and show first
		$(tabpages).addClass("closed");
		$(tabpages[0]).removeClass("closed");

		$("#gotoAcc").click(function (e) {
		    $("#tabsnav li").removeClass("active");
		    $("#generalblock").addClass("closed");
            	    $("#accblock").removeClass("closed");
		    $("#acc").addClass("active");
		    return false;
		});
		
		$("#goToProducts").click(function (e) {
		    $("#tabsnav li").removeClass("active");
		    $("#generalblock").addClass("closed");
            $("#productsblock").removeClass("closed");
		    $("#products").addClass("active");
		    return false;
		});
		
		// Add click-handlers to tabs
		$(tabs).find("a").click(function(e) {
			$(tabs).removeClass("active");
			$(tabpages).addClass("closed");
			$(this).parent().addClass("active");
			$(e.currentTarget.hash).removeClass("closed");

			// Toggle 'expand all' link visibility
			if ($(this).parent().attr("id") == "general") {
				$("#expand").css("visibility", "hidden");
			} else {
				$("#expand").css("visibility", "");
			}
			return false;
		});

		// Close all headings from tabpage 2 & 3 (products & accessories)
		$(headings).addClass("plus").removeClass("min");
		$(headings[0]).addClass("min").removeClass("plus");
		//$(headings).find("+ div").addClass("closed");
		$("#sitemap div.columns h2.plus + div").addClass("closed");

		// Open first panel of tabpage 2 & 3 (products & accessories)
		// $("#productsblock h2").eq(0).addClass("min").removeClass("plus");
		$("#sm-products1").removeClass("closed");
		$("#accblock h2").eq(0).addClass("min").removeClass("plus");
		$("#sm-accessories1").removeClass("closed");

		// Toggle panels on heading click
		$(headings).click(function(e) {
			$(this).toggleClass("plus").toggleClass("min");
			//$(this).find("+ div").toggleClass("closed");
			$(this).nextUntil("h2").toggleClass("closed");
			return false;
		});

		// Expand/collapse link functionality
		$("#expand").addClass("plus").removeClass("min").css("visibility", "hidden");
		$("#expand").click(function(e) {
			if ($(this).hasClass("plus")) {
				$(this).toggleClass("plus").toggleClass("min").text(typeof (txtCollapseAll) != "undefined" ? txtCollapseAll : "collapse all");
				$(headings).removeClass("plus").addClass("min");
				$("#productsblock > div").removeClass("closed");
				$("#accblock > div").removeClass("closed");
			} else {
				$(this).toggleClass("min").toggleClass("plus").text(typeof (txtExpandAll) != "undefined" ? txtExpandAll : "expand all");
				$(headings).addClass("plus").removeClass("min");
				$("#productsblock > div").addClass("closed");
				$("#accblock > div").addClass("closed");
			}
			return false;
		});
	}
	if (document.getElementById("selectblocks")) {
		var tabs = $("#tabsnav li");
		var tabpages = $("#selectblocks div.columns");

		// Close all pages and show first
		$(tabpages).addClass("closed");
		$(tabpages[0]).removeClass("closed");
		addClickHandlers();	
	}
	if (document.getElementById("socialMediaTabs")) {
		var tabs = $("#tabsnav li");
		var tabpages = $("#socialMediaTabs .tabscontent");

		// Close all pages and show first
		$(tabpages).addClass("closed");
		$(tabpages[0]).removeClass("closed");
		addClickHandlers();	
	}
	if (document.getElementById("tourlocatorTabs")) {
		var tabs = $("#tabsnav li");
		var tabpages = $("#tourlocatorTabs .tabscontent");

		// Close all pages and show first
		$(tabpages).addClass("closed");
		$(tabpages[1]).removeClass("closed");
		addClickHandlers();	
	}
	if (document.getElementById("mediaTabs")) {
		var tabs1 = $("#innergalnav li");
		var tabpages1 = $("#mediaTabs .tabscontent1");

		// Close all pages and show first
		$(tabpages1).addClass("closed");
		$(tabpages1[0]).removeClass("closed");
		// Add click-handlers to tabs
		$(tabs1).find("a").click(function(e) {
			$(tabs1).removeClass("active");
			$(tabpages1).addClass("closed");
			$(this).parent().addClass("active");
			$(e.currentTarget.hash).removeClass("closed");
			return false;
		});
	}
	
	function addClickHandlers (){
		// Add click-handlers to tabs
		$(tabs).find("a").click(function(e) {
			$(tabs).removeClass("active");
			$(tabpages).addClass("closed");
			$(this).parent().addClass("active");
			$(e.currentTarget.hash).removeClass("closed");
			return false;
		});
	}
}

function initPanels() {
	if (document.getElementById("panels")) {
		// Panels navigation        
		var tabpages = $("#panels div.panelcontent");
		var headings = $("#panels").find("h2");
		var category = getQueryStringValue('category');

		// Close all panels
		$(tabpages).addClass("closed");
		$(headings).addClass("headclosed");

		// Check for category and open panel
		if (category != undefined && $("#panel" + category).length > 0) {
			var panel = $("#panel" + category);
			$(panel).find("h2.headclosed").addClass("headopen");
			$(panel).find("div.panelcontent").removeClass("closed");
		} else {
			// Open first panel
			$(headings[0]).addClass("headopen");
			$(tabpages[0]).removeClass("closed");
		}

		// Toggle panels on heading click
		$(headings).click(function(e) {
			var isOpen = $(this).is('.headopen');
			$(headings).removeClass('headopen').addClass('headclosed');
			$(tabpages).addClass("closed");

			if (!isOpen) {
				$(this).removeClass("headclosed").addClass("headopen").find("+ div").removeClass("closed");
			}
			return false;
		});
	}
}

function initTables() {
	$("table.table1 tbody tr:last-child").addClass("lastrow");

	$("table.table1").each(function() {
		if (!$(this).parent().hasClass("divtable1")) {
			$(this).wrap('<div class="divtable1"></div>');
		}
	});

	$("table.table2").each(function() {
		if (!$(this).parent().hasClass("divtablebttm2")) {
			$(this).wrap('<div class="divtable2"></div>').wrap('<div class="divtablebttm2"></div>');
		}
	});
	$("table.table2 tbody tr:last-child").addClass("lastrow");
	$("table.table2 tbody").children("tr:odd").addClass("odd");
}

function initImagethumbs() {
	$(".category a").hover(function() {
		$(this).addClass("over");
	},
	function() {
		$(this).removeClass("over");
	});
}

function initLogin() {
	$("#frmLogin").submit(function() {
		var email = $(this).find("#txtEmailAddress");
		var pwd = $(this).find("#txtPassword");
		var message = "";

		if (!IsEmail(email.val())) {
			email.parent().addClass("error");
			message = "Emailaddress not correct. ";
		}
		else {
			email.parent().removeClass("error");
		}

		if (pwd.val().length < 2) {
			pwd.parent().addClass("error");
			message += "Enter your password.";
		}
		else {
			pwd.parent().removeClass("error");
		}

		if (message == "") {
			return true;
		}
		else {
			$(this).find(".noLabel").html(message);
		}
		return false;
	});

	$("#frmPassword").submit(function() {
		var email = $(this).find("#txtForgotEmail");
		var message = "";

		if (!IsEmail(email.val())) {
			email.parent().addClass("error");
			message = "Emailaddress not correct. ";
		}
		else {
			email.parent().removeClass("error");
		}

		if (message == "") {
			return true;
		}
		else {
			$(this).find(".noLabel").html(message);
		}
		return false;
	});
};

function IsEmail(email) {
	if (email.length > 0) {
		var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		return regex.test(email)
	}
	return false;
};

// Handle PNG transparency for images in Win IE 5.5 & 6.
function initCorrectPNG() {
	var arVersion = navigator.appVersion.split("MSIE")
	var version = parseFloat(arVersion[1])
	if ((version <= 6.0) && (document.body.filters)) {
		for (var i = 0; i < document.images.length; i++) {
			var img = document.images[i]
			var imgName = img.src.toUpperCase()
			if (imgName.substring(imgName.length - 3, imgName.length) == "PNG") {
				var imgID = (img.id) ? "id='" + img.id + "' " : ""
				var imgClass = (img.className) ? "class='" + img.className + "' " : ""
				var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
				var imgStyle = "display:inline-block;" + img.style.cssText
				if (img.align == "left") imgStyle = "float:left;" + imgStyle
				if (img.align == "right") imgStyle = "float:right;" + imgStyle
				if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
				var strNewHTML = "<span " + imgID + imgClass + imgTitle
			+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
			+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
			+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
				img.outerHTML = strNewHTML
				i = i - 1
			}
		}
	}
}

function initPopupWindow() {
	$('.printview').click(function() {
		window.print();
	});

	$('a.extern').click(function() {
		window.open(this.href);
		return false;
	});

    if ($("a.extern-disclaimer").length > 0) {
        $("#promptLeaveSite a.cancel").addClass("close");
        $("#promptLeaveSite a.cancel").attr("href", "javascript:void(0)");
        $("#promptLeaveSite a.cancel").click(function (e) {
            $(this).parent().hide();
			$("#externalLinkLayer").hide();
        });
        var externalLinkUrl = "";
		
		// create transparent layer
		var modalOverlay = $("div#externalLinkLayer");
		if (modalOverlay.length == 0) {
			modalOverlay = $("<div id=\"externalLinkLayer\"></div>");
			var style = "height:" + $(document).height() + "px; width:" + $(document).width() + "px;";
			style+= "position:absolute; top:0; left:0; display:none;z-index:10000";
			modalOverlay.attr("style", style);
			modalOverlay.click(function (e) {
				$(this).hide();
				$("#promptLeaveSite").hide();
			});
			modalOverlay.appendTo("body");
		}
		
        $("a.extern-disclaimer").click(function (e) {
			externalLinkUrl = $(this).attr("href");
			$("#externalLinkLayer").show();
			var left = ( $(document).width() - $("#promptLeaveSite").width() ) / 2;
			var top = $(window).scrollTop() + (( $(window).height() - $("#promptLeaveSite").height() ) / 2);
			$("#promptLeaveSite").attr("style", "top:" + top + "px; left:" + left + "px; z-index:11000");
			$("#promptLeaveSite").show();
			return false;
        });
		
        $("#promptLeaveSite button").click(function (e) {
            $("#promptLeaveSite a.cancel").trigger("click");
            window.open(externalLinkUrl, "");
        });
	}
}

function initOverlay() {

	function createOverlay() {
		var modalOverlay = $("div#overlay");

		if (modalOverlay.length == 0) {
			modalOverlay = $("<div class=\"overlay sendoverlay\" id=\"overlay\"><div class=\"close\">&#160;</div><div class=\"contentWrap\">&#160;</div></div>");
			modalOverlay.appendTo("body");
		}
		//else {
		//modalOverlay = overlay.html();
		//}

		return modalOverlay;
	};

	// if the function argument is given to overlay,
	// it is assumed to be the onBeforeLoad event listener	
	if ($("a#sendtofriend, a.sendtofriend").length > 0) {
		createOverlay();

		$("a[rel]").overlay({
			//top: '80%',
			left: 'center',
			absolute: false,
			//absolute: true,
			expose: {
				color: '#fff',
				loadSpeed: 100,
				opacity: 0.8
			},
			closeOnClick: true,

			// target element to be overlayed. by default taken from [rel]
			target: null,
			onBeforeLoad: function() {
				// grab wrapper element inside content
				var wrap = this.getContent().find(".contentWrap");

				// load the page specified in the trigger
				var params = { action: "sendtofriend", link: location.href, title: document.title, pubId: publicationID};

				var ajaxHtml = wrap.load(getHandler(this), params, function() {
					$(this).find("form").submit(function() {
						if (validateFriendForm($(this))) {
							emailFriendForm($(this));
						};
						return false;
					});
				});
			}
		});
	}
	
	if ($("a.wishlist").length > 0) {
		createOverlay();
		$("a[rel]").overlay({
			top: '29%',
			left: '66%',
			absolute: true,
			//expose: { 
			//color: '#fff', 
			//loadSpeed: 100, 
			//opacity: 0.1
			//}, 		

			closeOnClick: false,
			// target element to be overlayed. by default taken from [rel]
			target: null,
			onBeforeLoad: function() {
				// grab wrapper element inside content
				var wrap = this.getContent().find(".contentWrap");
				// load the page specified in the trigger
				wrap.load(this.getTrigger().attr("href"));
			}
		});
	}
	
	function getHandler(button) {
		var href = button != null ? button.getTrigger().attr("href") : "";

		if (typeof siteurl != "undefined") {
			href = siteurl + "/handlers/ajaxhandler.ashx";
		}
		return href;
	};

	function emailFriendForm(fform) {
		var emailto = $(fform).find(".emailto");
		var emailfrom = $(fform).find(".emailfrom");
		var emailsubj = $(fform).find(".emailsubject");
		var emailmsg = $(fform).find(".emailmessage");
		var emaillink = $(fform).find(".emaillink");

		var params = { action: "sendtofriendmail", emailfrom: emailfrom.val(), emailto: emailto.val(), link: emaillink.attr("href"), title: emaillink.text(), subject: emailsubj.val(), message: emailmsg.val(), pubId: publicationID };
		fform.parent().load(getHandler(null), params);
	}

	function validateFriendForm(fform) {
		var emailto = $(fform).find(".emailto");
		var emailfrom = $(fform).find(".emailfrom");
		var emailsubj = $(fform).find(".emailsubject");
		var label = $(fform).find(".noLabel");

		var message = "";

		if (!IsEmail(emailto.val())) {
			emailto.parent().addClass("error");
			message = "<li>Email 'from' not correct.</li>";
		}
		else {
			emailto.parent().removeClass("error");
		}

		if (!IsEmail(emailfrom.val())) {
			emailfrom.parent().addClass("error");
			message += "<li>Email 'to' not correct.</li>";
		}
		else {
			emailfrom.parent().removeClass("error");
		}

		if (emailsubj.val().length < 3) {
			emailsubj.parent().addClass("error");
			message += "<li>Enter subject.</li>";
		}

		if (message == "") {
			return true;
		}
		else {
			label.html("<ul>" + message + "</ul>");
		}
		return false;
	};
}

function initHideNav() {
/*
last update 191011
*/
if (self != top) {	
	jQuery.each(jQuery.browser, function(i) {
	   if($.browser.msie){
			if($("#flashcontent").length){
			$txtH = $("#flashcontent").height();
			//alert($txtH);
			$topN = $txtH+150;
			}else{
			$topN= 420;
			}
			$(".splitColumns").css({"width":"300px","position":"absolute","float":"right","right":"30px"});
			$(".visualandtext").css({"overflow":"visible"});
	   }else{
			$(".splitColumns").css({"width":"300px","position":"absolute","float":"left","right":"30px"});
			$(".splitColumns .line").css({"width":"300px"});
			$(".splitColumns .line .line,.visualandtext").css({"float":"left"});
			$(".imgdivright").css({"padding-right":"30px"});
			$(".visualandtext .innervisualandtext img").css({"margin-left":"-200px"});
		}
	});
		if(!$(".selectproducts").length){
		$(".maincontent p,.maincontent h2").css({"width":"540px","float":"left"});
		}
		
		$(".cols4").css({"width":"150px"});
		$(".rightbar,.Btnblock,.linkbox").css({'display':'none'});
		$(".breadcrumbs li:eq(0),.breadcrumbs li ul").css({"display":"none"});
		$(".icons,.banners").css({"visibility":"hidden","left":"-9999px"});
		$("a[href*='view=download'],.detailimages1,.flashcontent,.moreVideos").css({'display':'none'});
		$(".innercontent,#productsnav,.topnav,#content,.video").css({"background":"white"});
		/*$(".innercontent").css({"padding-bottom":"600px"});*/
		
		$(".topnav,.contentwrap").css({"padding":"0px 10px 0 10px"});
		$(".maincontent").css({"width":"940px"});
		$(".innervisualandtext").css({"position":"relative","float":"right","right":"75px","width":"920px"});
		$(".leftcol").css({"width":"250px"});
		$(".rightcol").css({"position":"relative","float":"right","width":"540px"});
		//tables
		$("table.table1").css({"background-image":"url('http://cdn.yamaha-motor.eu/static/img/table4-top.png')","width":"889px","padding":"0"});
		$(".divtable1").css({"background-image":"url('http://cdn.yamaha-motor.eu/static/img/table4-bottom.png')"});
		$(".table1 tbody th").css({"width":"300px"});
		$(".pricetable").css({"background-image":"url('http://cdn.yamaha-motor.eu/static/img/table1-top.png')","width":"584px"});
		if($(".divtable1 .pricetable").length){
		 $(".divtable1").css({"background-image":"url('http://cdn.yamaha-motor.eu/static/img/table1-bottom.png')"});
		} 
		
		if ($(".topnav").length) {
			$("#ctl00_ctl00_pnlWrapper").addClass("nonav1");
		} else {
			$("#ctl00_ctl00_pnlWrapper").addClass("nonav");
		}
	}
}

function getQueryStringValue(key) {
	var querystring = window.location.search.substring(1);
	var params = querystring.split("&");
	var param;
	for (i = 0; i < params.length; i++) {
		param = params[i].split("=");
		if (param[0] == key) {
			return param[1];
		}
	}
}

function goTo(url) {
	document.location.href = url;
	return false;
}

/* product selector functions */
function setFlashSize(width, height) {
	swffit.fit("productSelector_inner", width, height, width, height, false, false);
}

function showAreaJQ(top, bottom) {
    //posCorrection = the correction needed for the autoscrolling beacuase different position of flash. 200pixels in this case
    var posCorrection = 200;
    var scrollY = $(window).scrollTop();
	var windowHeight = $(window).height();
	if ((top + posCorrection) < scrollY) {
	    scrollTo(0, (top + posCorrection));
	}
	else if ((bottom + posCorrection) > (scrollY + windowHeight)) {
	    scrollTo(0, (bottom + posCorrection + 5) - windowHeight);
	}
}

function showArea(top, bottom) {
	var scrollY = getScrollY();
	var windowHeight = getWindowHeight();
	if (top < scrollY) {
		scrollTo(0, top);
	}
	else if (bottom > scrollY + windowHeight) {
		scrollTo(0, bottom + 5 - windowHeight);
	}
}

function getWindowHeight() {
	var myWidth = 0, myHeight = 0;
	if (typeof (window.innerWidth) == 'number') {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return myHeight;
}
/* end product selector functions */

function getScrollY() {
	var scrOfX = 0, scrOfY = 0;
	if (typeof (window.pageYOffset) == 'number') {
		//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}
	return scrOfY;
}
function initCheckBoxes() {
	// check for what is/isn't already checked and match it on the fake ones
	$("input[type=checkbox]").each(function() {
		(this.checked) ? $("#alt" + this.id).addClass('altchecked') : $("#alt" + this.id).removeClass('altchecked');
	});
	// function to 'check' the fake ones and their matching checkboxes
	$(".altcheck").click(function() {
		($(this).hasClass('altchecked')) ? $(this).removeClass('altchecked') : $(this).addClass('altchecked');
		$(this.hash).trigger("click");
		return false;
	});
}

function initScrollPane() {
	if ($(".scroll-pane").length > 0) {
		$(".scroll-pane").jScrollPane({ showArrows: true, scrollbarWidth: 9, arrowSize: 12 });
	}
};

function initFancybox() {
	if ($(".openImage").length) {	
		$(".openImage").fancybox({
			'padding'			: 0,
			'autoScale'			: false,
			'overlayShow'		: false
		});
	}
	if ($(".openContent").length) {	
		$(".openContent").fancybox({
			'width'				: '75%',
			'height'			: '75%',
			'autoScale'			: false
		});
	}
}

function initYTVideo() {
	if ($(".openVideo").length) {
	    $(".openVideo").click(function (e) {
            $("#frmYoutube").attr("src", this.href);
            $(".galleryLeft").animate({ height: '339px' }, 400);
	        $(".imagegalleryWrapper .scrollable").animate({ height: '376px' }, 400);
	        $(".youTubeVideo").show();
	        e.preventDefault();
	    });	 
		$(".youTubeVideo .close").bind("click", function(e){			
			$(".youTubeVideo").hide();		
			$(".galleryLeft").animate({height: '268px'}, 200);
			$(".imagegalleryWrapper .scrollable").animate({height: '303px'}, 200);							
			e.preventDefault();				
		});	 
		$(".imagegalleryWrapper .browse").bind("click", function(e){			
			if ($(".youTubeVideo").is(":visible")){
				$(".youTubeVideo").hide();		
				$(".galleryLeft").animate({height: '268px'}, 200);
				$(".imagegalleryWrapper .scrollable").animate({height: '303px'}, 200);							
				e.preventDefault();
			}
		});	
	}
}

function initFlashVideo() {
	if ($(".flashVideo").length) {		
		$(".playVideoButton").bind("click", function(e){
			$(".flashVideo").animate({height: '100%'}, 700).fadeIn(700);
			$(".content1 #content").animate({marginTop: '543px'}, 700); 
			$(".flashPlaceholder").fadeOut(700);
			$(".productExperience .flashcontent .close").show();
			$(this).hide();									
			e.preventDefault();				
		});	
		$(".productExperience .flashcontent .close").bind("click", function(e){		
			$(".flashVideo").hide();
			$(".content1 #content").animate({marginTop: '403px'}, 700); 
			$(".flashPlaceholder").fadeIn(700);
			$(".productExperience .flashcontent .close").hide();
			$(".playVideoButton").show();									
			e.preventDefault();		
		});
	}
}

function initFooter() {
	if (!$("#flashProductSelector").length) {
		var fheight = $("#footer");
		var wheight = $(window).height();
		var fposition = fheight.position();

		if (fposition.top < wheight) {
			$(".innercontent").css("height", wheight - 260 + "px");
		}
	}
}

function initPdfBox() {
	if ($("a.pdfbox").length > 0) {
		var tabs = $("div.printbox ul").children();
		tabs.each(function() {
			var ul = $(this).find("ul");
			$(this).hover(function()
				{
					ul.slideDown('fast', function() {});
				},function()
				{
					ul.hide();
				}
			)
		})
	}
}

function enableFeatureMouseOver() {

	// first we fetch the feature data from the <li> items and created <div>'s outside the <li>, to prevent buggy handling/flickering when hovering
	$('div.featureApp li').each(function(index) {
	
		$(this).css('opacity', 0);
		$(this).css('display', 'block');
		//Grab the title attribute's value and assign it to a variable
		var html = $(this).html();
		
		var tooltipDiv = $( document.createElement("div") );
		tooltipDiv.attr("class", "featureTooltip");
		//tooltipDiv.attr("style", "display:none;");
		tooltipDiv.append(html);
		
		// Find the overview image so the height and width can be determined
		var image = $(this).parent().parent().find('img.featureImage');
		
		image.parent().append(tooltipDiv);
		// Replace the h2 tekst for cufon font
		Cufon.replace('div.featureTooltip h2', { fontFamily: 'gftya' });
		
		var imagewidth = image.attr("width");
		var imageheight = image.attr("height");
		
		// Get the absolute position of the li's
		var positiontop = $(this).position().top;
		var positionleft = $(this).position().left;
		
		// Get the height and width of the tooltip to show
		var tooltipheight = tooltipDiv.height();
		var tooltipwidth = tooltipDiv.width();
		
		// set default values for position of tooltip & arrow image
		var tooltippositiontop = 0;
		var tooltippositionleft = 55;
		var arrowverticalposition = 0;
		var arrowhorizontalposition = 0;
		
		var featureimageheight = $(this).find('img').height();	
		
		// reset top position of tooltip and arrow image when too far up(100 pixels above the image is allowed)
		if(positiontop - featureimageheight <= -100 && featureimageheight != 0) {
			featureimageheight = -5;
			var featureimage = tooltipDiv.find('img');
			tooltipDiv.find('img').remove();
			tooltipDiv.append(featureimage);
		}
				
		arrowverticalposition = arrowverticalposition + (featureimageheight + 10);
				
		// reset left position of tooltip when too far to the right
		if((positionleft + tooltipwidth + tooltippositionleft) > imagewidth)
		{
			tooltippositionleft = - tooltipwidth - 5;
			arrowhorizontalposition = tooltipwidth;
			if ($(this).find("div span").length == 0) tooltipDiv.append("<span class=\"tooltipArrowRight\" style=\"top:"+ arrowverticalposition + "px; left:" + arrowhorizontalposition + "px\">&#160;</span>");
		}
		else
		{
			tooltipDiv.addClass("align-left");
			if ($(this).find("div span").length == 0) tooltipDiv.append("<span class=\"tooltipArrowLeft\" style=\"top:"+ arrowverticalposition + "px; left: -11px\">&#160;</span>");
		}
		
		tooltippositiontop = tooltippositiontop + positiontop;
		tooltippositionleft = tooltippositionleft + positionleft;
		tooltippositiontop = tooltippositiontop - featureimageheight;
		tooltipDiv.css("top", tooltippositiontop + 5);
		tooltipDiv.css("left", tooltippositionleft);
		
		$(this).delay(500*index).animate({opacity: 1}, 500, function() {});
		
		
	});
	if (!touchOS && !iOS && !android)
	{
		$('div.featureApp li').mouseover(function(e) {
			var tooltip = $($("div.featureApp div.featureTooltip")[$(this).index()]);
			
			$(this).addClass('hover');
			
			tooltip.css("opacity", 0).show();
			
			// make it appear animated in 500 ms
			tooltip.animate({
					opacity: 1
				}, 500, function() {
					// Animation complete.
				});
		}).mouseout(function(e) {
			var tooltip = $($("div.featureApp div.featureTooltip")[$(this).index()]);
			// make it dissapear in 100 ms
			$(this).removeClass('hover');
			
			tooltip.animate({
				opacity: 0
				}, 100, function() {
				$(this).hide();
			});
		});
	}
	else
	{
		$('div.featureApp li').mousedown(function(e) {
			var tooltip = $($("div.featureApp div.featureTooltip")[$(this).index()]);
			
			$('div.featureApp li').removeClass('hover');
			
			if (tooltip.is(':visible'))
			{
				tooltip.animate({
					opacity: 0
					}, 100, function() {
					tooltip.hide();
				});
			}
			else
			{
				$('div.featureTooltip').hide();
						
				$(this).addClass('hover');
			
				tooltip.css("opacity", 0).show();
						
				tooltip.animate({
					opacity: 1
					}, 500, function() {
					// Animation complete.
				});
			}
		});
		
		$('div.featureApp img').mousedown(function(e) {
		
			$('div.featureApp li').removeClass('hover');
						
			$('div.featureTooltip').animate({
					opacity: 0
					}, 100, function() {
					$('div.featureTooltip').hide();
				});
		});		
	}
}

jQuery(function($) {
	initMainNav();
	initProductNav();
	initGeneral();
	initGallerybrowsing();
	initSwapImg();
	initTooltip();
	initTabs();
	initPanels();
	initImagethumbs();
	initLogin();
	initCorrectPNG();
	initPopupWindow();
	initOverlay();
	initHideNav();
	initTables();
	initCheckBoxes();
	initScrollPane();
	initFancybox();	
	initYTVideo();
	initFlashVideo();
	initPdfBox();
	//initScrollExtend();
	//initFooter();
});

$(window).load(function () {
	// this function is placed in window.load because the page must be loaded before this can be executed.
  	enableFeatureMouseOver();
});
