$(document).ready(function() {

  if ($('#player').length > 0)
    flowplayer("player", "/data/lib/flowplayer-3.1.5.swf",{clip:{scaling: 'fit'}}); 
  
  var menu = new Menu('.HP_menu .menu');
  
  menu.li.find('a.root').each(function() {
    if(this.getAttribute('title') == 'Referenzen') {
      $(this).addClass('ref');
      $(this.parentNode).addClass('ref');
    }
  });
  
  var content = $('#content');
  var tabset = content.find('*[class*=tab-set]');
  
  if(tabset.length > 0) {
    
    var ul = document.createElement('ul');
    
    tabset.each(function() {
      
      var li  = document.createElement('li');
      var a = document.createElement('a');
      var jq_a  =  $(a);
      var title = this.title;
      
      ul.appendChild(li);
      li.appendChild(a);
      
      a.content_object = this;
      a.title = this.title;
      //a.href  = this.title == 'Kontakt' ? "/de/kontakt" : "javascript:void(null);";
      a.href  = 'javascript:void(null);';
      a.appendChild(document.createTextNode(this.title));
      
      /*$(this).find('form').each(function() {
        this.action = this.action + '#' + title;
      });*/
      
      //if(this.title != 'Kontakt') {
        
        //this.title = '';
        
        jq_a.click(function() {
          
          var jq_content_object = $(this.content_object);
          var jq_parent = $(this.parentNode);
          
          jq_content_object.siblings().hide();
          jq_content_object.show();
          
          jq_parent.siblings().removeClass('active-tab');
          jq_parent.addClass('active-tab');
          
        });
      //}
      
    });
    
    $('.slogan .tabset').append(ul);
    
    if(ul.childNodes.length != 0) {
      
      //var elm = null;
      
      //if(document.location.hash)
        //elm = $(ul).find('a[title*=' + document.location.hash.substr(1) + ']');
      
      //if(elm == null || elm.length == 0)
        //elm = $(ul.childNodes[0].firstChild);
      
      $(ul.childNodes[0].firstChild).click();
      
    }
    
  }
  
  addFormEvent($('.tab-set[title=Kontakt]'));
  addFormEvent2($('.response .HP_emaildirect'));
  
  
  content.find('div[class*=swo-hp-object:]').each(function() {
    
    var div = $(this);
    var classArray = this.className.split(' ');
    var hpObjectArray = null;
    
    for(i in classArray) {
      
      hpObjectArray = classArray[i].split(':');
      
      if(hpObjectArray.length == 2) {
        
        $.get('./choice=' + hpObjectArray[1], null, function(data) {
          
          data = $(data);
          div.html(data);
          
          if(hpObjectArray[1] == 'HP_emaildirect')
            data.each(function() {
              if(this.nodeName.toLowerCase() == 'form')
                this.setAttribute('action', '');
            });
          
        });
        
      }
      
    }
    
  });
  
  $('.tab-set.gallery a').lightBox({fixedNavigation:true,
                                    imageBlank: '/' + window.swo_template_path + 'images/lightbox-blank.gif',
                                    imageLoading: '/' + window.swo_template_path + 'images/lightbox-ico-loading.gif',
                                    imageBtnClose: '/' + window.swo_template_path + 'images/lightbox-btn-close.gif',
                                    imageBtnPrev: '/' + window.swo_template_path + 'images/lightbox-btn-prev.gif',
                                    imageBtnNext: '/' + window.swo_template_path + 'images/lightbox-btn-next.gif'
                                   });
  
});

function addFormEvent(formLayer) {
  
  if(formLayer.length != 0)
    var form = formLayer.find('form');
  else
    var form = null;
  
  if(form != null && form.length != 0)
    form[0].onsubmit = function() {
      
      $.post(this.action + ' ', getFormData(this), function(data) {
        
        var newFormLayer = $(data).find('.tab-set[title=Kontakt]');
        
        if(newFormLayer.length != 0) {
          formLayer.html(newFormLayer.html());
          addFormEvent(formLayer);
        }
        
      }, 'html');
        return false;
    
    };
  
}

function addFormEvent2(formLayer) {
  
  if(formLayer.length != 0)
    var form = formLayer.find('form');
  else
    var form = null;
  
  if(form != null && form.length != 0)
    form[0].onsubmit = function() {
      
      $.post(this.action + ' ', getFormData(this), function(data) {
        
        var newFormLayer = $(data).find('.response .HP_emaildirect');
        
        if(newFormLayer.length != 0) {
          formLayer.html(newFormLayer.html());
          addFormEvent2(formLayer);
        }
        
      }, 'html');
        return false;
    
    };
  
}

function buildLink(args) {
  
  var req_uri = location.pathname;
  
  if(typeof args == 'undefined' || !args)
    return req_uri;
  
  var url = '';
  var temp = '';
  
  req_uri = req_uri.split('/');
  
  for (var key in req_uri)
    if(req_uri[key] && typeof(req_uri[key]) == 'string' && !req_uri[key].match('='))
      url += '/'+req_uri[key];
  
  for (var arg in args)
    if(args[arg])
      url += '/'+arg+'='+args[arg];
  
  return url;
  
}

function Menu(context) {
  
  var self = this;
  
  self.context = $(context);
  self.li = $('li', self.context);
  self.is_out = false;
  self.timeout = false;
  
  self.context.find('li').each(function() {
    
    var obj = $(this);
    
    if(obj.find('ul').length > 0)
      obj.addClass('submenu');
    
  });
  
  self.li.mousedown(function(e) { e.stopPropagation(); });
  $(document).mousedown(function() { self.li.removeClass('hover'); });
  
  self.li.hover(function(e) {
    
    var obj = $(this);
    var ul = obj.find('> ul').get(0);
    
    self.is_out = false;
    
    window.clearTimeout(self.timeout);
    
    self.li.each(function() {
      
      var each_li = $(this);
      
      if(each_li.hasClass('hover') == true) {
        
        each_li.removeClass('hover');
        
        //if(each_li.hasClass('root') && obj.hasClass('root')) {
        //  each_li.find('> ul').slideUp('fast');
       // }
        
      }
      
    });
    
    obj.parents('li').addClass('hover');
    obj.addClass('hover');
    //obj.find('> ul').hide();
    //obj.find('> ul').slideDown('fast');
    
    e.stopPropagation();
    
  }, 
  function() {
    
    self.is_out = true;
    
    window.clearTimeout(self.timeout);
    
    self.timeout = window.setTimeout(function() {
      
      if(self.is_out == true) {
        
        self.li.removeClass('hover');
        
       // if(self.li.hasClass('root'))
        //  self.li.find('> ul').slideUp('fast');
        
      }
      
    }, 1500);
    
  });
  
}

function showOriginalPicture(thumbnail, image_url) {
  
  thumbnail.issetEvent = false;
  
  var thumbnail = $(thumbnail);
  
  thumbnail.bind('mouseenter', function() {
    
    if(thumbnail.get(0).issetEvent == false) {
      
      var doc = $(document);
      var layer = document.createElement('div');
      var img = $(document.createElement('img'));
      var getViewPort = function() {
        
        var view = {height:0, width:0};
        
        if (typeof(window.innerWidth) == 'number') {
          view.width = window.innerWidth;
          view.height = window.innerHeight;
        } else if(document.documentElement && document.documentElement.clientWidth) {
          view.width = document.documentElement.clientWidth;
          view.height = document.documentElement.clientHeight;
        } else if(document.body && document.body.clientWidth) {
          view.width = document.body.clientWidth;
          view.height = document.body.clientHeight;
        }
        
        return view;
        
      };
      var getScrollPos = function() {
        
        var pos = {y:0, x:0};
        if (typeof(window.pageYOffset) == 'number') {
            pos.y = window.pageYOffset;
            pos.x = window.pageXOffset;
        } else if (document.documentElement && document.documentElement.scrollTop) {
            pos.y = document.documentElement.scrollTop;
            pos.x = document.documentElement.scrollLeft;
        } else if (document.body && document.body.scrollTop) {
            pos.y = document.body.scrollTop;
            pos.x = document.body.scrollLeft;
        }
        
        return pos;
        
      };
      var left = 0;
      var top = 0;
      var view = null;
      var scroll = null;
      var mouse = {x:0, y:0};
      var correctPosition = function() {
        
        scroll = getScrollPos();
        view = getViewPort();
        
        left = mouse.x + scroll.x;
        top = mouse.y + scroll.y;
        
        if(isNaN(left) == false && isNaN(top) == false) {
          
          if(left + layer.offsetWidth - scroll.x + 40 > view.width)
            left = scroll.x + view.width - layer.offsetWidth - 30;
          else
            left += 10;
          
          if(top + layer.offsetHeight - scroll.y + 20 > view.height)
            top = scroll.y + view.height - layer.offsetHeight - 10;
          else
            top += 10;
          
          layer.style.left = left.toString() + 'px';
          layer.style.top = top.toString() + 'px';
          
        }
      
      };
      var docEvent = function(e) { 
        
        if(e.target !== thumbnail.get(0) && e.target !== layer && e.target !== img.get(0)) {
          $(layer).remove();
          doc.unbind('mousemove', docEvent);
          thumbnail.get(0).issetEvent = false;
        }
        
        mouse.x = e.clientX;
        mouse.y = e.clientY;
        correctPosition();
        
      };
      
      doc.bind('mousemove', docEvent);
      doc.bind('mousedown', function() { $(layer).remove(); });
      
      img.load(correctPosition);
      
      document.body.appendChild(layer);
      layer.setAttribute('class', 'mop-layer');
      layer.appendChild(img.get(0));
      layer.style.position = 'absolute';
      layer.style.zIndex = '9999999';
      img.get(0).src = image_url;
      thumbnail.get(0).issetEvent = true;
      
    }
    
  });
  
}

function getFormData(form) {
  
  var option = null;
  var obj = {};
  
  $('input, select, textarea', form).each(function() {
    
    switch(this.nodeName) {
      
      case 'INPUT':
        
        switch(this.type) {
          
          case 'checkbox':
          case 'radio':
            
            if(this.checked == true)
              obj[this.name] = this.value;
            
            break;
            
          case 'file':
            break;
            
          default:
            obj[this.name] = this.value;
           break;
           
        }
        
        break;
        
      case 'SELECT':
        
        if(this.multiple == true) {
          
          obj[this.name] = new Array();
          
          for(var j = 0; j < this.length; j++)
            if(this.options[j].selected)
              obj[this.name].push(this.options[j].value);
          
        } else {
          
          for(var j = 0; j < this.length; j++)
            if(this.options[j].selected)
              obj[this.name] = this.options[j].value;
          
        }
        
        break;
        
      case 'TEXTAREA':
        
        obj[this.name] = this.value;
        
        break;
      
    }
    
  });
  
  return obj;
  
}
