var defaultContainer='gMap2';
var defaultZaoom=14;
var googleMap={
 x: 0, y: 0, name: ''
}

var defaultYandexContainer='yMap';
var defaultYandexContainerPrefix='yMap_';
var defaultYandexZoom=15;
var yandexMap={
 x: 0, y: 0, name: '', zoom: 0
}

var noticePrefix='notice_';
var noticeSelected=[];
var noticeOver={};
var selectedClass="choosens";
var tablePrefix='page_';
var metroLoaded=false;
var winnerSFName='winnerSearchForm';

var mTable={};
var winnerSF;
var winnerSFInputs={};
var winnerSFInputSets={};

function showGoogleMap(x, y){
 if(!x||!y) return '';
 googleMap.x=x;
 googleMap.y=y;
 if(GBrowserIsCompatible()){
  googleMap.map = new GMap2(document.getElementById(defaultContainer));
  //googleMap.map.addControl(new GLargeMapControl());        
  //googleMap.map.addControl(new GMapTypeControl());
  //googleMap.map.enableContinuousZoom();
 }
 googleMap.map.setCenter(new GLatLng(googleMap.x, googleMap.y), defaultZoom);
 googleMap.map.addOverlay(new GMarker(new GLatLng(googleMap.x, googleMap.y)));
}

function showYandexMap(x, y, zoom){
 if(!x||!y) return '';
 zoom=zoom||defaultYandexZoom;
 yandexMap.x=x;
 yandexMap.y=y;
 yandexMap.zoom=zoom;
 yandexMap.zoom=defaultYandexZoom;
 yandexMap.map = new YMaps.Map( document.getElementById(defaultYandexContainer) );
 yandexMap.map.setCenter(new YMaps.GeoPoint(yandexMap.x, yandexMap.y), yandexMap.zoom, YMaps.MapType.MAP);
 var s = new YMaps.Style();
 s.iconStyle = new YMaps.IconStyle();
 s.iconStyle.offset = new YMaps.Point(-8, -28);
 s.iconStyle.href = "/images/metka.png";
 s.iconStyle.size = new YMaps.Point(27, 28);

 var atest=new YMaps.Placemark(new YMaps.GeoPoint(yandexMap.x, yandexMap.y), {style: s});
 yandexMap.map.addOverlay(atest);
}

function showYandexMapByBounds(leftBottom, rightTop){
 if(!leftBottom || !rightTop) return '';

 yandexMap.map = new YMaps.Map( document.getElementById(defaultYandexContainer) );

 var mBounds=new YMaps.GeoBounds(leftBottom, rightTop);
// yandexMap.map.setBounds(mBounds);
 var mCenter=mBounds.getCenter();
 yandexMap.x=mCenter.getLng();
 yandexMap.y=mCenter.getLat();
 yandexMap.zoom=mBounds.getMapZoom(yandexMap.map);
 if(yandexMap.zoom>defaultYandexZoom) yandexMap.zoom=defaultYandexZoom;
 yandexMap.zoom=defaultYandexZoom;

 yandexMap.map.setCenter(new YMaps.GeoPoint(yandexMap.x, yandexMap.y), yandexMap.zoom, YMaps.MapType.MAP);

 var s = new YMaps.Style();
 s.iconStyle = new YMaps.IconStyle();
 s.iconStyle.offset = new YMaps.Point(-8, -28);
 s.iconStyle.href = "/images/metka.png";
 s.iconStyle.size = new YMaps.Point(27, 28);

 var atest=new YMaps.Placemark(new YMaps.GeoPoint(yandexMap.x, yandexMap.y), {style: s});
 yandexMap.map.addOverlay(atest);
}

function showYandexMapByAddr(addr, obj){
 if(!addr) return '';
 if(typeof obj!="undefined") obj=$(obj);
 yandexMap.map = new YMaps.Map( document.getElementById(defaultYandexContainer) );
 var geocoder = new YMaps.Geocoder(addr, {results: 1});
 YMaps.Events.observe(geocoder, geocoder.Events.Load, function(){
  if(this.length()){
   geoResult = this.get(0);
//this command results in errors in ie...
//need more understanding. is this simply a point? o_o   yandexMap.map.addOverlay(geoResult);
   var mCenter=geoResult.getBounds().getCenter();
   yandexMap.x=mCenter.getLng();
   yandexMap.y=mCenter.getLat();
   yandexMap.zoom=geoResult.getBounds().getMapZoom(yandexMap.map);
   if(yandexMap.zoom>defaultYandexZoom) yandexMap.zoom=defaultYandexZoom;
   yandexMap.zoom=defaultYandexZoom;
   yandexMap.map.setCenter(new YMaps.GeoPoint(yandexMap.x, yandexMap.y), yandexMap.zoom, YMaps.MapType.MAP);
   var s = new YMaps.Style();
   s.iconStyle = new YMaps.IconStyle();
   s.iconStyle.offset = new YMaps.Point(-8, -28);
   s.iconStyle.href = "/images/metka.png";
   s.iconStyle.size = new YMaps.Point(27, 28);
   yandexMap.map.addOverlay(new YMaps.Placemark(mCenter, {style: s}));
   var x=yandexMap.x,y=yandexMap.y,zoom=yandexMap.zoom;
   saveGeocoderCache(addr, x, y, zoom);

   if(typeof obj=="undefined") return;

   obj.onmouseover=null;
   obj.stopObserving('mouseover');
   obj.observe('mouseover',
    function(event){
     overlib("<div id='yMap' style='width: 300px; height: 200px;'>&nbsp;</div>");
     showYandexMap(x, y, zoom);
     return false;
    });
  } else {
   if(typeof obj=="undefined") return;

   obj.onmouseover=null;
   obj.stopObserving('mouseover');
   nd();
   var text=obj.innerHTML;
   obj.parentNode.innerHTML=text;
//   document.getElementById(defaultYandexContainer).innerHTML="Адрес не найден на Яндекс.Картах";
  }
 });
}

function saveGeocoderCache(addr, x, y, zoom){
 var url='/scripts/ajax_geocoder_cache.php';
 zoom=zoom||defaultYandexZoom;
 var data=addr+':'+x+','+y+','+zoom;
 new Ajax.Request(url, {
  parameters: {data: data, action: 'save'},
  onSuccess: function(transport){
  }
 });
}

//on mouseover change tr style there and back
function ontrover(obj){
 obj=$(obj);
 noticeOver.className=obj.className;
 obj.className="hover1";
 var spans=obj.select("span");
 noticeOver.spClassName=spans[0].className;
 spans[0].className="";
 obj.stopObserving('mouseover');
 obj.onmouseover=null;
 obj.observe('mouseout', function(event){ontrout(this, event);});
}

function ontrout(obj, ev){
 var relTarg = ev.relatedTarget || ev.toElement;
 //browse through parents to find if we're still in #hover tr
 var checkLocation=false;
 if(relTarg!=null){
  var relTargParents=$(relTarg).ancestors();
  for(var i=0;i<relTargParents.length;i++){
   if(relTargParents[i].id==obj.id){
    checkLocation=true;
    break;
   }
  }
 }
 if(!checkLocation){
  obj.className=noticeOver.className;
  var spans=obj.select("span");
  spans[0].className=noticeOver.spClassName;
  obj.stopObserving('mouseout');
  obj.onmouseover=null;
  noticeOver={};
  obj.observe('mouseover', function(event){ontrover(obj);});
 }
}

function check_notice_new(obj, id, service, section_id, price_usd, price_rub, square, save2cookie){
	var obj=$(obj);
	var id=id||0;
	var service=service||'search';
	var section_id=section_id||1;
	
	var price_usd=price_usd||0;
	var price_rub=price_rub||0;
	var square=square||0;
	var save2cookie=save2cookie||false;

	if(!id) return false;
	
	if(service=='estimate'){
		var found=false;
		obj.up("tr").hide();
		if(save2cookie){
			var excluded=unescape(getCookie("excluded"));
			if(excluded){
				excluded=excluded.split(";");
				excluded.push(id);
			}
			else {
				excluded=[id];
			}
			setCookie("excluded", excluded.join(";"), 7);
		}
		else {
			save_notice_selection(id, 'add', service, section_id);
		}

		if(price_usd){
			if(average_prices["count"]["price_usd"]>1){
				average_prices["price_usd"]=Math.round((average_prices["price_usd"]*average_prices["count"]["price_usd"]-price_usd)/(average_prices["count"]["price_usd"]-1));
				average_prices["count"]["price_usd"]--;
//					$('average_price').innerHTML="$"+average_prices["price_usd"];
				if(square){
					var price_meter_usd=Math.round(price_usd/square);
					average_prices["price_meter_usd"]=Math.round((average_prices["price_meter_usd"]*average_prices["count"]["price_meter_usd"]-price_meter_usd)/(average_prices["count"]["price_meter_usd"]-1));
					average_prices["count"]["price_meter_usd"]--;
					$('average_meter_price').innerHTML="$ "+number_format(average_prices["price_meter_usd"], 0, ".", " ");
				}
			}
			else {
				average_prices["count"]["price_usd"]=0;
				average_prices["price_usd"]=0;
				average_prices["count"]["price_meter_usd"]=0;
				average_prices["price_meter_usd"]=0;
			}
//				$('average_price').innerHTML="$"+average_prices["price_usd"];
			$('average_meter_price').innerHTML="$ "+number_format(average_prices["price_meter_usd"], 0, ".", " ");
			if(average_prices["average_square"]){
				$('average_price').innerHTML="$ "+number_format(average_prices["price_meter_usd"]*average_prices["average_square"], 0, ".", " ");
			}
		}
/*		{
			obj.up("tr").removeClassName("unactive");
			if(save2cookie){
				var excluded=unescape(getCookie("excluded"));
				if(excluded){
					excluded=excluded.split(";");
					for(var i=0; i<excluded.length; i++){
						if(excluded[i]==id){
							excluded.splice(i, 1);
							break;
						}
					}
				}
				else {
					excluded=[];
				}
				setCookie("excluded", excluded.join(";"), 7);
			}
			else {
				save_notice_selection(id, 'remove', service, section_id);
			}
			
			if(price_usd){
				average_prices["price_usd"]=Math.round((average_prices["price_usd"]*average_prices["count"]["price_usd"]+price_usd)/(average_prices["count"]["price_usd"]+1));
				average_prices["count"]["price_usd"]++;
//				$('average_price').innerHTML="$"+average_prices["price_usd"];
				if(square){
					var price_meter_usd=Math.round(price_usd/square);
					average_prices["price_meter_usd"]=Math.round((average_prices["price_meter_usd"]*average_prices["count"]["price_meter_usd"]+price_meter_usd)/(average_prices["count"]["price_meter_usd"]+1));
					average_prices["count"]["price_meter_usd"]++;
					$('average_meter_price').innerHTML="$"+average_prices["price_meter_usd"];
				}
				if(average_prices["average_square"]){
					$('average_price').innerHTML="$"+average_prices["price_meter_usd"]*average_prices["average_square"];
				}
			}
		}
*/
	}
	else {
		var className=obj.className;
		var id=obj.id.substr(noticePrefix.length);
		var found=false;
		for(var i=0;i<noticeSelected.length;i++){
			if(noticeSelected[i].id==id){
				found=i;
				break;
			}
		}
		if(found===false){
			noticeSelected[noticeSelected.length]={id: id, cssclass: obj.className};
			//noticeOver.className=selectedClass;
			obj.className=selectedClass;
			save_notice_selection(id, 'add', service, section_id);
		}
		else {
			//noticeOver.className=noticeSelected[found].cssclass;
			obj.className=noticeSelected[found].cssclass;
			noticeSelected.splice(found, 1);
			save_notice_selection(id, 'remove', service, section_id);
		}
	}
}

function check_notice(obj, service, section_id, price_usd, price_rub, square, save2cookie){
	var obj=$(obj);
	var service=service||'search';
	var section_id=section_id||1;
	
	var price_usd=price_usd||0;
	var price_rub=price_rub||0;
	var square=square||0;
	var save2cookie=save2cookie||false;

	if(service=='estimate'){
		var id=obj.id.substr(6);
		var found=false;
		if(obj.checked){
			obj.up("tr").addClassName("unactive");
			if(save2cookie){
				var excluded=unescape(getCookie("excluded"));
				if(excluded){
					excluded=excluded.split(";");
					excluded.push(id);
				}
				else {
					excluded=[id];
				}
				setCookie("excluded", excluded.join(";"), 7);
			}
			else {
				save_notice_selection(id, 'add', service, section_id);
			}

			if(price_usd){
				if(average_prices["count"]["price_usd"]>1){
					average_prices["price_usd"]=Math.round((average_prices["price_usd"]*average_prices["count"]["price_usd"]-price_usd)/(average_prices["count"]["price_usd"]-1));
					average_prices["count"]["price_usd"]--;
//					$('average_price').innerHTML="$"+average_prices["price_usd"];
					if(square){
						var price_meter_usd=Math.round(price_usd/square);
						average_prices["price_meter_usd"]=Math.round((average_prices["price_meter_usd"]*average_prices["count"]["price_meter_usd"]-price_meter_usd)/(average_prices["count"]["price_meter_usd"]-1));
						average_prices["count"]["price_meter_usd"]--;
						$('average_meter_price').innerHTML="$"+average_prices["price_meter_usd"];
					}
				}
				else {
					average_prices["count"]["price_usd"]=0;
					average_prices["price_usd"]=0;
					average_prices["count"]["price_meter_usd"]=0;
					average_prices["price_meter_usd"]=0;
				}
//				$('average_price').innerHTML="$"+average_prices["price_usd"];
				$('average_meter_price').innerHTML="$"+average_prices["price_meter_usd"];
				if(average_prices["average_square"]){
					$('average_price').innerHTML="$"+average_prices["price_meter_usd"]*average_prices["average_square"];
				}
			}
		}
		else {
			obj.up("tr").removeClassName("unactive");
			if(save2cookie){
				var excluded=unescape(getCookie("excluded"));
				if(excluded){
					excluded=excluded.split(";");
					for(var i=0; i<excluded.length; i++){
						if(excluded[i]==id){
							excluded.splice(i, 1);
							break;
						}
					}
				}
				else {
					excluded=[];
				}
				setCookie("excluded", excluded.join(";"), 7);
			}
			else {
				save_notice_selection(id, 'remove', service, section_id);
			}
			
			if(price_usd){
				average_prices["price_usd"]=Math.round((average_prices["price_usd"]*average_prices["count"]["price_usd"]+price_usd)/(average_prices["count"]["price_usd"]+1));
				average_prices["count"]["price_usd"]++;
//				$('average_price').innerHTML="$"+average_prices["price_usd"];
				if(square){
					var price_meter_usd=Math.round(price_usd/square);
					average_prices["price_meter_usd"]=Math.round((average_prices["price_meter_usd"]*average_prices["count"]["price_meter_usd"]+price_meter_usd)/(average_prices["count"]["price_meter_usd"]+1));
					average_prices["count"]["price_meter_usd"]++;
					$('average_meter_price').innerHTML="$"+average_prices["price_meter_usd"];
				}
				if(average_prices["average_square"]){
					$('average_price').innerHTML="$"+average_prices["price_meter_usd"]*average_prices["average_square"];
				}
			}
		}
	}
	else {
		var className=obj.className;
		var id=obj.id.substr(noticePrefix.length);
		var found=false;
		for(var i=0;i<noticeSelected.length;i++){
			if(noticeSelected[i].id==id){
				found=i;
				break;
			}
		}
		if(found===false){
			noticeSelected[noticeSelected.length]={id: id, cssclass: obj.className};
			//noticeOver.className=selectedClass;
			obj.className=selectedClass;
			save_notice_selection(id, 'add', service, section_id);
		}
		else {
			//noticeOver.className=noticeSelected[found].cssclass;
			obj.className=noticeSelected[found].cssclass;
			noticeSelected.splice(found, 1);
			save_notice_selection(id, 'remove', service, section_id);
		}
	}
}

function save_notice_selection(id, action, service, section_id){
	AUTH_USER_ID=AUTH_USER_ID||0;
	var sid=getCookie('sid');
	var section_id=section_id||1;

	var page=mTable.id.substr(tablePrefix.length);
	var url='/scripts/ajax_notice_selection.php';
	new Ajax.Request(url, {
		parameters: {id: id, action: action, user: AUTH_USER_ID, sid: sid, page: page, service: service, section_id: section_id},
		onSuccess: function(transport){
			var aShowSelect=$('showselect');
			var aClearSelect=$('clearselect');
			var str, str1, parent;
			if(aShowSelect){ str=aShowSelect.innerHTML; parent=aShowSelect.parentNode; }
			if(aClearSelect){ str1=aClearSelect.innerHTML; parent=aClearSelect.parentNode; }
			var resp=transport.responseText.split(':');
			if(str) str=(resp[0]==1?"<a href='?lastsearch=1&select=1&service="+service+"' class='borderbottom' id='showselect'>"+str+"</a>":"<span id='showselect'>"+str+"</span>");
			else str='';
			if(str1) str1=(resp[0]==1||resp[1]==1?"<a href='#' onclick='clear_select(event, \""+service+"\", \""+section_id+"\");' class='borderbottom' id='clearselect'>"+str1+"</a>":"<span id='clearselect'>"+str1+"</span>");
			else str1='';
			parent.innerHTML=str+(str&&str1?"<br>":"")+str1;
		}
	});
}

function show_metro_map(){
 if(!metroLoaded){
  var content='';
  var url='/scripts/ajax_get_metro_map.php';
  if(typeof winnerSF!='undefined'){
   if(typeof winnerSF['metro']=='undefined'){
    var input=document.createElement('input');
    input.name='metro';
    input.value='';
    input.type="hidden";
    input.id='metroInput';
    winnerSF.appendChild(input);
   }
  }
  new Ajax.Request(url, {
   parameters: {},
   onSuccess: function(transport){
    var text=transport.responseText.split('-----------------------------------------------------------');
    alertbox.start(text[0], {type: 0, width: 800, height: 500, top: 160, type: 2});
    if(typeof text[1]!='undefined') eval(text[1]);
    metroLoaded=true;
   }
  });
 }
 else {
  alertbox.restart();
 }
 return false;
}

function buy_contact(id, event, section_id){
 event=event||window.event;
 Event.extend(event)
 event.stop();
 if(!AUTH_USER_ID) alertbox.start('Только зарегистрированные пользователи могут покупать контакты<br><br><a href="/registration/" class="all">Зарегистрироваться</a>');
 else {
  var id=id;
  var section_id=section_id||1;
  var url='/scripts/ajax_show_contact.php';
  new Ajax.Request(url, {
   parameters: {user: AUTH_USER_ID, id: id, section_id: section_id},
   onSuccess: function(transport){
    var params=transport.responseText.split(":");
    if(params[0]=='1'){
     nd();
     event.findElement('td').innerHTML=params[1].replace(',','<br>');
     $('user_balance').innerHTML=""+params[2]+"";
     var remark=params[3]||'';
     if(remark!=''){
      $('comment'+id).innerHTML="<a href='#' onclick='noaction(event);' onmouseover=\"return overlib('<div style=\\'margin: 5px; font-size: 11px; width: 250px;\\'>"+params[3].replace(/"/g, '&quot;').replace(/'/g, "\\'")+"</div>');\" onmouseout=\"return nd();\"><img src='/images/flat/info.png' alt='' title='' /></a>";
     }
    }
   }
  });
 }
}

function add_fav_notice(id, event, section_id){
 event=event||window.event;
 Event.extend(event)
 event.stop();
 if(!AUTH_USER_ID) alertbox.start('Только зарегистрированные пользователи могут добавлять предложения в избранное<br><br><a href="/registration/" class="all">Зарегистрироваться</a>');
 else {
  var id=id;
  var section_id=section_id||1;
  var url='/scripts/ajax_save_favorite_notice.php';
  new Ajax.Request(url, {
   parameters: {user: AUTH_USER_ID, id: id, section_id: section_id},
   onSuccess: function(transport){
    var params=transport.responseText.split(":");
    if(params[0]=='1'){
     nd();
//     event.findElement('td').innerHTML="<a href='#' onclick=\"rem_fav_notice("+id+", event, "+section_id+"); return false;\" onmouseover=\"overlib('<div style=\\'margin: 5px; font-size: 11px;\\'>Удалить вариант из Избранного</div>');\" onmouseout='return nd();'><img src='/images/fav1.png' border='0' /></a>";
     var alink=event.findElement('a');
     alink.href='#';
     alink.onclick=function(event){rem_fav_notice(id, event, section_id); return false;};
     alink.onmouseover=function(event){overlib("<div style='margin: 5px; font-size: 11px;'>Удалить вариант из Избранного</div>");};
     alink.onmouseout=function(event){return nd();};
     alink.innerHTML="<img src='/images/fav1.png' border='0' />";
    }
   }
  });
 }
}

function rem_fav_notice(id, event, section_id){
 event=event||window.event;
 Event.extend(event)
 event.stop();
 if(!AUTH_USER_ID) alertbox.start('Только зарегистрированные пользователи могут добавлять варианты в Избранное<br><br><a href="/registration/" class="all">Зарегистрироваться</a>');
 else {
  var id=id;
  var section_id=section_id||1;
  var url='/scripts/ajax_save_favorite_notice.php';
  new Ajax.Request(url, {
   parameters: {user: AUTH_USER_ID, id: id, remove: 1},
   onSuccess: function(transport){
    var params=transport.responseText.split(":");
    if(params[0]=='1'){
     nd();
//     event.findElement('td').innerHTML="<a href='#' onclick=\"add_fav_notice("+id+", event, "+section_id+"); return false;\" onmouseover=\"overlib('<div style=\\'margin: 5px; font-size: 11px;\\'>Добавить вариант в Избранное</div>');\" onmouseout='return nd();'><img src='/images/fav0.png' border='0' /></a>";
     var alink=event.findElement('a');
     alink.href='#';
     alink.onclick=function(event){add_fav_notice(id, event, section_id); return false;};
     alink.onmouseover=function(event){overlib("<div style='margin: 5px; font-size: 11px;'>Добавить вариант в Избранное</div>");};
     alink.onmouseout=function(event){return nd();};
     alink.innerHTML="<img src='/images/fav0.png' border='0' />";
    }
   }
  });
 }
}

function clear_select(e, service, section_id){
 e=e||window.event;
 service=service||'search';
 section_id=section_id||1;
//maybe temporary hack
 if(service=='estimate') document.location.href='/tools/cost-calculation/cost-calculation1.html?lastsearch=1&clearselect=1';
 Event.extend(e);
 e.stop();
 AUTH_USER_ID=AUTH_USER_ID||0;
 var sid=getCookie('sid');
 var url='/scripts/ajax_notice_selection.php';
 new Ajax.Request(url, {
  parameters: {action: 'clear', user: AUTH_USER_ID, sid: sid, service: service, section_id: section_id},
  onSuccess: function(transport){
   var aShowSelect=$('showselect');
   var aClearSelect=$('clearselect');
   var str, str1, parent;
   if(aShowSelect){ str=aShowSelect.innerHTML; parent=aShowSelect.parentNode; }
   if(aClearSelect){ str1=aClearSelect.innerHTML; parent=aClearSelect.parentNode; }
   if(transport.responseText=='1:0'||transport.responseText=='1:1'){
    parent.innerHTML=(str?"<span id='showselect'>"+str+"</span>":"")+(str&&str1?"<br>":"")+(str1?"<span id='clearselect'>"+str1+"</span>":"");
    for(var i=0;i<noticeSelected.length;i++){
     $(noticePrefix+noticeSelected[i].id).className=noticeSelected[i].cssclass;
    }
    noticeSelected=[];
   }
  }
 });
}

function card_request(user, id, section_id){
 var id=id;
 section_id=section_id||1;
 var text='<center><table width=344 cellpadding=0 cellspacing=0 border=0><tr><td width=56 align=left><image src=/netcat_files/126/139/h_6383d67a2dc7bce579876bb17ca039cd style="border: 1px #b6c5d1 solid;"></td><td width=288><div style="width: 288px; height: 50px; background:url(/images/req_note.gif);"><p class="f11" style="padding: 4px 0 0 28px; text-align: left;">В течение дня Вы получите консультацию и выгодные предложения от Совета экспертов по проверке и покупке этой квартиры.</p></div></td></tr></table><br>\
<form name=requestForm'+id+' method=post>\
<input type=hidden name=postRequest value=1/>\
<input type=hidden name=notice_ID value='+id+'/>\
<table celpadding=0 cellspacing=0 border=0 width=300>\
<tr><td width=50>&nbsp;</td><td width=200 align=left>Имя<br>\
<input type=text name=fio value="" class="largetext"><br><br>\
Телефон<br>\
<input type=text name=phone value="" class="largetext">\
</td><td width=50>&nbsp;</td></tr>\
<tr><td width=50>&nbsp;</td><td colspan=2 align=left>\
<br>Мне также нужно:<br>\
<table cellpadding=0 cellspacing=0 border=0 style="margin: 3px 0px 6px 0px;">\
<tr><td><input type=checkbox name=ipotec id=ipotec value=1 style="margin: 5px 3px 5px 0px;"></td><td><label for=ipotec>Подбор ипотечной программы</label></td></tr>\
<tr><td><input type=checkbox name=altbuy id=altbuy value=1 style="margin: 2px 3px 2px 0px;"></td><td><label for=altbuy>Организация альтернативной сделки</label></td></tr>\
</td></tr></table>\
</td></tr>\
</table>\
</form></center>\
<br>\
<input src="/images/send1.gif" id="yesButton" name="Ok" value="Ok" type="image"> <input src="/images/cancel_gray.gif" id="noButton" name="Отмена" value="Отмена" type="image">\
';
 alertbox.start(text, {width: 400, height: 240, type: 2});
 $('yesButton').observe('click', (function(e) {
  if(document.forms['requestForm'+id].fio.value!=''&&document.forms['requestForm'+id].phone.value!='') document.forms['requestForm'+id].submit();
 }));
 $('noButton').observe('click', (function(e) { alertbox.end(); }));
}

document.observe('dom:loaded', function(){
 var table=$$('table.muft');
 if(typeof table[0]!='undefined'){
  mTable=table[0];
  trSelected=mTable.getElementsBySelector("tr."+selectedClass);
  for(var i=0;i<trSelected.length;i++){
   var id=trSelected[i].id.substr(noticePrefix.length);
   var classNames=$w(trSelected[i].className);
   noticeSelected[noticeSelected.length]={id: id, cssclass: classNames[0]};
   trSelected[i].className=selectedClass;
  }
 }
//make form based on links
// winnerSF=$(winnerSFName);
 for(var i=0;i<document.forms.length;i++){
  if(document.forms[i].name==winnerSFName) winnerSF=document.forms[i];
 }
 if(typeof winnerSF!='undefined'){
  var inputs=$$('a[rel^=input]');
  for(var i=0;i<inputs.length;i++){
   var extInput=$(inputs[i]);
   var img=extInput.select("img");
   if(typeof img[0]!='undefined') img=img[0];
   var params=extInput.rel.split(":");
   if(typeof winnerSFInputs[params[1]]=='undefined'){
//global a:input array
//childs is a list of controls that must be unset when one of childs is clicked
//like sets, but sets are kinda global and are for multiple real inputs...???
    winnerSFInputs[params[1]]={value: 0, childs: new Array()};
//real input
    var input=document.createElement('input');
    input.name=params[1];
    input.id=params[1];
    input.value='';
    input.type="hidden";
    winnerSF.appendChild(input);
   }
//check a set
   if(typeof params[3]!='undefined'){
    if(params[3].substr(0, 3)=='set'&&typeof params[4]!='undefined'){
     if(typeof winnerSFInputSets[params[4]]=='undefined') winnerSFInputSets[params[4]]=new Array();
     winnerSFInputs[params[1]].fset=params[4];
     var newSetChild={};
     newSetChild.extInput=extInput;
     newSetChild.inputName=params[1];
     if(typeof img!='undefined') newSetChild.img=img;
     winnerSFInputSets[params[4]][winnerSFInputSets[params[4]].length]=newSetChild;
//list of inputs in set that this input ignore
     if(typeof params[5]!='undefined'){
      winnerSFInputs[params[1]].setIgnore=params[5].split(",");
     }
     else winnerSFInputs[params[1]].setIgnore=[];
    }
//check a switch
    else if(params[3]=='switch'){
    }
   }
//assign default value
   if(params[params.length-1]=='default'){
    winnerSFInputs[params[1]].value=params[2];
    $(params[1]).value=params[2];
   }
   if(typeof params[3]=='undefined') params[3]='';
//add a child
   var newChild={};
   newChild.extInput=extInput;
   newChild.value=params[2];
   if(typeof img!='undefined') newChild.img=img;
   newChild.add=params[3];
   winnerSFInputs[params[1]].childs[winnerSFInputs[params[1]].childs.length]=newChild;
  }
  for(input in winnerSFInputs){
   for(var i=0;i<winnerSFInputs[input].childs.length;i++){
    var child=winnerSFInputs[input].childs[i];
    var extInput=child.extInput;
    var src='';
    var img=child.img;
    if(typeof img.rel!='undefined'&&img.rel) src=img.rel;
    else src=img.src.substr(0, img.src.length-5);

    simplePreloadIMG(src+'1.png');
    simplePreloadIMG(src+'2.png');
    simplePreloadIMG(src+'3.png');
    (function(img, src, input, val, childs, param){
     if(param=='noselect'){
      extInput.observe('mouseover', function(event){
       img.src=src+'1.png';
       fixPNG(img);
      });
      extInput.observe('mouseout', function(event){
       img.src=src+'3.png';
       fixPNG(img);
      });
      extInput.observe('mousedown', function(event){
       img.src=src+'2.png';
       fixPNG(img);
      });
      extInput.observe('mouseup', function(event){
       img.src=src+'1.png';
       fixPNG(img);
      });
     }
     else if(param=='switch'){
      extInput.observe('mouseover', function(event){
       if(winnerSF[input].value==val) img.src=src+'2.png';
       else img.src=src+'1.png';
       fixPNG(img);
      });
      extInput.observe('mouseout', function(event){
       if(winnerSF[input].value==val) img.src=src+'2.png';
       else img.src=src+'3.png';
       fixPNG(img);
      });
      extInput.observe('click', function(event){
//we assume switch is single, so no unchecking childs
//check or uncheck selected input
       if(winnerSF[input].value==val){
        img.src=src+'3.png';
        fixPNG(img);
        $(input).value=0;
       }
       else {
        img.src=src+'2.png';
        fixPNG(img);
        $(input).value=val;
       }
      });
     }
     else {
      extInput.observe('mouseover', function(event){
       if(winnerSF[input].value==val) img.src=src+'2.png';
       else img.src=src+'1.png';
       fixPNG(img);
      });
      extInput.observe('mouseout', function(event){
       if(winnerSF[input].value==val) img.src=src+'2.png';
       else img.src=src+'3.png';
       fixPNG(img);
      });
      extInput.observe('click', function(event){
//uncheck all childs
       for(var i=0;i<childs.length;i++){
        if(typeof childs[i].img.rel!='undefined'&&childs[i].img.rel) tsrc=childs[i].img.rel;
        else tsrc=childs[i].img.src.substr(0, childs[i].img.src.length-5);
        childs[i].img.src=tsrc+'3.png';
        fixPNG(childs[i].img);
       }
//uncheck set if there is
       if(param=='set'&&typeof winnerSFInputs[input].fset!='undefined'){
        var mset=winnerSFInputSets[winnerSFInputs[input].fset];
        for(var i=0;i<mset.length;i++){
         if(!in_array(mset[i].inputName, winnerSFInputs[input].setIgnore)){
          if(typeof mset[i].img.rel!='undefined'&&mset[i].img.rel) tsrc=mset[i].img.rel;
          else tsrc=mset[i].img.src.substr(0, mset[i].img.src.length-5);
          mset[i].img.src=tsrc+'3.png';
          fixPNG(mset[i].img);
          $(mset[i].inputName).value='';
         }
        }
       }
//check selected input
       img.src=src+'2.png';
       fixPNG(img);
       $(input).value=val;
      });
     }
    })(img, src, input, child.value, winnerSFInputs[input].childs, child.add);
   }
  }
 }
});
//single card functions
var page_bookmarks=[];

function prepare_bookmarks(parent){
 var parent=parent||document.documentElement;
 var ps=$(parent).select('p');
 for(var i=0;i<ps.length;i++){
  if(ps[i].id.substr(0, 9)=='bookmark_'){
   var name, text, alink;
   name=ps[i].id.substr(9);
   if($(ps[i]).firstDescendant()) text=$(ps[i]).firstDescendant().innerHTML;
   else text=$(ps[i]).innerHTML;
   page_bookmarks[page_bookmarks.length]={name: name, text: text};
   if(alink=$(ps[i]).firstDescendant()){
    (function(name, text, alink){
     alink.onclick=function(){
      change_view(name);
      eval('glns.show_'+name+'();');
      return false;
     }
    })(name, text, alink);
   }
  }
 }
}

var glns={};

function change_view(view){
 for(var i=0;i<page_bookmarks.length;i++){
  var pbi=page_bookmarks[i];
  var td=$($('bookmark_'+pbi.name).parentNode);
  if(pbi.name==view){
   td.className='bg_zakl';
   td.next('td').className='';
   td.previous('td').className='';
   td.innerHTML="<p id='bookmark_"+pbi.name+"' class='h21'>"+pbi.text+"</p>";
  }
  else {
   td.className='bg_zakl borb text_zakl_pad';
   td.next('td').className='borb';
   td.previous('td').className='borb';
   td.innerHTML="<p id='bookmark_"+pbi.name+"'><a href='#' class='h21'>"+pbi.text+"</a></p>";
   (function(name, text, alink){
    alink.onclick=function(){
     change_view(name);
     eval('glns.show_'+name+'();');
     return false;
    }
   })(pbi.name, pbi.text, td.firstDescendant().firstDescendant());
  }
 }
}

function buy_contact_full(id, event, section_id){
 event=event||window.event;
 Event.extend(event)
 event.stop();
 if(!AUTH_USER_ID) alertbox.start('Только зарегистрированные пользователи могут покупать контакты<br><br><a href="/registration/" class="all">Зарегистрироваться</a>');
 else {
  var id=id;
  var section_id=section_id||1;
  var url='/scripts/ajax_show_contact.php';
  new Ajax.Request(url, {
   parameters: {user: AUTH_USER_ID, id: id, section_id: section_id},
   onSuccess: function(transport){
    var params=transport.responseText.split(":");
    if(params[0]=='1'){
     nd();
     $$('a.buy_link').each(function(obj){obj.parentNode.removeChild(obj);});
     $('user_balance').innerHTML=""+params[2]+"";
     var phone=params[1]||'';
     var remark=params[3]||'';
     var agency=params[4]||'';
     $('contact_info').innerHTML=''+remark+'';
     $('contact_info1').innerHTML=''+(agency!=''?'Агентство: '+agency+'<br><br>':'')+'Телефон: '+phone.replace(',', ', ');
     $('contact_info1_h').innerHTML='Контакты';
    }
   }
  });
 }
}

//для добавления адресов картинок в форму заявки виннера
function f_upload_string(_src, _dest, _list, _etarget, _name){
 _etarget.disabled=true;

 if(!_src){
  _etarget.disabled=false;
  return false;
 }
 var src;
 if(typeof _src=="string") src=_src;
 else src=$(_src).value;
 var dest=$(_dest);
 var list=$(_list);
 if(src==''){
  _etarget.disabled=false;
  return false;
 }
 if(dest.value=='') dest.value=src;
 else dest.value+=";"+src;

 var new_item=document.createElement("P");

 var newlink=document.createElement("A");
 newlink.href=src;
 newlink.target="_blank";

 var name=_name||src.substr(src.lastIndexOf('/')+1);
 newlink.innerHTML=name;
 new_item.appendChild(newlink);
 new_item.appendChild(document.createTextNode("  --  "));

 var dellink=document.createElement("A");
 dellink.href="#";
 dellink.innerHTML="Удалить";
 new_item.appendChild(dellink);

 list.appendChild(new_item);
//вешаем обработчик на ссылку удаления
 (function(obj, item, dest, str){
  obj.onclick=function(){
   return f_remove_string(item, dest, str);
  }
 })(dellink, new_item, dest, src);

 _etarget.disabled=false;
 return true;
}

function f_remove_string(item, dest, str){
   item.parentNode.removeChild(item);

   var arr=dest.value.split(";");
   for(var i=0; i<arr.length; i++){
    if(arr[i]==str){
     arr.splice(i, 1);
     break;
    }
   }
   dest.value=arr.join(";");
   return false;
}

function f_upload_file(_src, _dest, _list, _etarget, _form){
 var src=$(_src);
 if(!_src.value) return false;

 var args=[_src, _dest, _list, _etarget];
 _etarget.disabled=true;

 sendForm(_form,'/scripts/winner_upload.php', f_upload_file_complete, args);
}


function f_upload_file_complete(args, doc, final){
 var final=final||false;
 if(!doc){
  if(final){
   args[3].disabled=false;
   return false;
  }
//try fetch data with ajax
  else {
   var url='/scripts/winner_upload.php';
   var args=args;

   new Ajax.Request(url, {
    parameters: {filename: args[0].value, iframe_id: args[4]},
    onSuccess: function(transport){
     f_upload_file_complete(args, transport.responseText, 1);
    }
   });
  }
 }
 var text;

// text=doc.documentElement.firstChild.nodeValue.split('@');
 text=doc.body.innerHTML.split('@');

 var addr=text[0];
 var name=text[1]||'';
 f_upload_string(addr, args[1], args[2], args[3], name);
}


document.observe('dom:loaded', function(){
 if($('bookmark_heads')){
  prepare_bookmarks($('bookmark_heads'));
 }
});
