var motoToggleAction = function()
{
	var startImg = $(this).attr('src');
	var overImg = $(this).attr('lowsrc');
	$(this).attr('src',overImg);
	$(this).attr('lowsrc',startImg);
}
var mototipAction = function()
{
	$('#mototipContainer').remove();
	var path = $(this).attr('ajax') || $(this).attr('href');
	var params = $(this).attr('rel') || '?width=200&pos=south';
	var defaultContentContainer = $(this).attr('defaultDiv');
	var xtra = '';
	if ( defaultContentContainer )
	{
		xtra = $('#'+defaultContentContainer).html();	
	}
	var width = getURLParam( 'width', params ) || 200;
	var pos = getURLParam( 'pos', params ) || 'south';
	if ( getURLParam( 'top', params ) )
	{
		var top = getURLParam( 'top', params );
		pos = false;
	}
	if ( getURLParam( 'left', params ) )
	{
		var left = getURLParam( 'left', params );
		pos = false;
	}
	if ( getURLParam( 'class', params ) )
	{
		var classname = getURLParam( 'class', params );
	}
	else
	{
		var classname = 'mototipStyle1';
	}
	if ( $(this).attr('title') != undefined )
	{
		var caption = '<h2>'+$(this).attr('title')+'</h2>';	
	}
	$("body").append('<div id="mototipContainer" class="'+classname+'"><h1>X</h1><p><img src="/common/images/loading.gif" /></p>'+xtra+'<br /><a href="#" onclick="$(\'#mototipContainer\').remove(); return false;">Close</a><br />&nbsp;</div>');
	$('#mototipContainer').css('width', width+'px');
	$('#mototipContainer h1').click(function(){
		$('#mototipContainer').remove();
		return false;
	});
	
	switch ( pos )
	{
		case 'south':
			var top = getAbsY(this) + $(this).height() + 4;
			var left = getAbsX(this) - Math.ceil( $('#mototipContainer').width() / 2 );
			break;
		case 'southeast':
			var top = getAbsY(this) + $(this).height() + 4;
			var left = getAbsX(this) - $('#mototipContainer').width();
			break;
		case 'east':
			var top = getAbsY(this);
			var left = getAbsX(this) + $(this).width() + 4;
			break;
		case 'northeast':
			var top = getAbsY(this) - ( $('#mototipContainer').height() + 200);
			var left = getAbsX(this) + $(this).width() + 4;
			break;
	}
	
    //ensure this doesn't show up offscreen
    if(left + $('#mototipContainer').width() > ($('body').width() - 20) ){
        left = $('body').width() - $('#mototipContainer').width() - 20;
    }
        
	$('#mototipContainer').css('top', top+'px');
	$('#mototipContainer').css('left', left+'px');
	$('#mototipContainer').slideDown('fast');
	
	$.get( path, function(data) {
		$('#mototipContainer p').html(data);
	});
	return false;
}

var mototipsimpleAction = function()
{
	$('#mototipContainer').remove();
	var path = $(this).attr('ajax') || $(this).attr('href');
	var params = $(this).attr('rel') || '?width=200&pos=south';
	var defaultContentContainer = $(this).attr('defaultDiv');
	var xtra = '';
	if ( defaultContentContainer )
	{
		xtra = $('#'+defaultContentContainer).html();	
	}
	var width = getURLParam( 'width', params ) || 200;
	var pos = getURLParam( 'pos', params ) || 'south';
	if ( getURLParam( 'top', params ) )
	{
		var top = getURLParam( 'top', params );
		pos = false;
	}
	if ( getURLParam( 'left', params ) )
	{
		var left = getURLParam( 'left', params );
		pos = false;
	}
	if ( getURLParam( 'class', params ) )
	{
		var classname = getURLParam( 'class', params );
	}
	else
	{
		var classname = 'mototipStyle1';
	}
	//alert( classname );
	$("body").append('<span id="mototipContainer" class="'+classname+'"><img src="/common/images/loading.gif" /></span>');
	$(this).mouseout(function(){
		$('#mototipContainer').remove();
		return false;
	});
	
	switch ( pos )
	{
		case 'south':
			var top = getAbsY(this) + $(this).height() + 4;
			var left = getAbsX(this) - Math.ceil( $('#mototipContainer').width() / 2 );
			break;
		case 'southeast':
			var top = getAbsY(this) + $(this).height() + 4;
			var left = getAbsX(this) - $('#mototipContainer').width();
			break;
		case 'east':
			var top = getAbsY(this);
			var left = getAbsX(this) + $(this).width() + 4;
			break;
		case 'northeast':
			var top = getAbsY(this) - ( $('#mototipContainer').height() + 200);
			var left = getAbsX(this) + $(this).width() + 4;
			break;
	}
	
	$('#mototipContainer').css('top', top+'px');
	$('#mototipContainer').css('left', left+'px');
	$('#mototipContainer').show();
	
	$.get( path, function(data) {
		$('#mototipContainer').html(data);
	});
	return false;
}
var motoPopup = function()
{
	var name = "PopUpWindow";
	var setting, parameters, mysettings, b, a;
	
	// for overrideing the default settings
	mysettings = (jQuery(this).attr("rel") || "").split(",");

	
	settings = {
		height:600, // sets the height in pixels of the window.
		width:600, // sets the width in pixels of the window.
		toolbar:0, // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}.
		scrollbars:0, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}.
		status:0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}.
		resizable:1, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable.
		left:0, // left position when the window appears.
		top:0 // top position when the window appears.
		};
		
	if(mysettings.length == 1 && mysettings[0].split(":").length == 1)
	{
		a = mysettings[0];
		// see if a profile has been defined
		if(typeof profiles[a] != "undefined")
		{
			settings = jQuery.extend(settings, profiles[a]);
		}
	}
	else
	{
		// overrides the settings with parameter passed in using the rel tag.
		for(var i=0; i < mysettings.length; i++)
		{
			b = mysettings[i].split(":");
			if(typeof settings[b[0]] != "undefined" && b.length == 2)
			{
				settings[b[0]] = b[1];
			}
		}
	}
		
	parameters = "height=" + settings.height + ",width=" + settings.width + ",toolbar=" + settings.toolbar + ",scrollbars=" + settings.scrollbars  + ",status=" + settings.status + ",resizable=" + settings.resizable + ",left=" + settings.left  + ",screenX=" + settings.left + ",top=" + settings.top  + ",screenY=" + settings.top;	
	window.open(this.href, name, parameters).focus();
	return false;	
}

jQuery.fn.vjustify=function() {
    var maxHeight=0;
    this.each(function(){
        if (this.offsetHeight>maxHeight) {maxHeight=this.offsetHeight;}
    });
    this.each(function(){
        $(this).height(maxHeight + "px");
        if (this.offsetHeight>maxHeight) {
            $(this).height((maxHeight-(this.offsetHeight-maxHeight))+"px");
        }
    });
};
function savedRidesFilter(obj)
{
	var redirecturl = $(obj).attr('rel');
	if ( $(obj).val() )
	{
		var url = redirecturl+'&sMMY='+$(obj).val();
		window.location = url;
		return false;
	}
	else if ( $(obj).val() == 'addnew' )
	{
		tb_show('', $(obj).attr('alt'), false);
		return true;
	}
}
$(document).ready(function(){
	
	// resizes the the refine search lists if
	// # of items exceeds a given limit
	// adds scroll bar
	$('.refineSearchWrapper').each(function(){
		if ( $(this).attr('itemCount') )
		{
			var itemCount = $(this).attr('itemCount');
			var maxItemSize = $(this).attr('maxItemSize');
			var maxItemHeight = $(this).attr('maxItemHeight');
			if ( parseInt(itemCount) > parseInt(maxItemSize) )
			{
				$(this).height(maxItemHeight);
				$(this).css('overflow','auto');
			}
		}
	});
						   
	$('#sortForm :submit').hide();
	$('.horizMenuName').hovermenu({menuClass:'.horizMenuName'});
	$('.vertMenuItem').hovermenu({hoverbkg:'#FFFFFF', vertical:true, menuSelector:'.vertMenu',menuClass:'.vertMenuItem'});
	$('img.fixpng').ifixpng();
	$('.fixpng img').ifixpng();
	$('#logo img').ifixpng();
	$('#selector img').ifixpng();
	$('#helpLink').click(
		function(){
			var top = getAbsY(this) + $(this).height() + 4;
			var left = getAbsX(this);// - $('#helpLinkContainer').width();
			clearTimeout(hidemenu);
			$('#helpLinkContainer').css('top', top+'px');
			$('#helpLinkContainer').css('left', left+'px');
			$('#helpLinkContainer').slideDown('fast');
			var hidemenu = setTimeout( function() {
				$('#helpLinkContainer').hide();
			}, 5000 );
			return false;
		}
	);
	$('.hoursLink').click(
		function(){
			var top = getAbsY(this) + $(this).height() + 4;
			var left = getAbsX(this);// - $('#hoursLinkContainer').width();
			clearTimeout(hidemenu);
			$('#hoursLinkContainer').css('top', top+'px');
			$('#hoursLinkContainer').css('left', left+'px');
			$('#hoursLinkContainer').slideDown('fast');
			var hidemenu = setTimeout( function() {
				$('#hoursLinkContainer').hide();
			}, 5000 );
			return false;
		}
	);
	$('.mototoggle').mouseover(motoToggleAction);
	$('.mototoggle').mouseout(motoToggleAction);
	$('.pngtoggle').hover(
		function(){
			var off = $(this).attr('off');
			$(this).attr('src',off);
			$(this).ifixpng();
		},
		function(){
			var on = $(this).attr('on');
			$(this).attr('src',on);
			$(this).ifixpng();
		});
	$('.toggleonoff').hover(
		function(){
			var on = $(this).attr('on');
			$(this).attr('src',on);
			$(this).ifixpng();
		},
		function(){
			var off = $(this).attr('off');
			$(this).attr('src',off);
			$(this).ifixpng();
		});
	$('.mototiphover').mouseover(mototipAction);
	$('.mototipsimplehover').mouseover(mototipsimpleAction);
	$('.mototipclick').click(mototipAction);
	// show pulldown button next to link
	$('.mototipbutton').append('<img src="/common/images/rolloverpulldown.gif" align="absmiddle" border="0" style="margin-left: 3px;" />');

	// Popup windows
	$('.motoPopup').click(function(){
		var winref, parameters, settings;
		parameters = $(this).attr('rel') || 'width=555,height=450,centerscreen=true,chrome=yes';
		if( winref == null || winref.closed )
		{
			winref = window.open(this.href, this.target, parameters);
		}
		winref.focus();
		return false;		
	});
	
	// Popup windows
	$('.BMLmotoPopup').click(function(){
			var winref, parameters, settings;
			if( winref == null || winref.closed )
			{
				winref = window.open($(this).attr('href'), this.target, 'width=505,height=800,centerscreen=true,chrome=yes,scrollbars=yes');
			}
			winref.focus();
			return false;		
	});
	
	$('.EmailFriendPopUp').click(function(){
						var winref, parameters, settings;
						if( winref == null || winref.closed )
						{
							winref = window.open($(this).attr('href'), this.target, 'width=390,height=420,centerscreen=true,chrome=no,scrollbars=no,resizable=no');
						}
						winref.focus();
						return false;		
	});
	
	// Popup windows
	$('.LargemotoPopup').click(function(){
			var winref, parameters, settings;
			if( winref == null || winref.closed )
			{
				winref = window.open($(this).attr('href'), this.target, 'width=700,height=800,centerscreen=true,chrome=yes,scrollbars=yes');
			}
			winref.focus();
			return false;
	});
	$('#addaridelink').click(function(){
		$('#rideFilterContainer').removeClass('rideFilterContainer');
		$('#rideFilterContainer').addClass('rideFilterContainerOpened');
		$('#addRideContent').show(); return false;
	});
	$('.frmCheckout').submit(function(){
		$('.checkoutbutton').attr('disabled','disabled');
		$('.checkoutbutton').css('opacity','.5');
		$('.checkoutbutton').css('background-color','#EEEEEE');
		$('.checkoutbutton').css('border','solid 2px #CCCCCC');
		$('.checkoutbutton').html($('.checkoutbutton').attr('alt'));
	});
	$('.frmOrderUpdate').submit(function(){
		$('.frmOrderUpdate button').attr('disabled','disabled');
		$('.frmOrderUpdate button').css('opacity','.5');
		$('.frmOrderUpdate button').html($('.frmOrderUpdate button').attr('alt'));
	});
	var clearValues = function(){
		if ( $(this).val() !== $(this).attr('alt') ) return;
		$(this).val('');
		$(this).css('color','#333');
	}
	var resetValues = function(){
		if ( $(this).val() !== '' ) return;
		$(this).val($(this).attr('alt'));
		$(this).css('color','#999');
	}
	var clearPasswordValues = function(){
		if ( $(this).val() !== $(this).attr('alt') ) return;
		$(this).attr('type', 'password');
		$(this).attr('maxlength', '8');
		$(this).val('');
		$(this).css('color','#333');
	}
	var resetPasswordValues = function(){
		if ( $(this).val() !== '' ) return;
		$(this).attr('type', 'text');
		$(this).attr('maxlength', '20');
		$(this).val($(this).attr('alt'));
		$(this).css('color','#999');
	}
	$('.defaultText').each(resetValues);
	$('.defaultText').focus(clearValues).click(clearValues);
	$('.defaultText').blur(resetValues);
	$('.defaultPassword').each(resetPasswordValues);
	$('.defaultPassword').focus(clearPasswordValues).click(clearPasswordValues);
	$('.defaultPassword').blur(resetPasswordValues);
	$('#searchform').submit(function(){
		var s = $('#searchbox');
		if ( s.val() == s.attr('alt') )
		{
			s.val('');
		}
	});
	$('.addressForm').submit(
		function(){
			var elems = this.elements;
			for( var i = 0; i < elems.length; i++ )
			{
				if ( elems[i].className == 'defaultText' && elems[i].value == elems[i].alt )
				{
					elems[i].value = '';
				}
			}
		}						 
	);
	$('.sortSelect').change(function(){
		url = $("#url").val();
		url += '&sortOrder='+$(this).val();
		window.location = url;
	});
	
	
	$('.offsitelink').click(function()
		{
			$(this).append('<div id="offsiteLinkContent" style="display:none;"><p style="text-align:center; padding:0px; margin:0px;"></p></div>');
			tb_remove();
			var size = $(this).attr('rel') || 'width=400&height=75';
			a = '#TB_inline?modal=true&inlineId=offsiteLinkContent&'+size;
			msg = $(this).attr('message')+'<br /><img src="/common/images/loading.gif" border="0" align="center" />';
			$('#offsiteLinkContent p').html(msg);
			var t = this.title || this.name || null;
			var g = this.rel || false;
			tb_show(t,a,g);
			this.blur();
			setTimeout('window.location = "'+this.href+'"', 1000);
			return false;
		});

	
	
});
    var MOTOSPORT_COM_LOAD_LOADER = {
        clickDelegate:function(e){
            var href = $(e.target).attr('href');
            if(!href){
                href = $(e.target).attr('action');
            }
            var e_target_offset_top = $(e.target).offset().top;
            var e_has_class = $(e.target).hasClass('msDelayClose');
            setTimeout(function(){
                if(href && ( -1 != href.indexOf('/search/') || -1 != href.indexOf('/category/') ) && !e_has_class){
                    if($('div#msLoader').length > 0){
                        $('div#msLoader').css('display','block');
                    }
                    else{
                        //it's a search link, insert our loading text  
						if ( tb_imageDomain )
						{
							var loadingimg = tb_imageDomain + '/common/images/loading.gif';
						}
						else
						{
							var loadingimg = '/common/images/loading.gif';
						}
                        var the_img = '<div id="msLoader" style="border-color:#CCC;border-width:3px;border-style:solid;position:absolute;left:500px;top:200px;z-index:1500;background-color:#fff;width:200px;padding:5px;">';
                        the_img += '<img src="'+loadingimg+'" border="0" style="margin-right:10px;" align="absmiddle" />';
                        the_img += "Retrieving Results ... (<a href=\"#\" onclick=\"$('#msLoader').css('display','none');return false;\" class=\"msDelayClose\">Hide</a>)</p>";                
                        the_img += '</div>';
						
                        $('body').append(the_img);
                    }
                    
                    //position it
                    var the_left = parseInt(( $(window).width() - $('#content').width() ) /2) + (parseInt(990/2) - parseInt(($('#msLoader').width()/2)));
                    $('div#msLoader').css('left', the_left+'px');
                    
                    //scrollTop() isn't working... jQuery version? Name colission?  Who knows
                    //check to see if clicked element is below the fold, and if so position
                    //our loader to it lines up
                    var offset = $(window).height() - e_target_offset_top;
                    if(offset < 0){
                        //var new_top = 200;
                        //new_top += new_top+Math.abs(offset);
                        //new_top += $('div#msLoader').height();
                        new_top = e_target_offset_top;
                        $('div#msLoader').css('top',new_top+'px');
                    }
                }
    
            }, 1000);
            //ensure the link action goes where it's supposed to
            return true; //MAKE THIS TRUE SO LINKS WORK
        }        
    };


function setRideAlert( msg )
{
	$('#addedRideAlertBox').show('fast');
	$('#addedRideAlertBox').html( msg );
	$('#addedRideAlertBox').Pulsate(100,2);
	setTimeout("$('#addedRideAlertBox').hide('fast')", 3000);
}

function setRidesTable( p, sMMY )
{
	$('#rideSelectList').empty();
	$('#rideSelectList').html('<div id="rideList"></div>');
	
	
	$.each( p, function( type, row ) {
		setRidesListByType( type, row, sMMY );
	});
	$('#rideSelectList').removeClass('rideSelectListInit');
}



function selectMMY( url )
{
/*
	$.getJSON(
		callbackUrl, {
			rnd: 			Math.random(),
			action: 	"selectRide",
			mmy: 			mmy
			},
			function(json)
			{
					if ( redirect )
					{
						url = '/' + currentSkin + redirect + '&sMMY='+mmy;
						window.location = url;
					}
			}
		);
*/
window.location = url;
}

function setSelectedMMY(mmy)
{
	$.getJSON(
		callbackUrl, {
			rnd: 			Math.random(),
			action: 	"selectRide",
			mmy: 			mmy
			},
			function(json)
			{
				//alert( mmy );
			}
	);	
}

function setRidesListByType( type, rides, sMMY )
{
	//alert( type + '=' + rides.length );
	if ( rides.length != 0)
	{
		var useskin = rideMeta.data[type]['skin'];
		var label = rideMeta.data[type]['label'];
		var tableclass = rideMeta.data[type]['tclass'];
		$('<table id="ridesTable'+type+'" cellpadding="0" cellspacing="0" border="0" width="100%" class="'+tableclass+'"></table><br />').appendTo('#rideList');
		$('#ridesTable'+type).append( '<tr><th colspan="3">'+label+'</th></tr>' );
		var index = 0;
		for( i in rides )
		{
			$('#ridesTable'+type).append( '<tr id="rideRow'+type+index+'"></tr>' );
			$('#rideRow'+type+index).attr("mmy",i);
			if ( rides[i]['count'] )
			{
				var ridelabel = rides[i]['label'] + '<br /><span>('+rides[i]['count']+' results in '+catlabels+')</span>';
			}
			else
			{
				var ridelabel = rides[i]['label'];
			}
			$('#rideRow'+type+index).attr("title",rides[i]['label']);
			$('#rideRow'+type+index).attr("alt",ridelabel);
			$('#rideRow'+type+index).append( '<td id="rideLabel'+type+index+'"></td>' );
			$('#rideRow'+type+index).append( '<td id="rideActions'+type+index+'" align="center" valign="top" width="30"></td>' );
			$('#rideRow'+type+index).append( '<td id="rideActionsDelete'+type+index+'" align="center" valign="top" width="30"></td>' );
			$('#rideActionsDelete'+type+index).append( '<img src="/common/images/tinydeletelabel.gif" style="margin-bottom:8px;" /><img src="/images/deleteRide.gif" id="deleteRideButton'+type+index+'" />' );
			$('#deleteRideButton'+type+index).css({cursor:"pointer"});
			$('#deleteRideButton'+type+index).click( function() { 
					deleteRide( $(this).parent().parent().attr('mmy'), $(this) );
			} );
			if ( sMMY == i )
			{
				$('#rideRow'+type+index).css({background:"#FFC"});
				var selected = "checked=checked";
			} else {
				var selected = "";
			}
			$('#rideLabel'+type+index).css({padding: '8px'});
			
			$('#rideActions'+type+index).html('<div id="selectRide'+type+index+'"></div>');
			
			if ( redirect ) 
			{
				if ( currentSkin != useskin )
				{
					redirect = '/rideselector.php?sMMY='+i;
				}
				else
				{
					redirect = initredirect + '&sMMY='+i+'&cat0='+type;
				}
				link = '/'+useskin+redirect;
			}
			else
			{
				link = '/' + useskin + '/rideselector.php?sMMY=' + i;
			}
			
			$('#rideLabel'+type+index).html('<label id="rideSelectLabel'+type+index+'" for="rideSelect'+type+index+'" style="display:block;">'+ridelabel+'</label>');
			$('#selectRide'+type+index).css({border:0});
			$('#selectRide'+type+index).html('<img src="/common/images/tinyselectlabel.gif" style="margin-bottom:5px;" /><input type="radio" name="sMMYselect" id="rideSelect'+type+index+'" value="'+link+'" '+selected+' />');
			$('#rideSelectLabel'+type+index).css({cursor:"pointer"});
			$('#rideSelectLabel'+type+index).click(function(){
					//$('#rideSelect'+type+index).attr('checked',true);
					setSubmit();
					$('#rideList tr').css({background:"#FFF"});
					$(this).parent().parent().css({background:"#FFC"});
				});
			$('#rideSelect'+type+index).click(function(){
					$(this).attr('checked',true);
					setSubmit();
					$('#rideList tr').css({background:"#FFF"});
					$(this).parent().parent().parent().css({background:"#FFC"});
				});
			index++;
		}
	}
}

function isRideSelected()
{
	var selected = false;
	if( document.rideSelectorForm.sMMYselect.checked )
	{
		return true;
	}
	else if ( document.rideSelectorForm.sMMYselect.length > 0 )
	{
		$( document.rideSelectorForm.sMMYselect ).each( function(i) {
			
			if (document.rideSelectorForm.sMMYselect[i].checked == true )
			{
				selected = true;
			}
		});
		return selected;
	}
	else
	{
		return false;
	}
}

function enableAddSubmit(label)
{
	$('#addSubmit').attr({disabled:false});
}

function showSubmitMessage(label)
{
	$('#selectSubmit').val("   Continue...   ");
	$('#selectSubmit').attr({disabled:1});
	$('#selectSubmitLabel').fadeIn('fast');
	$('#selectSubmitLabel').html(label);
}

function selectRideAction()
{
	if ( document.rideSelectorForm.sMMYselect.length > 0 )
	{
		$( document.rideSelectorForm.sMMYselect ).each( function(i){
			if (document.rideSelectorForm.sMMYselect[i].checked)
			{
				var rideurl = document.rideSelectorForm.sMMYselect[i].value;
				var ride = $( document.rideSelectorForm.sMMYselect[i] ).parent().parent().parent().attr('alt');
				var label = "Finding Parts for "+ride+"...";
				showSubmitMessage(label);
				selectMMY( rideurl );
			}
		});
	}
	else if ( document.rideSelectorForm.sMMYselect.checked )
	{
			var rideurl = document.rideSelectorForm.sMMYselect.value;
			var ride = $( document.rideSelectorForm.sMMYselect ).parent().parent().parent().attr('alt');
			var label = "Finding Parts for "+ride+"...";
			showSubmitMessage(label);
			selectMMY( rideurl );
	}
}
//////////////////////////////////////////////////////////////////////
// DIRT RIDE SELECTOR JS
//////////////////////////////////////////////////////////////////////

$('#selectCats').change( setMakes );
$('#selectMakes').change( setYears );
$('#selectYears').change( setModels );
$('#selectModels').change( setSubmit );
$('#addSubmit').click( submitSelectedRide );

function setMakes()
{
	
	resetSelect('selectMakes','Select a Make');
	resetSelect('selectYears','Select a Year');
	resetSelect('selectModels','Select a Model');
	setSubmit();
	
	if ( this.value !== '' )
	{
		$('#makesInd').show();
		$.getJSON(
				callbackUrl, {
					rnd: Math.random(),
					action: "getMakes",
					category: $(this).val()
					},
					function(json) {
						$('#makesInd').hide();
						$('#selectMakes').attr('disabled',false);
						$.each( json, function(i, n){
							$('#selectMakes').addOption(json[i], json[i], false);
						});
					}
			);
	}
}

/*
function setYears()
{
	resetSelect('selectYears','Select a Year');
	resetSelect('selectModels','Select a Model');
	alert( callbackUrl );
}
*/

function setYears()
{
	resetSelect('selectYears','Select a Year');
	resetSelect('selectModels','Select a Model');
	setSubmit();
	if ( this.value !== '' )
	{
		$('#yearsInd').show();
		$.getJSON(
				callbackUrl, {
					rnd: Math.random(),
					action: "getYears",
					makeName: $(this).val(),
					category: $('#selectCats').val()
					},
					function(json) {
						$('#yearsInd').hide();
						$('#selectYears').attr('disabled',false);
						$.each( json, function(i, n){ 
							$('#selectYears').addOption(json[i], json[i], false);
						});
					}
			);
	}
}

function setModels()
{
	resetSelect('selectModels','Select a Model');
	setSubmit();
	if ( $(this).val() !== '' )
	{
		$('#modelsInd').show();
		$.getJSON(
				callbackUrl, {
					rnd: Math.random(),
					action: "getModels",
					year: $(this).val(),
					category: $('#selectCats').val(),
					makeName: $('#selectMakes').val()
					},
					function(json) {
						$('#modelsInd').hide();
						$('#selectModels').attr('disabled',false);
						
						var selectHtml = '';
						var displayName = '';
						$.each( json, function(i, n){ 
							
							if ( i )
							{
								selectHtml += '<optgroup label="'+i+'" id="'+i+'">';
							}
							$.each( n, function(a, b){ 
								displayName = trunc(n[a].DisplayName,25);
								selectHtml += '<option value="'+n[a].model+'" title="'+n[a].DisplayName+'">'+displayName+'</option>';
							});
							if ( i )
							{
								selectHtml += '</optgroup>';
							}
							
							
							//$('#'+i).addOption(i, label, false, json[i]);
							
						});
						$('#selectModels').append(selectHtml);
					}
			);
	}
}

function setSubmit() {
	
	var cat 	= $('#selectCats').val();
	var make 	= $('#selectMakes').val();
	var year 	= $('#selectYears').val();
	var model = $('#selectModels').val();
	if ( cat && make && year && model )
	{
		$('#addSubmit').attr({ disabled: false });
	}
	else
	{
		$('#addSubmit').attr({ disabled: true });
	}
}

function submitSelectedRide()
{
		var selCat 		= $('#selectCats').val();
		var selMake 	= $('#selectMakes').val();
		var selModel 	= $('#selectModels').val();
		var selYear 	= $('#selectYears').val();
		
		if ( selCat && selMake && selModel && selYear )
		{
			var label = "Saving "+ selCat + " " + selMake + " " + selModel + " " + selYear + " to your rides...";
			enableAddSubmit(label);
			addRide();
		}
		else
		{
			//selectRideAction();
		}
		
		
}

function savedRidesList(json)
{
	
	$('.savedRidesWidget').empty();
	$('.savedRidesWidget').append('<h2>My Saved Rides</h2>');
	$.each( json, function( type, rides ) {
		$('.savedRidesWidget').append('<h3 id="h'+type+'">'+rideMeta.data[type]['plural']+'</h3>');
			if ( rides.length != 0 )
			{
				var n = 0;
				for( i in rides )
				{
					n++;
					if ( manage )
					{
						var delBut = '<span style="float: right;" class="deleteRide"><a href="?deletemmy='+i+'" mmy="'+i+'" title="Delete this ride">Delete This Ride</A></span>';
					}
					else
					{
						var delBut = '';
					}
					$('.savedRidesWidget').append('<p class="isRide" mmy="'+i+'" id="r'+i+'" title="'+rides[i]['label']+'">'+delBut+'<b>'+rides[i]['label']+'</b></p>');
				}
			}
			else
			{
				$('.savedRidesWidget').append('<p><i>No saved '+rideMeta.data[type]['plural']+'</i></p>');			
				
			}
	});
	$('.deleteRide a').click(
	function(){
		deleteRide( $(this).attr('mmy') );
		return false;
	}
);
}

function myRidesAlert(msg)
{
	$('#addedRideAlertBox').html(msg);
	$('#addedRideAlertBox').show();
	setTimeout("$('#alertmsg').hide('fast')", 3000);
}

function deleteRide(mmy,source) 
{
	$.getJSON(
		callbackUrl, {
			rnd: 			Math.random(),
			action: 	"deleteRide",
			mmy: 			mmy
			},
			function(json)
			{
				savedRidesList( json );
				resetMiniSelector( json );
			}
	);
}

function addRide()
{
	sMMY = $('#selectMakes').val() + ";" + $('#selectModels').val() + ";" + $('#selectYears').val();
	$.getJSON(
			callbackUrl, {
				rnd: 			Math.random(),
				action: 	"addRide",
				mmy:			sMMY
				},
				function(json) {
					savedRidesList(json);
					resetMiniSelector( json, sMMY );
					eval( "rideLabel= json." + $('#selectCats').val() + "[sMMY]['label'];" );
					myRidesAlert('Thank you! Your  <span style="color:#900;">' + rideLabel + '</span> has been saved.');
					if ( redirect ) window.location = redirect + '&sMMY='+sMMY;
				}
		);
}
