
var BS = function(){
    var checkout_confirmed = false;
    return {
        'get_checkout_confirmed': function(){
            return checkout_confirmed;
        },
        'set_checkout_confirmed': function(val){
            checkout_confirmed = val;
        },
        'checkout_click': function(){
        		var usps_international_country = document.getElementById('ship_method_country_5');
                var extra_fee_us = 2;
                
                var add_us = document.getElementById('add_us');
                if(add_us != null)
                {
                    extra_fee_us = add_us.value;
                }
                
                var add_canada = document.getElementById('add_ca');
                var extra_fee_canada = 3;
                if(add_canada != null)
                {
                    extra_fee_canada = add_canada.value;
                }
                
				// check if the product is free shipping
				if(usps_international_country != null)
				{
					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()
                                            });
                        }
            		}
            		
					$.ajax({type: "GET",
                    url: "/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){
            var first_class_us = document.getElementById('ship_method_price_2');
            var first_class_us_country = document.getElementById('ship_method_country_2');  
            
			var usps_international_country = document.getElementById('ship_method_country_5');
                         
			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');

            var dhl_expedited = document.getElementById('ship_method_price_1');
            var dhl_expedited_country = document.getElementById('ship_method_country_1');
            
			if(data != null && data != '' ) 
			{
				if(data[0] != null && data[0] != 0 && priority_mail != null)
				{
					priority_mail.value = data[0];
					priority_mail_country.value = "CA";
					usps_international_country.value = "CR";
				}				
				if(data[1] != null && data[1] != 0 && first_class != null)
				{   
					first_class.value = data[1];
					first_class_country.value = "CA";
					usps_international_country.value = "CR";
				}
                if(data[2] != null && data[2] != 0 && first_class_us != null)            
                {
                    first_class_us.value = data[2];
                    first_class_us_country.value = 'US';
                }
                // DHL	
				if(data[3] != null && data[3] != 0 && dhl_expedited != null)			
				{
					dhl_expedited.value = data[3];
					dhl_expedited_country.value = 'US';
				}
			}
			var items = googlecart.getItems();
            var archiveInput = document.getElementById('archive');
            var archive = 0;
            if(archiveInput != null && archiveInput.value == "1")
            {
                archive = 1;    
            }
            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},
                                             'archive': archive
                                            });
            }
            $.ajax({type: "GET",
                    url: "/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();
                $.blockUI({message: "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?<br /><input type='button' onclick='BS.confirm_checkout(); return false;' value='Yes' />&nbsp;&nbsp;<input type='button' onclick='$.unblockUI(); return false;' value='No' /><br /><br />"});
            }
            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(){
            $.blockUI({message: "Sorry! We couldn't check out your cart due to a technical error.  Please try again later.<br /><input type='button' onclick='$.unblockUI()' value='Ok'/>"});
        },
        'add_to_cart': function(daily_steal_item_id){
            var archiveInput = document.getElementById('archive');
            var archive = 0;
            if(archiveInput != null && archiveInput.value == "1")
            {
                archive = 1;    
            }
            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: "/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,
                           'archive': archive
                          }]})},
                    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'];
            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 {
                $.blockUI({message: "Sold out!<br /> Sorry, we don't have any more of this item.<br /><input type='button' onclick='$.unblockUI()' value='Ok'/>"});
            }

        },
        'add_to_cart_failure': function(){
            $.blockUI({message: "Sorry! We couldn't add your item to the cart due to a technical error.  Please try again later.<br /><input type='button' onclick='$.unblockUI()' value='Ok'/>"});
        }


    };
}();
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;
    }
}

