String.prototype.repeat = function( num )
    {
        return new Array( num + 1 ).join( this );
    }

var okToAnimate = true;
var animateInterval = null;
var distance = 0;
var direction = 'right';
$(document).ready(function(){
    //disable input from secondary shipping table
    $('table.secondaryShipping').hide();
    
    $('input.differentFromShipping').click(function(){
        var table = $(this).parents('div.formTableHeader').siblings('table.secondaryShipping');
        
        table.toggle();
    });

    //get shipping rate
    $('select.shippingMethod').change(doShipping);
    $('select.shippingState,input.shippingZip').change(function(){
        var table = $(this).parents('table.shippingTable');
        table.find('select.shippingMethod').change();
    });

    $('input.placeOrderButton').click(function(){
        $('input.placeOrderButton').css({
            visibility:'hidden'
        });
    });

    $('a.dynamic').colorbox({
        iframe:true,
        width:1024,
        height:'85%'
    })
    
    detectCookieEnabled();
});

function detectCookieEnabled(){
    var tmpcookie = new Date();
    chkcookie = (tmpcookie.getTime() + '');
    document.cookie = "chkcookie=" + chkcookie + "; path=/";
    if (document.cookie.indexOf(chkcookie,0) < 0) {
        alert( 'You need to enable cookie to use this site.' );
    }
        
}

function doShipping()
{
    var that = this;
    var state = $('#shippingState');
    var zip = $('#shippingZip');
    var address1 = $('#shippingAddress1');
    var address2 = $('#shippingAddress2');
    var city = $('#shippingCity');
    var id = $(this).siblings('.cart_item_id').val();

    if($(this).val() != '')
    {
        if(state.length && zip.length && id.length)
        {
            if(state.val() != '')
            {
                if(zip.val() != '')
                {
                    $.ajax({
                        url:'/checkShippingRate',
                        type:'post',
                        data:'state='+state.val()+'&zip='+zip.val()+'&service='+$(that).val()+'&id='+id+'&address1='+address1.val()+'&address2='+address2.val()+'&city='+city.val(),
                        success:function(data){
                            if(data.length)
                            {
                                $('#totalTableWrapper').html(data).fadeIn();
                            }
                            else
                            {
                                $(document).message("Failed to get shipping rate.");
                            }
                        }
                    });
                }
                else
                {
                    $(document).message('Please enter your zip code.');
                }
            }
            else
            {
                $(document).message('Please select a shipping state.');
            }
        }
    }
}

function animateOptionText(option,text,animate)
{
    if(option.length)
    {
        if(animate == true && animateInterval == null)
        {
            animateInterval = setInterval(function()
            {
                var rand_no = Math.ceil(1000*Math.random())/100;
                var orginalText = text.split(' -- ');
                option.text(orginalText[0]+' -- $'+rand_no);
            },100,option,text);
        }
        else
        {
            clearInterval(animateInterval);
            animateInterval = null;
        }
    }
}

function updateTotal(shippingId,shippingTotal)
{
    var total = 0;
    var tax = toFloat($('.tax').text());
    var coupon = toFloat($('#coupon').text());
    var giftCertificate = toFloat($('#giftCertificate').text());
    
    if(shippingId)
    {
        $(shippingId).text('$'+shippingTotal);
    }
    $('.item').each(function(){
        var id = '#'+$(this).attr('id');
        var itemPrice = toFloat($(this).text());
        var shippingPrice = toFloat($(this).parent('tr').next('tr').children('td.shipping').text());
        var subTotalId = id.replace('item','subtotal');
        var differentShipping = $('input.differentFromShipping[rel="'+id.replace("#item_",'')+'"]');
        var differentShippingChecked = $('#differentBox_'+id.replace("#item_",'')+':checked');

        if(differentShipping.length)
        {
            if(differentShippingChecked.length==0)
            {
                shippingPrice = toFloat(shippingTotal);
            }
        }

        total += itemPrice+shippingPrice;
        $(subTotalId).text('$'+(Math.round((itemPrice+shippingPrice)*100)/100));
    });

    total += tax;
    total -= coupon;
    total -= giftCertificate;
    total = total > 0?total:0;
    
    $('.total').text('Total: $'+(Math.round(total*100)/100));

    if(total > 0)
    {
        $('table.billingTable').find('input,select').each(function(){
            $(this).removeAttr('disabled').removeClass('disabled');
        });
    }
    else
    {
        $('table.billingTable').find('input,select').each(function(){
            $(this).attr('disabled','true').addClass('disabled');
        });
    }
}

function toFloat(number)
{
    if($.trim(number.replace(/[^\d\.]+/ig,'')).length == 0)
        return 0;
    var n = number.replace(/[^\d\.]+/ig,'')*1;
    return n;
}
