﻿if (!window.HN) HN = window.HN = {};
HN.MS = {};
HN.MS.MPEL = {};
// Constants
HN.MS.MPEL.base_url = "/10_ans_msn/";
HN.MS.MPEL.base_rsc_url = "ressources/";
HN.MS.MPEL.INDEX_NAME = "";
HN.MS.MPEL.challenge_list = ["mode", "sport", "musique", "tv", "jv", "spectacle", "extreme", "environnement", "sciences", "hightech"];

// Global Vars
HN.MS.MPEL.xml = {
	parts: { file: null, data: null },
	profile: { file: null, data: null },
	rss: { file: null, data: null }
};
HN.MS.MPEL.select_challenge_interval = null;
HN.MS.MPEL.player_check_loaded_interval = null;

var cm = new HN.CookieManager();

// flv player
var player = null;
function playerReady(obj) { player = window.document[obj.id]; }

function FlashCall () {
	var expirationDate = new Date();
	expirationDate.setTime(expirationDate.getTime()+365*24*60*60*1000);
	cm.write("dragonChallengeDone", "1", expirationDate);
}

// Execute the Init function when DOM is ready
$(function(){ HN.MS.MPEL.Init(); });

HN.MS.MPEL.Init = function () {

	// Preload some images
	var img2preloadList = [
	];
	for (var i=0; i<img2preloadList.length; i++) {
		var img2preload = new Image();
		img2preload.src = HN.MS.MPEL.base_url+HN.MS.MPEL.base_rsc_url+"images/"+img2preloadList[i];
	}

	var $home = $("div.home");
	if ($home.length > 0) {
		var api = $("div.scrollable").scrollable({
			size: 1,
			speed: 500,
			interval: 5000,
			next: "div.cover div.scroll-r",
			prev: "div.cover div.scroll-l",
			onSeek: function(){
				if (this.getIndex() == 0) this.seekTo(10,0);
				else if (this.getIndex() == 11) this.seekTo(1,0);
				$("div.home a.btn-take-the-challenge").attr("href", this.getItems().get(this.getIndex()).href)
			},
			api: true
		});
		$("div.home a.btn-take-the-challenge").attr("href", "defi-mode.aspx");
		api.seekTo(1,0);
		//var s="";for(var k in api)s+=k+"="+api[k]+"\n";alert(s);
		$home.find("a.btn-take-the-challenge").click(function(){ (new Image()).src="http://g.msn.fr/FR1003/1721"; });
		$home.find("div.cover div.scroll-r").mousedown(function(){ api.getConf().interval = 0; (new Image()).src="http://g.msn.fr/FR1003/1720"; });
		$home.find("div.cover div.scroll-l").mousedown(function(){ api.getConf().interval = 0; (new Image()).src="http://g.msn.fr/FR1003/1719"; });
	}
	
	var $select_challenge = $("div.select-challenge-direct-access");
	if ($select_challenge.length > 0) {
		$select_challenge.hover(
			function(){ clearTimeout(HN.MS.MPEL.select_challenge_interval); $select_challenge.find("ul.menu").slideDown(200);},
			function(){ HN.MS.MPEL.select_challenge_interval = setTimeout(function(){ $select_challenge.find("ul.menu").slideUp(200); }, 200); }
		);
	}
	
	var $take_challenge = $("div.challenge a.btn-take-the-challenge");
	if ($take_challenge.length > 0) {
		$take_challenge.click(function(){ $("div.challenge-upload").slideDown(); return false; });
		$("div.challenge-upload a.close").click(function(){ $("div.challenge-upload").slideUp(); return false; });
		if (HN.MS.MPEL.missionPopup) $take_challenge.click();
		$("div.challenge-1, div.challenge-4, div.challenge-5, div.challenge-7, div.challenge-9").find("div.challenge-upload div.note-dft:eq(0)").html("Votre photo doit être au format JPG et ne doit pas dépasser 5 Mo.");
		$("div.challenge-2, div.challenge-3, div.challenge-6, div.challenge-8").find("div.challenge-upload div.note-dft:eq(0)").html("La taille de votre vidéo ne doit pas dépasser 50 Mo.");
		$challenge_upload = $("div.challenge-upload");
		$challenge_upload.find("div.input-file input").change(function(){
			var val = this.value;
			if (HN.browser.msie && HN.browser.version >= 8) val = val.replace(/C\:\\fakepath\\/, "");
			$challenge_upload.find("div.input-file div.input-value").html(val);
			$challenge_upload.find("div.error").hide();
			$challenge_upload.find("input.btn-send").click(function(){
				$challenge_upload.find("div.note-dft:eq(0)").html("Envoi en cours, cela peut durer plusieurs minutes, ne fermez pas cette page !");
				$challenge_upload.find("div.input-file, input.btn-send").hide();
				$challenge_upload.find("div.loading-mask1").show();
				var offset = -380;
				setInterval(function(){
					if (offset > 400) offset = -380;
					else offset += 2;
					$challenge_upload.find("div.loading-progress").css("left", offset+"px");
				}, 13);
			});
		});
	}

	var $sport = $("div.challenge-2");
	if ($sport.length > 0) {
		HN.MS.MPEL.xml["rss"].file = "HookHandler.ashx?rss=1";
		HN.MS.MPEL.GetXMLData("rss", function(xml){
			$sport.find("div.rss div.content").empty();
			$(xml).find("item").each(function(){
				$sport.find("div.rss div.content").append("<a href=\""+$(this).find("link").text()+"\">"+$(this).find("title").text()+"</a><br/>");
			});
		});
		$sport.find("div.rss div.content").jScrollPane({showArrows:true, scrollbarWidth: 14, arrowSize: 12, dragMinHeight: 14, dragMaxHeight: 14});
	}

	var $hightech = $("div.challenge-10");
	if ($hightech.length > 0) {
		var nickName = $("div.pan-right div.profile a.name").html();
		if (!nickName) nickName = "";
		$hightech.find("div.tab").append("\
			<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0\" width=\"482\" height=\"412\" id=\"dragon_MSN\" align=\"middle\">\
				<param name=\"allowScriptAccess\" value=\"Always\" />\
				<param name=\"allowFullScreen\" value=\"false\" />\
				<param name=\"movie\" value=\"http://85.118.62.134/DRAGONMSN/dragon_MSN.swf\" />\
				<param name=\"quality\" value=\"high\" />\
				<param name=\"bgcolor\" value=\"#ffffff\" />\
				<param name=\"flashvars\" value=\"Pseudo="+nickName+"\" />\
				<param name=\"wmode\" value=\"transparent\" />\
				<embed src=\"http://85.118.62.134/DRAGONMSN/dragon_MSN.swf\" quality=\"high\" bgcolor=\"#ffffff\" width=\"482\" height=\"412\" name=\"dragon_MSN\" align=\"middle\" allowScriptAccess=\"Always\" allowFullScreen=\"false\" wmode=\"transparent\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" flashvars=\"Pseudo="+nickName+"\" />\
			</object>");
	}
	
	var $profil = $("div.profil");
	if ($profil.length > 0) {
		HN.MS.MPEL.xml["profile"].file = HN.MS.MPEL.xmlProfile;
		HN.MS.MPEL.GetXMLData("profile", function(xml){
			var $parts = $(xml).find("parts");
			$profil.find("div.challenge-block").each(function(index){
				var $part = $parts.find("part[mission='"+(index+1)+"']");
				if ($part.length > 0) {
					if ($part.attr("completed") == "1") {
						$(this).find("div.state").addClass("state-done")
							.html("Vous avez participé à ce Défi<br/><a href=\"participations-defi-"+HN.MS.MPEL.challenge_list[index]+".aspx?pid="+$part.attr("id")+"\">Cliquez ici pour voir votre participation !</a>");
					}
					else {
						$(this).find("div.state").addClass("state-done")
							.html("<a href=\"defi-"+HN.MS.MPEL.challenge_list[index]+".aspx\">Votre participation à ce défi est en cours de validation</a>");
					}
				}
				else {
					var challenge_done = false;
					if (index == 9) {
						var dragonChallengeDone = cm.read("dragonChallengeDone");
						if (dragonChallengeDone && dragonChallengeDone == "1") {
							$(this).find("div.state").addClass("state-done")
								.html("Vous avez participé à ce Défi<br/><a href=\"defi-"+HN.MS.MPEL.challenge_list[index]+".aspx\">Cliquez ici pour voir votre participation !</a>");
							$profil.find("div.challenge-count").html(parseInt($profil.find("div.challenge-count").html())+1);
							challenge_done = true;
						}
					}
					if (!challenge_done) {
						$(this).find("div.state").addClass("state-todo")
							.html("Vous n’avez pas encore participé à ce Défi<br/><a href=\"defi-"+HN.MS.MPEL.challenge_list[index]+".aspx\">Cliquez ici pour participer !</a>");
					}
				}
			});
		});
		$profil.find("div.challenge-list-mask").scrollable({
			size: 1,
			speed: 500,
			items: "div.challenge-list-content",
			naviItem: "div.challenge-list-page",
			next: "div.challenge-next",
			prev: "div.challenge-previous"
		});
	}

	var $ilslontfait = $("div.ilslontfait");
	if ($ilslontfait.length > 0) {
		HN.MS.MPEL.xml["parts"].file = HN.MS.MPEL.xmlParts;
		//HN.MS.MPEL.xml["parts"].file = "ressources/xml/parts_mode.xml";

		var $detail_block = $ilslontfait.find("div.item-detail-block");
		$detail_block.find("div.close span").click(function(){
			$ilslontfait.find("div.item-list-mask").fadeIn(500);
			$ilslontfait.find("div.page-next, div.page-previous").slideDown(500);
		});

		HN.MS.MPEL.GetXMLData("parts", function(xml){
			var $parts = $(xml).find("parts");
			var type = $parts.attr("type");
			var vm = new HN.MS.MPEL.VoteManager($detail_block.find("div.note").get(0), $detail_block.find("div.note-msg").get(0), type);
			if (type == "1") {
				$detail_block.find("div.item").html("<div id=\"player-flv\"><a href=\"http://www.adobe.com/go/getflashplayer\">Get flash</a> to see this player</div>");
				 swfobject.embedSWF("ressources/player/player.swf", "player-flv", "393", "261", "9.0.115", false, {autostart:"true",controlbar:"over",abouttext:"Hook Network",aboutlink:"http://www.hook-network.com/"}, {allowfullscreen:"true",allowscriptaccess:"always",wmode:"transparent"}, {id:"player1",name:"player1"});
				$detail_block.find("div.close span").click(function(){ $detail_block.fadeOut(500, function(){ player.sendEvent('STOP'); }); });
			} else if (type == "2") {
				$detail_block.find("div.close span").click(function(){ $detail_block.fadeOut(500); });
			}
			$parts = $parts.find("part");
			if ($parts.length > 0) {
				var item_list_content = $ilslontfait.find("div.item-list-content").empty().get(0);
				var partIndex = 0;
				var item_list_page;
				var items = [];
				
				var item_thumb_star = document.createElement("img");
				item_thumb_star.src = "ressources/images/item-star.png";
				item_thumb_star.alt = "";
				$parts.each(function(index){
					/*<div class="item-list-page">
						<div class="item-thumb-block">
							<div class="item-thumb"><img src="ressources/images/item-thumb-sample-1.png" alt=""/></div>
							<div class="name">pseudo</div>
							<div class="note"><img src="ressources/images/item-star.png" alt=""/></div>
						</div> --> * 6
					</div>*/
					if (partIndex % 6 == 0) {
						item_list_page = document.createElement("div");
						item_list_page.className = "item-list-page";
					}

					var $part = $(this);
					var item_thumb_block = document.createElement("div");
					//item_thumb_block.id = $part.attr("id");
					item_thumb_block.className = "item-thumb-block";
					item_thumb_block.onclick = function(){
						$ilslontfait.find("div.item-list-mask").fadeOut(500);
						$ilslontfait.find("div.page-next, div.page-previous").slideUp(500);
						$detail_block.fadeIn(500);
						$detail_block.find("div.name").html($part.attr("nick"));
						if (type == "1") {
							HN.MS.MPEL.player_check_loaded_interval = setInterval(function(){
								if (player && typeof player.sendEvent == "function") {
									clearInterval(HN.MS.MPEL.player_check_loaded_interval);
									player.sendEvent('STOP');
									player.sendEvent('LOAD', (/\:/.test($part.attr("resource"))?"":"http://www.messengerpartenlive.com/Images/Data/")+$part.attr("resource"));
								}
							},100);
						} else if (type == "2") {
							$detail_block.find("div.item").html("<img src=\"Images/Data/"+$part.attr("resource")+"\" alt=\"\"/>");
						}

						vm.setPart($part.attr("id"), $part.attr("note"));
					};
						var item_thumb = document.createElement("div");
						item_thumb.className = "item-thumb";
						item_thumb_block.appendChild(item_thumb);
							var img_thumb = document.createElement("img");
							img_thumb.src = "Images/Data/"+$part.attr("thumb");
							img_thumb.alt = $part.attr("thumb");
							item_thumb.appendChild(img_thumb);
						var name = document.createElement("div");
						name.className = "name";
						name.innerHTML = $part.attr("nick");
						item_thumb_block.appendChild(name);
						var note_thumb = document.createElement("div");
						note_thumb.className = "note";
						item_thumb_block.appendChild(note_thumb);
						var note = Math.round(parseFloat($part.attr("note")));
						for (var i=1; i <= note; i++)
							note_thumb.appendChild(item_thumb_star.cloneNode(false));

					item_list_page.appendChild(item_thumb_block);
					items[index] = item_thumb_block;
					
					if (partIndex % 6 == 5)
						item_list_content.appendChild(item_list_page);

					partIndex++;
				});
				if (partIndex % 6 != 0)
					item_list_content.appendChild(item_list_page);

				var item_list = $("div.ilslontfait div.item-list-mask").scrollable({
					size: 1,
					speed: 500,
					items: "div.item-list-content",
					naviItem: "div.item-list-page",
					next: "div.ilslontfait div.page-next",
					prev: "div.ilslontfait div.page-previous",
					api: true
				});
				if (HN.MS.MPEL.pidParts) {
					var index = $parts.index($(xml).find("part[id='"+HN.MS.MPEL.pidParts+"']"));
					var page = (index-index%6) / 6;
					item_list.setPage(page, 200, function(){
						items[index].onclick();
					});
				}
			}
		});
	}

	// Preload rollover images
	/*HN.MS.MPEL.GetXMLData("products", function (xml) {
		if (typeof xml != "string") {
			var $products = $(xml).find("product");
			if ($products.length > 0) {
				$products.each(function(){
					var img2preload = new Image();
					var brand_model = ($part.attr("brand")+" "+$(this).attr("model")).replace(/\s/g,"-").replace(/\//g,"");
					img2preload.src = HN.MS.MPEL.base_url+HN.MS.MPEL.base_rsc_url+"images/pc/medium/"+brand_model+".png";
				});
			}
		}
	});*/

	// Credits
	$("div.footer a:eq(3)").click(function(){ $("div.credits").fadeIn(300); return false; })
	$("div.credits-close").click(function(){ $("div.credits").fadeOut(300); })

	// History popup
	$("a.btn-msn-discover-history").click(function(){ $("div.history-popup").fadeIn(300); return false; })
	$("div.history-popup-close").click(function(){ $("div.history-popup").fadeOut(300); })
	
	var urlInfos = new HN.URLinfos();
	HN.png2alpha("png2keep");
	if (!HN.browser.msie || HN.browser.version >= 7) {
		HN.MS.MPEL.CreateShadow($("div.profile-not-logged a"),1,1);
		HN.MS.MPEL.CreateShadow($("div.challenge-list-content .has-shadow"),1,1);
		HN.MS.MPEL.CreateShadow($("div.tab .has-shadow"),1,1);
		HN.MS.MPEL.CreateShadow($("div.register .has-shadow"),1,1);
	}
}

HN.MS.MPEL.VoteManager = function(_note_node, _note_msg_node, _type){
	var self = this;
	var type = _type;
	var type_text = type == "1" ? "vidéo" : "image";
	var note_node = _note_node;
	var note_msg_node = _note_msg_node;
	var part = { id: null, note: null, voted: false };
	var cur_note;
	var stars = [];
	
	var lpvotes = "-"+cm.read("lpvotes");
	if (lpvotes.lastIndexOf("-") != lpvotes.length-1)
		lpvotes = lpvotes + "-";

	for (var i=0; i<5; i++) {
		stars[i] = document.createElement("img");
		stars[i].src = "ressources/images/item-star-empty.gif";
		stars[i].alt = "";
		stars[i].onmouseover = function(){
			if (!part.voted) {
				cur = 0;
				while (this != stars[cur] && cur<5) cur++;
				for (var j=0; j<=cur; j++) stars[j].src = "ressources/images/item-star-filled.gif";
				for (var j=cur+1; j<5; j++) stars[j].src = "ressources/images/item-star-empty.gif";
				cur_note = cur+1;
			}
		};
		stars[i].onclick = function(){
			if (!part.voted) {
				$.webservice({
					url: "Vote.asmx",
					data: {id: part.id, note: cur_note},
					dataType: "text",
					nameSpace: "Hook.Microsoft.TenYearsMsgr",
					methodName: "AddVote",
					success:function(data,textStatus){
						part.note  = cur_note;
						part.voted = true;
						lpvotes += part.id+"-";
						self.refreshNote();
						note_node.style.display = "none";
						note_msg_node.innerHTML = "Vote enregistré !";
					}
				});
			}
			else {
				note_node.style.display = "none";
				note_msg_node.innerHTML = "Vous avez déjà voté pour cette "+type_text;
			}
		};
		note_node.appendChild(stars[i]);
	};
	
	this.getPart = function(){ return $part; };
	this.setPart = function(_id, _note){
		part.id = _id;
		part.note = Math.round(parseFloat(_note));
		if (lpvotes.indexOf("-"+part.id+"-") != -1){
			part.voted = true;
			note_node.style.display = "none";
			note_msg_node.innerHTML = "Vous avez déjà voté pour cette "+type_text;
		}
		else {
			part.voted = false;
			note_node.style.display = "block";
			note_msg_node.innerHTML = "";
		}
		this.refreshNote();
	};
	this.refreshNote = function(){
		for (var i=0; i<part.note; i++) stars[i].src = "ressources/images/item-star-filled.gif";
		for (var i=part.note; i<5; i++) stars[i].src = "ressources/images/item-star-empty.gif";
	};
	$(note_node).mouseleave(function(){ self.refreshNote();	});
};

HN.MS.MPEL.CreateShadow = function($nodes, ol, ot){
	$nodes.each(function(){
		var shadowNode = this.cloneNode(true);
		var position = $(this).position();
		shadowNode.className += (shadowNode.className!=""?" ":"") + "shadow";
		$(shadowNode).css({
			"background-image": "none",
			"position": "absolute",
			"left": (Math.floor(position.left)+ol)+"px",
			"top": (Math.floor(position.top)+ot)+"px"
		});
		if ($(this).css("position") == "static") this.style.position = "relative";
		this.parentNode.insertBefore(shadowNode, this);
	});
}

// UseFull Global Functions
HN.MS.MPEL.GetXMLData = function (xml_file, callback_function) {
	if (!HN.MS.MPEL.xml[xml_file]) {
		callback_function("XML doesn't exists");
		return false;
	}

	if (HN.MS.MPEL.xml[xml_file].data) {
		callback_function(HN.MS.MPEL.xml[xml_file].data);
	}
	else {
		$.ajax({
			async: false,
			data: "",
			dataType: "xml",
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				callback_function("Bad XML URL or XML is Malformed");
			},
			success: function (xml, textStatus) {
				HN.MS.MPEL.xml[xml_file].data = xml;
				callback_function(HN.MS.MPEL.xml[xml_file].data);
			},
			type: "GET",
			url: HN.MS.MPEL.xml[xml_file].file
		});
	}
	return true;
};

