﻿// Common JS
// Contains the following:
//    Video Player
//    Working pop ups

// Publishing Date: Montag, 30. Mai 2011 18:21

/* ********************************************************************************* */
/* ### View Helper                                                               ### */
/* ********************************************************************************* */
documentViewHelper = {
    init : function() {
        hoverImages.init();
        externalLinkParser();
        checkParam();		
    }
 }
 
hoverImages = {
    // HoverImages v0.1 is Copyright (c) by Philipp Reinstädtler and Martin Preiß. It's  
    // released under the MIT License: http://www.opensource.org/licenses/mit-license.php
    srcDelimiter : "#",
    preloadimages : new Array(),
    preload : function(imgsrc) {
        var img = new Image();
        img.src = imgsrc;
        return this.preloadimages.push(img);
    },
    init : function() {
        regExpTest = new RegExp(this.srcDelimiter);
        regExpFind = new RegExp("(.*)" + this.srcDelimiter + "(.*)");  
        images =$('topbar').getElementsByTagName('img');
        for (i = 0; i < images.length; i++) {
            img = images[i];
            if(regExpTest.test(img.getAttribute('src'))) {
                 img.setAttribute('src_reg', regExpFind.exec(img.getAttribute('src'))[1]);
                 img.setAttribute('src_ovr', regExpFind.exec(img.getAttribute('src'))[2]);
                 img.onmouseover = function(){ this.setAttribute('src', this.getAttribute('src_ovr')); };    
                 img.onmouseout = function(){ this.setAttribute('src', this.getAttribute('src_reg')); };
                 img.onmouseout();
                 this.preload(img.getAttribute('src_ovr'));
            }
        }
    }
};
function externalLinkParser() {
    links =$('main').getElementsByTagName('a');
    for (i = 0; i < links.length; i++) {
        link = links[i];
        if(link.getAttribute('target') && link.getAttribute('target')=='_blank'){                        
            link.setAttribute('target','_self');
            link.setAttribute('href','javascript:checkExtLink("'+link.getAttribute('href')+'");');
        }
    }
}     

/* ********************************************************************************* */
/* ### DOM Helper                                                                ### */
/* ********************************************************************************* */
domHelper = {
    bottomDiv : function(p) {
        $(p.rootID).insert($(p.rootID).select('.' + p.cssClassLast)[0].remove());
    },
    sortSelectOptions : function(p) {
        //{select:selectField,start:0}
        var a = new Array();
        while (p.select.options[p.start]!= null) { a.push([p.select.options[p.start].text, p.select.options[p.start].value]); p.select.options[p.start] = null; }
        a.sort(function(a, b) { return(a[0]>b[0])?1:-1; });
        $A(a).each(function(n) { p.select.options[p.select.length] = new Option(n[0], n[1], false) } )
    },
    randomSortDivs : function(p) {
        var currDivs = [];
        //var formFieldsDiv = $(p.rootID).getElementsByClassName(p.cssClass);
        var formFieldsDiv = $(p.rootID).select('.' + p.cssClass);
        
        formFieldsDiv.each(function(item){
            currDivs.push(item.innerHTML)
        });
        currDivs.sort(function() {return 0.5 - Math.random();})
        var index = 0;
        formFieldsDiv.each(function(item){
            item.show();
            item.innerHTML = currDivs[index ++];
        });
    } 
}
/* ********************************************************************************* */
/* ### CSS Helper                                                                ### */
/* ********************************************************************************* */
cssHelper = {
    addChildNodeClassNames : function(p) {
        var childNode = p.rootNode.firstChild;
        var i = 0;
        while (childNode != null) {
            if (typeof childNode.className != 'undefined' && childNode.tagName == 'DIV') {
                $(childNode).addClassName(p.classeNames[i]);
                if (++i >= p.classeNames.length) i = 0;
            }
            childNode = childNode.nextSibling;
        }
    },
    findLastElement : function(p) {
       //elements = p.rootNode.getElementsByClassName(p.cssClass);
       elements = p.rootNode.select('.' + p.cssClass);
       elements[elements.length-1].addClassName(p.additionalClass);
    }
    
}

/* ********************************************************************************* */
/* ### Page History Class                                                        ### */
/* ********************************************************************************* */
// JS Page History
function PageHistory(actualElement) {
    this.ids = new Array;
    this.ids.push(actualElement);
    
    
    if (typeof PageHistory._initialized == "undefined") {
        PageHistory.prototype.log = function() {
            console.log(this.ids);
        }
        PageHistory.prototype.addNextPage = function(newElement) {
            this.ids.push(newElement);
        }
        PageHistory.prototype.deleteLastPage = function() {
            this.ids = this.ids.slice(0,this.ids.length-1);
        }
        PageHistory.prototype.openLastPage = function() {
            this.deleteLastPage();
            $('box').childElements().each(function(value) {
                value.hide(); 
            });                                                
            (this.ids[this.ids.length-1]).show();
        }
    }
    PageHistory._initialized = true;                                        
}

/* ********************************************************************************* */
/* ### List Sorter Class                                                         ### */
/* ********************************************************************************* */
// order = 'desc' or 'asc'
function ListSorter(dataArray, order) {
  this._dataArray = dataArray;
  this._order = order || 'desc';
  this.sortList();
}
ListSorter.prototype = {
  sortList: function() {
    var date;
    for(var i = 0; i < this._dataArray.length; i++) {
      var reDateSeparator = /(\/|\-)/g;
      date = this._dataArray[i].date.toString().replace(reDateSeparator,".").split('.');
      this._dataArray[i].dateObj = new Date(parseInt(date[2]),parseInt(date[1]),parseInt(date[0]));
    }
    switch(this._order) {
      case 'asc':
        this._dataArray.sort(this._sortAsc);
      break;
      case 'desc':
        this._dataArray.sort(this._sortDesc);
      break;
      default:
        throw new Error('Sort-Type not allowed');
      break;
    }
  },
  writeHtml: function() {
    for(var i = 0; i < this._dataArray.length; i++) {
      document.write(this._dataArray[i].html);
    }
  },
  _sortAsc: function(a, b){
    if(a.dateObj > b.dateObj)
      return 1 ;
    else if(a.dateObj == b.dateObj)
      return 0;
    return -1;
  },
  _sortDesc: function(a, b){
    if(a.dateObj > b.dateObj)
      return -1 ;
    else if(a.dateObj == b.dateObj)
      return 0;
    return 1;
  }
};

/* ********************************************************************************* */
/* ### Browser Detection (IE / WII)                                              ### */
/* ********************************************************************************* */
/* check for the wii */
function browserDetectionWii(){
    if( window.opera && opera.wiiremote ) {
        document.write('\<LINK rel="stylesheet" type="text/css" href="/NOE/css/wiihacks.css">');
    }
}
function checkWii(){
    if(window.opera && opera.wiiremote){ return true; }
    else { return false; }
}

/* check for IE */
function checkIE() {
  var arVersion = navigator.appVersion.split("MSIE");
  var version = parseFloat(arVersion[1]);
  return ((version >= 5.5) && (version <= 7) );
}  
function checkIE6() {
  var arVersion = navigator.appVersion.split("MSIE");
  var version = parseFloat(arVersion[1]);
  return ((version >= 5.5) && (version < 7) );
} 

/* ********************************************************************************* */
/* ### Convert PNG (IE6 workaround)                                              ### */
/* ********************************************************************************* */
function convertPNG(element) {
  var arVersion = navigator.appVersion.split("MSIE");
  var version = parseFloat(arVersion[1]);
  if ((version >= 5.5) && (version < 7) ) {
    var imgName = element.src;
    if (imgName.substring(imgName.length-3, imgName.length) == "png") {
         var imgID = (element.id) ? "id='" + element.id + "' " : "";
         var imgClass = (element.className) ? "class='" + element.className + "' " : "";
         var imgTitle = (element.title) ? "title='" + element.title + "' " : "title='" + element.alt + "' ";
         var imgStyle = "display:inline-block" + element.style.cssText ;
         if (element.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
         var strNewHTML = "<span " + imgID + imgClass + imgTitle
         + " style=\"" + "width:" + element.width + "px; height:" + element.height + "px;" + imgStyle + ";"
         + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
         + "(src=\'" + element.src + "\', sizingMethod='image');\"></span>" ;
         element.outerHTML = strNewHTML;
    }
  }  
} 

/* ********************************************************************************* */
/* ### Support - Contact                                                         ### */
/* ********************************************************************************* */
function showNHideContact(array){
    //var boxes = $('col-cont-content-inner').getElementsByClassName('show-box'); 
    var boxes = $('col-cont-content-inner').select('.show-box'); 
    boxes.each(function(item){
        item.hide();
      }
      );
    array.each(function(item){
        new Effect.BlindDown('show-box-'+item, {duration:0.5});
    }
      );
    
}
/* opens an existing Support Box by passing the corressponding id Get Parameter 
  Example: /support.html?id=5  */ 
function openSupportBox(){
    var url   = window.location.search;
    if (url != "") {
        url = url.substring(1,url.length);                      
        urlParam = url.split("?");
        idValue = urlParam[0].split("=")[1];
        if($('box_3_'+idValue+'_closed') != null) {
              Event.observe(window, 'load', function() {
                  fadeNAppearDiv('box_3_'+idValue);
                  if($('anchor_3_'+idValue) != null) {
                      var elementOffsetTop = $('anchor_3_'+idValue).offsetTop + 400;
                      window.scrollTo(0,elementOffsetTop);
                  }
              });
        }
}}

/* switches the Tabs in the Support Area
 the dome parser will find all elements in the special div and will reset them to the default class (inactive or display none) */ 
function switchTabs(newNr){
    /* find all divs with id="tab_" and hide them */
    allTabs = $('tab_block').descendants();    
    regExpTab = /tab_/;
    newTab = "tab_" + newNr;
    allTabs.each(function(item) {
        if(regExpTab.test(item.id)) {
            if(item.getStyle('display')=='block'){
                $(item.id).hide();
            }
        }
    });
    $(newTab).show();
        
    /* find all links and set them to inactive */
    newLink = "link_" + newNr;
    allLinks = $('tabnav').descendants();
    regExpLink = /active/;    
    allLinks.each(function(item) {
        if(regExpLink.test(item.classNames())) {
            item.className = 'inactive';
        }
    });
    $(newLink).className = 'active';
}
//Wii Support Suggestion Box
function suggest(inputElementLength, layerElement) {    
    var countElements = 0;
    if(inputElementLength >= 1) {        
        layerElement.childElements().each(function(item, i) {
            //console.log("ID:"+ item.id +" VALUE:" + item.innerHTML)
            //$(item.id).hide();
            if (item.innerHTML.startsWith($('combo1').value))  {
                item.show();
                countElements = countElements + 1;
            } 
            else { item.hide(); }                            
        })
        if(countElements > 0) { layerElement.show()}
        else { layerElement.hide(); }
    }
                            
    else { layerElement.hide(); }
}       
                      
function showElements() {    
    var mycontent = $('combo1').value;             
    $('box').childElements().each(function(value, index) {
        value.hide(); 
    })                                                
    $(mycontent).show();
    $('combo1').value = '';    
}
function showElement(mycontent) {                                 
    $('box').childElements().each(function(value, index) {        
        value.hide(); 
    })                                                
    $(mycontent).show();
    if(PageHistory._initialized)pageHistory.addNextPage(mycontent);    
}

/* ********************************************************************************* */
/* ### Virtual Guide                                                             ### */
/* ********************************************************************************* */
function showHelpBox(element_box, element_link){
 if (element_box.visible())  {
    element_link.className = "link-arrow";
    new Effect.BlindUp(element_box, {duration:0.5}); 
 }
 else { 
    element_link.className = "link-arrow-down"; 
    new Effect.BlindDown(element_box, {duration:0.5});
 }
}

/* ********************************************************************************* */
/* ### Fading & Displaying/Hiding DOM Elements                                   ### */
/* ********************************************************************************* */
// Fade Elements
function initFading(element, id){
  //var games = $(element).getElementsByClassName(id);
  var games = $(element).select('.' + id);
  games.each(function(item, index){
    new Effect.Appear(item, {delay:0.1*(index+1), duration: 1.0, from: 0.3, to:1 });
  }
  );
 }
 
// Ein- und Ausfaden beliebiger Divs (z.B. Login)
function fadeDiv(div, time, pos){
    if (pos){
        new Effect.Fade(div, {duration:time, queue:pos});
    }else {
          new Effect.Fade(div, {duration:time});
    } 
}
function appearDiv(div, time, pos){
    if(pos){
        new Effect.Appear(div, {duration:time, queue: pos});    
    }else {
        new Effect.Appear(div, {duration:time});
    }
}
/** Fadet ein Div erst aus und dann das andere ein **/
function fadeNAppearDiv(div){
    div_closed = div + "_open";
    div_link = div + "_link";
    
    if($(div_closed).style.display!="none"){
        $(div_link).className ="link-arrow plus";
        new Effect.SlideUp(div_closed, {duration:0.3, queue: 'front'});
    }
    else{
        $(div_link).className ="link-arrow minus";
        new Effect.SlideDown(div_closed, {duration:0.5, queue: 'front'});
    }
    
}
// Layer-Functions
function closeLayer(layerID) {
    $(layerID).hide();
}

/* ********************************************************************************* */
/* ### AJAX Login Functions                                                      ### */
/* ********************************************************************************* */
function focusUsername(){
    input=$('login-username');
    input.value='';
    input.focus();
}
function blurUsername(){
    input=$('login-username');
    if(input.value=='')    input.value='Username';
}
function focusPassword(){
    input=$('login-password');
    if (input.value=='Password'){
        input.value='';
    }
    input.type='password';
    input.focus();
}
function blurPassword(){
    input=$('login-password');
    if(input.value==''){
        input.value='Password';
        input.type='text';
    }
}
function toggle_login()
{
    act=$('not-logged-in');
    if(act.className=='hidden_'){
        act.className='hidden';
        $('login').className='hidden_';
        return;
    }
    act= $('login');
    if(act.className=='hidden_'){
        act.className='hidden';
        $('logged-in').className='hidden_';
        return;
    }
    act=$('logged-in');
    if(act.className=='hidden_'){
        act.className='hidden';
        $('not-logged-in').className='hidden_';
        return;
    }
}

/* ********************************************************************************* */
/* ### Top-Navigation Functions                                                  ### */
/* ********************************************************************************* */
function changeClassName(id,newClass){
    $(id).className = newClass;
}
/* Function to change the State of the actual site in the Main Navigation,
 * Param actual_id is the actual webpage
 */ 
function changeActiveState(actual_id){
    
    /* Array with the content for the navigation
     * 
     * name = the id of the navigation element
     * pre  = the part in front of the link
     * nxt  = the part behind the link
     */
    if (actual_id != "") {
        var nav_element = new Array();
        
        nav_element[0] = new Object();
        nav_element[0].name = "home";
        nav_element[0].pre = "first";
        nav_element[0].nxt = "std_nxt";
        
        nav_element[1] = new Object();
        nav_element[1].name = "nds";
        nav_element[1].pre = "std_pre_red";
        nav_element[1].nxt = "std_nxt_red";
        
        nav_element[2] = new Object();
        nav_element[2].name = "wii";
        nav_element[2].pre = "std_pre_green";
        nav_element[2].nxt = "std_nxt_green";
        
        nav_element[3] = new Object();
        nav_element[3].name = "games";
        nav_element[3].pre = "std_pre";
        nav_element[3].nxt = "std_nxt";
        
        nav_element[4] = new Object();
        nav_element[4].name = "club";
        nav_element[4].pre = "std_pre";
        nav_element[4].nxt = "std_nxt";
        
        nav_element[5] = new Object();
        nav_element[5].name = "support";
        nav_element[5].pre = "std_pre";
        nav_element[5].nxt = "std_nxt";
        
        nav_element[6] = new Object();
        nav_element[6].name = "news";
        nav_element[6].pre = "std_pre";
        nav_element[6].nxt = "last";

        nav_element[7] = new Object();
        nav_element[7].name = "3ds";
        nav_element[7].pre = "std_pre_red";
        nav_element[7].nxt = "std_nxt_red";
        
        
        /* get all the siblings in front and after the actual link */
        previousNavElement = $(actual_id).previous();
        nextNavElement = $(actual_id).next();
        
        /* the name of the class for the snippets between the navigation items*/
        var reg_ex_holder =/holder/;
        
        getActives(nav_element, previousNavElement,nextNavElement,actual_id);
    }
}
/* Function to search for the menu item in the array and mark the active one */
function getActives(nav_element,prevLink,nextLink, actual_id) {
    
    nav_element.each(function(item) {
        if(actual_id==item.name){
            /* Adds the _act snippet to the actual class  */
            $(prevLink).addClassName(item.pre + "_act"); 
            $(nextLink).addClassName(item.nxt + "_act");
        }
    });
    
}
/* This function will be started on bodyload at sets to the first holder the "first" class */ 
function getTheFirstHolder(startID){
    /* find first child */
    firstChild = $('nav_main').down();
    firstChild.removeClassName("std");
    firstChild.addClassName("first");
}

/* ********************************************************************************* */
/* ### PopUp / Layer functions / Disclaimer Layer                                ### */
/* ********************************************************************************* */
function windowOpen(url, titel, width, height) {
    var left = 0;
    var top = 0;
    left = (screen.width/2)-(width/2);
    top = (screen.height/2)-(height/2);
    window.open(url, 'titel', 'width='+width+', height='+height+', scrollbars=yes, left='+left+', top='+top);
}
function windowOpenAdvanced(url, titel, width, height, top, left, options) {
    window.open(url, 'titel', 'width='+width+', height='+height+', '+options+', left='+left+', top='+top);
}
/* Functions for the popup layer */ 
var global_link;
/* this will fade in the background and the popup layer */
function checkExtLink(linkurl){
    
    global_link = linkurl;
    // horizontal centering
    margin_viewport = String(Position.page($('overlayer')));
    
    y_margin = margin_viewport.split(",");
    if(y_margin[1]>=0){
        y_margin[1] = y_margin[1];
    }
    else{
        y_margin[1]= y_margin[1] * -1;
    }
    
    $('warning').style.top = (y_margin[1] + (screen.height/2)-(260)) + 'px'; 
    $('warning').style.visibility = 'visible';
    
    // fading the background layer in
    new Effect.Appear('overlayer', {duration:0.6,to:0.5, beforeStart: function() { hideLayerElements() }} );
    $('warning').show();
}

/* this will fade out the popup layer and will open the external link - if necessary */        
function actionForExtLink(dec){
    new Effect.Fade('overlayer', {duration:0.6, afterFinish: function() { showLayerElements() }} );
    $('warning').hide();
    
    if(dec=="true"){
        window.open(global_link); 
    }
}
/* this will fade in the background and the popup layer for the facebook legal text */
function checkExtLinkFB(){
    
    // horizontal centering
    margin_viewport = String(Position.page($('overlayer')));
    
    y_margin = margin_viewport.split(",");
    if(y_margin[1]>=0){
        y_margin[1] = y_margin[1];
    }
    else{
        y_margin[1]= y_margin[1] * -1;
    }
    
    $('fb-legal-info').style.top = (y_margin[1] + (screen.height/2)-(400)) + 'px'; 
    $('fb-legal-info').style.visibility = 'visible';
    
    
    // fading the background layer in
    new Effect.Appear('overlayer', {duration:0.6,to:0.5, beforeStart: function() { hideLayerElements() }} );
    $('fb-legal-info').show();
}
/* this will fade out the popup layer and will open the facebook-link - if necessary */ 
function actionForExtLinkFB(name, link, image, description){
   new Effect.Fade('overlayer', {duration:0.6, afterFinish: function() { hideLayerElements() }} );
    $('fb-legal-info').hide();    
    
    new Effect.Fade('overlayer', {duration:0.6, afterFinish: function() { hideLayerElements() }} );
    $('warning').hide();
    
    flink = "http://www.nintendo.co.uk"+link;
    var message = ''; 
    var attachment = { 
        'name': name, 
        'href': link, 
        'description': description, 
        'media': [{ 'type': 'image', 'src': image, 'href': link}] 
    }; 

    if($('nav-sub') != null) {
        $('nav-sub').style.visibility = 'hidden';
    } 
    var action_links = null;

    FB.Connect.streamPublish(message, attachment, action_links, null, '', callback);
    function callback( post_id, exception ) {
        new Effect.Fade('overlayer', {duration:0.6, afterFinish: function() { showLayerElements() }} );
    }
}
function hideLayerElements() {
    if(navigator.appVersion.substring(17,25)=="MSIE 6.0"){
        var s = document.getElementsByTagName('select');
          for (var i=0; i<s.length; i++) {
                s[i].style.visibility = 'hidden';
          }
    } 
    if($('nav-sub') != null) {
        $('nav-sub').style.visibility = 'hidden';
    } 
    /* var objectElements = document.getElementsByTagName('object');
    if(objectElements.length > 0) {
       for (var i=0; i<objectElements.length; i++) {
           objectElements[i].style.visibility = 'hidden';
       }
    }
    var embedElements = document.getElementsByTagName('embed');
    if(embedElements.length > 0) {
        for (var i=0; i<embedElements.length; i++) {
           embedElements[i].style.visibility = 'hidden';
        }
    } */
}
function showLayerElements() {
    if(navigator.appVersion.substring(17,25)=="MSIE 6.0"){
        var s = document.getElementsByTagName('select');
          for (var i=0; i<s.length; i++) {
                s[i].style.visibility = 'visible';
          }
    } 
    if($('nav-sub') != null) {
        $('nav-sub').style.visibility = 'visible';
    } 
    
    /* var objectElements = document.getElementsByTagName('object');
    if(objectElements.length > 0) {
       for (var i=0; i<objectElements.length; i++) {
           objectElements[i].style.visibility = 'visible';
       }
    }
    var embedElements = document.getElementsByTagName('embed');
    if(embedElements.length > 0) {
        for (var i=0; i<embedElements.length; i++) {
           embedElements[i].style.visibility = 'visible';
        }
    }*/
}
/* this will fade in the background and the popup layer */
function showHelpLayer(layer){
    
    // horizontal centering
    margin_viewport = String(Position.page($('overlayer')));
    
    y_margin = margin_viewport.split(",");
    if(y_margin[1]>=0){
        y_margin[1] = y_margin[1];
    }
    else{
        y_margin[1]= y_margin[1] * -1;
    }
    
    layer.style.top = (y_margin[1] + (screen.height/2)-(400)) + 'px'; 
    layer.style.visibility = 'visible';
    
    // fading the background layer in
    new Effect.Appear('overlayer', {duration:0.6,to:0.5, beforeStart: function() { hideLayerElements() }} );
    layer.show();
    
}
/* this will fade out the popup layer and close the help window */        
function hideHelpLayer(layer){
    new Effect.Fade('overlayer', {duration:0.6, afterFinish: function() { showLayerElements() }} );
    layer.style.visibility = 'hidden';
}


ModalLayer = {
        
    _html: null,
    
    _$overlayer: null,
    _$wrapper: null,
    _$middle: null,
    _$content: null,
    
    _isOpen: false,
    _isInitialized: false,
    
    // counter to append on request URL for IE6 caching bug
    c: 0,
    
    init: function() {
        if(this._isInitialized) {
            return;
        }
        this.setTemplate("default");
        this._$overlayer = $('overlayer');
        this._isInitialized = true;
    },
    
    setTemplate: function(templateName) {
        switch(templateName) {
            case "default":
                this._$wrapper = new Element('div', {className: "help_layer help_layer_540 flexible"});
                this._$wrapper.insert(new Element('div', {className: "top"}).insert(new Element('img', {src: "/NOE/images/siteware/bg-540-popup-top-trans.png"})));
                
                this._$middle = new Element('div', {className: "middle clearfix"});
                this._$middle.insert(new Element('div', {className: "left"}).insert(new Element('img', {src: "/NOE/images/siteware/bg-12-popup-long-left-trans.png", className: 'shadow'})));
                this._$content = new Element('div', {className: "content"});
                this._$middle.insert(this._$content);
                this._$middle.insert(new Element('div', {className: "right"}).insert(new Element('img', {src: "/NOE/images/siteware/bg-12-popup-long-right-trans.png", className: 'shadow'})));
                this._$wrapper.insert(this._$middle);
                
                this._$wrapper.insert(new Element('div', {className: "bottom"}).insert(new Element('img', {src: "/NOE/images/siteware/bg-540-popup-bottom-trans.png"})));
            break;
        }
    },
    
    openContent: function(content) {
        this.init();
        var self = this;
        
        this._$content.update(content);
        this.fadeIn();
        
        var $forms = this._$content.getElementsBySelector('form');
        for(var i=0; i < $forms.length; i++) {
            var $form = $forms[i];
            $form.observe("submit", function(e) {
                Element.extend($form);
                self.openUrl($form.action, $form.method, $form.serialize());
                e.stop();
            });
        }
        
        var $closers = this._$content.getElementsBySelector('.modal_close');
        for(var i=0; i < $closers.length; i++) {
            var $closer = $closers[i];
            $closer.observe("click", function(e) {
                e.stop();
                self.fadeOut();
            });
        }
    },
    
    openUrl: function(url, method, params) {
        this.init();
        
        var m = method || "get";
        var self = this;
        new Ajax.Request(url + '?c=' + this.c++, {
            method: m,
            parameters: params,
            onSuccess: function(transport) {
              var response = transport.responseText;
              self.openContent(response);
            }
        });
    },
    
    fadeIn: function() {
        this._isOpen = true;
        var self = this;
        new Effect.Appear('overlayer', {
            duration: 0.6,
            to: 0.5, 
            recenterAuto: true,
            beforeStart: function() { 
                hideLayerElements() 
            }, 
            afterFinish: function() {
                var $images = self._$middle.getElementsBySelector('.shadow');
                for(var i=0; i < $images.length; i++) {
                    $images[i].setStyle({'display' : 'block', 'height' : self._$content.getHeight() + 'px', 'width': '12px'});
                }
                // ie6 resize bug...
                self._$overlayer.setStyle({'height': $('body_helper').getHeight() + 50 + 'px'});
            }
        });
        
        this._$overlayer.insert({before: this._$wrapper});
        this._$wrapper.style.display = 'block';
        this._$wrapper.style.visibility = 'visible';
    },
    
    fadeOut: function() {
        this._isOpen = false;
        this._$overlayer.hide();
        this._$wrapper.hide();
    }
}
/**
 * Helper methods for special modal layers
 */
ModalLayerController = {
    openNsmbSendToFriend: function(lang) {
        ModalLayer.openContent('<a style="float: right; margin-right: 15px; margin-top: -20px;" href="#" class="modal_close"><img title="x" alt="x" src="/NOE/images/buttons/close-x.png"/></a><iframe frameborder="0" scrolling="no" style="height:1050px; width: 481px; border: 0; overflow: hidden;" src="http://events.nintendo.de/nsmb/sendtofriend.php?lang='+lang+'"></iframe>');
    }
}
// doesn´t work for IE correctly, so the init is applied in the opener-functions
//document.observe("dom:loaded", function() {
//      ModalLayer.init();
//});



/* Appearing the Layer in the Stars catalog item list */
function showStarsCatalogeLayer(element){
    $(element).up().style.opacity = '1';
    $(element).hide();
    $(element).setStyle({visibility: 'visible'});
    if(!checkIE6()){
       new Effect.Appear(element, {duration:0.3});
    }
    else { $(element).show(); }
}
function hideStarsCatalogeLayer(element){
    if(!checkIE6()){
       new Effect.Fade(element, {duration:0.3});
    }
    else { $(element).hide(); }
}


/* ********************************************************************************* */
/* ### Club Nintendo related functions                                           ### */
/* ********************************************************************************* */
function hideNShow(element_hide, element_show){
    element_hide.hide();    
    element_show.show();    
    //new Effect.Fade(element_hide, {duration:0.5});
    //new Effect.Appear(element_show, {duration:0.5});
}
function hideNShowPwdFields(element_hide, element_show) {
    element_show.select('input[type="password"]').each(function(item) {
        item.value = '';
    });
    element_hide.hide();
    element_show.show();
}

/* Toggle the Tabs in the my Profile Area */
function toggleProfileTabs(element1, element2, link_tab, link_tab2){
    $(element1).show();
    $(element2).hide();
    
    previousElementLink1 = $(link_tab).previous();
    nextElementLink1 = $(link_tab).next();
    $(previousElementLink1).className= "std_act_pre";
    $(nextElementLink1).className= "std_act_after";
    $(link_tab).className = "active";
    
    previousElementLink2 = $(link_tab2).previous();
    nextElementLink2 = $(link_tab2).next();
    $(previousElementLink2).className= "std_non_act_pre";
    $(nextElementLink2).className= "std_non_act_after";
    $(link_tab2).removeClassName('active');
    
}
var productPos = 0;
function initRegisteredProducts(move){
    productPos += move;
    for(i=0;i<5;i++){
        id_nr = i +1;
        div_name = "rp_item_" + id_nr;
        array_pos = productPos +i;
        
        if(registered_products[array_pos]==null){
            $(div_name).className = 'empty';
            $(div_name).innerHTML ='&nbsp;';
        }
        else{
            $('registere_products_right').style.visibility = 'visible';
            $('registere_products_left').style.visibility = 'visible';
            $(div_name).className = 'item';
            $(div_name).innerHTML ='<img src="' + registered_products[array_pos].url +'" alt="' + registered_products[array_pos].name +'" title="' + registered_products[array_pos].name + '" />';
        }
        if(productPos<1){
            $('registere_products_left').style.visibility = 'hidden';
        }
        if(registered_products[array_pos+1]==null){
            $('registere_products_right').style.visibility = 'hidden';
        }
    }
}
/* adds recipients for "send wishlist" page  */
var numRecipients = 1;
//function addRecipient(container, max) {
function addRecipient(container) {
//    if (numRecipients < max) {
    if (numRecipients < 5) {
        numRecipients++;
        
        // row for name
        var rowName = document.createElement('div');
        rowName.className = 'row';
        // label for name
        var labelName = document.createElement('label');
        labelName.setAttribute('for','ff_name_'+numRecipients);
        labelName.appendChild(document.createTextNode('Name:'));
        
        // input for name
        var inputName = document.createElement('input');
        inputName.setAttribute('type','text');
        inputName.setAttribute('id','ff_name_'+numRecipients);
        inputName.setAttribute('name','ff_name_'+numRecipients);
        // put row for name together
        rowName.appendChild(labelName);
        rowName.appendChild(inputName);
        
        // row for email
        var rowEmail = document.createElement('div');
        rowEmail.className = 'row';
        // label for email
        var labelEmail = document.createElement('label');
        labelEmail.setAttribute('for','ff_email_'+numRecipients);
        labelEmail.appendChild(document.createTextNode('Email:'));
        
        // input for email
        var inputEmail = document.createElement('input');
        inputEmail.setAttribute('type','text');
        inputEmail.setAttribute('id','ff_email_'+numRecipients);
        inputEmail.setAttribute('name','ff_email_'+numRecipients);
        // put row for name together
        rowEmail.appendChild(labelEmail);
        rowEmail.appendChild(inputEmail);
        // append rows to container
        container.appendChild(rowName);
        container.appendChild(rowEmail);
    }
}
// Add & Remove recipients for "send wishlist" page
function showFirstInactiveRecipient() {
    //var hiddenRecipients = $('recipients').getElementsByClassName('hide');
    var hiddenRecipients = $('recipients').select('.hide');
    if(hiddenRecipients.length > 0){
        hiddenRecipients[0].removeClassName('hide');
        hiddenRecipients[0].down('.link-minus').show();
        hiddenRecipients[0].previous().down('.link-minus').hide();
    }
    if(hiddenRecipients.length == 1){ $('link_box_add').hide(); }
}
function removeRecipient(element, parentFlag) {
    var elementInputFields = $A(element.getElementsByTagName('input'));
    elementInputFields.each(function(item) {
        item.value = '';
    });
    element.addClassName('hide');
    if(parentFlag) {element.previous().down('.link-minus').show();}
    //if($('recipients').getElementsByClassName('hide').length > 0) {    $('link_box_add').show(); }
    if($('recipients').select('.hide').length > 0) {    $('link_box_add').show(); }
    if((errorWrapper = element.down('.error_wrapper')) && errorWrapper.visible()) {errorWrapper.remove();}
}
function checkRecipientValues(element) {
    if(element.down('input',0).value != '' || element.down('input',1).value != '') {
        element.removeClassName('hide');
        element.down('.link-minus').show();
        element.previous().down('.link-minus').hide();
    }
}
function changeSearchTab(id){
    //$('search_tabs').getElementsByClassName('tab_active').each(function(item){
    $('search_tabs').select('.tab_active').each(function(item){
        item.className = 'tab';
    });
    $(id).className = 'tab_active';
}
 
function checkParam(){
    if (window.location.search != "") {
        var param = window.location.search;
        var count = param.indexOf("=");
        var value = param.substr(count+1);
        if (value == "userData") {
            hideNShow ($('item-user-data'), $('item-user-data-form'))
        }
    }
}
function checkURLParamByKey(key){
    if (window.location.search != "") {
        var param = window.location.search;
        var count = param.indexOf(key);
        var value = param.substr(count);
        value = param.substr(param.indexOf("=")+1);
        return value;
    }
}
// Timestamp Comparison for AAA Games
function checkTimestampDiff(expireDateString) {
    if(expireDateString != "") {
        var expireDateArray = expireDateString.split("/");
        var expireDate = new Date((expireDateArray[2]),(expireDateArray[1]-1),(expireDateArray[0]),12,00,0);
        var actualDate = new Date();
        //console.log("Actual Date: " + actualDate);
        //console.log("Last Update: " + expireDate);
        var timestampDiff = Date.parse(expireDate) - Date.parse(actualDate);
        //console.log("Timestamp Difference: " + timestampDiff);
        if (timestampDiff > 0){ 
            return true;
        } 
    }
}
// Timestamp Comparison for StarsBonus
function checkStarsBonusTimestamp(dateString, maxDiff) {                                                        
    if (dateString.indexOf('.') > 0) { var dateArray =  dateString.split('.'); }
    if (dateString.indexOf('/') > 0) { var dateArray =  dateString.split('/'); }
    if (dateString.indexOf('-') > 0) { var dateArray =  dateString.split('-'); }
    var releaseDate = new Date((dateArray[2]),(dateArray[1]-1),(dateArray[0]),00,00,0);
    var actualDate = new Date();
    var timestampDiff = Date.parse(releaseDate) - Date.parse(actualDate);
    if(maxDiff >= timestampDiff && timestampDiff >= 0) {
        return true;
    }
}
function updateE3GameFinderForm(eid){  
  switch (eid) {
      case 'wii':
        $('nintendo_content').hide();
        $('ds_content').hide();
        $('wii_content').show();
        break;
    case 'ds':
        $('nintendo_content').hide();
        $('wii_content').hide();
        $('ds_content').show();
        break;
    case 'nintendo':
        $('wii_content').hide();
        $('ds_content').hide();
        $('nintendo_content').show();
        break;
      }
}
function checkUrl(){
    if (window.location.search != "") {
        var param = window.location.search;
        var count = param.indexOf("=");
        var value = param.substr(count+1);
    }
    switch (value) {
        case 'wii':
        $('nintendo_content').hide();
        $('ds_content').hide();
        $('wii_content').show();
        selectDropdownOption($('e3_games'),'wii');
        break;
    case 'ds':
        $('nintendo_content').hide();
        $('wii_content').hide();
        $('ds_content').show();
        selectDropdownOption($('e3_games'),'ds');
        break;
    default:
        $('wii_content').hide();
        $('ds_content').hide();     
        $('nintendo_content').show();   
        selectDropdownOption($('e3_games'),'nintendo');
        }
}
function selectDropdownOption(element,text)
{
    for (var i=0; i<element.options.length; i++) 
    {
        if (element.options[i].value == text) 
        {
            element.options[i].selected = true;        
            }
        else
        {
        element.options[i].selected = false;    
        }
    }
}

/* ********************************************************************************* */
/* ### DSi Interview Helper                                                              ### */
/* ********************************************************************************* */
var InterviewHelper = Class.create();
InterviewHelper.prototype = {
    initialize: function() {
        this.interviewContainer = $('interviewContent');
        this.interviewSubnav = $('interviewSubNav');
        this.activeCSSClassName = 'subMenuActive';
        this.pagingPrevious = $('prevPage');
        this.pagingNext = $('nextPage');
        this.activeNavItem = '';
        this.activeInterview = '';
        
        this._initalizeInterview()
        this._openTopicByURLParameter();
    },
    _initalizeInterview : function() {
        if(this.interviewSubnav.childElements().length != 0) {
            if($('interviewIntro') != undefined && $('interviewIntro').visible) { 
                $('interviewIntro').down().show();
            }
            this.activeNavItem = this.interviewSubnav.down(0);
            this.activeNavItem.className = this.activeCSSClassName;

            this.interviewContainer.select('.interview').each(function(item) {
              item.hide();
            });            

            this.activeInterview = this.interviewContainer.down(0);
            this.activeInterview.show();
            this._displayPagingNext(this.activeNavItem);

            // Display topic specific mood image if set
            var topicMood = this.activeInterview.firstDescendant().value;
            if(topicMood == "" || topicMood == undefined || this.activeInterview.firstDescendant().tagName != "INPUT") {    } 
            else { $('interviewMood').src = topicMood;}
        }
    },
    _displayPagingNext : function(activeItem) {
        if (activeItem.next() != null) { 
            this.pagingNext.down().innerHTML = activeItem.next().down().innerHTML;
            this.pagingNext.show();
        }
        else { this.pagingNext.hide(); }
    },
    _displayPagingPrevious : function(activeItem) {
        if (activeItem.previous() != null) {
            this.pagingPrevious.down().innerHTML = activeItem.previous().down().innerHTML;
            this.pagingPrevious.show(); 
        }
        else { 
            this.pagingPrevious.hide(); 
            if($('interviewIntro') != undefined ) { 
                $('interviewIntro').show();
            }
        }
    },

    _openTopicByURLParameter: function(){
        
        if (window.location.search != "") {
            var param = window.location.search;
            var count = param.indexOf('topic');
            
            if(count > 0) {
                var value = param.substr(count);
                topicId = parseInt(param.substr(param.indexOf("=")+1));
                
                if (topicId != undefined && topicId > 1 && topicId <= this.interviewSubnav.childElements().length) {
                    this.showInterview(this.activeNavItem.next(topicId-2).down(),this.activeInterview.next(topicId-2));                    
                }
            }
        }    
    },

    showInterview : function(navItem, interview, moodImg) {
        if($('interviewIntro') != undefined && $('interviewIntro').visible) { $('interviewIntro').hide();}
        
        this.activeNavItem.className = '';
        if(navItem.tagName == 'A') {
            this.activeNavItem = navItem.up(0);
        }
        else {
            this.activeNavItem = navItem;
        }
        this.activeNavItem.className = this.activeCSSClassName;
        
        this.activeInterview.hide();
        this.activeInterview = interview;
        this.activeInterview.show();
        
        this._displayPagingNext(this.activeNavItem);         
        this._displayPagingPrevious(this.activeNavItem);

        // Display topic specific mood image if set
        var topicMood = this.activeInterview.firstDescendant().value;
        if(topicMood == "" || topicMood == undefined || this.activeInterview.firstDescendant().tagName != "INPUT") {    } 
        else { $('interviewMood').src = topicMood;}    
    }                            
};
/* ********************************************************************************* */
/* ### Modal Layer Helper                                                        ### */
/* ********************************************************************************* */
MLHelper = {
  imageData: null,
  imagePos: 0,
  
  showVideo : function (strUrlVideo, strTitle, videoWidth, videoHeight, strUrlVideoXML, bgColor) {
    Dialog.info(
      {
        url: '/NOE/css/modal_layer.html', options: {method: 'get'}
      },{
        id: "unique",
        className: 'modal',
        title: strTitle,
        width: videoWidth,
        zIndex: 100,
        onShow : function () {
            MLHelper.playVideo('swfcontent', strUrlVideo, strUrlVideoXML, videoWidth, videoHeight, '', bgColor);
          if(!$('swfcontent')) {
            setTimeout("MLHelper.resizeModal(\"swfcontent\")", 2500);
          } else {
            MLHelper.resizeModal('swfcontent');
          }
          $('unique_close').observe('click', function() {
            Dialog.okCallback();
          });
        }
      }
    );
  },
  playVideo : function (id, flv,xml, w, h, playerskin, bgColor) {
    var videoWidth = w;
    var videoHeight = h;
    var swfVideoHeight = videoHeight + 30;
    var video_player = new SWFObject('/NOE/media/video_player.swf', id+flv, w, swfVideoHeight, "7", "#ffffff");
    video_player.addParam("quality", "high");
    video_player.addParam("wmode", "transparent");
    video_player.addVariable("libSwf", "/NOE/media/video_lib.swf");
    video_player.addVariable("langXml", "/NOE/media/video_lang.xml");
    video_player.addVariable("mediaPath", flv);
    video_player.addVariable("playerType", "basic");
    video_player.addVariable("thumbType", "hor");
    video_player.addVariable("playerWidth", videoWidth);
    video_player.addVariable("playerHeight", videoHeight);     
    video_player.addVariable("wa", "true");
    video_player.write(id); 
 },
 showLayer : function (url, width, minHeight) {
    Dialog.info({ url: url, options: {method: 'get'} },
      {
        id: "unique",
        className: 'wiifit',
        title: '',
        width: width,
        zIndex: 100,
        onShow : function () {
          $('unique').innerHTML.evalScripts();
          MLHelper.resizeModal('modal_dialog_message');
        }
     });
  },

showVideoEx : function (strUrlVideo, strTitle, videoWidth, videoHeight, strUrlVideoXML, bgColor,strPlayerSwf,strSubtitlesSMIL,strStylesXML,strVideoFLV, strAssets) {
    Dialog.info(
      {
        url: '/NOE/css/modal_layer.html', options: {method: 'get'}
      },{
        id: "unique",
        className: 'modal',
        title: strTitle,
        width: videoWidth,
        zIndex: 100,
        onShow : function () {
            MLHelper.playVideoEx('swfcontent', strUrlVideo, strUrlVideoXML, videoWidth, videoHeight, '', bgColor,strPlayerSwf, strSubtitlesSMIL,strStylesXML,strVideoFLV, strAssets);
          if(!$('swfcontent')) {
            setTimeout("MLHelper.resizeModal(\"swfcontent\")", 2500);
          } else {
            MLHelper.resizeModal('swfcontent');
          }
          $('unique_close').observe('click', function() {
            Dialog.okCallback();
          });
        }
      }
    );
  },
  playVideoEx : function (id, flv,xml, w, h, playerskin, bgColor,strPlayerSwf,strSubtitlesSMIL,strStylesXML,strVideoFLV, strAssets) {
    if(!strAssets) {
    strAssets = "/NOE/videos/interview_videos/assets/assets.swf";
    }
    var videoWidth = w;
    var videoHeight = h;
    var swfVideoHeight = videoHeight + 60;
    var video_player = new SWFObject(strPlayerSwf, id+flv, w, swfVideoHeight, "7", "#ffffff");
    video_player.addParam("quality", "high");
    video_player.addParam("wmode", "transparent");
    video_player.addParam("allowFullScreen", "true");
    video_player.addParam("scale", "showall");
    video_player.addVariable("libSwf", "/NOE/media/video_lib.swf");
    video_player.addVariable("langXml", "/NOE/media/video_lang.xml");
    video_player.addVariable("mediaPath", flv);
    video_player.addVariable("playerType", "basic");
    video_player.addVariable("thumbType", "hor");
    video_player.addVariable("playerWidth", videoWidth);
    video_player.addVariable("playerHeight", videoHeight);     
    video_player.addVariable("subtitlesSMIL", strSubtitlesSMIL);     
    video_player.addVariable("stylesXML", strStylesXML);
    video_player.addVariable("videoFile", strVideoFLV);
    video_player.addVariable("fontsFile", "/NOE/videos/interview_videos/assets/fonts.swf");
    video_player.addVariable("assetsFile", strAssets);
    video_player.addVariable("assetsFullscreenFile", "/NOE/videos/interview_videos/assets/fullscreen.swf");     
    video_player.addVariable("wa", "true");
    video_player.write(id); 
 },

showSWF : function (swf, strTitle, width, height) {    
    Dialog.info(
      {
        url: '/NOE/css/modal_layer.html', options: {method: 'get'}
      },{    
        id: "unique",
        className: 'modal',
        title: '',
        width: width,
        zIndex: 100,
        onShow : function () {
            MLHelper.playSWF('swfcontent', swf, width, height);
          if(!$('swfcontent')) {
            setTimeout("MLHelper.resizeModal(\"swfcontent\")", 2500);
          } else {
            MLHelper.resizeModal('swfcontent');
          }
          
          $('unique_close').observe('click', function() {
            Dialog.okCallback();
          });
        }
      }
    );
  },
    playSWF : function (id, swf, width, height) {
    
    var so = new SWFObject('"+url+"', 'tbObject', '"+TB_WIDTH+"', '"+TB_HEIGHT+"', '"+SWF_VERSION+"', '"+SWF_COLOR+"');
    var so = new SWFObject(swf, 'tbObject', width, height, 8, '#ffffff');
    so.addParam('wmode', 'transparent');
    so.addParam('scale', 'noscale');
    so.addParam('menu', 'true');
    so.write('swfcontent');
  },

  /**
   * imageData: array of img objects [{url: 'path/to/image.jpg', title: 'Picture 1', width: 609, height: 385}, {...}]
   * textPrevious, textNext: translated texts (String) for the buttons 
   */
  showImages: function (imageData, textPrevious, textNext) {
    this.textPrevious = textPrevious;
    this.textNext = textNext;
    
    this.imageData = imageData;
    // reset image position
    this.imagePos = 0;
    
    if(this.imageData && this.imageData.length > 0) {
      var img = this.imageData[0];
      this.showImage(img.url, img.title, img.width, img.height, true);
    }
  },
  
  getNavigationHtml: function() {
    // if one image, no navi needed
    if(!this.imageData || this.imageData.length < 2) {
      return '';
    }
    
    // fallback to english translations
    var strPrevious = this.textPrevious || 'previous';
    var strNext = this.textNext || 'next';
    
    var html = '<div class="imgnavigation clearfix">';
    if(this.imagePos > 0) {
      html += '<span class="previous" onclick="MLHelper.previousImage()">' + strPrevious + '</span>';
    }
    if(this.imagePos < this.imageData.length - 1) {
      html += '<span class="next" onclick="MLHelper.nextImage()">' + strNext + '</span>';
    }
    html += '</div>';
    return html;
  },
  
  nextImage: function() {
    this.imagePos++;
    // normalize wrong image pos
    if(this.imagePos > this.imageData.length - 1) {
      this.imagePos = this.imageData.length - 1;
    }
    
    var img = this.imageData[this.imagePos];
    
    var content = this.buildContentHtml(img.url, img.title, img.width, img.height, true);
    $('modal_dialog_message').update(content);
    $('unique_top').update(img.title);
  },
  
  previousImage: function() {
    this.imagePos--;
    // normalize wrong image pos
    if(this.imagePos < 0) {
      this.imagePos = 0;
    }
    
    var img = this.imageData[this.imagePos];
    
    var content = this.buildContentHtml(img.url, img.title, img.width, img.height, true);
    $('modal_dialog_message').update(content);
    $('unique_top').update(img.title);
  },
  
  buildContentHtml: function(url, title, width, height, withImageNavigation) {
    this.img = new Image()
    this.img.src = url;
    
    var content = '<div id="imgcontent"><img src="'+this.img.src+'" width="'+width+'" height="'+height+'" alt="' + title + '" title="' + title + '"  />';
    if(withImageNavigation) {
      content += this.getNavigationHtml();
    }
    content += '<\/div>';
    return content;
  },
  
  showImage : function (url, title, width, height, withImageNavigation) {
    if (url == "loading") {
      if (this.img.complete) {
       MLHelper.resizeModal('imgcontent');
      } else {
       window.setTimeout("MLHelper.showImage(\"loading\")", 100)
      }
      return;
    }
    
    var content = this.buildContentHtml(url, title, width, height, withImageNavigation);
    
    Dialog.info(content, {
      id: "unique",
      className: 'modal',
      title: title,
      width: width,
      zIndex: 100,
      recenterAuto: true,
      onShow : function() {
        MLHelper.showImage("loading");
        $('unique_close').observe('click', function() {
          Dialog.okCallback();
        });
      }
    });
  },
    resizeModal : function(innerId) {
     var dim      = $(innerId).getDimensions();
     var mainDim  = $('unique').getDimensions();
     var mainPos  = new Position.cumulativeOffset($('unique'));
     var newLeft = mainPos[0] - (dim.width - mainDim.width) * 0.5;
     var newTop  = mainPos[1] - (dim.height - mainDim.height) * 0.5;
     $('modal_dialog_message').setStyle({ width : dim.width + 'px', height : dim.height + 'px' } );
     $('unique_content').setStyle({ width : dim.width + 'px', height : dim.height + 'px' } );
     $('unique').setStyle({ width : dim.width + 'px', height : dim.height + 'px', left: newLeft + 'px', top: newTop + 'px' } );
     return;
   }
};
 
/* ********************************************************************************* */
/* ### ATG Layer Helper                                                          ### */
/* ********************************************************************************* */
AtgModal = {
    _strModalId: 'atg_modal',
    _container: null,
    _height: 0,
    _width: 0,
    init: function() {
        this._container = $(this._strModalId);
        // create a new container if not exisiting
        if(this._container == null) {
            var htmlContainer = new Element('div', { 'style': "z-index: 10000; position: absolute; top: 0;", 'id': this._strModalId });
            $('body_helper').insert({before: htmlContainer});
            this._container = htmlContainer;
        }
        
        var _this = this;
        // Attach resize events
        Event.observe(window, "scroll", function() {
            _this.center();
        });
        Event.observe(window, "resize", function() {
            _this.center();
        });
    },
    /**
     * Loads a flash into the modal layer
     */
    loadFlash: function(swfObject) {
        swfObject.write(this._strModalId);
        this.center();
    },
    
    /*
     * closes the layer
     */
    close: function() {
        if(this._container != null) {
            // display none and hide doen´t work! IE crash!
            this._container.setStyle({'visibility': 'hidden'});
        }
    },
    /**
     * reopen the modal layer
     */
    open: function() {
        if(this._container != null) {
            this._container.show();
        }
    },
    /**
     * centers the modal layer, takes notice of the current scroll values
     */
    center: function() {
        //alert(document.viewport.getScrollOffsets()['top']);
        var left = (document.viewport.getWidth() - this._container.getWidth() ) / 2 + document.viewport.getScrollOffsets()['left'];
        var top = (document.viewport.getHeight() - this._container.getHeight() ) / 2 + document.viewport.getScrollOffsets()['top'];
        this._container.setStyle({left: left + "px", top: top + "px"});
    }
};
/* ********************************************************************************* */
/* ### ATG Stage Helper                                                          ### */
/* ********************************************************************************* */
AtgStage = {
    _strModalId: 'atg_stage',
    _container: null,
    _height: 0,
    _width: 0,
    init: function() {
        this._container = $(this._strModalId);
        // create a new container if not exisiting
        if(this._container == null) {
            this._container = new Element('div', { 'id': this._strModalId, 'style': 'position: absolute; z-index: 10;' });
            $('stage').insert({before: this._container});
        }
    },
    
    /**
     * Loads a flash into the modal layer
     */
    loadFlash: function(swfObject) {
        swfObject.write(this._strModalId);
        $('topbar').setStyle({zIndex : 20}); 
    },
    
    /*
     * closes the layer
     */
    close: function() {
        if(this._container != null) {
            this._container.hide();
            $('topbar').setStyle({zIndex : 2}); 
        }
    },
    
    /**
     * reopen the modal layer
     */
    open: function() {
        if(this._container != null) {
            this._container.show();
            $('topbar').setStyle({zIndex : 20}); 
        }
    }
};
/* ********************************************************************************* */
/* ### Mouse Tracer                                                              ### */
/* ********************************************************************************* */
/**
 * One Stars Element, controlled by MouseTracer object
 */
var MouseTraceStar = Class.create();
MouseTraceStar.prototype = {
    /**
     * Constructor
     * 
     * @param options: an object with several parameters
     */
    initialize: function(options) {
        this.x = options.x; // mandatory
        this.y = options.y; // mandatory
        this.creationdate = new Date();
        this.speed = options.speed || 5;
        this.lifetime = options.lifetime || 5000; // milliseconds
        this.offsetX = options.offsetX || 0;
        this.offsetY = options.offsetY || 0;
        this.size = options.size || 25;
        this.container = new Element('img', { 'src': '/NOE/images/icons/yellow-star-trans.png', 'style': 'width: '+this.size+'px; height: '+this.size+'px; position: absolute; z-index: 9000; display: none' });
    },
    
    /**
     * Apply an effect, that let´s the container appear
     */
    appear: function() {
        new Effect.Appear(this.container);
    },
    
    /**
     * Get the html container
     */
    getContainer : function() {
        return this.container;
    },
    
    /**
     * Each element has an offset for a "wobble" effect.
     * This method creates a new random offset
     */
    randomizeOffset: function() {
        var randX = Math.floor(Math.random() * 4);
        var randY = Math.floor(Math.random() * 4);
        
        if(Math.floor(Math.random() * 2) == 1) {
            randX *= -1;
        }
        if(Math.floor(Math.random() * 2) == 1) {
            randY *= -1;
        }
        
        this.offsetX += randX;
        this.offsetY += randY;
    },
    
    /**
     * Set the x and y coordinate for the element
     */
    setXY: function(x,y) {
        this.speedX = !this.x ? 0 : x - this.x;
        this.speedY = !this.y ? 0 : y - this.y;
        this.x = x;
        this.y = y;
        this.updateContainer();
    },
    
    /**
     * Update he coordinates of the element
     */
    updateContainer: function() {
        this.container.setStyle({ left: (this.x) + "px", top: (this.y) + "px"});
    },
    
    /**
     * Check if lifetime of element is expired
     */
    isExpired: function() {
        var time = new Date().getTime();
        return time > this.creationdate.getTime() + this.lifetime;
    }
}
/**
 * Controller for Star-Elements, that follow the users mouse cursor
 */
MouseTracer = {
    position: {
        x: 0,
        y: 0
    },
    container: null,
    elements: null,
    maxHeight: 0,
    elementStdLifetime: 300,
    
    init: function() {
        this.container = new Element('div', { 'id': 'mouse-trace-container', 'style': '' });
        $('body_helper').insert({after: this.container});
        
        this.elements = new Array();
        for(var i = 0; i < 5; i++) {
            this.addElement(this.createRandomElement());
        }
        
        // set page borders (16x15 is the size of one star)
        this.maxWidth = $('body_helper').getWidth();
        this.maxHeight = $('body_helper').getHeight();
        
        var _this = this;
        
        this.interval = window.setInterval("MouseTracer.updateElements()", 30);
        
        Event.observe(document, "mousemove", function(e) {
            var x = Event.pointerX(e);
            var y = Event.pointerY(e);
            _this.setPosition(x, y);
        });    
    },
    
    createRandomElement: function() {
        var randomLifetime = (Math.round(Math.random() * 6000) + 500); // 500 - 6500
        var randomSize = (Math.round(Math.random() * 15) + 10); // 10-25
        var posX = (Math.floor(Math.random() * 1000) - 500);
        var posY = (Math.floor(Math.random() * 1000) - 500);
        
        return new MouseTraceStar({x: this.position.x + posX, y:this.position.y + posY, lifetime: randomLifetime, size: randomSize });
    },
    
    /**
     * Sets the current pointer position
     */
    setPosition: function(x,y) {
        this.position.x = x;
        this.position.y = y;
    },
    
    /**
     * Adds one element to the element list
     */
    addElement: function(element) {
        this.elements.push(element);
        this.container.insert(element.getContainer());
        element.appear();
    },
    
    /**
     * Update all elements // called by interval
     */
    updateElements: function() {
        for(var i=0; i < this.elements.length; i++) {
            var element = this.elements[i];
            
            if(element.isExpired()) {
                this.fallDown(i);
            }
            else {
                this.moveElement(i);
                element.randomizeOffset();
            }
        }
    },
    /**
     * Get the element on position i
     */
    getElement: function(i) {
        return this.elements[i];
    },
    
    /**
     * Add an element und remove the element on position i
     */
    setElement: function(i, element) {
        this.elements.splice(i, 1);
        this.addElement(element);
    },
    
    /**
     * Normal movement (when not expired)
     */
    moveElement: function(i) {
        var element = this.getElement(i);
        var newX = this.position.x + element.offsetX;
        var newY = this.position.y + element.offsetY;
        var distX = newX - element.x; 
        var distY = newY - element.y;
        var x = element.x + distX / element.speed;
        var y = element.y + distY / element.speed;
        element.setXY(x, y);
    },
    
    /**
     * Falling down movement (when expired)
     */
    fallDown: function(i) {
        var element = this.getElement(i);
        var maxHeight = this.maxHeight - element.size;
        var maxWidth = this.maxWidth - element.size;
        
        var x = element.x + element.speedX;
        element.speedY += 2;
        var y = element.y + element.speedY;
        if(x > maxWidth) {
            x = maxWidth;
        }
        if(y > maxHeight) {
            y = maxHeight;
            // if element is on ground, remove it from Elementlist and add a new element
            this.setElement(i, this.createRandomElement());
        }
        element.setXY(x, y);
    }
};
/**
 * Little Helper for shaking the page
 */
ScreenShaker = {
    interval: null,
    framerate: 30, //milliseconds
    
    /**
     * Start shaking
     */
    start: function() {
        this.interval = window.setInterval("ScreenShaker.shake()", this.framerate);    
    },
    
    /**
     * Stop shaking
     */
    stop: function() {
        window.clearInterval(this.interval);
        this.setOffsets(0,0);
    },    
    
    /**
     * Shakes the page // called via interval
     */
    shake: function() {
        var range = 30;
        var offsetX = Math.round(Math.random() * range);
        var offsetY = Math.round(Math.random() * range);
        this.setOffsets(offsetX, offsetY);
    },
    
    /**
     * Set the page offsets
     */
    setOffsets: function(offsetX, offsetY) {
        $('page_margins').setStyle({"paddingLeft": offsetX + "px"});
        $('page_margins').setStyle({"paddingTop": offsetY + "px"});        
    }
};
/* ********************************************************************************* */
/* ### Mouse Tracer                                                              ### */
/* ********************************************************************************* */
/**
 * One Stars Element, controlled by MouseTracer object
 */
var MouseTraceStar = Class.create();
MouseTraceStar.prototype = {
    /**
     * Constructor
     * 
     * @param options: an object with several parameters
     */
    initialize: function(options) {
        var _this = this;
        this.x = options.x; // mandatory
        this.y = options.y; // mandatory
        this.creationdate = new Date();
        this.speed = options.speed || 5;
        this.lifetime = options.lifetime || 5000; // milliseconds
        this.downtime = options.downtime || 10000; // how long star lays on the ground
        this.size = options.size || 25;
        this.direction = Math.floor(Math.random() * 2) == 1 ? 1 : -1; // 1 = clockwise
        this.offsetX = options.offsetX || this.size / 2;
        this.offsetY = options.offsetY || this.size / 2;
        this.container = new Element('img', { 'src': '/NOE/images/icons/yellow-star-trans.png', 'style': 'width: '+this.size+'px; height: '+this.size+'px; position: absolute; z-index:9000; display: none' });
    },
    
    /**
     * Apply an effect, that let´s the container appear
     */
    appear: function() {
//        new Effect.Appear(this.container);
        this.container.show();
    },
    
    disappear: function() {
        var _this = this;
//        Effect.Fade(this.getContainer(), {afterFinish: function() {
//            _this.getContainer().remove();
//            delete _this;
//        }});
        _this.getContainer().remove();
        delete _this;
    },
    
    /**
     * Get the html container
     */
    getContainer : function() {
        return this.container;
    },
    
    /**
     * Each element has an offset for a "wobble" effect.
     * This method creates a new random offset
     */
    randomizeOffset: function() {
        var randX = Math.floor(Math.random() * 4) + 1;
        var randY = Math.floor(Math.random() * 4) + 1;
        
        var border = 5;
        
        // Check, witch quartal we are in. 
        // the quartals around mouse pointer are:
        // 4 | 1
        // -----
        // 3 | 2
        
        // quartal 1
        if(this.offsetX >= 0 && this.offsetY < 0) {
            this.offsetX += randX * this.direction;
            this.offsetY += randY * this.direction;
            if(this.offsetX - border  <= 0 && 
               this.offsetY + border + this.size >= 0) {
                this.offsetX = border;
                this.offsetY = this.size * -1 - border;
            }
        }
        // quartal 2
        else if(this.offsetX > 0 && this.offsetY >= 0) {
            this.offsetX -= randX * this.direction;
            this.offsetY += randY * this.direction;
            if(this.offsetX - border <= 0 && 
               this.offsetY - border <= 0) {
                this.offsetX = border;
                this.offsetY = border;
            }
        }
        // quartal 3
        else if(this.offsetX <= 0 && this.offsetY > 0) {
            this.offsetX -= randX * this.direction;
            this.offsetY -= randY * this.direction;
            if(this.offsetX + border + this.size >= 0 && 
               this.offsetY - border <= 0) {
                this.offsetX = this.size * -1 - border;
                this.offsetY = border;
            }
        }
        // quartal 4
        else {
            this.offsetX += randX * this.direction;
            this.offsetY -= randY * this.direction;
            // check collision with mouse cursor:
            if(this.offsetX + border + this.size >= 0 && 
               this.offsetY + border + this.size >= 0) {
                this.offsetX = this.size * -1 - border;
                this.offsetY = this.size * -1 - border;
            }
        }
    },
    
    /**
     * Set the x and y coordinate for the element
     */
    setXY: function(x,y) {
        this.speedX = !this.x ? 0 : x - this.x;
        this.speedY = !this.y ? 0 : y - this.y;
        this.x = x;
        this.y = y;
        this.updateContainer();
    },
    
    /**
     * Update he coordinates of the element
     */
    updateContainer: function() {
        this.container.setStyle({ left: (this.x) + "px", top: (this.y) + "px"});
    },
    
    /**
     * Check if lifetime (time that star follows mouse) of element is expired
     */
    isExpired: function() {
        var time = new Date().getTime();
        return time > this.creationdate.getTime() + this.lifetime;
    },
    
    /**
     * Set the lifetime to zero, so that the element is expired
     */
    setExpired: function() {
        this.lifetime = 0;
    },
    
    /**
     * Check if star has to dissappear
     */
    isDead: function() {
        var time = new Date().getTime();
        return time > this.creationdate.getTime() + this.lifetime + this.downtime;
    }
}
/**
 * Controller for Star-Elements, that follow the users mouse cursor
 */
MouseTracer = {
    position: {
        x: 0,
        y: 0
    },
    lastPositions: null,
    container: null,
    elements: null,
    fallenElements: null,
    elementStdLifetime: 300,
    maxElements: 6,
    initialized: false,
    
    init: function() {
        this.container = new Element('div', { 'id': 'mouse-trace-container', 'style': '' });
        $('body_helper').insert({after: this.container});
        
        this.elements = new Array();
        this.fallenElements = new Array();
        
        this.lastPositions = new Array();
        this.lastShakeTime = new Date();
        
        var _this = this;
        
        this.interval = window.setInterval("MouseTracer.updateElements()", 30);
        
        Event.observe(document, "mousemove", function(e) {
            var x = Event.pointerX(e);
            var y = Event.pointerY(e);
            _this.setPosition(x, y);
            if(_this.isShaked()) {
                _this.toggleTracing();
            }
        });    
        
//        Event.observe(window, "resize", function(e) {
//            _this.initBorders();
//        })
        
        this.initialized = true;
        this.startTracing();
    },
    
    updateBorders: function() {
        // the borders of the page
        var width = $('body_helper').getWidth();
        var height = $('body_helper').getHeight();
        
        // check if the height differs from old, and delete elements if so!
        if(this.maxHeight != height || this.maxWidth != width) {
            this.cleanElements();
        }
        
        this.maxWidth = width;
        this.maxHeight = height;
        
        this.footerLeft = $('footer').cumulativeOffset()[0];
        this.footerTop = $('footer').cumulativeOffset()[1];
        this.footerWidth = $('footer').getWidth();
        this.footerHeight = $('footer').getHeight();
    },
    
    toggleTracing: function() {
        if(this.isStopped) {
            this.startTracing();
        }
        else {
            this.stopTracing();
        }
    },
    
    /**
     * Stop the tracing and expire all active stars
     */
    stopTracing: function() {
        for(var i=0; i < this.elements.length; i++) {
            var element = this.elements[i];
            element.setExpired();
        }
        this.isStopped = true;
    },
    
    /**
     * Start the tracing and add new random stars
     */
    startTracing: function() {
        this.isStopped = false;
        
        // init the starsrain with 5 stars
        for(var i = 0; i < this.maxElements; i++) {
            this.addElement(this.createRandomElement());
        }
    },
    
    /**
     * Creates a random Element with random coordinates and size
     */
    createRandomElement: function() {
        var randomLifetime = (Math.round(Math.random() * 6000) + 500); // 500 - 6500
        var randomSize = (Math.round(Math.random() * 15) + 10); // 10-25
        var posX = (Math.round(Math.random() * 400) + 100);
        var posY = (Math.round(Math.random() * 400) + 100);
        var offsetX = (Math.round(Math.random() * 5) + randomSize);
        var offsetY = (Math.round(Math.random() * 5) + randomSize);
        
        if(Math.floor(Math.random() * 2) == 1) {
            posX *= -1;
            offsetX *= -1;
        };
        if(Math.floor(Math.random() * 2) == 1) {
            posY *= -1;
            offsetY *= -1;
        };
        
        return new MouseTraceStar({x: this.position.x + posX, y:this.position.y + posY, lifetime: randomLifetime, size: randomSize, offsetX: offsetX, offsetY: offsetY });
    },
    
    /**
     * Sets the current pointer position
     */
    setPosition: function(x,y) {
        this.position.x = x;
        this.position.y = y;
        
        if(this.lastPositions.length > 2) {
            // remove the first element from array
            this.lastPositions.splice(0,1);
        }
        this.lastPositions.push({x:x, y:y});
    },
    
    /**
     * Checks, if the cursor has been "shaked"
     */
    isShaked: function() {
        // time, in which the mouse has to be shaked
        var shakeTime = 1000;
        if(this.lastPositions.length == 3) {
            var p = this.lastPositions;
            if(p[0].x > p[1].x && p[1].x < p[2].x ||
               p[0].x < p[1].x && p[1].x > p[2].x) {
                
                var time = new Date().getTime();
                // is shaketime expired?
                if(time > this.lastShakeTime.getTime() + shakeTime) {
                    // reset
                    this.lastShakeTime = new Date();                
                    this.countShakes = 0;
                }
                else {
                    this.countShakes++;
                }
                
                if(this.countShakes == 3) {
                    this.countShakes = 0;
                    return true;
                }
            }
        }
        
        return false;
    },
    
    /**
     * Adds one element to the element list
     */
    addElement: function(element) {
        if(!this.isStopped) {
            this.elements.push(element);
            this.container.insert(element.getContainer());
            element.appear();
        }
    },
    
    /**
     * Update all elements // called by interval
     */
    updateElements: function() {
        this.updateBorders();
        for(var i=0; i < this.elements.length; i++) {
            var element = this.elements[i];
            
            if(element.isExpired()) {
                this.fallDown(i);
            }
            else {
                this.moveElement(i);
                element.randomizeOffset();
            }
        }
        for(var i=0; i < this.fallenElements.length; i++) {
            var element = this.fallenElements[i];
            
            if(element.isDead()) {
                this.cleanElement(i);
            }
        }
    },
    /**
     * Get the element on position i
     */
    getElement: function(i) {
        return this.elements[i];
    },
    
    /**
     * Get the fallen element on position i
     */
    getFallenElement: function(i) {
        return this.fallenElements[i];
    },
    
    /**
     * Add an element und remove the element on position i
     */
    setElement: function(i, element) {
        this.elements.splice(i, 1);
        this.addElement(element);
    },
    
    /**
     * Normal movement (when not expired)
     */
    moveElement: function(i) {
        var element = this.getElement(i);
        var newX = this.position.x + element.offsetX;
        var newY = this.position.y + element.offsetY;
        var distX = newX - element.x; 
        var distY = newY - element.y;
        var x = element.x + distX / element.speed;
        var y = element.y + distY / element.speed;
        
        var maxHeight = this.maxHeight - element.size;
        var maxWidth = this.maxWidth - element.size;
        
        if(x > maxWidth) x = maxWidth;
        if(x < 0) x = 0;
        if(y > maxHeight) y = maxHeight;
        if(y < 0) y = 0;
        
        element.setXY(x, y);
    },
    
    /**
     * Falling down movement (when expired)
     */
    fallDown: function(i) {
        var element = this.getElement(i);
        var maxHeight = this.maxHeight - element.size;
        var maxWidth = this.maxWidth - element.size;
        var footerTop = this.footerTop - element.size;
        var footerBottom = this.footerTop + this.footerHeight;
        var footerLeft = this.footerLeft - element.size;
        var footerRight = this.footerLeft + this.footerWidth;
        
        var x = element.x + element.speedX;
        element.speedY += 2;
        var y = element.y + element.speedY;
        if(x > maxWidth) x = maxWidth;
        if(x < 0) x = 0;
        
        var isFallen = false;
        if(y > footerTop && this.position.y < footerTop && x > footerLeft && x < footerRight) {
            y = footerTop;
            isFallen = true;
        }
        else if(y > maxHeight) {
            y = maxHeight;
            isFallen = true;
        }
        if(isFallen) {
            var oldElement = this.elements[i];
            // push old element onto the fallen elements array
            this.fallenElements.push(oldElement);
            // if element is on ground, remove it from Elementlist and add a new element
            this.elements.splice(i, 1);
            if(this.elements.length < this.maxElements) {
                this.addElement(this.createRandomElement());
            }
        }
        element.setXY(x, y);
    },
    
    cleanElements: function() {
        var l = this.fallenElements.length;
        for(var i=0; i < l; i++) {
            var element = this.getFallenElement(i);
            element.disappear();
        }
        this.fallenElements = new Array();
    },
    
    /**
     * Removes a whole element from the page
     */
    cleanElement: function(i) {
        var element = this.getFallenElement(i);
        // remove from array
        this.fallenElements.splice(i, 1);
        element.disappear();
    }
};
Event.observe(window, 'load', function() {
    if($('ac_animation')) {
        var loginButton = $$('#login_wrapper img')[0];
        Event.observe(loginButton, 'click', function() {
            $('ac_animation').hide();
        });
    }
});

/* Start of functions for Software and Hardware Registration Process */
// Update Age and Gender fields in 'q2' survey
function updateAgeGender() {
    var q2_length = document.getElementById('q2').getElementsByClassName("row").length;
    for (i = 1; i <= q2_length; i++) {
        var ageGet = "q2_" + i + "_age";
        var ageSet = "q2b_age_" + i;
        var genderGet = "q2_" + i + "_gender";
        var genderSet = "q2b_gender_" + i;
        showAge(ageSet,document.getElementById(ageGet).value);
        showGender(genderGet,genderSet,document.getElementById(genderGet).value)
    }
}
// Displays user age in question about which user has highest priority
function showAge(age_id,value) {
    var age = "&nbsp;";
    if (value > 2 && (parseFloat(value) == parseInt(value)) && !isNaN(parseInt(value))) {
        age = value;
    }
    document.getElementById(age_id).innerHTML = age;
}
// Displays user gender in question about which user has highest priority
function showGender(form_id,gender_id,value) {
    var gender = "&nbsp;";
    if (value > 0) {
        var selected = document.getElementById(form_id)[document.getElementById(form_id).selectedIndex].innerHTML;
        gender = selected;
    }
    document.getElementById(gender_id).innerHTML = gender;
}

// Array of possible options for 'q8new' survey
var q8new_items = new Array("q8new_1","q8new_2","q8new_3","q8new_4","q8new_5","q8new_6","q8new_7","q8new_8","q8new_10");
var q8new_items_length = q8new_items.length;
// Disable/enable all systems in 'q8new' survey
function setSystems(value) {
    for (i = 0; i < q8new_items_length; i++) {
        var system_item = document.getElementById(q8new_items[i]);
        if (system_item) {
            system_item.disabled=value;
            system_item.checked=false;
        }
    }
}
// React to "No Systems" checkbox being clicked in 'q8new' survey
function toggleSystems() {
    var no_systems_value = document.getElementById('q8new_9').checked;
    setSystems(no_systems_value);
}

// Limits text area to length defined in function call
function limitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    }
}

// Shows+Activates and Hides+Deactivates Multiple Questions and Answers
function showQuest(){
    if($('q5_1').getValue() == 1){
        $('qshow').show();
    }
    else if($('q5_2').getValue() == 2){
        $('qshow').hide();
        
        var q6answers = $('q6').select('.radio');
        var q7answers = $('q7').select('.radio');
        var q8answers = $('q8new').select('.checkbox');
        
        q6answers.each(function(item){item.setValue(false);});
        q7answers.each(function(item){item.setValue(false);});
        q8answers.each(function(item){item.setValue(false);item.enable();});    
    }        
}
/* End of functions for Software and Hardware Registration Process */

/* Start of Function for Recent Games page */

var RecentDateString;
function getRecentDate () {
    Now = new Date();
    Minus = 6;
    Day = "01";
    Month = Now.getMonth() + 1;
    Year = Now.getYear();
    if ((Year > 99) && (Year < 1900)) Year += 1900;
    Month -= Minus;
    if (Month <= 0){Month += 12; Year -= 1}
    RecentDateString= "" + Day;
    RecentDateString+= ((Month<10) ? ".0" : ".") + Month;
    RecentDateString+= "." + Year;
    $('dateFrom').setValue(RecentDateString);
}
/* End of Function for Recent Games page */
