﻿// === BEGIN Google Analytics ===
var _gaq = _gaq || [];
_gaq.push(['_setAccount', googleAnalyticsId]);
_gaq.push(['_setDomainName', '.julieferrez.com']);
_gaq.push(['_trackPageview']);

(function () {
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
// === END Google Analytics ===

// === BEGIN Facebook initialization ===
window.fbAsyncInit = function () {
	FB.init({
		appId: facebookId, // julie app
		status: false, // check login status
		cookie: true, // enable cookies to allow the server to access the session
		xfbml: true, // parse XFBML
		channelUrl: fbChannelUrl, // channel.html file
		oauth: true // enable OAuth 2.0
	});
};
// === END Facebook initialization ===

$(document).ready(function () {
	// === BEGIN JW Player initialization ===
	if ($("#videoPreHome").length > 0) {
		jwplayer('videoPreHome').setup({
			'flashplayer': jwPlayerFile,
			'width': '692',
			'height': '393',
			'file': videoIntro,
			'skin': jwPlayerSkin,
			'autostart': true,
			'controlbar': { 'position': 'bottom' },
			'plugins': { 'hd-2': { 'file': videoIntroHD} }
		});
	}

	if ($("#videoJulie").length > 0) {
		jwplayer('videoJulie').setup({
			'flashplayer': jwPlayerFile,
			'width': '750',
			'height': '450',
			'file': videoIntro,
			'skin': jwPlayerSkin,
			'autostart': true,
			'controlbar': { 'position': 'bottom' },
			'plugins': { 'hd-2': { 'file': videoIntroHD} }
		});
	}

	if ($("#videoProgramHead").length > 0) {
		jwplayer('videoProgramHead').setup({
			'flashplayer': jwPlayerFile,
			'width': '754',
			'height': '445',
			'file': videoProgramHead,
			'skin': jwPlayerSkin,
			'autostart': true,
			'controlbar': { 'position': 'bottom' }
		});
	}

	if ($("#videoProgramSample").length > 0) {
		jwplayer('videoProgramSample').setup({
			'flashplayer': jwPlayerFile,
			'width': '312',
			'height': '238',
			'file': videoProgramSample,
			'skin': jwPlayerSkin,
			'autostart': false,
			'controlbar': { 'position': 'bottom' }
		});
	}
	// === END JW Player initialization ===

	// === BEGIN slide sur la home page ===
	$('.slideHome').slides({
		play: 5000,
		pause: 5000,
		slideSpeed: 500,
		hoverPause: true
	});
	// === END slide sur la home page ===

	$(document).ajaxStop(function () {
		checkCart();
		$(".js_button").button();
	});

	checkCart();
	$(".js_button").button();

	$("div.article div.priceBox").corner("10px");

	// === BEGIN select size ===
	$(".js_size").live("click", function () {
		var text = $(this).text();
		$(this).closest(".size").find(".selectedSize").text(text)
		$(this).closest(".article").find('input[name="selectedSize"]').val(text);
	});
	// === END select size ===

	// === BEGIN add to cart ===
	$(".js_addToCart").live("click", function () {
		var form = $(this).closest("form");
		if ($(this).closest(".article").find('.size').length == 1 && $(this).closest(".article").find('input[name="selectedSize"]').val() == "0") {
			$("<div>Merci de choisir d'abord votre pointure.</div>").dialog({
				title: "Information",
				modal: true,
				width: "300px",
				buttons: {
					Fermer: function () { $(this).dialog("close"); }
				}
			});
			return false;
		}
		$.get($(form).attr("action"), $(form).serialize(), function (data) {
			$("#cart").replaceWith(data);
			$('html,body').animate({ scrollTop: 0 }, 'slow');
		});
	});
	// === END add to cart ===

	// === BEGIN remove article from cart ===
	$(".js_removeCartItem").live("click", function () {
		var form = $(this).closest("form");
		$.post($(form).attr("action"), $(form).serialize(), function (data) {
			$("#cart").replaceWith(data);
		});
	});
	// === END remove article from cart ===

	// === BEGIN change quantity ===
	$(".js_quantityMinus").live("click", function () {
		var form = $(this).closest("form");
		var quantity = $(form).find('input[name="quantity"]')[0];
		if (!isValidInt(quantity.value)) return false;
		quantity.value = parseInt(quantity.value) - 1;
		$.post($(form).attr("action"), $(form).serialize(), function (data) {
			$("#cart").replaceWith(data);
		});
	});

	$(".js_quantityPlus").live("click", function () {
		var form = $(this).closest("form");
		var quantity = $(form).find('input[name="quantity"]')[0];
		if (!isValidInt(quantity.value)) return false;
		quantity.value = parseInt(quantity.value) + 1;
		$.post($(form).attr("action"), $(form).serialize(), function (data) {
			$("#cart").replaceWith(data);
		});
	});

	$(".js_quantity").live("focusout", function () {
		var form = $(this).closest("form");
		if (!isValidInt(this.value)) return false;
		$.post($(form).attr("action"), $(form).serialize(), function (data) {
			$("#cart").replaceWith(data);
		});
	});
	// === END change quantity ===

	// === BEGIN submit formule and display sips box ===
	$("#js_postSubmit").live("click", function (e) {
		e.preventDefault();
		var form = $(this).closest("form");
		$.post($(form).attr("action"), $(form).serialize(), function (data) {
			if (data.match(/id="ok"/) != null) {
				$("#sips").replaceWith(data);
				$("form.inscriptionForm *").attr("disabled", true);
				$("#cart *").attr("disabled", true);
				$("#cart .js_image, #cart .js_button").hide();
				$(".errMsg").css("display", "none");
			} else {
				$("#pageContent").html(data);
			}
		});
	});
	// === END submit formule and display sips box ===

	// === BEGIN check promo code ===
	$("#js_checkCode").live("click", function (e) {
		var form = $(this).closest("form");
		if ($(form).find('input[name="code"]:enabled').length == 1) {
			$.post($(form).attr("action"), $(form).serialize(), function (data) {
				if (data == "InvalidCode") {
					$("<div>Votre code n'est pas valide.</div>").dialog({
						title: "Erreur",
						modal: true,
						width: "300px",
						buttons: {
							Fermer: function () { $(this).dialog("close"); }
						}
					});
				} else {
					$("#cart").replaceWith(data);
				}
			});
		} else {
			$.get(URL_ClearPromoCode, function (data) {
				$("#cart").replaceWith(data);
			});
		}
	});
	// === END check promo code ===

	// === BEGIN change product photo ===
	$(".productThumbnail").live("mouseover", function () {
		$(this).closest("div.images").find("img.productImage").attr("src", this.src);
	});
	// === END change product photo ===

	// === BEGIN Scroll to top ===
	$(window).scroll(function () {
		if ($(window).scrollTop() == 0) {
			$('#scrollToTop').fadeOut("fast");
		} else {
			if ($('#scrollToTop').length == 0) {
				$('body').append('<div id="scrollToTop">' +
		'<a href="#">Retour en haut</a>' +
		'</div>');
			}
			$('#scrollToTop').fadeIn("fast");
		}
	});

	$('#scrollToTop a').live('click', function (event) {
		event.preventDefault();
		$('html, body').animate({ scrollTop: 0 }, 'slow');
	});
	// === END Scroll to top ===

	// === BEGIN login form ===
	$("#loginButton").click(function (e) {
		e.preventDefault();

		var form = $(this).closest("form");

		$.post(form[0].action, form.serialize(), function (response) {
			if (typeof response.url != "undefined")
				window.location = response.url;
			else alert(response.message);
		}, "json");
	});
	// === END login form ===

	// === BEGIN forgotten password workflow ===
	$("#forgottenPwdBtn").click(function (e) {
		e.preventDefault();
		var value = prompt("Veuillez entrer votre e-mail");

		$.post(this.href, { email: value }, function (response) {
			alert(response.message);
		});
	});
	// === END forgotten password workflow ===

	// === BEGIN input with default value ===
	//$("input.js_input_dyn:not([readonly])").blur(function () {
	//	if (this.value == "")
	//		this.value = this.getAttribute("value");
	//});

	//in IE, this.value always equals this.getAttribute("value")...failed...
	//	$("input.js_input_dyn:not([readonly])").focus(function () {
	//		if (this.value == this.getAttribute("value"))
	//			this.value = "";
	//	});
	$("input.js_input_dyn:not([readonly])").each(function () {
		$(this).attr("alt", this.value);
	});

	$("input.js_input_dyn:not([readonly])").focus(function () {
		if (this.value == this.getAttribute("alt"))
			this.value = "";
	});
	// === END input with default value ===

	// === BEGIN promo ===
	$("#promo").blur(function () {
		if (this.value == "") return;

		var form = $(this).closest("form");

		$.post(form[0].action, form.serialize(), function (response) {
			alert(response.message);
		}, "json");
	});
	// === END promo ===

	// === BEGIN newsletter subscription box ===
	$("#news_sub_button").click(function (e) {
		e.preventDefault();

		var form = $(this).closest("form");

		$.post(form[0].action, form.serialize(), function (response) {
			alert(response.message);
		}, "json");
	});
	// === END newsletter subscription box ===

	// === BEGIN facebook login for filling free checkup form ===
	$("#fb_checkup").click(function (e) {
		var form = $(this).closest("form");
		e.preventDefault();

		FB.getLoginStatus(function (response) {
			if (response.authResponse) {
				fillFreeCheckUpform(form, response.authResponse.userID);
			} else {
				FB.login(function (response) {
					var accessToken = response.authResponse.accessToken;
					var expiresIn = response.authResponse.expiresIn; // temps en secondes au bout duquel le token n'est plus valide.
					// response.authResponse.signedRequest => aucune idée
					var status = response.status; // statut connecté et autres
					var userID = response.authResponse.userID;

					fillFreeCheckUpform(form, userID);
				},
				{ scope: 'email,user_about_me,user_location,user_birthday' }
				);
			}
		});
	});

	function fillFreeCheckUpform(form, userID) {
		var query = FB.Data.query("select first_name,last_name,sex,email,timezone,locale,birthday from user where uid={0}", userID);
		query.wait(function (rows) {
			form.find("input[name='Email']")[0].value = rows[0].email;
			form.find("input[name='Name']")[0].value = rows[0].first_name + " " + rows[0].last_name.toUpperCase();

			if (rows[0].sex == "male")
				form.find("input[name='Sexe'][value='True']")[0].checked = true;
			else form.find("input[name='Sexe'][value='False']")[0].checked = true;
		});
	}
	// === END facebook login for filling free checkup form form ===

	// === BEGIN facebook login for filling subscription form ===
	$("#fb_subscription").click(function () {
		var form = $(this).closest("form");

		FB.getLoginStatus(function (response) {
			if (response.authResponse) {
				fillSubscriptionform(form, response.authResponse.userID);
			} else {
				FB.login(function (response) {
					var accessToken = response.authResponse.accessToken;
					var expiresIn = response.authResponse.expiresIn; // temps en secondes au bout duquel le token n'est plus valide.
					// response.authResponse.signedRequest => aucune idée
					var status = response.status; // statut connecté et autres
					var userID = response.authResponse.userID;

					fillSubscriptionform(form, userID);
				},
				{ scope: 'email,user_about_me,user_location,user_birthday' }
				);
			}
		});
	});

	function fillSubscriptionform(form, userID) {
		var query = FB.Data.query("select first_name,last_name,sex,email,timezone,locale,birthday from user where uid={0}", userID);
		query.wait(function (rows) {
			form.find("input[name='Email']")[0].value = rows[0].email;
			form.find("input[name='Name']")[0].value = rows[0].last_name;
			form.find("input[name='ForName']")[0].value = rows[0].first_name;

			if (rows[0].sex == "male")
				form.find("input[name='IsMale'][value='True']")[0].checked = true;
			else form.find("input[name='IsMale'][value='False']")[0].checked = true;
		});
	}
	// === END facebook login for filling free subscription form ===

	// === BEGIN show testimonials list ===
	$("#js_testimonialsList").click(function (e) {
		e.preventDefault();
		$.get($(this).attr("href"), null, function (data) {
			$(data).dialog({
				modal: true,
				width: "700px"
			});
		});
	});
	// === END show testimonials list ===

	// === BEGIN passage in the prehome ===
	$(".toggle_container2").hide();
	$(".toggle_container1").show();

	$("div.trigger1").click(function () {
		$(".toggle_container2").hide();
		$(".toggle_container1").show();
		$(this).css('color', '#FFFFFF');
		$(this).css('background-image', 'url(' + PRE_HOME_titleBackgroud01_png + ')');
		$("div.trigger2").css('color', '#ED8288');
		$("div.trigger2").css('background-image', 'none');
	});

	$("div.trigger2").click(function () {
		$(".toggle_container1").hide();
		$(".toggle_container2").show();
		$(this).css('color', '#FFFFFF');
		$("div.trigger1").css('color', '#ED8288');
		$(this).css('background-image', 'url(' + PRE_HOME_titleBackgroud02_png + ')');
		$("div.trigger1").css('background-image', 'none');
	});
	// === END passage in the prehome ===

	// === BEGIN image select in checkup questionnaire ===
	$(".votreBilan2 .choixsPhoto img.option").click(function () {
		var container = $(this).closest(".choixsPhoto");

		var selected = $(container).find("img.option[src$='_ROSE.png']");
		if (selected.length > 0) {
			selected = selected[0];
			selected.src = selected.src.replace("_ROSE", "");
		}
		this.src = this.src.replace(".png", "_ROSE.png");

		var index = $(container).find("img.option").index(this) + 1;
		$(container).find("input[type='hidden']")[0].value = "Answer" + index;
	});
	// === END image select in checkup questionnaire ===

	// === BEGIN coloration on menu ===
	if ($("#pageIndex").length > 0) {
		var index = parseInt($("#pageIndex")[0].value);
		$(".menuTop").find("a").eq(index).removeClass("backgroundColorBlack").addClass("backgroundColorRose");
	}
	// === END coloration on menu ===
});


//Tester si la valeur entée est un nombre entier
function isValidInt(val) {
	var re = new RegExp("^\\d+$");
	if (!re.exec(val)) {
		alert("Merci de saisir un entier.");
		return false;
	}
	return true;
}

//afficher ou cacher le panier
function checkCart() {
	if ($("#cart").find(".cartItem").length == 0)
		$("#js_checkOut").removeAttr('href').button({ disabled: true });
	else
		$("#js_checkOut").button();
	$("#cart div.rightPart").corner("5px");
}
