/* 
    Runs on document load and does all the nice and a little crazy stuff. 
*/

$( function() {

    var replacementTable = {
        'ά': 'α',
        'έ': 'ε',
        'ή': 'η',
        'ί': 'ι',
        'ό': 'ο',
        'ύ': 'υ',
        'ώ': 'ω',
        'Ά': 'Α',
        'Έ': 'Ε',
        'Ή': 'Η',
        'Ί': 'Ι',
        'Ό': 'Ο',
        'Ύ': 'Υ',
        'Ώ': 'Ω',
        'ς': 'σ'
    }

    /* 
        Replaces greek accents for better uppercase support. 
    */
    $( '#navigation span span, #content-container h1, , #content-container h2.single-project-title, #content-container h2.single-post-title' ).
        not( '.post-text h1' ).
        each( function () {
            var text =  $( this ).text();

            for ( var key in replacementTable ) {
                while ( text.indexOf( key ) > -1 ) {
                    text = text.replace( key, replacementTable[key] );
                }
            }

            $( this ).text( text );
        });

    /* 
        Sets up and initiates the mega menu. 
    */
    $( '.megaMenu' ).megaMenu({
        megaMenuContainer: '.megaMenuContainer',
        effect: 'fade',
        delay: 100,
        speed: 300
    });

    /* 
        Sets up and initiates the main slideshow in the home page. 
    */
    $( '#slideshow' ).slideshow({
        slide: '.slide',
        navigation: '.navigation a',
        navigationSelectedClass: 'selected',
        slideshow: true,
        slideshowSpeed: 6000,
        startFromIndex: 1,
        transition: 'fade',
        transitionSpeed: 800,
        mouseOverFreeze: true
    });
    
    /* 
        Shows the little project info on top of each project's thumbnail in the 
        featured projects slideshow in the home page. 
    */
    $( '#showcase .project' ).each( function () {
        var $_description = $( '.thumbnail .description', this );

        var thumbnailHeight = $( '.thumbnail', this ).outerHeight();

        if ( $_description.length ) {
            var descriptionHeight = $_description.outerHeight();

            $( this ).
                mouseenter( function () {
                    $_description.animate( { top: ( thumbnailHeight - descriptionHeight ) + 'px' }, { duration: 200, queue: false }, 'linear' );
                }).
                mouseleave( function () {
                    $_description.animate( { top: thumbnailHeight + 'px' }, { duration: 200, queue: false }, 'linear' );
                });
        }
    });

    /* 
        Sets up and initiates the featured projects slideshow in the home page. 
    */
    $( '#showcase' ).slideshow({
        slide: '.slide',
        next: '#next',
        previous: '#previous',
        slideshow: true,
        slideshowSpeed: 5000,
        startFromIndex: 1,
        transition: 'fade',
        transitionSpeed: 1000,
        mouseOverFreeze: true
    });

    /* 
        Sets up and initiates the portfolio projects slideshow. 
    */
    $( '#portfolio' ).slideshow({
        slide: '.project',
        next: '#next',
        previous: '#previous',
        slideshow: true,
        slideshowSpeed: 4000,
        startFromIndex: 1,
        transition: 'fade',
        transitionSpeed: 1000,
        mouseOverFreeze: true
    });

    /*
        Portoflio project's inner bulleted list slideshow.
    */
    $( '#portfolio .project ul.image-counter li a' ).click( function () {
        var index = parseInt( $( this ).attr( 'rel' ) ) - 1;

        $_links = $( 'a', $( this ).parent().parent() );

        $_images = $( this ).parent().parent().parent().find( 'img' );

        $_links.removeClass( 'selected' );
        $( this ).addClass( 'selected' );

        $_images.not( ':eq(' + index + ')' ).animate( { opacity: 0 }, { duration: 300, queue: false }, 'linear' );
        $_images.filter( ':eq(' + index + ')' ).css( 'display', 'block' ).animate( { opacity: 1 }, { duration: 300, queue: false }, 'linear' );

        return false;
    });

    /* 
        Updates the clock and the try-us-if-it-is-not-very-late-yet header. 
    */
    window.setInterval( function () {
        var date = new Date();
        var day = date.getDay();
        var hour = date.getHours();
        var minute = date.getMinutes()
        var seconds = date.getSeconds();
      
        /* Monday to Friday from 09:00 to 20:00. */
        if ( day > 0 && day < 6 && hour > 8 && hour < 20 ) {
            $('#lamp').removeClass('off').addClass( 'on' ); 
            $('#too-late').hide();
            $('#not-too-late').show();
        } else {
            $('#lamp').removeClass('on').addClass( 'off' ); 
            $('#too-late').show();
            $('#not-too-late').hide();
        }
        
        $( '#hour-1' ).text( hour < 9 ? 0 : Math.floor( hour/10 ) );
        $( '#hour-2' ).text( hour%10 );
        $( '#minute-1' ).text( minute < 9 ? 0 : Math.floor( minute/10 ) );
        $( '#minute-2' ).text( minute < 9 ? minute : minute%10 );
        $( '#ampm' ).text( hour < 12 ? 'ΠΜ' : 'MΜ' );
    }, 2000 );

    /* 
        Silly cloud animations at the top of the site. 
    */
    $( '#clouds-1' ).pan({
        fps: 15, 
        speed: 0.5, 
        dir: 'right'
    });
    $( '#clouds-2' ).pan({
        fps: 15, 
        speed: 1, 
        dir: 'right'
    });

    /* 
        Silly call us animation stuff at the top of the site. 
    */
    var callUsDoAnimation = true;
    var callUsToggleWait = true;
    
    var $_call_us = $( '#call-us' );
    var $_call_us_container = $( '#call-us-container' );

    var showCallUs = function () {
        $_call_us_container.animate( { top: '-20px' }, { duration: 200, queue: false }, 'linear' );
        return false;
    }

    var hideCallUs = function () {
        $_call_us_container.animate( { top: '-208px' }, { duration: 200, queue: false }, 'linear' );
        return false;
    }

    $_call_us.mouseenter( showCallUs );
    $_call_us_container.mouseover( showCallUs );

    $( document.body ).
        mouseover( hideCallUs ).
        mouseout( hideCallUs );

    /* 
        Sum of all paddings and margins and borders between
        the popup and the popup contents. Used in order to 
        calculate heights smoothly.
    */
    var bleedX = 42;
    var bleedY = 42;

    var loadingWidth = 340;
    var loadingHeight = 160;
    var errorHeight = 212;
    var errorWidth = 340;
    var startWidth = 980;
    var startHeight = 590;

    var duration = 250;

    /* 
        Monster, spaghetti code that pops up a custom dialog with project info
        and images slideshow when a project's thumbnail is clicked.
    */
    $( '#portfolio .project a.view-more, #portfolio-more .project .thumbnail a, #portfolio-more .project .view-more a' ).click( function () {
        /* Have the project id handy for later. */
        var project_id = $( this ).parent().parent().find( '.project-id' ).text();

        /* Create a loading elements at first. */
        $( document.body ).append( 
            '<div id = "popup-contents">' + 
                '<a class = "close" href = "#" title = "Close">Close</a>' + 
                '<div class = "loading">Παρακαλώ περιμένετε...</div>' +
            '</div>' 
        );

        /* Get a reference to your container inside the popup. */
        $_popup_contents = $( '#popup-contents' );

        /* F*cking show the popup with the project info. */
        $_popup_contents.popup({
            popupClass: 'popup',
            popupAnimationDuration: duration,
            closeElement: '.close', 
            overlayClass: 'overlay',
            overlayOpacity: 0.6,
            overlayAnimationDuration: duration,
            width: loadingWidth,
            height: loadingHeight,
            startZIndex: 1000,
            onCreate: function () { 
                /* As soon as the popup is, ehrr, up get the project data via ajax. */
                $.ajax({
                    url: BLOG_URL + '/wp-admin/admin-ajax.php',
                    method: 'GET',
                    data: 'action=get_project_contents&project_id=' + project_id,
                    dataType: 'json', 
                    success: 
                        function ( results ) {
                            var html = '<div class = "slide" style = "width: ' + startWidth + 'px; height: ' + startHeight + 'px;">';
                            
                            /* The title. */
                            html += '<h3>' + results['title'] + '</h3>'

                            /* The featured image. */
                            html += '<img class = "featured" src = "' + results['thumbnail']['src'] + '" alt = "' + results['thumbnail']['title'] + '" title = "' + results['thumbnail']['title'] + '"/>';
                            
                            /* The services. */
                            html += '<div class = "services">{';
                            for ( var k = 0; k < results['services'].length; k++ ) {
                                html += results['services'][k] + ( k < results['services'].length - 1 ? ', ' : '' );
                            }
                            html += '}</div>';
                            
                            /* The content (short - as many words as the AJAX call returned). */
                            html += '<p>' + results['content'] + '</p>';
                            
                            /* The project's website, if any. */
                            html += '<div class = "website">' + results['website'] + '</div>';
                            
                            /* Read-the-whole-project button. */
                            html += '<a class = "read-more" href = "' + results['permalink'] + '" title = "' + results['title'] + '">όλο το project αναλυτικά</a>';
                            
                            html += '</div>';
                            
                            /* The project's attached images. */
                            for ( var t in results['attachments'] ) {
                                html += '<img class = "slide" src = "' + results['attachments'][t]['src'] + '" alt = "' + results['attachments'][t]['title'] + '" title = "' + results['attachments'][t]['title'] + '"/>'
                            }
                            
                            /* The bullet-like navigator. */
                            html += '<ul class = "image-counter">';
                            html += '<li><a href = "#" title = "Προηγούμενη εικόνα" class = "previous">&nbsp;</a></li>';
                            
                            html += '<li><a href = "#" title = "Project" class = "selected" rel = "1">&nbsp;</a></li>';
                            var counter = 2;
                            for ( var t in results['attachments'] ) {
                                html += '<li><a href = "#" title = "Εικόνα ' + counter + '" rel = "' + counter + '">&nbsp;</a></li>';
                                counter++;
                            }
                            
                            html += '<li><a href = "#" title = "Επόμενη εικόνα" class = "next">&nbsp;</a></li>';
                            html += '</ul>'

                            /* IE png fix for close button. */
                            if ( typeof DD_belatedPNG != 'undefined' ) {
                                DD_belatedPNG.fix( '.close' );
                            }
                            
                            /* Remove loading message and show project info. */
                            $_popup_contents.find( '.loading' ).remove().end().append( html );
                            
                            /* Click event handler for the bullet-like navigator. */
                            $_popup_contents.find( 'ul.image-counter li a' ).click( function() {
                                $_slides = $_popup_contents.find( '.slide' );
                                $_anchors = $( this ).parent().parent().find( 'li a' ).not( '.previous, .next' );

                                var index = 0;
                                var previousIndex = 0;

                                if ( $( this ).hasClass( 'previous' ) ) {
                                    /* Previous bullet button hit. */
                                    previousIndex = parseInt( $_anchors.filter( '.selected' ).attr( 'rel' ) ) - 1;
                                    if ( previousIndex == 0 ) {
                                        index = $_anchors.length - 1;
                                    } else {
                                        index = previousIndex - 1;
                                    }
                                } else if ( $( this ).hasClass( 'next' ) ) {
                                    /* Next bullet button hit. */
                                    previousIndex = parseInt( $_anchors.filter( '.selected' ).attr( 'rel' ) ) - 1;
                                    if ( previousIndex == $_anchors.length - 1 ) {
                                        index = 0;
                                    } else {
                                        index = previousIndex + 1;
                                    }
                                } else {
                                    /* Numbered bullet button hit. */
                                    index = parseInt( $( this ).attr( 'rel' ) ) - 1;

                                    previousIndex = 0;
                                    for ( var k = 0; k < $_anchors.length ; k++ ) {
                                        if ( $_anchors.filter( ':eq(' + k + ')' ).hasClass( 'selected' ) ) {
                                            previousIndex = k;
                                            break;
                                        }
                                    }
                                }
                                
                                /* Select/deselect appropriate bullets. */
                                $_anchors.filter( ':eq(' + previousIndex + ')' ).removeClass( 'selected' );
                                $_anchors.filter( ':eq(' + index + ')' ).addClass( 'selected' );

                                /* Calculate new popup dimensions. */
                                var width = 0;
                                var height = 0;

                                if ( index == 0 ) {
                                    /* In case the first slide is selected. */
                                    width = startWidth;
                                    height = startHeight;
                                } else {
                                    /* Dont' forget these are plain images! */
                                    width = $_slides.filter( ':eq(' + index + ')' ).width();
                                    height = $_slides.filter( ':eq(' + index + ')' ).height();
                                }
                                
                                /* Nice name, lol. */
                                var maxFactor = 0.9;

                                /* Scale a bit, if out of window bounds. */
                                if ( height > document.documentElement.clientHeight * maxFactor || width > document.documentElement.clientWidth * maxFactor ) {
                                    var scaleFactorX = ( maxFactor * document.documentElement.clientWidth ) / width;
                                    var scaleFactorY = ( maxFactor * document.documentElement.clientHeight ) / height;

                                    if ( scaleFactorY < scaleFactorX ) {
                                        width = scaleFactorY * width;
                                        height = scaleFactorY * height;
                                    } else {
                                        width = scaleFactorX * width;
                                        height = scaleFactorX * height;
                                    }

                                    $_slides.filter( ':eq(' + index + ')' ).css( 'height', height + 'px' ).css( 'width', width + 'px' );
                                }
                                
                                /* Resize popup to new dimensions. */
                                $_popup_contents.popup( 'moove', { width: width + bleedX, height: height + bleedY } );
                                
                                /* Resize popup contents to new dimensions accordingly. */
                                $_popup_contents.animate( { width: width + 'px', height: height + 'px' }, duration );

                                /* Select/deselect appropriate slides. */
                                if ( index != previousIndex ) {
                                    /* Nothing to hide if the same index is selected. */
                                    $_slides.filter( ':eq(' + previousIndex + ')' ).animate( 
                                        { opacity: 0 }, 
                                        {
                                            duration: duration,
                                            easing: 'swing',
                                            queue: false,
                                            complete: function () {
                                                $( this ).css( 'display', 'none' );
                                            }
                                        } 
                                    );
                                }

                                /* Leave this here because the first time nothing was selected. */
                                $_slides.filter( ':eq(' + index + ')' ).
                                    css( 'display', 'block' ).
                                    css( 'opacity', '0' ).
                                    animate( { opacity: 1 }, duration );

                                return false;
                            });
                            
                            /* 
                                Show project info, the first slide, just as if the user 
                                had selected so by clicking the first numbered bullet.
                                That means the second element, with index = 1.
                            */
                            $_popup_contents.find( 'ul.image-counter li a:eq(1)' ).trigger( 'click' );
                        }, 
                    error: 
                        function () {
                            $_popup_contents.popup( 'moove', { width: errorWidth, height: errorHeight  } );
                            $_popup_contents.find( '.loading' ).html( 'Απίστευτο! Κάτι δεν πήγε καλά. <br/> Ζητάμε συγνώμη. Κάποιος θα απολυθεί. <br/> Το πρόβλημα, πάντως, θα διορθωθεί το ταχύτερο δυνατόν...' );
                        }
                });
            }
        });

        return false;
    });

    /* Popup bigger image in single project page thumbnails. */
    $( '#project-thumbnails a, a.thumbnail' ).not( '.no-popup' ).click( function () {
        $( document.body ).append( 
            '<div id = "popup-contents">' + 
                '<a class = "close" href = "#" title = "Close">Close</a>' + 
                '<div class = "loading">Παρακαλώ περιμένετε...</div>' +
            '</div>' 
        );

        /* Get a reference to your container inside the popup. */
        $_popup_contents = $( '#popup-contents' );

        var image_src = $( this ).attr( 'href' );
        var image_title = $( this ).find( 'img' ).attr( 'alt' );

        $_popup_contents.popup({
            popupClass: 'popup',
            popupAnimationDuration: duration,
            closeElement: '.close', 
            overlayClass: 'overlay',
            overlayOpacity: 0.6,
            overlayAnimationDuration: duration,
            width: loadingWidth,
            height: loadingHeight,
            startZIndex: 1000,
            onCreate: function () {
                var image = new Image();
                image.src = image_src;
                image.onload = function () {
                    /* Calculate new popup dimensions. */
                    var width = image.width;
                    var height = image.height;
                    
                    /* Nice name, lol. */
                    var maxFactor = 0.9;

                    /* Scale a bit, if out of window bounds. */
                    if ( height > document.documentElement.clientHeight * maxFactor || width > document.documentElement.clientWidth * maxFactor ) {
                        var scaleFactorX = ( maxFactor * document.documentElement.clientWidth ) / width;
                        var scaleFactorY = ( maxFactor * document.documentElement.clientHeight ) / height;

                        if ( scaleFactorY < scaleFactorX ) {
                            width = scaleFactorY * width;
                            height = scaleFactorY * height;
                        } else {
                            width = scaleFactorX * width;
                            height = scaleFactorX * height;
                        }
                    }

                    $_popup_contents.
                        find( '.loading' ).
                        remove().
                        end().
                        append( '<img src = "' + image_src + '" alt = "' + image_title + '" style = "width: ' + width + 'px; height: ' + height + 'px;"/>' );
                    
                    /* Resize popup to new dimensions. */
                    $_popup_contents.popup( 'moove', { width: width + bleedX, height: height + bleedY } );

                    /* Resize popup contents to new dimensions accordingly. */
                    $_popup_contents.width( width ).height( height );
                }
            }
        });

        return false;
    });

    /* 
        Makes elements get equal heights. Have to give it jQuery objects. 
    */
    function makeEqualHeight ( $_elements ) {
        /* The row length in elements. */
        var row = 3;

        /* Start with a non sensible height value; */
        var max = 0;

        /* Get the elements length once. */
        var length = $_elements.length;

        /* Calculate if any elements are left out in the end. */
        var residue = length % row;
        
        /* Iterate over elements. */
        for ( var k = 0; k < length; k++ ) {
            var height = $( $_elements.get( k ) ).outerHeight();

            /* 
                Update max height if current element has a greater height 
                than the previous ones. 
            */
            if ( height > max ) {
                max = height;
            }

            /* 
                If the number of elements in a row is reached then update all 
                their heights with the calculated max height. 
            */
            if ( ( k + 1 ) % row == 0 ) {
                for ( m = 0; m < row; m++ ) {
                    $( $_elements.get( k - m ) ).height( max );
                }
                max = 0;
            }
        }

        /* Update heights of leftover elements. */
        for ( m = 0; m < residue; m++ ) {
            $( $_elements.get( length - 1 - m ) ).height( max );
        }
    }

    /* 
        Now do the equal heights frenzy in the portfolio project's sea. 
    */
    makeEqualHeight( $( '#portfolio-more .project h2' ) );
    makeEqualHeight( $( '#portfolio-more .project .services' ) );
    makeEqualHeight( $( '#portfolio-more .project .website' ) );

    /* 
        Some nice effect for the metro navigation map below the content. 
    */
    $( '#metro-navigation .station-link, #metro-navigation .title' ).
        mouseenter( function () {
            $( this ).parent().addClass( 'hover' )
        }).
        mouseleave( function () {
            $( this ).parent().removeClass( 'hover' )
        });
    
    /* Make all links to external sources open in new window. */
    $( 'a[href^=http]' ).click( function () {
        var href = $( this ).attr( 'href' );
        if ( href.indexOf( BLOG_URL ) != 0 ) {
            window.open( $( this ).attr( 'href' ), '', 'location=yes,scrollbars=yes,menubar=yes,resizable=yes,toolbar=yes,status=yes' );
            return false;
        }
    });

    /* 
        Contact form's submit button hover stylings. 
    */
    $( '#contact-form input.submit' ).
        mouseenter( function () {
            $( this ).addClass( 'hover' );
        }).
        focus( function () {
            $( this ).addClass( 'hover' );
        }).
        mouseleave( function () {
            $( this ).removeClass( 'hover' );
        }).
        blur( function () {
            $( this ).removeClass( 'hover' );
        });

    /* 
        Validates and submits the contact form.
    */
    $( '#contact-form' ).formValidation({
        errorClass: 'error',
        errorMessage: '',
        jQueryUIDialogOptions: null,
        callback:
            function ( errorElements ) {
                /* Get a reference to the form. */
                $_form = $( '#contact-form' );

                if ( errorElements ) {
                    $( document.body ).append( 
                        '<div id = "popup-contents">' + 
                            '<a class = "close" href = "#" title = "Close">Close</a>' + 
                            '<div class = "loading">Λάθος στα στοιχεία της φόρμας! <br/> Παρακαλούμε συμπληρώστε σωστά όλα τα <br/> υποχρεωτικά στοιχεία της φόρμας προτού προσπαθήσετε να την υποβάλετε.</div>' +
                        '</div>' 
                    );

                    /* Get a reference to your container inside the popup. */
                    $_popup_contents = $( '#popup-contents' );

                    $_popup_contents.popup({
                        popupClass: 'popup',
                        popupAnimationDuration: duration,
                        closeElement: '.close', 
                        overlayClass: 'overlay',
                        overlayOpacity: 0.6,
                        overlayAnimationDuration: duration,
                        width: errorWidth,
                        height: errorHeight,
                        startZIndex: 1000,
                        onCreate: null
                    });
                    return false;
                } else {
                    $( document.body ).append( 
                        '<div id = "popup-contents">' + 
                            '<a class = "close" href = "#" title = "Close">Close</a>' + 
                            '<div class = "loading">Παρακαλώ περιμένετε...</div>' +
                        '</div>' 
                    );

                    /* Get a reference to your container inside the popup. */
                    $_popup_contents = $( '#popup-contents' );

                    var data = 'action=send_contact_form&' + $_form.serialize();

                    $_popup_contents.popup({
                        popupClass: 'popup',
                        popupAnimationDuration: duration,
                        closeElement: '.close', 
                        overlayClass: 'overlay',
                        overlayOpacity: 0.6,
                        overlayAnimationDuration: duration,
                        width: loadingWidth,
                        height: loadingHeight,
                        startZIndex: 1000,
                        onCreate: function () {
                            $.ajax({
                                url: BLOG_URL + '/wp-admin/admin-ajax.php',
                                method: 'GET',
                                data: data,
                                dataType: 'text', 
                                success: 
                                    function ( results ) {
                                        if ( results == 'success' ) {
                                            $_popup_contents.popup( 'moove', { width: 550, height: 340  } );
                                            $_popup_contents.find( '.loading' ).html( '<h4>Σας ευχαριστούμε για την επικοινωνία</h4><div class = "logo">Nevma.Gr</div>' );
                                        } else if ( results == 'validation' )  {
                                            $_popup_contents.popup( 'moove', { width: errorWidth, height: errorHeight  } );
                                            $_popup_contents.find( '.loading' ).html( 'Λάθος στα στοιχεία της φόρμας! <br/> Παρακαλούμε συμπληρώστε σωστά όλα τα <br/> υποχρεωτικά στοιχεία της φόρμας προτού προσπαθήσετε να την υποβάλετε.' );
                                        } else if ( results == 'problem' ) {
                                            $_popup_contents.popup( 'moove', { width: errorWidth, height: errorHeight  } );
                                            $_popup_contents.find( '.loading' ).html( 'Απίστευτο! Κάτι δεν πήγε καλά. <br/> Ζητάμε συγνώμη. Κάποιος θα απολυθεί. <br/> Το πρόβλημα, πάντως, θα διορθωθεί το ταχύτερο δυνατόν...' );
                                        } else {
                                            $_popup_contents.popup( 'moove', { width: errorWidth, height: errorHeight  } );
                                            $_popup_contents.find( '.loading' ).html( 'Απίστευτο! Κάτι δεν πήγε καλά. <br/> Ζητάμε συγνώμη. Κάποιος θα απολυθεί. <br/> Το πρόβλημα, πάντως, θα διορθωθεί το ταχύτερο δυνατόν...' );
                                        }

                                        /* IE png fix for close button. */
                                        if ( typeof DD_belatedPNG != 'undefined' ) {
                                            DD_belatedPNG.fix( '.logo' );
                                        }
                                    },
                                error: 
                                    function () {
                                        $_popup_contents.popup( 'moove', { width: errorWidth, height: errorHeight  } );
                                        $_popup_contents.find( '.loading' ).html( 'Απίστευτο! Κάτι δεν πήγε καλά. <br/> Ζητάμε συγνώμη. Κάποιος θα απολυθεί. <br/> Το πρόβλημα, πάντως, θα διορθωθεί το ταχύτερο δυνατόν...' );
                                    }
                            });
                        }
                    });

                    /* Prevent normal submit. It is done above via AJAX! */
                    return false;
                }
            }
    });

} );

