var sliders=[], /* 2d array of sliders. Index of child array mean:
				*  0 - object; sliding <ul>
				*  1 - number; maximum margin
				*  2 - object; left arrow
				*  3 - object; right arrow
				*  4 - number; slider column width;
				*/
	sliderStep=1, // number of slided columns one time
	stepsNumber=5, // animation iterations
	slideDelay=30; // animation delay

function initLoaf() {
	makeTelephones();

	var divs=document.getElementsByTagName('div'),
		sliderInd=0;
	for (var divInd=0, divsLen=divs.length; divInd<divsLen; divInd++) {
		var div=divs[divInd],
			divClass=div.className;
		if (divClass.indexOf('slider')>=0) {
			sliders[sliderInd]=[];
			var spans=div.getElementsByTagName('span'),
				anch=div.getElementsByTagName('a'),
				ul=div.getElementsByTagName('ul')[0];
			for (spanInd=0, spansLen=spans.length, anchLen=anch.length; spanInd<spansLen+anchLen; spanInd++) {
				var span=spans[spanInd]||anch[spanInd-spansLen];
				if (span.className.indexOf('left_arr')>=0) {
					span.setAttribute('index',sliderInd);
					span.onclick=function(event){
						event=event||window.event;
						event.preventDefault?event.preventDefault():event.returnValue=false;
						moveRight(this.getAttribute('index'));
					};
					span.style.display='none';
					sliders[sliderInd][2]=span;
				} // if .left_arr
				else if (span.className.indexOf('right_arr')>=0) {
					span.setAttribute('index',sliderInd);
					span.onclick=function(event){
						event=event||window.event;
						event.preventDefault?event.preventDefault():event.returnValue=false;
						moveLeft(this.getAttribute('index'));
					};
					sliders[sliderInd][3]=span;
				} // if .right_arr
			} // for (spans)

			var li=ul.getElementsByTagName('li')[0],
				liS=li.style;
			sliders[sliderInd][4]=li.clientWidth+(parseInt(liS.marginRight)||0)+(parseInt(liS.marginLeft)||0)+(parseInt(liS.borderLeftWidth)||0)+(parseInt(liS.borderRightWidth)||0);

			if (browser.isGecko || browser.is_gteIE8) { // fix of slider width for firefox and ie8+
				var hider=ul.parentNode,
					correctW=Math.floor(hider.clientWidth/sliders[sliderInd][4])*sliders[sliderInd][4];
				hider.style.width=correctW+'px';
				sliders[sliderInd][3].style.left=correctW+'px';
			} // if firefox

			if (ul.className.indexOf('slide_content')>=0) {
				sliders[sliderInd][0]=ul;
				ul.style.marginLeft='0';
				sliders[sliderInd][1]=-1*(ul.getElementsByTagName('li').length*sliders[sliderInd][4]-(ul.parentNode.clientWidth));
				if (sliders[sliderInd][1]>=0) {
					sliders[sliderInd][2].style.display='none';
					sliders[sliderInd][3].style.display='none';
				} // if all is visible
			} // if .slide_content

			sliderInd++;
		} // if (.slider)
		if (divClass.indexOf('production_inner')>=0) {
			initPopups();
			var links=div.getElementsByTagName('a');
			for (var linkInd=0, linksLen=links.length; linkInd<linksLen; linkInd++) {
				var link=links[linkInd];
				if (link.className.indexOf('slide_arrow')>=0) continue;
				link.onclick=function(event){
					event=event||window.event;
					event.preventDefault?event.preventDefault():event.returnValue=false;
					replaceDescription(this);
					makeActive(this);
				}
			}
		} // if (.production_inner)
		if (divClass.indexOf('production_line')>=0) {
			var links=div.getElementsByTagName('a');
			for (var linkInd=0, linksLen=links.length; linkInd<linksLen; linkInd++) {
				var link=links[linkInd];
				if (link.className.indexOf('slide_arrow')>=0) continue;
				link.onmouseover=function(){
					var text=this.getAttribute('role2');
					if (!text) return;
					showPopup(this,text);
				}
				link.onmouseout=hidePopup;
				link.onclick=function(event){
					event=event||window.event;
					event.preventDefault?event.preventDefault():event.returnValue=false;
					var target=document.getElementById(this.getAttribute('rel'));
					replaceDescription(this);//target);
					makeActive(target);
				}
			}
		} // if (.production_line)
	} // for (divs)

	var contactsCities=document.getElementById('contacts_cities'),
		contactsCitiesNav=document.getElementById('contacts_cities_navigation'),
		visibleCity=null,
		activeCityLink=null;
	if (contactsCities && contactsCitiesNav) {
		var cities=contactsCities.getElementsByTagName('div'),
			citiesLinks=contactsCitiesNav.getElementsByTagName('a');
		visibleCity=cities[0];
		activeCityLink=citiesLinks[0];
		for (cityInd=1, citiesLen=cities.length; cityInd<citiesLen; cityInd++) {
			var city=cities[cityInd];
			if (city.parentNode==contactsCities) {
				city.style.display='none';
			}
		}
		for (cityLinkInd=0, citiesLinksLen=citiesLinks.length; cityLinkInd<citiesLinksLen; cityLinkInd++) {
			var cityLink=citiesLinks[cityLinkInd];
			if (cityLinkInd==0) cityLink.parentNode.className+=' item_checked';
			cityLink.onclick=function(event){
				event=event||window.event;
				event.preventDefault?event.preventDefault():event.returnValue=false;
				if (visibleCity) visibleCity.style.display='none';
				if (activeCityLink) activeCityLink.parentNode.className=activeCityLink.parentNode.className.replace(' item_checked','');
				visibleCity=document.getElementById(this.href.substring(this.href.indexOf('#')+1));
				visibleCity.style.display='block';
				activeCityLink=this;
				this.parentNode.className+=' item_checked';
			}
		}
	}

	window.onresize=function(){
		for (var sliderInd=0, slidersLen=sliders.length; sliderInd<slidersLen; sliderInd++) {
			var ul=sliders[sliderInd][0];

			if (browser.isGecko || browser.is_gteIE8) { // fix of slider width for firefox and ie8+
				var hider=ul.parentNode;
				hider.style.width='';
				var correctW=Math.floor(hider.clientWidth/sliders[sliderInd][4])*sliders[sliderInd][4];
				hider.style.width=correctW+'px';
				sliders[sliderInd][3].style.left=correctW+'px';
			} // if firefox

			sliders[sliderInd][1]=-1*(ul.getElementsByTagName('li').length*sliders[sliderInd][4]-ul.parentNode.clientWidth);
			var margin=parseInt(ul.style.marginLeft);
			if (margin<=sliders[sliderInd][1]) {
				margin=sliders[sliderInd][1];
				sliders[sliderInd][3].style.display='none';
				ul.style.marginLeft=margin+'px';
			}
			else sliders[sliderInd][3].style.display='';
			if (margin>=0) {
				sliders[sliderInd][2].style.display='none';
				ul.style.marginLeft='0';
			}
			else sliders[sliderInd][2].style.display='';
			if (sliders[sliderInd][1]>=0) {
				sliders[sliderInd][2].style.display='none';
				sliders[sliderInd][3].style.display='none';
			}
		}
	}
} // initLoaf()

var popupBlock=null,
	popupText=null;
function initPopups() {
	if (popupBlock) return;
	popupBlock=document.createElement('div');
	popupBlock.className='popup_block';
	popupText=document.createElement('p');
	var topSpan=document.createElement('span'),
		bottomSpan=document.createElement('span');
	topSpan.className='popup_top';
	bottomSpan.className='popup_bottom';
	popupBlock.appendChild(topSpan);
	popupBlock.appendChild(bottomSpan);
	popupBlock.appendChild(popupText);
	document.getElementsByTagName('body')[0].appendChild(popupBlock);
} // initPopups()

function showPopup(target,text) {
	if (!popupBlock) initPopup();
	var params=offset(target),
		top=params.top+params.height,
		left=params.left+params.width/2;
	popupText.innerHTML=text;
	popupBlock.style.left=left+'px';
	popupBlock.style.top=top+'px';
	popupBlock.style.display='block';
} // showPopup()

function hidePopup() {
	if (!popupBlock) return;
	popupBlock.style.display='none';
} // hidePopup()

function offset(target) {
	var l=t=0,
		w=target.offsetWidth,
		h=target.offsetHeight;
	while(target) {
		l+=target.offsetLeft;
		t+=target.offsetTop;
		target=target.offsetParent;
	}
	return {'left':l,'top':t,'width':w,'height':h}
} // offset()

function replaceDescription(src) {
	var targetContainer=document.getElementById('production_description'),
		targetText=document.getElementById('production_description_text'),
		targetImage=targetContainer.getElementsByTagName('img');
	targetImage=targetImage[targetImage.length-1];
	targetText.innerHTML=document.getElementById(src.getAttribute('rel')).innerHTML;
	targetImage.src=src.getAttribute('role');
	//target.style.backgroundImage='url('+src.getAttribute('role')+')';
} // replaceDescription()

var lastActive=null;
function makeActive(target) {
	if (lastActive)	lastActive.className=lastActive.className.replace(' active_product','');
	target.className+=' active_product';
	lastActive=target;
} // makeActive()

function moveLeft(index,step,margin) {
	var step=step+1||1,
		slider=sliders[index][0],
		margin=typeof margin == 'undefined'?parseInt(slider.style.marginLeft):margin,
		newMargin=margin-sliders[index][4]*sliderStep/stepsNumber*step;
	if (newMargin<=sliders[index][1]) {
		newMargin=sliders[index][1];
		step=stepsNumber;
		sliders[index][3].style.display='none';
	}
	slider.style.marginLeft=newMargin+'px';
	sliders[index][2].style.display='';
	if (step<stepsNumber) setTimeout(function(){moveLeft(index,step,margin);},slideDelay);
} // moveLeft()

function moveRight(index,step,margin) {
	var step=step+1||1,
		slider=sliders[index][0],
		margin=typeof margin == 'undefined'?parseInt(slider.style.marginLeft):margin,
		newMargin=margin+sliders[index][4]*sliderStep/stepsNumber*step;
	if (newMargin>=0) {
		newMargin=0;
		step=stepsNumber;
		sliders[index][2].style.display='none';
	}
	slider.style.marginLeft=newMargin+'px';
	sliders[index][3].style.display='';
	if (step<stepsNumber) setTimeout(function(){moveRight(index,step,margin);},slideDelay);
} // moveRight()

var mobileUserAgentList=['Android','Symbian','Opera Mini'];
function makeTelephones() {
	var isMobile=false,
		thisBrowser=navigator.userAgent;
	for (var i=0, l=mobileUserAgentList.length; i<l; i++) {
		if (thisBrowser.indexOf(mobileUserAgentList[i])>=0) {
			isMobile=true;
			break;
		}
	}
	if (!isMobile) return;
	function getInnerText(code) {
		var _innerText=code.innerText;
		if (typeof _innerText == 'undefined') _innerText=code.replace(/<[^>]+>/gi,'');
		return _innerText;
	} // getInnerText()
	var body=document.getElementsByTagName('body')[0],
		allHTML=body.innerHTML,
		allText=getInnerText(allHTML),
		phoneCheck=new RegExp('(\\+?(\s| )*[0-9]?(\s| )*(\\([0-9]+\\))?(\s| )*([0-9]|-){7,})','gi'),
		phones=allText.match(phoneCheck);
	for (var i=0, l=phones.length; i<l; i++) {
		var phone=phones[i];
		for (var q=i+1; q<l; q++) {
			if (phone==phones[q]) {
				phones.splice(q,1);
				l--;
			}
		}
		var phoneText=phones[i].replace(/(^( |\s)+)|(( |\s)+$)/gi,''),
			phoneTextEscaped=phoneText.replace(/([\(\)\+])/gi,'\\$1'),
			phoneNum=phoneText.replace(/[ \s\(\)-]/gi,''),
			search=new RegExp(phoneTextEscaped,'gi');
		allHTML=allHTML.replace(search,'<a href="tel:'+phoneNum+'" class="telephone">'+phoneText+'<span></span></a>');
	}
	body.innerHTML=allHTML;
} // makeTelephones()

var browser={
	isIE: navigator.userAgent.indexOf('MSIE')>=0,
	is_gteIE8: /MSIE [^(1-7)\.]/g.test(navigator.userAgent),
	isIE6: navigator.userAgent.indexOf('MSIE 6')>=0,
	isWebKit: navigator.userAgent.indexOf('WebKit')>=0,
	isGecko: navigator.userAgent.indexOf('Gecko')>=0 && navigator.userAgent.indexOf('WebKit')<0
}

function bindReady(handler){ // onDomReady event

	var called = false

	function ready() {
		if (called) return
		called = true
		handler()
	}

	if ( document.addEventListener ) {
		document.addEventListener( "DOMContentLoaded", function(){
			document.removeEventListener( "DOMContentLoaded", arguments.callee, false)
			ready()
		}, false )
	} else if ( document.attachEvent ) {
		if ( document.documentElement.doScroll && window == window.top ) {
			function tryScroll(){
				if (called) return
				try {
					document.documentElement.doScroll("left")
					ready()
				} catch(e) {
					setTimeout(tryScroll, 0)
				}
			}
			tryScroll()
		}
		document.attachEvent("onreadystatechange", function(){
			if ( document.readyState === "complete" ) {
				document.detachEvent( "onreadystatechange", arguments.callee )
				ready()
			}
		})
	}

	if (window.addEventListener)
		window.addEventListener('load', ready, false)
	else if (window.attachEvent)
		window.attachEvent('onload', ready)
	else
		window.onload=ready
} // bindReady()

bindReady(initLoaf);
