function place(a){
	x=$(a)[0];
	var left = x.offsetLeft;
	var top = x.offsetTop;
	for (var parent = x.offsetParent; parent; parent = parent.offsetParent) {
		left += parent.offsetLeft - parent.scrollLeft;
		top += parent.offsetTop - parent.scrollTop;
	}
	return {left: left, top: top, width: x.offsetWidth, height: x.offsetHeight};
}
function getScrollTop() {
	return self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
}
function getScrollLeft()   {
	return self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;
}
function MouseEvent(e) {
	this.x = e.pageX;
	this.y = e.pageY;
	return this;
}


/*Popups begin*/
var totalpop = 0;
$.fn.showPopup = function(o) {
	totalpop++;
	var opts = $.extend({
			close:true,
			opacity:.7,
			onLoad:function(){},
			onClose:function(){}},
		o || {}), 
		$source = this,
		currentpop = totalpop,
		ie6 = ($.browser.msie && $.browser.version < 7),
		$overlay =  $('<div class="kvvoverlay" style="position:absolute;z-index:'+(1001+totalpop*3)+';padding:0;border:0;margin:0;top:0;left:0;width:100%;display:none;"/>');
	if (ie6) {
		$('body').addClass("noselects");
	}
	$('body').append($overlay);
	var temporary=document.createElement('div');
	var parent = $source[0].parentNode;
	document.body.appendChild(temporary);		
	if(parent){
		parent.insertBefore(temporary, $source[0]);
	}
	var $self = $('<div class="kvvp" style="display:none" />');
	if(opts.close){
		$self[0].innerHTML='<i class="icon close" title="Закрыть"></i>';
	}
	$self[0].appendChild($source[0]);
	$source.addClass("display");
	document.body.appendChild($self[0]);
	$source.addClass("display").addClass("left");
	$self.addClass("left");
	$self.css({zIndex: 1002+totalpop*3});
	setSelfPosition();
	setOverlayHeight();
	$overlay.css({background: 'black', opacity: opts.opacity});
	$overlay.fadeIn(500, function() {$("body").removeClass("progress");});
	$self.fadeIn(500, function() { setOverlayHeight(); opts.onLoad()});
	$(window).resize(setOverlayHeight)
		.resize(setSelfPosition)
		.scroll(setSelfPosition);
	$(window).bind('keydown', observeEscapePress);
	$self.find('.close').click(function() { removeModal(); return false; });
	$overlay.click(function() { removeModal(); return false; });
	$source.bind('close', removeModal);
	$self.bind('resize', setSelfPosition);
	$overlay[0].removeModal = removeModal;
	function removeModal() {
		removeOverlay();
		$self.fadeOut(300, function() {
			$self.find('.close').unbind('click');
			$source.unbind('close', removeModal);
			$self.unbind('resize');
			$(window).unbind('scroll', setSelfPosition);
			$(window).unbind('resize', setSelfPosition);
			$(window).unbind('keydown', observeEscapePress);
			if(parent){
				try {
					$source.removeClass("display");
					parent.insertBefore($source[0], temporary);
				}catch(e){}
			}
			$self.remove();
			$source.removeClass("left").removeClass("display");
			$(temporary).remove();
			totalpop--;
			if (ie6) {
				$('body').removeClass("noselects");
			}
		});
	}
	function removeOverlay() {
		$overlay.unbind('click');
		$overlay.fadeOut(350, function() {
			$(window).unbind('resize', setOverlayHeight);
			$overlay.remove();
			opts.onClose();
		})
	}
	function observeEscapePress(e) {
		if(e.keyCode == 27 || (e.DOM_VK_ESCAPE == 27 && e.which==0)){
			if (currentpop>=totalpop) {
				removeModal(); 
			}
		}
	}
	function setOverlayHeight() {
		if ($(window).height() < $(document).height()) {
			$overlay.css({height: $(document).height() + 'px'});
		} else {
			$overlay.css({height: '100%'});
			if (ie6) {$('html,body').css('height','100%'); }
		}
		if ($(window).width() < $(document).width()) {
			$overlay.css({width: $(document).width() + 'px'});
		} else {
			$overlay.css({width: '100%'});
		}
		if(ie6){$overlay.css({width: document.body.clientWidth+'px'});}
	}
	function setSelfPosition() {
		var s = $self[0].style;
		if ($self.height() + 80  >= $(window).height() && ($self.css('position') != 'absolute' || ie6)) {
			var topOffset = getScrollTop() + 15;
			$self.css({position: 'absolute', top: topOffset + 'px', marginTop: 0})
			if (ie6) {s.removeExpression('top');}
		} else if ($self.height()+ 80  < $(window).height()) {
			if (ie6) {
				s.position = 'absolute';
				s.setExpression('top', '(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"')
				s.marginTop = 0;
			} else {
				$self.css({ position: 'fixed', top: '50%', marginTop: (Math.round($self.outerHeight() / 2) * -1)+"px"});
			}
		}
		if ($(window).width() < ($self.width() + 80)) {
			$self.css({left: '20px', marginLeft: 0});
		} else {
			$self.css({left: '50%', marginLeft: -1 *Math.round($self.outerWidth() / 2)});
		}
	}
}
$.fn.hidePopup = function(options) {
	$(this).trigger('close');
}
/*Popups end*/

/*Disable selection begin*/
$.fn.disableSelection = function() {
	this.each(function() { 
		this.onselectstart = function() { return false; }; 
		this.unselectable = "on"; 
		jQuery(this).css('-moz-user-select', 'none'); 
	});
}
/*Disable selection end*/

/*Gallery begin*/
function gallery(fullimg) {
	var gallery = $('<div class="kvvg" />'),
		ie7 = ($.browser.msie && $.browser.version < 8),
		origwidth,
		origheight,
		ss;
	
	var source = $('.thumbimg');

	function circle(x) {
		current=0;
		for(var i=source.length-1;i>-1;i--){
			if('g-'+source[i].id==image.attr('id')){
				current = i;
				break;
			}
		}
		
		fadeable = false;
		gallery.find('.prev').css('visibility','visible');
		gallery.find('.next').css('visibility','visible');
		var res = current+x;
		if (res<=0) {
			gallery.find('.prev').css('visibility','hidden');
			res = 0;
		}
		if (res>=source.length-1) {
			gallery.find('.next').css('visibility','hidden');
			res = source.length-1;
		}
		if(x==0)return;
		phrase.html((res+1)+" / "+source.length);
		$(source[res]).click();
		//if (res != current+x)return res;
		image.parent().addClass('wait');
		image.attr('src',source[res].src.replace('_t','')).attr('id','g-'+source[res].id);
		return res;
	}
	function setSize() {
		wk = ($(window).width()-80)/(origwidth); // maybe to change 80, 125
		hk = ($(window).height()-155)/(origheight);
		iwidth = origwidth;
		iheight = origheight;
		if((wk<1)||(hk<1)){
			if(wk<=hk){
				iwidth = Math.round(wk*origwidth);
				iheight = Math.round(wk*origheight);
			} else {
				iwidth = Math.round(hk*origwidth);
				iheight = Math.round(hk*origheight);
			}
			if(iwidth<250){iwidth=250;iheight=Math.round(250/ss);}
			if(iheight<250){iheight=250;iwidth=Math.round(250/ss);}		
			image.css({width: iwidth + "px", height: iheight + "px"});
		}
		container.css({width: iwidth + "px", height: iheight + "px"});
		if (ie7) {
			gallery.css({width: iwidth + 0 + "px", height: iheight + 40 + "px"});
		}
	}
	
	var image = $('<img src="'+fullimg.src+'" id="'+fullimg.id.replace('f-','g-')+'" alt="" />'),
	
		container = $('<div style="zoom:1;display:none;position:relative;clear:both;overflow:hidden" />');

	
	gallery.append(container);
	var prev = $('<i class="prev" style="position:absolute;width:40%;background:transparent;cursor:pointer;height:100%;left:0" />'),
		next = $('<i class="next" style="position:absolute;width:50%;background:transparent;cursor:pointer;height:100%;right:0" />');
	container.append(image).append(prev).append(next);
	
	var fadeable = true;
	image.load(function(){
		container.css('display','block');
		image.css({width: 'auto', height: 'auto'});
		origwidth = image.width();
		origheight = image.height();
		ss = origwidth/origheight;
		setSize();
		$(this).parent().removeClass('wait');
		image.fadeIn(250, function(){
			gallery.trigger('resize');
			fadeable = true;
		});
	})
	gallery.disableSelection();
	$(window).bind('resize', setSize);
	var prev = $('<i class="nav icon prev" />');
	var next = $('<i class="nav icon next" />');
	var phrase = $('<span />');
	gallery.append(prev).append(next).append(phrase);
	circle(0);
	gallery.find('.prev').click(function(){
		if(fadeable){
			circle(-1);
		}
	});
	gallery.find('.next').click(function(){
		if(fadeable){
			circle(+1);
		}
	});
	$('body').append(gallery);
	gallery.showPopup({onClose:function(){
		gallery.remove();
		$('.kvvg').remove();
		$(window).unbind('resize', setSize);
	}});
}
$(document).ready(function(){
	$('.fullimg').click(function(){
		gallery(this);
		return false;
	});
});
/*Gallery end*/

/*Tooltips begin*/
function hideTT() {
	$('.kvvtooltip').trigger('close');
}
$.fn.showTooltip = function(par){
	if (this.hasClass('kvvhastooltip')) {
		return 0;
	}
	var $outer = $('<div class="kvvtooltip" style="position:absolute;overflow:hidden;float:left;display:none;z-index:600" />'),
		$tticon = $('<i class="icon tticon" />'),
		$parent = $(par),
		$original = this,
		$copy = this.clone(),
		loaded = false;
	$original.addClass('kvvhastooltip');
	$copy.addClass('tooltip');
	$copy.css('display','block !important')
	$outer.append($tticon).append($copy);
	$('body').append($outer);
	$outer.addClass('tt1');
	$outer.css({width:$outer.width()+"px",height:$outer.height()+"px"});
	$outer.removeClass('tt1');
	function setPlace(){
		pleft = place($parent).left + getScrollLeft() + Math.round(place($parent).width/2);
		ptop = place($parent).top + place($parent).height;
		if ($.browser.webkit) { ptop += getScrollTop() }
		
		a = (window.innerWidth - 20) > ($outer.width() + place($parent).left + Math.round(place($parent).width/2));
		b = (window.innerHeight - 20) > ($outer.height() + place($parent).top + place($parent).height);
		
		$outer[0].className='tt3';
		if(a&&b){
			$outer[0].className='tt1';
		}else{
			if(a){
				$outer[0].className='tt2';
			}else{
				if (b){
					$outer[0].className='tt4';
				}
			}
		}
		$outer.addClass('kvvtooltip');
		
		$outer.css({marginTop: "-3px"});
		if(!b){
			$outer.css({marginTop: (-place($parent).height-$outer.height()+3)+"px"});
		}
		if(!a){
			pleft-=$outer.width();
		}
		$outer.css({left:(pleft)+"px",top:(ptop)+"px"});
	}
	setPlace();
	$outer.fadeIn(100, function() {
		loaded = true;
		$(window).resize(setPlace)
				  .scroll(setPlace)
				  .click(hideTT);
	});
	function destroy() {	
		if (loaded) {
			$outer.fadeOut(100, function() {
				$(window).unbind('resize', setPlace);
				$(window).unbind('scroll', setPlace);
				$(window).unbind('click', hideTT);
				$outer.remove();
				$original.removeClass('kvvhastooltip');
			});
		}
	}
	$outer.bind('close', destroy);
}
/*Tooltips end*/

/*Frame begins*/
function showFrame(url){
	var $frame = $('<div style="display:none" class="frame"></div>');
	$frame[0].innerHTML='<iframe src="'+url+'" scrolling="auto" noresize="noresize">Ошибка просмотра. Вы можете просмотреть содержимое <a href="'+url+'">по ссылке</a>.</iframe>';
	$('body').append($frame);
	$frame.showPopup({onClose:function(){
		$frame.remove();
	}});	
}
/*Frame ends*/
