var map, placemark, new_placemark, placemarks = [], marker_style = [], markers = []
    ,objects= [], layers_status = {  object: true, landmark: true
                                    , air: false, rail:false }
    ,map_observ, zoom_after_search = false, last_open_id ;

function markersStyles() {

    // markers styles

    var s = new YMaps.Style();
    s.iconStyle = new YMaps.IconStyle("markers#flat");
    s.iconStyle.templateURL="markers#customPoint";
    s.iconStyle.offset=new YMaps.Point(-19, -40);
    s.iconStyle.href="/images/markers_dom.png";
    s.iconStyle.size=new YMaps.Point(38, 40);
    YMaps.Styles.add("markers#flat", s);

    var t = new YMaps.Template();
    t.text = "<div><img alt=\"$[m_name|0]\" style=\"height:$[style.iconStyle.size.y];width:$[style.iconStyle.size.x];\" \n\
src=\"$[style.iconStyle.href]\"\/>&nbsp;</div>";
    YMaps.Templates.add("markers#flat", t);

    marker_style['flat'] = s; // flat

    var s = new YMaps.Style();
    s.iconStyle = new YMaps.IconStyle("markers#flat_l");
    s.iconStyle.templateURL="markers#customPoint";
    s.iconStyle.offset=new YMaps.Point(-19, -40);
    s.iconStyle.href="/images/markers_dom_l.png";
    s.iconStyle.size=new YMaps.Point(38, 40);
    YMaps.Styles.add("markers#flat_l", s);

    var t = new YMaps.Template();
    t.text = "<div><img alt=\"$[m_name|0]\" style=\"height:$[style.iconStyle.size.y];width:$[style.iconStyle.size.x];\" \n\
src=\"$[style.iconStyle.href]\"\/>&nbsp;</div>";
    YMaps.Templates.add("markers#flat_l", t);

    marker_style['flat_l'] = s; // Locator flat

    var s = new YMaps.Style();
    s.iconStyle = new YMaps.IconStyle("markers#hotel");
    s.iconStyle.templateURL="markers#customPoint";
    s.iconStyle.offset=new YMaps.Point(-19, -40);
    s.iconStyle.href="/images/markers_hotel.png";
    s.iconStyle.size=new YMaps.Point(38, 40);
    YMaps.Styles.add("markers#hotel", s);

    var t = new YMaps.Template();
    t.text = "<div><img alt=\"$[m_name|0]\" style=\"height:$[style.iconStyle.size.y];width:$[style.iconStyle.size.x];\" \n\
src=\"$[style.iconStyle.href]\"\/>&nbsp;</div>";
    YMaps.Templates.add("markers#hotel", t);

    marker_style['hotel'] = s; // hotel

    var s = new YMaps.Style();
    s.iconStyle = new YMaps.IconStyle("markers#hotel_l");
    s.iconStyle.templateURL="markers#customPoint";
    s.iconStyle.offset=new YMaps.Point(-19, -40);
    s.iconStyle.href="/images/markers_hotel_l.png";
    s.iconStyle.size=new YMaps.Point(38, 40);
    YMaps.Styles.add("markers#hotel_l", s);

    var t = new YMaps.Template();
    t.text = "<div><img alt=\"$[m_name|0]\" style=\"height:$[style.iconStyle.size.y];width:$[style.iconStyle.size.x];\" \n\
src=\"$[style.iconStyle.href]\"\/>&nbsp;</div>";
    YMaps.Templates.add("markers#hotel_l", t);

    marker_style['hotel_l'] = s; // Locator hotel

    var s = new YMaps.Style();
    s.iconStyle = new YMaps.IconStyle("markers#hostel");
    s.iconStyle.templateURL="markers#customPoint";
    s.iconStyle.offset=new YMaps.Point(-19, -40);
    s.iconStyle.href="/images/markers_hostel.png";
    s.iconStyle.size=new YMaps.Point(38, 40);
    YMaps.Styles.add("markers#hostel", s);

    var t = new YMaps.Template();
    t.text = "<div><img alt=\"$[m_name|0]\" style=\"height:$[style.iconStyle.size.y];width:$[style.iconStyle.size.x];\" \n\
src=\"$[style.iconStyle.href]\"\/>&nbsp;</div>";
    YMaps.Templates.add("markers#hostel", t);

    marker_style['hostel'] = s; // hostel

    var s = new YMaps.Style();
    s.iconStyle = new YMaps.IconStyle("markers#hostel_l");
    s.iconStyle.templateURL="markers#customPoint";
    s.iconStyle.offset=new YMaps.Point(-19, -40);
    s.iconStyle.href="/images/markers_hostel_l.png";
    s.iconStyle.size=new YMaps.Point(38, 40);
    YMaps.Styles.add("markers#hostel_l", s);

    var t = new YMaps.Template();
    t.text = "<div><img alt=\"$[m_name|0]\" style=\"height:$[style.iconStyle.size.y];width:$[style.iconStyle.size.x];\" \n\
src=\"$[style.iconStyle.href]\"\/>&nbsp;</div>";
    YMaps.Templates.add("markers#hostel_l", t);

    marker_style['hostel_l'] = s; // Locator hostel

    var s = new YMaps.Style();
    s.iconStyle = new YMaps.IconStyle("markers#house");
    s.iconStyle.templateURL="markers#customPoint";
    s.iconStyle.offset=new YMaps.Point(-19, -40);
    s.iconStyle.href="/images/markers_cottage.png";
    s.iconStyle.size=new YMaps.Point(38, 40);
    YMaps.Styles.add("markers#house", s);

    var t = new YMaps.Template();
    t.text = "<div><img alt=\"$[m_name|0]\" style=\"height:$[style.iconStyle.size.y];width:$[style.iconStyle.size.x];\" \n\
src=\"$[style.iconStyle.href]\"\/>&nbsp;</div>";
    YMaps.Templates.add("markers#house", t);

    marker_style['house'] = s; // cottage

    var s = new YMaps.Style();
    s.iconStyle = new YMaps.IconStyle("markers#house_l");
    s.iconStyle.templateURL="markers#customPoint";
    s.iconStyle.offset=new YMaps.Point(-19, -40);
    s.iconStyle.href="/images/markers_cottage_l.png";
    s.iconStyle.size=new YMaps.Point(38, 40);
    YMaps.Styles.add("markers#house_l", s);

    var t = new YMaps.Template();
    t.text = "<div><img alt=\"$[m_name|0]\" style=\"height:$[style.iconStyle.size.y];width:$[style.iconStyle.size.x];\" \n\
src=\"$[style.iconStyle.href]\"\/>&nbsp;</div>";
    YMaps.Templates.add("markers#house_l", t);

    marker_style['house_l'] = s; // Locator cottage

    var s = new YMaps.Style();
    s.iconStyle = new YMaps.IconStyle("markers#landmark");
    s.iconStyle.templateURL="markers#customPoint";
    s.iconStyle.offset=new YMaps.Point(-19, -40);
    s.iconStyle.href="/images/markers_orient.png";
    s.iconStyle.size=new YMaps.Point(38, 40);
    YMaps.Styles.add("markers#landmark", s);

    var t = new YMaps.Template();
    t.text = "<div><img alt=\"$[m_name|0]\" style=\"height:$[style.iconStyle.size.y];width:$[style.iconStyle.size.x];\" \n\
src=\"$[style.iconStyle.href]\"\/>&nbsp;</div>";
    YMaps.Templates.add("markers#landmark", t);

    marker_style['landmark'] = s; // landmark

    var s = new YMaps.Style();
    s.iconStyle = new YMaps.IconStyle("markers#air");
    s.iconStyle.templateURL="markers#customPoint";
    s.iconStyle.offset=new YMaps.Point(-19, -40);
    s.iconStyle.href="/images/markers_air.png";
    s.iconStyle.size=new YMaps.Point(38, 40);
    YMaps.Styles.add("markers#rail", s);

    var t = new YMaps.Template();
    t.text = "<div><img alt=\"$[m_name|0]\" style=\"height:$[style.iconStyle.size.y];width:$[style.iconStyle.size.x];\"\n\ \n\
src=\"$[style.iconStyle.href]\"\/>&nbsp;</div>";
    YMaps.Templates.add("markers#air", t);

    marker_style['air'] = s; // air

    var s = new YMaps.Style();
    s.iconStyle = new YMaps.IconStyle("markers#rail");
    s.iconStyle.templateURL="markers#customPoint";
    s.iconStyle.offset=new YMaps.Point(-19, -40);
    s.iconStyle.href="/images/markers_zhd.png";
    s.iconStyle.size=new YMaps.Point(38, 40);
    YMaps.Styles.add("markers#rail", s);

    var t = new YMaps.Template();
    t.text = "<div><img alt=\"$[m_name|0]\" style=\"height:$[style.iconStyle.size.y];width:$[style.iconStyle.size.x];\" \n\
src=\"$[style.iconStyle.href]\"\/>&nbsp;</div>";
    YMaps.Templates.add("markers#rail", t);

    marker_style['rail'] = s; // rail

}

function loadMarkers() {

    var bounds = map.getBounds(),
        edgeT = bounds.getTop(),
        edgeR = bounds.getRight(),
        edgeB = bounds.getBottom(),
        edgeL = bounds.getLeft();
/*
	if( map.getBalloon() !== undefined ) {  // has opened balloon
		for(i in placemarks){  		
			if(placemarks[i].m_id != last_open_id)
				map.removeOverlay(placemarks[i]); 
		}
	
	} else {
		
		for(i in placemarks){  		
				map.removeOverlay(placemarks[i]); 
		}
	
	}
*/	
//  placemark = null, 
//	placemarks = [], 
	markers = [], objects = [];

    params = { filter: '', edgeT: edgeT, edgeR: edgeR, edgeB: edgeB, edgeL: edgeL };

    $.getJSON('/?task=ajax&action=map_markers_json&sort_by='+ ( $('#sortBy').val() ? $('#sortBy').val() : 'name' ) + '&'
                                                            + $('form[name=searchForm]').serialize()
                , params , function (data){ 
                    showMarkers(data); 
                });

}

function loadMarkersByMap( open_obj_id ) {

    open_obj_id = open_obj_id!=undefined ? open_obj_id : 0;

    var bounds = map.getBounds(),
        edgeT = bounds.getTop(),
        edgeR = bounds.getRight(),
        edgeB = bounds.getBottom(),
        edgeL = bounds.getLeft();


/*
	if( map.getBalloon() !== undefined ) {  // has opened balloon		

		for(i in placemarks){  		
			if(placemarks[i].m_id != last_open_id)
				map.removeOverlay(placemarks[i]); 
		}
	
	} else {
		
		for(i in placemarks){  		
				map.removeOverlay(placemarks[i]); 
		}
	
	}
*/
//    placemark = null, placemarks = [], 
	markers = [], objects = [];

    params = { filter: '', edgeT: edgeT, edgeR: edgeR, edgeB: edgeB, edgeL: edgeL };

    $.getJSON('/?task=ajax&action=map_markers_json'
                , params , function (data){

                    showMarkers(data);

                    if(open_obj_id) {
                        showHotelBalloon(open_obj_id);
                        showHotelDescription(open_obj_id);
                    }

                });

}

function switchLayer(layer_name) {

    if(layers_status[layer_name]) {

        for(i in placemarks){
            if(placemarks[i].m_layer == layer_name)
                map.removeOverlay(placemarks[i]);
        }

    } else {

        for(i in placemarks){
            if(placemarks[i].m_layer == layer_name)
                map.addOverlay(placemarks[i]);
        }

    }

    layers_status[layer_name] = !layers_status[layer_name];

}

function showHotelBalloon( obj_id ) {

    if(obj_id == undefined) return false;

    for(i in placemarks) {

        if(placemarks[i].m_layer == 'object' && placemarks[i].m_id == obj_id) {

            map.setCenter( new YMaps.GeoPoint(placemarks[i].m_lng-0.0007, placemarks[i].m_lat) , 20);

            placemark = placemarks[i];
            placemark.setBalloonContent('<img src="/images/loading.gif"/>');
            placemark.openBalloon();

            $.get('?task=ajax&action=obj_marker_content&id=' + placemark.m_id, function(text){
                placemark.setBalloonContent(text);
            });
        }
    }

    return false;
}

function showMarkers(json) {

    var marker;
    var bounds = [];
    
    for(i in json['objects']) {

        marker = json['objects'][i];

//        x = placemarks.length;
		x = marker.id;
		if(placemarks[x] != undefined ) continue;

        var obj_style = marker.type + (marker.is_locator==1 ? '_l' : '');

        placemarks[x] = new YMaps.Placemark( new YMaps.GeoPoint(marker.lng, marker.lat)
											, {style: marker_style[obj_style], hasHint: true} );
        placemarks[x].id = x;
        placemarks[x].m_id = marker.id;
        placemarks[x].m_layer = 'object';
        placemarks[x].m_type = marker.type;
        placemarks[x].m_lat = marker.lat;
        placemarks[x].m_lng = marker.lng;
        placemarks[x].m_name = marker.name;
        placemarks[x].m_is_locator = marker.is_locator;
        placemarks[x].setHintContent(marker.name);
		

        YMaps.Events.observe(placemarks[x], placemarks[x].Events.Click, function () {

            if(this.m_id == undefined) return false;
            
            this.setBalloonContent('<img src="/images/loading.gif"/>');
            placemark = this;
			last_open_id = this.m_id;
            
            $.get('?task=ajax&action=obj_marker_content&id=' + this.m_id, function(text){
                placemark.setBalloonContent(text);
            });

        });

        if(marker.lat && marker.lng)
            bounds.push( new YMaps.GeoPoint(marker.lng, marker.lat) );

        if( layers_status[placemarks[x].m_layer] ) {
            map.addOverlay(placemarks[x]);
        }
    }

/*
    if( zoom_after_search ) {

        if( bounds.length ) {

            var obj_bounds = new YMaps.GeoCollectionBounds( bounds );
            var new_zoom = obj_bounds.getMapZoom(map);
            map.setCenter( obj_bounds.getCenter(map), new_zoom < 14 ? new_zoom : 14 );

        }

        zoom_after_search = false;
    }
*/
    for(i in json['markers']) {
        var marker_list = json['markers'][i];

        for(j in marker_list) {

            marker = marker_list[j];

//            x = placemarks.length;
			x = marker.id + 10000;
			if(placemarks[x] != undefined ) continue;

            placemarks[x] = new YMaps.Placemark( new YMaps.GeoPoint(marker.lng, marker.lat)
												, {style: marker_style[marker.icons]} );
            placemarks[x].id = x;
            placemarks[x].m_id = marker.id;
            placemarks[x].m_layer = marker.icons;
            placemarks[x].m_type = marker.icons;
            placemarks[x].m_lat = marker.lat;
            placemarks[x].m_lng = marker.lng;
            placemarks[x].m_name = marker.name;
			placemarks[x].setHintContent(marker.name);

            if(marker.icons == 'landmark') {
                if(marker.image) {
                    placemarks[x].setBalloonContent('<div class="marker"><div class="markerTitle">'
                                                        + marker.name
                                                        + '</div><div class="markerText">'
                                                        + '<img class="markerImage" src="/downloads/markers/'
                                                        + marker.image
                                                        + '"/>'
                                                        + marker.description
                                                        + '</div></div>');
                } else {
                    placemarks[x].setBalloonContent('<div class="marker"><div class="markerTitle">'
                                                        + marker.name
                                                        + '</div><div class="markerText">'
                                                        + marker.description
                                                        + '</div></div>');
                }
            } else {
                if(marker.description!= undefined && marker.description.length) {
                    placemarks[x].setBalloonContent('<div class="marker"><div class="markerTitle">'
                                                        + marker.name
                                                        + '</div><div class="markerText">'
                                                        + marker.description
                                                        + '</div></div>');
                } else {
                    placemarks[x].disableBalloon();
                }
            }
                                                    
            if( layers_status[placemarks[x].m_layer] )
                map.addOverlay(placemarks[x]);
        }
    }

}

function showPage(url) {
    $('#searchResult').html(ajaxLoader)
                        .load(url);
}

function changePos() {
    
    if( !$("#cityObj").val() ) {
        
        showErr('Не выбран город!');
        return false;
    }

	
    sort_by = ( $('#sortBy').val() != undefined ? $('#sortBy').val() : 'name' );

    $('#searchResult').html(ajaxLoader);


    if( ( $('#staticMap').css('display') != 'none' )
			|| ($("#page_content").css('display') != 'none') 
		) {
        
        $('.rightBar').css('display','none');
        $('.centerCol').animate( {marginLeft:'227px', marginRight:'0px', left: '-10px'},
                                 300, function(){
                                     $('.rightBarSecond').slideDown("fast");
                                 });
								 
        $('#staticMap').css('display','none');
		$("#page_content").css('display','none');
		$('#map_content').removeClass('hidden');
		
        $('#YMap').css('display','block');

        map = new YMaps.Map(document.getElementById("YMap"));

		
        $().ready( function () {

            $().unload( function () {
                map.destructor();
            });

            markersStyles();

            map.addControl(new YMaps.TypeControl());
            //map.setCenter(new YMaps.GeoPoint(34.00543212890625, 44.873389196779264), 10);
            map.addControl(new YMaps.Zoom());
            map.addControl(new YMaps.ScaleLine());
            map.enableScrollZoom();

            findByGeocoder( );

        });

    } else {
        findByGeocoder( );        
    }

    if( $("#rightBar").css('display') != 'none' ) {
        
        $('.rightBar').css('display','none');
        $('.centerCol').animate( {marginLeft:'227px', marginRight:'0px', left: '-10px'},
                                 300, function(){
                                     $('.rightBarSecond').slideDown("fast");
                                 });
    }

    $('#searchResult').load('/ajax/action=obj_list&sort_by=' + sort_by + '&'
                                                             + $('form[name=searchForm]').serialize(), function() {

        zoom_after_search = true;
        loadMarkers();
        
        YMaps.Events.observe(map,map.Events.DOMMouseScroll, function () {
            loadMarkers();
        });

        $(".YMaps-slider ").click( function () {

            map_observ = YMaps.Events.observe(map,map.Events.Update, function () {
                                loadMarkers();
                                map_observ.cleanup();
            });

        });

        YMaps.Events.observe(map,map.Events.MouseDown, function () {

            map_observ = YMaps.Events.observe(map,map.Events.MoveEnd, function () {
                                loadMarkers();
                                map_observ.cleanup();
            });
        });
		
		if(layers_status['object']) {
			switchLayer('object');
			switchLayer('object');
		}
        
    });

    return false;
}

function showParamObject(obj_id, lat, lng) {

    if( $('#staticMap').css('display') != 'none' ) {

        $('#staticMap').css('display','none');
        $('#YMap').css('display','block');

        map = new YMaps.Map(document.getElementById("YMap"));
        map.addControl(new YMaps.TypeControl());
        map.addControl(new YMaps.ToolBar());
        map.addControl(new YMaps.Zoom());
        map.addControl(new YMaps.ScaleLine());
        map.enableScrollZoom();

    }

    $().ready( function () {
        
        map.setCenter( new YMaps.GeoPoint(lng, lat) , 20);

        markersStyles();


        YMaps.Events.observe(map,map.Events.DOMMouseScroll, function () {
            loadMarkersByMap();
        });

        $(".YMaps-slider ").click( function () {

            map_observ = YMaps.Events.observe(map,map.Events.Update, function () {
                                loadMarkersByMap();
                                map_observ.cleanup();
            });

        });

        YMaps.Events.observe(map,map.Events.MouseDown, function () {

            map_observ = YMaps.Events.observe(map,map.Events.MoveEnd, function () {
                                loadMarkersByMap();
                                map_observ.cleanup();
            });
        });

        loadMarkersByMap(obj_id);

    });
}

function findByGeocoder() {

	map.setZoom(11);
	var gpt = new YMaps.GeoPoint( 
										$("#cityObj option:selected").attr('rel_lng')
										, $("#cityObj option:selected").attr('rel_lat')
									);
	map.panTo( gpt );
	map.setCenter(  gpt	);

    return false;
}

function changeCityById(city_name) {
    $('#staticMap').css('display','none');
    $('#YMap').css('display','block');

    map = new YMaps.Map(document.getElementById("YMap"));
    map.addControl(new YMaps.TypeControl());
    map.addControl(new YMaps.ToolBar());
    map.addControl(new YMaps.Zoom());
    map.addControl(new YMaps.ScaleLine());
    map.enableScrollZoom();

    $().ready( function () {

        geocoder = new YMaps.Geocoder(city_name, {results: 1});

        YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {

            var results = this.length(), item = this.get(0);

            if (results > 0) {
                map.setZoom(8); // or 9
                map.setCenter(item.getGeoPoint());
            }

            markersStyles();

            loadMarkersByMap();

            YMaps.Events.observe(map,map.Events.DOMMouseScroll, function () {
                loadMarkersByMap();
            });

            $(".YMaps-slider ").click( function () {

                map_observ = YMaps.Events.observe(map,map.Events.Update, function () {
                                    loadMarkersByMap();
                                    map_observ.cleanup();
                });

            });

            YMaps.Events.observe(map,map.Events.MouseDown, function () {

                map_observ = YMaps.Events.observe(map,map.Events.MoveEnd, function () {
                                    loadMarkersByMap();
                                    map_observ.cleanup();
                });
            });

        });
    });
}

function showHotelDescription(obj_id) {
    if(obj_id == undefined) return false;
	
    for(i in placemarks) {

        if(placemarks[i].m_layer == 'object' && placemarks[i].m_id == obj_id) {

            map.setCenter( new YMaps.GeoPoint(placemarks[i].m_lng-0.0007, placemarks[i].m_lat) , 20);
			
			$('#hotelDescription .modal_content').html('<img src="/images/loading.gif"/>');
			$('#hotelDescription').slideDown( function() {
					$('#hotelDescription .modal_content').load('/?task=ajax&action=object_desc&id='+obj_id);
			});
		}
	}
    return false;
}

function showRoomsPhoto(obj_id, room_id) {

    if(obj_id == undefined) return false;
    if(room_id == undefined) room_id=0;
    $('.simpleModal .modal_content').html('<img src="/images/loading.gif"/>');
    $.get('/?task=ajax&action=object_room_photo&id=' +obj_id+ '&room_id=' +room_id , function(data){
			$('.simpleModal .modal_content').html(data);
    });

    $('.simpleModal').modal();

    return false;

}

function showRoomDescription(obj_id, room_id) {
    if(obj_id == undefined) return false;
    $('#roomDescription .modal_content').html('<img src="/images/loading.gif"/>');
    $('#roomDescription').slideDown( function() {
            $('#roomDescription .modal_content').load('/?task=ajax&action=object_room&id=' +obj_id+ '&room_id=' +room_id);
    });

    return false;
}

function saveReview(obj_id) {

    if(obj_id == undefined) return false;

    if( !$("#review_name").val() ||
        !$("#review_email").val() ||
        !$("#review_comment").val()
        )
                return false;

    param = {
        name: $("#review_name").val(),
        email: $("#review_email").val(),
        comment: $("#review_comment").val()
    };
    $.post('/?task=ajax&action=save_review&id=' +obj_id, param, function() {

        showReviews(obj_id);
        
    })

    return false;
}

function cancelReview() {

    $('#addReview').slideUp( function() {
            $('#listReview').show();
    });

    return false;
}

function addReview(obj_id) {
    if(obj_id == undefined) return false;

    $('#listReview').slideUp( function() {
            $('#addReview').show();
    });

    return false;
}

function showReviews(obj_id, page) {
    if(obj_id == undefined) return false;

    if(page == undefined) page = 1;

    $('#reviews .modal_content').html('<img src="/images/loading.gif"/>');
    $('#reviews').slideDown( function() {
            var now = new Date();
            $('#reviews .modal_content').load('/?task=ajax&action=object_review&id=' +obj_id
                                                +'&page=' +page+ '&_=' +now.getTime());
    });

    return false;
}

function showObjImages(obj_id, img_start) {

    if(img_start == undefined) img_start = 0;
    if(obj_id == undefined) return false;

    $('.simpleModal .modal_content').html('<img src="/images/loading.gif"/>');
    $.get('/?task=ajax&action=object_photo&id=' +obj_id + '&start_img=' + img_start, function(data){
        $('.simpleModal .modal_content').html(data);
    });

    $('.simpleModal').modal();

    return false;
}

function ShowToolTipPreloader() {
    $('#tootip .t_center').html('<img src="/images/loading.gif" />');
}

function showObjEditor(obj_id) {

    if( typeof(obj_id) == 'undefined' )
        obj_id = 0;

    $('#modal_edit').empty()
                    .jqm({
        overlay: 50,
        modal: true,
        trigger: false
    });

    //$('#modal_cabinet').jqmHide();

    $("#modal_edit").load('/?task=ajax&action=obj_form&id=' + obj_id,
        function() {
            $('#modal_edit').jqmAddClose('.jqmClose');
            $('#modal_edit').jqmShow();
            showYMap();
    });
}

function showCabinet() {

    $('#modal_cabinet').empty()
                        .jqm({
                            overlay: 50,
                            modal: true,
                            trigger: false
                        });

    $("#modal_cabinet").load('/?task=ajax&action=cabinet',
        function() {
            $('#modal_cabinet').jqmShow();

    });

    return false;
}

function objDeleteConfirm(obj_id) {

    if(confirm('Удалить объект?')) {

        $.post('/?task=ajax&action=obj_del&id=' + obj_id
        , function() {

                $('#o_'+obj_id).hide();
        });
        
    }
    return false;
}

function showRegister(mode, obj_id) {
    
	if(mode == undefined) mode='';
    if(obj_id == undefined) obj_id=0;

    $.get('/?task=ajax&action=check_session', function(data) {

//getCookie('id') && getCookie('u') && getCookie('p')

        if( data && data == getCookie('id')) {

            $.requireScript([
                                '/includes/jquery/jqmodal/jqmodal.js'
                                , '/includes/jquery/jquery.ajaxfileupload.js'
                                , '/includes/jquery/jquery.form.js'
                                , '/includes/jquery/jquery.ajaxupload.js'
                                , '/includes/jquery/jquery.pagination.js'
                                , '/includes/jquery/ui.tabs.js'
                            ]
                            , function(){

                                if (mode=='object') {
                                    showObjEditor(obj_id);
                                }

                                if (mode=='cabinet') {
                                    showCabinet();
                                }

                            });
            return false;
        }

        ShowToolTipPreloader();

        $('#tootip').slideDown();
        
        $.get('/tooltip_register.html', function(data){
               $('#tootip .t_center').html(data);
               return false;
       });

       return false;
    });

    return false;
}

function showAuth(msg) {
    if(!msg) return;
    $('#authMes p.t_center').html(msg);
    $('#authMes').slideDown();
}

function loginRestore() {
    var email = window.prompt("Введите ваш email");

    if(email) {
        $.post('/?task=ajax&action=user_login_restore&email='+email, function(data){
            if(data == '1') {
                showErr('Нет такого пользователя!');
                return false;
            } else {
                showOk('Новый пароль был выслан вам на почту');
                return false;
            }
        });
    }
    $("#authMes a.close").click();
    return false;
}

function loginConfirm() {

    $("#authMes .required").each( function() {
        if( !$(this).val() ) {
            $(this).addClass('required_hightlight');
        } else {
            $(this).removeClass('required_hightlight');
        }
    });

    if( $("#authMes .required_hightlight").size() ) { // there is hightlighted req
        alert('Заполните все поля, отмеченные желтым цветом.');
        return false;
    }

    var params_str = '';

    $("#authMes input").each( function() {
        params_str += '&' + $(this).attr('name') + '=' + $(this).val();
    });

    $.post('/?task=ajax&action=user_login', params_str, function(data){
        if(data == '1') {
            alert('Нет такого пользователя или неверный пароль!');
            return false;
        } else {
            $('#authMes p.t_center').html(data);
        }
    });

    return false;
}

function regConfirm() {

    $("#authMes .required").each( function() {
        if( !$(this).val() ) {
            $(this).addClass('required_hightlight');
        } else {
            $(this).removeClass('required_hightlight');
        }
    });

    if( $("#authMes .required_hightlight").size() ) { // there is hightlighted req
        alert('Заполните все поля, отмеченные желтым цветом.');
        return false;
    }

    if( $("#authMes input[name=pass1]").val() != $("#authMes input[name=pass2]").val() ) { // there is hightlighted req
        alert('Пароль не совпадает!');
        return false;
    }

    var params_str = '';

    $("#authMes input").each( function() {
        params_str += '&' + $(this).attr('name') + '=' + $(this).val();
    });

    $.post('/?task=ajax&action=user_reg', params_str, function(data){
        if(data == '1') {
            alert('Пользователь с таким логином уже существует!');
            return false;
        } else {
            $('#authMes p.t_center').html(data);
        }
    });

    return false;
}

function showAddPointer() {
    ShowToolTipPreloader();
    $('#tootip').slideDown();

    if( $('#staticMap').css('display') !='none' ) {
        $('#staticMap').css('display','none');
        $('#YMap').css('display','block');

        map = new YMaps.Map(document.getElementById("YMap"));
        map.addControl(new YMaps.TypeControl());
        map.addControl(new YMaps.ToolBar());
        map.addControl(new YMaps.Zoom());
        map.addControl(new YMaps.ScaleLine());
        map.enableScrollZoom();
        map.setZoom(14);

        $().ready( function () {
            geocoder = new YMaps.Geocoder( 'Киев', {results: 1});

            YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {

                var results = this.length(), item = this.get(0);

                if (results > 0) {
                    map.setZoom(14); // or 9
                    map.setCenter(item.getGeoPoint());
                }

                markersStyles();

                loadMarkersByMap();

                YMaps.Events.observe(map,map.Events.DOMMouseScroll, function () {
                    loadMarkersByMap();
                });

                $(".YMaps-slider ").click( function () {

                    map_observ = YMaps.Events.observe(map,map.Events.Update, function () {
                                        loadMarkersByMap();
                                        map_observ.cleanup();
                    });

                });

                YMaps.Events.observe(map,map.Events.MouseDown, function () {

                    map_observ = YMaps.Events.observe(map,map.Events.MoveEnd, function () {
                                        loadMarkersByMap();
                                        map_observ.cleanup();
                    });
                });

            });
        });
    }
    $.get('/tooltip_add.html', function(data){
            
           $('#tootip .t_center').html(data);
       });
}

function showOrder(obj_id, room_id) {

    if(obj_id == undefined) return false;
    if(room_id == undefined) room_id = 0;

    $('#order .modal_content').html('<img src="/images/loading.gif"/>');
    $('#order').slideDown( function() {
            $('#order .modal_content').load('/?task=ajax&action=object_order&id=' +obj_id+ '&room_id=' +room_id);
    });

    return false;
    
}

function showErr(msg) {
    if(!msg) return;
    $('#errMes p.t_center').html(msg);
    $('#errMes').slideDown(function(){ setTimeout(function(){$('#errMes').slideUp()}, 3000); });
}

function showOk(msg) {
    if(!msg) return;
    $('#okMes p.t_center').html(msg);
    $('#okMes').slideDown(function(){ setTimeout(function(){$('#okMes').slideUp()}, 3000); });
}

function prev() {    
    if($('.previews a.current').attr('rel') == 0) return false;
    else
    {
        var newRel = parseInt($('.previews a.current').attr('rel')) - 1;

        $('.previews a.current').removeClass('current');
        $('.previews a').eq(newRel).addClass('current');

        $('.bigImage img').attr('src', $('.previews a').eq(newRel).attr('href'));
        $('#photo_info').html( $('.previews a').eq(newRel).attr('title') );

        return false;
    }
}

function next() {    
    if(parseInt($('.previews a.current').attr('rel')) + 1 == $('.previews a').length) return false;
    else
    {
        var newRel = parseInt($('.previews a.current').attr('rel')) + 1;
        $('.previews a.current').removeClass('current');
        $('.previews a').eq(newRel).addClass('current');

        $('.bigImage img').attr('src', $('.previews a').eq(newRel).attr('href'));
        $('#photo_info').html( $('.previews a').eq(newRel).attr('title') );

        return false;
    }
}

function switchSearchType(type) {

    $(".searchParam").hide();
    $("#" + type).show();

}

function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

function orderByCC(id) {

    if(id == undefined) return false;

    $("#order_info .required").each( function() {
        if( !$(this).val() ) {
            $(this).addClass('required_hightlight');
        } else {
            $(this).removeClass('required_hightlight');
        }
    });

    if( $("#order_info .required_hightlight").size() ) { // there is hightlighted req
        alert('Заполните все поля, отмеченные желтым цветом.');
        return false;
    }


    $.post('/?task=ajax&action=create_order_and_pay&obj_id='+id, $("#order_info").serialize(), function(data){
        $("#order_form").html(data).submit();
        $("#order").hide();
    });

    return false;
}

function orderOther(id) {

    if(id == undefined) return false;

    $("#order_info .required").each( function() {
        if( !$(this).val() ) {
            $(this).addClass('required_hightlight');
        } else {
            $(this).removeClass('required_hightlight');
        }
    });

    if( $("#order_info .required_hightlight").size() ) { // there is hightlighted req
        alert('Заполните все поля, отмеченные желтым цветом.');
        return false;
    }
    
    $.post('/?task=ajax&action=create_order&obj_id='+id, $("#order_info").serialize(), function(){
        $("#order").hide();
    });

    return false;
}

function showRegistartionForm() {

    $('#tootip').slideUp();

    $.get('/?task=ajax&action=reg_form', function(data){
           showAuth(data);
       });

    return false;
}

function showLoginForm() {

    $('#tootip').slideUp();

    $.get('/?task=ajax&action=login_form', function(data){
           showAuth(data);
       });

    return false;

}

function searchAddress() {

    if( !$("input[name=searchAdd]").val() ) return false;

    geocoder = new YMaps.Geocoder( $("input[name=searchAdd]").val(), {results: 1});

    YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {

        var results = this.length(), item = this.get(0);

        if (results > 0) {
            map.setZoom(14); // or 9
            map.setCenter(item.getGeoPoint());
        }

        markersStyles();

        loadMarkersByMap();

        YMaps.Events.observe(map,map.Events.DOMMouseScroll, function () {
            loadMarkersByMap();
        });

        $(".YMaps-slider ").click( function () {

            map_observ = YMaps.Events.observe(map,map.Events.Update, function () {
                                loadMarkersByMap();
                                map_observ.cleanup();
            });

        });

        YMaps.Events.observe(map,map.Events.MouseDown, function () {

            map_observ = YMaps.Events.observe(map,map.Events.MoveEnd, function () {
                                loadMarkersByMap();
                                map_observ.cleanup();
            });
        });

    });

    return false;
}

function addLandmark() {

	$('#tootip').slideUp();
	
    if( map == undefined ) {

		$('#staticMap').css('display','none');
		$('#YMap').css('display','block');

		map = new YMaps.Map(document.getElementById("YMap"));
		
            map.addControl(new YMaps.TypeControl());
            map.setCenter(new YMaps.GeoPoint(34.00543212890625, 44.873389196779264), 10);
            map.addControl(new YMaps.Zoom());
            map.addControl(new YMaps.ScaleLine());
            map.enableScrollZoom();
	}
	
    $().ready( function () {
		
		$().unload( function () {
			map.destructor();
		});

		markersStyles();

		if(new_placemark)
					map.removeOverlay(new_placemark);

		new_placemark = new YMaps.Placemark( map.getCenter(), {draggable: true, hideIcon: false});
		new_placemark.name = "Новый ориентир";
		new_placemark.setIconContent( new_placemark.name );

		$.get('/?task=ajax&action=landmark_form', function(html){

			new_placemark.setBalloonContent(html);

		});

		map.addOverlay(new_placemark);

		YMaps.Events.observe(new_placemark, new_placemark.Events.Drag, function (mEvent) {

			$("#new_lat").val( mEvent.getGeoPoint().getLat() );
			$("#new_lng").val( mEvent.getGeoPoint().getLng() );

		});

		YMaps.Events.observe(new_placemark, new_placemark.Events.BalloonOpen, function (mEvent) {
			
			$("#new_lat").val( mEvent.getGeoPoint().getLat() );
			$("#new_lng").val( mEvent.getGeoPoint().getLng() );

		});

	});
}

function saveLandmark() {

    if( !$("#newLandmarkForm input[name=new_title]").val() ){ alert('Заполните все поля'); return false; }

    $('#newLandmarkForm').ajaxForm({
        url: '/?task=ajax&action=landmark_save',
        type: 'POST',
        success: function(text) {

            if(new_placemark) 
                map.removeOverlay(new_placemark);

            alert(text);
            return false;
        }
    });

    $('#newLandmarkForm').submit();

    return false;

}

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

$(document).ready(function(){

    $(".dragBlock").draggable({ containment: 'body', handle:'.dragzone' });

    $('.close').click(function(){
        $(this).parent().css("display","none");
        return false;
    });

    $('.bottomBlock span').click(function(){
        var ch = $(this).find('input');
        var im = $(this).find('.myCheckbox');

        if (ch.attr('checked'))
            {
                ch.attr("checked", false);
                im.attr("src", template_path + "images/checkbox_noch.jpg");
            }
        else
            {
                ch.attr('checked', true);
                im.attr("src", template_path + "images/checkbox_ch.jpg");
            }

        switchLayer( im.attr('alt') );
    });

    switchSearchType( $("select[name=typeObj]").val() );

    $().unload( function () {
        map.destructor();
    });

});


var ajaxLoader = '<table height="614" width="100%" border="0"><tbody>\n\
<tr><td align="center" valigh="bottom"><img src="/images/loading.gif"/></td></tr></tbody>\n\
</table>';

$.ajax({ cache: false});
