
var BS = function(){
    var checkout_confirmed = false;
    return {
        'get_checkout_confirmed': function(){
            return checkout_confirmed;
        },
        'set_checkout_confirmed': function(val){
            checkout_confirmed = val;
        },
        'show_error_dialog': function(message) {
            $("#dialog-message-text").html(message);
            $("#dialog-message").dialog({
                modal: true,
                buttons: {
                    Ok: function() {
                        $(this).dialog("close");
                    }
                }
            });
        },
        'show_checkout_error_dialog': function(message) {
            $("#dialog-message-text").html(message);
            $("#dialog-message").dialog({
                modal: true,
                buttons: {
                    Yes: function() {
                        $(this).dialog("close");
                        BS.confirm_checkout();
                    },
                    No: function() {
                        $(this).dialog("close");
                    }
                }
            });
        },
        'checkout_click': function(){
                // Try to send the google analytics information to google checkout
                try{
                    setUrchinInputCode(pageTracker);
                } catch(err) {
                }
                
                // Check the order limitation
                var orderLimitInput = document.getElementById('sn_order_limit');
                var orderLimit = 0;
                if (orderLimitInput != null && orderLimitInput.value == "1") {
                    orderLimit = 1;
                }
                var totalItems = 0;
                for (var i in googlecart.getItems()){
                    if (!googlecart.getItem(i).isMarkedForRemoval()) {
                        totalItems += googlecart.getItem(i).getQuantity();
                    }
                }
                if (orderLimit == 1 && totalItems > 1) {
                    BS.show_error_dialog("Sorry!<br /> You can only purchase one item per order.");
                    return false;
                }
                
                
                var shipping_type_id = document.getElementById("shipping_type_id");
                // check if the steal is carrier calculated
                if (shipping_type_id != null && shipping_type_id.value == "1") {
                    var extra_fee_us = 2;
                    var extra_fee_canada = 3;
                    
                    var add_us = document.getElementById('add_us');
                    var add_canada = document.getElementById('add_ca');
                    
                    if (add_us != null) {
                        extra_fee_us = add_us.value;
                    }

                    if (add_canada != null) {
                        extra_fee_canada = add_canada.value;
                    }
                    
                    var items = googlecart.getItems();
                    var request_items = {
                            'items': [], 
                            'extra_fee_us' : extra_fee_us, 
                            'extra_fee_canada' : extra_fee_canada
                    };
                    for (var item in items){
                        if (!items[item].isMarkedForRemoval()) {
                            var attributes = items[item].getCustomAttributes();
                            request_items['items'].push({
                                'weight'   : items[item].properties['weight'],
                                'quantity' : items[item].getQuantity(),
                                'daily_steal_item_id': attributes['daily_steal_item_id'],
                                'daily_steal_item_attribute_id': attributes['daily_steal_item_attribute_id'],
                                'is_digital': attributes['is_digital']
                            });
                        }
                    }
                    
                    $.ajax({type: "GET",
                        url: "/common/canadian_shipping.php",
                        cache: false,
                        dataType: "json",
                        data: {'request_json': $.toJSON(request_items)},
                        success: BS.checkout_success,
                        error: BS.checkout_success
                   });
                    
                } else {
                    BS.checkout_success('','');
                } 
            return false;
        },
        'checkout_success':function(data, textStatus){
            
            
            if (data != null && data != '' ) {
                
                var digital_download_country = document.getElementById('ship_method_country_3');
                
                var dhl_expedited = document.getElementById('ship_method_price_1');
                var dhl_expedited_country = document.getElementById('ship_method_country_1');
                
                var first_class_us = document.getElementById('ship_method_price_2');
                var first_class_us_country = document.getElementById('ship_method_country_2');  
                             
                var first_class = document.getElementById('ship_method_price_6');
                var first_class_country = document.getElementById('ship_method_country_6');
                            
                var priority_mail = document.getElementById('ship_method_price_7');
                var priority_mail_country = document.getElementById('ship_method_country_7');
                
                // Canada - Priority Mail International
                if (data['priorityCanada'] != null && data['priorityCanada'] != 0 && priority_mail != null) {
                    priority_mail.value = data['priorityCanada'];
                    priority_mail_country.value = "CA";
                    
                    // usps_international_country
                    $("#ship_method_name_5").remove();
                    $("#ship_method_price_5").remove();
                    $("#ship_method_currency_5").remove();
                    $("#ship_method_country_5").remove();
                }                
                
                // Canada - First Class International Package
                if (data['firstClassCanada'] != null && data['firstClassCanada'] != 0 && first_class != null) {   
                    first_class.value = data['firstClassCanada'];
                    first_class_country.value = "CA";
                    
                    // usps_international_country
                    $("#ship_method_name_5").remove();
                    $("#ship_method_price_5").remove();
                    $("#ship_method_currency_5").remove();
                    $("#ship_method_country_5").remove();
                }
                
                // USA - First class
                if (data['firstClassUs'] != null && data['firstClassUs'] != 0 && first_class_us != null) {
                    first_class_us.value = data['firstClassUs'];
                    first_class_us_country.value = 'US';
                }
                
                // USA - DHL
                if (data['dhl'] != null && data['dhl'] != 0 && dhl_expedited != null) {
                    dhl_expedited.value = data['dhl'];
                    dhl_expedited_country.value = 'US';
                }
                
                // Digital download
                if (data['digital'] == 1 && digital_download_country != null) {
                    try {
                        // Remove country shipping restriction to enable digital download
                        $("#ship_method_country_3").val('US');
                        $("#ship_method_country_4").val('CA');
                        
                        // Remove Carrier Calculated options
                        $("#ccs_company_12").remove();
                        $("#ccs_shipping_type_12").remove();
                        $("#ccs_price_12").remove();
                        $("#ccs_additional_fixed_price_12").remove();
                        $("#ccs_additional_fixed_currency_12").remove();

                        $("#ccs_company_13").remove();
                        $("#ccs_shipping_type_13").remove();
                        $("#ccs_price_13").remove();
                        $("#ccs_additional_fixed_price_13").remove();
                        $("#ccs_additional_fixed_currency_13").remove();
                        
                        $("#ccs_package_ship_from_id_1").remove();
                        $("#ccs_package_ship_from_city_1").remove();
                        $("#ccs_package_ship_from_region_1").remove();
                        $("#ccs_package_ship_from_country_1").remove();
                        $("#ccs_package_ship_from_postal_code_1").remove();
                        
                        // usps_international_country
                        $("#ship_method_name_5").remove();
                        $("#ship_method_price_5").remove();
                        $("#ship_method_currency_5").remove();
                        $("#ship_method_country_5").remove();
                        
                        $("#ship_method_name_8").remove();
                        $("#ship_method_price_8").remove();
                        $("#ship_method_currency_8").remove();
                        
                    } catch (err) {
                        alert(err);
                    }
                }
            }
            var items = googlecart.getItems();
            var request_items = {'items': []};
            for(var item in items){
                var attributes = items[item].getCustomAttributes();
                request_items['items'].push({
                    'daily_steal_item_id': attributes['daily_steal_item_id'],
                    'daily_steal_item_attribute_id': attributes['daily_steal_item_attribute_id'],
                    'extra_data': {'googlecart_id': item}
                });
            }
            $.ajax({
                type: "GET",
                url: "/common/check_steal_item.php",
                cache: false,
                dataType: "json",
                data: {'request_json': $.toJSON(request_items)},
                success: BS.checkout_success2,
                error: BS.checkout_failure
            });
        },
        'checkout_success2': function(data, textStatus){
            var quantity_changed  = [];
            var removed = [];
            for(var item in data){
                var gc_item = googlecart.getItem(data[item]['extra_data']['googlecart_id']);
                var asked_quantity = gc_item.getQuantity();
                if(data[item].count < asked_quantity){
                    if(data[item].count > 0){
                        gc_item.setQuantity(data[item].count);
                        quantity_changed.push({'title': gc_item.getTitle(),
                                               'new': data[item].count,
                                               'old': asked_quantity}
                                             );

                    }
                    else {
                        removed.push({'title': gc_item.getTitle()});
                        gc_item.markForRemoval();
                    }
                }
            }
            if (removed.length > 0 || quantity_changed.length > 0){
                googlecart.expungeMarkedForRemoval();
                googlecart.saveCartAndRefreshWidget();
                BS.show_checkout_error_dialog(
                    "Sorry! We sold out of some things in your cart while you were shopping. "
                    + " We've adjusted your cart as follows:<br />" 
                    + BS.cart_change_text(removed, quantity_changed) 
                    + "Would you still like to checkout?"
                );
            } else {
                BS.confirm_checkout();
            }
        },
        'confirm_checkout': function(){
            BS.set_checkout_confirmed(true);
            googlecart.checkout();
        },
        'cart_change_text': function(removed, quantity_changed){
            var return_string = "";
            if(removed.length > 0){
                return_string += "We removed the following items:<br /><ul>";
                for(var i in removed){
                    return_string += "<li>" + removed[i]['title'] + "</li>";
                }
                return_string += "</ul><br />";
            }
            if(quantity_changed.length > 0){
                return_string += "We changed the quantity the following items:<br /><ul>";
                for(var i in quantity_changed){
                    return_string += "<li>" + quantity_changed[i]['title'] + " from " + quantity_changed[i]['old'] + " to " + quantity_changed[i]['new'] + "</li>";
                }
                return_string += "</ul><br />";
            }
            return return_string;
        },
        'checkout_failure': function(){
            BS.show_error_dialog("Sorry! We couldn't check out your cart due to a technical error.  Please try again later.");
        },
        'add_to_cart': function(daily_steal_item_id){
            var orderLimitInput = document.getElementById('sn_order_limit');
            var orderLimit = 0;
            if (orderLimitInput != null && orderLimitInput.value == "1") {
                orderLimit = 1;
            }
            
            var biodiaper = 0;
            var totalItems = 0;
            for (var i in googlecart.getItems()){
                if (!googlecart.getItem(i).isMarkedForRemoval()) {
                    totalItems += googlecart.getItem(i).getQuantity();
                }
                if (googlecart.getItem(i).getCustomAttribute('daily_steal_item_id') == 3002673){
                    biodiaper = googlecart.getItem(i).getQuantity();
                }
            }
            if (orderLimit == 1 && totalItems > 0) {
                BS.show_error_dialog("Sorry!<br /> You can only purchase one item per order.");
                return false;
            }
            
            if (biodiaper == 1) {
                BS.show_error_dialog("Sorry!<br /> You can only purchase one per item per order.");
                return false;
            }
            
            var daily_steal_item_attribute_id = $('#daily_steal_item_' + daily_steal_item_id + ' .product-attr-daily_steal_item_attribute_id').val();
            $.ajax({type: "GET",
                    url: "/common/check_steal_item.php",
                    cache: false,
                    dataType: "json",
                    data: {'request_json': $.toJSON({'items': [{'daily_steal_item_id': daily_steal_item_id,
                           'daily_steal_item_attribute_id': daily_steal_item_attribute_id
                          }]})},
                    success: BS.add_to_cart_success,
                    error: BS.add_to_cart_failure
                   });
        },
        'make_googlecart_item': function(id){
            var properties_to_get = ['title', 'price', 'shipping', 'shipping-first', 'weight', 'image'];
            var custom_attributes_to_get = ['daily_steal_item_id', 'daily_steal_item_attribute_id', 'is_digital'];
            var properties = {};
            var custom_attributes = { };
            for(var i in properties_to_get){
            if($(id + " div.product-" + properties_to_get[i]).length != 0){
                    properties[properties_to_get[i]] = $(id + " .product-" + properties_to_get[i]).text().replace(/^\$/, '');
                }
                else if($(id + " input.product-" + properties_to_get[i]).length != 0){
                    properties[properties_to_get[i]] = $(id + " .product-" + properties_to_get[i]).val();
                }

            }
            for(var i in custom_attributes_to_get){
                custom_attributes[custom_attributes_to_get[i]] = $(id + " .product-attr-" + custom_attributes_to_get[i]).val();
            }
            if($(id + " select.product-attr-daily_steal_item_attribute_id").length != 0){
                properties['title'] += " - " + $(id +
" .product-attr-daily_steal_item_attribute_id option:selected").text();
            }
        var item = googlecart.makeItem(properties, custom_attributes, 1);
        return item;

        },
        'add_to_cart_success': function(data, textStatus){
            var item = data[0];
            var current_total = 0;
            for (var i in googlecart.getItems()){
                if((googlecart.getItem(i).getCustomAttribute('daily_steal_item_id') == item['daily_steal_item_id']) &&
                (googlecart.getItem(i).getCustomAttribute('daily_steal_item_attribute_id') == item['daily_steal_item_attribute_id'])){
                        current_total = googlecart.getItem(i).getQuantity();
                    }
            }
            
            if(item['count'] >= current_total + 1){
                googlecart.addItem(BS.make_googlecart_item('#daily_steal_item_' + item['daily_steal_item_id']));
            } else if (item['count'] == 1) {
                BS.show_error_dialog("Sorry!<br /> You can only purchase one per item per order.");
            } else if (item['count'] == 3) {
                BS.show_error_dialog("Sorry!<br /> You can only purchase three per item per order.");
            } else {
                BS.show_error_dialog("Aw snap!<br /> This item has sold out. Check back later for another steal!");
            }

        },
        'add_to_cart_failure': function(){
            BS.show_error_dialog("Sorry! We couldn't add your item to the cart due to a technical error.  Please try again later.");
        }
    };
}();

function googlecartWidgetLoaded(){
    for (var i in googlecart.getItems()){
       // console.log(googlecart.getItem(i).getCustomAttribute('daily_steal_item_id'));
        if(active_daily_steal_items[googlecart.getItem(i).getCustomAttribute('daily_steal_item_id')] == null ){
            // googlecart.getItem(i).remove();
        }
    }
    googlecart.saveCartAndRefreshWidget();
}

function googlecartOnCheckoutClick(items, form){
    if(BS.get_checkout_confirmed()){
        return true;
    }
    else {
        BS.checkout_click();
        return false;
    }
}
