jQuery(document).ready(function(){
	jQuery('#consumer').change(function(){
		var cId = jQuery(this).val();
		var elmObj = jQuery(this);
		if (cId){
			jQuery('#sale-wrapper').show();
			jQuery.ajax({
				type: 'POST',
				url: siteUrl+'consumers/consumerCompaigns',
				data: { cId: cId},
				beforeSend: function(){
					elmObj.after('<img src="'+siteUrl+'img/loading20.gif" id="loading"/>');
				},
				success: function(data){
					jQuery('#loading').remove();
					ajaxRunning = false;
					$('#active-compaign').html(data);
					check_offers();
				},
				statusCode: {
					404: function() {
						alert( message.noPage );
					}
				}
			});
		}else{
			jQuery('#sale-wrapper').hide();
			$('#active-compaign').html('');
		}
	});
	
	
	
});


function check_offers(){
	var offer_html = '<dd>'+message.freeItems+'</dd><dt><table class="tbl-list" cellpadding="0" cellspacing="0" border="0"><tr><th>'+message.brand+'</th><th>'+message.item+'</th></tr>';
	var offer_htmlTr = '';
	
	jQuery('[name="compaign[]"]').each(function(){
		//alert(this.value)
		var compId = $(this).val();
		var tempObj = {};
		jQuery("#sell-tbl tr:gt(0)").each( function(){
			var brand = jQuery(this).find('.td-brd select').val();
			var brandValue = jQuery(this).find('.td-brd select option:selected').text();
			//alert(brandValue);
			var unit = jQuery(this).find('.td-unt select').val();
			var qty = jQuery(this).find('.td-qty input').val();
			if (brand && unit && qty){
				if (tempObj[brand+'_'+unit]){
					tempObj[brand+'_'+unit] = parseFloat(tempObj[brand+'_'+unit]) + parseFloat(qty);
				}else{
					tempObj[brand+'_'+unit] = qty;
				}
				tempObj[brand+'value'+unit] = brandValue;
			}
		});
		
		if ( compaignObj[compId] ){
			//alert(compaignObj[compId].required_unit);
			var rQty = parseFloat(compaignObj[compId].required_qty);
			var rUnit = compaignObj[compId].required_unit;
			var brID = compaignObj[compId].brand_id;
			var cal_percent = compaignObj[compId].cal_percent;
			
			var orderQty = parseFloat(tempObj[brID+'_'+rUnit]);
			if (cal_percent==1){
				if (orderQty >= rQty) {
					var Ind = parseFloat(orderQty/rQty);
				}else{
					var Ind = 0;
				}
			}else{
				var Ind = parseInt(orderQty/rQty);
			}
			if (Ind > 0){
				var freeItem = parseFloat(compaignObj[compId].free_qty) * Ind;
				offer_htmlTr += '<tr><td>'+tempObj[brID+'value'+rUnit]+'</td><td>'+ freeItem +' '+ compaignObj[compId].free_unit +'<input type="hidden" name="freeItem[brand_id][]" value="'+brID+'" /><input type="hidden" name="freeItem[quantity][]" value="'+freeItem+'" /><input type="hidden" name="freeItem[unit][]" value="'+compaignObj[compId].free_unit+'" /> <input type="hidden" name="freeItem[compaign_id][]" value="'+compId+'" /></td></tr>';
			}
		}
		
		//alert(tempObj.toSource());
	});
 
	offer_html += offer_htmlTr + '</table></dt>';
	if (offer_htmlTr != ''){
		jQuery('#free_items').html(offer_html);
		jQuery('#free_items').show();
	}else{
		jQuery('#free_items').hide();
	}
}