var goog = goog || {};
goog.ui = goog.ui || {};
goog.ui.Scroller = function(config) {
  this.scroller = document.getElementById(config.scrollerId);
  this.itemsContainer = document.getElementById(config.itemsContainerId);
  this.selectedItemClass = config.selectedItemClass;
  this.selectedPageLink = config.selectedPageLinkClass;
  this.disabledControlClass = config.disabledControlClass;
  this.displayItemContentClass = config.displayItemContentClass;
  this.defaultSelectedItem = config.defaultSelectedItem || null;
  this.centerFlag = config.centerFlag || null;
  this.callbackOnSelect = config.callbackOnSelect || null;
  this.centerOnInitFlag = config.centerOnInitFlag || null;
  this.currentPage = 1;
  this.items = [];
  this.itemLookup = [];
  this.pageLinks = [];
  this.isAnimating = false;
  var item;
  this.scroller.style.overflow = 'hidden';
  this.scroller.className += ' ' + config.noOverflowClass;
  if (!this.checkAndInitItems(config)) {
    this.scroller.style.overflow = 'auto';
    this.removeClass(this.scroller, config.noOverflowClass);
    return false;
  }

  for (var i = 0; i < this.items.length; i ++) {
    item = this.items[i];
    item.item.id = item.item.id + '_old';
    item.link.onclick = this.createlinkClickHandler(this, item.id);
    item.item.style.display = 'none';
  }

  this.currentId = this.getStringAfterHash(location.href);
  if (!this.isValidItem(this.currentId)) {
    this.currentId = this.defaultSelectedItem || this.selectRandomItem();
  }

  this.selectItem(this.currentId);
  this.pageCount = Math.ceil((this.items.length - 1) / (this.itemsPerPage - 1));
  if (config.scrollerPageLinksId) {
    for (i = 0; i < this.pageCount; i ++) {
      pageLink = document.createElement('a');
      pageLink.innerHTML = i + 1;
      pageLink.href = "javascript: void 0";
      pageLink.onclick = this.createPageLinkClickHandler(this, i + 1);
      document.getElementById(config.scrollerPageLinksId).appendChild(pageLink);
      this.pageLinks[i] = pageLink;
    }
  }
  if (this.centerFlag || this.centerOnInitFlag) {
    this.centerOnItem(this.currentId);
  } else {
    this.scrollToPage(Math.floor(this.itemLookup[this.currentId].pos /
      (this.itemsPerPage - 1)) + 1);
  }
  this.callbackOnSelect ? eval(this.callbackOnSelect) : null;
  document.onkeyup = this.createKeyUpHandler(this);
};

goog.ui.Scroller.prototype.selectRandomItem = function() {
  return this.items[Math.floor(Math.random() *
    (this.items.length - 1)) + 1].id;
};

goog.ui.Scroller.prototype.isValidItem = function(id) {
  for (var i in this.items) {
    if (this.items[i].id == id) {
      return true;
    }
  }
  return false;
};

goog.ui.Scroller.prototype.checkAndInitItems = function(config) {
  var id, item, links = this.scroller.getElementsByTagName('a');
  var tempDiv = document.createElement('div');
  this.scroller.appendChild(tempDiv);
  var contentsWidth = config.contentsWidth || tempDiv.offsetWidth;
  this.scroller.removeChild(tempDiv);
  for (var i = 0; i < links.length; i ++) {
    
    id = this.getStringAfterHash(links[i].href);
    item = document.getElementById(id);
    
    if (!id || !item) {
      if (config.debugFlag) {
        console.log('An item refers to the non-existent element id: "' + id);
      }
      return false;
    }
    
    this.linkWidth = config.itemWidth || links[i].offsetWidth;
    this.itemsPerPage = contentsWidth / this.linkWidth;
    this.itemLookup[id] = { link: links[i], item: item, pos: i, id: id, onpage: Math.floor(i / this.itemsPerPage) + 1 };
    this.items[i] = this.itemLookup[id];
    
    if (Math.floor(this.itemsPerPage) != this.itemsPerPage) {
      if (config.debugFlag) {
        console.log('Your scroller width (' + contentsWidth + ') is not evenly divisible by the item width (' + this.linkWidth + ').');
      }
      return false;
    }
  }
  return true;
};

goog.ui.Scroller.prototype.createPageLinkClickHandler = function(me, page) {
  return function() {
    me.scrollToPage(page);
  };
};

goog.ui.Scroller.prototype.createKeyUpHandler = function(me) {
  return function(e) {
    if (!e) {
      e = window.event;
    }
    var pos = me.itemLookup[me.currentId].pos, targetPos = pos;
    switch (e.keyCode) {
      case 37:
        targetPos = pos - 1;
        break;
      case 39:
        targetPos = pos + 1;
        break;
    }
    if (targetPos < 0) {
      targetPos = me.items.length - 1;
    } else if (targetPos >= me.items.length) {
      targetPos = 0;
    }
    if (targetPos != pos) {
      me.selectItem(me.items[targetPos].id);
      me.scrollToItem(me.items[targetPos].id);
      window.location = '#' + me.items[targetPos].id;
    }
  };
};

goog.ui.Scroller.prototype.getStringAfterHash = function(str) {
  var regex = new RegExp('#([^&]*)');
  var results = regex.exec(str);
  return (results ? results[1] : null );
};

goog.ui.Scroller.prototype.scrollToPage = function(page, fastFlag) {
  this.currentPage = page;
  var x = (page - 1) * (this.linkWidth * (this.itemsPerPage - 1));
  if (fastFlag) {
    this.scroller.scrollLeft = x;
  } else {
    this.isAnimating = true;
    this.animateScroll(this.scroller, x, 10);
  }
};

goog.ui.Scroller.prototype.animateScroll = function(el, x, steps) {
  var me = this;
  if (steps > 0) {
    el.scrollLeft = Math.floor((el.scrollLeft + x) / 2);
    window.setTimeout( function() {
	me.animateScroll(el, x, steps - 1);
	}, 90);
  } else {
    el.scrollLeft = x;
    me.isAnimating = false;
    this.selectItem(this.currentId);
  }
};

goog.ui.Scroller.prototype.createlinkClickHandler = function(me, id) {
  return function() {
    me.selectItem(id);
    me.centerFlag ? me.centerOnItem(id) : null;
  };
};

goog.ui.Scroller.prototype.selectItem = function(id) {
  this.itemLookup[this.currentId].item.style.display = 'none';
  this.removeClass(this.itemLookup[this.currentId].link,
      this.selectedItemClass);
  this.formerId = id,
  this.currentId = id;
  var selectedItem = this.itemLookup[id];
  selectedItem.item.style.display = 'block';
  if (this.displayItemContentClass &&
      selectedItem.item.className.indexOf(this.displayItemContentClass < 0)) {
    selectedItem.item.className += ' ' + this.displayItemContentClass;
  }
  selectedItem.link.className = this.selectedItemClass;
  this.callbackOnSelect ? eval(this.callbackOnSelect) : null;
};

goog.ui.Scroller.prototype.selectSpecificItem = function(id) {
  if(this.centerFlag) {
    this.centerOnItem(id);
    this.scrollToPage(this.itemLookup[id].onpage + 1);
  } else {
    this.scrollToItem(id);
  }
  this.selectItem(id);
};

goog.ui.Scroller.prototype.createlinkFocusHandler = function(me, id) {
  return function() {
    me.scrollToItem(id);
  };
};

goog.ui.Scroller.prototype.centerOnItem = function(id) {
  var centerLoc = this.linkWidth * (this.itemLookup[id].pos) - (this.linkWidth * Math.floor(this.itemsPerPage / 2));
  var steps = Math.ceil(Math.abs(this.scroller.scrollLeft - centerLoc) / 90) + 1;
  (steps > 20) ? steps = 10 : null;
  if (!this.isAnimating) {
    this.isAnimating = true;
    this.animateScroll(this.scroller, centerLoc, steps);
  }
};


goog.ui.Scroller.prototype.removeClass = function(el, name) {
  el.className = el.className.replace(new RegExp(name, 'g'), '');
};

// JS for social networking links
function getElementsByClass(searchClass,node,tag) {
  var classElements = new Array();
  if ( node == null )
    node = document;
  if ( tag == null )
    tag = '*';
  var els = node.getElementsByTagName(tag);
  var elsLen = els.length;
  var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
  for (i = 0, j = 0; i < elsLen; i++) {
    if ( pattern.test(els[i].className) ) {
      classElements[j] = els[i];
      j++;
    }
  }
  return classElements;
}

var linkSetter = {};
linkSetter.linkTypes = [
  { 
    classStr: 'twitter',
    urlString: 'http://twitter.com/home?status=' + encodeURIComponent('Смотрите новые мультики про Gmail на www.google.ru/mirgmail')
  },
  {
    classStr: 'facebook',
    urlString: 'http://www.facebook.com/sharer.php?u={url}&t={title}'
  },
  {
    classStr: 'myspace',
    urlString: 'http://www.myspace.com/Modules/PostTo/Pages/?u={url}'
  }
];


linkSetter.setLinks = function(url, title) {
  var links, j, url;

  for (var i = 0; i < this.linkTypes.length; i ++) {
    // create the dynamic url
    hrefUrl = this.linkTypes[i].urlString.replace(
        '{url}', encodeURIComponent(url)).replace('{title}', title);   
    links = getElementsByClass(this.linkTypes[i].classStr, null, 'A');
    // loop through each anchor 
    for (j = 0; j < links.length; j ++) {
      // set the href of the anchor
      links[j].href = hrefUrl;
    }
  }
};

window.onload = function() {
  var myUrl = encodeURIComponent(document.location.href);
  var myTitle = encodeURIComponent(document.title); 
  linkSetter.setLinks(myUrl, myTitle);
  
}