var _FBOX_PARAMS = { animation: $.browser.msie ? false : true,
                            imagesList: true,
                            imagesListWidth: 120,
                            showOverlay: true,
                            overlayOpacity: 0.7,
                            padding: 0,
                            useLoaderAnim: true,
                            loaderParams: {
                                animatioLength: 400,
                                animationStep: 50,
                                animationTime: 100
                            },
                            navigationButtons: true,
                            navigationButtonsHover: true,
                            constraints: {
                                minWidth: 650,
                                minHeight: 540,
                                maxWidth: 880,
                                maxHeight: 750 }};

$(function() {
  window.tree = new Tree();
  window.region = new Region();

  // Popup submenu
  $("#menu .menu-item").hover(function() {
    /*if (!$.browser.msie) {
      $(".popup-comment", this).stop(true, true).fadeIn(50);
    } else {*/
      $(".popup-comment", this).show();
    //}
  }, function() {
    /*if (!$.browser.msie) {
      $(".popup-comment", this).stop(true, true).fadeOut(50);
    } else {*/
      $(".popup-comment", this).hide();
    //}
  });

  // Galleries
  $(".gallery").each(function() { this.gallery = new Gallery(this); });
  $(".gallery-item a").each(function() {
    //var href = this.href.replace(/http:\/\/.+?\//,"");
    this.fbox = new FBox($.extend({}, _FBOX_PARAMS, {ajax: {url: "/ajax/", href: this.href}}));
    this.onclick = function() { this.fbox.show(); return false; }
  });
  $(".certificate-list a img, .feedback-list a img, .prod-list a img").FBox({ animation: $.browser.msie ? false : true,
                                  imagesList: true,
                                  imagesListWidth: 120,
                                  showOverlay: true,
                                  overlayOpacity: 0.7,
                                  padding: 0,
                                  useLoaderAnim: true,
                                  loaderParams: {
                                      animatioLength: 400,
                                      animationStep: 50,
                                      animationTime: 100
                                  },
                                  navigationButtons: true,
                                  navigationButtonsHover: false,
                                  printButton: true,
                                  constraints: {
                                      minWidth: 650,
                                      minHeight: 540,
                                      maxWidth: 880,
                                      maxHeight: 750 }});
  addLinkHandlers();

  // Content
  $("table.table tr:even").addClass("even");

  // IE fixes
  pngFix();
  ieFix();
});

var pngFix = function() {
  if ($.browser.msie && $.browser.version <= 6) {
    $(".png").each(function() {
      if (this.tagName == "IMG") {
        this.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' +
                          this.src +
                          '", sizingMethod="crop")';
        this.src = "/i/e.gif";
      } else {
        var method = (this.currentStyle.backgroundRepeat == 'no-repeat') ? 'crop' : 'scale';
        this.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' +
                            this.currentStyle.backgroundImage.replace(/.*?url\(\"?(.*?)\"?\).*$/,"$1") +
                            '", sizingMethod="' + method + '")';
        this.style.backgroundImage = "none";
      }
    });
  }
}
var ieFix = function() {
  if ($.browser.msie && $.browser.version <= 7) {
    $("#map").hover(function() {
      $("#body").addClass("uppermost");
    }, function() {
      $("#body").removeClass("uppermost");
    });
  }
}
var addLinkHandlers = function(container) {
  container = container || document.body;
  $("a.popup", container).each(function() {
    if (!this._handler_added) {
      this._handler_added = true;
      $(this).click(function() {
        //var href = this.href.replace(/http:\/\/.+?\//,"");
        (this.fbox = new FBox({animation: $.browser.msie ? false : true,
                           imagesList: false,
                           showOverlay: true,
                           overlayOpacity: 0.7,
                           useLoaderAnim: true,
                           loaderParams: {
                              animatioLength: 400,
                              animationStep: 50,
                              animationTime: 100
                           },
                           navigationButtons: true,
                           navigationButtonsHover: true,
                           constraints: {
                               minWidth: 650,
                               minHeight: 465,
                               maxWidth: 650,
                               maxHeight: 465},
                           ajax: {
                               url: "/ajax/",
                               href: this.href }})).show();
      return false;
      });
    }
  });
}
var submitForm = function(form) {
  var params = $(form).serializeArray();
  params.push({ name: "iface", value: "action/submit" });
  $.post("/ajax/", params, function(data) { parseFormResponse(data, form); }, "xml");
  return false;
}
var parseFormResponse = function(data, form) {
  var successXML = data.getElementsByTagName("success")[0];
  if (successXML) {
    var cnt = _getTextContent(successXML.getElementsByTagName("html")[0]);
    $(form).replaceWith($("<div />").addClass("text").html(cnt));
  } else {
    var errorsXML = data.getElementsByTagName("errors")[0];
    if (errorsXML) {
      $(".error", form).removeClass("error");
      var attrs = errorsXML.getElementsByTagName("attr");
      for (var i = 0; i < attrs.length; i++) {
        $("."+attrs[i].getAttribute("name")).addClass("error");
      }
    }
  }
}
var _getTextContent = function(xmlElement) {
  if (xmlElement.text != undefined) return xmlElement.text;
  if (xmlElement.textContent != undefined) return xmlElement.textContent;
  if (xmlElement.firstChild != undefined) return xmlElement.firstChild.nodeValue;
  return "";
}

var stopPropagation = function(e) {
  e = e || window.event;
  if (e.stopPropagation) {
    e.stopPropagation();
  } else if (e) {
    e.cancelBubble = true;
  }
}

var Region = function() {
  this.$container = $("#head .head-region");
  this.$current = $(".current", this.$container);
  this.$list = $(".popup-comment", this.$container);
  this.$manager = $("#head .head-manager");
  var $a = $("a.active", this.$list);
  if ( $a.length > 0 ) {
    this.currentRegionId = $a.attr("href").split("?")[1].split("=")[1];
  } else {
    this.currentRegionId = -1;
  }
  this.fadeSpeed = 200;

  this.setup();
}
Region.prototype = {
  setup: function() {
    var self = this;
    $(".another", self.$container).click(function() { self.currentClickHandle(); return false; });
    $("a", self.$list).click(function() { self.regionClickHandle(this); return false; });
    self.$list.mousedown(function(e) { stopPropagation(e); });
  },
  currentClickHandle: function() {
    var self = this;
    if (self.$list.is(":visible")) {
      self.hideList();
    } else {
      self.showList();
      $(document).one('mousedown', function(event) { self.hideList(); });
    }
  },
  showList: function() {
    var self = this;
    self.$list.stop(true, true).fadeIn(self.fadeSpeed);
  },
  hideList: function() {
    var self = this;
    self.$list.stop(true, true).fadeOut(self.fadeSpeed);
  },
  regionClickHandle: function(a) {
    var self = this;
    var id = a.href.split("?")[1].split("=")[1];
    if (id != self.currentRegionId) {
      $.ajax({url: "/ajax/",
              dataType: "xml",
              type: "POST",
              data: {node_id: id, iface: 'region'},
              success: function(xml) { self.loadRegion(xml, a) },
              error: function() { document.location.href = a.href }});
    }
    self.hideList();
  },
  loadRegion: function(xml, a) {
    var self = this;
    var id = xml.getElementsByTagName('id')[0];
    if (id) {
      self.currentRegionId = _getTextContent(id);
      self.$current.html(a.innerHTML);
      $("a.active", self.$list).removeClass("active");
      $(a).addClass("active");
      var mContent = _getTextContent(xml.getElementsByTagName('manager')[0]);
      self.$manager.fadeOut(self.fadeSpeed, function() { $(this).html(mContent).fadeIn(self.fadeSpeed, function() { addLinkHandlers(this); }); });
    }
  }
}

var Map = function() {
  this.$container = $("#map .map-container");
  this.$nav = $("#map .map-nav");

  this.fadeSpeed = $.browser.msie ? 0 : 200;

  this.setup();
}
Map.prototype = {
  setup: function() {
    var self = this;
    $("a", self.$nav).click(function() {
      self.navClickHandle(this.rel);
      return false;
    });
    $("area", self.$container).each(function() {
      var $area = $(this);
      var $div = $("#"+$area.attr("rel"));
      var div = $div.get(0);

      div.mouseOn = false;
      div._area = this;
      this.mouseOn = false;
      this._div = div;

      $area.hover(function() {
        this.mouseOn = true;
        self.showComment(this);
      }, function() {
        this.mouseOn = false;
        var that = this;
        window.setTimeout(function() { self.hideComment(that); }, 1);
      });
      $div.hover(function() {
        this.mouseOn = true;
      }, function() {
        this.mouseOn = false;
        self.hideComment(this._area);
      });
    });
  },
  navClickHandle: function(id) {
    var self = this;
    var $current = $("#map .map-canvas").filter(":visible");
    if (id != $current.attr("id")) {
      self.showSlide(id);
    }
  },
  showSlide: function(id) {
    var self = this;
    $("#map .map-canvas").filter(":visible").fadeOut(self.fadeSpeed, function() {
      $("#"+id, self.$container).fadeIn(self.fadeSpeed);
      $("a", self.$nav).removeClass("active").filter("[rel='"+id+"']").addClass("active");
    });
  },
  showComment: function(area) {
    var self = this;
    $(area._div).stop(true, true).css({zIndex: 100}).fadeIn(self.fadeSpeed);
  },
  hideComment: function(area) {
    var self = this;
    if (!area.mouseOn && !area._div.mouseOn) {
      $(area._div).stop(true, true).fadeOut(self.fadeSpeed);
    }
  }
}

var Tree = function() {
  this.$slide = $(".slide-part");
  this.$sLink = $(".slide-link", this.$slide);
  this.$container = $("#tree");

  if (this.$container.size() > 0) {
    this.scrollElement = document.documentElement || document.body;

    this.slideDPos = this.$slide.css("left");
    this.slideAPos = "-"+$(".center-content").css("marginLeft");
    this.slideFDPos = -289;
    this.slideFAPos = 0;
    this.contentOffset = $(".content").offset().top;
    this.duration = 300;
    this.animate = !($.browser.msie && $.browser.version <= 7);
    this.slideShown = false;
    this.slideFixed = false;

    this.ie6 = $.browser.msie && $.browser.version <= 6;

    this.setup();
  }
}
Tree.prototype = {
  setup: function() {
    var self = this;
    self.defineLeafs();
    self.hideBranches(false);
    $("li ins", self.$container).click(function() {
      self.toggleBranch(this.parentNode);
    });
    self.$sLink.click(function() { self.toggleSlide(); return false; });
    $(window).scroll(function() { self.moveSlide(); });
  },
  defineLeafs: function() {
    var self = this;
    $("li", self.$container).each(function() {
      if (!$("> ul", this).get(0)) {
        $("ins", this).hide();
      }
    });
  },
  hideBranches: function(animate) {
    var self = this;
    $("ul.level-2, ul.level-3, ul.level-4", self.$container).each(function() {
      if (!$(this.parentNode).is(".current")) {
        $("ins", this.parentNode).addClass("closed");
        if (!self.animate || !animate) {
          $(this).hide();
        } else {
          $(this).slideUp(self.duration);
        }
      }
    });
  },
  toggleBranch: function(li) {
    var self = this;
    var $ul = $("> ul", li);
    $("> ins", li).addClass("closed");
    if ($ul.size() > 0) {
      if ($ul.is(":visible")) {
        self.hideBranch(li);
      } else {
        self.showBranch(li);
      }
    }
  },
  showBranch: function(li) {
    var self = this;
    var $ul = $("> ul", li);
    $("> ins", li).removeClass("closed");
    if (!self.animate) {
      $ul.show();
      self.moveSlide();
    } else {
      $ul.slideDown(self.duration, function() { self.moveSlide(); });
    }
  },
  hideBranch: function(li) {
    var self = this;
    var $ul = $("> ul", li);
    if (!self.animate) {
      $ul.hide();
      self.moveSlide();
    } else {
      $ul.slideUp(self.duration, function() { self.moveSlide(); });
    }
  },
  toggleSlide: function() {
    var self = this;
    if (!self.slideShown) {
      self.showSlide();
    } else {
      self.hideSlide();
    }
  },
  showSlide: function() {
    var self = this;
    self.slideShown = true;
    var params = {};
    if (!self.slideFixed) params.left = self.slideAPos
    else params.left = self.slideFAPos;
    if (!self.animate) {
      self.$slide.css(params);
      self.$sLink.addClass("slide-link-a");
    } else {
      self.$slide.stop(true, true).animate(params, {duration: self.duration, complete: function() { self.$sLink.addClass("slide-link-a"); }});
    }
  },
  hideSlide: function() {
    var self = this;
    self.slideShown = false;
    self.$slide.stop(true, true);
    var params = {};
    if (!self.slideFixed) params.left = self.slideDPos
    else params.left = self.slideFDPos;
    if (!self.animate) {
      self.$slide.css(params);
      self.$sLink.removeClass("slide-link-a");
    } else {
      self.$slide.stop(true, true).animate(params, {duration: self.duration, complete: function() { self.$sLink.removeClass("slide-link-a"); }});
    }
  },
  moveSlide: function() {
    var self = this;
    var params = {};
    if (self.ie6) return self.ie6MoveSlide();
    if (self.scrollElement.scrollTop > self.contentOffset) {
      if (!self.slideFixed) {
        self.slideFixed = true;
        if (self.slideShown) params.left = self.slideFAPos;
        self.$slide.addClass("slide-part-fixed").css(params);
      }
    } else if (self.slideFixed) {
      self.slideFixed = false;
      if (self.slideShown) params.left = self.slideAPos;
      self.$slide.removeClass("slide-part-fixed").css(params);
    }
  },
  ie6MoveSlide: function() {
    var self = this;
    var delta = self.scrollElement.scrollTop - self.contentOffset;
    var slideHeight = self.$slide.outerHeight(true);
    var eps = slideHeight - self.scrollElement.clientHeight;
    if (eps > 0) {
      delta -= eps;
    }
    if (delta < 0) { delta = 0; }
    self.$slide.css({top: delta});
  }
};

var Scroller = function(container) {
  this.$container = $(".gallery-content", container);
  this.$arrL = $(".gallery-scroll-left", container);
  this.$arrR = $(".gallery-scroll-right", container);

  this.duration = 300;
  this.delta = $("td").outerWidth(true);
  this.setup();
}
Scroller.prototype = {
  setup: function() {
    var self = this;
    self.$arrL.click(function() { self.scroll(-1); });
    self.$arrR.click(function() { self.scroll(1); });
    self.checkScrolls();
  },
  scroll: function(k) {
    var self = this;
    var container = self.$container.get(0);
    var value = container.scrollLeft + self.delta*k;
    var max = container.scrollWidth - container.clientWidth;
    if (value < 0) {
      value = 0;
    } else if (value > max) {
      value = max;
    }
    self.$container.animate({scrollLeft: value}, {duration: self.duration, complete: function() { self.checkScrolls(); }});
  },
  checkScrolls: function() {
    var self = this;
    var container = self.$container.get(0);
    var curValue = container.scrollLeft;
    var maxValue = container.scrollWidth - container.clientWidth;
    if (curValue == 0) {
      self.$arrL.hide();
    } else {
      self.$arrL.show();
    }
    if (curValue == maxValue) {
      self.$arrR.hide();
    } else {
      self.$arrR.show();
    }
  }
}

var Gallery = function(container) {
  this.container = container;

  this.fadeSpeed = 200;
  this.commentOffset = 8; // Смещение относительно превьюшки

  this.setup();
}
Gallery.prototype = {
  setup: function() {
    var self = this;
    self.scroller = new Scroller(self.contaienr);
    self.fbox = $("a img", self.container).FBox({ animation: $.browser.msie ? false : true,
                                                  imagesList: true,
                                                  imagesListWidth: 120,
                                                  showOverlay: true,
                                                  overlayOpacity: 0.7,
                                                  padding: 0,
                                                  useLoaderAnim: true,
                                                  loaderParams: {
                                                    animatioLength: 400,
                                                    animationStep: 50,
                                                    animationTime: 100
                                                  },
                                                  navigationButtons: true,
                                                  navigationButtonsHover: true,
                                                  constraints: {
                                                    minWidth: 650,
                                                    minHeight: 540,
                                                    maxWidth: 880,
                                                    maxHeight: 750 }});
    $("a", self.container).each(function() {
      this.comment = $("#"+this.rel, self.container);
    }).hover(function() {
      self.showComment(this);
    }, function() {
      self.hideComment(this);
    });
  },
  showComment: function(a) {
    var self = this;
    var $td = $(a.parentNode.parentNode);
    var offset = $td.position().left;
    $(a.comment).stop(true, true).css({left: offset + self.commentOffset}).fadeIn(self.fadeSpeed);
  },
  hideComment: function(a) {
    var self = this;
    a.comment.stop(true, true).fadeOut(self.fadeSpeed, function() { $(this).css({left: ''}); });
  }
}


var Dealers = function(){

  var $dealmap = null;
  var $dealers = null;
  var $managers = null;
  var $region_name = null;
  var $dealers_name = null;
  var $managers_name = null;

  var all_regions = { };

  function getScrollBody() {
    var _webkit = /webkit/.test(navigator.userAgent.toLowerCase());
    return (_webkit)
        ? document.body
        : document.documentElement;
  }

  function getRegions(){
      $.post('/ajax/',{iface: "dealers"}, function(xml){ parseRegions(xml) },"xml");
  }

  function parseRegions(xml){
      var regions = xml.getElementsByTagName("regions")[0];
      if(regions){
          var region = regions.getElementsByTagName("region");
          for(var i=0;i<region.length;i++){
              var reg_id = region[i].getAttribute("reg_id")
              all_regions[reg_id] = {region_name: region[i].getAttribute("region"),
                                     dealers: new Array(),
                                     managers: new Array() };
              var dealers = region[i].getElementsByTagName("dealer");
              if(dealers.length>0){
                  for(var j=0;j<dealers.length;j++){
                      all_regions[reg_id].dealers.push(dealers[j].getAttribute("id"));
                  }
              }
              var managers = region[i].getElementsByTagName("manager");
              if(managers.length>0){
                  for(var j=0;j<managers.length;j++){
                      all_regions[reg_id].managers.push(managers[j].getAttribute("id"));
                  }
              }
          }
      }
  }

  function showDealers(reg_id){
      $dealers.hide();
      $managers.hide();
      $region_name.html("");
      $dealers_name.hide();
      $managers_name.hide();

      if(all_regions[reg_id]){
        $region_name.html(all_regions[reg_id].region_name);

        if(all_regions[reg_id].dealers.length>0){
            $dealers_name.show();

            for(var i=0;i<all_regions[reg_id].dealers.length;i++){
                $dealers.filter("#deal-"+all_regions[reg_id].dealers[i]).show();
            }
        }else{
            $dealers.filter(".no-dealer").show();
        }

        if(all_regions[reg_id].managers.length>0){
            $managers_name.show();
            for(var i=0;i<all_regions[reg_id].managers.length;i++){
                $managers.filter("#man-"+all_regions[reg_id].managers[i]).show();
            }
        }
      }else{
        $dealers.filter(".no-dealer").show();
      }
  }

  return{
      init: function(){
          $dealers = $("#deal-text .dealer");
          $managers = $("#deal-mans .deal-man");
          $dealmap = $(".deal-map");
          if($dealers.length>0){
              $dealers.hide();
              $managers.hide();
              $region_name = $(document.createElement("h2"))
                                .insertBefore($("#deal-text"));
              $dealers_name = $(document.createElement("h2"))
                                .html("Дилеры")
                                .hide()
                                .insertBefore($("#deal-text"));
              $managers_name = $(document.createElement("h2"))
                                  .html("Региональные менеджеры")
                                  .hide()
                                  .insertBefore($("#deal-mans"));
              getRegions();
          }
      },
      load: function(region_id){
          $(getScrollBody()).scrollTop($dealmap.offset().top);
          region_id = region_id.replace(/^p/,"");
          showDealers(region_id);
      }
  }

}();

function loadRegion(reg_id){ Dealers.load(reg_id); }

$(function() {
    FlexitesSubscribe.Form('subscribe-form');
});

$(function() {
    $("a.show-in-window").click(function(e){
        e.preventDefault();
        window.open(this.href,'addwin','status=no,toolbar=no,scrollbars=yes,titlebar=no,menubar=no,resizable=yes,width=640,height=480,directories=no,location=no');
    });
});

