var colors = ['pink', 'blue', 'green'];

// Изменение внешнего вида на попап-окке текущего города
// type = plain, active
function changeCurrentCity(type) {
	var current_region = $('span.select-region-span:first').text(),
		$this = $('div.city-popup a:contains("'+current_region+'")');
	if (typeof type == 'undefined') type = 'plain';
	if (type == 'plain') {
		$this.replaceWith(current_region);
	}
	else {
		$this.addClass('active');
	}
}

function setActiveTab (index) {
	$('ul.tabs-title li:eq('+index+')').addClass('active');
}

function hideEmptyProjects(container) {
	$list = $(container).find('ul.projects-list > li');
	$list.each(function() {
		if ($(this).find('table.areatable').size() == 0) $(this).hide();
	});
	if ($list.filter(':visible').size() == 0) {
		$list.parent().hide().parent().before('<p class="no-projects">Ничего не найденно.</p>')
	}
}

// Изменение ширины левой колонки в зависимости от ширины экрана браузера
function resizeLeftCol() {
	var	width = $('.col-main').width(),
		width_left = (width > 1250) ? 257 : Math.ceil(width*0.15 + (width-1000)/250*69);
	$('.col-left').css('width', width_left);
	$('.col-main-in').css('margin-left', width_left+16);
	//$('.city-popup').css('left', width_left+24);
	$('.f-copy').css('width', width_left-47);
}


// Добавление линий к слайдеру
function AddHairline (container, pos, procent) {
	$touch = $(container).append('<div class="touch"></div>').find('div.touch:last');
	$touch.css('left', procent + '%');
  if (pos.toString().length > 0) $touch.html('<span>'+ pos +'</span>');
}

function AutoHairline (container, num) {
	if (container.length == 0) return;

	container.append('<div class="touches"></div>');
	var c = container.find('div.touches'),
		min = numberFormat(container.slider('option', 'min')),
		max = numberFormat(container.slider('option', 'max'));

	if (num >= 1) AddHairline(c, min, 0);
	if (num >= 2) AddHairline(c, max, 100);
	if (num >= 3) {
    num--;
		for (var i=1; i<num; i++)
      AddHairline(c, '', i/num*100);
	}
}


function filterNews (uri) {
    location.href = uri +'_t_/year='+ $('#select-year').val() +'/month='+ $('#select-month').val() +'/filial='+ $('#select-filial').val();
}

// Скрытие последней колонки, если она пустая
function lRemoveLastEmptyColumns() {
	$('table.areatable').each(function(){
		if ($(this).find('tbody tr td:last-child a').size() == 0) {
			$(this).find('tbody tr td:last-child, thead tr:first th:last').hide();
		}
		if ($(this).find('tbody tr td:nth-child(2) a').size() == 0) {
			$(this).find('tbody tr td:nth-child(2), thead tr:first th:nth-child(2)').hide();
		}
		


						
	});
}



// Автоматическая установка фонового изображения у документа, определяя тип по расширению
function projectDocAutoPic() {
  var uri = '';
  var reg_doc = /\.(doc|docx|txt)\/?$/i;
  var reg_jpg = /\.(jpg|jpeg|png|gif|bmp)\/?$/i;
  var reg_pdf = /\.(pdf)\/?$/i;
  var reg_xls = /\.(xls|xlsx)\/?$/i;
  $('div.project-docs ul li a').each(function() {
    $(this).removeAttr('class');
    uri = $(this).attr('href');
    if (reg_doc.test(uri) ) {
      $(this).addClass('doc-doc');
    }
    else if (reg_jpg.test(uri) ) {
      $(this).addClass('doc-jpg');
    }
    else if (reg_pdf.test(uri) ) {
      $(this).addClass('doc-pdf');
    }
    else if (reg_xls.test(uri) ) {
      $(this).addClass('doc-xls');
    }
  });
}


// OnReady
$(document).ready(function() {

	// Вкладки
  $tabs_title = $('ul.tabs-title');
  var realty_texts = ['Подобрать квартиру', 'Подобрать офис', 'Подобрать участок'];
  if ($tabs_title.find('li:not(.passive)').length == 0) {
    $tabs_title.hide()
      .parent().prev().removeClass('btitle-bot');
  }
  	$tabs_title.delegate('li:not(.active, .passive)', 'click', function() {
    var index = $(this).index();
		$(this)
			.addClass('active').siblings().removeClass('active')
			.parents('div.search-area').find('div.tab-body').removeClass('active').eq(index).addClass('active');
    $('div.projects').removeClass('active').hide().eq(index).addClass('active').fadeIn(200);
	var r_index;
      if ($(this).hasClass('tab-title-residental')) r_index = 0;
      if ($(this).hasClass('tab-title-commercial')) r_index = 1;
      if ($(this).hasClass('tab-title-suburban')) r_index = 2;
      $('#choose-realty-text').text(realty_texts[r_index]);
	});
    var gets = getQueryVariable();
  if (gets['type']) {
    var i;
    switch (gets['type']) {
      case 'residental': i = 0; break;
      case 'commercial': i = 1; break;
      case 'suburban':   i = 2; break;
    }
    $tabs_title.find('li:eq('+ i +')').click();
  }
  else {
    $tabs_title.find('li:not(.active, .passive):first').addClass('first').click();
  }

	// Показ маленькой карты справа с тултипами
	$map_right = $('div.map-right-hover');
	$map_area = $map_right.find('area');
	$map_area
		.click(function() {return false;})
		.qtip({
			content: {
				text: function(api) {
					var index = $map_right.find('area').index(this),
						$tooltip = $('div.map-list-out-'+index);
					return ($tooltip.length > 0) ? $tooltip : '<div class="map-list-out"><div class="map-list-value map-list-value-none">Нет активных городов</div></div>';
				}
			},
			style: {
				width:false, tip: {corner:'right top', width:27, height:19}
			},
			position: {
				my:'right top',
        at:'bottom center',
        adjust:{x:12, y:10}
			},
			show: {
				solo:true, effect:false
			},
			hide: {
				fixed:true,	delay:200, effect:false
			},
			events: {
				focus: function(event, api) {
          var index = this.id.substring(11);
					$map_right.css('background-position', '0-'+ (parseInt(index)*210) +'px');
          api.set('position.target', $('span.mrt-'+(parseInt(index)+1)));
				}
			}
		});

	var api = $map_area.data('qtip');
	$('.img-shadow img').click(function(){
		//alert(api.content.text);
		$map_area.qtip('option', 'content.text', function(){
			var index = $map_right.find('area').index(this),
				$tooltip = $('ul.map-list-value-1-'+index);
			return ($tooltip.length > 0) ? $tooltip : 'Нет активных городов';
		});
	});

	// Сity popup
	$('.select-region span').click(function() {
		$('.city-popup').fadeToggle(200);
		return false;
	});
	$('div.city-popup-close').click(function(){
		$(this).parent().fadeOut(200);
	});

  $('span.rmap-collapsing').click(function(){
    if ($(this).text() == 'Свернуть карту') {
      $(this).html('Развернуть карту<i></i>').addClass('rmap-collapse');
      $(this).next().addClass('map-right-collapse').animate({height:0}, 300);
      $.cookie('rmap-collapsing', null);
    }
    else {
      $(this).html('Свернуть карту<i></i>').removeClass('rmap-collapse');
      $(this).next().removeClass('map-right-collapse').animate({height:'210px'}, 300);
      $.cookie('rmap-collapsing', '1');
    }
  });
  if ($.cookie('rmap-collapsing') == '1') {
    $('span.rmap-collapsing').click();
  }

  
  /* ------------------------------- Галерея ------------------------------- */
  
  // Галерея изображений в проекте
  $('div.slides').each(function(){
    $slides = $(this);
    switch ($slides.find('img').size()) {
      case 0:
        $slides.hide();
        break;
      case 1:
        $slides.find('a.arrow-slide').removeAttr('href').click(function(){
          return false;
        }).end()
        .addClass('slides-disabled');
        break;
      default:
        $slides.slides({
          preload: true,
          preloadImage: '../img/loader.gif',
          play:0,
          pause:2500,
          hoverPause:true,
          pagination:false,
          generatePagination:false
        });
    }
  });

  // Изменение ширины ссылок-стрелок слева и справа изображения в галерее, чтобы они располагались вплотную к изображению
  function resizeArrowSlide() {
    $('div.slides').each(function() {
      var $this = $(this),
          w = $this.width(),
          wa = Math.ceil((w-716)/2);
      $this.find('a.arrow-slide').width((wa < 35) ? 35 : wa);
    });
  }

  // Ссылки с увеличивающимися картинками
  $('a.flyout').flyout();

  // OnReady
  resizeLeftCol();
  resizeArrowSlide();

  // OnResize
  $(window).resize(function(){
    resizeLeftCol();
    resizeArrowSlide();
  });
});
