function removeProductOrItem(element,removeUrl)
{
	jQuery(element).closest('tr').addClass('waiting');
	jQuery.get(removeUrl,null,function(data){
		jQuery(element).closest('tr').removeClass('waiting');
		if (data.success) {
			if (data.modifiedShipment) {
				var subTotal = jQuery(element).closest('table').find('tfoot .subtotal .price');
				subTotal.html(data.modifiedShipment.subTotal);
				var grandTotal = jQuery(element).closest('table').find('tfoot .grand-total .price');
				grandTotal.html(data.modifiedShipment.grandTotal);
			}
            // Update the available items section
            var deletedRow = jQuery(element).closest('tr');
            var productId = deletedRow.attr('product_id');
            var quantity = deletedRow.find('.col-qty').text() * 1;
            var productrow = jQuery('#productrow-' + productId);
            var oldUnscheduled = productrow.find('.unscheduled-qty').html() * 1;
            var oldScheduled = productrow.find('.col-qty').html() * 1;
            productrow.find('.unscheduled-qty').html(oldUnscheduled + quantity);
            productrow.find('.col-qty').html(oldScheduled - quantity);

            // Update the avialble items category headers
            var categoryTotalScheduled = productrow.closest('div.available-category').find('span.category-scheduled');
            categoryTotalScheduled.text(categoryTotalScheduled.html() * 1 - quantity);
            var categoryTotalunScheduled = jQuery(productrow.closest('div.available-category').find('span.category-unscheduled'));
            categoryTotalunScheduled.text(categoryTotalunScheduled.html() * 1 + quantity);

			deletedRow.addClass('deleted');
			deletedRow.fadeOut('slow',function(){
				jQuery(this).remove();
			});
            setTotals();
		} else {
			alert(data.error);
		}
	},'json');
	return false;
}

function addProducts(id) {

    // Destroy existing dialogs
    jQuery('div.addProducts').dialog('destroy');
    jQuery('div.addProducts').remove();

    // Create a fresh dialog
    jQuery('body').append("<div class='addProducts'></div>");
    jQuery('div.addProducts').dialog({
        autoOpen:false,
        width: 650,
        modal:true
    });
    
    // Request the category picker and show it in the dialog box
    jQuery.blockUI({message: "<h2>Loading the products</h2>"});
    jQuery.ajax({
         url: '/picker/index/getCategory/category_id/' + id,
         dataType: 'html',
         success: function(result) {
           jQuery.unblockUI();
           jQuery('div.addProducts').html(result);
           jQuery('div.addProducts').dialog('open');
         },
         error: function() {
            jQuery.unblockUI();
            alert('An error occured when trying to load the products.');
         }
    });
}

function updateProdQueueQty(inputFieldId,updateUrl)
{
	var row = jQuery('#' + inputFieldId).closest('tr');
    row.addClass('waiting');
	
	var qty = jQuery('#' + inputFieldId).val();
	var productId = inputFieldId.split('-')[1];

	jQuery.post(updateUrl,{'product_id': productId, 'qty': qty},function(data){
		jQuery('#' + inputFieldId).closest('tr').removeClass('waiting');
		if (data.success) {
            if(qty != 0) {
                var updatedRowSelector = '#product-row-' + data.product_id;
                jQuery(updatedRowSelector + ' .cart-price .price').text(data.product_subtotal);
                jQuery(updatedRowSelector).css('background','#ffff00');
                jQuery(updatedRowSelector).animate({backgroundColor:'#ffffff'},1500);
            } else {
                row.remove();
            }
            setTotals();
		} else {
			alert(data.error);
		}
	},'json');
	return false;
}

function setTotals() {
   var tables = jQuery('#available-products table.productqueue-cart-items');
   for(var i=0; i < tables.length; i++) {
       var rows = jQuery(tables[i]).find('tbody tr');
       var total = 0;
       for(var r=0; r < rows.length; r++) {
           var subtotal = jQuery(rows[r]).find('.cart-price .price').text();
           subtotal = subtotal.substr(1, subtotal.length - 1) * 1;
           total += subtotal;
       }
       jQuery(tables[i]).find('tfoot .price').text("$" + total.toFixed(2));
   }
}

function displayNextShipment()
{
	var currentShipment = jQuery('.shipment-items.shown');
	var nextShipment = currentShipment.next('.shipment-items');
	if (nextShipment.length) {
		currentShipment.removeClass('shown');
		nextShipment.addClass('shown');
	}
	return false;
}

function displayPrevShipment()
{
	var currentShipment = jQuery('.shipment-items.shown');
	var prevShipment = currentShipment.prev('.shipment-items');
	if (prevShipment.length) {
		currentShipment.removeClass('shown');
		prevShipment.addClass('shown');
	}
	return false;
}

function showEditItemDialog(productId)
{
    var itemrow = jQuery('.shipment-items.shown tr[product_id=' + productId + ']');
    var productrow = jQuery('#productrow-' + productId);
    var quantity = 0;
    var availableQty = 0;

	if (itemrow.length) {
        quantity = itemrow.find('.col-qty').text() * 1;

		jQuery('#edit-curr-items-cnt').text(quantity);
        jQuery('#original-shipment').val(quantity);
		jQuery('#edit-item-dialog').attr('item_id', itemrow.attr('id').split('-')[1]);
        jQuery('#edit-item-name').text(itemrow.find('.title a').text());
        jQuery('#edit-item-price').text(itemrow.find('.col-unitprice .price').text());

        var scheduledQty = 0;
        if(productrow.length) {
            scheduledQty = productrow.find('.col-qty').text() * 1;
            availableQty = productrow.find('.unscheduled-qty').text() * 1;
        }
        jQuery('#scheduled-items-cnt').text(scheduledQty - quantity);
        jQuery('#edit-available-items-cnt').text(availableQty);
        jQuery("#original-unscheduled").val(availableQty);
        jQuery('#edit-item-img').attr('src', itemrow.find('img.product-image').attr('src'));
	} else { 
		jQuery('#edit-curr-items-cnt').text(quantity);
        jQuery('#original-shipment').val(quantity);
        
		jQuery('#edit-item-dialog').attr('item_id','');
        jQuery('#edit-item-name').text(productrow.find('.title a').text());
        jQuery('#edit-item-price').text(productrow.find('.col-unitprice .price').text());

        availableQty = productrow.find('.unscheduled-qty').text() * 1;
        jQuery('#edit-available-items-cnt').text(availableQty);
        jQuery("#original-unscheduled").val(availableQty);
        jQuery('#edit-item-img').attr('src',productrow.find('img.product-image').attr('src'));

        jQuery('#scheduled-items-cnt').text(productrow.find('.col-qty').text() * 1);
	}
    // Hides the warning
    checkRemoveFromOtherShipments();
    
	jQuery('#edit-item-dialog').attr('product_id',productId);

	jQuery('#edit-item-dialog #monthly-budget-warning').hide();
	jQuery('#edit-item-dialog #chk-allow-exceeds').attr('checked','');
	
	jQuery('#edit-item-dialog span.subtotal').text(jQuery('.shipment-items.shown tfoot .subtotal .price').text());
	jQuery('#edit-item-dialog span.tax').text(jQuery('.shipment-items.shown tfoot .tax .price').text());
	jQuery('#edit-item-dialog span.shipping').text(jQuery('.shipment-items.shown tfoot .shipping .price').text());
	jQuery('#edit-item-dialog span.grand-total').text(jQuery('.shipment-items.shown tfoot .grand-total .price').text());
	
	jQuery('#edit-item-dialog .edit-item-totals-header .shipdate').text(jQuery('.shipment-items.shown .shipdate').text());

    jQuery('#edit-item-dialog').dialog('option', 'width', 550);
	jQuery('#edit-item-dialog').dialog('open');
	return false;
}

var estimateSubtotalsXhr = null;
function estimateSubtotals()
{
	jQuery('#edit-item-dialog #edit-item-shiptotals #monthly-budget-warning-over').hide(); //hiding this just in case it is showing.
	var parameters = {
        shipment_id: jQuery('.shipment-items.shown').attr('id').split('-')[1],
	    product_id: jQuery('#edit-item-dialog').attr('product_id'),
	    shipment_qty: jQuery('#edit-item-dialog #edit-curr-items-cnt').text()*1
	};
	
	var totalsUrl = jQuery('#edit-item-dialog #edit-item-shiptotals').attr('totalsUrl');
	jQuery('#edit-item-dialog #edit-item-shiptotals').addClass('waiting');
	jQuery('#edit-item-dialog #edit-item-shiptotals #monthly-budget-warning').hide();
	
	// kill any previous posts from this function which have not completed
	if (estimateSubtotalsXhr !== null) {
        estimateSubtotalsXhr.abort();
    }
	
	estimateSubtotalsXhr = jQuery.post(totalsUrl, parameters, function(data){
	    jQuery('#edit-item-dialog #edit-item-shiptotals').removeClass('waiting');
	    if (data.success) {
	        jQuery('#edit-item-dialog #edit-item-shiptotals span.subtotal').text(data.subtotal);
	        jQuery('#edit-item-dialog #edit-item-shiptotals span.grand-total').text(data.grand_total);
	        jQuery('#edit-item-dialog #edit-item-shiptotals span.shipping').text(data.shipping);
	        jQuery('#edit-item-dialog #edit-item-shiptotals span.tax').text(data.tax);
	        if (data.exceeds_budget) {
							var shipmentnumber = jQuery('#isfirst').val();
						  if(data.state == 'frozen' && shipmentnumber == '1' ){
								var overbudget = parseFloat(data.budget) + 25;
								var grandTotal = parseFloat(data.grand_total_unformated);
								if(grandTotal > overbudget){
									jQuery('#edit-item-dialog #edit-item-shiptotals #monthly-budget-warning').show();
									jQuery('#frozenbudget').val('1');
									
								}
								else{
									jQuery('#edit-item-dialog #edit-item-shiptotals #monthly-budget-warning-over').show();
									jQuery('#frozenbudget').val('0');
								}
							}
							else{
								jQuery('#edit-item-dialog #edit-item-shiptotals #monthly-budget-warning').show();
							}
	        } else {
	            jQuery('#edit-item-dialog #edit-item-shiptotals #monthly-budget-warning').hide();
	        }
	    } else {
	        alert(data.error);
	    }
	        
	    estimateSubtotalsXhr = null;
	},'json');

	return false;
}

function checkRemoveFromOtherShipments() {
    var originalShipment = jQuery('#original-shipment').val() * 1;
    var current = jQuery('#edit-curr-items-cnt').text() * 1;
    var total = jQuery('#edit-available-items-cnt').text() * 1;
    var other = jQuery('#scheduled-items-cnt').text() * 1;
    //alert(current + ' - ' + originalShipment + ' > ' + originalAvailable + ' && ' + other + ' > ' + 0 + ' && ' + total + ' == 0');
    if(current - originalShipment > total && other > 0) {
        jQuery('div.scheduled-warning').show();
    } else {
        jQuery('div.scheduled-warning').hide();
    }
    if(current - originalShipment > total + other) {
        jQuery('div.additional-warning').show();
    } else {
        jQuery('div.additional-warning').hide();
    }
}

function incrementCurrentShipmentQty() {
	var currentShipmentItemQty = jQuery('#edit-curr-items-cnt').text() * 1;
    jQuery('#edit-curr-items-cnt').text(currentShipmentItemQty + 1);
    estimateSubtotals();
    checkRemoveFromOtherShipments();
	return false;
}

function decrementCurrentShipmentQty() {
	var currentShipmentItemQty = jQuery('#edit-curr-items-cnt').text() * 1;
	if (currentShipmentItemQty > 0) {
		jQuery('#edit-curr-items-cnt').text(currentShipmentItemQty - 1);
        estimateSubtotals();
        checkRemoveFromOtherShipments();
	}
	return false;
}

function reloadEditShipmentsPage(selectedShipmentId, updatedHtml)
{
    jQuery('#edit-item-dialog').dialog('destroy');
    jQuery('.ship_dates').datepicker('destroy');
    jQuery('#edit-item-dialog').remove();
    jQuery('#main').html(updatedHtml);
    jQuery('#edit-item-dialog').dialog({
        autoOpen:false,
        modal:true
    });
    jQuery('.ship_dates').each(function(i, el){
        initChangeShipmentDate(el);
    });
    jQuery('.frm-edit-order-cap').each(function(i, el){
        initEditShipmentCapForm(el);
    });
    var currentShipment = jQuery('#shipment-' + selectedShipmentId);
    if (currentShipment.length) {
        jQuery('.shipment-items').removeClass('shown');
        currentShipment.addClass('shown');
    }
}

function updateItem(updateUrl)
{
    var newQty = jQuery('#edit-curr-items-cnt').text() * 1;
    var oldQty = jQuery('#original-shipment').val() * 1;
    if(newQty != oldQty) {
        var frozenMessage = jQuery('#monthly-budget-warning').hasClass('frozen');
        var monthlyBudgetWarningShown = (jQuery('#monthly-budget-warning').css('display') != 'none');
        if(monthlyBudgetWarningShown && frozenMessage) {
            alert('This amount exceeds your budget. Please change the quantity to be under your budget or press the cancel link.');
            return false;
        } else if (monthlyBudgetWarningShown && !jQuery('#chk-allow-exceeds:checked').length) {
            alert('You must agree to an increased shipment budget to proceed');
            return false;
        }

        jQuery('#edit-item-dialog').addClass('waiting');

        var parameters = {
            shipment_id: jQuery('.shipment-items.shown').attr('id').split('-')[1],
            shipment_qty: newQty,
            product_id: jQuery('#edit-item-dialog').attr('product_id')
        };

        // Ajax update
        jQuery.post(updateUrl,parameters,function(data){
            jQuery('#edit-item-dialog').removeClass('waiting');
            if (data.success) {
                reloadEditShipmentsPage(data.shipmentId, data.updatedHtml);
            } else {
                alert(data.error);
            }
        },'json');
    } else {
        jQuery('#edit-item-dialog').dialog('close');
    }
	return false;
}

function editItemQueueQuantity()
{
	jQuery('#edit-item-dialog #future-items-cnt').hide();
	jQuery('#edit-item-dialog #btn-edit-future-items').hide();
	jQuery('#edit-item-dialog #txt-future-items').show();
	return false;
}

function endOfDays(date) {
	var natDays = [
        [1, 29, 'us'],[1, 30, 'us'],[1, 31, 'us'],
        [2, 29, 'us'],[2, 30, 'us'],[2, 31, 'us'],
        [3, 29, 'us'],[3, 30, 'us'],[3, 31, 'us'],
        [4, 29, 'us'],[4, 30, 'us'],[4, 31, 'us'],
        [5, 29, 'us'],[5, 30, 'us'],[5, 31, 'us'],
        [6, 29, 'us'],[6, 30, 'us'],[6, 31, 'us'],
        [7, 29, 'us'],[7, 30, 'us'],[7, 31, 'us'],
        [8, 29, 'us'],[8, 30, 'us'],[8, 31, 'us'],
        [9, 29, 'us'],[9, 30, 'us'],[9, 31, 'us'],
        [10, 29, 'us'],[10, 30, 'us'],[10, 31, 'us'],
        [11, 29, 'us'],[11, 30, 'us'],[11, 31, 'us'],
        [12, 29, 'us'],[12, 30, 'us'],[12, 31, 'us']
    ];
	//There is a way to do this without the for loop I know there is...
	//But since my time is of the essence and the customers can wait a few
	//miliseconds we are going this route.
    for (i = 0; i < natDays.length; i++) {
      if (date.getMonth() == natDays[i][0] - 1
          && date.getDate() == natDays[i][1]) {
        return [false, natDays[i][2] + '_day'];
      }
    }
  return [true, ''];
}


function initChangeShipmentDate(inputEl)
{
    jQuery(inputEl).datepicker({
        showOn: 'button',
				beforeShowDay: endOfDays,
        buttonImage: jQuery(inputEl).attr('btn_img_src'),
        buttonImageOnly: true,
        buttonText: 'change shipment date',
        dateFormat: 'yy-mm-dd',
        minDate: jQuery(inputEl).attr('min_date_diff'),
        onSelect: changeShipmentDate
    });

    defaultDateString = jQuery.trim(jQuery(inputEl).siblings('.shipdate').text());
    if (defaultDateString != 'Not scheduled') {
        jQuery(inputEl).datepicker('option','defaultDate',jQuery.datepicker.parseDate('MM d, yy',defaultDateString));
    }
}

function changeShipmentDate(dateText, inst) {
    var parameters = {
		ship_date: dateText,
		shipment_id: inst.id.split('-')[1]
    };
    jQuery('.shipment-header').addClass('waiting');
    jQuery.getJSON(jQuery('.ship_dates').attr('save_href'), parameters, function(data) {
        jQuery('.shipment-header').removeClass('waiting');
    	if (data.success) {
    	    for (var i in data.new_shipment_dates) {
    	        shipment_id = data.new_shipment_dates[i]['shipment_id'];
    	        new_ship_date = jQuery.datepicker.parseDate('yy-mm-dd', data.new_shipment_dates[i]['shipment_date']);
    	        if (jQuery('#ship_date-' + shipment_id).length) {
    	            jQuery('#ship_date-' + shipment_id).html(jQuery.datepicker.formatDate('MM d, yy', new_ship_date));
    	        }
    	    }
    	} else {
    	    alert(data.error);
    	}
    });
}

function updateTestDate()
{
    jQuery.get('/productqueue/customer/getTestDate',function(data){
        var testDateSelector = '#queue-test-date span'; 
        if (data != jQuery(testDateSelector).text()) {
            jQuery(testDateSelector).text(data);
            jQuery(testDateSelector).css('background','#ffff00');
            jQuery(testDateSelector).animate({backgroundColor:'#ffffff'},1500);
        }
    });
}

function displayEditShipmentCap(el)
{
    var sectionEl = jQuery(el).closest('.shipment-order-cap');
    sectionEl.find('label span').hide();
    sectionEl.find('a').hide();
    sectionEl.find('form .txt-order-cap').show();
    sectionEl.find('form .txt-order-cap').focus();
    sectionEl.find('form .txt-order-cap').select();
    sectionEl.find('form button').show();
}

function initEditShipmentCapForm(el)
{
    var sectionEl = jQuery(el).closest('.shipment-order-cap');
    jQuery(el).ajaxForm({
        dataType: 'json',
        beforeSubmit: function() {
            sectionEl.addClass('waiting');
            sectionEl.find('.btn-save-order-cap').attr('disabled','disabled');
        },
        success:  function(data) {
            sectionEl.removeClass('waiting');
            sectionEl.find('.btn-save-order-cap').attr('disabled','');
            if (data.success && data.shipmentId) {
                reloadEditShipmentsPage(data.shipmentId,data.updatedHtml);
            } else {
                sectionEl.find('label span').show();
                sectionEl.find('a').show();
                sectionEl.find('form .txt-order-cap').hide();
                sectionEl.find('form button').hide();
                if (data.success) {
                    sectionEl.find('label span').text(sectionEl.find('form .txt-order-cap').val());
                } else {
                    alert(data.error);
                }
            }
        }
    });
}

function sendShipmentRequest(cur_id,dirn,link){

    jQuery.blockUI({message: "<h2>Loading Shipment</h2>"});
    jQuery.ajax({
        type:'POST',
        url:'/productqueue/customer/getshipment',
        dataType: 'json',
        data: {
            id:cur_id,
            move:dirn
        },
        success: function(data) {
            if(data.html){
                jQuery('#shipment').html(data.html);
            }
            if(data.error){
                alert(data.err);
            }
            jQuery.unblockUI();
        },
        error: function(XMLHttpRequest,textStatus,errorThrown) {
            jQuery.unblockUI();
            alert('error submitting the form');
        }
    });
}

function updateSortType(){
	jQuery.blockUI({message:"<h2>Updating your Queue</h2>"});

	jQuery.ajax({
		type:'POST',
		url:'/productqueue/customer/updatesorttype/',
		dataType:'json',
		data:{'id':-1},
		success:function(data){
			if(data.success == true) {
                jQuery('#consultant_message').hide();
                jQuery('#sort_changed').show();
                jQuery.unblockUI();
			} else {
				jQuery.unblockUI();
				alert('There was an error making the change please reload the page and try again');
			}
		},
		error: function(XMLHttpRequest,textStatus,errorThrown){
			jQuery.unblockUI();
          alert('error submitting the form');
        }
	});
}

function optimizeShipments() {
    jQuery('#optimize_shipments').dialog('open');
}

function toggleLock(checkbox, shipmentId) {
    var checked = jQuery(checkbox).is(':checked');
    var url = 'lockShipment';

    if(!checked) {
        url = 'unlockShipment';
    }

    jQuery.ajax({
        type:'POST',
        url:'/productqueue/customer/' + url,
        data: {'shipmentId': shipmentId},
        dataType: "json",
        success: function(result) {
           if(result.success) {

           } else {
               if(checked) {
                    jQuery(checkbox).removeAttr('checked');
                    alert('The system was unable to lock your shipment.  Try logging in again and retry.');
                } else {
                    jQuery(checkbox).addAttr('checked');
                    alert('The system was unable to unlock your shipment.  Try logging in again and retry.');
                }
           }
        },
        error: function() {
            if(checked) {
                jQuery(checkbox).removeAttr('checked');
                alert('The system was unable to lock your shipment.  Try logging in again and retry.');
            } else {
                jQuery(checkbox).addAttr('checked');
                alert('The system was unable to unlock your shipment.  Try logging in again and retry.');
            }
        }
    });
}

function updateBudget(){
	jQuery.blockUI({message:"<h2>Updating your Queue</h2>"});
}

jQuery(document).ready(
function() {       
    jQuery('#optimize_shipments').dialog({
		autoOpen: false,
		modal: true,
		buttons: {
            Cancel: function() {
                jQuery(this).dialog('close');
                return false;
            },
            'Continue': function() {
                jQuery(this).dialog('close');
                jQuery.blockUI({message:"<h2>Optimizing your shipments</h2>This may take a few minutes for Qs with large budgets and many items<br/>Please wait"});
                jQuery.ajax({
                    url: "/productqueue/customer/optimize",
                    type: "POST",
                    success: function() {
                        window.location.reload();
                    },
                    error: function() {
                        jQuery.unblockUI();
                        alert("An error occurred while trying to optimize your Q's shipments.  Please try again.");
                    }
                });
                return true;
            }
		}
	});

	jQuery('#btn-edit-budget').click(
        function(){
            jQuery('#budget_change_message').dialog('open');
        }
    );

	jQuery('#budget_change_message').dialog({
		autoOpen:false,
		modal:true,
		buttons: {
            Cancel: function() {
                jQuery(this).dialog('close');
                return false;
            },
            'Continue': function() {
                jQuery('.view-budget').hide();
                jQuery('.edit-budget').show();
                jQuery('#txt-budget input').focus();
                jQuery('#txt-budget input').select();
                jQuery(this).dialog('close');
                return true;
            }
		}
	});
	
	jQuery('#frm-budget').ajaxForm({
        dataType: 'json',
        beforeSubmit: function() {
            jQuery.blockUI({message:"<h2>Changing your Q's budget and<br/>optimizing your shipments</h2>This may take a few minutes for Qs with large budgets and many items<br/>Please wait"});
            //jQuery('#frm-budget').addClass('waiting');
            //jQuery('#btn-save-budget').attr('disabled','disabled');
        },
        success: function(data) {
            if (data.success) {
                window.location.reload();
            } else {
                jQuery('.view-budget').show();
                jQuery('.edit-budget').hide();
                jQuery.unblockUI();
								//jQuery('#frm-budget').removeClass('waiting');
                //jQuery('#btn-save-budget').removeAttr('disabled');
                alert(data.errorMessage);
            }
        },
        error: function() {
            jQuery.unblockUI();
            alert("An error occurred while trying to change your Q's budget.  Please try again.");
        }
    });

	jQuery('#edit-item-dialog').dialog({
		autoOpen:false,
		modal:true
	});

	jQuery('.ship_dates').each(function(i, el){
	    initChangeShipmentDate(el);
	});
	
	if (jQuery('#queue-test-date').length) {
	    setInterval('updateTestDate()',15000);
	}
	
	jQuery('.frm-edit-order-cap').each(function(i, el){
	    initEditShipmentCapForm(el);
    });
});
