var PopupWat = new Class({
    initialize: function(){
        
    },
    positionBox: function(box, element) {

		if (element == null) {
			return;
		}

        var elPos = element.getPosition();
		
        var leftPos = (elPos['x'] - (parseInt(box.getStyle('width')) / 1.5));
        if (leftPos < 0) {
            leftPos = 0;
        }

		box.setStyles({
			top: elPos['y'] + 20,
			left: leftPos
		});
		var windowSizes = $(window).getSize();
		var elBos = box.getCoordinates();
		if((elBos.top + 40) >windowSizes.y){
			box.setStyles({
				top: elBos.top - elBos.height - 40
			});
		}

		if( (elBos.left + elBos.width) > windowSizes.x){
			box.setStyles({
				left: windowSizes.x - elBos.width - 50
			});
		}
    },
    showDialog: function(idBox, urlback, element, shadow, block, callback, action, optional, fixe){

        if (!action) action = 'render';

        // on cache les selects si IE
        if (Browser.Engine.trident&&Browser.Engine.version<=6) {
            $$('select').each(function(item) {
                item.setStyle('display', 'none');
            });
        }
        // on cache les flash

        // si shadow => div anticlic
        if (shadow) {
            $('dialogShadow').setStyle('display', 'block');
            $('dialogShadow').setStyle('opacity', '0');
            $('dialogShadow').fade(0,.6);
        }

        if (!$(idBox)) {
            var blocRequest = new Request.JSON({
                method: 'post',
                url: '/ajax/bloc?bloc='+block+'&action='+action,
                onSuccess: function(response) {
                    var popup = new Element('div', {
                       'id': idBox,
                       'styles': {
                           'visibility': 'hidden',
                           'position': 'absolute',
                           'z-index': '1500000'
                       }
                    }).inject($('Grid'), 'top');
                    popup.set('html', response.content);
                    if (callback)
                        callback.run('', this);
					if (element) {
						this.positionBox($(idBox), element);
					}
                    $(idBox).setStyle('visibility', 'visible');
                    
                }.bind(this),
                onFailure: function() {
                    if ($('dialogShadow')) $('dialogShadow').hide();
                    if (element.href && element.href != '#') window.location.href = element.href;
                }
            });
            var nextSend = (optional) ? '&'+optional : '';
            blocRequest.send('page='+urlback+nextSend);
        } else {
            $(idBox).setStyle('display', 'block');
			if (element) {
				this.positionBox($(idBox), element);
			}
        }
		
		// si player on met en pause
		try {
			WATPlayer.getFlash().setPause();
		} catch(e) { }

    }
});var LoginWat = new Class({Extends: PopupWat,
    view: function(urlback, element, shadow){
        this.showDialog('LoginDialog',urlback, element, shadow, "Block_Popup_Login", function() {
            this.addFormEvent();
        }.bind(this));
    },
    hide: function() {
           $('LoginDialog').setStyle('display', 'none');
           $('dialogShadow').setStyle('display', 'none');
			// si player on remet en play
			try {
				WATPlayer.getFlash().setPlay();
			} catch(e) { }
    },
    addFormEvent: function() {
        $('SubmitLoginForm').addEvent('click',function(e){
				e.stop();
                this.checkLogin();
        }.bind(this));
        $('formDialogLogin').addEvent('submit',function(){
                this.checkLogin();
        }.bind(this));
       $('close_dialog').addEvent('click', function(e) {
           e.stop();
           this.hide();
       }.bind(this));
        $('fakeFBPopupBig').addEvent('click', function(e) {
            e.stop();
			    FB.login(function(response) {
				   if (response.authResponse) {
					 // on créé notre propre cookie avec user id, access_token et signed_request
					 setCookieWAT('FBS_WAT_uid', response.authResponse.userID);
					 setCookieWAT('FBS_WAT_token', response.authResponse.accessToken);
					 facebook_onlogin();
				   }
				 }, {scope: 'publish_stream,offline_access,email,user_interests,friends_interests,user_likes,friends_likes,friends_interests'});
        }.bind(this));
        if (typeof(FB) != 'undefined') {
             FB.XFBML.parse();
        }
    },
    checkLogin: function(){
        var rememberme = ($('RememberLogin').checked == true ? 1 : 0);
        var loginRequest = new Request.JSON({
            method: 'post',
            url: '/ajax/bloc?controller=User_Login&action=connect&bloc=Block_Popup_Login',
            onSuccess: function(response) {
                if(response.url){
                        var uri = response.url;
                        var temp = uri.split("?");
                        var url = temp[0].replace('http://', '');
                        var temp2 = url.split("/");
						var url2 = uri.split("#");

                        if (temp2[1] == '928'){
                            window.location.href = '/'+temp2[2];
                        } 
                        else{
                            window.location.href = response.url;
							if(url2[1]){ //Si ancre on force le rechargement
								window.location.reload();
							}
                        }

                        return false;
                }
                $('authError').innerHTML=response.error;
            }
        });
        loginRequest.send('rememberme='+rememberme+'&username='+$('UsernameLogin').value+'&password='+encodeURIComponent($('PasswordLogin').value)+'&url='+$('UrlLoginBack').value);
    }
});var SocialWat = new Class({
	Extends: PopupWat,
	Implements: [Options, Events],
	options: {
		social: 'facebook',
		user: false
	},
	initialize: function(options) {
		this.setOptions(options);
	},
    view: function(element, shadow) {
        this.showDialog('popupSocial', '', element, shadow, 'Block_Popup_Social', function() {
            this.addFormEvent();
       	}.bind(this), '', 'social=' + this.options.social);
    },
    hide: function() {
	   $('popupSocial').setStyle('display', 'none');
	   $('dialogShadow').setStyle('display', 'none');
    },
    askLogin:function(element, shadow) {
		this.showDialog('popupSocialLogin', '', element, shadow, 'Block_Popup_Social', function() {
			$('popupSocial').setStyle('display', 'none');
		}.bind(this), '', 'social=' + this.options.social);
    },
    addFormEvent: function() {
		var user_id = $(this.options.social + 'Id').get('html');
		if (this.options.social == 'facebook') {
			var query = FB.Data.query('select name, pic_square, uid from user where uid={0}', user_id);
			query.wait(function(rows) {
				document.getElementById(this.options.social + 'Username').innerHTML = rows[0].name;
				if (rows[0].pic_square) {
					document.getElementById(this.options.social + 'Picture').innerHTML = '<img src="' + rows[0].pic_square + '" alt="" title="" />';
				}
			}.bind(this));
		} else if (this.options.social == 'twitter' && this.options.user) {
			document.getElementById(this.options.social + 'Username').innerHTML = this.options.user.data('screen_name');
			document.getElementById(this.options.social + 'Picture').innerHTML =  '<img src="' + this.options.user.data('profile_image_url') + '" alt="" title="" />';
		} else {
			return;
		}

		$('SubmitSocialLoginForm').addEvent('click', function() {
			this.submitSocial();
		}.bind(this));
		$('formDialogSocial').addEvent('submit', function() {
			this.submitSocial();
		}.bind(this));
		$('close_dialog').addEvent('click', function(e) {
			e.stop();
			this.hide();
		}.bind(this));
    },
    submitSocial:function() {
		var controller = 'Facebook';
		var connect = 'FB';
		if (this.options.social == 'twitter') {
			controller = 'Twitter';
			connect = 'TW';
		}
		var blocRequest = new Request.JSON({
			method: 'post',
			url: '/ajax/bloc?controller=User_' + controller + '&action=' + connect + 'connect&bloc=Block_Popup_Social',
			onSuccess: function(response) {
				if (response.error == 'ok') {
					window.location.reload();
					return false;
				}
				$('authError').innerHTML = response.error;
				return true;
			}
		});
		blocRequest.send('username=' + $('UsernameSocialLogin').value + '&password=' + $('PasswordSocialLogin').value);
    }
});function showLoginBoxLink() {
    var logElement = getElementFromCookie();
    // Si loggué :
    if (logElement.length > 0 && logElement != 'null') {
        $('login_logged').style.display = "inline";
        $('li_deconnexion').style.display = "inline";
		$$('.li_moncompte').each(function(item) {
			item.style.display = "inline";
		});
        $('li_chaine').style.display = "inline";
        $('li_inscription').style.display = "none";
        if ($('li_connexion')) {

            $('li_connexion').style.display = "none";
        }
        if ($('facebook_login')) {
            $('facebook_login').style.display = "none";
        }
        $('logout_link').setProperty('href', '/logout?urlback='+encodeURIComponent(window.location.pathname));
        $('linkToChannel').set('href', '/' + logElement);
        $('channel_link').set('href', '/' + logElement);
        $('linkToChannel').set('html', logElement);
		$('linkToChannel').set('title', $('linkToChannel').get('title') + ', ' + logElement);
        //$('login_logged').innerHTML = $('login_logged').innerHTML + ' <a href="/' + logElement + '">' + logElement + '</a> ';
    }
    else {
        $('login_logged').style.display = "none";
        $('li_deconnexion').style.display = "none";
		$$('.li_moncompte').each(function(item) {
			item.style.display = "none";
		});
        if ($('fakeFBButton')) {
            $('fakeFBButton').addEvent('click', function(e) {
                e.stop();
			    FB.login(function(response) {
				   if (response.authResponse) {					 
					 // on créé notre propre cookie avec user id, access_token et signed_request
					 setCookieWAT('FBS_WAT_uid', response.authResponse.userID);
					 setCookieWAT('FBS_WAT_token', response.authResponse.accessToken);
					 facebook_onlogin();
				   }
				 }, {scope: 'publish_stream,offline_access,email,user_interests,friends_interests,user_likes,friends_likes,friends_interests'});
			});
        }
    }
}

function initLoginLink(){
	$$('a.btnCnx').each(function (login_link, index){
		login_link.setProperty('href', '/login?urlback='+encodeURIComponent(window.location.pathname));
		login_link.addEvent('click', function(e) {
			e.stop();
			var login = new LoginWat();
			target = e.target;
			if(target.tagName != 'A'){
				target = $(target).getParent('a');
			}
			login.view(window.location.href, target, true);
		});
	});

	// pub pour site mobile
	if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/Android/i))) {
        var div = new Element('div', {
            id: 'mobilePub',
			html: '<div class="content" onclick="window.location = \'http://m.wat.tv\'"><p style="text-align: center; padding: 15px; line-height: 32px;"><a href="http://m.wat.tv" style="color: white;">Visitez notre site optimisé pour votre mobile<br /><span style="text-decoration: underline;">m.wat.tv</span></a></p></div>',
            styles: {
				background: 'black',
				color: 'white',
				'font-size': '32px',
				'line-height': '32px'
            }
        });
        div.inject($('Header'), 'before');
	}
}

function facebook_onlogin() {
    var blocRequest = new Request.JSON({
        method: 'post',
        url: '/ajax/bloc?controller=User_Facebook',
        onSuccess: function(response) {
            if (response.msg == 'account') {
                // pas de compte user, on lui demande si il a un compte ou pas
                var socialWat = new SocialWat();
                socialWat.view($("li_connexion"), true);
                return;
            }
            if (response.msg == 'found') {
                window.location.reload();
            }
        }
    });
    blocRequest.send('bloc=Block_User_Login&action=connect');
}

window.addEvent("domready",initLoginLink);function chooseMenuLink() {
	var uri = location.href;
	var temp = uri.split("?");
	var url = temp[0].replace('http://', '');
	var temp2 = url.split("/");

	var onglet = temp2[1];
	try {
		var ongletBis = temp2[2];
	}
	catch (err) {
		var ongletBis;
	}

	if (onglet == 'top' || onglet == 'tophebdo') {
		if ($('onglet_top')) {
			$('onglet_top').addClass('bg1');
		}
    }
    else if (onglet == 'disclaimerSexy') {
		if ($('onglet_sexy')) {
			$('onglet_sexy').addClass('bg1');
		}
    }
    else if (ongletBis == 'secret-story') {
		if ($('onglet_secret')) {
			$('onglet_secret').addClass('selectSecret');
		}
    }
    else {
        if ($('onglet_' + ongletBis)) {
            $('onglet_' + ongletBis).addClass('bg1');
        }
    }

}var PlaylistWat = new Class({Extends: PopupWat,
    view: function(urlback, element, shadow, optionnal, id){
		this.showDialog('PlaylistDialog',urlback, element, shadow, "Block_Popup_Playlist", function() {
			this.idButton = id ? $(id).getChildren('a')[0].get('id') : 'addToChaineRailway';
			this.idMsg = id ? $(id).getChildren('span')[0].get('id') : 'msgAddPlaylistRailway';
			this.addFormEvent();
		}.bind(this), '', optionnal);
    },
    hide: function() {
           $('PlaylistDialog').dispose();
           $('dialogShadow').setStyle('display', 'none');
			// si player on remet en play
			try {
				WATPlayer.getFlash().setPlay();
			} catch(e) { }
    },
    addFormEvent: function() {
		$('close_dialog').addEvent('click', function(e) {
			e.stop();
			$(this.idMsg).setStyle('display', 'none');
			$(this.idButton).setStyle('display' , 'block');
			this.hide();
		}.bind(this));
		if ($('ChaineID')) {
			// Cas métacompte
			$('ChaineID').addEvent('change',function(change){
				var params = {
					bloc:'Block_Popup_Playlist',
					chaineid:change.target.get('value'),
					entryid:$(this.idButton).get('data-id'),
					action:'getChainePlaylists'
				};
				new Request.HTML({
					url:'/ajax/bloc',
					method:'post',
					data:Hash.toQueryString(params),
					onComplete:function(){
						$('AlbumID').set('html',arguments[2]);
						$('AlbumSelect').show();
						$('FolderCreation').show();
						$('linkCreateFolder').addEvent('click', function() {
							$('createFolder').toggle();
							return false;
						});
						$('SubmitAddToChaine').show();
						$('AlbumSelect').highlight();
						$('SubmitAddToChaine').addEvent('click',this.addToPlaylistOfChaine.bind(this));
						$('submitNameFolderEdit').addEvent('click', this.addNewPlaylist);
					}.bind(this)
				}).send();
			}.bind(this));
		} else {
			$('SubmitAddToChaine').addEvent('click',this.addToPlaylistOfChaine.bind(this));
			$('FolderCreation').show();
			$('linkCreateFolder').addEvent('click', function() {
				$('createFolder').toggle();
				return false;
			});
			$('submitNameFolderEdit').addEvent('click', this.addNewPlaylist);
		}
    },
	addNewPlaylist: function () {
		var flag = true;
		if ($('inputNameFolderEdit').value == '' || $('inputNameFolderEdit').value == window['errMsgPlaylist'][0]) {
			$('errorFolderEdit').set('html', window['errMsgPlaylist'][1]);
			flag = false;
		}

		if (flag) {
			var options = {
				bloc: 'Block_Popup_Playlist',
				action:'createFolder',
				folder:$('inputNameFolderEdit').value
			}
			if ($('ChaineID')) {
				options['chaine'] = $('ChaineID').value;
			}
			new Request.JSON({
				url:"/ajax/bloc?controller=User_Edit",
				method:"post",
				data:Hash.toQueryString(options),
				onComplete: function(data) {
					if (data.error) {
						$('errorFolderEdit').set('html', data.error);
						flag = false;
					} else {
						$('AlbumID').set('html', data.select);
						$('AlbumID').highlight();
					}
				}
			}).send();
		}

		if (flag) {
			$('createFolder').hide();
		}
	},
	addToPlaylistOfChaine: function (){
		var playlists   = [];
		var checked     = 0;
		$('AlbumID').getElements('.checkbox').each(function(input) {
			if (input.checked) {
				playlists[checked] = input.value;
				checked++;
			}
		}.bind(this));

		var params = {
			bloc:'Block_Popup_Playlist',
			requested:$(this.idButton).get('data-id')
		};
		if (checked > 0) {
			params.folder = playlists;
		} else if ($('ChaineID')) {
			params.chaineId = $('ChaineID').value;
		}
		new Request.HTML({
			url:'/ajax/bloc?controller=Media_Playlist&action=add',
			method:'post',
			data:Hash.toQueryString(params),
			onComplete:function(){
				var msg = $(this.idMsg).get('html');
				$(this.idMsg).set('html',arguments[2]);
				(function(){
					$(this.idMsg).setStyle('display', 'none');
					$(this.idMsg).set('html', msg);
					$(this.idButton).setStyle('display' , 'block');
				}.bind(this)).delay(5000);
				$('PlaylistDialog').dispose();
				$('dialogShadow').setStyle('display', 'none');
			}.bind(this)
		}).send();
		$('selectFolder').hide();
	}
});function addToChaineRailway(a,c){var b={bloc:"Block_Popup_Playlist",entryid:$(a).get("data-id")};new Request.JSON({url:"/ajax/bloc?controller=Media_Playlist&action=addToChaine",method:"post",evalScripts:true,evalResponse:true,data:Hash.toQueryString(b),onComplete:function(f,h){if(f.error){$("msgAddPlaylistRailway").setStyle("display","none");$(a).setStyle("display","block");if(f.error=="USER_NOT_LOGGED"){var d=new LoginWat();d.view(window.location.href+"#addToChaine",a,true)}else{if(f.error=="ENTRY_NOT_PLAYLISTABLE"){$(a).setStyle("display","none");$("msgAddPlaylistRailway").set("html",f.msg);$("msgAddPlaylistRailway").setStyle("display","block")}}return}if(f.dialog){$(a).setStyle("display","none");$("msgAddPlaylistRailway").setStyle("display","block");var e=new PlaylistWat();var g={entryId:$("media").value};e.view(window.location.href,$("msgAddPlaylistRailway"),true,Hash.toQueryString(g),c)}}}).send()};var ContestTab=new Class({Implements:[Options,Events],options:{tabs:false,contributif:false,player:false,link:false},initialize:function(a){this.setOptions(a);this.displayDiv="Block_Chaine_Premium";if(this.options.tabs[0]["idDiv"]){this.displayDiv=this.options.tabs[0]["idDiv"]}if(this.options.tabs){this.options.tabs.each(function(b){if(b.idTab){if(!b.link){$(b.idTab).addEvent("click",function(c){c.stop();this.changeTabs(b.idTab,b.idDiv,b.colour)}.bind(this))}}}.bind(this))}},changeTabs:function(a,b,f){$$(".selected").each(function(e){e.removeClass("selected");e.removeClass("bg1")}.bind(this));$(a).addClass("selected");$(a).addClass("bg1");if(this.options.contributif&&$("viewVideo")){$("viewVideo").show();$("videoDemo").setStyles({width:0,height:0});$("videoDemo").set("html",'<div id="containerVideo"></div>')}$(this.displayDiv).hide();$(b).show();$("Grid").setStyle("background",f);this.displayDiv=b;if(this.options.player){if(a==this.options.player.info.idTab){var c=new Element("div").inject($(this.options.player.info.idPlayer));c.set("id",this.options.player.infoPlayer.container);if(typeof(PWpreroll)!="undefined"){this.options.player.infoPlayer=$merge(this.options.player.infoPlayer,{PWpreroll:PWpreroll,isStartAd:"true"})}WATPlayer.showPlayer(this.options.player.infoPlayer)}else{try{$(this.options.player.info.idPlayer).empty()}catch(d){}}}}});var Block_Popup_Lightbox = new Class({
	Implements: [Options,Events],
    options: {
		id: '',
		pictures: [],
		nbPicture: 0,
		position: 0,
		myEffect: false,
		myEndEffect: false,
		counter: true,
		download: true,
		title: false
    },
    initialize: function(options) {
        this.setOptions(options);
		if (!this.options.id) {
			return;
		}
		this.initImages();
		if ($(this.options.id)) {
			$$('#' + this.options.id + ' img').each(function(image, index) {
				image.addEvent('click', function(e) {
					e.stop();
					this.launch(index);
				}.bind(this));
			}.bind(this));
		}
    },
	initEvents: function() {
		if ($('goToRight')) {
			$('goToRight').addEvent('click', function(e) {
				e.stop();
				this.nextImage();
			}.bind(this));
		}
		if ($('goToLeft')) {
			$('goToLeft').addEvent('click', function(e) {
				e.stop();
				this.previousImage();
			}.bind(this));
		}
		if ($('close')) {
			$('close').addEvent('click', function(e) {
				e.stop();
				this.exit();
			}.bind(this));
		}
		if ($('dialogShadow')) {
			$('dialogShadow').addEvent('click', function(e) {
				e.stop();
				this.exit();
			}.bind(this));
		}
		if (!this.options.counter) {
			$('counter').dispose();
		}
		if (!this.options.download) {
			$('download').dispose();
		}
		if (!this.options.title) {
			$('title').dispose();
		}
	},
	initImages: function() {
		var images = [];
		$$('#' + this.options.id + ' img').each(function(picture, index) {
			var src = picture.src.replace('_thumb', '');
			images[index] = src;
		}.bind(this));
		this.options.pictures = Asset.images(images);
		this.options.nbPicture = this.options.pictures.length;
	},
	launch: function(position) {
		this.options.position = position;
		$('dialogShadow').setStyle('display', 'block');
		$('dialogShadow').setStyle('opacity', '0');
		$('dialogShadow').fade(0,.6);
		if (!$('gallery')) {
            var blocRequest = new Request.JSON({
                method: 'post',
                url: '/ajax/bloc?bloc=Block_Popup_Lightbox&action=render',
                onSuccess: function(response) {
                    var popup = new Element('div', {
                       'id': 'gallery',
                       'styles': {
                           'visibility': 'hidden',
                           'position': 'absolute',
                           'z-index': '1500000'
                       }
                    }).inject($('Grid'), 'top');
                    popup.set('html', response.content);
					this.setImage();
					this.initEvents();
                    $('gallery').setStyle('visibility', 'visible');		
                }.bind(this),
                onFailure: function() {
                    if ($('dialogShadow')) {
						$('dialogShadow').hide();
					}
                }
            });
            blocRequest.send();
        } else {
			this.setImage();
			$('gallery').setStyle('display', 'block');
        }

		// si player on met en pause
		try {
			WATPlayer.getFlash().setPause();
		} catch(e) { }
	},
	setImage: function() {
		this.positionBox($('gallery'));
		if (!this.options.myEffect) {	
			this.options.myEffect = new Fx.Morph($('content_lightbox'), {
				duration: 'normal',
				transition: Fx.Transitions.linear,
				onStart: function() {		
					$('loading').show();
					this.hideFeature();
				}.bind(this),
				onComplete: function() {
					$('loading').hide();
					this.setFeature();
				}.bind(this)
			});
		}
		this.options.myEffect.start({
			'width': this.options.pictures[this.options.position].width,
			'height': this.options.pictures[this.options.position].height + 70
		});
	},
	positionBox: function(box) {
		var windowSize = $(window).getSize();
		var windowScroll = $(window).getScroll();
		var left = ( windowSize.x - (this.options.pictures[this.options.position].width + 40) ) / 2;

		box.morph({
			top: windowSize.x / 12 + windowScroll.y,
			left: left
		});

	},
	setFeature: function() {
		if ($('close')) {
			$('close').show();
		}
		if ($('button')) {
			$('button').show();
		}
		if (this.options.title && $('title')) {
			$('title').show();
		}
		if (this.options.download && $('download')) {
			$('download').show();
		}
		if (this.options.counter && $('counter')) {
			$('counter').show();
			$('counter').set('html', (this.options.position + 1 + '/' +  this.options.nbPicture));
		}
		if ($('link_download')) {
			var src = this.options.pictures[this.options.position].src.replace('.jpg', '_hd.jpg');
			$('link_download').set('href', src);
		}
		if ($('goToLeft')) {
			if (this.options.position == 0) {
				$('goToLeft').hide();
			} else {
				$('goToLeft').show();
			}
		}
		if ($('goToRight')) {
			if (this.options.position == this.options.nbPicture - 1) {
				$('goToRight').hide();
			} else {
				$('goToRight').show();
			}
		}
		if ($('image')) {
			$('image').grab(this.options.pictures[this.options.position]);
		}
	},
	hideFeature: function() {
		if ($('image') && $('image').getChildren('img')[0]) {
			$('image').getChildren('img')[0].dispose();
		}
		if ($('close')) {
			$('close').hide();
		}
		if ($('button')) {
			$('button').hide();
		}
		if (this.options.title && $('title')) {
			$('title').hide();
		}
		if (this.options.download && $('download')) {
			$('download').hide();
		}
		if (this.options.counter && $('counter')) {
			$('counter').hide();
		}
	},
	nextImage: function() {
		if (this.options.position == this.options.nbPicture - 1) {
			return;
		}
		this.options.position++;
		this.setImage();
	},
	previousImage: function() {
		if (this.options.position == 0) {
			return;
		}
		this.options.position--;
		this.setImage();
	},
	exit: function() {
		if(!this.options.myEndEffect) {
			this.options.myEndEffect = new Fx.Morph($('content_lightbox'), {
				duration: 'short',
				transition: Fx.Transitions.linear,
				onStart: function() {
					this.hideFeature();
				}.bind(this),
				onComplete: function() {
					var preload = new Asset.images(
						this.options.pictures[this.options.position], {
							onComplete: function() {
								if ($('gallery')) {
									$('gallery').hide();
								}
								if ($('dialogShadow')) {
									$('dialogShadow').hide();
								}
							}.bind(this)
						}
					);
				}.bind(this)
			});
		}
		this.options.myEndEffect.start({
			'width': 0,
			'height': 0
		});
	}
});
var Premium=new Class({Implements:[Options,Events],options:{currentDot:"ui",loaded:[],isAjax:false,slideShow:true,timeRotate:5000},initialize:function(a){if(!this.options.currentDot){return}this.setOptions(a);$$("#foreground_premium .position a").each(function(b){this.dotEvent(b)}.bind(this));$("premiumPrevious").removeEvent("click");$("premiumPrevious").addEvent("click",function(b){b.stop();if(!this.options.currentDot){return}oParent=this.options.currentDot.getParent();ul=oParent.getParent();if(ul.getChildren("li").length<2){return}li=oParent.getPrevious();if(!li){li=ul.getLast()}aDot=li.getFirst();this.onChange(aDot);this.options.slideShow=false}.bind(this));$("premiumNext").removeEvent("click");$("premiumNext").addEvent("click",function(c,b){if(c instanceof Event){c.stop()}if(!this.options.currentDot){return}oParent=this.options.currentDot.getParent();ul=oParent.getParent();if(ul.getChildren("li").length<2){return}li=oParent.getNext();if(!li){li=ul.getFirst()}aDot=li.getFirst();if(!b){this.options.slideShow=false;this.onChange(aDot)}if(b&&this.options.slideShow){this.onChange(aDot);$("premiumNext").fireEvent("click",[true,true],this.options.timeRotate)}}.bind(this));$("premiumNext").fireEvent("click",[true,true],this.options.timeRotate);this.options.currentDot=$("premiumFirstDot")},onChange:function(d){if(!d){return}this.options.currentDot.getFirst().innerHTML="&#x25CB;";this.options.currentDot.getParent().removeClass("activedot");if(!this.options.isAjax){var c=this.options.currentDot.getProperty("data-id");var a=new Fx.Tween("premiumText"+c,{property:"opacity"});a.start(1,0).chain(function(){$("premiumText"+c).setStyle("visibility","hidden")});var b=new Fx.Tween("premiumPreview"+c,{property:"opacity"});b.start(1,0).chain(function(){$("premiumPreview"+c).setStyle("visibility","hidden")})}this.options.currentDot=d;d.getFirst().innerHTML="&bull;";d.getParent().addClass("activedot");var f=d.getProperty("data-id");if(!this.options.isAjax){img=$("premiumPreview"+f);text=$("premiumText"+f);if(dynsrc=img.getProperty("data-src")){img.src=dynsrc;img.erase("data-src")}text.fade("hide");img.fade("hide");text.setStyle("visibility","visible");img.setStyle("visibility","visible");text.fade("in");img.fade("in");return}if(this.options.loaded[f]){this.fillValues(f)}else{var e={id:f};new Request.JSON({url:"/ajax/bloc?bloc=Block_Premium&action=getMedia",method:"post",data:Hash.toQueryString(e),onSuccess:function(g){if(g&&g.error){alert("Erreur: "+g.error)}this.options.loaded[g.id]=g;this.fillValues(g.id)}}).send()}},dotEvent:function(a){a.removeEvent("click");a.addEvent("click",function(c){c.stop();var b=c.target;if(b.tagName!="A"){b=b.getParent("a")}if(!b.getParent().get("class").match("activedot")){this.onChange(b)}this.options.slideShow=false}.bind(this))},fillValues:function(a){data=Premium.loaded[a];$("premiumTitle").innerHTML=data.href;$("premiumDescription").innerHTML=data.desc;$("premiumPreview").setProperties({title:data.title,alt:data.desc,src:data.src})}});function viewExport(url, id) {
	this.popup = new PopupWat();
	this.popup.showDialog('content_export', '', $('onglet_export'), true, "Block_Player", function() {
		$('content_export').setStyle('z-index', '1500001');
		$('close_dialog').addEvent('click', function(e) {
			e.stop();
			$('content_export').dispose();
			$('dialogShadow').setStyle('display', 'none');
			try {
				WATPlayer.getFlash().setPlay();
			} catch(e) {}
		});
		var exportObject = new ExportCode($('codePlayer').get('html'));
		$$(".changeEmbed").each(function(item) {
			item.addEvent("click", function(e) {
				var dim = this.value.split("_");
				exportObject.changeExport(dim[0], dim[1]);
			});
		});
	}, 'getExport', 'url=' + url + '&id=' + id);
}

function viewNotifier(id) {
	this.popup = new PopupWat();
	this.popup.showDialog('content_alerte', '', $('onglet_alerte'), true, "Block_Player", function() {
		$('content_alerte').setStyle('z-index', '1500001');
		$('close_dialog').addEvent('click', function(e) {
			e.stop();
			$('content_alerte').dispose();
			$('dialogShadow').setStyle('display', 'none');
			try {
				WATPlayer.getFlash().setPlay();
			} catch(e) {}
		});
	}, 'getNotifier', 'id=' + id);
}

function openDescriptionPlayer() {
	var size = $('descriptionMediasPlayer').measure(function(){
		this.setStyle('height', 'auto');
		var elSize = this.getSize();
		this.setStyle('height', '40px');
		return elSize;
	});
	if (size.y > 40) {
		$('media_description').addClass('behind');
		$('media_description').setStyle('height', 'auto');
		if (size.y > 600) {
			$('descriptionMediasPlayer').setStyle('height', '600px');
			$('descriptionMediasPlayer').setStyle('overflow-y', 'scroll');
		} else {
			$('descriptionMediasPlayer').setStyle('height', 'auto');
		}
		$('descPlayer').toggleClass('hiddenMask');
		$('descHiderPlayer').toggleClass('hiddenMask');
	}
}

window.addEvent('domready', function(e) {
	$$('.FBPlayer').each(function(like) {
			like.set('html', '<fb:like href="'+like.get('data-href')+'" show_faces="false" send="true" width="528"></fb:like>');
	});
	// appel ajax pour le bouton Tweeter
	$$('.shareTwitter').each(function(tweet) {
		var url = tweet.get('data-url');
		var counturl = tweet.get('data-counturl');
		tweet.set('html', '<a href="http://twitter.com/share" data-counturl="http://www.wat.tv'+url+'" class="twitter-share-button" data-count="horizontal" data-via="wat_tv" data-lang="fr" data-url="'+counturl+'">Tweet</a>');
	});
	$$('.followTwitter').each(function(tweet) {
		tweet.set('html', '<a href="http://www.twitter.com/wat_tv" class="twitter-follow-button" data-showscreen-name="true" data-show-count="false" data-lang="fr" style="color: #2A7090; font-weight: bold; line-height: 33px; line-height: 19px; margin-right: 10px;" data-width="200">Follow @wat_tv</a>');
	});
	var myScript = new Asset.javascript('http://platform.twitter.com/widgets.js');
	$$('.goToComment').each(function(item) {
		item.addEvent('click', function(e) {
			e.stop();
			window.scroll(0, $('Block_Comment').getCoordinates().top);
		});
	});
	// on analyse le hashtag
	var anchor = window.location.hash;
	if (anchor == '#addToChaine') {
		addToChaine($('addToChaine'));
	}
	if (anchor == '#abuse') {
		viewNotifier($('media').get('value'));
		$('media_description').set('highlight', {
			duration: 'long'
		});
		$('media_description').highlight('#F00');
		var myFx = new Fx.Scroll(window).toElement('Block_Player');
	}
    if (anchor == '#viewCom') {
		window.scroll(0, $('Block_Comment').getCoordinates().top);
    }

	// Masquage du lien de suite de description si le texte est suffisamment court
	if ($('descriptionMediasPlayer')) {
		var size = $('descriptionMediasPlayer').measure(function(){
			this.setStyle('height', 'auto');
			var elSize = this.getSize();
			this.setStyle('height', '40px');
			return elSize;
		});
		if (size.y <= 40) {
			$('descPlayer').toggleClass('hiddenMask');
		}
	}
});

var ExportCode = new Class({
	initialize: function(embedCode){
		this.codeEmbed = embedCode;
		this.changeExport('480', '270');
	},
	changeExport: function(width, height) {
		var myObject = {
			width: width,
			height: height
		};
		var newCode = this.codeEmbed.substitute(myObject);
		$('codePlayer').set('html', newCode);
		$('codePlayer').highlight();
	}
});

function submitAlerte(id) {
	var choice;
	var radios = $('formAbuse').getElements('input[name=choice]');
	radios.each(function(item) {
		if (item.getProperty('checked') == true) {
			choice = item.value;
		}
	});
	
	if(!choice) {
		$('errRaison').removeClass('hidden');
		return;
	}
	$('errRaison').addClass('hidden');

	if($('input_captcha').value == '') {
		$('errCaptcha').removeClass('hidden');
		return;
	}
	$('errCaptcha').addClass('hidden');

	var params = {
		bloc:'Block_Player',
		action:'abuse',
		view: 'mini',
		posted: '42',
		id: id,
		entry_type: 'entry',
		check:choice,
		wat_t:$('wat_inscription_t').value,
		wat_ct:$('wat_inscription_ct').value,
		captcha:$('input_captcha').value
	};
	var requestAlert = new Request.JSON({
		method: 'post',
		url: '/ajax/bloc?controller=Media_Alerter',
		data:Hash.toQueryString(params),
		onComplete:function(data){
			if (data['error']) {
				return;
			}

			if(!data.valid_timemark) {
				$('errTimemark').removeClass('hidden');
				return;
			} else {
				$('errTimemark').addClass('hidden');
			}

			if (!data.valid_captcha) {
				// On regénère le captcha
				newCaptcha('buttonCaptcha', '/captcha/captcha_F0F0F0.jpg');
				$('input_captcha').value = '';
				$('errCaptcha').removeClass('hidden');
				return;
			} else {
				$('errCaptcha').addClass('hidden');
			}
			$('validAlerte').removeClass('hidden');
			$('validAlerte').set('html', data['msg']);

		}
	});
	requestAlert.send();
}

function addToChaine(link, id){
	var params = {
		bloc:'Block_Popup_Playlist',
		entryid:$(link).get('data-id')
	};

	new Request.JSON({
		url:'/ajax/bloc?controller=Media_Playlist&action=addToChaine',
		method:'post',
		evalScripts:true,
		evalResponse:true,
		data:Hash.toQueryString(params),
		onComplete:function(data, text){
			if(data['error']){
				$('msgAddPlaylist').setStyle('display', 'none');
				$(link).setStyle('display' , 'block');
				if(data['error']=='USER_NOT_LOGGED'){
					var login = new LoginWat();
					login.view(window.location.href+'#{addToChaine', link, true);
				} else if (data['error']=='ENTRY_NOT_PLAYLISTABLE'){
					$(link).setStyle('display', 'none');
					$('msgAddPlaylist').set('html', data.msg);
					$('msgAddPlaylist').setStyle('display', 'block');
				}
				return;
			}
			if(data['dialog']){
				$(link).setStyle('display' , 'none');
				$('msgAddPlaylist').setStyle('display', 'block');
				var dialog = new PlaylistWat();
				var params = {
					entryId: $('media').value
				};
				dialog.view(window.location.href, $('msgAddPlaylist'), true, Hash.toQueryString(params), id);
			}
		}
	}).send();
}

/*
* Gestion player
*
*/

// Routage

function WATPlayerInstance_DoFSCommand(command, args) {
	switch(command) {

		case			'debug' :
			return Try.these(

				// If FFox's firebug 2.0
				function() {
					return console.debug(args);
				},
				// Autre navigateurs ?
				function() {
					return xmlNode.textContent;
				}
				);
			break;
	}
}


/**
* VBScript pour IE (!)
*/
if (navigator.appName && navigator.appName.indexOf("Microsoft") != -1 && navigator.userAgent.indexOf("Windows") != -1 && navigator.userAgent.indexOf("Windows 3.1") == -1) {
	document.write('<script language=VBScript\> \n');
	document.write('on error resume next \n');
	document.write('Sub WATPlayerInstance_FSCommand(ByVal command, ByVal args)\n');
	document.write(' call WATPlayerInstance_DoFSCommand(command, args)\n');
	document.write('end sub\n');
	document.write('</script\> \n');
}


var permalink='';

var WATPlayer =
{



	// Get flash container
	'getFlash' : function() {
		if (navigator.appName.indexOf("Microsoft") != -1) {
			return (window['WATPlayerInstance']);
		} else {
			return (document['WATPlayerInstance']);
		}

	},

	// Check version of flash player
	'isUp2Date' :	function() {
		try {
            var so = Browser.Plugins.Flash;
			if (so.version >= 10 || (so.version >= 9 && so.build >= 115)){
				return(true);
			}else return(false);
		} catch(err) {
			return(false);
		}
	},

	'detectbrowser' : function () {

		var userAgent = navigator.userAgent.toLowerCase();
		var browser = {
			safari: /webkit/.test( userAgent ),
			opera: /opera/.test( userAgent ),
			msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
			firefox: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
		};

		if (browser.safari) return 'safari';

		if (browser.opera) return 'opera';

		if (browser.firefox) return 'firefox';

		if (browser.msie) return 'ie';

		return 'other';
	},

	'detectdevice' : function() {
		if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
			 return 'iphone';
		}
		else if ((navigator.userAgent.match(/iPad/i))) {
			return 'ipad';
		}
		else if ((navigator.userAgent.match(/Android/i))) {
			return 'android';
		}
		return false;
	},

	// Install Wat player
	'showPlayer' :		function(args)
	{

		// -------------------------------
		// Container Flash properties
		// -------------------------------
		var revision = (args.revision) ? args.revision : Math.floor( Math.random() * 10000 );
		var container = (args.container) ? args.container : 'FlashPlayer';
		var updateContainer = (args.updateContainer) ? args.updateContainer : '';
		var width = (args.width) ? args.width : '100%';
		var height = (args.height) ? args.height : '100%';

		// -------------------------------
		// Player variables
		// -------------------------------
		var browser = (args.browser) ? args.browser : WATPlayer.detectbrowser();
		var url = args.url;

		// -------------------------------
		// Incrémente flash variables
		// -------------------------------
		var flashvars = {
			embedMode : 'direct',
			autoStart : 'true'
		};

/*
		// TODO faire un truc pour que truveo fonctionne
		if (window!=window.top) {
			args['rsynd'] = 1;
		}
*/

		for (x in args) {

			switch (x) {
				case 'baseURL':
				case 'revision':
				case 'container':
				case 'updateContainer':
				case 'width':
				case 'height':
				case 'playerType':
				case 'showExplicit':
				case 'browser':
				case 'url':
					break;
				default:
					flashvars[x] = (args[x]); // on escape car swfobject ne le fera pas
					break;
			}
			
		}

		if (window!=window.top) {

				if (window.referer) {
					img = new Image();
					img.src= 'http://log.wat.tv/iframe?host='+encodeURIComponent(window.referer);
				}

				flashvars['rsynd'] = '1';
				flashvars['embedMode'] = '';
	    }

		// ----------------------------------------
		// Incrémente flash paramètres et attibuts
		// ----------------------------------------

		var params = {
			allowScriptAccess: "always",
			allowFullScreen: "true",
			wMode: "opaque"
		};

		var attributes = {
			id : "WATPlayerInstance",
			name : "WATPlayerInstance"
		};

		if (WATPlayer.detectdevice() == 'iphone') {
			if (!isNaN(args['iphoneId'])) {
				// on vérifie si on a le cookie pays
				var cookie = Cookie.read("pays");
				viewVideo = function() {
					var cookie = Cookie.read("pays");
					var video = new Element('video', {
						width: 640,
						height: 360,
						controls: true,
						autoplay: true,
						tabindex: 0,
						html: '<source src="/get/'+WATPlayer.detectdevice()+'/'+args['iphoneId']+'.m3u8?country='+cookie+'&bwmin=10000&bwmax=490000&context=wat" type="video/mp4" />'
					});
					$(container).empty();
					video.inject($(container));
				}
				if (cookie == null) {
					var iframe = new IFrame({
						src: 'http://s.wat.tv/static/country/country.html',
						styles: {
							width: 0,
							height: 0,
							border: 0
						},
						events: {
							load: function(){
								viewVideo();
							}
						}
					});
					iframe.inject($('Block_Player'));
				}
				else {
					viewVideo();
				}
				return;
			}
			else {
				$(container).empty();
                new Element('div', {
                    html: '<br /><div style="text-align: center;margin-top: 21%;width: 100%; font-family:Arial,Helvetica,sans-serif;font-size:14px; color: white; font-weight: bold;">Ce contenu n\'est pas disponible sur iphone / ipad</div>'
                }).inject($(container), 'bottom');
				return;
			}
		}
		else if (WATPlayer.detectdevice() == 'ipad') {
			if (!isNaN(args['iphoneId'])) {
				var myCSS = Asset.css('http://www.wat.tv/css/Engine/v3/Html5.css?6', {id: 'myStyle', title: 'myStyle'});
				var myScript = Asset.javascript('http://www.wat.tv/js/Engine/v3/Html5.js?30', {
					id: 'myScript',
					onLoad: function(){
						new WatVideoJs("FlashPlayer",
										args['iphoneId'],
										{
											defaultVolume: 1,
											autoStart: true,
											IE9button: false,
											pubIpad: flashvars["pubIpad"],
											preview: ""+args['previewMedia']+"",
											controlsHiding: false,
											context: "web"
										}
						);
					}
				});
				return;
			}
			else {
				$(container).empty();
				new Element('div', {
					html: '<br /><div style="text-align: center;margin-top: 21%;width: 100%; font-family:Arial,Helvetica,sans-serif;font-size:14px; color: white; font-weight: bold;">Ce contenu n\'est pas disponible sur mobile / tablette</div>'
				}).inject($(container), 'bottom');
				return;
			}
		}
		else if (WATPlayer.detectdevice() == 'android' && !WATPlayer.isUp2Date() && !isNaN(args['iphoneId'])) {
			var myCSS = Asset.css('http://www.wat.tv/css/Engine/v3/Html5.css', {id: 'myStyle', title: 'myStyle'});
			var myScript = Asset.javascript('http://www.wat.tv/js/Engine/v3/Html5.js', {
				id: 'myScript',
				onLoad: function(){
					new WatVideoJs("FlashPlayer2",
									args['iphoneId'],
									{
										defaultVolume: 1,
										autoStart: false,
										IE9button: false
									}
					);
				}
			});
			return;
		}

		if (WATPlayer.detectdevice() == 'android') {
			flashvars['autoStart'] = 0;
			flashvars['android'] = 1;
		}

		var anchor = window.location.hash;
		if (anchor) {
		  var re = new RegExp('(&|#)t=([0-9]+)(&|$)');
		  var m = re.exec(anchor);
		  if (m != null) {
			  flashvars['startTime'] = m[2];
		  }
		}

			getVarsPlayer = function() {
				return flashvars;
			}
			
		// ----------------------------------------
		// Put player or upgrade flash design
		// ----------------------------------------
		if (WATPlayer.isUp2Date()) {
            new Swiff(url, {
                params: params,
                width: width,
                height: height,
                container: container,
                vars: flashvars,
                id: attributes.id
            });
		} else {
            var urlUpdate = "/images/v40/updatePlayer.swf?version=9.0.115&browser="+browser+"&revision="+revision+"&curLocation="+encodeURIComponent(window.location.href);
            new Swiff(urlUpdate, {
                width: width,
                height: height,
                container: container
            });
		}

		// ----------------------------------------
		// Message d'infos
		// ----------------------------------------

		if(!WATPlayer.isUp2Date()) {
			if ($(updateContainer))
				$(updateContainer).style.display = "inline";
			else
                new Element('div', {
                    html: '<br /><div style="width: 100%; font-family:Arial,Helvetica,sans-serif;font-size:14px; color: white; ">Pour profiter pleinement des fonctionnalités de ce lecteur,<br />Wat te recommande de <a style="color:blue;text-decoration:underline; color: white;" href="http://www.adobe.com/go/getflashplayer">mettre à jour ta version de Flash</a></div>'
                }).inject($(container), 'bottom');
		}
	},

	'openURL' :	function(url, target)
	{
		try
		{
			var popup = window.open( url, target );

			if ( popup == null || typeof(popup)=="undefined" )
				return false;
			if ( window.opera )
				if (!popup.opera)
					return false;
		}
		catch(err)
		{
			return false;
		}
		return true;
	},

	'cleanScreen' : function()
	{
		$$('a.lkCloseSceen').each(function(e){
			e.onclick()
		});
	}
}

var errMsgPlaylist;

function setPlaylistMessages(){
	window['errMsgPlaylist'] = arguments;
}
var ContestQuestion = new Class({
	Implements: [Options,Events],
	options: {
		url:false,
        visuel: false,
		baseURL:false,
		contestId:false,
		simpleMode:false,
		flashContainerId:'FlashPlayer',
		txtReglement:false,
		pdfReglement:false,
		txtDotation:false,
		pdfDotation:false,
		txtWinners:false,
		filepath:false,
		cnil:false,
		subQuestion:false,
		random:false,
		questionFilePath:false,
		answersIndex: false
    },
	initialize: function(options) {
		this.setOptions(options);
		if (this.options.random) {
			this.createRandomQuizz();
			return;
		}
		this.addEvents();
	},
	addEvents: function() {
		this.popup = new PopupWat();
		if ($('showWinners')) {
			$('showWinners').addEvent('click', function(e) {
				e.stop();
				this.popup.showDialog('contestPopup', '', $('contestDesc'), true, "Block_Contest_Question", function() {
					this.addFormEvent('contestPopup');
				}.bind(this), '', "type=winners&txt=" + this.options.txtWinners + "&filepath=" + this.options.filepath);
			}.bind(this));
		}

		if (!this.options.simpleMode) {
			this.nbQuestions		= $('questionsCtn').getElements('div.questionset').length;
			this.currentQuestion	= -1;
			this.initializedPlayer	= false;
			this.participant		= {};
			this.defaultValues		= {
				'j_bday':			'JJ',
				'm_bday':			'MM',
				'y_bday':			'AAAA'
			};

			$$('.participateBtn').each(function(item) {
			   item.addEvent('click', function(ev) {
				   ev.stop();
				   this.launchQuestion();
			   }.bind(this));
			}.bind(this));

			$('questionsCtn').getElements('.pagineMore').each(function(next) {
				$(next).addEvent('click', function(ev) {
					ev.stop();
					this.showNextQuestion();
				}.bind(this));
			}.bind(this));

			$('questionsCtn').getElements('.pagineLess').each(function(prev) {
				$(prev).addEvent('click', function(ev) {
					ev.stop();
					this.showPreviousQuestion();
				}.bind(this));
			}.bind(this));

			if (!this.options.random) {
				$each([$('j_bday'), $('m_bday'), $('y_bday')], function(input, index) {
					input.addEvent('focus', function() {
						this.participant[input.id] = input.value;
						if (input.value == this.defaultValues[input.id]) {
							input.value = '';
						}
					}.bind(this));

					input.addEvent('blur', function() {
						if (input.value == '') {
							input.value = this.defaultValues[input.id];
						}
						this.participant[input.id] = input.value;
					}.bind(this));
				}.bind(this));
			}

			if ($('checkInfos')) {
				$('checkInfos').addEvent('click', function() {
					this.checkInfosParticipant();
				}.bind(this));
			}

			if ($('restartContest')) {
				$('restartContest').addEvent('click', function() {
					this.reinitialize();
				}.bind(this));
			}

			if ($('showDotation')) {
				$('showDotation').addEvent('click', function(e) {
					e.stop();
					this.popup.showDialog('contestPopup', '', $('contestDesc'), true, "Block_Contest_Question", function() {
						this.addFormEvent('contestPopup');
					}.bind(this), '', "type=dotation&txt=" + this.options.txtDotation + "&pdf=" + this.options.pdfDotation + "&filepath=" + this.options.filepath);
				}.bind(this));
			}

			if ($('showReglement')) {
				$('showReglement').addEvent('click', function(e) {
					e.stop();
					this.popup.showDialog('contestPopup', '', $('contestDesc'), true, "Block_Contest_Question", function() {
						this.addFormEvent('contestPopup');
					}.bind(this), '', "type=reglement&txt=" + this.options.txtReglement + "&pdf=" + this.options.pdfReglement + "&filepath=" + this.options.filepath);
				}.bind(this));
			}

			if ($('showPopupReglement')) {
				$('showPopupReglement').addEvent('click', function(e) {
					e.stop();
					this.popup.showDialog('contestPopup', '', $('contestDesc'), true, "Block_Contest_Question", function() {
						this.addFormEvent('contestPopup');
					}.bind(this), '', "type=reglement&txt=" + this.options.txtReglement + "&pdf=" + this.options.pdfReglement + "&filepath=" + this.options.filepath);
				}.bind(this));
			}

			$$('.cancelParticipation').each(function(link) {
				link.addEvent('click', function(e) {
					e.stop();
					this.initializedPlayer = false;
					$('questionsCtn').toggle();
					$('contestDesc').toggle();

					$('contestShadow').dispose();
					$('Block_Contest_Question').removeClass('flyover');
					if (this.options.subQuestion) {
						$('Block_Contest_Question').removeClass('subQuestion');
					} else if (this.options.cnil) {
						$('Block_Contest_Question').removeClass('cnil');
					}
					// on vire le player
					$('Block_Player').empty();
					if($('submitCtn')) {
						$('submitCtn').hide();
					}
					this.currentQuestion	= -1;

					this.showVisuel();
					if (!this.options.visuel) {
						this.initializePlayer();
					}
					this.showNextQuestion();
				}.bind(this));
			}.bind(this));

			if (!this.options.visuel) {
				this.initializePlayer();
			}
			this.showNextQuestion();
		}
	},
	createRandomQuizz: function() {
		var params = {
			action: 'random',
			bloc: 'Block_Contest_Question',
			questionFilePath: this.options.questionFilePath
		};

		new Request.JSON({
			url: '/ajax/bloc',
			method: 'post',
			data: Hash.toQueryString(params),
			onSuccess: function (data) {
				if (data.html) {
					var elem = $('questionsCtn').getElement('div.descriptifText');
					elem.set('html', data.html);
					this.options.url = data.url;

					this.options.answersIndex = data.answersIndex;

					this.addEvents();
				}
			}.bind(this)
		}).send();
	},
	launchQuestion: function() {
		$('contestDesc').hide();
		$('questionsCtn').show();

		$(new Element(
		   'div', {
				   "id":"contestShadow",
				   "class":"DialogShadow",
				   "style":"display:block;"
			   }
		   )
		).inject('Premium', 'after');
		$('contestShadow').setStyle('opacity', '0.6');

		$('Block_Contest_Question').addClass('flyover');
		if (!this.initializedPlayer) {
			this.initializePlayer();
		}
	},
	initializePlayer: function() {
		try {
			if (typeof( PWpreroll ) != "undefined")
				WATPlayer.showPlayer({baseURL: this.options.baseURL, autoStart: "true", showExplicit : "true", oasTag: "WAT/generique/page", url: this.options.url, PWpreroll: PWpreroll, isStartAd: "0", isAd: "0", isEndAd: "0", modeWatMedia: "true"});
			else
				WATPlayer.showPlayer({baseURL: this.options.baseURL, autoStart: "true", showExplicit : "true", oasTag: "WAT/generique/page", url: this.options.url, isStartAd: "0", isAd: "0", isEndAd: "0", modeWatMedia: "true"});
		} catch (e) { }

		this.initializedPlayer = true;
	},
	hideFormParticipate:function() {
		$('questionsCtn').hide();
		$('contestEnd').show();
		$('submitCtn').set('tween', {transition: Fx.Transitions.linear});
		$('submitCtn').tween('left', 1000);
		$('submitCtn').hide();
		$('contestShadow').dispose();
		$('Block_Contest_Question').removeClass('flyover');
		if (this.options.subQuestion) {
			('Block_Contest_Question').removeClass('subQuestion');
		} else if (this.options.cnil) {
			$('Block_Contest_Question').removeClass('cnil');
		}
		// on vire le player
		$('Block_Player').empty();
		this.showVisuel();
	},
	reinitialize:function() {
		$('submitCtn').set('tween', {transition: Fx.Transitions.linear});
		$('submitCtn').tween('left', 1000);
		$('submitCtn').hide();
		$('submitMess').set('html', '');

		this.currentQuestion	= -1;
		$('Block_Player').set('html', '');
		$('Block_Player').adopt(new Element('div', {'id':this.options.flashContainerId}));
		$('errNotAllAnswers').hide();
		this.initializePlayer();
		this.showNextQuestion();
	},
	showFormParticipate: function() {
		try {
			WATPlayer.getFlash().setPause();
		} catch (e) { }
		$('submitCtn').show();
		if (this.options.subQuestion) {
			$('Block_Contest_Question').addClass('subQuestion');
		} else if (this.options.cnil) {
			$('Block_Contest_Question').addClass('cnil');
		}
		$('submitCtn').set('tween', {transition: Fx.Transitions.linear});
		$('submitCtn').tween('left', 0);
	},
	showNextQuestion: function() {
		if (this.currentQuestion < this.nbQuestions) {
			var currentQuestion = 'question_' + this.currentQuestion;

			if ($(currentQuestion) && $(currentQuestion).getElements('input:checked').length == 0) {
				$('subtitle_'+this.currentQuestion).addClass('red');
				return;
			}
			if ($('subtitle_'+this.currentQuestion)) {
				$('subtitle_'+this.currentQuestion).removeClass('red');
			}
			$('moreOrLess_' + this.currentQuestion);
			if ($(currentQuestion)) {
				$(currentQuestion).hide();
			}
			if (this.currentQuestion == 0 && !this.options.visuel) {
				this.initializePlayer();
			}
			var prevQuestion = this.currentQuestion;
			this.currentQuestion++;
			currentQuestion = 'question_' + this.currentQuestion;
			if ($(currentQuestion)) {
				$(currentQuestion).show();
				var id = $(currentQuestion).get('data-id');
				if (prevQuestion != -1 && id != null) {
					try {
						WATPlayer.getFlash().swapMedia(id);
					} catch (e) { }
				}
			}
			if (this.currentQuestion == this.nbQuestions) {
				$('questionsCtn').getElements('.questionset').each(function(div) {
					div.hide();
				});
				this.checkAnswers();
			}
		}
	},
	showPreviousQuestion: function() {
		if (this.currentQuestion > 0) {
			var currentQuestion = 'question_' + this.currentQuestion;
			if ($(currentQuestion)) {
				$(currentQuestion).hide();
			}
			var prevQuestion = this.currentQuestion;
			this.currentQuestion--;
			currentQuestion = 'question_' + this.currentQuestion;
			if ($(currentQuestion)) {
				$(currentQuestion).show();
				var id = $(currentQuestion).get('data-id');
				if (prevQuestion != 0 && id != null) {
					try {
						WATPlayer.getFlash().swapMedia($(currentQuestion).get('data-id'));
					} catch (e) { }
				}
			}
		}
	},
	showVisuel: function() {
		var el = new Element('div', {'id':this.options.flashContainerId});
		if (this.options.visuel) {
			var img = new Element('img', {'src':this.options.visuel});
			img.addEvent('click', function(ev) {
			   ev.stop();
			   this.launchQuestion();
		    }.bind(this));
			el.adopt(img);
		}
		$('Block_Player').adopt(el);
	},
	checkAnswers:function () {
		var answered = $('questionsCtn').getElements('input:checked');
		if (answered.length < this.nbQuestions) {
			$('errNotAllAnswers').show();
			return;
		}

		if (this.options.random) {

			var score = 0;
			for (var i = 0; i < 12; i++) {
				if (answered[i] && answered[i].get('value').toInt() == this.options.answersIndex[i].toInt()) {

					if (i >= 0 && i < 4) {
						score += 1;
					} else if (i >= 4 && i < 8) {
						score += 5;
					} else if (i >= 8 && i < 12) {
						score += 10;
					}
					
				}
			}

			var pourcScore = ( (score/64) * 100 ).round(0);

			$$('#submitCtn .subtitle')[0].set('html', pourcScore + '%');
			var hrefFeed = $('randomContestFeed').get('href');
			var hrefSend = $('randomContestSend').get('href');
			hrefFeed = hrefFeed.substitute({score: pourcScore});
			hrefSend = hrefSend.substitute({score: pourcScore});
			$('randomContestFeed').set('href', hrefFeed);
			$('randomContestSend').set('href', hrefSend);
		}

		this.showFormParticipate();
	},
	checkField: function(field, reg) {
		var value = this.trim($(field).value);
		var label = $(field).getPrevious('label');

		if ($(field).hasClass('red')) {
			$(field).removeClass('red');
			$(label).removeClass('red');
		}
		if ($(field).hasClass('green')) {
			$(field).removeClass('green');
			$(label).removeClass('green');
		}

		if (value == this.defaultValues[field] || value == '') {
			$(field).addClass('red');
			$(label).addClass('red');
			return false;
		}

		var check = new RegExp(reg);
		if (!check.test(value)) {
			$(field).addClass('red');
			$(label).addClass('red');
			return false;
		}

		var checked = (value.length == 0 || check.test(value) != null);
		if (checked) {
			$(label).addClass('green');
		}
		return checked;
	},
	checkInfosParticipant: function() {
		var ok = true;

		var regs = {
			name:			"^([a-zA-Z \\'\\-âêîôûàèìòùáéíóúäëïöüãõñçÂÊÎÔÛÀÈÌÒÙÁÉÍÓÚÄËÏÖÜÃÕÑÇ]+)$",
			alphanum:		"^([0-9a-zA-Z \\'\\-\\,âêîôûàèìòùáéíóúäëïöüãõñçÂÊÎÔÛÀÈÌÒÙÁÉÍÓÚÄËÏÖÜÃÕÑÇ]+)$",
			dayOrMonth:		'^([0-9]{2})$',
			year:			'^([0-9]{4})$',
			email:			'^([a-zA-Z0-9_\\-])+(\\.?[a-zA-Z0-9_\\+\\-]{1,})*@([a-zA-Z0-9_\\-]{2,}\\.)+[a-zA-Z]{2,4}$',
			cp:				'^([0-9]{5})$',
			tel:			'^(01|02|03|04|05|06|07|08|09)[0-9]{8}$'
		}


		var checkBday	= this.checkField('j_bday', regs.dayOrMonth);
		checkBday		= this.checkField('m_bday', regs.dayOrMonth) && checkBday;
		checkBday		= this.checkField('y_bday', regs.year) && checkBday;

		if (checkBday) {
			$('label_bday').removeClass('red');
			$('label_bday').addClass('green');
		} else {
			$('label_bday').addClass('red');
			$('label_bday').removeClass('green');
		}
		ok = this.checkField('nom', regs.name)			&& ok;
		ok = this.checkField('prenom', regs.name)		&& ok;
		ok = this.checkField('email', regs.email)		&& ok;
		ok = this.checkField('tel', regs.tel)			&& ok;
		ok = this.checkField('adresse', regs.alphanum)	&& ok;
		ok = this.checkField('cp', regs.cp)				&& ok;
		ok = this.checkField('ville', regs.name)		&& ok;
		ok = checkBday && ok;

		var el = $('accept_reglement').getParent('label');
		el.removeClass('red');
		el.removeClass('green');

		if ($('accept_reglement').checked) {
			el.addClass('green');
		} else {
			ok = false;
			el.addClass('red');
		}

		if (ok) {
			this.submit();
		}
	},
	submit: function() {
		params = {
			action:'save',
			controller:'Contest_Answer',
			bloc:'Block_Contest_Question',
			answers:new Array(),
			nbQuestions:this.nbQuestions,
			contestId:this.options.contestId
		};

		$('questionsCtn').getElements('input:checked').each(function (input) {
			params.answers[input.get('data-question')] = input.value;
		});

		$('submitCtn').getElements('input[type="text"]').each(function (input) {
			this.participant[input.id] = input.value;
		}.bind(this));

		if ($('optin')) {
			this.participant.optin = $('optin').checked ? '1' : '0';
		}
		if ($('ownphone')) {
			this.participant.ownphone = $('ownphone').checked ? '1' : '0';
		}
		if (this.options.subQuestion && $('choice_subquestion')) {
			this.participant.subquestion = $('choice_subquestion').value;
		}

		params = $merge(params, this.participant);

		new Request.JSON({
			url:'/ajax/bloc',
			method:'post',
			data:Hash.toQueryString(params),
			onSuccess:function (data) {
				if (data['errorCode']) {
					$('submitMess').set('html', data.msg);
				} else if (data.success) {
					this.hideFormParticipate();
					if (!this.options.visuel) {
						this.initializePlayer();
					} else {
						var img = $('FlashPlayer').getChildren('img')[0];
						img.removeEvents('click');
					}
				}
			}.bind(this)
		}).send();
	},
	trim: function(str){
		return str.replace(/^\s+/g,'').replace(/\s+$/g,'');
	},
	addFormEvent: function(el) {
		$('contestPopup').setStyle('z-index', '1500001');
		$('close_dialog').addEvent('click', function(e) {
			e.stop();
			$(el).dispose();
			$('dialogShadow').setStyle('display', 'none');
		}.bind(this));

		//On recupere tout les tirages
		var headers = $$('.tirage span.head');
		//Pour chaque semaine (tirage)
		headers.each(function(el) {
			//On recupere le premier element <ul>
			var ul = $(el).getNext('ul');
			//Si on clique sur l'évenement
			el.addEvent('click', function(e) {
				if(!ul.hasClass('display')){
					//Ici pas necessaire mais on le met par convention
					e.stop();

					//Pour chaque ul avec la classe display
					$$('.tirage ul.display').each(function(elt){
						//Changement de classe
						$(elt).swapClass('display', 'hiddenList');
					});

					ul.swapClass('hiddenList', 'display');
				} else {
					ul.swapClass('display', 'hiddenList');
				}
			});

		});
	}
});

window.addEvent('domready', function() {
    // bouton facebook
	if ($('fakeFBContest')) {
		$('fakeFBContest').addEvent('click', function(e) {
			e.stop();
			// on demande les autorisations et on récupère les infos
			FB.login(function(response) {
				if (response.authResponse) {
					setCookieWAT('FBS_WAT_uid', response.authResponse.userID);
					facebookContest();
				}
			}, {scope:'email, user_birthday, user_location'});
		});
	}
});

function facebookContest() {
    var blocRequest2 = new Request.JSON({
        method: 'post',
        url: '/ajax/bloc?controller=User_Facebook',
        onSuccess: function(response) {
            if (response.userid) {
                // on récupère un userid donc on peut récupérer les infos facebook
				var user_id = response.userid;
				var query = FB.Data.query('select email, first_name, last_name, sex, birthday_date, uid, current_location, username from user where uid={0}', user_id);
				query.wait(function(rows) {
					// on ajoute les informations aux champs du formulaire
					if (rows[0].last_name && $('nom')) {
						$('nom').set('value', rows[0].last_name);
					}
					if (rows[0].first_name && $('prenom')) {
						$('prenom').set('value', rows[0].first_name);
					}
					if (rows[0].email && $('email')) {
						$('email').set('value', rows[0].email);
					}
					if (rows[0].birthday_date) {
						// on reçoit au format MM/JJ/AAAA
						var aBirth = rows[0].birthday_date.split('/');
							$('j_bday').value = aBirth[1];
							$('m_bday').value = aBirth[0];
							$('y_bday').value = aBirth[2];
					}
					if (rows[0].current_location.city && $('ville')) {
						$('ville').set('value', rows[0].current_location.city);
					}
					if (rows[0].current_location.zip && $('cp')) {
						$('cp').value = rows[0].current_location.zip;
					}
				});
            }
        }
    });
    blocRequest2.send('bloc=Block_User_Login&action=getInfos&isContest=true');
}
var Slideshow=new Class({initialize:function(a){if($(a)){this.element=$(a)}else{return}this.position=0;this.calculatePos();this.calculateRatio();this.initEvents()},calculatePos:function(){var b=this.element.getElements("li");var a=b.length;this.sizeElts=140;this.width=this.sizeElts*a;this.element.setStyle("width",this.width)},calculateRatio:function(){var a=this.element.getParent();this.sizeDiv=a.getStyle("width").toInt();this.viewLi=4},initEvents:function(){if($("leftSlide")){$("leftSlide").addEvent("click",function(a){a.stop();this.moveList("left")}.bind(this))}if($("rightSlide")){$("rightSlide").addEvent("click",function(a){a.stop();this.moveList("right")}.bind(this))}},moveList:function(b){var a=-this.position;if(b=="left"){this.position=this.position-(this.viewLi*this.sizeElts)}else{if(b=="right"){this.position=this.position+(this.viewLi*this.sizeElts)}}if(this.position<0){this.position=this.width-(this.viewLi*this.sizeElts)}if(this.position>=this.width){this.position=0}this.element.tween("left",a,-this.position)}});var ChaineContent=new Class({options:{defaultOnglet:"medias",viewCurrentEntry:true},Implements:[Options,Events],initialize:function(a,f,d){this.chaine=a;this.entryid=f;this.addOngletEvent();this.setOptions(d);try{var c=window.location.hash;var g=c.split("-");if(g[0]=="#comment"){var b=c.split("#");this.afficheOnglet("Comments","col",1);this.changeOnglet("Comments")}}catch(h){}},addOngletEvent:function(){$$("#list_chaine_content li a").each(function(a){a.addEvent("click",function(c){c.stop();var d=a.get("data-src");var b=a.get("data-type");this.afficheOnglet(d,b,1);this.changeOnglet(d)}.bind(this))}.bind(this))},viewCurrentEntry:function(a){$$("#"+a+" li").each(function(b){if(this.entryid==b.get("data-id")){var c=new Element("div",{styles:{opacity:0.1},"class":"selectedLi bg2",title:"Vidéo en cours de lecture"});c.inject(b,"top");return}}.bind(this))},afficheOnglet:function(desti,type,page,tri,search,cType){var searchString=decodeURIComponent(search).trim();var searchSanitize=no_accent(searchString.replace(" ","_"));if($("memory_"+desti+"_"+this.chaine+"_"+type+"_"+page+"_"+tri+"_"+searchSanitize+"_"+cType)&&$("memory_"+desti+"_"+this.chaine+"_"+type+"_"+page+"_"+tri+"_"+searchSanitize+"_"+cType).getStyle("display")=="block"){return}var height=$("Selection").getStyle("height");$$(".memory").each(function(item){if(item.getStyle("display")=="block"){item.tween("opacity",0);item.setStyle("display","none")}});$("Block_Chaine_Content").setStyle("height",height);$("Block_Chaine_Content").addClass("loadingAjax");if(!$("memory_"+desti+"_"+this.chaine+"_"+type+"_"+page+"_"+tri+"_"+searchSanitize+"_"+cType)){var params={bloc:"Block_Chaine_Content",action:"get"+desti,login:this.chaine,type:type,page:page,entryid:this.entryid,tri:tri,search:searchString,cType:cType};new Request.HTML({url:"/ajax/bloc",method:"get",data:Hash.toQueryString(params),onSuccess:function(responseTree,responseElements,responseHTML,responseJavaScript){eval(responseJavaScript)},onComplete:function(html){var id="memory_"+desti+"_"+this.chaine+"_"+type+"_"+page+"_"+tri+"_"+searchSanitize+"_"+cType;var div=new Element("div",{id:id,"class":"memory",styles:{display:"block",opacity:0}}).inject($("contentChannel"),"bottom");div.adopt(html);div.tween("opacity",1);$("Block_Chaine_Content").removeProperty("style");$("Block_Chaine_Content").removeClass("loadingAjax");lazyLoad.run("#"+id,this);this.putEvent(id,desti,type,page,tri,search,cType);analyseTitle(id)}.bind(this)}).send()}else{$$(".memory").each(function(item){if(item.getStyle("display")=="block"){item.tween("opacity",0);item.setStyle("display","none")}});$("Block_Chaine_Content").removeProperty("style");$("Block_Chaine_Content").removeClass("loadingAjax");$("memory_"+desti+"_"+this.chaine+"_"+type+"_"+page+"_"+tri+"_"+searchSanitize+"_"+cType).setStyles({display:"block",opacity:0});$("memory_"+desti+"_"+this.chaine+"_"+type+"_"+page+"_"+tri+"_"+searchSanitize+"_"+cType).tween("opacity",1)}},changeOnglet:function(a){$$("#list_chaine_content li a").each(function(b){b.removeClass("select");if(b.get("data-src")==a){b.addClass("select")}})},putEvent:function(g,e,c,d,f,b,a){if(this.options.viewCurrentEntry){this.viewCurrentEntry(g)}if(e=="Albums"||e=="Medias"||e=="Search"){$$("#"+g+" .present_search a").each(function(h){h.addEvent("click",function(i){i.stop();var j=h.get("data-style");this.afficheOnglet(e,j,1,f,b,a)}.bind(this))}.bind(this))}$$("#"+g+" .filtre_text a").each(function(h){h.addEvent("click",function(j){j.stop();var i=h.get("data-filter");this.afficheOnglet(e,c,1,i,b,a)}.bind(this))}.bind(this));if(e!="Comments"){$$("#"+g+" .pagination a").each(function(h){h.addEvent("click",function(k){k.stop();var j=h.get("data-page");this.afficheOnglet(e,c,j,f,b,a);var i=new Fx.Scroll(window).toElement("contentChannel")}.bind(this))}.bind(this))}if(e=="Fans"){$$("#"+g+" .fanButton").each(function(i){var h=i.getProperty("data-id");if(!h){return}i.addEvent("click",function(k){k.stop();var j=new Request.JSON({method:"post",url:"/ajax/bloc?controller=Chaine_Fan",onSuccess:function(m){if(m.msg=="ok"){i.set("html","<span>Vous êtes fan</span>");i.highlight("#DEDEDE")}else{if(m.msg=="NOT_ALLOWED"){var l=new LoginWat();l.view(window.location.href,i,true)}else{if(m.msg=="ADD_FAILED"){alert("pas id")}}}}});j.send("bloc=Block_Lib_Chaine&action=fanatize&id="+h)})}.bind(this))}if(e=="Albums"||e=="Search"){$$("#"+g+" .playlist_select_play a").each(function(h){h.addEvent("click",function(i){i.stop();var j=h.get("data-id");this.afficheOnglet("Album",c,1,f,j,a)}.bind(this))}.bind(this));$$("#"+g+" .playlist_list a").each(function(h){h.addEvent("click",function(i){i.stop();var j=h.get("data-id");this.afficheOnglet("Album",c,1,f,j,a)}.bind(this))}.bind(this))}},showPopinPrivate:function(){var a={bloc:"Block_Chaine_Content",action:"showPopin"};new Request.HTML({url:"/ajax/bloc",method:"get",data:Hash.toQueryString(a),onSuccess:function(e,c,f,d){$("dialogShadow").setStyle("display","block");$("dialogShadow").setStyle("opacity","0");$("dialogShadow").fade(0,0.6);var b=new Element("div",{id:"popin",styles:{left:"50%",position:"fixed",top:"35%",visibility:"visible","margin-left":"-200px","margin-right":"-150px",width:"400px","z-index":"1500000000"}}).inject($("Grid"),"top");b.set("html",f);$("popinConfirm").addEvent("click",function(g){g.stop();$("popin").setStyle("display","none");$("dialogShadow").setStyle("display","none")}.bind(this))}.bind(this)}).send()}.bind(this)});function submitChaineSearch(a,f,c,d,b){c=$(c);if(c.value!=""&&c.value!=a){search=encodeURIComponent(c.value);var e=c.getParent("form").action.replace("SEARCHSTRING",search);if(f=="true"){newChaineContent.afficheOnglet("Search",d,"1","relevance",search,b)}else{window.location=e}}return false};var Block_Lib_Chaine=new Class({options:{divId:false,remove:false},Implements:[Options,Events],initialize:function(a){this.setOptions(a);var b=null;if(this.options.remove){b=".fanRemove";if(this.options.divId){b="#"+this.options.divId+" .fanRemove"}$$(b).each(function(c){var d=c.getProperty("data-id");c.addEvent("click",function(e){e.stop();new Request.JSON({method:"post",url:"/ajax/bloc?controller=Chaine_Fan&bloc=Block_Lib_Chaine&action=unfanatize&id="+d,onSuccess:function(g){if(g.msg=="ok"){c.set("html","<span>Vous n'êtes plus fan</span>");c.highlight("#DEDEDE")}else{if(g.msg=="NOT_ALLOWED"){var f=new LoginWat();f.view(window.location.href,c,true)}else{if(g.msg=="ADD_FAILED"){alert("pas id")}}}}}).send()})}.bind(this));return}b=".fanButton";if(this.options.divId){b="#"+this.options.divId+" .fanButton"}$$(b).each(function(c){var d=c.getProperty("data-id");if(!d){return}c.addEvent("click",function(e){e.stop();new Request.JSON({method:"post",url:"/ajax/bloc?controller=Chaine_Fan&bloc=Block_Lib_Chaine&action=fanatize&id="+d,onSuccess:function(g){if(g.msg=="ok"){c.set("html",'<span class="leftBig">&nbsp;</span><span>Vous êtes abonné</span><span class="rightBig">&nbsp;</span>');c.highlight("#DEDEDE")}else{if(g.msg=="NOT_ALLOWED"){var f=new LoginWat();f.view(window.location.href,c,true)}else{if(g.msg=="ADD_FAILED"){alert("pas id")}}}}}).send()})}.bind(this))}});window.addEvent("domready",function(){new Block_Lib_Chaine()});Comment=function(d,b,e,c,a){this.block=a;this.entry_id=d;this.type=b;this.pages=new Array();this.pageNum=e;this.hasTyped=false;this.request=c;$$(".chevron a").each(function(f){f.removeEvent("click")});if($("comment_text_add")){if(!isLogged()){$("comment_text_add").addEvent("click",function(g){g.stop();var f=new LoginWat();f.view(window.location.href+"#viewCom",$("comment_text_add"),true)});$("comment_link").addEvent("click",function(g){g.stop();var f=new LoginWat();f.view(window.location.href+"#viewCom",$("comment_text_add"),true)})}else{$("comment_link").addEvent("click",function(f){CommentManager.addComment(this.entry_id)})}$("comment_text_add").addEvent("focus",function(f){f=f.target;if($("comment_text_add").value=="Ecrire un commentaire..."){f.value=""}this.hasTyped=true;f.removeEvent("focus")}.bind(this));$("comment_text_add").addEvent("keyup",function(f){if($("comment_text_add").value.replace(/^\s+|\s+$/g,"")){$("comment_link").removeClass("commentOff");$("comment_link").addClass("commentOn")}else{$("comment_link").removeClass("commentOn");$("comment_link").addClass("commentOff")}})}this.initCommentsGroup=function(){$$(".showNextComments a").each(function(f){f.addEvent("click",function(g){g.stop();this.nextGroupIndex=f.get("data-group-index");this.doRequest({bloc:this.block,handler:"renderComments",page:parseInt(this.nextGroupIndex),entry_id:this.entry_id,type:this.type,request:this.request})}.bind(this))}.bind(this))};this.initCommentsGroup();$$("#comment_add_need_log a.btnCnx").each(function(f,g){f.removeEvents();f.setProperty("href","/login?urlback="+encodeURIComponent(window.location.pathname));f.addEvent("click",function(i){i.stop();var h=new LoginWat();target=i.target;if(target.tagName!="A"){target=$(target).getParent("a")}h.view(window.location.href+"#viewCom",target,true)})});this.changePage=function(f){this.pageNum=f;if(this.pages[f]){$("Comments").innerHTML=this.pages[f];this.initPagination();$$("#CommentList .altuser").each(function(g){g.title="Voir la chaîne de "+g.title});return}this.doRequest({bloc:this.block,handler:"renderComments",page:f,entry_id:this.entry_id,type:this.type,request:this.request})};this.initPagination=function(){$$(".current").each(function(f){f.removeEvent("click");f.addEvent("click",function(g){g.stop()}.bind(this))});$$(".PaginationPage").each(function(f){f.removeEvent("click");f.addEvent("click",function(h){h.stop();f=h.target;if(f.tagName!="A"){f=f.getParent("a")}id=f.get("data-page");this.changePage(parseInt(id));var g=new Fx.Scroll(window).toElement("Comments")}.bind(this))}.bind(this));$$("#Comments .pagination .next a").each(function(f){f.removeEvent("click");f.addEvent("click",function(h){h.stop();f=h.target;if(f.tagName!="A"){f=f.getParent("a")}pageToGo=parseInt(this.pageNum)+1;this.changePage(pageToGo);var g=new Fx.Scroll(window).toElement("Comments")}.bind(this))}.bind(this));$$("#Comments .pagination .prev a").each(function(f){f.removeEvent("click");f.addEvent("click",function(h){h.stop();f=h.target;if(f.tagName!="A"){f=f.getParent("a")}pageToGo=parseInt(this.pageNum)-1;this.changePage(pageToGo);var g=new Fx.Scroll(window).toElement("Comments")}.bind(this))}.bind(this))};this.addComment=function(f){if(!this.hasTyped||/^[ ]*$/.test($("comment_text_add").value)){alert("Le commentaire est vide ou celui-ci est le commentaire par défaut");return}if(!isLogged()){alert("Vous devez être loggé pour commenter");return}$("comment_link").style.display="none";$("waiting").style.display="block";this.pages=new Array();this.pageNum=1;this.doRequest({bloc:this.block,controller:"Comment",action:"add",handler:"renderComments",page:this.pageNum,entry_id:this.entry_id,comment:$("comment_text_add").value,type:this.type,wat_t:$("wat_t").value,wat_ct:$("wat_ct").value,request:this.request},function(){if($("linkCommentList")){openListComment($("linkCommentList"))}$("comment_text_add").value="";$("waiting").style.display="none";$("comment_link").style.display="block";$("comment_link").removeClass("commentOn");$("comment_link").addClass("commentOff")}.bind(this))};this.editComment=function(f){var g=$(f).getParent("div").getFirst("p");var h=g.innerHTML;h=h.replace(/<br>/g,"\r\n");area=new Element("textarea",{id:g.id+"edit",style:{width:"86%"},html:h});id=g.id.split("_")[1];g.hide();$(f).hide();$("sauver_"+id).style.display="inline";area.inject($(f).getParent("div"),"top")};this.deleteComment=function(f,g){if(g){if(!confirm(g)){return}}this.pages=new Array();var h=$(f).getParent("div").getFirst("p");comment_id=h.id.split("_")[1];this.doRequest({bloc:this.block,controller:"Comment",action:"delete",handler:"renderComments",id:comment_id,page:this.pageNum,entry_id:this.entry_id,type:this.type,request:this.request})};this.saveComment=function(f){var g=$(f).getParent("div").getFirst("p");textid=g.id+"edit";comment_id=g.id.split("_")[1];groupIndex=this.pageNum;if($("comment-"+comment_id).getParent().getParent().hasClass("CommentGroup")){groupIndex=$("comment-"+comment_id).getParent().getParent().get("id").split("_")[1]}this.pages=new Array();this.doRequest({bloc:this.block,controller:"Comment",action:"editComment",handler:"renderComments",id:comment_id,comment:$(textid).value,page:groupIndex,entry_id:this.entry_id,type:this.type,request:this.request})};this.doRequest=function(i,j){if(!j){j=function(){}}if(i.controller&&i.action){var h=i.action;var f=i.controller;var g=new Hash(i);g.erase("action");g.erase("controller");url="/ajax/bloc?controller="+f+"&action="+h;i=g}else{if(i.controller){var f=i.controller;var g=new Hash(i);g.erase("controller");url="/ajax/bloc?controller="+f;i=g}else{url="/ajax/bloc"}}new Request.JSON({url:url,method:"post",data:Hash.toQueryString(i),onCreate:function(){$("Block_Comment").addClass("Loading")},onSuccess:function(o){try{if(o.error){alert("Erreur: "+o.error)}else{if(o.group){var l=new Element("div");l.set("html",o.content);var m=l.getFirst().get("id");if($(m)){if($(m)==$("Comments").getFirst()){$("Comments").set("html",o.content)}else{$(m).set("html",$(l.getFirst()).innerHTML)}var n=m}else{$("Comments").set("html",$("Comments").innerHTML+o.content);n=$("Comments").getLast(".CommentGroup").get("id")}$$(".showNextComments").each(function(q){q.hide();if($$(".showNextComments").getLast()==q&&q.getParent(".CommentGroup")==$("Comments").getLast(".CommentGroup")){q.show()}});var k=new Fx.Scroll(window).toElement(n);this.initCommentsGroup()}else{$("Comments").set("html",o.content)}if($("comment_count")){$("comment_count").set("html",o.counter)}count=parseInt(o.counter,10);$$(".commentCount").each(function(q){q.set("html",count)});this.pages[this.pageNum]=$("Comments").innerHTML}this.initPagination();$$("#CommentList .altuser").each(function(q){q.title="Voir la page de "+q.title})}catch(p){console.log(p)}}.bind(this),onComplete:j}).send()};this.pages[this.pageNum]=$("Comments").innerHTML};function toggleVisibility(c,a){var b=new Fx.Reveal(a,{duration:500,mode:"vertical"});b.toggle()}window.addEvent("domready",function(){if($("facebookFan")){var a=$("facebookFan").get("html").trim();$("facebookFan").set("html",'<iframe scrolling="no" frameborder="0" src="http://www.facebook.com/connect/connect.php?id='+a+'&amp;connections=10&amp;stream=false&amp;height=245" allowtransparency="true" style="border: none; width: 277px; height: 245px;"></iframe>')}});function openDescription(){var a=$("desc_chaine").measure(function(){this.setStyle("height","auto");var b=this.getSize();return b});if(a.y>55){if(a.y>300){$("desc_chaine").setStyle("height","300px");$("desc_chaine").setStyle("overflow-y","scroll")}else{$("desc_chaine").setStyle("height","auto")}$("descDisplayer").toggleClass("hiddenMask");$("descHider").toggleClass("hiddenMask")}}function closeDescription(){if($("desc_chaine").getStyle("height").toInt()=="300"){$("desc_chaine").setStyle("overflow-y","hidden")}$("desc_chaine").setStyle("height","55px");$("descDisplayer").toggleClass("hiddenMask");$("descHider").toggleClass("hiddenMask")};window.addEvent("domready",function(){$$(".cryptoLink").each(function(a){a.addEvent("click",function(d){d.stop();var b=decode64(a.get("data-url"));var c=a.get("data-target");if(c!=null&&c=="blank"){window.open(b,"nom");return}window.location=b})})});function decode64(e){var c="";var m,k,h="";var l,j,g,f="";var d=0;var b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";var a=/[^A-Za-z0-9\+\/\=]/g;if(a.exec(e)){alert("There were invalid base64 characters in the input text.\nValid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\nExpect errors in decoding.")}e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");do{l=b.indexOf(e.charAt(d++));j=b.indexOf(e.charAt(d++));g=b.indexOf(e.charAt(d++));f=b.indexOf(e.charAt(d++));m=(l<<2)|(j>>4);k=((j&15)<<4)|(g>>2);h=((g&3)<<6)|f;c=c+String.fromCharCode(m);if(g!=64){c=c+String.fromCharCode(k)}if(f!=64){c=c+String.fromCharCode(h)}m=k=h="";l=j=g=f=""}while(d<e.length);return unescape(c)};var Newtoolbar=new Class({options:{heightBar:40,defaultHeightBar:40},Implements:Options,initialize:function(d,a,c,b){this.idData=a;this.typeData=d;this.pageName=c;this.chaineId=b;this.isVisible=GetCookieWAT("ToolbarVisibility");if($("IE6")){this.placeBarIE6();window.addEvent("scroll",function(){this.placeBarIE6()}.bind(this))}$("Block_Newtoolbar").addEvent("mouseenter",function(f){$("Block_Newtoolbar").setStyle("opacity",1)});$("Block_Newtoolbar").addEvent("mouseleave",function(f){$("Block_Newtoolbar").setStyle("opacity",0.8)});if((this.isVisible=="Hidden"&&!$("Block_Newtoolbar").hasClass("Hidden"))||(this.isVisible=="Visible"&&$("Block_Newtoolbar").hasClass("Hidden"))){this.hide(true)}this.initEvents();if(isLogged()){var e={dataType:d,dataId:a,pageName:c,chaineId:this.chaineId};new Request.HTML({url:"/ajax/bloc?bloc=Block_Newtoolbar&handler=render",method:"post",data:Hash.toQueryString(e),update:$("Block_Newtoolbar"),onSuccess:function(){this.initEvents()}.bind(this)}).send()}},placeBarIE6:function(){var a=document.documentElement.clientHeight-this.options.defaultHeightBar+document.documentElement.scrollTop;$("Block_Newtoolbar").setStyle("top",a)},initEvents:function(){if($("showHistory")){$("showHistory").addEvent("click",function(a){a.stop();this.showHistory()}.bind(this))}if($("showOpe")){if(this.pubCookie()&&$("showOpe").hasClass("openTab")){this.showOpe()}$("showOpe").addEvent("click",function(a){a.stop();this.showOpe()}.bind(this))}$$(".closeToolbar").addEvent("click",function(a){a.stop();this.hide(false)}.bind(this))},pubCookie:function(){var a=(GetCookieWAT("WatpubSony")!=""?GetCookieWAT("WatpubSony"):0);if(a>=1){return false}else{a=a.toInt()+1;setCookieWAT("WatpubSony",a);return true}},hide:function(a){var b=new Fx.Morph("Toolbar",{duration:500,transition:Fx.Transitions.Sine.easeOut});b.start({bottom:[0,"-30"]}).chain(function(){$("Block_Newtoolbar").toggleClass("Hidden");b.start({bottom:["-30",0]});if(!a){setCookieWAT("ToolbarVisibility",$("Block_Newtoolbar").hasClass("Hidden")?"Hidden":"Visible")}})},showHistory:function(){this.doTabRequest("historyTab",{bloc:"Block_Newtoolbar",action:"getUserHistory",dataType:"entry"},function(){this.success(arguments[2]);left=$("showHistory").getCoordinates().left;left+=$("showHistory").getCoordinates().width;width=$("historyTab").getCoordinates().width;$("historyTab").setStyle("left",left-width-10)}.bind(this))},showOpe:function(){this.doTabRequest("opeTab",{bloc:"Block_Newtoolbar",action:"getOpe"},function(){this.success(arguments[2]);analyseTitle("opeTab");$("Block_Newtoolbar").setStyle("opacity",1);$("opeTab").setStyle("left","20%")}.bind(this))},doTabRequest:function(b,f,e,g,c){if($(b)&&!c){$(b).toggleClass("visible");return}if(!g){g=function(){}}var a="/ajax/bloc?bloc="+f.bloc+"&handler="+f.handler;var d=new Hash(f);d.erase("bloc");d.erase("handler");new Request.HTML({url:a,method:"post",data:Hash.toQueryString(d),onSuccess:e,onRequest:g}).send()},closeTabs:function(){$$("#Toolbar .visible").removeClass("visible")},success:function(b,a){$$("#Toolbar .visible").removeClass("visible");var d=new Element("div",{html:b});d.inject($("Block_Newtoolbar"),"bottom");if(a){d.hide()}var c=d.getElement(".block_content");if(c){c.setStyle("max-height",$(window).getCoordinates().height-120)}else{var c=d.getElement(".content");if(c){c.setStyle("max-height",$(window).getCoordinates().height-120)}}$$(".closeTabs").addEvent("click",function(f){f.stop();this.closeTabs()}.bind(this));return d}});

