// Arnaud Huret 15/10/09

var nOffset = 0;
var nSlides = 0;
var nCurrentSlideId = 0;
var nSlidesShownCount = 0;
var bAutoScroll = true;
var bPreload = true;
var nSlideWidth = 900; // TODO get it via the DOM
var nDefaultSpeed = 1200; //ms
var nFullSpeed = 1; //ms
var nMaxRuns = 1;
var objPageLocators;
var pageLocatorItems = "";
var timer;
var pageLocaterDivName = "nav_slider";
var slidesIdName = "#slides";
var newsIdName = "#news";
var strCookieName = "C0_currentSlide";
var imgPath = "/customers/netbusiness/img/";
var imgPathArray = new Array(8);
imgPathArray[0]= "";
imgPathArray[1]= imgPath + "calendar.png";
imgPathArray[2]= imgPath + "airmail.png";
imgPathArray[3]= imgPath + "contact.png";
imgPathArray[4]= imgPath + "document.png";
imgPathArray[5]= imgPath + "smartphone.png";
imgPathArray[6]= imgPath + "users.png";
imgPathArray[7]= "";

function stopSlideShow() {
	if(bAutoScroll){
		if (nOffset !== 0 && nOffset <= -nSlideWidth) {
			nOffset +=nSlideWidth; // The timer as already run and incremented nOffset
		}
		bAutoScroll = false;
		clearTimeout(timer);
	}
}
function setPageLocatorStyle(slideId){
	for(var i = 0; i < nSlides; i++) { // Remove all styles previously set. Louzy ...
        document.getElementById("a" + i).className = "";
      }
	document.getElementById("a" + slideId ).className = "currentPageLocator";	
}
function setCurrentSlideId(){
	nCurrentSlideId = -nOffset % (nSlideWidth - 1);
	setPageLocatorStyle(nCurrentSlideId);
}
function getCurrentSlideID(){
	return nCurrentSlideId;
}
function setPageLocators(){
	for(var i = 0; i < nSlides; i++) {
		objPageLocators.innerHTML += "<a href='javascript:goToSlide("+ i +");' id='a" + i +"'>&#8226;<\/a>";
	}
}
function startSlideShow(){

	if(bAutoScroll) {
		nSlidesShownCount++;
		setCurrentSlideId();
		animateSlide(nOffset,nDefaultSpeed);	
		
		if (nCurrentSlideId  != nSlides -1) {
			nOffset -= nSlideWidth;
		} else {
			nOffset = 0;
		}
		
		if (nSlidesShownCount == (nMaxRuns * nSlides) + 1) {
			stopSlideShow();
		}
		timer = setTimeout('startSlideShow()', 10000);

	}
}
function goToSlide(slideId, nSpeed){
	stopSlideShow();
	setCurrentSlideId();
	loadImg(slideId,!bPreload);
	animateSlide(slideId * -nSlideWidth, (nSpeed !=null) ? nSpeed : nDefaultSpeed);
	setPageLocatorStyle(slideId);
}

function viewSlide(action){
	stopSlideShow();
	switch(action){
		case "+":
			nOffset -=nSlideWidth;
			if(nOffset == -nSlideWidth * nSlides) {
				nOffset = 0;
			}
			break;

		case "-": 
			if(nOffset == 0) {
				nOffset = -nSlideWidth * (nSlides -1) ;
			} else {
				nOffset +=nSlideWidth;
			}
			break;
		}

	bPreload = false;
	setCurrentSlideId();	
	animateSlide(nOffset,nDefaultSpeed);
}

function animateSlide(nOffset,nAnimationSpeed){ 
	loadImg(nCurrentSlideId, bPreload);
	nSpeed = (nAnimationSpeed != null) ? nAnimationSpeed : nDefaultSpeed;
	$(slidesIdName).animate({left: nOffset + "px"}, nSpeed, "swing"); //  jQuery
	setCookieSlideshow(nCurrentSlideId);
}
function loadImg(slideId, bPreload){ // normally, browser caching should avoid reloading what has alreday been loaded
	slideId += (bPreload)?1:0;
	if(slideId < nSlides -1) { //last slide has no image
		if(slideId != 0) { //first slide image does not need to be preloaded
			document.getElementById("img" + slideId).src = imgPathArray[slideId];
		}
	}
}	
function hide_label(label_id) {
	document.getElementById(label_id).className = 'hidden';
}

function toggle_hints(label_id, input_id) { 
	var strLabel = document.getElementById(label_id);
	var strInput = document.getElementById(input_id);
	if (strInput.value == null || strInput.value == 'undefined' || strInput.value == '') {
		strLabel.className = 'shown';
	} else {
		strLabel.className = 'hidden';
	};
}

function detectEnter(ev){
	var charCode = (navigator.appName == "Netscape") ? ev.which : window.event.keyCode;
	if (charCode == 0x0d) {
		login();
		return false;
	}
	return true;
}

function check_uncheck(obj){
	obj.className = (obj.className == 'unchecked') ? 'checked':'unchecked'; 
}

function setCookieSlideshow(strVal){
	setCookie(strCookieName, strVal, null, "/", null, false);
}

function setCookieInterfacePref(web_interface){
	var dateExpires = new Date();
	dateExpires.setTime(dateExpires.getTime() + (365 * 24 * 60 * 60 * 1000));
	setCookie("COInterface", web_interface, dateExpires , "/", null, false);
}

function defineLocaleCookieAndSet(customer, type, strLocale){
	var dateExpires = new Date();
	var cookieName = customer + type + "Locale"; //type = ex : login,...
	dateExpires.setTime(dateExpires.getTime() + (365 * 24 * 60 * 60 * 1000));
	setCookie(cookieName, strLocale, dateExpires, "/", null, false);
}
function setCookie(strName, strValue, expires, strPath, strDomain, bSecure){
	document.cookie = strName + "=" + escape(strValue) +
	((expires) ? "; expires=" + expires.toGMTString() : "") +
	((strPath) ? "; path=" + strPath : "") +
	((strDomain) ? ";domain=" + strDomain : "") +
	((bSecure) ? "; secure" : "");
}

function getCookie(check_name) {
	var allCookies = document.cookie.split( ';' );
	var tempCookie = '';
	var cookieName = '';
	var cookieValue = '';
	var bCookieFound = false; 

	for (i = 0; i < allCookies.length; i++){
		tempCookie = allCookies[i].split( '=' ); // split each name=value pair
		cookieName = tempCookie[0].replace(/^\s+|\s+$/g, ''); // trim left/right whitespace
		if (cookieName == check_name){ // if the extracted name matches passed check_name
			bCookieFound = true;
			if (tempCookie.length > 1){ // case where cookie has no value but exists
				cookieValue = unescape(tempCookie[1].replace(/^\s+|\s+$/g, ''));
			}
			return cookieValue; // In case the cookie is initialized but has no value, null is returned
			break;
		}
		tempCookie = null;
		cookieName = '';
	}
	if (!bCookieFound){
		return null;
	}
}

function writeToStatusBar(msg){
    window.status=msg;
    return true;
}

function submitLostPassword(){
	if(checkEMail()) {
		document.LostPasswordForm.submit();
		}
}

var startpage = "";

function login(){
	if (document.EntryForm.web_interface.checked) {
		setCookieInterfacePref("classic");
	} else {
		setCookieInterfacePref("ajax");
		startpage = "&startpage=%2Fnui%2Fvirtualoffice.jsp";	
	}

	if (document.EntryForm.Secure.checked) {
		secureLogin(); 
	} else {
		normalLogin();
	}
}

function countDigits(str){ 
	var nDigits = 0 ; 
		for(i = 0 ; i < str.length ; i++){ 
			var c = str.charAt(i) ; 
			if(("0" <= c) && (c <= "9")) nDigits++ ; 
		} 
	return nDigits ; 
}

var numbers = "0123456789";
var bad_chars = "'`\"\\/:; ";
var bad_chars_no_space = "'`\"\\/:;";
var bad_name_chars = "`\"\\/:;~!@#$%^&*()+={}[]|<>/?,";
var bad_name_chars_numbers = bad_name_chars + numbers;
var bad_email_chars = "`\"\\/ (){}[]|<>/,&+=*'%?!~#^:;";
var bad_username_chars = bad_chars + "~!@#$%^&*()-+={}[]|<>,./?\ ";
var bad_password_chars = bad_username_chars;

function containsOneOf(str, chars){
	var i; 
	for(i = 0; i < chars.length ; i++){
		if(str.indexOf(chars.charAt(i)) >= 0) 
		return true ; 
		} 
		return false ; 
}

function containsBadAddress(str, address){
		if(str.indexOf(address) >= 0) 
		return true ;
}

function isAlphaNumeric(c){
	return (('0' <= c) && (c <='9')) || (('A' <= c) && (c <= 'Z')) || (('a' <= c) && (c <= 'z'));
}

function isAlphaNumericString(str){
	var i;
	for (i = 0; i < str.length ; i++) {
		if (!isAlphaNumeric(str.charAt(i))) {
			return false;
		}
	}
	return true;
}

function changeLang(lang){
	defineLocaleCookieAndSet("ContactOffice", "Login", lang);
}

// Mange the language popup using jQuery for smoother effect
$(function () {
		$('#nav_top h2').each(function () {
				var distance = 10;
				var time = 250;
				var hideDelay = 500;
				var hideDelayTimer = null;
				var beingShown = false;
				var shown = false;
				var trigger = $('.language_selector', this);
				var info = $('.language_selector_popup', this).css('opacity', 0);

				$([trigger.get(0), info.get(0)]).mouseover(function () {
						if (hideDelayTimer) clearTimeout(hideDelayTimer);
						if (beingShown || shown) {
								// don't trigger the animation again
								return;
						} else {
								// reset position of info box
								beingShown = true;

								info.css({
										top: 0,
										left: 0,
										display: 'block'
								}).animate({
										top: '-=' + distance + 'px',
										opacity: 1
								}, time, 'swing', function() {
										beingShown = false;
										shown = true;
								});
						}

						return false;
				}).mouseout(function () {
						if (hideDelayTimer) clearTimeout(hideDelayTimer);
						hideDelayTimer = setTimeout(function () {
								hideDelayTimer = null;
								info.animate({
										top: '-=' + distance + 'px',
										opacity: 0
								}, time, 'swing', function () {
										shown = false;
										info.css('display', 'none');
								});

						}, hideDelay);

						return false;
				});
		});
});

/*
 *
 * Copyright (c) 2006-2008 Sam Collett (http://www.texotela.co.uk)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * Version 2.0.2
 * Demo: http://www.texotela.co.uk/code/jquery/newsticker/
 *
 * $LastChangedDate$
 * $Rev$
 *
 */
 
(function($) {
/*
 * A basic news ticker.
 *
 * @name     newsticker (or newsTicker)
 * @param    delay      Delay (in milliseconds) between iterations. Default 4 seconds (4000ms)
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @example  $("#news").newsticker(); // or $("#news").newsTicker(5000);
 *
 */
$.fn.newsTicker = $.fn.newsticker = function(delay)
{
	delay = delay || 5000;
	initTicker = function(el)
	{
		$.newsticker.clear(el);
		el.items = $("li", el);
		// hide all items (except first one)
		el.items.not(":eq(0)").hide().end();
		// current item
		el.currentitem = 0;
		startTicker(el);
	};
	startTicker = function(el)
	{
		el.tickfn = setInterval(function() { doTick(el) }, delay)
	};
	doTick = function(el)
	{
		// don't run if paused
		if(el.pause) return;
		// pause until animation has finished
		$.newsticker.pause(el);
		// hide current item
		$(el.items[el.currentitem]).fadeOut("slow",
			function()
			{
				$(this).hide();
				// move to next item and show
				el.currentitem = ++el.currentitem % (el.items.size());
				$(el.items[el.currentitem]).fadeIn("slow",
					function()
					{
						$.newsticker.resume(el);
					}
				);
			}
		);
	};
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase()!= "ul") return;
			initTicker(this);
		}
	)
	.addClass("newsticker")
	.hover(
		function()
		{
			// pause if hovered over
			$.newsticker.pause(this);
		},
		function()
		{
			// resume when not hovered over
			$.newsticker.resume(this);
		}
	);
	return this;
};


$.newsticker = $.newsTicker =
{
	pause: function(el)
	{
		(el.jquery ? el[0] : el).pause = true;
	},
	resume: function(el)
	{
		(el.jquery ? el[0] : el).pause = false;
	},
	clear: function(el)
	{
		el = (el.jquery ? el[0] : el);
		clearInterval(el.tickfn);
		el.tickfn = null;
		el.items = null;
		el.currentItem = null;
	}
}

})(jQuery);
