/*---
  CS-Cart uses jQuery 1.2.6, which doesn't have the $.closest() method.
  I used this method a LOT, so I replaced it with $.parents('elmt:first').
  Seems to work as expected.
  ---*/
var wait = false,
    toggle_s = 1,
    $s;

$(function(){
    if ($('#search').length != 1) { return; }
    
    // Define namespace.
    $s = $('#search');

    // Fill first dropdown.
    $.ajax({
        url: 'index.php?dispatch=iisearch.fetch_firstdropdown',
        success: function(data) {
			if (!$.browser.opera) {

									// select element styling
			$('select.select').each(function(){
			var title = $(this).attr('title');
			if( $('option:selected', this).val() != '' ) title = $('option:selected',this).text();
			$(this)
			.css({'z-index':10,'opacity':0,'-khtml-appearance':'none'})
			.after('<span class="select">' + title + '</span>')
			.change(function(){
			val = $('option:selected',this).text();
			$(this).next().text(val);
			})
			});
			};
            $('#parameters select[name=Make]',$s).html(data);
			
        }
    });
    
    // button styling
	$(':button, :submit',$s).addClass('button');
    $('.button',$s).each(function(){
        $(this)
            .addClass('ui-state-default')
            .bind('mouseover', function(){
                $(this).addClass('ui-state-hover');
            })
            .bind('mouseout', function(){
                $(this).removeClass('ui-state-hover');
            });
    });
	
	// input and select styling
	$('input, select, option',$s).hover(
		function(){
			$(this).addClass('hover');
		},
		function(){
			$(this).removeClass('hover');
		}
	);
	$('input.focus',$s).each(function(){
		if ($(this).val() == $(this).attr('defaultValue')) {
			$(this).addClass('blurred');
		}
	});
    $('input.focus',$s)
    .bind('focus', function () {
        if ($(this).val() == $(this).attr('defaultValue')) {
            $(this)
                .val('')
                .removeClass('blurred');
        }
        else {
            this.select();
        }
    })
    .bind('blur', function () {
        if ($(this).val() == '') {
            $(this)
                .val($(this).attr('defaultValue'))
                .addClass('blurred');
        }
    });
    
    $('select:disabled',$s).addClass('disabled');
    


    // Click to toggle the Tecdoc/KBA search.
    $('.toggle_s').click(function(){
        $('.toggle_s'+toggle_s).hide();
             if (toggle_s == 1) { toggle_s = 2; }
        else if (toggle_s == 2) { toggle_s = 1; }
        $('.toggle_s'+toggle_s).show();
    });
    
    // Make the KBA search picture dynamic.
    window.setInterval(function(){
        $('.kbasearch_img').toggleClass('alt');
    }, 2000);


    
    
    
    
    // FETCH DROPDOWN OPTIONS
    $('select[name=Make], select[name=Model], select[name=Engine_Size], select[name=Engine_1], select[name=Fuel]',$s)
      .bind('change', function(){

        // Shorthands.
        if ($(this).attr('name') == 'Engine_Size') {
            // The Engine_Size dropdown is the last in the table row,
            // so skip to the next for selecting the next dropdown.
            nxt = $(this).parents('tr:first').next('tr').find('td:first select').attr('name');
        } else {
            nxt = $(this).parents('td:first').next('td').find('select').attr('name');
        }
        var $nxt = $('select[name='+nxt+']',$s);

        // Set which dropdown should be fetched.
        $('#parameters form input[name=fetch]',$s).val(nxt);

        $.ajax({
            url: 'index.php?dispatch=iisearch.fetchdropdown',
            data: ii_serialize('#parameters form') + '&fv='+$nxt.attr('fv'),
            type: 'post',
            success: function(data) {

                // Enable next dropdown.
                $nxt
                    .removeAttr('disabled')
                    .html(data);
                // If only one option is fetched, select it.
                if ($('select[name='+nxt+'] option',$s).length == 1) {
                    $nxt
                        .val($nxt.find('option:last').val())
                        .change();
                    if ($nxt.find('option:last').val() == $nxt.attr('fv')) {
                        $nxt
                            .attr('disabled', 'disabled')
                            .addClass('disabled');
                    }
                }
                // If no options are fetched, disable the selectmenu.
                else if ($('select[name='+nxt+'] option',$s).length == 0) {
                    $nxt
                        .attr('disabled', 'disabled')
                        .html('<option>-</option>');
                }
    
                // Disable all selectmenus following the next.
                var n = nxt;
                while ($('#parameters select[name='+n+']',$s).parents('td:first').next('td').find('select').length > 0) {
                    $sel = $('select[name='+n+']',$s).parents('td:first').next('td').find('select');
                    $sel
                        .attr('disabled', 'disabled')
                        .addClass('disabled');
                    n = $sel.attr('name');
                }
                
                return false;
            }
        });
    });
    

    // DROPDOWN SEARCH
    $('#parameters select',$s).bind('change', function(){

        // Give the user (but mostly this script, when just one value is set in the next dropdown)
        // some time to use another dropdown before performing the actual search.
        if (wait) { return; }
        
        resetOtherSearches('dropdown');
        loadingMessage(1, 'f');
        wait = true;
        setTimeout(function(){

            $.ajax({
    			updateHTMLelements: ['#fitment_results'],
                url: 'index.php?dispatch=iisearch.search_dropdown',
                data: ii_serialize('#parameters form'),
                type: 'post',
                success: function(data) {
                    loadingMessage(0, 'f');
                    insertResultsets(data, 'f');
                    wait = false;
                }
            });
            
        }, 900);
    });
    
    function submit_search()
	{
		// if (wait) { return; }
		//alert("Hello123");
        
        resetOtherSearches('dropdown');
        loadingMessage(1, 'f');
        wait = true;
        setTimeout(function(){

            $.ajax({
    			updateHTMLelements: ['#fitment_results'],
                url: 'index.php?dispatch=iisearch.search_dropdown',
                data: ii_serialize('#parameters form'),
                type: 'post',
                success: function(data) {
                    loadingMessage(0, 'f');
                    insertResultsets(data, 'f');
                    wait = false;
                }
            });
            
        }, 900);
	}
    
    // Validate form: TECDOC SEARCH
    var tecdoc_previousvalue = $('#tecdoc',$s).val();
    $('#tecdoc',$s).bind('keyup', function(e){
		if($('#tecdoc',$s).val().length < 8 ){
		 $("#plate_info").hide("slow");
		}
		
        if (e.which==8) { return false;}
        formatPlate($('#tecdoc'));
      
	  	if ($(this).val().length >= $(this).attr('maxlength') && $(this).val() != tecdoc_previousvalue) {
			
            resetOtherSearches('tecdoc');            
            //loadingMessage(1, 'f');
            $('#parameters input[name=a]',$s).val('search_tecdoc');
			
			// reload the  dropdown stuff.
			// clear dropdown search
			 $(".mainbox-container").css('display', 'none');
             $("#fitment__result").css('display', 'block');
			 $("#search_slider").css('display', 'none');
			 $("#home_text").css('display', 'none');
			 $("#ajax_loading_box").css('display', 'block');

			$("#content_main_text").css('display', 'none');
			$("#product_results").css('display', 'none');
					
            $.ajax({
                url: 'index.php?reset_results=yes&dispatch=iisearch.search_tecdoc',
                data: ii_serialize('#parameters_open form'),
    			updateHTMLelements: ['#fitment_results', '#product_results'],
                type: 'post',
                success: function(data) {
					$("#ajax_loading_box").css('display', 'none');
					result=data.split("||");
					var vehicle_id=result[1];
					//alert();
					var plate_info=result[2];
					data1=result[0];
					//alert(data1);
					
					if(vehicle_id){
						data1=result[0];
						$("#ajax_loading_box").css('display', 'block');
						load_singal_products(vehicle_id);
						$("#ajax_loading_box").css('display', 'none');
						 $("#fitment__result").css('display', 'none');
					}
					
                    //$("#plate_info").hide("slow");
					
					if(plate_info){
					//$("#plate_info").css('display', 'block');
					$("#plate_info").html(plate_info);
					$("#plate_info").slideDown("slow");
					}
					
                    if (data1=='tecdoc_contact_error') {
                        alert('Er is een fout opgetreden bij het bereiken van de Tecdoc webservice. Probeer het later opnieuw.');
                        return;
                    }
                    

					 
					 
					//$(".clear_plus").css('display', 'none');
					//$("div.wysiwyg-content p").remove();
					
                    
                    // Display resultsets.
                    insertResultsets(data1, 'f');
					var clear_url = "tw/widgets/dropdowns.php?cmd=clear&search_type=tecdoc&reload=no";
					$("#search_boxes").load(clear_url);
                }
            });
        	
		}
            
        tecdoc_previousvalue = $(this).val();
    });
    
   
   function load_singal_products(Vehicle_ID){
	      		
            $.ajax({
			url: 'index.php?dispatch=iisearch.fetch_products',
			data: {
				Vehicle_ID: Vehicle_ID
			},
			updateHTMLelements: ['#product_results'],
			success: function(data){
				$("#product_results").css('display', 'block');
				$(".mainbox-container").css('display', 'none');
				
				insertResultsets(data, 'p');
				loadingMessage(0, 'p');
				}
			});
    
	}
    
    
    
    // Validate form: OPEN SEARCH
/*    $('#open_s',$s).bind('blur', function(){
										  
		
        if ($('input[name=open]',$s).val() == $('input[name=open]',$s).attr('defaultValue') || $('input[name=open]',$s).val() == '') {
            return;
        }	

			$("#search_boxes").css('display', 'none');		
			$("#search_slider").css('display', 'none');
			$("#fitment__result").css('display', 'none');	
			$("#plate_info").css('display', 'none');	
			$(".mainbox-container").css('display', 'none');	

			$("#ajax_loading_box").css('display', 'block');	   
			
        resetOtherSearches('open');
    
        // Show "Loading..." messages and set controller action.
        //loadingMessage(1, 'f');

			//alert("1st");
        $.ajax({
            url: 'index.php?reset_results=yes&dispatch=iisearch.search_open',
            type: 'post',
            data: ii_serialize('#parameters_open form'),
    		updateHTMLelements: ['#fitment_results', '#product_results'],
            success: function(data) {  
					 
				 
                insertResultsets(data, 'b');
				$("#ajax_loading_box").css('display', 'none');
				$("#product_results").css('display', 'block');	
                loadingMessage(0, 'p');
				var clear_url = "tw/widgets/dropdowns.php?cmd=clear&search_type=open&reload=no";
				//$("#search_boxes").load(clear_url);
                
            }
        });
        return false; 
    });
*/	
	


		
	$('#parameters_open form',$s).bind('submit', function(){
		
        if ($('input[name=open]',$s).val() == $('input[name=open]',$s).attr('defaultValue') || $('input[name=open]',$s).val() == '') {
            return false;
        }	

			$("#search_boxes").css('display', 'none');		
			$("#search_slider").css('display', 'none');
			$("#home_text").css('display', 'none');
			$("#fitment__result").css('display', 'none');	
			$("#plate_info").css('display', 'none');	
			$(".mainbox-container").css('display', 'none');	

			$("#ajax_loading_box").css('display', 'block');	   
			
        resetOtherSearches('open');
    
        // Show "Loading..." messages and set controller action.
        //loadingMessage(1, 'f');

			//alert("1st");
        $.ajax({
            url: 'index.php?reset_results=yes&dispatch=iisearch.search_open',
            type: 'post',
            data: ii_serialize('#parameters_open form'),
    		updateHTMLelements: ['#fitment_results', '#product_results'],
            success: function(data) {  
					 
				 
                insertResultsets(data, 'b');
				$("#ajax_loading_box").css('display', 'none');
				$("#product_results").css('display', 'block');	
                loadingMessage(0, 'p');
				var clear_url = "tw/widgets/dropdowns.php?cmd=clear&search_type=open&reload=no";
				//$("#search_boxes").load(clear_url);
                
            }
        });
        return false; 
  });
	
	
	
		
	$('#parameters form',$s).bind('submit', function(){ 
	 if ($('input[name=open]',$s).val() == $('input[name=open]',$s).attr('defaultValue') || $('input[name=open]',$s).val() == '') {
            return;
        }

        resetOtherSearches('open');
    
        // Show "Loading..." messages and set controller action.
        //loadingMessage(1, 'f');
		$("#fitment__result").css('display', 'block');
		$("#search_slider").css('display', 'none');
		$("#home_text").css('display', 'none');
		  $(".mainbox-container").css('display', 'none');
       $("#ajax_loading_box").css('display', 'block');
		//alert("3rd");
        
        $.ajax({
            url: 'index.php?reset_results=yes&dispatch=iisearch.search_open_page',
            type: 'post',
            data: ii_serialize('#parameters form'),
    		updateHTMLelements: ['#fitment_results', '#product_results'],
            success: function(data) {
                result=data.split("||");
                // Display resultsets.
                insertResultsets(result[0], 'b');
                
                // Hide "Loading..." messages.
                //loadingMessage(0, 'f');
				$("#fitment__result").css('display', 'block');
				$("#search_slider").css('display', 'none');
				$("#home_text").css('display', 'none');
               $("#ajax_loading_box").css('display', 'none');
				var clear_url = "tw/widgets/dropdowns.php?cmd=clear&search_type=open&reload=no&page_id=Y";
				$("#search_boxes").load(clear_url,function()
														   {				if (!$.browser.opera) {

				// select element styling
				$('select.select').each(function(){
				var title = $(this).attr('title');
				if( $('option:selected', this).val() != '' ) title = $('option:selected',this).text();
				$(this)
				.css({'z-index':10,'opacity':0,'-khtml-appearance':'none'})
				.after('<span class="select">' + title + '</span>')
				.change(function(){
				val = $('option:selected',this).text();
				$(this).next().text(val);
				})
				});
				
				};
}
										)
                									
								   

            }
        });
        return false; 
    });
    
    // Validate form: KBA SEARCH
    $('#KBA2',$s).keyup(function(){   
			
        if (($('input[name=KBA1]',$s).val() == $('input[name=KBA1]',$s).attr('defaultValue') || $('input[name=KBA1]',$s).val() == '') &&
            ($('input[name=KBA2]',$s).val() == $('input[name=KBA2]',$s).attr('defaultValue') || $('input[name=KBA2]',$s).val() == '')) {
            return;
        }
		
        if(document.getElementById("KBA2").value.length==3){
			document.getElementById("KBA2").focus();
        resetOtherSearches('KBA');
        
        // Show "Loading..." messages and set controller action.
       // loadingMessage(1, 'f');
	   $("#ajax_loading_box").css('display', 'block');
	   $("#search_slider").css('display', 'none');
	   $("#home_text").css('display', 'none');
	   $(".mainbox-container").css('display', 'none');
        
        $.ajax({
            url: 'index.php?dispatch=iisearch.search_KBA',
            type: 'post',
            data: ii_serialize('#prm'),
    		updateHTMLelements: ['#fitment_results', '#product_results'],
            success: function(data) {
				
				result=data.split("||");
				data=result[0];
				
				var vehicle_id=result[1];
					data=result[0];
					
               $("#product_results").css('display', 'none');
			   $("#fitment__result").css('display', 'block');
			   $("#search_slider").css('display', 'none');
			   $("#home_text").css('display', 'none');
                // Display resultsets.
                insertResultsets(data, 'b');
                
                // Hide "Loading..." messages.
                loadingMessage(0, 'f');
				$("#ajax_loading_box").css('display', 'none');
            }
        });
	}
        return false;
    });
    
    $('#parameters form',$s).submit(function(){
        return false;
    });
    
    
    // Open and KBA search:
    // reset other searches when something is entered.
    $('#parameters input[name=open]',$s).bind('keyup keydown', function(){
        resetOtherSearches(['open', 'dropdown']);
    });
    // reset open search when KBA is entered.
    $('#parameters input[name=KBA1]',$s).bind('keyup keydown', function(){
        resetOtherSearches(['KBA', 'dropdown']);
    });
    $('#parameters input[name=KBA2]',$s).bind('keyup keydown', function(){
        resetOtherSearches(['KBA', 'dropdown']);
    });

    
    
    
    
    
    
    
    
    
    
    
    
    
    // Click on product:
    // - link to product page
	
    $('#product_results td').bind('click', function(){
    
        
    });


});


// Click on fitment:
// - find linked products
function click_fitment() {
  //  alert("ajay");
    // Show "Loading..." messages.
   $("#ajax_loading_box").css('display', 'block');
   $("#search_slider").css('display', 'none');
   $("#home_text").css('display', 'none');
	loadingMessage(0, 'p');
    // Shorthand.
    Vehicle_ID = $(this).parents('tr:first').attr('id').substr(1);
    //alert();
	if(Vehicle_ID.length){
		
    // Fetch product links to show in the next search window.
			$.ajax({
				url: 'index.php?dispatch=iisearch.fetch_products',
				data: {
					Vehicle_ID: Vehicle_ID
				},
				updateHTMLelements: ['#product_results'],
				success: function(data){
					$("#product_results").css('display', 'block');
					
					insertResultsets(data, 'p');
				   $("#ajax_loading_box").css('display', 'none');
				   loadingMessage(0, 'p');
				}
			});
		}
}

// Click on product:
function click_product() {

    product_id = $(this).parents('tr:first').attr('id').substr(1);
    
    location.href = 'index.php?dispatch=products.view&product_id='+product_id;
}




// The following function is not mine! Credits fly out to its original creator.
function formatPlate(el){
  var kt = el.val().replace(/\-/g,'');
  var newkt = '';
  for(var i=0;i<kt.length;i++){
    newkt += kt.charAt(i);
    if(i==1)newkt += '-';
    if(i==3)newkt += '-';
    if(i==5){
      if((kt.charAt(4)==parseInt(kt.charAt(4)))!=(kt.charAt(5)==parseInt(kt.charAt(5)))){
        newkt = kt.charAt(0) + kt.charAt(1) + '-' + kt.charAt(2) + kt.charAt(3) + kt.charAt(4) + '-' + kt.charAt(5);
      }else{
        newkt = kt.charAt(0) + kt.charAt(1) + '-' + kt.charAt(2) + kt.charAt(3) + '-' + kt.charAt(4) + kt.charAt(5);
      }
    }
  }
  el.val(newkt);
}


/*---
 * Insert resultsets.
 * @param string data   all data
 * @param string type   b= both types, f= fitments, p= products
---*/
function insertResultsets(data, type) {

    var a = data.split('<!--|-_-|-BOUNDARY001-|-_-|-->', 2);
//alert(a);
    var f = type == 'b' ? a[0] : data;
    var p = type == 'b' ? a[1] : data;
    
    if ( (type == 'b' || type == 'f') && typeof f == 'string' ) {
        c = f.match(/<!--count:(.*?)-->/, '\1');
        if (c && c[1].substr(0,1) == '>') {
            /*$('#fitment_maxresults',$s)
                .slideDown('slow')
                .html( $('#fitment_maxresults').html().replace(/%d/g, c[1].substr(1)) );*/
        }
        $('#fitment_results',$s).html(f);

        // Click on fitment event handler
        $('#fitment_results td',$s).bind('click', click_fitment);
        
            
        // Display tooltips.
        $('#fitment_results tr td img',$s).tooltip({  
            track: true, 
            delay: 0,
			showURL: false,  	
            bodyHandler: function() {
                return $(this).parents('tr:first').find('.tooltip_body').html();
            }
        });
		
	
		
		
		
    }
	
    if ( (type == 'b' || type == 'p') && typeof p == 'string' ) {
        c = p.match(/<!--count:(.*?)-->/, '\1');
        if (c && c[1].substr(0,1) == '>') {
            $('#product_maxresults',$s)
                .slideDown('slow')
                .html( $('#product_maxresults').html().replace(/%d/g, c[1].substr(1)) );
        }
        $('#product_results',$s).html(p);
        
        // Click on product
      //  $('#product_results td',$s).bind('click', click_product);
    }
    
    
    // Add hover classes to resultset rows.
    $('.resultset tr',$s)
        .bind('mouseover', function() {
            $(this).addClass('hover');
        })
        .bind('mouseout', function(){
            $(this).removeClass('hover');
        });
    $('.resultset td',$s)
        .bind('click', function(){
            // Deselect previously selected rows and select the current one.
            $(this).parents('table:first').find('tr.selected').removeClass('selected');
            $(this).parents('tr:first').addClass('selected');
        });
		
		 $('#product_results tr td .myexternal',$s).tooltip({  
            track: true, 
            delay: 0,
			showURL: false,  	
            bodyHandler: function() {
                return $(this).parents('tr:first').find('.tooltip_body').html();
            }
        });
		
}

/*---
 * Display or hide the "Loading..." message.
 * @param boolean bShow     1= display, 0= hide
 * @param string  type      f= fitment_results, fi= fitment_info, p= product_results, pi= product_info
 * @param string/integer speed   the speed given to the jQuery animation. This defaults to 'slow' (400 ms)
---*/
var bFirstSearchedP = false;
var bFirstSearchedF = false;
function loadingMessage(bShow, type, speed) {
    
    // On first search, show resultset divs.
    if (type == 'f' && !bFirstSearchedF) {
        
        $('#fitment_results',$s).parents('.box').show();
        bFirstSearchedF = true;
        
    } else if (type == 'p' && !bFirstSearchedP) {
        
        $('#product_results',$s).parents('.box').show();
        bFirstSearchedP = true;
    }
    
    speed = speed != undefined ? speed : 'slow';
    
    switch (type) {
        case 'f':  sel = '#fitment_results_loading'; if(bShow){$('#fitment_maxresults',$s).slideUp('200');} break;
        case 'p':  sel = '#product_results_loading'; if(bShow){$('#product_maxresults',$s).slideUp('200');} break;
    }
    if (bShow) {
        $(sel,$s).slideDown(speed);
    } else {
        $(sel,$s).slideUp(speed);
    }
}

/*---
 * Reset all other searches.
 * @param string mCurrent   string or array of the current searchtypes; these won't be touched
---*/
function resetOtherSearches(mCurrent) {
    v = '';
    if ( typeof mCurrent == 'object' ) {
        for (x in mCurrent) {
            v += "'"+mCurrent[x]+"'";
        }
    } else {
        v = "'"+mCurrent+"'";
    }
    
    if (v.search(/'tecdoc'/) == -1) {
        $('#tecdoc',$s).val('');
    }
    if (v.search(/'dropdown'/) == -1) {
        $('select[name=Make]',$s).val('0');
        $('#parameters select',$s).each(function(){
            if ($(this).attr('name')!='Make') {
                if ($(this).find('option').length == 1) {
                    $(this).html('<option value="0">'+$(this).attr('fv')+'</option>');
                }
                $(this)
                    .attr('disabled', 'disabled')
                    .addClass('disabled');
                this.selectedIndex = 0;
            }
        });        
    }
    if (v.search(/'KBA'/) == -1) {
        $('#parameters input[name=kba1]',$s).val('').blur();
        $('#parameters input[name=kba2]',$s).val('').blur();
    }
    if (v.search(/'open'/) == -1) {
        $('#parameters input[name=open]',$s).val('').blur();
    }
}

/*---
  IE handled $.serialze() like a bitch, so I created my own.
  @param string sForm the jquery-like form identifier
  @return string
  ---*/
function ii_serialize(form) {
    var a = [];
    $(form + ' input',$s).each(function(){
        a.push( encodeURIComponent($(this).attr('name')) + '=' + encodeURIComponent($(this).val()) );
    });
    $(form + ' select',$s).each(function(){
        a.push( encodeURIComponent($(this).attr('name')) + '=' + encodeURIComponent($(this).find('option:selected').val() ) );
    });
    return a.join('&');
}


function kba1(){
		if(document.getElementById("KBA1").value.length > 3){
			document.getElementById("KBA2").focus();
		}
	}

	

