$(document).ready(initPage);
function initPage()
{
    if($('#content_id').val() != '')
    {
        $('.sub-nav a').bind('click', function(e){
            load_tab(e, $('#content_id').val());
            return false;
        });
    };
    initSearchForm();
    if($("div.gallery").length) {
        $('div.gallery').galleryScroll();
    }
    ieHover();
    
    $('.open-tech-data').click(function(){
        if($('.tech-data').css('display') == 'none')
        {
            $('.tech-data').show();
        } else {
            $('.tech-data').hide();
        };
        return false;
    });
        
    if($('#map-contact').length>0){
        var lat = 50.013106;
        var lng = 36.234973;
        var latlng = new google.maps.LatLng(lat, lng);
        var myOptions = {
            zoom: 15,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map-contact"),
            myOptions);
            
        var image = '/public/templates/default/images/icons/icon_avantazh.png';

        var image_marker =  new google.maps.MarkerImage(image,
          new google.maps.Size(56, 56),
          new google.maps.Point(0,0),
          new google.maps.Point(20, 50));

        var objlatlng = new google.maps.LatLng(lat, lng);
        var marker = new google.maps.Marker({
            position: objlatlng, 
            map: map, 
            icon: image_marker
        });
    };
}
function initSearchForm() 
{
	var _formBlock = 'fieldset.search-form';
	
	$(_formBlock).find('input.text').focus(function() {
		if (this.value == this.defaultValue){ 
			this.value = '';
		}
	});
	$(_formBlock).find('input.text').blur(function() {
		if (this.value == ''){ 
			this.value = this.defaultValue;
		}
	});
}

eval(function(p,a,c,k,e,r){e=function(c){return c.toString(a)};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('9 t(a,b){g(3=0;3<a.h;3++){k c=[],d=[],n=[],e=[],4=[],l=[];8(a[3].5(\'.\')!=-1||a[3].5(\'#\')==-1){8(a[3].5(\'>\')!=-1){c[3]=a[3].f(a[3].5(\'>\')+2);a[3]=a[3].f(0,a[3].5(\'>\')-1)}8(a[3].5(\'.\')!=-1){d[3]=a[3].f(a[3].5(\'.\')+1);a[3]=a[3].f(0,a[3].5(\'.\'))}n[3]=a[3];8(!d[3])d[3]=\'\';8(c[3]){l[3]=r.o(n[3]);g(k j=0;j<l[3].h;j++){8(l[3][j].6.5(d[3])!=-1){4[3]=l[3][j].o(c[3]);g(k i=0;i<4[3].h;i++){4[3][i].p=9(){7.6+=\' \'+b};4[3][i].q=9(){7.6=7.6.m(b,\'\')}}}}}s{4[3]=r.o(n[3]);g(k i=0;i<4[3].h;i++){8(4[3][i].6.5(d[3])!=-1){4[3][i].p=9(){7.6+=\' \'+b};4[3][i].q=9(){7.6=7.6.m(b,\'\')}}}}}s 8(a[3].5(\'#\')!=-1){8(a[3].5(\'>\')!=-1){c[3]=a[3].f(a[3].5(\'>\')+2);a[3]=a[3].f(0,a[3].5(\'>\')-1)}a[3]=a[3].m(\'#\',\'\');e[3]=r.u(a[3]);8(e[3]){8(c[3]){4[3]=e[3].o(c[3]);g(k i=0;i<4[3].h;i++){4[3][i].p=9(){7.6+=\' \'+b};4[3][i].q=9(){7.6=7.6.m(b,\'\')}}}s{e[3].p=9(){7.6+=\' \'+b};e[3].q=9(){7.6=7.6.m(b,\'\')}}}}}}',31,31,'|||_hoverItem|_hoverElement|indexOf|className|this|if|function||||_class|_id|substr|for|length|||var|_parent|replace|_tag|getElementsByTagName|onmouseover|onmouseout|document|else|hoverForIE6|getElementById'.split('|'),0,{}));
/* insert your class and id ***********************
_hoverClassName = 'hover';
_hoverEl = ['ul.ul-class > li',	'div.div-class', 'span', '#box', '#nav > li'];
/**************************************************/
function ieHover() {
	hoverForIE6(['div.ico-state'], 'hover');
}

function load_photo(url, this_handler, container){
    if(container == undefined)
    {
        container='photo-container';
    }
    var li_handler = $(this_handler).parent();
    if(!li_handler.hasClass('active')){
        li_handler.parent().children(".active").removeClass();
        $('#'+container).fadeOut('fast',function(){ 
            $('#'+container).css('height',$('#'+container).height()+'px');
            $('#'+container).text('');
            var onclick_func ='';
            if(container == 'photo-container-large') {                
                onclick_func += 'onclick="next_photo();"';
            }
            $('#'+container).html('<img src="'+url+'"'+onclick_func+' alt=""/>');
            $('#'+container).ready(function(){                           
                $('#'+container).fadeIn('fast', function(){$('#'+container).css('height', '')});     
            });            
            li_handler.addClass('active');
            block_actions = false; 
        });
    }
}

/*
 *
 *      Скрипты для работы карт
 *
 */

var map;
var infobox_handler; 
var objects_markers = new Array();
var map_filter_selected = 'all';
var block_actions = false;

function init_map() {
    var latlng = new google.maps.LatLng(49.989201, 36.260948);
    var myOptions = {
        zoom: 11,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map"),
        myOptions);
        
    google.maps.event.addListener(map, 'click', function(event){
        if(infobox_handler != undefined){ 
            infobox_handler.setMap(null)
        };
    });  
    
    parse_objects();
}

function init_map_infra(id, lat, lng) {
    var latlng = new google.maps.LatLng(lat, lng);
    var myOptions = {
        zoom: 14,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map-infrasctructure"),
        myOptions);
        
    google.maps.event.addListener(map, 'click', function(event){
        if(infobox_handler != undefined){ 
            infobox_handler.setMap(null)
        };
    });  
    
    parse_infrastructure(id);
}

function add_object(object_type, name, photo_url, classtype, stage, area, link, coord_lat,  coord_lng)
{
    var image = get_image(object_type);
    
    var float_div ='<div class="map-baloon"><img width="184" height="144" src="'+photo_url+'" alt="'+name+'" /><div class="map-info-text"><h3><a href="'+link+'">'+name+'</a></h3><strong>Класс:</strong> '+classtype+'<br/><strong>Стадия:</strong> '+stage+'<br/><strong>Район:</strong> '+area+'<a href="'+link+'" class="map-info-link">Подробнее...</a></div></div>';    

    var image_marker =  new google.maps.MarkerImage(image,
      new google.maps.Size(61, 56),
      new google.maps.Point(0,0),
      new google.maps.Point(21, 54));
      
    var objlatlng = new google.maps.LatLng(coord_lat, coord_lng);
    var marker = new google.maps.Marker({
        position: objlatlng, 
        map: map, 
        icon: image_marker
    }); 
   
   google.maps.event.addListener(marker, "click", function(event) {
        if(infobox_handler != undefined){ 
            infobox_handler.setMap(null)
        };
        infobox_handler = new InfoBox({latlng: event.latLng, map: map, content: float_div});
   });
   
   objects_markers.push(Array(marker, object_type));
    
}

//удаляет все обеъекты
function filter_objects(new_map_filter)
{
    if (objects_markers && block_actions == false) {
        //убрать все открытые всплывающие окна  
        if(infobox_handler != undefined)
        {
            infobox_handler.setMap(null);
        }
  
        if(new_map_filter != 'all')
        {
            for (i in objects_markers) {
                if(objects_markers[i][1] != new_map_filter)
                {
                    objects_markers[i][0].setMap(null);
                }      
            }
        }
        if(map_filter_selected != new_map_filter){
            $('#filter_'+new_map_filter).addClass('active-filter');
            $('#filter_'+map_filter_selected).removeClass('active-filter');
        }
        
        if(map_filter_selected != new_map_filter && map_filter_selected != 'all')
        {
            parse_objects(new_map_filter);    
                
        } else {
            map_filter_selected = new_map_filter;  
        }  
        
    }
}

function filter_infr_objects(new_map_filter) {
    if (objects_markers && block_actions == false) {
        //убрать все открытые всплывающие окна  
        if(infobox_handler != undefined)
        {
            infobox_handler.setMap(null);
        }
  
        if(new_map_filter != 'all')
        {
            for (i in objects_markers) {
                if(objects_markers[i][1] != new_map_filter)
                {
                    objects_markers[i][0].setMap(null);
                }      
            }
        }
        if(map_filter_selected != new_map_filter){
            $('#filter_'+new_map_filter).addClass('active-filter');
            $('#filter_'+map_filter_selected).removeClass('active-filter');
        }
        
        if(map_filter_selected != new_map_filter && map_filter_selected != 'all')
        {
            parse_infrastructure($('#content_id').val(),new_map_filter);    
                
        } else {
            map_filter_selected = new_map_filter;  
        }  
        
    }
}

function add_infr_object(object_type, name, description, lat, lng) {
    var image = '/public/templates/default/images/icons/icon_infr_'+object_type+'.png';
    
    var float_div ='<div class="map-baloon"><h3>'+name+'</h3>'+description+'</div>'; 
    
    var image_marker =  new google.maps.MarkerImage(image,
      new google.maps.Size(56, 56),
      new google.maps.Point(0,0),
      new google.maps.Point(20, 50));
      
    var objlatlng = new google.maps.LatLng(lat, lng);
    var marker = new google.maps.Marker({
        position: objlatlng, 
        map: map, 
        icon: image_marker
    }); 
    
    google.maps.event.addListener(marker, "click", function(event) {
        if(infobox_handler != undefined) {
            infobox_handler.setMap(null)
        };
        infobox_handler = new InfoBox({latlng: event.latLng, map: map, content: float_div});
   });
   
   objects_markers.push(Array(marker, object_type));
}

function parse_objects(type_filter){
   block_actions = true;
   var xml_data;
   var type, name, photo, classtype, stage, area, link, lat, lng;
    $.ajax({
        url: '/public/templates/default/xml/objects.xml',
        dataType: (jQuery.browser.msie) ? 'text' : 'xml',
        success: function(xmlData)
        {
            if ( typeof xmlData == 'string') {                
                xml_data = new ActiveXObject( 'Microsoft.XMLDOM');
                xml_data.async = false;
                xml_data.loadXML( xmlData);
            } else {
                xml_data = xmlData;
            };
            
            $(xml_data).find('object').each(function(){
                type = $(this).find('type').text();
                if(type_filter != undefined)
                {
                    if(type_filter == type || (type != map_filter_selected && type_filter == 'all')){
                        name = $(this).find('name').text();
                        photo = $(this).find('photo').text();
                        classtype = $(this).find('class').text();
                        stage = $(this).find('stage').text();              
                        area = $(this).find('area').text();
                        link = $(this).find('link').text();
                        lat = $(this).attr('lat');
                        lng = $(this).attr('lng');
                        add_object(type, name, photo, classtype, stage, area, link, lat, lng);
                    }
                }
                else {
                    name = $(this).find('name').text();
                    photo = $(this).find('photo').text();
                    classtype = $(this).find('class').text();
                    stage = $(this).find('stage').text();              
                    area = $(this).find('area').text();
                    link = $(this).find('link').text();
                    lat = $(this).attr('lat');
                    lng = $(this).attr('lng');
                    add_object(type, name, photo, classtype, stage, area, link, lat, lng);
                }              
            });
            if(type_filter != undefined)
            {
                map_filter_selected = type_filter;  
            };
            block_actions = false;
        }
    });
}

function parse_infrastructure(id, type_filter){
    block_actions = true;
    var xml_data;
    var url_value = '/public/templates/default/xml/infrastr'+id+'.xml';    
    $.ajax({
        url: url_value,
        dataType: (jQuery.browser.msie) ? 'text' : 'xml',
        success: function(xmlData){
            if ( typeof xmlData == 'string') {                
                xml_data = new ActiveXObject( 'Microsoft.XMLDOM');
                xml_data.async = false;
                xml_data.loadXML( xmlData);
            } else {
                xml_data = xmlData;
            };
            
           $(xml_data).find('object').each(function(){
               var type = $(this).find('type').text();
               if(type_filter != undefined)
                {
                   if(type_filter == type || (type != map_filter_selected && type_filter == 'all')){ 
                   var name = $(this).find('name').text();
                  var description = $(this).find('description').text();
                  var lat = $(this).attr('lat');
                  var lng = $(this).attr('lng');
                  add_infr_object(type, name, description, lat, lng);
                    }
                }else {                  
                  var name = $(this).find('name').text();
                  var description = $(this).find('description').text();
                  var lat = $(this).attr('lat');
                  var lng = $(this).attr('lng');
                  add_infr_object(type, name, description, lat, lng);
               }
            });
            if(type_filter != undefined)
            {
                map_filter_selected = type_filter;  
            };
            block_actions = false;    
        }
    });
} 

function mark_object(object_type, coord_lat,  coord_lng){
   var arr = object_type.toString().split('_');
   if (arr[1] == 'Текущий') {
        stage = 0;
    } else if (arr[1] == 'Перспективный') {
        stage = 1;
    } else {
        stage = 2;
    };
   var image = get_image(arr[0]+'_'+stage);
   
   var image_marker =  new google.maps.MarkerImage(image,
      new google.maps.Size(61, 56),
      new google.maps.Point(0,0),
      new google.maps.Point(21, 54));
      
    var objlatlng = new google.maps.LatLng(coord_lat, coord_lng);
    var marker = new google.maps.Marker({
        position: objlatlng, 
        map: map, 
        icon: image_marker
        //,zIndex:1000
    }); 
}

function get_image(object_type){
    var image = '';
    switch (object_type) {
        case 'comm_0':
            image = '/public/templates/default/images/icons/icon_com_current.png';
            break; 
        case 'comm_1':
            image = '/public/templates/default/images/icons/icon_com_perspective.png';
            break;     
        case 'comm_2':
            image = '/public/templates/default/images/icons/icon_com_realized.png';
            break;
        case 'zhil_0':
            image = '/public/templates/default/images/icons/icon_zh_current.png';
            break;
        case 'zhil_1':
            image = '/public/templates/default/images/icons/icon_zh_perspective.png';
            break;  
        case 'zhil_2':
            image = '/public/templates/default/images/icons/icon_zh_realized.png';
            break;
        default:
            break;
    }
    return image;
}

function center_object(){
    if(map != undefined)
    {
        var arr = $('#coordinates').val().split(';');
        var lat = arr[0];
        var lng = arr[1]; 
        map.setCenter(new google.maps.LatLng(lat, lng)); 
    }
}
/* An InfoBox is like an info window, but it displays
 * under the marker, opens quicker, and has flexible styling.
 * @param {GLatLng} latlng Point to place bar at
 * @param {Map} map The map on which to display this InfoBox.
 * @param {Object} opts Passes configuration options - content,
 *   offsetVertical, offsetHorizontal, className, height, width
 */
function InfoBox(opts) {
  google.maps.OverlayView.call(this);
  this.latlng_ = opts.latlng;
  this.map_ = opts.map;
  this.offsetVertical_ = -245;
  this.offsetHorizontal_ = -68;
  this.height_ = 196;
  this.width_ = 384;
  this.content = opts.content;

  var me = this;
  this.boundsChangedListener_ =
    google.maps.event.addListener(this.map_, "bounds_changed", function() {
      return me.panMap.apply(me);
    });

  // Once the properties of this OverlayView are initialized, set its map so
  // that we can display it.  This will trigger calls to panes_changed and
  // draw.
  this.setMap(this.map_);
}

/* InfoBox extends GOverlay class from the Google Maps API
 */
InfoBox.prototype = new google.maps.OverlayView();

/* Creates the DIV representing this InfoBox
 */
InfoBox.prototype.remove = function() {
  if (this.div_) {
    this.div_.parentNode.removeChild(this.div_);
    this.div_ = null;
  }
};

/* Redraw the Bar based on the current projection and zoom level
 */
InfoBox.prototype.draw = function() {
  // Creates the element if it doesn't exist already.
  this.createElement();
  if (!this.div_) return;

  // Calculate the DIV coordinates of two opposite corners of our bounds to
  // get the size and position of our Bar
  var pixPosition = this.getProjection().fromLatLngToDivPixel(this.latlng_);
  if (!pixPosition) return;

  // Now position our DIV based on the DIV coordinates of our bounds
  this.div_.style.width = this.width_ + "px";  
  this.div_.style.left = (pixPosition.x + this.offsetHorizontal_) + "px";
  this.div_.style.height = this.height_ + "px";
  this.div_.style.top = (pixPosition.y + this.offsetVertical_) + "px";
  this.div_.style.display = 'block';
  
  console.log(this.div_.style.left+'-'+this.div_.style.top );
};

/* Creates the DIV representing this InfoBox in the floatPane.  If the panes
 * object, retrieved by calling getPanes, is null, remove the element from the
 * DOM.  If the div exists, but its parent is not the floatPane, move the div
 * to the new pane.
 * Called from within draw.  Alternatively, this can be called specifically on
 * a panes_changed event.
 */
InfoBox.prototype.createElement = function() {
  var panes = this.getPanes();
  var div = this.div_;
  if (!div) {
    // This does not handle changing panes.  You can set the map to be null and
    // then reset the map to move the div.
    div = this.div_ = document.createElement("div");
    div.style.border = "0px none";
    div.style.position = "absolute";
    div.style.width = this.width_ + "px";
    div.style.height = this.height_ + "px";
    var contentDiv = document.createElement("div");
    contentDiv.style.padding = "0px";
    contentDiv.innerHTML = this.content;

    var topDiv = document.createElement("div");
    topDiv.className = 'map-baloon-top';
    topDiv.style.textAlign = "right";
    var closeImg = document.createElement("img");
    closeImg.style.width = "32px";
    closeImg.style.height = "32px";
    closeImg.style.cursor = "pointer";
    closeImg.src = "http://gmaps-samples.googlecode.com/svn/trunk/images/closebigger.gif";
    topDiv.appendChild(closeImg);    
    
    var bottomDiv = document.createElement("div");
    bottomDiv.className = 'map-baloon-bottom';
    
    function removeInfoBox(ib) {
      return function() {
        ib.setMap(null);
      };
    }

    google.maps.event.addDomListener(closeImg, 'click', removeInfoBox(this));

    div.appendChild(topDiv);
    div.appendChild(contentDiv);
    div.appendChild(bottomDiv);
    div.style.display = 'none';
    panes.floatPane.appendChild(div);
    this.panMap();
  } else if (div.parentNode != panes.floatPane) {
    // The panes have changed.  Move the div.
    div.parentNode.removeChild(div);
    panes.floatPane.appendChild(div);
  } else {
    // The panes have not changed, so no need to create or move the div.
  }
}

/* Pan the map to fit the InfoBox.
 */
InfoBox.prototype.panMap = function() {
  // if we go beyond map, pan map
  var map = this.map_;
  var bounds = map.getBounds();
  if (!bounds) return;

  // The position of the infowindow
  var position = this.latlng_;

  // The dimension of the infowindow
  var iwWidth = this.width_;
  var iwHeight = this.height_;

  // The offset position of the infowindow
  var iwOffsetX = this.offsetHorizontal_;
  var iwOffsetY = this.offsetVertical_;

  // Padding on the infowindow
  var padX = 40;
  var padY = 40;

  // The degrees per pixel
  var mapDiv = map.getDiv();
  var mapWidth = mapDiv.offsetWidth;
  var mapHeight = mapDiv.offsetHeight;
  var boundsSpan = bounds.toSpan();
  var longSpan = boundsSpan.lng();
  var latSpan = boundsSpan.lat();
  var degPixelX = longSpan / mapWidth;
  var degPixelY = latSpan / mapHeight;

  // The bounds of the map
  var mapWestLng = bounds.getSouthWest().lng();
  var mapEastLng = bounds.getNorthEast().lng();
  var mapNorthLat = bounds.getNorthEast().lat();
  var mapSouthLat = bounds.getSouthWest().lat();

  // The bounds of the infowindow
  var iwWestLng = position.lng() + (iwOffsetX - padX) * degPixelX;
  var iwEastLng = position.lng() + (iwOffsetX + iwWidth + padX) * degPixelX;
  var iwNorthLat = position.lat() - (iwOffsetY - padY) * degPixelY;
  var iwSouthLat = position.lat() - (iwOffsetY + iwHeight + padY) * degPixelY;

  // calculate center shift
  var shiftLng =
      (iwWestLng < mapWestLng ? mapWestLng - iwWestLng : 0) +
      (iwEastLng > mapEastLng ? mapEastLng - iwEastLng : 0);
  var shiftLat =
      (iwNorthLat > mapNorthLat ? mapNorthLat - iwNorthLat : 0) +
      (iwSouthLat < mapSouthLat ? mapSouthLat - iwSouthLat : 0);

  // The center of the map
  var center = map.getCenter();

  // The new map center
  var centerX = center.lng() - shiftLng;
  var centerY = center.lat() - shiftLat;

  // center the map to the new shifted center
  map.setCenter(new google.maps.LatLng(centerY, centerX));

  // Remove the listener after panning is complete.
  google.maps.event.removeListener(this.boundsChangedListener_);
  this.boundsChangedListener_ = null;
};

var block_tabs = false;
// загрузчик табов на странице объекта
function load_tab(event, content_id)
{
    var element = event.target;
    var element_id = element.getAttribute('id');
    if(element_id != $('.sub-nav li.active').children().attr('id') &&
        block_tabs == false)
    {
        $('.sub-nav li').removeClass('active');
        $('#'+element_id).parent().addClass('active');
   
        $('.description-info:visible').hide('fast', function(){
            show_loading();
            if($('#tab'+element_id).html() != '')
            { 
                hide_loading();
                $('#tab'+element_id).show('fast');
        
            } else {
                if(element_id == "Plans" && element.getAttribute('class') == "building-schema"){
                  element_id = "comPlans";
                }
                load_tab_content(element_id, content_id);
            }       
        });
    }
}

function load_tab_content(tab_type, content_id) {
    //здесь загружается содержимое вкладки
    
    switch (tab_type) {
        case 'Infrastructure':
            var arr = $('#coordinates').val().split(';');
            var lat = arr[0];
            var lng = arr[1]; 
            
            $.ajax({
                type: "POST",
                url : "./public/ajax_infrastrukture.php",
                data: {
                    id           : content_id,
                    title        : $('#content h1').text(),
                    object_type  : $('#object_type').val()
                },
                success: function(data) {
                    $('#tabInfrastructure').html(data);
                    $('#tabInfrastructure').ready(function(){
                        init_map_infra(content_id, lat, lng);
                        mark_object($('#object_type').val(), lat, lng);
                        hide_loading();
                        $('#tabInfrastructure').show('fast');
                    });        
                }
            });
            break;
        case 'Plans':
            var content = $('#plans_field').val();
            var path = '/public/upload/plans_commerce/';
            var photos = content.split(';');
            var html = '<div id="popup-plan">';
            html += '<a href="#" onclick="load_full_plan(\''+path+photos[0]+'\');return false;"><img width="631" src="'+path+photos[0]+'" alt="планировка"/></a>';
            if(photos.length >2)
            {
                html+='<span class="swicher"><ul>';
                for(i in photos)
                {
                    if(photos[i] != '')
                    {
                        if(i == 0) html+='<li class="active">';
                        else html+='<li>';
                        html+='<a href="#" onclick="load_plan(this, \''+path+photos[i]+'\');return false;">'+(i+1)+'</a></li>';            
                    }
                }
                html+='</ul></span>';
            }
            html += '</div>';
            $('#tabPlans').append(html);
            $('#tabPlans').ready(function(){
                hide_loading();
                $('#tabPlans').show('fast');
            });
            break;
        case 'comPlans':
            $.ajax({
                type: "POST",
                url : "./content/ajax/getcombuilding/",
                data: {
                    id           : content_id
                },
                success: function(data) {
                    $('#tabPlans').html(data);
                    $('#tabPlans').ready(function(){
                        hide_loading();
                        $('#tabPlans').show('fast');
                    });                    
                }
            });
            break;
        case 'BuildNews':
            $.ajax({
                type: "POST",
                url : "./content/ajax/getbuildnews/",
                data: {
                    id           : content_id
                },
                success: function(data) {
                    $('#tabBuildNews').html(data);
                    $('#tabBuildNews').ready(function(){
                        hide_loading();
                        $('#tabBuildNews').show('fast');
                   });                    
                }
            });
            break;
        case 'SaleAppartments':
            $.ajax({
                type: "POST",
                url : "./content/ajax/getbuilding/",
                data: {
                    id           : content_id
                },
                success: function(data) {
                    $('#tabSaleAppartments').html(data);
                    $('#tabSaleAppartments').ready(function(){
                        hide_loading();
                        $('#tabSaleAppartments').show('fast');
                    });                    
                }
            });
            break;
            
        default:
            break;
    }   
}

function show_loading() {
    block_tabs = true;
    $('#loading').show();
}

function hide_loading() {
    block_tabs = false;
    $('#loading').hide();
}

function update_filter() {    
    var rooms_current, square, price, price_sqm, app_div;
    var min_square      = parseFloat($("#square-min").text());
    var max_square      = parseFloat($("#square-max").text());
    var min_price       = parseFloat($("#price-min").text());
    var max_price       = parseFloat($("#price-max").text());
    var min_price_sqm   = parseFloat($("#price-sqm-min").text());
    var max_price_sqm   = parseFloat($("#price-sqm-max").text());
    var rooms           = new Array();
    $('input[name="rooms_num"]:checked').each(function(){
        rooms.push( parseInt($(this).val()) );
    });
    $('.app-link').each(function(){        
        app_div     = $(this).parent();
        square      = parseFloat(app_div.children('input[name="square"]').val());
        price       = parseFloat(app_div.children('input[name="price_total"]').val());
        price = (price/1000.0).toFixed(1);
        price_sqm   = parseFloat(app_div.children('input[name="price_m"]').val());
        rooms_current = parseInt($(this).text());
        
        if( min_square > square || max_square < square    ||
            min_price > price   || max_price < price      ||
            min_price_sqm  > price_sqm  || max_price_sqm < price_sqm  ||
            $.inArray( rooms_current, rooms) == -1 )
        {
            if(!app_div.hasClass('inactive'))
            {
                app_div.addClass('inactive');
            }
        } else {
            if(app_div.hasClass('inactive'))
            {
                app_div.removeClass('inactive');
            }
        }
    });

}

//popup - code
function displayPopup(_popup){
	var popup_h;
	var _duration = 200;
	if($('#popup_fader').length == 0) $(document.body).append('<div id="popup_fader"></div>');
	popup_h = $('#popup_fader');
	if($.browser.msie && $.browser.version < 7) _popup.css({display:'none', top: $(window).scrollTop()});
	else _popup.css({display:'block', top: $(window).scrollTop()});
	//popup show add function here//
	popup_h.css({
		position:'fixed',
		top: 0,
		left: 0,
		zIndex: 3,
		background: '#000',
		height: $('body').height(),
		width: '100%'
	}).show();

	popup_h.click(function(){
		if($.browser.msie && $.browser.version < 7){
			_popup.hide();
			popup_h.hide();
		}
		else{
			_popup.fadeOut(_duration/2, function(){
				popup_h.fadeOut(_duration);
			});
		}
		hideSelectBoxes(_popup);
		return false;
	});
	popup_h.fadeTo(_duration, 0.75, function(){
		if($.browser.msie && $.browser.version < 7) _popup.show();
	});
	$(".close").live('click', function(){
		if($.browser.msie && $.browser.version < 7){
			popup_h.hide();
		}
		else{
			_popup.fadeOut(_duration/2, function(){
				popup_h.fadeOut(_duration);
			});
		}
		return false;
	});
}

function initPopup()
{
    var popup_html, rooms_current, square, price, price_sqm, app_div, params, num_section, num_floor, photo_url, is_commercial = false;
    if($('.commercial').length > 0) is_commercial = true;
    $('a.app-link').each(function(){
        var _box = $('.popup');
            
        $(this).bind('click', function() {
            app_div     = $(this).parent();
            square      = parseFloat(app_div.children('input[name="square"]').val());
            price       = parseFloat(app_div.children('input[name="price_total"]').val());
            price = price/1000.0;
            price_sqm   = parseFloat(app_div.children('input[name="price_m"]').val());
            photo_url   = app_div.children('input[name="photo_url"]').val();
            rooms_current = parseInt($(this).text());
            params = app_div.parent().attr('id').split('_');
            num_section = params[2];
            num_floor   = params[4];
            popup_html = '';
            if(photo_url != '')
            {
                popup_html += '<div class="photo-box"><img src="'+photo_url+'" alt="Планировка" /></div>';
            }
            if(is_commercial)
            {
                popup_html += '<div class="text-box">\n\
                                                <ul>\n\
                                                <li>Номер офиса: <strong>'+str_replace('b_appnum_', '', app_div.attr('id'))+'</strong></li>\n\
                                                <li>Секция: <strong>'+num_section+'</strong></li>\n\
                                                <li>Этаж: <strong>'+num_floor+'</strong></li>\n\
                                                <li>Количество комнат: <strong>'+rooms_current+'</strong></li>\n\
                                                <li>Площадь помещения: <strong>'+square+'&nbsp;м&sup2;</strong></li>\n\
                                                <li>Стоимость кв.м.: <strong>'+price_sqm+'&nbsp;у.е.</strong></li>\n\
                                                <li>Стоимость помещения: <strong>'+price.toFixed(1)+'&nbsp;тыс. у.е.</strong></li>\n\
                                                </ul>\n\
                                               </div>';
            } else 
            {
                popup_html += '<div class="text-box">\n\
                                                <ul>\n\
                                                <li>Номер квартиры: <strong>'+str_replace('b_appnum_', '', app_div.attr('id'))+'</strong></li>\n\
                                                <li>Секция: <strong>'+num_section+'</strong></li>\n\
                                                <li>Этаж: <strong>'+num_floor+'</strong></li>\n\
                                                <li>Количество комнат: <strong>'+rooms_current+'</strong></li>\n\
                                                <li>Площадь квартиры: <strong>'+square+'&nbsp;м&sup2;</strong></li>\n\
                                                <li>Стоимость кв.м.: <strong>'+price_sqm+'&nbsp;у.е.</strong></li>\n\
                                                <li>Стоимость квартиры: <strong>'+price.toFixed(1)+'&nbsp;тыс. у.е.</strong></li>\n\
                                                </ul>\n\
                                               </div>';
            }
            $('.popup .text-box, .popup .photo-box-floor, .popup .photo-box').remove();
            $('#popup-plan-full, .popup #popup-plan').remove();
            $('.popup .content').append(popup_html);
            $('.popup .content').ready(function(){
                displayPopup(_box);                            
            });                           
            return false;
        });   
    });
        
    var floor_current;
    $('a.floor-link').each(function(){
        var _box = $('.popup');
            
        $(this).bind('click', function(){
            app_div     = $(this).parent();
            photo_url   = app_div.children('input[name="photo_url"]').val();
            floor_current = parseInt($(this).text());
            params = app_div.parent().children('.building-floor').attr('id').split('_');
            num_section = params[2];
                
            popup_html = '<div class="photo-box-floor"><h2>Планировка '+floor_current+' этажа '+num_section+' секции</h2>';
            if(photo_url != '' && photo_url!= undefined)
{
                popup_html += '<img src="'+photo_url+'" alt="Планировка этажа" />'
            } else {
                popup_html += 'Планировка не задана.';
            }
            
            popup_html += '</div>';
                    
            $('.popup .text-box, .popup .photo-box-floor, .popup .photo-box').remove();
            $('#popup-plan-full, .popup #popup-plan').remove();
            $('.popup .content').append(popup_html);
            $('.popup .content').ready(function(){
                displayPopup(_box);                            
            });                           
            return false;
        });
    });
}

function str_replace(search, replace, subject) {
    return subject.split(search).join(replace);
}

function load_gallery(item_id, type, handler)
{
    $.ajax({
        type: "POST",
        url : "./content/ajax/getgallery/",
        data: {
            id           : item_id,
            gallery_type : type
        },
        success: function(data) {
            $('#tabBuildNews .photos li').removeClass('active');
            $(handler).parent().addClass('active');
            $('#tabBuildNewsGallery').html(data);
            /*$('#tabBuildNewsGallery').ready(function(){
                $('#tabBuildNewsGallery').show('fast');
            });*/                   
        }
    });
}

function next_photo() {
  if(!block_actions)
  {
        block_actions = true;
        var num_elems = $('#tabBuildNewsGallery .swicher ul li').length;
        if(num_elems > 1) {
            var active = $('#tabBuildNewsGallery .swicher ul li.active');
            if(active.index() == num_elems - 1){
                $('#tabBuildNewsGallery .swicher ul li:first a').click();
            } else {
                $('#tabBuildNewsGallery .swicher ul li').eq(parseInt(active.index()+1)).children('a').click();        
            }
        }
    }
}

function load_plans(content, path)
{
    var _box = $('.popup');
    $('.popup .text-box, .popup .photo-box-floor, .popup .photo-box').remove();
    $('#popup-plan-full, .popup #popup-plan').remove();
    var photos = content.split(';');
    var popup_html = '<div id="popup-plan">';
    popup_html += '<img src="'+path+photos[0]+'" alt="планировка"/>';
    if(photos.length >2)
    {
        popup_html+='<span class="swicher"><ul>';
        for(i in photos)
        {
            if(photos[i] != '')
            {
                if(i == 0) popup_html+='<li class="active">';
                else popup_html+='<li>';
                popup_html+='<a href="#" onclick="load_plan(this, \''+path+photos[i]+'\');return false;">'+(i+1)+'</a></li>';            
            }
        }
        popup_html+='</ul></span>';
    }
    popup_html += '</div>';
    $('.popup .content').append(popup_html);
    displayPopup(_box); 
}

function load_plan(handler, full_path) {
    $('#popup-plan .swicher li').removeClass('active');
    $(handler).parent().addClass('active');
    $('#popup-plan img').attr('src', full_path);   
    var click_fun = new Function("load_full_plan('"+full_path+"');return false;");
    $('#popup-plan a:first').attr('onclick', '').click(click_fun);
}

function load_full_plan(path) {
    var _box = $('.popup');
    $('.popup .text-box, .popup .photo-box-floor, .popup .photo-box').remove();
    $('#popup-plan-full, .popup #popup-plan').remove();
    var popup_html = '<div id="popup-plan-full">';
    popup_html += '<img src="'+path+'" alt="планировка"/>';
    popup_html += '</div>';
    $('.popup .content').append(popup_html);
    displayPopup(_box); 
}

function load_tech_table() {
    var _box = $('.popup');    
    var style_show = 'table';
    if($.browser.msie && $.browser.version <= 7) {
        style_show = 'block';
    }
    var popup_html = '<a class="close" href="#">закрыть</a><div id="popup-plan"><h1>Технические характеристики дома</h1><table cellspacing="0" cellpadding="0" border="1" style="display:'+style_show+';" class="tech-data">';
    popup_html += $('.tech-data').html();
    popup_html += '</table></div>';
    $('.popup .content').html(popup_html);
    $('.popup .content').ready(displayPopup(_box));
}
