'use strict';

/*
 * A Design by GraphBerry
 * Author: GraphBerry
 * Author URL: http://graphberry.com
 * License: http://graphberry.com/pages/license
 */
$jq(document).ready(function ($) {

    var lastId,
        topMenu = $("#top-navigation"),
        topMenuHeight = topMenu.outerHeight(),
        // All list items
        menuItems = topMenu.find("a"),
        // Anchors corresponding to menu items
        scrollItems = menuItems.map(function () {
            var item = $($(this).attr("href"));
            if (item.length) {
                return item;
            }
        });

    //Get width of container
    var containerWidth = $('.page-section .container').width();
    //Resize animated triangle
    $(".triangle").css({
        "border-left": containerWidth / 2 + 'px outset transparent',
        "border-right": containerWidth / 2 + 'px outset transparent'
    });
    $(window).resize(function () {
        if (Math.max($(window).width(), window.innerWidth) > 529) {
            $('#block-custom_search_blocks-1').css('top', $('#da-slider').height() + 104);
        } else {
            $('#block-custom_search_blocks-1').css('top', '.5em');
        }
        containerWidth = $('.container').width();
        $(".triangle").css({
            "border-left": containerWidth / 2 + 'px outset transparent',
            "border-right": containerWidth / 2 + 'px outset transparent'
        });
    });

    //Initialize header slider.
    $('#da-slider').cslider();

    //Initial mixitup, used for animated filtering portfolio.
    $('#portfolio-grid').mixitup({
        'onMixStart': function (config) {
            $('div.toggleDiv').hide();
        }
    });

    //Initial Out clients slider in client section
    $('#client-slider').bxSlider({
        pager: false,
        minSlides: 1,
        maxSlides: 5,
        moveSlides: 2,
        slideWidth: 210,
        slideMargin: 25,
        prevSelector: $('#client-prev'),
        nextSelector: $('#client-next'),
        prevText: '<i class="icon-left-open"></i>',
        nextText: '<i class="icon-right-open"></i>'
    });

    $('input, textarea').placeholder();

    // Bind to scroll
    $(window).scroll(function () {

        if ($(this).scrollTop() > 130) {
            $('.navbar').addClass('navbar-fixed-top animated fadeInDown');
            $('#frontpage').css('margin-top','90px');
        } else {
            $('.navbar').removeClass('navbar-fixed-top animated fadeInDown');
            $('#frontpage').css('margin-top','0');
        }

        // Get container scroll position
        var fromTop = $(this).scrollTop() + topMenuHeight + 10;

        // Get id of current scroll item
        var cur = scrollItems.map(function () {
            if ($(this).offset().top < fromTop)
                return this;
        });

        // Get the id of the current element
        cur = cur[cur.length - 1];
        var id = cur && cur.length ? cur[0].id : "";

        if (lastId !== id) {
            lastId = id;
            // Set/remove active class
            menuItems
                .parent().removeClass("active")
                .end().filter("[href=#" + id + "]").parent().addClass("active");
        }
    });


    $(window).load(function () {

        $('#block-custom_search_blocks-1').css('visibility', 'visible');
        if (Math.max($(window).width(), window.innerWidth) > 529) {
            $('#block-custom_search_blocks-1').css('top', $('#da-slider').height() + 104);
        } else {
            $('#block-custom_search_blocks-1').css('top', '.5em');
        }

        // Show email
        $('#info-mail').html(function() {
        	var e = "man";
        	var a = "uel@";
        	var d = "cille";
        	var c = "ro.es";
        	var h = 'mailto:' + e + a + d + c;
        	$(this).parent('a').attr('href', h);
        	return e + a + d + c;
        });

        function filterPath(string) {
            return string.replace(/^\//, '').replace(/(index|default).[a-zA-Z]{3,4}$/, '').replace(/\/$/, '');
        }
        $('a[href*=#]').each(function () {
            if (filterPath(location.pathname) == filterPath(this.pathname) && location.hostname == this.hostname && this.hash.replace(/#/, '')) {
                var $targetId = $(this.hash),
                    $targetAnchor = $('[name=' + this.hash.slice(1) + ']');
                var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;

                if ($target) {

                    $(this).click(function () {

                        //Hack collapse top navigation after clicking
                        topMenu.parent().attr('style', 'height:0px').removeClass('in');
                        //Close navigation
                        $('.navbar .btn-navbar').addClass('collapsed');

                        var targetOffset = $target.offset().top - 63;
                        $('html, body').animate({
                            scrollTop: targetOffset
                        }, 800);
                        return false;
                    });
                }
            }
        });
    });

    /*
    Sand newsletter
    **********************************************************************/
    $('#subscribe').click(function () {
        var error = false;
        var emailCompare = /^([a-z0-9_.-]+)@([0-9a-z.-]+).([a-z.]{2,6})$/; // Syntax to compare against input
        var email = $('input#nlmail').val().toLowerCase(); // get the value of the input field
        if (email == "" || email == " " || !emailCompare.test(email)) {
            $('#err-subscribe').show(500);
            $('#err-subscribe').delay(4000);
            $('#err-subscribe').animate({
                height: 'toggle'
            }, 500, function () {
                // Animation complete.
            });
            error = true; // change the error state to true
        }

        if (error === false) {
            $.ajax({
                type: 'POST',
                url: 'php/newsletter.php',

                data: {
                    email: $('#nlmail').val()
                },
                error: function (request, error) {
                    alert("An error occurred");
                },
                success: function (response) {
                    if (response == 'OK') {
                        $('#success-subscribe').show();
                        $('#nlmail').val('')
                    } else {
                        alert("An error occurred");
                    }
                }
            });
        }

        return false;
    });

    /*
Sand mail
**********************************************************************/
    $("#send-mail").click(function () {

        var name = $('input#name').val(); // get the value of the input field
        var error = false;
        if (name == "" || name == " ") {
            $('#err-name').show(500);
            $('#err-name').delay(4000);
            $('#err-name').animate({
                height: 'toggle'
            }, 500, function () {
                // Animation complete.
            });
            error = true; // change the error state to true
        }

        var emailCompare = /^([a-z0-9_.-]+)@([da-z.-]+).([a-z.]{2,6})$/; // Syntax to compare against input
        var email = $('input#email').val().toLowerCase(); // get the value of the input field
        if (email == "" || email == " " || !emailCompare.test(email)) {
            $('#err-email').show(500);
            $('#err-email').delay(4000);
            $('#err-email').animate({
                height: 'toggle'
            }, 500, function () {
                // Animation complete.
            });
            error = true; // change the error state to true
        }


        var comment = $('textarea#comment').val(); // get the value of the input field
        if (comment == "" || comment == " ") {
            $('#err-comment').show(500);
            $('#err-comment').delay(4000);
            $('#err-comment').animate({
                height: 'toggle'
            }, 500, function () {
                // Animation complete.
            });
            error = true; // change the error state to true
        }

        if (error == false) {
            var dataString = $('#contact-form').serialize(); // Collect data from form
            $.ajax({
                type: "POST",
                url: $('#contact-form').attr('action'),
                data: dataString,
                timeout: 6000,
                error: function (request, error) {

                },
                success: function (response) {
                    response = $.parseJSON(response);
                    if (response.success) {
                        $('#successSend').show();
                        $("#name").val('');
                        $("#email").val('');
                        $("#comment").val('');
                    } else {
                        $('#errorSend').show();
                    }
                }
            });
            return false;
        }

        return false; // stops user browser being directed to the php file
    });



    //Function for show or hide portfolio desctiption.
    $.fn.showHide = function (options) {
        var defaults = {
            speed: 1000,
            easing: '',
            changeText: 0,
            showText: 'Show',
            hideText: 'Hide'
        };
        var options = $.extend(defaults, options);
        $(this).click(function () {
            $('.toggleDiv').slideUp(options.speed, options.easing);
            var toggleClick = $(this);
            var toggleDiv = $(this).attr('rel');
            $(toggleDiv).slideToggle(options.speed, options.easing, function () {
                if (options.changeText == 1) {
                    $(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text(options.showText);
                }
            });
            return false;
        });
    };

    //Initial Show/Hide portfolio element.
    $('div.toggleDiv').hide();
    $('.show_hide').showHide({
        speed: 500,
        changeText: 0,
        showText: 'View',
        hideText: 'Close'
    });

    /************************
    Animate elements
    *************************/
    
    //Animate thumbnails 
    $jq('.thumbnail').one('inview', function (event, visible) {
        if (visible == true) {
            $jq(this).addClass("animated fadeInDown");
        } else {
            $jq(this).removeClass("animated fadeInDown");
        }
    });

    //Animate triangles
    $jq('.triangle').bind('inview', function (event, visible) {
        if (visible == true) {
            $jq(this).addClass("animated fadeInDown");
        } else {
            $jq(this).removeClass("animated fadeInDown");
        }
    });
    
    //animate first team member
    $jq('#first-person').bind('inview', function (event, visible) {
        if (visible == true) {
            $jq('#first-person').addClass("animated pulse");
        } else {
            $jq('#first-person').removeClass("animated pulse");
        }
    });
    
    //animate sectond team member
    $jq('#second-person').bind('inview', function (event, visible) {
        if (visible == true) {
            $jq('#second-person').addClass("animated pulse");
        } else {
            $jq('#second-person').removeClass("animated pulse");
        }
    });

    //animate thrid team member
    $jq('#third-person').bind('inview', function (event, visible) {
        if (visible == true) {
            $jq('#third-person').addClass("animated pulse");
        } else {
            $jq('#third-person').removeClass("animated pulse");
        }
    });
    
    //Animate price columns
    $jq('.price-column, .testimonial').bind('inview', function (event, visible) {
        if (visible == true) {
            $jq(this).addClass("animated fadeInDown");
        } else {
            $jq(this).removeClass("animated fadeInDown");
        }
    });
    
    //Animate contact form
    $jq('#block-cillero_manuel-block-availability').bind('inview', function (event, visible) {
        if (visible == true) {
            $jq('#block-cillero_manuel-block-availability').addClass("animated pulse");
        } else {
            $jq('#block-cillero_manuel-block-availability').removeClass("animated pulse");
        }
    });
    $jq('#block-cillero_manuel-block-info-contact').bind('inview', function (event, visible) {
        if (visible == true) {
            $jq('#block-cillero_manuel-block-info-contact').addClass("animated pulse");
        } else {
            $jq('#block-cillero_manuel-block-info-contact').removeClass("animated pulse");
        }
    });

    //Animate skill bars
    $jq('.skills > li > span').one('inview', function (event, visible) {
        if (visible == true) {
            $jq(this).each(function () {
                $jq(this).animate({
                    width: $jq(this).attr('data-width')
                }, 3000);
            });
        }
    });
});

//Initialize google map for contact setion with your location.

function initializeMap() {

    var lat = '44.8164056'; //Set your latitude.
    var lon = '20.46090424'; //Set your longitude.

    var centerLon = lon - 0.0105;

    var myOptions = {
        scrollwheel: false,
        draggable: false,
        disableDefaultUI: true,
        center: new google.maps.LatLng(lat, centerLon),
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    //Bind map to elemet with id map-canvas
    var map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);
    var marker = new google.maps.Marker({
        map: map,
        position: new google.maps.LatLng(lat, lon),
    });

    var infowindow = new google.maps.InfoWindow();

    google.maps.event.addListener(marker, 'click', function () {
        infowindow.open(map, marker);
    });

    infowindow.open(map, marker);
}