/*******************************************************************
 *
 * Extensions to js-core for old crappy browsers
 *
 *******************************************************************/

 // Array support for the push method
 if(typeof Array.prototype.push != "function"){
 	Array.prototype.push = ArrayPush;
 	function ArrayPush(value){
 		this[this.length] = value;
 	}
 }
 // Array support for the pop method
 if(typeof Array.prototype.pop != "function"){
 	Array.prototype.pop = ArrayPop;
 	function ArrayPop() {
 		var lastItem = undefined;
 		if (this.length > 0 ) {
 			lastItem = this[this.length - 1];
 			this.length--;
 		}
 		return lastItem;
 	}
 }

/*******************************************************************
 *
 * Prototype extensions and fixes
 * Added functionality and bug fixes to the Prototype framework
 * @requires Prototype
 *
 *******************************************************************/
if(typeof Prototype != "undefined"){
  /**
   * Event#onDOMReady
   * @see http://www.vivabit.com/bollocks/2006/06/21/a-dom-ready-extension-for-prototype
   * Functionas passed to the onDOMReady method fires as soon as the DOM-structure is availible to the javascript engine
   *
   * @param {FUNCTION} f function to run
   *
   */
  Object.extend(Event, {
   _domReady: function() {
     if (arguments.callee.done) { return; }
     arguments.callee.done = true;
     if (this._timer) { clearInterval(this._timer); }
     this._readyCallbacks.each(function(f) {
       f();
     });
     this._readyCallbacks = null;
  	},
   onDOMReady: function(f) {
     if (!this._readyCallbacks) {
       var domReady = this._domReady.bind(this);
       if (document.addEventListener) {
         document.addEventListener("DOMContentLoaded", domReady, false);
       }
       /*@cc_on @*/
       /*@if (@_win32)
           document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
           document.getElementById("__ie_onload").onreadystatechange = function() {
               if (this.readyState == "complete") domReady(); 
           };
       /*@end @*/
       if (/WebKit/i.test(navigator.userAgent)) { 
         this._timer = setInterval(function() {
           if (/loaded|complete/.test(document.readyState)) { domReady(); }
         }, 10);
       }
       Event.observe(window, 'load', domReady);
       Event._readyCallbacks =  [];
     }
     Event._readyCallbacks.push(f);
   }
  });

  /** Leak free bind
   * Written by Arrix, 2006-08-24 17:15:55 GMT+0800
   * with input from Ross and Laurens
   */
  Function.prototype.bind = function() {
    var __method = this, args = $A(arguments), object = args.shift();
    return function() {
      return __method.apply(object, args.concat($A(arguments)));
    }.leak_free_closure();
  };
  Function.prototype.bindAsEventListener = function(object) {
    var __method = this, args = $A(arguments), object = args.shift();
    return function(event) {
      return __method.apply(object, [( event || window.event)].concat(args).concat($A(arguments)));
    }.leak_free_closure();
  };
  Function.prototype.leak_free_closure = function() {
    if (!window.__funs) { window.__funs = []; }
    var fun = this;
    var funId = this.__funId;
    if (!funId) { __funs[funId = fun.__funId = __funs.length] = fun; }
    fun = null;
    return function () {
      return __funs[funId].apply(null, arguments);
    };
  };

  /**
   * Written by Jonathan Snook, http://www.snook.ca/jonathan
   * Add-ons by Robert Nyman, http://www.robertnyman.com
   * @see http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/
   */
  function getElementsByClassName(oElm, strTagName, oClassNames){
  	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
  	var arrReturnElements = $A();
  	var arrRegExpClassNames = $A();
  	if(typeof oClassNames == "object"){
  		for(var i=0; i<oClassNames.length; i++){
  			arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)"));
  		}
  	}
  	else{
  		arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)"));
  	}
  	var oElement;
  	var bMatchesAll;
  	for(var j=0; j<arrElements.length; j++){
  		oElement = arrElements[j];
  		for(var k=0; k<arrRegExpClassNames.length; k++){
       if(arrRegExpClassNames[k].test(oElement.className)) {
         arrReturnElements.push($(oElement));
         break;
       }
  		}
  	}
  	if(arrReturnElements.length > 0) return arrReturnElements;
  	return false;
  }

  function insertAfter(parent, node, referenceNode) {
  	parent.insertBefore(node, referenceNode.nextSibling);
  }
  function prependChild(parent, node) {
  	parent.insertBefore(node, parent.firstChild);
  }
  /** 
   * Finds first ancestor element with given tag name
   */
  function getAncestorByTagName(e,tag){
    if(e.parentNode && e.parentNode.tagName)
      if(e.parentNode.tagName.toLowerCase() == tag.toLowerCase())
        return e.parentNode;
      else
        return getAncestorByTagName(e.parentNode,tag);
    else
      return false
  }

  Object.extend(Array.prototype, {
    maxHeight: function() {
      var h_max=0;
      this.each(function(node){
  			h = parseInt(node.getStyle('height') || node.clientHeight);
        if (h > h_max) h_max=h;
      });
      this.invoke('setStyle',{height:h_max+'px'});
      return this;
    }
  });
  
  /*
  Copyright (c) 2006 Dan Webb

  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
  documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
  the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, 
  and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all copies or substantial 
  portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
  TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 
  IN THE SOFTWARE.
  */
  DomBuilder = {
    IE_TRANSLATIONS : {
      'class' : 'className',
      'for' : 'htmlFor'
    },
    ieAttrSet : function(a, i, el) {
      var trans;
      if (trans = this.IE_TRANSLATIONS[i]) el[trans] = a[i];
      else if (i == 'style') el.style.cssText = a[i];
      else if (i.match(/^on/)) el[i] = new Function(a[i]);
      else el.setAttribute(i, a[i]);
    },
  	apply : function(o) { 
  	  o = o || {};
  		var els = ("p|div|span|strong|em|img|table|tr|td|th|thead|tbody|tfoot|pre|code|" + 
  					   "h1|h2|h3|h4|h5|h6|ul|ol|li|form|input|textarea|legend|fieldset|" + 
  					   "select|option|blockquote|cite|br|hr|dd|dl|dt|address|a|button|abbr|acronym|" +
  					   "script|link|style|bdo|ins|del|object|param|col|colgroup|optgroup|caption|" + 
  					   "label|dfn|kbd|samp|var").split("|");
      var el, i=0;
  		while (el = els[i++]) o[el.toUpperCase()] = DomBuilder.tagFunc(el);
  		return o;
  	},
  	tagFunc : function(tag) {
  	  return function() {
  	    var a = arguments, at, ch; a.slice = [].slice; if (a.length>0) { 
  	    if (a[0].nodeName || typeof a[0] == "string") ch = a; 
  	    else { at = a[0]; ch = a.slice(1); } }
  	    return DomBuilder.elem(tag, at, ch);
  	  }
    },
  	elem : function(e, a, c) {
  		a = a || {}; c = c || [];
  		var isIE = navigator.userAgent.match(/MSIE/)
  		var el = document.createElement((isIE && a.name)?"<" + e + " name=" + a.name + ">":e);
  		for (var i in a) {
  		  if (typeof a[i] != 'function') {
  		    if (isIE) this.ieAttrSet(a, i, el);
  		    else el.setAttribute(i, a[i]);
  		  }
  	  }
  		for (var i=0; i<c.length; i++) {
  			if (typeof c[i] == 'string') c[i] = document.createTextNode(c[i]);
  			el.appendChild(c[i]);
  		} 
  		return el;
  	}
  }  
  DomBuilder.apply($);
}


var ProductNavigation = Class.create();
ProductNavigation.prototype = {
  initialize: function(){
    this.toggler   = $('show_all_groups');
    this.container = $('groups_nav');
    this.list      = $(this.container.getElementsByTagName('ul')[0]);
    this.container.addClassName('scripted');
    this.list.hide();
    Event.observe(this.toggler,'click',this.toggle.bindAsEventListener(this));
  },
  toggle: function(ev){
    if (this.list.visible()) { this.hide(); }
    else { this.show(); }
    Event.element(ev).blur();
    Event.stop(ev);
  },
  show: function(ev){
    new Effect.SlideDown(this.list, {duration:0.4, queue: {position:'end', scope: 'menu'} });
  },
  hide: function(ev){
    new Effect.SlideUp(this.list, {duration: 0.4, queue: {position:'end', scope: 'menu'} });
  }
};

var Product = Class.create();
Product.prototype = {
  initialize: function(element){
    if (!(this.element = $(element) || $('product'))) { return; }
    this.about = getElementsByClassName(this.element, 'div', 'about')[0];
    this.lang = $$('html').first().lang;
    this.setupSpecifications();
    this.setupPrintAction();
  },
  setupPrintAction: function(){
    if ((printer = getElementsByClassName(this.element, 'a', 'print_product')[0])) {
      Event.observe(printer,'click', function(ev){
        window.print();
        Event.stop(ev);
      });
    }
  },
  setupSpecifications: function(){
    this.specifications = getElementsByClassName(this.element, 'div', 'specifications')[0];
    this.specifications.hide();
    this.specifications_header = $(this.specifications.getElementsByTagName('h2')[0].cloneNode(true));
    this.specifications_header.addClassName('specifications_header');
    this.about.appendChild(this.specifications_header);
    var link = $.A({href:'#product_images'},this.showLabel());
    this.specifications_header.appendChild(link);
    Event.observe(link, 'click', this.toggleSpecifications.bindAsEventListener(this));
  },
  toggleSpecifications: function(ev) {
    if (this.specifications.visible()) {
      new Effect.SlideUp(this.specifications, {duration:0.3, queue: {position:'end', scope:'specifications'}});
      var text = this.showLabel();
    } else {
     // new Effect.SlideDown(this.specifications, {duration:0.3, queue: {position:'end', scope:'specifications'}});
			Element.show(this.specifications);
			Element.scrollTo(this.specifications);
      var text = this.hideLabel();
    }
    if (ev) {
      el = Event.element(ev);
      Event.element(ev).firstChild.nodeValue = text;
    }
  },
  showLabel: function(){
    return $H({sv : 'Visa', en : 'Show', fi : 'Näytä'})[this.lang];
  },
  hideLabel: function(){
    return $H({sv : 'Stäng', en : 'Hide', fi : 'Hide'})[this.lang];
  }
};

Event.onDOMReady(function(){
  var lang = $('q-languages');
  var lang_toggler = $(lang.getElementsByTagName('a')[0]);
  var lang_list = $(lang.getElementsByTagName('ul')[0]);
  lang_list.hide();
  Event.observe(lang_toggler, 'click', function(ev){
    lang_toggler.blur();
    if (!lang_list.visible()) { new Effect.SlideDown(lang_list, {duration:0.5, queue: {position:'end', scope:'lang_select'}}); }
    else { new Effect.SlideUp(lang_list, {duration:0.3, queue: {position:'end', scope:'lang_select'}}); }
    Event.stop(ev);
  });

  if ($('show_all_groups') && $('groups')) {
    new ProductNavigation();
    new Product();
  }
  
});
