/// <reference path="JsLib.js" />
/// <reference path="TM.js" />

/* SPINNER */
Spinner = {
	Up: function (obj, arg) {
		var label = $(obj.labelId);
		var value = parseInt(label.innerHTML);
		if (value < parseInt(obj.maximumValue)) {
			value += 1;
			label.innerHTML = value;
			__doPostBack(obj.labelId, value + '|' + arg);
		}
	},
	Down: function (obj, arg) {
		var label = $(obj.labelId);
		var value = parseInt(label.innerHTML);
		if (value > parseInt(obj.minimumValue)) {
			value -= 1;
			label.innerHTML = value;
			__doPostBack(obj.labelId, value + '|' + arg);
		}
	}
};

MessageLabel = {
	Inverse: function (objid) {
		var obj_short = $(objid + '_short');
		var obj_long = $(objid + '_long');

		if (obj_short.visible()) {
			obj_short.hide();
			obj_long.show();
		}
		else {
			obj_short.show();
			obj_long.hide();
		}
	}
}

NumericTextBox = {
	Validate: function (obj) {
		var allowBlank = (obj.allowBlank == 'false') ? false : true;
		var rounded = (obj.rounded == 'false') ? false : true;
		var minimumValue = obj.minimumValue;
		var maximumValue = obj.maximumValue;
		var number = obj.value;
		var format = obj.format;
		var negative = false;
		var baseFormat = format.split('.')[0];
		var fixeFormat = format.split('.')[1];
		var baseText = '';
		var fixeText = '';

		number = number.replace(' ', '').replace(',', '.');
		minimumValue = minimumValue.replace(' ', '').replace(',', '.');
		maximumValue = maximumValue.replace(' ', '').replace(',', '.');

		if (number == '' && allowBlank) {
			obj.value = '';
			return;
		}
		else if (isNaN(number)) {
			number = Number(minimumValue);
		}
		else if (minimumValue != '' && Number(number) < Number(minimumValue)) {
			number = Number(minimumValue);
		}
		else if (maximumValue != '' && Number(number) > Number(maximumValue)) {
			number = Number(maximumValue);
		}
		else {
			number = Number(number);
		}

		negative = (number < 0) ? true : false;

		if (!fixeFormat) {
			fixeFormat = '';
		}
		if (negative) {
			number *= -1;
		}

		if (Math.pow(10, baseFormat.length) > number) {
			baseText = (parseInt(number, 10) + Math.pow(10, baseFormat.length) + '').substr(1);
		}
		else {
			baseText = parseInt(number, 10);
		}
		if (fixeFormat.length + 1 > 0) {
			fixeText = number.toFixed(fixeFormat.length).split('.')[1];
			if (!fixeText) {
				fixeText = fixeFormat;
			}
			if (rounded == true) {
				baseText = number.toFixed(fixeFormat.length).split('.')[0];
			}
		}

		if (negative) {
			baseText = '-' + baseText;
		}
		if (fixeText.length > 0) {
			obj.value = baseText + '.' + fixeText;
		}
		else {
			obj.value = baseText;
		}
	}
}

/* CALENDAR */
var Calendar = {
	zIndex: 1000,
	LastIFrame: '',
	timerId: 0,
	Display: function (id, uniqueID, hdnID, iFrameID, langID, postBackScript, calendarUrl, width, height) {
		this.LastIFrame = iFrameID;
		var iframe = $(iFrameID);
		var obj = $(id);
		var iframeUrl = calendarUrl + '?langid=' + langID + '&id=' + id + '&uniqueid=' + uniqueID + '&hdn=' + hdnID + '&iframe=' + iFrameID + '&date=' + $(hdnID).value + '&showOtherMonthDays=' + obj.showOtherMonthDays + '&minimumDate=' + obj.minimumDate + '&maximumDate=' + obj.maximumDate + '&visibleDate=' + obj.visibleDate;
		if (null == iframe) {
			iframe = document.createElement('iframe');
			iframe.id = iFrameID;
			iframe.style.marginLeft = '0px';
			iframe.style.marginTop = '1px';
			iframe.style.zIndex = '99';
			iframe.style.display = 'none';
			iframe.style.width = width + 'px';
			iframe.style.height = height + 'px';
			iframe.frameBorder = 0;
			iframe.scrolling = 'no';
			iframe.border = 0;
			iframe.style.position = 'absolute';
			iframe.src = iframeUrl
			document.body.appendChild(iframe);
		} else {
			var ifrurl = iframe.src;
			if (!(-1 != ifrurl.indexOf(iframeUrl) && ifrurl.indexOf(iframeUrl) + iframeUrl.length == ifrurl.length)) {
				iframe.src = iframeUrl;
			}
		}

		var pos = JsLib.Positioner.GetAbsolutePos($(id));
		var siz = JsLib.Positioner.GetElementSize($(id));
		iframe.style.top = (pos.y + siz.y) + 'px';
		iframe.style.left = (pos.x) + 'px';

		if (iframe.style.display != 'none') {
			$(Calendar.LastIFrame).hide();
			document.body.removeChild($(Calendar.LastIFrame));
			Calendar.LastIFrame = null;
		} else {
			obj.postBackScript = postBackScript;
			obj.langID = langID;
			iframe.style.zIndex = this.zIndex++;
			iframe.style.display = 'block';

			iframe.onmouseout = function () {
				Calendar.timerId = window.setTimeout('$(Calendar.LastIFrame).hide(); document.body.removeChild($(Calendar.LastIFrame)); Calendar.LastIFrame = null;', 500);
			};
			iframe.onmouseover = function () {
				window.clearTimeout(Calendar.timerId);
				Calendar.timerId = 0;
			};
			obj.onmouseout = function () {
				Calendar.timerId = window.setTimeout('$(Calendar.LastIFrame).hide(); document.body.removeChild($(Calendar.LastIFrame)); Calendar.LastIFrame = null;', 500);
			};
			obj.onmouseover = function () {
				window.clearTimeout(Calendar.timerId);
				Calendar.timerId = 0;
			};
		}
	},
	SetDate: function (id, uniqueID, hdnID, iFrameID, ticks) {
		var iframe = $(iFrameID);
		var obj = $(id);

		iframe.style.display = 'none';
		var oldticks = $(hdnID).value;
		$(hdnID).value = ticks;
		if (oldticks != ticks) {
			if (obj.postBackScript != undefined) {
				eval(obj.postBackScript.replace('#arg#', ticks));
			}
		}
		window.setTimeout('$(\'' + hdnID + '\').value=\'' + oldticks + '\'', 10);
	},
	ClearEmptyRow: function (id) {
		var trs = $$('#' + id + ' tr');
		var className = $(id).cssClass;
		trs.each(function (elmt) {
			var tds = elmt.select('td');
			var length = 0;
			tds.each(function (elmt2) {
				if (elmt2.hasClassName(className)) length++;
			});
			if (length == 7) {
				elmt.remove();
			}
		});
	}
};

var ReservItButton = {
	Initialize: function(searchText) {
		TM.GreyBox.Initialize(searchText);
	},
	DisableAllButtons: function (objid) {
		if (typeof (Page_IsValid) == 'undefined' || Page_IsValid) {
			if (objid) {
				var obj = $(objid);
				var loading = $(obj.loadingid);
				var p = obj.positionedOffset();
				var s = obj.getDimensions();

				loading.style.top = p.top + 'px';
				loading.style.left = p.left + 'px';
				loading.style.width = s.width + 'px';
				loading.style.height = s.height + 'px';

				loading.show();
			}

			$$('.webButton').each(function (elmt) { elmt.onclickold = elmt.onclick; elmt.onclick = function () { return false; }; elmt.addClassName('reservit-off'); });
			window.onerror = function () {
				$$('.webButton').each(function (elmt) { elmt.onclick = elmt.onclickold; elmt.removeClassName('reservit-off'); });
			};
		}
	},
	ShowGreyBox: function () {
		if (typeof (Page_IsValid) == 'undefined' || Page_IsValid) {
			TM.GreyBox.Show();

			window.onerror = function () {
				TM.GreyBox.Hide();
			};
		}
	}
};

var Editor = {
	UpdateLinkedField: function (name) {
		var oEditor = FCKeditorAPI.GetInstance(name);
		oEditor.UpdateLinkedField();
	}
};

var PhoneNumberTextBox = {
	ValidatePhoneNumber: function (sender, args) {
		var areaCode = $(sender.controltovalidate + '_1_input');
		var phoneNumber = $(sender.controltovalidate + '_2_input');
		var extension = $(sender.controltovalidate + '_3_input');
		args.IsValid = ((areaCode.value + phoneNumber.value + extension.value).length > 0);
	}
};

/* TWOSTATESHYPERLINK */
var TwoStatesHyperlink = {
	Initialize: function (oid, iid, i1, i2, i3) {
		var o = $(oid);
		o.clicked = false;
		o.imageUrl = i1;
		o.overImageUrl = i2;
		o.image = $(iid);
		o.onmouseover = function () { if (!this.clicked) this.image.src = this.overImageUrl; };
		o.onmouseout = function () { if (!this.clicked) this.image.src = this.imageUrl; };
		o.image.src = o.overImageUrl;
	}
};

/* THREESTATESHYPERLINK */
var ThreeStatesHyperlink = {
	Initialize: function (oid, iid, i1, i2, i3) {
		var o = $(oid);
		o.clicked = false;
		o.imageUrl = i1;
		o.overImageUrl = i2;
		o.clickImageUrl = i3;
		o.image = $(iid);
		o.onmouseover = function () { if (!this.clicked) this.image.src = this.overImageUrl; };
		o.onmouseout = function () { if (!this.clicked) this.image.src = this.imageUrl; };
		o.onclick = function () { this.image.src = this.clicked ? this.overImageUrl : this.clickImageUrl; this.clicked = !this.clicked; };
		o.image.src = o.overImageUrl;
	}
};

/* SLIDESHOWARTICLE */
var SlideShowArticle = {
	flashObj: false,
	SwitchImage: function (obj, src, cid, pid) {
		if (this.flashObj) {
			$(pid).innerHTML = '';
			this.flashObj = false;
		}
		$(pid).style.display = 'none';
		$(cid).style.display = 'block';
		var i = $(cid);
		i.alt = obj.alt;
		i.title = obj.title;
		i.src = src;
	},
	SwitchVideo: function (obj, type, src, cid, pid) {
		if (this.flashObj) {
			$(pid).innerHTML = '';
			this.flashObj = false;
		}
		$(cid).style.display = 'none';
		$(pid).style.display = 'block';
		var so = new SWFObject(src, 'TMVideo', '285', '206', '8', '#766E63');
		so.addParam('allowScriptAccess', 'sameDomain');
		so.addParam('quality', 'high');
		so.addParam('align', 'middle');
		so.addParam('play', 'true');
		so.addParam('loop', 'true');
		so.addParam('scale', 'noscale');
		so.addParam('wmode', 'transparent');
		so.addParam('devicefont', 'false');
		so.addParam('menu', 'true');
		so.addParam('allowFullScreen', 'false');
		so.addParam('allowScriptAccess', 'sameDomain');
		so.addParam('salign', '');
		so.addParam('defer', 'defer');
		$(pid).innerHTML = so.getSWFHTML();
		this.flashObj = true;
	}
};

/* RATING */
var Rating = {
	Initialize: function (objid) { },
	Switch: function (objid, imageUrlOn, imageUrlOff, index) {
		var imgs = $(objid).getElementsByTagName('img');
		for (var i = 0; i < imgs.length; i++)
			imgs[i].src = imageUrlOff;
		for (var i = 0; i < index + 1; i++)
			imgs[i].src = imageUrlOn;
		return false;
	},
	Select: function (value) {
		TM.GoogleAnalytics.trackEvent('rating', 'rate this article', TM.GoogleAnalytics.getDirectLinkValue(), value);
	}
};

var WaterMark = {
	Initialize: function (obj) {
		obj.defaultcolor = obj.style.color;
		obj.onblur = function () {
			if (this.value.length == 0) {
				this.value = this.text;
				this.style.color = this.textcolor;
			}
		};
		obj.onfocus = function () {
			if (this.value == this.text) {
				this.value = '';
				this.style.color = this.defaultcolor;
			}
		};
	}
};

var GoogleSearchTextBox = {
	Search: function (obj, url) {
		window.location.href = url + '/' + escape(obj.value.replace(/^\s*/, "").replace(/\s*$/, ""));
	}
};

var CustomTextBox = {
	Initialize: function (obj) {
		obj.onfocus = null;
		obj.onblur = function () {
			return CustomTextBox.Validate(this);
		};
		obj.onkeypress = function (e) {
			return CustomTextBox.KeyPressed(this, e);
		};
	},
	Validate: function (obj) {
		if ((obj.type == "text" || obj.type == "password" || obj.type == "textarea") && obj.value != "") {
			var rx = new RegExp("[^<>]+");
			var matches = rx.exec(obj.value);
			if (matches != obj.value) {
				obj.value = obj.value.replace("<", "").replace(">", "");
				EnableAlert(true);
				alert((currentLanguageId == 1 ? "Les caract\350res < et > sont interdits.\nIls ont \351t\351 supprim\351s de votre saisie." :
											"The < and > characters are forbidden.\nThey have been deleted from your entry."))
				obj.focus();
				return false;
			}
		}
		return true;
	},
	KeyPressed: function (obj, e) {
		if (!e) var e = window.event;
		if (obj.isclickable == 'true' && e.keyCode == 13) {
			this.Validate(obj);
			eval(obj.clientscript);
			return false;
		}
	}
};

/* CURRENCYDROPDOWN */
var CurrencyDropDown = {
	Select: function (clientid, text, value, autopostback, f) {
		if (autopostback) {
			f(value);
		}
	}
};

/* CUSTOMDROPDOWN */
var CustomDropDown = {
	Initialize: function (clientId) {
		var cdd = $(clientId);
		cdd.timerId = -1;
	},
	togglevisibility: function (controlid, callback) {
		var c = $(controlid);
		if (c.style.display == "block")
			c.style.display = "none";
		else
			c.style.display = "block";
		if (callback != '')
			eval(callback);
	},
	dropdownselectitem: function (o, control_with_text, list_to_hide_after, selected_value, selected_value_hidden_id, callback) {
		($(control_with_text)).innerHTML = o.innerHTML;
		if (null != selected_value_hidden_id)
			($(selected_value_hidden_id)).value = selected_value;
		CustomDropDown.togglevisibility(list_to_hide_after);
		if (callback != '')
			eval(callback);
	},
	hide: function (controlid, listId, timeout, callback) {
		var control = $(controlid);
		var list = $(listId);
		if (control != null && control.timerId < 0 && list != null && list.visible()) {
			control.timerId = window.setTimeout("JsLib.Utilities.Hide('" + listId + "');if ('" + callback + "' != '')eval('" + callback + "');$('" + controlid + "').timerId = -1;", timeout);
		}
	},
	cancelhide: function (controlid) {
		var control = $(controlid);
		window.clearTimeout(control.timerId);
		control.timerId = -1;
	}
};

/* CHECKBOXIMAGE */
var CheckBoxImage = {
	Click: function (imgChecked, imgUncheked, imgId, hiddenId) {
		var hdn = document.getElementById(hiddenId);
		var img = document.getElementById(imgId);
		if (1 == parseInt(hdn.value)) {
			img.src = imgUncheked;
			hdn.value = '0';
		} else {
			img.src = imgChecked;
			hdn.value = '1';
		}
	}
};

/* IFRAMEPANEL */
var IFramePanel = {
	Initialize: function (idpanel) {
		var panel = document.getElementById(idpanel);
		var iframe = document.getElementById(panel.attributes['iframeid'].value);
		panel.show = function () {
			var iframe = document.getElementById(this.attributes['iframeid'].value);
			iframe.contentWindow.location.href = this.attributes['iframeurl'].value;
		};
		panel.hide = function () {
			new Effect.SlideUp(this.id);
			window.setTimeout('document.getElementById(\'' + this.id + '\').style.display=\'none\'', 1000);
		};
	},
	IFrameLoadCompleted: function (iframename) { }
};

/* SLIDESHOW */
var SlideShow = {};

SlideShow.Main = {
	slideShowSpeed: 0,
	crossFadeDuration: 3,
	imageList: new Array(),
	altList: new Array(),
	p: 0,
	j: 0,
	preLoad: new Array(),
	prevlinkid: "",
	nextlinkid: "",
	init: function () {
		this.imageList = new Array();
		this.altList = new Array();
		this.preLoad = new Array();

		this.p = 0;
		this.j = 0;

		var a = arguments;
		this.prevlinkid = a[0];
		this.nextlinkid = a[1];
		for (i = 2, j = 0; i < a.length; i += 2, j++) {
			this.imageList[j] = a[i];
			this.altList[j] = a[i + 1];
		}
		this.p = this.imageList.length;
		for (i = 0; i < this.p; i++) {
			this.preLoad[i] = new Image();
			this.preLoad[i].src = this.imageList[i];
			this.preLoad[i].alt = this.altList[i];
		}
	},
	nextimage: function (forward) {
		if (forward) {
			this.j++;
		} else {
			this.j--;
		}
		if (this.j > 0) {
			$(this.prevlinkid).disabled = "";
			$(this.prevlinkid).href = "javascript:SlideShow.Main.nextimage(false);";
		} else {
			$(this.prevlinkid).disabled = "disabled";
			$(this.prevlinkid).href = "javascript:void(0);";
		}
		if (this.j >= (this.p - 2)) {
			$(this.nextlinkid).disabled = "disabled";
			$(this.nextlinkid).href = "javascript:void(0);";
		} else {
			$(this.nextlinkid).disabled = "";
			$(this.nextlinkid).href = "javascript:SlideShow.Main.nextimage(true);";
		}
		document.images.SlideShow2.style.visibility = (this.j == (this.p - 1) ? "hidden" : "visible");
		if (document.all) {
			document.images.SlideShow1.style.filter = "blendTrans(duration=2)";
			document.images.SlideShow1.style.filter = "blendTrans(duration=crossFadeDuration)";
			document.images.SlideShow1.filters.blendTrans.Apply();
			document.images.SlideShow2.style.filter = "blendTrans(duration=2)";
			document.images.SlideShow2.style.filter = "blendTrans(duration=crossFadeDuration)";
			document.images.SlideShow2.filters.blendTrans.Apply();
		}
		document.images.SlideShow1.src = this.preLoad[this.j].src;
		document.images.SlideShow1.alt = this.preLoad[this.j].alt;
		document.images.SlideShow1.title = this.preLoad[this.j].alt;

		document.images.SlideShow2.src = this.preLoad[(this.j + 1 == this.p ? 0 : this.j + 1)].src;
		document.images.SlideShow2.alt = this.preLoad[(this.j + 1 == this.p ? 0 : this.j + 1)].alt;
		document.images.SlideShow2.title = this.preLoad[(this.j + 1 == this.p ? 0 : this.j + 1)].alt;

		if (document.all) {
			document.images.SlideShow1.filters.blendTrans.Play();
			document.images.SlideShow2.filters.blendTrans.Play();
		}
	}
};
