$(document).ready(
    function() {
        compaSearchInit();
    }
);

/**
 * initialises the compatibility search.
 */
function compaSearchInit() {
	/* for customer testimonials */
	var additionalData = {};
	if ((typeof(js_isCustomerTestimonials) == 'boolean') && (js_isCustomerTestimonials === true)) {
		additionalData = { "isCustomerTestimonials": "true" }; 
	}
	if ((typeof(js_compaSearchLeader) == 'string') && (js_compaSearchLeader != '')) {
        additionalData["leader"] = js_compaSearchLeader;
        tb_show();
    } else if ((typeof(js_compaSearchEAN) == 'string') && (js_compaSearchEAN != '')) {
        additionalData["ean"] = js_compaSearchEAN;
        tb_show();
    }
	
	if ($("#compasearch").get().length > 0 && js_compaSearchInitURL.length > 0) {
		$.ajax({
	        url : js_compaSearchInitURL,
	        type : 'GET',
	        data : additionalData,
	        dataType : 'html',
	        timeout : 10000,
	        error : function(req, msg) {
	            status = "";
	            statusText = "";
	            try {
	                status = req.status;
	                statusText = req.statusText;
	            } catch (e) {
	            }
	        },
	        success : function(html) {
	        	leaderOrEAN = false;
	        	if (((typeof(js_compaSearchLeader) == 'string') 
                    && (js_compaSearchLeader != '')) 
                  || ((typeof(js_compaSearchEAN) == 'string') 
                    && (js_compaSearchEAN != ''))){
	        	 	leaderOrEAN = true;
	        	}
	        	if (leaderOrEAN) {
		        	tb_remove();
	        	}
	        	$("#compasearch").html(html);
                $("#compaSearchHighlights").hide();
                if (!$.browser.msie) {
                  $("#compasearch").slideDown("slow");
                } else {
                  $("#compasearch").show();
                }
                compaSearchAttachEventHandlers();
                if (leaderOrEAN){
                    if ($("#compaSearchModelsSelector > option").get().length > 0) {
                         tb_init('#compaSearchResults a.thickbox');
                         $("#compaSearchModelsSelector").show();
                    }
                }
	        }
	    });
	}
}

/**
 * attaches the necessary event handlers.
 */
function compaSearchAttachEventHandlers() {
	/* for customer testimonials */
	var additionalData = {};
    if ((typeof(js_isCustomerTestimonials) == 'boolean') && (js_isCustomerTestimonials === true)) {
        additionalData = { "isCustomerTestimonials": "true" }; 
    }
    
    $('#compaPremiumSelector').change(function() {
    	tb_show();
    	$.ajax({
            url : js_compaSearchGetManufacturersURL,
            type : 'POST',
            data : {"showAll": !this.checked},
            dataType : 'json',
            timeout : 10000,
            error : function(req, msg) {
            	tb_remove();
                status = "";
                statusText = "";
                try {
                    status = req.status;
                    statusText = req.statusText;
                } catch (e) {
                }
                alert("Communication Error:\n" + status + " "
                        + statusText + " (" + msg + ")");
            },
            success : function(json) {
            	html = '<option value="">' + js_compaSearchPleaseSelect + '</option>';
                for (i = 0; i < json.manufacturers.length; i++) {
                   html += '<option value="' + json.manufacturers[i].id + '">'
                   + json.manufacturers[i].name + '</option>';
                }
                $('#compaSearchManufaturerSelector').html(html);
                tb_remove();
            }
       });
    });
    
    $('#compaSearchManufaturerSelector').change(function() {
    	if (this.value === '') {
    		return;
    	}
        tb_show();
        $('#compaSearchModelsSelector').fadeOut();
        if (!$.browser.msie) {
          $("#compaSearchResults").slideUp("fast");
          $("#compaSearchHighlights").slideUp("fast");
        } else {
          $("#compaSearchResults").hide();
          $("#compaSearchHighlights").hide();
        }
        $.ajax({
            url : js_compaSearchGetModelsURL,
            type : 'POST',
            data : {"manufacturer": this.value},
            dataType : 'json',
            timeout : 10000,
            error : function(req, msg) {
                tb_remove();
                status = "";
                statusText = "";
                try {
                    status = req.status;
                    statusText = req.statusText;
                } catch (e) {
                }
                alert("Communication Error:\n" + status + " "
                        + statusText + " (" + msg + ")");
            },
            success : function(json) {
                html = '<option value="">' + js_compaSearchPleaseSelect + '</option>';
                for (i = 0; i < json.models.length; i++) {
                   html += '<option value="' + json.models[i].id + '">'
                   + json.models[i].name + '</option>';
                }
                $('#compaSearchModelsSelector').html(html).fadeIn();
                compaSearchShowHighlights(json);
                tb_remove();
                if ($.browser.msie) {
                    $('#compaPremiumSelector')[0].focus();
                }
            }
        });
    });    
    
    $('#compaSearchModelsSelector').change(function() {
    	if (this.value === '') {
            return;
        }
    	tb_show();
        if (!$.browser.msie) {
          $("#compaSearchResults").slideUp("fast");
          $("#compaSearchHighlights").slideUp("fast");
        } else {
          $("#compaSearchResults").toggle();
          $("#compaSearchHighlights").hide();
        }
        reqData = additionalData;
        reqData.model = this.value;
        reqData.lang = js_compaSearchLanguage;
        $.ajax({
            url : js_compaSearchGetProductsURL,
            type : 'POST',
            data : reqData,
            dataType : 'html',
            timeout : 10000,
            error : function(req, msg) {
                tb_remove();
                status = "";
                statusText = "";
                try {
                    status = req.status;
                    statusText = req.statusText;
                } catch (e) {
                }
                alert("Communication Error:\n" + status + " "
                        + statusText + " (" + msg + ")");
            },
            success : function(html) {
                $('#compaSearchResults').html(html);
                tb_init('#compaSearchResults a.thickbox');
                tb_remove();
                if (!$.browser.msie) {
                  $("#compaSearchResults").slideDown("slow");
                } else {
                  $("#compaSearchResults").show();
                  $('#compaPremiumSelector')[0].focus();
                }
            }
        });
    });
    
}

/**
 * shows the highlights
 */
function compaSearchShowHighlights(json) {
    if (json.highlights.length > 0 ) {
        highlightsHtml = '<ol start="1">';
        for (i = 0; i < json.highlights.length && i < 12; i++) {
            highlightsHtml += '<li><a class="compaSearchDirectLink" name="' +json.highlights[i].id + '">'
                + json.highlights[i].name + '</a></li>';
        }
        highlightsHtml += '</ol>';
        
        // add HTML to DOM
        $('#compaSearchHighlightList').html(highlightsHtml);
        
        // attach additional event handlers
        $('a.compaSearchDirectLink').click(function () {
        	id = this.name;
            if (id === '') {
               return false;
	        }
	        tb_show();
	        $("#compaSearchHighlights").hide();
	        if (!$.browser.msie) {
	          $("#compaSearchResults").slideUp("fast");
	        } else {
	          $("#compaSearchResults").toggle();
	        }
	        $('#compaSearchModelsSelector > option').each(function(i) {
	        	if (this.value == id) {
	        		this.selected = true;
	        	} else if (this.selected === true) {
	        		this.selected = false;
	        	}
	        });
	        $('#compaSearchModelsSelector').change();
	        return false;
        });
        
        if (!$.browser.msie) {
          $("#compaSearchHighlights").slideDown("slow");
        } else {
          $("#compaSearchHighlights").show();
        }
    } else {
    	if (!$.browser.msie) {
          $("#compaSearchHighlights").slideUp("fast");
        } else {
          $("#compaSearchHighlights").hide();
        }
    }
}
