function popitup(url) {
	newwindow=window.open(url,'PetFlow Chat | PetFlow.com','height=768,width=1024,resizable=0');
	if (window.focus) {
		newwindow.focus();
	}
	return false;
}

$(document).ready(function(){
	var cache = [];
	// Arguments are image paths relative to the current page.
	$.preLoadImages = function() {
		var args_len = arguments.length;
		for (var i = args_len; i--;) {
			var cacheImage = document.createElement('img');
			cacheImage.src = arguments[i];
			cache.push(cacheImage);
		}
	}

	if(Petflow.page != 'explorer' && Petflow.page != 'products'){
		deleteCookie('exp-position');
	}

	// Preload images for navigation hover.
	if ($('div#navigation-links').size()) {
		$.preLoadImages(Petflow.rewriteBase + 'images/nav/nav_home_hover.png');
		$.preLoadImages(Petflow.rewriteBase + 'images/nav/nav_about_hover.png');
		$.preLoadImages(Petflow.rewriteBase + 'images/nav/nav_howitworks_hover.png');
		$.preLoadImages(Petflow.rewriteBase + 'images/nav/nav_brands_hover.png');
		$.preLoadImages(Petflow.rewriteBase + 'images/nav/nav_faq_hover.png');
		$.preLoadImages(Petflow.rewriteBase + 'images/nav/nav_shipping_hover.png');
		$.preLoadImages(Petflow.rewriteBase + 'images/nav/nav_ambassador_hover.png');

		if ($('img.navhover').size() != 0){
			$('img.navhover').imghover({suffix: '_hover'});
		}
	}
	
	if(Petflow.page == 'confirmation' || Petflow.page == 'explorer'){
		$('#cf-toys').click(function(){
			$('#cf-treats').removeClass('cf-active-tab');
			$('#cf-treats').addClass('cf-inactive-tab');
			$(this).removeClass('cf-inactive-tab');
			$(this).addClass('cf-active-tab');
		});
		$('#cf-treats').click(function(){
			$('#cf-toys').removeClass('cf-active-tab');
			$('#cf-toys').addClass('cf-inactive-tab');
			$(this).removeClass('cf-inactive-tab');
			$(this).addClass('cf-active-tab');
		})
	}
	
	// apply hints to inputs
	$('#login-content-wrapper input').ztInputHint({
		hintClass: 'input_hint'
	});
	$('#login-content-wrapper #existing-member-form input').ztInputHint({
		hintClass: 'input_hint'
	});
	$('#petflow-checkout-form #login input').ztInputHint({
		hintClass: 'input_hint'
	});
	$('#petflow-checkout-form #registration input').ztInputHint({
		hintClass: 'input_hint'
	});
	$('form#search-form input#search').ztInputHint({
		hintClass: 'input_hint'
	});


	// Anchortag scrolling.
	$('.scroll').click(function(event){
		//get the full url - like mysitecom/index.htm#home
		var full_url = this.href;

		//split the url by # and get the anchor target name - home in mysitecom/index.htm#home
		var parts = full_url.split('#');
		var trgt = parts[1];

		//get the top offset of the target anchor
		var target_offset = $('#'+trgt).offset();
		var target_top = target_offset.top;

		//goto that anchor by setting the body scroll top to anchor top
		$('html, body').animate({scrollTop:target_top}, 500);
	});

	// Swap toggle links in toggle container.
	$(".toggle a").click(function(event) {
		event.preventDefault();
		$('a', $(this).parent()).toggleClass('hide');
	});

	if (!Petflow.loggedin) {
		$('#lost-password').click(function(event){
			event.preventDefault();
			$('#login-content').addClass('hide');
			$('#forgot-content').removeClass('hide');
			$('#forgot-content').css('display', 'block');
		});
		$('#login-password').click(function(event){
			event.preventDefault();
			$('#forgot-content').addClass('hide');
			$('#login-content').removeClass('hide');
			$('#forgot-content').css('display', '');
		});

		// Expand Panel
		/*$('#login-open').click(function(event){
			event.preventDefault();
			$('#login-content-wrapper').css('display');
			$('#login-content-wrapper').slideDown('slow');
		});
		$('#login-close').click(function(event){	
			event.preventDefault();
			$('#login-content-wrapper').slideUp('slow');
			$('#forgot-content-wrapper').slideUp('slow');
		});*/
	}

	// Switch buttons for show shopping cart.
	$('#shoppinglist-toggle a.open').click(function(event){
		$('#shoppinglist').css('display');
		$('#shoppinglist').slideDown('slow');
		//TODO: no point in this unless it saves state.
	});
	$('#shoppinglist-toggle a.close').click(function(event){	
		$('#shoppinglist').slideUp('slow');
		//TODO: no point in this unless it saves state.
	});
	
	//Loads up the jQuery image slider with the dots theme (homepage, newsletter).
	if ($('#galleria').size() > 0) {
		$('#galleria').galleria();
	}

	// Update minicart on qty change.
	$('form#minicart input.mini-cart-qty').each(function(){

		var qty_id = $(this).attr('id').split('-')[3];
		var typeoptions = {
			callback:function(){
				$.ajax({
					type: 'GET',
					url: Petflow.rewriteBase + 'cart/update/' + qty_id,
					success: function(data) {
						if (data.product_total == '$0.00') {
							$('#minicart-product-row-' + qty_id).remove();
						} else {
							$('#minicart-product-row-' + qty_id + '-price').html(data.product_total);
						}
						$('form#minicart .minicart_sum span').html(data.product_count);
						$('form#minicart .line-items .cart_sub .price').html(data.subtotal);
						if(parseFloat(data.shipping) == 0 && data.subtotal != '$0.00'){
							//Free Shipping
							$('form#minicart .line-items .cart_sh').html("<div class='free-ship-wrapper' style='text-align:center;font-size:10pt;padding-top:12px;'><div class='no-fl center' style='float:none;font-weight:bold;color:green;'>Free Shipping Activated!</div><div class='no-fl center' style=''>Load up Your Cart!</div><div class='no-fl center' style='float:none;font-weight:bold;color:green;'>Everything Ships FREE!!</div></div>");
						}else if(data.subtotal == '$0.00'){
							$('form#minicart .line-items .cart_sh').html("<span class='left flat_rate'>Shipping: </span><span class='price right'>$0.00</span>");	 
						}
						else{
							//Flat Rate
							$('form#minicart .line-items .cart_sh').html("<span class='left flat_rate'>Flat-Rate Shipping: </span><span class='price right'>$4.95</span>");
						}
						//$('form#minicart .line-items .cart_sh').html(data.shipping);
						$('form#minicart .line-items .cart_tax .price').html(data.tax);
						$('form#minicart .line-items .cart_total .price').html(data.total);
					},
					dataType: 'json',
					data: {
						qty:$('input#mini-cart-qty-' + qty_id).val(),
						ajax:'1'
					}
				});
			},
			wait:750,
			highlight:true,
			captureLength:0
		}

		$(this).typeWatch(typeoptions);

	});


	if (Petflow.page == 'products') {
		// click() with if/else statement to Hide & Show Ingredients div/containter.

		$('.view_ingredients').click(function(event) {
			event.preventDefault();
			$('.product-ingredients').slideDown('slow');
		});			
		$('.hide_ingredients').click(function(event) {
			event.preventDefault();
			$('.product-ingredients').slideUp('slow');
		});			


		$(".tab-content").hide(); //Hide all content
		$("ul.tabs li:first").addClass("active").show(); //Activate first tab
		$(".tab-content:first").show(); //Show first tab content

		//On Click Event
		$("ul.tabs li").click(function() {

			$("ul.tabs li").removeClass("active"); //Remove any "active" class
			$(this).addClass("active"); //Add "active" class to selected tab
			$(".tab-content").hide(); //Hide all tab content

			var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
			$(activeTab).fadeIn(); //Fade in the active ID content
			return false;
		});
		
		$(".product-ing-tab").click(function(){
			$("#product-desc-wrapper-ing").removeClass('hide');
			$("#product-desc-wrapper").addClass('hide');
			$(".product-desc-tab").addClass('product-details-inactive');
			$(".product-ing-tab").removeClass('product-details-inactive');
			$(".product-ing-tab").addClass('product-details-active');
			$(".product-desc-tab").removeClass('product-details-active');
		});
		$(".product-desc-tab").click(function(){
			$("#product-desc-wrapper-ing").addClass('hide');
			$("#product-desc-wrapper").removeClass('hide');
			$(".product-ing-tab").addClass('product-details-inactive');
			$(".product-desc-tab").removeClass('product-details-inactive');
			$(".product-desc-tab").addClass('product-details-active');
			$(".product-ing-tab").removeClass('product-details-active');
		});
		
		
	}



	if (Petflow.page == 'userAmbassador' || Petflow.page == 'user-ambassador' || Petflow.page == 'page-user-ambassador' || Petflow.page == 'ambassador'){
		$("#uniqueBtn").mouseover(function() {
			clip = new ZeroClipboard.Client();
			clip.setHandCursor( true );
			clip.glue('uniqueBtn');
			var txt = $('input#uniqueLink ').val();

			clip.addEventListener('mouseDown',function(client){
				clip.setText(txt);
			});

			clip.addEventListener('complete', function(client, text){
				alert('Your Link:\n' + text + '\nwas copied to the clipboard.');
			});
			return false;
		});

		//Sets the input to be highlighted when the user clicks inside the in put box.
		$("input#uniqueLink").focus(function(){
			// Select input field contents
			this.select();
		});
		

		if($('a.popupwindow').size() != 0){
 			$('a.popupwindow').popupwindow();
		}


		$('#prices').click(function(){
			$('#pricesBox-wrapper').slideDown(1100);
		})
		$('.closeLink').click(function(){
			$('#pricesBox-wrapper').slideUp(1100);
			curr = 1;
		})
		$('#sendInvitations').click(function(){
			$('#ambassador_email_form').slideDown(1100);
			$('#ambassador_email_form').removeClass('hide');
			$('#ambassador_email').slideUp(600);
			$('#ambassador_balance_total').css('text-align', 'center');
			$('#ambassador_balance_total h4').css('text-align', 'center');
		});
		$('#cancelInvitations').click(function(){
			$('#ambassador_email').slideDown(400);
			$('#ambassador_email_form').addClass('hide');
			$('#ambassador_email_form').slideUp(500);
			$('#ambassador_balance_total').css('text-align', 'center');
			$('#ambassador_balance_total h4').css('text-align', 'center');
		});
		//finds the natural height of a the div, then sets the height.
		referralHeight = $('#referral_stats');
		//naturla height
		startHeight = referralHeight.height();
		//Setting start height
		//1st find out how many rows are in the table
		rowCount = $('#referral_info tr').length;
		//take the height of 1 table row and multiple by 4
		rowHeight = ($('#referral_info tr').height() * 4);
		//now set the initial height to equal at least the 1st 3 referrals.
		if (rowCount >=4){
			referralHeight.css( "height", rowHeight);
		}else{
			referralHeight = $('#referral_stats');
		}
		
		if($('referral_stats').html() == 'Start referring people today!'){
			//alert('yep');
			$('#referral_stats').css({height : startHeight});
		}else{
		
		
		currState = 0;
		
		$('#referralBtn, #showAllBtn').toggle(
			function(){
				if(currState ==1){
					$('#referralBtn').attr('src', Petflow.rewriteBase + 'images/buttons/ambassador_hideAll.gif');					
					$('#showAllBtn').html('(hide all)');					
					$('#referral_stats').css({'overflow' : 'visible'});
					$('.ambassador-referral-rows').css({'visibility' : 'visible'});
					$('#referral_stats').animate({height : startHeight}, 400);
					currState = 0;
				}
			},
			function(){
				if(currState ==0){
					$('#referralBtn').attr('src', Petflow.rewriteBase + 'images/buttons/ambassador_showAll.gif');					
					$('#showAllBtn').html('(show all)');					
					$('#referral_stats').css({'overflow' : 'hidden'});
					$('.ambassador-referral-rows').css({'visibility' : 'hidden'});
					$('#referral_stats').animate({height : 40}, 400);
					currState = 1;
				}
			}
		)};
		
		
		/*$('#referralBtn, #showAllBtn').click(function(){
			$('#referralBtn').toggle();
			$('#showAllBtn').toggle();
		});*/
		
		
	}

	if (Petflow.page == 'contact') {
		$('textarea.resizable:not(.processed)').TextAreaResizer();
	}

	if (Petflow.page == 'userPrograms') {
		$('table.order tbody tr:even').css('background', '#ddeef6');
	}

	if (Petflow.page == 'testimonials') {
//		TODO: Make this work dynamically once the testimonial admin is functioning.
//		$('.testimonial-wrapper .testimonial-bubble:odd').css('background', '#ddeef6');
	}

	if (Petflow.page == 'confirm') {
		$('.non-recurring .form-submit').css('cursor', 'default');
		$('.non-recurring .form-select').change(function(){
			if ($('.non-recurring select').val() == '-'){
				$('.non-recurring .form-submit').css('cursor', 'default');
				$('.non-recurring .form-submit').attr('disabled','disabled');
			} else {
				$('.non-recurring .form-submit').css('cursor', 'pointer');
				$('.non-recurring .form-submit').attr('disabled','');
			}
		});
	}

	var todayDate = new Date();
	//Declares holiday dates [MM,DD]
	var natDays = [ [10, 3], [10, 4], [10, 5], [11, 24], [11, 26], [12, 24], [12, 25], [12, 26], [12, 31], [1, 1], [5,30], [7,4] ];
	
	function nationalDays(date) 
	{
		for (i = 0; i < natDays.length; i++) 
		{
			if (date.getMonth() == natDays[i][0] - 1 && date.getDate() == natDays[i][1]) 
			{
				return [false, natDays[i][1]];
			}
		}
		return [true, ''];
	} 
	
	if (Petflow.page == 'checkout' || Petflow.page == 'user-checkout') {
			var theDate = new Date();
			//Add next line to set custom minimum date
			//theDate = new Date(year, monthNumeral - 1, dayNumeral);
			
			$(".datePicker").datepicker({beforeShowDay: function(date){var noWeekend=$.datepicker.noWeekends(date);if(noWeekend[0]){return nationalDays(date);}else{return noWeekend;}}, minDate:theDate, maxDate:'+16w'});
			$(".datePicker").datepicker( "option", "defaultDate", +1 );
			
			var selectmenu=document.getElementById("edit-program-start-options");
			if(selectmenu){
				selectmenu.onchange=function(){
					var choice=this.options[this.selectedIndex]
					if (choice.value!="nothing" && choice.value=="3"){
						$(".checkout-date-pick").css('display', 'block');
					}else{
						$(".checkout-date-pick").css('display', 'none');	
					}
				}
			}
			//For prescription drop down
			if ($('#vet-prescription #edit-program-prescription-agree').attr("checked") == true) {
				$('#vet-prescription #vet-vet').show();
			}
			$('#vet-prescription #edit-program-prescription-agree').change(function(){
				$('#vet-prescription #vet-vet').toggle();
			}); 
			
			$("a.tip-trigger").hover(function() {
				$(this).children(".tip").css("display", "inline");
				$(this).children(".tip").css("z-index", "15000");
			},function() {
				$(this).children(".tip").css("display", "none");
				$(this).children(".tip").css("z-index", "0");
			}); 
			
			function check(theID)
			  {
			 	 document.getElementById(theID).checked=true;
			  }
			function uncheck(theID)
			  {
			 	 document.getElementById(theID).checked=false;
			  }
			
			$("#edit-program-interval").change(function(){
				if($(this).val() == '0'){
					check('edit-program-interval-once');
				}else{
					uncheck('edit-program-interval-once');		
				}
			});
		}
		
	if (Petflow.page == 'programs' || Petflow.page == 'user-programs'){
		$(".datePicker").datepicker({beforeShowDay: function(date){var noWeekend=$.datepicker.noWeekends(date);if(noWeekend[0]){return nationalDays(date);}else{return noWeekend;}}, minDate:'+1', maxDate:'+16w'});
		$('.programs_change_del_schedule_body .custom-date-select').change(function(){
			$('.programs_change_del_schedule_body .custom-date-select option:selected').each(function(){
				var programMatcher=$(this).parent().attr('id');
				if ($(this).val() == '3'){
					$(".programs_change_del_schedule_body #" + programMatcher + "-wrapper .checkout-date-pick").css('display', 'block');
				}else if($(this).val() == '0' || $(this).val() == '1'){
					$(".programs_change_del_schedule_body #" + programMatcher + "-wrapper .checkout-date-pick").css('display', 'none');	
				}
			});
		});
		// For some reason, the code above doesn't work for this specific select element, so I kind of hacked it by putting in a bunch of conditionals
		$('.programs_change_date_body .custom-date-select').change(function(){
			$('.programs_change_date_body .custom-date-select option:selected').each(function(){
				var orderMatcher=$(this).parent().parent().parent().attr('id');
				if ($(this).val() == 'select_date' && $(this).val() != null){
					$(".programs_change_date_body " + "#" + orderMatcher + " .checkout-date-pick").css('display', 'block');
				}else if($(this).val() == '-' || $(this).val() == '+1 weeks' || $(this).val() == '+2 weeks' || $(this).val() == '+3 weeks' || $(this).val() == '+4 weeks' || $(this).val() == '-1 weeks' || $(this).val() == '-2 weeks' || $(this).val() == '-3 weeks' || $(this).val() == '-4 weeks' || $(this).val() == 'cancel'){
					$(".programs_change_date_body " + "#" + orderMatcher + " .checkout-date-pick").css('display', 'none');	
				}
			});
		});
	}
});

function deleteCookie(key){
	document.cookie = key + '=;expires=Thu, 01-Jan-1970 00:00;01 GMT;path=/'; //;domain=.petflow.com
}

