if(!XMLHttpRequest)
{
  var XMLHttpRequest = function()
  {
    try
    {
      return new ActiveXObject('Msxml2.XMLHTTP');
    }
    catch(e)
    {
      try
      {
         return new ActiveXObject('Microsoft.XMLHTTP');
      }
      catch(E)
      {
        
      }
    }
    return null;
  }
}




var URL = function(href)
{
  var url = href.split('?');
    this.href = url[0];
      this.datas = arguments[1] || url[1] || '';
      };
      URL.prototype.toString = function()
      {
        var tmp = this.href;
	  if(!isNull(this.datas))
	      tmp += '?' + this.datas;
	        return tmp;
		};
		URL.getHash = function()
		{
		  var hash = document.location.hash
		    return hash.substring(1, hash.length);
		    };


/**
 * Fonction permettant de connaitre si une variable est nulle
  *
   * @param mixed variable variable Ã|  tester
    * @return boulean
     */

     /**
      * Function isNull to verify if the value is null or is a empty String
       * @params value    a Object (Number, String, ...), value to compare
        * @return          a Boolean, <code>true</code> if is null, <code>false</code>
	 * @need            #getAndCall()
	  */
	  function isNull(value)
	  {
	    return value === null || value === '';
	    }

	    /**
	     * Pointer to HTML DOMObject like document.body
	      */
	      document.html = document.documentElement;




var gE =
document.getElements = function()
{
  var elements = new Array();

for (var i = 0; i < arguments.length; i++)
 {
 var element = arguments[i];
 if (typeof element === 'string')
  element = document.getElementById(element) || null;
  if (arguments.length == 1)
  {
  if(element === null)
  return undefined;
  return element;
   }
  if(element != null)
  elements.push(element);
  }
 return elements;
 };







/*
 * Object AJAX contends method to make HTTPTransactions
 *
*/
//TODO: support XML, JSON
var AJAX = {
  /**
   * Method makeHTTPTransaction to initialise a new HTTPRequest and send it with values defined in parameters
   * @params params  An Object, with each properties are content value :
   *                 url, datas, httpMode, headers, asyncMode, user, pass, event
   *                 Only url is required.
   * @return         Void
   * @need           isNull()
   */
  makeHTTPTransaction : function(params)
  {
    if(params.url)
      var url = params.url;
    else
      return;
    var datas = params.datas || '',
    httpMode = params.httpMode || 'GET';
    if(httpMode == 'GET')
    {
      var curUrl = url.split('?');
      url = curUrl[0];
      if(!isNull(datas) && curUrl.length >= 2)
        datas = curUrl[1] + '&' + datas;
      else if(curUrl.length >= 2)
      {
        datas = curUrl[1];
      }
      url = new URL(url, datas);
    }
    //TODO: accept customs header
    //var headers = params.headers || new Array();    
    var asyncMode = params.asyncMode || true;// true : wait server response    
    var request = new XMLHttpRequest();
    request.onreadystatechange = (function()
    {
      return function()
      {
        (function()
        {
          switch(this.readyState)
          {
            /*
            0 = non initialisé ;
            1 = ouverture. La méthode open() a été appelée avec succès ;
            2 = envoyé. La méthode send() a été appelée avec succès ;
            3 = en train de recevoir. Des données sont en train d'être transférées, mais le transfert n'est pas terminé ;
            4 = terminé. Les données sont chargées.
            */
            case 0 : //Uninitialized
              if(typeof params.onuninitialize != 'undefined')
                params.onuninitialize.apply(this);
              break;
            case 1 : //Open
              if(typeof params.onopen != 'undefined')
                params.onopen.apply(this);
              break;
            case 2 : //Sent
              if(typeof params.onsend != 'undefined')
                params.onsend.apply(this);
              break;
            case 3 : //Receiving
              if(typeof params.onreceive != 'undefined')
                params.onreceive.apply(this);
              break;
            case 4 : //Loaded
              if(typeof params.onload != 'undefined')
                params.onload.apply(this);
							/*2xx Success // Status == 0 if it's local*/
              if(this.status == 0 || this.status >= 200 && this.status < 300 && typeof params.onsuccess != 'undefined'){
								params.onsuccess.apply(this);
							}
							/*3xx Redirection, 4xx Client Error, 5xx Server Error*/
              if(this.status >= 300){
								if(typeof params.onfailure != 'undefined'){
									params.onfailure.apply(this);
								}else{
	switch(this.status){
		case 401:
		break;
	/*other errors are here for debugging purpose*/
	case 400:
	break;
	case 404:
	break;
	case 414:
	break;
	default:
	break;
	}
	}
}
	break;
	default:
	//void
	break;
          }
        }).apply(request);
      }
    })();
    
    var user = params.user || null,
    pass = params.pass || null;
    if(isNull(user) && isNull(pass))
      request.open(httpMode, url, asyncMode);
    else
      request.open(httpMode, url, asyncMode, user, pass);
    switch(httpMode)
    {
      case 'get':
  		case 'GET':
        request.send(null);
        break;
  		case 'post':
  		case 'POST':
        request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        request.send(datas);
  		  break;
      default:
      //case 'PUT':
      //case 'DELETE':
  		//case 'HEAD':
        break;      
  	}
    return;
  },
  
  /**
   * Method getAndCall  to make a HTTP transaction and call function when request is completed
   * @params url      a String or URL, the location for make HTTP transaction
   * @param callback  a Function or FuncLink, the Function called when request is complete 
   *                  and status is in (200 to 299)(onsuccess)
   * @param hud				a Boolean, activate HUD or not
   * @return          Void
   * @need            #makeHTTPTransaction()
   */
  getAndCall : function(url, callback )
  {
		if(!callback){
    	this.makeHTTPTransaction({
      	url : url
    	});
		}else{
    	this.makeHTTPTransaction({
      	onsuccess : callback,
      	url : url
    	});
		}
  },
  
  /**
   * Method getAndUpdate  to make a HTTP transaction and refresh the content of an element with response
   * @params url      a String or URL, the location for make HTTP transaction
   * @param element   a DOMObject or String, the element or id of element will be update
   * @return          Void
   * @need            #getAndCall()
   * @need            gE() | document.getElement()
   */
  getAndUpdate : function(url, element)
  {
    var callback = function()
    {
      arguments.callee.element.innerHTML = this.responseText;
    };
    callback.element = gE(element);
    this.getAndCall(url, callback);
  },
  
  /**
   * Method getAndEval  to make a HTTP transaction and evaluate response
   * @params url      a String or URL, the location for make HTTP transaction
   */
  getAndEval : function(url)
  {
    this.getAndCall(url, function(){eval(this.responseText)});
  },
	
 /**
   * Method getAndEvalUpdate  to make a HTTP transaction, refresh the content of an element with response
	                       and evaluate javascript present in response
   * @params url      a String or URL, the location for make HTTP transaction
   * @param element   a DOMObject or String, the element or id of element will be update
   * @return          Void
   * @need            #getAndCall()
   * @need            gE() | document.getElement()
   */
  getAndEvalUpdate : function(url, element)
  {
		
    var callback = function()
    {
			var el = arguments.callee.element;
			
      el.innerHTML = this.responseText;

			var all = el.getElementsByTagName("*");
			var al = all.length;
			for (var i = 0; i < al; i++) {
			  all[i].id = all[i].getAttribute("id");
			  all[i].name = all[i].getAttribute("name");
			  all[i].className = all[i].getAttribute("class");
			}
			
			var allscript = el.getElementsByTagName("script");
			var asl = allscript.length;
			for(var i = 0; i < asl; i++){
				window.eval(allscript[i].text);
			}

    };
		
    callback.element = gE(element);
    this.getAndCall(url, callback);
  },


	/**
	* submitAndCall() send form datas with ajax and call a function back
	* @param  form        form object
	* @param  is_file        file upload (boolean)
	* @param  callback    callback function
	* @return void  
	**/
	submitAndCall : function(form, is_file, callback)
	{

		
		var handleSuccess =  function(o){
			if(callback != undefined){
				callback.call(o);
			}
		}

		var handleFailure = function(o){
  		if(o.status !== undefined){
				switch(o.status){
					case 401:
					break;
					/*other errors are here for debugging purpose*/
					case 400:
					break;
					case 404:
					break;
					case 414:
					break;
					default:
					break;
				}
			}
		}

		var handleUpload = function(o){
			//Since file uploading occurs through an iframe, 
			//traditional response data such as HTTP status codes 
			//are not directly available, and connection manager
			//cannot accurately discern success or failure.
			//Instead, the callback's upload handler will receive
			//a response object containing the body of the iframe 
			//document, as a string, when the transaction is complete.
	  	if(o.responseText !== undefined && callback != undefined){
				callback.call(o);
			}
		}

		var sendCallback ={ 
			success: handleSuccess,
	  	failure: handleFailure, 
			upload: handleUpload
		};
		
		YAHOO.util.Connect.setForm(form, is_file);
		YAHOO.util.Connect.asyncRequest('POST', form.action, sendCallback);
	},

	/**
	* submitAndUpdate() send form datas with ajax and update a HTMLElement content back
	* @param  form        form object
	* @param  is_file        file upload (boolean)
	* @param  element    HTMLElement to update
	* @return void  
	**/
	submitAndUpdate : function(form, is_file, element)
	{
		
		
    var el = gE(element);

		var handleSuccess =  function(o){
			if(o.responseText !== undefined){
      	el.innerHTML = o.responseText;
			}
		}
		
		var handleFailure = function(o){
  		if(o.status !== undefined){
				switch(o.status){
					case 401:
					break;
					/*other errors are here for debugging purpose*/
					case 400:
					break;
					case 404:
					break;
					case 414:
					break;
					default:
					break;
				}
			}
		}

		var sendCallback ={ 
			success: handleSuccess,
	  	failure: handleFailure, 
			upload: handleSuccess
		};

		YAHOO.util.Connect.setForm(form, is_file);
		YAHOO.util.Connect.asyncRequest('POST', form.action, sendCallback);

	}
	
};


/*pour ajouter des truc*/

function AddText(startTag,defaultText,endTag,idText) 

{
   
 
      if (gE(idText).createTextRange) 
      {
         var text;
         gE(idText).focus(gE(idText).caretPos);
         gE(idText).caretPos = document.selection.createRange().duplicate();
         if(gE(idText).caretPos.text.length>0)
         {
            //gère les espace de fin de sélection. Un double-click sélectionne le mot
            //+ un espace qu'on ne souhaite pas forcément...
            var sel = idText.caretPos.text;
            var fin = '';
            while(sel.substring(sel.length-1, sel.length)==' ')
            {
               sel = sel.substring(0, sel.length-1)
               fin += ' ';
            }
            gE(idText).caretPos.text = startTag + sel + endTag + fin;
         }
         else
            gE(idText).caretPos.text = startTag+defaultText+endTag;
      }
      else gE(idText).value += startTag+defaultText+endTag;

}


//POPUP en javascript !!!!!

/**
 * Object dialBox contend methods to make a in popup
 */
var dialBox = {
  mask : null,
  box : null,
  /**
   * draw is a method to draw the in popup
   *
   * @param content   a String, content of the in popup
   * @return          a DOMObject, return the link of created object
   */
  draw : function(content, titleContent, closeOnClick)
  {
		if(closeOnClick !== false){closeOnClick = true;};
		
    //Ajout du masque
    var mask = document.createElement('DIV');
    mask.style.visibility = 'hidden';
    mask.className = 'dialbox-mask';
    this.mask = document.body.appendChild(mask);
    //addEventListener(mask, 'click', function(){dialBox.erase();}, false);//IE Bugs
		
		if(closeOnClick){
	    mask.onclick = function()
  	  {
    	  dialBox.erase();
   		};
		}
    
    //TODO: add an annimation    
    
    var box = document.createElement('DIV');//create parent
    box.style.visibility = 'hidden';
    box.className = 'dialbox';
    this.box = document.body.appendChild(box);
    this.box.appendChild(document.createElement('H2')).innerHTML = titleContent || 'Information :';
    this.box = this.box.appendChild(document.createElement('DIV'));
        
    if(typeof content === 'string')
      this.box.innerHTML = content;
    else
      this.box.appendChild(content);
      
    var boxStyle = box.style;
		
		if(isIE && !isIE7){
			boxStyle.left = ( getViewportWidth() - box.offsetWidth ) / 2 + document.documentElement.scrollLeft + 'px';
			boxStyle.top = ( getViewportHeight() - box.offsetHeight ) / 2 + document.documentElement.scrollTop + 'px';
		}else{
	    boxStyle.top = ( mask.offsetHeight - box.offsetHeight ) /2 + 'px';
  	  boxStyle.left = ( mask.offsetWidth - box.offsetWidth ) /2 + 'px';
		}

    mask.style.visibility = 'visible';
    boxStyle.visibility = 'visible';
		
		if(isIE){
			swapSelects(box);
		}
		
    return box;
  },
  
  /**
   * erase is a method to remove the in popup
   *
   * @return     Void
   */
  erase : function()
  {
    //TODO: ajouter une annimation de disparition
    //Supression du masque

		if(isIE){
			this.box.style.visibility = 'hidden';
			swapSelects(this.box);
		}
				
    remove(this.mask);
    this.mask = null;
    remove(this.box.parentNode);
    this.box = null;
  },
  
  /**
   * drawAJAXContent is a method to make a HTTPTransaction and draw a in popup
   *
   * @params params  An Object, with each properties are content value : 
   *                 url, datas, httpMode, headers, asyncMode, user, pass, events
   *                 (Optional)
   * @return           Void
   */
  drawAJAXContent : function(params)
  {
    AJAX.makeHttpRequest(params);
  }
};

//upload de fichier en """ajax """"
/* This function is called when user selects file in file dialog */

function display_block(id){
if(gE(id).style.display == 'block'){
gE(id).style.display = 'none';

}
else{
gE(id).style.display = 'block';
}
}
function getX(id)
{
return gE(id).offsetLeft
}

// La valeur retournÃ©e peut Ãªtre ignorÃ©e ;:-)
function setX(id,x)
{
return gE(id).style.left=x+"px";
}

function getY(id)
{
return gE(id).offsetTop
}


// La valeur retournÃ©e peut Ãªtre ignorÃ©e ;:-)
function setY(id,y)
{
return gE(id).style.top=y+"px"
}


function getHeight(id)
{
return gE(id).offsetHeight
}


function getWidth(id)
{
return gE(id).offsetWidth
}

function displayState()
{
if(gE('country').options[gE('country').selectedIndex].value == "United States")
{
gE('stateregion').style.visibility = 'visible';
return true
}
else 
{
gE('stateregion').style.visibility = 'hidden';
return false
}
}

function submitCaseStudy() {
var ok = 0;

if(gE('firstname').value == ""){
	ok = 1;
	gE('firstnamel').style.color = "red";
}
else
{
       	gE('firstnamel').style.color = "black";
}

if(gE('lastname').value == ""){
	ok = 1;
	gE('lastnamel').style.color = "red";
}
else
{
	gE('lastnamel').style.color = "black";
}

if(gE('mail').value == ""){
	ok = 1;
	gE('maill').style.color = "red";
}
else 
{
	adresse = gE('mail').value;
	var place = adresse.indexOf("@",1);
	var point = adresse.indexOf(".",place+1);
	if ((place > -1)&&(adresse.length >2)&&(point > 1))
	{
		gE('maill').style.color = "black";

	}
	else
	{
		ok = 1;
		gE('maill').style.color = "red";
	}
}
if(gE('company').value == ""){
	        ok = 1;
	        gE('companyl').style.color = "red";
}
else
{
	gE('companyl').style.color = "black";
}

if(gE('country').value == ""){
	        ok = 1;
	        gE('countryl').style.color = "red";
}
else
{
gE('countryl').style.color = "black";
	if(displayState()) 
	{
		if(gE('state').value == ""){
	        	ok = 1;
	        	gE('statel').style.color = "red";
		}
		else 
		{
			gE('statel').style.color = "black";
		}

	}	
}
if(gE('phone').value == ""){
	        ok = 1;
	        gE('phonel').style.color = "red";
}
else 
{
	gE('phonel').style.color = "black";
}
if(gE('title').value == ""){
	        ok = 1;
	        gE('titlel').style.color = "red";
}
else 
{
	gE('titlel').style.color = "black";
}

if(ok == 1) return false;
else return true;

}

