﻿/// <reference path="jquery-vsdoc.js" />
/// <reference path="jquery.form.js" />
/// <reference path="jquery.ui.min.js" />

$(document).ajaxStart(function () {
	$("body").css("cursor", "wait");
}).ajaxStop(function () {
	$("body").css("cursor", "default");
});

$(document).ready(function () {
	$(".menu li").hover(function () {
		$(this).children('ul').show();
		$(this).addClass("over");
	}, function () {
		$(this).children('ul').hide();
		$(this).removeClass("over");
	});

	$(".churrascometro").fancybox({
		transitionIn: 'none',
		transitionOut: 'none',
		type: 'ajax',
		titleShow: false,
		onComplete: bindChurrascometro
	});

	if (location.hash.indexOf("#churrascometro") == 0)
		$('.churrascometro:first').click();

	$(".product .images a").fancybox({
		type: 'image',
		transitionIn: 'none',
		transitionOut: 'none',
		showNavArrows: true,
		titlePosition: 'over'
	});

	$(".products a.fancybox").fancybox({
		type: 'image',
		transitionIn: 'none',
		transitionOut: 'none',
		showNavArrows: true,
		titlePosition: 'over'
	});

	$("a.login").fancybox({
		type: 'ajax',
		href: '/User/LoginModal',
		margin: 100,
		titleShow: false,
		onComplete: function () {
			$("#fancybox-content form").submit(login);
			$("#fancybox-content .lostpassword").click(function (event) {
				event.preventDefault();

				$("#fancybox-content").load("/User/LostPassword", bindLostPassword);
			});
		}
	});

	$(".login form .lostpassword").fancybox({
		type: 'ajax',
		margin: 100,
		titleShow: false,
		onComplete: bindLostPassword
	});

	$(".search").focus(function () {
		if ($(this).val() == "Busca")
			$(this).val("")
	}).blur(function () {
		if ($(this).val() == "")
			$(this).val("Busca")
	});

	$(".newsletter #Email").focus(function () {
		if ($(this).val() == "Seu Email")
			$(this).val("")
	}).blur(function () {
		if ($(this).val() == "")
			$(this).val("Seu Email")
	});

	$("#reuseaddress").change(function () {
		if ($(this).is(":checked") == true) {
			$(".end_entrega input:text,.end_entrega select").addClass("disabled").attr("disabled", "disabled");

			$(".end_entrega").hide();
		} else {
			$(".end_entrega input:text,.end_entrega select").removeClass("disabled").removeAttr("disabled");
			$(".end_entrega").show();
		}
	});

	$(".newsletter form").ajaxForm(function (text) {
		switch (text) {
			case "error": alert("Por favor, preencha seu email corretamente."); break;
			case "already": alert("Este email já está cadastrado."); break;
			default: alert("Assinatura realizada com sucesso."); break;
		}
	});

	$('.share .email').fancybox({
		type: 'ajax',
		href: '/Wessel/SendEmail',
		onComplete: bindSendEmail
	});

	$(".phone").mask("(99) 9999-9999");
	$(".date").datepicker({ showOtherMonths: true, selectOtherMonths: true }).mask("99/99/9999");
	$(".cep").mask("99999-999");

	$(".cadastro .edit form.addresses").submit(saveAddress);

	$('.saved_addresses .address .info').equalizeCols();

	if ($('.content').is('.checkout_address')) {
		var context = $('.cadastro .saved_addresses');

		if ($('#order_postalCode').length > 0 && $('#order_postalCode').val() != '') {
			if ($('.address[data-cep=' + $('#order_postalCode').val() + ']', context).length > 0) {
				$('.address[data-cep=' + $('#order_postalCode').val() + ']', context).addClass('selected');
				$('#Shipping_ID').val($('.address[data-cep=' + $('#order_postalCode').val() + ']', context).data('id'));
			} else {
				var form = $('.end_entrega');
				$("#PostalCode", form).val($('#order_postalCode').val());
				getAddress(form, $("#PostalCode", form).get(0));
			}
		} else {
			$('.address:has(.label):first', '.cadastro .saved_addresses').addClass('selected');
		}

		if ($('#Shipping_ID').val() != '0') {
			$('.address.selected', context).removeClass('selected');
			$('.address[data-id=' + $('#Shipping_ID').val() + ']', context).addClass('selected');
		}
	}

	if ($('.content').is('.content_carrinho')) {
		$('.total_buy .postal .select').click(function (event) {
			event.preventDefault();
			$(this).blur();

			$('.postalcodes').toggle('slide', { direction: 'right' }, 500)
		});

		$('.postalcodes a').click(function (event) {
			event.preventDefault();
			$(this).blur();

			$('#zipcode').val($(this).text());
			$('.postalcodes').hide('slide', { direction: 'right' }, 500)
			$('#form-shipping').submit();
		});
	}

	$('.account').hover(function () {
		$('.account_menu').show();
	}, function () {
		$('.account_menu').hide();
	});

	EnableCheckout();

	$(".quickbuy").click(function (event) {
		event.preventDefault();
		$(this).blur();
	}).each(function () {
		$(this).qtip({
			content: {
				text: '<span class="loading">Carregando...</span>',
				ajax: {
					url: getQuickBuyUrl($(this).attr('href'))
				}
			},
			position: {
				my: 'bottom center',
				at: 'top center',
				viewport: $(window), // Keep the tooltip on-screen at all times
				effect: false // Disable positioning animation
			},
			show: {
				event: 'click',
				solo: true // Only show one tooltip at a time
			},
			hide: 'unfocus',
			style: {
				classes: 'ui-tooltip-quickbuy ui-tooltip-rounded ui-tooltip-light ui-tooltip-shadow'
			}
		});
	});

	// qTip jGrowl

	window.createGrowl = function (text, title, color, persistent) {
		// Use the last visible jGrowl qtip as our positioning target
		var target = $('.qtip.jgrowl:visible:last');

		color = color || 'dark';
		persistent = persistent || false;
		title = title || 'Aviso!';

		// Create your jGrowl qTip...
		$(document.body).qtip({
			// Any content config you want here really.... go wild!
			content: {
				text: text,
				title: {
					text: title,
					button: true
				}
			},
			position: {
				my: 'top right', // Not really important...
				at: (target.length ? 'bottom' : 'top') + ' right', // If target is window use 'top right' instead of 'bottom right'
				target: target.length ? target : $('.content'), // Use our target declared above
				adjust: { y: 5} // Add some vertical spacing
			},
			show: {
				event: false, // Don't show it on a regular event
				ready: true, // Show it when ready (rendered)
				effect: function () { $(this).stop(0, 1).fadeIn(400); }, // Matches the hide effect
				delay: 0, // Needed to prevent positioning issues

				// Custom option for use with the .get()/.set() API, awesome!
				persistent: persistent
			},
			hide: {
				event: false, // Don't hide it on a regular event
				effect: function (api) {
					// Do a regular fadeOut, but add some spice!
					$(this).stop(0, 1).fadeOut(400).queue(function () {
						// Destroy this tooltip after fading out
						api.destroy();

						// Update positions
						updateGrowls();
					})
				}
			},
			style: {
				classes: 'jgrowl ui-tooltip-' + color + ' ui-tooltip-rounded', // Some nice visual classes
				tip: false // No tips for this one (optional ofcourse)
			},
			events: {
				render: function (event, api) {
					// Trigger the timer (below) on render
					timer.call(api.elements.tooltip, event);
				}
			}
		})
			.removeData('qtip');
	};

	// Make it a window property see we can call it outside via updateGrowls() at any point
	window.updateGrowls = function () {
		// Loop over each jGrowl qTip
		var each = $('.qtip.jgrowl:not(:animated)');
		each.each(function (i) {
			var api = $(this).data('qtip');

			// Set the target option directly to prevent reposition() from being called twice.
			api.options.position.target = !i ? $(document.body) : each.eq(i - 1);
			api.set('position.at', (!i ? 'top' : 'bottom') + ' right');
		});
	};

	// Setup our timer function
	function timer(event) {
		var api = $(this).data('qtip'),
         lifespan = 5000; // 5 second lifespan

		// If persistent is set to true, don't do anything.
		if (api.get('show.persistent') === true) { return; }

		// Otherwise, start/clear the timer depending on event type
		clearTimeout(api.timer);
		if (event.type !== 'mouseover') {
			api.timer = setTimeout(api.hide, lifespan);
		}
	}

	// Utilise delegate so we don't have to rebind for every qTip!
	$(document).delegate('.qtip.jgrowl', 'mouseover mouseout', timer);

	$('.notification').each(function () {
		var title = 'Aviso!', color = 'dark';

		if ($(this).is('.error')) {
			title = 'Erro!';
			color = 'red';
		}

		if ($(this).is('.alert')) {
			title = 'Atenção!';
			color = 'yellow';
		}

		if ($(this).is('.success')) {
			title = 'Sucesso!';
			color = 'green';
		}

		createGrowl($(this).text(), title, color);
	});
});

Sys.Mvc.ValidatorRegistry.validators.mustMatch = function (rule) {
	var propertyIdToMatch = rule.ValidationParameters.propertyIdToMatch;
	var message = rule.ErrorMessage;

	return function (value, context) {

		var thisField = context.fieldContext.elements[0];
		var propertyIdToMatch = thisField.id.replace(/_[a-zA-Z0-9]$/, propertyIdToMatch);
		var otherField = $get(propertyIdToMatch, thisField.form);

		if (otherField.value != value) {
			return false;
		}

		return true;

	};
};

/**
 *
 * Copyright (c) 2007 Tom Deater (http://www.tomdeater.com)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 */
 
(function($) {
	/**
	 * equalizes the heights of all elements in a jQuery collection
	 * thanks to John Resig for optimizing this!
	 * usage: $("#col1, #col2, #col3").equalizeCols();
	 */
	 
	$.fn.equalizeCols = function(){
		var height = 0,
			reset = $.browser.msie && $.browser.version < 7 ? "1%" : "auto";
  
		return this
			.css("height", reset)
			.each(function() {
				height = Math.max(height, $(this).outerHeight());
			})
			.css("height", height)
			.each(function() {
				var h = this.offsetHeight;
				if (h > height) {
					$(this).css("height", height - (h - height));
				};
			});
			
	};
	
})(jQuery);
