$(document).ready(function() {
    // Fix back button issue showing old version of cart amount if updated via ajax
    
    function refreshBasket() {
        $.post('/my-basket/refreshcartcount', function(data) {

            $('#b_details .b_items a').text(data + ' Items');
            $('#floating_basket p span').html(data + ' Items | <a href="/my-basket">view</a>');
        }, 'json');
    }
    
    refreshBasket();
    
    // customer message
    $('.customer_message').delay('4000').fadeOut();

    // Dropdown menu

    $('li.activatemenu').hover(function(){
        $(this).children('ul.dropdown').show();
    },function(){
        $(this).children('ul.dropdown').delay(1600).hide();
    });

    // Notifications

    $('.product_cart').live('click',function(e){
        var productid = $(this).attr('rel');
        //console.log( productid );
        $.ajax({
            type: "GET",
            url: "/my-basket/ajax-to-cart/" + productid,
            success: function() {

                $('#added').fadeIn().delay(2000).fadeOut();
                $('#fade').fadeIn().delay(2500).fadeOut();
                
                refreshBasket();

//                $.get('/my-basket/refreshcartcount', function(data)
//                {
//                    $('#b_details span').html(data + ' Items | <a href="/my-basket">view</a>');
//                    $('#floating_basket p span').html(data + ' Items | <a href="/my-basket">view</a>');
//                });
            }
        })
        e.preventDefault();
    });

    //    $('.product_button_additional').live('click',function(e){
    //        var productid = $(this).attr('rel');
    //        var qty = $('.calculator').val();
    //        //console.log( productid );
    //        $.ajax({
    //            type: "GET",
    //            url: "/cart/ajaxtocartaddition/" + productid + '/' + qty,
    //            success: function() {
    //
    //                $('#added').fadeIn().delay(3000).fadeOut();
    //                $('#fade').fadeIn().delay(3000).fadeOut();
    //
    //                $.get('/my-basket/refreshcartcount', function(data)
    //                {
    //                    $('#b_details span').html(data + ' Items | <a href="/my-basket">view</a>');
    //                    $('#floating_basket p span').html(data + ' Items | <a href="/my-basket">view</a>');
    //                });
    //            }
    //        })
    //        e.preventDefault();
    //    });

    $('.remove a').live('click',function(e){
        var productid = $(this).attr('name');
        var cartheight = $('#basket_content ul').outerHeight()-70;
        //console.log( productid );
        $.ajax({
            type: "GET",
            url: "/cart/ajaxfromcart/" + productid,
            success: function() {

                $('#product_' + productid).remove();
                $('#basket_details').animate({
                    height : ''+cartheight+''
                });

                $.get('/cart/refreshcartcount', function(cartcount) {
                    $('#basket_count span').html(cartcount + ' Items ');
                });

                $.get('/cart/refreshcarttotal', function(pricing) {
                    $('#basket_total h4').html('&pound;' + pricing);
                });
            }
        })
        e.preventDefault();
    });

    $(".length select").change(function () {
        var productid = $(this).attr('id');
        var value = $(this).val();
        var thisis = $(this).attr('rel');
        $.ajax({
            type: "GET",
            url: "/cart/ajaxupdatecart/" + productid + '/' + value + '/' + thisis,
            success: function() {

                $.get('/cart/refreshcartcount', function(cartcount) {
                    $('#basket_count span').html(cartcount + ' Items ');
                });

                $.get('/cart/refreshcarttotal', function(pricing) {
                    //alert(pricing);
                    $('#basket_total h4').html('&pound;' + pricing);
                });
            }
        })

    });
    // none ajax calculator
    $("select.calculator").change(function(){
        var $price = $(this).attr('rel');
        //var $minprice = ;
        var $width = $(this).attr('name');
        var $length = $(this).val();
        var $delivery = false;

        switch($width)
        {
            case '2M':
                if($length <= '1'){
                    $delivery = 12;
                }
                if($length > '1' && $length <= '4'){
                    $delivery = 15;
                }
                if($length > '4' && $length <= '6'){
                    $delivery = 17;
                }
                if($length > '6' && $length <= '7'){
                    $delivery = 20;
                }
                $width = 2;
                break;
            case '3M':
                if($length <= '1'){
                    $delivery = 12;
                }
                if($length > '1' && $length <= '3'){
                    $delivery = 15;
                }
                if($length > '3' && $length <= '4'){
                    $delivery = 17;
                }
                if($length > '4' && $length <= '5'){
                    $delivery = 25;
                }
                if($length > '5' && $length <= '6'){
                    $delivery = 35;
                }
                if($length > '6' && $length <= '7'){
                    $delivery = 45;
                }
                $width = 3;
                break;
        }

        var $subtotal = $price * $length;
        var $incdelivery = $subtotal+$delivery;

        $('#base_info #subtotal').html('<strong>£<span id="subtotal_amount">' + $subtotal.toFixed(2) + '</span></strong>');
        $('#base_info #delivery').html('<strong>£' + $delivery.toFixed(2) + '</strong>');
        $('#base_info #incdelivery').html('<strong>£' + $incdelivery.toFixed(2) + '</strong>');
        $('#base_info #total').html('<h4>£' + $incdelivery.toFixed(2) + '</h4>');


    })

    $('#prodinfo_right a#button_basket, #base_info .product_button_additional').live('click',function(e){
        var productid = $(this).attr('rel');
        var qty = $('.calculator').val();

        var acc1qty = $('#single_synbrass .options');
        var acc2qty = $('#cover_synbrass .options');
        var acc3qty = $('#vinyl_tape .options');

        var acc1opt = $('#single_synbrass .opt_type');
        var acc2opt = $('#cover_synbrass .opt_type');
        var acc3opt = $('#vinyl_tape .opt_type');

        if (acc1qty.val() > 0) {
            firstAcc = acc1qty.val();
            if (acc1opt.val() !== undefined) {
                firstAcc = firstAcc + '-' + acc1opt.val();
            }
        } else {
            firstAcc = 0;
        }
        if (acc2qty.val() > 0) {
            secondAcc = acc2qty.val();
            if (acc2opt.val() !== undefined) {
                secondAcc = secondAcc + '-' + acc2opt.val();
            }
        } else {
            secondAcc = 0;
        }
        if (acc3qty.val() > 0) {
            thirdAcc = acc3qty.val();
            if (acc3opt.val() !== undefined) {
                thirdAcc = thirdAcc + '-' + acc3opt.val();
            }
        } else {
            thirdAcc = 0;
        }

        $.ajax({
            type: "GET",
            url: "/my-basket/ajax-with-options/" + productid + "/" + qty + "/" + firstAcc + "/" + secondAcc + "/" + thirdAcc,
            success: function() {

                $('#added').fadeIn().delay(2000).fadeOut();
                $('#fade').fadeIn().delay(2000).fadeOut();
                
                refreshBasket();
                
//                $.get('/my-basket/refreshcartcount', function(data)
//                {
//                    $('#b_details span').empty().html(data + ' Items | <a href="/my-basket">view</a>');
//                    $('#floating_basket p span').html(data + ' Items | <a href="/my-basket">view</a>');
//                });
//                
                // Clear the accessories
                acc1qty.val('');
                acc2qty.val('');
                acc3qty.val('');

                acc1opt.val('');
                acc2opt.val('');
                acc3opt.val('');
            }
        })

        e.preventDefault();
    });

    $('#prodinfo_right a#button_sample').live('click',function(e){
        var productid = $(this).attr('rel');

        //console.log( productid );
        $.ajax({
            type: "GET",
            url: "/samples/ajaxtosample/" + productid,
            success: function(data) {
                if (data == 'added') {
                    $('#addedsample').fadeIn().delay(3000).fadeOut();
                } else {
                    $('#samplemaxxed').fadeIn().delay(3000).fadeOut();
                }

                $('#fade').fadeIn().delay(3000).fadeOut();
            }
        })
        e.preventDefault();
    });

    $('a.removesample').live('click',function(e){
        var productid = $(this).attr('rel');

        //		console.log( productid );
        $.ajax({
            type: "GET",
            url: "/samples/ajaxfromsample/" + productid,
            success: function() {

                $('#product_' + productid).remove();
            }
        })
        e.preventDefault();
    });

    // none ajax buttoned pages
    $('#product_information ul li a').click(function(){
        var tabid = $(this).attr("name");
        // Change Button/Tab
        $('#product_information ul li a').removeClass('active').addClass('noneactive');
        $(this).removeClass('noneactive').addClass('active');
        // Change Content Div
        $('#product_content').children('.content_slide').removeClass('show').hide();
        $('#product_content').children('#' + tabid).addClass('show').show();

        return false;
    });

    $('#button_accessories, #button_accessories_additional').live('click',function(){
        var tabid = $(this).attr("name");

        $('#product_information ul li a').removeClass('active').addClass('noneactive');
        $('#accessories_btn').removeClass('noneactive').addClass('active');

        var elementClicked = $(this).attr("href");
        var destination = $(elementClicked).offset().top;
        $("html:not(:animated),body:not(:animated)").animate({
            scrollTop: destination-20
        }, 1000 );

        // Change Content Div
        $('#product_content').children('.content_slide').removeClass('show').hide();
        $('#product_content').children('#' + tabid).addClass('show').show();

        return false;
    })

    // IMAGE CHANGER /////////////////////////////////////////////////////////////////
    // load the first image in the list
    var current_img = $('#image_list ul li .current_img').attr("href");
    var current_genimg = '<img src="' + current_img + '" />';
    $(current_genimg).appendTo('#current_image');
    // load clicked image
    $('#image_list ul li a').live('click',function(e){
        var imgurl = $(this).attr("href");
        var genimg = '<img src="' + imgurl + '" />';
        $('#image_list ul li .current_img').removeClass('current_img');
        $(this).addClass('current_img');
        $('#current_image img').remove();
        $(genimg).appendTo('#current_image');

        e.preventDefault();
    });

    // enlarge current image
    $('#button_enlarge').live('click',function(e){
        var getimg = $('#image_list ul li .current_img').attr("href");

        getimg = getimg.replace("343", "600");
        getimg = getimg.replace("214", "400");

        var viewimg = '<img src="' + getimg + '" height="400" width="600" />';
        // display the viewer
        $('#photo_viewer').fadeIn();
        $('#fade').fadeIn();
        // append the image to the viewer
        $('#photo_viewer img').remove();
        $(viewimg).appendTo('#photo_viewer #imageholder');

        e.preventDefault();
    });

    $('.product_zoom').live('click',function(e){
        var getimg = $(this).attr("rel");

        getimg = getimg.replace("343", "600");
        getimg = getimg.replace("214", "400");

        var viewimg = '<img src="/image/' + getimg + '/thumb/600/400" height="400" width="600" />';
        // display the viewer
        $('#photo_viewer').fadeIn();
        $('#fade').fadeIn();
        // append the image to the viewer
        $('#photo_viewer img').remove();
        $(viewimg).appendTo('#photo_viewer #imageholder');

        e.preventDefault();
    })

    $('#photo_viewer #imageholder a').live('click',function(e){
        $('#photo_viewer').fadeOut();
        $('#fade').fadeOut();

        e.preventDefault();
    });

    // CATEGORY SEARCH /////////////////////////////////////////////////////////////
    $('.main_selection ul li a').live('click',function(e){
        var menuname = $(this).attr("name");
        $('.main_selection').animate({
            left:'-220'
        });
        $('#'+menuname).animate({
            left:'0'
        });
        $('#cancel_search').animate({
            right:'230'
        });
        e.preventDefault();
    });

    $('.sub_selection ul li a.more').live('click',function(e){
        var menuname = $(this).attr("name");
        $('#'+menuname).animate({
            left:'-220'
        });
        $('#'+menuname+'-more').animate({
            left:'0'
        });

        e.preventDefault();
    });

    $('.sub_selection ul li a.more2').live('click',function(e){
        var menuname = $(this).attr("name");
        $('#'+menuname+'-more').animate({
            left:'-220'
        });
        $('#'+menuname+'-more2').animate({
            left:'0'
        });

        e.preventDefault();
    });

    $('.sub_selection ul li a.more3').live('click',function(e){
        var menuname = $(this).attr("name");
        $('#'+menuname+'-more2').animate({
            left:'-220'
        });
        $('#'+menuname+'-more3').animate({
            left:'0'
        });

        e.preventDefault();
    });

    $('.sub_selection ul li a.more4').live('click',function(e){
        var menuname = $(this).attr("name");
        $('#'+menuname+'-more3').animate({
            left:'-220'
        });
        $('#'+menuname+'-more4').animate({
            left:'0'
        });

        e.preventDefault();
    });

    $('#cancel_search').live('click',function(e){
        $('.sub_selection').css("left","220px");
        $('.main_selection').animate({
            left:'0'
        });
        $(this).animate({
            right:'212'
        });

        e.preventDefault();
    });

    // access heights
    var cartheight = $('#basket_content ul').outerHeight();
    $('#basket_details').css('height',cartheight);

    $('#close_information').live('click',function(e){
        $('#information').hide();
        e.preventDefault();
    })

});

function number_format (number, decimals, dec_point, thousands_sep) {

    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
    prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
    sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
    dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
    s = '',
    toFixedFix = function (n, prec) {
        var k = Math.pow(10, prec);
        return '' + Math.round(n * k) / k;
    };
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

