/** Set HTML class **/
$('html').addClass('java');


/** Variable defaults **/
var h = 0;
var w = 0;
var x = 0;
var y = 0;
var xy = 0;
var videoID = 0;
var thisLocation = document.location.toString();

var baseHref = (function() {
    var css_url = document.styleSheets[0].href;
    var last_slash = css_url.lastIndexOf('/static');

    return css_url.substr(0, last_slash); // http://foobar.com  (notice no trailing slash)
})();


/** Simple plugins **/
jQuery.fn.slidefadeToggle = function(s, fn){
    return (this.is(":visible"))
        ? this.slideUp(s).fadeOut(s, fn)
        : this.slideDown(s).fadeIn(s, fn);
};
jQuery.fn.fadeToggle = function(s, fn){
    return (this.is(":visible"))
        ? this.fadeOut(s, fn)
        : this.fadeIn(s, fn);
};

/** Lock forms on submit **/
$('body.simple form, body.join form').submit(function(e) {
  $('form :input').attr('readonly','readonly').fadeTo('fast',.5);
  $('form :submit').attr('disabled','disabled').fadeTo('fast',.5);
});

/** Document.location timeout handling **/
/**setInterval(function() {
    if(thisLocation !== document.location.toString()) {
        // If location changes...
        // 1. Update thisLocation
        thisLocation = document.location.toString();
        
        // 2. Pull new location
        if(thisLocation.indexOf('#')) {
            alert(thisLocation);
        } else {
            alert('nope');
        }
    }
}, 300);**/


/** Alert box toggle and hide **/
function alertToggle() {
  if(!$('body.browse, body.album').length) {
    setTimeout(function() {
      $('blockquote.alert').not('.end').fadeOut(700,function(){
        $('blockquote.alert').not('.end').remove();
      });
    },2300)
    $('blockquote.alert').not('.end').click(function() {
      $(this).fadeOut(700,function(){
        $(this).remove();
      });
    });
  }
}



/** Simple functions **/
function clearMask() {
  $('<div>')
    .attr('id','clearMask')
    .bind('click', function() {
      $('div.pop, #clearMask').remove();
    })
    .appendTo('body');
}


function favorite(originID, obj) {
    // 0. Add loading class
    $(obj).parent('li, h3').addClass('loading');
    
    // 1. Send GET request, and update video accordingly
    $.get(baseHref + '/member/favorite/' + originID, function(favorite) {
        $(obj).parent('li, h3').removeClass('loading');
        if(favorite == "1") {
            $('#v' + originID).addClass('favorite');
            $('#v' + originID).parent('div').addClass('favorite');
            $('#superpop').addClass('favorite');
				$(obj).text('Remove favorite');
        } else {
            $('#v' + originID).removeClass('favorite');
            $('#v' + originID).parent('div').removeClass('favorite');
            $('#superpop').removeClass('favorite');
            $('body.favorites #v' + originID).parent('div').fadeOut('fast');
            $('body.favorites #superpop').fadeOut('fast');
				$(obj).text('Add to favorites');
        }
    });
    
    return false;
}

function rate(obj) {
    // 0. Add loading class
    $(obj).parents('div.stem, li.rating').addClass('loading');

    // 1. Send GET request, and update video accordingly
    $.get($(obj).attr('href'), function(rating) {
        // 1.1 Remove old star classes and add new ones
        $(obj).parents('div.stem').removeClass('stars0 stars1 stars2 stars3 stars4 stars5').addClass('stars' + rating);
        $(obj).parents('div.stem').find('a:first').removeClass('stars0 stars1 stars2 stars3 stars4 stars5').addClass('stars' + rating);
        $('.selected, .selected a:first, #superpop').removeClass('stars0 stars1 stars2 stars3 stars4 stars5').addClass('stars' + rating);
        
        // 1.2 Remove rating stars now that the rating is locked in
        $('.selected li.rate div, #superpop li.rate div').html('<span>Rated!</span>');
        $(obj).parents('div.stem').find('li.rate div').html('<span>Rated!</span>');
        $(obj).parents('div.stem').find('.secondary').remove();
        $('div.selected .secondary').remove();
        
        // 1.3 Fade out menu for the user
        setTimeout(function() {
            $('#thumbs div.stem.selected').removeClass('selected');
            $('#superpop').fadeOut('fast');
        }, 700);
    });
    
    return false;
}

function playVideo(videoID) {
    document.location = baseHref + '/member/videos/' + videoID;
        
    return false;
}



/** Begin document ready **/
$(document).ready(function() {


/** Breadcrumb building **/
$('#breadcrumbs a').not($('#breadcrumbs a:last')).addClass('back');


/** Select subpop menu 
if(document.location.toString().indexOf('sort=') > 0) {
    sortby = document.location.toString().split('sort=').slice(1);
    $("li.subpop a[href*='" + sortby + "']").css('text-decoration','underline').addClass('selected');
}**/


/** Inline favourites for photos **/
if ((thisLocation.indexOf('album') > 0) && (thisLocation.indexOf('search') < 0)) {
    $('body.photos .thumbs a').each(function() {
        // 0. Pull vars
        url = $(this).attr('href');
        photoID = url.split('/').slice(-1);
        classes = $(this).attr('class');
        
        // 1. Wrap links in stem
        $(this).wrap(
            $('<div/>').addClass('stem ' + classes)
        )
        
        // 2. Append favourite link
        $(this).after(
            $('<a/>')
                .attr('href',baseHref + '/member/favorite/' + photoID)
                .fadeTo(0, .5)
                .addClass('fav')
                .html('&hearts;')
                .attr('title','Click to favorite')
                .click(function() {
                    thisFav = $(this);
                    $(thisFav).addClass('loading');
                    $.get($(thisFav).attr('href'), function(favorite) {
                        $(thisFav).removeClass('loading');
                        if(favorite == "1") {
                            $(thisFav).siblings('a').addClass('favorite');
                            $(thisFav).parent('div').addClass('favorite');
                            $(thisFav).attr('title','Click to remove favorite').fadeTo(0, 1)
                        } else {
                            $(thisFav).siblings('a').removeClass('favorite');
                            $(thisFav).parent('div').removeClass('favorite');
                            $(thisFav).attr('title','Click to favorite').fadeTo(0, .5)
                        }
                    });
                    
                    return false;
                })
            );
    });
    $('body.photos .thumbs a').each(function() {
		$('body.photos .thumbs a.favorite').next('a.fav').fadeTo(0,1);
	});

    // Inline lightbox for photos
    //{"id":"3000265347","scaled_photo":"test/media/scaled_photo.jpg?3000265347","original":"test/media/original?3000265347"}
    // 1. Get albumID
        albumID = document.location.toString().split('/').slice(-2, -1);
    
    // 2. Pull links
        $.ajax({
            url: baseHref + '/member/photos/album/' + albumID + '?format=js',
            dataType: 'json',
            success: function(data, status) {
                $.each(data, function(i,photo) {
                    // 1. Attach scaled photo link
                    $('#v' + photo.id).find('img').attr('alt',photo.scaled_photo);
                    
                    // 2. Attach download link, somehow
                    $('#v' + photo.id).find('img').attr('longdesc',photo.full_photo);
                })
            },
            error: function(request, type, exception) {
                // Quietly redirect user on error
                //document.location = vidURL;
                alert(type);
            }
        });
    

    $('body.photos .thumbs a').not('.fav').click(function() {
        // 0. Grab defaults            
            imgid = $(this).attr("id").substring(1); 

        // 1. Build mask
            clearMask();

        // 2. Build lightbox
          $('<div/>')
            .attr('id','photoPop')
            .addClass('pop')
            .appendTo($('body'))
            .append('<div class="fullPhoto"><a href="' + $('#v' + imgid + ' img').attr('longdesc') + '">Download High-Res</a><img src="' + $('#v' + imgid + ' img').attr('alt') + '" alt="' + imgid + '" /></div>');// <b>' + $('#v' + imgid).text() + '</b></a></div>');
        
        // 3. Previous Link
            $('<a/>')
                .text('Previous image')
                .attr('title','Previous image')
                .attr('href','#')
                .addClass('prev')
                .click(function() {
                    // 0. Current img ID
                    currImgId = $('div.fullPhoto img').attr('alt');
                    
                    // 1. No image?  Close window
                    if($('#v' + currImgId).parent('div').prev('div').length < 1) {
                        $('#clearMask').click();
                        
                        return false;
                    }
                    
                    // 2. Get previous image in list
                    imgid = $('#v' + currImgId).parent('div').prev('div').children('a').attr('href').split('/').slice(-1); // bigthumb.jpg?3000265219
                    
                    // 3. Else, relace image with new one
                    $('#photoPop div.fullPhoto').html('<a href="' + $('#v' + imgid + ' img').attr('longdesc') + '">Download High-Res</a><img src="' + $('#v' + imgid + ' img').attr('alt') + '" alt="' + imgid + '" />');
                    
                    return false;
                })
                .appendTo($('#photoPop'))
					 	.clone(true)
					 	.removeClass('prev')
						.addClass('textPrev')
						.appendTo($('#photoPop'));
        
        // 4. Next Link
            $('<a/>')
                .text('Next image')
                .attr('title','Next image')
                .attr('href','#')
                .addClass('next')
                .click(function() {
                    // 0. Current img ID
                    currImgId = $('div.fullPhoto img').attr('alt');
                    
                    // 1. No image?  Close window
                    if($('#v' + currImgId).parent('div').next('div').length < 1) {
                        $('#clearMask').click();
                        
                        return false;
                    }
                    
                    // 2. Get previous image in list
                    imgid = $('#v' + currImgId).parent('div').next('div').children('a').attr('href').split('/').slice(-1); // bigthumb.jpg?3000265219
                    
                    // 3. Else, relace image with new one
                    $('#photoPop div.fullPhoto').html('<a href="' + $('#v' + imgid + ' img').attr('longdesc') + '">Download High-Res</a><img src="' + $('#v' + imgid + ' img').attr('alt') + '" alt="' + imgid + '" />');
                    
                    return false;
                })
                .appendTo($('#photoPop'))
					 	.clone(true)
					 	.removeClass('next')
						.addClass('textNext')
						.appendTo($('#photoPop'));
        
        // 5. Close Link
            $('<a/>')
                .text('Close')
                .attr('title','Click to close')
                .attr('href','#')
                .addClass('close')
                .click(function() {
                    $('#clearMask').click();
                    return false;
                })
                .appendTo($('#photoPop'));
        
        return false;
    })

}


/** Budding menu for videos **/
//$('body.search div.thumbs.videos, body.favorites div.thumbs.videos').attr('id','thumbs');
$('body.videos #thumbs a, body.search #thumbs a, body.favoritesasd div.thumbs.videos a, body.girl #thumbs.videos a').each(function() {
	if($(this).parent('div.stem').length < 1) {
		$(this).wrap('<div class="stem"></div>');
	}
																																										  
    // 0. Pull vars
    url = $(this).attr('href');
    videoID = url.split('/').slice(-2, -1); //member/videos/3000168093/title
    classes = $(this).attr('class');
    
    // 1. Wrap links in stem
    $(this).parent('div.stem').addClass(classes);
	 
	 // 1.2 Exclusive banner
	 if($(this).is('.exclusive')) {
		 $(this).parent('div.stem').append('<span class="exclusive">EXCLUSIVE!!!</span>');
	 }
	 
    $(this).mouseover(function() {
        if(!$(this).parent('div.stem').hasClass('selected')) {
            $('#thumbs div.stem.selected').removeClass('selected');
            //$('#thumbs ul.flowermenu').fadeOut('fast');
            $('#superpop').fadeOut('fast');
            return false;
        }
    });
    
    // 2. Append bud
    $(this).after(
        $('<a/>')
            .attr('href','#')
            .addClass('bud')
            .text('+')
            .click(function() {
                /**
                // 0. Already selected?  Close it out.
                    if($(this).parent('div.stem').hasClass('selected')) {
                        $('#thumbs div.stem.selected').removeClass('selected');
                        $('#thumbs ul.flowermenu').hide();
                        return false;
                    }
                // 1. Clear out all other buds
                    $('#thumbs div.stem.selected').removeClass('selected');
                    $('#thumbs ul.flowermenu').hide();
                
                // 2. Select this video
                    $(this).parent('div.stem').addClass('selected');
                    $(this).siblings('ul').slice(0,1).fadeIn('fast');
                **/
                
                // 0. Already selected? Close it out.
                    stem = $(this).parent('div.stem');
                    if(stem.hasClass('selected')) {
                        $('#thumbs div.stem.selected').removeClass('selected');
                        $('#superpop').remove();
                        return false;
                    }
                    
                // 1. Clear out all other buds
                    $('#thumbs div.stem.selected').removeClass('selected');
                    $('#superpop').remove();
                
                // 2. Select this video (we have to clone and append to the body because IE doesn't respect z-index ordering)
                    $(this).parent('div.stem').addClass('selected');
                    var thisbud = $(this).siblings('ul').slice(0,1);
                    var offset = $(this).offset();
                    
                    $('<div/>')
                        .attr('id','superpop')
                        .addClass(stem.attr('class'))
                        .css({
                            position: 'absolute',
                            top: offset.top + 'px',
                            left: offset.left + 'px'
                        })
                        .append($(thisbud).clone(true).fadeIn('fast'))
                        .appendTo($('body'));
					  
					  // 3. Populate download links
							vidURL = $('div.selected a:first').attr('href');
									
							$.ajax({
								 url: vidURL,
								 dataType: 'json',
								 success: function(data, status) {
									 $('#superpop div.formats').html('<a href="' + data.wmv + '" title="wmv">WMV</a>, <a href="' + data.h264_720p + '" title="h264_720p">H.264</a>, <a href="' + data.mp4 + '" title="mp4">PSP/iPod</a>');
								 }
							});
					  	                       
                
                return false;
            })
    );
    
    // 3. Grow flower
    $(this).after(
        $('<ul/>')
            .addClass('flowermenu')
            .hide()
            .html('<li class="favorite"><a href="' + baseHref + '/member/favorite/' + videoID + '" onClick="favorite(' + videoID + ', $(this)); return false;">Add to Favorites</a></li><li class="play"><a href="' + url + '" onClick="playVideo(' + videoID + '); return false;">Play Video</a></li><li class="rate"><a href="#" onClick="return false;">Rate Video</a><div class="stars"><a href="' + baseHref + '/member/rate/' + videoID + '/0" class="star0">X</a><a href="' + baseHref + '/member/rate/' + videoID + '/5" class="star1">&#9733;</a><a href="' + baseHref + '/member/rate/' + videoID + '/4" class="star2">&#9733;</a><a href="' + baseHref + '/member/rate/' + videoID + '/3" class="star3">&#9733;</a><a href="' + baseHref + '/member/rate/' + videoID + '/2" class="star4">&#9733;</a><a href="' + baseHref + '/member/rate/' + videoID + '/1" class="star5">&#9733;</a></div></li><li class="download"><a href="#" onClick="return false;">Download</a><div class="formats"><a href="#" title="wmv">WMV</a>, <a href="#" title="h264_720p">H.264</a>, <a href="#" title="mp4">PSP/iPod</a></div></li>')
    );
    
    // 4. Attach petal events
        // 4.1 Fade in/out download petal
        $(this).siblings('ul.flowermenu').find('li.download').hover(
          function () {
            $(this).find('div.formats').fadeIn('fast');
          }, 
          function () {
            $(this).find('div.formats').fadeOut('fast');
          }
        );
        
        // 4.2 Fade in/out star rating petal
        $(this).siblings('ul.flowermenu').find('li.rate').hover(
          function () {
            $(this).find('div.stars').fadeIn('fast');
          }, 
          function () {
            $(this).find('div.stars').fadeOut('fast');
          }
        );
        
        // 4.3 Append another set of rating stars
        $(this).after('<div class="stars secondary"><a href="' + baseHref + '/member/rate/' + videoID + '/0" class="star0">X</a><a href="' + baseHref + '/member/rate/' + videoID + '/5" class="star1">&#9733;</a><a href="' + baseHref + '/member/rate/' + videoID + '/4" class="star2">&#9733;</a><a href="' + baseHref + '/member/rate/' + videoID + '/3" class="star3">&#9733;</a><a href="' + baseHref + '/member/rate/' + videoID + '/2" class="star4">&#9733;</a><a href="' + baseHref + '/member/rate/' + videoID + '/1" class="star5">&#9733;</a></div>');
        
        // 4.4 Attach rating event
        $(this).parent('div').find('div.stars a').click(function() {
            rate($(this));
            
            return false;
        });
        
        // 4.5 Attach download event
        /**$(this).siblings('ul.flowermenu').find('li.download a').click(function() {
            // 0. Get URL and requested type
            vidURL = $('div.selected a:first').attr('href');
            vidFormat = $(this).attr('title'); // ugly hack VS assigning a class to each <a/>
            
            // 1. Query for JSON
            $.ajax({
                url: vidURL,
                dataType: 'json',
                success: function(data, status) {
                    if(vidFormat == 'wmv') {
                        document.location = data.wmv;                 
                    } else if(vidFormat == 'mp4') {
                        document.location = data.mp4;
                    } else {
                        document.location = data.h264_720p;
                    }
                },
                error: function(request, type, exception) {
                    // Quietly redirect user on error
                    document.location = vidURL;
                }
            });
            
            // 2. Redirect to actual video URL
            
            return false;
        });**/
        
    
    // 5. Also append Play hover
        $(this).append('<span class="play" title="Click to play">Click to play</span>');

});


$('#videomenu').each(function() {
    videoID = document.location.toString().split('/').slice(-2, -1); //member/videos/3000168093

    /** Attach favorite event to video page **/
    $('li.favorite a', this)
        .click(function() {
            thisFav = $(this);
            $(thisFav).addClass('loading');
            $.get(baseHref + '/member/favorite/' + videoID, function(favorite) {
                $(thisFav).removeClass('loading');
                if(favorite == "1") {
                    $(thisFav).siblings('a').addClass('favorite');
                    $(thisFav).parent('div').addClass('favorite');
                    $(thisFav).attr('title','Click to remove favorite').text('Remove favorite');
                } else {
                    $(thisFav).siblings('a').removeClass('favorite');
                    $(thisFav).parent('div').removeClass('favorite');
                    $(thisFav).attr('title','Click to favorite').text('Add to favorites');
                }
            })
        });

    /** Video page rating stars **/
    if($('li.rating.stars1, li.rating.stars2, li.rating.stars3, li.rating.stars4, li.rating.stars5').length < 1) {
		 $('li.rating').append('<div class="stars secondary"><a href="' + baseHref + '/member/rate/' + videoID + '/0" class="star0">X</a><a href="' + baseHref + '/member/rate/' + videoID + '/5" class="star1">&#9733;</a><a href="' + baseHref + '/member/rate/' + videoID + '/4" class="star2">&#9733;</a><a href="' + baseHref + '/member/rate/' + videoID + '/3" class="star3">&#9733;</a><a href="' + baseHref + '/member/rate/' + videoID + '/2" class="star4">&#9733;</a><a href="' + baseHref + '/member/rate/' + videoID + '/1" class="star5">&#9733;</a></div>');
	 }

// 4.4 Attach rating event
    $('li.rating a').click(function() {
        rate($(this));
		  
		  $('li.rating').addClass('stars' + ($(this).nextAll('a').length+1));
		  
		  $('div.stars.secondary').remove();

        return false;
    });

});



/** Various IE fixes **/
$('#submit_search').val('');


$('#videomenu li.montage a').click(function() {
	$('#montage').slidefadeToggle('fast');
	return false;
});


    $('#links a').click(function() {
        // 0. Grab defaults            
            imgid = $(this).attr("id").substring(1); 

        // 1. Build mask
            clearMask();

        // 2. Build lightbox
          $('<div/>')
            .attr('id','photoPop')
            .addClass('pop')
            .appendTo($('body'))
            .append('<div class="fullPhoto"><a href="' + $('#v' + imgid).attr('href') + '">Download</a><img src="' + $('#v' + imgid).attr('href') + '" alt="' + imgid + '" /></div>');// <b>' + $('#v' + imgid).text() + '</b></a></div>');
        
        // 3. Previous Link
            $('<a/>')
                .text('Previous image')
                .attr('title','Previous image')
                .attr('href','#')
                .addClass('prev')
                .click(function() {
                    // 0. Current img ID
                    currImgId = $('div.fullPhoto img').attr('alt');
                    
                    // 1. No image?  Close window
                    if($('#v' + currImgId).prev('a').length < 1) {
                        $('#clearMask').click();
                        
                        return false;
                    }
                    
                    // 2. Get previous image in list
                    imgid = $('#v' + currImgId).prev('a').attr("id").substring(1); 
                    
                    // 3. Else, relace image with new one
                    $('#photoPop div.fullPhoto').html('<a href="' + $('#v' + imgid).attr('href') + '">Download</a><img src="' + $('#v' + imgid).attr('href') + '" alt="' + imgid + '" />');
                    
                    return false;
                })
                .appendTo($('#photoPop'))
					 	.clone(true)
					 	.removeClass('prev')
						.addClass('textPrev')
						.appendTo($('#photoPop'));
        
        // 4. Next Link
            $('<a/>')
                .text('Next image')
                .attr('title','Next image')
                .attr('href','#')
                .addClass('next')
                .click(function() {
                    // 0. Current img ID
                    currImgId = $('div.fullPhoto img').attr('alt');
                    
                    // 1. No image?  Close window
                    if($('#v' + currImgId).next('a').length < 1) {
                        $('#clearMask').click();
                        
                        return false;
                    }
                    
                    // 2. Get previous image in list
                    imgid = $('#v' + currImgId).next('a').attr("id").substring(1); 
                    
                    // 3. Else, relace image with new one
                    $('#photoPop div.fullPhoto').html('<a href="' + $('#v' + imgid).attr('href') + '">Download</a><img src="' + $('#v' + imgid).attr('href') + '" alt="' + imgid + '" />');
                    
                    return false;
                })
                .appendTo($('#photoPop'))
					 	.clone(true)
					 	.removeClass('next')
						.addClass('textNext')
						.appendTo($('#photoPop'));
        
        // 5. Close Link
            $('<a/>')
                .text('Close')
                .attr('title','Click to close')
                .attr('href','#')
                .addClass('close')
                .click(function() {
                    $('#clearMask').click();
                    return false;
                })
                .appendTo($('#photoPop'));
        
        return false;
    })
	 
	 
	 $('body.model .minibio h3 a').click(function() {
		favorite($(this).attr('title'), $(this));
		return false;
	});
	 
/** body.memberFrontPage **/
$('.sec.topvid .dvd.covers a').click(function() {
    if($(this).is('.selected')) {
        document.location = $(this).attr('href');
    }
    
	$('.sec.topvid .dvd.covers a.selected').removeClass('selected');
	$(this).addClass('selected');
	
	var vidNum = $(this).prevAll('a').length;
	$('#flashCarosel tr:eq(' + vidNum + ')')
		.show()
		.siblings('tr').hide();
    
    return false;
});
$('.sec.topvid .dvd.covers a:first').click();
$('body.welcome .fullbio ul').append('<li class="clear"><br class="clear" /></li>');


$('body.photos .thumbs a.exclusive').append('<span class="exclusive">EXCLUSIVE!!!</span>');


/** Account page **/
/* Dynamic tabs */
if($('#lovelyTabs a.active').length < 1) {
  $('#lovelyTabs a').slice(0,1).addClass('active');
}
$('#content .tabbed').slice(1).hide();

$('#lovelyTabs a').click(function() {
  var target = $(this).attr('href');
  $(this).addClass('active')
  $('#lovelyTabs a.active').not($(this)).removeClass('active');
  $(target)
    .show()
    .siblings('.tabbed').hide();
});

var thisPage = window.document.location.toString();
if($('#lovelyTabs').length > 0 && thisPage.indexOf('#') > 0) {
  var target = $('#'+thisPage.split('#')[1]);
  if(target.size() > 0) {
    $('.tabbed').hide();
    target.show();
    // Show right tab
    $('#lovelyTabs li a').removeClass('active');
    var tabtarget = '#' + thisPage.split('#')[1] + '';
    $('#lovelyTabs li a[href=' + tabtarget + ']').addClass('active');
  }
}



$('select#form_country').change(function() {
  var country = $(this).val();
  if(country == 'us') {
    $('#form_state').parent().parent().show();
    $('#form_province').parent().parent().hide();
  } else {
    $('#form_state').parent().parent().hide();
    $('#form_province').parent().parent().show();
  }
});
$('select#form_country').change();

// hide alerts on click
if($('blockquote.alert').length) {
  alertToggle();
}

/** body.accountCheck toggler **/
$('body.accountCheck #content legend label').click(function() {
  $(this).parents('fieldset')
    .addClass('active')
    .siblings('fieldset').removeClass('active').find('div.options').slideUp('fast');
  $(this).parents('fieldset').find('div.options').slideDown('fast');
});

if(!$('body.accountCheck #content form input:checked').length) {
    $('body.accountCheck #content fieldset')
      .slice(0,1)
      .addClass('active');
    $('body.accountCheck #content fieldset div.options').slice(1).hide();

    $('body.accountCheck #content form input:radio').slice(0,1).attr('checked',true);
} else {
    $('body.accountCheck #content form input:checked').parents('fieldset').find('legend label').click();
}

$('#form_cvv2').next('a').click(function() {
  var target = $(this).attr('href');
  $(target).slideToggle('fast');
  return false;
});

/** Form validation **/
var errors = 0;
$('body.accountCheck #content form').submit(function(e) {
  errors = 0;
  // 1. Check obvious errors
    if($('#content input.error:visible').length) {
      e.preventDefault;
      errors = 1;
    }
    
  // 2. Check simple fields
  $('#form_name, #form_number, #form_cvv2, #form_address, #form_city, #form_zip, #recaptcha_response_field, #form_state:visible, #form_province:visible').each(function() {
    if($(this).val().length < 1) {
      ++errors;
      e.preventDefault;
      $(this).parent().addClass('error');
    } else {
      $(this).parent().removeClass('error').find('p.error').remove();
    }
  });
  
  // 3. Check email
  $('#form_email').each(function() {
    var email = $(this).val();
    if(email.length < 3) {
      $('#form_email').parent().find('p.error').remove();
      $('#form_email').parent().addClass('error').append('<p class="error">You must enter a valid email.</p>');
    } else if(email.indexOf('@') < 1) {
      $('#form_email').parent().find('p.error').remove();
      $('#form_email').parent().addClass('error').append('<p class="error">This is not a valid email.</p>');
    } else {
      $('#form_email').parent().removeClass('error').find('p.error').remove();
    }
  });
  
  // 4. Alert on errors
  if(errors) {
    alert('There were some errors in the form.  Please make sure you\'ve entered everything correctly.');
  }
  
  // 4. No errors?  Post form
  if(!errors) {
    return true;
  } else {
    $('#content :input').removeAttr('disabled').removeAttr('readonly').fadeTo('fast',1);
    return false;
  }
});

$('body.accountCheck').find('#form_email, #form_name, #form_number, #form_cvv2, #form_address, #form_city, #form_zip, #recaptcha_response_field, #form_expirationMonth, select[name=expirationYear], #form_state:visible, #form_province:visible').focus(function() {
  if($(this).parent().is('.error')) {
    $(this).one('blur',function() {
      if($(this).val().length < 1) {
        ++errors;
        e.preventDefault;
        $(this).parent().addClass('error');
      } else {
        $(this).parent().removeClass('error').find('p.error').remove();
      }
    });
  }
});


$('body.accountCheck #form_username').focus(function() {
  $(this).one('blur',function() {
    $('#form_username').parent().removeClass('error').find('p.error').remove();
    var username = $(this).val();
    $('#form_username').parent().find('p.error').remove();
    if(username.length < 2) {
        $('#form_username').parent().addClass('error').append('<p class="error">That usename is too short.</p>');
    } else {
        $('#form_username').parent().removeClass('error');
        $.getJSON(baseHref + '/session/checkUsername?username=' + username, function(data) {
          $('#form_username').parent().removeClass('error').find('p.error').remove();
          if(data.length) {
            $('#form_username').parent().addClass('error').append('<p class="error">That usename is already in use. How about one of these:</p>');
            var pp = $('#form_username').parent().find('p.error');
            $.each(data, function(i,name){
              $('<a/>')
                .text(name)
                .click(function() {
                  $('#form_username').val($(this).text());
                  $('#form_username').parent().removeClass('error').find('p.error').remove();
                })
                .appendTo($(pp));
            });
          } else {
            $('#form_username').parent().removeClass('error').find('p.error').remove();
          }
        });
    }
  });
});

$('body.accountCheck #form_passwordAgain').focus(function() {
  $(this).one('blur',function() {
    if($(this).val() !== $('#form_password').val()) {
      $('#form_password').parent().find('p.error').remove();
      $('#form_password').parent().addClass('error').append('<p class="error">Your passwords don\'t match!</p>');
      $('#form_passwordAgain').parent().addClass('error');
    } else if($(this).val().length < 2) {
      $('#form_password').parent().find('p.error').remove();
      $('#form_password').parent().addClass('error').append('<p class="error">Your password is too short!</p>');
      $('#form_passwordAgain').parent().addClass('error');
    } else {
      $('#form_password, #form_passwordAgain').parent().removeClass('error').find('p.error').remove();
    }
  });
});

/** End Document Ready **/
});
