// DIM {{{
$.extend({
    dim: function(speed, opacity, callback) {
        if($('#__dim').size() > 0) return;
        
        return $('<div>&nbsp;</div>').attr({
                id: '__dim'
            }).css({
            background: '#000',
            height: $(document).height() + "px",
            left: '0px',
            opacity: 0,
            position: 'absolute',
            top: '0px',
            width: '100%',
            zIndex: 999
        }).appendTo(document.body).fadeTo(speed, opacity, callback);
    },
    
    dimOff: function(speed, callback) {
        $('#__dim').fadeOut(speed, function() {
            $('#__dim').remove();
            if(typeof callback == 'function') callback();
        });
    }
}); // }}}

// CENTER {{{
$.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.outerHeight() ) /
            2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.outerWidth() ) /
            2+$(window).scrollLeft() + "px");
    return this;
}; // }}}

var update_cart = function() {
    $.ajax({
        url: '/order/cart.json',
        cache: false,
        dataType: 'json',
        success: function(data) {
            if (data.items == 1) {
                $('#cart-items').html('1 item');
            } else {
                $('#cart-items').html(data.items + ' items');
            }
            $('.subtotal').html('$' + data.subtotal);
        }});
};

var product_open = function() {
    $('#product-popup p.close').click(product_close);
    $('#product-popup select').val('1');
    $('#product-popup p.more a').attr('href', '/products/' + $(this).children('p.sku').html() + '/');
    $('#product-popup img.product').attr('src', $(this).children('img.lightbox').attr('src'));
    $('#product-popup img.nut-facts').attr('src', $(this).children('img.facts').attr('src'));
    $('#product-popup div.facts_description').html($(this).children('div.facts_description').html());
    $('#product-popup .name').html($(this).children('h3').html());
    $('#product-popup p.sku').html($(this).children('p.sku').html());
    $('#product-popup ul').html($(this).children('ul').html());
    $('#product-popup').center();
    $.dim(200, 0.5);
    $('#product-popup').fadeIn();
    return false;
};

var product_close = function() {
    $('#product-popup p.status').html('');
    $('#product-popup').fadeOut();
    $.dimOff(200);
};

var product_ordered = function(base) { return function () {
    units = base.parent().children('select').val();
    //units = $('#product-popup select').val();
    title = base.parents().children('.name').html()
    if (title==null){ title = base.parents().children('a').children('.name').html() }
    if (title==null){ title = "" }
    base.parents().children('p.status').hide().html(units + ' ' + title + ' added to your <a href="/order/cart/">shopping cart</a>.').fadeIn();
    base.parents().children('img.throbber').hide();
    base.parents().children('p.add-cart').hide();
    base.parents().children('select.hides').hide();
    base.parents().children('input[type=submit]').attr('disabled', '');
    update_cart();
};};

var product_order = function() {
    $(this).parent().children('img.throbber').show();
    $(this).attr('disabled', 'disabled');
    //units = $('#product-popup select').val();
    units = $(this).parent().children('select').val();
    if (isNaN(units)) {
        units = 1;
    }
    sku = $(this).parents().find('p.sku').html();
    if (sku == 'coriolus-versicolor-super-strength') {
        coupon = $('#id_coupon').val();
    } else {
        coupon = false;
    }
    $.post('/order/cart/', {'product': sku, 'add': units, 'coupon': coupon}, product_ordered($(this)));
    return false;
};

var quantity_changed = function(quantity) {
    return function() {
        var q = parseInt(quantity.val(),10);
        var free = Math.floor(q/5);
        var freespan = quantity.parent().children('.free');
        freespan.html('+' + free + ' FREE');
        if (free > 0) {
            freespan.show();
        } else {
            freespan.hide();
        }

        update_cart();
    };
};

var change_quantity = function(item) {
    var table = item.parent().parent();
    var units = item.val();
    var sku = table.children('.sku').html();
    var callback = function () {};

    if (isNaN(units)) {
        units = 0;
        item.val('0');
    }

    if (units > 0) {
        callback = quantity_changed(item);
    } else {
        callback = orderitem_deleted(item.parent().parent());
    }

    $.post('/order/cart/', {'product': sku, 'quantity': units}, callback);
};

var orderitem_deleted = function(row) { return function() {
    row.fadeOut(function() {
        row.detach();
        update_cart();
        if ($('table.cart tr.item').length === 0) {
            $('table.cart tr.header').delay(100).after('<tr><td colspan="5" class="empty">Your cart is empty. <a href="/products/">Go to the products page.</a></td></tr>');
            $('table.cart td.checkout').fadeOut();
        }
    });
};};

var delete_orderitem = function(item) {
    var row = item.parent().parent();
    var sku = row.children('.sku').html();
    $.post('/order/cart/', {'product': sku, 'quantity': '0'}, orderitem_deleted(row));
};

var update_shipping = function(type) {
    $.ajax({
        url: '/order/shipping/',
        type: 'post',
        data: 'type=' + type.val(),
        dataType: 'json',
        success: function(data) {
            $('.shipping').html(data.shipping_cost);
            $('.total').html(data.total)
        }
    });
}

/* Deprecating this entire function, had been used for fluid layout
var on_resize = function() {
    var products = $('#products');
    var product_set = $('#products div.product');
    var hcount = Math.floor(products.innerWidth() / 
                                product_set.innerWidth());
    var pad = Math.floor(
        (products.innerWidth()-hcount*product_set.innerWidth()) / 
                                            hcount / 2);

    product_set.css("margin", "5px " + pad + "px");

    if ($.browser.msie && $.browser.version.substr(0,1)<7) {
        $('#product-horiz').width($(document).width()-330);
        $('#product-horiz .scroll').width($('#product-horiz').innerWidth()-56);
        $('#product-horiz .scroll').height(158);
        $('#product-horiz .left, #product-horiz .right').height(158);
    } else {
        $('#product-horiz .scroll').width($('#product-horiz').innerWidth()-50);
        $('#product-horiz .scroll').height($('#product-horiz').innerHeight()-28);
        $('#product-horiz .left, #product-horiz .right').height($('#product-horiz').innerHeight()-28);
    }

};
*/

var hilight_benefit = function() {
    var loc = document.location.toString();

    if (loc.match('#')) {
        var anchor = loc.split('#')[1];
        $('#benefit-list div.benefit').removeClass('selected');
        $('#benefit-' + anchor).addClass('selected');
        $('#benefit-' + anchor).corner();
    }
};

$(function() {
    $('#product-horiz .product').click(product_open);
    $('#product-index .product .add-cart').click(product_order);
    $(".cart .delete a").click(function() { delete_orderitem($(this)); });
    $("td.quantity input").change(function() { change_quantity($(this)); });
    $('#product-popup-info input[type=submit]').click(product_order);
    $('#product-info p.cart img').mouseup(product_order);
    
});

$(function() {
    //$(window).resize(on_resize);
    //$(window).load(function() { $(window).resize(); });

    $('#product-detail menu li, #product-detail menu').mouseup(function() {
        $('#product-detail menu li, #product-detail menu').removeClass('selected');
        if ($(this).attr('id') == 'tab-i') {
            $('#product-detail menu').addClass('selected');
        } else {
            $(this).addClass('selected');
        }
        $('#product-detail .product-text').hide();
        if ($(this).is('#product-detail menu')) {
            $('#product-detail #text-tab-i').show();
        } else {
            $('#product-detail #text-'+$(this).attr('id')).show();
        }
        return false;
    });
    /*
    if (!$.browser.msie) {
        $('#product-detail').cornerz({'radius': 15});
        $('form input').corner();
        $('td.quantity input').corner();
        $('#product-horiz, #product-index').corner();
        $('#product-horiz h2').corner('top');
        $('#product-horiz .left').corner('bl');
        $('#product-horiz .right').corner('br');
        $('#benefit-list').corner();
        $('.corner').corner();
        $('.corner-top').corner('top');
        $('.corner-bottom').corner('bottom');
        $('#benefit-list p.deck').corner('top');
        $('#product-index .product').corner();
        $('#cart-list').corner();
        $('div.box').corner();
        $('div.box h2').corner('top');
        //$('#product-detail img.photo').corner();
    }
    */
    $('#product-horiz .left').click(function() {
        s = $('#product-horiz .scroll');
        s.animate({scrollLeft: s.scrollLeft()-400}, 1000, 'linear');
    });
    $('#product-horiz .right').click(function() {
        s = $('#product-horiz .scroll');
        s.animate({scrollLeft: s.scrollLeft()+400}, 1000, 'linear');
    });

    $('#health-benefits select').change(function() {
        if ($(this).val() !== '') {
            window.location.href = '/benefits/#' + $(this).val();
            hilight_benefit();
        }
    });
    
    $('select.benefits').change(function() {
        if ($(this).val() !== '') {
            window.location.href = '/benefits/#' + $(this).val();
            hilight_benefit();
        }
    });

    $.fipsify('select#id_bill-country', 'select#id_bill-state', 'label[for=id_bill-state]')
    bill_country = $('#id_bill-country_hidden').val();
    if (bill_country != '') {
        $('select#id_bill-country').val(bill_country)
        $('select#id_bill-country').trigger('change');
        if (bill_country === 'Canada' || bill_country === 'United States') {
		    $('#id_bill-company').parent().show();
    		$("label[for='id_bill-address2']").html('Apt. / Bldg. / Floor / Room / Suite #');
    		$('#id_bill-address3').hide();
        } else {
        	$('#id_bill-company').parent().hide();
        	$("label[for='id_bill-address2']").html('');
        	$('#id_bill-address3').show();
        }
        if ($('#id_bill-state_hidden').val() != '') {
            $('select#id_bill-state').val($('#id_bill-state_hidden').val())
        }
    }
    $.fipsify('select#id_ship-country', 'select#id_ship-state', 'label[for=id_ship-state]')
    ship_country = $('#id_ship-country_hidden').val();
    if (ship_country != '') {
        $('select#id_ship-country').val(ship_country)
        $('select#id_ship-country').trigger('change');
        if (ship_country === 'Canada' || ship_country === 'United States') {
		    $('#id_ship-company').parent().show();
    		$("label[for='id_ship-address2']").html('Apt. / Bldg. / Floor / Room / Suite #');
    		$('#id_ship-address3').hide();
        } else {
        	$('#id_ship-company').parent().hide();
        	$("label[for='id_ship-address2']").html('');
        	$('#id_ship-address3').show();
        }
        if ($('#id_ship-state_hidden').val() != '') {
            $('select#id_ship-state').val($('#id_ship-state_hidden').val())
        }
    }

    var $loaded = false;

    $('input[name=same]').change(function() {
        if ($(this).is(':checked')) {
            $('fieldset#info-ship ul').fadeOut();
        } else {
            $('fieldset#info-ship ul').fadeIn();
        }
    });
    
    $('select#id_bill-country').change(function() {
        if ($(this).val() === 'Canada' || $(this).val() === 'United States') {
		    $('#id_bill-company').parent().show();
    		$("label[for='id_bill-address2']").html('Apt. / Bldg. / Floor / Room / Suite #');
    		$('#id_bill-address3').hide();
        } else {
        	$('#id_bill-company').parent().hide();
        	$("label[for='id_bill-address2']").html('');
        	$('#id_bill-address3').show();
        }
        $('#id_bill-country_hidden').val($(this).val());
        $('#id_bill-state_hidden').val($('select#id_bill-state').val());
    });
    
    $('select#id_bill-state').change(function() {
        $('#id_bill-state_hidden').val($(this).val());
    });

    $('select#id_ship-country').change(function() {
        if ($(this).val() === 'Canada' || $(this).val() === 'United States') {
		    $('#id_ship-company').parent().show();
    		$("label[for='id_ship-address2']").html('Apt. / Bldg. / Floor / Room / Suite #');
    		$('#id_ship-address3').hide();
        } else {
        	$('#id_ship-company').parent().hide();
        	$("label[for='id_ship-address2']").html('');
        	$('#id_ship-address3').show();
        }
        $('#id_ship-country_hidden').val($(this).val());
        $('#id_ship-state_hidden').val($('select#id_ship-state').val());
    });

    $('select#id_ship-state').change(function() {
        $('#id_ship-state_hidden').val($(this).val());
    });
    
    $('select#id_shipping').change(function() {
        update_shipping($(this));
    });
    
    $('#cart-list td.quantity input').change(change_quantity);
    $('#cart-list td.delete').click(delete_orderitem);

    hilight_benefit();

    $('.product-name').css('color', $('#product-color').text());
});

$(function() { update_cart(); });

$(window).bind('load', function() {
    $('td.quantity input').each(function (i) {
            quantity_changed($(this))();
    });
    $('input[name=same]').change();
});

$(function() {
	// setup ul.tabs to work as tabs for each div directly under div.panes
	$("ul.tabs").tabs("div.panes > div");
});

$(document).ready(function() {
    $(".slidetabs").tabs(".images > div", {
	   effect: 'fade',
	   fadeOutSpeed: "slow",
	   rotate: true
    }).slideshow({
        interval: 8000,
        autoplay: true,
        clickable: false
    });

    $("img#overlayed2|rel").overlay({
        mask: {
		color: '#000',
		opacity: 0.5
	   }
    });
    $("img#overlayed3|rel").overlay({
        mask: {
		color: '#000',
		opacity: 0.5
	   }
    });
    
    // this is a really bad way of doing this, but jquery tools is buggy. 
    // it should be able to cover all img|rel, but it can't access more than 1
    // with assigning the output to a var. and using the onBeforeLoad functions inline
    // with the overlay call wasn't working.
    /*var overlay2 = $("img#overlayed2|rel").overlay();
    overlay2.onBeforeLoad = function() { $.dim(200, 0.5); }
    overlay2.onBeforeClose = function() { $.dimOff(200); }
    var overlay3 = $("img#overlayed3|rel").overlay();
    overlay3.onBeforeLoad = function() { $.dim(200, 0.5); }
    overlay3.onBeforeClose = function() { $.dimOff(200); } */
    
});    

