﻿this.menu = {
  levelIds: [],
  delay: 0.2,
  search_form_action: '',
  search_form_method: '',
  search_form_text: '',
  show_search_form: '',
  afterLoad: null,
  search_form: null,

  showMenu: function (el, over) {
    el = $(el);
    var active = el.up().down('.nav-current');    
    var activeSubitem = false;
    if (active) {
      activeSubitem = active.down('ol') || active.down('ul');
    }

    if (over) {
      var another = el.next('.nav-over') || el.previous('.nav-over');
      if (another && another.hider != el) {
        if (another.hideTimeout) window.clearTimeout(another.hideTimeout);
        if (another.displayTimeout) window.clearTimeout(another.displayTimeout);
        another.fixed = false;
        another.hider = el;
        another.hideTimeout = Element.removeClassName.delay(this.delay, another, 'nav-over');
      }
      if (active) {
        if (active != el) {
          if (active.showTimeout) window.clearTimeout(active.showTimeout);
          if (active.timeout) window.clearTimeout(active.timeout);
          //active.timeout = Element.hide.delay(this.delay, activeSubitem);
          active.deactivator = el;
        } else {
          if (active.showTimeout) window.clearTimeout(active.showTimeout);
          if (active.timeout) window.clearTimeout(active.timeout);
          //active.showTimeout = Element.show.delay(this.delay, activeSubitem);
        }
      }
      if (el.displayTimeout) window.clearTimeout(el.displayTimeout);
      if (el.hideTimeout) window.clearTimeout(el.hideTimeout);
      el.displayTimeout = Element.addClassName.delay(this.delay, el, 'nav-over');
    } else {
      if (!el.fixed) {
        if (el.displayTimeout) window.clearTimeout(el.displayTimeout);
        if (el.hideTimeout) window.clearTimeout(el.hideTimeout);
        if (active && active.deactivator === el && active.timeout) window.clearTimeout(active.timeout);
        el.hider = false;
        el.hideTimeout = Element.removeClassName.delay(this.delay, el, 'nav-over');
      }
      if (active && active != el) {
        if (active.showTimeout) window.clearTimeout(active.showTimeout);
        if (active.timeout) window.clearTimeout(active.timeout);
        //active.showTimeout = Element.show.delay(this.delay, activeSubitem);
      }
    }
  },

  menuHeight: function () {
    IE6 = /msie|MSIE 6/.test(navigator.userAgent);
    function equalHeight(theClass) {
      var items = $$(theClass);
      var max_height = items.invoke('getHeight').max();
      var nav_padding = 14;
      var inverted = $('genres');
      var inverted_height = 0;
      if (inverted && inverted.className.match('nav-current')) {
        inverted_height = inverted.down('ul').offsetHeight + 20;
      }
      if (inverted_height > max_height) {
        max_height = inverted_height;
      } else {
        max_height = max_height - nav_padding + 5;
      }
      if (IE6) {
        items.invoke('setStyle', {
          height: (max_height) + 'px'
        })
      } else {
        items.invoke('setStyle', {
          height: 'auto'
        });
        items.invoke('setStyle', {
          minHeight: (max_height) + 'px'
        });
      }
      if($$('.navigation-container')[0]){
        var nav_height = Element.getHeight($$('.navigation')[0]);
        var total_height = nav_height + max_height + nav_padding;
        $$('.navigation-container')[0].setStyle({
          'height':total_height+'px'
        })
      }
    }
    equalHeight('.navigation ol');
  },

  cleanWhitespace: function (node) {
    var notWhitespace = /\S/;
    for (var x = 0; x < node.childNodes.length; x++) {
      var childNode = node.childNodes[x]
      if ((childNode.nodeType == 3)&&(!notWhitespace.test(childNode.nodeValue))) {
        // that is, if it's a whitespace text node
        node.removeChild(node.childNodes[x])
        x--
      }
      if (childNode.nodeType == 1) {
        // elements can have text child nodes of their own
        this.cleanWhitespace(childNode)
      }
    }
  },

  onGetXml: function(transport){
    this.cleanWhitespace(transport.responseXML.documentElement);
    this.generateMenu(transport.responseXML.documentElement)
    this.menuHeight();
    this.afterLoad();
  },

  getMenuXml: function () {
		new Ajax.Request('/static/djuice/menu.xml',
    {
      method:'get',
      onSuccess: this.onGetXml.bind(this),
      onFailure: function(){
        alert('Error in xml')
      }
    });

  },

  onLoad: function () {
    this.getMenuXml();
  },

  level1: function (el, prefix) {
    var list = new Element('ul', {
      'class': 'navigation-ul'
    })
    var item = 0;
    for(var i=0; i<el.childNodes.length; i++) {
      if(!this.restricted(el.childNodes[i])){
        item = this.level1item(el.childNodes[i], prefix);
        list.insert(item);
      }
    }
    if (item) item.addClassName('last');

    return list;
  },

  explode: function(str){
    arr = str.split(',');
    for(var i=0; i<arr.length; i++){
      arr[i] = arr[i].replace(/(^\s+)|(\s+$)/g, "");
    }
    return arr;
  },

  restricted: function(el){
    if(this.restrictions.length == 0)return false;
    
    var restrictions = el.attributes.getNamedItem('restrictions') != null && el.attributes.getNamedItem('restrictions').value;
    if(restrictions){
      restrictions = this.explode(restrictions);
      for(var i=0; i<this.restrictions.length; i++) {
        if(restrictions.indexOf(this.restrictions[i])!=-1) {
          return true;
        }
      }
    }
    return false;
  },

  level1item: function (el, prefix) {
    var title = el.attributes.getNamedItem('title') != null && el.attributes.getNamedItem('title').value;
    var id = el.attributes.getNamedItem('id') != null && el.attributes.getNamedItem('id').value;
    var href = el.attributes.getNamedItem('href') != null && el.attributes.getNamedItem('href').value;
    
		href = fl(href);
    if(!title)title='Empty';

    var htmlId = prefix + '-' + id;
    var options = {
      'class': 'nav-top-level'
    }
    var nav_parent = (el.childNodes.length > 0) ? ' nav-parent' : '';
    var item = new Element('li', options)
    .insert(
      new Element('div', {
        'class':'nav-theme-'+id
      })
      .insert(
        new Element('a', {
          'href': href ? href : '#',
          'id': htmlId,
          'class':'nav-level-1' + nav_parent
        })
        .update(title)
        )
      .insert(this.level2(el, htmlId)))
    item.observe('mouseover', function (evt) {
      var element = Event.findElement(evt, 'LI');
      menu.showMenu(element, 1);
    });
    item.observe('mouseout', function(evt) {
      var element = Event.findElement(evt, 'LI');
      var relatedTarget = evt.relatedTarget || evt.toElement;
      if (relatedTarget && $(relatedTarget).ancestors().indexOf(element) === -1) {
        menu.showMenu(element, 0);
      }
    });

    if(this.levelIds[0] == id) {
      item.addClassName('nav-active');
      this.search_form_action = el.attributes.getNamedItem('form_action') != null && el.attributes.getNamedItem('form_action').value;
      this.search_form_method = el.attributes.getNamedItem('form_method') != null && el.attributes.getNamedItem('form_method').value;
      this.search_form_text = el.attributes.getNamedItem('form_text') != null && el.attributes.getNamedItem('form_text').value;
      this.show_search_form = el.attributes.getNamedItem('show_search_form') != null && el.attributes.getNamedItem('show_search_form').value;
    }
    return item;
  },

  level2: function (el, htmlId) {
    var leftArr = [];
    var rightArr = [];
    for(var i=0; i<el.childNodes.length; i++) {
      var is_left = el.childNodes[i].attributes.getNamedItem('is_left') != null && el.childNodes[i].attributes.getNamedItem('is_left').value;
      if (is_left) {
        leftArr.push(el.childNodes[i]);
      } else {
        rightArr.push(el.childNodes[i]);
      }
    }

    var listLeft = new Element('ul');
    var listRight = new Element('ul');

    var itemL = null;
    for(i=0; i<leftArr.length; i++) {
      if(!this.restricted(leftArr[i])){
        itemL = this.level2item(leftArr[i], htmlId);
        listLeft.insert(itemL);
      }
    }
    if (itemL) itemL.addClassName('last');

    var itemR = null;
    for(i=0; i<rightArr.length; i++) {
      if(!this.restricted(rightArr[i])){
        itemR = this.level2item(rightArr[i], htmlId);
        listRight.insert(itemR);
      }
    }
    if (itemR) itemR.addClassName('last');

    var list = new Element('ol')

    if(leftArr.length == 0 || rightArr.length == 0) {
      var selectedList = leftArr.length == 0 ? listRight : listLeft;
      list.insert(
        new Element('li', {
          'class':'nav-l2'
        })
        .insert(selectedList))
    } else {
      if(leftArr.length > 0) {
        list.insert(
          new Element('li', {
            'class':'nav-l2-left'
          })
          .insert(listLeft))
      }

      if(rightArr.length > 0) {
        list.insert(
          new Element('li', {
            'class':'nav-l2-right'
          })
          .insert(listRight))
      }
    }
    return list;
  },

  level2item: function (el, htmlId) {
    var is_genre_list = el.attributes.getNamedItem('is_genre_list') != null && el.attributes.getNamedItem('is_genre_list').value == '1';
    var title = el.attributes.getNamedItem('title') != null && el.attributes.getNamedItem('title').value;
    var id = el.attributes.getNamedItem('id') != null && el.attributes.getNamedItem('id').value;
    var href = el.attributes.getNamedItem('href') != null && el.attributes.getNamedItem('href').value;
		href = fl(href);
    if(!title)title='Empty';
  
    htmlId = htmlId + '-' + id;
    var options = {
      'id': htmlId
    }
    var nav_parent = (el.childNodes.length > 0) ? ' nav-parent' : '';
    if(is_genre_list) {
      options.id = "genres";
      options['class'] = "inverted";
    }
  
    var item = new Element('li', options)
    .insert(new Element('a', {
      'href': href ? href : '#',
      'class': nav_parent
    }).update(title));



    if(el.childNodes.length > 0) {
      item.insert(this.level3(el, htmlId))
    }
  
    if(this.levelIds[1] == id) item.addClassName('nav-current');
    return item;
  },

  level3: function (el, htmlId){
    var list = new Element('ul');

    var item =  null;

    for(var i=0; i<el.childNodes.length; i++) {
      if(!this.restricted(el.childNodes[i])){
        item = this.level3item(el.childNodes[i], htmlId);
        list.insert(item)
      }
    }
    if (item) item.addClassName('last');

    return list;
  },

  level3item: function (el, htmlId) {
    var id = el.attributes.getNamedItem('id') != null && el.attributes.getNamedItem('id').value;
    var href = el.attributes.getNamedItem('href') != null && el.attributes.getNamedItem('href').value;
    var title = el.attributes.getNamedItem('title') != null && el.attributes.getNamedItem('title').value;
		href = fl(href);
    if(!title)title='Empty';

    var a = new Element('a', {
      'href': href ? href : '#'
    }).update(title);
    if(this.levelIds[2] == id) a.addClassName('current');

    var item = new Element('li', {
      'id': htmlId + '-' + id
    })
    .insert(a)
    return item;
  },

  generateMenu: function (el) {
    if(current.restrictions==undefined)current.restrictions='';
    this.restrictions = this.explode(current.restrictions);

    // select menu with specified language
    var menus = el.getElementsByTagName('menu');
    var menu = null;
    var prefix = current.prefix;
    for(var a=0; a< menus.length; a++) {
      menu = menus[a];
      if(menu.attributes.getNamedItem('lang').value==current.language) break;
    }
    if(!menu){
      alert('language not found');
      return;
    }

    this.levelIds = current.id.split('-');

    var menuParts = new Element('div', {
      'class': 'navigation',
      'id': 'navigation'
    })
    .insert(this.level1(menu, prefix));

    var searchinput = new Element('input', {
      'class': 'input-text',
      'value': this.search_form_text,
      'name': 'serchstr'
    });

    searchinput.onclick = function(){if (searchinput.value==window.menu.search_form_text) {searchinput.value=''}};
    searchinput.onblur = function(){if(searchinput.value==''){searchinput.value=window.menu.search_form_text}}

    this.btn_search = new Element('button', {
        'class': 'button',
        'type': 'submit'
      });
    this.search_form =
    new Element('form', {
      'action': this.search_form_action,
      'method': this.search_form_method
    })
    .insert(new Element('div', {
      'class': 'form-search nav-theme-'+this.levelIds[0]
    })
    .insert(searchinput)
    .insert(this.btn_search
      .insert(new Element('span').update(this.search_form_text))));

    if(this.show_search_form) menuParts.insert(this.search_form);

    // render menu
    $('my-menu').insert(
      new Element('div', {
        'class': 'navigation-container'
      })
      .insert(menuParts)
      )
  }
}

//document.observe("dom:loaded", menu.onLoad.bindAsEventListener(menu));


// Р­С‚Р° С„СѓРЅРєС†РёСЏ РІС‹Р·С‹РІР°РµС‚СЃСЏ РїРѕ РѕРєРѕРЅС‡Р°РЅРёСЋ СЂРµРЅРґРµСЂРёРЅРіР° РјРµРЅСЋ
menu.afterLoad = function(){
  menu.search_form.onsubmit = function(){
    var search_value = menu.search_form.down('input').value;
    var url = "http://funs.djuice.ua/forum.asp?keyw="+search_value+"&cmd=topic_list&i_page=1";
    location.href = url;
    return false;
  }
}

function fl(s) {
	if (s.toString().indexOf('funs.djuice') < 1 && s.toString().indexOf('javascript')==-1)
		return 'http://login.djuice.com.ua/fcgi/d_redir.pl?forur=' + s;
	else
		return s;
}
