/*
Scripts File
Author: Wayne

*/

// IE8 ployfill for GetComputed Style (for Responsive Script below)

if (!window.getComputedStyle) {
    window.getComputedStyle = function(el, pseudo) {
        this.el = el;
        this.getPropertyValue = function(prop) {
            var re = /(\-([a-z]){1})/g;
            if (prop == 'float') prop = 'styleFloat';
            if (re.test(prop)) {
                prop = prop.replace(re, function () {
                    return arguments[2].toUpperCase();
                });
            }
            return el.currentStyle[prop] ? el.currentStyle[prop] : null;
        }
        return this;
    }
}

// as the page loads, call these scripts
jQuery(document).ready(function($) {
	$(function() {
    $( "#accordion" ).accordion();
    
    $("#navsearch").on("submit", function(){
   		window.location.href = "https://cobblestonefreeway.ca/?s="+$( "#findit").val();
   		return false;
 	});
    
    
  });
  
/*	
	$(function() {
	  $('a[href*=#]:not([href=#])').click(function() {
	    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
	        }, "slow");
	        return false;
	      }
	    }
	  });
	});
 */ 


// Find all YouTube videos
var $allVideos = $("iframe[src^='//www.youtube.com']"),

    // The element that is fluid width
    $fluidEl = $("body");

// Figure out and save aspect ratio for each video
$allVideos.each(function() {

  $(this)
    .data('aspectRatio', this.height / this.width)

    // and remove the hard coded width/height
    .removeAttr('height')
    .removeAttr('width');

});

// When the window is resized
$(window).resize(function() {

  var newWidth = $fluidEl.width();

  // Resize all videos according to their own aspect ratio
  $allVideos.each(function() {

    var $el = $(this);
    $el
      .width(newWidth)
      .height(newWidth * $el.data('aspectRatio'));

  });

// Kick off one resize to fix all videos on page load
}).resize();

 
 
   
    $(".video_container").fitVids();
    
    /* getting viewport width */
    var responsive_viewport = $(window).width();
    
    /* if is below 481px */
    if (responsive_viewport < 481) {
    
    } /* end smallest screen */
    
    /* if is larger than 481px */
    if (responsive_viewport > 481) {
        
    } /* end larger than 481px */
    
    /* if is above or equal to 768px */
    if (responsive_viewport >= 768) {
    
        /* load gravatars */
        $('.comment img[data-gravatar]').each(function(){
            $(this).attr('src',$(this).attr('data-gravatar'));
        });
        
    }
    
    /* off the bat large screen actions */
    if (responsive_viewport > 1030) {
        
    }
    
	
	// add all your scripts here
	
	//----------------------------
	
	jQuery('#form-contact').on( 'click', '#form-submit', function(event) {
		
		jQuery.ajax({
			url : "\/wp-admin\/admin-ajax.php",
			type : 'post',
			data : {
				action : 'contact_submit',
				name : jQuery( "#fname" ).val(),
				email : jQuery( "#femail" ).val(),
				subject : jQuery( "#fsubject" ).val(),
				opt : jQuery( "#fnews" ).prop('checked'),
				tour : jQuery( "#ftour option:selected" ).val(),
				message : jQuery( "#fmessage" ).val(),
				question : jQuery( "#fquestion" ).val()
			},
			success : function( response ) {
				//jQuery('#form-contact').fadeOut(600, function(){jQuery('#form-contact').html(response).fadeIn(900);});
				window.location.href = 'http://cobblestonefreeway.ca/thank-you/';
			}
		});
	
	});

	//-----------
	//----------------------------
		
	// calendars -----------------------------------

	if($('#firstTour').length){
		
		$('#firstTour').datepicker({
		    dateFormat: 'dd/mm/yy',
		    defaultDate: new Date(firstdates[0]), // this line is for testing
		    beforeShowDay: function	(date) {
			    for (var i = 0; i < firstdates.length; i++) {
			        if (new Date(firstdates[i]).toString() == date.toString()) { 
			            return [true, 'ui-state-active'];
			        }
			    }
			    return [false, ''];
			}
		}).attr('readonly', 'readonly');
			
	}
	
	if($('#secondTour').length){
			
		$('#secondTour').datepicker({
		    dateFormat: 'dd/mm/yy',
		    defaultDate: new Date(seconddates[0]), // this line is for testing
		    beforeShowDay: function	(date) {
			    for (var i = 0; i < seconddates.length; i++) {
			        if (new Date(seconddates[i]).toString() == date.toString()) {
			            return [true, 'ui-state-active'];
			        }
			    }
			    return [false, ''];
			}
		}).attr('readonly', 'readonly');
	
	}
		
	function highlightDays(date,datearray) {
	    for (var i = 0; i < datearray.length; i++) {
		    
		    //console.log( date+' got: '+date.toString() );
		    
	        if (new Date(datearray[i]).toString() == date.toString()) {
		        //console.log( 'found: '+date.toString() );
	            return [true, 'ui-state-active'];
	        }
	    }
	    return [false, ''];
	}
		

	var gallery = $('.tour-carousel');
	
	if(gallery.length){	
		
		var winw = $(window).width();

		var photos = 1;

		if(winw > 1023 ){photos = 2;}

		
		gallery.owlCarousel({
			loop:true,
			margin:20,
			nav:true,
			items: photos,
			dots: false,
			navText: ['','']
		});
				
	}//if length	


	var gallery = $('.home-carousel');
	
	if(gallery.length){	
		
		var winw = $(window).width();
		
		gallery.owlCarousel({
			loop:true,
			margin:0,
			nav:true,
			items: 1,
			dots: false,
			navText: ['',''],
			autoplay: true,
			autoplayTimeout: 6000,
			autoplaySpeed: 1200

		});
				
	}//if length	



	var testies = $('.testimonial-carousel');
	
	if(testies.length){	
		
		testies.owlCarousel({
			loop:true,
			margin:20,
			nav:false,
			items: 1,
			dots: false,
			autoplay: true,
			autoplayTimeout: 8000,
			autoplayHoverPause: true
		});
				
	}//if length	
	

	var gifties = $('.gift-carousel');
	
	if(gifties.length){	
		
		gifties.owlCarousel({
			loop:true,
			margin:20,
			nav:true,
			items: 5,
			dots: false,
			autoplay: true,
			autoWidth:true,
			autoplayTimeout: 8000,
			autoplayHoverPause: true,
			navText: ['','']
		});
				
	}//if length	
	
	//======================================================
	
	if(jQuery('a.serviceLevel').length){
		
		jQuery('.tour-details-content').on( 'click', 'a.serviceLevel,a.closeServiceLevel', function(event) {
			
			event.preventDefault();
			jQuery('.service-level').slideToggle(500);

		});
		
	};	


	jQuery('.tour-details-col').on( 'click', '.expand-request', function(event) {
		event.preventDefault();
		jQuery(this).slideToggle(300, function(){jQuery('.request-email').slideToggle(500);} );
	
	});

	jQuery('.tour-details-col').on( 'click', '.request-submit', function(event) {
		
		event.preventDefault();

		if( jQuery('.input-request-email').val().length > 3 && jQuery('.input-request-phone').val().length > 9 ){
			jQuery('.load-hidden.request-email').slideToggle(300);
			
			var news = 0;
			
			if(jQuery( "#news" ).prop("checked")){
				news = 1;
			}
			
			console.log(news);
			
			jQuery.ajax({
				url : "\/wp-admin\/admin-ajax.php",
				type : 'post',
				data : {
					action : 'itinerary_request_submit',
					email : jQuery( ".input-request-email" ).val(),
					phone : jQuery( ".input-request-phone" ).val(),
					news : news,
					tour : jQuery( ".input-tour" ).val()
				},
				success : function( response ) {
					//jQuery('.pdf-download').fadeOut(600);
					//console.log(response);
					//return true;
					//window.location.href = 'http://cobblestonefreeway.ca/thank-you/';
				}
			});		
			
			jQuery(this).slideToggle(300, function(){jQuery('.pdf-download').slideToggle(500);} );
		}
	
	});

	//jQuery('.tour-details-col').on( 'click', '.pdf-download', function(event) {


		
	//});	

	
	
}); /* end of as page load scripts */



/*! A fix for the iOS orientationchange zoom bug.
 Script by @scottjehl, rebound by @wilto.
 MIT License.
*/
(function(w){
	// This fix addresses an iOS bug, so return early if the UA claims it's something else.
	if( !( /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1 ) ){ return; }
    var doc = w.document;
    if( !doc.querySelector ){ return; }
    var meta = doc.querySelector( "meta[name=viewport]" ),
        initialContent = meta && meta.getAttribute( "content" ),
        disabledZoom = initialContent + ",maximum-scale=1",
        enabledZoom = initialContent + ",maximum-scale=10",
        enabled = true,
		x, y, z, aig;
    if( !meta ){ return; }
    function restoreZoom(){
        meta.setAttribute( "content", enabledZoom );
        enabled = true; }
    function disableZoom(){
        meta.setAttribute( "content", disabledZoom );
        enabled = false; }
    function checkTilt( e ){
		aig = e.accelerationIncludingGravity;
		x = Math.abs( aig.x );
		y = Math.abs( aig.y );
		z = Math.abs( aig.z );
		// If portrait orientation and in one of the danger zones
        if( !w.orientation && ( x > 7 || ( ( z > 6 && y < 8 || z < 8 && y > 6 ) && x > 5 ) ) ){
			if( enabled ){ disableZoom(); } }
		else if( !enabled ){ restoreZoom(); } }
	w.addEventListener( "orientationchange", restoreZoom, false );
	w.addEventListener( "devicemotion", checkTilt, false );
})( this );

