/**
 * This jQuery plugin creates an animated slider with the child elements as frames.
 
 simpleslider
    create/modify/register required markup
        wrapper - simply wraps all elements, no functionality
        boundary - encloses all children elements, shows only a single frame
        container - holds all frames, distrubutes them in correct order/position
        frames
    create requested controls: prev/next, navigation
    execute transition: slide (easing, direction), fade, cut    
    set timer for automatic transition

 * @author Justin Jones (justin(at)jstnjns(dot)com) @version 1.4

 */
(function($){
    $.fn.simpleslider = function(settings) {
        
        var defaults = {
            transition        : 'fade', // cut, fade
            easing            : 'swing', // linear
            direction        : 'horizontal', // for 'slide' style transition
            speed            : 500, // for 'slide' and 'fade' style transitions
            auto            : false,
            interval        : 2000, // pause between transitions if 'auto' is set to TRUE
            hoverPause        : true,
            navigation        : true,
            buttons            : true,
            prevText        : 'Previous',
            nextText        : 'Next',
            loop            : true
        };
        
        settings = $.extend({}, defaults, settings); 
        
        $(this).each(function() {
            // ----------------------------------------------------------------|| Setting Vars ||
            var $this = $(this),
            $frames,
            $wrapper,
            $boundary,
            $container,
            $prev,
            $next,
            $navigation,
            boundaryWidth,
            boundaryHeight,
            frameWidth,
            frameHeight,
            frameCount,
            currentFrame = 1,
            auto,
            
            _init = function() {
                                    
                $frames            = $this
                                    .children()
                                    .addClass('slider-slide');
                            
                // Get values and dimensions necessary for more advanced structure
                frameCount        = $frames.length;
                
                frameWidth        = 0;
                frameHeight        = 0;
                
                boundaryWidth    = 0;
                boundaryHeight    = 0;
                
                // Set up the basic physical structure of the slider
                $wrapper        = $this
                                    .wrap('<div />')
                                        .parent()
                                        .addClass('slider-wrapper');
                                
                $boundary        = $this
                                    .wrap('<div />')
                                        .parent()
                                            .addClass('slider-boundary');
                                    
                $container        = $this
                                    .addClass('slider-container');
                                
                if(settings.buttons) {
                                        $prev        = $('<a />')
                                    .addClass('slider-control-prev')
                                    .text(settings.prevText)
                                    .click(function(e){ 
                                        e.preventDefault()
                                        
                                        if(!$this.hasClass('disabled')) {
                                            _transition(currentFrame - 1);
                                        }
                                     });
                                
                    $next        = $('<a />')
                                    .addClass('slider-control-next')
                                    .text(settings.nextText)
                                    .click(function(e){
                                        e.preventDefault();
                                        
                                        if(!$this.hasClass('disabled')) {
                                            _transition(currentFrame + 1);
                                        }
                                    });
                                
                    $wrapper
                        .prepend($prev)
                        .append($next);
                }
                
                if(settings.navigation) {
                    $navigation = $('<ol />')
                                    .addClass('slider-control-navigation');
                                    
                    $frames.each(function(i, frame) {
                        var $tab = $('<li />')
                                        .addClass('slider-control-navigation-tab')
                                            .append('<span />').find('span')
                                                .addClass('number')
                                                .text(i + 1)
                                                .end()
                                        .click(function(e) {
                                            e.preventDefault();
                                            
                                            if((i+1) != currentFrame) {
                                                _transition(i+1);
                                                console.log(i+1);
                                            }
                                        });
                                        
                        if(i == 0) {
                            $tab
                                .addClass('current');
                        }
                        
                        if($(frame).attr('title')) {
                            $('<span />')
                                .addClass('title')
                                .text($(frame).attr('title'))
                                .appendTo($tab)
                        }
                                        
                        $navigation
                            .append($tab);
                    });
                                    
                    $wrapper
                        .append($navigation);
                }
                
                // if(settings.navigation) {
                //     var tab = {};
                //     
                //     $navigation        = $('<ol />')
                //                         .addClass('slider-control-navigation');
                //                         
                //     $frames.each(function(i) {
                //         tab[i] = i;
                //     })
                // }
                
                $frames.each(function() {
                    if($(this).width() > frameWidth) frameWidth = $(this).width(); // Get widest frame's width
                    if($(this).height() > frameHeight) frameHeight = $(this).height(); // Get tallest frame's height
                    
                    if($(this).outerWidth(true) > boundaryWidth) boundaryWidth = $(this).outerWidth(true); // Get widest frame's outer width
                    if($(this).outerHeight(true) > boundaryHeight) boundaryHeight = $(this).outerHeight(true); // Get tallest frame's outer height
                });
                
                // Set dimensions on elements that need sizing
                $frames.css({
                    width    : frameWidth,
                    height    : frameHeight,
                    float    : 'left'
                });
                
                if(settings.transition == 'slide') {
                    if(settings.direction == 'horizontal') {
                        $container.css({
                            width    : boundaryWidth * frameCount,
                            height    : boundaryHeight,
                            overflow: 'hidden'
                        });
                    } else {
                        $container.css({
                            width    : boundaryWidth,
                            height    : boundaryHeight * frameCount,
                        overflow: 'hidden'
                        });
                    }
                } else {
                    $container.css({
                        position: 'relative',
                        width    : boundaryWidth,
                        height    : boundaryHeight
                    });
                    
                    $frames
                        .css({
                            position: 'absolute',
                            left    : 0,
                            top        : 0
                        })
                        .hide();
                    
                    $frames.eq(0)
                        .show();
                }
                    
                $boundary.css({
                    width    : boundaryWidth,
                    height    : boundaryHeight,
                    overflow: 'hidden'
                });
                
                if(settings.auto) {
                    _startTimer(settings.interval);
                    
                    if(settings.hoverPause) {
                        $wrapper.hover(function() {
                            _stopTimer();
                        }, function() {
                            _startTimer();
                        });
                    }
                }
                
            },

            // Transitions to frame
            _transition = function(toFrame) {
                
                // LOOPING
                // If out of bounds, send to the opposite side
                if(settings.loop) {
                    if(toFrame > frameCount) {
                        _transition(1);
                        return;
                    } else if(toFrame <= 0) {
                        _transition(frameCount);
                        return;
                    }
                    
                // NON-LOOPING
                // If out of bounds, do nothing
                } else {
                    if(toFrame > frameCount || toFrame <= 0) return;
                }
                
                switch(settings.transition) {
                    case 'slide':
                        var diff = toFrame - currentFrame;
                        _slide(diff);
                        break;
                        
                    case 'fade':
                        _fade(toFrame);
                        break;
                        
                    default:
                        _cut(toFrame);
                        break;
                }
                
                currentFrame = toFrame;
                
                /*
                    TODO get the button disabling / enabling and looping to work
                */
                if(!settings.loop && settings.buttons) {
                    // Sets 'previous' button to disabled if on first frame
                    if(currentFrame == 1) {
                        $prev.addClass('disabled');
                    } else {
                        $prev.removeClass('disabled');
                    }
                        
                    // Sets 'next' button to disabled if on last frame
                    if(currentFrame == frameCount) {
                        $next.addClass('disabled');
                    } else {
                        $next.removeClass('disabled');;
                    }
                }
                
                if(settings.navigation) {
                    $navigation
                        .children()
                            .removeClass('current')
                            .eq(currentFrame - 1)
                                .addClass('current');
                            
                    console.log(currentFrame - 1);
                }
                
            },
            
            _slide = function(frames) {
                
                if(settings.direction == 'horizontal') {
                    $this.stop().animate({
                        marginLeft: (-1) * (currentFrame + frames - 1) * boundaryWidth + 'px'
                    }, settings.speed, settings.easing);
                } else if(settings.direction == 'vertical') {
                    $this.stop().animate({
                        marginTop: (-1) * (currentFrame + frames - 1) * boundaryHeight + 'px'
                    }, settings.speed, settings.easing);
                }
                
            },
            
            _fade = function(toFrame) {
                
                $frames.eq(toFrame - 1)
                    .fadeIn(settings.speed);
                    
                $frames.eq(currentFrame - 1)
                    .fadeOut(settings.speed);
                
            },
            
            _cut = function(toFrame) {
                
                $frames.eq(toFrame - 1)
                    .show();
                    
                $frames.eq(currentFrame - 1)
                    .hide();
                    
            },

            _startTimer = function() {
                auto = setInterval(function() {
                    _transition(currentFrame + 1);
                }, settings.interval);
            },
            
            _stopTimer = function() {
                if(settings.auto !== false){
                    clearInterval(auto);
                }
            }
            
            _init();
        });
    }
})(jQuery);


/* IE6nomore
------------------------------------------------------------------------------------------------ */

$.IE6nomore = function() {

    if(!$('#ie6nomore').length)
        return;

    $('#ie6nomore').css({
        'left'      : 0,
        'top'       : 0,
        'bottom'    : 0,
        'right'     : 0,
        'position'  : 'absolute',
        'z-index'   : 9999
    });

};

/* Swap image
------------------------------------------------------------------------------------------------ */

function swapImage(element, newimage) {

    var oldsrc      = element.src;
    element.src     = newimage;

    if (!element.onmouseout) {
        element.onmouseout = function() {
            swapImage(this, oldsrc);
        }
    }

}


/* Spam protection
------------------------------------------------------------------------------------------------ */

function getAdr(prefix, postfix, text) {
    document.write('<a href="mailto:' + prefix + '@' + postfix + '">' + (text ? text.replace(/&quot;/g, '"').replace(/%EMAIL%/, prefix + '@' + postfix) : prefix + '@' + postfix) + '</a>');
}


/* Als ganzes Klickbar
------------------------------------------------------------------------------------------------ */

    function clicklinks() {
        $('.downloads td').css({cursor: 'pointer'}).click(function() {
            if ($('a', this).attr('class').indexOf('popup') > -1) {
                $('a', this).click();
            } else {
                if ($('a', this).attr('target') == '_blank') {
                    window.open($('a', this).attr('href'));
                } else {
                    window.location = $('a', this).attr('href');
                }
            }
        });        
    }

/*!
* jQCloud Plugin for jQuery
*
* Version 0.1.8
*
* Copyright 2011, Luca Ongaro
* Licensed under the MIT license.
*
* Date: Fri Apr 8 10:24:15 +0100 2011
*/
 
(function( $ ){
  $.fn.jQCloud = function(word_array, callback_function) {
    // Reference to the container element
    var $this = this;
    // Reference to the ID of the container element
    var container_id = $this.attr('id');

    // Add the "jqcloud" class to the container for easy CSS styling
    $this.addClass("jqcloud");

    var drawWordCloud = function() {
      // Helper function to test if an element overlaps others
      var hitTest = function(elem, other_elems){
        // Pairwise overlap detection
        var overlapping = function(a, b){
          if (Math.abs(2.0*a.offsetLeft + a.offsetWidth - 2.0*b.offsetLeft - b.offsetWidth) < a.offsetWidth + b.offsetWidth) {
            if (Math.abs(2.0*a.offsetTop + a.offsetHeight - 2.0*b.offsetTop - b.offsetHeight) < a.offsetHeight + b.offsetHeight) {
              return true;
            }
          }
          return false;
        };
        var i = 0;
        // Check elements for overlap one by one, stop and return false as soon as an overlap is found
        for(i = 0; i < other_elems.length; i++) {
          if (overlapping(elem, other_elems[i])) {
            return true;
          }
        }
        return false;
      };

      // Make sure every weight is a number before sorting
      for (i = 0; i < word_array.length; i++) {
        word_array[i].weight = parseFloat(word_array[i].weight, 10);
      }
      
      // Sort word_array from the word with the highest weight to the one with the lowest
      word_array.sort(function(a, b) { if (a.weight < b.weight) {return 1;} else if (a.weight > b.weight) {return -1;} else {return 0;} });

      var step = 2.0;
      var already_placed_words = [];
      var aspect_ratio = $this.width() / $this.height();
      var origin_x = $this.width() / 2.0;
      var origin_y = $this.height() / 2.0;

      // Move each word in spiral until it finds a suitable empty place
      $.each(word_array, function(index, word) {

        // Define the ID attribute of the span that will wrap the word, and the associated jQuery selector string
        var word_id = container_id + "_word_" + index;
        var word_selector = "#" + word_id;

        var angle = 6.28 * Math.random();
        var radius = 0.0;

        // Linearly map the original weight to a discrete scale from 1 to 10
        var weight = Math.round((word.weight - word_array[word_array.length - 1].weight)/(word_array[0].weight - word_array[word_array.length - 1].weight) * 9.0) + 1;

        var inner_html = word.url !== undefined ? "<a href='" + encodeURI(word.url).replace(/'/g, "%27") + "'>" + word.text + "</a>" : word.text;
        $this.append("<span id='" + word_id + "' class='w" + weight + "' title='" + (word.title || "") + "'>" + inner_html + "</span>");

        var width = $(word_selector).width();
        var height = $(word_selector).height();
        var left = origin_x - width / 2.0;
        var top = origin_y - height / 2.0;
        $(word_selector).css("position", "absolute");
        $(word_selector).css("left", left + "px");
        $(word_selector).css("top", top + "px");

        while(hitTest(document.getElementById(word_id), already_placed_words)) {
          radius += step;
          angle += (index % 2 === 0 ? 1 : -1)*step;

          left = origin_x - (width / 2.0) + (radius*Math.cos(angle)) * aspect_ratio;
          top = origin_y + radius*Math.sin(angle) - (height / 2.0);

          $(word_selector).css('left', left + "px");
          $(word_selector).css('top', top + "px");
        }
        already_placed_words.push(document.getElementById(word_id));
      });

      if (typeof callback_function === 'function') {
        callback_function.call(this);
      }
    };

    // Delay execution so that the browser can render the page before the computatively intensive word cloud drawing
    setTimeout(function(){drawWordCloud();}, 100);
    return this;
  };
})(jQuery);


/* DOM
------------------------------------------------------------------------------------------------ */

$(document).ready(function() { 
    // IE6nomore

    $.IE6nomore();
    
    // Search
    $('#search input[type=text]').placeholder();

    // Menu
    $('#nav').menu({
        'removeTitle' : false
    });


if (!$('.startpage').length) { 

        // als ganzes Klickbar
        clicklinks();
    
        // Forms
        $('textarea').autogrow();

            
        // Datepicker
        $('input.date').datepicker({
            'hideInput' : true
        });
    
        // News object
        $('#news_selection').createOnchangeSelect({
            'label' : '#news_selection h3'
        });

        // DATEV Unternehmen online
        $.datev_uo();
}

    // Popup plugin
    $('.popup').popup();

    // Slider in Navigation
    $(function() {
        $('.trialogtv_sliderul').simpleslider({
            transition : 'cut',
            easing : 'swing',
            direction : 'horizontal',
            speed : 500,
            auto : true,
            interval : 2500,
            hoverPause : true,
            navigation : false,
            buttons : true,
            prevText  : 'Previous',
            nextText : 'Next',
            loop  : true
        });
    });

    // Navigations Link UID Nr Check
    $('#nav_' + uid_check_id).click(function() {
        window.open(uid_check_url);
        return false;
    });

    $('li#subnav_' + uid_check_id).click(function() {
        window.open(uid_check_url);
        return false;
    });
    
    $('.link.uid_check').click(function() {
        window.open(uid_check_url);
        return false;
    });

});

