var productImageViewerImages = null;
var productImageViewerImage = null;

function showProductImages(productId, imageId) {
    productImageViewerImages = null;
    productImageViewerImage = null;
    $('#productImageViewerDiv .leftBar').hide();
    $('#imageViewerAddBucketStatusArea').hide();
    $('#imageViewerAddBucketForm').show();
    $('#productImageViewerDiv').dialog('open');
    var $imageViewerImg = $('#imageViewerPrimary')
    $imageViewerImg.parent().addClass('loading');
    $imageViewerImg.hide();
    if ($('#productImageViewerDiv .zoomable').hasClass('zoomOut')) {
        $('#productImageViewerDiv .zoomable').removeClass('zoomOut');
        $('#productImageViewerDiv .zoomable').addClass('zoomIn');
    }
    
    $.ajax({
      url: "/shop/"+productId+"/data/",
      dataType:'json',
      error:function(jqXHR, textStatus, errorThrown) {
          alert('Could not load product info: ' + textStatus);
      },
      success:function(data){
          populateProductImageViewer(data, imageId);
      }
    });
}

function populateProductImageViewer(productInfo, toShowImageId) {
    // console.log('Product Info: ', productInfo)
    $('#imageViewerProductName').html(productInfo['product_name']);
    $('#imageViewerBrandName').html(productInfo['brand_name']);
    if (productInfo['alternate_versions']) {
        if (productInfo['sale_price']) {
            versions_text = '<input type="radio" name="theProdID" value="' + productInfo['product_iid'] + '"<strike>' + productInfo['reg_price'] + '</strike> <span class="standouttext">' + productInfo['sale_price'] + '</span> Personal License</input><br />';
        } else {
            versions_text = '<input type="radio" name="theProdID" value="' + productInfo['product_iid'] + '">' + productInfo['reg_price'] + ' Personal License</input><br />';
        }
        $.each(productInfo['alternate_versions'], function(index, version) { 
            if (version['description']) {
                versions_text += '<input type="radio" name="theProdID" value="' + version['product_id'] + '"><strike>' + version['reg_price'] + '</strike> <span class="standouttext">' + version['cur_promo_price'] + '</span> ' + version['title'] + '</input><br />';
            } else {
                versions_text += '<input type="radio" name="theProdID" value="' + version['product_id'] + '">' + version['reg_price'] + ' ' + version['title'] + '</input><br />';
            }
        });
        $('#imageViewerPriceSection').html(versions_text);
    } else if (productInfo['commercial_version']) {
        if (productInfo['sale_price']) {
            $('#imageViewerPriceSection').html('<input type="radio" name="theProdID" value="' + productInfo['product_iid'] + '"<strike>' + productInfo['reg_price'] + '</strike> <span class="standouttext">' + productInfo['sale_price'] + '</span> Personal License</input><br /><input type="radio" name="theProdID" value="' + productInfo['commercial_version']['product_iid'] + '"><strike>' + productInfo['commercial_version']['reg_price'] + '</strike> <span class="standouttext">' + productInfo['commercial_version']['sale_price'] + '</span> Commercial License</input>');
        } else {
            $('#imageViewerPriceSection').html('<input type="radio" name="theProdID" value="' + productInfo['product_iid'] + '">' + productInfo['reg_price'] + ' Personal License</input><br /><input type="radio" name="theProdID" value="' + productInfo['commercial_version']['product_iid'] + '">' + productInfo['commercial_version']['reg_price'] + ' Commercial License</input>');
        }
    } else {
        if (productInfo['sale_price']) {
            $('#imageViewerPriceSection').html('<strike>' + productInfo['reg_price'] + '</strike> <span class="standouttext">' + productInfo['sale_price'] + '</span><input type="hidden" name="theProdID" value="' + productInfo['product_iid'] + '">');
        } else {
            $('#imageViewerPriceSection').html('' + productInfo['reg_price'] + '<input type="hidden" name="theProdID" value="' + productInfo['product_iid'] + '">');
        }
    }

    productImageViewerImages = {};
    var $imageViewerThumbnails = $('#imageViewerThumbnails');
    $imageViewerThumbnails.html('');
    $(productInfo['product_images']).each(function(index, imageData) {
        var imageId = imageData['id'];
        productImageViewerImages[imageId] = imageData;
        if (imageId == toShowImageId) {
            productImageViewerImage = imageData;
        }
        $imageViewerThumbnails.append('<div class="imageViewerThumbnail" style="width:64px; height:64px; margin-left:10px; margin-top:10px; text-align:center; float:left;"><img id="imageViewerThumbnail_' + imageData['id'] + '" src="' + imageData['thumbnail_url'] + '" style="max-width:64px; max-height:64px;" /></div>');
    });
    $imageViewerThumbnails.append('<div style="clear:both;"></div>');
    
    $('#productImageViewerDiv .leftBar').show();
    
    if (productImageViewerImage === null) {
        productImageViewerImage = productImageViewerImages[0];
    }
    if ($('#imageViewerPrimary')[0].src !== productImageViewerImage['medium_url']) {
        $('#imageViewerPrimary')[0].src = productImageViewerImage['medium_url'];
    } else {
        $('#imageViewerPrimary').parent().removeClass('loading');
        $('#imageViewerPrimary').fadeIn();
    }
}

$(document).ready(function() {
    $('#productImageViewerDiv').dialog({ autoOpen:false, modal:true, resizable:false, width:895,  height:675, dialogClass:'imageViewer', closeText:'close' })

    $('#imageViewerAddBucketForm').submit(function() {
        addToBucket(this);
        return false;  
    })

    $('#imageViewerPrimary').load(function () {
        $(this).parent().removeClass('loading');
        $(this).fadeIn();
    }).error(function () {
        alert('Error loading image viewer image.');
    });

    $('#productImageViewerDiv .zoomable').addClass('zoomIn');
    $('#productImageViewerDiv .zoomable').click(function(e) {
        if (productImageViewerImage) {
            if ($('#productImageViewerDiv .zoomable').hasClass('zoomIn')) {
                $('#productImageViewerDiv .zoomable').removeClass('zoomIn');
                $('#productImageViewerDiv .zoomable').addClass('zoomOut');
                $('#productImageViewerDiv .zoomable img')[0].src = productImageViewerImage['large_url'];
            } else {
                $('#productImageViewerDiv .zoomable').removeClass('zoomOut');
                $('#productImageViewerDiv .zoomable').addClass('zoomIn');
                $('#productImageViewerDiv .zoomable img')[0].src = productImageViewerImage['medium_url'];
            }
        }
    });

    $('#productImageViewerDiv .zoomable').mousemove(function(e){
        var zoomableWidth = $(this).width();
        var zoomableHeight = $(this).height();
        var $parent = $(this).parent();
        var parentWidth = $parent[0].clientWidth;
        var parentHeight = $parent[0].clientHeight;
        if (zoomableWidth > parentWidth) {
            var dx = (zoomableWidth-parentWidth) / parentWidth;
            var x = e.pageX - $(this).parent().offset().left;
            var newScrollLeft = x * dx;
            $parent.scrollLeft(newScrollLeft);
        }
        if (zoomableHeight > parentHeight) {
            var dy = (zoomableHeight-parentHeight) / parentHeight;
            var y = e.pageY - $(this).parent().offset().top;
            var newScrollTop = y * dy;
            $parent.scrollTop(newScrollTop);
        }
    });

    $('#productImageViewerDiv .imageViewerThumbnail img').live('click', function(e) {
        var idParts = this.id.split('_');
        var imageId = idParts[idParts.length-1];
        var imageData = productImageViewerImages[imageId];
        var $imageViewerImg = $('#imageViewerPrimary')
        if ($imageViewerImg[0].src !== imageData['medium_url']) {
            $imageViewerImg.parent().addClass('loading');
            $imageViewerImg.hide();
            if ($('#productImageViewerDiv .zoomable').hasClass('zoomOut')) {
                $('#productImageViewerDiv .zoomable').removeClass('zoomOut');
                $('#productImageViewerDiv .zoomable').addClass('zoomIn');
            }
            $imageViewerImg[0].src = imageData['medium_url'];
            productImageViewerImage = imageData;
        }
    });
});

