curl([
  'js!'+window.res_path+'/js/libs/history.js/history.js',
  'js!'+window.res_path+'/js/libs/history.js/history.adapter.jquery.js'
]).then(function () {
  $(function () {
    if ( ! window.History.enabled || typeof(window.slider) !== 'undefined') // if this is in an iframe we don't want to do anything here.
      return false;

    var $styles = $('link[rel="stylesheet"]');
    var slider = {
      
      sliding: false,
      
      current: {
        skin: $styles.filter('[href*="css/skin_"]'),
        brand: window.brand,
        height: $('#content_wrapper > div').height()
      },

      previous: {
        brand: null
      },

      init: function init () {
        slider.skinBasePath = slider.current.skin.attr('href').match(/^[^"]*skin_/)[0];
        $('#content_wrapper').height(slider.current.height).css('overflow', 'hidden');
        
        $(window).bind('statechange', slider.stateHandler);
        /* TODO: Remove this is the slider-fb-like-issue is fixed */
        /*$('.nav_brand_ul_wrapper > ul a').live('click', slider.clickHandler);*/
        
        slider.heightInterval = setInterval(function () {
          slider.checkHeight($('.content.brand_'+slider.current.brand));
        }, 500);
      },

      stateHandler: function stateHandler () {
        var state = History.getState();
        slider.sliding = true;
        $.ajax({
          type: 'GET',
          url: state.url+'?'+(+new Date()),
          dataType: "text",
          error: console.dir,
          success: slider.parsePage
        });
      },

      clickHandler: function clickHandler (e) { 
        e.preventDefault();
        History.pushState({}, false, this.href);
      },

      parsePage: function parsePage (html) {
        var xmlError;
        try {
          var xml = $.parseXML(html),
              $context = $(xml),
              new_brand = $context.find('link[href*="css/skin_"]').attr('href').match(/css\/skin_([\w]*).css$/)[1],
              new_header = $context.find('#header_wrapper > div.header_outer').html(),
              new_content = $context.find('#content_wrapper > div.content').html()
              new_bg = $context.find('body').attr('style');
          xmlError = $context.find('div').text().match(/^error[^\n]*/);
        } catch (e) {
          xmlError = true;
        } 

        if (xmlError) {
          console.log('SLIDER CONTENT FAILED: '+xmlError);
          window.location.reload();
        }
        
        slider.current.fromRight = new_brand === slider.previous.brand;
        if (slider.current.fromRight && slider.previous.fromRight) {
          slider.current.fromRight = false;
        }
        slider.previous.fromRight = slider.current.fromRight;
        
        slider.addSkin(new_brand);
        slider.changeBackground(new_bg)
        slider.changeBrand(new_brand);

        slider.slide(new_header, new_content);
      },

      changeBrand: function changeBrand (new_brand) {
        if (slider.current.brand !== slider.previous.brand) {
          slider.removePrevious();
          slider.previous.brand = slider.current.brand;
          slider.current.brand = new_brand;
          $('body').addClass(new_brand);
        }
      },

      removePrevious: function removePrevious () {
        $('.brand_'+slider.previous.brand+' .widget_wrapper:not(.slided_new)').each(function () {
          var widget = $(this).widget();
          if (widget)
            widget.destroy();
        }).remove();
        $('div.brand_'+slider.previous.brand+':not(.slided_new)').remove();
        $('.slided_new').removeClass('slided_new');
        
        if (slider.previous.brand !== slider.current.brand) {
          $('body').removeClass(slider.previous.brand);
        }
      },

      slide: function slide(header, content) {
        $('.nav_main.nav_level_0').css('visibility', 'hidden'); // Dont let the Navi freak out dog!
        var width = 992,
            startXPosition = slider.current.fromRight ? '+' : '-',
            xDirection = slider.current.fromRight ? '-' : '+';
        $(document).trigger('sliding');
        
        var $content = $('<div class="content slided_new brand_'+slider.current.brand+'"></div>')
                          .appendTo('#content_wrapper')
                          .html(content)
                          .css('left', startXPosition+width+'px');
                          
        $('<div class="header_outer slided_new brand_'+slider.current.brand+'"></div>')
          .appendTo('#header_wrapper')
          .html(header)
          .css('left', startXPosition+width+'px');
          
        var $new_context = $('body > div > div.brand_'+slider.current.brand+'.slided_new');

        slider.checkHeight($content);
        slider.rewriteLinks($new_context);
        
        setTimeout(function () {
          if (slider.current.brand === 'mcb' || slider.previous.brand === 'mcb') {
            $('#userbox_mcb_link_logo_mcb, #userbox_mcb_link_logo_brand').fadeToggle(800);
          }
          $('div.content, div.header_outer').animate({
            'left': xDirection+'='+width+'px'
          }, {
            duration: 800,
            complete: function () {
              if (slider.sliding === true) {
                slider.removePrevious();
                slider.sliding = false;
                slider.checkHeight($content, true);
                $(document).trigger('slided_or_ready', [$new_context]);
              }
            }
          });
        }, 200);
      },

      checkHeight: function checkHeight ($content, force) {
        var new_height = $content.height();
        if (new_height > slider.current.height || force === true) {
          $('#content_wrapper').height(new_height);
        }
      },
      
      rewriteLinks: function rewriteLinks ($context) {
        if ( ! History.emulated.pushState)
          return true; // relative links are already correct thanks to pushState :)
        
        var path = '../'+History.getState().url.match(/\/([^\/]*)\/[^\/]*\.html$/)[1]+'/';
        $('a[href]', $context).each(function () {
          if (this.href !== 'javascript:' && ! $(this).hasClass('brand_select_link')) {
            var isRelative = $(this).attr('href').match(/^[^\/]*?\.html/);
            if (isRelative) {
              $(this).attr('href', path+isRelative[0]);
            }
          }
        });
      },

      addSkin: function changeSkin (skin) {
        var new_href = slider.skinBasePath+skin+'.css';

        if ($('link[href="'+new_href+'"]').length === 0) {
          slider.current.skin = $('<link/>', {
            rel: 'stylesheet',
            type: 'text/css',
            href: new_href
          }).appendTo('head');
        }
      },
      
      changeBackground: function changeBackground (style) {
        $('body').attr('style', style);
      }
    };
    if(window.location.hostname == 'www.meincokebonus.de') {
      window.slider = slider;
      /*slider.init();*/
    }
  });
});
