// Init jQuery
var $ 			= jQuery.noConflict();
var ajaxurl 	= MyAjax.ajaxurl;
var pluginDIR 	= '/wp-content/plugins/truckmanager/';

// Get/Create the PDF of a single vehicle
function downloadVehiclePDF(vehicleID, pdfTitle, thisURL)
{
	showOverlay('<h3>Getting PDF. Please wait...</h3>');
	// Run ajax script to see if this PDF currently exists
	// If it doesn't exist, create a new copy.
	var formdata 	= "action=vehiclePDF_check&id="+vehicleID+"&title="+pdfTitle+"&url="+thisURL;
	// Submit ajax
	$.post( ajaxurl, formdata)
		.done(function( data ) {
			showOverlay('<h3>Now Downloading PDF</h3>');
			var win = window.open(data, '_blank');
			if (win) {
			    //Browser has allowed it to be opened
			    win.focus();
			} else {
			    //Browser has blocked it
			    showOverlay('<h3>Your download is ready.</h3><p>Please click the button below.</p><a class="download-pdf-btn" href="'+data+'" download>DOWNLOAD</a>');
			}
	});
}

// Show Ask Question Overlay
function askQuestion(postID, vehicleName)
{
	var overlayHTML = '<h3>Ask a question about the vehicle</h3><form class="vehicle_question_form" id="vehicle_question_form" name="vehicle_question_form">';
	overlayHTML += '<div class="overlay-form-row"><label>Name<sup>*</sup></label><input type="text" id="vehicle_question_name" name="vehicle_question_name" /></div>';
	overlayHTML += '<div class="overlay-form-row"><label>Email<sup>*</sup></label><input type="text" id="vehicle_question_email" name="vehicle_question_email" /></div>';
	overlayHTML += '<div class="overlay-form-row"><label>Confirm Email<sup>*</sup></label><input type="text" id="vehicle_question_email_confirm" name="vehicle_question_email_confirm" /></div>';
	overlayHTML += '<div class="overlay-form-row"><label>Question<sup>*</sup></label><textarea id="vehicle_question" name="vehicle_question"></textarea></div>';
	overlayHTML += '<div class="overlay-form-row"><label>Vehicle</label><input type="text" id="vehicle_question_post_title" name="vehicle_question_post_title" value="'+vehicleName+'" readonly /></div>';
	overlayHTML += '<input type="hidden" id="vehicle_question_id" name="vehicle_question_id" value="'+postID+'" />';
	overlayHTML += '<div class="overlay-form-row"><a onClick="submitQuestion(this);">Submit Question</a></div></form>';
	showOverlay(overlayHTML);
}
// Submit the 'Ask Question' form
function submitQuestion(ele)
{
	var e 			= $(ele);
	e.hide();
	//var con_email 	= $("#vehicle_question_email_confirm").val();
	var email 		= $("#vehicle_question_email").val();
	var userName 	= $("#vehicle_question_name").val();
	var question 	= $("#vehicle_question").val();
	var validEmail 	= validateEmail(email);
	var form 		= $("#vehicle_question_form");
	var gCaptcha = grecaptcha.getResponse();

	if( validEmail == true && email != "" && userName != "" && question != "" )
	//if( email == con_email && validEmail == true && email != "" && userName != "" && question != "" )
	{
		showOverlay('<div id="fountainG" class="loading-holder"><div id="fountainG_1" class="fountainG"></div><div id="fountainG_2" class="fountainG"></div><div id="fountainG_3" class="fountainG"></div><div id="fountainG_4" class="fountainG"></div><div id="fountainG_5" class="fountainG"></div><div id="fountainG_6" class="fountainG"></div><div id="fountainG_7" class="fountainG"></div><div id="fountainG_8" class="fountainG"></div></div>');
		var formdata 	= form.serialize()+"&action=submitAskQuestion&cap="+gCaptcha;

		$.post( ajaxurl, formdata)
			.done(function( data ) {
				showOverlay('<img style="width: 70%;margin: 0 auto 20px;text-align: center;display: block;" src="/wp-content/themes/fleetex/libs/images/Fleetex-Logo.png" /><h3>Thank you for your enquiry!</h3><p>Your message has been sent successfully.</p><p>A member of our sales team will be in contact as soon as possible.</p>');
				$('.vehicleask-form-control').val('');
				dataLayer.push({'event': 'enquire_form'});
				ga('send', 'event', 'Enquire Now', 'Submission', 'Truck Contact');
		});
	}
	else
	{
		alert('Please make sure you have completed all of the mandatory fields.');
		e.show();
	}
}

function validateEmail(email) 
{
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}

// Show Send to Friend Overlay
function showSendToFriend(postID, postTitle, thisURL)
{
	$.get( pluginDIR+"html-templates/pop-up-sendtofriend.html", function( data ) 
	{
		var htmlContent = data.replace("###truck###", postTitle);
		htmlContent 	= htmlContent.replace("###trucklink###", thisURL);
		htmlContent 	= htmlContent.replace("###truckid###", postID);
		showOverlay(htmlContent);

	});
}
// SUBMIT Send to Friend
function submitSendToFriend(ele)
{
	$(ele).hide();
	var form 		= $("#form_sendtofriend");
	form.children('.input_content').hide(400);
	var formdata 	= form.serialize()+"&action=submitSendtoFriend";

	$.post( ajaxurl, formdata)
		.done(function( data ) {
			form.children('.complete_content').show(400);
	});
}

// SHOW Youtube Video
function openYoutubeVideo(youtubeCode)
{
	var html = '<div id="popup-youtube"><iframe width="700" height="400" src="https://www.youtube.com/embed/'+youtubeCode+'?&autoplay=1" frameborder="0" allowfullscreen></iframe></div>';
	showOverlay(html, 'large');
}

// Add functionality to the next/prev buttons on the main img
function vehicleImgSlider(direction)
{
	var mainImg = $("#vehicle-current-image img");
	var listImg = $("#vehicle-img-thumbail-list");
	var actItem	= listImg.children('li.active');
	if( direction == 'next' )
	{
		var isLast 	= actItem.is(':last-child');	
		if( isLast == true )
		{
			var liItem 	= listImg.children('li:first-child');
		}
		else
		{
			var liItem 	= actItem.next('li');
		}
		
	}
	else
	{
		var isFirst = actItem.is(':first-child');
		if( isFirst == true )
		{
			var liItem 	= listImg.children('li:last-child');
		}
		else
		{
			var liItem 	= actItem.prev('li');
		}
		
	}
	var showIMG = liItem.data('img');
	// Change IMG & Change Active List Item
	actItem.removeClass('active');
	liItem.addClass('active');
	mainImg.attr('src', showIMG);
}

// Show image on the main slider by clicking a thumbnail
$("#vehicle-img-thumbail-list li").click(function() 
{
	var mainImg = $("#vehicle-current-image img");
	var liItem = $(this);
	var listImg = $("#vehicle-img-thumbail-list");
	var showIMG = liItem.data('img');
	listImg.children('li').removeClass('active');
	liItem.addClass('active');
	mainImg.attr('src', showIMG);
});


function showOverlay(content, cssClass)
{
	if (cssClass === undefined) {
        cssClass = "no";
    }

	if( cssClass != 'no' )
	{
		$('#site-overlay-centre').addClass(cssClass);
	}
	$('#site-overlay-content').html(content);
	$("#site-overlay").fadeIn(400, function() {
		$('html, body').animate({
        	scrollTop: $("#site-overlay-content").offset().top -100
    	}, 500);
	});


}

function hideOverlay()
{
	$("#site-overlay").fadeOut('400', function() {
		$('#site-overlay-content').empty();
		$('#site-overlay-centre').attr('class', '');
	});
}

// Get List of Vehicles in Fleet
function getFleetList(fleetID, currentPost, e)
{
	var fleetListHolder = $("#fleet-list-"+fleetID);
	var ele = $(e);
	ele.hide();
	fleetListHolder.html('<p id="fleet-loading">Loading...</p><div id="fountainG"><div id="fountainG_1" class="fountainG"></div><div id="fountainG_2" class="fountainG"></div><div id="fountainG_3" class="fountainG"></div><div id="fountainG_4" class="fountainG"></div><div id="fountainG_5" class="fountainG"></div><div id="fountainG_6" class="fountainG"></div><div id="fountainG_7" class="fountainG"></div><div id="fountainG_8" class="fountainG"></div></div>');
	$('#fleet-list-title-'+fleetID).hide();
	$('#fleet-grey-border-'+fleetID).hide();
	var formdata 	= "action=getFleetList&fleetID="+fleetID+"&currentPost="+currentPost;
	$.post( ajaxurl, formdata)
		.done(function( data ) {
			//console.log(data);
			fleetListHolder.html(data);
	});
}

$('#hideOverlay').click(hideOverlay);


function singleTruck_recentlyViewed()
{
	var rvContentHolder = $('#recently_viewed_truck_content')
	var rvContentNumber	= rvContentHolder.length;
	// If content holder exists get the content via Ajax
	if( rvContentNumber == 1 )
	{
		var formdata 	= "action=getRecentlyViewed";
		$.post( ajaxurl, formdata)
			.done(function( data ) {
				rvContentHolder.html(data);
			});
	}
}

function slideshowArrowClick(direction)
{
	var mainImg = $("#vehicle-current-image img");
	var listImg = $("#vehicle-img-thumbail-list");
	var actItem	= listImg.children('li.active');
	if( direction == 'next' )
	{
		var isLast 	= actItem.is(':last-child');	
		if( isLast == true )
		{
			var liItem 	= listImg.children('li:first-child');
		}
		else
		{
			var liItem 	= actItem.next('li');
		}
		
	}
	else
	{
		var isFirst = actItem.is(':first-child');
		if( isFirst == true )
		{
			var liItem 	= listImg.children('li:last-child');
		}
		else
		{
			var liItem 	= actItem.prev('li');
		}
		
	}
	var showIMG = liItem.data('img');
	// Change IMG & Change Active List Item
	actItem.removeClass('active');
	liItem.addClass('active');
	$('#slideshow-currentimg').attr('src', showIMG);
}

function openSlideShow()
{
	$("#site-overlay-centre").hide();
	// Current IMG
	var currentIMG 	= $('#vehicle-current-image img').attr('src');
	var overlayHTML = "<div id='truck-slideshow-holder'><a onClick='closeSlideshow();' id='truck-slideshow-close'><i class='fa fa-times' aria-hidden='true'></i></a>";
	overlayHTML += "<div id='slideshow-currentimg-holder'><img id='slideshow-currentimg' src='"+currentIMG+"' />";
	overlayHTML += "<a onClick='slideshowArrowClick(\"prev\");' id='slideshow-arrow-prev-btn' class='slideshow-arrow-btn'><i class='fa fa-caret-left' aria-hidden='true'></i></a>";
	overlayHTML += "<a onClick='slideshowArrowClick(\"next\");' id='slideshow-arrow-next-btn' class='slideshow-arrow-btn'><i class='fa fa-caret-right' aria-hidden='true'></i></a>";
	overlayHTML += "</div></div>";
	
	$("#site-overlay").append(overlayHTML).fadeIn(400);
}

function closeSlideshow()
{
	$("#site-overlay").fadeOut('400', function() {
		$("#site-overlay-centre").show();
		$("#truck-slideshow-holder").remove();
	});
}

function showMobileSearch()
{
	var overlayHTML = $("#mobile-search-overlay").html();
	showOverlay(overlayHTML, 'mobile-search');
}

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

	// Check that for recently viewed.
	//singleTruck_recentlyViewed();

	$("#vehicle-sort-order").change(function(event) {
		var e  		= $(this);
		var val 	= e.val();
		if( val != '0')
		{
			var order 	= "?order="+val;
			window.location.href = order;
		}
	});

	$("#vehicle-tractor-sort-type").change(function(event) {
		var e  		= $(this);
		var val 	= e.val();
		if( val != '0')
		{
			var tractorType 		= "/vehicle-type/tractor-units/?type="+val;
			window.location.href 	= tractorType;
		}
	});

	$("#vehicle-sort-order-searchpage").blur(function(event) {
		var e  		= $(this);
		var val 	= e.val();
		if( val != '0')
		{
			window.location.href = val;
		}
	});

	$("#show-all-truck-enquiries").click(function(event) {
		$('.truck-enquiry-tablerow.hidden').removeClass('hidden');
		$(this).remove();
	});
});