// JavaScript Document
var mouseX = 0;
var mouseY = 0;
function getMouseXY() {
  if (IE) { // grab the x-y pos.s if browser is IE
    tempX = event.clientX + document.body.scrollLeft
    tempY = event.clientY + document.body.scrollTop
  } else {  // grab the x-y pos.s if browser is NS
    tempX = e.pageX
    tempY = e.pageY
  }  
  // catch possible negative values in NS4
  if (tempX < 0){tempX = 0}
  if (tempY < 0){tempY = 0}  
  // show the position values in the form named Show
  // in the text fields named MouseX and MouseY
  mouseX = tempX;
  mouseY = tempY;
  //alert(mouseX+'x'+mouseY);
}
var mousePos;
if (!IE) { document.onmousemove = mouseMove; }
function mouseMove(ev){
	ev           = ev || window.event;
	mousePos = mouseCoords(ev);
	
}

function mouseCoords(ev){
	if(ev.pageX || ev.pageY){
		return {x:ev.pageX, y:ev.pageY};
	}
	return {
		x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		y:ev.clientY + document.body.scrollTop  - document.body.clientTop
	};
}


function maximizePan(id) {       
   _Elem(id).style.display = 'none';
   newHeight = _Elem(id).parentNode.offsetHeight;
   _Elem(id).style.height = newHeight;
   _Elem(id).style.display = '';
}

function Status(msg) {
  str = '';
  if (msg) {
    _Elem('imgStatus').src = imgStatusInfos.src;
  } else { _Elem('imgStatus').src = imgVide.src; }
  _Elem('statusDv').innerHTML = str+msg;
}

function showImgGr(src) {
	_Elem('grImg').src=src;

	Show('grImgDv');
	_Elem('grImgDv').style.top = document.body.scrollTop+10;
	if (_Elem('grImgDv').style.top.replace(/px/,'') < 232) _Elem('grImgDv').style.top = 232;
}
var selectDefVal = new Array();
function doSelect(nom, optObj){
	strNew = '';
  aryOpt = getElementsByClass('opt'+nom, _Elem('opt'+nom));

	for (ii = 0 ; ii < aryOpt.length; ii++) {
			if (aryOpt[ii].checked == true) {
        	HTMLStr = aryOpt[ii].parentNode.innerHTML.split('&nbsp;') ;
					strNew += ', '+HTMLStr[1];
			}
		}
	_Elem('input'+nom).value=strNew.replace(/^, /,'');
  if (!_Elem('input'+nom).value) _Elem('input'+nom).value = selectDefVal[nom];
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}
// insere du code html avant un element de la page..
function _InsertHtmlBefore( html, element ) {
    	if ( element.insertAdjacentHTML )	// IE
    	{
    		element.insertAdjacentHTML( 'beforeBegin', html ) ;
    	}
    	else								// Gecko
    	{
    		var oRange = document.createRange() ;
    		oRange.setStartBefore( element ) ;
    		var oFragment = oRange.createContextualFragment( html );
    		element.parentNode.insertBefore( oFragment, element ) ;
    	}
  }

// surcharge de la fonction getElementById pour simplifer le codage
function _Elem(id) {
  return document.getElementById(id);
}

// modifier simplement le style d'un id..
function _Style(id) {
  return _Elem(id).style ;
}

function activate() {
	for (var i = 0; i < arguments.length; ++i) {
		_Elem(arguments[i]).disabled = false;
	}
}

function desactivate() {
	for (var i = 0; i < arguments.length; ++i) {
		_Elem(arguments[i]).disabled = true;
	}
}

function Show() {
	for (var i = 0; i < arguments.length; ++i) {
		_Elem(arguments[i]).style.display = '';
		_Elem(arguments[i]).style.visibility = 'visible';
	}
}

function Hide() {
	for (var i = 0; i < arguments.length; ++i) {
		_Elem(arguments[i]).style.display = 'none';
		_Elem(arguments[i]).style.visibility = 'hidden';
	}
}

function showHide(id) {
	if (_Elem(id).style.display != 'none')
		Hide(id);
	else
		Show(id);
		
}

function ucFirst(str) {
   return str.substr(0,1).toUpperCase() + str.substr(1,str.length);
}

function selectAddOption(sId, oText, oVal, where) {
	sTmp = _Elem(sId);
	nbOptions = sTmp.options.length;
	
	if (where == 'top') {
		for(i=nbOptions; i >= 1  ; i--) {
			sTmp.options[i] = new Option (sTmp.options[i-1].innerHTML, sTmp.options[i-1].value);
		}
		sTmp.options[0] = new Option(oText, oVal);
	} else {
		sTmp.options[nbOptions] = new Option(oText, oVal);
	}
}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function setCheckedValue(radioObj, val) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].value == val) {
			radioObj[i].checked = true;
		} else radioObj[i].checked = false;
	}
	return "";
}
function resetInnerHTMLByClass(className){
  ids = getElementsByClass(className);
  for (i=0; i<ids.length; i++) {
      _Elem(ids[i].id).innerHTML = '';
      
  }
}

function HideByTagName(tag) {
         tags = document.getElementsByTagName(tag);
         for (i=0; i<tags.length; i++) {
           if (_Elem(tags[i].id))
          _Elem(tags[i].id).style.visibility = 'hidden';
         }
}

function ShowByTagName(tag) {
         tags = document.getElementsByTagName(tag);
         for (i=0; i<tags.length; i++) {
             if (_Elem(tags[i].id))
             Show(tags[i].id);
         }
}
function gotoUrl (url){
  window.open('http://'+url);
}

function checkMail(adresse){

var regEx = /([a-z0-9]+([-_]?[a-z0-9]+)*.)*[a-z0-9]+([-_]?[a-z0-9]+)*@([a-z0-9]+([-_]?[a-z0-9]+)*.)+[a-z]{1,4}/gi;  

if (adresse.match(regEx) != adresse ) {

 return false;

} else {

 return true;

}
}

function loading(id) {
w = _Elem(id).clientHeight;
_Elem(id).innerHTML = '<center><br><img src="'+imagesPath+'loader.gif" ></center>';
_Elem(id).style.height = w;
}


function isNumber(val) {return (val == (val*1)); }

function saving (id) { _Elem(id).style.backgroundImage = 'url('+imagesPath+'save.png)'; }

function saved(id) { _Elem(id).style.backgroundImage = 'none'; }

function gotoLogin() {
//self.location = 'index.php?targeturl='+self.location;
}

function getarraysize(thearray) {
	for (i = 0; i < thearray.length; i++) {
		if ((thearray[i] == "undefined") || (thearray[i] == "") || (thearray[i] == null))
			return i;
		}
	return thearray.length;
}
// Replacement for arrayname.push(value) not implemented in IE until version 5.5
// Appends element to the array
function arraypush(thearray,value) {
	thearray[ getarraysize(thearray) ] = value;
}

// Replacement for arrayname.pop() not implemented in IE until version 5.5
// Removes and returns the last element of an array
function arraypop(thearray) {
	thearraysize = getarraysize(thearray);
	retval = thearray[thearraysize - 1];
	delete thearray[thearraysize - 1];
	return retval;
}
// bbCode control 
// Startup variables
var imageTag = false;
var theSelection = false;

// Check for Browser & Platform for PC & IE specific bits
// More details from: http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html
var clientPC = navigator.userAgent.toLowerCase(); // Get client info
var clientVer = parseInt(navigator.appVersion); // Get browser version

var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
var is_nav = ((clientPC.indexOf('mozilla')!=-1) && (clientPC.indexOf('spoofer')==-1)
                && (clientPC.indexOf('compatible') == -1) && (clientPC.indexOf('opera')==-1)
                && (clientPC.indexOf('webtv')==-1) && (clientPC.indexOf('hotjava')==-1));
var is_moz = 0;

var is_win = ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));
var is_mac = (clientPC.indexOf("mac")!=-1);
// Define the bbCode tags
var bbcode = new Array();
var bbtags = new Array('[b]','[/b]','[i]','[/i]','[u]','[/u]','[quote]','[/quote]','[code]','[/code]','[list]','[/list]','[list=]','[/list]','[img]','[/img]','[url]','[/url]');
imageTag = false;
function bbstyle(txtId, bbnumber) {
	var txtarea = _Elem(txtId) ;

	donotinsert = false;
	theSelection = false;
	bblast = 0;

	if (bbnumber == -1) { // Close all open tags & default button names
		while (bbcode[0]) {
			butnumber = arraypop(bbcode) - 1;
			txtarea.value += butnumber;
			buttext = _Elem('bbcodeBtn'+bbnumber).value;
			_Elem('bbcodeBtn'+bbnumber).value = buttext.substr(0,(buttext.length - 1));
		}
		imageTag = false; // All tags are closed including image tags :D
		txtarea.focus();
		return;
	}

	if ((clientVer >= 4) && is_ie && is_win)
	{
		theSelection = document.selection.createRange().text; // Get text selection
		if (theSelection) {
			// Add tags around selection
			document.selection.createRange().text = bbtags[bbnumber] + theSelection + bbtags[bbnumber+1];
			txtarea.focus();
			theSelection = '';
			return;
		}
	}
	else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0))
	{
		mozWrap(txtarea, bbtags[bbnumber], bbtags[bbnumber+1]);
		return;
	}

	// Find last occurance of an open tag the same as the one just clicked
	for (i = 0; i < bbcode.length; i++) {
		if (bbcode[i] == bbnumber+1) {
			bblast = i;
			donotinsert = true;
		}
	}

	if (donotinsert) {		// Close all open tags up to the one just clicked & default button names
		while (bbcode[bblast]) {
				butnumber = arraypop(bbcode) - 1;
				txtarea.value += bbtags[butnumber + 1];
				buttext = _Elem('bbcodeBtn' + bbnumber).value;
				_Elem('bbcodeBtn' + bbnumber).value = buttext.substr(0,(buttext.length - 1));
				imageTag = false;
			}
			txtarea.focus();
			return;
	} else { // Open tags

		if (imageTag && (bbnumber != 14)) {		// Close image tag before adding another
			txtarea.value += bbtags[15];
			lastValue = arraypop(bbcode) - 1;	// Remove the close image tag from the list
			document.post.addbbcode14.value = "Img";	// Return button back to normal state
			imageTag = false;
		}

		// Open tag
		txtarea.value += bbtags[bbnumber];
		if ((bbnumber == 14) && (imageTag == false)) imageTag = 1; // Check to stop additional tags after an unclosed image tag
		arraypush(bbcode,bbnumber+1);
		_Elem('bbcodeBtn' + bbnumber).value +='*';
		txtarea.focus();
		return;
	}
	storeCaret(txtarea);
}

// From http://www.massless.org/mozedit/
function mozWrap(txtarea, open, close)
{
	var selLength = txtarea.textLength;
	var selStart = txtarea.selectionStart;
	var selEnd = txtarea.selectionEnd;
	if (selEnd == 1 || selEnd == 2)
		selEnd = selLength;

	var s1 = (txtarea.value).substring(0,selStart);
	var s2 = (txtarea.value).substring(selStart, selEnd)
	var s3 = (txtarea.value).substring(selEnd, selLength);
	txtarea.value = s1 + open + s2 + close + s3;
	return;
}

// Insert at Claret position. Code from
// http://www.faqts.com/knowledge_base/view.phtml/aid/1052/fid/130
function storeCaret(textEl) {
	if (textEl.createTextRange) textEl.caretPos = document.selection.createRange().duplicate();
}


function in_array(val, ary) {
         for (i in ary) {
         if (ary[i] == val) return true;
         }
         return false;
}

var cp = '';
var old_cp = '';
var villePrx = '';
function doVilles(prx) {
	var remoteVilles = new villes(villesCallBack);
  cp = _Elem(prx+'code_postal').value;
  villePrx = prx;
  if (cp != old_cp){
    if (cp) { remoteVilles.getvilles(cp); }
    old_cp = cp ;
  }
}

var villesCallBack = {
  getvilles: function (aryVilles) {
    var sel = _Elem(villePrx+'ville_id');
    sel.length=0;

	if (!aryVilles) {
		var res = document.createElement('option');
        res.value=0;
        res.innerHTML='Pas de villes pour ce Code postal';
        sel.appendChild(res);
	}
    else {
      for (var i = 0; i < aryVilles.length; ++i) {
        var res = document.createElement('option');
        res.value=aryVilles[i]['ville_id'];
        res.innerHTML=aryVilles[i]['commune'];
        sel.appendChild(res);
      }
      }
    }
  }

function _Error(id) { _Elem(id).style.borderColor = '#FF0000'; _Elem(id).style.backgroundColor = '#CC0033';}
function _Validate(id) { _Elem(id).style.borderColor = '#CECECE'; _Elem(id).style.backgroundColor = '#FFFFFF';}

function imprimerRelances(user_id) {
  ajaxGui.CallGlobalFunction('getRelanceListing', Array(user_id));
}

function getRelanceListingCallBack(ary) {
  _Elem('PrintDiv').innerHTML = ary ;
  window.print();
}

function closeAppel() {
  Hide('divAppel');
}
function getAppelForm() {
  if (!_Elem('divAppel')) {
	var t = document.createElement('div');
	t.id = 'divAppel';
	t.className = 'divAppel';
	document.body.appendChild(t);
  } else {
	Show('divAppel');
  }
  ajaxGui.CallGlobalFunction('getAppelForm', Array());
}
function getAppelFormCallBack(ary) { _Elem('divAppel').innerHTML  = ary; }

function SaveAppelEverywhere() {
   obj = {
	    user_id: _Elem('appel_user_id').value,
		commercial_id: _Elem('appel_commercial_id').value,
		date_appel:CalGetTimestampWithHour('appel_date_appel'),
		date_rappel:CalGetTimestampWithHour('appel_date_rappel'),
		motif: _Elem('appel_motif').value,
		vehicule: _Elem('appel_vehicule').value,
		acheteur_vendeur: _Elem('appel_acheteur_vendeur').value,
		nom: _Elem('appel_nom').value,
		telephone: _Elem('appel_telephone').value,
		email: _Elem('appel_email').value,
		appel_delais_id: _Elem('appel_appel_delais_id').value,
		appel_motif_id: _Elem('appel_appel_motif_id').value,
		tache: _Elem('appel_tache').value,
		commentaire: _Elem('appel_commentaire').value
	};
  ajaxGui.CallGlobalFunctionObj('saveAppel', obj);
}

function saveAppelCallBack(ary) { Hide('divAppel'); }

