function manageEvent (eventObj, event, eventHandler) {
	if (eventObj.addEventListener) {
		eventObj.addEventListener(event, eventHandler, false);
	} else if (eventObj.attachEvent) {
		event = "on" + event;
		eventObj.attachEvent(event, eventHandler);
	}
}

var heightObjs = new Array();

function setHeight(objName) {
	var obj = document.getElementById(objName);
	if(obj.clientHeight) {
		var height = obj.clientHeight;
		heightObjs[objName] = height;
	}
	obj.style.height = "0";
}

/*
manageEvent(window, "load", function() {
	
	setHeight('one');

	document.getElementById('oneplus').style.display = 'block';
});*/

function expand(newItem) {
	document.getElementById(newItem + 'plus').style.display='none';
	document.getElementById(newItem + 'negative').style.display = 'block';
	var currentItem = document.getElementById(newItem);
	
	var incr = heightObjs[newItem] / 10;
	for (var i=0; i<10; i++) {
		var val = (i+1) * incr;
		var func = "adjustItem("+val+",'"+newItem+"')";
		setTimeout(func,(i+1)*20);
	}
}

function collapse (newItem) {
	document.getElementById(newItem + 'plus').style.display = 'block';
	document.getElementById(newItem + 'negative').style.display = 'none';
	var currentItem = document.getElementById(newItem);
	
	var decr = heightObjs[newItem] / 10;
	for (var i=0; i<10; i++) {
		var val = heightObjs[newItem]-(decr*(i+1));
		var func = "adjustItem("+val+",'"+newItem+"')";
		setTimeout(func,(i+1)*20);
	}
}

function adjustItem(val, newItem) {
	document.getElementById(newItem).style.height = val+"px";
}

function build_geo(current_name,child_name,def_text)
{
	var data = new Object();
	var current = $('#' + current_name);
	var child = $('#' + child_name);
	
	if (current_name == 'country') {
		$("#cities").empty();
		$("#cities").attr('disabled', true);
		
		if (current.val() == 0) {
			$('#regions').empty();
			$('#regions').attr('disabled', true);
		} else {
			$('#regions').attr('disabled', false);
		}
	}

	if(current_name == 'regions') {
		if (current.val() == 0) {
			$('#cities').empty();
			$('#cities').attr('disabled', true);
		} else {
			$('#cities').attr('disabled', false);
		}		
	}
	
	if (current.val() == 0)
		return false;
	
	
	$.ajax({type:       "POST",
			url:        "/ajax/"+child_name+"/"+current.val(),
			data:       {data: encodeURIComponent(JSON.stringify(data))},
			dataType:   'json',
			error:      function() {
				alert("Internal error occured!");
			},
			success:    function (data) {								
				child.empty();
				$("<option></option>")
					.attr("value", "0")
					.html(def_text)
					.appendTo(child);
				child.attr('disabled', false);
				for (i=0;i<data.length;i++) {
					$("<option></option>")  
					.attr("value", data[i]['id'])
					.html(data[i]['name']) 
					.appendTo(child);
				}
				child.change();
			}	
	});
	
	
}


function getChildOptions (parid, childid, foption) {
	var data = new Object();
	var num = document.getElementById(parid);
	var child = document.getElementById(childid);
	var clrcr = $(".rc_ch");
	$.ajax({type:       "POST",
			url:        "/ajax/"+childid+"/"+num.value,
			data:       {data: encodeURIComponent(JSON.stringify(data))},
			dataType:   'json',
			error:      function() {
				alert("Internal error occured!");
			},
			success:    function (data) {
				if (parid == 'contry') {
					$("#cities").empty();
					citi = document.getElementById('cities');
					if(citi)
						citi.disabled = true;
					if (num.value == 0) {
						document.getElementById('regions').disabled = true;
					} else {
						document.getElementById('regions').disabled = false;
					}
				}									
				$("#"+childid).empty();
				$("<option></option>")
					.attr("value", "0")
					.html(foption)
					.appendTo(child);
				child.disabled = false;
				for (i=0;i<data.length;i++) {
					$("<option></option>")  // создаем требуемый элемент
					.attr("value", data[i]['id'])     // устанавливаем значение одного из его атрибутов
					.html(data[i]['name']) // записываем в него текст
					.appendTo(child);
				}
			}	
	});
}


var exp = 0;
function expand_serach() {
	var link = $('expLink');
	if (exp == 0) {
		if (new Effect.BlindDown('expandedForm')) {
			exp = 1;
		}
	} else {
		link.innerHTML = '<span style="display:block;text-align:center;padding:5px 10px;color:#121617;text-decoration:none;">Pасширенный поиск</span>';
		new Effect.BlindUp('expandedForm');
		exp = 0;
		link.innerHTML = '<a href="#" title="Открыть расширенный поиск" style="display:block;text-align:center;padding:5px 10px;color:#121617;text-decoration:none;" onclick="expand_serach();return false">Pасширенный поиск</a>';
	}
}


function wopen(url,w,h,r,s,st){
          var w=window.open(url,'',"width="+w+",height="+h+",resizable="+r+",toolbar=0,location=0,status="+st+",menubar=0,directories=0,scrollbars="+s);
}


img1 = new Image(16, 16);  
img1.src="/media/img/spinner.gif";

img2 = new Image(220, 19);  
img2.src="/media/img/ajax-loader.gif";


$(function () {

    $('#map_tab').click(function () {
        $('#object_card_photo').hide(); 
        $('#map_canvas').show();
		$('#AllPhotos').hide();
		$('#BigMap').show();        
        $('#photo_tab').removeClass('selected'); 
        $(this).addClass('selected');         
        show_map();
        return false;
    });
    
    $('#photo_tab').click(function () {
        $('#map_canvas').hide(); 
        $('#object_card_photo').show();
		$('#AllPhotos').show();
		$('#BigMap').hide();
        $('#map_tab').removeClass('selected'); 
        $(this).addClass('selected'); 
        return false;
    });
    
    
    $("#login_link").click(function(){
		$('#login_form').modal();
	});
	
	
	$("#status > form").submit(function(){  
		$('#login_submit').hide();
		$('#ajax_loading').show();
		var str = $(this).serialize();  
		$.ajax({  
    		type: "POST",
    		url: "/user/login",  // Send the login info to this page
    		data: str,  
    		success: function(msg){  
   				$("#status").ajaxComplete(function(event, request, settings){  
 					$('#login_submit').show();
					$('#ajax_loading').hide();  
					if(msg == 'OK') // LOGIN OK?
 					{  
 						var login_response = '<div>' +
	 						'<img style="margin: 10px auto;" src="/media/img/ajax-loader.gif">' +
	 						'<p style="text-align:center">'+ 
	 						 "Вы успешно вошли! <br /> Пожалуйста, подождите несколько секунд...</p></div>";  
						$('a.modalCloseImg').hide();  
						$(this).html(login_response); // Refers to 'status'
						setTimeout('window.location.reload()', 3000); 
 					} else {  
 						var login_response = msg;
 						$('#login_response').html(login_response);
 					}        
 				});     
 			}     
  		});  
	return false;
	});
});
    


    var map = null;
    var geocoder = null;
 
    function map_initialize() {
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
        map.clearOverlays();
        //map.setCenter(new GLatLng(37.4419, -122.1419), 13);
        geocoder = new GClientGeocoder();
 
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
 
      }
    }
 
    function showAddress(address) {
      if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
              alert("АДРЕС НЕ НАЙДЕН!");
            } else {
              map.setCenter(point, 13);
              var marker = new GMarker(point);
              map.addOverlay(marker);
           //   marker.openInfoWindowHtml(address);
            }
          }
        );
      }
    };
    
    
    
    var arrowimages={down:['downarrowclass', 'down.gif', 23], right:['rightarrowclass', 'right.gif']}

    var jqueryslidemenu={

    animateduration: {over: 150, out: 100},

    buildmenu:function(menuid, arrowsvar, type){
    	jQuery(document).ready(function($){
    		var $mainmenu=$("#"+menuid+">ul")
    		var $headers=$mainmenu.find("ul").parent()
    		$headers.each(function(i){
    			var $curobj=$(this)
    			var $subul=$(this).find('ul:eq(0)')
    			this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()}
    			this.istopheader=$curobj.parents("ul").length==1? true : false
    			$subul.css({left:this.istopheader? this._dimensions.w+"px" : 0})


    			

    			$curobj.hover(
    				function(e){
    					var $lala=$(this)
    					var $targetul=$(this).children("ul:eq(0)")
    					this._offsets={left:$(this).offset().left, top:$(this).offset().top}

    					$lala.css({})

    					if (type==2)
    					{
    					var menuleft=this._dimensions.w
    					$targetul.css({top:"0px"})
    					}
    					else
    					{
    					var menuleft=this.istopheader? 0 : this._dimensions.w
    					}

    					menuleft=(this._offsets.left+menuleft+this._dimensions.subulw>$(window).width())? (this.istopheader? -this._dimensions.subulw+this._dimensions.w : -this._dimensions.w) : menuleft
    					$targetul.css({left:menuleft+"px",width:this._dimensions.subulw+'px'}).slideDown(jqueryslidemenu.animateduration.over)

    				},
    				function(e){

    					var $targetul=$(this).children("ul:eq(0)")
    					$targetul.slideUp(jqueryslidemenu.animateduration.out)
    				}
    			)
    		})
    		$mainmenu.find("ul").css({display:'none', visibility:'visible'})
    	})
    }
    }

//build menu with ID="myslidemenu" on page:
jqueryslidemenu.buildmenu("menu", arrowimages,1);