var op5 = (navigator.userAgent.indexOf("Opera 5")!=-1) 
	||(navigator.userAgent.indexOf("Opera/5")!=-1);
var op6 = (navigator.userAgent.indexOf("Opera 6")!=-1) 
	||(navigator.userAgent.indexOf("Opera/6")!=-1);
var agt=navigator.userAgent.toLowerCase();
var mac = (agt.indexOf("mac")!=-1);
var ie = (agt.indexOf("msie") != -1); 
var mac_ie = mac && ie;

function focusSearchField(field, defaultText) {
	if (field.value==defaultText) {
		field.value='';
		field.className='';
	}
	else {
		//Leave current search keywords
	}
}

function blurSearchField(field, defaultText) {
	if (field.value=='') {
		field.value=defaultText;
		field.className='search_inactive';
	}
}


function manageDisplayBlock(eltToDisplay, className){
	var blockList = $$('.'+className);
	for(var i = 0; i < blockList.length; i++){
		var isshown = (blockList[i].id == eltToDisplay);
		blockList[i].style.display = (isshown)?"block":"none";
	}
}   
function ManageLineDisplay(input){
	var line = input;
	do{
		line = line.parentNode;
	}while(line!=null && line.tagName!='TR');
	if(line!=null){
		var classes = line.className.split(' ');
		var i= classes.indexOf("checked");
		if(i>=0){
			if(input.checked) return;
			else classes.splice(i,1);
		}else{
			if(!input.checked) return;
			else classes.push("checked");
		}
		line.className = classes.join(' ');
	}	
}

/********************************************************/
/*		 Check a String validity 		*/
/********************************************************/
function isValidString(str) {
	if(str==null) return false;
	return str.trim().length>0;
}

/********************************************************/
/*    Function Which return the selected value of a     */
/* javascript select object                             */
/********************************************************/
function getSelectedValue(select) {
	var i=0;
	selectedIndex = -1;
	for(i=0; i<select.options.length; i++) {
		if(select.options[i].selected == true) {
			selectedIndex = i;
		}
	}
	if(selectedIndex == -1) {
		return '';
	}

	return select.options[selectedIndex].value;
}

/********************************************************/
/*    Function Which return the selected value of a     */
/* javascript select object                             */
/********************************************************/
function getSelectedValues(select) {
	var selectedValues = new Array();
	for(var i=0; i<select.options.length; i++) {
		if(select.options[i].selected) {
			selectedValues[selectedValues.length] = select.options[i].value;
		}
	}

	return selectedValues;
}

/********************************************************/
/* Add the selected value of the left combo to the 	*/
/* right combo except if this value already exists	*/
/* for an option in the right combo			*/
/* return false if no option was selected in the left,  */
/* true otherwise					*/
/********************************************************/
function addOption(comboLeft, comboRight) {
	var selectedIndexes = new Array();
	var nbSelectOption = 0;
	var i=0;
	for(i=0;i<comboLeft.options.length; i++) {
		if(comboLeft.options[i].selected) {
			selectedIndexes[nbSelectOption] = i;
			nbSelectOption++;
		}
	}
	
	if(nbSelectOption == 0) {
		return false;
	} else {
		for(i=0; i<nbSelectOption; i++) {
			var selectedValue = comboLeft.options[selectedIndexes[i]].value;
			var nbRightCombo = comboRight.options.length;
			var j=0;
			var isSuchValueInRightCombo = false;
			for(j=0; j<nbRightCombo; j++) {
				if(comboRight.options[j].value == selectedValue) {
					isSuchValueInRightCombo = true;
					break;
				}

			}

			if(!isSuchValueInRightCombo) {
				comboRight[comboRight.options.length] = new Option(comboLeft.options[selectedIndexes[i]].text, comboLeft.options[selectedIndexes[i]].value);
			}
		}
	
		return true;		
	}
}

/********************************************************/
/* Remove the selected value of the right combo. 	*/
/* If this value don't already exists in the left 	*/
/* combo, the option will be added to the left		*/
/* return false if no option was selected in the right, */
/* true otherwise					*/
/********************************************************/
function removeOption(comboRight) {
	var selectedValues = getSelectedValues(comboRight);
	if(selectedValues.length==0) {
		return false;
	} else {
		for(var i=0; i<selectedValues.length; i++) {
			var hasFoundValue = false;
			if(comboRight.options[comboRight.options.length-1].value == selectedValues[i]) {
				comboRight.options[comboRight.options.length-1] = null;
			} else {
				for(j=0; j<comboRight.options.length-1; j++) {
					if(comboRight.options[j].value == selectedValues[i]) {
						hasFoundValue = true;
					}
					if(hasFoundValue) {
						comboRight.options[j] = new Option(comboRight.options[j+1].text, comboRight.options[j+1].value);
					}
				}
				if(hasFoundValue) {
					comboRight.options[comboRight.options.length-1] = null;			
				}
			}
		}

		return true;		
	}
}

/********************************************************/
/* Function which check if a list has one checkbox 	*/
/* checked. Be cautious, a checkbox checked on a other  */
/* page is a hidden input on the current page		*/
/* @param theForm the form with the checkoxed data      */
/* @param checkboxName the name of the parameter	*/
/********************************************************/
function hasOneChecked(theForm, checkboxName) {
	for(var i=0; i<theForm.elements.length; i++) {
		if(theForm.elements[i].name == checkboxName) {
			if(theForm.elements[i].type == 'checkbox') {
				if(theForm.elements[i].checked && theForm.elements[i].value.length>0) {
					return true;
				}
			} else if(theForm.elements[i].type == 'hidden' && theForm.elements[i].value.length>0) {
				return true;
			}
		}
	}
	return false;
}

function invertSort() {
	if(document.mainform.g01page!=null) {
		document.mainform.g01page.value='1';
	}
	if(document.mainform.g01sort.value=='asc') {
		document.mainform.g01sort.value='desc';
	} else {
		document.mainform.g01sort.value='asc';
	}
	document.mainform.submit();
}

/********************************************************/
/* Function which delete in an input all the char whose */
/* aren't numeric                                       */
/********************************************************/
function stringFilter (input) {
	s = input.value;
	notFilteredValues = "1234567890";     // Characters stripped out
	var i;
	var returnString = "";
	for (i = 0; i < s.length; i++) {  // Search through string and append to
				    //unfiltered values to returnString.
		var c = s.charAt(i);
		if (notFilteredValues.indexOf(c) != -1) returnString += c;
	}
	input.value = returnString;
}

/********************************************************/
/* Function which search in all forms of the page an	*/
/* element with the given name				*/
/********************************************************/
function changeCategory() {
	document.mainform.s01categoryid.value=getSelectedValue(document.mainform.s02categoryid);
}

function checkDate(theDay, theMonth, theYear) {
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
	var dayPat = /^(\d{1,2})$/;
	var monthPat = /^(\d{1,2})$/;
	var yearPat = /^(\d{4})$/;
	var isOk = 1;

        if(!theDay.match(dayPat)) {
			isOk = -1;
		} else if(!theMonth.match(monthPat)) {
			isOk = -1;
		} else if(!theYear.match(yearPat)) {
			isOk = -1;
		} else  if (theMonth < 1 || theMonth > 12) {
			isOk = -2;
        } else if (theDay < 1 || theDay > 31) {
			isOk = -2;
        } else if ((theMonth==4 || theMonth==6 || theMonth==9 || theMonth==11) && theDay==31) {
			isOk = -2;
        } else if (theMonth == 2) {
            var isleap = (theYear % 4 == 0 && (theYear % 100 != 0 || theYear % 400 == 0));
            if (theDay>29 || (theDay==29 && !isleap)) {
				isOk = -2;
            }
        }
        return isOk;
}

/**
* Open a url in a popup
*/
function OpenPopup(newhtml, windowname, wide, high) {
    var w = 800, h = 600;
    var width1 = 0;
    var height1 = 0;

    if (document.all) {
       /* the following is only available after onLoad */
       w = document.body.clientWidth;
       h = document.body.clientHeight + 50;
    } else if (document.layers) {
       w = window.innerWidth;
       h = window.innerHeight;
    }
    var topPos = ((h-high)/2), leftPos = ((w-wide)/4);

    var windowFeatures = "width=" + wide + ",height=" + high + ",left=" + leftPos + ",top=" + topPos + ",directories=no,location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no" ;
    NewWindow = window.open(newhtml, windowname, windowFeatures);
    if(NewWindow != null) {
    	NewWindow.focus();
    }
    return NewWindow
}

function OpenPopupFromFrame(newhtml, windowname, wide, high) {
    var w = 800, h = 600;
    var width1 = 0;
    var height1 = 0;

    if (document.all) {
       /* the following is only available after onLoad */
       w = document.body.clientWidth;
       h = document.body.clientHeight + 50;
    } else if (document.layers) {
       w = window.innerWidth;
       h = window.innerHeight;
    }
    var topPos = ((h-high)/2), leftPos = ((w-wide)/4);

    var windowFeatures = "width=" + wide + ",height=" + high + ",left=" + leftPos + ",top=" + topPos + ",directories=no,location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no" ;
    NewWindow = window.open(newhtml, windowname, windowFeatures);
    if(NewWindow != null) {
    	NewWindow.focus();
    }
}

function changeSortOrder(sortflag) {
	if(document.mainform.g01page!=null) {
		document.mainform.g01page.value='1';
	}
	if(document.mainform.g01sort.value=='desc') {
		document.mainform.g01sort.value='asc';
	}
	document.mainform.g01criterion.value=sortflag;
	document.mainform.submit();
}


function setDefaultAlertUnit(input, istask) {
	if(!isValidString(input.value)) {
		if(istask) {
			input.value='3';
		} else {
			input.value='5';
		}
	}
}

function switchSyncMessage()
{
	var global_block = document.getElementById('C_mobile_sync_summary');
	var img = document.getElementById('C_reduce_sync_block');
	var block = document.getElementById('C_message_sync_block');
	var sync_button = document.getElementById('C_action_sync_block');
		
	var phone_img = document.getElementById('C_small_phone_img_sync_block');
	
	var url_min = '../vox42/image/picto_message_reduce.gif';
	var url_max = '../vox42/image/picto_message_maximize.gif';
	
	if(block.style.display == "none")
	{
		block.style.display = "block";
		sync_button.style.display = "block";
		
		global_block.className="C_mobile_sync_maximized";
		img.src = url_min;
		if(phone_img != null){
			phone_img.src = big_phone.src; //defined within sync-info.jsp
		}
		
		if(document.getElementById("navigation").displaySyncInfo != null)
		{
			document.getElementById("navigation").displaySyncInfo.value = "yes";
		}
	}
	else
	{
		block.style.display = "none";
		sync_button.style.display = "none";
		
		global_block.className="C_mobile_sync_minimized";
		img.src = url_max;
		if(phone_img != null){
			phone_img.src = small_phone.src; //defined within sync-info.jsp
		}
		
		if(document.getElementById("navigation").displaySyncInfo != null)
		{
			document.getElementById("navigation").displaySyncInfo.value = "no";
		}
	}
}

var shadowCounter = 0;
function hideShadowLayerForPopup(){
	shadowCounter--;
	if(shadowCounter<=0){
		var shadowLayer = document.getElementById("L_shadow_layer_for_popup");
		shadowLayer.style.display = 'none';
	}	
}
function displayShadowLayerForPopup(bgcolor){
	shadowCounter++;
	var shadowLayer = document.getElementById("L_shadow_layer_for_popup");
	//shadowLayer.style.height = (op5?document.style.pixelWidth:document.body.offsetHeight)+ "px";
	try{
		shadowLayer.contentWindow.document.body.style.backgroundColor = (bgcolor==null)?'#999999':bgcolor;
	}catch(e){}	
	if(agt.indexOf("msie 6.0") != -1){
		shadowLayer.style.height = document.body.offsetHeight + "px";
	}
	shadowLayer.style.display = 'block';
	/*var top = Math.min((((document.body.clientHeight)?document.body.clientHeight:window.innerHeight - document.getElementById("MESSAGE_BLOCK").offSetHeight) / 3),250);
	var left = Math.min((((document.body.clientWidth)?document.body.clientWidth:window.innerWidth - document.getElementById("MESSAGE_BLOCK").offSetWidth) / 3),350);
	document.getElementById('MESSAGE_BLOCK').style.top = top + "px";
	document.getElementById('MESSAGE_BLOCK').style.left = left + "px";
	*/
}

function update(i) // call back
{
	var elt_bar = document.getElementById("M_fillUpBar");
	var elt_state1 = document.getElementById("M_progressStep1");
	var elt_state2 = document.getElementById("M_progressStep2");
	var elt_state3 = document.getElementById("M_progressStep3");
	var elt_state4 = document.getElementById("M_progressStep4");
	switch(i)
	{
		case SYNC_FINISHED:
			swapMessage(i);
			clearTimeout(window.ii);
			clearTimeout(window.iii);
  			elt_bar.style.width = "0px";
  			SyncStepDAO.terminate();
  			SyncStepDAO.getSyncStatus(showSyncStatus);
  			break;
  		case SYNC_ERROR:
			swapMessage(i);
  			clearTimeout(window.ii);
  			clearTimeout(window.iii);
  			elt_bar.style.width = "0px";
  			SyncStepDAO.terminate();
  			SyncStepDAO.getSyncStatus(showSyncStatus);
  			swapMessage(i);
  			break;
  		case SYNC_TIMEOUT:
  			swapMessage(i);
  			clearTimeout(window.ii);
  			clearTimeout(window.iii);
  			elt_bar.style.width = "0px";
  			SyncStepDAO.terminate();
  			SyncStepDAO.getSyncStatus(showSyncStatus);
  			break;
  		case SYNC_STARTED:
  			swapMessage(i);
  			/*
  			var current_width = elt_bar.offsetWidth;
			current_width = Number(current_width) - step;
			
			if(current_width >= 0)
			{
				elt_bar.style.width = current_width + "px";
  				swapMessage(i);
	  		}
	  		else // synchro is not finished but we reached the end of the progress bar
	  		{
	  			update(SYNC_ERROR); //call with error
	  		}
	  		*/
	  		if(!updateProgressBar.started)
	  		{
		  		updateProgressBar.started = true;
		  		window.iii = setInterval('updateProgressBar()', 200);
		  	}
  			break;
  	}
}

function showSyncStatus(status)
{	
	var elt_msg = document.getElementById("M_syncStatusMessage" + String(status));
	if(elt_msg != null) elt_msg.style.display = "block";
}
function swapMessage(index)
{
	for(var i = 1; i <=6; i++ )
	{
		var elt_msg = document.getElementById("M_progressStep" + i);
		if(elt_msg == null)
			continue;
		
		if(i == index) elt_msg.style.display = "block";
		else elt_msg.style.display = "none";
	}
}
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

//GROUP EDIT METHODS
function swapSide(cmd)
{
	var on_phone_elt = document.getElementById("inp_contact_group_list");
	var not_on_phone_elt = document.getElementById("inp_contact_list");

	var indexes_to_remove = new Array();
	var cpt = 0;
	
	var elt_from = null;
	var elt_to = null;
	
	if(cmd == 'add')
	{
		elt_from = not_on_phone_elt;
		elt_to = on_phone_elt;
	}
	else if(cmd == 'remove')
	{
		elt_from = on_phone_elt;
		elt_to = not_on_phone_elt;
	}
	else
	{
		return;
	}
	
	for(var i = 0; i < elt_from.options.length; i++)
		{
			if(elt_from.options[i].selected)
			{
				var value = elt_from.options[i].value;
				var text = elt_from.options[i].text;
				var l_contact = getContact(value);
				l_contact.inGroup = !l_contact.inGroup;
			
				var l_option = document.createElement('option');
			    l_option.text = text;
			    l_option.value = value;
				if(filterCanContain(elt_from.options[i])){
					try 
					{
						elt_to.add(l_option, null); // standards compliant; doesn't work in IE
					}
					catch(ex) 
					{
						elt_to.add(l_option, 0); // IE only
					}
				}
				indexes_to_remove[cpt] = i;
				cpt++;
			}
		}
		
		for(var i = 0; i < indexes_to_remove.length; i++)
		{
			var index_to_remove = indexes_to_remove[i];
			elt_from.remove(index_to_remove);
			for(var j = i+1; j < indexes_to_remove.length; j++)
			{
				indexes_to_remove[j] = indexes_to_remove[j] -1;
			}	
		}
}

function filter(eltName, letter)
{
	letterFilter = letter.split(',');
	fillContacts(eltName, false);
}

function fillContacts(elt, status)
{
	var selectElt = document.getElementById(elt);
	selectElt.length = 0;
	
	for(var i = 0; i < contactArray.length; i++)
	{
		var contact = contactArray[i];
		var contactFiltered = false;
		var fname_first = contact.firstName.substring(0,1);
		var lname_first = contact.lastName.substring(0,1);
		var nname_first = contact.nickName.substring(0,1);

		if(letterFilter != null && letterFilter.length > 0 && letterFilter[0] != "")
		{
			for(var j = 0; j < letterFilter.length; j++)
			{
				if(letterFilter[j].toUpperCase() == fname_first.toUpperCase())
				{
					contactFiltered = true;
					continue;
				}
				else if(letterFilter[j].toUpperCase() == lname_first.toUpperCase())
				{
					contactFiltered = true;
					continue;
				}
				else if(letterFilter[j].toUpperCase() == nname_first.toUpperCase())
				{
					contactFiltered = true;
					continue;
				}
			}
		}
		else
		{
			contactFiltered = true;
		}
		
		if(status == contact.inGroup && contactFiltered)
		{
			var length = selectElt.length;
			var value = contact.id;
			var text = contact.firstName + " " + contact.lastName;
			//if(contact.nickName != '')
			//	text += " (" + contact.nickName + ")";
			
			var l_option = document.createElement('option');
		    l_option.text = text;
		    l_option.value = value;
			
			try 
			{
				selectElt.add(l_option, null); // standards compliant; doesn't work in IE
			}
			catch(ex) 
			{
				selectElt.add(l_option, length); // IE only
			}
		}
	}
}

function filterCanContain(elt){
	var contact = getContact(elt.value);
	var result = false;
	var fname_first = contact.firstName.substring(0,1);
	var lname_first = contact.lastName.substring(0,1);
	var nname_first = contact.nickName.substring(0,1);

	if(letterFilter != null && letterFilter.length > 0 && letterFilter[0] != ""){
		for(var i = 0; i < letterFilter.length; i++)
		{
			if(letterFilter[i].toUpperCase() == fname_first.toUpperCase())
			{
				result = true;
				continue;
			}
			else if(letterFilter[i].toUpperCase() == lname_first.toUpperCase())
			{
				result = true;
				continue;
			}
			else if(letterFilter[i].toUpperCase() == nname_first.toUpperCase())
			{
				result = true;
				continue;
			}
		}
	}else{
		result = true;
	}
	return result;
}

function getContact(value)
{
	if(contactArray.length == 0)
		return null;
		
	var l_contact = null;
	
	for(var i = 0; i < contactArray.length; i++)
	{
		if(contactArray[i].id == value)
		{
			l_contact = contactArray[i];
		}
	}
	return l_contact;
}
//END GROUP EDIT METHODS

/********************************************************/
/* Function Which hides Tip message 	*/
/********************************************************/
function hideTip() {
	var tipBlock = document.getElementById("C_tip_message");
	if(tipBlock != null){
		tipBlock.style.display = "none";
	}
}

/********************************************************/
/* Function Which closes Tip message 	*/
/********************************************************/
function closeTip() {
	hideTip();
	createCookie("display_ab_tip", "false", 365);
}

/************************************************************************/
/* Function Which hides Tip message at page load if a cookie says so 	*/
/************************************************************************/
function hideTipIfShould() {
	var displayTipCookie = readCookie("display_ab_tip");
	if(displayTipCookie == "false") {
		hideTip();
	}
}

/********************************************************/
/* Function To Manage Onglet (highlighting) 	*/
/********************************************************/
function ongletClicked(elt){
	var ongletBar = elt.parentNode;
	var ongletList = ongletBar.childNodes;
	for(var i = 0; i < ongletList.length; i++){
		if(ongletList[i].className != null && ongletList[i].className.indexOf('C_onglet_highlight') != -1){
			ongletList[i].className = ongletList[i].className.replace(' C_onglet_highlight', '');
		}
	}
	elt.className += ' C_onglet_highlight';	
}

/******************************************************/
/* Function to convert size in octect to Ko / Mo / Go */
/******************************************************/

function getSizeName(octet){
    
	if (octet < 1024) // octet
    {
        return octet + " octect";
    }
    else 
    {
        if (octet < 1048576) // ko
        {
            ko = Math.ceil(octet/1024*100)/100;
            return ko + " ko";
        }
        else // Mo ou Go 
        {
            if (octet < 1073741824) // Mo 
            {
                mo = Math.ceil(octet/(1024*1024)*100)/100;
                return mo + " Mo";
            }
            else // Go 
            {
                go = Math.ceil(octet/(1024*1024*1024)*100)/100;
                return go + " Go";    
            }
        }
    }
}		

/******************************************************/
/* Function to limit number of characters in textarea */
/******************************************************/
function fieldlimitchar(elt, m) {
	if(elt.value.length > m){
		elt.value = elt.value.substr(0, m);
	}
}