
$(document).ready(function(){

    var options = {
        dataType: "html",

        success: function(data){
          $("#resultsDiv").html(data);
            $(".tablesorter").tablesorter({
                    headers: { 2: {sorter: false } }
            });
            $.notify.add('Обновлено',3);
        }
    };
    $("#fastSearch").ajaxForm(options);
    
        
    
    $("#fastModel, #fastEngine, #fastKpp, #fastYearFrom, #fastYearTo").change(function(){
        $("#fastSearch").submit();
    });
        
    $("#fastMarka").change(function(){
        var marka_id = $(this).val();
        if (marka_id == 0)
        {
            $("#fastModel").attr('disabled', 'disabled');
            $("#fastModel option").removeAttr('selected');
            $("#fastModel option:first").attr('selected', 'selected');
            $("#fastSearch").submit();
            return;
        }
        $.getJSON(
            'action-ajaxModelListGet.html?id='+marka_id,
            function(data){
                $("#fastModel option").each(function(){
                    if ($(this).val() != 0)
                    {
                        $(this).remove();
                    }
                });
                //парсинг новых моделей
                $.each(data.models, function(key, val) {
                    var tpl = '<option value="' + val.id+ '">' + val.head + '</option>';
                    $("#fastModel").append(tpl);
                });
                $("#fastModel").removeAttr('disabled');
                
                $("#fastSearch").submit();
            }
        );//getJSON
        
    });
    
    
    $("#tblSortable").tablesorter({
            headers: { 2: {sorter: false } }
    });
    
    
    //раздел мототехники
    $("#fastSearchMoto").ajaxForm({
        dataType: "html",
        success: function(data){
          $("#resultsDiv").html(data);
            $(".tablesorter").tablesorter({
                    headers: { 2: {sorter: false } }
            });
            $.notify.add('Обновлено',3);
        }
    });
    
        
    $(".sbmChange").change(function(){
        $("#fastSearchMoto").submit();
    });
})




/**
 * Добавление автомобиля в сравнение
 * @param id
 * @return
 */
function compareAdd(id)
{
    $.ajax({
	   type: "GET",
	   url: "/catalog/action-ajaxCompareAdd.html",
	   data: {id: id},
	   dataType: "json",
	   cache: false,
           success: function(msg){
	         if (msg.status == 'bad')
	         {
	        	 alert('Произошла ошибка - ' + msg.error);
	        	 return false;
	         }
		   
               document.getElementById('addCompareBlock').style.display = 'none';
	       //покажем правый блок, если был скрыт
               document.getElementById('compareBlock').style.display = 'block';
	       document.getElementById('compareBtn').style.display = 'block';
               
	       document.getElementById('compareRightHeader').style.display = 'block';
	       document.getElementById('compareIconCar').style.display = 'none';
	       
                $("#compareItems").hide();
                $("#compareItems").html("");
    	   
	       $(msg.cars).each(function(i)
		   {
	    	   tmp = '<div id="compareID'+ this.id + '" class="compareItems"><input type="button" value="" class="sr_del" onclick="compareOneDelete('+ this.id + ');" /><a href="#" class="ind_cat_autoname" style="margin-right:9px">' + this.head +
	    	   '</a><strong>'+ this.price + ' р.</strong>'+
	    	   '<font style="margin-left:9px;">' + this.year +' г.в.</font>'+
	    	   '</div>';
	    	   $(tmp).appendTo("#compareItems");
		   }
	       );
	       
	       $("#compareItems").show();
	       
	       
        }
     });
	  
	return;
}



function compareClean()
{
    if (confirm('Очистить список для сравнения?'))
    {
        $.ajax({
           type: "GET",
           url: "/catalog/action-ajaxCompareClean.html",
           datatype: "json",
           cache: false,
           success: function(msg){
                document.getElementById('compareBlock').innerHTML = '<div class="up_sr"></div><div class="ramka_kont_sr"><div class="right_ram_sr"><div class="centr_sr"><div style="width:260px; padding-top:4px;"><img src="/images/bp-srav-null.gif" width="73" height="26" alt="" style="margin:6px 0px 9px;"><br clear="all">Вы можете добавить в избранное любое предложение, а так же сравнивать машины из каталога.<br> </div><div id="compareItems"><div id="compareID{$itm.id}" class="compareItems"><br></div></div></div></div></div><div class="down_sr"></div>';
                 //удаление списка машин для сравнениея
                        $(".compareItems").each(function(){
                                $(this).remove();
                        });
            }
          });

        document.getElementById('compareItems').innerHTML = 'Вы можете добавить в избранное любое предложение, а так же сравнивать машины из каталога.';
        document.getElementById('compareBtn').style.display = 'none';
        document.getElementById('compareRightHeader').style.display = 'none';
        document.getElementById('compareIconCar').style.display = 'inline';

        //если на текущей странице автомобиля, то покажем ссылку добавления в сравнение
        lnkAddCompare = document.getElementById('addCompareBlock');
        if (lnkAddCompare != null ) document.getElementById('addCompareBlock').style.display = 'block';
        
        $(".compareAddLinks").each(function(){
            $(this).show();
        });
        //document.getElementById('compareBtn').style.display = 'none';
        //если на странице авто - то снова показать ссылку для добавления в сравнение
        //lnkAddCompare = document.getElementById('addCompareBlock');
        //if (lnkAddCompare != null ) document.getElementById('addCompareBlock').style.display = 'block';

        return true;
    }
}

function compareOneDelete(id)
{
	
    if (confirm('Удалить из списка сравнения?'))
    {
        //удаление
        $("#compareID" + id).remove();
        $("#lnk2addCompare" + id).show();

        $.ajax({
               type: "GET",
               url: "/catalog/action-ajaxCompareDeleteOne.html",
               data: {id: id},
               datatype: "json",
               cache: false,
            success: function(msg){
                     //alert(msg)
             }
            });
            
            
            //ничего не осталось - скроем блок
            if ($(".compareItems").length == 0)
            {
                document.getElementById('compareItems').innerHTML = 'Вы можете добавить в избранное любое предложение, а так же сравнивать машины из каталога.';
                document.getElementById('compareBtn').style.display = 'none';
                document.getElementById('compareRightHeader').style.display = 'none';
                document.getElementById('compareIconCar').style.display = 'inline';
            }

            //если на текущей странице автомобиля, то покажем ссылку добавления в сравнение
            if (id == current_id)
            {
                lnkAddCompare = document.getElementById('addCompareBlock');
                if (lnkAddCompare != null ) document.getElementById('addCompareBlock').style.display = 'block';
            }

        return false;
    }
    else return false;
	
}


/**
 * Удаление автомобиля из сравнения и обновление страницы
 * @param id
 * @return
 */
function compareOneDeleteAndRefresh(id)
{
	if (confirm('Удалить из списка сравнения?'))
	{
		//удаление
		$("#compareID" + id).remove();
		
	    $.ajax({
		 	   type: "GET",
		 	   url: "/catalog/action-ajaxCompareDeleteOne.html",
		 	   data: {id: id},
		 	   datatype: "json",
		 	   cache: false,
		        success: function(msg){
		 	         //alert(msg)
		         }
		      });
    	
	    document.location.href="action-compare.html";
		return false;
	}
	else return false;
	
	
}

/**
 * Получение списка моделей марки
 * @param marka_id
 * @return
 */
function getModelsRightMenu(marka_id)
{
	cleanModelList();
	
	$.getJSON("/catalog/action-ajaxModelListGet.html", {id: marka_id},
			function(json){
				innr = '';
	    		for (i=0; i<json.models.length; i++)
	    		{
	    			innr += "<option value='" + json.models[i].id + "'>"+ json.models[i].head + "</option>";
				    //console.log(json.models[i].head, json.models[i].id);
	    		}
	    		$(innr).appendTo("#rightMenuModelList");
			}
	)

}

/**
 * Получение списка марок в правом меню
 * @param tip_id
 * @return
 */
function getMarkaRightMenu(tip)
{
	cleanMarkalList();
	
	$.getJSON("/catalog/action-ajaxMarkaListGet.html", {tip_id: tip},
			function(json){
				innr = '';
	    		for (i=0; i<json.marks.length; i++)
	    		{
	    			innr += "<option value='" + json.marks[i].id + "'>"+ json.marks[i].head + "</option>";
				    //console.log(json.models[i].head, json.models[i].id);
	    		}
	    		$(innr).appendTo("#marka_id");
			}
	)

}

/**
 * Очистка списка марок
 * @return
 */
function cleanMarkalList()
{
	$("#marka_id option").each(function(i){
		if (i != 0)
		{
			$(this).remove();
		}
	});
}

/**
 * Очистка списка моделей
 * @return
 */
function cleanModelList()
{
	$("#rightMenuModelList option").each(function(i){
		if (i != 0)
		{
			$(this).remove();
		}
	});
}

/**
 * Переключение информационных блоков
 */
function switchInfo(id)
{
	if (id == 'vikup') {
		st_vikup = 'block'; 
		document.getElementById(id).parentNode.style.backgroundImage='url(/images/menu_select.gif)';	
		document.getElementById(id).parentNode.parentNode.childNodes[1].style.backgroundImage='url(/images/firm_str2.gif)';
		document.getElementById(id).style.color='#ffffff';	
	}
	else {
		st_vikup = 'none'; 	
		document.getElementById("vikup").parentNode.style.backgroundImage='url(/images/menu_back.gif)';	
			if (id=='obmen') {
				document.getElementById("vikup").parentNode.parentNode.childNodes[1].style.backgroundImage='url(/images/firm_str.gif)';	

			} else {
				document.getElementById("vikup").parentNode.parentNode.childNodes[1].style.backgroundImage='url(/images/menu_back.gif)';	
			}
		document.getElementById("vikup").style.color='#153978';
	}



	if (id == 'obmen') {
		st_obmen = 'block';
		document.getElementById(id).parentNode.style.backgroundImage='url(/images/menu_select.gif)';	
		document.getElementById(id).parentNode.parentNode.childNodes[1].style.backgroundImage='url(/images/firm_str2.gif)';
		document.getElementById(id).style.color='#ffffff';	
	}
	else {
		st_obmen = 'none';
		document.getElementById("obmen").parentNode.style.backgroundImage='url(/images/menu_back.gif)';
			if (id=='sale') {
				document.getElementById("obmen").parentNode.parentNode.childNodes[1].style.backgroundImage='url(/images/firm_str.gif)';	

			} else {
				document.getElementById("obmen").parentNode.parentNode.childNodes[1].style.backgroundImage='url(/images/menu_back.gif)';	
			}
		document.getElementById("obmen").style.color='#153978';
	}

	
	if (id == 'sale') {
		st_sale = 'block'; 
		document.getElementById(id).parentNode.style.backgroundImage='url(/images/menu_select.gif)';	
		document.getElementById(id).parentNode.parentNode.childNodes[1].style.backgroundImage='url(/images/firm_str4.gif)';
		document.getElementById(id).style.color='#ffffff';	
		

	}
	else {
		st_sale = 'none';
		document.getElementById("sale").parentNode.style.backgroundImage='url(/images/menu_back.gif)';
		document.getElementById("sale").parentNode.parentNode.childNodes[1].style.backgroundImage='url(/images/menu_right.gif)';
		document.getElementById("sale").style.color='#153978';	
	}
	
	document.getElementById('info-vikup').style.display = st_vikup;
	document.getElementById('info-obmen').style.display = st_obmen;
	document.getElementById('info-sale').style.display = st_sale;
	return false;
}


function mainmenuselect(obj) {
	obj.parentNode.parentNode.childNodes[0].style.backgroundImage='url(/images/mmenu_select.gif)';
	obj.parentNode.parentNode.childNodes[1].style.backgroundImage='url(/images/mmenu_right.gif)';	
	obj.parentNode.parentNode.childNodes[0].style.color="#FFFFFF";
}

function mainmenuselectout(obj) {
	obj.parentNode.parentNode.childNodes[0].style.backgroundImage='url(/images/menu_back.gif)';	
	obj.parentNode.parentNode.childNodes[1].style.backgroundImage='url(/images/menu_right.gif)';	
	obj.parentNode.parentNode.childNodes[0].style.color="#153978";
}

/**
 * Добавление в сравнение из списка автомобилей
 */
function addToCompare(id)
{
    $.ajax({
	type: "GET",
	url: "/catalog/action-ajaxCompareAdd.html",
	data: {id: id},
	dataType: "json",
	cache: false,
        success: function(msg){
          if (msg.status == 'bad')
          {
             alert('Произошла ошибка - ' + msg.error);
             return false;
          }

          document.getElementById('lnk2addCompare'+id).style.display = 'none';
          //покажем правый блок, если был скрыт
          document.getElementById('compareBlock').style.display = 'block';
          document.getElementById('compareBtn').style.display = 'block';

          document.getElementById('compareRightHeader').style.display = 'block';
          document.getElementById('compareIconCar').style.display = 'none';

          $("#compareItems").html(""); //очистить список справа

           $(msg.cars).each(function(i)
               {
               tmp = '<div id="compareID'+ this.id + '" class="compareItems"><input type="button" value="" class="sr_del" onclick="compareOneDelete('+ this.id + ');" /><a href="#" class="ind_cat_autoname" style="margin-right:9px">' + this.head +
               '</a><strong>'+ this.price + ' р.</strong>'+
               '<font style="margin-left:9px;">' + this.year +' г.в.</font>'+
               '</div>';
               $(tmp).appendTo("#compareItems");
               }
           );
	       
	   $("#compareItems").show();
        }
     });
    return true;
}


function requestCar(id)
{
    $("#requestDialog").dialog({
        modal: true,
        width: 700
    });
    
    var options = {
      dataType: "json",
      resetForm: true,
      beforeSubmit: function(){
          var fio = $("#rqForm [name=fio]");
          if (fio.val() == '')
          {
              $.notify.add('Не указаны ФИО', 'errorMsg', 4);
              fio.focus();
              return false;
          }
          var eml = $("#rqForm [name=email]");
          if (eml.val() == '')
          {
              $.notify.add('Не указан e-mail', 'errorMsg', 4);
              eml.focus();
              return false;
          }
          return true
      },
      success: function(data){
          
          $.notify.add('Ваша заявка принята', 5);
          $("#requestDialog").dialog("close");
      }
    }
    $("#rqForm").ajaxForm(options);
}

/*menu2011*/
mouseover = Array();
function id1() {
	for (i=1; i<7; i++) {
		var id = "m2011-"+i;
		var elm1 = document.getElementById(id);
		mouseover[id] = false;
		elm1.onclick = function() {
			for (i=1; i<7; i++) {
			var id2 = "m2011-"+i;
			var id3 = "m2011-"+i+"-1";
			var elm2 = document.getElementById(id2);
			var elm3 = document.getElementById(id3);
			elm2.className="";
			elm3.style.display="none";
			}
			this.className="menu-st-on"; 
			document.getElementById(this.id+"-1").style.display="block";
			
		}

	}
}
