/*
// 2007-07-23
// Copyright (c) Nekovision | http://www.nekovision.ru/
// Author - Stepan Galkin
*/

// -----------------------------------------------------------------------------------

//
//	Global Variables
//

var objOverlay = document.createElement("div");

var animated = false;
var overlayOpacity = 0.5;	// controls transparency of shadow overlay
var overlayDuration = 0.2;	// shadow fade in/out duration
var resizeSpeed = 7;		// controls the speed of the image resizing animations (1=slowest and 10=fastest)
var resizeDuration = (11 - resizeSpeed) * 0.15;

var imagesPath = '/ii/';

var ua = navigator.userAgent.toLowerCase();
var isFirefox = Boolean(ua.indexOf('firefox') != -1);
var isOpera = Boolean(ua.indexOf('opera') != -1);
var	isIE = Boolean(ua.indexOf('msie') != -1 && !isOpera && (ua.indexOf('webtv') == -1));
var	isSafari = Boolean(ua.indexOf('safari') != -1);

var versionMinor = parseFloat(navigator.appVersion); 
if (isIE && versionMinor >= 4) versionMinor = parseFloat( ua.substring( ua.indexOf('msie ') + 5 ) );
var versionMajor = parseInt(versionMinor);
var isIE4up = (isIE && versionMajor >= 4);

// -----------------------------------------------------------------------------------

//
//	Additional methods for Element added by SU, Couloir
//	- further additions by Lokesh Dhakar (huddletogether.com)
//
Object.extend(Element, {
	getWidth: function(element) {
	   	element = $(element);
	   	return element.offsetWidth; 
	},
	getHeight: function(element) {
	   	element = $(element);
	   	return element.offsetHeight; 
	},
	setWidth: function(element,w) {
	   	element = $(element);
    	element.style.width = w +"px";
	},
	setHeight: function(element,h) {
   		element = $(element);
    	element.style.height = h +"px";
	},
	setTop: function(element,t) {
	   	element = $(element);
    	element.style.top = t +"px";
	},
	setLeft: function(element,l) {
	   	element = $(element);
    	element.style.left = l +"px";
	},
	setSrc: function(element,src) {
    	element = $(element);
    	element.src = src; 
	},
	setHref: function(element,href) {
    	element = $(element);
    	element.href = href; 
	},
	setInnerHTML: function(element,content) {
		element = $(element);
		element.innerHTML = content;
	},
	setVisible: function(element) {
		element = $(element);
		element.style.visibility = 'visible';
	},
	setHidden: function(element) {
		element = $(element);
		element.style.visibility = 'hidden';
	}
});

// -----------------------------------------------------------------------------------

function Initialize()  {
	var objBody = document.getElementsByTagName("body").item(0);
	objOverlay.setAttribute('id','overlay');
	objOverlay.style.display = 'none';
	objBody.appendChild(objOverlay);
		
	AttentionUtils.check();
}

// -----------------------------------------------------------------------------------

SigninUtils = {
	open: function () {
		objOverlay.onclick = function() { SigninUtils.close(); }
		OverlayUtils.show(function() {
			Element.show('signinSplash');
			SigninUtils.move();
			Form.Element.focus(signinEmailId);
		});
	},
	close: function () {
		Element.hide('signinSplash');
		OverlayUtils.hide();
	},
	move: function () {
		var button = $('signin');
		Element.setTop('signinSplash', button.offsetTop);
		Element.setLeft('signinSplash', button.offsetLeft);
	}
}

// -----------------------------------------------------------------------------------

CartUtils = {
	addItem: function (pid, qpos, animate, pos) {
		try {
		    if (!addCart(pid, pos))
		    return;
		
			var element = $('orderBtn' + pid);
			var qty = $('qty' + qpos);
			var busy = element.getAttribute('busy');

			if (busy == 1) return; // prevent click during animation
			else element.setAttribute('busy', 1);
			
			qty.disabled = true; // disable qty input (ie bug fix)
			element.toggleClassName('added'); // change style
			
			$('hRegister').style.display = "none";
			$('hCart').style.display = "block";
			
			// highlight cart box
			if (animate) new Effect.Highlight('cart', { durartion: 1.2, startcolor: '#ffffaa' });

			new PeriodicalExecuter(function (pe) {
				element.toggleClassName('added');
				element.setAttribute('busy', 0)
				qty.disabled = false;
				pe.stop();
			}, 1.2);
		} catch (error) {}
	}
}

function addCart(pid, qpos) {

	var el = document.getElementById("qty" + qpos);
	var qty = el.value;
	if (!/^\d{1,5}$/.test(qty)) {
		window.alert("Требуется указать число из 1-5 цифр, а не " + qty + "!");
		return false;
    }
	
	var iqty = parseInt(qty);
	if (iqty < 1) {
		window.alert("Требуется указать число от 1 до 99999, а не " + qty + "!");
		return false;
	}

	mkcb("ac-" + pid + "-" + qty);
	return true;
}

function cclb(res) {

	var strs = res.split('~');
	var ecart = document.getElementById("icart");
	if (ecart) ecart.innerHTML = "Всего товаров: <b>" + strs[0] + "</b><br />На сумму: <b>" + strs[1] + " руб.</b>";
}

// -----------------------------------------------------------------------------------

OverlayUtils = {
	show: function (afterFinish) {
		hideSelectBoxes();
		hideFlash();
		
		// stretch overlay to fill page and fade in
		var arrayPageSize = getPageSize();
		Element.setWidth('overlay', arrayPageSize[0]);
		Element.setHeight('overlay', arrayPageSize[1]);
	
		new Effect.Appear('overlay', {
			duration: overlayDuration,
			from: 0.0, to: overlayOpacity,
			afterFinish: afterFinish
		});
	},
	hide: function () {
		new Effect.Fade('overlay', { duration: overlayDuration });
		showSelectBoxes();
		showFlash();
	}
}

// -----------------------------------------------------------------------------------

Element.toggleSlider = function (target) {
	if (!Element.visible(target)) {
		Element.toggleClassName(target + '_btn', 'current');
		new Effect.BlindDown(target, { duration: 0.5 });
	} else {
		new Effect.BlindUp(target, {
			duration: 0.5,
			afterFinish: function () {
				Element.toggleClassName(target + '_btn', 'current');
			}
		});
	}
}

// -----------------------------------------------------------------------------------

AnnounceUtils = {
	hide: function (announceId) {
		if (announceId) {
			var name = 'announce' + announceId;
			if (getCookie(name) != 1) {
				setCookie(name, 1, 365);
			}
		}
		new Effect.DropOut('announce', {
			duration: 0.5,
			afterFinish: function () {
				if (isIE) Element.hide('announceHolder');
			}
		});
	}
};


// -----------------------------------------------------------------------------------

M2BUtils = {
	selected: null,
	toggle: function (id) {
		try {
			if (this.selected == null) {
				this.selected = Number($('brandsTabs').getAttribute('default'));
			}
			if (id == this.selected) return;
			this.hide();
			this.selected = id;
			this.show();
		} catch (e) {}
	},
	show: function () {
		new Effect.BlindDown('brand' + this.selected, { duration: 0.2 });
		$('link' + this.selected).className = 'current';
	},
	hide: function () {
		new Effect.BlindUp('brand' + this.selected, { duration: 0.2 });
		$('link' + this.selected).className = '';
	}
};

// -----------------------------------------------------------------------------------

AttentionUtils = {
	check: function () {
		if (getCookie('screenError') == 1 || 
			getCookie('browserError') == 1) return;
		var error = false;
		var splash = $('attention');
		var message = '';
		if (window.screen.width < 1024 && window.screen.height < 768) {
			message = '<h2>У вашего монитора низкое разрешение экрана!</h2>' +
					  'Для оптимального просмотра и&nbsp;полноценной работы веб-сайта<br />компании Europarts Rus необходимо ' +
					  'разрешение экрана<br />не&nbsp;менее <span class="red"><b>1024&times;768</b></span>&nbsp;пикселей/дюйм!';
			splash.setAttribute('name', 'screenError');
			error = true;
		}
			if ((isFirefox && versionMajor <= 4) || (isIE && versionMajor <= 4)) {
			message = '<h2>Вы используете устаревший браузер!</h2>' +
					  'Для оптимального просмотра и&nbsp;полноценной работы веб-сайта<br />компании Europarts Rus необходимо ' +
					  'использовать следующие браузеры: <b>Internet Explorer версии 5.5</b> и&nbsp;выше, ' +
					  '<b>Mozilla Firefox версии 1.5</b> и&nbsp;выше, <b>Apple Safari версии 3.0</b> и&nbsp;выше.';
			splash.setAttribute('name', 'browserError');
			error = true;
		}
		if (error) {
			message += '<br /><br /><a href="javascript:void(0)" onclick="AttentionUtils.close()" class="closeLink">Закрыть</a>';
			splash.innerHTML = message;
			Element.setTop('attention', (getPageSize()[3] - splash.getHeight() - 80) / 2 + getPageScroll()[1]);
			Element.setLeft('attention', (getPageSize()[2] - splash.getWidth()) / 2);
			this.open();
		}
	},
	open: function () {
		//objOverlay.onclick = function() { AttentionUtils.close(); }
		OverlayUtils.show(function() {
			Element.show('attention');
		});
	},
	close: function () {
		var splash = $('attention');
		setCookie(splash.getAttribute('name'), 1, 7);
		Element.hide('attention');
		OverlayUtils.hide();
	}
}

function setCookie(name, value, days, hours, minutes) {
	if (days || hours || minutes) {
		var date = new Date();
		days = days ? days : 0;
		hours = hours ? hours :0;
		minutes = minutes ? minutes : 0;
		date.setTime(date.getTime() + 60 * 1000 * (minutes + 60 * (hours + 24 * days)));
		var expires = "; expires=" + date.toGMTString();
	}
	else expires = "";
	document.cookie = name + "=" + escape(value) + expires + "; path=/";
}

function getCookie(name) {
	var c = document.cookie;
	if (c.indexOf(name) == -1) return null;
	else
	{
		var start = c.indexOf(name) + name.length + 1;
		for (var end = start; end < c.length; end++) {
			if (c.charAt(end) == ";") break;
		}
		return unescape(c.substring(start, end))
	}
}

// -----------------------------------------------------------------------------------

//
//	Image preloader, we need to fix delay in case onmouseover event
//

ImagePreloader = {
	doPreload: function (images) {
		images.each(this.preloadImage);
	},
	preloadImage: function (src) {
		var preloader = new Image();
		preloader.src = imagesPath + src;
	}
};


// -----------------------------------------------------------------------------------

//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.com
//
function getPageScroll(){

	var xScroll, yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}

	arrayPageScroll = new Array(xScroll,yScroll) 
	return arrayPageScroll;
}

// -----------------------------------------------------------------------------------

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.com
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

// ---------------------------------------------------

function ResizeHandler() {
	
	if (!Element.visible('overlay')) return false;
						 
	// stretch overlay to fill page and fade in
	var arrayPageSize = getPageSize();
	Element.setWidth('overlay', arrayPageSize[0]);
	Element.setHeight('overlay', arrayPageSize[1]);

	SigninUtils.move();
}

// ---------------------------------------------------

function showSelectBoxes(){
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}
}

// ---------------------------------------------------

function hideSelectBoxes(){
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "hidden";
	}
}

// ---------------------------------------------------

function showFlash(){
	var flashObjects = document.getElementsByTagName("object");
	for (i = 0; i < flashObjects.length; i++) {
		flashObjects[i].style.visibility = "visible";
	}

	var flashEmbeds = document.getElementsByTagName("embed");
	for (i = 0; i < flashEmbeds.length; i++) {
		flashEmbeds[i].style.visibility = "visible";
	}
}

// ---------------------------------------------------

function hideFlash(){
	var flashObjects = document.getElementsByTagName("object");
	for (i = 0; i < flashObjects.length; i++) {
		flashObjects[i].style.visibility = "hidden";
	}

	var flashEmbeds = document.getElementsByTagName("embed");
	for (i = 0; i < flashEmbeds.length; i++) {
		flashEmbeds[i].style.visibility = "hidden";
	}

}

// -----------------------------------------------------------------------------------

function OpenWindow (file, width, height, target, scroll) {
	var width  = width ? width : 640;
	var height = height ? height : 550;
	var x = (screen.width - width)/2;
	var y = (screen.height - height)/4;
	var scroll = (scroll != null ? scroll : true);
	window.open(
		file, target, 'left=' + x + ', top=' + y + ', width=' + width + ', height=' + height + ', ' +
		'menubar=no, resizable=yes, scrollbars=' + (scroll ? 'yes' : 'no') + ', status=yes, titlebar=yes, toolbar=no, help=no'
	);
}

function ResponseLocation (URL) {
	if (URL) document.location.href = URL;
}

// -----------------------------------------------------------------------------------

Event.observe(window, 'load', Initialize, false);
Event.observe(window, 'resize', ResizeHandler, false);

// preload images declared in css
ImagePreloader.doPreload([
	'btn-cart-a.png', 'btn-help-a.gif', 'exchange-a.gif', 'form-a.gif', 'btn-add-sm-a.gif',
	'p-next-a.gif', 'p-prev-a.gif', 'p-round-a.gif', 'plus-a.gif', 'minus.gif', 'incart.png',
	'sort-down-a.gif', 'sort-up-a.gif', 'btn-search-sm-a.gif', 'btn-search-sm-c.gif'
]);