
elements = '';

$(function() {

	//$('.tabs').tabs().find('li').addClass( 'ui-tabs-nav-item' );
	//set up cart dropdown
	var cart_list = $('#pick_cart');
	if(cart_list[0]) {
		$('#pick_cart').hover(function() {
			$('#cart_list').show();	
			$('#cart_list').hover(function() {},
				function() {
					$(this).hide();
				});			
		}, function() {});
	}
	
	$('.fromdate').datepicker({
		minDate: '+2w'
	});
	
	$('.todate').datepicker({
		minDate: '+1m'						
	});
	
	$('.ricafromdate').datepicker({
		minDate: '+8w'
	});
	
	$('.ricatodate').datepicker({
		minDate: '+2m'						
	});	

    $('.qrvdate').datepicker({
        minDate: '+6w'
    });

	$('.fivedays').datepicker({
		minDate: '+5d'						
	});	
	
	$('.promodate').datepicker({ defaultDate: '+1m' });

	$('.date').not('.duedate').datepicker({
		onSelect: function(dateText, inst){
			$(this).removeClass('error');
			$(this).next('.error').hide();
		}
	});
	
	$('.duedate').datepicker( {
		minDate : '+4w'
	});
	
	$('.catalinadate').datepicker( {
		minDate : '+7w'
	});
	
	//alert($('.cat_overview').size());
	if($('.cat_overview').size()) {
		//alert('here');
		$('.cat_overview').dialog({
			autoOpen: true,
			modal:true,
			title: 'Program Overview',
			width: 630
		});
	}
		
	$('.textfield').focus(function() {
	  this.select();
	});
	$('.delete').click(function() {
		return confirm( 'Are you sure you wish to remove this item from your cart?' );
	});
	
	$('form').submit(function() {
		var valid = true;
	
		$(this).find('.integer').each(function() {
			var val = $(this).val();
			
			if ( isNaN( parseInt(val) ) ) {
				alert( val + ' is not a number.' );
				valid = false; 
			} else {
				$(this).val( parseInt(val) );
			}
			
		});
		
		
		return valid;
	});
	
	$('.order_link').click(function() {
	
		$.get( $(this).attr('href'), null, function( form, statusText ) {
		
			elements = $(form);
			$(elements).dialog({ width: 300 });
			
			$(elements).find('form').ajaxForm({
				beforeSubmit: displaySending, 
				success: processResults
			});
			
		});
		
		return false;
	});
	
	
	$('.order_form').submit(function() {
		var valid = false;
		
		$('.quantity').each(function() {
			if ( $(this).val() > 0 ) {
				valid = true;
			}
		});
		
		if ( valid ) {
			return true;
		} else {
			alert( 'Please select some items to add to the cart.' );
			return false;
		}
		
	});
	

	$('.order_form').ajaxForm({
		beforeSubmit: function( data ) {
			var valid = false;
			
			for ( var i=0; i < data.length; i++ ) {
				if ( data[i].value > 0 ) {
					valid = true;
					break;
				}
			}
			
			if ( !valid ) {
				alert( 'Please select some items to add to the cart.' );
				return false;
				
			} else {
			    $('.quantity').val(0);
			    
				
				$('input[type=submit]').removeClass('cart_btn');
				
			    $('input[type=submit]')
			    	.val('Updating')
			    	.attr( 'disabled', true );
			    
			    elements = '';
			    
			    return true;
			}
		}, 
		
		success: function( data ) {
			elements = $(data);
			
		
			$(elements)
				.dialog({
					width: 300,
					close: function() {
				    	$('input[type=submit]').addClass('cart_btn').val('').attr( 'disabled', false );
					}
				})
				.find('.close_link').click(function() {
					$(elements).dialog('close');
				})
				;
				
		}
	});
	
	
	$('.order_form2').submit(function(data) {
		var valid = false;
		$('.quantity').each(function() {
			if ( $(this).val() > 0 ) {
				valid = true;
			}
		});
		
		if(!valid) 
			alert( 'Please select some items to add to the cart.' );
		
		return valid;
	});
	
	/* Sampling section javascript */
	$('#sampling_divisions').change(function() {
		$('#sampling_products').load(homeDir + 'sampling/list.products', {
			'id' : $(this).find('option:selected').val()
		}, function(){
			$('#sampling_products').attr( 'disabled', false );
		});
		
		
		$('#sampling_flavors').empty().html('<option value="" selected="selected">Select Product</option>').attr('disabled',true);
	});

	$('#sampling_products').change(function() {
		$('#sampling_flavors').load(homeDir + 'sampling/list.flavors', {
			'id' : $(this).find('option:selected').val()
		}, function(){
			$('#sampling_flavors').attr('disabled',false);
		});
	});


	$('#sampling_divisions1').change(function() {
		$('#sampling_products1').load(homeDir + 'sampling/list.qrv.products', {
			'id' : $(this).find('option:selected').val()
		}, function(){
			$('#sampling_products1').attr( 'disabled', false );
		});


		$('#sampling_flavors1').empty().html('<option value="" selected="selected">Select Product</option>').attr('disabled',true);
	});

	$('#sampling_products1').change(function() {
		$('#sampling_flavors1').load(homeDir + 'sampling/list.flavors', {
			'id' : $(this).find('option:selected').val()
		}, function(){
			$('#sampling_flavors1').attr('disabled',false);
		});
	});
    	$('#sampling_divisions2').change(function() {
		$('#sampling_products2').load(homeDir + 'sampling/list.products', {
			'id' : $(this).find('option:selected').val()
		}, function(){
			$('#sampling_products2').attr( 'disabled', false );
		});


		$('#sampling_flavors2').empty().html('<option value="" selected="selected">Select Product</option>').attr('disabled',true);
	});

	$('#sampling_products2').change(function() {
		$('#sampling_flavors2').load(homeDir + 'sampling/list.flavors', {
			'id' : $(this).find('option:selected').val()
		}, function(){
			$('#sampling_flavors2').attr('disabled',false);
		});
	});

	$('#sampling_divisions3').change(function() {
		$('#sampling_products3').load(homeDir + 'sampling/list.products', {
			'id' : $(this).find('option:selected').val()
		}, function(){
			$('#sampling_products3').attr( 'disabled', false );
		});


		$('#sampling_flavors3').empty().html('<option value="" selected="selected">Select Product</option>').attr('disabled',true);
	});

	$('#sampling_products3').change(function() {
		$('#sampling_flavors3').load(homeDir + 'sampling/list.flavors', {
			'id' : $(this).find('option:selected').val()
		}, function(){
			$('#sampling_flavors3').attr('disabled',false);
		});
	});

    $('#sample_order_form').submit(function(){
       if (($('#sampling_flavors1').val()==0)||($('#sampling_flavors2').val()==0)) {
           alert('Please select at least 2 flavors');
           return false;
       }
       return true;
    });
    $('#sample_order_form').submit(function(){
       if (($('#qty1').val()=='')||($('#qty2').val()=='')) {
           alert('Please specify the quantity');
           return false;
       }
       return true;
    });
	$('#sampling_flavors').change(function() {
		$.post( homeDir + 'sampling/add.item', {
			'id' : $(this).find('option:selected').val(),
			'order_id' : $('#order_id').val()
		}, function( data, textStatus ) {
			
			$('#products_selected').empty().append( data );
			$('#sampling_products').empty().html('<option value="" selected="selected">Select Division</option>').attr('disabled',true);
			$('#sampling_flavors').empty().html('<option value="" selected="selected">Select Product</option>').attr('disabled',true);
			$('#sampling_divisions option:selected').attr( 'selected', false );
			$('#sampling_divisions option[value=""]').attr( 'selected', true );
			$('.delete-sample-item').click( deleteSampleItem );
			var n = $("#products_selected tr").length;
				if(n > 1){
			$('#samplingcont').attr('disabled', false);
		}
		});
		
	});
	
	
	$('.delete-sample-item').click( deleteSampleItem );
	
	
	$('#distribute-0').click(function() {
		$('#coupons,label[for=coupons]').hide();
		$('#coupons').val( '' );
	});
	
	$('#distribute-1').click(function() {
		alert(
"Programs including distribution of GMI manufacturer coupons are considered high-risk and must be managed or executed by Mass Connections. \n\n GMI manufacturers coupons must be approved by CPG Manager. Coupon disribution requires 8-week lead time."
		);
		
		$('#coupons,label[for=coupons]').show();
		
	});
	
	$('#distribute2-0').click(function(){
		$('#handouts,label[for=handouts]').hide();
		$('#handouts').val( '' );
	});
	
	$('#distribute2-1').click(function(){
		$('#handouts,label[for=handouts]').show();
	});	
	
	
	$('#coupons,label[for=coupons]').hide();
	$('#handouts,label[for=handouts]').hide();
	
	
	/* sampling festival */
	
	if ($('#other')) {
		$('#funding').change(function(){
			if($(this).val() == 'other') {
				$('#other, label[for=other]').show();
			} else {
				$('#other, label[for=other]').hide();
				$('#other').val( '' );	
			}
		});
	}
	
	$('#sampling-0').click(function(){
		$('[name=products],label[for=products]').hide();
		$('[name=qty],label[for=qty]').hide();
		
		$('[name=qty]').val( '' );
		$('[name=products]').val( '' );	

	});
	
	$('#sampling-1').click(function(){
		$('[name=products],label[for=products]').show();
		$('[name=qty],label[for=qty]').show();
	});	
	
	
	//alert($('#sampling-0:checked').val());
	if ($('#sampling-0:checked').val()) {
		$('[name=products],label[for=products]').hide();
		$('[name=qty],label[for=qty]').hide();
	}
	
	
	if($('#other').val() == '')
		$('#other, label[for=other]').hide();
	
	
	/* NRO TOOLS */
	$('.value').change(function() {
		var sum = 0;
		for(var i = 1; i <= 6; i++) {
		
			if($('#value0' + i).val())
				sum += parseInt($('#value0' + i).val());
		}
		$('#non_cereal_category_total').val(sum);
		$('#category_total').val(parseInt($('#value00').val()) + sum);
	});
	
	$('.kitButton').change(function() {
		
		if ($(this).val() == 'A') {
            if ($('#kit_qty_A').attr('disabled')==true)
                $('#kit_qty_A').attr('disabled', false);
            else {
                $('#kit_qty_A').attr('disabled', true);
                $('#kit_qty_A').attr('value', '');
            }
		}
		else {
            if ($('#kit_qty_B').attr('disabled')==true)
                $('#kit_qty_B').attr('disabled', false);
            else {
                $('#kit_qty_B').attr('disabled', true);
                $('#kit_qty_B').attr('value', '');

            }
		}
			
	});
    $('#coupons-0').attr('checked',true);
    $('#coupon_printer_row').hide();
    $('#coupons-1').click(function(){
        $('#coupon_printer_row').show();
    });
    $('#coupons-0').change(function(){
        $('#coupon_printer_row').toggle();
        $('#coupon_printer').val('');
        $('#coupon_printer_other').val('');
    });

    $('#coupon_printer_other_row').hide();
    $('#coupon_printer').change(function(){
        if ($(this).val()=='other') $('#coupon_printer_other_row').show();
        else $('#coupon_printer_other_row').hide();
    });



	$('.nro_form').submit(function() {
		
		if (!$('.kitButton:checked').val()) {
			alert('Must select a kit!');
			return false;
		}
		
		if((($('#kit_qty_A').val()*1)+($('#kit_qty_B').val()*1)) >50) {
			alert('Combined quantity of kits must not exceed 50');
			return false;			
		}	
		if(($('#kit_qty_A').val()+$('#kit_qty_B').val()) ==0) {
			alert('Must enter quantity for each kit');
			return false;
		}

		if(($('#category0').val()=='')||($('#value00').val()==0)) {
			alert('Must enter a category and # of cases');
			return false;
		}


		for (var i = 0; i <= 6; i++) {
			if ($('#value0' + i).val() != 0 && $('#value0' + i).val() < 100) {
				//removed 2/12/09
				//alert('Must order a minimum of 100 cases per category.');
				//return false;
			}
		}
		
		
		return true;
	});
	
	
	$('#low_risk_fields').hide();
	$('.program_id').click(function() {
		
		if($(this).val() == 3) {
			
			$('#low_risk_fields').show();
			$('#low_risk_fields input').addClass('required');
		} else {
			$('#low_risk_fields').hide();
			$('#low_risk_fields input').removeClass('required');			
		}
	});
	
	$('#review_sample_order').validate();
	
	
	
	$('.funding_dropdown').change(function() {
		var source = $(this).attr('source');
		if($(this).val() == 'Third Party Payment') {
			$('#dropdown_msg_' + source).text('Third Party Payments are paid through the Customer Service Center');
		} else {
			$('#dropdown_msg_' + source).text('');
		}
	});
	
	
		$('.advertised').change(function() {
			if($(this).val() === '1') {
				$('.ad_options').show();
			} else {
				$('.ad_options').hide();
			}
		});
		$('.ad_options').hide();	
		
		
	$('.second_offer').click(function() {
			
			if($(this).val() === '1') {
				$('#offer_2').show();
			} else {
				$('#offer_2').hide();
			}		

	});
	

	$('#offer_2').hide();
	
	
	$('#catalina_form').submit(function() {
			
		var errors = false;
		$('.required').each(function() {
			if($(this).val() === '') {
				alert('You have missed a required field. Please enter the information \ninto the required field that is currently empty');
				errors = true;
				return false;	
			}			
		});
		
		if(errors) {
			return false;
		}
		
	});	
	
	$('#feedback_form').dialog({
		autoOpen: false,
		modal:true,
		title: 'Send Us Feedback',
		width: 535
	});
	
	$('#send_feedback').click(function() {
		$('#feedback_form').dialog('open');
		$('#feedback_uri').val($(this).attr('rel'));
		return false;
	});
	
	$('.item_embed_link').click(function() {

		$('.item_code').hide();
		$('.item_code[rel="' + $(this).attr('rel') + '"]').show();
		
		//auto select the embed code
		var textArea = $('.item_code[rel="' + $(this).attr('rel') + '"]').find('textarea');
		textArea.focus();
		textArea.select();

	});
		
});


function deleteSampleItem() {
	val = confirm( 'Are you sure you wish to delete this item?' );
	
	if ( val == true ) {
		url = $(this).attr('href');
		$.post( url, null, function( data, textStatus ) {
			$('#products_selected').empty().append( data );
			$('.delete-sample-item').click( deleteSampleItem );
		});
	
		var n = $("#products_selected tr").length;
		if (n-1 < 2) {
			$('#samplingcont').attr('disabled', true);
		}
	}
	
	return false;
}



function displaySending( data, form, options ) {
	$(form).find('input[type=submit]').val('updating').attr('disabled',true);
}

function processResults(data) {
	var newelements = $(data);
	
	if ( elements ) {
		$(elements).empty().append(newelements);
	} else {
		elements = newelements;
		$(elements).dialog({width: 300});
	}
	
	$(newelements).find('.close_link').click(function() {
		$(elements).dialog('close');
		return false;
	});
	
	$('input[type=submit]').attr('disabled',false).val('Add to cart');
	
	var forms = $(newelements).find('form');
	if ( forms.length > 0 ) {
		makeAjax( forms );
	}
	
	return false;
}



