$(function () {
	
	$('a.dashed').click (function(){
        tabContainers.hide().filter('#write_review').show();
        $('div.tabs ul.tabNavigation a').removeClass('selected');
        $('div.tabs ul.tabNavigation a[href=#write_review]').addClass('selected');
        $('a.tabTop:first').focus();
        return false;
	});
	
	if ($('.priceValue').html() == 'Free' && added == 1) {
		$('.buyContainer').remove();
	} else {
	    drawActualOrderState();
	}
	
    $('.productImagesAdditional').show();

    $(".lightbox").lightbox({
        fitToScreen: false,
        imageClickClose: true
    });

    var tabContainers = $('div.tabs > div');
    
    $('div.tabs ul.tabNavigation a').click(function () {
        tabContainers.hide().filter(this.hash).show();
        $('div.tabs ul.tabNavigation a').removeClass('selected');
        $(this).addClass('selected');
        location.href = location.href.substring(0,location.href.indexOf('#')) + this.hash;
        $('a.tabTop:first').focus();
        return false;
    });

    if (location.href.indexOf('#') != -1 && location.href.indexOf('#write_review') == -1) {
        tabContainers.hide().filter(location.href.substring(location.href.indexOf('#'),location.href.length)).show();
        $('div.tabs ul.tabNavigation a').removeClass('selected');
        $('div.tabs ul.tabNavigation a[href=' + location.href.substring(location.href.indexOf('#'),location.href.length) +']').addClass('selected');
        location.href = location.href.substring(0,location.href.indexOf('#')) + location.href.substring(location.href.indexOf('#'),location.href.length);
        $('a.tabTop:first').focus();
    } else {
      var url = window.location.href;
      if (url.search('write_review') > 0 && url.search('bvdisplaycode') > 0) {
        $('div.tabs ul.tabNavigation li:last').prev().children('a').click();
      } else {
        tabContainers.hide().filter('#description').show();
    	  $('div.tabs ul.tabNavigation a:first').addClass('selected');        
      }
    }

    $('#productImagesAdditionalCarousel li, .lessThanFour li').click(function () {
        
    	$('#productImagesAdditionalCarousel .activeImage, .lessThanFour .activeImage').removeClass('activeImage');
    	$(this).addClass('activeImage');
        
        var replace = $(this).children('img').attr('rel');

        
        if ($(this).children('img').hasClass('video')) {
                
            if (!$('.bestSellerRibbon').parent().hasClass('productImages')) {
            	$('.bestSellerRibbon').parent().replaceWith('<div class="bestSellerRibbon"></div>');
            }
            if (!$('.riskfreeRibbon').parent().hasClass('productImages')) {
            	$('.riskfreeRibbon').parent().replaceWith('<div class="riskfreeRibbon"></div>');
            }
            if (!$('.testedRibbon').parent().hasClass('productImages')) {
            	$('.testedRibbon').parent().replaceWith('<div class="testedRibbon"></div>');
            }
            $('.productImagesMainBorder').html('<div id="container">Loading the player ...</div>');
            
            if (jwplayer("container") !== null) {            
	            jwplayer("container").setup({
	                file: replace.replace('medium', 'video').replace('jpg', 'mp4'),
	                flashplayer: "/jwplayer/player.swf",
	                autostart: true,
	                height: 270,
	                width: 325
	            });            
            }

            $('.zoomIcon').hide();

        } else {
            
            var newUrl = replace.split('/medium/').join('/large/');
            $('.productImages').find('.lightbox').attr('href', newUrl);
            $('.productImagesMainBorder').html('<a class="lightbox" href="' + newUrl + '"><img src="' + $(this).children('img').attr('rel') + '" /></a>');
            $('.zoomIcon').show();
            if ($('.bestSellerRibbon').parent().hasClass('productImages')) {
            	$('.bestSellerRibbon').replaceWith('<a class="lightbox" href="' + newUrl + '"><div class="bestSellerRibbon"></div></a>');
            }
            if ($('.riskfreeRibbon').parent().hasClass('productImages')) {
            	$('.riskfreeRibbon').replaceWith('<a class="lightbox" href="' + newUrl + '"><div class="riskfreeRibbon"></div></a>');
            }
            if ($('.testedRibbon').parent().hasClass('productImages')) {
            	$('testedRibbon').replaceWith('<a class="lightbox" href="' + newUrl + '"><div class="testedRibbon"></div></a>');
            }
            $(".lightbox").lightbox({ });
            
    	}
        
    });
    
    $('.productAddButton, .productByMoreButton').live('click', function() {
        addToCart();
    	if ($('.priceValue').html() == 'Free') {
    		$('.buyContainer').remove();
    	}
    });
    
    
    $("#write_review_form").validate({
        
        submitHandler: function(form) {
            
            $('.success').show();
            $('#write_review').html($('.success').html());
            
            $(form).ajaxSubmit({
                success: function(data) {
                    // console.log(data);
                }
            })
        },
        focusInvalid: true,
        focusCleanup: true,
        rules: {
            overall_rating: {
                required: true
            },
            review_summary: {
                required: true
            },
            nickname: {
                required: true
            },
            your_review: {
                required: true,
                minlength: 50  
            },
            email: {
                required: true,
                email: true
            }
            
        },
        messages: {
            overall_rating: {
                required: '<div class="rating_error"><span style="color: red">This field is required</span></div>'
            },
            review_summary: {
                required: '<br><span style="color: red">This field is required</span>'
            },
            nickname: {
                required: '<br><span style="color: red">This field is required</span>'
            },
            your_review: {
                required: '<br><span style="color: red">This field is required</span>',
                minlength: '<br><span style="color: red">You must write at least 50 characters for this field</span>'
            },
            email: {
                required: '<br><span style="color: red">This field is required</span>',
                email: '<br><span style="color: red">This field is not valid</span>'
            }
        }
    });    
    
});

function itemTpl(qty) {
    price = productJson.calcPrice[1]; 
    var item = '<strong>' + productJson.firstName + '</strong>'
        + '<div><span class="value">' + qty + '</span>$<span class="price">' + (price - (price % 1)) + '</span>.<span class="c">' + (price % 1).toFixed(2).substr(2) + '</span></div>'
        + '<a href="/' + productJson.urlName + '">' + productJson.secondName + '</a>';
    return item;
}


function addToCart() {
    
    if (added < 8) {
        
        $('.buyContainer').find('.mask').show();
        
        userActionFlag = 0;
        
        $.ajax({
            type: 'post', 
            url: '/cart.ajax.php',
            data: {
                isCartBlock: true,
                action: 'add',
                name: $('.selfLink').attr('value'),
                item: $('.itemNumber').attr('value'),
                qty: parseInt($("#addQty option:selected").val())
            },
            success: function(msg) {
                $('.buyContainer').find('.mask').hide();
                $('div#cart').replaceWith(msg);
                added = added + parseInt($("#addQty option:selected").val()) > 8 ? 8 : added + parseInt($("#addQty option:selected").val());
                drawActualOrderState();
                $('.withimage').show();
                openCart();

                setTimeout("$('.withimage').hide(); $('.lastAdded').show(); if (!userActionFlag) { closeCart(); }", 10000);
            }
        });
        
    }
}

function drawActualOrderState() {
    if (added > 0) {
        $('.productAddButton').addClass('productByMoreButton').removeClass('productAddButton');
    }
    $('#addQty').html(function() {
        var list = '';
        if ($('.priceValue').html() == 'Free') {
        	list += '<option value="1">&nbsp;1&nbsp;</option>';
        } else {
            for (var i = 1; i <= 8 - added; i++ ) {
                list += '<option value="' + i + '">&nbsp;' + i + '&nbsp;</option>';
            }
        }
        return list;
    });
    if (added >= 8) {
        $('.productAddButton, .productByMoreButton').css('opacity', '0.3').css('cursor', 'default').unbind('click');
        $('.Qty').css('opacity', '0');
    }
}

