
function tabsInit() {

    if( $("#obj_type").val() == 'flat' || $("#obj_type").val() == 'house') {

        $("#edit_tabs").tabs('option', 'disabled', [5]);

    } else {

        $("#edit_tabs").tabs('option', 'disabled', []);
    }
}

function showYMap() {

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

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

    map.addControl(new YMaps.TypeControl());
    map.addControl(new YMaps.SmallZoom());
    map.addControl(new YMaps.ScaleLine());
    map.enableScrollZoom();

    lng = $("#obj_lng").val() ? $("#obj_lng").val() : 30.498047;
    lat = $("#obj_lat").val() ? $("#obj_lat").val() : 50.457504;

    map.setCenter(new YMaps.GeoPoint( lng , lat ), 13);

    placemark = new YMaps.Placemark(new YMaps.GeoPoint(lng, lat), {draggable: true} );
    placemark.setIconContent( "" );

    if( $("#obj_name").val() ) {
        placemark.setIconContent( "<b>" + $("#obj_name").val() + "</b>" );
        map.setZoom(15);
    }

    map.addOverlay(placemark);

    YMaps.Events.observe(map, map.Events.Click, function (mEvent) {

        var newGeoPoint = mEvent.getGeoPoint();
        placemark.setGeoPoint(newGeoPoint);
        placemark.setIconContent( "<b>" + $("#obj_name").val() + "</b>" );

        $("#obj_lat").val( mEvent.getGeoPoint().getLat() );
        $("#obj_lng").val( mEvent.getGeoPoint().getLng() );

    })

//    YMaps.Events.observe(placemark, placemark.Events.Drag, function (mEvent) {
//
//        var newGeoPoint = mEvent.getGeoPoint();
//        placemark.setGeoPoint(newGeoPoint);
//        placemark.setIconContent( "<b>" + $("#obj_name").val() + "</b>" );
//
//        $("#obj_lat").val( mEvent.getGeoPoint().getLat() );
//        $("#obj_lng").val( mEvent.getGeoPoint().getLng() );
//
//    })

    YMaps.Events.observe(placemark, placemark.Events.DragEnd, function (mEvent) {

        var newGeoPoint = mEvent.getGeoPoint();
        placemark.setGeoPoint(newGeoPoint);
        placemark.setIconContent( "<b>" + $("#obj_name").val() + "</b>" );

        $("#obj_lat").val( mEvent.getGeoPoint().getLat() );
        $("#obj_lng").val( mEvent.getGeoPoint().getLng() );

    })

    $("#obj_lng").val(lng);
    $("#obj_lat").val(lat);

    return false;
}

function findByGeocoderEdit (inp_name) {

    if (inp_name && inp_name != 'undefined' && $("input[name="+inp_name+"]").val() ) {

        address = $("#obj_city").find('option').filter(':selected').text()
                            + ', ' + $("input[name="+inp_name+"]").val();
    } else {

        address = $("#obj_city").find('option').filter(':selected').text();
    }

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

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

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

        if (results > 0) {

            map.panTo( item.getGeoPoint() );
            map.setZoom(16);
            placemark.setGeoPoint( item.getGeoPoint() );
            placemark.setIconContent( "<b>" + $("#obj_name").val() + "</b>" );

            $("#obj_lat").val( item.getGeoPoint().getLat() );
            $("#obj_lng").val( item.getGeoPoint().getLng() );

        } 
    });

    return false;
}

function showCityCenter() {
    findByGeocoderEdit();
}

// Start Images script

function deleteImage(j_obj) {

    if(confirm('Удалить фотографию?')) {

        file_id = j_obj.siblings("input[type=file]").attr('id').replace(/file_/, '');

        if( ! j_obj.siblings("input[type=file]").val() ) { // existed object & saved image

            $.post(document.location.href.replace(/#/, ''), { task: 'ajax', action: 'obj_image_del'
                                            , file: file_id, id: $("#object_id").val() } );

        }

        j_obj.siblings('a').html( 'Загрузить' )
                .siblings('div.imgDel').hide()
                .siblings("input[type=file]").val('')
                .change( function() { setImagePreview(this); })
                .parent().css( 'background-image', '' )
                .mousemove( function(e) { ImageMouseMove(e, this); } )
                .mouseout( function() { ImageMouseOut(this) } );

    }
}

function ImageMouseMove(event,obj) {

    position = $("#modal_edit").position();

    position_div = $(obj).position();

    div_left  = position.left-300+position_div.left+1;
    div_top   = position.top+position_div.top+1;
    div_right = position.left-300+position_div.left+1 + $(obj).width();
    div_bot   = position.top+position_div.top+1 + $(obj).height();

    file_input_width = $(obj).children('input[type=file]').width();
    $(obj).children('input[type=file]').css( 'left', event.pageventX-file_input_width ).css( 'top', event.pageY-10 );

    file_left = (event.pageX - position.left + $(obj).children('input[type=file]').width()/2 + 10 );
    file_top = (event.pageY - position.top - $(obj).children('input[type=file]').height()/2);

    $(obj).children('input[type=file]').css( 'left', file_left ).css( 'top', file_top );

    if( event.pageX<div_left || event.pageX>div_right || event.pageY<div_top || event.pageY>div_bot ) {

        $(obj).children('input[type=file]').css( 'left', '-10000px' ).css( 'top', '184px' );

    }
}

function ImageMouseOut(obj) {
    $(obj).children('input[type=file]').css( 'left', '-10000px' ).css( 'top', '184px' );
}

function setImageEvents() {

    $("#photo_list div").mousemove( function(e) { ImageMouseMove(e, this); } )
                        .mouseout( function() { ImageMouseOut(this) } );

    // set events

    $("#photo_list div input[type=file]").change( function() {
                                                    setImagePreview(this);
                                            });

}

function setImagePreview(obj) {

    //console.log( $(obj).val() );

    $(obj).siblings('a').html( '<img src="/images/loading.gif">' );

    $.ajaxFileUpload(
                        {
                            url: document.location.href.replace(/#/, '')
                                    + '?task=ajax&action=obj_image_upload_n_preview&id=' + $("#object_id").val()
                                    + '&image_id=' + $(obj).attr('id').replace(/file_/, ''),
                            secureuri:false,
                            fileElementId: $(obj).attr('id'),
                            dataType: 'json',

                            success: function (data )
                            {

                                if(typeof(data.error) != 'undefined')
                                {
                                    if(data.error != '')
                                    {
                                        alert(data.error);

                                    }else
                                    {
                                        $("#" +data.img_id).siblings('a').html( '&nbsp;' ) // Clean text
                                                            .siblings('div').show() // Show trash
                                                            .parent().css( 'background-image', data.preview )
                                                            .unbind()
                                                            .change( function() {
                                                                                setImagePreview(this);
                                                                     });

                                        if( $("input[name=image_default]:checked").val() == undefined) {

                                            $('input[name=image_default][value=' +data.id+ ']').attr('checked', 'checked').change();

                                        }
                                    }
                                }
                            },
                            error: function (data, status, e)
                            {
                                alert(e); // data, status
                            }
                        }
                    );
}

// End Images script


function showDependLi() {

    $(".input_list li.depend, .input_list li span.depend").hide();
    $(".input_list li." + $("#obj_type").val() + ", .input_list li span." + $("#obj_type").val() ).show();

    if($("#obj_type").val() != 'hotel') {
        $(".input_list li.no_depend" + ", .input_list li span.no_depend").show();
    }

    showTypeParams( $("#obj_type_option").val() );

    tabsInit();
}

function showTypeParams( typeParams ){
    $("#obj_type_option").html( $("#options_"+$("#obj_type").val()).html() ).val(typeParams);
}

function objSave(obj_id) {
    if( typeof(obj_id) == 'undefined' )
        obj_id = 0;

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

    if( $(".required_hightlight").size() ) { // there is hightlighted req
        return false;
    }

    $('#modal_form').ajaxForm({
        url: '?task=ajax&action=obj_save&id=' +obj_id,
        type: 'POST',
        success: function() {

           $('#modal_edit').jqmHide();
           $('#modal_edit').empty();

        }
    });

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

    return false;
}

function apptDel(obj_id, name) {

    if( confirm('Удалить номер/комнату "' + name + '"?') ) {

        $.post('/?task=ajax&action=appt_del&id=' + obj_id +'&obj_id=' + $("#object_id").val()
            , function() {
                $("#appt_"+obj_id).remove();
        });

        return false;

    }

    return false;
}

function apptEditSave() {

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

    if( $("#appt_form .required_hightlight").size() ) { // there is hightlighted req
        return false;
    }

    $('#appt_form').ajaxForm({
        url: '/?task=ajax&action=appt_edit_save&obj_id=' + $("#object_id").val(),
        type: 'POST',
        success: function() {
            $("#edit_tabs").tabs( 'load' , 4 );
            $("#objSave").show();
        }
    });

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

    return false;
}

function apptEditCancel() {
     $("#edit_tabs").tabs( 'load' , 5 );
     $("#objSave").show();

     return false;
}

function apptEditShow(obj_id) {

    $(".comment_out").hide();
    $(".app_editor").html('');
    $("#appt_"+obj_id).show();
    $("#appt_"+obj_id+" div").hide();

    $("#objSave").hide();

    $("#appt_"+obj_id+" .app_editor").show().load('/?task=ajax&action=appt_edit_show&id=' + obj_id
                                                            +'&obj_id=' + $("#object_id").val() );

    return false;
}

