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

    //die function handles the contentswitches
    $.fn.pager();

    //references slider
    $('#slider').aspediaSlider();

    //menu show / hide handler
    $('#header > .headbar').bind('mouseenter mouseleave', function(e){

        if(e.target.className != "open_menu"){
            if(e.type == 'mouseenter'){
                $(this).addClass('active');
                $(this).stop().animate({
                    'top' : 0
                }, 'slow', function(){
                    $('span[class=open_menu]').fadeOut();
                });
            }else{
                $(this).removeClass('active');
                $(this).stop().animate({
                    'top' : "-"+$(this).height()
                });
            }
        }

    });

    //show and hide the imprint box
   /* var imprint = $('#imprint');
    $('#imprintlink').toggle(function(){
        imprint.css('display', 'block');
        imprint.stop().animate({
            'right':'30px'
        }, 600, function(){
            imprint.addClass('active');
            imprint.css('display', '');
        });
    },
    function(){
        $('#imprint').stop().animate({
            'right':'-340px'
        }, 600, function(){
            imprint.removeClass('active');
        });
    });*/

    //handles the dynamic page view of the clients
    $('#kunden').dynamicSizes();

    //clients mouse over effects
    $('#kunden > ul > li').bind('mouseenter mouseleave', function(e){

        var $this = $(this);

        if(e.type == 'mouseenter'){
            $this.children('.normal').toggle();
        }

        if(e.type == 'mouseleave'){
            $this.children('.normal').toggle();
        }
    });
    
    function getInternetExplorerVersion()
    // Returns the version of Internet Explorer or a -1
    // (indicating the use of another browser).
    {
      var rv = -1; // Return value assumes failure.
      if (navigator.appName == 'Microsoft Internet Explorer')
      {
        var ua = navigator.userAgent;
        var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
          rv = parseFloat( RegExp.$1 );
      }
      return rv;
    }

    var versionIE = getInternetExplorerVersion();
    if(versionIE != -1  && versionIE < 9){
        $('#kunden > ul > li > img').attr('style', 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader()');
    }

    //contact form handler
    var contactFormElements = $('#kontakt').find('input,textarea,form');
    contactFormElements.each(function(i, val){
        var $this = $(val);
        if($this.is('textarea')){
            if($this.val() != $this.attr('defaultText')){
                $this.val($this.attr('defaultText'));
            }
            
            $this.bind('focus', function(){
                if($this.val() == $this.attr('defaultText')){
                    $this.val("");
                }
            });

            $this.bind('blur', function(){
                if($.trim($this.val()) == ""){
                    $this.val($this.attr('defaultText'));
                }
            });
        }else if($this.is('input') && $this.attr('type') != 'submit'){

            $this.bind('focus', function(){
                if($this.val() == $this.attr('defaultText')){
                    $this.val("");
                }
            });

            $this.bind('blur', function(){
                if($.trim($this.val()) == ""){
                    $this.val($this.attr('defaultText'));
                }
            });

            if($this.val() != $this.attr('defaultText')){
                $this.val($this.attr('defaultText'));
            }
        }else if($this.is('form')){
            $this.bind('submit', function(){
                var errors = new Array();
                var $form = $(this);
                var data = $form.serializeArray();
                $.each(data, function(i2, val2){
                    var empty = false;
                    if($.trim(val2.name) == "" || val2.value == $form.find('[name='+val2.name+']').attr('defaultText')){
                        empty = true;
                    }
                    switch(val2.name){
                        case 'email':
                            if(val2.value.isEmail() == false){
                                errors.push('Ungültige E-Mail Adresse');
                            }
                            if(empty == true){
                                errors.push('E-Mail Adresse leer');
                            }
                            break;
                        case 'name':
                            if(empty == true){
                                errors.push('Name leer');
                            }
                            break;
                        case 'subject':
                            if(empty == true){
                                errors.push('Betreff leer');
                            }
                            break;
                        case 'body':
                            if(empty == true){
                                errors.push('Nachricht leer');
                            }
                            break;
                        default:
                    }
                });

                $form.children('[class="error"]').remove();
                $form.children('[class="success"]').remove();
                if(errors.length > 0){
                    var element = $('<ul class="error"></ul>');
                    $.each(errors, function(i3, val3){
                        element.append('<li>'+val3+'</li>');
                    });
                    $form.prepend(element);

                    element.fadeIn('slow');
                }else{
                    $.ajax({
                        type: "POST",
                        url: "mailme.php",
                        data: data
                    }).done(function( msg ) {
                        var element = $('<div class="success">Vielen Dank! Die Kontaktanfrage wurde erfolgreich versendet.</div>');
                        $form.prepend(element);
                        element.fadeIn('slow');

                        contactFormElements.each(function(i4, val4){
                            if($(val4).is('textarea')){
                                $(val4).val($(val4).attr('defaultText'));
                            }else if($(val4).is('input') && $(val4).attr('type') != 'submit'){
                                $(val4).val($(val4).attr('defaultText'));
                            }
                        });

                        setTimeout(function(){
                            element.fadeOut('slow');
                        }, 5000)
                    }).fail(function(jqXHR, textStatus) {
                        var element = $('<div class="error">Es ist ein Fehler aufgetreten. Bitte versuchen Sie es noch einmal.</div>');
                        $form.prepend(element);
                        element.fadeIn('slow');
                    });
                }

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


//custom plugins
(function( $ ) {

    $.fn.aspediaSlider = function(options) {

        var settings = $.extend( {
            'classActive' : 'active',
            'animationImage' : {
                'speed' : 600
            },
            'current' : 0,
            'intervalId' : null,
            'timeoutId' : null,
            'auto' : true,
            'keys' : true,
            'swipe' : true
        }, options);

        var methods = {
            slide: function(to, object, modus){
                var direction = null;
                if(to < settings.current){
                    direction = 'backward';

                    if(modus == 'auto'){
                        direction = 'forward';
                    }
                }else if(to > settings.current){
                    direction = 'forward';
                }else{
                    direction = 'none';
                }

                var iDots = object.children('div:eq(0)');
                var tags = object.children('div:eq(1)');
                var projects = object.children('div:eq(2)');

                if(to < 0 || to >= projects.children('div').length){
                    console.log('Index ('+to+') not found');
                    return;
                }

                iDots.find('ul > li').removeClass(settings.classActive);
                iDots.find('ul > li:eq('+to+')').addClass(settings.classActive);

                var oldCard = projects.children('div:eq('+settings.current+')');
                var newCard = projects.children('div:eq('+to+')');

                var oldTags = tags.children('div:eq('+settings.current+')');
                var newTags = tags.children('div:eq('+to+')');

                if(direction == 'none'){
                    return;
                }

                oldTags.children('div').each(function(i, val){
                    $(this).stop().animate({
                        left: "-"+(100+parseInt($(val).width()))+"px"
                    }, (settings.animationImage.speed + (i * 200)), function(){
                        if(i == 0){

                            

                    }
                    });
                });


                var positionLeft = newCard.position().left;

                if(direction == 'forward'){

                    var position = "100%";
                    var positionOld = "-100%";

                    if(modus == 'drag'){
                        position = newCard.position().left + "px";
                        positionOld = "-"+$(document).width()+"px";
                    }

                    oldCard.stop().animate({
                        left: positionOld
                    }, settings.animationImage.speed, function(){
                        oldCard.removeClass(settings.classActive);
                    });

                    newCard.css({
                        left: position
                    });
                }else{

                    var position = "-100%";
                    var positionOld = "100%";
                    if(modus == 'drag'){
                        position = newCard.position().left + "px";
                        positionOld = $(document).width()+"px";
                    }

                    oldCard.stop().animate({
                        left: positionOld
                    }, settings.animationImage.speed, function(){
                        oldCard.removeClass(settings.classActive);
                    });

                    newCard.css({
                        left: position
                    });
                }

                var positionNew = "0%";
                if(modus == 'drag'){
                    positionNew = "0px";
                }

                newCard.stop().animate({
                    left: positionNew
                }, settings.animationImage.speed, function(){

                    newCard.addClass(settings.classActive);

                    oldTags.removeClass(settings.classActive);

                    newTags.children('div').each(function(i, val){
                        $(this).stop().animate({
                            left: "0px"
                        }, (settings.animationImage.speed + (i * 200)), function(){

                            if((i+1) == newTags.children('div').length){
                                newTags.addClass(settings.classActive);
                            }

                        });
                    });

                });


                settings.current = to;
            },
            keyHandler: function(event, object){
                
                if(settings.keys == false || object.is(':visible') == false){
                    return;
                }

                var projects = object.children('div:eq(2)');

                //setting the key code
                var keyCode = event.keyCode;

                //disable all default actions for this key codes
                if(	keyCode == 37
                    || keyCode == 39){
                    if(event.preventDefault)
                        event.preventDefault();
                    else
                        event.returnValue=false;

                    methods.timeoutHandler(object, true);
                }

                var to = settings.current;

                //setting custom actions for this key code
                switch (keyCode) {
                    case 37: //Links
                        if(to > 0){
                            to -= 1;
                        }
                        break;
                    case 39: //Rechts
                        if(to < projects.children('div').length-1){
                            to += 1;
                        }
                        break;
                    default:
                        break;
                }

                methods.slide(to, object);
            },
            timeoutHandler: function(object, interaction){

                if(settings.auto == false){
                    return;
                }
                
                var projects = object.children('div:eq(2)');


                clearInterval(settings.intervalId);
                clearTimeout(settings.timeoutId);
                var startInterval = function(){
                                        
                    if(object.is(':visible') == false){
                        return false;
                    }
                    
                    settings.intervalId = setInterval(function(){
                        
                        if(object.is(':visible') == false){
                            return;
                        }
                        
                        var to = settings.current;

                        to += 1;
                        if(to > projects.children('div').length-1){
                            to = 0;
                        }
                        
                        methods.slide(to, object, 'auto');

                    }, 5000);
                }

                if(interaction != true){
                    startInterval();
                }else{
                    settings.timeoutId = setTimeout(function(){
                        startInterval();
                    }, 10000);
                }
            },
            swipeHandler: function(object){

                if(settings.swipe == false){
                    return;
                }

                var projects = object.children('div:eq(2)');
                var to = settings.current;

                var start = 0;
                var end = 0;
                var drag = false;
                var newCard = null;
                var oldCard = null;
                var to = settings.current;

                projects.bind('mousedown mousemove mouseup', function(e){

                    if(e.type == 'mousedown'){
                        start = e.pageX;

                        drag = true;
                    }

                    if(e.type == 'mouseup'){
                        drag = false;
                        end = e.pageX;

                        if(end > start){
                            //forward
                            if(to > 0 && (settings.current - (to-1)) <= 1){
                                to -= 1;
                            }
                        }else{
                            //backward
                            if(to < projects.children('div').length-1 && ((to+1) - settings.current) <= 1){
                                to += 1;
                            }
                        }

                        methods.slide(to, object, 'drag');
                    }

                    if(e.type == 'mousemove' && drag == true){

                        if(e.pageX > start){
                            //forward
                            if(to > 0 && (settings.current - (to-1)) <= 1){
                                to -= 1;
                            }
                        }else{
                            //backward
                            if(to < projects.children('div').length-1 && ((to+1) - settings.current) <= 1){
                                to += 1;
                            }
                        }

                        if(to != settings.current){
                            methods.timeoutHandler(object, true);


                            newCard = projects.children('div:eq('+to+')');
                            oldCard = projects.children('div:eq('+settings.current+')');
                        }else{
                            return;
                        }

                        if(e.pageX > start){

                            oldCard.css({
                                left: (parseInt(e.pageX) - parseInt(start))+"px"
                            });
                            newCard.css({
                                left:"-"+($(document).width() - (parseInt(e.pageX) - parseInt(start)))+"px"
                            });
                        }else{
                            if(oldCard.position().left <= parseInt($(document).width()) && oldCard.position().left >= "-"+parseInt($(document).width())){
                                oldCard.css({
                                    left: "-"+((parseInt(start) - parseInt(e.pageX)))+"px"
                                });
                                newCard.css({
                                    left: (parseInt($(document).width()) - (parseInt(start) - parseInt(e.pageX)))+"px"
                                });
                            }
                        }

                    }

                });
            }
        }

        return this.each(function(key, value){

            var $this = $(this);

            var iDots = $this.children('div:eq(0)');
            var tags = $this.children('div:eq(1)');
            var projects = $this.children('div:eq(2)');

            projects.children('div:eq('+settings.current+')').addClass(settings.classActive);
            tags.children('div:eq('+settings.current+')').addClass(settings.classActive);
            iDots.find('ul > li:eq('+settings.current+')').addClass(settings.classActive);

            if(	projects.length == 0
                || projects.children('div').length == 0
                || iDots.length == 0
                || tags.length == 0){
                console.log('Your DOM doesn\'t match the required structure');
                return $this;
            }

            if(projects.children('div').length == 1){
                return $this;
            }


            $(document).keydown(function(e){
                methods.keyHandler(e, $this);
            });

            methods.timeoutHandler($this);
            methods.swipeHandler($this);


            var dots = iDots.find('ul > li > a');
            dots.each(function(i, val){
                $(this).bind('click', function(){
                    methods.timeoutHandler($this, true);
                    methods.slide(i, $this);

                });
            });


        });

    };
})( jQuery );

(function($){

    // Store the initial location.hash so that the event isn't triggered when
    // the page is first loaded.
    var last_hash = location.hash,

    // An id with which the polling loop can be canceled.
    timeout_id;

    // Special event definition.
    $.event.special.hashchange = {
        setup: function() {
            // If the event is supported natively, return false so that jQuery
            // will bind to the event using DOM methods instead of using the
            //  polling loop.
            if ( 'onhashchange' in window ) {
                return false;
            }

            // Start the polling loop if it's not already running.
            start();
        },
        teardown: function() {
            // If the event is supported natively, return false so that jQuery
            // will bind to the event using DOM methods instead of using the
            // polling loop.
            if ( 'onhashchange' in window ) {
                return false;
            }

            // Stop the polling loop. Since this event is only evern bound to
            // the `window` object, multiple-element tracking is unnecessary.
            stop();
        },
        add: function( handleObj ) {
            // Save a reference to the bound event handler.
            var old_handler = handleObj.handler;

            // This function will now be called when the event is triggered,
            // instead of the bound event handler.
            handleObj.handler = function(event) {

                // Augment the event object with the location.hash at the time
                // the event was triggered.
                event.fragment = location.hash.replace( /^#/, '' );

                // Call the originally-bound event handler, complete with modified
                // event object! The result from this call doesn't need to be
                // returned, because there is no default action to prevent, and
                // nothing to propagate to.
                old_handler.apply( this, arguments );
            };
        }
    };

    // Start (or continue) the polling loop.
    function start() {
        // Stop the polling loop if it has already started.
        stop();

        // Get the current location.hash. If is has changed since the last loop
        // iteration, store that value and trigger the hashchange event.
        var hash = location.hash;
        if ( hash !== last_hash ) {
            $(window).trigger( 'hashchange' );
            last_hash = hash;
        }

        // Poll, setting timeout_id so the polling loop can be canceled.
        timeout_id = setTimeout( start, 100 );
    };

    // Stop the polling loop.
    function stop() {
        clearTimeout( timeout_id );
    };

})(jQuery);

(function( $ ) {

    $.fn.pager = function(options) {

        var $this = $(this);
        
        var settings = $.extend( {
            'router' : {
                'referenzen' : 'slider',
                'ueberuns' : 'ueberuns',
                'kunden' : 'kunden',
                'kontakt' : 'kontakt',
                'impressum' : 'impressum'
            },
            'defaultInit' : 'referenzen'
        }, options);

        var init = location.hash.replace( /^#/, '' );
        var referrer = null;

        var methods = {
            change: function(route, init){

                if(init === true){
                    $.each(settings.router, function(i, val){
                        $('#'+settings.router[i]).removeClass('active');
                    });

                    if(settings.router[route] != undefined){
                        $('#'+settings.router[route]).addClass('active');
                    }else{
                        $('#'+settings.router[settings.defaultInit]).addClass('active');
                    }

                    referrer = route;
                }else{

                    if(settings.router[referrer] == settings.router[route]){
                        return true;
                    }

                    if(referrer == undefined || referrer == "" || referrer == null){
                        referrer = settings.defaultInit;
                    }


                    if(route == undefined || route == "" || route == null){
                        route = settings.defaultInit;
                    }
                    // do the slide change here
                    
                    if($('#'+settings.router[referrer]).is(':visible')){

                        var ref = $('#'+settings.router[referrer]);
                        var rou = $('#'+settings.router[route]);

                        if(ref.is(':animated') == true){
                            return false;
                        }

                        ref.stop().animate({
                            top: '-100%'
                        }, 1600, function(){
                            ref.removeClass('active');
                            ref.css('top', '');
                            ref.css('display', '');
                            referrer = route;
                        });


                        rou.css('display', 'block');
                        rou.stop().animate({
                            top: '0%'
                        }, 1600, function(){
                            rou.addClass('active');
                            referrer = route;
                        });
                    }else{
                        $.each(settings.router, function(i, val){
                            $('#'+settings.router[i]).removeClass('active');
                        });

                        $('#'+settings.router[settings.defaultInit]).addClass('active');

                        referrer = route;
                    }
                }

                //@todo change this to something normal
                if(route == 'impressum'){
                    $('#impressum .center .slider').jScrollPane();
                }
            }
        }

        methods.change(init, true);

        $(window).bind('hashchange', function(event) {
            methods.change(event.fragment);
        });

        return this;

    };
})( jQuery );

(function( $ ) {

    $.fn.dynamicSizes = function(options) {

        var settings = $.extend({
            'minMargin' : 30
        }, options);

        var methods = {
            doAction: function(object){
                var currentDocumentWidth = object.width();
                var currentDocumentHeight = object.height();

                var partCount = object.children().length;
                var elementCount = object.children(':first').children().length;

                
                var elemMaxWidth = Math.floor(currentDocumentWidth / elementCount);
                var elemMaxHeight = Math.floor(currentDocumentHeight / partCount);

                var height = elemMaxWidth;
                var width = elemMaxHeight;
                var minified = null;
                
                if(elemMaxWidth > elemMaxHeight){
                    height = elemMaxHeight;
                    width = elemMaxHeight;
                    minified = elemMaxWidth - elemMaxHeight;
                }else if(elemMaxWidth < elemMaxHeight){
                    height = elemMaxWidth;
                    width = elemMaxWidth;
                    minified = elemMaxHeight - elemMaxWidth;
                }



                var trashWidth = currentDocumentWidth - (width * elementCount);
                var trashHeight = currentDocumentHeight - (height * partCount);

                var marginWidth = 0;
                
                if(trashWidth > 0){
                    marginWidth = Math.floor(((trashWidth) / elementCount) / 2);
                }
                
                if(marginWidth < settings.minMargin){
                    height -= (settings.minMargin - marginWidth) * 2;
                    width -= (settings.minMargin - marginWidth) * 2;

                    marginWidth = settings.minMargin
                }

                var marginHeight = 0;

                if(trashHeight > 0){
                    marginHeight = Math.floor((trashHeight / partCount) / 2);
                }
                if(marginHeight < settings.minMargin){
                    height -= (settings.minMargin - marginHeight) * 2;
                    width -= (settings.minMargin - marginHeight) * 2;

                    marginHeight = settings.minMargin
                }
                
                object.children().each(function(i, val){
                    $(val).children().each(function(i2, val2){
                        $(val2).width(width+"px");
                        $(val2).height(height+"px");
                        $(val2).css("margin", marginHeight+"px "+marginWidth+"px "+marginHeight+"px "+marginWidth+"px");
                    });
                });
            }
        }

        return this.each(function(key, value){

            var $this = $(this);
            methods.doAction($this);
            $(window).resize(function(e){
                methods.doAction($this);
            });

        });

    };
})( jQuery );

//single js functions
String.prototype.isEmail = function(){
    var filter = /^([a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~])+@(([a-zA-Z0-9\-])+.)+\.([a-zA-Z0-9]{2,4})+$/;
    if (filter.test(this)) {
        return true;
    }
    return false;
}
