//------  web.js -------
// Copyright © 2010 by LeKiosque SAS — All Right Reserved
// By SDL on 2010-08-12 9:36
// common js features for web site.
var debug = debug||function(text) { 
	if (typeof console !=="undefined") console.log(text);
};
//alert("debug? "+debug);

// -----
var fbAppId = "5767084252"; //cats
var supportModalSignIn = false;

var Search = {
	defaultString : "Magazine, quotidien, mot-clés",
	defaultCodePromo : "Code promo"
};


// ----- Categories -----
var Category = {
	home:			0
}
var CategoryInfo = {
	home: 			{name:"Accueil",id:0,isAdult:0}
}
var CategoryTree = null;

//var currentCategory = null; //Category.home;

function _redirectToCategory(category) {
	
	// cache useless redirections
	//if (currentCategory!=null && currentCategory == category) return;
	//currentCategory = category;
	
	// homepage, not category
	if (category==0) {
		$(location).attr("href", "index.html");
		return;
	}
	
	
	// category page
	
	/*
	if ($(location).attr("href").match(/index.*?\.html/)) {
		$("li[class=active]").removeClass("active");
		var p = $(this).parent();
		p.addClass("active");
	}
	else {
		*/
	var url = urlCategory(category);
	for(cat in CategoryInfo){
		if(CategoryInfo[cat]["id"]==category){
			if(CategoryInfo[cat]["isAdult"] && !isAuthenticated()){
				url = "signin.html?url="+escape(urlCategory(CategoryInfo[cat]["id"], CategoryInfo[cat]["name"]));
				break;
			}
			else{
				url = urlCategory(CategoryInfo[cat]["id"], CategoryInfo[cat]["name"]);
				break;
			}
		}
	}
	$(location).attr("href", url);
	//}
}


function getCategories() {
	
	ApiLK.apiCall({
		url: ApiLK.getCategories(),
		async: false,
		success: function(ws) {
			//var ws = object["ws"];
			CategoryTree = ws["response"]["ArrayOfCategory"]["category"];
			if(!CategoryTree.length) {
				alert("Pas de catégorie disponible.");
				return;
			}
			$.each(CategoryTree, function(j,c) {
				Category[c["Title"]] = parseInt(c["ID"]);
				CategoryInfo[c["Title"]] = {name: c["Title"], id: parseInt(c["ID"]), isAdult:(c["IsAdult"]=="false"?0:1)};
			});
		},
		error: function(req,str,e) {
			alert(str);
			return;
		}
	});
}

function populateHeaderAndFooterCategories() {
	var html ="";
	//currentCategory = $.cookie('category')||Category.home;
	currentCategory = getUrlParameter("catId")||Category.home;
	
	
	// header bar
	$.each(Category, function(category, i) {

		html += "<li";
		
		if (i==currentCategory) {
			html += " class=\"active\"";
		}	
		html += ">\n\
			<a id=\"navcategory"+i+"\" href=\"javascript:_redirectToCategory("+i+");\">\n\
				<span>"+CategoryInfo[category]["name"]+"</span>\n\
			</a>\n\
		</li>\n";
	});

	$("#nav").html(html);
	
	$("#nav>li").click(function(e){
		//Cancel the link behavior  
		//e.preventDefault();  
        
		$("li[class=active]").removeClass("active");
		$(this).addClass("active");
// SDL on 2011-03-06: I don't undestand this limitation, I get rid of
if (false) {
		if (/category.html/i.test($(location).attr("href"))
			|| /(category|categorie)-(\d+)-.*/i.test($(location).attr("href"))) {
			$("li[class=active]").removeClass("active");
			$(this).addClass("active");
		}
		else {
			//$(location).attr("href", "category.html?catId="+$(this).attr());
		}
}
	});
	
	
	// footer bar, spread on 5-row columns
	var j=0;
	html = "<ul>\n";
	$.each(Category, function(category, i) {
		if (i==0) {
			//html += "<!-- skip ()"+CategoryInfo[category]["name"]+", "+i+") -->\n";
			return;	// skip homepage
		}
		html += "\
		<li>\n\
			<a href=\"javascript:_redirectToCategory("+i+");\">\n\
				<span>"+CategoryInfo[category]["name"]+"</span>\n\
			</a>\n\
		</li>\n";
		j++;
		
		if (j%5==0) html += "</ul>\n<ul>\n";
	});
	

	html += "</ul>\n";

	$("#footerCats").html(html);
}




function populateAllMagazineCategories() {
	// construit le tableau des catégories
	var html = "\n";
	var i = 1;
	$.each(CategoryTree, function(j,c) {	
		// Rangées de 5 colonnes
		if(i <= 5 && j != 2 && j != 3) {
			html += "<div class=\"box\">\n\
						<h3>"+c["Title"]+"</h3>\n\
			";
			var children = c["Children"];
			if (children)
			{
				html += "<ul>\n";
				$.each(children, function(k,ch){
					html += "\
					<li>\n\
						<a href=\"javascript:_redirectToCategory("+CategoryTree[j]["ID"]+");\">"+ch["Title"]+"</a>\n\
					</li>\
					\n";
				});
				html += "</ul>\n";
			}
			html += "</div>\n";
			i++;
		}
	});
	$("#J-block").html(html);
}




// ----- sign in/ou /off -----
function goToLogin() {
	if (autoSignIn()) return;
	
	redirectTo("signin.html");
}
function goToLoginAndGoBackHere(sessionExpired) {
	if (autoSignIn()) return;

	if (sessionExpired) alert("Votre session a expirée, vous allez devoir vous reconnecter…");
	
	redirectTo("signin.html?url="+escape($(location).attr("href")));	
}
function signIn() {
	
	if (supportModalSignIn) showModalWindow("#signin");
	
	$("#signin-login").val($.cookie("login"));
	//redirectTo("login.html");
}
function signOut() {
	ApiLK.signOut();
	deleteCookie("encryptedPassword");
	deleteCookie("sessionId");
	deleteCookie("isAdult");
	deleteCookie("login");
	//deleteCookie("Cart");
	redirectTo(urlHomepage());
	return;
}
function signOff() {
	
}

// ------ redirects -------
function startSearch() {
	var search = $("#search").val();
	
	if (!search.length
		|| /Magazine, quotidien, mot-clés/i.test(search)){ alert("Veuillez saisir le nom de la publication ou le mot à rechercher.");return; }
	
	$(location).attr("href",urlSearch(escape(search)));
}


// ------ redirects -------
function redirectToHome() {
	if (isAuthenticated()) {
		$(location).attr("href","indexin.html");
		return;
	}
	$(location).attr("href","index.html");
}

//------- facebook --------
function facebookInclude() {
	var e = document.createElement('script');
	e.async = true;
	//e.src = /*document.location.protocol + */'http://connect.facebook.net/en_US/all.js';
	e.src = protocol+'connect.facebook.net/en_US/all.js';
    document.getElementById('fb-root').appendChild(e);
 }

function facebookListener(response) {
	if (response.session) {
  		// A user has logged in, and a new cookie has been saved
	} else {
  		// The user has logged out, and the cookie has been cleared
	}
}

// change CSS 
function performChanging(){

	if(!isBoulanger) return;
	
	$("head").append("<link type=\"text/css\" rel=\"stylesheet\" href=\"css/boulanger.css\" />");
	footerWhiteLabel(isBoulanger);
}

var exp = /lekiosque\.fr/ig;
var expExclude = /((@)|(\.)lekiosque\.fr)|(lekiosque-eu)/ig;
jQuery.expr[':'].Contains = function(a, i, m) { 

	// If having children	
	if($(a).children().size() > 0)
		return false;
	// If not in Exclude filter
	if(expExclude.test($(a).text()))
		return false;
	// Replacement
	return exp.test($(a).text());
  //return jQuery(a).text().match(/m[3]/ig); 
};

function footerWhiteLabel(isBoulanger){

	if(isBoulanger){
		
		//$("div[class=main-info]").remove();
		// Title update
		$(document).attr("title", $("title").html()
									.replace(exp, ' Le kiosque presse de Boulanger'));
		// Access Category
		if(/category\.access\.html/i.test(document.location.href)){
			$("#loginForm>fieldset").html($.load("Boulanger/boulanger.category.access.html"));
		}
		// FAQ email
		else if(/faq\.html/i.test(document.location.href)){
			$("a[href=mailto:contact@lekiosque.fr]").html("contactboulanger@lekiosque.fr");
			$("a[href=mailto:contact@lekiosque.fr]").attr("href", "mailto:contactboulanger@lekiosque.fr");
		}
		// Ads For Category
		else if(/category|categorie/.test(document.location.href)){
			
			$("div[class=ad]").html('<iframe title="Le kiosque première application iPad: le premier kiosque à journaux 3D au monde !" width="300" height="243" src="http://www.youtube.com/embed/hVZQq-wMI9g?controls=0&autoplay=0" frameborder="0" allowfullscreen></iframe>'
			);
		}
		
		// Logo redirect
		$("#header>div[class=header-holder]>strong[class=logo]>a").attr("href", "http://www.boulanger.fr");
		// Bannière
		$("div[class=advantages-box]").removeAttr("style");
		$("div[class=advantages-box]").removeAttr("onclick");
		$("#groupon").remove();
		// Contact
		$("#sidebar>div[class=block]>div[class=holder]").html($.load("Boulanger/contact.boulanger.fragment.html"));
		// Remplacer la like box facebook
		$("#facebooklike").html($.load("Boulanger/facebook.likebox.boulanger.fragment.html"));
		// Remove Twitter
		$("#twitterlike").remove();
		// Footer
		$("#footer").html($.load("Boulanger/footer.boulanger.fragment.html"));
		// load gallery content via a fragment
		//var html = $.load("Boulanger/gallery.boulanger.fragment.html");
		//$('div.intro-gallery').html(html);
		// Lien vers page d'accueil
		if(/signup\.html/.test(document.location.href)){
			$("div.number-column").append($.load("Boulanger/boulanger.retour.fragment.html"));
		}
		// Remplacer Lekiosque par Le kiosque presse de Boulanger
		if(!/cgv\.html/i.test(document.location.href)){
			
			var elements = [];
			elements.push($("body").find("div:Contains('')"));
			elements.push($("body").find("a:Contains('')"));
			elements.push($("body").find("h2:Contains('')"));
			elements.push($("body").find("h3:Contains('')"));
			elements.push($("body").find("p:Contains('')"));
			elements.push($("body").find("li:Contains('')"));
			elements.push($("body").find("span:Contains('')"));
			elements.push($("body").find("strong:Contains('')"));
			elements.push($("body").find("td:Contains('')"));

			$.each(elements, function(i, e){
				if($(e).html()){
					
					if($(e).length > 1){
					
						$.each($(e), function(i, h){
							if($(h)) $(h).html($(h).html().replace(exp, ' Le kiosque presse de Boulanger'));
						});
					}
					else{
						$(e).html($(e).html().replace(exp, ' Le kiosque presse de Boulanger'));
					}
				}
			});
		}
		// Banner Up Right
		$("#bannerupright").html($.load("Boulanger/banner.nl.upright.fragment.html"));
	}
}

// ------ iPAD surfing ----
// The first time, propose to load the iPad App when surfing from the iPad
function proposeIPadAppIfNecessary() {
	if (!isiPad) return;

	if (getCookie("redirectToAppStoreForLeKiosqueOnIPad")) return;
	setCookie("redirectToAppStoreForLeKiosqueOnIPad", "asked already");
	
	googleAnalyticsNewQueue();
	
	if (confirm("Vous pouvez télécharger gratuitement notre application iPad depuis l'App Store afin de bénéficier d'une expérience utilisateur hors du commun.\n\nVoulez-vous la télécharger ?")) {
		_gaq.push(['_trackEvent', 'iPad', 'Accepted', 'Accepted to go to the Ap Store to download the app']);
		googleAnalyticsSendQueue();
		// bit.ly is: http://itunes.apple.com/fr/app/le-kiosque/id399639226?mt=8&ls=1&lekiosqueleadfrom=website
		redirectTo("http://bit.ly/pGFqH3");
	}
	else {
		_gaq.push(['_trackEvent', 'iPad', 'Refused', 'Refused to go to App Store to download the app']);
		googleAnalyticsSendQueue();
	}
}

// ----- boot straps -----

function bootHeader() {

	var signPages = /sign(in|up)\.html/.test($(location).attr("href"));
	var supportSocial = false;
	//var supportSocial = !(
	//	signPages
	//||	/category\.access\.html/	.test($(location).attr("href"))
	//||	/account\.html/				.test($(location).attr("href"))
	//||	/referral\.html/			.test($(location).attr("href"))
	//||	/404\.html/					.test($(location).attr("href"))
	//||	/codepromo\.html/					.test($(location).attr("href"))
	//||	/(contact|jobs|kpis|admin)\.html/				.test($(location).attr("href"))
	//);
	
	// include header/footer
	// add header
	var header = $.load("header.fragment.html");
	var cart = new Cart();
	var count = cart.length();
	//for(id in cart.products) count++;
	header = header.replace(/\{cart\.articles\}/i, count+" "+(count>1?"articles":"article"));
	$("#wrapper").append(header);

	// hide the 'Ma bibliothèque' button when in library.html page
	if (document.location.href.indexOf("/library.html") != -1)
		$("#myLibraryButton").css("display", "none");

	// add footer
	var footer = $.load("footer.fragment.html");
	$("body").append(footer);

	
	// sign in and sign up pages
	if (signPages) {	

		// enable sign in/up on all pages but sign pages

		$("#signin-block").hide();
		$("#header>div.header-area").remove();
		$("#nav").remove();
		$("#main").css({"padding-top": "80px"});
		
		// preload user's info
		if ($("#signin-login").length) {
			if ($.cookie("recallLogin")=="true") {
				$("#signin-login").val(($.cookie("login") != null) ? ($.cookie("login")) : (""));
				$("#signin-recall").attr("checked","true");
			}
		}
	}
	else {
		
		if  (isAuthenticated())  {
			$("#login").html("Bonjour "+$.cookie("login"));
			/*
			// SDL on 2010-09-07 16:45 : keep button library according to issue
			if (!/library\.html/i.test($(location).attr("href"))) {
				$("a[href=library.html]").show();
			}
			*/
		}
		else {
			var signInAction = "signin.html";
			
			if (supportModalSignIn) {
				$("body").prepend("<div id=\"modal-mask\"></div>\n");
				$("body").prepend($.load("signin.fragment.html"));	// modal signin fragment
				signInAction = "javascript:signIn();";
			}
			
			$("#signin-block").html("\
			<li id=\"login\">Bonjour</li>\n\
			<li><a href=\""+signInAction+"\">Connexion</a></li>\n\
			<li><a href=\"signup.html\">Inscription</a></li>\n\
			");
			/*
			// SDL on 2010-09-07 16:45 : keep button library according to issue
			$("a[href=library.html]").hide();
			*/
		}
	}
	
	// want social footer?
	if(supportSocial) {
		// add social footer
		var socialFooter =  $.load("footer.social.fragment.html");
		$("div.main-holder").append(socialFooter);
	}
	
	performChanging();
	// search field
	$("#search")
	.focus(function(){
		$(this).val("");
	})
	.blur(function(){
		var search = $(this).val().trim();
		if (!search.length) {
			$(this).val(getCookie("lastSearch")||Search.defaultString);
		}
	});
	
	$("#search").val(getCookie("lastSearch")||Search.defaultString);
	
	// Code Promo field
	$("#codepromoHeader")
	.focus(function(){
		$(this).val("");
	})
	.blur(function(){
		var cp = $(this).val().trim();
		if (!cp.length) {
			$(this).val($.cookie("lastPromoCode")||Search.defaultCodePromo);
		}
	});
	
	$("#codepromoHeader").val($.cookie("lastPromoCode")||Search.defaultCodePromo);
	
	// don't show faq onto itself
	if (/faq\.html/i.test($(location).attr("href"))) {
		$("#faq").hide();
	}

	// Fetch categories and populate
	getCategories();
	populateHeaderAndFooterCategories();
	
	// handle google analytics asynchronuously
	bootGoogleAnalytics();
	// handle facebook asynchronuously
	bootFacebook();             
	
	// build numbering
	if (!isRemote) {
		$("body").prepend(build.getTatoo());
	}
	
	// Tracking Sellers
	var vid = getUrlParameter("vid");
	if(vid){
		setCookieOneHourLifeTime("channel", vid);
	}
	
	// Auto Apply Code Promo
	autoCodePromo();
	
	// The first time, propose to load the iPad App when surfing from the iPad
	proposeIPadAppIfNecessary();
}

function bootHeaderASPX() {
	
	// include header/footer
	// add header

	// hide the 'Ma bibliothèque' button when in library.html page
	if (document.location.href.indexOf("/library.html") != -1)
		$("#myLibraryButton").css("display", "none");

	
	// sign in and sign up pages
		if  (isAuthenticated())  {
			$("#login").html("Bonjour "+$.cookie("login"));
			/*
			// SDL on 2010-09-07 16:45 : keep button library according to issue
			if (!/library\.html/i.test($(location).attr("href"))) {
				$("a[href=library.html]").show();
			}
			*/
		}
		else {
			var signInAction = "signin.html";
			
			if (supportModalSignIn) {
				$("body").prepend("<div id=\"modal-mask\"></div>\n");
				$("body").prepend($.load("signin.fragment.html"));	// modal signin fragment
				signInAction = "javascript:signIn();";
			}
			
			$("#signin-block").html("\
			<li id=\"login\">Bonjour</li>\n\
			<li><a href=\""+signInAction+"\">Connexion</a></li>\n\
			<li><a href=\"signup.html\">Inscription</a></li>\n\
			");
			/*
			// SDL on 2010-09-07 16:45 : keep button library according to issue
			$("a[href=library.html]").hide();
			*/
		}
	
	// search field
	$("#search")
	.focus(function(){
		$(this).val("");
	})
	.blur(function(){
		var search = $(this).val().trim();
		if (!search.length) {
			$(this).val(getCookie("lastSearch")||Search.defaultString);
		}
	});
	
	performChanging();
	$("#search").val(getCookie("lastSearch")||Search.defaultString);
	
	// Code Promo field
	$("#codepromoHeader")
	.focus(function(){
		$(this).val("");
	})
	.blur(function(){
		var cp = $(this).val().trim();
		if (!cp.length) {
			$(this).val($.cookie("lastPromoCode")||Search.defaultCodePromo);
		}
	});
	
	$("#codepromoHeader").val($.cookie("lastPromoCode")||Search.defaultCodePromo);
	
	// Fetch categories and populate
	getCategories();
	populateHeaderAndFooterCategories();
	
	// handle google analytics asynchronuously
	bootGoogleAnalytics();
	// handle facebook asynchronuously
	bootFacebook();             
	
	// build numbering
	if (!isRemote) {
		$("body").prepend(build.getTatoo());
	}
	
	// Tracking Sellers
	var vid = getUrlParameter("vid");
	if(vid){
		setCookieOneHourLifeTime("channel", vid);
	}
	
	// Auto Apply Code Promo
	autoCodePromo();
	
	// The first time, propose to load the iPad App when surfing from the iPad
	proposeIPadAppIfNecessary();
}

// ----- boot straps -----

function bootHeaderAdminSI(location) {

    var signPages = /sign(in|up)\.html/.test($(location).attr("href"));
    var supportSocial = false;
    //var supportSocial = !(
    //	signPages
    //||	/category\.access\.html/	.test($(location).attr("href"))
    //||	/account\.html/				.test($(location).attr("href"))
    //||	/referral\.html/			.test($(location).attr("href"))
    //||	/404\.html/					.test($(location).attr("href"))
    //||	/codepromo\.html/					.test($(location).attr("href"))
    //||	/(contact|jobs|kpis|admin)\.html/				.test($(location).attr("href"))
    //);

    // include header/footer
    // add header
    var header = $.load(location + "/header.fragment.html");
    var cart = new Cart();
    var count = cart.length();
    //for(id in cart.products) count++;
    header = header.replace(/\{cart\.articles\}/i, count + " " + (count > 1 ? "articles" : "article"));
    $("#wrapper").append(header);

    // hide the 'Ma bibliothèque' button when in library.html page
    if (document.location.href.indexOf("/library.html") != -1)
        $("#myLibraryButton").css("display", "none");

    // add footer
    var footer = $.load(location + "/footer.fragment.html");
    $("body").append(footer);


    // sign in and sign up pages
    if (signPages) {

        // enable sign in/up on all pages but sign pages

        $("#signin-block").hide();
        $("#header>div.header-area").remove();
        $("#nav").remove();
        $("#main").css({ "padding-top": "80px" });

        // preload user's info
        if ($("#signin-login").length) {
            if ($.cookie("recallLogin") == "true") {
                $("#signin-login").val(($.cookie("login") != null) ? ($.cookie("login")) : (""));
                $("#signin-recall").attr("checked", "true");
            }
        }
    }
    else {

        if (isAuthenticated()) {
            $("#login").html("Bonjour " + $.cookie("login"));
            /*
            // SDL on 2010-09-07 16:45 : keep button library according to issue
            if (!/library\.html/i.test($(location).attr("href"))) {
            $("a[href=library.html]").show();
            }
            */
        }
        else {
            var signInAction = "signin.html";

            if (supportModalSignIn) {
                $("body").prepend("<div id=\"modal-mask\"></div>\n");
                $("body").prepend($.load("signin.fragment.html")); // modal signin fragment
                signInAction = "javascript:signIn();";
            }

            $("#signin-block").html("\
			<li id=\"login\">Bonjour</li>\n\
			<li><a href=\"" + signInAction + "\">Connexion</a></li>\n\
			<li><a href=\"signup.html\">Inscription</a></li>\n\
			");
            /*
            // SDL on 2010-09-07 16:45 : keep button library according to issue
            $("a[href=library.html]").hide();
            */
        }
    }

    // want social footer?
    if (supportSocial) {
        // add social footer
        var socialFooter = $.load("footer.social.fragment.html");
        $("div.main-holder").append(socialFooter);
    }

    performChanging();
    // search field
    $("#search")
	.focus(function () {
	    $(this).val("");
	})
	.blur(function () {
	    var search = $(this).val().trim();
	    if (!search.length) {
	        $(this).val(getCookie("lastSearch") || Search.defaultString);
	    }
	});

    $("#search").val(getCookie("lastSearch") || Search.defaultString);

    // Code Promo field
    $("#codepromoHeader")
	.focus(function () {
	    $(this).val("");
	})
	.blur(function () {
	    var cp = $(this).val().trim();
	    if (!cp.length) {
	        $(this).val($.cookie("lastPromoCode") || Search.defaultCodePromo);
	    }
	});

    $("#codepromoHeader").val($.cookie("lastPromoCode") || Search.defaultCodePromo);

    // don't show faq onto itself
    if (/faq\.html/i.test($(location).attr("href"))) {
        $("#faq").hide();
    }

    // Fetch categories and populate
    getCategories();
    populateHeaderAndFooterCategories();

    // handle google analytics asynchronuously
    bootGoogleAnalytics();
    // handle facebook asynchronuously
    bootFacebook();

    // build numbering
    if (!isRemote) {
        $("body").prepend(build.getTatoo());
    }

    // Tracking Sellers
    var vid = getUrlParameter("vid");
    if (vid) {
        setCookieOneHourLifeTime("channel", vid);
    }

    // Auto Apply Code Promo
    autoCodePromo();

    // The first time, propose to load the iPad App when surfing from the iPad
    proposeIPadAppIfNecessary();
}

function autoCodePromo(){
	var code = getUrlParameter("cp");
	if(!code) return;
	
	setCookie("lastPromoCode", code);

	var retour = applyPromoCode(code);
	if(retour){
		alert(retour);
		deleteCookie("lastPromoCode");
		if(/indexin\.html/i.test($(location).attr("href"))){
			getLibrarySnapShot();
		}
		else if(/magazine-(\d+)/i.test($(location).attr("href"))){
			location.reload();
		}
	}
	else{ 
		
		alert("Le code promo saisi est invalide.");
	}
}

function saveCodePromo(){
	var code = getUrlParameter("cp");
	if(!code) return;
	
	setCookie("lastPromoCode", code);
}

function bootFacebook() {
	
	// handle facebook asynchronuously
	$("body").prepend(
	"<div id=\"fb-root\"></div>\n\
	<script type=\"text/javascript\">\n\
		window.fbAsyncInit = function() {\n\
			FB.init({appId: fbAppId, status: true, cookie: true, xfbml: true});\n\
			FB.Event.subscribe('auth.sessionChange', facebookListener);\n\
		};\n\
		(function() {facebookInclude();}());\n\
	</script>\n\
	");
}

//------- google --------
/*
function googleAnalyticsInclude() {
	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);
}
*/
var _gaq = _gaq||[];

//var secondTracker; 
//var timeTracker = new TimeTracker();
function googleAnalyticsNewQueue() {
	
	// If Boulanger
	if(/presse-numerique\.boulanger\.fr/ig.test(document.location.href)){
		//_gaq.push(['pageTracker._setAccount', 		'UA-423812-8']);
		//_gaq.push(['loadTracker._setAccount', 		'UA-423812-8']);
		_gaq.push(['_setAccount', 		'UA-423812-8']);
		return;
	}
	else if(/(beta|test)\.lekiosque\.fr/ig.test(document.location.href)){
		// Beta Site 
		//_gaq.push(['pageTracker._setAccount', 		'UA-423812-6']);
		//_gaq.push(['loadTracker._setAccount', 		'UA-423812-6']);
		_gaq.push(['_setAccount', 		'UA-423812-6']);
	}
	else if(/www\.lekiosque\.fr/ig.test(document.location.href)){
		// LeKiosque 
		//_gaq.push(['pageTracker._setAccount', 		'UA-423812-4']);
		//_gaq.push(['loadTracker._setAccount', 		'UA-423812-4']);
		_gaq.push(['_setAccount', 		'UA-423812-4']);
	} 
	else
		return;

	_gaq.push(['_setDomainName', 	'.lekiosque.fr']);
}

// Time Traking
function googleTrackPageLoadTime(){
	timeTracker._recordEndTime();
	timeTracker._track(secondTracker);
}

// init queue
googleAnalyticsNewQueue();
_gaq.push(['_trackPageview']);	// track page
//_gaq.push(function() {

//});
//timeTracker._recordStartTime();

function googleAnalyticsSendQueue() {
	//if (!_gaq) return;
	//if (!_gaq.length) return;
	
	(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);
	  //secondTracker = _gat._createTracker('UA-423812-4');
	})();
}

// End Time Tracking
function googleAnalyticsEndTimeTracking() {
	/*
	var plend = new Date();
	var plload = plend.getTime() - plstart.getTime();
	if(plload<1000)
		lc = "Very Fast";
	else if (plload<2000)
		lc = "Fast";
	else if (plload<3000)
		lc = "Medium";
	else if (plload<5000)
		lc = "Sluggish";
	else if (plload<10000)
		lc = "Slow";
	else
		lc="Very Slow";

	var fn = document.location.pathname;
	if( document.location.search)
		fn += document.location.search;
		
	try {
		_gaq.push(['_trackEvent','Page Load (ms)',lc + ' Loading Pages',fn,plload]);
	} catch(err){}   
	*/
}


var lekiosqueGaFireWall = false;
function bootGoogleAnalytics() {
	if (lekiosqueGaFireWall) {
		return;
	}
	lekiosqueGaFireWall = true;
	
	googleAnalyticsSendQueue();
}

function notImplemented(txt) {
	alert("Not yet implemented: "+txt);
}


// Load history

function loadHistory(issueId) {	
	// include header/footer
	var history = $.load("body.history.consultation.html");
	$("#history-place").html(history);

	populateHistoryConsultation(issueId);
}

function populateHistoryConsultation(issueId){
	var url = ApiLK.getConsultationHistory(issueId);
	if(url){
		$.ajax ({
			url: url,
			dataType: "json",
			success: function(object) {
				var ws = object["ws"];
				var response = ws["response"];
				if(response){
					if(response["ArrayOfIssue"]){
						populateHistory(response["ArrayOfIssue"]["issue"]);
					}
				}
			},
			error: function(req,str,e) {
			}
		});
	}
	else
	{
		$("#history-place").css("display", "none");
	}
}
function getHistorySimilars(pubId){
	var retour = null;
	var url = ApiLK.getSimilars(pubId);
	
	$.ajax ({
		url: url,
		dataType: "json",
		async: false,
		success: function(object) {
			var ws = object["ws"];
			var response = ws["response"];
			if(response){
				if(response["ArrayOfIssue"]){
					retour = response["ArrayOfIssue"]["issue"];
				}
			}
		},
		error: function(req,str,e) {
		}
	});
	return retour;
}


function checkexistingmail(email){
	var retour = null;
	var url = ApiLK.checkexistingmail(email);
	
	$.ajax ({
		url: url,
		dataType: "json",
		async: false,
		success: function(object) {
			var ws = object["ws"];
			var response = ws["response"];
			if(response){
				if(response["boolean"]){
					retour = response["boolean"];
					alert(retour);
				}
			}
		},
		error: function(req,str,e) {
		alert('rien');
		}
	});
	return retour;
}


function populateHistory(history){
	if(history){
		var html = "";
		if(!history.length) history = [history];
		
		var id = "";
		$.each(history, function(i, s){
			id += s["IDPublication"] + ",";
			html += "<li>\
						<a href=\"javascript:redirectTo(urlProduct("+s["ID"]+", '"+s["Publication"].replace(/'/g, "\\'")+"'));\">"+s["Publication"]+"</a>"+getShortLocalDate(s["DateParution"])+"\n\
					</li>\n";
		});
		id = id.substring(0, id.lastIndexOf(","));
		
		$("#historyaside>ul").html(html);
		if(id){
			var similars = getHistorySimilars(id);
			if(similars){
				html = "";
				if(!similars.length) similars = [similars];
				$.each(similars, function(i, s){
					html += '<li>\
								<table style="width:94px"><tr><td class="img-holder" style="padding:0; margin:0;vertical-align:bottom;height:134px">\n\
									<a href="{urlredirect}">\
										<img class="cover" src="{urlcover}" alt="{publication}" style="max-width:94px; max-height:134px" />\n\
									</a>\n\
								</td></tr></table>\n\
								<strong><a href="{urlredirect}">{publication}</a></strong>\n\
								<span>{dateparution}</span>\n\
							</li>\n'
							.replace(/\{urlredirect\}/ig, urlProduct(s["ID"], s["Publication"]))
							.replace(/\{urlcover\}/ig, s["URLCover"].replace(/Detail/ig, "Categorie"))
							.replace(/\{publication\}/ig, s["Publication"])
							.replace(/\{dateparution\}/ig, getShortLocalDate(s["DateParution"]));
				});
				$("#historygallery>div.gallery-hold>ul").html(html);
				$('div.history-box div.gallery').gallery({
					duration: 300,
					autoRotation: 5000,
					listOfSlides: 'div.gallery-hold>ul>li'
				});
			}
		}
	}
	else
	{
		$("#history-place").css("display", "none");
	}
}

// Lost Password //
function showLostPassword(){
	if($("#divlostpassword").css("display")=="none"){
		$("#divlostpassword").css("display", "block");
	}
	else{
		$("#divlostpassword").css("display", "none");
	}
}
		
function getPassword(){
	if($("#lostpassword").val()){
		$("#divlostpassword>img").css("display", "block");
		var url = ApiLK.getPassword($("#lostpassword").val());

		$.ajax ({
			url: url,
			dataType: "json",
			success: function(object) {
				var ws = object["ws"];
				var response = ws["response"];
				if(response){
					if(response["boolean"]=="true"){
						alert("Vous receverez un mail avec votre nouveau mot de passe, dans les minutes qui suivent votre demande.");
					}
					else{
						alert("Un problème est survenu lors du traitement de votre demande, nous vous invitons à essayer utltérieurement.");
					}
				}
				else{
					alert($("#lostpassword").val() + " ne correspond à aucun de nos client.\nVeuillez saisir une adresse mail valide.");
				}
				$("#divlostpassword>img").css("display", "none");
			},
			error: function(req,str,e) {
				alert("Impossible de donner suite à votre demande.\nVeuillez contactez le service client.");
				$("#divlostpassword>img").css("display", "none");
			}
		});
	}
	else{
		alert("Veuillez saisir votre adresse mail.");
	}
}

// Pager
var pagerHtmlFragment__ = null;

function getPager(pages, pageNumber, callMethod, params, pagerFragmentName){
	//alert("getPager("+pages+", "+pageNumber+", "+callMethod+", "+params+", "+pagerFragmentName+")");
	var pager = pagerHtmlFragment__||(pagerHtmlFragment__=$.load(pagerFragmentName||"paging.fragment.html"));	// add to cache, don't reload again & again & again
	var pagerHtml = "";
	var start = 1+(DefaultValues.PagingEnd*Math.floor((pageNumber-1)/DefaultValues.PagingEnd));
	var end = start+(DefaultValues.PagingEnd-DefaultValues.PagingStart);

	var jsCall = callMethod+"({pageNumber}";
		$.each(params, function(i, p){
			jsCall+=", "+p;
		});

	if(end > pages)
		end = pages
		
	if(start>DefaultValues.PagingEnd){

		pagerHtml += "<li>{page}</li>\n"
			.replace(/\{page\}/ig, "<a href=\"javascript:"+jsCall.replace(/\{pageNumber\}/ig, 1)+");\">1</a>");
		pagerHtml += "<li>{page}</li>\n"
		.replace(/\{page\}/ig, "<a href=\"javascript:"+jsCall.replace(/\{pageNumber\}/ig, (start-1))+");\">…</a>");
	}
	if(pageNumber>0){
		var lnkP = "";
		if(pageNumber>1){
			var url = "javascript:"+jsCall.replace(/\{pageNumber\}/ig, (pageNumber-1))+");\"";
			lnkP = "<a href=\""+url+"\" class=\"prev\">«</a>";
		}
		pager = pager.replace(/\{urlPrevious\}/ig, lnkP);
	}
			
	for(var i = start; i<=end; i++){
		pagerHtml += "<li>{page}</li>\n"
		.replace(/\{page\}/ig, (i==pageNumber)?"<strong>"+i+"</strong>":"<a href=\"javascript:"+jsCall.replace(/\{pageNumber\}/ig, i)+");\">"+i+"</a>");
	}
		
	if(pages>end){
		pagerHtml += "<li>{page}</li>\n"
		.replace(/\{page\}/ig, "<a href=\"javascript:"+jsCall.replace(/\{pageNumber\}/ig, (end+1))+");\">…</a>");			pagerHtml += "<li>{page}</li>\n"
		.replace(/\{page\}/ig, "<a href=\"javascript:"+jsCall.replace(/\{pageNumber\}/ig, pages)+");\">"+pages+"</a>");
	}
	if(end<=pages){
		var lnkS = "";
		if(pageNumber<pages){
			var url = "javascript:"+jsCall.replace(/\{pageNumber\}/ig, (pageNumber+1))+");\"";
			lnkS = "<a href=\""+url+"\" class=\"next\">»</a>";
		}
		pager = pager.replace(/\{urlNext\}/ig, lnkS);
	}
	
	return pager.replace(/\{pages\}/ig, pagerHtml);
}

// SEO

function seoTags(title, tags, keywords){

	// Warning: dont access to .html(title) because it breaks IE 7 & 8 
	if(title) document.title=title;
	if(tags) $("head").prepend("<meta name=\"Description\" content=\""+tags+"\" />");
	if(keywords) $("head").prepend("<meta name=\"Keywords\" content=\""+keywords+"\" />");
}

//Loader
function LoaderDisplay(btn, img, show){
	if(show){
		$(btn).attr("disabled", "disabled");
		$(img).css("display", "block");
	}
	else{
		$(btn).removeAttr("disabled");
		$(img).css("display", "none");
	}
}

function applyPromoCode(code){
	
	if(checkCodePromo(code)){
		document.location.href = "/CodePromo.html?code="+code;
		return;
	}
	
	var retour = 0;
	
	var url = ApiLK.applyCodePromo(code);

	$.ajax ({
		url: url,
		dataType: 'json',
		async: false,
		success: function(object){
			var response = object["ws"]["response"];
			if(response){
				retour = response["string"];
				_gaq.push(['_trackEvent', 'Code Promo', code+'-OK', code]);
			}
			else{
				_gaq.push(['_trackEvent', 'Code Promo', code+'-KO', code]);
			}
		},
		error: function(req,str,e){
			_gaq.push(['_trackEvent', 'Code Promo', code+'-KO', code]);
		}
	});
	return retour;
}

function checkCodePromo(code){
	
	var retour = 0;
	
	var url = ApiLK.checkExternalCodePromo(code, 0);

	$.ajax ({
		url: url,
		dataType: 'json',
		async: false,
		success: function(object){
			var response = object["ws"]["response"];
			if(response){
				if(response["boolean"]=="true") retour = 1;
			}
		},
		error: function(req,str,e){
		}
	});
	
	return retour;
}
