ie6 = $.browser.msie && /MSIE (6).+Win/.test(navigator.userAgent) && !/MSIE (7|8|9).+Win/.test(navigator.userAgent);
ie7 = $.browser.msie && /MSIE (7).+Win/.test(navigator.userAgent) && !/MSIE (8|9).+Win/.test(navigator.userAgent);
$.fn.delayedHover = function (over, out, delay) {
	var timerIn = false;
	var timerOut = false;

	if ( ! delay) {
		var delay = 500;
	}

	return this.hover(function() {
		clearTimeout(timerIn);
		clearTimeout(timerOut);
		var el = this;
		if ($.isFunction(over)) {
			timerIn = setTimeout(function(){ over.apply(el) }, delay);
		}
	}, function(){
		clearTimeout(timerIn);
		clearTimeout(timerOut);
		var el = this;
		if ($.isFunction(out)) {
			timerOut = setTimeout(function(){ out.apply(el) }, delay);
		}
	})
}
function fixPNG(element) {
	/*
	 * browser checking in fixPNG is depricated
	 */
	//if (/MSIE (5\.5|6|7|8|9).+Win/.test(navigator.userAgent))	{
		var src;
		if ( typeof element != 'object') {
			element = this;
		}
		if (element.getAttribute('src'))	{
			//if (/\.png$/.test(element.getAttribute('src'))) {
				src = element.getAttribute('src');
				element.src = "/images/blank.gif";
			//}
		} else {
			element.runtimeStyle.backgroundImage = "";
			src = element.currentStyle.backgroundImage.match(/url\("(.+)"\)/i);
			if (src) {
				src = src[1];
				element.runtimeStyle.backgroundImage = "none";
			} else {
			}
		}
		if (src) element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
	//}
}

function fixIE() {
	if ($.browser.msie) {
		$('.png').each(fixPNG);
		$('#main-menu a.item:first-child').addClass('first-child');
		$('.chain span:last-child').addClass('last-child');
		if(ie6) {
			$('.fixpng6').each(fixPNG);
		}
	}

	$('#catalog ins').hover(function() {$(this).addClass('hover');}, function() {$(this).removeClass('hover');});

}

function init_popup() {
	var flag = false;
	var main = $('body');
	var popup = $('#popup-order');
	var button = $('#popup-button-01>a');
	var close_button = $('#popup-order img.close-button');
	
	button.click(function() {
		popup.slideDown();
		flag = true;
		return false;
	});
	
	popup.hover(function() {
		flag = false;
	}, function() {
		flag = true;
	});

	main.click(function() {
		if(flag) {
			popup.slideUp();	
		}
	});
	
	close_button.click(function() {
		popup.slideUp();
		return false;
	});
}

function init_inner_popup() {
	var flag = false;
	var main = $('body');
	var popup = $('#inner-popup');
	var button = $('#popup-inner-button');
	var close_button = $('#inner-popup img.close-button');

	button.click(function() {
		popup.slideDown();
		flag = true;
		return false;
	});

	popup.hover(function() {
		flag = false;
	}, function() {
		flag = true;
	});

	main.click(function() {
		if(flag) {
			popup.slideUp();	
		}
	});
	
	close_button.click(function() {
		popup.slideUp();
		return false;
	});
}

function init_tablesorter() {
	var table = $('.catalog-table');
	table.tablesorter();
}
function init_fancybox() {
	$('a[rel=gallery]').fancybox();
	$('a[rel=draw]').fancybox();
	$('a.gallery').fancybox();
}
$(function() {
	var main_cat_item = $('#cat td.item');
	var main_cat_item_image = main_cat_item.find(".item-image-color");
	var main_cat_list = $('#cat .item .list');
	var main_cat_parent = $('#cat .item a.title[rel=dash]');
	var cat_menu = $('#content .left-coll');
	var cat_first = $('#content .left-coll .item > a.first');
	var cat_second = $('#content .left-coll .item .sub > a.second');
	var catalog_item = $('#catalog .item h2, #catalog .item img');
	var catalog_item_image = $('#catalog .item');
	var catalog_sub = $('#catalog .item ins h3');
	var opt = $('a.dalink');
	var opt_cont = $('div.dalink');
	var image_src = 0;
	var timeout = false;

	fixIE();

	init_popup();
	init_inner_popup();
	init_tablesorter();
	init_fancybox();
	
	opt.click(function() {
		opt_cont.toggleClass('hidden');
		return false;
	});
	catalog_sub.parent().delayedHover(function() {
		$this = $(this);
		if($this.attr('href')) {
			if(!image_src) {
				image_src = $this.parent().find('img').attr('src');
			}
			$this.parent().find('img').attr('src', $this.attr('href'));
		}
	},
	function() {
		$this = $(this);
		if(image_src) {
			$this.parent().find('img').attr('src', image_src);
			image_src = 0;
		}
	}, 100);

	catalog_sub.click(function() {
		$this = $(this);
		$this.parent().toggleClass('hide');
	});
	cat_first.click( function() {
		var $this = $(this);
		$this.parent().toggleClass('hide');
		return false;
	});
	cat_second.click( function() {
		var $this = $(this);
		$this.parent().toggleClass('hide');
		return false;
	});
	
	var animate_main_cat_item = function(list) {
		var _this 			= this;
		this.list 			= list;
		this.currentElement = false;
		this.hideCalled 	= false;
		
		this.show = function($thisItem) {
			var $thisImage = $thisItem.find(".item-image-color");
			_this.currentElement = $thisImage;
			_this.hide();
			$thisImage.css({opacity: ""})
				.show();
		};
	
		this.showAnimate = function($thisItem) {
			var $thisImage = $thisItem.find(".item-image-color");
			_this.currentElement = $thisImage;
			if(!$thisImage.is(":visible")) {
				$thisImage.show()
					.css({opacity: 0});
			}
			$thisImage.stop(true)
				.animate({opacity: 1}, {
					easing: "swing",
					duration: 500,
					complete: function() {
						_this.show($thisItem);
					}
			});
		};
		
		this.hide = function(all) {
			if(all) {
				_this.currentElement = false;
				_this.list.removeAttr("style");
			} else {
				_this.list.not(_this.currentElement)
					.removeAttr("style");
			}
		};
		
		this.hideAnimate = function() {
			_this.hideCalled = false;
			_this.list.stop(true)
				.animate({opacity: 0}, {
					easing: "swing",
					duration: 500,
					complete: function() {	
						if(!_this.hideCalled) {
							_this.hide();
						}
						_this.hideCalled = true;
					}
			});
		};
	};

	if(main_cat_item.length) {
		var animateObj = new animate_main_cat_item(main_cat_item_image);
		main_cat_item.click(function() {
			var $this = $(this);
			clearTimeout(timeout);
			timeout = setTimeout(function(e) {
				$this.addClass('hide');
			}, 2000);

			var isHasClass = $this.hasClass('hide');
			main_cat_item.addClass('hide');
			if(isHasClass) {
				$this.removeClass('hide');
			}
		}).hover(function(){
			animateObj.showAnimate($(this));
		}, function(){
			animateObj.hideAnimate();
		});
	}
	
	if(catalog_item_image.length) {
		var animateObj = new animate_main_cat_item(catalog_item_image.find(".item-image-color"));
		catalog_item_image.hover(function(){
			animateObj.showAnimate($(this).find("div.item-image"));
		}, function(){
			animateObj.hideAnimate();
		});
	}

	main_cat_parent.click(function() {
		var $this =$(this);
		$this.parent().find('.sub').toggleClass('hide');
		return false;
	});

	main_cat_list.hover(function() {
		clearTimeout(timeout);
	},
	function() {
		var $this = $(this);
		timeout = setTimeout(function(e) {
			$this.parent().addClass('hide');
		}, 2000);
	});
	
	$(".yandex-map").each(function(){
		InstallYandex($(this));
	});
	InstallCatalogItem();
	InstallUppod();
	InstallForms();
	InstallBenefits();
	InstallResizeImages();
	InstallLanguage();
});

function InstallYandex(elem)
{
	if (typeof elem == "undefined") {
		if (!$("#yandex-map").length) {
			return;
		}
		elem = $("#yandex-map");
	}
	if(elem.data("yandex") == 1) { 
		return; 
	}
	
	var fYandexMap = function($yandexMap) {
		$yandexMap.html("");
		var map;
		var points = $yandexMap.attr("points").split(",");
		for(i in points) {
			points[i] = parseFloat(points[i]);
		}
		map = new YMaps.Map( $yandexMap[0] );
		map.setCenter( new YMaps.GeoPoint( points[0], points[1] ), 16, YMaps.MapType.MAP );
		Zoom = new YMaps.Zoom();
		TypeControl = new YMaps.TypeControl();
		TypeControl.removeType(YMaps.MapType.HYBRID);
				
		if ($yandexMap.attr("baloon").length) {
			var content = document.createElement('span');
			content.innerHTML = $yandexMap.attr("baloon");
			map.openBalloon(new YMaps.GeoPoint( points[0], points[1] ), content);
		}
				
		map.addControl(Zoom);
		map.addControl(TypeControl);
	}
	
	fYandexMap(elem);
	elem.data("yandex", 1);
}

function InstallCatalogItem()
{
	$item = $(".cat-item");
	if(!$item.length) return;
	
	$catItemAddText = $(".cat-item-add-text");
	$(".cat-item-add", $item).bind("click", function(){
		$catItemAddText.slideToggle();
		$(this).toggleClass("cat-item-open");
		return false;
	});
	
	if(ie6) {
		var $c = $("#content .right-coll .cat-item .draw");
		$("ins.l", $c).css("height", $("img", $c).height()+27+"px");
	}
}

function InstallUppod()
{
	$(".uppod-video").each(function(){
		var $this = $(this);
		var flashvars = {"comment": $this.attr("comment") ,"st":"/js/uppod/video105-186.txt", "file": $this.attr("file")};
		var params = {wmode:"transparent", allowFullScreen:"true", allowScriptAccess:"always"}; 
		new swfobject.embedSWF("/js/uppod/uppod.swf", $this.attr("id"), "800", "450", "9.0.0", false, flashvars, params);
	});
}

function InstallResizeImages()
{
	var $images = $(".right-coll .content").find("img.resize");
	if(!$images.length) return;
	
	$images.each(function(){
		$(this).data("width", $(this).width());
		$(this).data("height", $(this).height());
	});
	
	$(window).bind("resize", function(){
		var width = $(".right-coll .content").width();
		$images.each(function(){
			var $this = $(this),
				k = width/$this.data("width");
			if(k >= 1) {
				$this.removeAttr("style");
				return;
			}
			$this.css({
				width: parseInt($this.data("width") * k) + "px",
				height: parseInt($this.data("height") * k) + "px"
			});
		});
	}).trigger("resize");
}

function InstallForms() {
	
	$(".forms1, .forms2").each(function(){
		$(this).append("<input type='hidden' name='ajax' value='true' />");
	});
	
	$("#popup-order, #inner-popup").each(function(){
		var $this 	= $(".popup", $(this)),
			$result = $(".popup-results", $this),
			$loader = $(".popup-loader", $this),
			$form 	= $("form", $this),
			loading = false;
			
		$form.bind("submit", function(){
			if(loading) return;
			var i = 0;
			$form.find("p.label").each(function() {
				if(    $("input[type='text']", $(this)).attr("value")
					|| $("textarea", $(this)).attr("value")
					|| $("select", $(this)).attr("value")
					|| $("input[type='radio']", $(this)).attr("checked")
					|| $("input[type='checkbox']", $(this)).attr("checked")
				) {
					i++; return;
				}
			});
			if (!i) return false;
			loading = true;
			$form.hide();
			$result.hide();
			$loader.show();
			
			$.post($form.attr("action"), $form.serialize(), function(data){
				$loader.hide();
				$form.show();
				loading = false;
				if(data.error) {
					$result.html(data.error).show();
				} else if(data.text) {
					
					if (($form.attr('id') == 'add_question_form') && ($form.find('[name="cc"]').val() == 67))
					{
						yaCounter4482094.reachGoal('call_order');
					};
					
					$result.html(data.text).show();
					$form.hide();
				} else if (data.location) {
					window.location = data.location;
				}
			}, "json");
			return false;
		});
		
		$(".close-button", $this).bind("click", function(){
			$loader.hide();
			$result.hide();
			$form.show();
		});
	});
}

function InstallBenefits() {
	var menu_item = $('#main-menu .menu .item');
	menu_item.each(function() {
		$this = $(this);
		if($this.text() == 'преимущества' || $this.text() == 'Преимущества' || $this.text() == 'advantages' || $this.text() == 'Advantages') {
			$this.addClass('gray');
		}
	});

	var $aLink = $("#benefits .item a");
	if(!$aLink.length) return;
	
	var $image = $("#benefits img.ben"),
		$bNav = $("#benefits .benefits-nav"),
		$item = $("#benefits .item");
		imageWidth = $image.width(), 
		imageHeight = $image.height(),
		$benCont = $('#ben-cont');
		
	$benCont.data("default", $benCont.html());
		
	$aLink.click(function() {
		$this = $(this);
		var hasClass = $this.hasClass("current");
		$aLink.removeClass("current");
		if(hasClass) {
			$benCont.html($benCont.data("default"));
			return false;
		}
		
		$this.addClass("current");
		$benCont.html($('#ben-content div.'+$this.attr('rel')).html());
		return false;
	});
		
	$item.each(function(){
		$(this).data("top", parseInt($(this).position().top));
	});
		
	$(window).bind("resize", function(){
		var maxWidth = $bNav.width() - 280;
		maxWidth += ($.browser.msie && ie6) ? 30 : 0;
		var k = maxWidth / imageWidth;
		
		if(maxWidth >= imageWidth) {
			$image.removeAttr("style");
			$item.each(function(){
				$(this).css({top: $(this).data("top")+"px"});
			});
		} else {
			$image.css({width: maxWidth+"px", height: parseInt(imageHeight*k)+"px"});
			$item.each(function(){
				$(this).css({top: parseInt($(this).data("top")*k)+"px"});
			});
		}
	}).trigger("resize");
}

function InstallLanguage() {
	var $el = $(".lang-select"),
	    $main = $("#main");
	if( !$el.length ) return;
	
	$(window).bind("resize", function(){
		if ( $main.width() > 1045 ) {
			$el.removeAttr("style");
		} else {
			if(ie7) {
				setTimeout(function(){
					$el.removeAttr("style");
					$el.css({top: "-40px"});
				}, 500);
			} else if(!ie6) {
				$el.css({top: "-40px"});
			}
		}
	}).trigger("resize");
}

$(document).ready(function(){
	
	$('.blinked').css('cursor', 'pointer');
	
	blinkthis = setInterval(function(){
	
	if ($('.blinked').children().css('visibility') == 'visible')
	{
		$('.blinked').children().css('visibility', 'hidden');
	} else
	{
		$('.blinked').children().css('visibility', 'visible');	
	};
									 
	}, 250);
	
	$('.blinked').click(function(){
	
		document.location.href = $(this).find('a').attr('href');
	
	});
});
