// jQuery.fn.reverse = function() {
// 	return this.pushStack(this.get().reverse(), arguments);
// };

$(function(){
	
	var zs = 2;
	$('.scroll-layout #main:not(.alt) #items-nav .item-nav').mouseenter(function(){
		$(this).css('z-index', zs); zs++;
		$(this).find('.details').stop(true, true).slideDown(200);
		$(this).siblings().find('.details').hide();
	});
	$('.scroll-layout #main:not(.alt) #items-nav .item-nav').mouseleave(function(){
		$(this).find('.details').slideUp(200);
	});

	$('input[type="checkbox"]').hide().wrap('<span class="checkbox" />');
	$('.checkbox').each(function(){
		// console.log($(this).find('input').attr('checked'));
		if($(this).find('input').attr('checked')) {
			$(this).addClass('checked');
		} else {
			$(this).addClass('unchecked');
		}
	});
	$('.checkbox, .check label').click(function(){
		if($(this).closest('.input').find('input').attr('checked')) {
			// uncheck
			$(this).closest('.input').find('input').attr('checked', false);
			$(this).closest('.input').find('.checkbox').removeClass('checked');
			$(this).closest('.input').find('.checkbox').addClass('unchecked');
		} else {
			// check
			$(this).closest('.input').find('input').attr('checked', true);
			$(this).closest('.input').find('.checkbox').removeClass('unchecked');
			$(this).closest('.input').find('.checkbox').addClass('checked');
		}
		return false;
	});
	
	$('.scroll-layout #items .item .gallery').each(function(){
		// console.log($(this).closest(".item").find(".contents .more .prev").html());
		// console.log($(this).closest(".item").attr('id'));
	});
	
	$('.scroll-layout #items .item .gallery, .on-your-lot .gallery').each(function(){
		var start = $(this).closest('.item');
		var prev = $(start.find('.contents .more .prev'));
		var next = $(start.find('.contents .more .next'));
		// $(prev, next).click(function(e) { e.preventDefault(); });
		$(this).cycle({
			fx: 'fade',
			speed: 400,
			// prev: '$(this).closest(".item").find(".contents .more .prev")',
			// prev: $(this).closest(".item").find(".contents .more .prev"),
			prev: prev,
			next: next,
			timeout: 0
		});
	});
	
	setupValidate('#quick-contact form');
	setupValidate('.contact #main form');
	
	
	$('#quick-contact form, .contact #main form').each(function(){
		var thanks = $(this).find('.thankyou');
		var options = {
			target: thanks,   // target element to update
			beforeSubmit: showLoader,  // pre-submit callback
			resetForm: true,
			success: showResponse  // post-submit callback
		};
		$(this).ajaxForm(options);
	});
	// $('#test').ajaxForm(options);
	
	$('#jsm > li').bind('mouseover', jsm_open);
	$('#jsm > li').bind('mouseout',  jsm_timer);
	// iOS Hover Event Class Fix
	// console.log(navigator.userAgent);
	if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
		$('#jsm > li#drop').bind('click', jsm_open);
		$('#jsm > li ul a').bind('click', function(){
			location.href = $(this).attr('href');
		});
	}
	
	$('.text label, .textarea label').inFieldLabels();
	
	$('a[href^=#]:not(.prev, .next)').bind('click', Jump);

	$(window).scroll(UpdateSidebarPosition);
	UpdateSidebarPosition();

});

function showLoader(array, $form, options) {
	// console.log("thank you");
	// console.log($('#quick-contact form').attr('id'));
	// console.log($($(this)));
	// console.log($form.attr('id'));
	$form.find('button').hide();
	$form.find('.loading').show();
	// $('.text label, .textarea label').inFieldLabels();
	// $(this).closest('.fields').find('input').attr('disabled', 'disabled').css('background', 'red');
	// $('#quickcontact input, #quickcontact button').attr('disabled', 'disabled');
	// $('#quickcontact .thankyou').fadeIn('fast');
	
	// $('#emailusWrapper').fadeOut('fast', function() {
	// 	$('#thankyou').fadeIn('fast');
	// });
}

function showResponse(responseText, statusText, xhr, $form) {
	// setupValidate($form);
	$form.find('.text label:not(.error), .textarea label:not(.error)').css('opacity', '1').css('display', 'block');
	$form.find('.loading').fadeOut(400, function(){
		$form.find('.thankyou').fadeIn(400);
	});
}

function setupValidate(obj) {
	$(obj).validate({
		rules: {
			name: 'required',
			email: {
				required: true,
				email: true
			}
		 },
		 messages: {
			name: 'Required',
			email: 'Invalid'
		}
	});
}


var AmountVisible = function(c) {
	var a = $(window).scrollTop(); //1000
	var b = a + $(window).height(); //1000
	var e = c.offset().top; //1500
	var d = e + c.height(); //2000
	if (d > a && d < b) { //false
		return d - a; //1000
	} else {
		// console.log(c.height() - Math.floor(d));
		// console.log(c.height());
		// console.log(c.height());
		return b - e;
		// return c.height() - Math.floor(e);
	}
};

function UpdateSidebarPosition() {
	var headerHeight = $('.scroll-layout header').outerHeight(true) + ($('.scroll-layout #main aside').outerHeight(true) - $('.scroll-layout #main aside').innerHeight());
		// var footerHeight = ($('footer').height()) + ($('footer #swirl').css('marginTop').replace('px', ''));
		var footerHeight = $('.scroll-layout footer').height() + ($('.scroll-layout footer #swirl').outerHeight(true) - $('.scroll-layout footer #swirl').innerHeight() + 1);
		
		var scrollTop = $(window).scrollTop();
		var scrollBottom = $(document).height() - $(window).height() - scrollTop;
		var scrollStop = (scrollBottom - footerHeight) * -1 + $('.scroll-layout #main aside').height();
		// console.log($(window).height() + ', ' + $('#main aside').height());
		if($(window).height() > $('.scroll-layout #main aside').height()) {
			if(scrollTop >= headerHeight && scrollStop <= $(window).height()) {
				$('.scroll-layout #main aside').removeClass().addClass('fixed');
			} else if(scrollStop >= $(window).height()) {
				$('.scroll-layout #main aside').removeClass().addClass('bottom');
			} else {
				$('.scroll-layout #main aside').removeClass();
			}
		}
		SetCurrent();
}

function SetCurrent() {
	var a = null;
	var b = $('.scroll-item:in-viewport');
	// var visibles = '';
	// b.each(function(c) {
	b.each(function() {
	// b.reverse().each(function() {
		// visibles += $(this).attr('id') + ', ';
		var d = $(this);
		if (a == null || AmountVisible(d) >= AmountVisible(a)) {
		// if (a == null || AmountVisible(d) > AmountVisible(a)) {
			a = d;
			// console.log(Math.floor(AmountVisible(d)) + ' ' + Math.floor(AmountVisible(a)));
			// console.log(a.attr('id'));
			// visibles += $(d).attr('id') + ', ';
		}
		// console.log(Math.floor(AmountVisible(d)) + ': ' + d.attr('id'));// + ', ' +
						// Math.floor(AmountVisible(a)) + ': ' + a.attr('id'))
	});
	var aid = $(a).attr('id');
	// console.log(aid);
	if (a && (aid == 'above' || aid == 'footer')) {
		$('.scroll-layout #items-nav .item-nav').removeClass('current')
	} else {
		var current = '.scroll-layout #items-nav .item-nav.' + aid;
		// console.log(current);
		$(current).addClass('current');
		$(current).siblings().removeClass('current');
	}
	// console.log(visibles);
	// console.log(' ');
};

function Jump(e) {
	ScrollTo($($(this).attr('href')));
	e.preventDefault();
	return false;
}

function ScrollTo(target) {
	var timer = 800;
	// console.log(targetz.offset().top);
	$('html, body').animate({
		scrollTop: target.offset().top
	},timer,function(){
		// location.hash = target;
	});
}


// menu =========================

var timeout = 500;
var closetimer = 0;
var ddmenuitem = 0;
var isOpen = false;
function jsm_open() {
	// console.log($(this).get(0));
	jsm_canceltimer();
	jsm_close();
	ddmenuitem = $(this).find('ul').css('visibility', 'visible');
	if (!isOpen) {
		return false;	
	}
	isOpen = true;
}
function jsm_close() {
	if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');
	isOpen = false;
}
function jsm_timer() {
	closetimer = window.setTimeout(jsm_close, timeout);
}
function jsm_canceltimer() {
	if(closetimer) {
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}
document.onclick = jsm_close;


