$(function(){
    var currentTime = new Date();
    key = ''+currentTime.getDate()+currentTime.getHours();
    key = Math.random();
    initMap();
    if ($('#galleryphoto').size()) {
        photoGalery();
    }
    indexMenuInit();
    
    // selectbox
        var selects = $('select.selectbox');
        if (selects.size()) {
            selects.selectbox({
            className: 'j-selbox',
            listboxMaxSize: 20
            });
        }
});

var map = null;
var infoWindow = null;
var key = 0;
// заменить после тестов на 
// var key=1;

/**
 * признак работы на карте (map) или списком (list)
 */
var viewType = 'map';

function initMap() {
    map = document.getElementById("map");
    if (map) {
        var latlng = new google.maps.LatLng(55.742, 37.68);
        var myOptions = {
          zoom: 1,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(map,
            myOptions); 
        showForm('#mapSearchFotm');
        infoWindow = new google.maps.InfoWindow({
            content: ''
        });
//        loadNewKml('http://'+window.location.hostname+'/kml/index.html?'+$('#mapSearchFotm').serialize()+'&r='+key);
        var imgs = $('img.border');
        if (imgs.size() == 3) {
            $(imgs[2]).hide();
        }
    } else {
        map = document.getElementById('minimap');
        if (map) {
            var latlng = new google.maps.LatLng(55.742, 37.68);
            var myOptions = {
              zoom: 1,
              center: latlng,
              mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(map,
                myOptions); 
            var propId = parseInt($('#minimap').attr('rel'));
            if (propId) {
                loadNewKml('http://'+window.location.hostname+'/kml/index.html?id='+propId+'&withparent=1'+'&r='+key);
            }
        }
    }
}

var tecKml = null;
function loadNewKml(url) {
    if (tecKml) {
        tecKml.setMap(null);
    }
    tecKml = new google.maps.KmlLayer(url, {map:map, suppressInfoWindows: true});
    google.maps.event.addListener(tecKml, 'click', function(kmlEvent) {
      var text = kmlEvent.featureData.description;
      infoWindow.setContent(text);
      infoWindow.setPosition(kmlEvent.latLng);
      infoWindow.open(map);
    });

    window.setTimeout("checkMapZoom()", 1000);
}
function checkMapZoom() {
    if (map.getZoom() > 15) {
        map.setZoom(15);
    }
}

function showForm(form) {
    if (arguments.length == 2 && arguments[1] == 'clear') {
        $(form).find('select').val(0);
        $(form).find('input[name=text]').val('');
    }
    $(form).parent().css({opacity:0});
    $(form).parent().load('/mapform/index.html?'+$(form).serialize(), '', function(){
        var selects = $('select.selectbox');
        if (selects.size()) {
            selects.selectbox({
            className: 'j-selbox',
            listboxMaxSize: 20
            });
        }
        $('#mapSearchFotm, #search-param').animate({opacity:1}, 'fast');
    });
    $('select.selectbox').parents().unselectbox();
//    if (viewType == 'map') {
        loadNewKml('http://'+window.location.hostname+'/kml/index.html?'+$(form).serialize()+'&r='+key);
//    } else {
        $.ajax({
            url : 'http://'+window.location.hostname+'/ajax/property/index.html?'+$(form).serialize(),
            dataType : 'json',
            success : function(data) {
                $('#objectList').html(data.data);
                if (!data.data) {
                    window.setTimeout("centerMap()", 1000);
                }
            }
        })
//    }
}

function centerMap() {
    map.setZoom(4);
    map.setCenter(new google.maps.LatLng(58.4,52));
}

function loadNextPage(page) {
    $.ajax({
            url : 'http://'+window.location.hostname+'/ajax/property/index.html?'+$('#mapSearchFotm').serialize()+'&page='+page,
            dataType : 'json',
            success : function(data) {
                $('#objectList').html(data.data);
            }
        })
}

function switchSearchTo(newType) {
    switch (newType) {
        case 'map':
            var el = $('#objectList');
            var parent = el.parent();
            el.hide().detach();
//            $('#mapwrap').slideDown();
//            $('#objectList').slideUp();
            parent.append(el);
            el.slideDown();
            viewType = 'map';
            showForm('#mapSearchFotm');
            break;
        case 'list':
            var el = $('#mapwrap');
            var parent = el.parent();
            el.hide().detach();
//            $('#mapwrap').slideUp();
//            $('#objectList').slideDown();
            parent.append(el);
            el.slideDown();
            viewType = 'list';
            showForm('#mapSearchFotm');
            break;
    }
}

/* фотогалерея */
var tecGalIndex = 0;
var movingElement = null;
    
function photoGalery() {
    var sheight = $('#galleryphoto').height();
    var allwidth = 0;
    $('#galleryphoto a').wrap('<div class="phgallery" />').fancybox({
        onClosed : onClosedFancybox
    }).each(function(index) {
        var t = $(this);
        t.parent().css({
            'paddingTop': ((sheight-t.height())/2)+'px'
            });
        allwidth += t.width();
    });
    //        $('div.phgallery').height(sheight);
    //        $('div.phgallery');
    movingElement = $('#inphoto');
    movingElement.css({
        'position' : 'relative'
    });
    movingElement.width(allwidth*1.5);
    $('#goLeft').click(goLeft);
    $('#goRight').click(goRight);
    moveToElement(tecGalIndex+1);
}
    
function goLeft() {
    if (movingElement) {
        // поиск следующиего
        var elts = $('#galleryphoto div.phgallery');
        if (tecGalIndex < elts.length-2) {
            moveToElement(++tecGalIndex);
        } else {
    //                alert('no left');
    }
    }
    return false;
}
function goRight() {
    if (movingElement) {
        // поиск следующиего
            
        if (tecGalIndex >1) {
            moveToElement(--tecGalIndex);
        } else {
    //                alert('no right');
    }
    }
    return false;
}
function moveToElement(index){
    var elts = $('#galleryphoto div.phgallery');
    if (elts.size()  < 2) {
        return;
    }
    var w = $('#galleryphoto').width() - $(elts[index]).outerWidth();
    w /= 2;
    w = $(elts[index]).position().left - w;
    movingElement.animate({
        'left': (-w)+'px'
        });
}
    
function onClosedFancybox (arr, index, opts) {
    tecGalIndex = index;
    moveToElement(tecGalIndex);
}

var tecMenuIndex = 0;
var timer = null;
var NavElements = null;
var PicElements = null;
function indexMenuInit() {
    if ($('#index-nav').size() == 0) return;
    NavElements = $('#index-nav .lof-navigator li');
    NavElements.click(function(){
       location.href = $(this).find('a:first').attr('href'); 
    });
    PicElements = $('#index-nav .lof-main-wapper li');
    $(NavElements[tecMenuIndex]).addClass('active');
    PicElements.css({opacity:0});
    $(PicElements[tecMenuIndex]).css({opacity:1});
//    timer = window.setInterval(nextIndexMenuItem, 3000);
    NavElements.
        each(
            function(index, el) {
                $(el).attr('rel', index);
            }
        ).hover(
        function (el){
//            window.clearInterval(timer);
//            timer = null;
            PicElements.hide().css({opacity:0});
            var index = parseInt($(el.currentTarget).attr('rel'));
            $(PicElements[index]).show().css({opacity:1});
            
            NavElements.removeClass('active');
            $(NavElements[index]).addClass('active');
            
//            nextIndexMenuItem($(el.currentTarget).attr('rel'));
        },
        function (el){
//            timer = window.setInterval(nextIndexMenuItem, 3000);
//            PicElements.hide().css({opacity:0});
//            $(PicElements[tecMenuIndex]).show().css({opacity:1});
        }
    );
}
function nextIndexMenuItem() {
    var saveIndex = tecMenuIndex;
    if (arguments.length == 2) {
        tecMenuIndex = arguments[1];
    } else {
        tecMenuIndex++;
    }
    if (tecMenuIndex == NavElements.size()) {
        tecMenuIndex = 0;
    }
    PicElements.hide();
    $(PicElements[saveIndex]).show();
    $(NavElements[saveIndex]).removeClass('active');
    $(PicElements[saveIndex]).animate({opacity:0}, {duration: 600, 
        complete: function(){
            $(PicElements[saveIndex]).hide();
        }});
    $(PicElements[tecMenuIndex]).show().css({opacity:0});
    $(PicElements[tecMenuIndex]).animate({opacity:1}, 600);
    $(NavElements[tecMenuIndex]).addClass('active');
}
