﻿
$('document').ready(function () {
    enableReviewDialog();
    enableQA();
    enableHelpful();
    tabs();
    setThrower();

    if ($('.length-weight-select').length) {
        $('.length-weight-select li').click(function (e) {
            if ($(this).find('input:radio').attr('checked') == false) {
                $(this).find('input:radio').attr('checked', true);
                $.uniform.update();
            }
        });
    } else {
        $('#kit-products select').bind('change click', function () {
            $.uniform.update();
        });
    }

    $('.length, .weight').click(function () {
        $(this).siblings('.radio').find('input').attr('checked', 'checked');
        $('.length-weight-select').find('span').removeClass('checked');
        $(this).siblings('.radio').find('span').addClass('checked');
    });

    // Form Validation
    $('#add-item-to-cart-form').submit(function () {
        var addItemErrors = 0;
        $('.add-error').remove();

        // Check to see if a L/W was selected, if so submit form
        if ($('.length-weight-select').length) {
            if (!$('.length-weight-select li .checked, .length-weight-select li input:checked').length) {
                if (window.location.pathname.indexOf('/softball-gloves/') > -1) {
                    $('.length-weight-select').after('<p class="error add-error" style="clear:right">Please select a throwing hand.</p>');
                }
                else {
                    $('.length-weight-select').after('<p class="error add-error" style="clear:right">Please select a length and weight for this bat.</p>');
                }
                addItemErrors = 1;
            }
        }

        // If we have a bat pack
        if ($('#kit-products').length) {
            // Check for selects. Validate bat count.
            if ($('#kit-products select').length) {
                $('#kit-products > li').each(function () {
                    var kitProduct = $(this);
                    var reqCount = parseInt(kitProduct.find('.kit-count').text());
                    var selectCount = 0;

                    kitProduct.find('select').each(function () {
                        selectCount += parseInt(($(this).find('option:selected').val()).split('_')[1]);
                    });

                    if (reqCount !== selectCount) {
                        if (!$('#lw-error-' + kitProduct.attr('id')).length)
                            $('#kit-products').after('<p id="lw-error-' + kitProduct.attr('id') + '" class="error add-error">You need to choose ' + reqCount + ' ' + kitProduct.find('.kit-name').text() + ' bats.</p>');
                        addItemErrors = 1;
                    }
                });
            }

            // Check for radios. Validate radios.
            if ($('#kit-products input[type="radio"]').length) {
                $('#kit-products > li').each(function () {
                    var kitProduct = $(this);
                    if (!kitProduct.find('input:checked').length) {
                        if (!$('#lw-error-' + kitProduct.attr('id')).length)
                            $('#kit-products').after('<p id="lw-error' + kitProduct.attr('id') + '" class="error add-error">Please select a length and weight for each product in the bat pack.</p>');
                        addItemErrors = 1;
                    }
                });
            }
        }

        if (addItemErrors === 1) {
            return false;
        }
    });

    // Alternative images
    if ($('.additional-image-thumbnail').length) {
        $(".additional-image-thumbnail").fancybox({
            'transitionIn': 'elastic',
            'transitionOut': 'elastic',
            'speedIn': 220,
            'speedOut': 200,
            'overlayShow': true,
            'overlayOpacity': 0.4,
            'overlayColor': '#000'
        });
        $('.additional-image-thumbnail').click(function () {
            var productUrl = $('#details-header').text().replace(/^\s*|\s*$/g, '').replace(/ /g, '-').replace(/:/g, '-');
            pageTracker._trackEvent('Product', 'Image Zoom', productUrl); // GA Event Tracker
        });
    }

    $('#expert-link').click(function () {
        var productUrl = $('#details-header').text().replace(/^\s*|\s*$/g, '').replace(/ /g, '-').replace(/:/g, '-');
        pageTracker._trackEvent('Product', 'Live Chat', productUrl); // GA Event Tracker
    });

    $('#more-reviews-button').click(function () {
        var productUrl = $('#details-header').text().replace(/^\s*|\s*$/g, '').replace(/ /g, '-').replace(/:/g, '-');
        pageTracker._trackEvent('Product', 'More Reviews', productUrl); // GA Event Tracker
    });

    // Share Tracking
    $('.facebook-link a').click(function () {
        var productUrl = $('#details-header').text().replace(/^\s*|\s*$/g, '').replace(/ /g, '-').replace(/:/g, '-');
        pageTracker._trackEvent('Product', 'Share on Facebook', productUrl); // GA Event Tracker
    });

    // YouTube Videos: Get View Data
    if ($('#product-video-strip').length) {
        var videoList = '';
        $('#product-video-strip li').each(function (i) {
            if (videoList != '')
                videoList += ' OR ';
            var ytkey = $(this).metadata({ type: 'attr', name: 'data' }).ytkey;
            videoList += ytkey.indexOf('-') == 0 ? ytkey.substring(1) : ytkey;
        });

        $.ajax({
            url: 'http://gdata.youtube.com/feeds/api/videos?q=' + videoList + '&alt=json',
            dataType: 'jsonp',
            success: function (data) {
                $.each(data.feed.entry, function (i, v) {
                    if (data.feed.entry[i].yt$statistics) {
                        var viewCount = data.feed.entry[i].yt$statistics.viewCount;
                        var key = data.feed.entry[i]['id']['$t'].substring(42);
                        $('#vid_' + key).append('<span class="product-video-view-count"><strong>' + add_commas(viewCount) + '</strong> Views</span>');
                    }
                });

                // Set up video lightbox
                $('#product-video-strip li a').each(function () {
                    $(this).fancybox({
                        'transitionIn': 'elastic',
                        'transitionOut': 'elastic',
                        'speedIn': 220,
                        'speedOut': 200,
                        'overlayShow': true,
                        'overlayOpacity': 0.4,
                        'overlayColor': '#000',
                        'href': this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
                        'type': 'swf',
                        'swf': { 'wmode': 'transparent', 'allowfullscreen': 'true' },
                        'onStart': function () {
                            pageTracker._trackEvent('Product', 'Video', this.href); // GA Event Tracker
                        }
                    });
                });
            }
        });
    }

    $('.placeholder').inFieldLabels({
        fadeOpacity: 0,
        fadeDuration: 2
    });
});

$(window).load(function() {
    //summaryFollow();

    // Audio Player
    if ($('#audio-player').length) {
        $('#jplayer').jPlayer({
            nativeSupport: true, oggSupport: false, customCssIds: true,
            swfPath: '/flash', preload: 'auto'
        })
            .jPlayer("cssId", "play", "audio-control")
	        .jPlayer("cssId", "stop", "audio-control")
	        .jPlayer('onSoundComplete', function() {
	            $('#audio-player a').html('<img src="/images/icons/audio.gif" alt="Audio Player" />');
	        });

        $('#audio-control').click(function() {
            $('#jplayer').jPlayer('setFile', $(this).attr('href')).jPlayer('play');
            $(this).html('<img src="/images/icons/audio-playing.gif" alt="Audio Player" />');
            var productUrl = $('#details-header').text().replace(/^\s*|\s*$/g, '').replace(/ /g, '-').replace(/:/g, '-');
            pageTracker._trackEvent('Product', 'Audio', productUrl); // GA Event Tracker
        });

        $('#audio-download-link').click(function() {
            var productUrl = $('#details-header').text().replace(/^\s*|\s*$/g, '').replace(/ /g, '-').replace(/:/g, '-');
            pageTracker._trackEvent('Product', 'Audio Download', productUrl); // GA Event Tracker
        });
    }
});


function enableReviewDialog() {
    var dialogwidth = window.location.pathname.indexOf('/softball-gloves/') > -1 ? 635 : 529,
        dialogheader = window.location.pathname.indexOf('/softball-gloves/') > -1 ? 'Glove' : 'Bat';


    var dialogOptions = {
		width: dialogwidth,
		autoOpen: false,
		dialogClass: 'dialog',
		resizable: false,
		modal: true,
		open: function(e, ui) {
			ratingSelect();
			$('.ui-dialog').find('#submit-review #nickname').focus();
			$('.ui-dialog .rating div').attr('class', $('#rating-activity .rating div').attr('class'));
			$('.ui-dialog .rating-review-link strong').html($('#rating-activity .rating-count').html());
			$(".ui-dialog .reviewError").hide();
		}
	};

	$('.review-bat-link').click(function(e) {
        $('#review-dialog').remove();
		$('body').append("<div id='review-dialog' class='dialog-hidden'></div>");
		$('#review-dialog').html($('#submit-review-dialog').html());
		$('#review-dialog').dialog(dialogOptions).dialog('option', 'title', 'Submit Your ' + dialogheader + ' Review').dialog('open');

		var productUrl = $('#details-header').text().replace(/^\s*|\s*$/g, '').replace(/ /g, '-').replace(/:/g, '-');
		pageTracker._trackEvent('Product', 'Review This ' + dialogheader, productUrl); // GA Event Tracker

		e.preventDefault();
	});
}

function enableQuestionDialog() {
    var dialogwidth = 529;
    if (window.location.pathname.indexOf('/softball-gloves/') > -1) {
        dialogwidth = 635;
    }

	var dialogOptions = {
		width: dialogwidth,
		autoOpen: false,
		dialogClass: 'dialog',
		resizable: false,
		modal: true,
		open: function(e, ui) {
			$('.ui-dialog #ask-question #Text').focus();
			if($('.ui-dialog #ask-question').height() < $('.ui-dialog .bat-details').height())
			    $('.ui-dialog #ask-question').css('height', ($('.ui-dialog .bat-details').height()) + 'px');
			$('.ui-dialog .rating div').attr('class', $('#rating-activity .rating div').attr('class'));
			$('.ui-dialog .rating-review-link strong').html($('#rating-activity .rating-count').html());
			$(".ui-dialog .askError").hide();
				 
			 $('.ui-dialog #receive-email-marketing-label').click(function() {
			    var $ch = $('.ui-dialog #recieve-email-marketing');
			    $ch.attr('checked', !$ch.attr('checked'));
			    $.uniform.update();
			 });
			
			// Reload uniform for checkbox
            $('select, input:checkbox, input:radio, input:file').uniform();
		}
	};

	$('.ask-question-link').click(function(e) {
		$('body').append("<div id='question-dialog' class='dialog-hidden' style='background: #ffffc9'></div>");
		$('#question-dialog').html($('#ask-question-dialog').html());
		$('#question-dialog').dialog(dialogOptions).dialog('option', 'title', 'Ask A Question').dialog('open');

		var productUrl = $('#details-header').text().replace(/^\s*|\s*$/g, '').replace(/ /g, '-').replace(/:/g, '-');
		pageTracker._trackEvent('Product', 'Ask A Question', productUrl); // GA Event Tracker

		e.preventDefault();
	});    
}

function enableQA() {
    // Handle dialog behavior
    enableQuestionDialog();
    
    var counter = 0;
 
    // Show answer form
    $('.qa-answer-question-link').click(function(e) {
        var questionID = $(this).parent().find('.question-id').html();
        var answerQuestionForm = $(this).parent().find('.qa-answers .qa-answer-question');
        
        if(answerQuestionForm.is(':hidden')) {
            $('#qa-questions .qa-answer-question:visible').hide(); // Hide any open answer forms
            answerQuestionForm.html($('#qa-answer-question-template').html());
            answerQuestionForm.find('form').attr('id', 'answer-for-' + questionID);
            answerQuestionForm.find('input[name="QuestionId"]').val(questionID);
            answerQuestionForm.find('button').click(function(e) {
                SubmitAnswer(questionID);
                e.preventDefault();
            });
            
            answerQuestionForm.find('textarea, input:text').each(function() {
                var eleId = $(this).attr('id');
                var lbl = answerQuestionForm.find('label[for="' + eleId + '"]');
                $(this).attr('id', eleId + '' + counter);
                lbl.attr('for', $(this).attr('id'));
            });
            
            answerQuestionForm.show();
            answerQuestionForm.find('.placeholder').inFieldLabels({ fadeOpacity: 0, fadeDuration: 2 });
        } else {
            answerQuestionForm.hide();
        }
        
        counter++;
        e.preventDefault();
    });
}

function enableHelpful() {
	$('.review-helpful-yes').click(function(e) {
		var review = $(this);
		var reviewData = $(this).metadata({ type: 'attr', name: 'data' });
		
		if(!review.parents('ul').hasClass('already-voted')) {
			$.get("/product/VoteUp", { reviewId: reviewData.reviewId }, function(data) {
				review.parents('.helpful').children('p').fadeOut('fast', function() { $(this).html('<strong style="color: green">Thank you for voting!</strong>').fadeIn('fast'); });
				review.html(parseInt(review.html()) + 1);
				review.parents('ul').addClass('already-voted');

                var productUrl = $('#details-header').text().replace(/^\s*|\s*$/g, '').replace(/ /g, '-').replace(/:/g, '-');
                pageTracker._trackEvent('Product', 'Review Helpful Yes', productUrl); // GA Event Tracker
			});
		}

		e.preventDefault();
	});

	$('.review-helpful-no').click(function(e) {
		var review = $(this);
		var reviewData = $(this).metadata({ type: 'attr', name: 'data' });
		
		if(!review.parents('ul').hasClass('already-voted')) {
			$.get("/product/VoteDown", { reviewId: reviewData.reviewId }, function(data) {
				review.parents('.helpful').children('p').fadeOut('fast', function() { $(this).html('<strong style="color: green">Thank you for voting!</strong>').fadeIn('fast'); });
				review.html(parseInt(review.html()) + 1);
				review.parents('ul').addClass('already-voted');

                var productUrl = $('#details-header').text().replace(/^\s*|\s*$/g, '').replace(/ /g, '-').replace(/:/g, '-');
                pageTracker._trackEvent('Product', 'Review Helpful No', productUrl); // GA Event Tracker
			});
		}

		e.preventDefault();
	});
}

function submitReview(reviewDialog) {
	var rating = reviewDialog.find("#selected-rating").text();
	var nick = reviewDialog.find("#nickname").val();
	var pros = reviewDialog.find("#pros").val();
	var cons = reviewDialog.find("#cons").val();
	var productId = reviewDialog.find("#productId").val();

    $.post("/product/SubmitReview",
        { Pros: pros, Cons: cons, NickName: nick, Rating: rating, productId: productId },
        function(data) {
            if (data == "") {
                reviewDialog.find(".reviewError").hide();
                $('#review-dialog').dialog('close').dialog('destroy');
                $('#review-dialog').remove();
            }
            else {
            	reviewDialog.find(".reviewError").show();
                reviewDialog.find(".reviewError").html(data);
            }
        });
}

function SubmitQuestion(f)
{
	var action = f.attr("action");
	var serializedForm = f.serialize();
	var passed = false;
	var formValidated = true;
	
	// Validate form
	// Email address regex check 9/20/10 Rach
	var errorLog = "";
	var errorCount = 0;
	var emailRegex = /^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$/;

	f.find('input:text, textarea').each(function () {

	    // Check to see if field is blank
	    if ($(this).val().length < 1) {
	        if ($(this).attr('type') == 'text')
	            var lbl = $(this).closest('td').find('label').html().toLowerCase();
	        else
	            var lbl = "question";

	        errorLog += ('Please provide your ' + lbl + '.\n');
	        errorCount++;
	    }

	    // If field is email address, check w/ regex
	    else if ($(this).attr('name') == 'EmailAddress' && $(this).val().match(emailRegex) == null) {
	        errorLog += ('Email address is invalid, please verify.\n');
	        errorCount++;
	    }
	});

	if (errorCount > 0) {
	    formValidated = false;

	    if (errorCount > 1)
	        alert('Could not submit your question for the following reasons:\n\n' + errorLog);
        else
            alert('Could not submit your question for the following reason:\n\n' + errorLog);
	}
	
	if(!formValidated)
	    return false;

	$.post(action, serializedForm, function(data) {
		if(data == '') {
			$('#question-dialog').dialog('close').dialog('destroy');
			$('#question-dialog').remove();
			f.find('.askError').hide();
			
			// Show confirmation dialog
			var dialogOptions = {
                width: 406,
                autoOpen: false,
                dialogClass: 'dialog',
                resizable: false,
                modal: true,
                open: function(e, ui) {
                    $('#ask-question-confirmation button').click(function(e) {
                        $('#ask-question-confirmation').dialog('close');
                        e.preventDefault();
                    });
                }
            };
            
            $('#ask-question-confirmation').dialog(dialogOptions).dialog('option', 'title', 'Question Received').dialog('open');
			
		} else {
			f.find('.askError').show();
			f.find('.askError').html(data);
		}
	});
}

function SubmitAnswer(qId)
{
	var f = $("#answer-for-" + qId);
	var action = f.attr("action");
	var serializedForm = f.serialize();
	var passed = true;
	
	if(f.find('input:text').val().length < 1 || f.find('textarea').val().length < 1) {
	    passed = false;
	}

    if(passed) {
	    $.post(action, serializedForm, function(data) {
			// Show confirmation dialog
			var dialogOptions = {
                width: 406,
                autoOpen: false,
                dialogClass: 'dialog',
                resizable: false,
                modal: true,
                open: function(e, ui) {
                    $('#answer-question-confirmation button').click(function(e) {
                        $('#answer-question-confirmation').dialog('close');
                        e.preventDefault();
                    });
                }
            };
            
            $('#answer-question-confirmation').dialog(dialogOptions).dialog('option', 'title', 'Answer Received').dialog('open');
	        $('.qa-answer-question:visible').hide();
	    });
	} else {
	    alert('Please provide your answer and nickname.');
	}
}

function loadReviewBars() {
	// Onclick of bars, filter reviews by rating

}

function loadReviewChart() {
    // Check to see if percentages total to 100, if not add 1 to lowest %
	var total = 0;
	var lowestAmount = 0;
	
    $('.rating-percent').each(function() {
		var percent = parseInt($(this).text());
		if(lowestAmount == 0 && percent != 0)
			lowestAmount = percent;
		if(percent < lowestAmount && percent != 0)
			lowestAmount = percent;	
		total += percent;
	});
	
    if(total < 100) {
		$('.rating-percent:contains("'+lowestAmount+'")').html((parseInt(lowestAmount) + 1) + "%");
	}
}

function summaryFollow() {
	  var msie6 = $.browser == 'msie' && $.browser.version < 7;
  
	  if(!msie6) {
			var top = $('#review-summary').offset().top;

			$(window).scroll(function(event) {
			  var y = $(this).scrollTop();
			  if (y >= top) {
				$('#review-summary').addClass('fixed').fadeTo(300, 0.9);
			  } else {
				$('#review-summary').removeClass('fixed').fadeTo(300, 1).css('top', 0);
			  }
			});
	  }  
}

var currentRating = 0;

function ratingSelect() {
	$('.ui-dialog #submit-review .rating li').hover(function() {
		var rating = $(this).text();
		$('.ui-dialog #submit-review .rating li').removeClass('selected');
		$('.ui-dialog #submit-review .rating li').slice(0, parseInt(rating)).attr('class', 'selected');
		$('.ui-dialog #selected-rating').text(rating);
	}, function() {
		$('.ui-dialog #submit-review .rating li').removeClass('selected');
		if(currentRating) {
			$('.ui-dialog #submit-review .rating li').slice(0, parseInt(currentRating)).attr('class', 'selected');
			$('.ui-dialog #selected-rating').text(currentRating);	
		} else {
			$('.ui-dialog #selected-rating').text('0');
		}
	}).click(function() {
		currentRating = $(this).text();
		$('.ui-dialog #selected-rating').text(currentRating);
		$('.ui-dialog #submit-review .rating li').slice(0, parseInt(currentRating)).attr('class', 'selected');
		if($('html.ie6').length || $('html.ie7').length) {
			$('.ui-dialog').find('#selected-rating').html(currentRating);
		}
	}).focus(function() {
		$('.ui-dialog #submit-review .rating li').removeClass('selected');
		var rating = $(this).text();
		$('.ui-dialog #selected-rating').text(rating);
		$('.ui-dialog #submit-review .rating li').slice(0, parseInt(rating)).attr('class', 'selected');
	}).blur(function() {
		$('.ui-dialog #submit-review .rating li').removeClass('selected');
		if(currentRating) {
			$('.ui-dialog #submit-review .rating li').slice(0, parseInt(currentRating)).attr('class', 'selected');
			$('.ui-dialog #selected-rating').text(currentRating);	
		} else {
			$('.ui-dialog #selected-rating').text('0');
		}	
	}).keyup(function(e) {
		var code = e.keyCode || e.which;
		if(code == 13) { // Enter was pressed
			$(this).click();
			$('.ui-dialog #pros').focus();	
		}
	});
}

//Glove Simple tabs minus the bloat
function tabs() {
    gloveAlt();

    var $tabs = $('#infoTabs'),
        $tab = $tabs.children(),
        $content = $('#infoWrap').children(),
        $moreRev = $('#more-reviews-button-glove');

    $('html').hasClass('ie6') ? $content.hide() : "";

    $($content[0]).show();

    $tabs.on('click', 'span', function () {
        var $el = $(this),
        $index = $el.index();

        $tab.removeClass('selected');
        $content.hide();

        $el.addClass('selected');
        $($content[$index]).show();
    });

    //Open tab when more review is clicked
    $moreRev.click(function () {
        $($tab[1]).click();
    });

    hashListen($tab);
}

function gloveAlt() {
    var $alts = $('#altImg'), //Alts wrap
        $hero = $('#heroGlove'), //Main Image
        origImg = $hero.attr('src'); //Original Image

    $alts.on('mouseover mouseout', 'img', function (e) {
        var $el = $(this),
            newImg = $el.attr('src').split('.jpg')[0] + 'l.jpg';

        if (e.type === 'mouseover') {
            $hero
                .attr('src', newImg)
                .css({ width: '50%', 'margin-top': '-3px' });

            clearTimeout(timerId);
        } else {
            timerId = setTimeout(AltImgMouseOut, 100);
        }
    });

    function AltImgMouseOut() {
        $hero
            .attr('src', origImg)
            .css({ width: '80%', 'margin-top': '-115px' });
    }

}

function getSizeCookie(cookiename) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(cookiename + "=");
        if (c_start != -1) {
            c_start = c_start + cookiename.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

function setThrower() {

    var throwingHand = getSizeCookie('thrower');

    var f = $('.length-weight-select');

    if (f.find('input').length == 1) {
        f.find('input').attr('checked', true); //check the only option if there's only one option
        f.find('input').parent().addClass('checked');
    }
    else {
        if (window.location.pathname.indexOf('/softball-gloves/') > -1) {
            if (f.length > 0) {
                if (throwingHand != "") {
                    f.find('li').each(function () {
                        if ($(this).find('span:contains("' + throwingHand + '")').length) {
                            $(this).find('input').attr('checked', true);
                            $(this).find('input').parent().addClass('checked');
                        }
                    });
                }
                else {
                    //If no cookie is set, Right Hand Thrower is the default option
                    f.find('span:contains("Right Hand Thrower")').siblings('div').find('input').attr('checked', true);
                    f.find('span:contains("Right Hand Thrower")').siblings('div').find('span').addClass('checked');
                }
            } else {
                return false;
            }
        }
    }
}

function hashListen (trig) { //Open tab for hash tags in url
    var url = window.location.hash,
        tab = url.split('#')[1];

    tab === "product-reviews" ||  tab === "/product-reviews" ? $(trig[1]).click() : "";
}


function add_commas(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; }

