$.browser.safari = ( $.browser.safari && /chrome/.test(navigator.userAgent.toLowerCase()) ) ? false : true; 
$.browser.chrome = (/chrome/.test(navigator.userAgent.toLowerCase()) ) ? true : false; 

var map;
var markers = [];
initGMAP = function() {
    map = new google.maps.Map(document.getElementById("GMAP"), {
        disableDefaultUI: false,
        scrollwheel: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: new google.maps.LatLng(44, 48),
        maxZoom: 16,
    });
    
    $('a.Cost').click(function(){
        filterMarkers(str_replace('Cost_', '', $(this).attr('Id')));
    });
    
}

initGMAP2 = function() {
    map = new google.maps.Map(document.getElementById("GMAP2"), {
        disableDefaultUI: false,
        scrollwheel: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: new google.maps.LatLng(55.755786, 37.617633),
        zoom: 7,
        maxZoom: 19,
        noClear: true,
    });
}

toggleBounce = function() {
    if (marker.getAnimation() != null) {
      marker.setAnimation(null);
    } else {
      marker.setAnimation(google.maps.Animation.BOUNCE);
    }
  }


filterMarkers = function(Id) {
    
    for (i in markers) {
        if (markers[i].costId != Id) {
            markers[i].setMap(null);
        } else {
            markers[i].setMap(map);            
        }
    }
    
}

setMarker = function(options) {
    content = '<div class="MapInfoWindow"><p class="title"><a href="/viewrealty/objectid/' + options.id + '">' + options.name + '</a></p>';
    if (options.image) {
        content += '<p><img width="100" src="' + options.image + '" /></p>';
    }
    
    if (options.highway.length || options.distance.Id) {
        content += '<p>';
        if (options.highway) {
            for (highway in options.highway) {
                content += '<a href="/highway/locationid/' + options.highway[highway].Id + '">' + options.highway[highway].Name + '</a> шоссе';
                if (highway < options.highway.length - 1) {
                    content += ', '
                }
            }
        }
        
        if (options.highway.length && options.distance.Id) {
            content += ', ';
        }
        
        if (options.distance.Id) {
            content += '<a href="search?DistanceFrom=' + options.distance.Id + '&DistanceTo=' + options.distance.Id + '">' + options.distance.Name + '</a> км от МКАД';
        }
        content += '</p>';
    }
    
    if (options.area.Id) {
        content += '<p><b>Площадь:</b> <a href="/search?AreaHouseFrom=' + options.area.Id + '&AreaHouseTo=' + options.area.Id + '">' + options.area.Name + ' м<sup>2</sup></a></p>';
    }
    
    if (options.cost.Id) {
        content += '<p><b>Стоимость:</b> <a href="/search?CostFrom=' + options.cost.Id + '&CostTo=' + options.cost.Id + '">' + options.cost.Name + ' млн руб.</a></p>';
    }
    
    if (options.status.Id) {
        content += '<p><b>Готовность:</b> <a href="/search?StatusBuildFrom=' + options.status.Id + '&StatusBuildTo=' + options.status.Id + '">' + options.status.Name + '</a></p>';
    }
    
    
    
    content += '</div>';
    
//    alert(content);
    
    marker = new google.maps.Marker({
        position: options.position,
        map: map,
        title: options.name,
        flat: true,
    });
    
    if (options.cost.Id != '') {
        icon = new google.maps.MarkerImage('/img/Cost' + options.cost.Id + '.gif');
        marker.costId = options.cost.Id;
    } else {
        icon = new google.maps.MarkerImage('/img/Cost0.gif');
        marker.costId = 0;
    }
    icon.anchor = new google.maps.Point(5, 5);
    icon.size = new google.maps.Size(10, 10);
    marker.setIcon(icon);
    
    marker.infowindow = new google.maps.InfoWindow({
        content: content,
        maxWidth: 200,
    });
    
    google.maps.event.addListener(marker, 'click', function() {
        for (i in markers) {
            markers[i].infowindow.close();
        }
        this.infowindow.open(map,this);
    });
    
    if (options.near) {
        marker.near = options.near;
    }
    
    markers.push(marker);
    
    if (options.selected) {
        marker.infowindow.open(map,marker);
    }
    
    return marker;
    
}

$(document).ready(function(){
    
    $('div.expandable').expander({
        slicePoint:       1000,  
        expandPrefix:     ' ', 
        expandText:       ' Далее', 
        collapseTimer:    0, 
        userCollapseText: 'Свернуть',
    });
        
    $('#ToggleLinkTownships').click(function(){
        $('ul#Townships').slideToggle('fast', function(){
            if ($(this).css('display') == 'none') {
                $('#ToggleLinkTownships').css('background-image', "url('/img/right_arrow.png')");
            } else {
                $('#ToggleLinkTownships').css('background-image', "url('/img/down_arrow.png')");
            }                
        });
    });
    
    $('#ToggleLinkTowns').click(function(){
        $('div#TownsDiv').slideToggle('fast', function(){
            if ($(this).css('display') == 'none') {
                $('#ToggleLinkTowns').css('background-image', "url('/img/right_arrow.png')");
            } else {
                $('#ToggleLinkTowns').css('background-image', "url('/img/down_arrow.png')");
            }                
        });
    });
    
    $('#ImagesContainer #Images img').click(function(){
        var src = $(this).attr('src');
        if ($.browser.webkit == true) {
            $('#Pic').attr('src', src);
        } else {
            $('#Pic').animate({
                opacity: '.1',
            }, {
                complete: function(){
                    $(this).attr('src', src);
                    $(this).animate({
                        opacity: 1
                    });
                }
            });
        }
    });
    
    
    
    $("#FeedbackError").bind("click", function(e){

        $("#FeedbackWindow #Errors").html('');
        $('#mask').css({'width':$(window).width(),'height':$(document).height()});
        $('#mask').fadeTo("slow",0.8);
        
        $('#FeedbackWindow').css('top', $(window).height() / 2 - $('#FeedbackWindow').height() / 2);
        $('#FeedbackWindow').css('left', $(window).width() / 2 - $('#FeedbackWindow').width() / 2);
        $('#FeedbackWindow').fadeIn(500);
        return false;
    });
    
    $('#FeedbackWindow .close a').live("click", function() {
        $('#mask').hide();
        $('#FeedbackWindow').hide();
    });
    
    
    
    $('#FeedbackWindow #Submit').live("click", function(){
        var Name = $('#FeedbackWindow input[name="Name"]').val();
        var Email = $('#FeedbackWindow input[name="Email"]').val();
        var Message = $('#FeedbackWindow textarea[name="Text"]').val();
        
        $("#FeedbackWindow #Errors").html('');
        
        regexp = /[a-zA-Z0-9\_\.\-]+\@[a-zA-Z0-9\_\.\-]+\.[a-zA-Z]{2,4}/gi;

        if (!Name) {
            $('#FeedbackWindow #Errors').html('<p>Укажите свое имя</p>');
        }
        if (! (Email && regexp.exec(Email))) $('#FeedbackWindow #Errors').append('<p>Укажите корректный email</p>');
        if (!Message) $('#FeedbackWindow #Errors').append('<p>Опишите проблему более подробно</p>');
        
        if ($('#FeedbackWindow #Errors').html()) {
            return;
        } else {
            $.ajax({
                type: 'POST',
                url: '/FeedBackError.html',
                data: {Name: Name, Email: Email, Message: Message, URL: window.location.href},
                success: function() {
                    $('#mask').hide();
                    $('#FeedbackWindow').hide();
                    alert('Ваше сообщение отправлено администратору');
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    alert('Произошла ошибка при отправке сообщения. Попробуйте отправить еще раз');
                }
            });
        }
    });

    $('#Action .Left a').click(function(){
        ActionIndex--;
        if (ActionIndex < 0) {
            ActionIndex = Actions.length - 1;
        }
        $('#Action #Inner').animate({
            opacity: 0
        }, {
            complete: function() {
                $('#Action #Inner').html('<div class="Pic"><img src="' + Actions[ActionIndex].ImageSrc + '" /></div>' +
                    '<div class="Text">' +
                    '<p class="header">' + Actions[ActionIndex].Title + '</p>' +
                    '<p>' + Actions[ActionIndex].Announce + '</p>' +
                    '<p class="more"><a target="_blank" href="' + Actions[ActionIndex].URL + '">' + Actions[ActionIndex].URLName + '</a></p></div>');
                $('#Action #Inner').animate({
                    opacity: 1,
                });
                
            }
        });
    });

    $('#Action .Right a').click(function(){
        ActionIndex++;
        if (ActionIndex > Actions.length - 1) {
            ActionIndex = 0;
        }
        $('#Action #Inner').animate({
            opacity: 0
        }, {
            complete: function() {
                $('#Action #Inner').html('<div class="Pic"><img src="' + Actions[ActionIndex].ImageSrc + '" /></div>' +
                    '<div class="Text">' +
                    '<p class="header">' + Actions[ActionIndex].Title + '</p>' +
                    '<p>' + Actions[ActionIndex].Announce + '</p>' +
                    '<p class="more"><a target="_blank" href="' + Actions[ActionIndex].URL + '">' + Actions[ActionIndex].URLName + '</a></p></div>');
                $('#Action #Inner').animate({
                    opacity: 1,
                });
            }
        });
    });
    
    updateGallery();    
    
});

var PicWidth = $('#Pic').width();

updateGallery = function() {
    if (document.getElementById('Gallery')) {
        $('#Gallery #leftArrow').unbind('click');
        $('#Gallery #rightArrow').unbind('click');
        if ($('#ImagesContainer #Images').position().left + $('#ImagesContainer #Images img:last').position().left > (PicWidth / 5 + 4) * 4) {
            $('#rightArrow').html('<a href="javascript:;"><img src="/img/grightdark.png" /></a>');
        
            $('#Gallery #rightArrow').bind('click', function(){
                $('#ImagesContainer #Images').animate({
                    left: '-=' + (PicWidth / 5 + 4) + 'px',
                }, {
                    complete: function(){
                        updateGallery();
                    }
                });
            });
        } else {
            $('#rightArrow').html('<img src="/img/grightlight.png" />');
        }
        
    //    alert($('#ImagesContainer #Images').position().left);
        
        if ($('#ImagesContainer #Images').position().left < 0) {
            $('#leftArrow').html('<a href="javascript:;"><img src="/img/gleftdark.png" /></a>');
        
            $('#Gallery #leftArrow').bind('click', function(){
                $('#ImagesContainer #Images').animate({
                    left: '+=' + (PicWidth / 5 + 4) + 'px',
                }, {
                    complete: function(){
                        updateGallery();
                    }
                });
            });
        } else {
            $('#leftArrow').html('<img src="/img/gleftlight.png" />');
        }
        
    }
    
}


function str_replace ( search, replace, subject ) {    // Replace all occurrences of the search string with the replacement string
    // 
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni

    if(!(replace instanceof Array)){
        replace=new Array(replace);
        if(search instanceof Array){//If search    is an array and replace    is a string, then this replacement string is used for every value of search
            while(search.length>replace.length){
                replace[replace.length]=replace[0];
            }
        }
    }

    if(!(search instanceof Array))search=new Array(search);
    while(search.length>replace.length){//If replace    has fewer values than search , then an empty string is used for the rest of replacement values
        replace[replace.length]='';
    }

    if(subject instanceof Array){//If subject is an array, then the search and replace is performed with every entry of subject , and the return value is an array as well.
        for(k in subject){
            subject[k]=str_replace(search,replace,subject[k]);
        }
        return subject;
    }

    for(var k=0; k<search.length; k++){
        var i = subject.indexOf(search[k]);
        while(i>-1){
            subject = subject.replace(search[k], replace[k]);
            i = subject.indexOf(search[k],i);
        }
    }

    return subject;

}


function in_array(what, where) {
    for(var i=0; i<where.length; i++)
        if(what == where[i]) 
            return true;
    return false;
}

