/**
 * Created by Nathan J. Brauer
 * Date: 9/27/11
 * Time: 6:30 PM
 */

/**
 * This deals with editing the mPlan details (not questions -- questions are further below)
 */
$(function(){

	$('#MVmPlanForm_Form_mPlanEdit').bind('submit', function(e) {
		var errorMsg = "You have the following errors: ";
		var isGood = true;
		var theType = $('#repeatType').val();

		if ($('#StartRecurring').val() == '') {
			errorMsg += "You must specify a Start Date";
			isGood = false;
		}
		if ($('#EndByRecurring').val() == '') {
			errorMsg += "You must specify an End Date";
			isGood = false;
		}
		if (isGood) {
			var startDateS = $('#StartRecurring').val().split("/");
			var endDateS = $('#EndByRecurring').val().split("/");
			
			var oneDayinMs = 1000*60*60*24;
			var startDate = new Date(startDateS[2], (startDateS[1]-1), startDateS[0]);
			var endDate = new Date(endDateS[2], (endDateS[1]-1), endDateS[0]);
			var dateDiff = endDate.getTime() - startDate.getTime();
			var dayDiff = Math.round(dateDiff/oneDayinMs);

			if (dayDiff <= 0) {
				errorMsg += "Your start and end dates will not work.  Either the end date is before the start date or the start date and the end date are the same days.";
				isGood = false;
				//return errorMsg;
			}

		}	
		if (theType == "OneTime") {
			//only need to check the
			//start and end and that's 
			//already done above
			if (!isGood) {
				alert(errorMsg);
			}
			return isGood;
		}
		if ($('#recurringEndSelect').find(':checked').val() == "on") {
			var recurEndString = $('#EndRecurring').val();
			var recurEndStringS = $('#EndRecurring').val().split("/");
			var recurEndDate = new Date(recurEndStringS[2], (recurEndStringS[1] - 1), recurEndStringS[0]);
			var recurDateDiff = recurEndDate.getTime() - endDate.getTime();
			var recurDayDiff = Math.round(recurDateDiff/oneDayinMs);
			if (recurEndString == "" || recurDayDiff < 0) {
				errorMsg += "Your repeat end date is either blank or is set to before the end date of your mplan. Please adjust your repeat end date to a date after the end date of your mplan.";
				//return errorMsg;
				isGood = false;
			
			}
		}
		else {
		// then they specified number of occurrences
			var numOfRecurrences = $('#recurringEndOccurrences').val();
			if (parseInt(numOfRecurrences) <= 0) {
				errorMsg += "You must specify a positive number greater than zero as the number of times the mplan will repeat.";
				//return errorMsg;
				isGood = false;
			}
		}

		//check for the endRecurrence stuff

		//
		if (theType == "Daily") {
			if (dayDiff != 1) {
				errorMsg += "If you choose to repeat an mplan daily you must have an mplan that lasts one day long. In other words the start date must be the day before the end date.";
				//return errorMsg;
				isGood = false;
			}
		}
		else if (theType == "Weekly") {
			if (dayDiff > 7) {
				errorMsg += "If you choose to repeat an mplan weekly you must have an mplan that lasts no longer than one week. Otherwise the mplan would overlay on itself.";
				//return errorMsg;
				isGood = false;
			}
		}
		else if (theType == "BiWeekly") {
			if (dayDiff > 7) {
				errorMsg += "If you choose to repeat an mplan bi-weekly you must have an mplan that lasts no longer than one week.";
				//return errorMsg;
				isGood = false;
			}
		}
		else {//Monthly
			var endDayOfMonth = endDateS[0];
			if (dayDiff > 28 || endDayOfMonth > 28) {
				errorMsg += "If you choose to repeat an mplan monthly you must have an mplan that lasts no longer than 28 days and does not end any later than the 28th. Otherwise the mplan could overlap itself in Feb.";
				//return errorMsg;
				isGood = false;
			}

		}
		if (!isGood) {
			alert(errorMsg);
		}
		return isGood;
	});

/*
	var $recurringChk = $('#MVmPlanForm_Form_mPlanEdit_Reoccuring').change(function() {
		alert("This is recurring "+$(this).attr('checked'));
	});
*/
	$('#endRecurringBy').hide();
	$('#repeatByWrap').hide();

		$('#repeatType').change(function() {
			var theType = $(this).val();

			if (theType == "OneTime") {
				$('#repeatTypeClarification').html('');
				$('#endRecurringBy').hide();
				$('#repeatByWrap').hide();
			}
			else if (theType == "Daily") {
				$('#repeatTypeClarification').html('');
				$('#endRecurringBy').show();
				$('#repeatByWrap').hide();
			}
			else if (theType == "Weekly") {
				$('#repeatTypeClarification').html('(Repeats based on day of the week)');
				$('#endRecurringBy').show();
				$('#repeatByWrap').hide();
			}
			else if (theType == "BiWeekly") {
				$('#repeatTypeClarification').html('(Repeats based on day of the week)');
				$('#endRecurringBy').show();
				$('#repeatByWrap').hide();
			}
			else {//Monthly
				$('#repeatTypeClarification').html('');
				$('#endRecurringBy').show();
				$('#repeatByWrap').show();
			}
			//alert("This is recurring "+$(this).attr('checked'));
		});


		$('#repeatType').change();

		var $mPlanForm = $('#MVmPlanForm_Form_mPlanEdit');
		window.$mPlanQuestions = $('#mPlanQuestions');
		window.mPlanData = $mPlanQuestions.data();
		if ($mPlanForm.length) {
			var	$StoreGroup = $('select[name=AssignedGroupID]',$mPlanForm), //ONE select
				$Producers = $('select[name=AssignedToID]',$mPlanForm), //MULTIPLE selects
				$SubmitButton = $('.Actions',$mPlanForm),
				$FieldDiv = $('#AssignedToID');
			$StoreGroup.bind('change keyup',function(){
				var $this = $(this);
				$SubmitButton.hide(); $FieldDiv.hide();
				$Producers.val(0)
					.css('display','none').attr('disabled','disabled');
				if ($this.val() > 0) {
				var $option = $this.find(':selected'),
					RetailerID =
						($option.hasClass('level_1'))
						? $option.val()
						: $option.prevAll('option.level_1').first().val();
				$Producers.filter('[data-store-group-id='+RetailerID+']')
					.show().removeAttr('disabled');
				$SubmitButton.show();
				$FieldDiv.show();
			}
		});
		if (!$StoreGroup.val()) $StoreGroup.keyup();
	}

});

function showStoreWindow() {
	$.colorbox({
		innerWidth: '400px',
		innerHeight: '400px',
		transition: 'fade',
		title: "Recurring Schedule",
		inline: true,
		open: true,
		//opacity: 0,
		//fixed: true,
		href: "#recurringSchedule",
		onClosed: function(){ 
					$("#AddRepAssignment").toggle();
					$("#treeStoreSelector").jstree("uncheck_all");
					$("#treeStoreSelector").jstree("close_all");
			   } 
	});
}


