var IE = false;
if (navigator.userAgent.indexOf ("MSIE") != -1) IE = true;

var toHide = Array();
var toDestroy = Array();
var activDP = '';

var myRequest = null;
var myRequestStr = '';
var nextRequest = 1;

function hideFinded(thisid) {
	if (thisid != '') toHide[toHide.length] = thisid;
	addHideAndDestroyToBody();
}

function destroyFinded(thisid) {
	if (thisid != '') toDestroy[toDestroy.length] = thisid;
	addHideAndDestroyToBody();
}

function addHideAndDestroyToBody() {
	$(document.body).onclick = function() { 
		hideDivs();
		destroyDivs();
	};
}

function hideAndDestroy() {
	hideDivs();
	destroyDivs();
}

function hideDivs() {
	if (myRequest != null) myRequest.cancel();
	nextRequest = 1;
	for (var i=0; i < toHide.length; i++){
		$(toHide[i]).style.visibility = 'hidden'; 
	}
}

function destroyDivs() {
	for (var i=0; i < toDestroy.length; i++){
		if ($(toDestroy[i])) $(toDestroy[i]).destroy(); 
	}
	activDP = '';
}

function setDateDateNYAAA(str) {
	if (activDP != ''){
		if ($(activDP)) $(activDP).value = str;
		//if ($('dp_'+activDP+'_div') != null) $('dp_'+activDP+'_div').destroy();
	}
	destroyDivs();
}

function createFindedDiv(id) {

	if (id != '' && $(id)) {
		$(id).onkeyup = new Function('', 'searchRows(this.id, $("'+id+'").value)');
        var f_div = new Element('div', { 'id': id+'_search' });
        /*if (IE) {
			f_div.style.top = $(id).getTop() + $(id).getHeight() + "px";
			f_div.style.left = $(id).getLeft() + "px";
		}
		else {
			f_div.style.top = parseInt($(id).top) + 30 + "px";
			f_div.style.left = $(id).left;
		}*/
		
		f_div.style.top = getObjectPosition($(id)).y + 20 + 'px';
		f_div.style.left = getObjectPosition($(id)).x + 'px';
		
		//f_div.style.top = parseInt($(id).getTop() + 30) + "px";
		//f_div.style.left = parseInt($(id).getLeft()) + "px";
        f_div.style.position = 'absolute';
        f_div.style.visibility = 'hidden';
        f_div.style.borderStyle = 'solid';
        f_div.style.fontSize = '80%';
        f_div.style.backgroundColor = 'white';
        f_div.style.zIndex = 999;
        //$(document.body).appendChild(f_div);
		$(id).parentNode.appendChild(f_div);
        hideFinded(id+'_search');
    }
}

function searchRows(id, str)//, table, field, limit, tvid
{
	if (str.length == 0) $(id+'_search').style.visibility = 'hidden';
	else if (str.length > 1) 
	{
		var tmpstr = "&id="+id+"&str="+str;//+"&table="+table+"&field="+field+"&limit="+limit+"&tvid="+tvid;
		if (nextRequest == 1) tmpstr += '&param=1';
		if (IE) tmpstr += "&IE";

		if(str.length > 0 && (str != myRequestStr || nextRequest == 0)) {
			//var myRequest = new Request({url: 'mypage.html', method: 'get'}).send('some=data');
			//myRequest.cancel();
			myRequestStr = str;
			if (myRequest) {
				myRequest.cancel();
				nextRequest = 1;
			}
			myRequest = new Request({
					method: "post",
					data: "action=" + "web/kladr/search" +
						tmpstr,
					onSuccess: function(response) {
							var str = Array();
							str = response.split('||');
							if (str.length == 2) {
								$(str[0]).style.visibility = "visible";
								$(str[0]).innerHTML = str[1];
							}
							//if (myRequest) myRequest.cancel();
							//myRequest = null;
							if (nextRequest == 1) 
							{
								if (myRequest) {
									myRequest = null;
									nextRequest = 0;
								}
								//nextRequest = 0;
								var id = str[0].replace('_search', '');
								searchRows(id, $(id).value);
							}
							else if (nextRequest == 0) nextRequest = 1;
							/*var resp = JSON.parse(response);
							if (resp.success) MochaUI.actionPoliciesMgrWnd(resp.message);
							else MochaUI.notification(resp.message);*/
					},
					/*onFailure: function() {
							MochaUI.notification("Ошибка при выполнении запроса!");
					},*/
					url: "assets/components/2nets/connector.php"
			}).send();
		}
		else if ($(id+'_searched')) $(id+'_searched').value = "";
	}
}

function setActivDP(thisid, event) {
	if (thisid != '') {
		hideAndDestroy();
		activDP = thisid;
		var event = event || window.event;
		if (event.stopPropagation) event.stopPropagation();
		else event.cancelBubble = true;
		if ($('dp_'+thisid+'_div') != null) return;
		var datePicker = new Element('div', {
			'id': 'dp_'+thisid+'_div',
		    'class': 'date_picker',
		    'html': '<div id="fdp_'+thisid+'"></div>'//getDatePicker()
		});
		datePicker.style.position = 'absolute';
		datePicker.style.zIndex = 999;
		destroyFinded(datePicker.id);
		datePicker.style.width = '185px';
		datePicker.style.height = '185px';
		datePicker.style.top = getObjectPosition($('dp_'+thisid)).y + 'px';
		datePicker.style.left = getObjectPosition($('dp_'+thisid)).x + 20 + 'px';
		$(thisid).parentNode.appendChild(datePicker);
		swfobject.embedSWF("assets/flash/cl.swf", "fdp_"+thisid, "185px", "165px", "9", "expressInstall.swf", null, null);
	}
}


function getObjectPosition(obj) {
	var offset = obj.getOffsets();
	var scroll = obj.getScrolls();
	var position = {x: offset.x - scroll.x, y: offset.y - scroll.y};
	return {x: position.x, y: position.y};
}

/*getPosition: function(relative){
		if (isBody(this)) return {x: 0, y: 0};
		var offset = this.getOffsets(), scroll = this.getScrolls();
		var position = {x: offset.x - scroll.x, y: offset.y - scroll.y};
		var relativePosition = (relative && (relative = $(relative))) ? relative.getPosition() : {x: 0, y: 0};
		return {x: position.x - relativePosition.x, y: position.y - relativePosition.y};
	}*/

function rowSelected(thisid) {
	if (myRequest) {
		myRequest.cancel();
		nextRequest = 1;
	}
	var str = thisid.split('_searched');
	if ($(str[0])) {
		var str1 = '';
		if (IE) str1 = $(thisid).innerHTML.replace('<B>', '').replace('</B>', '');
		else str1 = $(thisid).innerHTML.replace('<b>', '').replace('</b>', '');
		str1 = str1.substring(0, str1.indexOf(' (Россия', 1)).substring(str1.indexOf(' ', 1) + 1, 255);
		$(str[0]).value = str1;
	}
	
	var str1 = str[1].split('_');
	if ($(str[0]+'_searched')) $(str[0]+'_searched').value = str1[0];
	if ($('utc')) selectRowByValue('utc', str1[1]);
	if ($(thisid)) $(thisid).parentNode.style.visibility = 'hidden';
	
	/*var str = thisid.split('_searched');
    if ($(str[0])) $(str[0]).value = $(thisid).innerHTML;
    if ($(str[0]+'_searched')) $(str[0]+'_searched').value = str[1];
    $(thisid).parentNode.style.visibility = 'hidden';*/
}

// id - идишник селекта, str - выбранные оптионы (0||2||5)
function selectRow(id, str) {
	alert('selectRow');
	if (!str) str = '0';
	var a = Array();
	a = str.split("||");
	for (var i=0; i < a.length; i++){
		if ($(id).options[a[i]]) $(id).options[a[i]].selected = true;
	}
}

function selectRowByValue(id, value) {
	for (var i=0; i < $(id).options.length; i++){
		//alert($(id).options[i].value+' '+value);
		if ($(id).options[i].value == value) {
			//alert(id);
			
			//alert($(id).options[i].selected);
			$(id).options[i].selected = true;
			//return;
		}
	}
	/*if (!str) str = '0';
	var a = Array();
	a = str.split("||");
	for (var i=0; i < a.length; i++){
		if ($(id).options[a[i]]) $(id).options[a[i]].selected = true;
	}*/
}

function getSelected(id) {
	alert('getSelected');
	var arr = new Array();
	var obj = document.getElementById(id);
	var c = 0;
	for (var i=0; i<obj.options.length; i++) {
		if (obj.options[i].selected) {
			arr[c] = obj.options[i].value;
			c++;
		}
	}
	return arr;
}
