var infoHidden = false;

jQuery(setupFranchisesEvents);

function setupFranchisesEvents(){
	window.DDC = window.DDC || {};
	DDC.FranchiseNav = DDC.FranchiseNav || {};
	var event = DDC.FranchiseNav.activateOnClick ? 'click' : 'mouseover';
	var activateOnClick = DDC.FranchiseNav.activateOnClick;
	
	// hide contact info by default
	$('.groupInfo .contactInfo').hide();
	$('.groupInfo .hours').hide();
	infoHidden = true;
	
	// hide dropdowns if activate on click is set
	if (activateOnClick) {
		$('ul.childSites').css({visibility: 'hidden'});
	}
		
	$('#franchiseNavigation .franchise h4').bind(event, function(){
		switcheroo2(this);
		if (activateOnClick) {
			switcheroo($(this).parent().find('li:eq(0)')[0]);
			if(infoHidden){
				$('.groupInfo .contactInfo').show(500);
				$('.groupInfo .hours').show(500);
				infoHidden = false;
			}
			return false;
		}
	});
	$('#franchiseNavigation .child').bind(event, function(){
		switcheroo(this);
		// show info if necessary
		if(infoHidden){
			$('.groupInfo .contactInfo').show(500);
			$('.groupInfo .hours').show(500);
			infoHidden = false;
			return false;
		}
	});
	
	// setup a new element and copy the dealer name into it.
	$('.groupInfo').prepend('<h3 class=\"dealerName\">'+$('.contactInfo>div>dl>dt').html()+'</h3>');
};

function switcheroo(elem){
	$('.contactInfo>div>dl').html($(elem).find('.contact:eq(0)').html());
	$('.groupInfo>.dealerName').html($('.contactInfo:eq(0)>div>dl>dt').html());
	$('.widget.hours ul').html($(elem).find('.hours:eq(0)').html());
	$('.contactInfo .visit>div').addClass('submit');
	readdressDirectionsForm();
	return false;
};

function switcheroo2(elem){
	$('.contactInfo>div>dl').html($(elem).parent().find('.contact:eq(0)').html());
	$('.groupInfo>.dealerName').html($('.contactInfo:eq(0)>div>dl>dt').html());
	$('.widget.hours ul').html($(elem).parent().find('.hours:eq(0)').html());
	$('.contactInfo .visit>div').addClass('submit');
	readdressDirectionsForm();
	return false;
};

function readdressDirectionsForm(){
	var currentAdr = $('div.groupInfo div.contactInfo address.adr > p.street-address').html() + ', ' + $('div.groupInfo div.contactInfo address.adr > span.locality').html() + ', ' + $('div.groupInfo div.contactInfo address.adr > span.region').html() + ' ' + $('div.groupInfo div.contactInfo address.adr > span.postal-code').html();
	if($('input[name=daddr]').length > 0){
		$('input[name=daddr]').attr('value',currentAdr);
	}
};
