var FADE_INCREMENT = 0.1
var FADE_DURATION = 120
var SHINE_INCREMENT = 0.1
var SHINE_DURATION = 500
var SCROLL_DISTANCE = 6
var SCROLL_DISTANCE_ONE = 24
var SCROLL_INTERVAL = 30
var VITRINE_FADE_INCREMENT = 0.07
var VITRINE_FADE_DURATION = 400
var VITRINE_SWAP_INTERVAL = 3200
var VITRINE_AUTO_START = true
var ROLLOVER_SUFFIX = '_rollover'
var CPU_ADEQUATE = document.cookie.match(/cpu_adequate=(\d)/) ? (RegExp.$1 == '1') : true

var domEnabled = !!(document.getElementById && document.getElementsByTagName)
var isGecko = (navigator.product == 'Gecko')
var isOpera = !!window.opera
var isIE = ([,].length == 2)

var PRELOADER = []
PRELOADER.load = function(url, callback) {
  var image = new Image()
  setTimeout(function(){ // Because of error when the image is cached
    image.src = url
  }, 10)
  if (callback) {
    image.onload = callback
  }
  PRELOADER[getBaseName(url)] = image
  PRELOADER[getFileName(url)] = image
  return image
}
PRELOADER.getCompleted = function() {
  for (var i = 0; i < arguments.length; i++) {
    if (this[arguments[i]] && this[arguments[i]].complete) continue
    return false
  }
  return true
}

var productsMenuTimer
var productsMenuClosingLink

function rolloverInit(container, effect) {
  effect = effect || 'fade' // 'simple', 'fade' or 'shine'
  var links = container.getElementsByTagName('a')
  for (var i = 0, link; link = links[i]; i++) {
    if (!link.getAttribute('noeffect')) {
      link.effect = effect
      preloadFadeRollover(link)
    }
  }
}

function rolloverInitArray(ids, effect) {
  effect = effect || 'fade' // 'simple', 'fade' or 'shine'
  var links = []
  for (var i = 0, id; id = ids[i]; i++) {
    var link = $(id)
    if (!link.getAttribute('noeffect')) {
      link.effect = effect
      preloadFadeRollover(link)
    }
  }
}

function rolloverSelectFadeInit(container) {
  if (!supportsOpacity(container)) return
  var links = container.getElementsByTagName('a')
  for (var i = 0, link; link = links[i]; i++) {
    if (!link.getAttribute('noeffect')) {
      link.setAttribute('minOpacity', 0.5)
      link.onmouseover = link_mouseover_fade
      link.onmouseout = link_mouseout_fade
    }
  }
}

function preloadFadeRollover(link) {
  var url = link.firstChild.src.replace(/\.gif$/, ROLLOVER_SUFFIX + '.gif')
  var image = PRELOADER.load(url, rolloverImage_load)
  image.link = link
}

function rolloverImage_load() {
  // Rollover image is loaded
  var link = this.link
  if (link.effect != 'simple' && supportsOpacity(link)) {
    // Position as background in the table cell
    link.parentNode.style.backgroundImage = 'url(' + this.src + ')'
  } else {
    // Simple rollover
    link.imageSrc = link.firstChild.src
    link.rolloverImageSrc = this.src
  }
  // Attaching the link events
  if (link.effect == 'shine') {
    if (supportsOpacity(this)) {
      link.onmouseover = link_mouseover_shine
    }
  } else if (link.effect == 'fade') {
    link.onmouseover = link_mouseover_fade
    link.onmouseout = link_mouseout_fade
  } else {
    link.onmouseover = link_mouseover_simple
    link.onmouseout = link_mouseout_simple
  }
}

function link_mouseover_simple() {
  this.firstChild.src = this.rolloverImageSrc
}

function link_mouseout_simple() {
  this.firstChild.src = this.imageSrc
}

function link_mouseover_fade() {
  if (supportsOpacity(this)) {
    fadeEffect(this.firstChild, FADE_DURATION, -FADE_INCREMENT, this.getAttribute('minOpacity') || 0)
  } else {
    this.firstChild.src = this.rolloverImageSrc
  }
}

function link_mouseout_fade() {
  if (supportsOpacity(this)) {
    fadeEffect(this.firstChild, FADE_DURATION, FADE_INCREMENT, this.getAttribute('minOpacity') || 0)
  } else {
    this.firstChild.src = this.imageSrc
  }
}

function link_mouseover_shine() {
  if (supportsOpacity(this)) {
    shineEffect(this.firstChild, -FADE_INCREMENT)
  } else {
    this.firstChild.src = this.rolloverImageSrc
  }
}

/* Home News */
function homeNewsInit() {
  var table = $('home-news')
  var clone = table.cloneNode(true)
  clone.id = null
  clone.style.position = 'absolute'
  clone.style.top = '0px'
  clone.style.left = '0px'
  table.parentNode.appendChild(clone)
  var tds1 = table.getElementsByTagName('td')
  var tds2 = clone.getElementsByTagName('td')
  for (var i = 0, td1, td2; td1 = tds1[i], td2 = tds2[i]; i++) {
    if (td2.className == 'item') {
      td2.onmouseover = homeNewsCell_mouseover
      td2.onmouseout = homeNewsCell_mouseout
      td2.twin = td1
      if (supportsOpacity(td1)) {
        setOpacity(td1, 0)
      } else {
        td1.style.visibility = 'hidden'
      }
    } else if (td2.className == 'title-cell') {
      var image =  td1.getElementsByTagName('img')[0]
      image.src = image.src.replace(/\.gif$/, '_rollover.gif')
      td2.onmouseover = homeNewsTitle_mouseover
      td2.onmouseout = homeNewsTitle_mouseout
    } else if (td2.className == 'girl-cell') {
      td1.firstChild.firstChild.src = 'images/girl_white.jpg'
      td2.onmouseover = homeNewsGirl_mouseover
    }
  }
  table.className += ' under'
}

function homeNewsCell_mouseover() {
  var td = this.twin
  if (supportsOpacity(td)) {
    fadeEffect(td, FADE_DURATION, FADE_INCREMENT)
  } else {
    td.style.visibility = 'visible'
  }
}

function homeNewsCell_mouseout() {
  var td = this.twin
  if (supportsOpacity(td)) {
    fadeEffect(td, FADE_DURATION, -FADE_INCREMENT)
  } else {
    td.style.visibility = 'hidden'
  }
}

function homeNewsGirl_mouseover() {
  if (supportsOpacity(this) && !this.timer) {
    shineEffect(this)
  }
}

function homeNewsTitle_mouseout() {
  if (supportsOpacity(this)) {
    fadeEffect(this, FADE_DURATION, FADE_INCREMENT)
  } else {
    this.style.visibility = 'visible'
  }
}

function homeNewsTitle_mouseover() {
  if (supportsOpacity(this)) {
    fadeEffect(this, FADE_DURATION, -FADE_INCREMENT)
  } else {
    this.style.visibility = 'visible'
  }
}

/* Content Scroll */
function contentScrollInit() {
  PRELOADER.load('images/scrollbar_arrow_down_over.gif')
  PRELOADER.load('images/scrollbar_arrow_up_over.gif')
}

function scrollContentUp(image, onlyOne) {
  if (image && PRELOADER.getCompleted('scrollbar_arrow_down_over', 'scrollbar_arrow_up_over')) {
    image.srcInit = image.src
    image.src = PRELOADER['scrollbar_arrow_up_over'].src
  }
  var container = $('content-text-container')
  var scroller = $('scroller')
  if (scroller.timer) clearTimeout(scroller.timer)
  var scrollerTop = parseInt(scroller.style.top) || 0
  scrollerTop += onlyOne ? SCROLL_DISTANCE_ONE : SCROLL_DISTANCE
  if (scrollerTop > 0) scrollerTop = 0
  scroller.style.top = scrollerTop + 'px'
  if ((scrollerTop < 0) && !onlyOne) {
    scroller.timer = setTimeout(arguments.callee, SCROLL_INTERVAL)
  } else {
    scroller.timer = null
  }
}

function scrollContentDown(image, onlyOne) {
  if (image && PRELOADER.getCompleted('scrollbar_arrow_down_over', 'scrollbar_arrow_up_over')) {
    image.srcInit = image.src
    image.src = PRELOADER['scrollbar_arrow_down_over'].src
  }
  var container = $('content-text-container')
  var scroller = $('scroller')
  if (scroller.timer) clearTimeout(scroller.timer)
  var scrollerTop = parseInt(scroller.style.top) || 0
  var minTop = Math.min(container.offsetHeight - scroller.offsetHeight, 0)
  scrollerTop -= onlyOne ? SCROLL_DISTANCE_ONE : SCROLL_DISTANCE
  if (scrollerTop < minTop) scrollerTop = minTop
  scroller.style.top = scrollerTop + 'px'
  if ((scrollerTop > minTop) && !onlyOne) {
    scroller.timer = setTimeout(arguments.callee, SCROLL_INTERVAL)
  } else {
    scroller.timer = null
  }
}

function scrollContentStop(image){
  if (image.srcInit) image.src = image.srcInit
  var scroller = $('scroller')
  clearTimeout(scroller.timer)
  scroller.timer = null
}

function scrollInitVisibility() {
  var container = $('content-text-container')
  var scroller = $('scroller')
  if (scroller.offsetHeight > container.offsetHeight) {
    $('scroll-arrow-up').style.visibility = 'visible'
    $('scroll-arrow-down').style.visibility = 'visible'
  }
}

function scrollWheelInit(scrollAreaId, containerId, scrollerId) {
  if (window.addEventListener) {
    window.addEventListener('DOMMouseScroll', scrollWheel, false)
    window.onmousewheel = scrollWheel;
  } else {
    window.document.onmousewheel = scrollWheel;
  }
  function scrollWheel(e) {
    e = e || event || {}
    var element = e.srcElement || e.target
    var wheelAreaElement = $(scrollAreaId)
    while (true) {
      if (element == wheelAreaElement) {
        break
      } else {
        element = element.parentNode
        if (!element) {
          return
        }
      }
    }
    var delta = 0
    if (e.wheelDelta) {
      delta = e.wheelDelta / 120
      if (window.opera) {
        delta = -delta
      }
    } else if (e.detail) {
      delta = -e.detail / 3
    }
    if (delta > 0) {
      scrollContentUp(null, true)
    } else if (delta < 0) {
      scrollContentDown(null, true)
    }
    if (e.preventDefault) {
      e.preventDefault()
    } else {
	    e.returnValue = false
	  }
  }
}

/* Companies Menu */
function companiesMenuInit(container) {
  var container = $('companies-menu')
  var tds = container.getElementsByTagName('td')
  var links = []
  for (var i = 0, td; td = tds[i]; i++) {
    links[i] = td.firstChild
    if (td.className == 'selected') {
      links[i].selected = true // The selected link is div in reality.
    }
  }
  for (var i = 0, link; link = links[i]; i++) {
    link.onmouseover = companiesMenuLink_mouseover
    link.onmouseout = companiesMenuLink_mouseout
    link.refPrevious = links[i - 1]
    link.refNext = links[i + 1]
    if (link.selected) {
      if (link.refPrevious) link.refPrevious.parentNode.className = 'preselected'
      if (link.refNext) link.refNext.parentNode.className = 'postselected'
    }
  }
}

function companiesMenuLink_mouseover() {
  if (!this.selected) {
    this.parentNode.style.borderColor = 'white'
    if (this.refPrevious && !this.refPrevious.selected) {
      this.refPrevious.parentNode.style.borderBottomColor = 'white'
    }
    if (this.refNext && !this.refNext.selected) {
      this.refNext.parentNode.style.borderTopColor = 'white'
    }
  }
}

function companiesMenuLink_mouseout() {
  if (!this.selected) {
    this.parentNode.style.borderColor = ''
    if (this.refPrevious && !this.refPrevious.selected) {
      this.refPrevious.parentNode.style.borderBottomColor = ''
    }
    if (this.refNext && !this.refNext.selected) {
      this.refNext.parentNode.style.borderTopColor = ''
    }
  }
}

/* Company Photo Gallery */
var COMPANY_PHOTO_GALLERY = {
  pictures: [],
  index: 0,
  init: function() {
    for (var i = 0, picture; picture = this.pictures[i]; i++) {
      PRELOADER.load('images/' + picture)
    }
  },
  getPreviousIndex: function() {
    return (this.index > 0) ? this.index - 1 : this.pictures.length - 1
  },
  getNextIndex: function() {
    return (this.index < this.pictures.length - 1) ? this.index + 1 : 0
  },
  clearTimer: function() {
    if (this.timer) {
      clearTimeout(this.timer)
      this.timer = null
    }
  },
  start: function() {
    this.scheduleNext(VITRINE_SWAP_INTERVAL - 2 * VITRINE_FADE_DURATION)
  },
  scheduleNext: function(interval) {
    var self = this
    this.clearTimer()
    this.timer = setTimeout(function() {self.checkedNext()}, interval || VITRINE_SWAP_INTERVAL)
  },
  checkedNext: function() {
    if (PRELOADER.getCompleted(this.pictures[this.getNextIndex()])) {
      this.changeImage(this.getNextIndex())
    }
    this.scheduleNext()
  },
  changeImage: function(newIndex) {
    var imageElement = $('company-photo')
    if (supportsOpacity(imageElement)) {
      var self = this
      fadeEffect(imageElement, VITRINE_FADE_DURATION, -VITRINE_FADE_INCREMENT, 0, function(){
        self.updateImage(newIndex)
        fadeEffect(imageElement, VITRINE_FADE_DURATION, VITRINE_FADE_INCREMENT)
      })
    } else {
      this.updateImage(newIndex)
    }
  },
  updateImage: function(newIndex) {
    this.index = newIndex
    $('company-photo').src = 'images/' + this.pictures[newIndex]
  }
}

/* Products Menu, Submenu */
function productsMenuInit() {
  var container = $('products-menu')
  var tds = container.getElementsByTagName('td')
  var links = []
  for (var i = 0, td; td = tds[i]; i++) {
    links[i] = td.firstChild
    links[i].onclick = returnFalse
    if (td.className == 'selected') {
      links[i].selected = true
    }
  }
  for (var i = 0, link; link = links[i]; i++) {
    link.onmouseover = productsMenuLink_mouseover
    link.onmouseout = productsMenuLink_mouseout
    link.refPrevious = links[i - 1]
    link.refNext = links[i + 1]
    if (link.selected) {
      if (link.refPrevious) link.refPrevious.parentNode.className = 'preselected'
      if (link.refNext) link.refNext.parentNode.className = 'postselected'
    }
  }
}

function productsMenuSelect(categoryId) {
  var container = $('products-menu')
  var tds = container.getElementsByTagName('td')
  for (var i = 0, td; td = tds[i]; i++) {
    td.className = 'normal'
  }
  for (var i = 0, td; td = tds[i]; i++) {
    var link = td.firstChild
    link.selected = (Number(link.getAttribute('cat_id')) == categoryId)
    if (link.selected) {
      appendClass(td, 'selected')
      if (link.refPrevious) link.refPrevious.parentNode.className = 'preselected'
      if (link.refNext) link.refNext.parentNode.className = 'postselected'
    }
  }
}

function returnFalse() {
  return false
}

function productsMenuLink_mouseover() {
  if (productsMenuTimer) {
    if (productsMenuClosingLink == this) {
      clearTimeout(productsMenuTimer)
      productsMenuTimer = null
      productsMenuClosingLink = null
      return
    }
    productsMenuClose(productsMenuClosingLink)
  }
  var linkPos = getElementPosition(this)
  this.style.backgroundColor = '#6DA6D1'
  this.parentNode.style.borderColor = 'white'
  if (this.refPrevious && !this.refPrevious.selected) {
    this.refPrevious.parentNode.style.borderBottomColor = 'white'
  }
  if (this.refNext && !this.refNext.selected) {
    this.refNext.parentNode.style.borderTopColor = 'white'
  }
  // Rendering του sub-menu
  var subCategories = getSubcategoriesByCategoryId(this.getAttribute('cat_id'))
  if (subCategories) {
    var html = new TemplateEngine(submenuTemplate, true).process({list:subCategories, supportsFilter:(typeof this.style.filter == 'string')})
    var placeholder = $('submenu-placeholder')
    placeholder.innerHTML = html
    placeholder.style.left = (linkPos.x + 140) + 'px'
    placeholder.style.top = (linkPos.y + (isGecko ? -1 : isOpera ? -1 : 1)) + 'px'
    $('submenu-placeholder').style.display = ''
    placeholder.refLink = this
  }
}

function productsMenuLink_mouseout() {
  startMenuCloseTimeout(this)
}

function startMenuCloseTimeout(link) {
  productsMenuClosingLink = link
  productsMenuTimer = setTimeout(function() {
    productsMenuClose(link)
  }, 100)
}

function productsMenuClose(link) {
  if (productsMenuTimer) clearTimeout(productsMenuTimer)
  productsMenuTimer = null
  productsMenuClosingLink = null
  link.style.backgroundColor = ''
  link.parentNode.style.borderColor = ''
  if (link.refPrevious && !link.refPrevious.selected) {
    link.refPrevious.parentNode.style.borderBottomColor = ''
  }
  if (link.refNext && !link.refNext.selected) {
    link.refNext.parentNode.style.borderTopColor = ''
  }
  $('submenu-placeholder').innerHTML = ''
  $('submenu-placeholder').style.display = 'none'
}

function productsSubmenu_mouseover(element) {
  if (productsMenuTimer) clearTimeout(productsMenuTimer)
  productsMenuTimer = null
  productsMenuClosingLink = null
}

function productsSubmenu_mouseout(element) {
  startMenuCloseTimeout(element.refLink)
}

// Products Vitrine
var VITRINE = {
  products: [],
  index: 0,
  getPreviousIndex: function() {
    return (this.index > 0) ? this.index - 1 : this.products.length - 1
  },
  getNextIndex: function() {
    return (this.index < this.products.length - 1) ? this.index + 1 : 0
  },
  clearTimer: function() {
    if (this.timer) {
      clearTimeout(this.timer)
      this.timer = null
    }
  },
  scheduleNext: function(interval) {
    var self = this
    this.clearTimer()
    this.timer = setTimeout(function() {self.checkedNext()}, interval || VITRINE_SWAP_INTERVAL)
  },
  previous: function() {
    if (this.products.length < 2) return
    this.clearTimer()
    this.changeProductImage(this.getPreviousIndex())
  },
  next: function() {
    if (this.products.length < 2) return
    this.clearTimer()
    this.changeProductImage(this.getNextIndex())
  },
  checkedNext: function() {
    if (PRELOADER.getCompleted(this.products[this.getNextIndex()].prd_image)) {
      this.changeProductImage(this.getNextIndex())
    }
    this.scheduleNext()
  },
  select: function(index) {
    this.clearTimer()
    this.changeProductImage(index)
  },
  changeProductImage: function(newIndex) {
    var imageElement = $('product-image')
    var productInfoCell = $('product-info-cell')
    if (supportsOpacity(imageElement)) {
      var self = this
      fadeEffect(imageElement, VITRINE_FADE_DURATION, -VITRINE_FADE_INCREMENT, 0, function(){
        self.updateImage(newIndex)
        fadeEffect(imageElement, VITRINE_FADE_DURATION, VITRINE_FADE_INCREMENT)
      })
      if (this.subcategoryId) {
        fadeEffect(productInfoCell, VITRINE_FADE_DURATION, -VITRINE_FADE_INCREMENT, 0, function(){
          fadeEffect(productInfoCell, VITRINE_FADE_DURATION, VITRINE_FADE_INCREMENT)
        })
      }
    } else {
      this.updateImage(newIndex)
    }
  },
  updateImage: function(newIndex) {
    var product = this.products[this.index]
    if (product) {
      var thumbTable = $('product#' + product.prd_id)
      if (thumbTable) stripClass(thumbTable, 'selected')
    }
    this.index = newIndex
    var product = this.products[this.index]
    $('product-image').src = 'data/images/' + product.prd_image
    $('product-image').alt = encodeHTML(product.prd_name)
    $('product-info-name').innerHTML = formatProductNameHTML(product.prd_name)
    $('product-info-characteristics').innerHTML = 'Code: ' + encodeHTML(product.prd_code) + ', Pack: ' + product.prd_characteristics
    if (this.subcategoryId) {
      $('product-details-prompt').style.display = 'none'
      $('product-info').style.display = ''
    }
    var thumbTable = $('product#' + product.prd_id)
    if (thumbTable) appendClass(thumbTable, 'selected')
  },
  initPreselected: function() {
    if (typeof DataSet == 'undefined') return
    this.products = []
    for (var i = 0; product = DataSet.Products[i]; i++) {
      if (product.prd_vitrine) {
        this.products.push(product)
        PRELOADER.load('data/images/' + product.prd_image)
      }
    }
    this.products.sort(function(p1, p2) {
      return (p1.prd_order || 0) - (p2.prd_order || 0)
    })
    this.setInitialImage()
    this.updateButtonsVisibility()
    if (VITRINE_AUTO_START && this.products.length > 1) {
      this.scheduleNext(VITRINE_SWAP_INTERVAL - 2 * VITRINE_FADE_DURATION)
    }
  },
  initSubcategory: function(subcategoryId, atPageLoad) {
    if (typeof DataSet == 'undefined') return
    this.subcategoryId = subcategoryId
    var subcategory = getSubcategoryById(subcategoryId)
    productsMenuSelect(subcategory.sct_cat_id)
    this.products = []
    for (var i = 0; product = DataSet.Products[i]; i++) {
      if (product.prd_sct_id == subcategoryId || product.prd_sct_id == 'TEST') { //@
        this.products.push(product)
        PRELOADER.load('data/images/' + product.prd_image)
      }
    }
    var list = this.products.slice(0)
    while ((list.length == 0) || (list.length % 6 != 0)) {
      list.push({empty:true})
    }
    var html = new TemplateEngine(productsListTemplate, true).process({list:list})
    $('mini-sites').style.display = 'none'
    $('products-list').style.display = ''
    $('products-list').innerHTML = html
    $('products-list-title').src = 'data/images/' + subcategory.sct_title_image
    rolloverSelectFadeInit($('products-list'))
    this.clearTimer()
    if (atPageLoad) {
      this.setInitialImage()
    } else {
      this.changeProductImage(0)
    }
    this.updateButtonsVisibility()
  },
  updateButtonsVisibility: function() {
    $('product-right-button').parentNode.style.visibility = (this.products.length > 1) ? 'visible' : 'hidden'
    $('product-left-button').parentNode.style.visibility = (this.products.length > 1) ? 'visible' : 'hidden'
  },
  setInitialImage: function() {
    if (this.products.length > 0) {
      $('product-image').src = 'data/images/' + this.products[0].prd_image
    }
  }
}

function formatProductNameHTML(name, eSize) {
  eSize = eSize || 15
  return encodeHTML(String(name)).replace(/\s+e$/, '&nbsp;<span style="font-family:arial;font-size:' + eSize + 'px;font-weight:normal">e</span>')
}

/* Effects */
function fadeEffect(element, duration, increment, minOpacity, onEnd) {
  minOpacity = minOpacity || 0
  if (element.timer) clearTimeout(element.timer)
  var opacity = getOpacity(element)
  opacity += increment * (1 - minOpacity)
  if (opacity > 0.99) opacity = 1
  if (opacity < minOpacity + 0.01) opacity = minOpacity
  setOpacity(element, opacity)
  if (opacity != minOpacity && opacity != 1) {
    element.timer = setTimeout(function() {fadeEffect(element, duration, increment, minOpacity, onEnd)}, Math.abs(duration * increment))
  } else {
    element.timer = null
    if (onEnd) onEnd()
  }
}

function shineEffect(element, increment) {
  increment = increment || -SHINE_INCREMENT
  if (element.timer) clearTimeout(element.timer)
  var opacity = getOpacity(element)
  opacity += increment
  if (opacity > 0.99) { opacity = 1; increment = 0 }
  if (opacity < 0.01) { opacity = 0; increment = -increment }
  setOpacity(element, opacity)
  if (increment != 0) {
    element.timer = setTimeout(function() {shineEffect(element, increment)}, SHINE_DURATION * SHINE_INCREMENT / 2)
  } else {
    element.timer = null
  }
}

function supportsOpacity(element) {
  return CPU_ADEQUATE && (element.style.opacity != null || element.style.filter != null)
}

function getOpacity(element) {
  if (element.style.opacity != null) {
    return (element.style.opacity == '') ? 1 : Number(element.style.opacity)
  } else if (element.style.filter != null) {
    return (element.opacity != null) ? Number(element.opacity) : 1
  }
}

function setOpacity(element, value) {
  if (element.style.opacity != null) {
    element.style.opacity = value
  } else if (element.style.filter != null) {
    element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + Math.round(value * 100) + ')'
    element.opacity = value
  }
}

// DOM functions
function $(id) {
  return document.getElementById(id)
}

function hasClass(element, className) {
  var re = new RegExp('(^| )' + className + '( |$)', 'i')
  return re.test(element.className)
}

function appendClass(element, className) {
  if (!hasClass(element, className)) element.className += ' ' + className
}

function stripClass(element, className) {
  var re = new RegExp('(^| )' + className + '( |$)', 'gi')
  element.className = element.className.replace(re, ' ').replace(/^\s+|\s+$/g, '')
}

function getParentNode(element, parentTagName) {
  parentTagName = parentTagName.toLowerCase()
  var parent = element.parentNode
  while (parent) {
    if (parent.nodeName.toLowerCase() == parentTagName) return parent
    parent = parent.parentNode
  }
}

function getPreviousSibling(element, tagName) {
  tagName = tagName.toLowerCase()
  var sibling = element
  while (sibling = sibling.previousSibling) {
    if (sibling.nodeName.toLowerCase() == '') return sibling
  }
}

function getElementPosition(element) {
  var x = 0, y = 0
  while (element && element.offsetParent) {
    x += element.offsetLeft
    y += element.offsetTop
    element = element.offsetParent
  }
  return {x:x, y:y}
}

function writeFlash(filename, width, height, transparent) {
  document.write(
    '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="' + width + '" height="' + height + '">'
    + '\n<param name="movie" value="' + filename + '">'
    + '\n<param name="quality" value="best">'
    + (transparent ? '\n<param name="wmode" value="transparent">' : '')
    + '\n<embed src="' + filename + '" quality="best"' + (transparent ? ' wmode="transparent"' : '') + ' bgcolor="#ffffff" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="' + width + '" height="' + height + '">'
    + '\n</object>'
  )
}

// Core JS
if (!Array.prototype.push) Array.prototype.push = function() {
  var start = this.length
  for (var i = 0; i < arguments.length; i++) this[start + i] = arguments[i]
  return this.length
}

function TemplateEngine(source,html){var a=0,c=0,d=0,x=0,u=[],h={'if':function(j){e(1,'(('+j+')?(',0);a<<=1},'elseif':function(j){e(0,'):('+j+')?(',0)},'else':function(){e(0,'):(',0);a++},'/if':function(){e(0,(a%2)?'))':'):"")',1);a>>=1},'for':function(j){var k=j.match(/^(\w+)\s+in\s+([^\}]+)$/);e(1,'(_I_('+k[2]+',function('+k[1]+','+k[1]+'_index){return ',0);c<<=1},'forelse':function(){e(0,'})||(',0);c++},'/for':function(){e(0,(c%2)?'))':'}))',1);c>>=1},'block':function(j){e(1,j+'(',0)},'/block':function(){e(0,')',1)},'component':function(j){e(1,'(_C_.'+j+'=function(_A_){return ',0)},'/component':function(){e(0,'},"")',1)},'placeholder':function(j){e(1,'_A_.'+j,1)},'instance':function(j){d<<=1;e(1,'_C_.'+j+'({',0);d++},'/instance':function(){d>>=1;e(0,'})',1)},'template':function(j){d--;e(0,(x?',':'')+j+':',0)},'/template':function(){d++;x=1}},l=/\$\{(([^\}]+)\|HTML|([^\}]+))\}|\{(if|elseif|for|block)\s+([^\}]+)\}|\{(else|forelse|\/if|\/for|\/block|\/component|\/instance|\/template)\}|\{(component|placeholder|instance|template):(\w+)\}/g,m=new RegExp(l.source),s=String(source).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g,''),p=s.match(l)||[],q=(' '+s.replace(l,'\x01')).split('\x01');q[0]=q[0].substr(1);for(var i=0;i<q.length;i++){e(1,'\''+q[i].replace(/([\\'])/g,'\\$1').replace(/\r/g,'\\r').replace(/\n/g,'\\n').replace(/\t/g,'\\t')+'\'',1);if(p[i]){var k=p[i].match(m);if(k[1]){e(1,((html&&k[3])?'_H_(':'_U_(')+(k[2]||k[3])+')',1)}else if(k[4]){h[k[4]](k[5])}else if(k[6]){h[k[6]]()}else{h[k[7]](k[8])}}}this.process=new Function('_CONTEXT','var _C_={};function _I_(o,f){var b=[];for(var i=0,v;(v=o[i])!=null;i++){b[b.length]=f(v,i)}return b.join("")}function _U_(v){return v!=null?v:""}function _H_(v){return (typeof v!="string")?_U_(v):(/[&<>"]/).test(v)?v.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"):v}with(_CONTEXT){return '+u.join('').replace(/^''\+|\+''$/g,'')+'}');function e(y,s,z){if(d%2)return;u[u.length]=((x&&y)?'+'+s:s);x=z}}
function getFileName(path) { return path.match(/[\/\\]([^\/\\]*)$/) ? RegExp.$1 : path }
function getFileExtension(path) { return path.match(/[^\/\\]+\.([^\/\.\\]+)$/) ? RegExp.$1 : '' }
function getFolderPath(path) { return path.match(/^(.*[^\/\\])[\/\\]+[^\/\\]*$/) ? RegExp.$1 : '' }  
function getBaseName(path) { return path.match(/([^\/\\]+)\.[^\/\.\\]+$/) ? RegExp.$1 : path }

function encodeHTML(value) {
  return String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
}

function aspm() {
  var links = document.links
  for (var i = 0, link; link = links[i]; i++) {
    if (link.getAttribute('aspm')) {
      var _ = link.getAttribute('aspm')
      if (_.match(/^(.+):f$/)) {
        _ = RegExp.$1 + '#ath:forthnet:gr'
      } else {
        _ = _ + '#bingo:gr'
      }
      _ = _.replace(/#/g, '@').replace(/:/g, '.')
      link.setAttribute("href", "mailto:" + _)
//      link.innerHTML = _
    }
  }
}