
jQuery(function($) {
	"use strict";

	//Menu toggle
	$('header nav .menu-icon-left, header nav .menu-icon-right').toggle(function(){
		$('header nav .menu').slideDown('slow');
	}, function(){
		$('header nav .menu').slideUp('slow');
	})

	$( window ).load(function() {
		//Isotope
		if($('.isotope-gutter').length){
			$('.isotope-gutter').isotope({
				itemSelector: '.item',
				layoutMode: 'packery',
				packery : {
					gutter : '.gutter'
				}
			});
		}

		if($('.isotope').length){
			$('.isotope').isotope({
				itemSelector: '.item',
				layoutMode: 'packery'
			});
		}
	});

	//Sliders
	if($('.home-slider .slider, .home-brands .slider, .post-slider').length){
		$('.home-slider .slider, .home-brands .slider, .post-slider').flexslider({
			animation: "slide",
			pauseOnHover: true,
			controlNav: false,
			prevText: "",
			nextText: ""
		});
	}

	if($('.image-box .slider').length){
		$('.image-box .slider').flexslider({
			animation: "slide",
			controlNav: false,
			directionNav: false,
			animationLoop: false,
			slideshow: false,
			itemMargin: 0,
			sync: ".slider-nav"
		});
	}
	if($('.slider-nav').length){
		$('.slider-nav').flexslider({
			animation: "slide",
			direction: "vertical",
			controlNav: false,
			directionNav: false,
			animationLoop: false,
			slideshow: false,
			maxItems: 3,
			minItems: 1,
			asNavFor: ".image-box .slider",
			move: 1,
			itemWidth: 140
		});
	}

	//Touch check
	function isTouchDevice(){
		return typeof window.ontouchstart !== 'undefined';
	}

	//Dropdown
	if($('.dropdown-select, .dropdown').length && isTouchDevice() == false){
		var $selects = $('select');

		$selects.easyDropDown({
			cutOff: 10,
			wrapperClass: 'dropdown-select, dropdown',
			onChange: function(selected){
				// do something
			}
		});
	}

	//UI Price
	if($('.rangeSldier_scale').length){
		var min_count = $('.sliderRange_first').val();
		var max_count = $('.sliderRange_last').val();
		$( ".rangeSldier_scale" ).slider({
			range: true,
			min: 0,
			max: 550000,
			values: [ min_count, max_count ],
			slide: function( event, ui ) {
				$( ".sliderRange_first" ).val( ui.values[ 0 ] );
				$( ".sliderRange_last" ).val( ui.values[ 1 ] );
			}
		});
		$( ".sliderRange_first" ).val( $( ".rangeSldier_scale" ).slider( "values", 0 ));

		$( ".sliderRange_last" ).val( $( ".rangeSldier_scale" ).slider( "values", 1 ) );
	}

	//Pop up window
	$('.page-template-about .video .image .overlay i').live('click',function(e){
		$('.page-template-about .video .pop-up').fadeIn('slow');
	});

	$('.single-post-page .wrapper-inside article .image .overlay i').live('click',function(e){
		$('.single-post-page .wrapper-inside article .pop-up').fadeIn('slow');
	});

	if($('.exit').length){
		$('.exit').on('click', function(){
			$('.pop-up').fadeOut('slow');
		});
	}

	//Scroll on reservation page
	var itemCount = $('.reservation-listing .scroll article').length,
		itemWidth = 170,
		itemBox = itemWidth * itemCount;
	$('.reservation-listing .scroll').css('width',itemBox);

	//Scroll
	if($('.scroll-pane').length){
		$('.scroll-pane').jScrollPane();
	}

	//Datepicker
	$('#contact-form-date').datepicker();

	//Tabs
	$(".tabs").tabs({
		collapsible: true
	});

	//Filter for special offers
	function filter_special() {
		var brand=0,body=0,year=0,type=0,fuel= 0,count= 5,min= 0,max=60000;

		$('#brand_select').change(function() {
			brand=$(this).val();
			count=5;
			$.post(ajaxurl,{action:'filterPosts',brand:brand,body:body,year:year,type:type,fuel:fuel,count:count,min:min,max:max},function(data) {
				$('.typical-page .content_box').html(data);
			})
			$('.pagination').hide();
		});

		$('#body_select').change(function() {
			body=$(this).val();
			count=5;
			$.post(ajaxurl,{action:'filterPosts',brand:brand,body:body,year:year,type:type,fuel:fuel,count:count,min:min,max:max},function(data) {
				$('.typical-page .content_box').html(data);
			})
			$('.pagination').hide();
		})

		$('#year_select').change(function() {
			year=$(this).val();
			count=5;
			$.post(ajaxurl,{action:'filterPosts',brand:brand,body:body,year:year,type:type,fuel:fuel,count:count,min:min,max:max},function(data) {
				$('.typical-page .content_box').html(data);
			})
			$('.pagination').hide();
		})

		$('#v_all label').on('click',function() {
			type=$(this).val();
			count=5;
			var c=new Array();
			var checked=$(this).attr("checked");
			var counts=0;
			$('.vehicle_type input').each(function() {
				if($(this).attr("checked")) {
					var l=$(this).val();
					counts=counts+1;
					c.push(l);
				}
			});
			if(checked=='checked') {
				if(counts>1) {
					type=c;
				}
				else {
					type=c;
				}
				$.post(ajaxurl,{action:'filterPosts',brand:brand,body:body,year:year,type:type,fuel:fuel,count:count,min:min,max:max},function(data) {
					$('.typical-page .content_box').html(data);
				});
			}
			else {
				type=c;
				$.post(ajaxurl,{action:'filterPosts',brand:brand,body:body,year:year,type:type,fuel:fuel,count:count,min:min,max:max},function(data) {
					$('.typical-page .content_box').html(data);
				});
			}
			$('.pagination').hide();
		});

		$('#f_all label').on('click',function() {
			fuel=$(this).val();
			count=5;
			var s=new Array();
			var check=$(this).attr("checked");
			var counts=0;
			$('.fuel_type input').each(function() {
				if($(this).attr("checked")) {
					var f=$(this).val();
					counts=counts+1;
					s.push(f);
				}
			});
			if(check=='checked') {
				if(counts>1) {
					fuel=s;
				}
				else {
					fuel=s;
				}
				$.post(ajaxurl,{action:'filterPosts',brand:brand,body:body,year:year,type:type,fuel:fuel,count:count,min:min,max:max},function(data) {
					$('.typical-page .content_box').html(data);
				});
			}
			else {
				fuel=s;
				$.post(ajaxurl,{action:'filterPosts',brand:brand,body:body,year:year,type:type,fuel:fuel,count:count,min:min,max:max},function(data) {
					$('.typical-page .content_box').html(data);
				});
			}
			$('.pagination').hide();
		});

		$('.rangeSlider .ui-slider .ui-slider-handle').on('click', function() {
			min=$(this).val();
			count=5;
			$.post(ajaxurl,{action:'filterPosts',brand:brand,body:body,year:year,type:type,fuel:fuel,count:count,min:min,max:max},function(data) {
				$('.typical-page .content_box').html(data);
			})
			$('.pagination').hide();
		})

		$('.rangeSlider .ui-slider .ui-slider-handle:last-child').on('click', function() {
			max=$(this).val();
			count=5;
			$.post(ajaxurl,{action:'filterPosts',brand:brand,body:body,year:year,type:type,fuel:fuel,count:count,min:min,max:max},function(data) {
				$('.typical-page .content_box').html(data);
			})
			$('.pagination').hide();
		})
	}

	if($('#brand_select')) {
		filter_special();
	}
});

Modernizr.addTest('ipad', function () {
	return !!navigator.userAgent.match(/iPad/i);
});

Modernizr.addTest('iphone', function () {
	return !!navigator.userAgent.match(/iPhone/i);
});

Modernizr.addTest('ipod', function () {
	return !!navigator.userAgent.match(/iPod/i);
});

Modernizr.addTest('appleios', function () {
	return (Modernizr.ipad || Modernizr.ipod || Modernizr.iphone);
});

Modernizr.addTest('positionfixed', function () {
	var test    = document.createElement('div'),
		control = test.cloneNode(false),
		fake = false,
		root = document.body || (function () {
			fake = true;
			return document.documentElement.appendChild(document.createElement('body'));
		}());

	var oldCssText = root.style.cssText;
	root.style.cssText = 'padding:0;margin:0';
	test.style.cssText = 'position:fixed;top:42px';
	root.appendChild(test);
	root.appendChild(control);

	var ret = test.offsetTop !== control.offsetTop;

	root.removeChild(test);
	root.removeChild(control);
	root.style.cssText = oldCssText;

	if (fake) {
		document.documentElement.removeChild(root);
	}

	/* Uh-oh. iOS would return a false positive here.
	 * If it's about to return true, we'll explicitly test for known iOS User Agent strings.
	 * "UA Sniffing is bad practice" you say. Agreeable, but sadly this feature has made it to
	 * Modernizr's list of undectables, so we're reduced to having to use this. */
	return ret && !Modernizr.appleios;
});


// Modernizr.load loading the right scripts only if you need them
Modernizr.load([
	{
		// Let's see if we need to load selectivizr
		test : Modernizr.borderradius,
		// Modernizr.load loads selectivizr and Respond.js for IE6-8
		nope : [ale.template_dir + '/js/libs/selectivizr.min.js', ale.template_dir + '/js/libs/respond.min.js']
	},{
		test: Modernizr.touch,
		yep:ale.template_dir + '/css/touch.css'
	}
]);



jQuery(function($) {
	var is_single = $('#post').length;
	var posts = $('article.post');
	var is_mobile = parseInt(ale.is_mobile);

	var slider_settings = {
		animation: "slide",
		slideshow: false,
		controlNav: false
	}

	$(document).ajaxComplete(function(){
		try{
			if (!posts.length) {
				return;
			}
			FB.XFBML.parse();
			gapi.plusone.go();
			twttr.widgets.load();
			pin_load();
		}catch(ex){}
	});

	// open external links in new window
	$("a[rel$=external]").each(function(){
		$(this).attr('target', '_blank');
	});

	$.fn.init_posts = function() {
		var init_post = function(data) {
			// close other posts
			data.post.siblings('.open-post').find('a.toggle').trigger('click', {
				hide:true
			});

			var loading = data.post.find('span.loading');

			if (data.more.is(':empty')) {
				data.post.addClass('post-loading');
				loading.css('visibility', 'visible');
				data.more.load(ale.ajax_load_url, {
					'action':'aletheme_load_post',
					'id':data.post.data('post-id')
				}, function(){
					loading.remove();
					data.more.slideDown(400, function(){
						data.post.addClass('open-post');
						data.toggler.text('Close Post');
						$('.video', data.more).fitVids();
						if (data.scroll) {
							data.scroll.scrollTo('fast');
						}
					});
					init_comments(data.post);
				});
			} else {
				data.more.slideDown(400, function(){
					data.post.addClass('open-post');
					data.toggler.text('Close Post');
					if (data.scroll) {
						data.scroll.scrollTo('fast');
					}
				});
			}
		}

		var load_post = function(e, _opts) {
			e.preventDefault();
			var data  = {
				toggler:$(this),
				scroll:false
			};
			var opts = $.extend({
				comments:false,
				hide:false,
				add_comment:false
			}, _opts);
			data.post = data.toggler.parents('article.post');
			data.more = data.post.find('.full');

			if (data.more.is(':visible')) {
				if (opts.hide == true) {
					// quick hide for multiple posts
					data.more.hide();
				} else {
					data.more.slideUp(400);
				}
				data.toggler.text('Open Post');
				data.post.removeClass('open-post');
			} else {
				if (typeof(e.originalEvent) != 'undefined' ) {
					data.scroll = data.post;
				}
				init_post(data);
			}
		}

		var init_comments = function(post) {
			var respond = $('section.respond', post);
			var respond_form = $('form', respond);
			var respond_form_error = $('p.error', respond_form);
			//var respond_cancel = $('.cancel-comment-reply a', respond);
			var comments = $('section.comments', post);

			/*$('a.comment-reply-link', post).on('click', function(e){
			 e.preventDefault();
			 var comment = $(this).parents('li.comment');
			 comment.find('>div').append(respond);
			 respond_cancel.show();
			 respond.find('input[name=comment_post_ID]').val(post.data('post-id'));
			 respond.find('input[name=comment_parent]').val(comment.data('comment-id'));
			 respond.find('input:first').focus();
			 }).attr('onclick', '');

			 respond_cancel.on('click', function(e){
			 e.preventDefault();
			 comments.after(respond);
			 respond.find('input[name=comment_post_ID]').val(post.data('post-id'));
			 respond.find('input[name=comment_parent]').val(0);
			 $(this).hide();
			 });
			 */
			respond_form.ajaxForm({
				'beforeSubmit':function(){
					respond_form_error.text('').hide();
				},
				'success':function(_data){
					var data = $.parseJSON(_data);
					if (data.error) {
						respond_form_error.html(data.msg).slideDown('fast');
						return;
					}
					var comment_parent_id = respond.find('input[name=comment_parent]').val();
					var _comment = $(data.html);
					var list;
					_comment.hide();

					if (comment_parent_id == 0) {
						list = comments.find('ol');
						if (!list.length) {
							list = $('<ol class="commentlist "></ol>');
							comments.find('.scrollbox .jspContainer .jspPane').append(list);
						}
					} else {
						list = $('#comment-' + comment_parent_id).parent().find('ul');
						if (!list.length) {
							list = $('<ul class="children"></ul>');
							$('#comment-' + comment_parent_id).parent().append(list);
						}
						respond_cancel.trigger('click');
					}
					list.append(_comment);
					_comment.fadeIn('fast');
					//.scrollTo();

					respond.find('textarea').clearFields();
				},
				'error':function(response){
					var error = response.responseText.match(/\<p\>(.*)<\/p\>/)[1];
					if (typeof(error) == 'undefined') {
						error = 'Something went wrong. Please reload the page and try again.';
					}
					respond_form_error.html(error).slideDown('fast');
				}
			});
		}
		$(this).each(function(){
			var post = $(this);
			// init post galleries
			$(window).load(function(){
				$('.preview .flexslider', post).flexslider(slider_settings);
			});
			// do not init ajax posts & comments for mobile
			if (!is_mobile) {
				// ajax posts enabled
				if (ale.ajax_posts) {
					$('a.toggle', post).click(load_post);
					$('.video', post).fitVids();
					$('.preview figure a', post).click(function(e){
						e.preventDefault();
						$(this).parents('article.post').find('a.toggle').trigger('click');
					});
				}
			}
		});
		// init ajax comments on a single post if ajax comments are enabled
		if (is_single && parseInt(ale.ajax_comments)) {
			init_comments(posts);
		}
		// open single post on page
		if (parseInt(ale.ajax_open_single) && !is_single && posts.length == 1) {
			posts.find('a.toggle').trigger('click');
		}
	}
	posts.init_posts();

	$.fn.init_gallery = function() {
		$(this).each(function(){
			var gallery = $(this);
			$(window).load(function(){
				$('.flexslider', gallery).flexslider(slider_settings);
			});

		})
	}
	$('#gallery').init_gallery();

	$.fn.init_archives = function()
	{
		$(this).each(function(){
			var archives = $(this);
			var year = $('#archives-active-year');
			var months = $('div.months div.year-months', archives);
			var arrows = $('a.up, a.down', archives);
			var activeMonth;
			var current, active;
			var animated = false;
			if (months.length == 1) {
				arrows.remove();
				activeMonth = months.filter(':first').addClass('year-active').show();
				year.text(activeMonth.attr('id').replace(/[^0-9]*/, ''));
				return;
			}
			arrows.click(function(e){
				e.preventDefault();
				if (animated) {
					return;
				}
				var fn = $(this);
				animated = true;
				arrows.css('visibility', 'visible');
				var current = months.filter('.year-active');
				if (fn.hasClass('up')) {
					active = current.prev();
					if (!active.length) {
						active = months.filter(':last');
					}
				} else {
					active = current.next();
					if (!active.length) {
						active = months.filter(':first');
					}
				}
				current.removeClass('year-active').fadeOut(150, function(){
					active.addClass('year-active').fadeIn(150, function(){
						animated = false;
					});
					year.text(active.attr('id').replace(/[^0-9]*/, ''));

					if (fn.hasClass('up')) {
						if (!active.prev().length) {
							arrows.filter('.up').css('visibility', 'hidden');
						}
					} else {
						if (!active.next().length) {
							arrows.filter('.down').css('visibility', 'hidden');
						}
					}
				});
			});
			activeMonth = months.filter(':first').addClass('year-active').show();
			year.text(activeMonth.attr('id').replace(/[^0-9]*/, ''));
			arrows.filter('.up').css('visibility', 'hidden');
		});
	}
	$('#archives .ale-archives').init_archives();

});

// HTML5 Fallbacks for older browsers
jQuery(function($) {
	// check placeholder browser support
	if (!Modernizr.input.placeholder) {
		// set placeholder values
		$(this).find('[placeholder]').each(function() {
			$(this).val( $(this).attr('placeholder') );
		});

		// focus and blur of placeholders
		$('[placeholder]').focus(function() {
			if ($(this).val() == $(this).attr('placeholder')) {
				$(this).val('');
				$(this).removeClass('placeholder');
			}
		}).blur(function() {
				if ($(this).val() == '' || $(this).val() == $(this).attr('placeholder')) {
					$(this).val($(this).attr('placeholder'));
					$(this).addClass('placeholder');
				}
			});

		// remove placeholders on submit
		$('[placeholder]').closest('form').submit(function() {
			$(this).find('[placeholder]').each(function() {
				if ($(this).val() == $(this).attr('placeholder')) {
					$(this).val('');
				}
			});
		});
	}
});

