// Used to track which row to invalidate. It is set by the invalidate button, and read when the confirm button is pressed.
var lastClickedInvalidate = null;
// Used to track the last clicked marketing rep 
var lastClickedMR = null;
$(document).ready(function() {
	var ie6 = (jQuery.browser.msie && jQuery.browser.version.indexOf("6") == 0);
	//alert(ie6);
	//Navigation Highlight for IE6
	if(ie6) {
		$("#top-nav ul li").hover(function() {
			$(this).addClass("hovers");
		}, function() {
			$(this).removeClass("hovers");
		});
	}

	// Flag/Unflag
	$("a.flag").click(function() {
       		$(this).html($(this).attr("class") == "flag" ? "Unflag this app" : "Flag this app");
       		$(this).toggleClass("unflag");
    });
	//Hide Navigation
	var pageId = $("body").attr("id").toLowerCase();
	if(pageId.indexOf("step") > -1) {
		$("#top-nav ul").hide();
		$("#top-nav").css("height", "0");
	} else {
		$("#top-nav ul").show();	
	}
	
	if(pageId.indexOf("enroll") > -1) {
		$("#top-nav ul li#enroll-now").addClass("selected");
	}
	
	//Breadcrumb Selected
	var currStep = $("body").attr("id");
	$(".breadcrumbs li").each(function(){
		var stepId = $(this).attr("id").toLowerCase();
		if(stepId.indexOf(currStep) > -1) {
			$(this).addClass("current");
			var curr = $(this);
			for(i = 0; i<=2; i++) {
				curr = curr.prev();
				curr.addClass("done");
			}
		}
	});
	if (currStep == "step5") {
		$(".breadcrumbs li").each(function(){
			$(this).addClass("done");
		});
	}
	if (currStep == "step3a") {
		$("#step1").addClass("done");
		$("#step2").addClass("done");		
		$("#step3").removeClass("current");		
	}
	
	//TABS
	$(".tabs a").click(function() {
		$(".tabs a").removeClass("selected");
		$(this).addClass("selected").blur();
		$(".internal-tab-content").addClass("hidethis");
		var currentTab = $(this).attr("sid");
		$("#" + currentTab).removeClass("hidethis");
	});
		
	$("a.map-it").click(function() {
		$("ul.tabs li#nav2 a").trigger("click");
	});
	
	//Button Click
	$("button[goto]").click(function(){
		location.href = $(this).attr("goto");
	});
	
	// Search Button
	$("#search-btn").click(function() {
		$("#search-results").show();
		//$(this).parents("fieldset.collapsable").addClass("collapsed");
	});
	
	//Table Alternate Rows
	
	$("table.alternate-rows tbody tr:even").addClass("odd");
	
	
	$("input:text[placeholder]").placeholder();
	
	//Table Row Selection
	$("table.grid").find("button.select-btn").enable();
	
	$("table.grid td button.select-btn").not("#plan-table").click(function() {
		$(this).parents("table.grid").find("button.select-btn").enable();
		$(this).disable().parents("tr").addClass("selected").siblings().removeClass("selected");
	});
	
	//Table row selection for plan table
	$("table.grid").find("button.select-btn-v").enable();			
	$("button.select-btn-v").click(function () {
		var eq = $(this).parents("td:eq(0)").prevAll().length;
		
		$(this).parents("table:eq(0)").find("tr").each(function () {
			$(this).find("td:eq(" + (eq-1) + ")").addClass("select").siblings().removeClass("select");
			$(this).find("td:eq(" + (eq-1) + ")").find("button.select-btn-v").attr("disabled","disabled");
			$(this).find("td:eq(" + (eq-1) + ")").siblings().find("button.select-btn-v").removeAttr("disabled","disabled");
		});
	});
	
	
	/*************************************************************
		Code shared by the "Earnings Summary" and "Marketing Rep Earnings" pages
	**/
		
		try {
			$("input.dateFld").datePicker({clickInput:true, createButton:false, startDate:'04/01/2010'});
		} catch (e) {  }
		// Mimics the "for" attribute for radio labels. i.e.: Clicking on a span with class "label" will click on the element before it (a radio button).
		$("span.label").click(function () { $(this).prev().click(); });
		
		// Makes the bottom half of teh enter payment popup dissabled. (It will be re-enabled after some user actions)
		$("#enter-payment-subfieldset input, #enter-payment-subfieldset textarea").attr("disabled","disabled");
		
		// lastClickedInvalidate is a global variable used to track which row to invalidate after confirmation.
		// This segment sets that variable when the invalidate button is clicked.
		$("table button.invalidate").click(function () {
			lastClickedInvalidate = $(this);
		});
		
		// Finds the correct row to "invalidate" through lastClickedInvalidate, changes the DOM accordingly, and shows the message
		$("#invalidate-yes").click(function () {
			if (lastClickedInvalidate)
			{
				lastClickedInvalidate.parents("td:eq(0)").removeClass("valid").addClass("invalid");
				writeMessage("Discount Code has been invalidated.");
			} else {
				// This should never happen, but- If this is thrown, the confirmation popup was prematurely opened.
				throw new Error("lastClickedInvalidate was null.");
			}
		});
		
		
		$("#member_invalidate-yes").click(function () {
			if (lastClickedInvalidate)
			{
				lastClickedInvalidate.parents("td:eq(0)").removeClass("valid").addClass("invalid");
				writeMessage("Member has been invalidated.");
			} else {
				// This should never happen, but- If this is thrown, the confirmation popup was prematurely opened.
				throw new Error("lastClickedInvalidate was null.");
			}
		});
		
	/*************************************************************
		Page-specific code
	**/
	switch ($("body").attr("id"))
		{
			case "earnings-summary":
				$("div.popup li.type-dependant select").change(writeAmounts);
				$("#popup-enter-payment input.dateFld:lt(2)").change(writeAmounts);
				// This will disable the "Enter Payment" button if the criteria is not met (And since it will not be met on page startup, it always disables the button)
				validateEnterPaymentButton();
				// When the targets are changed, the required elements are checked for input, and will enable the "Enter Payment" button if ready.
				$("div.popup li.type-dependant select, #popup-enter-payment input").change(validateEnterPaymentButton);
				
				/* This was in-page code */
				$("#page-wrapper select[name=region]").change(function () {
					var eq = this.selectedIndex;
					if (eq == 0)
						$("#discount-table tbody tr").show();
					else {
						/*	This next segment searches through the table and shows the director's segment, hiding the rest.
							See documentation at the top marked "Director Filtering" for explanation. */
						var region = $(this).val();
						var mode = "searching";
						$("#discount-table tbody tr").each(function () {
							switch (mode)
							{
								case "searching": if ($(this).children("td:eq(0)").text() == region) { $(this).show(); $(this).prev().show(); mode="showing"; } else { $(this).hide(); } break;
								case "showing": if ($(this).hasClass("header")) { $(this).hide(); mode="closing"; } else { $(this).show(); } break;
								case "closing": $(this).hide();
							}
						});
					}
				});
				break; // (end) of the "earnings-summary" segment
			
			
			case "marketing-rep-earnings":
				$("div.popup li.type-dependant select").change(writeAmounts_MR);
				$("#popup-marketing-rep-enter-payment input.dateFld:lt(2)").change(writeAmounts_MR);
				// This will disable the "Marketing Rep Enter Payment" button if the criteria is not met (It will not be met on page startup)
				validateEnterPaymentButton_MR();
				// When the targets are changed, the required elements are checked for input, and will enable the "Marketing Rep Enter Payment" button if ready.
				$("div.popup li.type-dependant select, #popup-marketing-rep-enter-payment input").change(validateEnterPaymentButton_MR);
				break; // (end) of the "marketing-rep-earnings" segment
			
			
			case "marketing-reps":
				// lastClickedMR is a global variable - set to hold onto the last clicked account while waiting for confirmation
				$("table.marketing-rep-table button.invalidate").click(function () {
					lastClickedMR = $(this);
				});
				
				$("#confirm-remove-marketing-rep-btn").click(function () {
					if (lastClickedMR)
					{
						lastClickedMR.parents("td:eq(0)").removeClass("active").addClass("inactive");
						writeMessage("Marketing Rep Account was disabled.");
					} else
						throw new Error("lastClickedMR was null.");
				});
				/* Sets the values of the popup form to match the existing values of the row clicked on. */
				$("a.edit").click(function () {
					var tr        = $(this).parents("tr:eq(0)");
					var director_id=''  
					var membertype=jQuery.trim(tr.attr('class')); 
					var editprofileId =jQuery.trim(tr.attr('profileId')); 
					
					//alert(profileId);
					  
					var name      = tr.children("td:eq(1)").html().split(" ");
					
					
					var firstName = name[0];
					var lastName  = name[1];
					var email     = tr.children("td:eq(2)").text();
					var phone     = tr.children("td:eq(3)").html();
					var region    = tr.children("td:eq(4)").html();
					
					//alert(region);
					
					
					 if(membertype=='director'){
 						 jQuery("#edit_marketing_director").attr("checked","checked") ;
						 jQuery(".show-if-rep").hide();
 						 //jQuery("#edit_director").hide();
						 jQuery("#dir_region_li").show();
						 jQuery("#rep_region_li").hide();
						 
						 var pri=tr.attr("pri");
						 
						 if(jQuery.trim(pri)==1){
							 jQuery("#edit_privileges").attr("checked","checked") ; 
						 }
 						 jQuery("#edit_privileges_div").show();
					 }else{
						 jQuery("#edit_marketing_rep").attr("checked","checked") ;
						 //jQuery("#edit_director").show();
						 jQuery("#dir_region_li").hide();
						 jQuery("#rep_region_li").show();
 						 var director_id=tr.attr("title"); 
 						 
						 var rep_region= tr.children("td:eq(4)").attr('region_title');
 						 jQuery("#edit_director_id   option[value="+director_id+"]").attr("selected","selected") ;
 						 jQuery("#edit_rep_region  option[value="+rep_region+"]").attr("selected","selected") ;
						 jQuery("#edit_privileges_div").hide();
   					 }
					  
					
					
					//var p = $("#popup-new-marketing-rep");
					
					var p         = $("#popup-edit-marketing-rep");
					p.find("input[name=profil_edit]").val(editprofileId);
					p.find("input[name=edit_first-name]").val(firstName);
					p.find("input[name=edit_last-name]").val(lastName);
					p.find("input[name=edit_phone]").val(phone);
					p.find("input[name=edit_region]").val(region);
					p.find("input[name=edit_email]").val(email);
					$("#popup-edit-marketing-rep").addClass("edit-mode");
					openPopup("popup-edit-marketing-rep");
					
					//$("#popup-new-marketing-rep").addClass("edit-mode");
					//openPopup("popup-new-marketing-rep");
					
				});
				$("#add-marketing-rep-btn").click(function () {
					$("#popup-new-marketing-rep").removeClass("edit-mode");
					openPopup("popup-new-marketing-rep");
				});
				$("#popup-new-marketing-rep input[name=type]").click(function () {
					var eq = $(this).prevAll("input").length;
					var dir = $(".show-if-rep");
					if (eq == 0)
						dir.fadeIn();
					else
						dir.fadeOut();
				});
				$("#director-filter").change(function () {
					if (this.selectedIndex == 0)
					{
						$("table.marketing-rep-table tbody tr").show();
					} else {
						/*	This next segment searches through the table and shows the director's segment, hiding the rest.
							See documentation at the top marked "Director Filtering" for explanation. */
						var dir = $(this).val();
						var mode = "searching";
						$("table.marketing-rep-table tbody tr").each(function () {
							switch (mode)
							{
								case "searching":
									if ($(this).children("td:eq(1)").html() == dir) { $(this).show(); mode="showing"; } else { $(this).hide(); } break;
								case "showing": if ($(this).hasClass("director")) { $(this).hide(); mode="closing"; } else { $(this).show(); } break;
								case "closing": $(this).hide();
							}
						});
					}
				});
				break; // (end) of the "marketing-reps" segment
		}
 
});

// Used for the "Enter Payments" popup to write a random set of amounts when the user enters enough information to do so.
function writeAmounts ()
{
	var slct = $("div.popup li.type-dependant select");
	var date1 = $("#popup-enter-payment input.dateFld:eq(0)");
	var date2 = $("#popup-enter-payment input.dateFld:eq(1)");
	var abler = $("#enter-payment-subfieldset input, #enter-payment-subfieldset textarea");
	if (slct[0].selectedIndex > 0 && date1.val() != "" && date2.val() != "")
	{
		$("#amount-earned-span").html("$"+rand(100,999)+"."+rand(10,99));
		$("#amount-paid-span").html("$"+rand(100,999)+"."+rand(10,99));
		abler.removeAttr("disabled");
	} else {
		abler.attr("disabled","disabled");
		$("#amount-earned-span").html("$XXX.XX");
		$("#amount-paid-span").html("$XXX.XX");
	}
}

// Used for the "Marketing Rep Enter Payments" popup to write a random set of amounts when the user enters enough information to do so.
function writeAmounts_MR ()
{
	var date1 = $("#popup-marketing-rep-enter-payment input.dateFld:eq(0)");
	var date2 = $("#popup-marketing-rep-enter-payment input.dateFld:eq(1)");
	var abler = $("#enter-payment-subfieldset input, #enter-payment-subfieldset textarea");
	if (date1.val() != "" && date2.val() != "")
	{
		$("#amount-earned-span").html("$"+rand(100,999)+"."+rand(10,99));
		$("#amount-paid-span").html("$"+rand(100,999)+"."+rand(10,99));
		abler.removeAttr("disabled");
	} else {
		abler.attr("disabled","disabled");
		$("#amount-earned-span").html("$XXX.XX");
		$("#amount-paid-span").html("$XXX.XX");
	}
}

// Finished the Enter Payment process by closing the popup, sending messaging, and stops the form from leaving the page.
function enterPayment ()
{
	writeMessage("Payment of $123.99 was added for discount code XYZ for marketing rep John Smith.");
	closePopup();
	return false;
}

function confirmInvalidate ()
{
	writeMessage("Discount Code XY3-HS34 was created for John Smith.");
	closePopup();
	return false;
}

// This funciton is called from the onsubmit attribute in the form from popup_new_discount
function addDiscountCode () {
	writeMessage("Discount Code XY3-HS34 was created for John Smith.");
	closePopup();
	return false;
}

// When the New Marketing Rep Popup is submited, this function is called. It currently just shows this message.
function addMarketingRep ()	{ writeMessage('Marketing Rep "New Guy" was added.'); closePopup(); return false; }

// Attempts to validate the "Enter Payment" button by checking if the required inputs are filled in.
// Depending on these checks, the button will either be enabled or disabled.
function validateEnterPaymentButton ()
{
	var good = true;
	
	if ($("div.popup li.type-dependant select").length > 0)
		if ($("div.popup li.type-dependant select")[0].selectedIndex == 0) { good = false; }
	
	 $("#popup-enter-payment input.reqdInput").each(function () { if ($(this).val() == "") { good = false; } });
	
	if (good)
		$("#enter-payment-button").removeAttr("disabled");
	else
		$("#enter-payment-button").attr("disabled","disabled");
}

// Attempts to validate the "Enter Payment" button by checking if the required inputs are filled in.
// Depending on these checks, the button will either be enabled or disabled.
function validateEnterPaymentButton_MR ()
{
	var good = true;
		
	 $("#popup-marketing-rep-enter-payment input.reqdInput").each(function () { if ($(this).val() == "") { good = false; } });
	
	if (good)
		$("#enter-payment-button").removeAttr("disabled");
	else
		$("#enter-payment-button").attr("disabled","disabled");
}

// Adds a message to the "message-dropzone"
function writeMessage (msg)	{ $("#message-dropzone").append('<div class="msg-acknowledge">' + msg + '</div>'); $("#message-dropzone").children(":last-child").slideDown(); }

// Returns a random integer between (and including) a and b.
function rand (a,b) { b = b || a; return Math.floor(Math.random() * (Math.abs(b-a) + 1)) + Math.min(a,b) - 1; }


(function($) {
$.fn.placeholder = function (text)
{
	var text = text || null;
	return $(this).each(function () {
		
		var value = (text) ? text : $(this).attr("placeholder");
		
		$(this).addClass("active-placeholder").val(value);
		
		$(this).focus(function () {
			if ($(this).val() == value)
				$(this).removeClass("active-placeholder").val("");
		});
		
		$(this).blur(function () {
			if ($(this).val() == "")
				$(this).addClass("active-placeholder").val(value);
		});
	});
}

})(jQuery);

