$(document).ready(function(){
	
	$('#take-action').fadeIn(2000);
	
	$('.close-take-action').click(function() {
		$(this).parent().hide();
	});
	simpleSlide({
		'callback' : function(){
		
			$(".product-preview").fancybox({
				'titleShow'    : false,
				'transitionIn' : 'elastic',
				'transitionOut': 'elastic'
			});
			
			$('#cartCheckoutFrame').load('../store/storesub/inc/cartCheckoutFrame.php', function() {
				$('#add-to-cart, #view-cart').fancybox({
					'titleShow'      : false,
					'width'          : 560,
					'height'         : 340,
					'autoDimensions' : false,
					'onClosed'		 : function() {
						$('#cartBox').hide();
					}
				});

				$('#view-cart').click( function() {
					var item_price  = 0;
					var total_price = 0;
					$('#cartBox').load('../store/storesub/inc/showCart.php').fadeIn(300, function(){
						$('.cart-item .right').each(function() {
							item_price   = $(this).text().split('$');
							item_price   = parseFloat(item_price[1]);
							total_price += item_price;
						});
						$('.cart-total .right').html('<b>total:</b> $' + total_price.toFixed(2));
					});
				});
			});
		}
	});
			
	$('#add-to-cart').click( function() {
		$('#cart_error').remove();
		
		var options_checked = true;
		
		$('.checkthis').each( function() {
			if($(this).children('.selected, :selected').size() == 0 || $(this).children('.selected').attr('value') == '' || $(this).children(':selected').attr('value') == ''){
				options_checked = false;
			}
		});
		
		if(options_checked){
			var sku           = $('#add-to-cart').attr('rel');								  
			var option_string = '';
			var name          = $(this).siblings('.product-name').text();
			var price         = $(this).siblings('.options').children('#price').text().split('$');
			price             = price[1]; 
			var item_price   = 0;
			var total_price   = 0;
			
			$('.selected, :selected').each( function() {
				option_string +=  '(' + $(this).parent().attr('name') + ':' + $(this).attr('value') + ')';
			});
			
			$.ajax({
			
				url    : '../store/storesub/inc/setCartCookie.php',
				type   : 'post',
				data   : 'sku=' + sku + '&do=additem&options=' + option_string + '&name=' + name + '&price=' + price,
				success: function() {
					$('#cartBox').load('../store/storesub/inc/showCart.php').fadeIn(300, function(){
						$('.cart-item .right').each(function() {
							item_price   = $(this).text().split('$');
							item_price   = parseFloat(item_price[1]);
							total_price += item_price;
						});
						$('.cart-total .right').html('<b>total:</b> $' + total_price.toFixed(2));
					});
				}
			
			});
		} else {
			$('#add-to-cart').after('<div id="cart_error">Please select one of each option.</div>');
			$.fancyBox.cancel;
		}
	});
	
	$('.cart-delete-item').live( 'click', function() {
		var item_index = $(this).attr('value');
		var el         = $(this).parents('.cart-item-container');
		var item_price = 0;
		var total_price= 0;
		
		$.ajax({
		
			url    : '../store/storesub/inc/setCartCookie.php',
			type   : 'post',
			data   : 'do=removeitem&index=' + item_index,
			success: function() {
				$(el).fadeOut(300, function() {
					$(this).html('<div class="cart-removed-message">Item removed from cart.</div>');
					
					$('.cart-item .right').each(function() {
						item_price   = $(this).text().split('$');
						item_price   = parseFloat(item_price[1]);
						total_price += item_price;
					});
					$('.cart-total .right').html('<b>total:</b> $' + total_price.toFixed(2));
					
				}).fadeIn(300);
				
			}
		});

	});
	
	$('.color').click( function() {
		$('.color')
			.removeClass('selected')
			.css('outline', 'none');
		$(this)
			.addClass('selected')
			.css('outline', '1px solid #FFF');
	});
	
	$('option').click( function() {
		$(this).parent().children().removeClass('selected');
		$(this).addClass('selected');
	});	
			
	$('.contribute_more').toggle( function() {
			$(this).siblings('.contribute_hidden').slideDown(500);
			$(this).fadeOut(250, function() {
				$(this).text('learn less').fadeIn(250);
			});
		}, function() {
			$(this).siblings('.contribute_hidden').slideUp(500);
			$(this).fadeOut(250, function() {
				$(this).text('learn more').fadeIn(250);		
			});
		}
	);
									
	$('.enabled').live('click', function() {
	
		var emailsubmitted = $('input[name="email"]').attr('value');
		
		var result = '';
		
		$('#match').fadeOut(300);
		$('.newsletterForm #form').fadeOut(300);		
				
		$.ajax({
			type: "POST",
			url: "/php/newsletterSubmit.php",
			dataType: "text",
			success: function(result) {
				$('#submitting').fadeOut(300, function() {
					if(result == 'yes') {
						$.ajax({
							type: "POST",
							url: "/php/newsletterMail.php",
							dataType: "text",
							data: 'email=' + emailsubmitted,
							success: function(emailresult) {
								if (emailresult == 'yes') {
									$('#submitting').fadeOut(300, function() {
										$('#submitted').fadeIn(300);
									});
								}
								
								else {
									$('#submitted').fadeIn(300).text('There was something wrong with attempting to e-mail to your address.');
								}
							}
						});
					}
					
					else {
						$('#submitted').fadeIn(300).text('It appears your e-mail address is already in our database.');
					}
				});
			},
			error: function() {
				$('#submitting').fadeOut(300, function() {
					$('#submitError').fadeIn(300);
				});
			},
			data: "email=" + emailsubmitted,
			beforeSend: function() {
				$('#submitting').fadeIn(300);
			}
		});
	});
					
	$("input, textarea").keyup(function() {	
		
		var address1 = $('input[name="email"]').attr('value');
		var address2 = $('input[name="emailconf"]').attr('value');
			
		if(address1 != address2) {
			$('#match').fadeOut(300, function(){
				$('#match').remove();
			});
			
			$('#bademail').slideUp(300, function() {
				$('#bademail').remove();
			});

			if($('input[name="emailconf"]').next().attr('id') != "nomatch" && address2 != $('input[name="emailconf"]').attr('defaultfield')) {
				$('input[name="emailconf"]').after('<div id="nomatch"></div>');
				$('#nomatch').fadeIn(300);
			}
		$('#submitButton').removeClass('enabled').addClass('disabled').css('cursor', 'default').attr('disabled', 'disabled');
						
		} else {
			$('#nomatch').fadeOut(300, function(){
				$('#nomatch').remove();
			});
			if($('input[name="emailconf"]').next().attr('id') != "match") {
				$('input[name="emailconf"]').after('<div id="match"></div>');
				$('#match').fadeIn(300, function() {
					
					if(!isValidEmailAddress(address1)){
						$('#match').after('<div id="bademail">Your fields match, but your e-mail address is invalid. It should be formatted like \'john@doe.com\'</div>');
						$('#bademail').slideDown(300);
					}
					
					else {
						$('#bademail').slideUp(300, function() {
							$('#bademail').remove();
						});
						$('#submitButton').removeClass('disabled').addClass('enabled').css('cursor', 'pointer').removeAttr('disabled');
					}
				});
			}
		}
	});
	
	$('.months').css('display', 'block');
	
	$('.years a').click(function() {
		
		var year = $(this).text();
		
		$.ajax({
			type: "POST",
			url: "/php/articlesbydate.php",
			dataType: "text",
			data: 'command=months&passedyear=' + year,
			beforeSend: function(){
				$('.months').animate({
						opacity: '0'				 
					}, 300, function() {
						$(this).remove(); // $(this) was key to making it work
					});
			},
			success: function(monthslist) {
				$('.years').after(monthslist);
				$('.months').css({
					display: 'block',
					opacity: '0'
				}).animate({
					opacity: '1'
				}, 300);
			}
		});
		
		$('.years a').each( function() {
			pinkyear = $(this).text();
			$(this).html(pinkyear);
		});
		
		$(this).html('<span>' + year + '</span>');
		
	});
	
	$('.default-value').each(function() {
		var default_value = $(this).val();
		$(this).attr('rel', default_value);
	});
	
	$('.default-value').focus(function(){
		if($(this).val() == $(this).attr('rel')) { 
			$(this).val(''); 
		} 
	}); 
		
	$('.default-value').blur(function(){ 
		if($(this).val() == '') { 
			$(this).val($(this).attr('rel')); 
		} 
	});

	$('input[rel="error_check"], textarea').focus(function() {
		if($(this).prev().attr("class") == "formalert") {
			$(this).prev().animate({
				opacity: '0'
				}, 200, "swing", function() {
					$(this).remove();
				}
			);
		}
	});								 
	
	$('.enabledEmail').live('click', function() {	
		var name = $('input[name="name"]').val();
		var email = $('input[name="email"]').val();
		var title = $('input[name="title"]').val();
		var details = $('textarea[name="details"]').val();


		var result = '';
		
		$.ajax({
			type: "POST",
			url: "../php/quotemail.php",
			dataType: "html",
			success: function(result) {
				$('.error_window').fadeOut(300, function() {
					$(this).html(result);
					$(this).css('display', 'block');
					$(this).animate({
						opacity: '1'
					}, 300, "swing");
				});
			},
			error: function(error) {
				$('.error_window').animate({
					'opacity': 0
				},300, function() {
					$('.error_window').html('There was a problem, please try again later.<br>' + error);					
					$('.error_window').animate({
						opacity: '1'
					}, 300, "swing");
				});
				$('.error_window');
			},
			data: "email=" + email + "&name=" + name + "&title=" + title + "&details=" + details,
			beforeSend: function() {
				$('#contact_form').animate({
						opacity: '0'
					}, 300, "swing", function() { 
					$('.error_window').css('display', 'block');
					$('.error_window').text('Sending...');
					$('.error_window').animate({
						opacity: '1'
					}, 300, "swing");
				});
			}
		});
	});
	
	$('.error_window').live('click', function() {
		$(this).animate({
			opacity: 0
		}, 300, "swing", function() {
			$(this).css('display', 'none');
			$('.submitting').text('Submitting...');
		});
		$('#contact_form').animate({
			opacity: 1
		});
		
		document.getElementById('captcha').src = '/securimage/securimage_show.php?' + Math.random(); 
		
	});	
	
	$('input[rel="error_check"], textarea').blur( function() {
		if($(this).val() == "") {
			
			if($(this).prev().attr('class') == 'formalert') {
				$(this).prev().animate({
					opacity: '0'
					}, 200, "swing", function() {
						$(this).remove();
					}
				);
			}
			
			$(this).before('<div class="formalert">This field may not be left blank.</div>');
			$(this).prev('.formalert').animate({
				'display' : 'inline',							   
				'opacity' : '1'
				}, 200, "swing"
			);
		}
	});
	
	$('input[rel="error_check"], textarea').keyup(function() {	
		
		var email = $('input[name="email"]').val();

		if($(this).val() == '') {
			$(this).attr('error', '1');
		} else {
			$(this).attr('error', '0');
		}

		if(email == '') {
			$('input[name="email"]:focus').prev('.formalert').animate({
				opacity: '0'
				}, 200, "swing", function() {
					$(this).remove();	
				}
			);
		}

		if(isValidEmailAddress(email)) {
			$('input[name="email"]:focus').prev('.formalert').animate({
				opacity: '0'
				}, 200, "swing", function() {
					$(this).remove();	
				}
			);
			$('input[name="email"]:focus').attr('error', '0');		
		} else {
			if($('input[name="email"]:focus').prev().attr('class') != 'formalert') {
				$('input[name="email"]:focus').before('<div class="formalert">This e-mail address is not valid.</div>');
				$('input[name="email"]:focus').prev('.formalert').animate({
					'display' : 'inline',
					'opacity' : '1'
					}, 200, "swing"
				);
			}
			$('input[name="email"]:focus').attr('error', '1');		
		}
		
		var errorcount = 0;
		var formsfilled = 'yes';
		var email = $('input[name="email"]').val();
		
		$('input[rel="error_check"], textarea').each( function() {
			if($(this).attr('error') == 1) {
				errorcount++;
			}
		});
		
		if(errorcount === 0) {
		
			if(email == '') {
				$(this).prev('.formalert').animate({
					opacity: '0'
					}, 200, "swing", function() {
						$(this).remove();
				});
				$(this).attr('error', '0');									
			}

			
			$('input[rel="error_check"], textarea').each( function() {
				var thisvalue = $(this).val();
				
				if(thisvalue == "") {
					formsfilled = 'no';
				}
			}); 
			
			if(errorcount == 0) {
				if(formsfilled == 'yes') {
					$('#submit').attr('class', 'enabledEmail');
					$('#submit').val('Send away!');		
				} 
	
			} else {
				$('#submit').attr('class', 'disabled');
				$('#submit').val('Please fill out the form correctly to continue.');
			}
		} else {
			$('#submit').attr('class', 'disabled');
			$('#submit').val('Please fill out the form correctly to continue.');
		}		
	});
	
	$('.color').each( function() {
		var color = $(this).attr('rel');										  
		$(this)
			.css({
				'backgroundColor': color
			});
	});
	
	$(window).load( function(){
		blogImageResizer();	
	});	
});

function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}

function blogImageResizer(){
	var $images = $('#genericBody img, .blogtext img');
	
	$($images).each( function(){
		if($(this).width() > $(this).parent().innerWidth()){
			var oldWidth = $(this).width();
			var oldHeight = $(this).height();
			var newWidth = $(this).parent().width();
			
			var newHeight = ( newWidth * oldHeight) / oldWidth;
						
			$(this).attr({
				width: newWidth,
				height: newHeight
			});
			
		}
	});
}
