$(document).ready(function()
{
   // sidenav expand and collapse
   //$(".sidenavbody").hide();
 setRollovers();
 // main nav *********************************
 $(['/assets/images/ui/shield-on.png']).preload();
 $('.flyout').mouseover(function() {
		hideflyout();
		$('#nav').removeClass('suboff').addClass('subon');	
		$('#flyout'+$(this).attr('rel')).show();
  });
 $('#nav').mouseleave(function() {
  		hideflyout();
  });
 $('.hideflyout').mouseover(function() {
  		hideflyout();
  });
 
 function hideflyout() {
	 $('div[id^="flyout"]').hide();
	 $('#nav').removeClass('subon').addClass('suboff');	
 }

 // homepage *********************************
 $("#homepage_image").delay(250).fadeIn(1000);
	
  
  // product page ********************* 
  if ( $('#product_thumbs_wrapper').length > 0) { 
  		 $('#product_thumbs_wrapper > img').click(function() {
					$('#product_img_big').attr('src',$(this).attr('src'));														  
		 });
  }
  
  // category & artist pages ********************
  loadCategoryHandlers()
  function loadCategoryHandlers() {
	  if ( $('#product_preview_column1').length > 0) {
			// show hover div for products
			 $('.previewbox > img').mouseenter(function() {
					$('.previewbox > img').removeClass('onstate');
					$('.product_preview_hover').hide();
					$(this).addClass('onstate');	
					$(this).parent().find('.product_preview_hover').show();
				});
			 // hide hover div for products
			 $('.product_preview_hover').mouseleave(function() {
					$('.product_preview_hover').hide();
					$('.previewbox > img').removeClass('onstate');
					$(this).hide();
				});
			 $('#product_details_wrapper').mouseleave( function() { 
					$('.product_preview_hover').hide(); 
					$('.previewbox > img').removeClass('onstate'); 
				});
			 $('.product_preview_hover').click(function() {
					document.location = $(this).attr('rel');													  
				});
			 $('.thumbsNav > a').click(function() {
						$('#category_products').load('/cust/products/ajaxhosts/moreimages.asp',{'offset':$(this).attr('rel'),'catId':$(this).attr('title')},function() {
							loadCategoryHandlers()
						});
						return false;
				});
			 $('.thumbsNavArtist > a').click(function() {
						$('#artist_products').load('/cust/products/ajaxhosts/moreimages_artists.asp',{'offset':$(this).attr('rel'),'artistid':$(this).attr('title')},function() {
							loadCategoryHandlers()
						});
						return false;
				});
			 $('.thumbsNavArtOnLocation > a').click(function() {
						$('#artonloc_products').load('/cust/art_on_location/ajaxhosts/moreimages_artonloc.asp',{'offset':$(this).attr('rel'),'artonloc_id':$(this).attr('title')},function() {
							loadCategoryHandlers()
						});
						return false;
				});
	  }
  }
  // live form footer
	$('#live_name2').focus(function() {
		if ( $(this).val() == 'Name') { $(this).val('').css('color','#000'); }									 
	});
	$('#live_email2').focus(function() {
		if ( $(this).val() == 'Email') { $(this).val('').css('color','#000'); }									 
	});
	$('#btn_go').click(function() {
		if ( $('#live_name2').val() != '' && $('#live_email2').val() != '' && $('#live_name2').val() != 'Name' && $('#live_email2').val() != 'Email' && isEmail($('#live_email2').val()) ) { 
			$.post('/cust/email_signup/ajaxhosts/submit/',$('#live_signup2').serialize());
			$('#footer_signup_wrapper').fadeOut(200);
			setTimeout('$(\'#signup_complete2\').fadeIn(200);',200);
		} 										
	});
		
  // shopping cart
  cart_handlers();
	function cart_handlers() {
		if ($('#cart_items_wrapper').length > 0) {
			// update quantity link
			$('.update_qty').click(function() {
				qty_field = $(this).prev().prev();
				if ( isNumeric($(qty_field).val())) { 
					$('#cart_cell').load('/cust/shopping_cart/ajaxhosts/updateqty.asp', { 'id':$(qty_field).attr('rel'), 'qty':$(qty_field).val() }, function(data) {
						//alert($(qty_field).attr('rel'));
						$('#cartrow_'+$(qty_field).attr('rel')).animate({'background-color':'#b4d6f1'},200, function() {
								$('#cartrow_'+$(qty_field).attr('rel')).animate({'background-color':'#fff'},300);								
						});
						cart_handlers();																																												
					})
				}
				return false;
			});
			// select tax state
			$('input[name="shipping_id_display"]').click(function() {
				$('#cart_cell').load('/cust/shopping_cart/ajaxhosts/setshippingmethod.asp', { 'id':$(this).val() }, function(data) {
					cart_handlers();																																							
				});
			});
		}
		// process discount code
		$('#coupon_apply').click(function() {
			$('#cart_cell').load('/cust/coupon_codes/ajaxhosts/applycoupon.asp', { 'code':$('#coupon_code').val() }, function(data) {
				cart_handlers();																																							
			});
		});
	}
	// checkout step 1
	checkout_step1_handlers();
	function checkout_step1_handlers() {
		if ($('.payments').length > 0) {
			$('#use_different_address').click(function() {
				$('#billing_fields').slideDown();
			});
			$('#use_same_address').click(function() {
				$('#billing_fields').slideUp(function() {
					populateBillingAddress();
				});
			});
			$('#checkout_submit_1').click(function() {
				if ($('#use_same_address').attr('checked')) { 
					populateBillingAddress();
				}
				e = 0
				$('#authorizedotnetform').find('input,select').each(function(i) {
					$(this).removeClass('val_required'); 
					if ( $(this).val() == '') {
						if ($(this).attr('name') != 'address2' && $(this).attr('name') != 'address2_bill' && $(this).attr('id') != 'checkout_submit_1' && $(this).attr('id') != 'shipping_id') {
							//e += $(this).attr('name') + ',';
							e = 1;
							$(this).addClass('val_required'); 
						}
					}
					if ( ($(this).attr('name') == 'email') && (!isEmail($(this).val())) ) { $(this).addClass('val_required');  e=1;}
					//if ( ( $(this).attr('name') == 'address' || $(this).attr('name') == 'address2') && (isPOAPO($(this).val())) ) { $(this).addClass('val_required');  e=2;}
				});
				if (e==0) { return true; }
				//else if (e==2) {alert('We currently do not ship to this location. Please select another shipping address.'); return false; }
				else if (e==1) { alert('Please complete all required fields.'); return false;  }
				else {  alert('We currently do not ship to this location. Please select another shipping address.'); return false; }
			});
		}
	}
	// print confirmation
	if ($('#print_button').length > 0) {
			$('#print_button').click(function() {
											window.print();			 
														 });
	}
	
	function populateBillingAddress() {
		$('#firstname_bill').val($('#firstname').val());
		$('#lastname_bill').val($('#lastname').val());
		$('#country_bill').val($('#country').val());
		$('#address_bill').val($('#address').val());
		$('#address2_bill').val($('#address2').val());
		$('#city_bill').val($('#city').val());
		$('#state_bill').val($('#state').val());
		$('#zip_bill').val($('#zip').val());
		$('#phone_bill').val($('#phone').val());
	}
  
  // product details *****************************
  if ($('#product_details_wrapper').length > 0) {
		$("a#fb_sendhint").fancybox(
				{'showCloseButton':false,'overlayOpacity':.9,'autoScale':false,'height':472,'width':473,'overlayColor':'#000','margin':0,'padding':0,
					'onComplete':function() {
						loadHintHandlers();
					}
				}
		 );
		function loadHintHandlers() {
			$(['/assets/images/ui/bg-hint-thanks.gif']).preload();
			$('#fancybox_close').click(function() { $.fancybox.close(); });	
			$('#sendhint_submit').click(function() { 
				 $.post('/cust/products/ajaxhosts/sendhint.asp',$('#sendhintform').serialize(),function(data) { 
							$('#sendhint').css('background','url(/assets/images/ui/bg-hint-thanks.gif)');
							$('#sendhintform').hide();
							//$.fancybox.close();																											 
				 });												 
			});
		}
  		
  }
  // search **************************************
  if ( $('#search_results_wrapper').length > 0) {
  		$('#search_form  select').change(function() {
			$('#search_results_wrapper').html('<img src="/assets/images/ui/blue-loading.gif">').load('/cust/search/ajaxhosts/search.asp',{'artist':$('#artist_id').val(),'category':$('#category_id').val(),'price_range':$('#price_range').val()},function(){
																																																																  loadCategoryHandlers()
																																																																  });
		});
  }
  
  // desire landing page *************************
  if ( $('#desire_landing_cats_inner').length > 0) {
		  $('#desire_landing_cats_inner').hover(
				function() { 
					$(this).css('background','url(/assets/images/ui/desire-left-frame-on.png)');
					$(this).find('.desire_landing_list').show();
				},
				function() { 
					$(this).css('background','url(/assets/images/ui/desire-left-frame-off.png)');
					$(this).find('.desire_landing_list').hide();
				}
			);
		  $('#desire_landing_art_inner').hover(
				function() { 
					$(this).css('background','url(/assets/images/ui/desire-right-frame-on.png)');
					$(this).find('.desire_landing_list').show();
				},
				function() { 
					$(this).css('background','url(/assets/images/ui/desire-right-frame-off.png)');
					$(this).find('.desire_landing_list').hide();
				}
			);
		  $('#artist_down').click(function() {  
				$('#artist_list_scroll').animate({ top:'-=350'},1000);
				$(this).hide();
				$('#artist_up').show();
			} );
		  $('#artist_up').click(function() {  
				$('#artist_list_scroll').animate({ top:'+=350'},1000);
				$(this).hide();
				$('#artist_down').show();
			} );
  }
  
});

$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}

// cart functions ****************************************************************************************************************
function isNumeric(input) {
   return (input - 0) == input && input.length > 0;
}

function isEmail(x) {
	mail_at = x.indexOf("@");
	mail_dot = x.lastIndexOf(".");
	if( mail_at < 2 || mail_dot < 4 || mail_dot < (mail_at + 2) ) { return false; }
	else { return true; }
}

function checkForShipping(x) {
		if ($('input[name="shipping_id_display"]:checked').length == 0) { 
			alert('Please choose a shipping method.');
			//$('#tax_state').addClass('chooseShipping');
			return false; 
		}
		else { 
			return true;
		}
}

function showColor() {
	if ( $("#color option:selected").attr("title") != "") {
		$("#mainpic").attr("src",$("#color option:selected").attr("title"));
	}
}

function showShipping() {
		$("#shippinginfo").slideToggle();
}

function changeBackground(y) {
		var x;
		$.ajax({
			type: "POST",
			url: '/cust/ui/tweakui.asp',
			data: "rKey="+y,
			success: function(data) {
    			parent.$("body").css("background-image","url('"+ data +"')");
  			}
		});
}

// removes items from carts. 
function updateCart() {
	numrows = $("tr[id^='cartrow_']").length;
	c=0;
	$("input[name='remove']").each( function () {
		if (this.checked) { 
			c++;
			$("#cartrow_"+this.value).css('background-color','#46B5DC').load("/cust/shopping_cart/ajaxhosts/removeitemfromcart.asp", { 'id': this.value } ).fadeOut(500);
			setTimeout('$(\'#cartrow_'+this.value+'\').remove();',500);			
		}
	});
	// if cart is now empty, clear the table, else reset the price total
	if (numrows==c) {
		 setTimeout('$(\'#cart\').remove();',500);
		 setTimeout('$(\'#emptycart\').fadeIn(500).html("Your cart is empty");',500);
	}
	else {
		setTimeout('updateTotal();',1000);
	}
}

function updateTotal() {
	//total = 0
	//$(".price").each( function () {
	//	total += parseFloat(this.innerHTML.substr(1));	
	//});
	//total += parseFloat($("#shipping").html().substr(1));
	//$('#total').html('$'+total);
	$("#shipping").load("/cust/shopping_cart/ajaxhosts/updatetotal.asp",  { 'update': 'shipping' });
	$("#total").load("/cust/shopping_cart/ajaxhosts/updatetotal.asp",  { 'update': 'total' });	
}

function setdate(x,Item_Id,date,field) {
	var url = '/cust/orders/admin/ajaxhosts/ajax.asp?f=setdate&Item_Id=' + Item_Id + '&field=' + field;
	new Ajax.Updater('blanky', url);
}

function setRollovers() {
	$('.rollover').unbind('mouseenter mouseleave');
	$('.rollover').hover(function() {
        var currentImg = $(this).attr('src');
        $(this).attr('src', $(this).attr('rel'));
        $(this).attr('rel', currentImg);
   }, function() {
        var currentImg = $(this).attr('src');
        $(this).attr('src', $(this).attr('rel'));
        $(this).attr('rel', currentImg);
   });	
}
