/*
 * seriesplus.js
 * © 2008 seriesplus.com
 */

// Banner adds
var si_site_name = 'sri.seriesplus';
var si_ord = Math.round(Math.random()*100000000000);
function SIWriteAdvert(si_zone, si_tile_id, si_size) {
  try {
    var dcopt_val = '';
    if (si_tile_id == 1) {
      dcopt_val='dcopt=ist;'
    } else if (si_tile_id == 2) {
			dcopt_val='pos=top;'
    } else if (si_tile_id == 3) {
			dcopt_val='pos=bottom;'
		}
    document.write("<sc"+"ript type=\"text/jav"+"ascript\" src=\"http://ad.double"+"click.net/adj/"+si_site_name+"/"+si_zone+";"+dcopt_val+"tile="+si_tile_id+";sz="+si_size+";ord="+si_ord+"?\"></scr"+"ipt>");
  } catch (e) { 
    // alert('error');
    return; 
  }
}
 
// Fireworks rollovers
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
   var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
   if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}


// Layers
function MM_showHideLayers() { // v3.0
	var i, p, v, obj, args = MM_showHideLayers.arguments;
	for (i = 0; i<(args.length - 2); i += 3) if ((obj=MM_findObj(args[i]))!=null) { 
		v = args[i+2];
		if (obj.style) { 
			obj = obj.style; 
			v = (v == 'show') ? 'visible' : (v='hide') ? 'hidden' : v; 
		}
	obj.visibility = v; 
	}
}


// Print section
function printSpecial() {
	if (document.getElementById != null) {
		var html = '<HTML>\n<HEAD>\n';
		if (document.getElementsByTagName != null) {
			var headTags = document.getElementsByTagName("head");
			if (headTags.length > 0) {
				html += headTags[0].innerHTML;
			}
		}
		html += '\n</HE>\n<BODY>\n';
		var printReadyElem = document.getElementById("printReady");
		if (printReadyElem != null) {
			html += printReadyElem.innerHTML;
		} else {
			// alert("Fonction printReady introuvable.");
			return;
		}
		html += '\n</BO>\n</HT>';
		var printWin = window.open("","printSpecial");
		printWin.document.open();
		printWin.document.write(html);
		printWin.document.close();
		if (gAutoPrint) {
			printWin.print();
		}
	} else {
		// alert("Votre fureteur ne supporte pas cette fonction. Veuillez le mettre à jour.");
	}
}

function printWindow(){
   bV = parseInt(navigator.appVersion)
   if (bV >= 4) window.print()
}


// Random
function getRandom(maxValue) {
	var randomNumber = Math.floor(Math.random()*(maxValue+1));
	if ((randomNumber > maxValue) || (randomNumber == 0)) {
		return getRandom((maxValue));
	} else {
		return randomNumber;
	}
}


// Form validation
function checkIfNumeric(input) {
	var isNumeric = false;
	var NUMERIC = "0123456789";
	input = input.toUpperCase();
	for(var i=0; i<input.length; i++) {
		var CHAR = input.charAt(i);
		if((NUMERIC.indexOf(CHAR) >= 0) && !isNumeric) {
			isNumeric = true;
		}
	}
	return isNumeric;
}

function getCheckRadioValue(radios) {
	var checkedValue = -1;
	for (i=0; i<radios.length; i++) {
		if (radios[i].checked) {
			checkedValue = radios[i].value;
		}
	}
	return checkedValue;
}

function checkIfValidUploadFile(file) {
	var isValid = true;
	var indexExe = file.indexOf('.exe');
	var indexJs = file.indexOf('.js');
	if ((indexExe > -1) || (indexJs > -1)) {
		isValid = false;
	}
	return isValid;
}

function checkIfValidImageFile(file) {
	var isValid = true;
	var indexJpeg = file.toLowerCase().lastIndexOf('.jpeg');
	var indexJpg = file.toLowerCase().lastIndexOf('.jpg');
	var indexGif = file.toLowerCase().lastIndexOf('.gif');
	if ((indexJpeg == -1) && (indexJpg == -1) && (indexGif == -1)) {
		isValid = false;
	}
	return isValid;
}

function checkIfMail(address) {
	var filterRegExp =/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,200})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
	return filterRegExp.test(address)
}

function checkRecr(recrForm) {
	var errorContainer;
	if (document.getElementById) {
		// Level 1 DOM code
		errorContainer = document.getElementById("errorContainer");
	} else if (document.all) {
    	// Microsoft DOM code
		errorContainer = document.all['errorContainer'];
	}
	var errorMsg = "<b>Erreur : </b><br/>";
	for (var i=0; i<recrForm.length; i++) {
		var element = recrForm.elements[i];
		if ((element.type != "hidden") && (element.type != "submit")) {
			// Text
			if (element.type == "text") {
				if ((element.name.indexOf("optionnel") == -1) && (element.value == "")) {
					errorMsg += "Veuillez remplir le champ \"" + element.name + "\".<br/>";
				} else if (element.name == "Courriel") {
					if (!checkIfMail(element.value)) {
						errorMsg += "Votre adresse de courriel ne semble pas valide.<br/>";
					}
				}
			}
			// Textarea
			if (element.type == "textarea") {
				if ((element.name.indexOf("optionnel") == -1) && element.value == "") {
					errorMsg += "Veuillez remplir le champ \"" + element.name + "\".<br/>";
				}
			}
			// Radio
			if (element.type == "radio") {
				if (element.name.indexOf("optionnel") == -1) {
					if (getCheckRadioValue(recrForm.elements[element.name]) == -1) {
						if (errorMsg.indexOf(element.name) == -1) {
							errorMsg += "Veuillez faire votre choix pour \"" + element.name + "\".<br/>";
						}
					}
				}
			}
			// Checkbox
			/* (release - voir www.canalvie.com/emission/monenfant_monheros/recrutement2.jsp) */
			if (element.type == "checkbox" && element.name == "Release" && element.checked == false) {
				errorMsg += "\nVeuillez cocher la case \"" + element.value + "\".\nEn soumettant votre témoignage, vous devez accepter que \nLes Chaînes Télé Astral puissent publier votre texte, \nune partie de celui-ci ou encore toute photo \nque vous aurez jointe à votre témoignage.<br/>";
			} else if (element.type == "checkbox") {
				if (element.name.indexOf("optionnel") == -1) {
					if (element.checked == false) {
						errorMsg += "Veuillez cocher la case \"" + element.name + "\".\n<br/>";
					}
				}
			}
			// File
			if (element.type == "file") {
				if (element.name.indexOf("optionnel") == -1) {
					if (element.value == "") {
						errorMsg += "Veuillez sélectionner un fichier pour le champ \"" + element.name + "\".<br/>";
					} else {
						if (element.name.indexOf("Photo") > -1) {
							if (!checkIfValidImageFile(element.value)) {
								errorMsg += "Les seuls fichiers acceptés sont \".gif\", \".jpg\" ou \".jpeg\".<br/>";
							}
						} else if (!checkIfValidUploadFile(element.value)) {
							errorMsg += "Les seuls fichiers acceptés sont \".gif\", \".jpg\" ou \".jpeg\".<br/>";
						}
					}
				}
			}
		}
	}
	if (errorMsg != "<b>Erreur : </b><br/>") {
		errorContainer.innerHTML = "" + errorMsg + "";
		errorContainer.style.display = "block";
		return false;
	} else {
		return true;
	}
}


// Correctly handle PNG transparency in Win IE 5.5 or higher.
// http://homepage.ntlworld.com/bobosola. Updated 02-March-2004
function correctPNG() {
	for(var i=0; i<document.images.length; i++) {
		var img = document.images[i]
		var imgName = img.src.toUpperCase()
		if (imgName.substring(imgName.length-3, imgName.length) == "PNG") {
			var imgID = (img.id) ? "id='" + img.id + "' " : ""
			var imgClass = (img.className) ? "class='" + img.className + "' " : ""
			var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
			var imgStyle = "display:inline-block;" + img.style.cssText 
			if (img.align == "left") imgStyle = "float:left;" + imgStyle
			if (img.align == "right") imgStyle = "float:right;" + imgStyle
			if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle		
			var strNewHTML = "<span " + imgID + imgClass + imgTitle
			+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
			+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
			+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
			img.outerHTML = strNewHTML
			i = i-1
		}
	}
}
if (document.all) { 
	window.attachEvent("onload", correctPNG);
}


// CheckBoxes
function alterCheckBoxes(idCSVList, state) {
	// Ids must be unique in page.
	var idArray = new Array();
	idArray = idCSVList.split(", ");
	for (i = 0; i < idArray.length; i++) {
		document.getElementsByName(idArray[i])[0].checked = state;
	}
}

// Fonction qui switch le contenu d'un div
function switchDivContent(htmlToInsert, divId){
	if (document.getElementById) {
		obj = document.getElementById(divId);
		obj.innerHTML = htmlToInsert;
	} else if (document.all) {
		obj = document.all[divId]
		obj.innerHTML = htmlToInsert;
	}
}

// Menu déroulant
function jumpBox(list) {location.href =list.options[list.selectedIndex].value}

function jumpBoxBlank(list) {
	url = list.options[list.selectedIndex].value;
	if (url != '') {
		window.open(url);
		}
	}

// Function used to include js files. Script must "end" before included script can be active.
function jsInclude(jsFile) {
	document.write('<' + 'script');
	document.write(' language="JavaScript"');
	document.write(' type="text/javascript"');
	document.write(' src="' + jsFile + '">');
	document.write('</' + 'script' + '>');
}

// On incrémente le compteur de nouvelles
function incNewsCount(newsId) {
	var ieRant = Math.floor(Math.random()*1000001); // Generate random so that this f***ing IE browser does not cache xml response
	$.ajax({
		type: "GET",
		url: "/_dyn/incNewsCount.jsp",
		data: "newsId=" + newsId + "&ieRant=" + ieRant,
		dataType: "xml",
		success: function(xml) {
			// Do nothing
		}
	});
}

// On incrémente le compteur de bannière concours
function clickThroughDraw(drawId, imageId, statZone) {
	var ieRant = Math.floor(Math.random()*1000001); // Generate random so that this f***ing IE browser does not cache xml response
	$.ajax({
		type: "GET",
		url: "/_dyn/incDrawCount.jsp",
		data: "drawId=" + drawId + "&imageId=" + imageId + "&statZone=" + statZone + "&ieRant=" + ieRant,
		dataType: "xml",
		success: function(xml) {
			var opResult = $(xml).find("opResult").text();
			var opMessage = $(xml).find("opMessage").text();
			var linkUrl = $(xml).find("linkUrl").text();
			if (opResult == 'ok') {
				self.location.href = linkUrl;
			} else {
				alert(opMessage);
			}
		}
	});
}

// Submit Research in webtele
function submitFormRechercheWebtele() {
	var typeId = $("#typeId").val();
	var programId = $("#programId").val();
	var episodeId = 0;
	self.location.href = "/webtele/recherche/?type=" + typeId + "&emission=" + programId + "&episode=" + episodeId + "&tri=0";
	return false;
}

// Endswith
function endsWith(str, endStr) {

	// http://preprod.canalvie.com/ decoration/ : 39
	// decoration/ : 11
	var originalStringWithEndStrInserted = str.substring(0, str.length - endStr.length) + endStr;
	
	//alert("str.substring(str.length - endStr.length) + endStr : " + str.substring(0, str.length - endStr.length) + endStr);
	//alert("originalStringWithEndStrInserted : " + originalStringWithEndStrInserted);

	if (str == originalStringWithEndStrInserted) {
		return true;
	} else {
		return false;
	}
}

// Removes white space (leading and trailing)
function trim(toTrim) {
	return toTrim.replace(/^\s+/g,'').replace(/\s+$/g,'');
}