// ==============
// = prototypes =
// ==============
// ================
// = start global =
// ================
var isiPad = navigator.userAgent.match(/iPad/i) != null;
var featureDelay = 4500;
var featureInterval = null;
var slideOverride = null;
var slideDir = 'left'
var hasMoved = false;
var slideTime = 750;
var featureTimeout = null;
var isIe = false;
var nonFlashIntro = false;

if (top!= self) top.location.replace(self.location.href);

$(document).ready(function() {

	if ($('body').hasClass('ie')) {
		isIe = true;
	}

	$('a[rel=external]').click(function() {
		$(this).attr('target', '_blank');
	});

	$('#topNav .dropdownLink').mouseover(function() {

		var tab = $(this).attr('href').split('#')[1];
		if (isIe) {
			$('#' + tab).show().siblings().hide();
		} else {
			$('#' + tab).fadeIn(300).siblings().fadeOut(300);
		}
		return false;

	});

	$('.topDropdown').mouseleave(function() {
		if ($('.calendarPopup').is(':visible')) {
			return false;
		}
		if (isIe) {
			$(this).hide();
		} else {
			$(this).fadeOut(300);
		}
	});
	
	

	// init per-page functionality as needed
	$('*[init]').each(function() {

		var init = $(this).attr('init');

		try {
			eval('init_' + init + '();');
		} catch(e) {}

	});

	$('*[ready]').each(function() {
		var init = $(this).attr('ready');
		eval('ready_' + init + '();');
	});

	if (bdayFormatted = readCookie('fb_birthday')) {

		$('.birthdayReplace').html('Your Birthday: <strong>' + bdayFormatted + "</strong>");

	}

	init_join_form();

	$('.slideLeft').live('click', function() {
		if (isIe) {
			document.location = $(this).attr('href');
			return false;
		} else {
			slideDir = 'left';
			$.address.value($(this).attr('href'));
			return false;
		}
	});

	$('.slideRight').live('click', function() {
		if (isIe) {
			document.location = $(this).attr('href');
			return false;
		} else {
			slideDir = 'right';
			$.address.value($(this).attr('href'));
			return false;
		}
	});

	$('.moreBirthdays input').calendar();
	$('.moreBirthdays .date .icon').click(function() {
		$('.moreBirthdays input').focus();
	});

	$('.moreBirthdaysBox').css({
		cursor: 'pointer'
	}).click(function() {
		var theLink = $('a', $(this)).attr('href');
		if (theLink) {
			document.location = theLink;
		}
	});

	if ($('body').hasClass('ie6')) {

		var errorBox = '<div id="iewarning" style="position: absolute; border: 1px solid rgb(204, 204, 204); padding: 20px; background: rgb(255, 255, 255) none repeat scroll 0% 0%; width: 600px; height: 260px; position: absolute; top: 100px; left: 217.5px; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous; list-style-type: none; color: rgb(79, 79, 79); font-size: 12px" id=_d><a href="javascript:closeiewarning();" style="border: 1px solid rgb(204, 204, 204); width: 10px; height: 10px; position: absolute; top: 5px; right: 5px; display: block">X</a><h1 style="display: block; font-size: 1.3em; margin-bottom: 0.5em; color: rgb(51, 51, 51); font-family: Helvetica,Arial,sans-serif; font-weight: bold" id=_h>Did you know that your Internet Explorer is out of date!</h1><p style="margin-bottom: 1em" id=_p1>To get the best possible experience using our website we recommend that you upgrade to a newer version or other web browser. A list of the most popular web browsers can be found below.</p><p style="margin-bottom: 1em" id=_p2>Just click on the icons to get to the download page</p><ul style="padding: 0px 0px 0px 10px; list-style-image: none; list-style-position: outside; list-style-type: none" id=_ul><li style="margin: 0pt 10px 10px 0pt; width:110px;float:left;background: transparent none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous; cursor: pointer; width: 120px; height: 122px" id=_li1><div style="background: transparent url(/images/browser_ie.gif) no-repeat scroll left top; width: 100px; height: 100px; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous" id=_ico1></div><div style="margin: 1px auto; color: rgb(128, 128, 128); font-size: 0.8em; height: 18px; line-height: 17px; width: 118px; text-align: center" id=_lit1>Internet Explorer 7+</div></li><li style="margin: 0pt 10px 10px 0pt;  width:110px;float:left;background: transparent none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous; cursor: pointer; width: 120px; height: 122px" id=_li2><div style="margin: 1px auto; background: transparent url(/images/browser_firefox.gif) no-repeat scroll left top; width: 100px; height: 100px; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous" id=_ico2></div><div style="margin: 1px auto; color: rgb(128, 128, 128); font-size: 0.8em; height: 18px; line-height: 17px; width: 118px; text-align: center" id=_lit2>Firefox 3+</div></li><li style="margin: 0pt 10px 10px 0pt; width:110px;float:left; background: transparent none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous; cursor: pointer; width: 120px; height: 122px" id=_li3><div style="margin: 1px auto; background: transparent url(/images/browser_safari.gif) no-repeat scroll left top; width: 100px; height: 100px; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous" id=_ico3></div><div style="margin: 1px auto; color: rgb(128, 128, 128); font-size: 0.8em; height: 18px; line-height: 17px; width: 118px; text-align: center" id=_lit3>Safari 3+</div></li><li style="margin: 0pt 10px 10px 0pt; width:110px;float:left; background: transparent none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous; cursor: pointer; width: 120px; height: 122px" id=_li4><div style="margin: 1px auto; background: transparent url(/images/browser_chrome.gif) no-repeat scroll left top; width: 100px; height: 100px; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous" id=_ico4></div><div style="margin: 1px auto; color: rgb(128, 128, 128); font-size: 0.8em; height: 18px; line-height: 17px; width: 118px; text-align: center" id=_lit4>Chrome 2.0+</div></li></ul></div>';

		$('body').append(errorBox);

		//Get the window height and width
		var winH = $(window).height();
		var winW = $(window).width();

		$('#_li1').click(function() {
			document.location = "http://www.microsoft.com/windows/internet-explorer"
		});
		$('#_li2').click(function() {
			document.location = "http://www.getfirefox.com"
		});
		$('#_li3').click(function() {
			document.location = "http://www.apple.com/safari"
		});
		$('#_li4').click(function() {
			document.location = "http://www.google.com/chrome"
		});

		//Set the popup window to center
		$('#iewarning').css('top', winH / 2 - $('#iewarning').height() / 2);
		$('#iewarning').css('left', winW / 2 - $('#iewarning').width() / 2);

	}

});

var closeiewarning = function() {
	$('#iewarning').remove();
}

var init_join_form = function() {
	$('input[default], textarea').focus(function() {
		if ($(this).val() == $(this).attr('default')) {
			$(this).val('');
			$(this).removeClass('default');
		}
	}).blur(function() {
		if ($(this).val() == '') {
			$(this).val($(this).attr('default'));
			$(this).addClass('default');
		}
	}).each(function() {
		if ($(this).val() == '' || $(this).val() == $(this).attr('default')) {
			$(this).val($(this).attr('default'));
			$(this).addClass('default');
		}
	});

	$('.formJoin .birthday').calendar({
		onClose: function() {
			$('.formJoin .birthday').removeClass('default');
		}
	});

	$('.formJoin .date input, .formJoin .date img').click(function() {
		$('.formJoin .birthday').focus();
	}).keydown(function() {
		return false;
	});

	$('form[name=frmJoin]').submit(function(e) {
		
		$('input', $(this)).removeClass('formFieldError').keydown(function() {
			$(this).removeClass('formFieldError')
		}).change(function() {
			$(this).removeClass('formFieldError')
		});
		$('.formError', $(this)).text('').hide();

		var errors = false;

		if ($('.fname', $(this)).val().length < 2 || $('.fname', $(this)).val() == $('.fname', $(this)).attr('default')) {
			errors = true;
			$('.fname', $(this)).addClass('formFieldError');
		}

		if ($('.lname', $(this)).val().length < 2 || $('.lname', $(this)).val() == $('.lname', $(this)).attr('default')) {
			errors = true;
			$('.lname', $(this)).addClass('formFieldError');
		}

		var email = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;

		if ($('.email', $(this)).val().length < 2 || !$('.email', $(this)).val().match(email)) {
			$('.email', $(this)).addClass('formFieldError');
			errors = true;
		}
		
		//variations: Oct 10, October 10, 10/10, 10.10
		//10/10
		var date_1 = /^((([0]{1}[1-9])|([1]{1}[0-2])){1})((\/){1})((([0-3]{1})[0-9]){1})((\/(([0-9]{2})|([1-2]{1})([0-9]{3})))?)$/;
		//10.10
		var date_2 = /^((([0]{1}[1-9])|([1]{1}[0-2])){1})((\.){1})((([0-3]{1})[0-9]){1})((\.(([0-9]{2})|([1-2]{1})([0-9]{3})))?)$/;
		//October 10
		var months_long = ["January", "February", "March", "April", "May", "June", "July", "August","September", "October", "November", "December"];
		var date_3 = new RegExp("^("+months_long.join("|")+") (([1-9]{1}|([0]{1}[1-9])|([1-2]{1}[0-9])|([3]{1}[0-1])){1}( (([0-9]{2})|([1-2]{1})([0-9]{3})))?)$");
		//Oct 10
		var months_short = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug","Sep", "Oct", "Nov", "Dec"];
		var date_4 = new RegExp("^("+months_short.join("|")+") (([1-9]{1}|([0]{1}[1-9])|([1-2]{1}[0-9])|([3]{1}[0-1])){1}( (([0-9]{2})|([1-2]{1})([0-9]{3})))?)$");
		
		var dateMatch = false;
		
		if(!!$('.birthday', $(this)).val().match(date_1))
		{
			dateMatch |= true;
		}
		
		if(!!$('.birthday', $(this)).val().match(date_2))
		{
			dateMatch |= true;
		}
		
		if(!!$('.birthday', $(this)).val().match(date_3))
		{
			dateMatch |= true;
		}
		
		if(!!$('.birthday', $(this)).val().match(date_4))
		{
			dateMatch |= true;
		}		
		
		if (!dateMatch || $('.birthday', $(this)).val() == $('.birthday', $(this)).attr('default') ) {
			$('.birthday', $(this)).addClass('formFieldError');
			errors = true;
		}

		if (!errors) {
			$.ajax({
				data: $(this).serialize(),
				url: $(this).attr("action"),
				type: $(this).attr("method"),
				error: function() {alert('error submitting')},
				success: function(r) {
					if (r == "refresh") {
						$('.boxForm').fadeOut("fast", function() {
							$('.boxThankYou').fadeIn("fast");
						});
					} else {
						$('.join').fadeOut("fast", function() {
							if(peel_unwrap)
							{
								peel_unwrap();
							}
							$('.join').hide();
							$('#topNav a[rel="popJoin"]').next().hide();
							$('#topNav a[rel="popJoin"]').hide();
						});
					}
				}
			});
		}
		return false;
	});

	$('textarea[maxlength], input[maxlength]').keyup(function() {
		var max = parseInt($(this).attr('maxlength'));
		if ($(this).val().length > max) {
			$(this).val($(this).val().substr(0, $(this).attr('maxlength')));
		}
	});
}

var fbsuccess = function() {
	FB.getLoginStatus(function(response) {

		if (response.session) {

			$('.fbLogin').html("<i>Facebook Features Coming Soon");

			FB.api('/me', function(response) {

				var bday = response.birthday.split('/');
				var bdayFormatted = response.birthday; //$.datepicker.formatDate('MM d', new Date(bday[2], bday[0] - 1, bday[1]));
				createCookie('fb_birthday', bdayFormatted, 1);

				$('.birthdayReplace').html('Your Birthday: <strong>' + bdayFormatted + "</strong>");

			});

			FB.api({
				method: 'fql.query',
				query: 'SELECT uid, name, birthday_date FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = ' + response.session.uid + ')'
			},
			function(response) {
				var bdays = new Array();

				for (var i = 0; i < response.length; i++) {
					if (response[i].birthday_date) {
						var bday = response[i].birthday_date.split('/');
						response[i].birthday_date_sortable = ''; //$.datepicker.formatDate('mm-dd', new Date(bday[2], bday[0] - 1, bday[1]));
						response[i].birthday_date_display = ''; //$.datepicker.formatDate('MM d', new Date(bday[2], bday[0] - 1, bday[1]));
						bdays.push(response[i]);
					}
				}

			});

		}

	});
}

var slideRight = function(url) {
	slide(url, 1);
}

var slideLeft = function(url) {
	slide(url, -1);
}

var slide = function(url, mult) {

	if (slideOverride) {
		if (slideOverride == 'right') {
			mult = 1;
		} else if (slideOverride == 'left') {
			mult = -1;
		}
	}
	slideOverride = null;

	if (!mult) mult = 1;

	var offset = $('.mainContent:first').position();
	if (offset.left == 0) {
		offset = $('.mainContent:first').offset();
	}

	$('#container').append('<div class="wrapper" id="movingContentNew"></div>');
	$('#movingContentNew').css({
		position: 'absolute',
		left: -2000 * mult
	});

	$('#movingContentNew').load(url, function(response, status, xhr) {

		if (status == "error") {
			return false;
		}

		try {
			$('#movingContentNew *[init]').each(function() {
				var init = $(this).attr('init');
				eval('init_' + init + '(true);');
			});
		} catch(e) {}

		$('#container').animate({
			height: $('#movingContentNew').outerHeight()
		});

		$('#innerContent').css({
			position: 'absolute',
			left: offset.left
		});

		$('#movingContentNew').animate({
			left: offset.left
		},
		slideTime, 'swing');

		$('#innerContent').animate({
			left: 2000 * mult
		},
		slideTime, 'swing', function() {
			$('#innerContent').remove();
			$('#movingContentNew').attr('id', 'innerContent').css({
				left: 0,
				top: 0,
				position: 'relative'
			});

			try {
				$('#innerContent *[ready]').each(function() {
					var init = $(this).attr('ready');
					eval('ready_' + init + '();');
				});
			} catch(e) {}

			$('#container').css('height', 'auto');

			if ($('.mainContent').attr('title')) {
				$.address.title($('.mainContent').attr('title'));
			}

		});
	});

}



function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	} else var expires = "";
	document.cookie = name + "=" + value + expires + "; path=/";
}



function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}



function eraseCookie(name) {
	createCookie(name, "", -1);
}

// ==============
// = end global =
// ==============
// ========================
// = start gallery detail =
// ========================
var activeSong = "";
var init_gallery_detail = function(secondary) {

	var cbox = "";

	if (secondary) {
		cbox = "#movingContentNew ";
	}

	$(cbox + '.showcase .art li').hide();
	$(cbox + '.showcase .art li:first').show();

	buildShowcaseNavArt();

	$('.toggleBox ul').slideUp(1).fadeOut(1);

	$('.toggleBox h2').click(function() {
		$(this).toggleClass('open');
		$('ul', $(this).parent()).animate({
			"height": "toggle",
			"opacity": "toggle"
		},
		250);
	});
	
	$(cbox + '.toggleBox.open h2').each(function() {
		$(this).toggleClass('open');
		$('ul', $(this).parent()).animate({
			"height": "toggle",
			"opacity": "toggle"
		},
		1);
	});

	$('.zoomedArt').css({
		opacity: 0,
		display: 'block',
		height: 0,
		overflow: 'hidden'
	});

	$('.zoomedArt').click(function() {
		$('.zoomedArt').animate({
			opacity: 0,
			height: 0
		},
		500, 'easeOutQuad');
		return false;
	});

	$('.showcaseNavZoom').click(function() {
		$('.zoomedArt').css({
			opacity: -0.5
		});
		$('.zoomedArt').animate({
			opacity: 1,
			height: $('.zoomedArt img').height()
		},
		500, 'easeInQuad');
		return false;
	});

	$('.productList .preview').click(function() {
		$('.showcaseNavPage[href=#' + $(this).attr('href').split('#')[1] + ']').click();
		return false;
	});

	$('.showWallpaper').click(function() {
		$('.wallpaper').slideToggle();
		return false;
	});

	$('.zoomedVideo .unzoom').click(function() {
		$('video').each(function() {
			try {
				$(this)[0].pause();
			} catch(e) {}
		});
		$('object, embed').each(function() {
			try {
				$(this)[0].toggle();
			} catch(e) {}
		});
		$(this).parent().slideUp('fast');
		return false;
	});

	$('.fullVideo').click(function() {
	  try {
  		$('video').each(function() {
  			$(this)[0].currentTime = 0;
  			$(this)[0].pause();
  			$(this).closest('.videoPlayer').find('.playPause').removeClass('pause').addClass('play');
  		});
  		$('object, embed').each(function() {
  			try {
  				$(this)[0].toggle();
  			} catch(e) {}
  		});
	  } catch(e) {
	    
	  }
		$('.zoomedVideo').slideUp('fast');
		$('.zoomedVideo[rel=' + $(this).attr('rel') + ']').slideDown('fast', function() {

		});

		return false;
	});

	$('.toggleArea .toggle').click(function() {
		$(this).parent().find('.content').css({
			width: 380
		}).slideToggle();
		$(this).toggleClass('open');
	});

	// Disabled real-time inventory checkin since the feed isn't listing availability anymore
	//insertQty();
	
	// Download music dialog
	$(".downloadMusic2").fancybox({
		'titlePosition'		: 'inside',
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'overlayColor'		: '#000',
		'overlayOpacity'	: 0.35,
		'titleShow'			: false
	});
	
	$(".downloadMusic").click(function() {
		activeSong = $(this).attr("data-music");
		
		$.ajax({
			url: "/download/allow/" + activeSong,
			success: function(response) {
				if(response == 1) {
					document.location = "/download/music/" + activeSong;
					$(".available").show();
					$(".unavailable").hide();
				} else {
					$(".available").hide();
					$(".unavailable").show();
				}
				
				$(".downloadMusic2").trigger('click');
			}
		})
	});
	
	$("#showShare").click(function(){
		$("#shareOptions").show();
	});
	
	$(".shareIcons a").click(function() {
		document.location = '/thankyou/download';
	});

}

var buildShowcaseNavArt = function() {

	$('.showcase').each(function() {

		var cnt = $('.art li', $(this)).length;
		var showcase = $(this);
		var paging = '';

		if (cnt > 1) {
			for (var i = 0; i < cnt; i++) {
				active = (i == 0) ? ' active' : '';
				paging += ' &nbsp;<a class="showcaseNavPage' + active + '" href="#' + i + '">' + (i + 1) + '</a>';
			}
			$('.showcaseNav', $(this)).replaceWith('<div class="showcaseNav"><span class="showcaseZoom"><a class="showcaseNavZoom" href="#zoom">+ zoom</a>&nbsp; /</span>' + paging + '</div>');
		} else {
			if($(this).attr('id') == "artist-showcase") {
				$('.showcaseNav', $(this)).replaceWith('<div class="showcaseNav"><span class="showcaseZoom"><a class="showcaseNavZoom" href="#zoom">+ zoom</a></span></div>');
			}
		}

	})

	$('.showcaseNavPage').click(function() {
		var page = $(this).attr('href').split('#')[1];
		$('.showcaseNavPage').removeClass('active');
		$('.showcase .art li').hide();
		$('.showcase .art li:eq(' + page + ')').show();

		if (page == 0) {
			$('.showcaseZoom').fadeIn(100);
		} else {
			$('.showcaseZoom').fadeOut(100);
		}
		$(this).addClass('active');
		return false;
	});

	$('.showcase .art img').click(function() {
		var active = $('.showcaseNavPage.active').attr('href').split('#')[1];
		active = (active * 1);
		if ($('.showcaseNavPage[href$=#' + (active + 1) + ']').length) {
			$('.showcaseNavPage[href$=#' + (active + 1) + ']').click();
		} else {
			$('.showcaseNavPage[href=#0]').click();
		}
		return false;
	});

}

// ======================
// = end gallery detail =
// ======================
var autoInterval = null;
var autoDelay = 6000;
var itemWidth = 385;
var lastScrollVisibleItemsCount = 2;

var init_about = function() {
	$('.rotator').scrollLeft(0);

	init_join_form();
	
	//autoInterval = window.setInterval(rotatorNextFull, autoDelay);

	if ($('#rotatorContent li').length > 1) {
		$('.rotatorContainer .next').removeClass('disabled');
	}
	
	$('.rotatorContainer .prev').addClass('disabled');

	$('.rotatorContainer .next').mousedown(function() {
		rotatorNextFull();
		featureInterval = window.setInterval(rotatorNextFull, 600);
		
		clearInterval(autoInterval);
		//autoInterval = window.setInterval(rotatorCycle, autoDelay);
		
		return false;
	}).mouseup(function() {
		clearInterval(featureInterval);
		return false;
	}).click(function() {
		return false;
	});

	$('.rotatorContainer .prev').mousedown(function() {
		rotatorPrevFull();
		featureInterval = window.setInterval(rotatorPrevFull, 600);
		
		clearInterval(autoInterval);
		//autoInterval = window.setInterval(rotatorCycle, autoDelay);
		
		return false;
	}).mouseup(function() {
		clearInterval(featureInterval);
		return false;
	}).click(function() {
		return false;
	});

	if(isiPad) {
		$('.rotatorContainer .next').hide();
		$('.rotatorContainer .prev').hide();
	}

	$('.rotatorContainer .birthday').calendar({
		onClose: function() {
			$('.rotatorContainer .birthday').removeClass('default');
		}
	});

	$('.rotatorContainer .date input, .rotatorContainer .date img').click(function() {
		$('.rotatorContainer .birthday').focus();
	}).keydown(function() {
		return false;
	});
}

var rotatorCycle = function() {
	var maxScroll = itemWidth * ($('#rotatorContent li').length - lastScrollVisibleItemsCount);
	if ($('.rotator').scrollLeft() >= maxScroll) {
		$('.rotator').animate({
			scrollLeft: 0
		},
		1000, 'swing', function() {
			$('.rotatorContainer .prev').addClass('disabled');
			$('.rotatorContainer .next').removeClass('disabled');
		});
	} else {
		rotatorNextFull();
	}
}

var rotatorNextFull = function() {
	if ($('.rotator:animated').length) {
		return false;
	}

	$('.rotatorContainer .prev').removeClass('disabled');

	var maxScroll = itemWidth * ($('#rotatorContent li').length - lastScrollVisibleItemsCount);
	if ($('.rotator').scrollLeft() < maxScroll) {
		$('.rotator').animate({
			scrollLeft: '+='+itemWidth+'px'
		},
		500, 'swing', function() {
			if ($('.rotator').scrollLeft() >= maxScroll) {
				$('.rotatorContainer .next').addClass('disabled');
			}
		});
	}
}

var rotatorPrevFull = function() {
	if ($('.rotator').scrollLeft() < 10) {
		return false;
	}

	$('.rotatorContainer .next').removeClass('disabled');

	$('.rotator').animate({
		scrollLeft: '-='+itemWidth+'px'
	},
	500, 'swing', function() {
		if ($('.rotator').scrollLeft() < 10) {
			$('.rotatorContainer .prev').addClass('disabled');
		}
	});
}

// ==================
// = start homepage =
// ==================
var init_home = function() {
	$('.rotator').scrollLeft(0);

	if ($('#rotatorContent li').length > 5) {
		$('.rotatorContainer .next').removeClass('disabled');
	}

	$('.rotatorContainer .next').mousedown(function() {
		rotatorNext();
		featureInterval = window.setInterval(rotatorNext, 600);
		return false;
	}).mouseup(function() {
		clearInterval(featureInterval);
		return false;
	}).click(function() {
		return false;
	});

	$('.rotatorContainer .prev').mousedown(function() {
		rotatorPrev();
		featureInterval = window.setInterval(rotatorPrev, 600);
		return false;
	}).mouseup(function() {
		clearInterval(featureInterval);
		return false;
	}).click(function() {
		return false;
	});
	
	if(isiPad) {
		$('.rotatorContainer .next').hide();
		$('.rotatorContainer .prev').hide();
	}

	$('.rotatorContainer .birthday').calendar({
		onClose: function() {
			$('.rotatorContainer .birthday').removeClass('default');
		}
	});

	$('.rotatorContainer .date input, .rotatorContainer .date img').click(function() {
		$('.rotatorContainer .birthday').focus();
	}).keydown(function() {
		return false;
	});

	$('.communityNav a').click(function() {
		var item = $(this).closest('.item');
		$('a', item).removeClass('active');
		$(this).addClass('active');
		$('.communityText', item).hide();
		$('.communityText.' + $(this).attr('href').split('#')[1]).show();
		return false;
	});

	if(nonFlashIntro) {
		$("#splash").delay(7000).animate({opacity: 0}, 500, function() { $("#splash").hide() } );
	}
}

var rotatorNext = function() {
	if ($('.rotator:animated').length) {
		return false;
	}

	$('.rotatorContainer .prev').removeClass('disabled');

	var maxScroll = 192 * ($('#rotatorContent li').length - 5);
	if ($('.rotator').scrollLeft() < maxScroll) {
		$('.rotator').animate({
			scrollLeft: '+=192px'
		},
		500, 'swing', function() {
			if ($('.rotator').scrollLeft() >= maxScroll) {
				$('.rotatorContainer .next').addClass('disabled');
			}
		});
	}
}

var rotatorPrev = function() {
	if ($('.rotator').scrollLeft() < 10) {
		return false;
	}

	$('.rotatorContainer .next').removeClass('disabled');

	$('.rotator').animate({
		scrollLeft: '-=192px'
	},
	500, 'swing', function() {
		if ($('.rotator').scrollLeft() < 10) {
			$('.rotatorContainer .prev').addClass('disabled');
		}
	});
}


// ================
// = end homepage =
// ================
// ========================
// = start gallery (grid) =
// ========================
var ready_gallery = function() {
    var top = $('.galleryHeader').offset().top - parseFloat($('.galleryHeader').css('marginTop').replace(/auto/, 0));
    // this fixes a webkit bug that prevents a fixed element to work correctly if it's bottom position is set, but is below the page scroll
    window.scroll(0,10000);
    window.scroll(0,0);
    $(window).unbind('scroll.galleryScroll').bind('scroll.galleryScroll', function(event) {
		
        var y = $(this).scrollTop();

        if (y >= top) {
            $('.galleryHeader').addClass('fixed');

        } else {
            $('.galleryHeader').removeClass('fixed');
        }

        var h = $(document).height();
        var b = h - $(window).scrollTop() - $(window).height();

        if (b < 244) {
            $('.galleryViewOptions').css({
                position: 'absolute',
                bottom: 60
            });
        } else {

            $('.galleryViewOptions').css({
                position: 'fixed',
                bottom: 40
            });

        }

    });
}

var galleryItems = new Array();
var init_gallery = function() {
	galleryItems = new Array();

	$('.item.invis').css({
		opacity: 0
	});

	$('.mainContent.gallery').masonry({
		// only apply masonry layout to visible elements
		columnWidth: 163 + 29,
		itemSelector: '.item:not(.invis)',
		animate: true,
		animationOptions: {
			duration: speed,
			queue: false
		}
	});

	var speed = 1000;

	$('.mode a').click(function() {
		$('.mode a').removeClass('active');
		$(this).addClass('active');
		var colorClass = '.' + $(this).attr('href').split('#')[1];
		
		$('header.blurb').children().not(colorClass).addClass('hidden');
		$('header.blurb span' + colorClass).removeClass('hidden');

		if (colorClass == '.all') {
			// show all hidden boxes
			$('.mainContent.gallery').children('.invis').toggleClass('invis').animate({
				opacity: 1
			},
			{
				duration: speed
			});
		} else {			
			// hide visible boxes 
			$('.mainContent.gallery').children().not(colorClass+", .galleryFact").not('.invis').toggleClass('invis').animate({
				opacity: 0
			},
			{
				duration: speed
			});
			// show hidden boxes
			$('.mainContent.gallery').children(colorClass + '.invis').toggleClass('invis').animate({
				opacity: 1
			},
			{
				duration: speed
			});
		}
		$('.mainContent.gallery').masonry();
		
		return false;
	});

	if ($('.mainContent').hasClass('art')) {
		$('.mainContent.gallery').children().not('.art'+", .galleryFact").addClass('invis').animate({
			opacity: 0
		},
		{
			duration: speed
		});
		$('.mode a').removeClass('active');
		$('.mode a[href~=#art]').addClass('active');
		$('.mainContent.gallery').masonry();
		slideOverride = 'right';
	}

	if ($('.mainContent').hasClass('music')) {
		$('.mainContent.gallery').children().not('.music'+", .galleryFact").addClass('invis').animate({
			opacity: 0
		},
		{
			duration: speed
		});
		$('.mode a').removeClass('active');
		$('.mode a[href~=#music]').addClass('active');
		$('.mainContent.gallery').masonry();
		slideOverride = 'left';
	}

	$('.gallery img').each(function() {
		$(this).attr('otop', $(this).offset().top);
	});
	
	// Art Fact Roll Over
	/*$('.gallery .art.item a').hover(function() {
		$('.factoid', $(this)).show();
	},
	function() {
		$('.factoid', $(this)).hide();
	});*/

}

var filterGallery = function(type, animTime) {
	return false;

	if (!animTime) animTime = 300;
	if (!type) type = 'all';

	$('.mainContent.gallery').css('width', '932px');

	$('.mainContent.gallery').fadeOut(animTime, function() {

		var items = $('.column li').length;

		if (!galleryItems.length) {
			for (var j = 0; j < items; j++) {
				var ii = $('.column:eq(' + (j % 5) + ') li:eq(0)').detach();
				if (!ii.attr('order')) {
					ii.attr('order', (j + 1));
				}
				galleryItems.push(ii);
			}
		}

		var col = -1;

		for (var i = 0; i < galleryItems.length; i++) {

			if (type == 'all') {
				galleryItems[i].show();
				col++;
			} else {
				if (galleryItems[i].hasClass(type)) {
					galleryItems[i].show();
					col++;
				} else {
					galleryItems[i].hide();
				}
			}

			galleryItems[i].appendTo('.column:eq(' + (col % 5) + ')');

		}
		$(window).scroll();
		$(this).fadeIn(animTime);
	});
}

// ======================
// = end gallery (grid) =
// ======================
// ==============
// = start join =
// ==============
var init_join = function() {
	init_home();
}

// ============
// = end join =
// ============
// =======================
// = star musician video =
// =======================
var init_musicianVideo = function() {

	$('select, input[type=checkbox], input[type=radio]').uniform();

	/**** Martin Change ****/
	/*
		For some reason -1 doesnt work
	*/
	var maxScroll = ($('.page').length - 2) * 400;

	if ($('.smallGallery .pageContainer').scrollLeft() == 0) {
		$('.smallGallery .side a.previous').hide();
	}

	if ($('.smallGallery .pageContainer').scrollLeft() > maxScroll) {
		$('.smallGallery .side a.next').hide();
	}

	$('.smallGallery a.next').click(function() {
		if ($('.smallGallery .pageContainer').scrollLeft() > maxScroll) {
			return false;
		}
		$('.smallGallery .pageContainer').animate({
			scrollLeft: '+=400px'
		},
		300, function() {
			$('.smallGallery .side a.previous').show();
			if ($('.smallGallery .pageContainer').scrollLeft() > maxScroll) {
				$('.smallGallery .side a.next').hide();
			}
		});
		return false;
	});

	$('.smallGallery a.previous').click(function() {
		$('.smallGallery .pageContainer').animate({
			scrollLeft: '-=400px'
		},
		300, function() {
			$('.smallGallery .side a.next').show();
			if ($('.smallGallery .pageContainer').scrollLeft() == 0) {
				$('.smallGallery .side a.previous').hide();
			}
		});
		return false;
	});

	$('.page li .caption').css({
		opacity: 0.7
	});
	
	$('.page li').hover(function() {
		$('.caption', $(this)).animate({
			opacity: 1
		},
		150);
	},
	function() {
		$('.caption', $(this)).animate({
			opacity: 0.7
		},
		150);
	}).click(function() {
		$(this).siblings().removeClass('active');
		$('#musician').val($(this).attr('rel'));
		$('.selectGallery h1').text($('.caption', $(this)).text());
		$.uniform.update();
		$('#musicianVideo').video({
			xmlPath: $(this).attr('video'),
			noShare: true
		});
	});

	$('.previewButton, .cart, .pay').click(function() {
		$('form[name=frmSend]').submit();
		return false;
	});

	$('#musician').change(function() {
		$('li[rel=' + $(this).val() + ']').click();
	});

	$('input[name=send_date]').calendar({
		minYear: 2012,
		maxYear: 2013
	}).keydown(function() {
		return false;
	}).focus(function() {
		$('.send_now').attr('checked', false);
		$('#datecheck').attr('checked', 'checked');
		$('.send_date').removeClass('gray');
		$.uniform.update();
	});

	$('#datecheck, .date .icon').click(function() {
		$('input[name=send_date]').focus();
	});

	$('.donate_no').click(function() {
		$('.donation').addClass('gray');
	});

	$('.send_now').click(function() {
		$('.send_date').addClass('gray');
	});

	$('.donate_yes').click(function() {
		$('.donation').removeClass('gray');
	});

	$('.send_later').click(function() {
		$('.send_date').removeClass('gray');
	});

	$('.message_1').data('clean', $('.message_1').val()).change(function() {
		$(this).data('clean', false);
	});

	$('.friend_name').keyup(function() {
		if ($('.message_1').data('clean')) {
			$('.message_1').val($('.message_1').data('clean') + ', ' + $(this).val());
		}
	});

	$('form[name=frmSend]').submit(function() {

		errors = false;

		$('.formFieldError').removeClass('formFieldError');
		$('.floatingError, .errorMessage').remove();
    
    var email = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
    
    if(!$('.sender_fbid').val() || !$('.friend_fbid').val()) {
  		if ($('.sender_name', $(this)).val().length < 2 || $('.sender_name', $(this)).val() == $('.sender_name', $(this)).attr('default')) {
  			errors = true;
  			$('.sender_name', $(this)).addClass('formFieldError');
  		}

  		if ($('.sender_email', $(this)).val().length < 2 || !$('.sender_email', $(this)).val().match(email)) {
  			errors = true;
  			$('.sender_email', $(this)).addClass('formFieldError');
  		}

  		if ($('.friend_name', $(this)).val().length < 2 || $('.friend_name', $(this)).val() == $('.friend_name', $(this)).attr('default')) {
  			errors = true;
  			$('.friend_name', $(this)).addClass('formFieldError');
  		}

  		if ($('.friend_email', $(this)).val().length < 2 || !$('.friend_email', $(this)).val().match(email)) {
  			errors = true;
  			$('.friend_email', $(this)).addClass('formFieldError');
  		}
  	}

		if ($('.message_1', $(this)).val().length < 2 || $('.message_1', $(this)).val() == $('.message_1', $(this)).attr('default')) {
			errors = true;
			$('.message_1', $(this)).addClass('formFieldError');
		}

		if ($('.message_2', $(this)).val().length < 2 || $('.message_2', $(this)).val() == $('.message_2', $(this)).attr('default')) {
			errors = true;
			$('.message_2', $(this)).addClass('formFieldError');
		}

		if ($('.send_later').is(':checked') && ($('.send_date').val() == '' || $('.send_date').val() == $('.send_date').attr('default') || !checkDate($('.send_date').val()))) {
			errors = true;
			$('.send_later').addClass('formFieldError');
		}

		var currency = /\$?((\d{1,3}(,\d{3})*)|(\d+))(\.\d{2})?$/;

		/*if ($('.donate_yes').is(':checked')) {
			var value = $('.donation', $(this)).val();
			value = value.replace("$", "");

			if (value.length < 1 || !value.match(currency) || value < 5) {
				errors = true;
				$('.donate_yes', $(this)).addClass('formFieldError');
			}
		}*/

		if (errors) {

			$('.createHeader').prepend('<div class="errorMessage">Please correct the highlighted fields below</div>');

			$('.formFieldError').each(function() {
				var top = $(this).offset().top;
				var left = $(this).offset().left - 15;
				if ($(this).is("input[type=radio]")) {
					top -= 3;
				}
				$('body').append('<div class="floatingError" style="top: ' + top + 'px; left:' + left + 'px"></div>');
			});

			return false;
		}
		
	});

	var found = false;
	var musicianId = $('.mainContent').attr('rel');

	$('.page li').each(function() {
		if ($(this).attr('rel') == musicianId) {
			$(this).click();
			found = true;
		}
	});

	if (!found) {
		$('.page li:first').click();
	}
  
  $('.sendForm .fbConnect').click(function(){    
      fbShowFriendsList(updateFacebookFriend, cancelFacebookFriend);
      
      var user = getUserDetails();
      if(user.first_name) {
        $('.sendEmail').hide();
        $('.sendFacebook').show();
        $('.sendFacebook .friend').hide();
        $('.sendFacebook .actions').hide();
      
        $(".sendFacebook .user").css({backgroundImage: 'url(http://graph.facebook.com/'+user.uid+'/picture)'});
        $(".sendFacebook .user .name").text(user.first_name+' '+user.last_name);
        $(".sendFacebook .user .birthday").text('Birthday: '+user.birthday.split(',')[0]);
      }
      
  });
  
  $('.sendFacebook .newFriend').click(function(){
      fbShowFriendsList(updateFacebookFriend, nullCallback);
      return false;
  });
  
  $('.sendFacebook .switchEmail').click(function(){
      sendEmail();
      return false;
  });
  
}

var nullCallback = function() {}

var sendEmail = function() {
    $('.sendFacebook').hide();
    $('.sendEmail').show();
    $('input.sender_fbid').val('');
    $('input.friend_fbid').val('');
}

var cancelFacebookFriend = function() {
    sendEmail();
}

var updateFacebookFriend = function(fbUser) {    
    user = getUserDetails();
    friend = fbUser[0];
    
    $('.sender_name,.sender_email,.friend_name,.friend_email').removeClass('formFieldError');
    $('.floatingError').remove()
    $('.formFieldError').each(function() {
			var top = $(this).offset().top;
			var left = $(this).offset().left - 15;
			if ($(this).is("input[type=radio]")) {
				top -= 3;
			}
			$('body').append('<div class="floatingError" style="top: ' + top + 'px; left:' + left + 'px"></div>');
		});

    $(".sendFacebook .user").css({backgroundImage: 'url('+user.pic_square+')'});
    $(".sendFacebook .user .name").text(user.first_name+' '+user.last_name);
    $(".sendFacebook .user .birthday").text('Birthday: '+user.birthday.split(',')[0]);
    
    $(".sendFacebook .friend").show().css({backgroundImage: 'url(http://graph.facebook.com/'+friend.uid+'/picture)'});
    $(".sendFacebook .friend .name").text(friend.name);
    $('.sendFacebook .actions').show();
    if(friend.birthday) {
        $(".sendFacebook .friend .birthday").text('Birthday: '+friend.birthdayLong.split(',')[0]);
        $(".send_date").val(friend.birthdayLong.toLowerCase());
        
        $('.send_now').attr('checked', false);
    		$('#datecheck').attr('checked', 'checked');
    		$('.send_date').removeClass('gray').removeClass('default');
    		$.uniform.update();
        
    } else {
        $(".sendFacebook .friend .birthday").text('');
    }
    
    $('.sendEmail').hide();
    $('.sendFacebook').show();
    
    //$('input.sender_fbid').val(fbSession.uid);
	$('input.sender_fbid').val(fbSession.accessToken);
    $('input.friend_fbid').val(friend.uid);
	$('.message_1').val($('.message_1').data('clean') +', '+ friend.name); 
    
    $('input.sender_name').val('').blur();
    $('input.sender_email').val('').blur();
    $('input.friend_name').val('').blur();
    $('input.friend_email').val('').blur();
}

var checkDate = function(date) {
	var theDate = new Date(date);
	var curDate = new Date();

	var split = date.split(',');
	if (!split[1]) {

		tdate = date + ', ' + curDate.getFullYear();
		var theDate = new Date(tdate);
		if (theDate < curDate) {
			tdate = date + ', ' + (curDate.getFullYear() + 1);
			var theDate = new Date(tdate);
		}
	}

	if (theDate < curDate) {
		return false;
	}

	return true;

}

// ======================
// = end musician video =
// ======================
// ============================
// = star musician phone call =
// ============================
var init_musicianPhonecall = function() {

	$('select, input[type=checkbox], input[type=radio]').uniform();

	/**** Martin Change ****/
	// For some reason -1 doesnt work
	var maxScroll = ($('.page').length - 2) * 400;

	if ($('.smallGallery .pageContainer').scrollLeft() == 0) {
		$('.smallGallery .side a.previous').hide();
	}

	if ($('.smallGallery .pageContainer').scrollLeft() > maxScroll) {
		$('.smallGallery .side a.next').hide();
	}

	$('.smallGallery a.next').click(function() {
		if ($('.smallGallery .pageContainer').scrollLeft() > maxScroll) {
			return false;
		}
		$('.smallGallery .pageContainer').animate({
			scrollLeft: '+=400px'
		},
		300, function() {
			$('.smallGallery .side a.previous').show();
			if ($('.smallGallery .pageContainer').scrollLeft() > maxScroll) {
				$('.smallGallery .side a.next').hide();
			}
		});
		return false;
	});

	$('.smallGallery a.previous').click(function() {
		$('.smallGallery .pageContainer').animate({
			scrollLeft: '-=400px'
		},
		300, function() {
			$('.smallGallery .side a.next').show();
			if ($('.smallGallery .pageContainer').scrollLeft() == 0) {
				$('.smallGallery .side a.previous').hide();
			}
		});
		return false;
	});

	$('#state_why').click(function() {
		$(this).toggleClass('ltblueColor');
		$('#state_why_answer').slideToggle();
		return false;
	});

	$('.page li .caption').css({
		opacity: 0.7
	});
	$('.page li').hover(function() {
		$('.caption', $(this)).animate({
			opacity: 1
		},
		150);
	},
	function() {
		$('.caption', $(this)).animate({
			opacity: 0.7
		},
		150);
	}).click(function() {
		$(this).siblings().removeClass('active');
		$('#musician').val($(this).attr('rel'));
		$('.selectGallery h1').text($('.caption', $(this)).text());
		$.uniform.update();

		$('#audioImage')[0].src = $('img', $(this)).attr('src');

		var plflashvars = {};

		plflashvars.audio_url = $(this).attr('audio');

		var plparams = {};
		plparams.menu = "false";
		plparams.scale = "noscale";
		plparams.salign = "t";
		plparams.allowscriptaccess = "always";
		plparams.allownetworking = "all";
		var plattributes = {};
		plattributes.id = "audioPlayer";
		plattributes.name = "player";
		swfobject.embedSWF("/swf/audio.swf", "audioPlayer", "278", "100", "10", false, plflashvars, plparams, plattributes);

	});

	$('.previewButton, .cart, .pay').click(function() {
		//$('form[name=frmSend]').submit();
		return false;
	});

	$('#musician').change(function() {
		$('li[rel=' + $(this).val() + ']').click();
	});

	$('input[name=send_date]').calendar({
		minYear: 2012,
		maxYear: 2013,
		requireYear: true
	}).keydown(function() {
		return false;
	}).focus(function() {
		$('.send_now').attr('checked', false);
		$('#datecheck').attr('checked', 'checked');
		$('.send_date').removeClass('gray');
		$.uniform.update();
	});
 
	$('#datecheck, .date .icon').click(function() {
		$('input[name=send_date]').focus();
	});
 
	$('input[name=send_time]').selectTime();
 
	$('.time .icon').click(function() {
		$('input[name=send_time]').focus();
	});
	
	var found = false;
	var musicianId = $('.mainContent').attr('rel');
	
	//console.log("musician: " + musicianId);

	$('.page li').each(function() {
		if ($(this).attr('data-id') == musicianId) {
			$(this).click();
			found = true;
		}
	});

	if (!found) {
		$('.page li:first').click();
	}

    init_acsIvrCallScheduler();
}

/*MARTIN*/
var init_acsIvrCallScheduler = function() {
    ACS_IVR_CallSchedulerInit();
}

var valid_time = function(time, state) {
	if (!time) {
		return false;
	}
	return true;
}

var showMessageBox = function(html) {
    removeMessageBox();
    $('.messageArea').append('<div class="messageBox">'+html+'</div>');
}

var removeMessageBox = function() {
    $('.messageArea .messageBox').remove();
}

var disableSelection = function() {
    enableSelection();
    $('.selectGallery').append('<div class="selectorBlinder"></div>');
    $('.selectorBlinder').css({opacity: 0.7}).click(function(){return false});
}

var enableSelection = function() {
    $('.selectorBlinder').remove();
}

// ====================
// = start art e-card =
// ====================
var init_artistECard = function() {
            
    $('select, input[type=checkbox], input[type=radio]').uniform();
    
    var maxScroll = ($('.pages').length-1) * 400;
    
    if($('.smallGallery .pageContainer').scrollLeft() == 0) {
        $('.smallGallery .side a.previous').hide();
    }
    
    if($('.smallGallery .pageContainer').scrollLeft() > maxScroll) {
        $('.smallGallery .side a.next').hide();
    }
    
    $('.smallGallery a.next').click(function(){

        if($('.smallGallery .pageContainer').scrollLeft() > maxScroll) {
            return false;
        }
        $('.smallGallery .pageContainer').animate({scrollLeft: '+=400px'}, 300, function(){
            $('.smallGallery .side a.previous').show();
            if($('.smallGallery .pageContainer').scrollLeft() > maxScroll) {
                $('.smallGallery .side a.next').hide();
            }
        });
        return false;
    });
    
    $('.smallGallery a.previous').click(function(){
        $('.smallGallery .pageContainer').animate({scrollLeft: '-=400px'}, 300, function(){
            $('.smallGallery .side a.next').show();
            if($('.smallGallery .pageContainer').scrollLeft() == 0) {
                $('.smallGallery .side a.previous').hide();
            }
        });
        return false;
    });
    
    $('.page li .caption').css({opacity: 0.7});
        $('.page li').hover(function(){
            $('.caption', $(this)).animate({opacity: 1}, 200);
        }, function(){
            $('.caption', $(this)).animate({opacity: 0.7}, 200);
        }).click(function(){
            $(this).siblings().removeClass('active');
            $('#artist').val($(this).attr('rel'));
            $('.selectGallery h1').text($('.caption', $(this)).text());
            $.uniform.update();
            $('.selectGallery div.preview').html('<img src="'+$(this).attr('large')+'" />');
            var img = $('img', $(this));
            if(img.width() > img.height()) {
                $('.selectGallery div.preview img').css({marginTop: '66px'});
            } else {
                $('.selectGallery div.preview img').css({marginTop: '20px'});
            }
        });
    
    $('.page li').each(function(){
        jQuery.preLoadImages($(this).attr('large'));
    });
    
      $('.preview, .cart, .pay').click(function(){
         $('form[name=frmSend]').submit();
         return false;
      });

     $('#artist').change(function(){
         $('li[rel='+$(this).val()+']').click();
      });

    $('input[name=send_date]').calendar({
		  minYear:2012,
		  maxYear:2013
  	}).keydown(function(){return false;}).focus(function(){
  	  $('.send_now').attr('checked', false);
  	  $('#datecheck').attr('checked','checked');
  	  $('.send_date').removeClass('gray');
	    $.uniform.update();
  	});

  	$('#datecheck, .date .icon').click(function(){
  	    $('input[name=send_date]').focus();
  	});

    $('.donate_no').click(function(){
       $('.donation').addClass('gray'); 
    });

    $('.send_now').click(function(){
      $('.send_date').addClass('gray');
    });

    $('.donate_yes').click(function(){
      $('.donation').removeClass('gray');  
    });

    $('.send_later').click(function(){
      $('.send_date').removeClass('gray');  
    });

    $('.message_1').data('clean', $('.message_1').val()).change(function(){
      $(this).data('clean', false);
    });
    
    $('.friend_name').keyup(function(){
      if($('.message_1').data('clean')) {
        $('.message_1').val($('.message_1').data('clean') +', '+$(this).val() );
      }
    });  

    $('form[name=frmSend]').submit(function(){

        errors = false;

        $('.formFieldError').removeClass('formFieldError');
        $('.floatingError, .errorMessage').remove();

        if ($('.sender_name', $(this)).val().length < 2 || $('.sender_name', $(this)).val() == $('.sender_name', $(this)).attr('default')) {
  			errors = true;
  			$('.sender_name', $(this)).addClass('formFieldError');
  		}

  		var email = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;

  		if ($('.sender_email', $(this)).val().length < 2 || !$('.sender_email', $(this)).val().match(email)) {
  			errors = true;
  			$('.sender_email', $(this)).addClass('formFieldError');
  		}

  		if ($('.friend_name', $(this)).val().length < 2 || $('.friend_name', $(this)).val() == $('.friend_name', $(this)).attr('default')) {
  			errors = true;
  			$('.friend_name', $(this)).addClass('formFieldError');
  		}

  		if ($('.friend_email', $(this)).val().length < 2 || !$('.friend_email', $(this)).val().match(email)) {
  			errors = true;
  			$('.friend_email', $(this)).addClass('formFieldError');
  		}

  		if ($('.message_1', $(this)).val().length < 2 || $('.message_1', $(this)).val() == $('.message_1', $(this)).attr('default')) {
  			errors = true;
  			$('.message_1', $(this)).addClass('formFieldError');
  		}

  		if ($('.message_2', $(this)).val().length < 2 || $('.message_2', $(this)).val() == $('.message_2', $(this)).attr('default')) {
  			errors = true;
  			$('.message_2', $(this)).addClass('formFieldError');
  		}

        if($('.send_later').is(':checked') && ($('.send_date').val() == '' || $('.send_date').val() == $('.send_date').attr('default') || !checkDate($('.send_date').val()))) {
            errors = true;
            $('.send_later').addClass('formFieldError');
        }

        var currency = /\$?((\d{1,3}(,\d{3})*)|(\d+))(\.\d{2})?$/;

        /*if($('.donate_yes').is(':checked')) {
			var value = $('.donation', $(this)).val();
			value = value.replace("$","");
			
            if (value.length < 1 || !value.match(currency) || value < 5) {
                errors = true;
     			$('.donate_yes', $(this)).addClass('formFieldError');
            }            
        }*/

        if(errors) {

             $('.createHeader').prepend('<div class="errorMessage">Please correct the highlighted fields below</div>');

            $('.formFieldError').each(function(){
               var top = $(this).offset().top;
               var left = $(this).offset().left - 15;
               if($(this).is("input[type=radio]")) {
                 top -= 3;
               }
               $('body').append('<div class="floatingError" style="top: '+top+'px; left:'+left+'px"></div>'); 
            });            

            return false; 
        }
    });
	
	
	var found = false;
	var artistId = $('.mainContent').attr('rel');
	
	$('.page li').each(function() {
		if($(this).attr('rel') == artistId) {
			$(this).click();
			found = true;
		}
	});
	
	if(!found) {
		$('.page li:first').click();
	}
}

