 var nonIE6Function = "";

// All Products drop down

var HIDE_LEFT_ATTRIB = 'nu_orig_left';
var HIDE_TOP_ATTRIB = 'nu_orig_top';
var HIDE_POSITION_ATTRIB = 'nu_orig_position';
var HIDE_HEIGHT_ATTRIB = 'nu_orig_height';
var GROUP_ATTRIB = 'nu_orig_group';
var HIDE_POSITION_TOP = '-300000em';

function toggle_the_div(div,fast,with_fade,customFunction)
{
    $(div).each( function() {
        var item = $(this);
        if (HIDE_POSITION_TOP==item.css('top')){
            show_the_div(item,fast,with_fade,customFunction);
		}
        else
            hide_the_div(item,fast,with_fade,customFunction);
    });
}

function hide_the_div(div,fast,with_fade,customFunction)
{
    $(div).each( function() {
        var item = $(this);
        if (HIDE_POSITION_TOP == item.css('top'))
            return;

        item.attr( HIDE_TOP_ATTRIB, item.css('top') );
		item.attr( HIDE_LEFT_ATTRIB, item.css('left') );
        item.attr( HIDE_POSITION_ATTRIB, item.css('position') );
        if (item.height()!='100%')
            item.attr( HIDE_HEIGHT_ATTRIB, item.height() );
        if (fast) {
            item.css('height','0px').css('position','absolute').css('top',HIDE_POSITION_TOP).css('left',0);
			if (customFunction != undefined) {
				customFunction();
			}
        }
        else {
            var settings = null;
            if (with_fade)
                settings = {height:'0px',opacity:0.0};
            else
                settings = {height:'0px'};
            // Now it's been stored we can animate and hide the div
            item.animate( settings, 'normal', function() {
                $(item).css('position','absolute').css('top',HIDE_POSITION_TOP).css('left',0);
				if (customFunction != undefined) {
					customFunction();
				}
            });
        }
    } );
}

function show_the_div(div,fast,with_fade,customFunction)
{
    $(div).each( function() {
		var item = $(this);

		if (item.attr(HIDE_TOP_ATTRIB) == item.css('top'))
            return;

        if (undefined == item.attr(HIDE_TOP_ATTRIB))
            return;
		if (undefined == item.attr(HIDE_LEFT_ATTRIB))
            return;
        if (with_fade)
            item.css('opacity',0.0);
        item.css('top', item.attr(HIDE_TOP_ATTRIB) );
		item.css('left', item.attr(HIDE_LEFT_ATTRIB) );
        item.css('position', item.attr(HIDE_POSITION_ATTRIB) );

        if (undefined == item.attr(HIDE_HEIGHT_ATTRIB))
            var new_height = '';
        else
            var new_height = item.attr(HIDE_HEIGHT_ATTRIB);

		if (fast) {
            item.css('height','').css('opacity',1.0);
			if (customFunction != undefined) {
				customFunction();
			}
        }
        else {
			if (with_fade) {
				item.animate( {opacity:1.0,height:new_height}, 'slow', function() { $(this).height(''); if (customFunction != undefined) {customFunction(); } });
			}
			else {
				item.css('opacity',1.0).animate( {height:new_height}, function() { $(this).height(''); if (customFunction != undefined) {customFunction(); } });
			}
		}
    } );
}


function fadein_the_div(div, customFunction) {
	$(div).each( function() {
		var item = $(this);
        if (undefined == item.attr(HIDE_TOP_ATTRIB))
            return;
		if (undefined == item.attr(HIDE_LEFT_ATTRIB))
            return;

        item.css('top', item.attr(HIDE_TOP_ATTRIB) );
		item.css('left', item.attr(HIDE_LEFT_ATTRIB) );
        item.css('position', item.attr(HIDE_POSITION_ATTRIB) );

		item.css('opacity',0.0);
		item.animate( {'opacity':1.0}, 'slow', function() { if (customFunction != undefined) {customFunction();} });
	});
}

var live_fade_boxes = new Array();
var top_live_fade_boxes = new Array();

// For a dropdown show the layer corresponding to the value and hide all others
// containerList matches to the options in the dropdown

function checkDropdown( obj , containerList, fast ) {
	$(obj).each( function() {
		var setVal = $(this).val();
		var div = containerList[setVal];
		if ((div != null) && (div != undefined)) {
			if(fast){
				show_the_div($(div),true);
			} else {
				show_the_div($(div),false,false);
			}
		} else {
			div = null;
		}


		for(i in containerList){
			var otherDivs = "";
			otherDivs += containerList[i];
			otherDivs = otherDivs.replace(" ","");
			var otherDivsArray = otherDivs.split(",");

			if (div != null) {
				div = div.replace(" ","");
				var divs = div.split(",");

				for( j in divs ) {
					var theDiv = divs[j];
					theDiv = theDiv.replace(",","");
					if(containerList[i] != undefined){
						if (containerList[i].match(theDiv) != null)
						{
							otherDivsArray.splice(getIndexOf(otherDivsArray,theDiv), 1);
						}
					}
				}
			}
			if(otherDivsArray.length > 0) {
				for(k in otherDivsArray){
					if(fast){
						hide_the_div($(otherDivsArray[k]),true);
					} else {
						hide_the_div($(otherDivsArray[k]),false,false);
					}
				}
			}
		}
	});
}

// Show the layer when the input has be checked
// Hide the layer if not
function showLayer(obj, layerName, fast){
	if($(obj).attr('checked') == true){
		if(fast){
			show_the_div($(layerName),true);
		} else {
			show_the_div($(layerName),false,false);
		}
	} else {
		if (fast) {
			hide_the_div($(layerName),true);
		} else {
			hide_the_div($(layerName),false,false);;
		}
	}
}

function showLayerOnId(obj, evalId, layerName, fast){
	$(obj).each( function() {
		if($(this).attr('id').match(evalId) != null){
			if($(this).attr('checked') == true){
				if(fast){
					show_the_div($(layerName),true);
				} else {
					show_the_div($(layerName),false,false);
				}
			} else {
				if (fast) {
					hide_the_div($(layerName),true);
				} else {
					hide_the_div($(layerName),false,false);
				}
			}
		}
	});
}


//Fix for IE6 Image Flicker
try {
  document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}


function highlightFormRow(input){
	$(input).each( function() {
		var thisParents = $(this).parents('.appFormRow, .appFormRowWide');
		$('.appForm input, .appForm select, .appForm textarea').parents('.appFormRow, .appFormRowWide').not(thisParents).each( function(){
			$(this).removeClass('active').addClass('inactive');	
		});
		$(thisParents).removeClass('inactive').addClass('active');
	});
}

/*-------------------------------------------------------------------- 
 * Sets default text for inputs and auto blanks on click and focus
--------------------------------------------------------------------*/

(function() {
    jQuery.fn.autoDefaultText = function(default_text) {
        return this.each(function() {
            var $this=$(this);
            $this.attr('default_text',default_text);
			$this.adtFill();
			
			$this.click(function(){$(this).adtClear()}).focus(function(){$(this).adtClear()}).blur(function(){$(this).adtFill()});
        });
    };
    
    jQuery.fn.adtFill = function() {
        return this.each(function() {
            var $this=$(this);
            if ( undefined==$this.attr('default_text') )
                return;
            else if ($this.val()=='')
                $this.val( $this.attr('default_text') );
        });
    };
    
    jQuery.fn.adtClear = function() {
        return this.each(function() {
            var $this=$(this);
            if ( undefined==$this.attr('default_text') )
                return;
            if ($this.val() == $this.attr('default_text'))
                $this.val('');
        });
    };
})();



function openPopWin(windowURL, windowWidth, windowHeight, windowFeatures, windowName, windowLeft, windowTop) {
	if (windowName == null) {
		windowName = "";
	}

	if (windowLeft=="cen") {
		windowLeft = (screen.width - windowWidth)/2 - 20;
	}
	windowTop =+ 20;

	var windowProperties = "width=" + windowWidth + ",height=" + windowHeight + "," + windowFeatures + ",left=" + windowLeft + ",top=" + windowTop;
	window.open(windowURL,windowName,windowProperties);
}

/**
 * --------------------------------------------------------------------
 * Javascript to alert user that an item has been added to their basket
 * This is only required when the ajax shopping basket solution is not
 * in use.
 * --------------------------------------------------------------------
**/

function createBubble(bubble_content, close_button_available){
	
	var newBubble = $('<div class="popupBox">' +
				'<table cellspacing="0">' +
					'<colgroup>' +
						'<col class="leftCol" />' +
						'<col class="centerCol" />' +
						'<col class="rightCol" />' +
					'</colgroup>' +
					'<tr class="topRow">' +
						'<td class="leftCol"><img src="/assets/images/blank.gif" alt="" /></td>' +
						'<td class="mid"><img src="/assets/images/blank.gif" alt="" /></td>' +
						'<td class="rightCol"><img src="/assets/images/blank.gif" alt="" /></td>' +
					'</tr>' +
					'<tr class="midRow">' +
						'<td class="leftCol"><div><img src="/assets/images/blank.gif" alt="" /></div></td>' +
						'<td class="mid">'+bubble_content+'</td>' +
						'<td class="rightCol"><img src="/assets/images/blank.gif" alt="" /></td>' +
					'</tr>' +
					'<tr class="bottomRow">' +
						'<td class="leftCol"><img src="/assets/images/blank.gif" alt="" /></td>' +
						'<td class="mid"><img src="/assets/images/blank.gif" alt="" /></td>' +
						'<td class="rightCol"><img src="/assets/images/blank.gif" alt="" /></td>' +
					'</tr>' +
				'</table>' +
			'</div>');
	
		if (close_button_available) {
			$(newBubble).append('<a class="close"><img src="/assets/images/close.png" alt="close"></a>');
		}
		
		$(newBubble).find('.close').click(function(e) {
			e.preventDefault();
			hide_the_div($('.popupBox'),false,true, function(){$('.popupBox').remove();});							
		})
	
	return newBubble;
}

function showBubble(initiatingElement, bubble_content, close_button_available, popupWidth){
	if ($('.popupBox').length > 0){
		hide_the_div($('.popupBox'),false,true, function(){$('.popupBox').remove(); showBubble(initiatingElement, bubble_content, close_button_available, popupWidth); });			
	} else {		
		var newBubble = createBubble(bubble_content, close_button_available);
			
		$('body').append(newBubble);

		var pos = $(initiatingElement).offset();
		var height = $(initiatingElement).height();
		var width = $(initiatingElement).width();
		
		var elmWidth = $(window).width() - (( pos.left + width - 2 ) - $(window).scrollLeft() ) ;
		if (popupWidth) {
			popupWidth = parseInt(popupWidth.replace('px'));
			if (popupWidth < elmWidth) {
				elmWidth = popupWidth;
			}
		}
		if (elmWidth < 200){
			elmWidth = 200;
		}
		
		var leftPosition = pos.left + width - 2;
		if ((leftPosition+elmWidth) > ($(window).width() + $(window).scrollLeft())){
			leftPosition = ($(window).width() + $(window).scrollLeft()) - elmWidth;
		}
		
		$(newBubble).css('opacity',0.0).css('display','block').css("top", ( pos.top - 12 )+"px").css("left", leftPosition+"px").css('width',elmWidth+'px');
		$(newBubble).animate( {'opacity':1.0}, 'slow');
	}
}

/*
News ticker plugin (BBC news style)
Bryan Gullan,2007-2009
version 1.2.2
updated 2009-02-15
http://www.makemineatriple.com/jquery
Use and distrubute freely with this header

Options (defaults shown):
newsList: "#news" 	// assumes unordered list; specify the ul holding the news items
tickerRate: 80 		// time gap between display of each letter (ms)
startDelay: 100 	// delay before first run of the ticker (ms)
loopDelay: 3000 	// time for which full text of each item is shown at end of print-out (ms)
placeHolder1: " |"	// character placeholder shown on even loops
placeHolder2: "_"	// character placeholder shown on odd loops

Sample usage:
$(document).ready(function() {
	var options = {
  		newsList: "#news",
 		startDelay: 10,
 		placeHolder1: " []"
	}
	$().newsTicker(options);
});

for markup as follows:

<ul id="news">
<li><a href="http://www.makemineatriple.com">MakeMineATriple.com</a></li>
<li><a href="http://www.jquery.com">jQuery</a></li>
</ul>

Underline text decoration on the link is not recommended! :-)

*/

(function($) {
	
	function runTicker(settings) {
		if(settings.firstRun == 1){
			currentLength = settings.currentLength;
			currentItem = settings.currentItem;
			settings.firstRun = 0;
		}
		if(currentItem == settings.newsItemCounter + 1){
			currentItem = 0;
		}
		
		if(currentLength == 0) {
			if(settings.newsLinks[currentItem].length > 0) {
				$(settings.newsList).empty().append('<li><a href="'+ settings.newsLinks[currentItem] +'"></a></li>');
			}
			else {
				$(settings.newsList).empty().append('<li></li>');
			}
		}
		
		if( currentLength % 2 == 0) {
				placeHolder = settings.placeHolder1;
		}
		else {
			placeHolder = settings.placeHolder2;
		}
		
		if( currentLength <= settings.newsItems[currentItem].length + 1) {
			var tickerText = settings.newsItems[currentItem].substring(0,currentLength);
			if(settings.newsLinks[currentItem].length > 0) {
				$(settings.newsList + ' li a').text(tickerText + placeHolder);
			}
			else {
				$(settings.newsList + ' li').text(tickerText + placeHolder);
			}
			currentLength ++;
			setTimeout(function(){runTicker(settings); settings = null;},settings.tickerRate);
		}
		else {
			if(settings.newsLinks[currentItem].length > 0) {
				$(settings.newsList + ' li a').text(settings.newsItems[currentItem]);
			}
			else {
				$(settings.newsList + ' li').text(settings.newsItems[currentItem]);
			}
			currentLength = 0;
			currentItem ++;
			setTimeout(function(){runTicker(settings); settings = null;},settings.loopDelay);	
		}	
	}
	
	$.fn.extend({
		newsTicker: function(settings) {
			settings = jQuery.extend({
		 	  	newsList: "#news",
		   		tickerRate: 80,
		    	startDelay: 100,
		    	loopDelay: 3000,
		    	placeHolder1: " |",
		    	placeHolder2: "_"
			}, settings);
			
			var newsItems = new Array();
			var newsLinks = new Array();
			var newsItemCounter = 0;
			
			$(settings.newsList + ' li').hide();
			
			$(settings.newsList + ' li').each(function(){
				if($(this).children('a').length) {
					newsItems[newsItemCounter] = $(this).children('a').text();
					newsLinks[newsItemCounter] = $(this).children('a').attr('href');
				}
				else {
					newsItems[newsItemCounter] = $(this).text();
					newsLinks[newsItemCounter] = '';
				}
				newsItemCounter ++;
			});
			
			settings = jQuery.extend(settings,{
				newsItems: newsItems,
				newsLinks: newsLinks,
				newsItemCounter: newsItemCounter - 1,
				currentItem: 0,
				currentLength: 0,
				firstRun:1
			});
			
			setTimeout(function(){runTicker(settings); settings = null;},settings.startDelay);
		}
	
	});
	

})(jQuery);

$(document).ready(function(){
	$('body').addClass('jsEnabled');
				
	hide_the_div($('#socialMediaLinks'),true,false);
	
	function toggleIcon(thisDiv) {
		thisDiv.each( function() {
			if ( HIDE_POSITION_TOP==$(this).css('top') ){
				 $('#getInvolved').removeClass('open');
			} else {
				$('#getInvolved').addClass('open');
			}
		});
	}
	$('#getInvolved').click(function(){
		toggle_the_div($('#socialMediaLinks'),false,true, function(){toggleIcon($('#socialMediaLinks'))} );		
	});
	
	$('#searchMenu').mouseenter(function(){ $('#site_search').focus(); });
	
	$('.gotAQuestion input[type=text]').autoDefaultText('Enter your question');	
	$('.planARoute input[type=text]').autoDefaultText('Enter a location or postcode');	
	$('.enterLocation input[type=text]').autoDefaultText('Enter location');	
	$('.enterReg input[type=text]').autoDefaultText('Enter registration number');
	$('.enterComment').autoDefaultText('Enter your comments here...');
	
	$('form').submit( function() { $(this).find('input[type=text]').adtClear(); });

	$('.appForm input, .appForm select, .appForm textarea').focus( function(){ // colour rows on selecting an input
		highlightFormRow($(this));
	});
	
	
	function toggleDropdownStatus(thisDD) {
		thisDD.each( function() {
			var thisDT = $(this).prev();
			if ( HIDE_POSITION_TOP==$(this).css('top') ){
				 $(thisDT).removeClass('open');
			} else {
				$(thisDT).addClass('open');
			}
		});
	}
	
	hide_the_div($('#homepageAccordian dd, #productsAccordian dd'), true, false);
	$('#homepageAccordian dt, #productsAccordian dt').click(function(){
		var thisDD = $(this).next();
		hide_the_div($(thisDD).siblings('dd'), false, true, function(){toggleDropdownStatus($(thisDD).siblings('dd'))} );
		toggle_the_div($(thisDD), false, true, function(){toggleDropdownStatus(thisDD)} );
	});
	
	hide_the_div($('#contactUsAccordian li span.content'), true, false);
	$('#contactUsAccordian li span.title').click(function(){
		var thisDD = $(this).next();
		hide_the_div($('span.content'), false, true, function(){toggleDropdownStatus($('span.content'))} );
		toggle_the_div($(thisDD), false, true, function(){toggleDropdownStatus(thisDD)} );
	});
	
	
	$('form.newWindow').attr('target','_blank');
	
	$('form.gotAQuestion').submit(function(e){
		e.preventDefault();
		openWin($('#nlpq').val(), $('#kb').val());							
	});
	
	function openWin(textIn, text2In){
		textIn == 'Enter your question' ? nlpq = '' : nlpq = textIn;
		var kb = text2In;
		var mfWin=window.open("http://help.rac.co.uk/templates/rachelp/seo/resultsPage?nlpq=" + nlpq + "&kb=" + kb,mfWin,"screenX=10,screenY=10,left=10,top=10,width=700,height=600,scrollbars=yes,resizable=yes,toolbar=yes,menubar=yes");
		mfWin.focus();
	}
	
	$('a').each( function() {

		var pageUrl = window.location.hostname;
		if (pageUrl.indexOf('uat.') == 0) {
			pageUrl = pageUrl.replace('uat.','');
		} else if (pageUrl.indexOf('prod.') == 0) {
			pageUrl = pageUrl.replace('prod.','');
		}

		var elementUrl = $(this).attr('href');
		
		if(elementUrl != undefined) {
			if ((elementUrl.indexOf('http') == 0) && (elementUrl.indexOf('rac.co.uk') == -1) && (elementUrl.indexOf('search.rac') == -1) && (elementUrl.indexOf(pageUrl) == -1) && ( $(this).attr('rel') == '' ))
            {
				$(this).attr('rel','external');
			} 
		}						  
						  
		var popupType = $(this).attr('rel');

		if(popupType == "popup")
		{
			$(this).click( function(event) {
				event.preventDefault();
				openPopWin($(this).attr('href'), '520', '500', 'scrollbars=yes,resizable=yes');
			});
		}
		else if((popupType == "external") || (popupType == "newWindow"))
		{
			$(this).click( function(event) {
				event.preventDefault();
				openPopWin($(this).attr('href'), '800', '600', 'location=yes,scrollbars=yes,resizable=yes,menubar=yes,status=yes,toolbar=yes');
			});
		}

		if ((popupType == "popup") || (popupType == "external") || (popupType == "quoteWindow") || (popupType == "newWindow")) {
			if (($(this).attr('title') == null) || ($(this).attr('title') == '')) {
				if($(this).hasClass('linkPdf')){
					$(this).attr('title', 'This link will open a PDF in a new browser window');
				} else {
					$(this).attr('title', 'This link will open in a new window');
				}
			}
			else {
				if($(this).hasClass('linkPdf')){
					var newTitle = $(this).attr('title') + ' - This link will open a PDF in a new browser window';
				} else {
					var newTitle = $(this).attr('title') + ' - This link will open in a new window';
				}
				$(this).attr('title', newTitle);
			}
		}
	});

	$('.learnMoreOrange, .learnMoreOrangeIcon, .learnMorePlain').each( function() {
		var contentId = $(this).attr('href');
		if ((contentId) && (contentId != '#') && (contentId != '')) {
			var content = $(contentId).html();
			if (content) {
				$(this).click(function(e){
					e.preventDefault();
					showBubble($(this), content, true, '360px');
				});
			}
		}
	});
	
	if($(".newsTicker").length > 0) {
		$(".newsTicker").css('display','block');
		var news_ticker_options = {
			newsList: ".newsTicker",
			tickerRate: 80,
			startDelay: 0, 
			loopDelay: 5000,
			placeHolder1: " "
		}
		$().newsTicker(news_ticker_options);
	}


	/* add in hover effect for IE */
	if ( jQuery.browser.msie ) {
		
	};
});