$(document).ready(function() {
    // If we have a qlDialog, create the Quick Look dialog object
    var $qlDialog = $("#qlDialog");
    if ($qlDialog.length > 0) {
        $qlDialog.dialog( { draggable: false, autoOpen: false, resizable: false, height: 240, width: 420 });
    }
    
    // Check for bad images
    $('#productArea img').each(
        function(i) {
            var $img = $(this);
            $img.error(
                function() {
                    this.src="https://www.twopeasinabucket.com/graphics/brk_img_100x100.gif";
                }
            );
        }
    );
});

/*
    Update the Quick Look body and Display
*/
function updateQL(text) {
    $qlDialog = $("#qlDialog");
    $qlDialog.html(unescape(unescape(text)));
    $qlDialog.dialog( { position: 'center' });
    $qlDialog.dialog("open");
}

/*
    Add a product to the user's cart
*/
function addToBucket(form) {
    var $form = $(form);
    var product_id = $form.attr("id").split('_')[1]
    var $statusArea = $('#addStatusArea_' + product_id)
    var $imageViewerStatusArea = $('#imageViewerAddBucketStatusArea')
    
    // Add to bucket callback
    function addToBucketCallback(data) {
        // Check if this item was already in the cart
        if (data.search(":") >= 0) {
            $statusArea.html("Item Added To Cart");
            $imageViewerStatusArea.html('Item Added To Cart');
            showAddedToCartDialog(data);
        } else {
            $statusArea.html("Item Already In Cart");
            $imageViewerStatusArea.html('Item Already In Cart');
        }
        return false;
    }
    
    // Hide the quick look, hide the form and display some status
    $("#qlDialog").dialog("close");
    $form.hide();
    $statusArea.html('Adding item to cart...').show();
    $imageViewerStatusArea.html('Adding item to cart...').show();
    
    // Ajaxify the form and submit
    $form.ajaxForm();
    $form.ajaxSubmit({success: addToBucketCallback, url: '/shop_bucket/add/'});
    
    return false;
}

/*
    Display Added To Cart Dialog
*/
function showAddedToCartDialog(data) {
    a = data.split(":");
    var request = {
        totalCost: a[0],
        itemsInBucket: a[1],
        cartTotal: a[2],
        curProductId: a[3],
        priceEach: a[4],
        itemQuantity: a[5],
        isLoggedIn: a[6]
    }

    // Header Cart Summary
    $("#headerItemsInBucket").html(request.itemsInBucket);
    $("#headerCartTotal").html(request.cartTotal);

    // Panel Cart Summary and Link
    var panelFooter = "<br />Items in Cart: " + request.itemsInBucket + "&nbsp;&nbsp;|&nbsp;&nbsp; Cart Subtotal: " + request.cartTotal 
    panelFooter += '<br /><a href="/shop_bucket/">View Cart</a>'    
    
    // Product Image
    src = $('#product_image_' + request.curProductId)[0].src
    icon = '<img src=' + src + ' style="margin-left:5px; max-width:100px; width:expression(this.width > 100 ? 100 : true); max-height:100px; height: expression(this.height > 100 ? 100 : true);">'
    
    // Dialog HTML
    var boxHTML = '<b>' + document.getElementById('productName_' + request.curProductId).innerHTML + '</b>';
    boxHTML += '<table><tr><td>Price:</td><td>' + request.priceEach + '</td></tr>'
    boxHTML += '<tr><td>Quantity:</td><td>' + request.itemQuantity + '</td></tr>'
    boxHTML += '<tr><td>Total:</td><td>' + request.totalCost + "</td></tr></table>"
    
    // Create the Dialog and display
    showTopRightNotification("Item Added To Cart", boxHTML, panelFooter, icon)
}

/*
    Add a product to the user's wishlist
*/
function addToWishList(product_id) {
    // Throbber
    if ( $('#addToWishImg').length > 0 ) {
        $('#addToWishImg').show();
    } else {
        $('#addToWishText_' + product_id).html('<span class="standouttext">Adding To Wishlist...</span>');
    }

    // Doit
    $.get("/shop_bucket/add/",
        { ajax: "true", wish: "1", 'product_id': product_id },
        function(data) {
            if ( $('#addToWishImg').length > 0 ) {
                $('#addToWishImg').hide();
                $('#addToWishText').html('<span class="standouttext">Item added to your wishlist</span>');
            } else {
                $('#addToWishText_' + product_id).html('<span class="standouttext">Item added to your wishlist</span>');
            }
        }
    );
}
var addToWish = addToWishList;

/*
    Add a product to the user's Bookmarks
*/
function addToBos(product_id) {
	$("#addToBosImg").show();
    $.get("/bos_add_ajax.asp", {t: 'PROD', id: product_id}, function(data) {
        $("#addToBosText").html("<span class=\"standouttext\">Item added to your bookmarks</span>");
	    $("#addToBosImg").hide();
    });
	return false;
}

/*
    Add a product to a user's recommended produts
*/
function addToRecommended(product_id) {
	$("#addToRecommendedImg").show();
    $.get("/AJAX/addToRecommendedProducts.asp", {product_id: product_id}, function(data) {
        $("#addToRecommendedText").html("<span class=\"standouttext\">Item added to your recommended products</span>");
	    $("#addToRecommendedImg").hide();   
    });
	return false;
}


var notifySlots = new Array(50);
var doCheck = true;
var session_id = "";

// $(document).ready(function(){
//     
//     // Get Session ID
//     session_id = $.cookie('TwoPeasSession');
//     
//     if (session_id.length > 0) {
//         
//         // Fill notifySlots array
//         $.each(notifySlots, function(i, val) {
//             notifySlots[i] = false;
//         });
//         
//         // Start Notify Loop
//         //doNotificationCheck();
//         //setInterval("doNotificationCheck()", 10000);
//         
//     }
// });

function doNotificationCheck() {
    if (doCheck) {
        $.getJSON(document.location.protocol + '//www.twopeasinabucket.com/notification/?callback=?', {id: session_id}, function(data) {
            if (data != "BAD") {
                for (var i=0; i < data.length; i++) {
                    // loop all slots and find first availble slot
                    for (var j=0; j < 50; j++) {
                        if (!notifySlots[j]) {
                            notifySlots[j] = true;
                            showNotification(data[i].title, data[i].body, j, data[i].icon_url);
                            
                            // Update PeaMail Count
                            if (data[i].type_id == 4 && data[i].pea_mail_new) {
                                $('#peaMailNew').text(data[i].pea_mail_new);
                            }
                            break;
                        }
                    }
                } 
            } else {
                doCheck = false;
            }          
        });
    }
}

function showNotification(title, body, slot, icon_url) {

    // How many can we fit per column?
    var vert = parseInt($(window).height() / 110)
    
    // determine column and row (0 indexed)
    var column = Math.floor(slot / vert);
    var row = slot - column * vert
    
    // Determine location
    var right = (column * 250) + 10 + (column * 10)
    var bottom = (row * 100) + 10 + (row * 10)

    // Create notification DOM object
    $note = $('#baseNotification').clone().css('bottom', bottom).css('right', right);
    $note.notificationmsg({slot: slot});
    $note.appendTo('body');
    
    // determine if we have an icon
    if (icon_url && icon_url.length > 0) {
        if ($.browser.msie && parseInt($.browser.version) == 6) {
            icon_url = icon_url.replace(".png", ".gif");
        }
        icon_html = '<img style="padding-left: 3px;" src="' + icon_url + '" />'
    } else {
        icon_html = ""
    }
    
    // Updated contents and show
    $note.html($note.html().replace('{{ title }}', title));
    $note.html($note.html().replace('{{ body }}', body));
    $note.html($note.html().replace('{{ slot }}', slot));
    $note.html($note.html().replace('{{ icon }}', icon_html));
    $note.html($note.html().replace('{{ footer }}', ""));
    
    // Treat the close button specially if we are in IE6
    $img = $note.children('span').children('img');
    if ($.browser.msie && parseInt($.browser.version) == 6) {
        $img.attr("src", '/static/graphics/shop/notification/closebox_pressed.gif');
        $img.hover( function() { this.src = '/static/graphics/shop/notification/closebox.gif' }, function() { this.src = '/static/graphics/shop/notification/closebox_pressed.gif' });
    } else {
        $img.hover( function() { this.src = '/static/graphics/shop/notification/closebox.png' }, function() { this.src = '/static/graphics/shop/notification/closebox_pressed.png' });
    }
    
    $note.notificationmsg('show');
}

/*
    Show a dialog that is not slotted (positioned at the top right)
*/
function showTopRightNotification(title, body, footer, icon) {
    
    // Hide any existing
    $(".topRightNotification").notificationmsg("hide");
    
    // Create notification DOM object
    yOffset = (document.all)?document.documentElement.scrollTop:window.pageYOffset + 30;
    $note = $('#baseNotification').clone().addClass("topRightNotification").css("top", yOffset.toString() + 'px');
    $note.notificationmsg({slot: 'topRightNotification'});
    $note.appendTo('body');
    
    // Populate the Dialog
    $note.html($note.html().replace('{* title *}', title));
    $note.html($note.html().replace('{* body *}', body));
    $note.html($note.html().replace('{* footer *}', footer));
    $note.html($note.html().replace('{* slot *}', "topRightNotification"));
    $note.html($note.html().replace('{* icon *}', icon));

    // Treat the close button specially if we are in IE6
    $img = $note.children('span').children('img');
    if ($.browser.msie && parseInt($.browser.version) == 6) {
        $img.attr("src", '/static/graphics/shop/notification/closebox_pressed.gif');
        $img.hover( function() { this.src = '/static/graphics/shop/notification/closebox.gif' }, function() { this.src = '/static/graphics/shop/notification/closebox_pressed.gif' });
    } else {
        $img.hover( function() { this.src = '/static/graphics/shop/notification/closebox.png' }, function() { this.src = '/static/graphics/shop/notification/closebox_pressed.png' });
    }
 
    $note.notificationmsg('show');
}

/* 
    Widget for notification message 
*/
(function($) {
    $.widget("ui.notificationmsg", {
        
        init: function() {
            $.ui.notificationmsg._bottompost=this.element.css("bottom");
            $.ui.notificationmsg._height=this.element.css("height");  
        },
        
        show: function(){
            var o = this.options;
            if(this.element.is(":hidden")){
                this.element.queue( function() { $.ui.notificationmsg.animations[o.animation](this, o); } ).dequeue();
            }            
        },
        
        hide: function(){
            this.element.stop(true);
            var o = this.options;
            if(this.element.is(":visible")){
                this.element.queue(function(){$.ui.notificationmsg.animations[o.animation](this, o);}).dequeue();
            }
        }
        
    });    
    $.ui.notificationmsg._bottompost = "0px";
    $.ui.notificationmsg._css;
    $.extend($.ui.notificationmsg.prototype, {
        options: {
            // speed for the animation
            speed: 2000,
            // provide a period for the popup to keep showing
            period: 10000, 
            // animation algorithm
            animation:'fade',
            // Slot number for this notification
            slot: 0
        }
    })
    $.extend($.ui.notificationmsg, {
        animations: {
            fade: function(e, options) {
                
                function fadeCloseIn() {
                    $(".notificationCloseButton_" + options.slot).fadeIn();
                }
                function fadeCloseOut() {
                    $(".notificationCloseButton_" + options.slot).fadeOut();
                }
        
                if($(e).is(":hidden")){
                    var timeout;
                    
                    //  animate
                    $anim = $(e).animate({opacity: "show"}, options.speed);
                    
                    // Set Timer
                    timeout = setTimeout(function() { $(e).notificationmsg('hide'); }, options.period )
                    
                    // Set events
                    $(e).hover(fadeCloseIn, fadeCloseOut);
                    $(".notificationCloseButton_" + options.slot).click( function() { 
                        options.speed = 500;
                        $(e).notificationmsg('hide'); 
                    });
                    $(e).mouseover( function() {
                        clearTimeout(timeout);
                    });
                    $(e).mouseout( function() {
                        timeout = setTimeout(function() { $(e).notificationmsg('hide'); }, options.period )
                    });
                }
                else{
                    $(e).animate({opacity: "hide"}, options.speed, function () { notifySlots[options.slot] = false; });
                }
                
                $(e).css("opacity",1.0);
            }
        }
    });
})(jQuery);

