var city = new Array();
var flag_findCity=true;
var currfindCityObj=null;

function findObjCity(inputId, elem){
	for (i=0; i<city.length; i++){
	    if (elem=='div')
			if (inputId==city[i].parentDiv.id) return city[i];
	}
}

function Init(parentDiv, selectPath){
	city.push(new findCity (parentDiv, selectPath));
}

findCity = function (parentDiv, selectPath) {
	//свойства
	this.parentDiv=main.findObj(parentDiv);

	var tempArr=this.parentDiv.getElementsByTagName('input'); //input для php
	this.pEdit=tempArr[0];
	this.pEditHidden=tempArr[1];
			
	this.pListDiv=this.parentDiv.getElementsByTagName('div')[0];

	this.pListDiv.style.left=0;
	this.pListDiv.style.top=(this.pEdit.clientHeight+2)+"px";

	this.pListDiv.style.width=(this.parentDiv.clientWidth-2)+"px";
	if (main.is_khtml) {
		this.pListDiv.style.width=(this.parentDiv.clientWidth+2)+"px";
	}
			
	if (main.is_opera) {
		this.browser='opera';
	} else {
		this.browser='';
	}
				
	this.selectPath='/cities/';

	this.selectedLi=null;
	this.trueCity='asddhtshfdjawetast';
	this.arrLi =  new Array();
	this.fff=false;
	//события	
	main.addEvent(this.pEdit, "keyup", this.viewCity);//pEdit
	if (flag_findCity){
		flag_findCity=false;
		main.addEvent(document, "click", this.closeOpenerList);//document
    }
}

findCity.prototype.activateObj = function(ev) {
	var el = main.getElement(ev);
	var currentObj=findObjCity(el.parentNode.id, 'div');
	currfindCityObj=currentObj;
}

//при потере фокуса
findCity.prototype.closeOpenerList2 = function(ev) {
	if (main.is_khtml) {frameId=ev.target;} else {frameId=event.srcElement;}
	var currentObj=findObjCity(frameId.parentNode.id, 'div');
    currentObj.pEdit.focus();
    currentObj.pEdit.blur();
}

//при клике на любом элементе документа
findCity.prototype.closeOpenerList = function(ev) {
	if (main.is_khtml) {frameId =ev.target;} else {frameId=event.srcElement;}
	if (frameId.tagName=='input') {
		var currentObj=findObjCity(frameId.parentNode.id, 'div');//!!
		if ((currfindCityObj!=null)&&(currfindCityObj!=currentObj)) currfindCityObj.hideList(currfindCityObj);
	} else {
		if (currfindCityObj!=null) currfindCityObj.hideList(currfindCityObj);
	}
}

findCity.prototype.viewCity = function(ev) {
	var el = main.getElement(ev);
	var currentObj = findObjCity(el.parentNode.id, 'div');

	if (main.is_opera && ev.keyCode==0) {el.className = 'wrongCity';} //delete in Opera
	if (ev.keyCode==46 || ev.keyCode==8) {el.className = 'wrongCity';} //delete
	
	if (ev.keyCode==40 || ev.keyCode==38) { //если стрелочки или enter
		if ((currentObj.pListDiv.style.display!='none')&&(currentObj.pListDiv.style.display!='')) {
			currentObj.nextLi(currentObj, ev.keyCode);
		}
	} else if (ev.keyCode==13){
		currentObj.enter(currentObj);
	} else if (ev.keyCode==27) {
		currentObj.hideList(currentObj);
	} else {  //запрос, если буквы
		var edit_value=el.value;//считываем значение edit
		if (edit_value.length>0) { //если непустое поле, делаем запрос
			if (currentObj.trueCity!=edit_value) {
				var lang='';
				var reg = new RegExp("^[a-zA-Z, ]+$", "g");
				if (reg.test(edit_value)) {
					lang='eng';
				} else {
					reg = new RegExp("^[а-щь-яА-ЩЬ-Я ]+$", "g");
					if (reg.test(edit_value)&&((language=='rus')||(language=='ukr'))) {
						lang=language;
					} else {
						reg = new RegExp("^[а-яА-Я,ёЁ ]+$", "g");
						if (reg.test(edit_value)) {
							lang='rus';
						} else {
							reg = new RegExp("^[а-щь-яА-ЩЬ-Я,ї'і ]+$", "g");
							if (reg.test(edit_value)) lang='ukr';
						}
					}
				}

				var path;
				reg = new RegExp(language, "g");
					
				path = '/cities/'+lang+'/'+edit_value+'/'+this.browser;

				if (lang!='') {
					currentObj.ajaxManagerCity(path, currentObj, lang);
				} else {
					currentObj.hideList(currentObj);
				}
			} else {
				el.className = 'trueCity';//если город совпал с тем, что был выбран во время последнего изменения
			}
		} else {
			currentObj.hideList(currentObj); //если пустое поле, спрятать лист
		}
	}
}

/*******************************************************************************************************************************/

findCity.prototype.treeLength = function(root) {
    var j=0;var count=0;
    while (j<root.childNodes.length) {
		if (root.childNodes.item(j).tagName){count++;}
        j++;
    }
    return count;
}

findCity.prototype.ajaxManagerCity = function (path, currentObj, lang){
	if (document.getElementById) {
		var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
	}
	
	if (x) {
		x.onreadystatechange = function() {
        	if (x.readyState == 4) {
				var root=x.responseXML.documentElement;
        						
				if (currentObj.treeLength(root)!=0){
					currentObj.formCity(root, currentObj);
					currentObj.showList(currentObj);
				} else {  //если дерево нулевое
					currentObj.pEdit.className='wrongCity';
					currentObj.hideList(currentObj);
				}
			}
		}

		x.open("GET", path, true);
		x.send(null);
	}
}


/*******************************************************************************************************************************/
findCity.prototype.formCity = function(root, currentObj) {
	if(root==null) return;
	var str='<ul>';
	var elem;
	for (i=0;i<root.childNodes.length; i++) {
		if (root.childNodes.item(i).tagName) {
			elem=root.childNodes.item(i);
			str+='<li id='+elem.getAttribute("tid")+'><div style="width:100%;">'+elem.getAttribute("name")+'</div></li>';
		}
	}
	 
	if (root.getAttribute("full")=="false") {
		str+='<span>&nbsp;...</span>';
	}
	
	str+='</ul>'
	currentObj.pListDiv.innerHTML=str;
	currentObj.liEvent(currentObj);
}

findCity.prototype.liEvent=function (currentObj){
	currentObj.arrLi=currentObj.pListDiv.getElementsByTagName('LI');
	for (i=0; i<currentObj.arrLi.length; i++) {	
		main.addEvent(currentObj.arrLi[i], "mouseover", currentObj.activatetLi);
		main.addEvent(currentObj.arrLi[i], "mouseout", currentObj.deactivateLi);
		main.addEvent(currentObj.arrLi[i], "click", currentObj.chooseLi);
	}
}


/*******************************************************************************************************************************/
//спрятать List
findCity.prototype.hideList = function(currentObj) {
    if (currentObj.pListDiv.style.display!='none') {
		currentObj.pListDiv.style.display='none';
		currentObj.pListDiv.style.zIndex=1;
		currentObj.parentDiv.style.zIndex=1;
	}
}

//показать List
findCity.prototype.showList = function(currentObj) {
	currfindCityObj=currentObj;
    var sss=main.getAbsolutePos(currentObj.pEdit);
    currentObj.pListDiv.style.display='block';
    
	// Mozilla, Opera 5, 6 - pageXOffset, pageYOffset ;
    // MSIE, Opera 7 - document.body.scrollLeft, scrollTop ;
    // MSIE+Doctype - document.documentElement.scrollLeft, scrollTop
	if ((sss.y+currentObj.pEdit.clientHeight+currentObj.pListDiv.clientHeight)>document.documentElement.clientHeight) {
		if (main.is_ie) {
			currentObj.pListDiv.style.top=-1*(currentObj.pListDiv.clientHeight-1)+"px";
		} else {
			currentObj.pListDiv.style.top= -1*(currentObj.pListDiv.clientHeight+1)+"px";
		}
    } else {
		if (main.is_ie) {
			currentObj.pListDiv.style.top=(currentObj.pEdit.clientHeight+2)+"px";
		} else {
			currentObj.pListDiv.style.top=(currentObj.pEdit.clientHeight+1)+"px";
		}
    }

	currentObj.pListDiv.style.zIndex=250;
    currentObj.parentDiv.style.zIndex=1000;
}

/*******не смогла соединить для мыши и клавиатуры :(**********************************************************/
/*для мыши*/
findCity.prototype.deactivateLi=function(ev){
	var obj = main.getElement(ev);
	var currentObj=findObjCity(obj.parentNode.parentNode.parentNode.id, 'div');
	currentObj.deactLi(obj);
}

findCity.prototype.activatetLi=function(ev){
	var obj = main.getElement(ev);
	var currentObj=findObjCity(obj.parentNode.parentNode.parentNode.id, 'div');
	
	if (currentObj.fff) { 
		currentObj.deactLi(currentObj.selectedLi);
		currentObj.fff=false;
	}
	
	currentObj.selectedLi = obj;
	currentObj.actLi(currentObj.selectedLi);
}


/*для клавиатуры*/
findCity.prototype.actLi = function(obj){
	obj.className='selected';
}

findCity.prototype.deactLi = function(obj){
	obj.className='';
}

findCity.prototype.findInd=function (actLi, currentObj){
	var i=0;
	
	while (i<currentObj.arrLi.length){
		if (actLi==currentObj.arrLi[i]) {return i;}
		i++;
	}
	
	return -1; //если объект не найден начинаем с первой лишки
}

findCity.prototype.nextLi = function(o, keyCode){
	if (o.fff==false) {
		o.fff=true;
	}
	
	if (o.selectedLi!=null) {
		var actLiInd=o.findInd(o.selectedLi,o);
		if (keyCode==38 && actLiInd>0){
			o.deactLi(o.selectedLi);
			o.selectedLi=o.arrLi[actLiInd-1];
			o.actLi(o.selectedLi);
		}
		
		if (keyCode==40 && actLiInd<(o.arrLi.length-1)) {			
			o.deactLi(o.selectedLi);
			o.selectedLi=o.arrLi[actLiInd+1];
			o.actLi(o.selectedLi);
		}
	} else {
		o.selectedLi=o.arrLi[0];
		o.actLi(o.selectedLi);
	}
}


findCity.prototype.enter = function(o){
    //если список открыт
   	if ((o.pListDiv.style.display!='none')&&(o.pListDiv.style.display!='')) {
        if (o.selectedLi!=null){
			o.deactLi(o.selectedLi);
			o.chLi(o.selectedLi,o);
        } else if (o.arrLi.length==1) { //если в списке остался только один город
            o.chLi(o.arrLi[0],o);
        }
    } else { //если список закрыт
		o.searchCity(o);
	}
}

/*****************При выборе города/страны****************************************************************************************/
findCity.prototype.chooseLi=function(ev){
	var obj = main.getElement(ev);
	var o=findObjCity(obj.parentNode.parentNode.parentNode.id, 'div');
    o.chLi(obj, o);
}

findCity.prototype.chLi=function(obj, o){
  	o.pEdit.value=obj.firstChild.firstChild.nodeValue;
	o.pEditHidden.value=obj.id;

	o.trueCity=o.pEdit.value;
	o.pEdit.className = 'trueCity';
	o.pListDiv.innerHTML='';
	o.hideList(o);
	o.selectedLi=null;
	o.searchCity(o);
}
/********перегрузка страницы*******************************************************************************************************/

findCity.prototype.searchCity = function(o){
	if (o.pEdit.className=='trueCity') {
		//oCityUrl = main.findObj('cityListSelectedUrl');
		
		if (!informerUrl) {
			self.location.href = '/'+o.pEditHidden.value+'/'+language+'/';
		} else {
			informerUrl = o.pEditHidden.value;
			refreshInformers();
		}
	} else {
		alert(messages['There is no such city in the database.']);
	}
}
