"use strict";
function isOnScreen(elem) {
	// if the element doesn't exist, abort
	if( elem.length == 0 ) {
		return;
	}
	var $window = jQuery(window)
	var viewport_top = $window.scrollTop()
	var viewport_height = $window.height()
	var viewport_bottom = viewport_top + viewport_height
	var $elem = jQuery(elem)
	var top = $elem.offset().top
	var height = $elem.height()
	var bottom = top + height

	return (top >= viewport_top && top < viewport_bottom) ||
	(bottom > viewport_top && bottom <= viewport_bottom) ||
	(height > viewport_height && top <= viewport_top && bottom >= viewport_bottom)
}

// start custom scripts
(function($) {
jQuery(document).ready(function($){
    /*==========  Swicher ==========*/

    /*==========  Progress bar  ==========*/
    function animate() {
        $(".progress-bar").each(function(){
            var progressValue = $(this).attr('data-value');
            $(this).animate({width: progressValue +'%'}, 6000);
        });
    }
    //career
    var expand = false;
    $('.position').on('click', function(ev) {
        //ev.preventDefault();
        
        $(this).find(".chev").toggleClass('chevron--down chevron--up');
        $(this).closest(".position-cont").find(".collapse").toggleClass("show");
       
        $(this).toggleClass("active"); //css({"background-color": "#993c95", "color": "white"});            
        

        expand= !expand;
    });
    $('.chev').on('click', function(ev) {
        //ev.preventDefault();
        
        $(this).toggleClass('chevron--down chevron--up');
        $(this).closest(".position-cont").find(".collapse").toggleClass("show");
       
        $(this).closest(".position").toggleClass("active"); //css({"background-color": "#993c95", "color": "white"});            
        

        expand= !expand;
    });
    //end career

    //apply
    // $(".resume-cont").click(function()
    // {
    //     $(".resume-file").click();
    // });
    if( $("#positions").length)
    {
        $("#positions").selectize({
            create: true,
            sortField: {
                field: 'text',
                direction: 'asc'
            },
       
        });
    }
    var resume = "";
    $("input:file").change(function (event){
        var fileName = $(this).val();
        

        var reader = new FileReader();

        reader.onload = function(e)
        {       
            resume  = e.target.result;
        }
        reader.readAsDataURL(this.files[0]);
        var fileExtensionAt = fileName.lastIndexOf(".") + 1;
        console.log(fileName.substring(fileExtension, fileName.length));
        var fileExtension = fileName.substring(fileExtensionAt, fileName.length);
        if(fileName!="" && fileExtension == "doc" || fileExtension == "docx" || fileExtension == "pdf")
        {
            var from = fileName.lastIndexOf("\\") + 1;
            var to = fileName.length ;
            fileName = fileName.substring(from, to);
        }
        else{
            fileName="Choose file";
        }
        $(".resume-file-cont label").html(fileName);
     
      });
    $(".btn-delete-file").click(function(e)
    {
        e.preventDefault();
        $(".resume-file-cont label").html("Choose file");
    });
    var btn_apply  = $("#apply-submit");
    var apply_form = $("#apply-form");

    apply_form.bind('submit',  function(ev) {
        ev.preventDefault();

        var resume_file = document.getElementById("resume-file").files[0]; 
 
        console.log(resume.toString());        
        var data = new FormData(document.getElementById("apply-form"));
        data.append("resume", "'" + resume + "'");
        data.append("resume-file", resume_file);
     
        $.ajax({
            url: "job_apply.php?call=upload",
            method: "POST",
            data: data,
            contentType: false,
            cache: false,
            processData:false,
            success : function(data) {
                console.log(data)
                $(".apply-msg").addClass("active");
            },
            error: function(error) 
            {
                console.log(console.error);
            }

          });
        
    });

    //apply end
    //contact form 

    var form = document.getElementById("contact-form");
    var button = jQuery("#contact-form #submit");
    var status = jQuery(".log");

    function success(data)
    {
        form.append(xhr.response);
    }

    function error()
    {
        form.append(xhr.response);
    }

    button.on("submit", function(ev) 
    {        
        var data = new FormData(form);
        ajax(form.method, form.action, data, success, error);
    });

    function ajax(method, url, data, success, error) {
        var xhr = new XMLHttpRequest();
        xhr.open(method, url);
        xhr.setRequestHeader("Accept", "application/json");
        xhr.onreadystatechange = function() {
            if (xhr.readyState !== XMLHttpRequest.DONE) return;
            if (xhr.status === 200) {
               success();
             
            } else {
                error();
            }
        };
        xhr.send(data);
    }

    //end contact form
    // $('#contact-wrap').waypoint(function() {
    //     animate();
    // });  
    //nikola

    $('.clear_storage').on('click', function(e){
        window.localStorage.clear();
    });
  
    var get_id = localStorage.getItem('pg_id');

 // check page id, then scroll to its div
    if(get_id)
        scrollToID(null, get_id, 300);

 // click event to scroll to div
 //section link in nav which refer to section on homepage 
    $('.home_link').on('click', function(e){
        e.preventDefault();
        var id = '#'+$(this).data('id');
        localStorage.setItem('pg_id', id);
        var url = $(this).attr("href");
        scrollToID(url, id, 300);
     
    }); 
  //Link from our partners section on homepage which refer to section on portfolio page
    $('.partners_link').on('click', function(e){
        e.preventDefault();
        var id = '#'+$(this).data('id');
        localStorage.setItem('pg_id', id);
        var url = $(this).attr("href");
        scrollToID(url, id, 300);
        
    }); 

    function scrollToID(url, id, speed) {
        if(url!==null)
        {
            window.location.href = url;
        }
        var offSet = 50;
        var obj = jQuery(id).offset();
        var targetOffset = 0;
        if(jQuery(id).length)
        {
            targetOffset = jQuery(id).offset().top - offSet;
        }
        jQuery('html,body').animate({ scrollTop: targetOffset }, speed);
    }

    window.addEventListener('scroll', function(e) {
        var loc  = window.location;
        if(loc.pathname.substring(loc.pathname.lastIndexOf('/') + 1, loc.pathname.length)=='index.html')
        {
            if( isOnScreen( $( '#intro-wrap' ) ) ) { /* Pass element id/class you want to check */
                $("nav li.active").removeClass("active").find('.nav-active-mark').remove();
                $("nav li.intro-wrap").addClass("active").append('<span class="nav-active-mark"></span>'); 
            }
            if( isOnScreen( $( '#about-wrap' ) ) ) { /* Pass element id/class you want to check */
            
                $("nav li.active").removeClass("active").find('.nav-active-mark').remove();
                $("nav li.about-wrap").addClass("active").append('<span class="nav-active-mark"></span>'); 
            }	
            if( isOnScreen( $( '#our_partners-wrap' ) ) ) { /* Pass element id/class you want to check */
            
                $("nav li.active").removeClass("active").find('.nav-active-mark').remove();
                $("nav li.our_partners-wrap").addClass("active").append('<span class="nav-active-mark"></span>'); 
            }
            if( isOnScreen( $( '#services-wrap' ) ) ) { /* Pass element id/class you want to check */
            
                $("nav li.active").removeClass("active").find('.nav-active-mark').remove();
                $("nav li.services-wrap").addClass("active").append('<span class="nav-active-mark"></span>'); 
            }	           
            if( isOnScreen( $( '#teams-wrap' ) ) ) { /* Pass element id/class you want to check */
            
                $("nav li.active").removeClass("active").find('.nav-active-mark').remove();
                $("nav li.teams-wrap").addClass("active").append('<span class="nav-active-mark"></span>'); 
            }
            if( isOnScreen( $( '#contact-wrap' ) ) ) { /* Pass element id/class you want to check */
            
                $("nav li.active").removeClass("active").find('.nav-active-mark').remove();
                $("nav li.contact-wrap").addClass("active").append('<span class="nav-active-mark"></span>'); 
            }
        
        }	
    });

    //nikola
    /*==========  Disables ==========*/
    if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
        $('#animate_css_file, #wow_js_file').remove();
    } else {

        /*==========  WOW Animations  ==========*/
        var wow = new WOW(
          {
            animateClass: 'animated',
            offset:       100
          }
        );
         wow.init(); 

    }

    /*==========  Logo Retina ==========*/
    if( window.devicePixelRatio > 1 ) {
        var logoWidth = $('#logo img').width();
        var logoHeight = $('#logo img').height();
        $('#logo img').attr("src", "images/logo@2x.png");
        $('#logo img').css({ 'width': logoWidth , 'height': logoHeight });
    }    

    /*==========  Team Item Hover  ==========*/
        $('.team-item').each(function(){
        var memberImage = $(this).find('.member-face').attr('style');
        var current = $(this).find('.change-color');
        $(this).find('.hex-in2.outer-hex').first().hover(function(){
            $(this).find('.member-face').css('background','#000');
            $(current).css('background-color','#f3b202');
            $(this).find('.socials').show();
        },function(){
            $(this).find('.socials').hide();
            $(this).find('.member-face').attr('style', memberImage);
            $(current).css('background-color','#000');
        });
        });

    /*==========  Gallery Item Hover  ==========*/

    $('.gallery-item').hover(function(){
        $(this).find('.gallery-info').stop(true,true).animate({ "top": "0" } );
    },function(){
        $(this).find('.gallery-info').stop(true,true).animate({ "top": "-999" } );
    });

    /*==========  FlexSlider  ==========*/
    $('.flexslider').flexslider({
        animation: "fade",
        animationLoop: false,
        directionNav: false,
        slideshow: false
    });

    /*==========  Pie Chart  ==========*/
    $('.days').waypoint(function() { 
        $('.chart').easyPieChart({
            easing: 'easeOutBounce',
            barColor: '#f3b202',
            trackColor: '#595959',
            lineWidth: '18',
            lineCap: 'butt',
            size: '160',
            scaleColor: false,
            onStep: function(from, to, percent) {
                $(this.el).find('.percent').text(Math.round(percent));
            }
        });
    }); 

    /*==========  Smooth Scroll  ==========*/
    $('a[href*=#]:not([href=#])').click(function() {
        $("li.active").removeClass("active").find('.nav-active-mark').remove();
        $(this).parent().addClass('active').end().append('<span class="nav-active-mark"></span>');
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top - 53
        }, 1000);
        return false;
      }
    }
    });
  
    /*==========  Graph Bars Animate  ==========*/
    $('.days').waypoint(function() {
        $('.graph ul li.bar').each(function() {
            var curBarHeight = $(this).data('bar-height');
            $(this).animate({ height: curBarHeight }, 2000, "easeInOutBack");
        });
    });

    /*==========  Intro Note Box Tooltip  ==========*/
    /*$('.note-1').hover(function(){
        $(this).find('.note-tooltip').fadeIn();
    },function(){
        $(this).find('.note-tooltip').fadeOut();
    });
    */
    
    /*==========  PrettyPhoto  ==========*/
    $("a[data-rel^='prettyPhoto']").prettyPhoto({theme:'dark_rounded', hook: 'data-rel'});

    /*==========  Flickr  ==========*/
    var flickrImageSrc = [ ];
    var flickrLink = [ ];
    $('.flickr_badge_image').each(function(i){
        flickrImageSrc[i] = $(this).find('img').attr('src'); 
        flickrLink[i] = $(this).find('a').attr('href');        
    });
    $('.flickr-item').each(function(i){
        $(this).find('.hex-area').css('background-image', 'url(' + flickrImageSrc[i] + ')');
        $(this).find('.flickr-link').attr('href', flickrLink[i] );
    });    

    /*==========  Window Resize  ==========*/
    var windowWidth = $(window).width();
    var numberOfHexagon = windowWidth / 106;
    var offsetBackground = ((numberOfHexagon - 14) * 106 ) /2;
    $('#hexagon-overlay').css('background-position', offsetBackground + 'px' + ' ' + 'top');

    $(window).resize(function() {
      var currentWindowWidth = $(window).width();
      if(currentWindowWidth <= 940) return;
      $('#hexagon-overlay').css('background-position', - ( ( (windowWidth - currentWindowWidth)/2 ) - offsetBackground ) + 'px' + ' ' + 'top');
    });

    /*==========  Mobile Menu  ==========*/
    $('.mobile-nav-toggle').on('click',function(){
        if($(this).attr('class') == 'mobile-nav-toggle deactive') {
            $('#mobile-navigation').fadeIn();
            $(this).removeClass('deactive');
        } else {
            $('#mobile-navigation').fadeOut();
            $(this).addClass('deactive');
        }
    });

    $("#mobile-navigation li a").on("click", function(){
        $('#mobile-navigation').fadeOut();
        $(".mobile-nav-toggle").addClass('deactive');

    });

    $(window).resize(function(){
                var w = $(window).width();
                if(w > 767) {
                    $('#mobile-navigation').fadeOut();
                    $(".mobile-nav-toggle").addClass('deactive');
                }
            });
    
    /*==========  Contact Form Validation  ==========*/
    
    function isValidEmailAddress(emailAddress) {
        var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
        return pattern.test(emailAddress);
    }    

    // $('.contact-form form').submit(function() {
    
    //     var hasError = false;
      
    //     var comment = $('#message-txt').val();
    //     if ($.trim(comment) == '') {
    //         $('#message-txt').addClass('error');
    //         $('#message-txt').focus();
    //         hasError = true;
    //     }
    //     else {
    //         $('#message-txt').removeClass('error');
    //     }

    //     var subject = $('#subject-txt').val();
    //     if ($.trim(subject) == '') {
    //         $('#subject-txt').addClass('error');
    //         $('#subject-txt').focus();
    //         hasError = true;
    //     }
    //     else {
    //         $('#subject-txt').removeClass('error');
    //     }        
        
    //     var emailVal = $('#email-txt').val();
    //     if ($.trim(emailVal) == '' || !isValidEmailAddress(emailVal)) {
    //         $('#email-txt').addClass('error');
    //         $('#email-txt').focus();
    //         hasError = true;
    //     }
    //     else {
    //         $('#email-txt').removeClass('error');
    //     }
        
        
    //    var name = $('#name-txt').val();
    //     if ($.trim(name) == '') {
    //         $('#name-txt').addClass('error');
    //         $('#name-txt').focus();
    //         hasError = true;
            
    //     }
    //     else {
    //         $('#name-txt').removeClass('error');
    //     }
        
    //     if (!hasError) {
    //         $('#submit').fadeOut('normal', function(){
    //             $('.loading').css({
    //                 display: "block"
    //             });
                
    //         });
            
    //         // $.post($('.contact-form form').attr('action'), $('.contact-form form').serialize(), function(data){
    //         //     $('.log').html(data);
    //         //     $('.loading').remove();
    //         //     $('.contact-form form').slideUp('slow');
    //         // });
            
    //     }
        
    //     return false;
        
    // });    
 


}); // end jquery init
})(jQuery);
