// Uses http://jQuery.com
var portfolioDocumentsHideTimeout = null;
var portfolioDocumentsShown = false;
var portfolioResizeTimer = null;

$(function()
{
    // Insert background opacity object
    $('body').append('<div id=\'portfoliodocuments-background\' style=\'display:none\'>&nbsp;</div>');
    
    // Hide when background clicked
    $('#portfoliodocuments-background').click(
        function()
        {
            ShowHidePortfolioDocuments();
        }
    );
            
    // Show/Hide document details
    $('#portfoliodocuments').click(
        function()
        {
            ShowHidePortfolioDocuments();
        }
    );
    
    // Validation
   //$('input.portfoliodocuments-buttonsubmit').live('click', 
   $('input.portfoliodocuments-buttonsubmit').click(
        function()
        {
            var valid = $('#aspnetForm').validate({ 
                errorClass:'formerror', 
                errorElement:'div',
                //errorLabelContainer:'#validationMessage',
                //wrapper:"li",
                rules: {
                    txtTo: "required",
                    txtFrom: "required",
                    txtMessage: "required"
                }
            }).form();

            if (valid)
            {
                var vintageId = $('#VintageId').val();   // I don't think this will ever exist
                var wineryId = $('#WineryId').val();    // There is a global winery id on the Producer page
                var siteId = 0;
                var to = $('#txtTo').val();
                var from = $('#txtFrom').val();
                var message = $('#txtMessage').val();
                var attachAs = $("input[@name='attachDocumentsAs']:checked").val();
                
                DoAction({w:wineryId, v:vintageId, site:siteId, action:'doemail', txtTo:to, txtFrom:from, txtMessage:message, attachDocumentsAs:attachAs });
            }
            
            return false;
        }
    );
    
        // Prevent links from bubbling, but we still want to follow any links
    // Add some "ajax" style handling to the document add links
    $('a.add').click(
        function(event)
        {
            event.stopPropagation();
            return DynmaicAddDocument($(this));
        }
     );
     
    // The vintage document links do not exist at time of document load, so use live binding to attach to those.
    $('a.add').live('click',
        function(event)
        {
            return DynmaicAddDocument($(this));
        }
    );
    
    // Prevent links from bubbling, but we still want to follow any links
    $('a.file').click(
        function(event)
        {
            event.stopPropagation();
        }
    );
    
    UpdateDocumentTitle();
});

$(window).bind('resize', function() {
    if (portfolioResizeTimer) clearTimeout(portfolioResizeTimer);
    portfolioResizeTimer = setTimeout('MovePopup();', 100);
});

function ShowHidePortfolioDocuments()
{
    if (portfolioDocumentsShown)
    {
        $('#portfoliodocuments-popup').slideUp(200);
        $('#portfoliodocuments-background').fadeOut(200, function() {
            if(jQuery.browser.msie) this.style.removeAttribute('filter');
        });
        $('#portfoliodocuments > span').removeClass('selected');
    }
    else
    {
        $('#portfoliodocuments > span').addClass('selected');
        $('#portfoliodocuments-background').fadeIn(200, function() {
            if(jQuery.browser.msie) this.style.removeAttribute('filter');
        });
        MovePopup();
        $('#portfoliodocuments-popup').slideDown(200);
    }
    portfolioDocumentsShown = !portfolioDocumentsShown;
}

function MovePopup()
{
    var objPDocs = $('#portfoliodocuments');
    var objFrame = $('.frame');
    
    var leftpos = objFrame.position().left
    if (leftpos == 0)
        leftpos = objFrame[0].offsetLeft;

    $('#portfoliodocuments-popup').css('left', leftpos);
    $('#portfoliodocuments-popup').css('top', objFrame.position().top + objPDocs.position().top + objPDocs.height());
}
// Call documents.aspx, and inject the HTML into the correct locations.
function DoAction(tupples)
{
    $.post(gDocumentsLocation, tupples, function(data)
        {
            var doclist = $(data).find('div.document-list');
            var docbutton = $(data).find('#portfoliodocuments');
            var docmessage = $(data).find('#portfoliodocuments-popup > div.message');
            var docCount = parseInt(docbutton.find('span > strong').html(), 10);

            $('div.document-list').html( doclist.html() );
            $('#portfoliodocuments').html( docbutton.html() );
            $('#portfoliodocuments-popup > div.message').html( docmessage.html() );
            
            if ($('#portfoliodocuments-popup > div.message').html().length > 0)
                $('#portfoliodocuments-popup > div.message').show();
            else
                $('#portfoliodocuments-popup > div.message').hide(); 
         }
     );
}

function DynmaicAddDocument(obj) {
    var vintageId = obj.find('.VintageId').val();
    var siteId = 0;
    var assetId = obj.siblings('.AssetId').val();
    var wineryId = obj.siblings('.WineryId').val();
    
    DoAction({w:wineryId, v:vintageId, site:siteId, action:'docadd', asset:assetId});

    obj.parent().toggleClass('remove');

    UpdateDocumentTitle();
    return false;
}

function UpdateDocumentTitle()
{
    // Producer and Item (Vintage) documents. Doc cart items are hard-coded since they will always be "remove".
    $('div.producer-downloads, div.item').each(function() {
        $(this).find('ul.tastingnote > li, ul.pos > li, ul.press > li, ul.image > li').each(function(idx) {
            if ($(this).hasClass('remove')) 
            {
                $(this).children('a.add').attr('title', 'Click to remove from e-mail cart');
            }
            else
            {
                $(this).children('a.add').attr('title', 'Click to add to e-mail cart');
            }
        });    
    });
}
