// ================================================================================
// ojo/
// ================================================================================

function addEvent( obj, type, fn ) { 
	if ( obj.attachEvent ) { 
		obj['e'+type+fn] = fn; 
		obj[type+fn] = function(){obj['e'+type+fn]( window.event );} 
		obj.attachEvent( 'on'+type, obj[type+fn] ); 
	} else {
		obj.addEventListener( type, fn, false ); 
	}
} 

function removeEvent( obj, type, fn ) { 
	if ( obj.detachEvent ) { 
		obj.detachEvent( 'on'+type, obj[type+fn] ); 
		obj[type+fn] = null; 
	} else {
		obj.removeEventListener( type, fn, false ); 
	}
} 


function HttpRequest() {
	function initConnector() {
		var o = null;
		var success = false;
		var MSXML_XMLHTTP_PROGIDS = new Array(
			'MSXML2.XMLHTTP.5.0',
			'MSXML2.XMLHTTP.4.0',
			'MSXML2.XMLHTTP.3.0',
			'MSXML2.XMLHTTP',
			'Microsoft.XMLHTTP'
		);

		for (var i=0;i < MSXML_XMLHTTP_PROGIDS.length && !success; i++) {
			try {
				o = new ActiveXObject(MSXML_XMLHTTP_PROGIDS[i]);
				success = true;
			} catch (e) {}
		}
		if( null==o && typeof XMLHttpRequest != "undefined") o = new XMLHttpRequest();
		return o;
	} this.initConnector = initConnector;


	function doRequest(method,url,parms) {
			var ret = false;
			var x = this.initConnector();
			if(null==x)  return;
			var self = this;

			var i, n;
			var post_data;
			method = method.toUpperCase();

			if (method == "GET") { 
				if (url.indexOf("?") == -1) url += "?";
				for( var qparam in parms) { url += qparam+"="+escape(parms[qparam])+"&"; }
				var dt = new Date();
				url += '_'+dt.getTime()+'=1';
				post_data = null;
			} else {
				post_data = "&";
				for( var qparam in parms) { post_data += qparam+"="+escape(parms[qparam]); }
				if(2<post_data.length) post_data = post_data.substr(1);
				else post_data = "";
			}
			x.onreadystatechange = function() {
				if (x.readyState != 4) return;
				if( x.status == 200) {
					self.owner.triggerFunction(self.owner.fireFunc,x);
				} else {
					if( undefined!=self.owner.handleConnError ) self.owner.handleConnError( x );
					else alert(x.status);
				}
			}

			try {
				x.open(method, url, true);
				if (method == "POST") {
					x.setRequestHeader("Method", "POST " + url + " HTTP/1.1");
					x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				}
				x.send(post_data);
				ret = true;
			} catch (e) {
				alert(e);
			}
			delete x;
			return ret;

	} this.doRequest = doRequest;


	this.owner = arguments[0];
}


String.prototype.trim = function(){
	var m=((0==arguments.length?'lr':arguments[0].replace(/\s*/gi,"")).toUpperCase());
	var s=(m.indexOf('L')>-1?this.replace(/^\s*/,""):this);
	return (m.indexOf('R')>-1?s.replace(/\s*$/,""):s);
}

String.prototype.isMailAddr = function checkMailAddr() {
	var addr = this.split("@");
	if(addr.length==1 || addr.length>2) return false;
	var dom = addr[1].split(".");
	if(dom.length == 1) return false;
	var domLen = dom.length
	if(domLen>2 && (dom[domLen-1]).length==0) domLen--;
	if(dom[domLen-1].length<2 || dom[domLen-1].length>3) return false;
	for(var i=0;i<domLen;i++) { if(dom[i].length==0) return false; }

	var acc = addr[0].split(".");
	for(i=0;i<acc.length;i++) { if(acc[i].length==0) return false; }
	var okChars = "abcdefghijklmnopqrstuvwxyz";
	okChars += okChars.toUpperCase()+"0123456789-_";
	var testString = acc.join("")+"."+dom.join("");
	if("."==testString) return false;
	i=0;
	while( i<testString.length ) { 
		if('.'==testString.substr(i,1)) {
			okChars = okChars.substr(0,okChars.length-1);
		} else {
			if(okChars.indexOf(testString.substr(i,1))==-1 ) return false;
		}
		i++;
	}
	return true;
}

String.prototype.substrCount = function (s) {
	return this.split(s).length - 1;
}

String.prototype.isAlpha = function () {
    return (this >= 'a' && this <= 'z') || (this >= 'A' && this <= 'Z');
}

String.prototype.isDigit = function () {
    return (this  >= '0' && this  <= '9');
}

Number.prototype.round = function (d) {
	return Math.round(this*Math.pow(10,d))/Math.pow(10,d);
}


function toUpperCase127(input) { 
	var lower = "aàâäbcçdeéèêëfghiîïjklmnoôöpqrstuùûvwxyz" 
	var upper = "AAAABCCDEEEEEFGHIIIJKLMNOOOPQRSTUUUVWXYZ" 
	var output = ""; 
	var car;
	for (var i = 0 ; i < input.length ; i++) { 
	  car = input.substr(i, 1); 
	  output += (lower.indexOf(car) != -1) ? upper.substr(lower.indexOf(car), 1) : car; 
	} 
	return output; 
} 



function SetCookie(cookieName,cookieValue,nDays) {
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue) + ((nDays==null || nDays==0)?'':";expires="+expire.toGMTString());
}

function getCookie(cookieName) {
	var ret = undefined;
	var toks = document.cookie.split(";");
	for( var i=0; i<toks.length; i++) {
		toks[i] = toks[i].replace(/^\s*/,"");
		if( 0==toks[i].indexOf(cookieName+"=") ) {
			ret = unescape(toks[i].substr(toks[i].indexOf("=")+1));
			break;
		}
	}
	return ret;
}



// XOR decode
function usr_str_xor(pStr,pKey) {
	var cs = pStr.length;
	var ck = pKey.length;
	var ret="";
	for(i=0;i<cs;i++) { ret += String.fromCharCode(pKey.charCodeAt(i%ck)^pStr.charCodeAt(i)); }
	return ret
}

// Base64 encoding
var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var base64DecodeChars = new Array(
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
    -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
    -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);

function base64encode(str) {
    var out, i, len;
    var c1, c2, c3;

    len = str.length;
    i = 0;
    out = "";
    while(i < len) {
	c1 = str.charCodeAt(i++) & 0xff;
	if(i == len)
	{
	    out += base64EncodeChars.charAt(c1 >> 2);
	    out += base64EncodeChars.charAt((c1 & 0x3) << 4);
	    out += "==";
	    break;
	}
	c2 = str.charCodeAt(i++);
	if(i == len)
	{
	    out += base64EncodeChars.charAt(c1 >> 2);
	    out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
	    out += base64EncodeChars.charAt((c2 & 0xF) << 2);
	    out += "=";
	    break;
	}
	c3 = str.charCodeAt(i++);
	out += base64EncodeChars.charAt(c1 >> 2);
	out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
	out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >>6));
	out += base64EncodeChars.charAt(c3 & 0x3F);
    }
    return out;
}

function base64decode(str) {
    var c1, c2, c3, c4;
    var i, len, out;

    len = str.length;
    i = 0;
    out = "";
    while(i < len) {
	/* c1 */
	do {
	    c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
	} while(i < len && c1 == -1);
	if(c1 == -1)
	    break;

	/* c2 */
	do {
	    c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
	} while(i < len && c2 == -1);
	if(c2 == -1)
	    break;

	out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));

	/* c3 */
	do {
	    c3 = str.charCodeAt(i++) & 0xff;
	    if(c3 == 61)
		return out;
	    c3 = base64DecodeChars[c3];
	} while(i < len && c3 == -1);
	if(c3 == -1)
	    break;

	out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));

	/* c4 */
	do {
	    c4 = str.charCodeAt(i++) & 0xff;
	    if(c4 == 61)
		return out;
	    c4 = base64DecodeChars[c4];
	} while(i < len && c4 == -1);
	if(c4 == -1)
	    break;
	out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
    }
    return out;
}
// Base64 encoding ==


function rgbToHexColor(c) {
	if( 0==c.indexOf('#') ) return c;
	c = c.replace(/\s/g,'').toLowerCase().substr(4);
	var triplet = c.substr(0,c.lastIndexOf(')')).split(',');
	for( var i=0;i<3;i++) {
		triplet[i] = (new Number(triplet[i])).toString(16);
		if( 1==triplet[i].length ) triplet[i] = '0'+triplet[i];
	}
	return '#'+triplet.join('');
}




// UI ================================================


function winOnloadAppendScriptFragment(frag) {
	if( null==window.onload ) window.onload = function() {};
	var onloadStr = window.onload.toString();
	onloadStr = onloadStr.substr(onloadStr.indexOf('{')+1);
	onloadStr = onloadStr.substr(0,onloadStr.lastIndexOf('}')).replace(/\n/g," ");
	onloadStr = onloadStr.replace(/\n/g,"");
	onloadStr += ";"+frag;
	var rewritten = eval('new Function("","'+onloadStr+'")');
	window.onload = rewritten;
}

function evtHandlerAppendScriptFragment(o,hndler,frag) {
	if( null==o[hndler] ) o[hndler] = function() {};
	var onloadStr = o[hndler].toString();
	onloadStr = onloadStr.substr(onloadStr.indexOf('{')+1);
	onloadStr = onloadStr.substr(0,onloadStr.lastIndexOf('}')).replace(/\n/g," ");
	onloadStr = onloadStr.replace(/\n/g,"");
	onloadStr += ";"+frag;
	var rewritten = eval('new Function("","'+onloadStr+'")');
	o[hndler] = rewritten;
}


function getEventAbsPos(evt) {
	var p = new Object();
	p.x = evt.pageX?evt.pageX:evt.x+document.body.scrollLeft;
	p.y = evt.pageY?evt.pageY:evt.y+document.body.scrollTop;
	return p;
}

function handleFrDateInputting(evt,el) {
	var bounds;
	if( evt.shiftKey )  bounds = new Array(48,57,191);
	else   bounds = new Array(96,105,111);
	var directions = new Array(35,40);

	if( bounds[2]!=evt.keyCode ) {
		if(evt.keyCode<bounds[0] || evt.keyCode>bounds[1] ) {
			if( 8==evt.keyCode || (evt.keyCode>=directions[0] || evt.keyCode<=directions[1]) ) return;
			el.value = el.value.substr(0,el.value.length-1);
			return;
		}
	}
	if( 2==el.value.length || 5==el.value.length ) el.value += "/";
	el.value = el.value.replace("//","/");
}

function ieEnableSWF() {
	var theObjects = document.getElementsByTagName("object"); 
	for (var i = 0; i < theObjects.length; i++) { 
		theObjects[i].outerHTML = theObjects[i].outerHTML; 
	}
}

// UI ==




//
// Globals ========================================================================
//

var ImgExts = new String("|gif|jpg|jpe|jpeg|png|bmp|wbmp|tif|tiff|pcx|psd|emf|raw|tga|");


//
// ================================================================================


//
// Proj ========================================================================
//
function MyFilter(filterURL,filterLanguage) {
	function init(arrSelList,POSContainer) {
		this.POSResultContainer = document.getElementById(POSContainer);
		var tmp;
		for( var i=0; i<arrSelList.length; i++ ) {
			if( (tmp = document.getElementById(arrSelList[i])) )  {
				this.nbElements++;
				this.elements[arrSelList[i]]=tmp;
				this.elements[arrSelList[i]].owner = null;
				if( 1>i ) {
					this.elements[arrSelList[i]].owner = this.elements[arrSelList[i-1]];
				} else {
					this.elements[arrSelList[i]].disabled = true;
				}
				this.elementsIndexMap[arrSelList[i]] = i;
			}
		}
	} this.init = init;


	function triggerFunction(fncId,parm) {
		if( 'undefined'!=typeof this[fncId] ) {
			this[fncId](parm);
		}
	} this.triggerFunction = triggerFunction;

	function updateElements(oResp) {
		if( 4==this.hashQueryString['step'] ) {
			this.updateStoresList(oResp)
		} else {
			this.updateFilter(oResp);
		}
	} this.updateElements = updateElements;

	function updateFilter(respObject) {
		alert(respObject.responseText);
		var currentFieldName = respObject.responseText.substr(0,respObject.responseText.indexOf('">'));
		currentFieldName = currentFieldName.substr(currentFieldName.indexOf('"')+1);
		this.currentElement = document.getElementById(currentFieldName);
		var targetElement = document.getElementById(currentFieldName).cloneNode(false);
		if( document.all && targetElement.outerHTML ) {
			var spl = targetElement.outerHTML.split("><")
			this.currentElement.outerHTML = spl[0]+">"+respObject.responseText+"<"+spl[1];
		} else {
			this.currentElement.innerHTML = respObject.responseText;
		}
		this.currentElement = document.getElementById(targetElement.id);
		for( exploreProperty in this.elements ) { this.elements[exploreProperty] = document.getElementById(exploreProperty); }
		this.clearDependencies();
		var doNextRequest = false;
		if( 1==this.currentElement.options.length ) {
			/*
			this.currentElement.options[0].text = "";
			this.currentElement.disabled = true;
			*/
			this.disableOptList(this.currentElement);
			if( 3==this.hashQueryString['step'] ) doNextRequest = true;
		} else {
			this.currentElement.disabled = false;
			if( 2==this.currentElement.options.length ) {
				this.currentElement.selectedIndex = 1;
				this.currentElement.options[this.currentElement.selectedIndex].selected = true;
				this.currentElement.value = this.currentElement.options[this.currentElement.selectedIndex].value;
				doNextRequest = true;
			}

			if( 3==this.hashQueryString['step'] ) {
				this.hashQueryString['step'] = 4;
				this.hashQueryString["code_postal"] = "";
				validContactForm(this.elements['code_postal']);
				doNextRequest = false;
			}
			if( doNextRequest ) validContactForm(this.currentElement);
			if( !this.currentElement.disabled ) {
				if( '0'==this.currentElement.options[this.currentElement.options.length-1].value ) {
					this.currentElement.options.length = this.currentElement.options.length-1;
				}
				if( 1==this.currentElement.options.length ) {
					this.disableOptList(this.currentElement);
				} else {
					this.currentElement.focus();
				}
			}
		}
		this.clearDependencies();
	} this.updateFilter = updateFilter;

	function updateStoresList(respObject) {
		var xploreSource = "";
		if( this.POSResultContainer && 1==this.POSResultContainer.nodeType && 'ul'==this.POSResultContainer.nodeName.toLowerCase() ) {
			if( 0<this.POSResultContainer.childNodes.length &&  'li'==this.POSResultContainer.childNodes[0].nodeName.toLowerCase() ) {
				if( this.POSResultContainer.childNodes[0].className ) {
					var xploreSource = respObject.responseText;
					xploreSource = xploreSource.replace(/<LI>/ig,'<li class="'+this.POSResultContainer.childNodes[0].className+'">');
					xploreSource = xploreSource.replace(/<SPAN>/ig,'<span class="'+this.POSResultContainer.childNodes[0].childNodes[0].className+'">');
				}
			}
			this.POSResultContainer.innerHTML = (""==xploreSource?respObject.responseText:xploreSource);
			this.POSResultContainer.style.display = 'block';
		}
	} this.updateStoresList = updateStoresList;

	function disableOptList(oOl) {
		if( 1==oOl.nodeType && 'select'==oOl.nodeName.toLowerCase() ) {
			this.hashQueryString[oOl.id] = "";
			oOl.options[0].value = "";
			oOl.options[0].text = "";
			oOl.options.length = 1;
			oOl.selectedIndex = 0;
			oOl.disabled = true;
		}
	} this.disableOptList = disableOptList;


	function doPosQuery(elId) {
		this.POSResultContainer.style.display = 'none';
		if( !this.currentElement || !this.currentElement.id ) this.currentElement = this.elements[elId];
		var i = -1;
		for( exploreProperty in this.elements ) {
			i++;
			if( i==this.elementsIndexMap[this.currentElement.id]+1) {
				this.currentElement = this.elements[exploreProperty];
				break;
			}
		}
		this.hashQueryString['lng'] = this.queryLanguage;
		if(this.elements["reg_id"].disabled) { this.hashQueryString["reg_id"] = ""; }
		if(this.elements["dep_bcode"].disabled) { this.hashQueryString["dep_bcode"] = ""; }

		this.fireFunc = "updateElements";
		if( this.elements[elId] && this.elements[elId].options && this.elements[elId].selectedIndex ) {
			this.hashQueryString[elId] = this.elements[elId].options[this.elements[elId].selectedIndex].value;
		}
		this.hashQueryString['step'] = this.elementsIndexMap[elId];
		this.srvConn.doRequest("GET",this.queryURL,this.hashQueryString);
	} this.doPosQuery = doPosQuery;

	function clearDependencies() {
		var iForceClear = -1;
		var forceClear  = (2==(this.elementsIndexMap[this.currentElement.id]-this.hashQueryString['step'])?2:-1);
		var clearFromStep = this.hashQueryString['step']+1;
		for( var testId in this.elements ) {
			iForceClear++;
			if( this.currentElement.id==testId ) continue;

			if( (clearFromStep <= this.elementsIndexMap[testId]) || (iForceClear==forceClear) ) {
				this.disableOptList(this.elements[testId]);
			}

			if( 0==1==this.elements[testId].options.length || (1==this.elements[testId].options.length && -1==this.elements[testId].options[0].value) ) {
				this.disableOptList(this.elements[testId]);
			}
		}
	} this.clearDependencies = clearDependencies;

	this.elements = {};
	this.elementsIndexMap = {};
	this.nbElements = 0;
	this.queryURL = filterURL;
	this.queryLanguage = filterLanguage;
	this.currentElement = Object();
	this.POSResultContainer = Object();
	this.hashQueryString = {'step':-1};
	
	
	this.srvConn = new HttpRequest(this);
}
//
// ================================================================================
