var YM = {            
	layout: {
		init: function() { 
			// IE6 .png fix
			$('#header h1, #touts a, #sidebar .talking-point').supersleight({
				shim: '/images/blank.gif'
			});        
			
			
			// font replacement
			Cufon.replace('h1, h3, label, #sale h2');
			Cufon.replace('#tabs a, .caption', {
				hover: true
			});
			// get IE to behave
			Cufon.now();  
			
			// hide subnav
			var $subnav_yantraway = $('#nav li.yantra ul');
			var $subnav_using = $('#nav li.using ul');
			var $yantraway_link = $('#nav a.yantra');
			var $using_link = $('#nav a.use');

			
			$('#nav li.yantra').hoverIntent(function() {
				$subnav_yantraway.show();
			}, function() {
				$subnav_yantraway.hide();
			}); 
			
			$('#nav li.using').hoverIntent(function() {
				$subnav_using.show();
			}, function() {
				$subnav_using.hide();
			}); 
			
			// open links in new windows
			$('a.target-blank').click(function() {
				window.open(this.href);
				return false;
			});
			
			// get image buttons to have hover effect in IE6 
			if(typeof document.body.style.maxHeight === "undefined") {
				$('input.img-button').hover(function() {
					$(this).css('background-position', 'center left');
				}, function() {
					$(this).css('background-position', 'top left');
				});
			}
			
		}
	},
	
	index: {
		init: function() {
            YM.Shared.Nav.make_selected('home');

			// reset order confirmed cookie
			YM.Shared.Cookies.reset_order();

			// basic positions slideshow (not in IE6) 		
			if(typeof document.body.style.maxHeight === "undefined") {
				var truthy = true;
			} else {  
				
				var $pos_back = $('<img src="/images/hp_tout_pos1.jpg" alt="Basic Positions - Back" />');
				var $pos_sit = $('<img src="/images/hp_tout_pos3.jpg" alt="Basic Positions - Sitting" />');			
				var $pos_cheek = $('<img src="/images/hp_tout_pos4.jpg" alt="Basic Positions - Cheek" />');
				
			    $('#slideshow').append($pos_back, $pos_sit, $pos_cheek).cycle({
					fit: 1,
					delay: 6000,
					timeout: 8000
				});
			}
		}
	},
	
	yantra_way: {
		init: function() {   
			// reset order confirmed cookie
			YM.Shared.Cookies.reset_order();
						
			YM.Shared.Tabs.init();
		    YM.Shared.Nav.make_selected('yantra');
		
			$('#body-mind .enlarge a').lightBox(YM.Shared.Lightbox.options);
			$('#the-yantra .enlarge a').lightBox(YM.Shared.Lightbox.options);
		}
	}, 
	
	use: {
		init: function() { 
									
			YM.Shared.Tabs.init(); 
		    YM.Shared.Nav.make_selected('use');
		
			// reset order confirmed cookie
			YM.Shared.Cookies.reset_order();		
		    
			// hide buzz sidebar if on Buzz page
			var subpage = YM.Shared.Tabs.get_tab_path(location.pathname);
			if (subpage == 'testimonials') {
				$('#sidebar .buzz').hide();
			};			
		}
	},
	
	contact: {
		init: function() {      
		    YM.Shared.Nav.make_selected('contact');
		
			// reset order confirmed cookie
			YM.Shared.Cookies.reset_order();		
		
			// pre-populate textarea depending on topic dropdown
			var $topic_menu = $('#email-us select');
			var $textarea = $('#email-us textarea');
			
			$topic_menu.change(function() {
				var $topic = $('#email-us select option:selected');
				var prepopulate = "";
				switch($topic.val()) {
					case "Product Questions":
						break;
					case "Placing an Order":
						prepopulate = "Please include your full name and mailing address.";
					    break;
				    case "Shipping and Delivery":
						prepopulate = "Please include all that apply: 1) the ZIP/postal code we're shipping to; 2) when you placed your order; and 3) your order number.";
						break;
					case "Returns":
						prepopulate = "Please include your mailing address and all that apply: 1) the date you shipped the item; 2) the purchase date.";
						break;
					default:
						prepopulate = "Please include your mailing address and/or any other information that will help us answer your question.";
				}
				$textarea.val(prepopulate);        
			});          
		}                
	},               
	
	buy: {
		init: function() { 
			
		  YM.Shared.Nav.make_selected('buy');	   

			// reset order confirmed cookie
			YM.Shared.Cookies.reset_order();		   		
			
			// disable autocomplete attr in form to workaround FF selected radio button bug
			$('form').attr('autocomplete', 'off');
			
			// insert price display HTML
      // var $price_display = $('<h4 class="clear"></h4>');
      // $('.select-size').after($price_display);  
			                                        
      // // price callback function
      // function get_price_display(size) {
      //  $.get('/mat-prices', {size: size}, function(data, response) {
      //    if (response == 'success') {
      //      $price_display.text(data);
      //    };
      //  });
      // }
    	    
			// get initial price
			// TODO -- logic for making the initial price display the next highest size if lower sizes are out of stock
			// get_price_display('med'); 
			
			// enable price display change depending on size      		 
			$('input[name="size"]').click(function() {
				var size = $(this).val();  
				get_price_display(size);     				
			});
			
			// enable photo change depending on color
			var $mat_pic = $('#main-content.buy img');
			var $pic_link = $('#main-content.buy .enlarge a');
			$('input[name="color"]').click(function() {
				var color = $(this).val();
				var thumb_src, img_src;
				switch(color) {
					case 'green':
						thumb_src = "/images/buynow_mat_green.jpg";
						img_src = "/images/buynow_large_green.jpg";
						break;
					default:
						thumb_src = "/images/buynow_mat.jpg";
						img_src = "/images/buynow_large_purple.jpg";						
				}
				$mat_pic.attr('src', thumb_src);
				$pic_link.attr('href', img_src);
			});
			
			// lightbox
		   	$('#main-content.buy .enlarge a').lightBox(YM.Shared.Lightbox.options);
			
			// new get price for new catalog / display pages 5.14.2010
		 /*
 $('#catalog select').change(function() {		CHANGED_THIS
		    var $price_display = $(this).parent().parent().find('h4');
		    var size = $(this).val();
		    $.get('/mat-prices', {size: size}, function(data, response) {
					if (response == 'success') {
					  $price_display.text(data);
					  return false;
					} else {
					  return false;
					}
				});		    	    
		  });
*/
		  
		  
		  // VERY kludgy way to 'disable' select options in IE6 & 7
		  // http://www.goodercode.com/wp/disable-select-options-internet-explorer-jquery/
		  $('option[disabled]').css({'color': '#999999'});
		  $('select').change(function() {
		    if (this.options[this.selectedIndex].disabled) {
		      if (this.options.length == 0) {
		        this.selectedIndex = -1;
		      } else {
		        this.selectedIndex--;
		      }
		      $(this).trigger('change');
		    }
		  });
		  $('select').each(function(index) {
		    if (this.options[this.selectedIndex].disabled) {
		      this.onchange();
		    };
		  });
		}
	},
	
	details: {
	  
	  init: function() {
	    
	    // price display changes with radio click event
		/* CHANGED THIS
	$('#catalog-details input[type="radio"]').click(function() {
		    var $price_display = $(this).parent().parent().parent().find('h4');
		    var size = $(this).val();
		    $.get('/mat-prices', {size: size}, function(data, response) {
					if (response == 'success') {
					  return $price_display.text(data);
					} else {
					  return false;
					}
				});
			});
*/
			
	    // determine proper price display based on which radio button is clicked
	    var $initial_radio = $('#catalog-details input[type="radio"]:checked');
	    console.info($initial_radio);
	    $initial_radio.click();			
			
		 	// disable radio buttons for out of stock variants
			// each time the user selects a color radio button, make an AJAX request to determine which variants are in stock
			// for each variant that's out of stock, disable the radio buttons			
      // function check_availability(color) {
      //  $.getJSON('/in-stock', {color: color}, function(data, response) {
      //    if (response == "success") {
      //      $.each(data, function(index, value) {
      //        $('input[type="radio"][value="' + value[0] + '"]').attr('disabled', value[1]);
      //      });
      //    };
      //  });
      //  
      // }
      // var $color = $('input[type="hidden"]').val();
      // check_availability($color);      
	  }
	},
	
	cart: { 
		
		init: function() {
			// remove the JS message
			$('.js-required').hide();   
			
			// reset order confirmed cookie
			YM.Shared.Cookies.reset_order();	
		}, 
		
		items: function() {       		
			// set the shipping select menu at the proper rate
			var $shipping_select = $('#cart select[name="shipping"]');
			var get_random_number = function() {
				return Math.floor(Math.random() * 1000001);
			};    
			$.get('/get-shipping/' + get_random_number(), function(data) {
			   $shipping_select.val(data); 
			});			
			
			
			// modify shipping costs
			var $grand_total = $('#cart tr.total td.price strong'); 
			
			$shipping_select.change(function() {
				var shipping_id = $(this).val();
				$.post('/post-shipping', {shipping_id: shipping_id}, function(data) {
					$grand_total.text(data);
					get_coupon();
				});
			});
			
	 		// add proper checkout links  
			var $checkout_link = $('#actions a.checkout');
			$checkout_link.attr('href', '/checkout/start');
			var $ppe_link = $('#actions a.ppe');
			$ppe_link.attr('href', '/checkout/paypal-express');
			
			
			// get coupon data on load 
			var $coupon = $('input[name="coupon"]');
			var $coupon_row = $('#coupon-row');
			var $coupon_apply = $('input[name="apply-coupon"]');
			var $discount = $('#coupon-row .price');
			var $description = $('#coupon-row .description');
	 		var $coupon_code = $('#coupon-row span');
						
			var get_coupon = function() {
				$.getJSON('/coupon/' + get_random_number(), function(data) {
				   	$discount.text(data[0]);
					$description.text(data[1]);
					$coupon_code.text(data[2]); 
				});
			};
			get_coupon();
			
			
			// coupon AJAX call
			$coupon_apply.click(function() {
				var coupon_code = $.trim($coupon.val());     			
				var data = {code: coupon_code};
				$.post('/coupon', data, function(data) {
					clear_coupon(); 
					if (data[0]) {
					  	$discount.text(data[1]);
						$description.text(data[2]);
						$coupon_code.text(data[3]);  
					} else {
						$message = $('<span></span>').addClass('required')
						             .css({
										position: 'absolute',
										fontStyle: 'italic'
									}).text(data[1]);
						$coupon.after($message).css({
						   border: '1px dotted #f00' 
						});
						clear_coupon_row();
					};
					$shipping_select.change();
				}, 'json');
			});
			
			
			$coupon.focus(function() {
				clear_coupon();
			});
			
			var clear_coupon = function() {
				$('#coupon-code .required').remove();
				$coupon.css('border', '1px solid #fff');
			};
			
			var clear_coupon_row = function() {
				$discount.text('-$0.00');
				$description.text('n/a');
			};
			
			// gift logic
			// $gift_checkbox = $('input[name="send_as_gift"]');
			// $gift_area = $('#gift_area');
			// $gift_textarea = $('#gift_area textarea');
			// $gift_msg_button = $('#gift_area button');
			// $gift_row = $('#gift-row');
			// $gift_total = $('#gift-total');     
			
			// changed event from 'change' to 'click' for IE compat
			//  			$gift_checkbox.click(function() {
			//  				if ($(this).attr('checked')) {
			// 		$gift_area.show(); 		  
			// 		data = {gift: true};
			// 		post_gift(data, function() {
			// 			$gift_row.show();
			// 		});   
			// 	} else {
			// 		$gift_area.hide();
			// 		data = {gift: false};
			// 		post_gift(data, function() {
			// 			$gift_row.hide();
			// 		});
			// 	};
			//  			});
			// 
			// var get_gift = function() {
			// 	$.getJSON('/gift/' + get_random_number(), function(data) {
			// 		$gift_total.text(data);
			// 		if (data == '$0.00') {                   
			// 			$gift_checkbox.attr('checked', false);
			// 			$gift_area.hide();
			// 			$gift_row.hide();
			// 		} else { 
			// 			$gift_checkbox.attr('checked', true);
			// 			$gift_area.show();
			// 			$gift_row.show();
			// 		};
			// 	});				
			// };
			// get_gift();   
			
			// gift message 'validation'
			// $gift_textarea.textlimit('span.counter', 200);			
			// $gift_textarea.charCount({
			// 	allowed: 200
			// });   
			
						
			// var post_gift = function(data, callback) {
			// 	$.post('/gift', data, function(data) {
			// 	   	$shipping_select.change();
			// 	   	$gift_total.text(data[0]);
			// 	    get_gift();
			// 	  	callback();
			// 	});				
			// };
			// 
			// 		    var post_gift_msg = function(data) {
			// 	$.post('/gift-msg', data, function(data) {
			// 	});
			// 		    };          

			
			// gift msg autosave
			// $gift_textarea.typeWatch({
			// 	callback: function() {
			// 		// gift message validation
			// 		var text = $gift_textarea.val();
			// 		var regex = /^[a-z-!;:?.,()'\"\s\d]+$/i;
			// 		if (!text.match(regex)) {
			// 			$('label.error').remove();  
			// 			var error_label = $('<label class="error">Only letters, numbers, spaces and standard punctuation, please.</label>');
			// 			$('span.counter').after(error_label);
			// 			$gift_textarea.addClass('error');
			// 		} else {
			// 			$('label.error').remove();
			// 			$gift_textarea.removeClass('error');
			// 			var data = {gift_msg: $gift_textarea.val()};
			// 			post_gift_msg(data);
			// 		}
			// 		return false;
			// 	}
			// });  
		}
	},
	
	checkout_address: {
		init: function() { 
			// check if order confirmed
			YM.Shared.Cookies.order_confirmed();			
			
			// copy billing address to shipping address
			var $billing_shipping = $('input[name="billing_shipping"]');
			$billing_shipping.click(function() {
				if ($(this).is(':checked')) { 
					$('input[name*="shipping_"]').each(function(index) { 
						var name = $(this).attr('name');
						var billing_name = name.replace('shipping_', 'billing_');  
						var billing_val = $('input[name="' + billing_name + '"]').val();
						$(this).val(billing_val);
					});
					$('select[name*="shipping_"]').each(function(index) { 
						var name = $(this).attr('name');
						var billing_name = name.replace('shipping_', 'billing_');  
						var billing_val = $('select[name="' + billing_name + '"]').val();
						$(this).val(billing_val);
					});
	
					validate_address_form();
  
				} else {
					$('input[name*="shipping_"]').each(function(index) {
						$(this).val("");
					});
					$('select[name*="shipping_"]').each(function(index) {
						$(this).val("");
					});
				}
			});
			
			// handle sticky address form fields
			var $address_submit = $('input[type="submit"]');
			var $text_inputs = $('input[type="text"]');
			var $selects = $('select');			
                           
			$address_submit.click(function() {
				$text_inputs.each(function(index) {
					$(this).cookify();
				});
				$selects.each(function(index) {
					$(this).cookify();
				});
			});
			
			if ($.cookies.get()) {
				$text_inputs.each(function(index) {
					$(this).cookieFill();
				});
				$selects.each(function(index) {
					$(this).cookieFill();
				});
			};     
			
			// validate the address form
			jQuery.validator.addMethod("postalcode", function(postalcode, element) {
			// 	return this.optional(element) || postalcode.match(/(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXYabceghjklmnpstvxy]{1}\d{1}[A-Za-z]{1} ?\d{1}[A-Za-z]{1}\d{1})$/);
			// }, "Please specify a valid zip code.");
				return this.optional(element) || postalcode.match(/(^\d{5}(-\d{4})?$)/);
			}, "Please specify a valid zip code."); 
			
			jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
			    phone_number = phone_number.replace(/\s+/g, ""); 
				return this.optional(element) || phone_number.length > 9 &&
					phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})[-.]?[2-9]\d{2}[-.]?\d{4}$/);
			}, "Please specify a valid phone number.");
			
			jQuery.validator.addMethod("AK_HI", function(state, element) {
				return this.optional(element) || !state.match(/^AK|HI$/);
			}, "Please call (508) 403-0505 for sales to Alaska or Hawaii.");
			
			
			function validate_address_form() { 
				$('#checkout').validate({
					rules: {
						'customer[billing_first_name]': {
							required: true,
							maxlength: 40
						},
						'customer[billing_last_name]': {
							required: true,
							maxlength: 40						
						},
						'customer[billing_address_1]': {
							required: true,
							maxlength: 40						
						},
						'customer[billing_city]': {
							required: true,
							maxlength: 40						
						},
						'customer[billing_state]': {
							required: true,
							AK_HI: true					
						},
						'customer[billing_zip]': {
							required: true,
							maxlength: 10,
							postalcode: true  					
						},
						'customer[billing_country]': {
							required: true						
						},
						'customer[billing_phone]': {
							required: true,
							maxlength: 20,
							phoneUS: true						
						},
						'customer[email]': {
	 						required: true,
							maxlength: 255,
							email: true   					
						},
						'customer[shipping_first_name]': {
							required: true,
							maxlength: 40						
						},
						'customer[shipping_last_name]': {
							required: true,
							maxlength: 40						
						},
						'customer[shipping_address_1]': {
							required: true,
							maxlength: 40						
						},
						'customer[shipping_city]': {
							required: true,
							maxlength: 40						
						},
						'customer[shipping_state]': {
							required: true,
							AK_HI: true				
						},
						'customer[shipping_zip]': {
							required: true,
							maxlength: 10,
							postalcode: true 					
						},
						'customer[shipping_country]': {
							required: true 					
						},
						'customer[shipping_phone]': {
							required: true,
							maxlength: 20,
							phoneUS: true						
						}					
					},
					messages: {
						'customer[billing_first_name]': {
							required: "Please enter your first name."         
						},
						'customer[billing_last_name]': {
							required: "Please enter your last name."         						
						},
						'customer[billing_address_1]': {
							required: "Please enter your billing street address." 
						},
						'customer[billing_city]': {
							required: "Please enter your billing city."  						
						},
						'customer[billing_state]': {
							required: "Please enter your billing state or province."
						},
						'customer[billing_zip]': {
							required: "Please enter your billing zip code."
						},
						'customer[billing_country]': {
							required: "Please enter your billing city."  						
						},
						'customer[billing_phone]': {
							required: "Please enter your billing phone number."
						},
						'customer[email]': {
							required: "Please enter your email address.",
							email: "Please enter a valid email address."
						},
						'customer[shipping_first_name]': {
							required: "Please enter the shipping first name."   						
						},
						'customer[shipping_last_name]': {
							required: "Please enter the shipping last name."
						},
						'customer[shipping_address_1]': {
							required: "Please enter the shipping street address."
						},
						'customer[shipping_city]': {
							required: "Please enter the shipping city."
						},
						'customer[shipping_state]': {
							required: "Please enter the shipping state or province."
						},
						'customer[shipping_zip]': {
							required: "Please enter the shipping zip code."
						},
						'customer[shipping_country]': {
							required: "Please enter the shipping country."
						},
						'customer[shipping_phone]': {
							required: "Please enter the shipping phone number."
						}					                                     
					}
				});   			
			}
			validate_address_form();		   
		}
	},
	
	checkout_pay: {
		init: function() { 
			// check if order confirmed
			YM.Shared.Cookies.order_confirmed();
			
			
			// CVV2 popup
			var $cvv = $('#cvv');
			// var $cvv_html = '<p>The <span>Card Verification Number</span> is a 3 or 4 digit code found on your credit card. We are requesting it as an added security precaution.</p><img src="/images/cc_logos/ccv2-275x108px.jpg" alt="CCV2"/>';
			// $cvv.bt($cvv_html, { 
			// 	fill: '#fff',
			// 	positions: 'right',
			// 	shadow: true,
			// 	shadowBlur: 8,
			// 	strokeStyle: '#999',
			// 	width: '275px'
			// });   
			$cvv.click(function() {
				return false;
			});

			// credit card info animation  
			// COMMENTED OUT FOR NO_PPE BRANCH!!!
			var $cc_radio = $('#checkout .paypal-cc input[value="credit_card"]');
			var $pp_radio = $('#checkout .paypal-cc input[value="paypal"]');
			var $payment_radios = $('#checkout .paypal-cc input[name="payment_method"]'); 
			var $cc_info = $('#checkout #credit-card-info');
			var $ppe = $('#checkout #place-order a.ppe');
			var $cc_submit = $('#checkout #place-order .img-button');
			// if ($cc_radio.is(':checked')) {
			// 	$cc_info.show();
			// 	$cc_submit.show();
			// } else {
			// 	$ppe.show();
			// };   
			$payment_radios.click(function() {
				if ($cc_radio.is(':checked')) {
					$cc_info.show();
					$cc_submit.show();
					$ppe.hide();
				} else {
					$cc_info.hide();
					$cc_submit.hide();
					$ppe.show();
				};
			});   
			
			// validate form
			$('#checkout').validate({
				rules: {
					// payment_option: {
					// 	required: true
					// },    
					'cc[type]': {
						required: true
					},
					'cc[number]': {
						required: true,
						// creditcard: true 
						creditcard2: function() {
							// cc type values for creditcard2 rule must be: amex, discover, mastercard, visa
							cc_type = $('select[name="cc[type]"]').val();
							mapped_cc_type = cc_type;
							if (cc_type == 'american_express') {
								mapped_cc_type = 'amex';
							};                          
							if (cc_type == 'master') {
								mapped_cc_type = 'mastercard';
							};  
							return mapped_cc_type; 
						}            
					},
					'cc[verification_value]': {
						required: true,
						digits: true,
						rangelength: [3, 4]
					},
					'cc[month]': {
						required: true
					},
					'cc[year]': {
						required: true
					}
				},
				messages: {
					// payment_option: {
					// 	required: "Please select a payment option."
					// },   
					'cc[type]': {
						required: "Please choose your credit card issuer."
					},
					'cc[number]': {
						required: "Please enter your credit card number.",
						creditcard2: "Please enter a valid credit card number."
					},
					'cc[verification_value]': {
						required: "Please enter your card verification value.",
						digits: "Your card verification value must only consist of digits.",
						rangelength: "Your card verification value can be only 3 or 4 digits."
					},
					'cc[month]': {
						required: "Please select the date your card expires."
					},
					'cc[year]': {
						required: "Please select the date your card expires."
					}
				}
			});
			
			var creditcard2_counter = 0;
			
			$('select[name="cc[type]"]').change(function() { 
				if (creditcard2_counter > 0) {
					$('#checkout').validate().element('input[name="cc[number]"]');					
				};
				creditcard2_counter += 1;
			});   
		}
	},
		
	ppe_checkout_pay: {
		
		init: function() {
			// check if order confirmed
			YM.Shared.Cookies.order_confirmed();			
		}
	},
	
	order_confirmation: {
		
		init: function() {
			$.cookies.set('order_confirmed', 'true');
		}
	},
	
	admin: {
		general: {
			init: function() {
				$('input[name$="date]"]').datepicker({
					dateFormat: 'yy-mm-dd'
				});
			}			
		},
		coupons: {
        	init: function() {}
		},
		
		press: {
			init: function() {},
			order: function() {
			  // enable sortable functionality
				$('#sortable').sortable({
					stop: function(event, ui) {
            $('option').each(function(index) {
              $(this).text(index + 1);
            });
					},
					cursor: 'pointer'
				});
				$('#sortable').disableSelection();
				
				// submit functionality
				$('form').submit(function() {
          // create array
          var new_order = [];
          // loop through each li, putting the id and order in a sub-array
          $('#sortable li').each(function(index) {
            var subarray = [];
            var order_number = $('select:eq(index)').text();
            var press_id = $('input:eq(index)').val();
            subarray.push(press_id);
            new_order.push(subarray);
          });
          console.info(new_order);
				  return false;
				});
			}
		},
		
		shipping: {
			init: function() {}
		}
	},
	
	Shared: {
		
		Tabs: {
			init: function() {
				var $tabs = $('#tabs li a');
				var $container = $('.tabs');
				var $divs = $('.tabs > div');
				var subpage = YM.Shared.Tabs.get_tab_path(location.pathname);

				// logic for hiding/showing divs
				$divs.hide();
        if (subpage) {
	        $('#' + subpage).show();
				} else {
					$divs.eq(0).show(); 
				}; 
				
				// logic for selecting/unselecting navs 
				make_selected = function(href) {      
					$tabs.removeClass('selected');
					if (href) {
						$tabs.filter('[href*=' + href + ']').addClass('selected');   	
					} else {
						$tabs.eq(0).addClass('selected');
					};
				};
				make_selected(subpage);
		  
			},
			
			get_tab_path: function(pathname) {
			   	var tab_regex = /^.+\/(.+)$/;
				var path_match = pathname.substr(0, (pathname.length - 11)).match(tab_regex);
				if (path_match) {
					return path_match[1];
				}
				return false; 
			}
		},
		
		Nav: {
			make_selected: function(page) {
				$('#nav li a').removeClass('selected');
				// ie6 workaround
				$('#nav li a').each(function(i) {
				   $(this).get(0).className == $(this).get(0).className.replace(/\b\w+_selected\b/g, '');
				});
				$('#nav li a.' + page).addClass('selected').addClass(page + '_selected');
			}
		},
		
		Lightbox: {
			options: {
				imageLoading: '/images/lightbox/lightbox-ico-loading.gif',
				imageBtnClose: '/images/lightbox/lightbox-btn-close.gif',
				imageBtnPrev: '/images/lightbox/lightbox-btn-prev.gif',
				imageBtnNext: '/images/lightbox/lightbox-btn-next.gif'
			}
		},
		
		Cookies: {
			order_confirmed: function() {
				// check if order confirmed
				if ($.cookies.get('order_confirmed')) {
					var base_url = location.host;
					window.location = "http://" + base_url + "/sorry";
				};
			},
			
			reset_order: function() {
				if ($.cookies.get('order_confirmed')) {
					$.cookies.del('order_confirmed');
				};
			}
		}
	}
};
/*
 * jQuery Form Plugin
 * version: 2.17 (06-NOV-2008)
 * @requires jQuery v1.2.2 or later
 *
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id$
 */
;(function($) {

/*
    Usage Note:  
    -----------
    Do not use both ajaxSubmit and ajaxForm on the same form.  These
    functions are intended to be exclusive.  Use ajaxSubmit if you want
    to bind your own submit handler to the form.  For example,

    $(document).ready(function() {
        $('#myForm').bind('submit', function() {
            $(this).ajaxSubmit({
                target: '#output'
            });
            return false; // <-- important!
        });
    });

    Use ajaxForm when you want the plugin to manage all the event binding
    for you.  For example,

    $(document).ready(function() {
        $('#myForm').ajaxForm({
            target: '#output'
        });
    });
        
    When using ajaxForm, the ajaxSubmit function will be invoked for you
    at the appropriate time.  
*/

/**
 * ajaxSubmit() provides a mechanism for immediately submitting 
 * an HTML form using AJAX.
 */
$.fn.ajaxSubmit = function(options) {
    // fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
    if (!this.length) {
        log('ajaxSubmit: skipping submit process - no element selected');
        return this;
    }

    if (typeof options == 'function')
        options = { success: options };

    options = $.extend({
        url:  this.attr('action') || window.location.toString(),
        type: this.attr('method') || 'GET'
    }, options || {});

    // hook for manipulating the form data before it is extracted;
    // convenient for use with rich editors like tinyMCE or FCKEditor
    var veto = {};
    this.trigger('form-pre-serialize', [this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
        return this;
    }

    // provide opportunity to alter form data before it is serialized
    if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
        log('ajaxSubmit: submit aborted via beforeSerialize callback');
        return this;
    }    
   
    var a = this.formToArray(options.semantic);
    if (options.data) {
        options.extraData = options.data;
        for (var n in options.data) {
          if(options.data[n] instanceof Array) {
            for (var k in options.data[n])
              a.push( { name: n, value: options.data[n][k] } )
          }  
          else
             a.push( { name: n, value: options.data[n] } );
        }
    }

    // give pre-submit callback an opportunity to abort the submit
    if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
        log('ajaxSubmit: submit aborted via beforeSubmit callback');
        return this;
    }    

    // fire vetoable 'validate' event
    this.trigger('form-submit-validate', [a, this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
        return this;
    }    

    var q = $.param(a);

    if (options.type.toUpperCase() == 'GET') {
        options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
        options.data = null;  // data is null for 'get'
    }
    else
        options.data = q; // data is the query string for 'post'

    var $form = this, callbacks = [];
    if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
    if (options.clearForm) callbacks.push(function() { $form.clearForm(); });

    // perform a load on the target only if dataType is not provided
    if (!options.dataType && options.target) {
        var oldSuccess = options.success || function(){};
        callbacks.push(function(data) {
            $(options.target).html(data).each(oldSuccess, arguments);
        });
    }
    else if (options.success)
        callbacks.push(options.success);

    options.success = function(data, status) {
        for (var i=0, max=callbacks.length; i < max; i++)
            callbacks[i].apply(options, [data, status, $form]);
    };

    // are there files to upload?
    var files = $('input:file', this).fieldValue();
    var found = false;
    for (var j=0; j < files.length; j++)
        if (files[j])
            found = true;

    // options.iframe allows user to force iframe mode
   if (options.iframe || found) { 
       // hack to fix Safari hang (thanks to Tim Molendijk for this)
       // see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
       if ($.browser.safari && options.closeKeepAlive)
           $.get(options.closeKeepAlive, fileUpload);
       else
           fileUpload();
       }
   else
       $.ajax(options);

    // fire 'notify' event
    this.trigger('form-submit-notify', [this, options]);
    return this;


    // private function for handling file uploads (hat tip to YAHOO!)
    function fileUpload() {
        var form = $form[0];
        
        if ($(':input[@name=submit]', form).length) {
            alert('Error: Form elements must not be named "submit".');
            return;
        }
        
        var opts = $.extend({}, $.ajaxSettings, options);
		var s = jQuery.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);

        var id = 'jqFormIO' + (new Date().getTime());
        var $io = $('<iframe id="' + id + '" name="' + id + '" />');
        var io = $io[0];

        if ($.browser.msie || $.browser.opera) 
            io.src = 'javascript:false;document.write("");';
        $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });

        var xhr = { // mock object
            aborted: 0,
            responseText: null,
            responseXML: null,
            status: 0,
            statusText: 'n/a',
            getAllResponseHeaders: function() {},
            getResponseHeader: function() {},
            setRequestHeader: function() {},
            abort: function() { 
                this.aborted = 1; 
                $io.attr('src','about:blank'); // abort op in progress
            }
        };

        var g = opts.global;
        // trigger ajax global events so that activity/block indicators work like normal
        if (g && ! $.active++) $.event.trigger("ajaxStart");
        if (g) $.event.trigger("ajaxSend", [xhr, opts]);

		if (s.beforeSend && s.beforeSend(xhr, s) === false) {
			s.global && jQuery.active--;
			return;
        }
        if (xhr.aborted)
            return;
        
        var cbInvoked = 0;
        var timedOut = 0;

        // add submitting element to data if we know it
        var sub = form.clk;
        if (sub) {
            var n = sub.name;
            if (n && !sub.disabled) {
                options.extraData = options.extraData || {};
                options.extraData[n] = sub.value;
                if (sub.type == "image") {
                    options.extraData[name+'.x'] = form.clk_x;
                    options.extraData[name+'.y'] = form.clk_y;
                }
            }
        }

        // take a breath so that pending repaints get some cpu time before the upload starts
        setTimeout(function() {
            // make sure form attrs are set
            var t = $form.attr('target'), a = $form.attr('action');
            $form.attr({
                target:   id,
                method:   'POST',
                action:   opts.url
            });
            
            // ie borks in some cases when setting encoding
            if (! options.skipEncodingOverride) {
                $form.attr({
                    encoding: 'multipart/form-data',
                    enctype:  'multipart/form-data'
                });
            }

            // support timout
            if (opts.timeout)
                setTimeout(function() { timedOut = true; cb(); }, opts.timeout);

            // add "extra" data to form if provided in options
            var extraInputs = [];
            try {
                if (options.extraData)
                    for (var n in options.extraData)
                        extraInputs.push(
                            $('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
                                .appendTo(form)[0]);
            
                // add iframe to doc and submit the form
                $io.appendTo('body');
                io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
                form.submit();
            }
            finally {
                // reset attrs and remove "extra" input elements
                $form.attr('action', a);
                t ? $form.attr('target', t) : $form.removeAttr('target');
                $(extraInputs).remove();
            }
        }, 10);

        function cb() {
            if (cbInvoked++) return;
            
            io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);

            var operaHack = 0;
            var ok = true;
            try {
                if (timedOut) throw 'timeout';
                // extract the server response from the iframe
                var data, doc;

                doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
                
                if (doc.body == null && !operaHack && $.browser.opera) {
                    // In Opera 9.2.x the iframe DOM is not always traversable when
                    // the onload callback fires so we give Opera 100ms to right itself
                    operaHack = 1;
                    cbInvoked--;
                    setTimeout(cb, 100);
                    return;
                }
                
                xhr.responseText = doc.body ? doc.body.innerHTML : null;
                xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
                xhr.getResponseHeader = function(header){
                    var headers = {'content-type': opts.dataType};
                    return headers[header];
                };

                if (opts.dataType == 'json' || opts.dataType == 'script') {
                    var ta = doc.getElementsByTagName('textarea')[0];
                    xhr.responseText = ta ? ta.value : xhr.responseText;
                }
                else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
                    xhr.responseXML = toXml(xhr.responseText);
                }
                data = $.httpData(xhr, opts.dataType);
            }
            catch(e){
                ok = false;
                $.handleError(opts, xhr, 'error', e);
            }

            // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
            if (ok) {
                opts.success(data, 'success');
                if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
            }
            if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
            if (g && ! --$.active) $.event.trigger("ajaxStop");
            if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');

            // clean up
            setTimeout(function() {
                $io.remove();
                xhr.responseXML = null;
            }, 100);
        };

        function toXml(s, doc) {
            if (window.ActiveXObject) {
                doc = new ActiveXObject('Microsoft.XMLDOM');
                doc.async = 'false';
                doc.loadXML(s);
            }
            else
                doc = (new DOMParser()).parseFromString(s, 'text/xml');
            return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
        };
    };
};

/**
 * ajaxForm() provides a mechanism for fully automating form submission.
 *
 * The advantages of using this method instead of ajaxSubmit() are:
 *
 * 1: This method will include coordinates for <input type="image" /> elements (if the element
 *    is used to submit the form).
 * 2. This method will include the submit element's name/value data (for the element that was
 *    used to submit the form).
 * 3. This method binds the submit() method to the form for you.
 *
 * The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
 * passes the options argument along after properly binding events for submit elements and
 * the form itself.
 */ 
$.fn.ajaxForm = function(options) {
    return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
        $(this).ajaxSubmit(options);
        return false;
    }).each(function() {
        // store options in hash
        $(":submit,input:image", this).bind('click.form-plugin',function(e) {
            var form = this.form;
            form.clk = this;
            if (this.type == 'image') {
                if (e.offsetX != undefined) {
                    form.clk_x = e.offsetX;
                    form.clk_y = e.offsetY;
                } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
                    var offset = $(this).offset();
                    form.clk_x = e.pageX - offset.left;
                    form.clk_y = e.pageY - offset.top;
                } else {
                    form.clk_x = e.pageX - this.offsetLeft;
                    form.clk_y = e.pageY - this.offsetTop;
                }
            }
            // clear form vars
            setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 10);
        });
    });
};

// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
    this.unbind('submit.form-plugin');
    return this.each(function() {
        $(":submit,input:image", this).unbind('click.form-plugin');
    });

};

/**
 * formToArray() gathers form element data into an array of objects that can
 * be passed to any of the following ajax functions: $.get, $.post, or load.
 * Each object in the array has both a 'name' and 'value' property.  An example of
 * an array for a simple login form might be:
 *
 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
 *
 * It is this array that is passed to pre-submit callback functions provided to the
 * ajaxSubmit() and ajaxForm() methods.
 */
$.fn.formToArray = function(semantic) {
    var a = [];
    if (this.length == 0) return a;

    var form = this[0];
    var els = semantic ? form.getElementsByTagName('*') : form.elements;
    if (!els) return a;
    for(var i=0, max=els.length; i < max; i++) {
        var el = els[i];
        var n = el.name;
        if (!n) continue;

        if (semantic && form.clk && el.type == "image") {
            // handle image inputs on the fly when semantic == true
            if(!el.disabled && form.clk == el)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
            continue;
        }

        var v = $.fieldValue(el, true);
        if (v && v.constructor == Array) {
            for(var j=0, jmax=v.length; j < jmax; j++)
                a.push({name: n, value: v[j]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: n, value: v});
    }

    if (!semantic && form.clk) {
        // input type=='image' are not found in elements array! handle them here
        var inputs = form.getElementsByTagName("input");
        for(var i=0, max=inputs.length; i < max; i++) {
            var input = inputs[i];
            var n = input.name;
            if(n && !input.disabled && input.type == "image" && form.clk == input)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
        }
    }
    return a;
};

/**
 * Serializes form data into a 'submittable' string. This method will return a string
 * in the format: name1=value1&amp;name2=value2
 */
$.fn.formSerialize = function(semantic) {
    //hand off to jQuery.param for proper encoding
    return $.param(this.formToArray(semantic));
};

/**
 * Serializes all field elements in the jQuery object into a query string.
 * This method will return a string in the format: name1=value1&amp;name2=value2
 */
$.fn.fieldSerialize = function(successful) {
    var a = [];
    this.each(function() {
        var n = this.name;
        if (!n) return;
        var v = $.fieldValue(this, successful);
        if (v && v.constructor == Array) {
            for (var i=0,max=v.length; i < max; i++)
                a.push({name: n, value: v[i]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: this.name, value: v});
    });
    //hand off to jQuery.param for proper encoding
    return $.param(a);
};

/**
 * Returns the value(s) of the element in the matched set.  For example, consider the following form:
 *
 *  <form><fieldset>
 *      <input name="A" type="text" />
 *      <input name="A" type="text" />
 *      <input name="B" type="checkbox" value="B1" />
 *      <input name="B" type="checkbox" value="B2"/>
 *      <input name="C" type="radio" value="C1" />
 *      <input name="C" type="radio" value="C2" />
 *  </fieldset></form>
 *
 *  var v = $(':text').fieldValue();
 *  // if no values are entered into the text inputs
 *  v == ['','']
 *  // if values entered into the text inputs are 'foo' and 'bar'
 *  v == ['foo','bar']
 *
 *  var v = $(':checkbox').fieldValue();
 *  // if neither checkbox is checked
 *  v === undefined
 *  // if both checkboxes are checked
 *  v == ['B1', 'B2']
 *
 *  var v = $(':radio').fieldValue();
 *  // if neither radio is checked
 *  v === undefined
 *  // if first radio is checked
 *  v == ['C1']
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If this value is false the value(s)
 * for each element is returned.
 *
 * Note: This method *always* returns an array.  If no valid value can be determined the
 *       array will be empty, otherwise it will contain one or more values.
 */
$.fn.fieldValue = function(successful) {
    for (var val=[], i=0, max=this.length; i < max; i++) {
        var el = this[i];
        var v = $.fieldValue(el, successful);
        if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
            continue;
        v.constructor == Array ? $.merge(val, v) : val.push(v);
    }
    return val;
};

/**
 * Returns the value of the field element.
 */
$.fieldValue = function(el, successful) {
    var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
    if (typeof successful == 'undefined') successful = true;

    if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
        (t == 'checkbox' || t == 'radio') && !el.checked ||
        (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
        tag == 'select' && el.selectedIndex == -1))
            return null;

    if (tag == 'select') {
        var index = el.selectedIndex;
        if (index < 0) return null;
        var a = [], ops = el.options;
        var one = (t == 'select-one');
        var max = (one ? index+1 : ops.length);
        for(var i=(one ? index : 0); i < max; i++) {
            var op = ops[i];
            if (op.selected) {
                // extra pain for IE...
                var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
                if (one) return v;
                a.push(v);
            }
        }
        return a;
    }
    return el.value;
};

/**
 * Clears the form data.  Takes the following actions on the form's input fields:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 */
$.fn.clearForm = function() {
    return this.each(function() {
        $('input,select,textarea', this).clearFields();
    });
};

/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function() {
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (t == 'text' || t == 'password' || tag == 'textarea')
            this.value = '';
        else if (t == 'checkbox' || t == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};

/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 */
$.fn.resetForm = function() {
    return this.each(function() {
        // guard against an input with the name of 'reset'
        // note that IE reports the reset function as an 'object'
        if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
            this.reset();
    });
};

/**
 * Enables or disables any matching elements.
 */
$.fn.enable = function(b) { 
    if (b == undefined) b = true;
    return this.each(function() { 
        this.disabled = !b 
    });
};

/**
 * Checks/unchecks any matching checkboxes or radio buttons and
 * selects/deselects and matching option elements.
 */
$.fn.selected = function(select) {
    if (select == undefined) select = true;
    return this.each(function() { 
        var t = this.type;
        if (t == 'checkbox' || t == 'radio')
            this.checked = select;
        else if (this.tagName.toLowerCase() == 'option') {
            var $sel = $(this).parent('select');
            if (select && $sel[0] && $sel[0].type == 'select-one') {
                // deselect all other options
                $sel.find('option').selected(false);
            }
            this.selected = select;
        }
    });
};

// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
    if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
        window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};

})(jQuery);


$(document).ready(function(){

	var hovconfig = {
	
		interval:100,
		over:function(){
			$(this).find('.popthis').fadeIn();
			return false;
		},
		out:function(){
			$(this).find('.popthis').fadeOut('fast');
			return false;	
		},
		timeout:350
	
	}
	
	$('a.popup').hoverIntent(hovconfig);

});

