﻿$(function () {
	// Initialize language picker menu
	$('#language_picker').jqDock({ align: 'top', distance: 50, size: 18, labels: 'bc', source: function () { return this.src.replace("-bw.png", '.png'); } });

	// Animate social link icons on hover
	$('#social_links li a img').each(function () { $(this).css('background-image', 'url("' + $(this).attr('src').replace('-bw.png', '.png') + '")'); });
	$('#social_links li').prepend('<img class="shadow" src="' + globalImagesFolder + 'icons-shadow.jpg" width="34" height="12" alt="" />');
	$('#social_links li').hover(
		function () {
			$(this).find('a').stop().animate({ marginTop: '-4px' }, 250); $(this).find('img.shadow').stop().animate({ width: '80%', height: '13px', marginLeft: '4px', opacity: 0.4 }, 250);
		},
		function () {
			$(this).find('a').stop().animate({ marginTop: '0px' }, 250); $(this).find('img.shadow').stop().animate({ width: '100%', height: '14px', marginLeft: '0px', opacity: 1 }, 250);
		}
	);

	// Handle search box events (submit, focus & blur)
	$('.site_search').each(function () {
		var siteSearchHint = $(this).find('span');
		var siteSearchText = $(this).find('input[type=text]');
		var siteSearchButton = $(this).find('input[type=image]');
		if (siteSearchHint && siteSearchText && siteSearchButton) {
			siteSearchHint
			.removeClass('hidden')
			.click(function () { siteSearchText.focus(); })
			.mousedown(function () { siteSearchText.focus(); });
			siteSearchText
			.focus(function () { if ($(this).val() == '') siteSearchHint.hide(); })
			.blur(function () { if ($(this).val() == '') siteSearchHint.show(); })
			.keypress(function () { if (window.event.keyCode == 13) { siteSearchButton.click(); return false; } });
			if (siteSearchText.val() != '') siteSearchHint.hide();
		}
	});

	// Top navigation menu style (link & hover)
	var menuBack = '#F1F1F1', menuFront = '#252525', menuBorder = '#D3D3D3';
	var menuBackH = '#1F1F1F', menuFrontH = '#FFFFFF', menuBorderH = '#000000';
	// Animate menu on hover    
	$('#topnav a').not($('.selected')).hover(
		function () { $(this).stop().animate({ backgroundColor: menuBack, color: menuFront, borderBottomColor: menuBorder, borderLeftColor: menuBorder, borderRightColor: menuBorder, borderTopColor: menuBorder }, 350); },
		function () { $(this).stop().animate({ backgroundColor: menuBackH, color: menuFrontH, borderBottomColor: menuBorderH, borderLeftColor: menuBorderH, borderRightColor: menuBorderH, borderTopColor: menuBorderH }, 350); }
	);

	// Append '>>' to read more links
	$("a.read_more").append(" &raquo;");

	// Prepend '<<' to navigate back links
	$("a.navigate_back").prepend("&laquo; ");

	// Initialize product weel
	$('#product_wheel').jqDock({ align: 'right', labels: 'mr', distance: 70, size: 35 });
	setTimeout(ShowProductWeel, 100);
	$('#product_wheel_container a').click(function () { window.location = this.href; });

	// Initialize news scroller
	$("#news_scroller").hover(
		function () { isMouseOverNewsScroller = true; },
		function () { isMouseOverNewsScroller = false; }
	);
	InitNewsScroller();

	//InitMainPageCanvas();

	InitTreeview();

	InitContactUsPage();

	// Apply styles to specific elements
	ApplyCustomStyles();

	// Activate video gallery
	objects = $(".video-gallery object");
	for (var i = 0; i < objects.length; i++) {
		objects[i].outerHTML = objects[i].outerHTML;
	}
});

/************** Create the ad rotator on the main page **************/

// Initialize canvas
function InitMainPageCanvas() {
	var homeCanvas = $('#home_canvas');
	if (!homeCanvas[0] || !homeCanvas[0].getContext) return;
	var ctx = homeCanvas[0].getContext('2d');

	// Add "read more" link
	homeCanvas.parent('div').append('<a href="/products" class="canvas_read_more">Read more &raquo;</a>');

	currentAdImage = null;
	nextImage(ctx, null, -1);
}

// Load next image on the list and show it
function nextImage(ctx, previousImg, imgId) {
	var adImagePath = 'img/ads/';
	var adImages = ['crab.jpg', 'tree.jpg', 'tiger.jpg', 'fish.jpg', 'lake.jpg'];

	imgId += 1;
	if (imgId >= adImages.length) imgId = 0;

	var img = new Image();
	img.onload = function () {
		ctx.save();
		if (navigator.appName == 'Microsoft Internet Explorer')
			swithImagesIE(ctx, previousImg, this, 0);
		else
			swithImages(ctx, previousImg, this, 0);
		ctx.restore();

		previousImg = this;
		setTimeout(function () { nextImage(ctx, previousImg, imgId); }, 15 * 1000);
	}
	img.src = adImagePath + adImages[imgId];
}

// Create transition from one image to next
function swithImages(ctx, oldImg, newImg, alfa) {
	ctx.clearRect(0, 0, 900, 300);
	if (oldImg) {
		ctx.globalAlpha = 1;
		ctx.drawImage(oldImg, 0, 0);
	}
	ctx.globalAlpha = alfa;
	ctx.drawImage(newImg, 0, 0);
	if (alfa < 1) setTimeout(function () { swithImages(ctx, oldImg, newImg, alfa + 0.05); }, 50);
}

// IE cannot draw transparent images. Create different transition from one image to next
function swithImagesIE(ctx, oldImg, newImg, alfa) {
	ctx.clearRect(0, 0, 900, 300);
	if (alfa <= 1) {
		if (oldImg) {
			ctx.drawImage(oldImg, 0, 0);
			ctx.fillStyle = 'rgba(255,255,255,'+alfa+')';
			ctx.fillRect(0, 0, 900, 300);
		}
		else alfa = 1;
	}

	if (alfa > 1) {
		ctx.drawImage(newImg, 0, 0);
		ctx.fillStyle = 'rgba(255,255,255,' + (2 - alfa) + ')';
		ctx.fillRect(0, 0, 900, 300);
	}

	if (alfa < 2) setTimeout(function () { swithImagesIE(ctx, oldImg, newImg, alfa + 0.05); }, 50);
}

/************** Initialize tree views **************/

function InitTreeview() {
	$('ul.treeview').find('li:last-child').addClass('tvil').end()
	.find('li:has(ul)').not('li:last-child').addClass('tvic').end()
	.swapClass('tvil', 'tvilc').append('<div class="tvca">').find('div.tvca').click(function () {
		$(this).parent('li').swapClass('tvic', 'tvie').swapClass('tvilc', 'tvile').find('>ul').toggle('normal');
	});

	$('.treeview_controls .collapse_all').click(function (e) { ExpandCollapseTreeview('tvic', 'tvie', 'tvilc', 'tvile'); e.preventDefault(); });
	$('.treeview_controls .expand_all').click(function (e) { ExpandCollapseTreeview('tvie', 'tvic', 'tvile', 'tvilc'); e.preventDefault(); });
}

function ExpandCollapseTreeview(c1, c2, cA, cB) {
	$('ul.treeview').find('li:has(ul)').each(function () {
		if ($(this).hasClass(c1)) { $(this).removeClass(c1).addClass(c2).find('>ul').toggle('normal'); }
		if ($(this).hasClass(cA)) { $(this).removeClass(cA).addClass(cB).find('>ul').toggle('normal'); }
	});
}

$.fn.swapClass = function (c1, c2) {
	return this.each(function () {
		if ($(this).hasClass(c1)) { $(this).removeClass(c1).addClass(c2); }
		else if ($(this).hasClass(c2)) { $(this).removeClass(c2).addClass(c1); }
	});
}

/************** Initialize news scroller **************/

var isMouseOverNewsScroller = false;
function InitNewsScroller() {
	$("#news_scroller").removeClass('hidden');
	$("#news_scroller span.tick").css("left", $("body").width());
	setInterval(function () {
		if (isMouseOverNewsScroller) return;
		var left = parseInt($("#news_scroller span.tick").css("left"));
		if (left < -$("#news_scroller span.tick").width()) {
			left = $("body").width();
		}
		$("#news_scroller span.tick").css("left", left - 1);
	}, 10);
}

/************** Show product weel **************/

function ShowProductWeel() {
	var right = parseInt($('#product_wheel_container').css("right"));
	$('#product_wheel_container').css("right", ++right);
	if (right < 0) setTimeout(ShowProductWeel, 10);
}

/************** Initialize Contact Us page **************/

function InitContactUsPage() {
	$('.contacts_form input[type=submit]').click(function (e) {
		// Validate form
		$('.contacts_form label').each(function () { $(this).removeClass('invalid').attr('title', ''); });
		$('.warning_image').addClass('hidden');

		var invalid = false;
		if ($.trim($('#txtName').val()) == '') {
			invalid = true;
			$('#txtName').prev().addClass('invalid').attr('title', $('#txtName').next().val());
		}
		if ($.trim($('#txtEmail').val()) == '') {
			invalid = true;
			$('#txtEmail').prev().addClass('invalid').attr('title', $('#txtEmail').next().val());
		}
		else if (!validateEmail($('#txtEmail').val())) {
			invalid = true;
			$('#txtEmail').prev().addClass('invalid').attr('title', $('#txtEmail').next().next().val());
		}
		if ($.trim($('#txtMessage').val()) == '') {
			invalid = true;
			$('#txtMessage').prev().addClass('invalid').attr('title', $('#txtMessage').next().val());
		}

		if (invalid) {
			$('.warning_image').removeClass('hidden');
			e.preventDefault();
		} else {
			$(this).addClass('hidden').prev().removeClass('hidden');
		}
	});
}

function validateEmail(elementValue) {
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]{2,4}$/;
	return emailPattern.test(elementValue);
}

/************** Apply styles to specific elements **************/
function ApplyCustomStyles() {
	// List of all solution groups
	$('.solutions_overview_list li:nth-child(3n+1)').addClass('clear');

	// List of solutions in group
	$('.solutions_list li:nth-child(2n+1)').addClass('clear');

	// List of all solution groups
	$('.products_list li:nth-child(2n+1)').addClass('clear');

	// Site map
	$('.site_map .level3').each(function () { $(this).find('li').not(':first').prepend('| '); });
}

