jQuery.validator.addMethod("alphanumeric", function(value, element) {
	return this.optional(element) || (/^\w+$/i).test(value);
}, "Letters, numbers or underscores only please");  

$(function(){
    if ($.browser.msie && $.browser.version == 6) {
		// alert('got here');
	}
    if (typeof(jQuery.fn.pngFix) == 'function') {
        // $(document).pngFix({ blankgif: '/images/blank.gif' });
    }

	$('#main-kicker ul').before('<div id="main-kicker-nav-holder"><div id="main-kicker-nav-position"><a href="#" id="main-kicker-prev">&nbsp;</a><ul id="main-kicker-nav"></ul><a href="#" id="main-kicker-next">&nbsp;</a></div></div>').cycle({
        fx:     'fade', 
		timeout:	5000,
	    speed:  3000,
	    prev: '#main-kicker-prev',
	    next: '#main-kicker-next',
	    pager: '#main-kicker-nav',
		// callback fn that creates a thumbnail to use as pager anchor 
		    pagerAnchorBuilder: function(idx, slide) { 
		        return '<li><a href="#">&nbsp;</a></li>'; 
		    }
	});
	
	$('#main-kicker-nav-position').css('width', $('#main-kicker #main-kicker-nav li').length*17+33);

	$('#product-tabs > ul li').hover(function(){
		$(this).not('.ui-tabs-selected').addClass('over');
	}, function(){
		$(this).removeClass('over');
	});
	
	$('.prodListItemWrapOut').hover(function(){
		$(this).css('background-color', '#f7f7f7');
	}, function(){
		$(this).css('background-color', '');
	}).click(function(){
		window.location = $('a:first', this).attr('href');
	}).css('cursor', 'pointer');
    
    if ($.browser.msie && $.browser.version == 6) {
        // alert('ie 6');
        $('#shop-access').css('width', 175);
        $('#search').css('width', 210);
        $('ul.double').css('width', 220);
        
        $('.prodDescription').css('clear', 'none');
        $('.shippingFields, .billingFields').css('width', 250);
    }
    $("a[rel='external']").attr('target', '_blank');
    
    $('ul, ol, table, thead, tbody, tfoot, tr')
        .find('> :first').not('thead, tbody, tfoot').addClass('first').end().end()
        .find('> :last').not('thead, tbody, tfoot').addClass('last').end().end();
        
    if ($.browser.msie) {
        $('h2.catTitle').css('color', $('h2.catTitle').parent().css('color'));
    }
    
    // Auto set value for text fields
    $('input.autofill').each(function(){
        var $$ = $(this);
        var $l = $('label[for="'+$$.attr('id')+'"]');
        $l.hide();
        
        $$.focus(function(){
            if ($.trim($$.val()) == $l.text().toLowerCase()) {
                $$.val('');
            }
            
            $$.removeClass('blur');
        });
        
        $$.blur(function(){
            if ($.trim($$.val()) == '') {
                $$.val($l.text().toLowerCase());
            }
            
            $$.addClass('blur');
        });
        
        $$.blur();
    });
    
    // Menu system setup
    var finalOpacity = 0.9;
    if ($.browser.msie) {
        finalOpacity = 0.95;
    }
    $('#top-nav li.mainLevel')
        .hover(function(){
			$(this).siblings().find('> ul, > div.menuWrap').stop(true).css({opacity: 0, display: 'none'});
            $('> ul, > div.menuWrap', this)
                .css({
                    'display': 'block',
                    'z-index': '501'
                })
                .stop(true)
                .fadeTo('fast', finalOpacity);
        }, function(){
            $('> ul, > div.menuWrap', this)
                .css({
                    'z-index': '500'
                })
                .stop(true)
				.animate({opacity: finalOpacity}, 800)
                .fadeTo('fast', 0, function(){
                    $(this).stop(true).css('display', 'none');
                });
        })
        .find('> ul, > div.menuWrap')
        .css({
            'opacity': '0'
        });

    $('.fmQuantity input').attr('autocomplete', 'off');
    $('.fmRemove')
        .find('input').css('display', 'none').end()
        .find('a')
            .css('display', 'inline')
            .click(function(){
                $(this).prev().attr('checked', 'checked');
                $('#basket-form').submit();
                return false;
            });
    $('#cart-contents th.fmRemove').text('');
    $('#cart-contents tbody tr:odd').addClass('odd');
    
    if (typeof(jQuery.fn.fancyZoom) == 'function') {
		var fzDir = document.location.protocol+'//www.clivecoffee.com/images/fancyzoom';
		var ftDir = document.location.protocol+'//www.clivecoffee.com/fancytext';
		
        $('a.fancy').each(function(){
            $(this)
                .css('display', 'inline')
                .fancyZoom({
                    width: 500,
                    height: 300,
                    directory: fzDir
                });
        });
        
        var srcDiv = $('#prod-expanded');
        $('#prod-zoom, #prod-expand')
            .attr('href', '#'+srcDiv.attr('id'))
            .fancyZoom({
                closeOnClick: true,
                directory: fzDir
            });
        
        preLoad = new Image();
        preLoad.src = $('img', srcDiv).attr('src');
        
        $('#additional-images a').each(function(){
            $(this).removeClass('external');
            var preLoad = new Image();
            preLoad.src = $(this).attr('href');
            
            $(this)
                .attr('href', '#'+$(this).attr('class'))
                .fancyZoom({
                   closeOnClick: true,
                   directory: fzDir
                });

        });

		$('a.cvvExpand').each(function(){
			$(this).fancyZoom({
				closeOnClick: true,
				directory: fzDir
			});
		});
		$('a.fancytext').each(function(){
			$(this).fancyZoom({
				closeOnClick: true,
				directory: ftDir
			});
		});
		

    }
    
    $('#button-registry').click(function(){
        $($(this).parents('form')[0]).attr('action', '/MYREG.html');
    });
    
    $('#button-basket').click(function(){
        $($(this).parents('form')[0]).attr('action', '/BASK.html');
    });
    
    
    if (typeof(jQuery.fn.corner) == 'function') {
        $('.pageHead').corner();
    }
    
    if ($('#acct-email').size() > 0) {
        $('#ship-email, #bill-email, #acct-login').parent().css('display', 'none');
    }
    
    $('#acct-email').blur(function(){
        $('#ship-email, #bill-email, #acct-login').val($(this).val());
    });
    
    $('#ship-state, #bill-state').change(function(){
        if ($(this).val() == '') {
            $(this).parent().next().show('normal');
        } else {
            $(this).parent().next().hide('normal');
            if ($(this).attr('id').substring(0, 4) == 'ship') {
                $('#ship-country').val('US');
            } else {
                $('#bill-country').val('US');
            }
        }
    });
    
    $('#ship-state, #bill-state').change();
    
    $('select[name="Customer_ShipCountry"], select[name="ShipCountry"]').attr('id', 'ship-country');
    $('select[name="Customer_BillCountry"], select[name="BillCountry"]').attr('id', 'bill-country');
    
    $('#copy-ship-to-bill').click(function(){
        if ($(this).is(':checked')) {
            $('.shippingFields').find('select, input').each(function(){
                var billId = $(this).attr('id').replace(/ship-/, 'bill-');
                $('#'+billId).val($(this).val());
            });
        } else {
            $('.billingFields').find('select, input').val('');
        }
        
        $('#ship-state, #bill-state').change();
    });
    
    // $('#acct-create-form').validate();
    
    
    $('#delivery-options li:odd').addClass('odd');
    $('#delivery-options li')
        .hover(function(){
            $(this).addClass('over');
        }, function(){
            $(this).removeClass('over');
        })
        .click(function(){
            $('label', this).click();
        });
    
    $('#pay-form input').attr('autocomplete', 'off');
    
    $('.searchProdList li').hover(function(){
        $(this).addClass('over');
    }, function(){
        $(this).removeClass('over');
    });
    
    $('.searchProdList li > :nth-child(2)').widont();

	$('#gform form').submit(function(event){
		setUrchinInputCode(pageTracker);
	});

	if ($.browser.mozilla) {
		$('#product-carousel li').css('-moz-border-radius', '5px');
	} else if ($.browser.safari) {
		$('#product-carousel li').css('-webkit-border-radius', '5px');
	}
	
	if ($('#product-carousel ul > *').size() > 3 && !($.browser.msie && $.browser.version == 6)) {
		$('#product-carousel ul').jcarousel({
			// scroll: 3,
			// visible: 3,
			buttonNextHTML: '<img src="/images/Right.png"/>',
			buttonPrevHTML: '<img src="/images/Left.png"/>'
		});
		
	}
	
    if ($.browser.msie && $.browser.version == 6) {
		// alert(parseInt($('#content-top > div').css('top')));
		$('#content-top').css('height', ($('#content-top > div').height() + parseInt($('#content-top > div').css('top'), 10))+'px');
		// $('.jcarousel-clip').css('width', '636px');
	}
	
	
	$('.widget_tag_cloud a').each(function(){
		// console.log(parseInt($(this).attr('style').replace(/^font-size: (\d+)pt;$/, '$1')));
		$(this).attr('style', '');
	});
	
	// CART PAGE
	if ($('#cart-contents').length) {
		var shippingOptions = [];
		var output = $('#cart-totals tr:first-child td:last-child');
		var total = $('#cart-totals .grandTotal td:last-child');
		var originalTotal = parseFloat(total.text().replace(/\s?\$/, ''));
		output.text('Shipping Options');
		output.prev().text('');
		output.parent().after('<tr><td colspan="2"><table id="shipping-options" style="width: 100%; line-height: 1.8;"></table></td></tr>');
		
		$.getJSON('/SHIPCALC.html?TKShip=1&TK_ShipState=OR&TK_ShipZip=97214&TK_ShipCountry=US', function(data){
			// output.html('');
			shippingOptions = data.options;
			$.each(shippingOptions, function(i){
				if (!this.name || this.name.search(/^Will-Call/) !== -1 || this.name.search(/US?PS/) !== -1) return;
				
				$('#shipping-options').append('<tr><td style="font-weight: bold; text-align: left; border-width: 0; padding: 0;">'+this.name+'</td><td style="border-width: 0; padding: 0;">'+this.amount+'</td>');
			});
			
			$('#shipping-options').append('<tr><td style="border-width: 0; padding: 0;" colspan="2"><em>(Int\'l Calculated at Checkout)</em></td></tr>');
			
		});
	}
	
	
	if ($('fieldset.attributes select').length) {
		// set up interval to check for select existance along with function
		var intervalHolderSelect = setInterval(function(){
			if ($('fieldset.attributes select').length) {
				clearInterval(intervalHolderSelect);
				var title;
				
				var blurFunc = function(e){
					if (!$(e.target).parents('.selector-options').length) {
						$('body').unbind('mousedown', blurFunc);
						$('.selector-options').data('bound', false);
						$('.selector-options dd').not(':animated').slideUp('fast');
					}
				};
				
				$('fieldset.attributes select').each(function(i){
					var $s = $(this);
					var id = 'so-'+$s.attr('name').replace(/[\:\[\]\.]/g, '');
					if ($s.val()) {
						title = $(':selected', $s).text();
					} else {
						title = $('option:first-child', $s).text();
					}
					$s.hide().before('<dl id="'+id+'" class="selector-options"><dt>'+title+'</dt><dd><ul></ul></dd></dl>');
					
					$s.change(function(){
						var title = $(':selected', this).text();
						$(this).prev().find('dt').text(title);
					});
					
					$s.children().each(function(j){
						var v = $(this).attr('value');
						var t = $(this).text();
						var s = $('#'+id);
					
						if (v == 'none') {
							t = 'None';
							 // return;
						}
					
						v = i+'-'+v;
						var content = '<li id="option-'+v+'">'+t+'</li>';
						// if (t.search(/Out of Stock\s*$/) !== -1) content = '<li id="option-'+v+'" class="disabled">'+t+'</li>';
						$('ul', s).append(content);
						// $('ul li.disabled', s).click(function(){ return false; });

						$('#option-'+v+':not(.disabled)').click(function(){
							$s.val($(this).attr('id').replace(/^option-(\d-)?/, '')).change();
							blurFunc({target: $('body').get(0)});
						}).hover(function(){
							$(this).css({ backgroundColor: '#f5f5f5'});
						}, function(){
							$(this).css({ backgroundColor: '#ffffff'});
						});
					});
				});

				$('.selector-options').hover(function(){
					// $(this).css({ backgroundColor: '#d5ccbb'});
				}, function(){
					// $(this).css({ backgroundColor: '#E4DFD6'});
				}).click(function(){
					if (!$(this).data('bound')) {
						$(this).data('bound', true);
						$('body').bind('mousedown', blurFunc);
					}
					if ($('dd:visible', this).length) {
						$('dd', this).not(':animated').slideUp('fast');
					} else {
						$('dd', this).not(':animated').slideDown('fast');
					}
				});
			}
		}, 300);
	}
	
	// alert('AE DEV PAGE');
});