﻿var Genifique = {};

Genifique.ConnectCallbacks = new Array();
Genifique.DisconnectCallbacks = new Array();
Genifique.FBInitializedCallbacks = new Array();
Genifique.FacebookUnavailable = function() { alert((location.toString().indexOf('en-ca') > 0) ? 'We are currently unable to retrieve information from your Facebook account. This might be due to your network settings, or the connexion to Facebook might be unavailable at the moment. Please try again later.' : 'Nous sommes présentement dans l\'incapacité de récupérer les informations de votre compte Facebook, en raison de votre configuration réseau ou de l\'indisponibilité de la connexion Facebook. Veuillez réessayer plus tard.'); };

Genifique.SendGA = function(votedAge, realAge, delta) {
	if (typeof (_gaq) != "undefined") {
		_gaq.push(['_trackPageview', '/flash/resultat-age']);
		_gaq.push(['_trackEvent', 'vote', votedAge.toString(), realAge.toString(), delta.toString()]);
	}
};

Genifique.IsFBDefined = function() {
	return (typeof (window["FB"]) == "undefined") ? false : true;
}

Genifique.OnConnect = function(fnct) {
	if (typeof fnct != "function")
		throw "Must be a function";
	Genifique.ConnectCallbacks.push(fnct);
};

Genifique.OnDisconnect = function(fnct) {
	if (typeof fnct != "function")
		throw "Must be a function";
	Genifique.DisconnectCallbacks.push(fnct);
};

Genifique.OnFBInitialized = function(fnct) {
	if (typeof fnct != "function")
		throw "Must be a function";
	Genifique.FBInitializedCallbacks.push(fnct);
};

Genifique.Facebook = {};

Genifique.Facebook.OnConnect = function() {
	for (var i = 0; i < Genifique.ConnectCallbacks.length; i++)
		Genifique.ConnectCallbacks[i]();
};

Genifique.Facebook.OnDisconnect = function(d) {
	for (var i = 0; i < Genifique.DisconnectCallbacks.length; i++)
		Genifique.DisconnectCallbacks[i]();
}

if (Genifique.IsFBDefined()) {
	Genifique.Connect = function(callback) {
		FB.ensureInit(function() {
			FB.Connect.showPermissionDialog("publish_stream", function(perms) {
				if (typeof callback == 'function')
					callback();
				Genifique.Facebook.OnConnect();
			});
		});
	};

	Genifique.Disconnect = function(callback) {
		FB.Connect.logout(function() {
			if (typeof callback == 'function')
				callback();
			Genifique.Facebook.OnDisconnect();
		});
	};

	Genifique.IsConnected = function(callback) {
		FB.ensureInit(function() {
			FB.Connect.get_status().waitUntilReady(function(status) {
				if (typeof callback == 'function')
					callback(status == FB.ConnectState.connected);
			});
		});
	};

	FB.init("aeea4690fa9c4bba8db16f2e972dcfc5", "/xd_receiver.htm");

	$(document).ready(function() {
		FB.ensureInit(function() {
			for (var i = 0; i < Genifique.FBInitializedCallbacks.length; i++)
				Genifique.FBInitializedCallbacks[i]();
		});
	});
}
else {
	Genifique.Connect = Genifique.FacebookUnavailable;
	Genifique.Disconnect = Genifique.FacebookUnavailable;
	Genifique.IsConnected = function(callback) { callback(false); };
}

//////////////////////////////////////////////////////////////
// Cropping Tool
//////////////////////////////////////////////////////////////

Genifique.CroppingTool = function(size, id, objContainer, objSlider) {
	if (typeof size != "number" || size <= 0)
		throw "The cropping tool size must be a positive int";

	if (typeof id != "string")
		throw "The cropping tool id must be a string";

	if (typeof objContainer != "object")
		throw "The cropping tool container must be a DOM object";

	if (typeof objSlider != "object")
		throw "The cropping factor slider must be a DOM object";

	this.Size = size;
	this.Handle = $('<div></div>').attr('id', id).appendTo(objContainer).css({ "overflow": "hidden", "position": "relative", "width": size, "height": size });
	this.Slider = $(objSlider).slider();
};

Genifique.CroppingTool.prototype.Size = undefined;
Genifique.CroppingTool.prototype.Handle = undefined;
Genifique.CroppingTool.prototype.Slider = undefined;
Genifique.CroppingTool.prototype.Image = undefined;
Genifique.CroppingTool.prototype.MaxFactor = undefined;
Genifique.CroppingTool.prototype.MinFactor = undefined;
Genifique.CroppingTool.prototype.OriginalWidth = undefined;
Genifique.CroppingTool.prototype.OriginalHeight = undefined;

Genifique.CroppingTool.prototype.InitializeWithImage = function(url) {
	if (typeof url != "string")
		throw "The url must be a string";

	var ct = this;
	this.Handle.empty();
	this.Image = $('<img />').css({ "position": "absolute", "top": this.Size, "width": "auto", "height": "auto", "cursor": "move" }).attr("src", url);
	this.Handle.append(this.Image);
	this.Slider.hide();

	$('body').css('cursor', 'wait');
	(waitforLoad = function() {
		if (ct.Image.width() <= 0 || ct.Image.height() <= 0 || (ct.Image.width() == 28 && ct.Image.height() == 30)) {
			setTimeout(function() { waitforLoad(); }, 50);
			return;
		}
		else {
			ct.OriginalWidth = ct.Image.width();
			ct.OriginalHeight = ct.Image.height();
			ct.MinFactor = ct.OriginalWidth > ct.OriginalHeight ? ct.RoundFactor(ct.Size / ct.OriginalHeight) : ct.RoundFactor(ct.Size / ct.OriginalWidth);
			ct.MaxFactor = ct.RoundFactor(ct.MinFactor + 0.75);
			ct.Slider.slider('destroy');
			ct.Slider.slider({ slide: function(event, ui) { ct.OnFactorChangeRequest(event, ui); }, value: ct.MinFactor, min: ct.MinFactor, max: ct.MaxFactor, step: 0.025 });
			ct.Image.draggable();
			ct.RecenterOriginal();
			ct.ChangeFactor(ct.MinFactor);
			ct.Slider.show();
			$('body').css('cursor', 'auto');
		}
	})();
};

Genifique.CroppingTool.prototype.OnFactorChangeRequest = function(event, ui) {
	this.ChangeFactor(ui.value);
};

Genifique.CroppingTool.prototype.ChangeFactor = function(factor) {
	var position = this.Image.position();
	var halfViewport = Math.floor(this.Size / 2);
	var newHeight = Math.ceil(factor * this.OriginalHeight);
	var newWidth = Math.ceil(factor * this.OriginalWidth);
	var ratioX = (-position.left + halfViewport) / this.Image.width();
	var newLeft = Math.floor(-((ratioX * newWidth) - halfViewport));
	var ratioY = (-position.top + halfViewport) / this.Image.height();
	var newTop = Math.floor(-((ratioY * newHeight) - halfViewport));

	if (newLeft > 0)
		newLeft = 0;
	if (newTop > 0)
		newTop = 0;
	if (-newLeft > (newWidth - this.Size))
		newLeft = -(newWidth - this.Size);
	if (-newTop > (newHeight - this.Size))
		newTop = -(newHeight - this.Size);

	this.Image.css({ "width": newWidth, "height": newHeight, "left": newLeft, "top": newTop });

	var pos = this.Handle.offset();
	var deltaX = this.Image.width() - this.Size;
	var deltaY = this.Image.height() - this.Size;
	this.Image.draggable('option', 'containment', [-deltaX + pos.left, -deltaY + pos.top, pos.left, pos.top]);
};

Genifique.CroppingTool.prototype.RecenterOriginal = function() {
	this.Image.css({ "left": Math.floor((this.Size - this.OriginalWidth)) / 2, "top": Math.floor((this.Size - this.OriginalHeight)) / 2 });
};

Genifique.CroppingTool.prototype.RoundFactor = function(factor) {
	return Math.ceil(factor * 100) / 100;
};

Genifique.CroppingTool.prototype.SerializeCurrentState = function() {
	var position = this.Image.position();
	var infos = '';

	infos += 'width=' + Math.ceil(this.Image.width());
	infos += '&height=' + Math.ceil(this.Image.height());
	infos += '&cropx=' + -position.left;
	infos += '&cropy=' + -position.top;
	infos += '&cropwidth=' + this.Size;
	infos += '&cropheight=' + this.Size;
	infos += '&image=' + escape(this.Image.attr('src'));

	return infos;
};

Genifique.CroppingTool.prototype.SerializeCurrentStateJSON = function() {
	var position = this.Image.position();
	return {
		width: Math.ceil(this.Image.width()),
		height: Math.ceil(this.Image.height()),
		cropx: -position.left,
		cropy: -position.top,
		cropwidth: this.Size,
		cropheight: this.Size,
		image: this.Image.attr('src')
	};
};

//////////////////////////////////////////////////////////////
// Google Analytics
//////////////////////////////////////////////////////////////
$('#hplLancome, #hplBuyOnline, #productCoupon').click(function() { if (typeof (_gaq) != 'undefined') { _gaq.push(['_trackEvent', 'exit', window.location.href, this.href]); } });
$('#imgProducts').click(function() { if (typeof (_gaq) != 'undefined') { _gaq.push(['_trackPageview', window.location.pathname + window.location.search + (window.location.search > 0 ? '&' : '?') + 'utm_action=gamme_genifique']); } });
$('#hplTermsOfUse').click(function() { if (typeof (_gaq) != 'undefined') { _gaq.push(['_trackPageview', window.location.pathname + window.location.search + (window.location.search > 0 ? '&' : '?') + 'utm_action=conditions_utilisation']); } });
$('#hplContest').click(function() { if (typeof (_gaq) != 'undefined') { _gaq.push(['_trackPageview', window.location.pathname + window.location.search + (window.location.search > 0 ? '&' : '?') + 'utm_action=concours']); } });

