/*
	jquery functions and operations
*/

$(document).ready(function() {
                   
	/******************************************************************/                                       

	$('a.menuButton').mouseover(function() {
				$(this).addClass('hover');
            });
            
	$('a.menuButton').mouseout(function() {
				$(this).removeClass('hover');
            });
            
	/******************************************************************/
	
	$('input[@type=password]:not([@readonly])').focus(function(){
				$(this).addClass('focused');
            });
            
	$('input[@type=password]:not([@readonly])').blur(function() {
				$(this).removeClass('focused');
            });	            
           
	$('input[@type=text]:not([@readonly])').focus(function(){
				$(this).addClass('focused');
            });
            
	$('input[@type=text]:not([@readonly])').blur(function() {
				$(this).removeClass('focused');
            });
            
	$('input[@readonly]').focus(function() {
				$(this).blur();
            });          
    
    $('input[@readonly]').addClass('readonly');        
	$('input[@readonly]').css('cursor', 'default');              
            
	$('textarea').focus(function() {
				$(this).addClass('focused');
            });
            
	$('textarea').blur(function() {
				$(this).removeClass('focused');
            });
            
	$('#chooseFileInput').change(function() {
				$('#filePath').val($(this).val());
            });
            
	/******************************************************************/            
	
	$('.showMore').click(function() {
				var data = $(this).parents('.collapseTitle').siblings('.collapseData');
				var img = $(this).parents('.collapseTitle').children('.image');
				
				if (data.hasClass('expanded'))
				{
					data.removeClass('expanded');
					img.removeClass('expanded');
				}
				else
				{
					data.addClass('expanded');
					img.addClass('expanded');					
				}
			});
			
	/******************************************************************/			
			
	$('.linkBarItem').mouseover(function() {
				$(this).addClass('hover');
            });
            
	$('.linkBarItem').mouseout(function() {
				$(this).removeClass('hover');
            });
            
	/******************************************************************/			
			
	$('.styledComboBoxCaption').click(function() {
				$(this).siblings('.styledComboBoxContent').slideToggle();
			});
			
	$('#userShortcuts .styledComboBoxCaption').click(function() {
				//if (navigator.appVersion.indexOf("MSIE 6.0") > 0)
				$('#userButtons').slideToggle();
			});
			
	$('.styledComboBoxContent').mouseout(function() {
				//$(this).slideToggle();
			});
					
	/******************************************************************/
			
	$('.sstab .option:last-child').css('border', 'none');
	
	$('#orientationPage .universeSummary:last-child').css('margin', '0');		
	
	$('div.sortBar .sortItem:last-child').css('border-right', 'none');
	
	/******************************************************************/
	
	//Affecte les valeurs des deux ajaxComboBox des pages d'accueil 	
   	$('#categoriesSelector select#category').val($('input#categoryValue').val());
   	//On fait croire qu'ils ont chang�, haha vive la gruge :-)
   	$('#categoriesSelector select#category').trigger("change");
   	$('#categoriesSelector select#subCategory').trigger("change");
   	
   	$('#categoriesSelector select#subCategory').one("change", function () { 
   		 $('#categoriesSelector select#subCategory').val($('input#subCategoryValue').val());
   	});	
	
	/******************************************************************/
	
	$('div.menuList > div').hover(function() {
				$(this).addClass('hover');
			}, function() {
				$(this).removeClass('hover');
			});
			
	$('div.menuList > div').click(function() {
				document.location.href = $(this).children('a').attr('href');
			});
			
	/******************************************************************/
});

/*
 	Fonction Ajax permettant d'afficher les images suivantes ou pr�c�dentes 
 */
function loadPictureNavigation(url,limit,nb) {
	$.ajax({   
		 	type: "GET",   
		 	data: "limit="+limit+"&nbpictures="+nb+"#thumbnail",
		 	url: url,   
		 	success: function(msg){
		 		//document.getElementById("DivDisplayPicture").bind('change', function() { $("div.demo").slide() }); 
	 			document.getElementById('DivDisplayThumbnail').innerHTML = msg;
	 			//jQuery(document.getElementById("main_image")).remove('.galleria_wrapper');
	 			//$("div#main_image").empty();
	 			$(document).ready(function(){ $("div.demo").slide(false) });
		 	} });
}

/*
	Allow to open a new window in the center of the screen.
*/
function newWindow(width, height, webAddress, winName) 
{
	var win = window.open(webAddress, winName, 
	'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width=' + width + ',height=' + height);
	win.moveTo(screen.availWidth / 2 - (width / 2), screen.availHeight / 2 - (height / 2));
}

function rank_on(index, rankMax, themeFolder)
{
	for (i=1; i <= index; i++)
	{
		document.getElementById('rank_' + i).src = themeFolder + "images/icons/rank_on.gif";
	}
	for (h=i; h <= rankMax; h++)
	{
		document.getElementById('rank_' + h).src = themeFolder + "images/icons/rank_off.gif";
	}
}
function rank_off(index, themeFolder)
{
	if (document.getElementById('lockStar').value != 1)
	{
		for (g=1; g <= index; g++)
		{
			document.getElementById('rank_' + g).src = themeFolder + "images/icons/rank_off.gif";
		}
	}
}
function rate(rank, themeFolder)
{
	document.getElementById('rank_' + rank).src = themeFolder + "images/icons/rank_on_light.gif";
}

function refreshCaptcha(url)
{
	document.getElementById('captchaImg').src = url + '&sid=' + Math.random();
}

/*
	Affiche un message de confirmation
*/
function confirmBox(question, url) 
{
    if (confirm(question)) 
    { 	//Click sur OK
        document.location.href = url;
    }
}

function submitForm(id)
{
	document.forms[id].submit();
	//document.getElementById(id).submit();
}

/*
	Valide un formualaire
*/
function validateForm()
{
	//Champ de type texte:
	//pas de chaine vide
	var formID = validateForm.arguments[0];
	var form = document.forms[formID];
	var errorFound = false;
	//Reset des erreurs
	document.getElementById('infos').innerHTML = "";
	for (i=1; i< validateForm.arguments.length; i++)
	{
		var elt = form.elements[validateForm.arguments[i]];
		//CHAMPS TEXTE
		if (elt.type == "text" || elt.type == "textarea" || elt.type == "password")
		{
			if (elt.value == "")
			{
				errorFound = true;
				elt.className="inputFieldError";
				document.getElementById('infos').innerHTML += form.elements[elt.name + 'ErrorMessage'].value +'<br/>';
			}
			else
				elt.className="";
		}
		
		if (elt.type == "checkbox")
		{
			if (elt.checked == false)
			{
				errorFound = true;
				elt.className="inputFieldError";
				document.getElementById('infos').innerHTML += form.elements[elt.name + 'ErrorMessage'].value +'<br/>';
			}
			else
				elt.className="";
		}
	}
	//si on a pas eu d'erreurs, on valide le formulaire
	if (errorFound == false)
		submitForm(formID)
}

// verifie la validite d'un email //
// Si invalide renvoie le message d'erreur errmsg localis� //
function validemail(champ,errmsg)
{
	test = document.getElementById(""+champ+"").value;
	valeur = test.indexOf("@");
	valeur2 = test.lastIndexOf(".");
	valeur3 = valeur2 + 1;
	longueur = test.length;
	ext = test.substring(valeur3,longueur);
	ok=0;
	temp = ext.length;
	if ( temp==2 || temp==3 ) 
	   { ok=1; }
	else
	   { ok=0; }
	if ( valeur2 == (valeur + 1) )
	    { ok=0; }
	if (valeur==0)
	    { ok=0; }
	if (valeur==-1 || valeur2==-1 || ok==0)
	{ 
	   	alert(errmsg);
	   	return false; 
	}
	else { return true; }
}

/*
	V�rifie la validit� d'un e-mail
*/
function isValidEmail(email, required) {
    if (required==undefined) {   // if not specified, assume it's required
        required=true;
    }
    if (email==null) {
        if (required) {
            return false;
        }
        return true;
    }
    if (email.length==0) {  
        if (required) {
            return false;
        }
        return true;
    }
    if (!allValidChars(email)) {  // check to make sure all characters are valid
        return false;
    }
    if (email.indexOf("@") < 1) { //  must contain @, and it must not be the first character
        return false;
    } else if (email.lastIndexOf(".") <= email.indexOf("@")) {  // last dot must be after the @
        return false;
    } else if (email.indexOf("@") == email.length) {  // @ must not be the last character
        return false;
    } else if (email.indexOf("..") >=0) { // two periods in a row is not valid
		return false;
    } else if (email.indexOf(".") == email.length) {  // . must not be the last character
		return false;
    } else if (email.indexOf("@") != email.lastIndexOf("@")) {  // @ must not be several times in the string
		return false;
    }
    
    //return true;
}

/*
	Indique si une cha�ne contient des caract�res valides	
*/
function allValidChars(value) {
	 var parsed = true;
	 var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
	 for (var i=0; i < value.length; i++) {
	   var letter = value.charAt(i).toLowerCase();
	   if (validchars.indexOf(letter) != -1)
	     continue;
	   parsed = false;
	   break;
	 }
	 return parsed;
}

/*
	Renvoie les caract�res invalides
*/
function getInvalidChars() {
	return "!@#$%^&*()+=[]\\\';,/{}|\":<>?";
}

function str_repeat(i, m) { for (var o = []; m > 0; o[--m] = i); return(o.join('')); }

function sprintf () {
  var i = 0, a, f = arguments[i++], o = [], m, p, c, x;
  while (f) {
    if (m = /^[^\x25]+/.exec(f)) o.push(m[0]);
    else if (m = /^\x25{2}/.exec(f)) o.push('%');
    else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
      if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) throw("Too few arguments.");
      if (/[^s]/.test(m[7]) && (typeof(a) != 'number'))
        throw("Expecting number but found " + typeof(a));
      switch (m[7]) {
        case 'b': a = a.toString(2); break;
        case 'c': a = String.fromCharCode(a); break;
        case 'd': a = parseInt(a); break;
        case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
        case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
        case 'o': a = a.toString(8); break;
        case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
        case 'u': a = Math.abs(a); break;
        case 'x': a = a.toString(16); break;
        case 'X': a = a.toString(16).toUpperCase(); break;
      }
      a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
      c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
      x = m[5] - String(a).length;
      p = m[5] ? str_repeat(c, x) : '';
      o.push(m[4] ? a + p : p + a);
    }
    else throw ("Huh ?!");
    f = f.substring(m[0].length);
  }
  return o.join('');
}

//M�thode pour la connexion mobile
function setLoginField() {
	var loginValue = document.getElementById('login').value;
	var newUrl = "http://www.mobilegovsaas.com/SAWS_BADGE.html?" + loginValue;
	document.getElementById('mobilegovsaas').src = newUrl;
}