function init_swap_text_boxes(){
	$('input[type=text][value].swaptextbox, textarea.swaptextbox').each(function() {
		$(this).data('default',$(this).attr('value')).bind('focus', function() {
			if($(this).val() == $(this).data('default')) {
				$(this).val('');
			}
		}).bind('blur', function() {
			if($(this).val() == '') {
				$(this).val($(this).data('default'));
			}
		});
	});
		
	$('form').bind('submit',function(){
		$(this).find('input[type=text][value].swaptextbox, textarea.swaptextbox').each(function(){
			if($(this).val() == $(this).data('default')) {
				$(this).val('');
			}
		});
	});
}

// open all external links in new window
$.fn.external = function(){
	$(this).bind('click', function(){
		if ((!$(this).is('[href*=' + self.document.location.hostname + ']')) && (this.href.indexOf('shop.wentevineyards.com') == -1))
		{
			return !window.open(this.href);
		}
	});

	return this;
};

// set example text for text fields
$.setExamples = function(){
	$('input[type=text][name=address]').each(function(i){
		var title = $(this).attr('title');
		var value = $(this).val();

		if (value != title)
		{
			$(this).example(title);
		}
	});
}


$(document).ready(function(){
	//make Promotion entries linking to vinovisit open in a thickbox
	$('.portal-readmore-div a[href*="vinovisit"]').addClass("thickbox").each(function(i,element){
		tb_init(element);
	});

	// add location finder
	if ($('#location-finder').length > 0)
	{
		$('a.directions, a.print', '.marker-content').live('click', function(e){
			e.preventDefault();

			return !window.open(this.href);
		});

		$('#location-finder').locationFinder({
			marker: {
				icon: '/_assets/img/location-marker.png',
				shadow: new google.maps.MarkerImage('/_assets/img/location-marker-shadow.png', null, null, new google.maps.Point(10, 33))
			},
			infoWindow: {
				height: 62
			},
			results: {
				dataType: 'xml',
				complete: function(){
					$.setExamples();

					var results = $('#location-results li').not('.no-results').length;

					$('#location-result-count em').text(results);

					$('#location-results').jScrollPane({
						scrollbarWidth: 18,
						showArrows: true,
						scrollbarMargin: 0
					});
				}
			}
		});
	}

	// set example text for text fields
	$.setExamples();

	// create AddThis button
	if ($.browser.safari)
	{
		ui_offset_top = 0;
	}
	else
	{
		ui_offset_top = -14;
	}

	// configure AddThis
	var addthis_config = {
		services_compact: 'mailto, twitter, facebook, googlebuzz, delicious, digg, stumbleupon, more',
		services_exclude: 'print',
		ui_offset_top: ui_offset_top,
		ui_offset_left: -5,
		ui_508_compliant: true,
		data_ga_tracker: pageTracker
	}

	// configure AddThis sharing
	var addthis_share = {
		templates: {
			twitter: '{{title}}: {{url}}'
		}
	}

	$('#social-links li.share a').each(function(i){
		addthis.button(this, addthis_config, addthis_share);
	});

	init_swap_text_boxes();
	// handle home page slideshow
	$('#slideshow').cycle({
	    	fx:     'fade',
	    	speed:  'slow',
	    	timeout: 5000,
	    	pager:  '#headernav',
		prev: '#prev_arrow',
		next: '#next_arrow'
	});
	
	// set initial external links
	$('a[href^=http]').not('.thickbox').external();
	
	// fix PNG-24 inline images
	// $(document).pngFix();
	$('img[src$="png"], ul#trade_buttons li a').DD_belatedPNG();
	
	// handle trade validation response
	function tradeResponse(responseText, statusText){
		var errors = $('#messages', responseText).html();
		var title = $('#messages', responseText).prev('h1').text();
	
		if($('.portal-promo-trade').is('#form_register')){
			var header = 'Registration';
			var location = '/trade/confirm/';
		}
		else{
			var header = 'Login';
			var location = '/trade/';
		}
	
		if(errors != null){
			if($('li', errors).length > 0){
				$('#messages').css('display', 'block').html('<h3>' + header + ' Error:</h3>' + errors).hide().fadeIn(300);
			}
			else if($('.portal-promo-trade').is('#forgot_password')){
				$('.portal-promo-trade form, .portal-promo-trade #messages').hide();
				$('.portal-promo-trade > h1.promos-1-h1').text(title);
				$('#sign_up').html(errors);
			}
			else{
				top.location.href = location;
			}
		}
		else{
			top.location.href = location;
		}
	}

	// handle POS validation response
	function posResponse(responseText, statusText){
		$('form#posform input, form#posform textarea').removeAttr('disabled');
	
		var errors = $('#messages', responseText).html();
		var success = '<p class="success">Your Request has been made!</p>';
	
		if(errors != null){
			if($('li', errors).length > 0){
				$('#pos_form #messages').css('display', 'block').hide().html('<h3>Request Error:</h3>' + errors).fadeIn(300);
			}
			else{
				$('#rightside > .content .jumps, .content #posform').hide();
				$('#rightside > .content').append(success);
			}
		}
		else{
			$('#rightside > .content .jumps, .content #posform').hide();
			$('#rightside > .content').append(success);
		}
	}
	
	$('form#posform').submit(function(){
		$('.image_logo', this).each(function(){
			var quantity = $('.info p.quantity input.quantity', this);
			var quantityHidden = quantity.prev('input[type="hidden"]');
			var comments = $('.description p textarea', this);
			var commentsHidden = comments.prev('input[type="hidden"]');
	
			if(quantityHidden.data('val') == undefined){
				quantityHidden.data('val', $(quantityHidden).val());
				commentsHidden.data('val', $(commentsHidden).val());
			}
			else{
				quantityHidden.val(quantityHidden.data('val'));
				commentsHidden.val(commentsHidden.data('val'));
			}
	
			if(quantity.val() == ''){
				quantity.attr('disabled', 'disabled');
				quantityHidden.attr('disabled', 'disabled');
				comments.attr('disabled', 'disabled');
				commentsHidden.attr('disabled', 'disabled');
			}
			else{
				quantityHidden.val(quantityHidden.data('val') + ' ' + quantity.val());
				quantity.attr('disabled', 'disabled');
	
				if(comments.val() == 'Comments:' || comments.val() == ''){
					comments.attr('disabled', 'disabled');
					commentsHidden.attr('disabled', 'disabled');
				}
				else{
					commentsHidden.val(commentsHidden.data('val') + ' ' + comments.val());
					comments.attr('disabled', 'disabled');
				}
			}
		});
		
		var options = {
			success: posResponse
		};

		$(this).ajaxSubmit(options);
		
		return false;
	});
	
	// handle comments text field
	$('.image_logo textarea.field').focus(function(){
		if($(this).val() == 'Comments:'){
			$(this).val('');
		}
	}).blur(function(){
		if($(this).val() == ''){
			$(this).val('Comments:');
		}
	});

	// handle POS toggling
	$('.pos_section h3').next('.products').hide();
	$('.pos_section h3 a').toggle(function(){
		$(this).addClass('active').parents('h3').next('.products').slideDown(200);
	}, function() {
		$(this).removeClass('active').parents('h3').next('.products').slideUp(200);
	});
	
	$("#mailinglist_form").validate({
		rules: {
			email: {email:true}
		},
		submitHandler: function(form) {
			form.submit();
		},
		invalidHandler: function(form, validator) {
			$("#mailing_list_message").html('Please fill out all fields to sign up for the mailing list.').hide(1,function (){$(this).slideDown()});
		}
	});

	$("#loading").bind("ajaxSend", function(){
	   $(this).fadeIn('slow');
	 }).bind("ajaxComplete", function(){
	   $(this).hide();
	 });
	
	$("#mailinglist_form_main #ajax").val("true");
	$("#mailinglist_form_main").validate({
		debug: true,
		ignoreTitle: true,
		rules: {
			firstname: {
				required: true,
				minlength: 2
			},
			lastname: {
				required: true,
				minlength: 2
			},
			address1: {
				required: true
			},
			zipCode: {
				required: true,
				minlength: 5
			},
			eMailAddress: {
				email: true
			},
			state: {
				required: true
			},
			Birthdate: {
				required: false,
				date: true
			}
		},
		messages: {
			eMailAddress: {
				email: function() {$("#mailinglist_form_message").html('The "E-Mail" field must be a valid email address.')}
			},
			Birthdate: {
				date: function() {$("#mailinglist_form_message").html('The "Birthdate" field must be a valid date.')}
			}
		},
		submitHandler: function(form) {
			$("#mailinglist_form_message").slideUp();
			$(form).ajaxSubmit({
				type: 'POST',
				success: function(data) {
					if (data.result == 'success') {
						$('#mailinglist_form_container').html(data.message);
					}
					else {
						$("#mailinglist_form_message").html(data.message).hide(1,function (){ $(this).slideDown() });
					}
				},
				dataType: 'json'
			});
		},
		invalidHandler: function(form, validator) {
			$("#mailinglist_form_message").html('Please fill out all fields to sign up for the mailing list.').hide(1,function (){ $(this).slideDown() })
		}
	});
});

