/*
seriesplus.js
© 2011 seriesplus.com
*/


/* ### MACROMEDIA ROLLOVERS - start ### */

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_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; 
	}
}

/* ### MACROMEDIA ROLLOVERS - end ### */



/* ### STRING MANIPULATION - start ### */

// Removes white space - leading and trailing
function trim(toTrim) {
	return toTrim.replace(/^\s+/g,'').replace(/\s+$/g,'');
}

// Removes unwanted chars - see allowedCharacters
function alphaNumericalOnly(inputStr, replaceOthersWith) {
	var allowedCharacters = "abcdefghijklmnopqrstuvwxyz0123456789";
	var outputWithOnlyAllowedChars = "";
	var output = inputStr.toLowerCase();
	for (var i=0; i<output.length; i++) {
		if (allowedCharacters.indexOf(output.charAt(i)) != -1) {
			outputWithOnlyAllowedChars += output.charAt(i);
		} else {
			outputWithOnlyAllowedChars += replaceOthersWith;
		}
	}
	return outputWithOnlyAllowedChars;
}

// Removes unwanted chars - see allowedCharacters
function numericalOnly(inputStr, replaceOthersWith) {
	var allowedCharacters = "0123456789";
	var outputWithOnlyAllowedChars = "";
	var output = inputStr.toLowerCase();
	for (var i=0; i<output.length; i++) {
		if (allowedCharacters.indexOf(output.charAt(i)) != -1) {
			outputWithOnlyAllowedChars += output.charAt(i);
		} else {
			outputWithOnlyAllowedChars += replaceOthersWith;
		}
	}
	return outputWithOnlyAllowedChars;
}

/* ### STRING MANIPULATION - end ### */


// 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 - start ### */

function endsWith(str, endStr) {
	var originalStringWithEndStrInserted = str.substring(0, str.length - endStr.length) + endStr;
	if (str == originalStringWithEndStrInserted) {
		return true;
	} else {
		return false;
	}
}

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 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").html(errorMsg);
		$("#errorContainer").addClass("block");
		return false;
	} else {
		return true;
	}
}

/* ### FORM VALIDATION - end ### */



/* ### CLICK THROUGH COUNTER FOR CONTESTS - start ### */

function clickThroughDraw(drawId, imageId, statZone) {
	var ieRant = Math.floor(Math.random()*1000001);
	$.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);
			}
		}
	});
}

/* ### CLICK THROUGH COUNTER FOR CONTESTS - end ### */



/* ### AD OPS - start ### */

var BASE_AD_TAG = "http://ad.doubleclick.net/adj/sri.";
var SUBDOMAINS_TO_IGNORE = "preprod, wc1, wc2, noc, dev, www, concours";
var pageTile=0;
var ord = "ord=" + Math.round(Math.random()*100000000000) + "?";

function printAdTag(adSize, position) {

	// Init vars
	// var pageURL = self.location.href; Is this for iframes?
	var pageUrl = document.location + "";
	var zonename = "";
	var keyvaluepair1 = "";
	var keyvaluepair2 = "";

	// Increment tiles
	pageTile++;

	// Dcopt for use with tile 1
	var dcopt = "";
	if (pageTile == 1) {
		dcopt = "dcopt=ist;";
	}

	// Adjust position for usage (valid values : top, bottom / Defaults to top)
	if (position == null) {
		var position = "top";
	}
	var pos = "pos=" + position + ";";

	// Valid sizes : 728x90, 300x250, 160x600
	if (adSize == undefined || adSize == '') return 0;

	// Remove http://subdomain.
	var pageUrlTransit = pageUrl.substring(pageUrl.indexOf(".")+1);

	// Split url on /
	var urlSplitArray = pageUrlTransit.split("/");

	// Add site to base ad tag
	var baseAdTagWithSite = BASE_AD_TAG + urlSplitArray[0].substring(0, (urlSplitArray[0].length-4)) + "/";

	// Add subdomain to array if it's not blacklisted
	var subdomain = (document.domain + "").substring(0, (document.domain + "").indexOf("."));
	if (SUBDOMAINS_TO_IGNORE.indexOf(subdomain) == -1) {
		urlSplitArray.splice(1, 0, subdomain);
	}

	// Build zonename
	if (urlSplitArray.length >= 2) {
		if (urlSplitArray[1] != "") {
			zonename = alphaNumericalOnly(urlSplitArray[1], "").toLowerCase();
		} else {
			// This is homepage
			zonename = "homepage";
		}
	}

	// Build keyvaluepair1
	if (urlSplitArray.length >= 3) {
		if (urlSplitArray[2] != "") {
			keyvaluepair1 = "ss=" + alphaNumericalOnly(urlSplitArray[2], "").toLowerCase() + ";";
		} else if (zonename != "homepage" && zonename != "") {
			// This is a section's homepage
			keyvaluepair1 = "ss=sectionhome;";
		}
	}

	// Build keyvaluepair2
	if (urlSplitArray.length >= 4) {
		if (urlSplitArray[3] != "") {
			// Don't use value #3, use all the remaining url
			var restOfUrl = pageUrlTransit.substring(pageUrlTransit.indexOf(urlSplitArray[3]));
			keyvaluepair2 = "title=" + numericalOnly(restOfUrl, "").toLowerCase() + ";";
		}
	}

	// Build ad tag src
	var adTagSrc = baseAdTagWithSite + zonename + ";" + keyvaluepair1 + keyvaluepair2 + dcopt + pos + "tile=" + pageTile + ";sz=" + adSize + ";" + ord;

	// Build ad tag to print
	var adTag = "<sc"+"ript type='text/jav"+"ascript' src='" + adTagSrc + "'></scr"+"ipt>";

	// Finally, print it
	document.write(adTag.toLowerCase())

}

/* ### AD OPS - end ### */


function displayWallpaper(startDateString, endDateString, src, color, repeat, position, attachment) {
		var startDate=new Date(startDateString);
		var endDate=new Date(endDateString);
		var today = new Date();
		
		if ( (startDate < today) && (today < endDate) ) {
			$('body, html').css('background-image', 'url(' + src + ')');  
			$('body, html').css('background-color', color);  
			$('body, html').css('background-repeat', repeat);  
			$('body, html').css('background-position', position);  
			$('body, html').css('background-attachment', attachment);  
		}
		
}
