/**
 * Code to execute once the document is loaded
 */
function EkJs_onLoaded(func) {
  $(document).ready(func);
}

/**
 * String manipulation
 */

function EkJs_trim(str) {
  return jQuery.trim(str);
}

/**
 * Enable/disable the loading div
 */
function EkJs_doLoading() {
  var wpos = { left: 0, top: 0, width: $("body").width(), height: $("body").height() };
  var lpos = { left: 0, top: 0, width: $(window).width(), height: $(window).height() };

  // Add a div for the reloading
  if ($("#loading").length == 0)
    $("body").prepend('<div id="loading"><div class="wrapper"></div><div class="loader"></div></div>');
  $("#loading div.loader").css({ left: lpos.left, top: lpos.top, width: lpos.width, height: lpos.height }).show();
  $("#loading div.wrapper").css({ left: wpos.left, top: wpos.top, width: wpos.width, height: wpos.height }).show();

  return true;
}

/**
 * Popuping up an alert message
 *
 * @param string msg    message to display
 *
 * @return false
 */
function EkJs_alert(msg) {
  alert(msg);
  return false;
}

/**
 * Popuping up a confirm message and let the end-user accept or
 * reject the action
 *
 * @param string msg    message to display
 *
 * @return bool
 */
function EkJs_confirm(msg) {
  return confirm(msg);
}

/**
 * Over/out Event Management
 */
var Element_SwapClass = {

  classes: new Array(),

  set: function(object, classname) {
    if (!object)
      return;
    this.classes[object] = object.className;
    object.className = classname ? classname : 'over';
  },

  restore: function(object) {
    if (!object)
      return;
    object.className = this.classes[object];
  },

  override: function(object, name) {
    object.className = this.classes[object] = name;
  }
};

/**
 * Popup Window
 */

var _TOKEN_BLOCKED_WINDOW = "Your browser is blocking popup window. Disable it in order to proceed";

function EkJs_openWindow(url, name) {
  var width  = 640;
  var height = 480;
  var top    = (screen.height - height) / 2;
  var left   = (screen.width  - width) / 2;
  var params = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width=' + width + ',height=' + height + ',top=' + top + ',left=' + left;

  if (name == null)
    name = 'ekpopup';

  var win = window.open(url, name, params);
  if (win)
    win.focus();
  else
    EkJs_alert(_TOKEN_BLOCKED_WINDOW);
  return win;
}

/**
 * Lightbox and popup handling inside the page
 */
function LightBox() {
}

LightBox.prototype = {

  body_changed: false,

  activate: function(id) {
    this.updateHtml();

    if (this.isBuggedIE()) {
      this.IE_saveScroll();
      this.IE_updateStyles('100%', 'hidden');
    }

    var lightbox = document.getElementById('lightbox');
    var element = document.getElementById(id);
    lightbox.innerHTML = element.parentNode.innerHTML;
    this.setOpacity(lightbox, 0);
    lightbox.style.display = 'block';

    // Find the image div and the name div to set the width of the popup
    var divs = lightbox.getElementsByTagName('div', true);
    var element;
    for (i = 0; i < divs.length; i++)
      if (divs[i].className == 'name') {
	if (divs[0].offsetWidth) {
	  var length = divs[0].offsetWidth;
	  divs[i].style.display = 'none';
	  if (divs[0].offsetWidth < length)
	    divs[i].style.width = divs[0].offsetWidth + 'px';
	  divs[i].style.display = 'block';
	}
	break;
      }

    // Center
    if (lightbox.offsetWidth && lightbox.offsetHeight) {
      var offset_left = Math.round(lightbox.offsetWidth / 2);
      var offset_top  = Math.round(lightbox.offsetHeight / 2);
      lightbox.style['top'] = '50%';
      lightbox.style['left'] = '50%';
      lightbox.style['margin'] = '-' + offset_top + 'px 0 0 -' + offset_left + 'px';
    }
    this.setOpacity(lightbox, 100);

    var overlay = document.getElementById('overlay');
    overlay.style.display = 'block';
    this.setOpacity(document.getElementById('overlay'), 85);
  },

  setOpacity: function(element, value) {
    value = Math.round(value);
    if (value < 0)
      value = 0;
    else if (value > 100)
      value = 100;
    element.style['opacity']     = value / 100;
    element.style['moz-opacity'] = value / 100;
    element.style['filter']      = 'alpha(opacity=' + value + ')';
  },

  updateHtml: function() {
    if (this.body_changed)
      return;
    this.body_changed = true;
    document.body.innerHTML = '<div id="overlay" onclick="myLightBox.deactivate()"></div><div id="lightbox"></div>' + document.body.innerHTML;
    document.getElementById('overlay').style.height = document.body.clientHeight + 'px';
  },

  deactivate: function() {
    if (this.isBuggedIE()) {
      this.IE_restoreScroll();
      this.IE_updateStyles('auto', 'auto');
    }
    document.getElementById('lightbox').style.display = 'none';
    document.getElementById('overlay').style.display = 'none';
  },

  isBuggedIE: function() {
    var _version = navigator.userAgent.split("MSIE");
    return _version.length > 1 && parseFloat(_version[1]) >= 5.5 && parseFloat(_version[1]) < 7;
  },

  IE_saveScroll: function() {
    if (self.pageYOffset)
      this.scroll_ypos = self.pageYOffset;
    else if (document.documentElement && document.documentElement.scrollTop)
      this.scroll_ypos = document.documentElement.scrollTop; 
    else if (document.body)
      this.scroll_ypos = document.body.scrollTop;
    window.scrollTo(0, 0);
  },

  IE_restoreScroll: function() {
    window.scrollTo(0, this.scroll_ypos);
  },

  IE_updateStyles: function(height, overflow) {

    bod = document.getElementsByTagName('body')[0];
    bod.style.height = height;
    bod.style.overflow = overflow;
  
    htm = document.getElementsByTagName('html')[0];
    htm.style.height = height;
    htm.style.overflow = overflow; 
  }
};

var myLightBox = new LightBox();

/**
 * Manage product attributes supported in the product home
 * page
 */
function EkJs_ProductAttributes(element_id, combinations) {
  this.element_id = element_id;
  this.combinations = combinations;
}

EkJs_ProductAttributes.prototype = {

  onChange: function(element) {
    // Get the combination value selected
    var v = new Array();
    for (var i = 0; i < element.form.length; i++) {
      var item = element.form.elements[i];
      if (item.name != element.name)
	continue;
      var v1 = typeof(item.options) == "undefined" ? item.value : item.options[item.selectedIndex].value;
      if (parseInt(v1) > 0)
	v[v.length] = parseInt(v1);
    }
    v = v.sort(function(a,b){ return a - b });
    v = v.length > 0 ? ',' + v.join(',') + ',' : '';

    // Try to find in the list of supported combinations
    var id = -1;
    for (var i = 0; i < this.combinations.length; i++)
      if (this.combinations[i].value == v) {
	id = this.combinations[i].id;
	break;
      }

    // Get current selected id
    if (id == -1) {
      hideLayer(this.element_id + '_on');
      showLayer(this.element_id + '_off');
    } else if (id == element.form.elements['cID'].value) {
	// This is the current product: no need to reload
      showLayer(this.element_id + '_on');
      hideLayer(this.element_id + '_off');
    } else {
      // Change the combination and reload it
      element.form.elements['cID'].value = id;
      element.form.elements['action'].value = '';
      EkJs_doLoading();
      element.form.submit();
    }
  }
};

/**
 * Layer/Div Management
 *
 * This section defines functions to hide or show layers.
 * It also provide function to check whether a layer is visible
 * or not.
 */

function showLayer(id) { 
  $("#" + id).show();
} 

function hideLayer(id) {
  $("#" + id).hide();
} 
