// ==ClosureCompiler==
// @output_file_name jsmkt.js
// @compilation_level ADVANCED_OPTIMIZATIONS
// @externs_url https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js
// ==/ClosureCompiler==

/******************************************************************************/
/**
 * Look marketing javascript library naming
 */
var JSMKT = (JSMKT||{});
window['JSMKT'] = JSMKT; // export name

/******************************************************************************/
/**
 * Show layer and hide others in an object.
 * @param obj String
 * @param layer String
 */
JSMKT.showLayer = function(obj, layer, target) {
    $('.'+obj+' .layer').addClass('hide');
	$('.'+obj+' .'+layer).toggleClass('hide');
	$('.'+obj+' .item').removeClass('selectedItem');
	$(target).addClass('selectedItem');
};
JSMKT['showLayer'] = JSMKT.showLayer; // export name

JSMKT.toggleBloc = function(obj, layer) {
	$('.'+obj+' .'+layer).toggleClass('hide');
};
JSMKT['toggleBloc'] = JSMKT.toggleBloc; // export name

 JSMKT.tabDM = function() {
   $(document).ready(function() {
    $(".tabLink").each(function(){
      $(this).click(function(){
        tabeId = $(this).attr('id');
        $(".tabLink").removeClass("activeLink");
        $(this).addClass("activeLink");
        $(".tabcontent").addClass("hide");
        $("#"+tabeId+"-1").removeClass("hide")   
        return false;	  
      });
    });  
  });
};
JSMKT['tabDM'] = JSMKT.tabDM; // export name

/******************************************************************************/
/**
 * Object to sort table rows by a col.
 * Sortable column's heading must be in <thead> and must have a 'sortable' className
 * Cells with '.date' className are match as date 'weel_day jj/mm'.
 * Cells with '.obj-price' className are match as price 'xxxx &nbsp;' and support 'del' price.
 * Cells with '.promo' className are match as promo % '-xx%'.
 * Usage : simply initialize with JSMKT.sortTable(your_table_id) call, click on headings for sort.
 * A two-column generated has an 'alt' className.
 * @constructor
 * @param table_id String
 */
JSMKT.sortTable = function(table_id){
	this.table_id = table_id; // table ID
	this.table = null; // table object
	this.tbody = null; // tbody object
	this.cache = []; // cache with rows and cells fomated values
	this.default_sort = []; // default sort order for each column, O==asc 1==desc
	this.sort_index = null; // last sorted column index
	
	this.init();
};
JSMKT.sortTable.prototype = {
	/**
	 * Get the table, copy rows in a cache
	 * and set onclick listener on cell with 'sortable' className.
	 * Cells with '.date' className are match as date 'weel_day jj/mm'.
	 * Cells with '.obj-price' className are match as price 'xxxx &nbsp;' and support 'del' price.
	 * Cells with '.promo' className are match as promo % '-xx%'.
	 */
	init : function(){
		that = this;
		// get rows
		this.table = $('#' + this.table_id);
		this.tbody = $('tbody', this.table);
		var rows = $('tr', this.tbody);
		// set cache
		for (i = 0; i < rows.length; i++) {
			this.cache[i] = []
			this.cache[i][0] = rows[i];
			var cells = rows[i].cells;
			for (x = 0; x < cells.length; x++) {
				if ($(cells[x]).hasClass('date')) {
					// parse date in format 'week_day jj/mm'
					var reg = /\d{2}/g;
					var parsed = $(cells[x]).text().match(reg);
					this.cache[i][x+1] = parsed[1] + parsed[0];
					that.default_sort[x] = '0';
				} else if ($(cells[x]).hasClass('obj-price')) {
					// match price in format 'nnnn &euro;'
					var reg = /\d{2,4}/;
					var parsed = $('.price', cells[x]).text().match(reg);
					this.cache[i][x+1] = parsed[0];
					that.default_sort[x] = '0';
				} else if ($(cells[x]).hasClass('promo')) {
					// parse promo % in format '-nn%'
					var reg = /\d{1,2}/;
					var parsed = $(cells[x]).text().match(reg);
					this.cache[i][x+1] = parsed[0];
					that.default_sort[x] = '1';
				} else {
					this.cache[i][x+1] = $(cells[x]).text();
					that.default_sort[x] = '0';
				}
			}
		}
		// set listener
		$('#' + this.table_id + ' .sortable').live('click', function(){
			that.sort(this.cellIndex);
		});
	},
	/**
	 * Sort this.table by col n° passed in 'index' parameter
	 * @param index Int
	 */
	sort : function(index){
		// resort on the same index = reverse
		if (index == this.sort_index) {
			this.cache.reverse();
		} else {
			this.sort_index = index;
			var to_sort = []
			// extract value for sorting
			for (i in this.cache) {
				to_sort[i] = [];
				to_sort[i][0] = i;
				to_sort[i][1] = this.cache[i][index+1];
			}
			to_sort.sort(this.compareFunction);
			// update cache
			var new_cache = [];
			for (i = 0; i < to_sort.length; i++) {
				new_cache[i] = this.cache[to_sort[i][0]]
			}
			this.cache = null;
			this.cache = new_cache;
			// default sort order by data type
			if (this.default_sort[index] == 1) {
				this.cache.reverse();
			}
		}
		// update tbody
		for (i = 0; i < this.cache.length; i++){
			if (i%2 == 0) {
				$(this.cache[i][0]).removeClass('alt')
			} else {
				$(this.cache[i][0]).addClass('alt')
			}
			$(this.tbody).append(this.cache[i][0]);
		}
	},
	/**
	 * Compare v1[1] to v2[1]
	 * @param v1 Array
	 * @param v2 Array
	 */
	compareFunction : function(v1, v2){
		return (v1[1] > v2[1] ? 1 : ( v1[1] < v2[1] ? -1 : 0))
	}
};
JSMKT['sortTable'] = JSMKT.sortTable;
/******************************************************************************/
/**
 * Carousel.
 * Download all images for the carousel then show tabs and arrow.
 * Mouseover on tabs show the image.
 * Click on arrow show prev. or next image.
 * An autoplay change the main image every autoplay_delay ms.
 * listing parameter is a table of carousel item.
 * 		A carousel item is a table [name, price, link url, img src, Eulerian tracking code]
 * id parameter is the html id of the carousel container
 * @param id String
 * @param listing Table
 * @param width Int
 * @param height Int
 * @constructor
 */
JSMKT.carousel = function(id, listing, width, height) {
	this.image_width = width; // images width
	this.image_height = height; // images height
	this.autoplay_delay = 3000; // delay in ms between slide for autoplay
	this.autoplay_timeout = null;
	this.step = 0; // actual step for autoplay
	this.fade_speed = 15; // fade steps duration in ms
	this.fade_timeout = null;
	this.tabs = listing; // listing with all slideshow elements
	this.html = $("#"+id); // slideshow html container
	this.html_tabs = [];
	
	this.init();
};
JSMKT.carousel.prototype = {
	/**
	 * Delay carousel initialization after .ready()
	 */
	init : function(){
		$(window).bind("load",{that: this}, function(event) {
		   event.data.that.delayedInit();
		});
	},
	/**
	 * Init the slideshow.
	 * Load all images and set a downloaded state.
	 * Add a mouseover listener on the carousel to stop autoplay and show arrows.
	 * Add a mouseout listener on the carousel to start autoplay and hide arrows.
	 */
	delayedInit : function(){
		for (i=0; i<this.tabs.length ;i++) {
			// add a download state
			this.tabs[i][5] = null;
			// hack IE : first image is always donwloaded
			this.tabs[0][5] = true;
			// load image
			this.loadImage(i);
		}
	},
	/**
	 * Asynchronous load the image for item[id].
	 * Add it with a link in the carousel.
	 * @param id Int 
	 */
	loadImage : function(id){
		that = this;
		var img = new Image(this.image_width, this.image_height);
		img.src = this.tabs[id][3];
		$(img).attr('alt', this.tabs[id][0]);
		var link = $("<a href='"+this.tabs[id][2]+"'></a>");
		// tracking Eulerian
		if (!this.tabs[id][4] == "") {
			link.bind('click', {id: id, that: this}, function(event){
				EA_link(that.tabs[event.data.id][4]);
			});
		};
		// wrap link in a dic beacause jquery fadeTo doesn't work on inline element in IE8
		var container = $("<div class='img"+id+"'></div>");
		link.append(img);
		container.append(link);
		container.hide();
		this.html.prepend(container);
		//$(img).hide();
		img.onload = function() {
			// set dowload state
			that.tabs[id][5] = true;
			// try slideshow creation
			that.create();
			i.onload = null;
		};
	},
	/**
	 * Create tabs and arrow when all images are dowloaded.
	 * Add mouseover listener on each tab to change.
	 * Add a click listener on each arrow.
	 */
	create : function(){
		// test if all images are downloaded
		var all_downloaded = true;
		for (i=0; i<this.tabs.length ;i++) {
			if (this.tabs[i][5] == null) {
				all_downloaded = null;
			}
		}
		if (all_downloaded) {
			// create tabs container
			var html_tabs = $("<div class='tabs grd-line'></div>");
			// create all tabs
			for (i=0; i<this.tabs.length ;i++) {
				var tab_css = "grd-unit grd-size1of" + this.tabs.length;
				if (i == 0) {
					tab_css += " activ";
				} else if (i == this.tabs.length-1) {
					tab_css += " grd-lastUnit";
				}
				var html_tab = $("<div class='tab " + tab_css + "'></div>");
				var html_link = $("<a href='" + this.tabs[i][2] + "' class='link'><b>" + this.tabs[i][0] + "</b><br/>" + this.tabs[i][1] + "</a>");
				html_link.bind('mouseover', {id: i, that: this}, function(event){
					that.show(event.data.id);
				});
				// tracking Eulerian
				if (!this.tabs[i][4] == ""){
					html_link.bind('click', {id: i, that: this}, function(event){
						EA_link(that.tabs[event.data.id][4]);
					});
				}
				html_tab.append(html_link);
				this.html_tabs.push(html_tab);
				html_tabs.append(html_tab);
			}
			// show tabs
			this.html.children(".main").remove();
			this.html.children(".img0").show();
			this.html.append(html_tabs);
			// autoplay and arrow listeners
			this.html.bind('mouseover', {that: this}, function(event){
				//window.clearTimeout(that.autoplay_timeout);
				that.stopAutoplay()
			});
			this.html.bind('mouseout', {that: this}, function(event){
				that.startAutoplay();
			});
			// add listener on tabs
			this.startAutoplay();
			// previous and next arrows
			var prev_arrow = $("<div class='arrow prev'></div>");
			prev_arrow.bind('click', {that: this}, function(event){
				if (that.step > 0) {
					that.show(that.step-1)
				} else {
					that.show(that.tabs.length-1)
				}
			});
			this.html.append(prev_arrow);
			var next_arrow = $("<div class='arrow next'></div>");
			next_arrow.bind('click', {that: this}, function(event){
				if (that.step == that.tabs.length-1) {
					that.show(0)
				} else {
					that.show(that.step+1)
				}
			});
			this.html.append(next_arrow);
		}
	},
	/**
	 * Remove 'activ' class on all tabs.
	 */
	resetTabsCss : function(){
		for (i=0; i<that.tabs.length; i++) {
			this.html_tabs[i].removeClass('activ');
		}
	},
	/**
	 * Hide current image, replace with new (id)
	 * @param id Int
	 */
	show : function(id){
		this.resetTabsCss();
		this.html_tabs[id].addClass('activ');
		this.html.children('.img'+this.step).hide();
		this.html.children('.img'+id).show();
		this.step = id;
	},
    fade : function(that, from, to, next_step) {
        that.html.children('.img'+that.step).fadeTo(0, to);
        if (to > 0 && to < 1) {
            var actual = to;
            if (from > to) {
                // fade out
                to = Math.round((to - 0.1)*100)/100;
            } else if (from < to) {
                //fade in
                to = Math.round((to + 0.1)*100)/100;
            }
            //TODO : not call it if from = 1
            that.fade_timeout = window.setTimeout(function(){that.fade(that, actual, to, next_step)}, that.fade_speed);
        } else if (from == 0.1) {
            // change image and fade in
            that.resetTabsCss();
			that.html.children('.img'+that.step).hide();
			that.step = next_step;
			that.html_tabs[next_step].addClass('activ');
            that.html.children('.img'+that.step).fadeTo(0, 0);
			that.html.children('.img'+next_step).show();
			that.fade_timeout = window.setTimeout(function(){that.fade(that, 0, 0.1, next_step)}, that.fade_speed);
        }
    },
    
	/**
	 * Auto change carousel (obj) visual.
	 * @param obj Object JSMKT.carousel
	 */
	autoplay : function(obj){
		if (this.step < this.tabs.length-1){
			next_step = this.step + 1;
		} else {
			next_step = 0;
		}
		// We can not use jquery fadeOut and fadeIn 
		// because the callback is not sent any arguments
		//this.fadeOut(this, 1, next_step);
        this.fade(this, 1, 0.9, next_step);
		this.startAutoplay();
	},
	/**
	 * Stop carousel autoplay
	 */
	stopAutoplay : function(){
		window.clearTimeout(this.autoplay_timeout);
		window.clearTimeout(this.fade_timeout);
		that.html.children('.img'+this.step).fadeTo(0, 1);
	},
    /**
     * Start carousel autoplay
     */
    startAutoplay : function(){
        var that = this;
        that.autoplay_timeout = window.setTimeout(function(){that.autoplay(that)}, that.autoplay_delay);
    }
}
JSMKT['carousel'] = JSMKT.carousel; // export name

/**************************/
/****** pop in cookie *****/
/**************************/
var path = location.pathname; // définit l'url en cours
var nb_views = 1; // initialise le nb de pages vues à la première connection
var myDomain="/"; // définit le nom de domaine global du site
var date_exp = new Date();
date_exp.setTime(date_exp.getTime()+(15*24*3600*1000)); // durée de vie du cookie de 15 jours
// fonctions necessaires à la gestion des cookies - ne pas modifier
function SetCookie (name, value) {
	var argv=SetCookie.arguments;
	var argc=SetCookie.arguments.length;
	var expires=(argc > 2) ? argv[2] : null;
	var path=(argc > 3) ? argv[3] : null;
	var domain=(argc > 4) ? argv[4] : null;
	var secure=(argc > 5) ? argv[5] : false;
	document.cookie=name+"="+escape(value)+
		((expires==null) ? "" : ("; expires="+expires.toGMTString()))+
		((path==null) ? "" : ("; path="+path))+
		((domain==null) ? "" : ("; domain="+domain))+
		((secure==true) ? "; secure" : "");
}
function getCookieVal(offset) {
	var endstr=document.cookie.indexOf (";", offset);
	if (endstr==-1)
      		endstr=document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}
function GetCookie (name) {
	var arg=name+"=";
	var alen=arg.length;
	var clen=document.cookie.length;
	var i=0;
	while (i<clen) {
		var j=i+alen;
		if (document.cookie.substring(i, j)==arg)
                        return getCookieVal (j);
                i=document.cookie.indexOf(" ",i)+1;
                        if (i==0) break;}
	return null;
}
// fonctions propre à la gestion de la pop-in
function PopinCookie(){
    var path_temp = GetCookie("path_temp"); // url de la page précédente stockées dans une variable
    nb_views = GetCookie("views");   // récupération du nombre de pages uniques vues
    if (path_temp != path) { // si on reste sur la meme page
        nb_views++;	// incrémentation du nombre de pages uniques vues
    }
    if (nb_views == 3) { // test des cond pour afficher la popin
        $(document).ready(function() { // affiche la popin
	        $(".obj-popin").overlay({ top: 210, left:390, closeOnClick: true, load: true, fixed:true, mask: { color: '#000', loadSpeed: 200, opacity: 0.3} });
        });
	}
    SetCookie("views",nb_views,date_exp,myDomain);	// enregistre dans cookie du pages uniques vues
    SetCookie("path_temp",path,null,myDomain); // met a jour l'url de la page precedente avec celle en cours
}
PopinCookie();
