/*
Copyright (C) 2011 profil1
*/
// hashe function
(function($,e,b){var c="hashchange",h=document,f,g=$.event.special,i=h.documentMode,d="on"+c in e&&(i===b||i>7);function a(j){j=j||location.href;return"#"+j.replace(/^[^#]*#?(.*)$/,"$1")}$.fn[c]=function(j){return j?this.bind(c,j):this.trigger(c)};$.fn[c].delay=50;g[c]=$.extend(g[c],{setup:function(){if(d){return false}$(f.start)},teardown:function(){if(d){return false}$(f.stop)}});f=(function(){var j={},p,m=a(),k=function(q){return q},l=k,o=k;j.start=function(){p||n()};j.stop=function(){p&&clearTimeout(p);p=b};function n(){var r=a(),q=o(m);if(r!==m){l(m=r,q);$(e).trigger(c)}else{if(q!==m){location.href=location.href.replace(/#.*/,"")+q}}p=setTimeout(n,$.fn[c].delay)}$.browser.msie&&!d&&(function(){var q,r;j.start=function(){if(!q){r=$.fn[c].src;r=r&&r+a();q=$('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){r||l(a());n()}).attr("src",r||"javascript:0").insertAfter("body")[0].contentWindow;h.onpropertychange=function(){try{if(event.propertyName==="title"){q.document.title=h.title}}catch(s){}}}};j.stop=k;o=function(){return a(q.location.href)};l=function(v,s){var u=q.document,t=$.fn[c].domain;if(v!==s){u.title=h.title;u.open();t&&u.write('<script>document.domain="'+t+'"<\/script>');u.close();q.location.hash=v}}})();return j})()})(jQuery,this);
// imgesload callback
$.fn.imagesLoaded=function(callback){var $images=this.find('img'),len=$images.length,_this=this,blank='data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';function triggerCallback(){callback.call(_this,$images)}function imgLoaded(){if(--len<=0&&this.src!==blank){setTimeout(triggerCallback);$images.unbind('load error',imgLoaded)}}if(!len){triggerCallback()}$images.bind('load error',imgLoaded).each(function(){if(this.complete||this.complete===undefined){var src=this.src;this.src=blank;this.src=src}});return this};
// custom fadein/out
(function($){$.fn.customFadeIn=function(speed,callback){$(this).fadeIn(speed,function(){if(jQuery.browser.msie)$(this).get(0).style.removeAttribute('filter');if(callback!=undefined)callback()})};$.fn.customFadeOut=function(speed,callback){$(this).fadeOut(speed,function(){if(jQuery.browser.msie)$(this).get(0).style.removeAttribute('filter');if(callback!=undefined)callback()})}})(jQuery);

var hash='',tagsort='',fail=1,groupsort=0,article,onloadhashchange=false,
    loadingMsg = $('<div id="loadingMsg">Lade...</div>');
    jQuery.easing.def = "easeOutExpo";

$(function(){
  $(window).hashchange( function(){
    // Alerts every time the hash changes!
    hash=window.location.hash;
    if(hash!='') onloadhashchange=true;
    initHashAction();
  })
  // Trigger the event (useful on page load).
  $(window).hashchange();

});

$(document).ready(function() {
  initDefaults();
  // if(onloadhashchange===false) 
  initdefaultsliders();
  //if(onloadhashchange===true) initfirstchange();
  initAnimateFilterNav();
  getAjaxLink('.rex-navi1 a, .favorites a');
  initCheckFilter(hash);
  initlBox();
  $('#slider_wrapper').addClass('loadtrue');
});

/////////////////////////////////////////
// initDefaults
/////////////////////////////////////////
function initDefaults() {
  $('.navigation ul li:last-child, .favorites ul li:last-child').addClass('last-child');

  $('a.icon.facebook, a.icon.twitter, a.icon.addthis').live('click', function() {
    window.open($(this).attr('href'), '_blank', 'width=640,height=360');
    return false;
  });
  
  $('#footer a[rel=external], a.external-link').live('click', function() {
    window.open($(this).attr('href'), '_blank');
    return false;
  });

}

/////////////////////////////////////////
// initdefaultsliders
/////////////////////////////////////////
function initdefaultsliders() {
  var slider1 = $('#slider_1'),
      slider0 = $('#slider_0');

  slider1
    .hide()
    .slidecarousel({controls:true,pager:true})
    .find('.box-base .box .overlay').css('opacity','0');
    
  showLoading();
  
//  slider1.imagesLoaded( function( $images ) {
  slider1.find('.overview li:eq(1)').imagesLoaded( function( $images ) {
    slider1.customFadeIn(450,function(){
      initAnimateBoxeOverlays(350,slider1,false,'');
    });
    hideLoading();
  });
  
  slider0.hide().slidecarousel({controls:true});
  getAjaxFilterLink($('#slider_1 .box a, #slider_0 a'));
  overviewclickevents();
}
function initfirstchange() {
  $('#slider_0').empty();
  $('#slider_1').empty();
};

/////////////////////////////////////////
// get back ajaxfilterlinks
/////////////////////////////////////////
function getAjaxFilterLink(glink) {
  $(glink).each(function() {
    rwiteAjaxHref($(this)) 
    
    // setCurrentFilterLink();
    $(this).bind('click',function() {
      setCurrentFilterLink($(this));
    });
  });
}

/////////////////////////////////////////
// get back ajaxlinks
/////////////////////////////////////////
function getAjaxLink(glink) {
  $(glink).each(function() {
    rwiteAjaxHref($(this));
  });
}

/////////////////////////////////////////
// get rwriteAjaxHref
/////////////////////////////////////////
function rwiteAjaxHref(glink) {
  glink.attr('href', function(i) {
    var href   = this.href.replace(location.protocol + '//' + location.hostname + '/',''),
        hashes = window.location.href.slice(window.location.href.indexOf('/') + 1).split('#'),
        wlocation = hashes[0].replace(location.hostname + '/','');


    href = href.replace('#','');
    // später check location hash und gib group und tag id zurück setze diese ein sonst default
    
    var arrhref = href.split('++');
    if(arrhref.length == 1) {
      href = arrhref[0] + '++/group/0/tag/9/';
    } 

    $(this).attr('rel', '#' + href);
    return wlocation + "#" + href;
  });
}
/////////////////////////////////////////
// setCurrentFilterLink
/////////////////////////////////////////
function setCurrentFilterLink(glink) {
  var thishref = glink.attr('href').split('#');
      thishash = '#'+thishref[1];
  // by click or load set second-link or first-link current in filter-navigation
  if(glink.parent().parent().parent().hasClass('filter-navigation')) {
    if(glink.hasClass('first-link')) {
      $('.filter-navigation .first-link').each(function() {
        if(getGroupId($(this),'rel') != groupsort) {
          $(this).removeClass('current');
        }
      });
      glink.addClass('current');
    }
    if(glink.hasClass('second-link') && glink.parent().parent().hasClass('first-line')) {
      $('.first-link').removeClass('current');
      $('.first-line .second-link').removeClass('current');
      if(glink.attr('rel') == thishash) {
        glink.addClass('current');
      }
    }
  }
}

/////////////////////////////////////////
// initSecondFilterLink
/////////////////////////////////////////
function initSecondFilterLink(glink,hash) {
  $(glink).each(function() {
      // by click or load set second-link an first-link current in filter-navigation-second-line
    $(this).bind('click',function() {
      if(glink.parent().parent().parent().parent().hasClass('filter-navigation-second-line') && $(this).hasClass('second-link')) {
        var thishref      = $(this).attr('href').split('#'),
            thishash      = '#'+thishref[1],
            filters_link  = $('li.second-li').find('a.second-link');
            filterf_link  = $('li.first-li').find('a.second-link');
            groupsort     = getGroupId($(this),'rel');
            
        initResetId('group','false',groupsort);
        
        $('.filter-navigation .first-line').find('a.first-link').each(function() {
          if(groupsort != getGroupId($(this),'rel')) {
            $(this).removeClass('current');
          }
        });
        // set this current
        $(this).removeClass('active');
        if($(this).attr('rel') == thishash) {
          filterf_link.removeClass('current');
          filters_link.removeClass('current');
          $(this).addClass('current');
          
          $('.filter-navigation .first-line').find('a.first-link').each(function() {
         	if(groupsort != getGroupId($(this),'rel')) {
           		$(this).removeClass('current');
         	}
         	$(this).removeClass('active');
       	  });
          
		  filters_link.each(function() {
            if($(this).attr('rel') == thishash) {
              $(this).addClass('current');
            }
          });

        }
      }
    });
  });
}

/////////////////////////////////////////
// initCheckFilter
/////////////////////////////////////////
function initCheckFilter(hash) {
  var filters_link = $('.filter-navigation li.second-li').find('a.second-link'),
      filtern_link = $('.filter-navigation li.first-li').find('a.first-link, a.sec-first');
  getCurrSecondFilterFromHash(filters_link,hash);
  getCurrFirstFilterFromHash(filtern_link,hash);
}

/////////////////////////////////////////
// getCurrFirstFilterFromHash
/////////////////////////////////////////
function getCurrFirstFilterFromHash(filter_link,hash) {
  if (hash != '') {
    var thishashes       = hash.split('++'),
        thishasheget     = thishashes[1].split('/');
        
        if(thishasheget[1] == 'group') {
          var thishashegrouid  = parseInt(thishasheget[2]),
              thishashetagid   = parseInt(thishasheget[4]);
              groupsort        = thishashegrouid;
        } else {
          var thishashegrouid  = 0;
              thishashetagid   = parseInt(thishasheget[2]);
        }
    
    if(filter_link.length > 0) {
    
      initResetId('group','false',thishashegrouid);
      
      filter_link.each(function() {
        var thisgroupid  = getGroupId($(this),'rel'),
            thistagid    = getTagId($(this),'rel');
      
        if($(this).hasClass('first-link')) {
          if(thishashegrouid == thisgroupid) {
            $(this).addClass('current');
            
            // init animation
            var thisFilterLayer  = $('.filter-navigation-second-line .inner'),
                thisFiltersHTML  = '<ul>' + ($(this).next('ul').html()) + '</ul>',
                tbPadding        = 10*2,
                animateeasing    = 'swing';
                
            if ((thisFiltersHTML.length > 0) || (thisFilterLayer.hasClass('animateToHide'))) {
              thisFilterLayer.html(thisFiltersHTML).hide().stop().customFadeIn();
              $('.filter-navigation').addClass('show-seconds');

              // initSecondFilterLink /////////////////////////////////////////
              initSecondFilterLink(thisFilterLayer.find('a'));
              
              thisFilterLayer.parent().stop().animate({'height':(thisFilterLayer.height() + tbPadding)+'px'},animateeasing,function() {
                thisFilterLayer.addClass('show');
              });
            }
            
          } else {
            $(this).removeClass('current');
          }
        } else {
          if(thishashetagid == thistagid) {
            $(this).addClass('current');
          } else {
            $(this).removeClass('current');
          }
        }
      });
    }
  }
}

/////////////////////////////////////////
// getCurrSecondFilterFromHash
/////////////////////////////////////////
function getCurrSecondFilterFromHash(filter_link) {
  if (hash != '') {
    var thishashes       = hash.split('++'),
        thishasheget     = thishashes[1].split('/');
        
        if(thishasheget[1] == 'group') {
          thishashetagid   = parseInt(thishasheget[4]);
        } else {
          thishashetagid   = parseInt(thishasheget[2]);
        }
        // alert(thishashes + ' ' + thishasheget);
        
    if(filter_link.length > 0) {
      filter_link.each(function() {
        var thistagid  = getTagId($(this),'rel');
        if(thishashetagid == thistagid) {
          $(this).addClass('current');
          // alert(thishashetagid + ' ' + thistagid + ' ' + $(this).attr('class'));
        } else {
          $(this).removeClass('current');
        }
      });
    }
  }
}

/////////////////////////////////////////
// getGroupId
/////////////////////////////////////////
$.fn.hasAttr = function(name) {  
   return this.attr(name) !== undefined;
};

function getGroupId(glink,atr) {
  if(glink.hasAttr(atr)) {
    if(glink.attr(atr)!='') {
      var thishashes = glink.attr(atr).split('++'),
          thishasheget = thishashes[1].split('/');

      if (thishasheget[1] == 'group') {
        return parseInt(thishasheget[2]);
      } else {
        return 0;
      }
    }
  }
}

/////////////////////////////////////////
// getTagId
/////////////////////////////////////////
function getTagId(glink,atr) {
  if(glink.hasAttr(atr)) {
    if(glink.attr(atr)!='') {
      var thishashes = glink.attr(atr).split('++'),
          thishasheget = thishashes[1].split('/');
  
      if (thishasheget[1] == 'tag') {
        return parseInt(thishasheget[2]);
      } else if (thishasheget[3] == 'tag') {
        return parseInt(thishasheget[4]);
      } else {
        return 0;
      }
    } else {
      return 0;
    }
  }
}

/////////////////////////////////////////
// initAnimateFilterNav
/////////////////////////////////////////
function initAnimateFilterNav() {
  
  var thisFilterLayer    = $('.filter-navigation-second-line .inner'),
      filter_navigation  = $('.filter-navigation ul.first-line li'),
      filter_links       = filter_navigation.find('a'),
      animateeasing      = 'swing';
      
      // getAjaxFilterLink /////////////////////////////////////////
      getAjaxFilterLink(filter_links);
  
  $('.filter-navigation ul.first-line li').each(function() {
    var thisfLink  = $(this).find('a.first-link'),
        thissLink  = $(this).find('a.second-link'),
        thiscLink  = $(this).find('a.sec-first'),
        tbPadding  = 10*2;
        
    thisfLink.bind('click',function() {
      var thisFilterLayerHTML = thisFilterLayer.html(),
          thisFiltersHTML     = '<ul>' + ($(this).next('ul').html()) + '</ul>';
      if ((thisFiltersHTML.length > 0 && thisFilterLayerHTML != thisFiltersHTML) || (thisFilterLayer.hasClass('animateToHide'))) {
        thisFilterLayer.html(thisFiltersHTML);
        $('.filter-navigation').addClass('show-seconds');
         thisfLink.removeClass('active');
        if(getGroupId($(this),'rel')!=groupsort) {
          $(this).addClass('active').addClass('current');
        }
        // initSecondFilterLink /////////////////////////////////////////
        initSecondFilterLink(thisFilterLayer.find('a'));
        
        thisFilterLayer.parent().stop().animate({'height':(thisFilterLayer.height() + tbPadding)+'px'},animateeasing,function() {
          thisFilterLayer.addClass('show');
        });
      }
      return $(this).attr('href');
    });
    thiscLink.bind('click',function() {
      // close && init filterung /////////////////////////////////////////
      thisFilterLayer.parent().stop().animate({'height':'0px'},animateeasing,function() {
        thisFilterLayer.removeClass('show');
        $('.filter-navigation').removeClass('show-seconds');
      });
      return $(this).attr('href');
    });
  });
}

/////////////////////////////////////////
// .wait()
/////////////////////////////////////////
$.fn.wait = function(time,type) {
  time = time || 1000;
  type = type || "fx";
  return this.queue(type, function() {
    var self = this;
    setTimeout(function() {
      $(self).dequeue();
    }, time);
  });
};

var anim_t;

/////////////////////////////////////////
// later animate overlay
/////////////////////////////////////////
function initAnimateBoxeOverlays(setfirsttime,thisslider,delslider,oldslider) {
  thisslider.find('.box-base .box .second-overlay').css('opacity','0');
  var thisBoxeOverlays = thisslider.find('.box-base .box .overlay').css('opacity','0'),
      count = 1,
      firsttime = 800,
      defaulttime = 50,
      time = defaulttime;

  if (setfirsttime > 0) {
    firsttime = setfirsttime;
  }
  
  thisBoxeOverlays.each(function() {
    if (count == 1) {
      time = firsttime;
    } else {
      time = (defaulttime * count) + firsttime;
      // callback init animat hover
      if (thisBoxeOverlays.length > 12) {
        var lengthCount = 12;
      } else {
        var lengthCount = thisBoxeOverlays.length;
      }
    }
    $(this).stop().wait(time,'fx').animate({'opacity':'0.9'},'swing')
      .parent().find('.second-overlay').wait((time),'fx').animate({'opacity':'0.2'},'swing');
    count++;
  });
  
  // blendout oldslider
  // cleartimer by reinitialisation
  if(anim_t) clearTimeout(anim_t);
  anim_t = setTimeout(function() {
    initAnimateOverlaysByHover(thisslider);
    if(delslider==true) {
      oldslider.stop().customFadeOut(800);
    }
  },(firsttime+(12*defaulttime)));
}

/////////////////////////////////////////
// animate overlay by hover
/////////////////////////////////////////
function initAnimateOverlaysByHover(thisslider) {
  var thisBoxLink = thisslider.find('.box-base .box a');
  thisBoxLink.unbind();
  
  thisBoxLink.bind({
    mouseenter: function() {
      $(this).parent().find('.overlay').stop().animate({'opacity':'0'},'swing');
    },
    mouseleave: function() {
      $(this).parent().find('.overlay').stop().animate({'opacity':'0.9'},'swing');
    }
  });
/*  thisBoxLink.hover(function() {
    $(this).parent().find('.overlay').stop().animate({'opacity':'0'},'swing');
  },function() {
    $(this).parent().find('.overlay').stop().animate({'opacity':'0.9'},'swing');
  });*/
}

/////////////////////////////////////////
// initHashAction
/////////////////////////////////////////
function initHashAction() {
  if (hash == '') { hash = window.location.hash; }
  if (hash != '') { initLoading(hash); }
}

/////////////////////////////////////////
// initResetTagId
/////////////////////////////////////////
function initResetId(id_name,old_id,new_id) {
  var filter_links = $('.filter-navigation ul.first-line li a.first-link, #header a, a.news-teaser-link');
  filter_links.each(function() {
    if(old_id != 'false') {
      var this_old_id = old_id;
    } else {
      if(id_name == 'tag') {
        var this_old_id = getTagId($(this),'href');
      }
      if(id_name == 'group' && !$(this).hasClass('first-link')) {
        var this_old_id = getGroupId($(this),'rel');
      }
    }
    var href = $(this).attr('href').replace('/' + id_name + '/' + this_old_id,'/' + id_name + '/' + new_id);
    $(this).attr('href',href);
  });
}

/////////////////////////////////////////
// initReloadSlider
/////////////////////////////////////////
function initReloadSlider(new_slider0,new_slider1,fail) {
  var slider0 = $('#slider_0'),
      slider1 = $('#slider_1'),
      slider2 = $('#slider_2'),
      setfirsttime = 450;

  slider0.hide().html(new_slider0).slidecarousel({controls:true,pager:true});
  $('.fullslidelink .firstinner').css({'opacity':0.9});
  
   if(!slider2.hasClass('thisslide2')) {
      var slider_1 = slider2.addClass('thisslide2').removeClass('thisslide1'),
          slider_2 = slider1.addClass('thisslide1').removeClass('thisslide2');
    } else {
      var slider_1 = slider1.addClass('thisslide2').removeClass('thisslide1'),
          slider_2 = slider2.addClass('thisslide1').removeClass('thisslide2');
    }
    
    if(fail=='true') {
      // img preload
      slider_1.imagesLoaded( function( $images ) {
        slider_1.hide().html(new_slider1).customFadeIn();
        slider_2.empty();
        hideLoading();
      });
    } else {
      slider_1.hide().html(new_slider1).slidecarousel({controls:true,pager:true});
      // img preload
      slider_1.imagesLoaded( function( $images ) {
        initAnimateBoxeOverlays(setfirsttime,slider_1,true,slider_2);
        slider_2.find('.buttons,.pager').customFadeOut();
        slider_1.customFadeIn(200,function() {
          getAjaxFilterLink($('.box a, a.fullslidelink'));
        });
        hideLoading();
      });
    }
    overviewclickevents();
  
}

/////////////////////////////////////////
// favoritesclickevent
/////////////////////////////////////////
function favoritesclickevent() {
  $('.addtofavorites').each(function() {
    $(this).click(function() {
      var obj = $(this).addClass('current');
      var relid = $(this).attr('rel');
      
      $('#slider_5 li:eq('+ relid +')').find("span.thisisfav").html('true');
      $('#slider_3 li:eq('+ relid +')').find("span.thisisfav").html('true');
      
      $.ajax({
        url: obj.attr('href'),
        success: function (html) { 
          $('.favorites li span').html(html);
          if(obj.hasClass('remove')) {
            obj.parents('.box.small').fadeOut(350);
            if(!parseFloat(html)) {
              $('.content_wln').html('Ihre Favoritenliste ist leer.').fadeIn(600);
              $('.content_wln + .extra').fadeOut(650);
            }
          }
        }
      });
      return false;
    });
  });
  $('.remove').each(function(){
    $(this).click(function() {

      var relid = $(this).attr('rel');
      
      $.ajax({
        url: $(this).attr('href'),
        success: function (html) { 
          $('.favorites li span').html(html);
          
          if(html > 0) {
/*
            $('#slider_5 li:eq('+ relid +')').remove();
            $('#slider_5 .pager li:eq('+ relid +')').remove();
            $('#slider_5 .pager li').each(function(index){
              $(this).find('a').attr('rel',index);
            });
            $('#slider_6 li:eq('+ relid +')').remove();
            $('#slider_7 .overview-box:eq('+ relid +')').remove();

            $('#slider_5').slidecarousel();
            $('#slider_6').slidecarousel();
            $('#slider_7').slidecarousel();
*/
            initLoading('#de/favoriten.html');
          } else {
            initLoading('#de/favoriten.html');
          }
          
        }
      });
      
      
      return false;
    });
  });
}

/////////////////////////////////////////
// initAnimateClientContent
/////////////////////////////////////////
function initAnimateClientContent(getcontent) {
  var thisClientLayer    = $('.client-bar .inner'),
      tbPadding          = 10*2,
      animateeasing      = 'swing';
      
  // jump opacity 0 use only css
  thisClientLayer.hide().html(getcontent);
    
  detailsliders('3','4');
  
  $('.client-corner .corner').stop().animate({'top':'-10px','height':'17px'},200,'swing');
  thisClientLayer.stop().customFadeIn();
  thisClientLayer.parent().stop().animate({'height':(thisClientLayer.height() + tbPadding)+'px','margin-bottom':'23px'},animateeasing,function() {
    thisClientLayer.parent().addClass('show');
    animateToClientContent();
  });

  hideLoading();
}

/////////////////////////////////////////
// animateToClientContent
/////////////////////////////////////////
function animateToClientContent() {
  clientBarPos = $('.client-bar').offset().top;
    
    if($(document).height() - clientBarPos < $(window).height()) {
      clientBarPos = $(document).height() - $(window).height();
    }
    
    $('html, body').animate({scrollTop:clientBarPos}, 800);
}

/////////////////////////////////////////
// initAnimateMainContent
/////////////////////////////////////////
function initAnimateMainContent(getcontent) {
  var thisContentLayer    = $('.content-bar .inner'),
      tbPadding          = 10*2,
      animateeasing      = 'swing';
    
  var hashes = window.location.href.slice(window.location.href.indexOf('/') + 1).split('#'),
      thishref= hashes[1].split('++');
        
  $('.navigation a, .favorites a').removeClass('current').each(function() {
    var navhref = $(this).attr('href').replace('/#',''),
        navhref = navhref.replace('#',''),
        thisnavhref = navhref.split('++');
    if(thishref[0] == thisnavhref[0]) {
      $(this).addClass('current');
    }
  });
    
  var headoffset = $('#header').offset();
  var navoffset = $('#header a.current').offset();
  if(!navoffset) navoffset = 0;
  var positionleft = ((navoffset.left - headoffset.left) + ($('#header a.current').width()/2)-13);
        
  // jump opacity 0 use only css
  thisContentLayer.hide().html(getcontent);

  detailsliders('6','7');

  //$("#slider_news").slidecarousel({controls:true,axis:"y",gotoheight:true});
  
   window.setTimeout(function() {
   $("#slider_news").slidecarousel({controls:true,axis:"y",gotoheight:true});
 },2);
 
  
  $('.close-agency, .close-contact, .close-news, .close-favorites, .close-clients').bind('click',function() {
    closebar('content');
    return "/#";
  });
  
   $('.client-link').click(function(){
   window.setTimeout(function() {
     initCheckFilter(hash);
   },2);
 });

  getAjaxLink('a.news-teaser-link');

  $('.content-corner').css({'left':positionleft+'px'});
  $('.content-corner .corner').stop().animate({'top':'-10px','height':'17px'},200,'swing');
  thisContentLayer.stop().customFadeIn();
  thisContentLayer.parent().stop().animate({'height':(thisContentLayer.height() + tbPadding)+'px','margin-bottom':'23px'},animateeasing,function() {
    thisContentLayer.parent().addClass('show');
  });

  hideLoading();
}

/////////////////////////////////////////
// initAnimateMainContent
/////////////////////////////////////////
function initAnimateNewsContent(getcontent) {
  $('.news-content').hide().html(getcontent).stop().customFadeIn();
  $('.content-bar').animate({'height':($('.content-bar .inner').height()+20)+'px'},'swing');
}

/////////////////////////////////////////
// detailsliders
/////////////////////////////////////////
function detailsliders(id1,id2) {
  $('#slider_'+id1).slidecarousel({controls:true,pager:false,slider2:true,centerimgwrapper:true,share:true,remove:true});
  $('#slider_'+id2).hide().slidecarousel({controls:true,pager:true,slider2:true});

  $('#slider_'+id1+' li').each(function(index) {
    $(this).find('.gotoslide_5').attr('rel',(index+1)).click(function() {
      var relid = $(this).attr('rel');
      var item = $('#slider_5 li:eq('+ (relid-1) +')');
      lboxopen();
      $('#slider_5').slidecarousel_move(relid);
      if($(this).hasClass('autostart')) {
        setnewyoutubeobj(item,'1');
        startflash(item);
      }
      return false;
    });
  });
  $('#slider_'+id2+' .overview-box-inner').each(function(index) {
    $(this).attr('rel',(index+1));
  }).click(function() {
    if(!$(this).hasClass('external')) {
      var relid = $(this).attr('rel');
      var item = $('#slider_5 li:eq('+ (relid-1) +')');
      lboxopen();
      $('#slider_5').slidecarousel_move($(this).attr('rel'));
      if($(this).find('div.play-button.gotoslide_5').hasClass('autostart')) {
        setnewyoutubeobj(item,'1');
        startflash(item);
      }
      return false;
    }
  });
  
  $('.extlink-button, .external .pagenum em').css({'opacity':0.7});

  clientviewclickevents(id1,id2);
  favoritesclickevent();

}

/////////////////////////////////////////
// initLboxContent
/////////////////////////////////////////
function initLboxContent(getcontent) {
  $('#lbox-message').html(getcontent);
  $('#slider_5').slidecarousel({controls:true,pager:true,slider2:true,fullsizeimg:true,share:true,flash:true,remove:true});

  $('.extlink-button, .external .pagenum em').css({'opacity':0.7});

  resizelBox();
  setfirstimgsize();
  initflashlinks();
  favoritesclickevent();
}

/////////////////////////////////////////
// overviewclickevents
/////////////////////////////////////////
function overviewclickevents() {

  $('.client-overview .icon.oview').unbind();
  $('.client-overview .icon.detail').unbind();
  
  var animateeasing = 'swing';
  
    // click overview
    $('.client-overview .icon.oview').bind('click',function() {
      showLoading();
      $('#slider_0').hide();
      $('.thisslide2').imagesLoaded( function( $images ) {
        $('.thisslide2').stop().customFadeIn();
        $('.thisslide1').hide();
        hideLoading();
      });
    });
    
    // click detail
    $('.client-overview .icon.detail').bind('click',function() {
      showLoading();
      $('.thisslide2,.thisslide1').hide();
      $('#slider_0').imagesLoaded( function( $images ) {
        $('#slider_0').stop().customFadeIn();
        hideLoading();
      });
    });
}

/////////////////////////////////////////
// clientviewclickevents
/////////////////////////////////////////
function clientviewclickevents(id1,id2) {
  var animateeasing      = 'swing';
  
  $('.client-headline .icon.overview, .content-headline .icon.overview').unbind();
  $('.client-headline .icon.detail, .content-headline .icon.detail').unbind();
  $('.client-headline .lbox-open, .content-headline .lbox-open').unbind();
  
    // click overview
    $('.client-headline .icon.overview, .content-headline .icon.overview').bind('click',function() {
      $('#slider_'+id1).removeClass('current-slider').hide();
      $('#slider_'+id2).stop().customFadeIn();
    });
    // click detail
    $('.client-headline .icon.detail, .content-headline .icon.detail').bind('click',function() {
      $('#slider_'+id2).hide();
      $('#slider_'+id1).addClass('current-slider').stop().customFadeIn();
    });
    // click detail
    $('.client-headline .close-gototop').bind('click',function() {
      $('html, body').animate({scrollTop:0}, 400);
    });
    // click lighbtox
    $('.client-headline .lbox-open, .content-headline .lbox-open').bind('click', function () {
      lboxopen();
      var nextbutton = $(this).parent().parent().parent().parent().parent().find('.current-slider .buttons.next');
      if(nextbutton.length > 0) {
        var nextbuttonrel = nextbutton.attr('rel');
        if(nextbuttonrel > 0) {
          $('#slider_5').slidecarousel_move(nextbuttonrel);
        }
      }
      return false;
    });
}

/////////////////////////////////////////
// closebar
/////////////////////////////////////////
function closebar(typ) {
  var thisLayer      = $('.'+ typ +'-bar .inner'),
      thisCorner     = $('.'+ typ +'-corner .corner'),
      animateeasing  = 'swing';

  thisCorner.stop().animate({'top':'0px','height':'0px'},200,animateeasing);
  
  if (typ == 'content') $('.navigation a, .favorites a').removeClass('current');
  
  thisLayer.parent().stop().animate({'height':'0px','margin-bottom':'0px'},animateeasing,function() {
    thisLayer.parent().removeClass('show');
    thisLayer.hide().empty();
  });
}

/////////////////////////////////////////
/////////////////////////////////////////


/////////////////////////////////////////
// show/hide loading info
/////////////////////////////////////////
function showLoading() {
  loadingMsg.fadeOut(0);
  $('body').append(loadingMsg);
  loadingMsg.fadeIn(200, 'swing');
}

function hideLoading() {
  loadingMsg.fadeOut(200, 'swing', function() {
    loadingMsg.remove();
  });
}


/////////////////////////////////////////
// initLoading
/////////////////////////////////////////

$.get('/callback/', {cache: false});

function initLoading(url) {

  showLoading();

  if (url) { geturl=url.replace('#','/'); } else {
    var hashes = window.location.href.slice(window.location.href.indexOf('/') + 1).split('#');
    if (hashes != 'undefined') geturl='/'+hashes[1];
  }
  if (geturl != '/undefined') {
    $.ajax({
      type: "GET",
      url: geturl,
      cache: false,
      data: "&ajax=json",
      dataType: "json",
      success: function(data) {
      
       // hideLoading();
        
        /////////////////////////////////////////
        // need new client overview?
        if ((tagsort != data.tagsort || data.readyload == 'true') && (data.tagsort > 0)) {
          if(tagsort == '') tagsort = data.tagsort;

          // reset new default tag in group navi
          initResetId('tag',tagsort,data.tagsort);

          // reload slider
          if (data.slider1 != '') {
            // later blend out blend in
            initReloadSlider(data.slider0,data.slider1,data.sliderfail)
          }
          tagsort = data.tagsort;
        } else {
          hideLoading();
        }
        
        /////////////////////////////////////////
        // getproject content
        if (data.clientid > 0 && data.content != '') {
          if($('.content-bar').hasClass('show')) closebar('content');
          initAnimateClientContent(data.content);
          if (data.lbox!='') initLboxContent(data.lbox);
        } else {
          if (data.lbox!='' && data.artid == 24) initLboxContent(data.lbox);
        }
        if (data.clientid == 0 || data.clientid == '' ) {
          // closebar('client');
        }
        if (data.newsid > 0) {
          if($('.content-bar').hasClass('show')) {
            initAnimateNewsContent(data.content);
          }
       } else {
          if ((data.clientid == 0 || data.clientid == '') && data.content!='' && data.content != $('.content-bar .inner').html()) {
            if($('.client-bar').hasClass('show')) closebar('client');
            initAnimateMainContent(data.content);
          }
        }
        
        /////////////////////////////////////////
        // get site-title
        if (data.title != '' && data.title != document.title) {
          document.title = data.title;
        }
        
        /////////////////////////////////////////
        // set latest tagsort id
        tagsort = data.tagsort;
        article = data.article;
      }
    });
  }
}

if(tagsort=='') {
  tagsort = 9;
}

// window.setTimeout(function() {
// },200);


// dialogbox
/**
/ THIRD FUNCTION
* getPageScroll() by quirksmode.com
*
* @return Array Return an array with x,y page scroll values.
*/
function getPageSize() {
  var xScroll, yScroll;
  if (window.innerHeight && window.scrollMaxY) {
        xScroll = window.innerWidth + window.scrollMaxX;
        yScroll = window.innerHeight + window.scrollMaxY;
  } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
  } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
  }
  var windowWidth, windowHeight;
  if (self.innerHeight) {  // all except Explorer
        if(document.documentElement.clientWidth) {
          windowWidth = document.documentElement.clientWidth;
        } else {
          windowWidth = self.innerWidth;
        }
        windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
  }
  // for small pages with total height less then height of the viewport
  if(yScroll < windowHeight) {
        pageHeight = windowHeight;
  } else {
        pageHeight = yScroll;
  }
  // for small pages with total width less then width of the viewport
  if(xScroll < windowWidth) {
        pageWidth = xScroll;
  } else {
        pageWidth = windowWidth;
  }
  arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
  return arrayPageSize;
};
function getPageScroll() {
  var xScroll, yScroll;
  if (self.pageYOffset) {
        yScroll = self.pageYOffset;
        xScroll = self.pageXOffset;
  } else if (document.documentElement && document.documentElement.scrollTop) {   // Explorer 6 Strict
        yScroll = document.documentElement.scrollTop;
        xScroll = document.documentElement.scrollLeft;
  } else if (document.body) {// all other Explorers
        yScroll = document.body.scrollTop;
        xScroll = document.body.scrollLeft;
  }
  arrayPageScroll = new Array(xScroll,yScroll);
  return arrayPageScroll;
};
function lboxopen() {
  resizelBox();
  setfirstimgsize();
  $('#lbox-overlay').show().css({'opacity':0.9});
  $('#lbox').fadeIn(300);
}
function resizelBox() {
  var animTime,
      arrPageScroll = getPageScroll(),
      arrPageSizes = getPageSize(),
      browsWidth = $(window).width();
      browsHeight = $(window).height();

  $('#lbox-overlay').css({'height':arrPageSizes[1]+'px', 'width':arrPageSizes[0]+'px'});
  $('#lbox').css({'height':browsHeight+'px','width':browsWidth+'px','top':'0px','left':'0px','position':'fixed'});
  $('.lbox-content, .lbox-message, .lbox_content').css({'height':browsHeight+'px','width':browsWidth+'px'});
  
  $('.lboxslider .overview li img').width();
  $('.lboxslider .viewport, .lboxslider .overview li').css({'height':(browsHeight-155)+'px','width':(browsWidth-200)+'px'});
  $('.lboxslider .buttons').css({'height':(browsHeight-155)+'px'});

  $('#slider_5').css({'height':(browsHeight-60)+'px'});

}
function initlBox() {
  $(window).bind('resize', function () {
    if (!$('#lbox').is(':hidden')) {
      resizelBox();
    }
  });
/*
  $(window).bind('scroll', function() {
  //  resizelBox();
  });
  $('.lbox-open').bind('click', function () {
     lboxopen();
    return false;
  });
*/
  $('a.close, #lbox-overlay').click(function () {
    $('#lbox-overlay, #lbox').fadeOut(300);
    clearflash();
    return false;
  });
}
function setfirstimgsize() {
  $('.lboxslider .overview li').each(function() {
    var w_w  = $(this).outerWidth(true),
        w_h  = $(this).outerHeight(true),
        r_w  = w_h / w_w,
        i_w  = $(this).find('img').attr('width'),
        i_h  = $(this).find('img').attr('height'),
        r_i  = i_h / i_w,
        new_w,new_h,
        new_l,new_t;
    if (w_h==0) w_h = i_h
    if (r_w < r_i) {
      new_h  = w_h;
      new_w  = w_h / r_i;
    } else {
      new_h  = w_w * r_i;
      new_w  = w_w;
    }
    if(new_w > i_w || new_h > i_h) {
      new_w = i_w;
      new_h = i_h;
    }
    new_t = '0';
    if(new_h < w_h) {
      new_t = (w_h - new_h)/2;
    }
    if(!$(this).hasClass('noresize')) {
      $(this).find('img').css({ 'height': new_h, 'width': new_w, 'margin-top': new_t});
      $(this).find('.external-link').css({'width': new_w});
    }
    if($(this).find('.object_center').hasClass('object_show')) {
      var o_h = $(this).find('.object_center').attr('height');
          new_t = (w_h - o_h)/2;
          
      $(this).find('.object_center').parent().css({'margin-top':new_t});
    }
  });
}


function getParam(name,url) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( url );
  return ( results == null ) ? "" : results[1];
}

function str_replace(search, replace, subject) {
  return subject.split(search).join(replace);
}

function initflashlinks() {
  var flashlinks = $('.flashlink');
  
  flashlinks.unbind();
  flashlinks.bind('click',function() {
    var item = $(this).parent().parent();
    startflash(item);
    return false;
  });
}

function clearflash() {
  $('.flashlink').show();
  $('.flashinner').empty();
}

function setnewyoutubeobj(item,typ) {
  if(typ==1) {
    var search = 0,
        replace = 1;
  } else {
    var search = 1,
        replace = 2;
  }
  if(!item.find('.object_center').hasClass('flashwrapper') && item.find('.object_center').hasClass('object_show')) {
    var object = item.find('object.object_center'),
        objdiv = object.parent(),
        objecthtml = object.html();
    
    objecthtml = objecthtml.replace('autoplay='+search,'autoplay='+replace);
    object.html(objecthtml);
    
    var embedsrc = item.find('embed').attr('src');
    embedsrc = embedsrc.replace('play='+search,'play='+replace);
    object.find('embed').attr('src',embedsrc);
    
    var objdivHTML = objdiv.html();
    
    object.remove();
    objdiv.html(objdivHTML);
    
  }
}

function startflash(item) {
  if(item.find('.object_center').hasClass('flashwrapper')) {
    var flashlinks = item.find('.flashwrapper a').hide(),
        flashfile  = flashlinks.attr('href'),
        relcontainer = flashlinks.attr('rel'),
        flashcontainer = $('#'+relcontainer),
        flashmarkup = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="{width}" height="{height}"><param name="wmode" value="{wmode}" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="{path}" /><embed src="{path}" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="{width}" height="{height}" wmode="{wmode}"></embed></object>',
        pp_dimensions_width = getParam('width',flashfile),
        pp_dimensions_height = getParam('height',flashfile),
        wmode = "",
        flash_vars = "";
    
    flashmarkup = str_replace("{width}",pp_dimensions_width,flashmarkup);
    flashmarkup = str_replace("{height}",pp_dimensions_height,flashmarkup);
    flashmarkup = str_replace("{wmode}",wmode,flashmarkup);
    flashmarkup = str_replace("{path}",flashfile+'?'+flash_vars,flashmarkup);
    flashcontainer.empty().append(flashmarkup);
  }
}
