jQuery.extend({
   getUrlVars: function($){
      var vars = {hostname: '', pathname: [], pathinfo: [], params: [], protokol : ''};
      vars.protocol = window.location.protocol;
      vars.hostname = window.location.hostname;
      vars.pathname = window.location.pathname;
      vars.pathinfo = window.location.pathname.split('/');
      var hash;
      var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
      for(var i = 0; i < hashes.length; i++) {
         hash = hashes[i].split('=');
         vars.params.push(hash[0]);
         vars.params[hash[0]] = hash[1];
      }
      return vars;
   },
   getUrlVar: function(name){
      return $.getUrlVars()[name];
   }
});

(function( $ ){
  var ctx = {};
  var methods = {
    init : function( options ) {
        ctx.me  = this;
        ctx.$me = $(this);

        ctx.$listContainer    = $( '.innovationslist_wrapper', ctx.$me );
        ctx.$list             = $( 'ul', ctx.$listContainer );
        ctx.$listitems        = $( 'a', ctx.$list );

        ctx.$display          = $( '.innovationsdisplay' , ctx.$me );
        ctx.$displayContainer = $( '.innovationsdisplay_content' , ctx.$me );

        ctx.cfg = {
            filter_result:  '#page_body_main_content > div',
            listOrigHeight:      ctx.$listContainer.height(),
            listOrigHeight_lock: Math.min(ctx.$listContainer.height(), ctx.$list.height()),
            scrollLock: ctx.$listContainer.height() > ctx.$list.height(),
            ytravel:        '130%',
            takeoverFactor: 0.9
        };

        ctx.timers ={};

        if(options) {
            // dieser Selektor bestimmt, welcher Teil der geladenen Seite angezeigt wird
            $.extend(ctx.cfg, options);
        }

        ctx.$listitems.click(function(){return false;});
        ctx.$listitems.click(methods.loadItem);
        ctx.$listContainer.jparallax({
            xparallax:          false,
            triggerExposesEdges:true,
            takeoverFactor:     ctx.cfg.takeoverFactor,
            ytravel:            ctx.cfg.ytravel,
            mouseActiveOutside: true
        },methods.jparallax);
        ctx.$listContainer.mouseover(methods.showlist);
        ctx.$listContainer.bind('mouseleave',methods.hidelist);

        window.setTimeout(function(){
            var allVars = $.getUrlVars();
            if (allVars.pathinfo[2] != undefined
               && allVars.pathinfo[2].substr(0, 14)  == "innovation-kw-") {
               ctx.$listitems.each(function () {
                  var pattern = new RegExp(allVars.pathinfo[2]);
                  if (pattern.exec($(this).attr("href")) != null) {
                    methods.loadItem($(this).attr("href"));
                    //$(this).click();
                    ctx.$listContainer.trigger('mouseleave');
                  }
               });
               
            } else {
               ctx.$listitems.eq(ctx.$listitems.length-1).click();
               ctx.$listContainer.trigger('mouseleave');
            }
        },500);
    },

    jparallax: {}, // platzhalter für funktionen die aus jparallax rausgezogen werden, sog. delegates
    loadItem : function ( href ) {
        var finalize = false;
        if (this.href == undefined) {
            var url = href+' '+ctx.cfg.filter_result;
            var finalize = true;
        } else {
            var url = this.href+' '+ctx.cfg.filter_result;
        }
        methods.collapseItem();
        ctx.$listitems.removeClass('active');
        $(this).addClass('active');

        $.get(this.href, function (data) {
           var image = $(data).find("#page_head_title_content .title_img").attr("src");
           if (typeof(image) == "undefined")
              image = default_background_image;
           $("#page_head_alternate_head .innovations_teaser .background_image img").attr("src", image);
        });
        //console.dir(finalize);
        ctx.$displayContainer.load( url, function() {
            ctx.cfg.textreplacer.replaceText(ctx.cfg.textreplacerItemsName);
            // alte expand- und collapselinks entfernen
            $('.expandlink',ctx.$display).remove();
            $('.collapselink',ctx.$display).remove();

            // erster extra_link vergrößert
            $('.extra_link',ctx.$displayContainer).eq(0)
              .click(methods.expandItem)
              .addClass('expandlink')
              .appendTo(ctx.$display);

            // zweiter extra_link bekommt noch einen hotspot zum verkleinern des layers
            $('<div title="schliessen" class="collapselink_hotspot"></div>').appendTo(  // schliessen-hotspot anhängen an
              $('.extra_link',ctx.$displayContainer)                                    // ..den extra link
              .eq(0)                                                                    // ..und zwar den ersten
              .wrap('<div ></div>')                                                     // ..eingepackt in ein wrapper div
              .addClass('collapselink')                                                 // ..das die klasse 'collapselink' bekommt.
              .appendTo(ctx.$display)                                                   // Den eingepackten link holen wir aus dem richtext raus und hängen ihn ins display-div
              .hide()                                                                   // erstmal wollen wir das wrapper-div nicht sehen
              .find('a').append('<span class="decorator">&nbsp;</span>')                // der link da drinnen bekommt noch einen decorator angehängt
              .parent()                                                                 // rückgabe soll das elternelement des a-elements sein
            )
            .click(methods.collapseItem);                                               // action des hotspot-divs

            // zweiten textblock ausblenden
            $('.content_object',ctx.$displayContainer).eq(1).hide();
            $('.content_object',ctx.$displayContainer).eq(1).find('.img_container').addClass('secondpicture');

            if (finalize) {
               $(".innovationsdisplay .expandlink a").click();
            }
        });

        return false;
    },
    expandItem: function( ) {
        ctx.$display.addClass('innovationsdisplay_expanded');
        $('.expandlink',ctx.$display).hide();
        $('.collapselink',ctx.$display).show();
        $('.scrollable_dock_container').hide();
        $('.content_object',ctx.$displayContainer).eq(1).show();
        return false;
    },
    collapseItem: function() {
        ctx.$display.removeClass('innovationsdisplay_expanded');
        $('.expandlink',ctx.$display).show();
        $('.collapselink',ctx.$display).hide();
        $('.scrollable_dock_container').show();
        $('.content_object',ctx.$displayContainer).eq(1).hide();

    },
    showlist: function(){
        if( ctx.timers.hidelist )
            window.clearTimeout(ctx.timers.hidelist);
        ctx.$listContainer.height(ctx.cfg.listOrigHeight);
        ctx.$listContainer.trigger("resize",{
            ytravel:ctx.cfg.ytravel,
            takeoverFactor: ctx.cfg.takeoverFactor
        });
        ctx.$listContainer.height(ctx.cfg.listOrigHeight_lock);
        ctx.cfg.scrollLock ? methods.jparallax.suspend() : methods.jparallax.resume();
            
    },

    hidelist: function(){
        if( ctx.timers.hidelist )
            window.clearTimeout(ctx.timers.hidelist);

        var activeItem = $('.active',ctx.$list).eq(0);
        var ref = '#'+activeItem.attr('name');
        ctx.$listContainer.trigger("jparallax", [ref]);
        ctx.timers.hidelist = window.setTimeout(function() {
            ctx.hidelistTimer = false;
            methods.jparallax.suspend();
            ctx.$listContainer.animate({
                height:activeItem.outerHeight()
            },300,function(){
                ctx.$listContainer.trigger("resize",{
                    ytravel:'100%',
                    takeoverFactor: 0
                });
                ctx.$listContainer.trigger("jparallax", [ref]);
            });
        },1000);
    }
  };

  $.fn.vda_innovations = function( method ) {
    if ( methods[method] ) {
      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.vda_innovations' );
    }
  };
})( jQuery );

var default_background_image = null;
$(document).ready(function() {
   default_background_image = $("#page_head_alternate_head .innovations_teaser .background_image img").attr("src");
});
