var url = 'http://'+location.hostname;
var spin = '<div style="width:100%;text-align:center;"><img src="'+url+'/components/com_vm_ext_search/img/spinner.gif"/></div>';
var left=0;
var width=0;
jQuery.noConflict();
jQuery(document).ready(function(){
f_adding()
adding()

});
 
//при изменении категории меняем все остальное
function mod_categoryChange() {
    var qString = jQuery("#mod_vm_search_form").formSerialize();
    jQuery("#mod_typ_div").fadeTo("slow", 0.22);
    jQuery("#mod_mf_div").fadeTo("slow", 0.22);
    jQuery.ajax({
        type: "POST",
        url: url+'/index2.php?task=ajax_com&no_html=1&task2=manufacturer',
        data: qString,
        dataType: 'HTML',
        success: function (data){
            jQuery("#mod_mf_div").html(data);
            jQuery("#mod_mf_div").fadeTo("slow", 1);
        }
    });
    jQuery.ajax({
        type: "POST",
        data: qString,
        url: url+'/index2.php?task=ajax_mod&no_html=1&task2=typ',
        dataType: 'HTML',
        success: function (data){
            jQuery("#mod_typ_div").html(data);
            jQuery("#mod_typ_div").fadeTo("slow", 1);
            mod_typeChange();
        }
    });
return;
}

function mod_mfChangeMulti() {
    var qString = jQuery("#mod_vm_search_form").formSerialize();
    jQuery("#mod_typ_div").fadeTo("slow", 0.22);
//    jQuery("#com_harakt_div").slideUp("slow");
    jQuery.ajax({
        type: "POST",
        url: url+'/index2.php?task=ajax_mod&no_html=1&task2=typ',
        data: qString,
        dataType: 'HTML',
        success: function (data){
            jQuery("#mod_typ_div").html(data);
            jQuery("#mod_typ_div").fadeTo("slow", 1);
            mod_typeChange();
        }
    });
    return;
}

function mod_typeChange(){
    var qString = jQuery("#mod_vm_search_form").formSerialize();
    jQuery("#mod_harakt_div").fadeTo("slow", 0.22);
    jQuery.ajax({
        type: "POST",
        url: url+'/index2.php?task=ajax_mod&no_html=1&task2=harakt',
        data: qString,
        dataType: 'HTML',
        success: function (data){
            jQuery("#mod_harakt_div").html(data);
            jQuery("#mod_harakt_div").fadeTo("slow", 1);
        }
    });
    return;
}

function mod_loadProduct( limitstart,a,typ ){
    if(typ==0&&parseInt(jQuery("#f_disk_total").val())>0){//если фильтрация в примерке - обнулять, для кореектности
        jQuery("#f_disk_count").attr('value',0);
        left=0;
    } 
    if(typ==0)//Подборки по внутреннему фильтру(количество, тип, сезон и тд)
        var into=jQuery("#main_search");
    else if(typ==1)//Подборки слева
        var into=jQuery("#vmMainPage");
    else if(typ==2)//Подбокра с морды
        var into=jQuery("#innerMainPage");
    else if(typ==3)//Примерка дисков
        var into=jQuery("#f_disk_filter");  
    else if(typ==4)//Примерка дисков, подгрузка
        var into=jQuery("#f_disk_view_centr");  
    var qString = jQuery("#"+a).formSerialize();
    if(typ!=4){
        if(typ!=3)
            f_disk_remove();
        into.html('<div id="loader">Подождите, идет загрузка...<img src="/images/stories/ajax-loader.gif"></div>');   }
    jQuery.ajax({
        type: "POST",
        url: url+'/index2.php?task=ajax_mod&task2=load_page&limitstart='+limitstart+'&no_html=1',
        data: qString+'&type='+typ+m_s_p(a),
        dataType: 'HTML',
        success: function (data){
                if(typ!=4)
                    into.html(data).fadeTo("slow", 1);
                else{
                    into.append(data).fadeTo("slow", 1);
                    f_disk_center_resize();
                }
                if(typ!=0&&typ!=4)                  
                    adding();
                if(typ==1)
                    adding_tips();
                if(typ==2)
                   into.find('h3').eq(0).remove(); 
                if(typ==0&&parseInt(jQuery("#f_disk_total").val())>0){
                    f_disk_resize();
                }
                if(typ==3)
                   feel_wheel()//Если у нас в первый раз загружаются шины и машина - делаем ресайз стандартных шин
                        
                    
        }
    });
    return;
}

function mod_uncheck( name ){
    for (var obj = document.getElementsByName ( name ), j = 0; j < obj.length; j++) obj [j].checked = false;
    if (name == 'mf_id[]') mod_mfChangeMulti();
    else mod_typeChange();
}

function set_filter(type,id ){
    type=type.split(" ");
    type=type[0];
  if(type=='c1'||type=='c2'||type=='c3'){  
    var tmp=jQuery('#mod_vm_search_form .cat_param').val().split("");
    tmp[type[1]]=id;
    tmp=tmp.join("");
    jQuery('#mod_vm_search_form .cat_param').val(tmp);
  }
  else if(type=='srpp'){
         jQuery('#srpp').val(id);
  }
  else if(type=='sort'){
         number_sort(id);
  }
  mod_loadProduct(0,'mod_vm_search_form',0);  
}
//--------------------Обработка подбора по авто с левой колонки
function reload_main(limitstart,form,type){

if(jQuery('#'+form).find('select[name="mark"]').attr('disabled')!='disabled'&&jQuery('#'+form).find('select[name="modification"] option:selected').val()==0){
       alert('Выберите пожалуйста все пункты');   
    }
    else{
       if(jQuery('#vmMainPage').size()==0)
        jQuery('#center').html("<div id='vmMainPage'>&nbsp</div>");
       jQuery('#fast_podbor').remove();
       mod_loadProduct(0,form,1); 
    }
    

}
//--------------------Обработка подбора по авто с морды
function reload_vvod(limitstart,form,type){
    if(form=='fastpodbor_body_a_f'&&jQuery('#'+form).find('#fastvvod_modification option:selected').val()==0){
        alert('Выберите пожалуйста все пункты');
    }
    else{
       if(jQuery('#vmMainPage').size()==0){
        jQuery('#gl_menu, #hit').remove();
        jQuery('#center').append("<div id='vmMainPage'>&nbsp</div>");
        }
        jQuery('#fast_podbor div.titl_brand').show();
        jQuery('#fast_podbor div.body_brand,table.blog').hide();
        jQuery('#fast_podbor div.titl_brand').click(function(){
           jQuery(this).parent().find('div.body_brand').toggle(); 
        });
        
        mod_loadProduct(0,form,1);  
    }
}
//--------------------Обработка примерки дисков
function reload_f_disk(){
    var modification=jQuery('#f_disk_main').find('#fastvvod_modification option:selected').val();
    fuckin_global_wheel_img_this="00000000-0000-0000-0000-000000000000-00000.png";//Если у нас ещё не выбраны шины мы поставляем стандартные
    if(modification!=0){
                
        //var imageObj = new Image();
        //imageObj.onload = function () {
        //    f_disk_show_all(modification);
        //};
        //imageObj.onerror = function () {
        //    f_disk_close_all();
        //};
        //imageObj.src="/images/stories/auto_view/"+modification+".png";
        left=0;
        mod_loadProduct(0,'f_disk_main',3);  
        jQuery('#car_model').css('background','url("/images/stories/auto_view/'+modification+'.png")').html('');
    }
    else{
        alert('Выберите пожалуйста все пункты');
    }
}

function f_adding(){
    jQuery('span.sort_click').click(function(){
        jQuery(this).parent().parent().find('.sort_field').hide().parent().find("select").attr('disabled','disabled');
        jQuery(this).parent().find('.sort_field').show().find("select").removeAttr('disabled');
        if(jQuery(this).parent().find('select[name="mark"]').size()==1){
            jQuery(this).parent().find('select[name="mark"] option').removeAttr('selected').eq(0).attr('selected','selected').parent().trigger('change')
        } 
    }); 
    jQuery('#fastpodbor_vid input').click(function(){
        var a=jQuery(this).parent().parent().parent().find('input[name="cat_param"]').val().split("");
        a[3]=jQuery(this).val();
        a=a.join("");
        jQuery(this).parent().parent().parent().find('input[name="cat_param"]').val(a); 
    });
    jQuery('#fastpodbor_heading span').click(function(){
        jQuery('#fastpodbor_heading span').removeClass("fast_a");
        jQuery(this).addClass('fast_a'); 
    });  
    jQuery('#fast_s').click(function(){
        jQuery('div.fastpodbor_body').hide()
        jQuery('#fastpodbor_body_t').show();
    });
    jQuery('#fast_w').click(function(){
        jQuery('div.fastpodbor_body').hide()
        jQuery('#fastpodbor_body_w').show(); 
    }); 
    jQuery('#fast_a').click(function(){
        jQuery('div.fastpodbor_body').hide()
        jQuery('#fastpodbor_body_a').show(); 
    }); 
    jQuery('div.left_heading').click(function(){
        jQuery('div.left_body').hide()
        jQuery(this).parent().find('.left_body').show(); 
    });  
    jQuery('#address_delivery_r1').click(function(){
        if(jQuery('div.all_delivery').css('display')!='block')
            jQuery('div.all_delivery, div.all_store').toggle();
    });
    jQuery('#address_delivery_r2').click(function(){
        if(jQuery('div.all_store').css('display')!='block')
            jQuery('div.all_delivery, div.all_store').toggle();
    });  
    //-----Навешиваем на выборку по авто
jQuery('select[name="mark"]').change(function(){
    var mark=jQuery(this).find('option:selected').val();
    //Если это примерка дисков - показываем толькопроверненные модели с картинками
    var adding="";
    if(jQuery(this).parent().parent().parent().attr('id')=='f_disk_main')
       adding="&adding=1";
    if(mark!=0){
       jQuery.ajax({
        type: "POST",
        url: url+'/index2.php?task=ajax_mod&no_html=1&task2=model',
        data: '&option=com_vm_ext_search_free&mark='+mark+adding,
        dataType: 'HTML',
        success: function (data){
           jQuery('select[name="model"]').removeAttr("disabled").html(data);
            }
        }); 
        jQuery('select[name="year"],select[name="modification"]').html('<option value="0">-</option>').attr('disabled','disabled');  
    }
    else    
      jQuery('select[name="model"],select[name="year"],select[name="modification"]').html('<option value="0">-</option>').attr('disabled','disabled');   
});
//-----Навешиваем на выборку по модификациям
jQuery('select[name="model"]').change(function(){
    var model=jQuery(this).find('option:selected').val();
        //Если это примерка дисков - показываем толькопроверненные модели с картинками
    var adding="";
    if(jQuery(this).parent().parent().parent().attr('id')=='f_disk_main')
        adding="&adding=1";
    if(model!=0){
       jQuery.ajax({
        type: "POST",
        url: url+'/index2.php?task=ajax_mod&no_html=1&task2=year',
        data: '&option=com_vm_ext_search_free&model='+model+adding,
        dataType: 'HTML',
        success: function (data){
           jQuery('select[name="year"]').removeAttr("disabled").html(data);
            }
        });
        jQuery('select[name="modification"]').html('<option value="0">-</option>').attr('disabled','disabled');  
    }
    else    
      jQuery('select[name="year"],select[name="modification"]').html('<option value="0">-</option>').attr('disabled','disabled');   
});
//------- 
//-----Навешиваем на выборку по модификациям
jQuery('select[name="year"]').change(function(){
    var year=jQuery(this).find('option:selected').val();
        //Если это примерка дисков - показываем толькопроверненные модели с картинками
    var adding="";
    if(jQuery(this).parent().parent().parent().attr('id')=='f_disk_main')
        adding="&adding=1";
    if(year!=0){
       jQuery.ajax({
        type: "POST",
        url: url+'/index2.php?task=ajax_mod&no_html=1&task2=modification',
        data: '&option=com_vm_ext_search_free&year='+year+adding,
        dataType: 'HTML',
        success: function (data){
           jQuery('select[name="modification"]').removeAttr("disabled").html(data);
            }
        }); 
    }
    else    
      jQuery('select[name="modification"]').html('<option value="0">-</option>').attr('disabled','disabled');   
});
//--ДЛя показа подсказок
    jQuery('img.show_tips').live('click',function(){
       jQuery.get('/modules/mod_vm_universal_search_free/files/aj_tips.php', function(data) {
        jQuery('body').append(data).find('div.cbContainer').fadeIn(400);
       });
    });
    jQuery('form.addtocart_form').live('submit',function(){
       jQuery.get('/modules/mod_vm_universal_search_free/files/aj_tmpl.php', function(data) {
        jQuery('body').append(data);
       });
       var qString = jQuery(this).formSerialize(); 
       jQuery.ajax({
        type: "POST",
        url: jQuery(this).attr('action'),
        data: qString,
        dataType: 'HTML',
        success: function (data){ 
               jQuery('div.cbContent').html(data).parent().parent().fadeIn(400).delay(2000).fadeOut(400);
               jQuery.ajax({
                        type: "POST",
                        url: url,
                        data: "only_page=1&page=shop.basket_short&option=com_virtuemart",
                        dataType: 'HTML',
                        success: function (data){
                             jQuery('div.vmCartModule').html(data).fadeOut(0).fadeIn(800);
                        }
                });
        }
       });
       return false;
    });
    jQuery('div.cbCloseButton').live('click',function(){
        jQuery('div.cbContainer').remove();
    });
    jQuery('div.cbButtons input').live('click',function(){
        if(jQuery(this).attr('value')=="Продолжить"||jQuery(this).attr('value')=="Закрыть")
            jQuery('div.cbContainer').remove();
        if(jQuery(this).attr('value')=="Корзина"){
           location=url+"/index.php?option=com_virtuemart&page=shop.cart"; 
        }
            
    });
//-------Для полного вида товара
jQuery('a[href*="shop.product_view"]').live('click',function(){
       jQuery('.imazafak').removeClass('imazafak');
       jQuery(this).addClass('imazafak');
       jQuery.get('/modules/mod_vm_universal_search_free/files/aj_shop_view.php', function(data) {
       jQuery('body').append(data);
        jQuery.ajax({
            type: "POST",
            url: jQuery('.imazafak').attr('href').replace("index.php","index2.php"),
            dataType: 'HTML',
            success: function (data){
                data=data.split('body');
                if (  !jQuery.browser.msie )
                    data=data[1].slice(46,-10);//46
                else
                    data=data[1].slice(25,-10);
               jQuery('div.cbContent1').html(data).fadeIn(400);
               jQuery('#shop_detail_dop_h tr:even').addClass('sectiontableentry2').eq(0).removeClass('sectiontableentry2');
               
            }
        });
       });
       return false;
})
//-------  
    jQuery('#inner_menu_td').mouseenter(
        function(){jQuery('#inner_menu').show();}
    );
    jQuery('#inner_menu').parent().mouseleave(
        function(){jQuery('#inner_menu').hide();}
    );
//----Для примерки дисков
jQuery('#f_disk_find').click(function(){
    reload_f_disk();
    load_car_model();
});
//Для переключения чекбокса при примерке диска
jQuery('#f_disk_ch input[type="checkbox"]').click(function(){
    if(jQuery(this).attr('checked')!='checked'){
      jQuery('#fd_model input[name="find_without_store_and_price"],#f_d_name, #f_d_val').removeAttr('disabled'); 
    }
    else{
      jQuery('#fd_model input[name="find_without_store_and_price"],#f_d_name, #f_d_val').attr('disabled','disabled');  
    }
});
//------При ресайзе
jQuery(window).resize(function(){
    if(jQuery('#f_disk_view').length > 0)
        f_disk_resize();    
});

//Вправо
    jQuery('#f_disk_view_r').live('click',function(){
        f_disk_r(); 
        return false;   
    });
//Влево
    jQuery('#f_disk_view_l').live('click',function(){
        f_disk_l(); 
        return false;   
    });
//------Конец
}
function adding(){//То, что навешивается постоянно - фильтрация
    jQuery('#mod_s_form span.c3').click(function(){
        jQuery('#mod_s_form span.c3 img').removeClass('sezon_img_a');
        jQuery(this).find('img').addClass('sezon_img_a');
        switch (jQuery(this).attr('rel')){
            case '1': jQuery('#i_3, #i_4').hide(); break;
            case '2': jQuery('#i_3, #i_4').show(); break;
            case '3': jQuery('#i_2').addClass('sezon_img_a'); break;
            case '4': jQuery('#i_2').addClass('sezon_img_a'); break;
            default : jQuery('#mod_s_form span.c3 img').removeClass('sezon_img_a'); jQuery('#i_3, #i_4').hide();
        }
    });
    jQuery('#mod_s_form span[rel="0"]').not('.srpp').addClass('f_activ');
    jQuery('#mod_s_form span.srpp').eq(jQuery('#srpp').val()).addClass('f_activ');
    jQuery('#mod_s_form span').click(function(){
        jQuery('#mod_s_form .'+jQuery(this).attr('class')).removeClass('f_activ');
        jQuery(this).addClass('f_activ');
        set_filter(jQuery(this).attr('class'),jQuery(this).attr('rel'));
    });
    jQuery('#f_d_filtr_s').change(function(){
        var a=jQuery('#f_d_filtr');
        if(jQuery(this).find("option:selected").text()=="Все"){
            a.attr('name','modification');    
        }
        else{
            a.attr('name','f_disk_typ');             
        }
        a.attr('value',jQuery(this).find("option:selected").val());
        mod_loadProduct(0,'mod_vm_search_form',0);  
    });
    f_disk_resize();
}
function adding_tips(){
   jQuery('#tips a').click(function(){
   var a=jQuery(this).attr('href');
   a=m_s_a(a);
  jQuery(this).parent().find('div.param_search').html(a);
   mod_loadProduct(0,jQuery(this).parent().attr('id'),2);
   return false;
}); 
}  
function m_s_p(form){
    var tmp="";
   jQuery("#"+form).find('select:enabled').each(function(){
       tmp+="&s_name[]="+jQuery(this).attr('name')+"&s_val[]="+jQuery(this).find(' option:selected').val();
   }); 
    return tmp;
}
function m_s_a(href){
    var tmp='';
    href=href.split("&");
    for(var i=0;i<href.length;i++){
       href[i]=href[i].split("=");
       tmp+="<input type='hidden' name='s_name[]' value='"+href[i][0]+"'><input type='hidden' name='s_val[]' value='"+href[i][1]+"'>";
       tmp+="<input type='hidden' name='"+href[i][0]+"' value='"+href[i][1]+"'>";  
    }
    return tmp;
}
//--------Сортировки
function number_sort(id){
    var a=jQuery('#sort').val();
if(id=='0'){
    jQuery("#sort_img_1").show();
    jQuery("#sort_img_2").hide();
    if(a=='1'){
      jQuery('#sort').val('0');
      jQuery("#sort_img_1").attr('src','/images/downarrow.png');    
    }      
    else{
      jQuery('#sort').val('1');  
      jQuery("#sort_img_1").attr('src','/images/uparrow.png');         
    }
}
else{
    jQuery("#sort_img_2").show();
    jQuery("#sort_img_1").hide();
    if(a=='2'){
      jQuery('#sort').val('3');
      jQuery("#sort_img_2").attr('src','/images/downarrow.png');    
    }    
    else{
      jQuery('#sort').val('2');  
      jQuery("#sort_img_2").attr('src','/images/uparrow.png');         
    }
}
}
//ДЛя шинного калькулятора
function fnCalcRRD(vw, vh, vd){
        jQuery.ajax({
            type: "POST",
            data: "size_width="+vw+"&size_height="+vh+"&size_diametr="+vd,
            url: "/modules/mod_vm_universal_search_free/files/aj_shin_calc.php",
            dataType: 'HTML',
            success: function (data){
                 jQuery('#crrd').val(data);
            }
        });    
}
//Ресайз для нормального вида примерки дисков
function f_disk_resize(){
    var new_width=parseInt(jQuery("#f_disk_wrapper").css('width'))-46;
    width=new_width-new_width%108;
    var margin=23+(new_width%108)/2;
    jQuery("#f_disk_view").css({'width':width+'px','margin-left':margin+'px','margin-right':margin+'px'});     
}
function f_disk_l(){
    if(left>width)
        left-=width;
    else
        left=0;
    jQuery("#f_disk_view_centr").animate({left:'-'+left+'px'},300, function(){});        
}
function f_disk_r(){
    var colvo=parseInt(jQuery(".f_disk_img").length);
    var total=parseInt(jQuery("#f_disk_total").val());
    if((left+width)<parseInt(jQuery("#f_disk_view_centr").width())){
        left+=width;
        if(colvo*108<left+width&&colvo<total)
            f_disk_add_disk();
    }
    jQuery("#f_disk_view_centr").animate({left:'-'+left+'px'},300, function(){});     
}
function f_disk_add_disk(){
   var count=parseInt(jQuery("#f_disk_count").val());
   jQuery("#f_disk_count").attr('value',count+20);
   mod_loadProduct(count+20,'mod_vm_search_form',4) ;  
}
function f_disk_center_resize(){
    var colvo=parseInt(jQuery(".f_disk_img").length);
    jQuery("#f_disk_view_centr").css('width',(colvo*108));    
}
function f_disk_remove(){
    jQuery('#right_content .header_diler_f_disk, #right_content .body_diler_fon_f_disk').remove();
}
