var JV = {};

/* IE png transparent fix */
Prototype.Browser.Version = (navigator.userAgent.toLowerCase().match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1];
Prototype.FixPNG = { Pixel: '/img/d-t.gif' };
  document.Browser = {
	IE:     navigator.userAgent.indexOf('MSIE') > -1,
	Opera:  navigator.userAgent.indexOf('Opera') > -1,
	WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
	Gecko:  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
	MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/),
	Safari:navigator.userAgent.indexOf('Safari') > -1,
	Firefox:navigator.userAgent.indexOf('Firefox') > -1
  };
      document.Platform = {
        isMac: !!(navigator.appVersion.match(/(Macintosh|Mac OS X)/)),
        isWin: !!(navigator.appVersion.match(/(Windows)/)),
        browser: (document.Browser.IE ? 'ie' : ((document.Browser.Opera) ? 'opera' : ((document.Browser.Safari) ? 'safari' : ((document.Browser.Firefox || document.Browser.Gecko) ? 'firefox' : '') ) ) )
      };



Element.addMethods({
  fixpng: (Prototype.Browser.IE && Prototype.Browser.Version < 7) ? function(element) {
	function fixPosition(element) { if(element.style.position != 'absolute') element.style.position == 'relative'; }
	function filter(src) { return "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=crop,src='" + src + "')"; }
	var elementName = element.nodeName.toLowerCase();
	if(elementName == 'img' || elementName == 'input') {
	  if(element.src && element.src.match(/.*\.png([?].*)?$/i)) {
		element.setStyle({
		  filter: filter(element.src),
		  width: element.getWidth(),
		  height: element.getHeight()
		});
		element.src = Prototype.FixPNG.Pixel;
		fixPosition(element);
	  }
	} else {
	  var image = element.currentStyle.backgroundImage;
	  if (image.match(/^url\(["']?(.*\.png([?].*)?)["']?\)$/i)) {
		element.setStyle({
		  filter: filter(RegExp.$1),
		  backgroundImage: "none"
		});
		element.childElements().each(fixPosition);
	  }
	}
	return element;
  } : function(element) { return element; }
});

Element.addMethods({
  fixpngd: (Prototype.Browser.IE && Prototype.Browser.Version <= 8) ? function(element) {
	function fixPosition(element) { if(element.style.position != 'absolute') element.style.position == 'relative'; }
	function filter(src) { return "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=crop,src='" + src + "')"; }
	var elementName = element.nodeName.toLowerCase();
	if(elementName == 'img' || elementName == 'input') {
	  if(element.src && element.src.match(/.*\.png([?].*)?$/i)) {
		element.setStyle({
		  filter: filter(element.src),
		  width: element.getWidth(),
		  height: element.getHeight()
		});
		element.src = Prototype.FixPNG.Pixel;
		fixPosition(element);
	  }
	} else {
	  var image = element.currentStyle.backgroundImage;
	  if (image.match(/^url\(["']?(.*\.png([?].*)?)["']?\)$/i)) {
		element.setStyle({
		  filter: filter(RegExp.$1),
		  backgroundImage: "none"
		});
		element.childElements().each(fixPosition);
	  }
	}
	return element;
  } : function(element) { return element; }
});

function addBrowserNameToBody() {
	var body = document.getElementsByTagName('body')[0];
	body.className += " " + document.Platform.browser.toLowerCase();
}


var updateBlockShadow = function(element) {
	var element = $(element);
	
	if (!Object.isElement(element) || !Prototype.Browser.IE) {
		return;
	}
	
	var blockHeight = element.getHeight();
	element.select('.cn').each(function(el) {
		el.setStyle({height: blockHeight}).fixpng();
	});
}

// Обратная совместимость



var initScrollBlock = function (listElement,prevElement,nextElement,visibleCount,previewPrefix,imagePrefix) {

    var options = {
		'previous_element':prevElement,
		'next_element':nextElement,
		'visible_count':visibleCount,
		'preview_prefix':previewPrefix,
		'image_prefix':imagePrefix
	};
	initScrollBlockInner (listElement,options);
};


var showBigImage = function (bigImg) {
	if (bigImg) {
		if (bigImg.up('div').down('.visible')) bigImg.up('div').down('.visible').removeClassName('visible');
		bigImg.addClassName('visible');
	}
};

var initScrollBlockInner = function (listElement,options) {
	var prevElement = $(options.previous_element);

	var nextElement = options.next_element;
	var visibleCount = options.visible_count;
	var previewPrefix = options.preview_prefix;
	var imagePrefix = options.image_prefix;

	var bigImages = options.big_images;
	var slideOnClick = options.slide_on_click || false;
	var roundRoll = options.slide_on_click || false;
	var looping = options.looping || false;
    var vertical = options.vertical || false;
    var startLeftOffset = options.left_offset || 0;
	var scrolling = false;
	var _options = options;
	var currentPosition = 0;
	var itemWidth = 0;
	var itemHeight = 0;

	if (looping) {
		var inner = $(listElement).innerHTML;
		var ini_count = $(listElement).childElements().size();
        //console.log(ini_count);
	}
	
	
var updatePosition = function (newValue) {
	$(listElement).removeClassName('current'+currentPosition);
	currentPosition = newValue;
	$(listElement).addClassName('current'+newValue);
}

var redrawPosition = function (newValue) {
    
    updatePosition(newValue);



    if (vertical) {
        if (itemHeight==0) {
            itemHeight = $(listElement).down('li').getHeight()
                +parseInt($(listElement).down('li').getStyle('marginTop'))
                +parseInt($(listElement).down('li').getStyle('marginBottom'));
        }

        $(listElement).setStyle ({
            marginTop:'-'+itemHeight*currentPosition+'px'
        });

    } else {
        if (itemWidth==0) {
            itemWidth = $(listElement).down('li').getWidth()
                +parseInt($(listElement).down('li').getStyle('marginRight'))
                +parseInt($(listElement).down('li').getStyle('marginLeft'));
        }

        $(listElement).setStyle ({
            marginLeft:'-'+itemWidth*currentPosition+'px'
        });

    }

}

var removeTopElements = function () { 
	for (i=0;i<ini_count;i++) {
		$(listElement).down('li:first').remove();
	}
}

var removeBottomElements = function () { 
	if ($(listElement).childElements().size()>ini_count*2) {
		for (i=0;i<ini_count;i++) {
			$(listElement).down('li:last').remove();
		}
	}
}

var onSuccessScroll = function () {
	scrolling = false;
}

var scrollGallery = function (direction,scrollDuration) {
	
	if (!scrolling) {
		if (itemWidth==0) {
			itemWidth = $(listElement).down('li').getWidth()
				+parseInt($(listElement).down('li').getStyle('marginRight'))
				+parseInt($(listElement).down('li').getStyle('marginLeft'));
		}
        if (itemHeight==0) {
            itemHeight = $(listElement).down('li').getHeight()
                +parseInt($(listElement).down('li').getStyle('marginTop'))
                +parseInt($(listElement).down('li').getStyle('marginBottom'));
        }
		
		var size = $(listElement).childElements().size();
		var newPosition = currentPosition + direction;
		
		if (looping && size-newPosition<=visibleCount*2) {
			
			$(listElement).insert({
				bottom : inner
			});
			
			initPreviewClickObserve();
			removeTopElements();
			redrawPosition(currentPosition-ini_count);
		}
		
		if (looping && newPosition<=visibleCount) {
			
			$(listElement).insert({
				top : inner
			});
			
			initPreviewClickObserve();
			removeBottomElements();
			redrawPosition(currentPosition+ini_count);
			
		}
		
		var size = $(listElement).childElements().size();
		var newPosition = currentPosition + direction;
		
		if (newPosition>=0 && newPosition<=size-visibleCount) {
			
			$(listElement).fire('b:scrolled',{
				position:newPosition
			})
			updatePosition(newPosition);
			
			scrolling = true;

            if (vertical) {
                new Effect.Morph($(listElement), {
                    style: 'margin-top:-'+(itemHeight*newPosition)+'px',
                    duration: scrollDuration,
                    afterFinish: onSuccessScroll
                });
            } else {
                new Effect.Morph($(listElement), {
                    style: 'margin-left:-'+(itemWidth*newPosition+startLeftOffset)+'px',
                    duration: scrollDuration,
                    afterFinish: onSuccessScroll
                });
            }


			if (!looping) {
				if (newPosition==size-visibleCount) {
					$(nextElement).removeClassName('next');
					$(nextElement).addClassName('next-na');
				} else {
					$(nextElement).removeClassName('next-na');
					$(nextElement).addClassName('next');
				};
				
				if (newPosition==0) {
					$(prevElement).removeClassName('prev');
					$(prevElement).addClassName('prev-na');
				} else {
					$(prevElement).removeClassName('prev-na');
					$(prevElement).addClassName('prev');
				};
			}
		}
	}
	
}

var previewOnclick = function (e) {
	if (!scrolling && imagePrefix) {
		if (Event.element(e).up('ul').down('li.current')) 
			Event.element(e).up('ul').down('li.current').removeClassName('current');
		var eLi = Event.element(e).up('li')?Event.element(e).up('li'):Event.element(e);
		eLi.addClassName('current');
		if (eLi.down('img')) {
            var uId = eLi.down('img').id.substr(previewPrefix.length);
        }
		eLi.fire('b:selected', { position: imagePrefix+uId });
		var tmp_pos = e.findElement('ul').select('li').indexOf(e.findElement('li'));
		
		if (bigImages) {
			
			tmpLoad = new Image ( _options.big_images_width, _options.big_images_height );
			tmpLoad.src = bigImages[uId-1];
			
			if (tmpLoad.width >0) {
				var newBigImg = $(imagePrefix+uId);
				
				if (newBigImg) {
					newBigImg.down('img').src = bigImages[uId-1];
					showBigImage(newBigImg);
				}
				
				if (slideOnClick) {
					scrollGallery(tmp_pos-currentPosition+1,0.5);
				}
				
			} else {
				tmpLoad.onload = function () {
					var newBigImg = $(imagePrefix+uId);
					
					if (newBigImg) {
						newBigImg.down('img').src = bigImages[uId-1];
						showBigImage(newBigImg);
					}
					
					if (slideOnClick) {
						scrollGallery(tmp_pos-currentPosition+1,0.5);
					}
				};
			}
			
		} else {
			showBigImage($(imagePrefix+uId));
			if (slideOnClick) {
				scrollGallery(tmp_pos-currentPosition+1,0.5);
			}
		}
	}
};

var initPreviewClickObserve = function () {
	$(listElement).childElements().invoke('observe','click',previewOnclick);
};

var resetPreviewClickObserve = function () {
	$(listElement).childElements().invoke('stopObserving','click',previewOnclick);
};

	var size = $(listElement).childElements().size();
	
	updatePosition(0);
	if (looping) {
		scrollGallery(1,0);
	}
	if (!looping) {
		$(prevElement).removeClassName('prev');
		$(prevElement).addClassName('prev-na');
	}
	
	if (size==visibleCount) {
		$(nextElement).hide();
		$(prevElement).hide();
	}
	
	if (size<=visibleCount) {
		$(nextElement).removeClassName('next');
		$(nextElement).addClassName('next-na');
	}
	
	$(prevElement).observe('click',function(n){
		scrollGallery(-1,0.5);
	});
	
	$(nextElement).observe('click',function(n){
		scrollGallery(1,0.5);
	});
	
	if (!$('comics-gallery')) {
		initPreviewClickObserve();
	}

}



var initHoverScroll = function (content,up,down) {
	$(down).observe('mouseover',function(n){
		cont = $(content);
		p = cont.down('ul');
		if (cont.getHeight() < p.getHeight()) {
			l = p.getHeight()-cont.getHeight()+parseInt(p.getStyle('marginTop'));
			newT = cont.getHeight()-p.getHeight();
			currentScroll = new Effect.Morph(p, {
				style: 'margin-top:'+newT+'px', 
				duration: l*0.01
			});
		}
	});
	$(down).observe('mouseout',function(n){
		currentScroll.cancel();
	});
	$(up).observe('mouseover',function(n){
		cont = $(content);
		p = cont.down('ul');
		if (cont.getHeight() < p.getHeight()) {
			l = 0 - parseInt(p.getStyle('marginTop'));
			newT = cont.getHeight()-p.getHeight();
			currentScroll = new Effect.Morph($(cont).down('ul'), {
				style: 'margin-top:0px', 
				duration: l*0.01
			});
		}
	});
	$(up).observe('mouseout',function(n){
		currentScroll.cancel();
	});
}

var getRealDelta = function (event) {
	// normalize the delta
	if (event.wheelDelta) // IE & Opera
	  realDelta = event.wheelDelta / 120;
	else if (event.detail) // W3C
	  realDelta = -event.detail / 3;
	return realDelta;
}

var currentScroll;

/***********************************************************************/
getWindowSize = function(w) {
var array = [];

w = w ? w : window;
array.width = array[0] = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
array.height = array[1] = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);

return array;
}

var changeTab = function(n) {
	$$('.entry-list-header .tabs li').each(function(n){
		$(n).removeClassName('active');
		$(n).removeClassName('first');
	});
	$$('.entry-list-header .tabs li:first')[0].addClassName('first');
	if ($('all-tabs-link')) $('all-tabs-link').removeClassName('all-tabs-selected');

	if ($(n).id=='all-tabs-link') {
			$('all-tabs-link').addClassName('all-tabs-selected');
			count = 40;
	} else {
		$(n).up('li').addClassName('active');
		if ($(n).up('li').next('li')) $(n).up('li').next('li').addClassName('first');
		ar = $(n).up('li').id;
		count = ar.substr(ar.indexOf('_')+1);
	}
	
	$$('.encycl-index .main ul.tags').invoke('hide');
	$$('.encycl-index .main ul.tags').each(function(n){
		if ($(n).id=='tab_content_'+count) { 
			$(n).show(); 
			rr = Math.floor(Math.random()*($(n).childElements().size() - 1));
			ra = $(n).childElements().toArray()[rr];
			changeContent(ra.down('a'));
		} else $(n).hide();
	});
}
	var changeContent = function(link) {
		id = (link=='all-tabs-link'?link:$(link).up('li').id);
		id = id.substr(id.indexOf('_')+1);
		mainImageLink = $('an_'+id).down('a').href;
		
		loadImg = new Image ( 730, 411 );
		loadImg.src = $('imagesrc_'+id).innerHTML;
		loadImg.onload = function () {
		
		
		$('main-image').src = $('imagesrc_'+id).innerHTML;
		
		if ($$('.encycl-index ul.tags li.active').first())
			$$('.encycl-index ul.tags li.active').first().removeClassName('active');
		
		if ($$('.encycl-index .main .info').first())
			$$('.encycl-index .main .info').first().removeClassName('info').addClassName('info-na');
		
		if ($$('.encycl-index .main .v-copy').first()) 
			$$('.encycl-index .main .v-copy').first().removeClassName('v-copy');
		$(link).up('li').addClassName('active').fixpng();

		
		$('main-image').up('a').href = mainImageLink;
		
		
		$('an_'+id).removeClassName('info-na').addClassName('info');
		if (!Prototype.Browser.IE && $('copy_'+id)) {
			conty = $('copy_'+id).down('span').innerHTML;
			if ($('copy_'+id).down('object')==undefined) {
				$('copy_'+id).insert('<object data="data:image/svg+xml; charset=utf-8,<svg xmlns=\'http://www.w3.org/2000/svg\'><text x=\'-300\' y=\'12\' font-family=\'Arial\' font-size=\'9\' fill=\'#c6c6c6\' transform=\'rotate(-90)\' text-rendering=\'optimizeSpeed\'>'+conty+'</text></svg>" type="image/svg+xml"></object>',{
					position:'bottom'
				});
			}
		}
		if ($('copy_'+id)) $('copy_'+id).addClassName('v-copy');
		
		};
	}

Event.observe(window, 'load', function() {
	
	addBrowserNameToBody();
	
	if ($('window-shadow')) {
		
		$('window-shadow').setStyle({height:$('footer').cumulativeOffset().top+$('footer').getHeight()+'px'});
	}
	
$$('.features .header li a').each(function(n){
	$(n).observe('click', function(e){
		$$('.features .header li').each(function(n){
			$(n).removeClassName('active');
			$(n).removeClassName('first');
		});
		$$('.features .header li:first')[0].addClassName('first');
		Event.element(e).up('li').addClassName('active');
		if (Event.element(e).up('li').next('li')) Event.element(e).up('li').next('li').addClassName('first');
		ar = $A(Event.element(e).up('li').classNames());
		count = ar[0].substr(ar[0].indexOf('_')+1);
		$$('.features .blog_content').each(function(n){
			if ($(n).hasClassName('blog_content_'+count)) $(n).show(); else $(n).hide();
		});
		e.preventDefault();
	});
});
$$('.features .blog_content').each(function(n){
	t=$A($(n).classNames());
	count = t[1].substr(13);
	liA = $$('.features .header li.blog_'+count).first();
	if (liA.hasClassName('active')) $(n).show(); else $(n).hide();
	
});

	$$('.entry-list-header .tabs:not(.truelink) li a').each(function(n){
		$(n).observe('click', function(e){
			e.preventDefault();
			changeTab(n);
		});
	}); 

	$$('.features .blog_content').each(function(n){
		t=$A($(n).classNames());
		count = t[1].substr(13);
		if ($$('.features .header li.blog_'+count) && !$$('.features .header li.blog_'+count).first().hasClassName('active')) $(n).hide();
		
		if ($('features-2nd-list-'+count)) {
			initScrollBlock($('features-2nd-list-'+count),$('f-bl-prev-'+count),$('f-bl-next-'+count),3,'gal_pre_','gal_img_');
			/*
			$('features-2nd-'+count).observe('mouseover',function(e){
				$('features-2nd-'+count).addClassName('hover');
			});
			
			$('features-2nd-'+count).observe('mouseout',function(e){
				$('features-2nd-'+count).removeClassName('hover');
			});*/
		}
	});
	$$('.encycl-index ul.tags li a').each(function(n){
		if ($('main-image')) {
			var mainImageLink = '';
		}
		$(n).observe('click', function(e){
			link=Event.element(e);
			e.preventDefault();
			changeContent(link);
		});
	});
	if ($('all-tabs-link')) {
		$('all-tabs-link').observe('click',function(e){
			e.preventDefault();
			if (!$('all-tabs-link').hasClassName('all-tabs-selected')) {
				changeTab('all-tabs-link');
			}
		});
		changeTab('all-tabs-link');
	}
	
/************************************ENTRY GALLERY INIT**************************************/
	
	$$('.entry-body .gallery .preview').each (function(n,i){
		$(n).up('.gallery').select('.big-image','ul li img').each(function(k){
			$(k).id=i+'_'+$(k).id;
		});
		initScrollBlock($(n).down('ul'),$(n).down('.prev'),$(n).down('.next'),3,i+'_gal_pre_',i+'_gal_img_');
	});
	
/*********************************FONT SIZE CHANGER*******************************************/
	
	var fontSizeClasses = new Array ('small-text','normal-text','big-text');
	var setFontSize = function (el, value) {
        fontSizeClasses.each(function(n) {
            el.removeClassName(n);
        });
        el.addClassName(fontSizeClasses[value]);
    };
	
	$$('.font-size-changer a').invoke('observe','click',function(e){
		e.preventDefault();
        var el = Event.element(e);
        var entry = el.up('.entry-body');
		delta = (el.hasClassName('plus')?1:-1);
        var currentV = (entry.hasClassName('small-text') ? 0 : (entry.hasClassName('big-text') ? 2 : 1));
		delta = currentV + delta;
		if (delta<=2 && delta>=0) {
			setFontSize(el.up('.font-size-changer'),delta);
			setFontSize(entry,delta);
		}
	});
	
/****************************************FIXPNG***********************************************/
	
	$$('.png').each (function(n){
			$(n).fixpng();
		});
	
/*********************************BLOCK SHADOWS**********************************************/
	
		$$('.popup-type1').each(function(n){
			updateBlockShadow(n);
	});
	
});



var morphCount = function (count, cases) {
    //count - количество склонямых объектов
    //cases - падежи объекта ['объект','объекта','объектов']
    if (cases) {

        var l = count % 10,
                ll = count % 100,
                res;

        if (l <= 4 && l > 0)
        {
            res = cases[1]; //объекта
            if (l == 1 && ll != 11)
            {
                res = cases[0]; //объект
            }

            if ([0,11,12,13,14].include(ll))
            {
                res = cases[2]; //объектов
            }
        }
        else
        {
            res = cases[2]; //объектов
        }

    }

    return res;
};


/*****************************************************************************************************/

//var JvScrollBlock

var PlusMinusSwitcher = Class.create({
	initialize: function(block) {
		this.block = $(block);
		
		if (!Object.isElement(this.block))
			return;
		
		this.block.select('.content .pm-navigation li a').invoke('observe', 'click', this.switchContent.bindAsEventListener(this));
	},
	switchContent: function(e) {
		Event.stop(e);
		var element = Event.findElement(e, 'A');
		var controls = this.block.select('.content .pm-navigation li a');
		var content = this.block.down('.content .pm-tabs');
		
		if (!element.hasClassName('active')) {
			controls.invoke('toggleClassName', 'active');
			content.toggleClassName('minuses');
		} else {
			return;
		}
	}
});

var DietTableSwitcher = Class.create({
	initialize: function(block)
    {
		this.block = $(block);
		this.controls = this.block.select('.controls li a');
		this.contents = this.block.select('.inner > div');
		
		if (!Object.isElement(this.block))
			return;
		
		//this.contents.invoke('setStyle', {height: this.contents.invoke('getHeight').max() + 'px'});
		
		this.block.select('.controls li a').invoke('observe', 'click', this.switchContent.bindAsEventListener(this));
	},
	switchContent: function(e)
    {
		Event.stop(e);
		var element = Event.findElement(e, 'A');
		
		if (!element.hasClassName('active')) {
			this.controls.invoke('removeClassName', 'active');
			element.addClassName('active');
			
			this.contents.invoke('hide');
			this.id = parseInt(element.up('li').readAttribute('id').replace('tab_', ''), 10);
			$('block_' + this.id).show();
		} else {
			return;
		}
	}
});

document.observe("dom:loaded", function() {

/********************HOVER LISTENER************************************/

		$$('.hover-listener').each(function(n){
		if (Prototype.Browser.IE) {
			$(n).hover(
			  function(event) {
				$(this).addClassName('hover');
                  $(this).fire('b:hover');
			  },
			  function(event){
				$(this).removeClassName('hover');

			  }
			);
		} else {

			$(n).observe('mouseover',function(e){
                var ev;
				el = Event.element(e);
				if (el.hasClassName('hover-listener'))
					ev = el;
				else
					ev = el.up('.hover-listener');
				$(ev).addClassName('hover');
                $(ev).fire('b:hover');
			});

			$(n).observe('mouseout',function(e){
				el = Event.element(e);
                var ev;
				if (el.hasClassName('hover-listener'))
					ev = el;
				else
                    ev = el.up('.hover-listener');
				$(ev).removeClassName('hover');
			});
		}
	});

});