var homepage = function($) {

	var priv = {
		carList : null,
		searchMode : 0,
		licensePlate : '',
		busy : false,
		searchTarget : new Array('searchresult.aspx?eqs=','new.aspx?cid='),
		allSelected : false,
		allSelectedNew : false,
		
		showcaseCurrentIndex : 1,
		showcaseHeaderTexts : new Array('Meest bekeken auto\'s', 'Milieuvriendelijke auto\'s', 
		                        		'Auto\'s met de meeste pk\'s','Veilige auto\'s',  'Best beoordeelde auto\'s'),
        showcaseInterval : null,		  
        showcaseCurrentMousePos : 'out',        		    
		                        		       
        
		successSelectAllBrands : function(results) {
		    //set the new html in the div for all brands
		    var html = '';
		    eval('html = ' + results + '*/');
		    $('#brandListFull').html(html);
		    
		    //loop through the old brands and select the selected brands in the new html
		    $('#brandListPartial input.brandselect').each(function() {
		        if ($(this).is(':checked')) {
		            //find the equivalent input in the full brandlist
		            //if there is a label, the 'select all' was selected, then we won't show the dropdown
		            if ($('#occ-link-'+$(this).val()+' label').html() != null) {
		                $('#occ-link-'+$(this).val()+'full input.brandselect').attr('checked', 'checked');
		            }
		        }
		    });
		    
		    //clear the old div to avoid them from interfering with the results
		    $('#brandListPartial').html('');
		    $('#brandListPartial').hide();
		    $('#brandListFull').show();		    
		    $('#occasionTab input.brandselect').attr('checked', 'checked');
		    $('#occasionTab input.brandselect').each(function() {
		        var clickevent = String($(this).attr('onclick')).replace('selectBrand', 'removeBrand');
                //IE places a function around the onclick event, we have to remove that
                clickevent = clickevent.replace('function anonymous()\n{', '');
                clickevent = clickevent.replace('\n}', '');
		        $(this).attr('onclick', clickevent);
		        $(this).attr('disabled', 'disabled');
		    });
		},
		
		successAllBrandsSelectNew : function(results){
      //set the new html in the div for all brands
          var html = '';
          eval('html = ' + results + '*/');
          $('#brandListFullNew').html(html);
          
          //clear the old div to avoid them from interfering with the results
          $('#brandListPartialNew').html('');
          $('#brandListPartialNew').hide();
          $('#brandListFullNew').show();  
          $('#newCarTab input.brandselect').attr('checked', 'checked');
          $('#newCarTab input.brandselect').each(function() {
              var clickevent = String($(this).attr('onclick')).replace('selectBrand', 'removeBrand');
                    //IE places a function around the onclick event, we have to remove that
                    clickevent = clickevent.replace('function anonymous()\n{', '');
                    clickevent = clickevent.replace('\n}', '');
              $(this).attr('onclick', clickevent);
              $(this).attr('disabled', 'disabled');
          });
      },
		
		
		successLicensePlateSearch : function(results){
		    priv.busy = false;
			var exist = false;
			$('#txtLicensePlate').attr('disabled', '');
			
			eval('exist = ' + results + '*/');
			logger.info('exist : ' + exist.Value);
			
			if(!exist.Value){
			    if (exist.Error == 'ErrorMatching'){
    				document.location = global.pathPrefix + '/my/CarValue.aspx';	
			    }
			    else if (exist.Error == 'error-matching-no-main'){
			        priv.licensePlate = exist.Message;
			        document.location = global.pathPrefix + '/my/CarValue.aspx?nomain=1';	
			        //tb_show('', global.pathPrefix+'/popup.aspx?height=204&width=488&modal=true', false);
			    }
			    else if (exist.Error == 'no-main-car'){
			        priv.licensePlate = exist.Message;
			        document.location = global.pathPrefix + '/my/CarValue.aspx?nomain=1';	
       				//tb_show('', global.pathPrefix+'/popup.aspx?height=204&width=488&modal=true', false);
			    }
			    else {
                    document.location = global.pathPrefix + '/SearchMyCar.aspx?error=1';				
                }
			}
			else{
				//document.location = global.pathPrefix + '/my/CarValue.aspx';
				var plate = $('#txtLicensePlate').attr('value');
                var page_mode = $('#page_mode').attr('value');
                
                if(page_mode == 'ad')
    				document.location = global.pathPrefix + '/SearchMyCar.aspx?lp='+plate+'&type=ad';
    			else 
    			    document.location = global.pathPrefix + '/SearchMyCar.aspx?lp='+plate;
			}
		},
		
		successSetActiveCarMain : function(results){
			var exist = false;
			
			eval('exist = ' + results + '*/');
			document.location = global.pathPrefix + '/my/CarValue.aspx';
		},
		
		/**
		 * This function is called when the Ajax call for license plates has failed
		 */
		errorLicensePlateSearch : function (){
		    priv.busy = false;
			$('#txtLicensePlate').attr('disabled', '');
			$('#lblLicensePlateSearch').html('error');
		},
		
		errorSetActiveCarMain : function() {
		    
		},

	    
	    successSelectBrand : function(results)
	    {
	       	var result = false;
			
			eval('result = ' + results + '*/');
			var brandId = result[0];
			var postfix = result[1];
			var html = result[2];
			
			if(postfix != 'partial')
			{
			$('#occ-link-'+brandId+postfix).html(html); 
			}
			else 
			{
			$('#occ-link-'+brandId).html(html); 
			}
	    },
		    
		successSelectBrandNew : function(results){
			var result = false;
			
			eval('result = ' + results + '*/');
			var brandId = result[0];
			var postfix = result[1];
			var html = result[2];
			
			if(postfix != 'partial')
			{
			$('#new-link-'+brandId+postfix).html(html); 
			}
			else 
			{
			$('#new-link-'+brandId).html(html); 
			}
		},
		
		errorSelectBrand : function(){
		},
		
		successAllBrands : function(results){
		    //set the new html in the div for all brands
		    var html = '';
		    eval('html = ' + results + '*/');
		    $('#brandListFull').html(html);

            var brandsAdded = new Array();

		    //loop through the old brands and select the selected brands in the new html
		    $('#brandListPartial input.brandselect').each(function() {
		        if ($(this).is(':checked')) {
		        
		            //find the equivalent input in the full brandlist
		            //if there is a label, the 'select all' was selected, and we won't show the dropdown
		            if ($('#occ-link-'+$(this).val()+' label').html() != null) {
		            
		                $('#occ-link-'+$(this).val()+'full input.brandselect').attr('checked', 'checked');
                    }
		            else {
		                var brandId = $(this).val();
		                
		                var contains = false;
                        for(var i = 0; i < brandsAdded.length; i++)
                        {
                            if(brandId == brandsAdded[i])
                            {
                                contains = true;
                            }
                        }
                        
                        if(contains == false)
                        {
	                        var li = $('#occ-link-'+ brandId + 'full');
    	                    var oldLi = $('#occ-link-'+ brandId);
    	                    
    	                    var oldHtml = oldLi.html().replace(/partial/gi, "full");
	                        li.html(oldHtml);
    		                
		                    brandsAdded[brandsAdded.length] = brandId;
		                }
		            }
		        }
		    });
	        $('#brandListPartial select.modelselect').each(function() {
                if($(this).attr('selectedIndex') != undefined)
                {
                    var select = $(this).parent().attr('id').replace(/partial/gi, "full")
                    $('#'+select).find('select').attr('selectedIndex', $(this).attr('selectedIndex'));
                }
            });

		    //clear the old div to avoid them from interfering with the results
		    $('#brandListPartial').html('');
		    $('#brandListPartial').hide();
		    $('#brandListFull').show();
		},
		
		successAllBrandsNew : function(results){
		    //set the new html in the div for all brands
		    var html = '';
		    eval('html = ' + results + '*/');
		    $('#brandListFullNew').html(html);
		    
		    //loop through the old brands and select the selected brands in the new html
            var brandsAdded = new Array();

		    //loop through the old brands and select the selected brands in the new html
		    $('#brandListPartialNew input.brandselect').each(function() {
		        if ($(this).is(':checked')) {
		        
		            //find the equivalent input in the full brandlist
		            //if there is a label, the 'select all' was selected, and we won't show the dropdown
		            if ($('#new-link-'+$(this).val()+' label').html() != null) {
		            
		                $('#new-link-'+$(this).val()+'full input.brandselect').attr('checked', 'checked');
                    }
		            else {
		                var brandId = $(this).val();
		                
		                var contains = false;
                        for(var i = 0; i < brandsAdded.length; i++)
                        {
                            if(brandId == brandsAdded[i])
                            {
                                contains = true;
                            }
                        }
                        
                        if(contains == false)
                        {
	                        var li = $('#new-link-'+ brandId + 'full');
    	                    var oldLi = $('#new-link-'+ brandId);
    	                    
    	                    var oldHtml = oldLi.html().replace(/partial/gi, "full");
	                        li.html(oldHtml);
    		                
		                    brandsAdded[brandsAdded.length] = brandId;
		                }
		            }
		        }
		    });
	        $('#brandListPartialNew select.modelselect').each(function() {
                if($(this).attr('selectedIndex') != undefined)
                {
                    var select = $(this).parent().attr('id').replace(/partial/gi, "full")
                    $('#'+select).find('select').attr('selectedIndex', $(this).attr('selectedIndex'));
                }
            });
		    
		    //clear the old div to avoid them from interfering with the results
		    $('#brandListPartialNew').html('');
		    $('#brandListPartialNew').hide();
		    $('#brandListFullNew').show();
		},
		
		successSelectBrandHP : function(results) 
		{
		    var html = '';
		    eval('html = ' + results + '*/');
		    
		    $('#selectModel').html(html);
		    $('#selectModel').removeClass("disabled");
		    $('#selectModel').removeAttr("disabled");
		},
		
		successSelectBrandNewHP : function(results) 
		{
		    var html = '';
		    eval('html = ' + results + '*/');
		    
		    $('#selectModelNew').html(html);
		    $('#selectModelNew').removeClass("disabled");
		    $('#selectModelNew').removeAttr("disabled");		    
		},
		
		errorAllBrands : function(){
		}
	};
	
	return {
	    clearLicensePlate : function(){
	        $('#txtLicensePlate').css('background', 'url('+global.pathPrefix+'/images/home/search_mycar_box.gif)');
	    },
	    
	    firstEndecaString : null,
	    selectedSearchIndex : 0,
	    maxSearchIndex : -1,
		
		/**
		 * this function is called when the page loads
		 */
		initialize : function (){
            $('input.brandselect').attr('checked', '');
            $('.home-link').attr('href', 'javascript:void(0);');
            $('.switch-links').hide();
            $('.switch-labels').show();
		},

		licensePlateKeyDownEvent : function (event){
			if (event.keyCode == 13) {
				this.searchLicensePlate();
    			return false;
			}
		},
		
    	showSearchResultsKeyUpEvent : function (event){
		   if (event.keyCode == 13) {
				document.location = this.firstEndecaString;
			}
		},
		

		searchLicensePlate : function (skipMyCarCheck){
		    if (priv.busy){
		        return;
		    }
		    priv.busy = true;
		    var skip = false;
		    if (skipMyCarCheck){
		        skip = true;
		    }
			var plate = $('#txtLicensePlate').attr('value');
			if(plate == undefined){
			    priv.busy = false;
				return;
			}

		    //var dataStr = '{"licensePlate":"'+ plate +'"}';
	        //$('#lblLicensePlateSearch').html('');
	        $('#txtLicensePlate').attr('disabled', 'disabled');
	        var dataStr = zomoto.ajaxParams(['licensePlate', 'skip'], [plate, skip]);
	        zomoto.ajaxCall('CarSearch', 'SearchMyCar', priv.successLicensePlateSearch, priv.errorLicensePlateSearch, dataStr);
		},
	
	    //used in profile.js
		setActiveCarMain : function(main){
		    //if this should be the main car, check if we're logged in, if not, do that
		    if (main && profile.getProfileObj() == null){
		        profile.setAfterLoginAction('setactivemain');
		        profile.showLogin();
		    }
		    else {
		        var params = zomoto.ajaxParams(['main'], [main]);
			    zomoto.ajaxCall('Profile', 'SetActiveCarMain', priv.successSetActiveCarMain, priv.errorSetActiveCarMain, params);
			}
		},

		selectBrand : function(id, name, postfix, selectedModel, count) {
	        var params = zomoto.ajaxParams(['brandId', 'brandName', 'postfix', 'selectedModel', 'count'], [id, name, postfix, selectedModel, count]);
		    zomoto.ajaxCall('CarSearch', 'GetModelgroupListByEndeca', priv.successSelectBrand, priv.errorSelectBrand, params);
		},
		
		removeBrand : function(id, name, postfix, count) {
		    var html = '';
            html = '<input class="brandselect" type="checkbox" value="' + id + '" onclick="homepage.selectBrand(\'' + id + '\', \'' + name + '\', \'' + postfix + '\', \'\', \'' + count + '\')">';

            if(count != -1)
            {
		        html += '<label><a class="home-link" onclick="homepage.selectBrand(\'' + id + '\', \'' + name + '\', \'' + postfix + '\', \'\', \'' + count + '\')" href="javascript:void(0);">' + name + '</a><span style=\'color:#7C8390\'>&nbsp;(' + count + ')</span></label>';
		    }
		    else
		    {
		        html += '<label><a class="home-link" onclick="homepage.selectBrand(\'' + id + '\', \'' + name + '\', \'' + postfix + '\', \'\', \'' + count + '\')" href="javascript:void(0);">' + name + '</a></label>';
		    }
		    
		    if(postfix != 'partial') {
		        $('#occ-link-'+id+postfix).html(html);
		    }
		    else{
		        $('#occ-link-'+id).html(html);
		    }
		},
		
		selectAllBrands : function(){
		    priv.allSelected = true;
		
		    var params = zomoto.ajaxParams(['selectAll'], [false]);
		    zomoto.ajaxCall('CarSearch', 'GetAllBrands', priv.successSelectAllBrands, priv.errorAllBrands, params);
		},
		
		removeAllBrands : function() {
		    priv.allSelected = false;
		
		    $('#occasionTab input.brandselect').each(function() {
		        if ($(this).is(':checked')) {
	                var clickevent = String($(this).attr('onclick'));
                    //IE places a function around the onclick event, we have to remove that
                    clickevent = clickevent.replace('function anonymous()\n{', '');
                    //Firefox 3 also does this, but another syntax
                    clickevent = clickevent.replace('function onclick(event) {\n', '');
                    clickevent = clickevent.replace('\n}', '');
		            eval(clickevent);
		            $(this).removeAttr('disabled');
		        }
		    });
        },
		
		
		gotoExtendedSearch : function() {
		    //first select all checked checkboxes
		    var selected = '';
		    var added = new Array();
		    $('#occasionTab input.brandselect').each(function() {
                if($(this).parent().css('display') != 'none')
                {		    
		            if ($(this).attr('checked') != null && $(this).attr('checked') != '') {
		                
		                var contains = false;
		                for(var i = 0; i < added.length; ++i)
		                {
		                    if(added[i] == $(this).val())
		                    {
		                        contains = true;
		                    }
		                }
		                
		                if(contains == false)
		                {
    		                selected += $(this).val() + '+';
    		                added[added.length] = $(this).val();
                        }    		                
		            }
		        }
		    });
		    //then try to get the contents of the dropdowns
		    $('#occasionTab select.modelselect').each(function() {
                if($(this).parent().css('display') != 'none')
                {
    		        if ($('option:selected', this).val() != '-1') {
	    	            selected += $('option:selected', this).val() + '+';
		            }
		        }
		    });
		    if (selected != '') {
		        selected = selected.substring(0, selected.length - 1);
		    }
		    
		    //get the selected price
		    var fromValue = $('#dropDownFromPrice').val();
	        var toValue = $('#dropDownToPrice').val();
	        var priceFilter = '';
	        if (toValue == -1 && fromValue == 0) {
	            //nothing selected, do nothing
	        }
	        else if (toValue == -1) {
	            //just from selected
	            priceFilter = 'Nf=Price|GTEQ+' + fromValue;
	        }
	        else {
                priceFilter = 'Nf=Price|GTEQ+'+fromValue+'||Price|LT+'+toValue;
	        }

            if (priceFilter != '' && selected != '') {
                location.href = global.pathPrefix + '/SearchExtended.aspx?eqs=' + encodeURIComponent('N=' + selected + '&' + priceFilter);
            }
            else if (priceFilter == '' && selected != '') {
		        location.href = global.pathPrefix + '/SearchExtended.aspx?eqs=' + encodeURIComponent('N=' + selected);
		    }
		    else if (priceFilter != '' && selected == '') {
		        location.href = global.pathPrefix + '/SearchExtended.aspx?eqs=' + encodeURIComponent(priceFilter);
		    }
		    else {
		        location.href = global.pathPrefix + '/SearchExtended.aspx';
		    }
		},
		
		focusLicenseSearch : function() {
	        //if it's the original value, remove it
	        $('#txtLicensePlate').removeClass('active');
	        $('#txtLicensePlate').addClass('active');

	        if ($('#txtLicensePlate').val() == 'Vul hier uw kenteken in') {
	            $('#txtLicensePlate').val('');
	            
	            //add the 'active' class to the textbox and the div around it
	        }
	        $('#licensesearchdiv').addClass('active');
	        
	    },
	    
	    blurLicenseSearch : function() {
	        //if the textbox is still empty, set in the default text
	        if ($('#txtLicensePlate').val() == '') {
	            $('#txtLicensePlate').val('Vul hier uw kenteken in');
	            $('#txtLicensePlate').removeClass('active');
	        }
	        $('#licensesearchdiv').removeClass('active');
	    },
	    
	    allBrands : function() {
		    var params = zomoto.ajaxParams(['selectAll'], [true]);
		    zomoto.ajaxCall('CarSearch', 'GetAllBrands', priv.successAllBrands, priv.errorAllBrands, params);
	    },
	    
	    switchTab : function(tabId) {
	        if (tabId == 2){
	            //new cars
	            $('#occasionTab').hide();
	            $('#newCarTab').show();
	        }
	        else {
	            //occasions
	            $('#occasionTab').show();
	            $('#newCarTab').hide();
	        }
	    },
	    
	
		removeBrandNew : function(id, name, postfix, count) {
		    var html = '';
		    html = '<input class="brandselect" type="checkbox" value="' + id + '" onclick="homepage.selectBrandNew(\'' + id + '\', \'' + name + '\', \'' + postfix + '\', \'\', \'' + count + '\')">';
		    html += '<label><a class="home-link" onclick="homepage.selectBrandNew(\'' + id + '\', \'' + name + '\', \'' + postfix + '\', \'\', \'' + count + '\')" href="javascript:void(0);">' + name + '</a>&nbsp;<span style=\'color:#7C8390\'>('+ count +')</span></label>';
		    
		    if(postfix!= 'partial')
		    {
                $('#new-link-'+id+postfix).html(html);
            }
            else 
            {
                $('#new-link-'+id).html(html);
            }
                
		},
		
        selectAllBrandsNew : function() {
            priv.allSelectedNew = true;
        
		    var params = zomoto.ajaxParams(['selectAll'], [false]);
		    zomoto.ajaxCall('CarSearch', 'GetAllBrandsNew', priv.successAllBrandsSelectNew, priv.errorAllBrands, params);
		},
		
		removeAllBrandsNew : function() {
		    priv.allSelectedNew = false;
		
		    $('#newCarTab input.brandselect').each(function() {
		        if ($(this).is(':checked')) {
	                var clickevent = String($(this).attr('onclick'));
                    //IE places a function around the onclick event, we have to remove that
                    clickevent = clickevent.replace('function anonymous()\n{', '');
                    clickevent = clickevent.replace('\n}', '');
		            eval(clickevent);
		        }
		    });
		},
		
		allBrandsNew : function() {
		    var params = zomoto.ajaxParams(['selectAll'], [false]);
		    zomoto.ajaxCall('CarSearch', 'GetAllBrandsNew', priv.successAllBrandsNew, priv.errorAllBrands, params);
	    },
	    
	    doTextSearchNew : function() {
		    //first select all checked checkboxes
		    var selected = '';
    
		    var added = new Array();
		    $('#newCarTab input.brandselect').each(function() {
                if($(this).parent().css('display') != 'none')
                {		    
		            if ($(this).attr('checked') != null && $(this).attr('checked') != '') {
		                
		                var contains = false;
		                for(var i = 0; i < added.length; ++i)
		                {
		                    if(added[i] == $(this).val())
		                    {
		                        contains = true;
		                    }
		                }
		                
		                if(contains == false)
		                {
    		                selected += $(this).val() + '+';
    		                added[added.length-1] = selected;
                        }    		                
		            }
		        }
		    });
		    
		    //then try to get the contents of the dropdowns
		    $('#newCarTab select.modelselect').each(function() {
		        if ($('option:selected', this).val() != '-1') {
		            selected += $('option:selected', this).val() + '+';
		        }
		    });
		    

		    if (selected != '') {
		        selected = selected.substring(0, selected.length - 1);
		    }
		    //get the selected price
		    var fromValue = $('#dropDownFromPriceNew').val();
	        var toValue = $('#dropDownToPriceNew').val();
	        var priceFilter = '';
	        if (toValue == -1 && fromValue == 0) {
	            //nothing selected, do nothing
	        }
	        else if (toValue == -1) {
	            //just from selected
	            priceFilter = 'Nf=Price|GTEQ+' + fromValue;
	        }
	        else {
                priceFilter = 'Nf=Price|GTEQ+'+fromValue+'||Price|LT+'+toValue;
	        }

	        var as = "0";
	        if(priv.allSelectedNew == true)
	        {
	            as = "1"
	        }

            if (priceFilter != '' && selected != '') {
                location.href = global.pathPrefix + '/new/Searchresult.aspx?eqs=' + encodeURIComponent('N=' + selected + '&' + priceFilter) + "&as=1";
            }
            else if (priceFilter == '' && selected != '') {
		        location.href = global.pathPrefix + '/new/Searchresult.aspx?eqs=' + encodeURIComponent('N=' + selected) + "&as=1";
		    }
		    else if (priceFilter != '' && selected == '') {
		        location.href = global.pathPrefix + '/new/Searchresult.aspx?eqs=' + encodeURIComponent(priceFilter) + "&as=1";
		    }
		    else {
		        location.href = global.pathPrefix + '/new/Searchresult.aspx';
		    }
		},
		
		//this is called when the user selects a model, a link should be added to be able to select another model
		//mode can be 'full' or 'partial'
	    test : function(brandId, mode) {
   
		    //het aantal extra geselecteerde modellen (de eerste niet meegeteld)
		    var modelsAdded =  $('.divExtraModel_'+brandId+'_'+mode).size();
		    
		    var addModelLink = "<div class='divAddModelLink_"+brandId+"_"+modelsAdded+"_"+mode+"' style='margin:5px 0px 0px 20px;width:180px'><a href='javascript:void(0);' id='"+modelsAdded+"'  onclick='javascript:homepage.toggleAddModel(\""+brandId+"\", \""+mode+"\");' style='font-size:11px;color:#8D949F'>[+] Model toevoegen</a></div>";
		
            //de eerste modelselectie dropdown (het origineel):
            var originalDD = $('#divBrandSelect_'+ brandId + '_' + mode).html();
            
            //replace the 'removeBrand()' function with the 'deselectModel()' function
            //otherwise, all models of a brand will be deselected when a user clicks the checkbox next to a dropdown
            if(mode == 'review_') 
            {
                var postfix = "_review_"
                originalDD = originalDD.replace(/removeBrand(.)*?[(](.)*?[)]/, "deselectModel('divExtraModel_"+brandId+"_"+modelsAdded+postfix+"');");
            }
            else 
            {
                //the currentpage mode is homepage, make a distinction between the new cars and occasions list
                originalDD = originalDD.replace(/removeBrand(.)*?[(](.)*?[)]/, "deselectModel('divExtraModel_"+brandId+"_"+modelsAdded+"_"+mode+"');");
            }
            
            //de toegevoegde DD's:
            var addedDDs = $('#divExtraBrandSelect_' + brandId + '_' + mode).html();

            var selectedIds = new Array();
            for(var i = 0; i < modelsAdded; i++)
            {
                if($("#divExtraModel_"+brandId+"_"+i+"_"+mode+" select").val() != '-1')
                {
                    selectedIds[i] = $("#divExtraModel_"+brandId+"_"+i+"_"+mode+" select").val();
                }
            }
            
            //nieuwe DD eraan toevoegen, met als extra ID het aantal aanwezige DD van dat merk+1 (modelsAdded)
            var htmlToAdd = "<div id='divExtraModel_"+brandId+"_"+modelsAdded+"_"+mode+"' class='divExtraModel_"+brandId+"_"+mode+"'>";
		    htmlToAdd = htmlToAdd + originalDD;
	        htmlToAdd = htmlToAdd + "</div>";
	    
	        htmlToAdd = addedDDs + htmlToAdd;
	        
	        //only show the link if its not shown yet
	        //$('.divAddModelLink_'+brandId+'_1').css('display')
	        if(modelsAdded != 0)
	        {
    	        if($('.divAddModelLink_'+brandId+'_'+(modelsAdded-1)+'_'+mode).css('display') != 'block')
	            {
	                htmlToAdd = htmlToAdd + addModelLink;
	                
	                 //show the added dropdowns
		            $('#divExtraBrandSelect_'+brandId+'_'+mode).html(htmlToAdd);	    
        		    
		            for(var i = 0; i < modelsAdded; i++)
                    {
                        $("#divExtraModel_"+brandId+"_"+i+"_"+mode+" select").val(selectedIds[i]);
                    }
		            $("#divExtraModel_"+brandId+"_"+modelsAdded+"_" +mode).hide();
	            }
	            else 
	            {
            
	            }
	        }
	        else{
	            htmlToAdd = htmlToAdd + addModelLink;
	            
                 //show the added dropdowns
	            $('#divExtraBrandSelect_'+brandId+'_'+mode).html(htmlToAdd);	    
    		    
	            for(var i = 0; i < modelsAdded; i++)
                {
                    $("#divExtraModel_"+brandId+"_"+i+"_"+mode+" select").val(selectedIds[i]);
                }

	            $("#divExtraModel_"+brandId+"_"+modelsAdded+"_"+mode).hide();	       	            
	        }
	    },		
		
		toggleAddModel : function(brandId, mode)
		{
		    //het aantal extra geselecteerde modellen (de eerste niet meegeteld)
		    var modelsAdded =  $('.divExtraModel_'+brandId+'_'+mode).size()-1;		
		
            //hide the link
		    $('.divAddModelLink_'+brandId+'_'+modelsAdded+'_'+mode).hide();
		    
		    //show the dropdown
		    $("#divExtraModel_"+brandId+"_"+modelsAdded+"_"+mode).attr('style', 'padding-top:4px');	
		    $("#divExtraModel_"+brandId+"_"+modelsAdded+"_"+mode).show();		    
		    
		    $("#divExtraModel_"+brandId+"_"+modelsAdded+"_"+mode).find('input.brandselect').attr('id', "select_"+brandId+"_"+modelsAdded+"_"+mode);
		    $("#divExtraModel_"+brandId+"_"+modelsAdded+"_"+mode).find('input.brandselect').attr('onclick', "homepage.deselectModel('divExtraModel_"+brandId+"_"+modelsAdded+"_"+mode+"')");
		},
		
		deselectModel : function(id)
		{
		    $('#'+id).css('display','none');
		},
		
		//this is called when the user selects a model, a link should be added to be able to select another model
	    test_new : function(brandId, mode) {
   
		    //het aantal extra geselecteerde modellen (de eerste niet meegeteld)
		    var modelsAdded =  $('.divExtraModel_'+brandId+'_new_' + mode).size();
		    
		    var addModelLink = "<div class='divAddModelLink_"+brandId+"_"+modelsAdded+"_new_"+mode+"' style='margin:5px 0px 0px 20px;width:180px'><a href='javascript:void(0);' id='"+modelsAdded+"'  onclick='javascript:homepage.toggleAddModel_new(\""+brandId+"\", \""+mode+"\");' style='font-size:11px;color:#8D949F'>[+] Model toevoegen</a></div>";
		                     
            //de eerste modelselectie dropdown (het origineel):
            var originalDD = $('#divBrandSelect_' + brandId + '_new_' + mode).html();
            
            //replace the 'removeBrand()' function with the 'deselectModel()' function
            //otherwise, all models of a brand will be deselected when a user clicks the checkbox next to a dropdown
            originalDD = originalDD.replace(/removeBrand(.)*?[(](.)*?[)]/, "deselectModel('divExtraModel_"+brandId+"_"+modelsAdded+"_new_"+mode+"');");
            
            //de toegevoegde DD's:
            var addedDDs = $('#divExtraBrandSelect_' + brandId + '_new_' + mode).html();

            var selectedIds = new Array();
            for(var i = 0; i < modelsAdded; i++)
            {
                if($("#divExtraModel_"+brandId+"_"+i+"_"+mode+" select").val() != '-1')
                {
                    selectedIds[i] = $("#divExtraModel_"+brandId+"_"+i+"_new_"+mode+" select").val();
                }
            }
            
            //nieuwe DD eraan toevoegen, met als extra ID het aantal aanwezige DD van dat merk+1 (modelsAdded)
           var htmlToAdd = "<div id='divExtraModel_"+brandId+"_"+modelsAdded+"_new_"+mode+"' class='divExtraModel_"+brandId+"_new_"+mode+"'>";
            htmlToAdd = htmlToAdd + originalDD;
	        htmlToAdd = htmlToAdd + "</div>";
	        htmlToAdd = addedDDs + htmlToAdd;	    
	    
             //show the added dropdowns
	        //only show the link if its not shown yet
	        //$('.divAddModelLink_'+brandId+'_1').css('display')
	        if(modelsAdded!=0)
	        {
	            if($('.divAddModelLink_'+brandId+'_'+(modelsAdded-1)+'_new_'+mode).css('display') != 'block')
	            {
	                htmlToAdd = htmlToAdd + addModelLink;
	                
	                 //show the added dropdowns
		            $('#divExtraBrandSelect_'+brandId+'_new_'+mode).html(htmlToAdd);	    
        		    
		            for(var i = 0; i < modelsAdded; i++)
                    {
                        $("#divExtraModel_"+brandId+"_"+i+"_new_"+mode+" select").val(selectedIds[i]);
                    }

		            $("#divExtraModel_"+brandId+"_"+modelsAdded+"_new_"+mode).hide();
	            }
	        }
	        else{
	            htmlToAdd = htmlToAdd + addModelLink;
	            
                 //show the added dropdowns
	            $('#divExtraBrandSelect_'+brandId+'_new_'+mode).html(htmlToAdd);	    
	            for(var i = 0; i < modelsAdded; i++)
                {
                    $("#divExtraModel_"+brandId+"_"+i+"_new_"+mode+" select").val(selectedIds[i]);
                }

	            $("#divExtraModel_"+brandId+"_"+modelsAdded+"_new_" +mode).hide();	       	            
	        }
	    },	
		
		toggleAddModel_new : function(brandId, mode)
		{
		    //het aantal extra geselecteerde modellen (de eerste niet meegeteld)
		    var modelsAdded =  $('.divExtraModel_'+brandId+'_new_'+mode).size()-1;		
		
            //hide the link
		    $('.divAddModelLink_'+brandId+'_'+modelsAdded+'_new_'+mode).hide();
		    
		    //show the dropdown
		    $("#divExtraModel_"+brandId+"_"+modelsAdded+"_new_"+mode).attr('style', 'padding-top:4px');	
		    $("#divExtraModel_"+brandId+"_"+modelsAdded+"_new_"+mode).show();		    
		    
		    $("#divExtraModel_"+brandId+"_"+modelsAdded+"_new_"+mode).find('input.brandselect').attr('id', "select_"+brandId+"_"+modelsAdded+"_new");
		    $("#divExtraModel_"+brandId+"_"+modelsAdded+"_new_"+mode).find('input.brandselect').attr('onclick', "homepage.deselectModel_new('divExtraModel_"+brandId+"_"+modelsAdded+"_new_"+mode+"')");
		},
		
		deselectModel_new : function(id)
		{
		    $('#'+id).css('display','none');
		},		
		
		focusLicensePlateBox : function()
		{
		    if ($('#txtLicensePlate').val() == 'Vul uw kenteken in')
		    {
		        $('#txtLicensePlate').val('');
		        $('#txtLicensePlate').attr('maxlength', '8');
		        $('#txtLicensePlate').css('text-transform','uppercase');
		        $('#txtLicensePlate').css('padding-left','22px');
		        $('#txtLicensePlate').css('width','132px');
		        $('#txtLicensePlate').css('color','#31363E');
		        $('#txtLicensePlate').css('font-weight','bold');
		        $('#txtLicensePlate').css('font-size','14px');
		        $('#txtLicensePlate').css('text-align','center');
		    }
		},
		
		blurLicensePlateBox : function()
		{
		    if ($('#txtLicensePlate').val() == '')
		    {
		        $('#txtLicensePlate').removeAttr('maxlength');
		        $('#txtLicensePlate').val('Vul uw kenteken in');
		        $('#txtLicensePlate').css('text-transform','none');
		        $('#txtLicensePlate').css('width','132px');
		        $('#txtLicensePlate').css('color','gray');
		        $('#txtLicensePlate').css('font-weight','normal');
		        $('#txtLicensePlate').css('font-size','11px');
		    }
		},
		
        startShowcase : function()
        {
            $('.auto-control').css('background', 'url('+global.pathPrefix+'/images/redesign/btn-showcase-play.gif)')
            if(priv.showcaseInterval != 'undefined')
            {
                priv.showcaseInterval = setInterval('homepage.showShowcaseTab()', 3000);
            }
        },
        
        clickShowcaseTab : function(tabId)
        {
            $('.auto-control').css('background', 'url('+global.pathPrefix+'/images/redesign/btn-showcase-pauze.gif)')
            clearInterval(priv.showcaseInterval);
            
            if(tabId != -1)
            {
                priv.showcaseCurrentIndex = tabId;
                homepage.showShowcaseTab();
            }
        },
        
        showShowcaseTab : function()
        {
            var currentTab = $("#tab" + priv.showcaseCurrentIndex);
            var currentShowcase = $("#showcase" + priv.showcaseCurrentIndex);
        
            $('.auto-info div.showcase-container').each(function() {
                $(this).hide();                
            });
            currentShowcase.show();
            
            $('.auto-head a').each(function() {
                $(this).removeClass('active');            
            });
            currentTab.addClass('active');
            $('#spanTopViewedText').text(priv.showcaseHeaderTexts[priv.showcaseCurrentIndex]);
            
            if(priv.showcaseCurrentIndex == priv.showcaseHeaderTexts.length-1)
            {
                priv.showcaseCurrentIndex = 0;
            }
            else 
            {
                priv.showcaseCurrentIndex = priv.showcaseCurrentIndex + 1;
            }
        },
        
        selectBrandHP : function() {
            var brandId = $('#selectBrand').val();
            
            if(brandId!=-1)
            {
                var params = zomoto.ajaxParams(['brandId_s'], [brandId]);
		        zomoto.ajaxCall('CarSearch', 'GetModelgroupListByEndecaHomepage', priv.successSelectBrandHP, priv.errorSelectBrand, params);
            }
            else 
            {
                $('#selectModel').attr('class', 'disabled');
                $('#selectModel').attr('disabled', 'disabled');
                $('#selectModel').attr('selectedIndex', 0); 
            }
		},
        
        selectBrandNewHP : function() {
            var brandId = $('#selectBrandNew').val();

            if(brandId!=-1)
            {
	            var params = zomoto.ajaxParams(['brandId_s'], [brandId]);
		        zomoto.ajaxCall('CarSearch', 'GetModelgroupListByEndecaNewHomepage', priv.successSelectBrandNewHP, priv.errorSelectBrand, params);
		    }
            else 
            {
                $('#selectModelNew').attr('disabled', 'disabled');
                $('#selectModelNew').attr('selectedIndex', 0);             
                $('#selectModelNew').attr('class', 'disabled');
            }		    
		},
		
        searchOccasions : function() {
            //get the selected N values for the brand and model
		    var brandId = $('#selectBrand').val();
		    var modelId = $('#selectModel').val();
		    
		    //construct the N part of the endecaQuery
		    var nQuery = "N="
		    if(brandId != -1) { nQuery = nQuery + brandId + "+"; }
		    if(modelId != -1) { nQuery = nQuery + modelId; }
		    
		    //if nothing is chosen, query all brands and models
		    if(nQuery == "N=") nQuery = "N=0";
		    
		    //get the selected price
	        var toValue = $('#selectToPrice').val();
	        var priceFilter = '';
	        if(toValue != -1) { priceFilter = 'Nf=Price|GTEQ+0||Price|LT+'+toValue; }

            if (priceFilter != '' && nQuery != '') {
                location.href = global.pathPrefix + '/SearchResult.aspx?eqs=' + encodeURIComponent(nQuery + '&' + priceFilter);
            }
            else if (priceFilter == '' && nQuery != '') {
		        location.href = global.pathPrefix + '/SearchResult.aspx?eqs=' + encodeURIComponent(nQuery);
		    }
		    else {
		        location.href = global.pathPrefix + '/SearchResult.aspx?eqs=' + encodeURIComponent(priceFilter);
		    }
		},
		
        searchOccasionsNew : function() {
            //get the selected N values for the brand and model
		    var brandId = $('#selectBrandNew').val();
		    var modelId = $('#selectModelNew').val();
		    
		    //construct the N part of the endecaQuery
		    var nQuery = "N="
		    if(brandId != -1) { nQuery = nQuery + brandId + "+"; }
		    if(modelId != -1) { nQuery = nQuery + modelId; }
		    
		    //if nothing is chosen, query all brands and models
		    if(nQuery == "N=") nQuery = "N=0";
		    
		    //get the selected price
	        var toValue = $('#selectToPriceNew').val();
	        var priceFilter = '';
	        if(toValue != -1) { priceFilter = 'Nf=Price|GTEQ+0||Price|LT+'+toValue; }

            if (priceFilter != '' && nQuery != '') {
                location.href = global.pathPrefix + '/new/SearchResult.aspx?eqs=' + encodeURIComponent(nQuery + '&' + priceFilter);
            }
            else if (priceFilter == '' && nQuery != '') {
		        location.href = global.pathPrefix + '/new/SearchResult.aspx?eqs=' + encodeURIComponent(nQuery);
		    }
		    else {
		        location.href = global.pathPrefix + '/new/SearchResult.aspx?eqs=' + encodeURIComponent(priceFilter);
		    }
		},
		
		redirect : function(url)
		{
		    window.location = url;
		},
		
		updateCurrentMousePos : function(status)  { priv.showcaseCurrentMousePos = status; },
		getCurrentMousePos : function() { return priv.showcaseCurrentMousePos; }
	}
}(jQuery);

//starts the automatic tab roulation on the homepage
$(function() 
    {
        //unbind the functions that keeps track of the mouseposition before the page is done loading (those are bound in default.aspx file)
        $('.auto').unbind();
    
        //determine where the mouse is positioned when the pageload is finished
        if(homepage.getCurrentMousePos() == 'out') //'out' = not on the showcase tabs
            homepage.startShowcase();
        else 
            homepage.clickShowcaseTab(-1); 
        
        //bind the new functions that will start and pause the showcase tabs
        $('.auto').bind('mouseout', function(){
            homepage.startShowcase();
        });   
        
        $('.auto').bind('mouseover', function(){
            homepage.clickShowcaseTab(-1);
        });
    }
);

