var orangeToken="";


/*----------------------------------------------*/
/* isIE						*/
/*----------------------------------------------*/
/* Is Internet Explorer Running ?		*/
/*----------------------------------------------*/
function isIE()
{
	if (window.ActiveXObject){
		return (true);
	}else{
		return(false);
	}
}

/*----------------------------------------------*/
/* makeXmlRequest				*/
/*----------------------------------------------*/
/* return an XML DomDoc from url received as	*/
/* argument					*/
/*----------------------------------------------*/
function makeXmlRequest(url) {
	var http_request = false;

	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return null;
	}

	http_request.open('GET', url, false);
	http_request.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=utf-8');
	http_request.send(null);

	if (http_request.status == 200) {
		var xmldoc;
		if (isIE()){
			xmldoc = new ActiveXObject("MSXML2.DOMDocument");
            xmldoc.async="false";
			resp=http_request.responseText;
			//xmldoc.loadXML( http_request.responseText);
            xmldoc.load( http_request.responseXML);
		}else{
			xmldoc = http_request.responseXML;
		}
		return (xmldoc);
	}else{

		return(null);
		
	}

}

function Serialize(doc)
{
	if (!isIE()){
		return new XMLSerializer().serializeToString(doc);
	}else{
		return doc.xml;
	}
}


function findContactList(token, search){
	var axel = Math.random()+"";
	var a = axel * 10000000000000;
	xmldoc = makeXmlRequest("/expedier/findContactListOrange.do?token=" + token + '&search=' + search + '&RelayState=contacts&num=' + a);
	return xmldoc;
}
			
function importContact(id){
	var axel = Math.random()+"";
	var a = axel * 10000000000000;
	xmldoc = makeXmlRequest("/expedier/getContactOrange.do?token=" + orangeToken + '&id=' + id + '&RelayState=contacts&num=' + a);
	privacyURL=getValue(xmldoc,"url");
  var result = getValue(xmldoc,"result");
  // alert ('result = '+result);
	// if (privacyURL != ""){
	//	s='<a href=' + privacyURL + '&id=' + id + '>Privacy exception. Modify your settings.</a>';
	//	var obj = document.getElementById("yourcalendar");
	//	obj.innerHTML=s;
	//	//location=privacyURL;
	//}else 
    if (result != 0) {
		document.getElementById("blocShippingStep1Orange").style.display="block";
		document.getElementById("blocShippingOrangeResult").style.display="none";
		s='<span class="texteErreur"><i>&nbsp;Aucun contact correspondant</i></span>';
		document.getElementById("blocShippingOrangeMessage").innerHTML=s;
		document.getElementById("blocShippingOrangeMessage").style.display="block";
	}else{
        var country = document.getElementById("dast");
        var state = document.getElementById("etat");//recipient.state
        var lastname = document.getElementById("nom");//recipient.lastname
        var firstname = document.getElementById("pren");//recipient.firstname
        var address = document.getElementById("adre");//recipient.address
        var pcode = document.getElementById("codp");//recipient.zipCode
        var city = document.getElementById("idCityCombo2");//recipient.cityCombo
        var numtel2 = document.getElementById("telm");//recipient.phoneNumber
        var email = document.getElementById("emai");//recipient.email
        var numtel = document.getElementById("telm");// --> telephone fixe
		lastname.value= 	getValue(xmldoc, 'lastname');
		storeCookie("lastname",lastname.value);
		firstname.value= 	getValue(xmldoc, 'firstname');
		storeCookie("firstname",firstname.value);
		addrLst = xmldoc.getElementsByTagName('address');
		if (addrLst.length > 0){
			alert0="";
			for (i=0;i<addrLst.length;i++){
				addr = addrLst.item(i);
				
				if (getAttribute('info-type',addr.attributes) == 'home'){
					address.value= 	getValue(addr,'streetline1') + ' ' + getValue(addr, 'streetline2');
					pcode.value= getValue(addr,'zip-code');
					city.value= getValue(addr,'city');
					state.value= getValue(addr,'state');
					
					var countryText= getValue(addr,'country');
					// si pas de pays, alors on initialise la liste déroulante à FRANCE
					if (countryText == "") { countryText = 'FRANCE'; }
					for (var n=0;n<country.length;n++){
						if(country.options[n].text.toUpperCase() == countryText.toUpperCase()) {
							country.selectedIndex=n;
						}
					}

				}
			}

		}else{
			address.value= "";
			pcode.value= "";
			city.value= "";
			state.value= "";
			// si pas de pays, alors on initialise la liste déroulante à FRANCE
			for (var n=0;n<country.length;n++){
				if(country.options[n].text.toUpperCase() == 'FRANCE') {
					country.selectedIndex=n;
				}
			}
		}
		storeCookie("country",country.value);
		storeCookie("state",state.value);
		storeCookie("city",city.value);
		storeCookie("pcode",pcode.value);	
		storeCookie("address",address.value);				
		devLst = xmldoc.getElementsByTagName('device');
		//numtel.value="";
		numtel2.value="";
		email.value="";
		if (devLst.length > 0){
			for (d=0;d<devLst.length;d++){
				dev = devLst.item(d);
				devSubType = getAttribute('subtype',dev.attributes);
				if (devSubType == 'voice'){
					if (numtel.value == ""){
						numtel.value=dev.firstChild.data;
					}
				}else if (devSubType == 'cell'){
					if (numtel2.value == ""){
						numtel2.value=dev.firstChild.data;
					}
				}
				else if (devSubType == 'internet'){
					if (email.value == ""){
						email.value=dev.firstChild.data;
					}
				}
				
			}
		}

		storeCookie("numtel2",numtel2.value);
		//storeCookie("numtel",numtel.value);
		storeCookie("email",email.value);
    // Rechargement de la liste des villes
    loadCityReceiver();
		resetCalendar();
	}
	
}
			
function importContactFromCookies(){
		//var gender = document.getElementById("gender");
		var country = document.getElementById("selectPays2");//recipient.country
		var state = document.getElementById("inputEtatRegion2");//recipient.state
		var lastname = document.getElementById("inputNom2");//recipient.lastname
		var firstname = document.getElementById("inputPrenom2");//recipient.firstname
		var address = document.getElementById("inputAdresse2");//recipient.address
		var pcode = document.getElementById("inputCodePostal2");//recipient.zipCode
		var city = document.getElementById("idCityCombo2");//recipient.cityText
		var numtel2 = document.getElementById("inputTelephone2");//recipient.phoneNumber
		var email = document.getElementById("inputEmail2");//recipient.email
		var search = document.getElementById("search");
		
		//gender.value = getCookie("gender");
		lastname.value= getCookie("lastname");
		firstname.value= getCookie("firstname");
		address.value= getCookie("address");
		pcode.value= getCookie("pcode");
		city.value= getCookie("city");
		numtel.value= getCookie("numtel");
		numtel2.value= getCookie("numtel2");
		search.value= getCookie("search");
	}
				
		function showCalendar_12(){
			//var obj = document.getElementById("yourcalendar");
		    var obj = document.getElementById("blocShippingOrangeResult");
		    //document.getElementById("blocShippingOrangeResult").style.display="block";
			var search = document.getElementById("search").value;
			storeCookie("search", search);
			obj.innerHTML="";
			if (search.length<3) {
				s='<span class="texteErreur"><i>&nbsp;Entrez au moins 3 caract&egrave;res</i></span>';
				obj.innerHTML=s;
				obj.style.display="block";
			}else{
				//obj.innerHTML='<img width=140 src="pages/images/orange/progressbar.gif"/>';
//alert('search='+search);
//alert('orangeToken='+orangeToken);
				var url = document.location.href;
				var domaine=url.substring(0,url.indexOf("/",7));
				if (orangeToken == "") {
					document.location.href=domaine+'/expedier/sendContactOrange.do?RelayState=contacts';
				} else {
					//obj.innerHTML='<img width=140 src="../images/orange/progressbar.gif"/>';
					//obj.innerHTML='<span class="texteErreur"><i>Recuperation Orange</i></span>';
				    //obj.style.display="block";
					xmldoc = findContactList(orangeToken, search);
					privacyURL=getValue(xmldoc,"url");
					var invalidToken=getValue(xmldoc,"detail");
					if (xmldoc == null) {
						s='<span class="texteErreur"><i>Unable to reach Orange server.</i></span>';
						obj.innerHTML=s;
						obj.style.display="block";
					}else if (invalidToken.indexOf('InvalidToken') > -1){
						s='<span class="texteErreur"><i>Invalid token.</i></span>';
						s="";
						window.location.reload();
						document.getElementById("search").value=search;
						obj.innerHTML=s;
						obj.style.display="block";
					}else if (privacyURL != ""){
						var urlRetour='urlRetour='+domaine+'/expedier/findContactListOrange.do?RelayState=contacts&search='+search+'&token='+orangeToken;
						privacyURL=privacyURL+'&'+urlRetour;
						var redirected = getCookie('redirected') == 'true';
						if (redirected) {
							s='<span class="texteErreur">Privacy.&nbsp;<a href=' + privacyURL + ' style="font-size:9px;color:blue;">Modify your settings.</a></span>';
							obj.innerHTML=s;
							obj.style.display="block";
						} else {
							setTempCookie('redirected', 'true', 15);
							location=privacyURL;
						}
					}else{
						s='<table width="375" cellspacing="1" cellpadding="0" style="border: solid 1px grey">';
						s+='<tr><th width="375" cellspacing="1" cellpadding="0" colspan=2 style="background-color: #ffffff; vertical-align: center">&nbsp;&nbsp;&nbsp;Vos contacts</th></tr>'; //style="border: solid 1px black; background-color: black; color: orange"
					ctcLst = xmldoc.getElementsByTagName('data');
					firstnames = new Array(ctcLst.length);
					lastnames = new Array(ctcLst.length);
					ids = new Array(ctcLst.length);
					for (c=0;c<ctcLst.length;c++){
						ctc = ctcLst.item(c);
						//firstnames[c]=ctc.getElementsByTagName("firstname").item(0).firstChild.data;
						//lastnames[c]=ctc.getElementsByTagName("lastname").item(0).firstChild.data;
						firstnames[c]=getValue(ctc,"firstname");
						lastnames[c]=getValue(ctc,"lastname");
						
						ids[c] = getAttribute('id',ctc.attributes);
					}
					for (i=0; i<lastnames.length;i++)
							s+='<tr style="border: solid 1px grey; background-color:white; height:10px;"><td onmouseover="this.style.background=\'#ff6010\'" onmouseout="this.style.background=\'#ffffff\'" class="td_cal" style="padding:0px; height:10px;"><a class="a_tab" href="javascript:importContact(' + ids[i] + ')"><span style="font-size:9px;">'+firstnames[i]+' '+lastnames[i]+'</span></a></td></tr>';
							//<img width=10 src="../fichiers/import.png"/></td><td class="td_cal" width="40" style="background-color: #ffffff; color: #fff0f0; text-align:center; font-size:9px; padding:0px; height:10px;"><a class="a_tab" href="javascript:importContact(' + ids[i] + ')"><img width=10 src="../fichiers/import.png"/></a></td></tr>';
					s+='</table>';
					//alert('s = '+s);
					if (s.indexOf('td')<0) {
						s='<span class="texteErreur"><i>&nbsp;Aucun contact correspondant</i></span>';
						obj.innerHTML=s;
						obj.style.display="block";
						//s+=xmldoc.textContent;
					} else {
						//document.getElementById("widget").style.display="block";
						document.getElementById("blocShippingStep1Orange").style.display="none";
						document.getElementById("blocShippingOrangeMessage").style.display="none";
						document.getElementById("blocShippingOrangeResult").style.display="block";
						document.getElementById("blocShippingOrangeResult").innerHTML=s;
					}
					}
				}
			}
		}

			function resetCalendar(){
				document.getElementById("search").value="";
				document.getElementById("blocShippingStep1Orange").style.display="";
				document.getElementById("blocShippingOrangeResult").style.display="none";
				document.getElementById("blocShippingOrangeMessage").style.display="none";
			}
			
			function showTerms(){
				//var obj = document.getElementById("terms");
				//var link = document.getElementById("link");
				//link.innerHTML='<a href="javascript:hideTerms()">x fermer</a>';
				//obj.innerHTML='<span style="background: url(../images/orange/GetContact_bottom.png) no-repeat">En vous identifiant, <u>Chronopost</u> obtiendra la permission de r&eacute;cup&eacute;rer vos contacts Orange jusqu &agrave; ce que vous r&eacute;voquiez ce lien &agrave; votre compte. Vous pouvez r&eacute;voquer les liens &agrave; tout moment en allant sur le partage de vos informations</span>';
			}
			
			function hideTerms(){
				//var obj = document.getElementById("terms");
				//var link = document.getElementById("link");
				//link.innerHTML='<a href="javascript:showTerms()">+ en savoir plus</a>';
				//obj.innerHTML="";
			}
			
/*----------------------------------------------*/
/* getValue					*/
/*----------------------------------------------*/
/* get the value of the firs sub node tabName	*/
/* int the xml document xmldoc			*/
/*----------------------------------------------*/

function getValue(xmldoc, tagName)
{
	var value="";
	try {
		var root_nodes = xmldoc.getElementsByTagName(tagName);
		value = root_nodes.item(0).firstChild.data;
	}catch (e){}
	return value;
}

function getAttribute(name, attLst)
{
    for(i=0;i<attLst.length;i++){
    	att=attLst.item(i);
        if(att.name==name) {
            return 	att.value;
        }
    }
    return null;
}	

function storeCookie(name, value)
{
var argv=storeCookie.arguments;
var argc=storeCookie.arguments.length;
var expires=(argc > 2) ? argv[2] : null;
var path=(argc > 3) ? argv[3] : null;
var domain=(argc > 4) ? argv[4] : null;
var secure=(argc > 5) ? argv[5] : false;
document.cookie=name+"="+escape(value)+
((expires==null) ? "" : ("; expires="+expires.toGMTString()))+
((path==null) ? "" : ("; path="+path))+
((domain==null) ? "" : ("; domain="+domain))+
((secure==true) ? "; secure" : "");
}

function getCookieVal(offset)
{
var endstr=document.cookie.indexOf (";", offset);
if (endstr==-1) endstr=document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}

function getCookie(name)
{
var arg=name+"=";
var alen=arg.length;
var clen=document.cookie.length;
var i=0;
while (i<clen)
{
var j=i+alen;
if (document.cookie.substring(i, j)==arg) return getCookieVal(j);
i=document.cookie.indexOf(" ",i)+1;
if (i==0) break;

}
return "";
}

function fct_KeyPress(event) {
  if (event && event.keyCode == 13)
    showCalendar_12();
  else
    return true;
}
function decodeUTF8(utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;

while ( i < utftext.length ) {

    c = utftext.charCodeAt(i);

    if (c < 128) {
	string += String.fromCharCode(c);
	i++;
    }
    else if((c > 191) && (c < 224)) {
	c2 = utftext.charCodeAt(i+1);
	string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
	i += 2;
    }
    else {
	c2 = utftext.charCodeAt(i+1);
	c3 = utftext.charCodeAt(i+2);
	string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
	i += 3;
    }

}

return string;
}
function encodeUTF8(string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    }
function setTempCookie( name, value, expires) {
       
        var today = new Date();
        today.setTime( today.getTime() );

        if ( expires ) {
                expires = expires * 1000 * 60;
        }
       
        var expires_date = new Date( today.getTime() + (expires) );
        document.cookie = name + "=" +escape( value ) +
        ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" );
} 

