jQuery.preventDefaultEvent = function(e, options) {
  options = options || {shift:1, ctrl:1, alt:1, meta:1, wheel:1};
  var href = e.currentTarget.href;
  if(((options.shift && e.shiftKey)
    || (options.alt && e.altKey)
    || (options.ctrl && e.ctrlKey)
    || (options.meta && e.metaKey)
    || (options.wheel && e.button == 1))
    && href && href.indexOf('#') != 0
    && href.indexOf('javascript:') != 0
  ) return true;
  e.preventDefault();
  return false;
}

var Data = {};

var deviceAgent = navigator.userAgent.toLowerCase();
isIOS = false;
var iOSID = deviceAgent.match(/(iphone|ipod|ipad)/);
if (iOSID) {
  isIOS = true;
  $("html").addClass(".is-ios");
}

isMobile = false;
var mobileID = deviceAgent.match(/(iemobile|windows ce|netfront|playstation|midp|up\.browser|symbian|nintendo|wii)/);
if (mobileID) {
  isMobile = true;
  $("html").addClass(".is-mobile");
}

var S = {
  initialize: function() {
  this.detectIE();
  this.doubleHover();
	this.removeSelfLinks();
	this.dontClickRSSLinks();

	  this.window = $(window);
	 this.watchWidth.initialize();

	//this.Placeholder.initialize();

	if (!isIE) {
		this.Popover.initialize();
		this.SubMenuPopover.initialize();
	}
	this.checkRequiredFields();
	this.root = $("#root");

	this.wmodeOpaque();

	this.body = $("body");


	this.body.removeClass("js-off");

	this.topNews.initialize();

  },

	watchWidth: {
		initialize: function() {
			var block = $('.js-watch-width');
			if (block.size()) {
				this.block = block;
				this.block.each(function(){
					var $this = $(this);
					$(this).data({mean: $this.attr('data-mean'), size: $this.attr('data-size')});
				});
				this.toggleBlocks();
				S.window.bind('resize', function(){S.watchWidth.toggleBlocks()});
			}

		},
		toggleBlocks: function() {
			this.getWindowWidth();
			this.block.each(function(){
				var $this = $(this);
				var mean = $this.data('mean');
				var size = $this.data('size');
				//console.log(mean, size, S.watchWidth.windowWidth);
				if (mean == 'min') {
					if (size < S.watchWidth.windowWidth) {
						$this.show();
					} else {
						$this.hide();
					}
				} else if (mean == 'max') {
					if (size >= S.watchWidth.windowWidth) {
						$this.show();
					} else {
						$this.hide();
					}
				}
			});
		},
		getWindowWidth: function() {
			this.windowWidth = S.window.width();
		}
	},

	topNews: {
		initialize: function() {
			var container = $('#top-news');
			if (container.size()) {
				this.container = container;
				this.url = '/news.html #top-news';
				this.load();
			}
		},
		load: function() {
			this.container.load(this.url);
		}
	},

	removeSelfLinks: function() {
		// Убираем зацикленные ссылки
		$("a[href$='" + document.location + "']")
		.addClass("current")
		.removeAttr("href")
		.click(function() { return false; } );
	},

	dontClickRSSLinks: function() {
		$('.for-rss').click(function(e){
			e.preventDefault();
		});
	},

	wmodeOpaque: function() {
		var iframe = $("iframe:not(.js-opaque)");
		if (iframe.size()) {
			iframe.each(function(){
				var clone = $(this).clone();
				var src = clone.attr('src');
				var q = src.indexOf("?") > 0 ? '&' : '?';
				clone.attr('src', src+q+'wmode=opaque').addClass("js-opaque");
				$(this).after(clone).remove();
			});
		}

		var object = $("object:not(.js-opaque)");
		if (object.size()) {
			object.each(function(){
				var clone = $(this).clone();
				clone.addClass("js-opaque");
				$('<param name="wmode" value="opaque">').appendTo(clone);
				$("embed", clone).attr({'wmode': 'opaque'});
				$(this).after(clone).remove();
			});
		}
	},

  /* Проверка браузера — ИЕ, Вебкит, Айось? */
  detectIE: function() {
    isIE = false;
    isIE6 = false;
    isIE7 = false;
    isWebkit = false;
    if (jQuery.browser.msie) {
      isIE = true;

      if ('6.0' == jQuery.browser.version) {
        isIE6 = true;
      }

      if ('7.0' == jQuery.browser.version) {
        isIE7 = true;
      }
    }
    if (jQuery.browser.webkit) {
      isWebkit = true;
    }
  },

  /* Подсветка парных ссылок (картинка + заголовок, например) */
  doubleHover: function() {
    $("a:not(.dashed)").live("mouseover",
       function() {
         $("a[href='" + $(this).attr("href") + "']").not($(this)).addClass("pseudo-hover");
       }
    );
    $("a:not(.dashed)").live("mouseout",
       function() {
         $("a").removeClass("pseudo-hover");
       }
    );
  },

	/* Проверяем обязательные поля в формах */
	/* Форме, которую хотим проверять на заполненость полей, добавляем класс js-required,
	* обязательным полям и чекбоксам тот же класс — js-required, субмиту .js-submit.
	* Клик на субмите необходимо обрабатывать только если субмит не задизейблен, проверка может быть такой:
		button.click(function(){
			if (!$(this).data("disabled")) {
			}
		});
	* */
	checkRequiredFields: function() {
		var form = $("form.js-required");
		if (form.size()) {
			this.form = form;
			this.form.each(function() {
				form = $(this);
				var submit = $(".js-submit", form);
				$(".js-required", form)
					.live("keyup", checkForEmpty)
					.live("change", checkForEmpty);

				checkForEmpty();

				function checkForEmpty() {
					var fields = $(".js-required", form).filter(":visible");
					var empty = false;
					for (i = 0; i < fields.size(); i++) {
						if (!fields.eq(i).is(":checkbox")) {
							if (!fields.eq(i).val() || fields.eq(i).hasClass("js-error")) {
								empty = true
							}
						} else {
							if (!fields.eq(i).is(":checked")) {
								empty = true
							}
						}
					}

					if (empty) {
						submit.data({"disabled": true}).addClass('b-button_disabled submit_disabled').attr("disabled", "disabled");
					} else {
						submit.data({"disabled": false}).removeClass('b-button_disabled submit_disabled').removeAttr("disabled");
					}
				}
			});
		}
  },

  /* Пласехолдеры из тайтлов в инпутах и текстариях */
  Placeholder: {
    initialize: function() {
      var inputPlaceholder = $("input.js-placeholder");
      var textareaPlaceholder = $("textarea.js-placeholder");
      inputPlaceholder
        .each(function() {
          S.Placeholder.showInputPlaceholder($(this));
        })
        .blur(function() {
          S.Placeholder.showInputPlaceholder($(this));
        })
        .focus(function() {
          var $input = $(this);
          if ($input.val() === $input.attr("title")) {
            $input
              .css({color: "#000"})
              .val("");
          }
        });
      textareaPlaceholder
        .each(function() {
          S.Placeholder.showTextareaPlaceholder($(this));
        })
        .blur(function() {
          S.Placeholder.showTextareaPlaceholder($(this));
        })
        .focus(function() {
          var $textarea = $(this);
          if ($textarea.html() === $textarea.attr("title")) {
            $textarea
              .css({color: "#000"})
              .html("");
          }
        });
    },
    showInputPlaceholder: function($input) {
      if (!isWebkit || !$input.attr("placeholder")) {
        var placeholderText = $input.attr("title");
        if ($input.val() === "" || $input.val() === placeholderText) {
          $input
            .css({color: "#aaa"})
            .val(placeholderText);
        }
      }
    },
    showTextareaPlaceholder: function($textarea) {
      var placeholderText = $textarea.attr("title");
      if ($textarea.val() === "" || $textarea.val() === placeholderText) {
        $textarea
          .css({color: "#aaa"})
          .html(placeholderText);
      }
    }
  },

	/*Запрет выделения мышкой указанного элемента*/
  disableSelection: function (target) {
    target
        .mousemove(function(event){
          event.preventDefault();
        })
        .mousedown(function(event){
          event.preventDefault();
        });
  },

	/*Поповер суб-меню */
	SubMenuPopover: {
		initialize: function() {
			var switcher = $("#sub-menu .toswitch");
			if (switcher.size()) {
				this.switcher = switcher;
				this.switcher.addClass('switch');
				this.popover = $("#sub-menu-popover");

				S.Popover.set(this.popover, this.switcher, "bottom");


				this.switcher.click(function(e){
					e.preventDefault();
					S.SubMenuPopover.popover.data({'switcher': $(this)});
					if ($(this).hasClass("switch_switched")) {
						S.Popover.hide(S.SubMenuPopover.popover);
					} else {
						S.SubMenuPopover.showSection($(this).attr("data-section"));
						S.Popover.show(S.SubMenuPopover.popover);
						S.SubMenuPopover.switcher.not($(this)).removeClass('switch_switched');
					}
				});
			}
		},
		showSection: function(id) {
			var sectionId = '#sub-menu__' + id;
			$(sectionId).show().siblings().hide();
		}
	},

  /*Класс для вызова и рисования поповеров, можно настроить связь между переключалкой и поповером,
  задать позиционирование поповера, относительно переключалки, скрывать показывать поповер, перерисовывать при изменении хтмл внутри */
	Popover: {
	  container: $(),
	  switcher: $(),
	  initialize: function() {
		  $(document).click(function(){
			    if (S.Popover.container.size()) {
						S.Popover.hide(S.Popover.container);
			    }
		  });
		  
		  var close = $(".b-popover__close");
		  close.click(function(){
			  //console.log("close click");
			  //console.log($(this).parents(".b-popover"));
			  S.Popover.hide($(this).parents(".b-popover"), true);
		  });
	  },
	  set: function(container, switcher, position) {
		  var containerById = document.getElementById(container.attr("id"));

		  container.data({"switcher": switcher, "close": $(".b-popover__close", container).size() ? true : false, "position": position, "style": container.attr("data-popoverStyle")});
		  this.container = this.container.add(container);

		  container.add(switcher).click(function(e){
			  e.stopPropagation();
			  S.Popover.hide(S.Popover.container.not(container));
		  });

			this.time = 100;



		  S.window.resize($.proxy(function(){
          clearTimeout(this.resizeTimeout);
          this.resizeTimeout = setTimeout($.proxy(function(){
            S.Popover.onResize();
          },this),100);
        },this));
	  },
	  onResize: function() {

			for(i=0;i<this.container.size();i++) {
				var container = this.container.eq(i);
				if (container.data("isVisible")) {
					this.reDraw(this.container.eq(i));
				}
			}
	  },
	  draw: function(container, switcher, position, style, animate) {
			var $container = $(container);
		  var content = $(".b-popover__content", container);

		  var rootWidth = S.root.width() + 50;
		  var rootHeight = S.root.height();
		  var rootLeft = S.root.offset().left;
		  var scrollTop = $(window).scrollTop();

		  var switcherPosition = switcher.offset();
		  var switcherTop = switcherPosition.top;
		  var switcherLeft = switcherPosition.left - rootLeft;
		  var switcherHeight = switcher.height();
		  var switcherWidth = switcher.width();



			var br = 5;
      var ts = 10;
	    var tc = 0;

		  var withShadow = true;
		  var levitate = false;

		  /* !!! 13.09.11 Изменение позиционирования поповеров (начало) */
//		  switch (position) {
//		    case "top":
//				    content.css({"padding-bottom": ts});
//		    break;
//		    case "right":
//				    content.css({"padding-left": ts});
//		    break;
//		    case "bottom":
//				    content.css({"padding-top": ts});
//		    break;
//		    case "left":
//				    content.css({"padding-right": ts});
//		    break;
//	    }

		  content.attr({'class': 'b-popover__content b-popover__content_'+position});

		  /* !!! 13.09.11 Изменение позиционирования поповеров (конец) */

			var strokeColor, backgroundColor;
			switch (style) {
				case "subMenu":
					strokeColor = "#127238";
					backgroundColor = "#f0f7ef";
				break;
				case "error":
					strokeColor, backgroundColor = "#f7bcbc";
					withShadow = false;
				break;
				case "white":
					strokeColor = "#131211";
			    backgroundColor = "#fffefd";
					//withShadow = false;
				break;
	    }

      var w = $container.width();
      var h = $container.height();

		  if (levitate) {
			  var containerCircle = {
						obj: $container,
						r: 3, //радиус окружности
						a: 0, // текущий угол
						/** угловая скорость */
						angle: function(){
							if (!arguments.length) {
									// нет аргументов — работаем как getter
									return this.a;
							} else {
									// есть аргумент — работаем как setter
									this.a = arguments[0];

									// переводим угол из градусов в радианы
									var a = this.a / 180 * Math.PI;

									// считаем новые координаты
									this.obj.css("margin-left", (Math.sin(a) * this.r));
									this.obj.css("margin-top", (Math.cos(a) * this.r)-this.r);
							}
						}
				};

			  $container.data({"circle": containerCircle});

			  $container.mouseenter(function(){
				  jTweener.removeTween(containerCircle);
			  });
			  $container.mouseleave(function(){
				  startLevitate(containerCircle.angle());
			  });

			  setTimeout(function(){
				  startLevitate(0);
			  }, 500);

			  function startLevitate(angle) {
				  jTweener.addTween(containerCircle, {
						time: 1.5, // время круга
						transition: "easenone",
						angle: angle-360, // полный оборот по часовой стрелке
					  onComplete: function() {
						  containerCircle.angle(angle);
						  startLevitate(angle);
					  }
					});
			  }
		  }

		  var popoverLeft, popoverLeftStart, popoverTop, popoverTopStart;

			var d = 2;

			switch (position) {
		    case "top":
				    popoverTop = switcherTop - h - 3;
				    //popoverTopStart = popoverTop + h/2;
		    break;
		    case "right":
				    popoverLeft = switcherLeft + switcherWidth + 3;
				    //popoverLeftStart = popoverLeft - w/2;
		    break;
		    case "bottom":
				    popoverTop = switcherTop + switcherHeight + 3;
				    //popoverTopStart = popoverTop - h/2;
		    break;
		    case "left":
				    popoverLeft = switcherLeft - w - 3;
				    //popoverLeftStart = popoverLeft + w/2;
		    break;
	    }


		  if (position == "top" || position == "bottom") {
			  popoverLeft = switcherLeft + switcherWidth/2 - w/d;
			  var popoverRight = rootWidth - (popoverLeft + w);
			  if (popoverLeft < 10) {
				  tc = popoverLeft - 10;
				  popoverLeft = 10;
			  } else if (popoverRight < 10) {
					tc = -popoverRight + 10;
				  popoverLeft = popoverLeft + (popoverRight - 10);
			  }
				popoverLeftStart = popoverLeft;
		  }

		  if (position == "right" || position == "left") {
			  popoverTop = switcherTop + switcherHeight/2 - h/d;
			  var popoverBottom = rootHeight - (popoverTop + h);
			  if (popoverTop - scrollTop < 10) {
					tc = popoverTop - scrollTop - 10;
					popoverTop = scrollTop + 10;
				} else if (popoverBottom < 10) {
					tc = -popoverBottom + 10;
					popoverTop = popoverTop + (popoverBottom - 10);
				}
			  popoverTopStart = popoverTop;
		  }
			if (animate != "position") {
		    $container.css({"left": popoverLeft, "top": popoverTop});
			} else {
				$container.animate({"left": popoverLeft, "top": popoverTop}, 250);
			}
		  //$container.css({"left": popoverLeftStart, "top": popoverTopStart});
		  //$container.animate({"left": popoverLeft, "top": popoverTop}, S.Popover.time*2);

      function path(w, h, brPlus) {
        var t = 0;
        var r = w;
        var b = h;
        var l = 0;

	      if (brPlus) {
		      br = br + brPlus;
	      }

	      var topTail, rightTail, bottomTail, leftTail;


	      switch (position) {
					case "top":
						b = b - ts;
	          bottomTail = ("L"+(w/d+tc+ts)+","+b) + ("L"+(w/d+tc)+","+(b+ts)) + ("L"+(w/d+tc-ts)+","+b);
					break;

		      case "right":
						l = l + ts;
	          leftTail = ("L"+l+","+(h/d+tc+ts)) + ("L"+(l-ts)+","+(h/d+tc)) + ("L"+l+","+(h/d+tc-ts));
					break;

		      case "bottom":
						t = t + ts;
	          topTail = ("L"+(w/d+tc-ts)+","+t) + ("L"+(w/d+tc)+","+(t-ts)) + ("L"+(w/d+tc+ts)+","+t);
					break;

		      case "left":
				    r = r - ts;
	          rightTail = ("L"+r+","+(h/d+tc-ts)) + ("L"+(r+ts)+","+(h/d+tc)) + ("L"+r+","+(h/d+tc+ts));
					break
				}

        var path = ("M"+(l+br)+","+t) + topTail + ("L"+(r-br)+","+t) + ("S"+r+","+t+","+r+","+(t+br)) + rightTail + ("L"+r+","+(b-br)) + ("S"+r+","+b+","+(r-br)+","+b) + bottomTail + ("L"+(l+br)+","+b) + ("S"+l+","+b+","+l+","+(b-br)) + leftTail + ("L"+l+","+(t+br)) + ("S"+l+","+t+","+(l+br)+","+t);
        //console.log(path);
        return path;

      }

      var shadowBlur = 3;
      var shadowPadding = 10;

      var shadowPath = path(w,h);
      var shadowTranslation = ("0,0");
      var strokePath = path(w - shadowPadding, h - shadowPadding);
      var strokeTranslation = (shadowPadding / 2) + "," + (shadowPadding / 2);
      var backgroundPath = path(w - (shadowPadding + 1), h - (shadowPadding + 1), -1);
      var backgroundTranslation = ((shadowPadding + 1) / 2) + "," + ((shadowPadding + 1) / 2);

		  var paper = $container.data("paper");
			if (paper) {
				paper.remove();
			}

		  paper = Raphael(container, w, h);
			$container.data({"paper": paper});
			var shadow = paper.path(shadowPath);
			$container.data({"shadow": shadow});
		  var stroke = paper.path(strokePath);
			$container.data({"stroke": stroke});
			var background = paper.path(backgroundPath);
			$container.data({"background": background});
		  if (withShadow) {
				shadow.attr({fill: "#020100", opacity: 0.2, "stroke": "transparent", "stroke-width": 0, translation: shadowTranslation});
		  } else {
			  shadow.attr({opacity: 0});
		  }
			stroke.attr({fill: strokeColor, "stroke": "transparent", "stroke-width": 0, translation: strokeTranslation});
      background.attr({fill: backgroundColor, "stroke": "transparent", "stroke-width": 0, translation: backgroundTranslation});

	    if (animate == "full") {
		    var startFrame = {scale: "0.1"};
		    var endFrame = {scale: "1"};
		    var easing = ">";

		    shadow.attr(startFrame);
		    stroke.attr(startFrame);
		    background.attr(startFrame);
		    shadow.animate(endFrame, this.time, easing, function() {
			    $container.addClass("b-popover_visible-content");
			    S.checkRequiredFields()
		    });
		    stroke.animateWith(shadow, endFrame, this.time, easing);
		    background.animateWith(shadow, endFrame, this.time, easing);
	    }
	  },
    show: function(container) {
	    var animate = "full";

	    if (container.data("isVisible")) animate = "position";
	    container.show().data({"isVisible": true});
	    S.Popover.hide(S.Popover.container.not(container));
	    var containerById = document.getElementById(container.attr("id"));
	    var switcher = container.data("switcher");
	    if (switcher.hasClass("switch")) {
				switcher.addClass("switch_switched");
			} else if (switcher.hasClass("b-button")) {
				switcher.addClass("b-button_checked");
			}

	    this.draw(containerById, switcher, container.data("position"), container.data("style"), animate);

	    //фикс поповеров для ИЕ
	    if(isIE){
		    //height = container.find("> div").not(".b-popover__content").height();
				//container.find(".b-popover__content").css({"margin-top":-height});
	    }
    },
	  hide: function(container, force) {
		  var time = this.time;
		  container.each(function(){
			  var container = $(this);
			  var close = container.data("close");
				if (!close || force) {
					// Закрываем поповер, по клику мимо, если у него нет иконки «×», или по клику на эту иконку
					jTweener.removeTween(container.data("circle"));
					var content = $(".b-popover__content", container);
					var paper = container.data("paper");
					var shadow = container.data("shadow");
					var stroke = container.data("stroke");
					var background = container.data("background");

					var switcher = container.data("switcher");
					if (switcher.hasClass("switch")) {
						switcher.removeClass("switch_switched");
					} else if (switcher.hasClass("b-button")) {
						switcher.removeClass("b-button_checked");
					}

					if (shadow && stroke && background) {
						var endFrame = {opacity: "0"};
						var easing = "<";

						container
								.data({"isVisible": false})
								.removeClass("b-popover_visible-content");

						shadow.animate(endFrame, time, easing, function(){
							shadow.remove();
						});
						stroke.animate(endFrame, time, easing, function(){
							stroke.remove();
							background.remove();
							container
								.attr({"style": ""})
								.hide();
						});
					}
				}
		  });
	  },
	  reDraw: function(container) {
		  var containerById = document.getElementById(container.attr("id"));
	    this.draw(containerById, container.data("switcher"), container.data("position"), container.data("style"), false);
	  }
  }
}

$($.proxy(S.initialize, S));


