// GoodSpark Javascript

/* -----------------------------------------------------
	The initHeader function takes care of the show/hide
	functionality of the main charity
	menu and sign in form on the header on all pages.
-------------------------------------------------------- */
function initHeader() {	
	$("#signin-form").hide();

	if($.browser.msie){
		// fading in and out is fugly in IE, so just show/hide
		 $("#find-charity").toggle(
			function() { $("#charity-menu").show(); },
			function() { $("#charity-menu").hide(); }
		 );
		$("#signin-link").toggle(
			function() { $("#signin-form").show(); },
			function() { $("#signin-form").hide(); }
		);
	} else {
		$("#find-charity").toggle(
			function() { $("#charity-menu").fadeIn("normal"); },
			function() { $("#charity-menu").fadeOut("normal"); }
		);
		$("#signin-link").toggle(
			function() { $("#signin-form").fadeIn("normal"); },
			function() { 
				$("#signin-form").fadeOut("normal"); 
				$("#signin-error").hide();
				// clear username and password
				$("#signin-username").val("");
				$("#signin-password").val("");
			}
		);
	}


	// have close icons work the toggling fun too
	$("#charity-menu-close").click( function() {
		$("#find-charity").click();
	});
	
	$("#signin-cancel").click( function() {
		$("#signin-link").click();
	});

	
	$("#signin-submit").click(function() {

	    //reset the error fields
	    $("#signin-error-username").hide();
	    $("#signin-error-password").hide();

	    var errors = false;

	    var username = document.getElementById('username');
	    if (username && username.value == '') {
	        $("#signin-error-username").show();
	        errors = true;
	    }

	    var password = document.getElementById('password');
	    if (password && password.value == '') {
	        $("#signin-error-password").show();
	        errors = true;
	    }

	    return (!errors);
	});

}

/* -----------------------------------------------------
	initMiniMenu is used for the small, in-page menus,
	such as the mini-charity menu, the mini donate menu.
-------------------------------------------------------- */
function initMiniMenu() {
	$(".mini-menu .mini-menu-selected").css("cursor", "pointer");

	if($.browser.msie){
		// fading in and out is fugly in IE, so just show/hide
		$(".mini-menu .mini-menu-selected").toggle(
			function() { $(".mini-menu ul li").show(); },
			function() { $(".mini-menu ul li").not(".mini-menu-selected").hide(); }
		); 
	} else {
		$(".mini-menu .mini-menu-selected").toggle(
			function() { $(".mini-menu ul li").fadeIn(); },
			function() { $(".mini-menu ul li").not(".mini-menu-selected").fadeOut(); }
		);
	}
}

/* -----------------------------------------------------
	The initMoreLinks is for use anywhere you want to 
	have the "More..." links appear that expose more
	of the content. Note that the set-up should be 
	something like this:
	
	<p>blah blah blah <a class="more-link"></p>
	<p class="more-content">blah blah blah</p>
-------------------------------------------------------- */
function initMoreLinks() {
    $(".more-link").css("cursor", "pointer");
    $(".more-prog-link").css("cursor", "pointer");

    $(".more-content").hide();
	
	if($.browser.msie) {
		$(".more-link").toggle(
			function() { 
				$(this).html("Less...");
				$(this).parent().next(".more-content").show();
			},
			function() { 
				$(this).html("More &raquo;"); 
				$(this).parent().next(".more-content").hide();
			}
		);
		
		$(".more-prog-link").toggle(
		    function() {
		        $(this).html("Less...");
		        $(this).next(".more-content").show();
            },
			function() {
			    $(this).html("More &raquo;");
			    $(this).next(".more-content").hide();
			}
		);
    } else {
        $(".more-link").toggle(
			function() {
			    $(this).html("Less...");
			    $(this).parent().next(".more-content").fadeIn();
			},
			function() {
			    $(this).html("More &raquo;");
			    $(this).parent().next(".more-content").fadeOut();
			}
		);
		
		$(".more-prog-link").toggle(
			function() { 
				$(this).html("Less..."); 
				$(this).next(".more-content").fadeIn();
			},
			function() { 
				$(this).html("More &raquo;"); 
				$(this).next(".more-content").fadeOut();
			}
		);
	}

}

/* -----------------------------------------------------
	The initDonationSelect functions selectes a select
	box on the Basket and My Account pages. 
-------------------------------------------------------- */
function initOneTimeDonationSelect() {
	$("#one-time-donation").show();
	$("#one-time-error").hide();
	
	$("#one-time-amount").focus();

	// add a focus even to the input to show error state
	$("#one-time-amount").change(function(event) {
	    //$("#one-time-error").fadeIn();
	    $.post("Donate/ChangeDnationAmount/index.html",
	    //post values
	        {
	        amount: $("#one-time-amount").val(),
	        duration: 0,
	        clickId: "one-time"
	    },
	        function(data) {
	            alert('lol');
	            alert(data);
	            alert(data.Amount);
	            $("#one-time-donation").val(data.Amount);
	        },
	        "json");
	});

}
function initDonationSelect(isOneTime) {
	// add hover states to divs to simulate select box
	$("#donation-select div").hover(
		function() {
			$(this).addClass("mmHover");
		},
		function() {
			$(this).removeClass("mmHover");
		}
	);

		if (isOneTime) {
		    $("#one-time-donation").fadeIn();
		    $("#one-time-amount").focus();
		}
		else {
		    $("#one-time-donation").hide();
		}
	    
	$("#one-time-error").hide();
	
	// attach click action to divs
	$("#donation-select div").not("#selected-donation").click(function() {
	    //send an ajax update
	    $.post("Donate/ChangeDonationAmount/index.html",
	        //post values
	        { 
	            amount: $(this).attr("amount"),
	            duration: $(this).attr("duration"),
	            clickId: $(this).attr("id")
	        },
	        //success function
	        function(data) {
	            $("#selected-donation").text(data.DisplayString);
	            // fade in/out one time donation area
	            if (data.ClickId == "one-time") {
	                $("#one-time-donation").fadeIn();
	                $("#one-time-amount").val(50);
	                $("#one-time-amount").focus();
	            } else {
	                $("#one-time-donation").fadeOut();
	            }
	        }, 
	        //method to retrieve data
	        'json');

	    // close menu
	    $(".mini-menu .mini-menu-selected").click();
	});

	// add a focus even to the input to show error state
	$("#one-time-amount").change(function(event) {
	    //$("#one-time-error").fadeIn();
	    $.post("Donate/ChangeDonationAmount/index.html",
	    //post values
	        {
	        amount: $("#one-time-amount").val(),
	        duration: 0,
	        clickId: "one-time"
	        },
	        function(data) {
	            $("#one-time-amount").val(data.Amount);
	        },
	        "json");
	});
}

function initDonationCurrentSelect() {
	// add hover states to divs to simulate select box
	$("#donation-current div").hover(
		function() {
			$(this).addClass("mmHover");
		},
		function() {
			$(this).removeClass("mmHover");
		}
	);
	
	// attach click action to divs
	$("#donation-current div").not("#selected-donation").click( function() {
	    $.post("Account/ChangeDonationAmount/index.html",
		    //post values
	        {
	        amount: $(this).attr("amount"),
	        duration: $(this).attr("duration"),
	        clickId: $(this).attr("id")
	        },
		    //success function
	        function(data) {
	            $("#selected-donation").text(data.DisplayString);
                $("#one-time-donation").fadeOut();
	        },
		//method to retrieve data
	        'json');
		// close menu
		$(".mini-menu .mini-menu-selected").click();
	});
}


/* -----------------------------------------------------
	The following functions are for the Spread the
	Word page to add more folks to spam
-------------------------------------------------------- */
var numFriends = 1;
function removeFriend(friendID) {
	var friend = "#friend-"+friendID;
	$(friend).fadeOut("normal", function() { $(this).remove(); } );
}
function createFriend() {
	// increment the number of friends
	numFriends++;
	
	// create form elements for the friend's name and email
	var friendName = document.createElement("input");
	var friendNameLabel = document.createElement("label");
	friendName.setAttribute("type","text");
	friendName.setAttribute("id","friendname-" + numFriends);
	friendName.setAttribute("name", "friendname-" + numFriends);
	friendName.className = "full-length";
	friendNameLabel.setAttribute("for", "friendname-" + numFriends);
	friendNameLabel.innerHTML = "Other Friend's Name";

	var friendEmail = document.createElement("input");
	var friendEmailLabel = document.createElement("label");
	friendEmail.setAttribute("type","text");
	friendEmail.setAttribute("id","friendemail-" + numFriends);
	friendEmail.setAttribute("name", "friendemail-" + numFriends);
	friendEmail.className = "full-length";
	friendEmailLabel.setAttribute("for", "friendemail-" + numFriends);
	friendEmailLabel.innerHTML = "Other Friend's Email";

	// assistive text
	var nameAssText = document.createElement("p");
	nameAssText.className = "form-asstext";
	nameAssText.innerHTML = "e.g. Robert Frost";
	
	var emailAssText = document.createElement("p");
	emailAssText.className = "form-asstext";
	emailAssText.innerHTML = "e.g. you@domain.com";

	// build structure
	var nameDiv = document.createElement("div");
	nameDiv.appendChild(friendNameLabel);
	nameDiv.appendChild(friendName);
	var nameRow = document.createElement("div");
	nameRow.className = "form-row";
	nameRow.appendChild(nameDiv);
	nameRow.appendChild(nameAssText);

	var emailDiv = document.createElement("div");
	emailDiv.appendChild(friendEmailLabel);
	emailDiv.appendChild(friendEmail);
	var emailRow = document.createElement("div");
	emailRow.className = "form-row";
	emailRow.appendChild(emailDiv);
	emailRow.appendChild(emailAssText);

	// add remove button
	var removeLink = document.createElement("a");
	removeLink.setAttribute("title","Do not send a message to this friend");
	removeLink.className = "remove-button";
	removeLink.setAttribute("href","javascript:removeFriend("+numFriends+");");

	// create fieldset element to wrap everything
	var fieldset = document.createElement("fieldset");
	
	fieldset.appendChild(removeLink);
	fieldset.appendChild(nameRow);
	fieldset.appendChild(emailRow);
	
	fieldset.className = "invisible";
	fieldset.setAttribute("id","friend-" + numFriends);
	
	// TO DO: add error checking ability to form fields
	return fieldset;
}
function initAddFriendButton() {
	$("#add-friend-button").click(function() {
		$("#add-friend").before(createFriend());
		var newFriend = "#friend-" + numFriends;
		$(newFriend).fadeIn("normal");
		var newFriendName = "#friendname-" + numFriends;
		$(newFriendName).focus();
	});
}


/* -----------------------------------------------------
	The following functions are for the Gifts page
	to add more folks to send moola too.
-------------------------------------------------------- */
var numGifts = 1;
function removeGift(giftID) {
	var gift = "#gift-"+giftID;
	$(gift).fadeOut("normal", function() { $(this).remove(); } );
}
function createGift() {
	// increment the number of gifts
	numGifts++;
	
	// create form elements for the gift's name and email
	var giftAmount = document.createElement("input");
	var giftAmountLabel = document.createElement("label");
	giftAmount.setAttribute("type","text");
	giftAmount.setAttribute("id","amount-" + numGifts);
	giftAmount.setAttribute("name", "amount-" + numGifts);
	giftAmount.className = "full-length";
	giftAmountLabel.setAttribute("for", "amount-" + numGifts);
	giftAmountLabel.innerHTML = "Other Recipient's Amount";

	var giftAmountPreLabel = document.createElement("div");
	var giftAmountPreLabelSpan = document.createElement("span");
	giftAmountPreLabel.className = "prepend-label";
	giftAmountPreLabelSpan.innerHTML = "$";
	giftAmountPreLabel.appendChild(giftAmountPreLabelSpan);
	giftAmountPreLabel.appendChild(giftAmount);

	var giftName = document.createElement("input");
	var giftNameLabel = document.createElement("label");
	giftName.setAttribute("type","text");
	giftName.setAttribute("id","name-" + numGifts);
	giftName.setAttribute("name", "name-" + numGifts);
	giftName.className = "full-length";
	giftNameLabel.setAttribute("for", "name-" + numGifts);
	giftNameLabel.innerHTML = "Other Recipient's Name";

	var giftEmail = document.createElement("input");
	var giftEmailLabel = document.createElement("label");
	giftEmail.setAttribute("type","text");
	giftEmail.setAttribute("id","email-" + numGifts);
	giftEmail.setAttribute("name", "email-" + numGifts);
	giftEmail.className = "full-length";
	giftEmailLabel.setAttribute("for", "email-" + numGifts);
	giftEmailLabel.innerHTML = "Other Recipient's Email";

	var giftMessage = document.createElement("textarea");
	var giftMessageLabel = document.createElement("label");
	giftMessage.setAttribute("id","message-" + numGifts);
	giftMessage.setAttribute("name", "message-" + numGifts);
	giftMessage.setAttribute("rows", "5");
	giftMessage.setAttribute("cols", "10");
	giftMessage.className = "full-length";
	giftMessageLabel.setAttribute("for", "message-" + numGifts);
	giftMessageLabel.innerHTML = "Other Recipient's Message";
	

	// assistive text
	var amountAssText = document.createElement("p");
	amountAssText.className = "form-asstext";
	amountAssText.innerHTML = "min $25";
	
	var emailAssText = document.createElement("p");
	emailAssText.className = "form-asstext";
	emailAssText.innerHTML = "e.g. you@domain.com";

	var messageAssText = document.createElement("p");
	messageAssText.className = "form-asstext";
	messageAssText.innerHTML = "This is optional";

	// build structure
	var amountDiv = document.createElement("div");
	amountDiv.appendChild(giftAmountLabel);
	amountDiv.appendChild(giftAmountPreLabel);
	var amountRow = document.createElement("div");
	amountRow.className = "form-row";
	amountRow.appendChild(amountDiv);
	amountRow.appendChild(amountAssText);

	var nameDiv = document.createElement("div");
	nameDiv.appendChild(giftNameLabel);
	nameDiv.appendChild(giftName);
	var nameRow = document.createElement("div");
	nameRow.className = "form-row";
	nameRow.appendChild(nameDiv);

	var emailDiv = document.createElement("div");
	emailDiv.appendChild(giftEmailLabel);
	emailDiv.appendChild(giftEmail);
	var emailRow = document.createElement("div");
	emailRow.className = "form-row";
	emailRow.appendChild(emailDiv);
	emailRow.appendChild(emailAssText);

	var messageDiv = document.createElement("div");
	messageDiv.appendChild(giftMessageLabel);
	messageDiv.appendChild(giftMessage);
	var messageRow = document.createElement("div");
	messageRow.className = "form-row";
	messageRow.appendChild(messageDiv);
	messageRow.appendChild(messageAssText);

	// add remove button
	var removeLink = document.createElement("a");
	removeLink.setAttribute("title","Do not send a gift to this friend");
	removeLink.className = "remove-button";
	removeLink.setAttribute("href","javascript:removeGift("+numGifts+");");

	// create fieldset element to wrap everything
	var fieldset = document.createElement("fieldset");
	
	fieldset.appendChild(removeLink);
	fieldset.appendChild(amountRow);
	fieldset.appendChild(nameRow);
	fieldset.appendChild(emailRow);
	fieldset.appendChild(messageRow);
	
	fieldset.className = "top-dotted-line invisible";
	fieldset.setAttribute("id","gift-" + numGifts);
	
	// TO DO: add error checking ability to form fields
	return fieldset;
}
function initAddGiftButton() {
	$("#amount-1").focus();
	$("#add-gift-button").click(function() {
		$("#add-gift").before(createGift());
		var newGift = "#gift-" + numGifts;
		$(newGift).fadeIn("normal");
		var newGiftAmount = "#amount-" + numGifts;
		$(newGiftAmount).focus();
	});
}



/* -----------------------------------------------------
	The following functions add and remove charities
	from the my account page.
-------------------------------------------------------- */
var numCharities = 2;
function removeCharity(charityID) {
	var charity = "#charity-"+charityID;
	if ($(charity).hasClass("existing-charity")) {
        var orgId = 
	    $.post("Account/RemoveDonationFromCurrentDonation/index.html",
                { organizationId: charityID },
                function(data) {
                    // grey out
                    $(charity).addClass("removed-item");

                    // replace slider with "re-add" charity
                    $(charity).find(".item-remove").css("visibility", "hidden");
                    $(charity).find(".charity-slider").attr("charitystatus", "0");
                    $(charity).find(".item-slider").fadeOut("normal",
		                    function() {
		                        $(this).after("<div class='span-13 item-slider right-dotted-line last re-add-link'>Removed from your donation distribution. <a href='javascript:reAddCharity(" + charityID + ")'>Undo Remove</a></div>");
		                        setSlidersEqual();
		                    });

                    //setup the new allocations
                    jQuery.each(data.CharityStatus, function() {
                        //console.log("Charity: " + this.CharityId + " - Alloc: " + this.Allocation);
                        $("#charity" + this.CharityId).slider('moveTo', this.Allocation, 0, true);
                    });
                    //updateChart();
                },
                "json");
		//$(charity).find(".item-slider").replaceWith("<div class='span-13 item-slider right-dotted-line last'>Removed from your donation distribution. <a href='javascript:reAddCharity("+charityID+")'>Undo Remove</a></div>");
		//$(charity).find(".item-slider").after("<div class='span-13 item-slider right-dotted-line last re-add-link'>Removed from your donation distribution. <a href='javascript:reAddCharity(" + charityID + ")'>Undo Remove</a></div>");
	} else {
		$(charity).fadeOut("normal", function() { $(this).remove(); } );
	}
}
function reAddCharity (charityID) {
    var charity = "#charity-" + charityID;

    $.post("Account/AddDonationToCurrentDonationJSON/index.html",
                { organizationId: charityID },
                function(data) {
                    $(charity).removeClass("removed-item");
                    $(charity).find(".item-remove").css("visibility", "visible");
                    $(charity).find(".item-slider").fadeIn("normal");
                    $(charity).find(".charity-slider").attr("charitystatus", "1");
                    $(charity).find(".re-add-link").remove();
                    setSlidersEqual();

                    //setup the new allocations
                    jQuery.each(data.CharityStatus, function() {
                        //console.log("Charity: " + this.CharityId + " - Alloc: " + this.Allocation);
                        $("#charity" + this.CharityId).slider('moveTo', this.Allocation, 0, true);
                    });
                    //updateChart();
                },
                "json");
}


function addCharity() {
	// increment the number of charities
	numCharities ++;

	// remove button
	var buttonDiv = document.createElement("div");
	var button = document.createElement("a");
	button.setAttribute("href","javascript:removeCharity("+numCharities+");");
	button.setAttribute("title","Remove this Charity");
	button.className = "remove-button";
	buttonDiv.className = "span-2 item-remove";
	buttonDiv.appendChild(button);

	/*
	// image
	var imageDiv = document.createElement("div");
	var image = document.createElement("img");
	image.setAttribute("src","images/kids.jpg");
	imageDiv.className = "span-5 item-photo";
	imageDiv.appendChild(image);
	
	// name
	var nameDiv = document.createElement("div");
	nameDiv.className = "span-7 item-name";
	nameDiv.innerHTML = "New Charity Name";
	*/
	
	// select
	var selectDiv = document.createElement("div");
	selectDiv.className = "span-12 item-select";
	var selectWidget = document.createElement("select");
	var option1 = document.createElement("option");
	var option2 = document.createElement("option");
	var option3 = document.createElement("option");
	var option4 = document.createElement("option");
	option1.innerHTML = "Select a Charity";
	option2.innerHTML = "Charity X";
	option3.innerHTML = "Charity Y";
	option4.innerHTML = "Charity Z";
	selectWidget.appendChild(option1);
	selectWidget.appendChild(option2);
	selectWidget.appendChild(option3);
	selectWidget.appendChild(option4);
	selectDiv.appendChild(selectWidget);
	
	// slider
	var sliderDiv = document.createElement("div");
	var sliderWrap = document.createElement("div");
	var sliderHand = document.createElement("div");
	sliderHand.className = "ui-slider-handle";
	sliderWrap.setAttribute("id","slider-"+numCharities);
	sliderDiv.className = "span-13 item-slider right-dotted-line last";
	sliderWrap.appendChild(sliderHand);
	sliderDiv.appendChild(sliderWrap);

	// container
	var container = document.createElement("div");
	container.className = "span-27 added-item bottom-dotted-line invisible last";
	container.setAttribute("id","charity-"+numCharities);
	container.appendChild(buttonDiv);
	container.appendChild(selectDiv);
	container.appendChild(sliderDiv);

	// send it back
	return container;
}

function initAddCharityButton() {
	$("#add-charity-button").click( function() {
		$("#add-charity").before(addCharity());

		// init slider
		var newSlider = "#slider-" + numCharities;
		$(newSlider).slider({
			min: 0,
			max: 100,
			startValue: 0,
			stop: alertSliderValue
		});
		initSlider(numCharities);
		
		// fade in
		var newCharity = "#charity-"+numCharities;
		$(newCharity).fadeIn();
	});
}


function donationRemoveDonation(orgId) {
    //ajax-tastic!
    $.post("Donate/RemoveDonationFromCart/index.html",
            { organizationId: orgId },
            function(data) {
                $("#charity_" + data.OrganizationIdRemoved).fadeOut("normal", function() { $(this).remove(); });
                if (data.AllRemoved) {
                    $("#check-out").fadeOut("normal", function() { $(this).remove(); });
                    top.location.href = "Account/Login4757.html";
                }

                //setup the new allocations
                jQuery.each(data.CharityStatus, function() {
                    //console.log("Charity: " + this.CharityId + " - Alloc: " + this.Allocation);
                    $("#charity" + this.CharityId).slider('moveTo', this.Allocation, 0, true);
                });
                updateChart();
            },
            "json");
}


/* -----------------------------------------------------
	The following is for setting up the FAQs
-------------------------------------------------------- */
function initFAQs() {
	// make the dt's look clickable
	$(".faq-list dt").css("cursor","pointer");
	$(".faq-list dt").hover(
		function() {
			$(this).addClass("dtHover");
		},
		function() {
			$(this).removeClass("dtHover");
		}
	);							
	
	// hide the initial dd's
	$(".faq-list dd").css("display", "none");
	
	// add clicking toggle
	$(".faq-list dt").toggle( 
		function() {
			$(this).addClass("dtOpen");
			$(this).next("dd").slideDown();
		},
		function() {
			$(this).removeClass("dtOpen");
			$(this).next("dd").slideUp();
		}
	);
}

/* -----------------------------------------------
	Slider functions
   ----------------------------------------------- */

var alertSliderValue = function (e, slider) {
	//The value of the slider is passed as slider.value
	//alert("Your slider is at: " + slider.value);
}

function initSliders() {
	$(".item-slider").hover(
		function() {
			$(this).addClass("sliderHover");
		},
		function() {
			$(this).removeClass("sliderHover");
		}
	);
	
	
}
function initSlider(sid) {
	var slider = "#charity-" + sid;
	$(slider).find(".item-slider").hover(
		function() {
			$(this).addClass("sliderHover");
		},
		function() {
			$(this).removeClass("sliderHover");
		}
	);
}

/* --------------------------------------------
	Form validation fun - totally customized
	for the sign in page
----------------------------------------------- */

function createErrorMsg (msg) {
	var error = document.createElement("p");
	error.innerHTML = msg;
	error.className = "form-error";
	
	return error;
}
var errors = false;
function validate(fid) {
	if (errors) {
		// clear out error messages
		$(".error").removeClass("error");
		$(".standalone").remove();
		$("p.form-error").remove();
		errors = false;
	}
	
	var form = document.getElementById(fid);	
	if (form.email.value == "") {
		var msg = createErrorMsg("Please enter your username");
		errors = true;
		$("#email").parent().contents().wrapAll("<div class='error'></div>");
		$("#email").parent().prepend(msg);		
	}
	if (form.password.value == "") {
		var msg = createErrorMsg("Please enter your password.");
		errors = true;
		$("#password").parent().addClass("error");
		$("#password").parent().prepend(msg);		
	}
	
	if (!errors) {
		/*
		errors = true;
		var message = document.createElement("div");
		message.className = "standalone error";

		var msg = createErrorMsg("I'm sorry, the username or password does not match any of our records. Try again. Remember, your password is cAsE SenSItIve!");
		var formID = "#"+fid;
		message.appendChild(msg);

		$(formID).prepend(message);
		*/
	    form.submit();
	}
}

function submitForm(fid) {
    $(fid).submit();
}

function goToUrl(url) {
    document.location.href = url;
}