var IS_IE /*@cc_on = true @*/
var IS_IE6 /*@cc_on @if (@_jscript_version <= 5.6) = true @end @*/
var DOM_ENABLED = !!(document.getElementById && document.getElementsByTagName)

// JS Mark
function markJS() {
  if (DOM_ENABLED) {
    appendClass(document.body, 'js')
    stripClass(document.body, 'no-js')
  }
}

// validateHeaderSearch
function validateHeaderSearch(form) {
  if (!trim(form.elements['term'].value)) {
    alert('Δεν υπάρχει κείμενο προς αναζήτηση'); return false
  }
  return true
}

// validateHeaderLogin
function validateHeaderLogin(form) {
  if (!trim(form.elements['email'].value)) {
    alert('Το Email είναι κενό'); return false
  } else if (!trim(form.elements['password'].value)) {
    alert('Το Password είναι κενό'); return false
  }
  return true
}

/* PRELOADER */
var PRELOADER = []
PRELOADER.load = function(url, callback) {
  var image = new Image()
  setTimeout(function(){
    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
}

/* Products Rotator */
var ROTATOR_FADE_INCREMENT = 0.07
var ROTATOR_FADE_DURATION = 400
var ROTATOR_SWAP_INTERVAL = 5200
var PRODUCTS_ROTATOR = {
  pictures: [],
  folderPath: null,
  index: 0,
  init: function() {
    for (var i = 0, picture; picture = this.pictures[i]; i++) {
      PRELOADER.load(this.folderPath + picture.prd_image)
    }
  },
  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(ROTATOR_SWAP_INTERVAL - 2 * ROTATOR_FADE_DURATION)
  },
  scheduleNext: function(interval) {
    var self = this
    this.clearTimer()
    this.timer = setTimeout(function() {self.checkedNext()}, interval || ROTATOR_SWAP_INTERVAL)
  },
  checkedNext: function() {
    if (PRELOADER.getCompleted(this.pictures[this.getNextIndex()].prd_image)) {
      this.changeImage(this.getNextIndex())
    }
    this.scheduleNext()
  },
  changeImage: function(newIndex) {
    var containerElement = IS_IE ? $('products-rotator-container-ie') :  $('products-rotator-container')
    if (supportsOpacity(containerElement)) {
      var self = this
      fadeEffect(containerElement, ROTATOR_FADE_DURATION, -ROTATOR_FADE_INCREMENT, 0, function(){
        self.updateImage(newIndex)
        fadeEffect(containerElement, ROTATOR_FADE_DURATION, ROTATOR_FADE_INCREMENT)
      })
    } else {
      this.updateImage(newIndex)
    }
  },
  updateImage: function(newIndex) {
    this.index = newIndex
    var picture = this.pictures[newIndex]
    $('products-rotator-image').src = this.folderPath + picture.prd_image
    $('products-rotator-image').alt = picture.prd_title
    $('products-rotator-image').title = picture.prd_title
    $('products-rotator-link-image').href = picture.prd_page
    $('products-rotator-link-title').href = picture.prd_page
    $('products-rotator-link-title').innerHTML =
      '<span style="display:block">' + encodeHTML(picture.prd_author) + '</span>' +
      '<span style="display:block;margin-top:5px">Έκδοση: ' + encodeHTML(picture.prd_publication_date_formated) + '</span>' +
      '<span style="display:block;margin-top:5px">Σελίδες: ' + encodeHTML(picture.prd_pages_count_formated) + '</span>' +
      '<span style="display:block;margin-top:5px;color:#E62E20;font-weight:bold">' + encodeHTML(picture.prd_price_formated) + '</span>'
  }
}

function toggleInvoiceInit() {
  markJS()
  document.write(
    '<style type="text/css">' +
    '  .js .js-hidden {' +
    '    display:none;' +
    '  }' +
    '</style>'
  )
}

function toggleInvoice(checked) {
  var row1 = $('invoice-row-1')
  var row2 = $('invoice-row-2')
  if (checked) {
    if (row1) stripClass(row1, 'js-hidden')
    if (row2) stripClass(row2, 'js-hidden')
  } else {
    if (row1) appendClass(row1, 'js-hidden')
    if (row2) appendClass(row2, 'js-hidden')
  }
}

function FormValidator(form, briefThreshold) {
  var failed = []
  var emptyCount = 0
  this.status = true
  this.check = function(name, literal) {
    var field = form.elements[name]
    if (field && trim(field.value) == '') {
      failed[failed.length] = 'Το πεδίο ' + literal + ' δεν έχει συμπληρωθεί'
      emptyCount++
      this.status = false
    }
  }
  this.checkEmail = function(name, literal) {
    var value = trim(form.elements[name].value)
    var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/
    var reg2 = /^.+\@(\[?)[\w\-\.]+\.\w{1,3}(\]?)$/
    if (value && !(!reg1.test(value) && reg2.test(value))) {
      failed[failed.length] = 'Το πεδίο ' + literal + ' δεν περιέχει έγκυρο email'
      this.status = false
    }
  }
  this.report = function() {
    if (emptyCount > (briefThreshold || 3)) {
      alert('Υπάρχουν ' + emptyCount + ' υποχρεωτικά πεδία που δεν έχουν συμπληρωθεί')
    } else if (failed.length > 0) {
      alert(failed.join('\n'))
    }
  }
}

/* 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 supportsOpacity(element) {
  return 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 echo(s) {
  document.write(s)
}

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 addEvent(obj, evType, callback, useCapture){
  if (obj.addEventListener){
    obj.addEventListener(evType, callback, useCapture)
    return true
  } else if (obj.attachEvent) {
    var r = obj.attachEvent('on' + evType, callback)
    return r
  } else {
    return false
  }
}

function getElementByClassName(element, _tagName, _className) {
  var re = new RegExp('(^| )' + _className + '( |$)')
  var children = element.getElementsByTagName(_tagName || '*')
  for (var i = 0, child; child = children[i]; i++) {
    if (re.test(child.className)) {
      return child
    }
  }
}

function getElementsByClassName(element, tagName, className) {
  var re = new RegExp('(^| )' + encodeRE(className) + '( |$)')
  var children = element.getElementsByTagName(tagName)
  var list = []
  for (var i = 0, child; child = children[i]; i++) {
    if (re.test(child.className)) {
      list[list.length] = child
    }
  }
  return list
}

function getParentNode(element, parentTagName, className) {
  if (parentTagName) parentTagName = parentTagName.toLowerCase()
  if (className) className = new RegExp('(^| )' + encodeRE(className) + '( |$)')
  while (element = element.parentNode) {
    if (parentTagName && (element.nodeName.toLowerCase() != parentTagName)) continue
    if (className && !className.test(element.className)) continue
    return element
  }
}

function getChildNodes(element, tagName) {
  tagName = tagName.toUpperCase()
  var list = []
  var child = element.firstChild
  while (child) {
    if (child.nodeName.toUpperCase() == tagName) {
      list[list.length] = child
    }
    child = child.nextSibling
  }
  return list
}

function getNextSibling(element, tagName) {
  tagName = tagName.toUpperCase()
  element = element.nextSibling
  while (element) {
    if (element.nodeName.toUpperCase() == tagName) {
      return element
    }
    element = element.nextSibling
  }
}

function getPreviousSibling(element, tagName) {
  tagName = tagName.toUpperCase()
  element = element.previousSibling
  while (element) {
    if (element.nodeName.toUpperCase() == tagName) {
      return element
    }
    element = element.previousSibling
  }
}

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 getElementStyle(element, property) {
  if (element.currentStyle) {
    return element.currentStyle[property]
  } else if (document.defaultView && document.defaultView.getComputedStyle) {
    var style = document.defaultView.getComputedStyle(element, null)
    return (style && style.getPropertyValue) ? style.getPropertyValue(property) : ''
  } else {
    return ''
  }
}

function getCookie(name) {
  var re = new RegExp(encodeRE(name) + '=([^;]*)', 'i')
  var match = document.cookie.match(re)
  if (match) return unescape(match[1])
}
function addCookie(name, value, days, seconds) {
  var cookie = name + '=' + escape(value)
  if (days || seconds) {
    cookie += '; expires=' + new Date(new Date().getTime() + (days || 0) * 24 * 60 * 60 * 1000 + (seconds || 0) * 1000).toGMTString()
  }
  document.cookie = cookie
}
function removeCookie(name) {
  addCookie(name, '', -365)
}

function preloadImage(url) {
  var image = new Image()
  arguments.callee['#' + url] = image
  image.src = url
}
function preloadImages() {
  for (var i = 0; i < arguments.length; i++) {
    preloadImage(arguments[i])
  }
}

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
function encodeRE(s) {
  return s.replace(/([\^\$\.\*\?\+\{\}\(\)\[\]\/\|\\])/g, '\\$1')
}
function encodeJS(s) {
  return s.replace(/([\\'])/g, '\\$1').replace(/\r/g, '\\r').replace(/\n/g, '\\n').replace(/\t/g, '\\t').replace(/[\x00-\x1f]/g, '')
}
function encodeHTML(value) {
  return String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\x22/g, '&quot;')
}
function trim(s) {
  return String(s).replace(/^\s+|\s+$/g, '')
}
function forEach(array, f) { 
  for (var i = 0, item; item = array[i]; i++) {
    f(item, i)
  }
}
function getFileName(path) { return path.match(/[\/\\]([^\/\\]*)$/) ? RegExp.$1 : path }
function getBaseName(path) { return path.match(/([^\/\\]+)\.[^\/\.\\]+$/) ? RegExp.$1 : path }
function aspm2(s) {
  var m = 'qwymtvhkijasndp@ulc.xeobrzfg'
  if (!aspm2.r) {aspm2.r = {}; for (var i = 0; i < 28; i++) aspm2.r[m.charAt(i)] = m.charAt((i + 9) % 28)}
  var o = ''; for (var i = 0; i < s.length; i++) {o += aspm2.r[s.charAt(i)] || s.charAt(i)};
  document.write('<a href="mailto:' + o + '">' + o + '</a>')
}