/* Fix item height on product grid view.
   Requires custom plugin jquery.equalheights.js */
$(function() {
    $('#product-grid').equalHeights('.grid-item-body');
});

$(document).ready(function() {
	if ($('#grid').length) {
		var slider = $('#grid').slider();
	}
	
	$('#SearchText').bind({
		focus: function() {
			if (this.value == this.defaultValue) {
				$(this).val('');
			}
			$(this).css({'font-style': 'normal', 'color': '#666'});
		},
		blur: function() {
			if (this.value == '') {
				$(this).val(this.defaultValue).css({'font-style': 'italic', 'color': '#9d9d9d'});
			}
		}
	});

	// clear inputs for all forms
	$('input[type="text"]').bind({
		focus: function() {
			if (this.value == this.defaultValue) {
				$(this).val('');
			}
		},
		blur: function() {
			if (this.value == '') {
				$(this).val(this.defaultValue);
			}
		}
	});
	
	// secondary navigation
	(function() {
		var $secondary_nav = $('ul.secondary-nav-items', $('div#secondary-nav')),
			$products_nav = $('ul.products-nav-items', $('div#products-nav')),
			$nav;
	
		$secondary_nav.length ? $nav = $secondary_nav : $nav = $products_nav;
		
		if ($nav) {
			// bind navigational elements
			$nav.find('li').hover(
				function() {
					if ($(this).children('ul').length) {
						$(this).children('a:first-child').addClass('hover').end().children('ul').show();
					}
				},
				function() {
					if ($(this).children('ul').length && $(this).children('ul:visible')) {
						$(this).children('a:first-child').removeClass('hover').end().children('ul').hide();
					}
				}
			);
		}
	})();
});

$(window).unload(function() {});

// clearFocus extension
// ;(function($) {
// 	$.fn.clearFocus = function() { 
// 		return this.each(function() {
// 			if ($(this).hasClass('cF-ignore')) { return false; }
// 			
// 			$('input:text', $(this)).live('focus', function() {
// 				if (this.value == this.defaultValue) {
// 					$(this).val('');
// 				}
// 			});
// 		});
// 	};
// })(jQuery);

// slider extension
;(function($) {
	$.fn.slider = function(options) {
		// set internal values
		var self = this,
			$context = $(this).find('ul:first-child'),
			page_count = $context.find('li').size(),
			page_width = parseInt($context.find('li').css('width'));
			$left_arrow = $('div#grid-arrow-left'),
			$right_arrow = $('div#grid-arrow-right');
			
		self.init = function() {
			// set context (container) width
			$context.css('width', page_count * page_width);
		
			// check count.  if greater than 1 ten show/bind prev/next buttons.
			if (page_count < 2) {
				 self.hideLeft();
				 self.hideRight();
			} else {
				self.hideLeft();
				self.showRight();
			}
			
			// set hover bindings for thumbnails
			$('div.thumbnail-container', self).hover(
				function() {
					var $thumbnail = $(this).find('div.product-thumbnail');
					$thumbnail.addClass('hover-state');
					
					var id = $thumbnail.attr('id').split('_');
					var id = id[1];

					// hide default
					$('div#detail_0').hide();
					
					if (!id) {
						id = 1;
					}
					
					// show corresponding detail
					$('div#detail_' + id).show();
				},
				function() {
					var $thumbnail = $(this).find('div.product-thumbnail');
					$thumbnail.removeClass('hover-state');

					var id = $thumbnail.attr('id').split('_');
					var id = id[1];

					// temporary
					if (!id) {
						id = 1;
					}

					// hide corresponding detail
					$('div#detail_' + id).hide();
				
					// show default
					$('div#detail_0').show();
				}			
			);
		}

		self.showLeft = function() {
			$left_arrow.find('a').unbind('click');
			$left_arrow.find('img').attr('style', 'left: -34px;');

			$left_arrow.find('a').bind({
				mouseover: function() {
					$left_arrow.find('img').attr('style', 'left: -68px;');
				},
				mouseout: function() {
					$left_arrow.find('img').attr('style', 'left: -34px;');
				},
				click: function() {
					// stop current animation and clear queue
					$context.stop(true, true);

					var current_page = self.currentPage();
					
					self.slideTo(current_page - 1);

					if ((current_page - 1) == 0) {
						self.hideLeft();
					}
					
					if ((current_page - 1) < (page_count - 1)) {
						self.showRight();
					}

					return false;
				}
			});
		}

		self.hideLeft = function() {
			$left_arrow.find('img').attr('style', 'left: 0;');
			$left_arrow.find('a').unbind('click').unbind('mouseover').unbind('mouseout').bind('click', function() {
				return false;
			});
		}

		self.showRight = function () {
			$right_arrow.find('a').unbind('click');
			$right_arrow.find('img').attr('style', 'left: -34px;');

			$right_arrow.find('a').bind({
				mouseover: function() {
					$right_arrow.find('img').attr('style', 'left: 0;');
				},
				mouseout: function() {
					$right_arrow.find('img').attr('style', 'left: -34px;');
				},
				click: function() {
					// stop current animation and clear queue
					$context.stop(true, true);

					var current_page = self.currentPage();

					self.slideTo(current_page + 1);

					if ((current_page + 1) == (page_count - 1)) {
						self.hideRight();
					}
					
					if ((current_page + 1) > 0) {
						self.showLeft();
					}

					return false;
				}
			});
		}

		self.hideRight = function() {
			$right_arrow.find('img').attr('style', 'left: -64px;');
			$right_arrow.find('a').unbind('click').unbind('mouseover').unbind('mouseout').bind('click', function() {
				return false;
			});
		}
		
		self.currentPage = function() {
			var margin = $context.css('marginLeft');
			return Math.abs(parseInt(margin)) / page_width;
		}
		
		self.setDestination = function(page) {
			return (page * page_width) * -1;
		}
		
		self.slideTo = function(page) {
			destination = self.setDestination(page);
			$context.animate({marginLeft: destination}, opts.speed);
			return true;
		}
		
		self.test = function() {
			console.log('this was a test');
		}
		
		// set default values
		$.fn.slider.defaults = {
			speed: 300
		}
		var opts = $.extend({}, $.fn.slider.defaults, options);

		// initialize
		return this.each(function() {
			self.init();
		});
	} 
})(jQuery);

// z-index correction extension
//$(function() {
//	if ($.browser.msie) {
//		var zIndexNumber = 1000;
//		$('div').each(function() {
////			console.log($(this));
//			var idName = $(this).attr('id');
//			if (idName != 'molding' && idName != "callouts") {
//				$(this).css('zIndex', zIndexNumber);
//				zIndexNumber -= 10;
//			}
//		});
//	}
//});

/* GENERAL FUNCTIONS */
function submitForm(url, formID, injectID, inject, disable) {
    if(url && formID) {
        _gaq.push(['_trackEvent', 'ajax_form', formID]);
    }

	if (typeof(inject) == 'undefined') { inject = true; }
	if (typeof(disable) == 'undefined') { disable = true; }
	if (disable) {
		if ($(formID).find('div.button input')) {
			$(formID).find('div.button input').attr('onclick','');
		}
	}
	$.post(url, $(formID).serialize(), function(data){
		if ($(injectID).hasClass('hide')) {
			$(injectID).show();
		}
		if (inject) {
			$(injectID).html(data);
		}
	});
}

function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function average() {
	var items = average.arguments.length;
	var sum = 0;
	for (i = 0; i < items; i++) {
		sum += average.arguments[i];
	}
	return (sum/items);
}

function ajaxEcard (node_id) {
	url = '/ecard/send?height=470&width=455&node_id=' + node_id;
	tb_show('Send E-mail', url);
    _gaq.push(['_trackEvent', 'sharetools', 'ecard', node_id+'']);
}

function showRating (node_id) {
	var url = '/content/view/ajax/' + node_id + '/(rating)/';
	$.ajax({
		type: "POST",
		url: url,
		success: function(data){
			$('div#product-rating-' + node_id).html(data);
		}
	});	
}

function addRating (rating_url, node_id) {
	$('div#product-rating-' + node_id).html('<div class="loader"><img src="/design/site/images/loading_animation.gif" alt="Loading..."/></div>');
	$.ajax({
		type: "POST",
		url: rating_url,
		data: { 
			ajax: 1
		},
		success: function(data){
			showRating(node_id);
		}
	});	
}

function rememberZip(nodeId) {
    var zipCode = $('#zip_code_'+nodeId).val();
    setZipcodeCookie(zipCode);
}

function ajaxAvailability (form_id) {
	var zip_code = $('#' + form_id + ' .zip_code').val();
	var product_id = $('#' + form_id + ' .product_id').val();
	var url = '/milo/availability?height=470&width=455&draw=1&product_id=' + product_id + '&zip_code=' + zip_code; 
	tb_show('Local Availability', url); // merely draws the box with a waiting status

	// talk to Analytics
	_gaq.push(['_trackEvent', 'Zip Search', product_id, zip_code]);
	
	// then actually fill offers
	getOffers(product_id, zip_code);
}

function getOffers (product_id, zip_code) {
	$.ajax({
		type: "POST",
		url: '/milo/availability',
		data: { 
			product_id: product_id,
			zip_code: zip_code
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			alert(errorThrown);
		},
		success: function(data){
			if (data == 'retry') {
				if (document.miloRetry == null) {
					document.miloRetry = 1;
				} else {
					document.miloRetry++;
				}
				if (document.miloRetry < 5) {
					setTimeout( function() { getOffers(product_id, zip_code); }, 1000 );
				} else {
					$('#offer-results').html("Sorry, there is currently no availability information for your area.");
					$('#offers-loading').hide();
				}
			} else {
				$('#offer-results').html(data);
				$('#offers-loading').hide();
                                if(typeof bf == 'object' && bf.ga) {
                                    $('#offer-results').find('a').each(function() {
                                        var a = this;
                                        bf.ga.trackLink(a);
                                    });
                                }
			}
		}
	});	
}

function showPrice (node_id, show_offers) {
	if (typeof(show_offers) == 'undefined') { show_offers = true; }
	var url = '/content/view/ajax/' + node_id + '/(price)/';
	if (show_offers) {
		url = url + '1/(offers)';
	}
	$.ajax({
		type: "POST",
		url: url,
		success: function(data){
			$('div#price-' + node_id).html(data);
		}
	});	
}

function getZipcodeCookie() {
	return($.cookie("userZipCode"));
}

function setZipcodeCookie(zipCode) {
	$.cookie("userZipCode", zipCode);
}

