$(document).ready(function(){

    $("a[rel='gallery']").colorbox();
    $("a[rel='gallery1']").colorbox();
    $("a[rel='gallery2']").colorbox();
    $("a[rel='gallery3']").colorbox();

    $('a[rel=external]').click(function(){
        window.open($(this).attr('href')); return false;
    });

    $('#mals').show();
    $('#mals2').show();
    
    $('a[rel=popup]').click(function(){
        window.open($(this).attr('href'), 'popUp', 'width=300,height=200,status=0,toolbar=0'); return false;
    });

    $('input[type=image], img.hover').each( function(){ 
        // Preload
        var x = new Image();
        x.src = this.src.substring(0, this.src.length - 5) + "2.jpg";

        // Mouseover
        $(this).mouseover( function(){ 
            this.src = this.src.substring(0, this.src.length - 5) + "2.jpg"; 
        });

        // Mouseout
        $(this).mouseout( function(){
            if (this.src.substring( (this.src.length - 5) , (this.src.length) ) == "2.jpg" ) { 
                this.src = this.src.substring(0, this.src.length - 5) + "1.jpg"; 
            }
        });
    });

    var ider = 2;

    if ($('#mals2').length != 0) {
        // Setup calculator
        $('#mals2 #quantity').live('click keyup change', function(){
            calculateExtras();
        });
        $('#mals2 #variant').live('click keyup change', function(){
            calculateExtras();
        });
        calculateExtras();
    }

    function calculateExtras() {
        var q = parseInt($('#mals2 #quantity').val());
        if ((parseFloat(q) != parseInt(q)) && isNaN(q)) {
            q = 1;
        }
        var s = parseFloat($('#mals2 input[name=standard]').val());
        var a = parseFloat($('#mals2 input[name=additional]').val())
        var p = parseFloat($('#mals2 input[name=price]').attr('rel'));
        var np = q * p
        
        // update title
        $('#mals2 input[name=product]').val($('#mals2 input[name=product]').attr('rel') + ' x' + q)
        if ($('#mals2 #variant').length != 0) {
            var t = $('#mals2 input[name=product]').attr('rel');
            var tt = $('#mals2 #variant option:selected').eq(0).html()
            $('#mals2 input[name=product]').val(t + ' (' + tt + ')' + ' x' + q);
        }
        // update price
        $('#mals2 input[name=price]').val(Math.round(np*100)/100);
        if ($('#mals2 #variant').length != 0) {
            $('#mals2 input[name=price]').val($('#mals2 #variant option:selected').eq(0).val() * q);
            $('#mainprice span').html($('#mals2 #variant option:selected').eq(0).val())
        }
        // update shipping
        $('#mals2 input[name=units]').val(s);
        if (q > 1) {
            $('#mals2 input[name=units]').val(s + (a * q) - a);
        }
    }
    
    if ($('#pieces').length != 0) {
    
        // Setup addPiece
        $('#addPiece').click( function(){
            addPiece();
        });

        // Setup removePiece
        $('.removePiece').live('click', function(){
            removePiece($(this));
        });

        // Setup calculator
        $('#pieces select').live('click keyup change', function(){
            calculatePiece($(this).parents('tr'));
        });
        
        // Setup gluestick/seaming
        $('#seaming input, #gluestick input').live('click keyup change', function(){
            calculateTotal();
        });

        // Recalibrate list
        reCalibrate();
    }

    $('#mals').submit(function(){
        var t = 0;
        $('#pieces tr .malprice').each(function(){
            t+= parseFloat($(this).val());
        });
        if (t < 1) {
            alert("Please select your dimensions before adding to the cart!");
            return false;
        }
    })
    
    // Add a piece
    function addPiece() {
        $('#pieces tr:eq(1)').clone().appendTo('#pieces');
        // Generate some unique ids for the new piece
        $('#pieces tr:last-child label[for=width]').attr('for','width' + ider);
        $('#pieces tr:last-child label[for=height]').attr('for','height' + ider);
        $('#pieces tr:last-child .width').attr('id','width' + ider);
        $('#pieces tr:last-child .height').attr('id','height' + ider);
        $('#pieces tr:last-child .price').html('0.00');
        $('#pieces tr:last-child .ppm').html('0.00');
        $('#pieces tr:last-child .metres').html('0');
        $('#pieces tr:last-child .malprice').val('0.00');
        $('#pieces tr:last-child .units').val('0');
        $('#pieces tr:last-child .title').val('');
        $('#pieces tr:last-child select option:first-child').attr('selected', true);
        ider++;
        reCalibrate();
    }

    // Remove a piece
    function removePiece(that) {
        $(that).parents('tr').remove();
        reCalibrate();
    }

    // Ensures the correct remove links are show, and hides the remove if only one element exists
    function reCalibrate() {
        
        // Hide/show remove/add buttons
        $('.removePiece, #addPiece').show();
        if ($('.removePiece').length == 1) {
            $('.removePiece').eq(0).hide();
        }
        if ($('.removePiece').length == 48) {
            $('#addPiece').hide();
        } else {
            $('#addPiece').show();
        }

        // Recreate the names in correct order
        var i = 0;
        $('#pieces tr').each(function() {
            $(this).find('input[type=hidden]').each(function() {
                $(this).attr('name', $(this).attr('id') + i);
            });
            $(this).find('select').each(function() {
                $(this).attr('name', $(this).attr('class') + i);
                $(this).attr('id', $(this).attr('class') + i);
            });
            $(this).find('label').each(function() {
                $(this).attr('for', $(this).attr('rel') + i);
            });
            i++;
        });
        $('#seaming .pro').attr('name', 'product' + i);
        $('#seaming .pri').attr('name', 'price' + i);
        $('#seaming input[type=text]').attr('name', 'qty' + i);
        $('#gluestick .pro').attr('name', 'product' + (i + 1));
        $('#gluestick .pri').attr('name', 'price' + (i + 1));
        $('#gluestick input[type=text]').attr('name', 'qty' + (i + 1));
        calculateTotal();
    }
    
    // Calculate Piece
    function calculatePiece(that) {
        var w = $(that).find('.width').val();
        var h = $(that).find('.height').val();
        if (((parseFloat(w) == parseInt(w)) && !isNaN(w)) && ((parseFloat(h) == parseInt(h)) && !isNaN(h))) {
            var p = prices[parseInt(w)][parseInt(h)];
            var s = shipping[parseInt(w)][parseInt(h)];
            var ppsm = p / (w * h);
            $(that).find('.price').eq(0).html(p.toFixed(2));
            $(that).find('.units').eq(0).val(s);
            $(that).find('.metres').eq(0).html(w * h);
            $(that).find('.ppm').eq(0).html(ppsm.toFixed(2));
            $(that).find('.title').eq(0).val($('#product_title').html() + ' (' + w + 'x' + h + ')');
            $(that).find('.malprice').eq(0).val(p.toFixed(2));
        } else {
            $(that).find('.malprice').eq(0).val('0.00');
            $(that).find('.price').eq(0).html('0.00');
        }
        calculateTotal();
    }
    
    // Calculate total from each piece totat
    function calculateTotal() {
   
        var t = 0;
        $('#pieces td .price').each(function(){
            t+= parseFloat($(this).html());
        });
        var s = parseFloat($('#seaming input[type=text]').val());
        var sp = parseFloat($('#seaming span').html());
        var g = parseFloat($('#gluestick input[type=text]').val());
        var gp = parseFloat($('#gluestick span').html());
        s = !isNaN(s) ? s : 0;
        g = !isNaN(g) ? g : 0;
        var st = s * sp;
        var gt = g * gp;
        t+= s * sp;
        t+= g * gp;
        $('#gluestick .price').html(gt.toFixed(2));
        $('#seaming .price').html(st.toFixed(2));
        $('#total').html(t.toFixed(2));
        
    }
    
});
