$(document).ready(function(){
	$('.vendorLogoHolder .vendorWrapper a').mouseover( function(){ $(this).parents('.vendorWrapper').addClass('over'); });
	$('.vendorLogoHolder .vendorWrapper a').mouseout( function(){ $(this).parents('.vendorWrapper').removeClass('over'); });
});



// Обновление селект боксов в формах обратной связи
function updateOptions( oSelect ){
	var obj = $(oSelect);
	alert(oSelect);
	// FIXME
}





// Обновление селект боксов на главной в форме поиска
function switchUsedNew(num){
	if (num == 1){
		$('#vendorsSelectBox').html(newContent);
		$('#searchForm').attr('action', newAction);
		/*
		$('#searchForm input[name], #searchForm select[name]').each(function(i){
			var name = $(this).attr('name');
			$(this).attr('name', name.replace('tx_stdcat_pi1','tx_incom_pi4'));
		});
		*/
	} else {
		$('#vendorsSelectBox').html(usedContent);
		$('#searchForm').attr('action', usedAction);
		/*
		$('#searchForm input[name], #searchForm select[name]').each(function(i){
			var name = $(this).attr('name');
			$(this).attr('name', name.replace('tx_incom_pi4','tx_stdcat_pi1'));
		});
		*/
	}
}






// Обновление селект боксов в форме выбора комбинации в автомобилях
function updateSelectBoxes(sbobj){
	
	var engineSelector = $("#enginesSelectBox").get(0);
	var currentEngine = engineSelector.options[engineSelector.selectedIndex].value;
	var lastEngineOption = ( engineSelector.options.length <= 1 ) ? $("#enginesSelectBox option:first") : '';
	if (lastEngineOption) $("#transSelectBox option:first ~ option").remove();
	
	var transSelector = $("#transSelectBox").get(0);
	var currentCombID = transSelector.options[transSelector.selectedIndex].value;

	// Заполняем движки	
	for ( var eng in data ) {

		var selected = '';
		// если currentID есть в текущем движке ...
		if ( currentID && data[eng][currentID]) {
			selected =  ' selected ';
			currentID = '';
			currentEngine = eng;
		}

		// Если движки заполняем в первый раз
		if (lastEngineOption) lastEngineOption = lastEngineOption.after('<option'+ selected +' value="'+ eng +'">'+ eng +'</option>');
	}

	// Если для данного движка всего одна трансмиссия
	if ( currentEngine && sbobj == engineSelector ) {
		var count = 0;
		for ( var combID in data[currentEngine]  ) count++;
		if (count == 1) window.location.href = '/' + data[currentEngine][combID]['href'];
	}

	// Если есть выбранная КПП, но при этом функцию вызвал не движковый селект
	if ( currentCombID && sbobj != engineSelector) {
		if ( !currentEngine || currentID_backup ==  currentCombID ) return;
		window.location.href = '/' + data[currentEngine][currentCombID]['href'];
		return;
	}
	
	// Заполняем трансмиссии
	if ( currentEngine ) {
		$("#transSelectBox").removeAttr("disabled");
		$("#transSelectBox option:first ~ option").remove();
		lastTransOption = $("#transSelectBox option:first");
		for ( var id in data[currentEngine] ){
			selected = id == currentID_backup ? ' selected' : '';
			var trans = data[currentEngine][id]['trans'];
			trans = trans=='auto' ? 'Автоматическая' : 'Механическая';
			lastTransOption = lastTransOption.after('<option' +selected+' value="'+ id +'">'+ trans +'</option>');
		}
	} else {
		$("#transSelectBox").attr('disabled', 1 );
	}
}



// Считает количество свойств объекта
function countProperties(obj) {
  var count = "__count__",
  hasOwnProp = Object.prototype.hasOwnProperty;

  if (typeof obj[count] === "number" && !hasOwnProp.call(obj, count)) {
    return obj[count];
  }
  count = 0;
  for (var prop in obj) {
    if (hasOwnProp.call(obj, prop)) {
      count++;
    }
  }
  return count;
};



// Обработка оперций в прайс-листе
function processPriceList( complUID, optUID, checkObj ){
	var currentPrice = jsDataCompls[complUID].currentPrice ? jsDataCompls[complUID].currentPrice : jsDataCompls[complUID].price


	
	// Опция включена
	if ( checkObj.checked && ! jsDataOptions[complUID][optUID].checked ) {
		jsDataOptions[complUID][optUID].checked = true
		currentPrice = currentPrice + jsDataOptions[complUID][optUID].price
		
	} else if ( !checkObj.checked && jsDataOptions[complUID][optUID].checked ) {
		jsDataOptions[complUID][optUID].checked = false
		currentPrice = currentPrice - jsDataOptions[complUID][optUID].price	
	}
	
	// Проверяем исключенные опции на предмет исключения их другими опциями, кроме текущей
	if ( jsDataOptions[complUID][optUID].exclude ) {

		var excluded = new String(jsDataOptions[complUID][optUID].exclude).split(",");
		
		for ( i in excluded ){
			var doExclude = true;

			for ( uid in jsDataOptions[complUID] ) {
				// Пропускаем все опции без чекбоксов, ибо они не могут исключать другие опции
				if ( jsDataOptions[complUID][uid].enabled || !jsDataOptions[complUID][uid].price ) continue;
				// Если чекбокс неактивен - прорускаем тоже
				if ( !jsDataOptions[complUID][uid].checked ) continue;
				// Ничего не исключает
				if ( !jsDataOptions[complUID][uid].exclude ) continue;
				// Список исключенных
				tmpExcluded = new String(jsDataOptions[complUID][uid].exclude).split(",");
				for ( j in tmpExcluded ) if ( tmpExcluded[j] == excluded[i] ) { doExclude = false; break; }
			}
	
			// Мы не встретили другой опции, которая вырубает эту
			// При этом на галку нажали и активировали ее
			// Вырубаем опцию 
			if ( jsDataOptions[complUID][optUID].checked  ){
				// Выключаем, но сохраняем бывший контент
				if ( !jsDataOptions[complUID][excluded[i]].defaultContent )
					jsDataOptions[complUID][excluded[i]].defaultContent = $("#optcell_c"+ complUID +"o"+ excluded[i] ).html();
				$("#optcell_c"+ complUID +"o"+ excluded[i] ).html('<b class="yesNo">-</b>');
									
				// Если опция была с чекбоксом, и была активна, отнимаем сумму из общей суммы
				if ( ! jsDataOptions[complUID][excluded[i]].enabled && jsDataOptions[complUID][excluded[i]].price && jsDataOptions[complUID][excluded[i]].checked ) 
					currentPrice -= jsDataOptions[complUID][excluded[i]].price
				
			// Мы встретили другую опцию, которая вырубает эту
			// При этом на галку нажали и деактивировали ее
			// То есть опция занята другой - ничего не делаем
			} else if ( ! doExclude && ! jsDataOptions[complUID][optUID].checked ) {
				// nothing
	
			// Мы не встретили другую опцию, которая вырубает эту
			// При этом на галку нажали и активировали ее
			// То есть опцию можно включать - врубаем назад на исходный контент
			} else if ( doExclude && ! jsDataOptions[complUID][optUID].checked  ) {
				$("#optcell_c"+ complUID +"o"+ excluded[i] ).html(jsDataOptions[complUID][excluded[i]].defaultContent);
				
				// Если опция была с чекбоксом, и была активна, добавляем ее к сумме и не забываем сделать checked
				if ( ! jsDataOptions[complUID][excluded[i]].enabled && jsDataOptions[complUID][excluded[i]].price && jsDataOptions[complUID][excluded[i]].checked ) {
					currentPrice += jsDataOptions[complUID][excluded[i]].price			
					$("#optcell_c"+ complUID +"o"+ excluded[i] ).checkCheckboxes();
				}				
			}
		}

	} // if (excluded) {
	

	// Записываем итог
	jsDataCompls[complUID].currentPrice = currentPrice
	$("#totalCell_c"+ complUID).html( addSpacesToNumber(currentPrice) + ' руб.');
	//$("#totalCell_c"+ complUID).html( currentPrice + ' руб.');
}


// Добавляет пробел - разделиель тысяч
function addSpacesToNumber(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
	 x1 = x1.replace(rgx, '$1' + ' ' + '$2');
	}
	return x1 + x2;
}



// Обработка точек продаж и сервиса на карте
function processPoints(){
	var points = $('.map .point');
	if ( points ) {
		for (var i=0; i<points.length; i++ ){
			var left = points.eq(i).css('left');
			left = left.replace(/\D+/, '');
			var width = 200;
			if ( Number(left) + Number(width) > 450 ) points.eq(i).addClass('goRight');
			points.eq(i).bind( 'mouseenter mouseleave', function(e){ $(this).toggleClass("active"); } );
			points.eq(i).click(function() {
				window.location = '/' + $(this).find('a').attr('href');
			});
		}	
	}
}


// Перключалка вкладок в меню ЧК и ПС
function switchTab ( selector, num ){
	if ( num==1 ) {
		$(selector).eq(0).addClass('active');
		$(selector).eq(1).removeClass('active');
	} else {
		$(selector).eq(1).addClass('active');
		$(selector).eq(0).removeClass('active');
	}
}


// Показывает фотки на странице модели
function showPhoto( obj ){
	$('.foto a').removeClass('active');
	$(obj).addClass('active');
	$(obj).blur();
	
	var src = $(obj).parent().find('span img').get(0).src;
	var oncl = $(obj).parent().find('span a').get(0).onclick;
	$('.carViewHolder').css('background', 'url("'+src+'") no-repeat 50% 50%' );
	$('.carViewHolder').css('cursor', 'pointer' );
	$('.carViewHolder').get(0).onclick = oncl
}


// Открывает подробную карту в салонах/сервисах
function openBigimage(){
	var openFunc = $('.bigimage a').get(0).onclick;
	openFunc();
}


