	// The global variable that stores the active filters
	var ActiveFilters = [];
	
	// Will the trim be replaceble or not
	var TrimReplaceable = false;	
	
	// Array.indexOf( value, begin, strict ) - Return index of the first element that matches value
	Array.prototype.indexOf = function( v, b, s ) 
	{for( var i = +b || 0, l = this.length; i < l; i++ ) { if( this[i]===v || s && this[i]==v ) {return i; }} return -1; };
	
	// Array.forEach( function ) - Apply a function to each element // Used to url encode the text
	Array.prototype.forEach = function( f ) 
	{ var i = this.length, j, l = this.length; for( i=0; i<l; i++ ) { if( ( j = this[i] ) ) { this[i] = f(j); } } return this; };
	

	// Replaces all instances of the given substring. Used for encoding. strTarget=what want to replace, strSubString = where want
	String.prototype.replaceAll = function(strTarget,strSubString)
	{	var strText = this;
		var intIndexOfMatch = strText.indexOf( strTarget );	 
		while (intIndexOfMatch != -1) // Keep looping while an instance of the target string still exists in the string.
		{ 	strText = strText.replace( strTarget, strSubString ); // Relace out the current instance.
			intIndexOfMatch = strText.indexOf( strTarget ); // Get the index of any next matching substring.
		}	 
		return( strText ); // Return the updated string with ALL the target strings replaced out with the new substring.
	}
	
	function encodeChars(el) // Function used to encode some characters for passing them to flash
	{
		el = el.replaceAll( "%", "~25" );
		el = el.replaceAll( "&", "~26" );
		el = el.replaceAll( ",", "~27" );		
		return el;
	}
	function decodeChars(el) // Function used to decode some characters for use 
	{
		el = el.replaceAll( "~25", "%" );
		el = el.replaceAll( "~26", "&" );
		el = el.replaceAll( "~27", "," );
		el = el.replaceAll( "|", " " );			
		return el;
	}	


	function removeSubstring(myStr, mySubstr) {
	  myStr = "," + myStr + ",";
	  myStr = myStr.split("," + mySubstr + ",").join(",");
	  myStr = myStr.substring(1, myStr.length-1);
	  return myStr;
	}

	function DisableComplete() // This function check if all trims from a model are disabled and disable the model name/thumb
	{

		var cateinactive = $('#ModelsColumn>div>ul').find('li.inactive').length;
//		$("#Debug").html("<b>We have " +  cateinactive + " inactive trims!</b> <br>");
		// Loop over each model
		$( "#ModelsColumn div.model" ).each(
			// For each model, run this code. The "indIndex" is the loop iteration index on the current element.
			function(intIndex){
				var InactiveTrimsNumber = $(this).find('li.inactive .content').size();
				var TotalTrimsNumber = $(this).find('li .content').size();
				if (InactiveTrimsNumber==TotalTrimsNumber) $(this).find('.modelheader img').addClass('inactive');
				else $(this).find('.modelheader img').removeClass('inactive');	 
			}
		);

	}

	function CheckOfferInColumns(ProcessedFilter, action)
	{
		var FilterExists=false;
		colum1TrimID = $('#column1 div.colcontent').attr('id'); // Get the ID's of the contents for each column
		colum2TrimID = $('#column2 div.colcontent').attr('id'); // in order to identify the corresponding trim
		colum3TrimID = $('#column3 div.colcontent').attr('id'); // who populated that area
		
		Trim1ID = String(colum1TrimID).substring(8, String(colum1TrimID).length); // Produce the effective ID of the trim
		Trim2ID = String(colum2TrimID).substring(8, String(colum2TrimID).length); 
		Trim3ID = String(colum3TrimID).substring(8, String(colum3TrimID).length); 
		
		$("#Debug").html("<b>Procesare " + ProcessedFilter + "</b><br>");
		$("#Debug").append("["+ Trim1ID + "] - [" + Trim2ID + "] - [" + Trim3ID + "]<br>");		
		
		
		Trim1Genuine=false; Trim2Genuine=false; Trim3Genuine=false;
		if (!Trim1ID) Trim1Genuine=true; 
		if (!Trim2ID) Trim2Genuine=true; 
		if (!Trim3ID) Trim3Genuine=true; 				
		
		
		if (Trim1ID)
		if ($('#'+Trim1ID).is('.'+ProcessedFilter)) 
					{ 	$("#Debug").append("["+ Trim1ID + "] are " + ProcessedFilter +  " <br>"); 
						Trim1Genuine=true; 
					} 
					else 
					{ 	$("#Debug").append("["+ Trim1ID + "] nu are " + ProcessedFilter +  " <br>"); 
						if (action=="remove") RemoveColumn($('#'+colum1TrimID).find('.ContentRemove a'));
					} 

		if (Trim2ID)
		if ($('#'+Trim2ID).is('.'+ProcessedFilter)) 
					{ 	$("#Debug").append("["+ Trim2ID + "] are " + ProcessedFilter +  " <br>");
						Trim2Genuine=true; 
					} 
					else 
					{ 	$("#Debug").append("["+ Trim2ID + "] nu are " + ProcessedFilter +  " <br>");
						if (action=="remove") RemoveColumn($('#'+colum2TrimID).find('.ContentRemove a'));
					} 

		if (Trim3ID)
		if ($('#'+Trim3ID).is('.'+ProcessedFilter)) 
					{ 	$("#Debug").append("["+ Trim3ID + "] are " + ProcessedFilter +  " <br>");
						Trim3Genuine=true; 
					} 
					else 
					{ 	$("#Debug").append("["+ Trim3ID + "] nu are " + ProcessedFilter +  " <br>");
						if (action=="remove") RemoveColumn($('#'+colum3TrimID).find('.ContentRemove a'));					
					} 

		$("#Debug").append(Trim1Genuine  + ", " + Trim2Genuine + ", " + Trim3Genuine + " <br>");
		
		if (!Trim1Genuine || !Trim2Genuine || !Trim3Genuine) 
		{
			UnmatchedModels = "<ul>"; // build the html for showing what trims don't apply to the offer just selected
			HowMany = 0; // counts how many models don't fit the offer
			pluralS	="";
			whatCars ="the";
			artCars ="this";
			

			if (!Trim1Genuine) { UnmatchedModels += "<li>" + $('#column1 div.colcontent .modelname').html() + 
			" (1<span class=\"sup\">st</span> column)</li>"; HowMany++; }
			if (!Trim2Genuine) { UnmatchedModels += "<li>" + $('#column2 div.colcontent .modelname').html() + 
			" (2<span class=\"sup\">nd</span> column)</li>"; HowMany++;}
			if (!Trim3Genuine) { UnmatchedModels += "<li>" + $('#column3 div.colcontent .modelname').html() + 
			" (3<span class=\"sup\">rd</span> column)</li>"; HowMany++;}
			UnmatchedModels += "</ul>"
			
			if (HowMany>1) { pluralS="s"; whatCars ="the following"; artCars ="these"; }
			//obtain the id of the Offer Selected (FilterList)			
			offerID = parseInt(String(ProcessedFilter).substring(6,String(ProcessedFilter).length))-1;
			OfferSelected = decodeChars(FilterList[offerID]); // get the name of the Offer Selected

			alertMessage = "The offer that you have just selected (<b>"+ OfferSelected +"</b>) does not apply to " + whatCars +" model"+ pluralS +" that you have selected to compare:<br>" + UnmatchedModels + "<b>Do you want to remove "+artCars+" model"+ pluralS +" from the comparison table?</b><input type='hidden' id='filterUsed' name='filterUsed' value='" + ProcessedFilter +"' />";
			if (action == "prompt") AddPopup(alertMessage)			
		}


//		if (colum1TrimID!="") $("#Debug").html("<b>Column empty! </b> <br> " + ProcessedFilter);
//		else $("#Debug").html("<b>We have " +  Trim1ID + " in columns! </b> <br>" + colum1TrimID);
//		if (column1busy && column2busy && column3busy) return true;
//		else return false;

	}

	// This function gets a filter as a parameter and process it.
	function UpdateFilters(ProcessedFilter) // This function gets called by Flash using ExternalInterface
	{

		// see if this filter don't exists in the array. 
		if (ActiveFilters.indexOf(ProcessedFilter) == -1) // it means that the filter must be added (tick)
			{
				ActiveFilters.push(ProcessedFilter);
				CheckOfferInColumns(ProcessedFilter, "prompt");
			}
		else // it means that the filter exists allready and we have a request to remove it (untick)
			{
				ActiveFilters = jQuery.grep(ActiveFilters, function(value) {
				return value != ProcessedFilter;
				});
			}

		var FilterVisualList = "";
		for (var i = 0; i<ActiveFilters.length; i++) {
		   FilterVisualList += "." + ActiveFilters[i];
		}				
		// For visual refference only you can remove the block bellow		
//		$("#Debug").html(FilterVisualList);
		// For visual refference only you can remove the block above

		if (FilterVisualList)
		{
			$('#ModelsColumn>div>ul>li').addClass('inactive');
			$('#ModelsColumn>div>ul>li.'+FilterVisualList).removeClass('inactive');		
		}
		else
			$('#ModelsColumn>div>ul>li.inactive').removeClass('inactive');
		DisableComplete(); // Disable the header of a model if all it's trims are inactive
	}
	
	function makefilteractive (whatfilter)
	{
		$("#ModelFilters input#"+whatfilter).attr('checked', true);		
	}
	
	function AddCTALinks (whatcolumn)
	{
	// Define the XHTML for the CTA Links		
		$CTAlinks =  "<div id='columncta"+whatcolumn+"'></div>";
		$CTAlinks += "<script type='text/javascript'>";
		$CTAlinks += "var cta = new SWFObject('/Assets/flash/offers/cta-banner.swf', 'ctabanner', '160', '75', '8', '#ffffff');";
		$CTAlinks += "cta.addParam('wmode', 'transparent');";		
		$CTAlinks += "cta.addParam('menu', 'false');";
		$CTAlinks += "cta.addVariable('carid', carId);";	
        $CTAlinks += "cta.write('columncta"+whatcolumn+"');";
		$CTAlinks += "</script>";
		return $CTAlinks;		
	}
	



/*
 * jQuery replaceText - v1.1 - 11/21/2009
 * http://benalman.com/projects/jquery-replacetext-plugin/
 * 
 * Copyright (c) 2009 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($){$.fn.replaceText=function(b,a,c){return this.each(function(){var f=this.firstChild,g,e,d=[];if(f){do{if(f.nodeType===3){g=f.nodeValue;e=g.replace(b,a);if(e!==g){if(!c&&/</.test(e)){$(f).before(e);d.push(f)}else{f.nodeValue=e}}}}while(f=f.nextSibling)}d.length&&$(d).remove()})}})(jQuery);

	
	function makefilterinactive (whatfilter)
	{
		$("#ModelFilters input#"+whatfilter).attr('checked', false);		
	}	
	
    $(document).ready(function()
	{
	// This is used to fix the layout when javascript is turned on
		FixLayout()
	// This functions adds necessary HTML on the page
		AddExtraHTML();
	
		
		flashMovie = document.getElementById("bannerflash");			
	// Used to cache images and avoid the flickering for IE6		
		if (document && document.execCommand) { try { document.execCommand("BackgroundImageCache",false, true); } catch (e) { } }		
				
	// Pupulate the columns with the default content
		$(this).find('div.colcontent').html($("#EmptyColumn").html());		
	// Make all the filter checkboxes unchecked when page is loaded
		$("#ModelFilters input.filter").attr('checked', false);
	// The behaviour of the clicked checkboxes
		$("#ModelFilters input.filter").click(function(){ UpdateFilters($(this).attr('name')); });
	// Add the custom tooltip text for the models
		$("div.modelheader .colex").attr('title', 'Collapse trims');	

	// This is the click to expand colapse functionality for the models
		$("div.modelheader .colex").click(function () {
			  var showstatus = $(this).parent().parent().find("ul").css("display");
			  if (showstatus != "block") // if the model is collapsed
			  	{
					$(this).parent().parent().find("ul").show("slide", { direction: "up" }, 300);
					$(this).attr('title', 'Collapse trims');
					colapseinnerHTML = "<span><img src='/Assets/images/bg/minus-sign.jpg'></span>";
					$(this).html(colapseinnerHTML);
				}
			  else 
			    {
				    $(this).parent().parent().find("ul").hide("slide", { direction: "up" }, 300);
					$(this).attr('title', 'Expand trims');
					colapseinnerHTML = "<span><img src='/Assets/images/bg/plus-sign.jpg'></span>";
					$(this).html(colapseinnerHTML);					
				}
		});

   // build the hover functionality for the models	
		$('#ModelsColumn>div>ul>li').hover(function() {$(this).addClass('model-hover');}, function() { $(this).removeClass('model-hover');});

	});
	
	function FixLayout()
	{
		/* Styles to refix the javascript design*/	
		$('#Columns').css("display", "block");
		$('#Columns').addClass('columnssize');
		$('#ModelsColumn').css("width", "170px");	
		$('.model ul li div.content').css("display", "none");	
		$('.model>ul>li').css("width", "162px");	
		$('.model ul li div.content').css("display", "none");	
		$('.model ul li div.content').css("display", "none");	
		$('.model').css("text-align", "right");	
		$('.model').css("width", "170px");
		$('.modelname').css("display", "block");
		$('.price').css("display", "block");
		$('.noshow').css("display", "none");		
	}
	
	

	function RemoveColumn(el)
	{
		el = $(el).parent().parent().find('.ContentRemove');

		var ContentId = $(el).parent().attr('id');
		WhatColumn =  $(el).parent().parent().attr('id');
		
		ContentId = ContentId.substring(String(ContentId).indexOf("_")+1,ContentId.length);
		// Remove the 'present' class from the corresponding li
		$("#"+ContentId).removeClass("present");
		$("#"+ContentId).hover(function() {$(this).removeClass('present-model-hover'); $(this).addClass('model-hover');}, function() { $(this).removeClass('model-hover');});		
		
		// Replace the content column with the default initial text
		$(el).parent().html($("#EmptyColumn").html());
		// Make the trim back dragable
		$("#"+ContentId).draggable( 'enable');

		//Make the column dragable
		if (!TrimReplaceable) {$('#'+WhatColumn).droppable( 'enable'); }		
		
		// Delete the ID of that column
		$('#Content_' + ContentId).attr('id','');			
		// Hide the alert - this is no longer necessary
		// $("#UserAlerts").html('');			
	}
	
	$(function() {
		$("#ModelsColumn>div>ul>li:not(.inactive)").draggable({ revert: false, helper: 'clone', containment: '#OffersArea', scroll: false,
			start: function(event, ui) 
					{															  
						if (ColumnsNotAvailable() && !TrimReplaceable) NoColumnsAlert()				
					}
				});

		
		$("#Columns>div.column").droppable({
			accept: '#ModelsColumn>div>ul>li:not(.inactive)',
			hoverClass: 'column-hover',
			drop: function(event, ui) 
			{
				
				// if I just dropped the model into a column which had another model then clear the old model in the selection
				if ($(this).find('div.colcontent').attr('id')) 
				   {
					   RemoveColumn($(this).find('div.colcontent').find('.ContentRemove a'));
				   }							
				// add the html for the remove button
				$(this).addClass('dropped').find('div.colcontent').html($("#RemoveColumn").html()); 
				//add the corresponding copy for this model
				$(this).addClass('dropped').find('div.colcontent').append(ui.draggable.find('div').html()); 
				// add the CTA
				$(this).addClass('dropped').find('div.colcontent').append(AddCTALinks($(this).attr('id')));
				// highlight the coresponding draggble trim level as present.
				ui.draggable.addClass('present');
				// Add the specific hover classes for this element because IE6 don't accept chained classes declaration
				ui.draggable.hover(function() {$(this).addClass('present-model-hover');}, function() { $(this).removeClass('present-model-hover');});				
				// Make the curent trim just dragged undraggable
				ui.draggable.draggable( 'disable');
				// If ReplaceTrims inactive make the curent column undroppable				
				if (!TrimReplaceable) { $(this).droppable( 'disable'); }
				
				// Get the id of the model and apply it to the column content
				var TrimId = ui.draggable.attr('id');
				$(this).find("div.colcontent").attr('id','Content_' + TrimId);
				
			},
			over: function(event, ui) 
				 {  // if the hovered column don't have a model specific content then load the default Hover content
					if (!$(this).find('div.colcontent').attr('id')) $(this).find('div.colcontent').html($("#OverColumn").html());
				 },
			out: function(event, ui) 
				 {  // if the recent hovered column don't have a model specific content then load the default empty content
					if (!$(this).find('div.colcontent').attr('id')) $(this).find('div.colcontent').html($("#EmptyColumn").html());
				 }
			
		});
	});

	function ColumnsNotAvailable()
	{
		var colavail=true;
		column1busy = $('#column1').droppable( 'option' , 'disabled');
		column2busy = $('#column2').droppable( 'option' , 'disabled');
		column3busy = $('#column3').droppable( 'option' , 'disabled');	
		if (column1busy && column2busy && column3busy) return true;
		else return false;
	}


	function NoColumnsAlert()
	{
	var errorMessage = "<div class='note'>You can only compare 3 models at a time, please remove one of the models in order to compare this additional model.</div>";
	// 	$("#UserAlerts").html(errorMessage); This functionality was disabled by request
	AddInfoPopup(errorMessage);
	
//	alert(errorMessage);
	}
	
	function AddPopup(AlertMessage)
	{
		$.prompt(AlertMessage,{ buttons: {Yes: true, No: false}, top:'150px', show:'slideDown', focus:'-1' ,callback: ClearConflictingColumns })
	}
	
	function AddInfoPopup(AlertMessage)
	{
		$.prompt(AlertMessage,{ buttons: {OK: true}, top:'150px', show:'slideDown', focus:'-1' })
	}	

    function removetick(whatfilter) {
        flashMovie = document.getElementById("bannerflash");
		flashMovie.callFlashFunctions(whatfilter); 
    }

	function ClearConflictingColumns(v,m,f)
	{
		  if (v) 
		  { $("#Debug").append("You selected Yes to be removed."); 
			// Redo this function with anotehr task. I'm using as parameter the input value with the id filterUsed included in the AlertMessage
			CheckOfferInColumns(f.filterUsed, "remove");
		   }
		  else  {
			  	$("#Debug").append("Don't do anything you selected No or canceled the popup. "); 
				removetick(f.filterUsed);
				}
	}

		
	function AddExtraHTML()	
	{
		colapseHTML = "<div class='colex'><span><img src='/Assets/images/bg/minus-sign.jpg'></span></div>"
		$(".modelheader").append(colapseHTML); 
		
	}
	