/*jslint white:false, maxerr:10000, nomen:false, browser:true, laxbreak:true, onevar:false */
/*global $ jQuery Base64 window*/

/* === General Functions */
var defaultMultiSelectOptions = {
  noneSelected: "Bitte auswählen",
  oneOrMoreSelected: '*',
  selectAllText: 'Alle auswählen',
  focusTimeout: false,
  showConfirmation: 'Schließen'
};
  
/*
 * Enables or disables an element (input) and its belonging label
 */
function enableDisable( element, enable ) {
  var label = $( 'label[for=' + element.attr( 'id' ) + ']' );
  if( enable ) {
    element.attr( 'disabled', false ); // the element itself
    label.removeClass( 'disabled' ); // its label
  } else {
    element.attr( 'disabled', true ); // the element itself
    label.addClass( 'disabled' ); // its label
  }
}

/*
 *  ajax setup to send correct mime-type
 */
jQuery.ajaxSetup({
  'beforeSend': function(xhr) {
    xhr.setRequestHeader("Accept", "text/javascript");
  }
});

jQuery.fn.fadeToggle = function(speed, easing, callback) {
  return this.animate({
    opacity: 'toggle'
  }, speed, easing, callback);
};

/*
 * takes a html string and replaces this with the thml of the element.
 * After that, it fades the element in if it's no visible already.
 */
jQuery.fn.htmlWithFadeIn = function(html) {
  $(this).html( html );
  if ($(this).is(":hidden")) {
    $(this).fadeIn();
  }
};



jQuery.fn.ajaxify = function( options ) {
  var self = $(this);

  // defined the options
  var defaultOptions = {
    type: 'GET', 
    target: self.attr( 'target' ) || self.attr( 'ajax_target' ),
    url: self.attr( 'href' ),
    ajaxifyForm: true, 
    scrollToTarget: false,
    fadeIn: true
  };
  options = jQuery.extend( {}, defaultOptions, options );

  // remove/overwrite unwanted attributes
  self.attr( 'href', '#' );
  self.removeAttr( "ajax_target" );
  
  self.click( function() {
    $.ajax({
      type: options['type'],
      url: options['url'],
      success: function(html) {
        var target = $( options['target'] );
        
        if( target ) {
          target.html( html );
          if ( target.is(":hidden") && options['fadeIn'] ) target.fadeIn();

          // show the containing close button
          target.find( '.buttonCloseWindow, .closeWindow' ).each( function() {
            if ( $(this).attr('href') ) $( this ).attr('href', '#');

            $(this).click( function() {
              $( target ).fadeOut();
            }).show();
          });

          // ajaxify the containing form
          if( options['ajaxifyForm'] ) target.find( 'form' ).addClass( 'ajaxify' );

          // move to the element and highlight it
          if( options['scrollToTarget'] ) {
            $.scrollTo( target, {
              duration: 500,
              offset: { 
                top: -25
              }
            });
          }
        }
      }
    });
    
    return false;
  });
}

// implement Array.indexOf for IE
// http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
if(!Array.indexOf) {
  Array.prototype.indexOf = function(obj){
    for(var i=0; i<this.length; i++){
      if(this[i] == obj) {
        return i;
      }
    }
    return -1;
  }
}

var referrerFromAnotherSite = function() {
  return document.referrer && document.referrer.indexOf(window.location.hostname + "/") == -1
}
var autohaus24_ca = $(document).getUrlParam("k");
if(autohaus24_ca || (!$.cookie('_autohaus24_data') && referrerFromAnotherSite())) {
  if(autohaus24_ca) {
    autohaus24_ca = Base64.decode(decodeURIComponent(autohaus24_ca));
    autohaus24_ca = autohaus24_ca.replace(";", "") // ; is the delimiter
  }
  var autohaus24_data = [ autohaus24_ca, document.referrer ];
  autohaus24_data = Base64.encode(autohaus24_data.join(";"));
  $.cookie('_autohaus24_data',autohaus24_data , {
    expires: 60,
    path: '/'
  });
}


/*!--------------------------------------------------------------------
 * JQuery Plugin: "LinkListToSelect"
 * by: Michael Raidel
 *
 * Description: Replace a list of links with a select. The element without a link is considered the currently active and is selected
 * Usage Example: $(element).linkListToSelect();
--------------------------------------------------------------------*/

$.fn.linkListToSelect = function() {
  list = $(this).find('li').map( function() {
    anchor = $(this).find("a");
    if(anchor.length) {
      return('<option value="' + anchor.attr("href") + '">' + anchor.html() + '</option>');
    } else {
      return('<option value="" selected="selected">' + $(this).html() + '</option>');
    }
  })

  form = $('<form method="get" class="link-select"><select>' + jQuery.makeArray(list).join("\n") + '</select></form>');
  $(this).replaceWith(form);

  $('form.link-select select').change( function() {
    if(this.value) {
      window.location.href = this.value;
    }
  });
  
  return this;
};


/**
 * jQuery IVW extension with randomizer
 *
 * Version: 0.0.1
 * Requires jQuery 1.2.6+
 *
 * by Rudolf Schmidt
 *
 * create a hidden field element and give the IVW url to it as value:
 * <input type="hidden" value="http://client.ivwbox.de/cgi-bin/ivw/CP/IDENTIFIER" name="ivw_client" id="ivw_client"/>
 *
 * $( "#ivw_client" ).toIvwTag();
 * => <img width="1" height="1" id="ivw_client" src="http://client.ivwbox.de/cgi-bin/ivw/CP/IDENTIFIER;?=6347285960" alt=""/>
 *
 **/
jQuery.fn.toIvwTag = function() {
  var self = $(this);

  var random = new Array(10); // array with 10 elements
  for( i = 0; i < random.length; i++) random[i] = Math.floor( Math.random()*10 ) // fill array with random digits
  var src = self.val() + ";?d=" + random.join("") // generate the image source

  html = '<img width="1" height="1" alt="" src="' + src + '" id="' + self.attr("id") + '" />';
  $(self).after(html).remove(); // insert after current element and then remove existing
};

/*
 * An instant tooltip jQuery extension
 *
 * Version: 0.0.1
 *
 * by Rudolf Schmidt
 *
 * Takes a few options, see the 'default options' section
 *
 * <div class="tooltip">
 *  <div class="tooltip-wrapper">
 *    <div class="tooltip-title"></div>
 *    <div class="tooltip-content"></div>
 *  </div>
 *  <div class="tooltip-tip"></div>
 * </div>
 *
 */
if(jQuery) (function($){

  $.extend($.fn, {
    instaTip: function( o ) {
      if( !o ) var o = {};

      // default options
      if( o.title == undefined ) o.title = "";
      if( o.content == undefined ) o.content = "";
      if( o.target == undefined ) o.target = $(this);
      if( o.button == undefined ) o.button = 'OK';

      // build the template
      var html = '<div class="tooltip">' +
      '  <div class="tooltip-wrapper">' +
      '    <div class="tooltip-title">'+ o.title +'</div>' +
      '    <div class="tooltip-content">'+ o.content +'</div>' +
      '    <div class="tooltip-button"><a>' + o.button + '</a></div>' +
      '  </div>' +
      '  <canvas width="14" height="14"></canvas>' +
      '</div>';

      // remove old tooltips in case we already rendered any
      $( ".tooltip" ).remove();

      // append the tooltip
      $( o.target ).after( html );
      var currentTooltip = $( o.target ).next( ".tooltip" );

      // position the tooltip
      var targetPos = o.target.position();
      currentTooltip.css({
        left: Math.floor( targetPos.left ),
        top: Math.floor( targetPos.top - currentTooltip.outerHeight() )
      });

      // apply close button behaviour
      currentTooltip.find( ".tooltip-button a" ).click( function() {
        $( ".tooltip" ).remove();
      });

      // draw the tip on the canvas -- HTML 5 woohoo ;-)
      var canvas = currentTooltip.find( "canvas" ).get( 0 );
      if( canvas && canvas.getContext ) {
        var context = canvas.getContext( '2d' );
        context.fillStyle = currentTooltip.find( '.tooltip-wrapper' ).css( 'border-left-color' );

        context.beginPath();
        context.moveTo(0, 0);
        context.lineTo(14, 0);
        context.lineTo(0, 14);

        context.fill();
      }

    },

    instaTipWithPrepare: function(options) {
      var defaultOptions = {
        link: '[info]',
        title: 'Info'
      };
      options = jQuery.extend( {}, defaultOptions, options );

      $(this).each( function() {
        html = '<a href="#" class="descriptionTip">' + options['link'] + '</a>';
        $(this).after( html );
        
        var link = $(this).next( "a.descriptionTip" );
        link.data( "description", $(this).html() );
        $(this).remove();

        link.click( function() {
          $(this).instaTip({
            title: options['title'],
            content: $(this).data( "description" )
          });

          return false;
        });
      });
    }    
  });

})(jQuery);

//animation function for the backend 'news' menu title
function animateNewsTitle(){
    var aLilnk = $('li.last a.urgent:first');
    aLilnk.animate({fontSize: 17},{duration:500}).animate({fontSize: 16},{duration:500});
    window.setTimeout("animateNewsTitle()", 10);
}

/* === jQuery setup */
$( document ).ready( function() {

  /*
   * Every link with the class 'ajaxify' with be submitted as an ajax request
   */
  $( "a.ajaxify" ).livequery( function() {
    $(this).ajaxify();
  });

  $( "a.link-disabled" ).livequery( function() {
    $(this).attr('href', '#');
  });

  $( "a.ajaxify-with-scroll" ).livequery( function() {
    $(this).ajaxify({
      scrollToTarget: true
    });
  });

  /*
   * Every form with the class 'ajaxify' with be submitted as an ajax request
   */
  $( "form.ajaxify" ).livequery( function() {
    var form = $(this);
    form.ajaxForm({
      dataType: 'script',
      beforeSend: function() {
        form.find( "input[name=format]" ).attr("value","js");
        form.find( ":submit" ).attr("disabled", "true"); // disable submit
        form.find( ".spinner" ).show();
      },
      complete: function() {
        form.find( ":submit" ).removeAttr("disabled"); // enable submit
        form.find( ".spinner" ).hide();
      }
    });
  });

  /*
   * This takes care that every button with the class ajaxify add the class
   * ajaxify to its wrapping form.
   */
  $('input.ajaxify').livequery( function() {
    $(this.form).addClass( 'ajaxify' );
  });

  /*
   * This functions defines the behaviour for the conversation documentation
   * We apply a toggle method on the preview and the expanded view.
   */
  $( '.expandable' ).livequery( function() {
    var expandable = $(this);

    expandable.find( '.clickable' ).click( function() {
      expandable.children().toggle();

      if( $(this).is( "a" ) ) {
        $.ajax({
          type: "GET",
          url: $(this).attr( "href" )
        });
        return false;
      }
    });
  });

  /*
   * This functions defines the behaviour for the scroll panels
   */
  $( 'div.scroll-box' ).livequery( function() {
    var box = $(this);
    var scrollerBox = box.find( '#historyScroller' );

    // set-up/reset the scroller altogether
    box.find( '.scroll-panel li' ).css( "width", box.width() ); // update widths
    box.find( '.scroll-nav a:first' ).addClass( 'active' );
    scrollerBox.scrollTo( 'li:first', 0 );

    // add click behaviour
    box.find( '.scroll-nav a' ).click( function() {
      var target = scrollerBox.find( $(this).attr('id') );
      box.find( '.scroll-nav a' ).removeClass( 'active' ); // remove active classes
      $(this).addClass( 'active' ); // addd active class to current
      scrollerBox.scrollTo( target, 250 ); // scroll to designated element
      return false;
    });
  });

  /*
   *
   */
  $( 'a.ajaxify-with-current' ).livequery("click", function() {
    var current_row = $(this).parent().parent();
    var target = $( $(this).attr( 'ajax_target' ) || "#boxCurrentContent" );

    $.ajax({
      type: 'GET',
      url: $( this ).attr( 'href' ),
      success: function(html) {
        target.html( html );

        // remove all highlightings
        current_row.parent().find( 'tr.rowActive' ).removeClass( 'rowActive' );

        // add the active to the current row
        current_row.addClass('rowActive');
      }
    });

    return false;
  });


  /*
   * Generic way to have links that toggle specific contents on and off
   */
  $( ".toggleBox .toggleLinks a" ).live( "click", function() {
    var active = $(this).hasClass( "active" );

    $( ".toggleBox .toggleLinks a" ).removeClass( "active" );
    $( ".toggleBox .toggleContents" ).children().hide();

    if ( !active ) {
      $(this).addClass( "active" );
      $( ".toggleBox .toggleContents #" + $(this).attr('id') + "Content" ).show();
    }
  });

    //animation function call for the backend 'news' menu title
    if($('li.last a.urgent').length){
        animateNewsTitle();
    }

});
