/*
	Global Javascript For the NIE Template
	created 8.11.2011
	by Jay Pilgreen
	copyright River City Studio
*/


var GLOBAL = {};
var rotationTicker = 0;
var sponsors;
var activityTicker = 0;
var activities;

GLOBAL.init = function() {

	/*
	 * Welcome Fancybox Popups
	 */

	if(window.location.pathname === "/") {
		if($.cookie("returningVisitor") == null) {
			$.fancybox({
				type: "ajax",
				href: "/welcomePopup.html"
			});

			$.cookie("returningVisitor", true, { expires: 365, path: '/' });
		}
	}

	if(window.location.pathname === "/account/") {
		if($("#accountPopup").length > 0) {
			$.fancybox({
				type: "inline",
				content: $("#accountPopup"),
				maxWidth: "400px"
			});
		}
	}

	/*
	 * Styles and Effects
	 */
	
	// Add label helpers to all text inputs
	$(":text").labelify({
		labelledClass: "labelInside"
	}); 

	// Make the Right Rail the right height
	GLOBAL.resetRightRailHeight();
	$("#sponsors img").load(function() {
		GLOBAL.resetRightRailHeight();
	});
	

	/*
	 * Form Handlers and Click Events
	 */

	// Convenience Clicker for the School Selection Form
	$(".schoolListing").live("click", function() {
		$(this).find("input[name='school']").attr("checked", "checked");
	});


	// Password Login Swap
	$("#passwordLogin").focus(function() { 
		document.getElementById("passwordLogin").type = "password";
	});

	$("#passwordLogin").blur(function() { 
		if ($(this).val() == "" || $(this).val() == "Password/Class Password") {
			document.getElementById("passwordLogin").type = "text";
		};
	});


	// Slider Functionality
	jQuery(".slider").scrollable();


	// Chapter Swap function
	$(".chapterSwapper").click(function(evt) {
		evt.preventDefault();
		thisLink = $(this);

		$.ajax({
			type: "GET",
			url: thisLink.attr("href"),
			beforeSend: function() {
				$(".chapterSwapper").removeClass("active").parents(".box").removeClass("active");
				$("#chapter").animate({
					"opacity": 0
				}, 500, function() {
					$("#chapter").before($("<img class='chapterPreloader' src='/_img/preloader.gif' />"));	
				});
			},
			success: function(result) {
				$("#chapter").html($(result).find("#chapter").html());
				$(".chapterPreloader").remove();
				$("#chapter").stop(true).animate({
					"opacity": 1
				}, 500)
				$(".chapterSwapper").each( function() {
					if($(this).data("id") == thisLink.data("id")) {
						$(this).addClass("active");
						$(this).parents(".box").addClass("active");
					}
				})
			}
		});
	});


	/* 
	 * Dashboard Bar Functionality 
	 */

	// Check our content divs
	GLOBAL.toggleContentHightlight();

	$("#cmsHelper").click(function() {
		$(this).toggleClass("active");
		GLOBAL.toggleContentHightlight();
	});
	
	$(".managed").click(function() {
		var thisPiece = $(this);

		// set up our info to pass along
		dataObject = {
			id: thisPiece.data("id")
		}
		
		// this serializes the string for passing to the new page
		dataToPass = jQuery.param(dataObject, true);

		// Content Wrapper .. used to bring in the styles
		contentWrapper = thisPiece.data("wrapper");

		$.fancybox({
			href: "/admin/content/update.content.php",
			type: "ajax",
			showCloseButton: true,
			autoSize: false,
			width: 700,
			height: 475,
			centerOnScroll: true,
			transitionIn: "none",
			transitionOut: "none",
			overlayShow: false,
			orig: $(this),
			ajax: {
				type: "POST",
				data: dataToPass
			},
			afterShow: function() {
				$(".tinymce").tinymce({
					// Location of TinyMCE script
					script_url : '/tiny_mce/tiny_mce.js',
					body_id: contentWrapper,
					body_class: "editor",
					content_css : "/_css/white.layout.css",
					theme: "advanced",
					width: 700,
					height: 385,
					plugins: "paste, fullscreen, table",
					paste_auto_cleanup_on_paste: true,
					paste_remove_spans: true,
					paste_remove_styles: true,
					paste_text_sticky: true,
					theme_advanced_buttons1: "bold, italic, underline, separator, bullist, numlist, separator, link, unlink, separator, removeformat, pastetext, separator, formatselect, separator, code, fullscreen",
					theme_advanced_buttons2: "tablecontrols",
					theme_advanced_buttons3: ""
				});
			},
			afterClosed: function() {
				var opener = $(this.orig);

				$.ajax({
					url: window.location.href,
					beforeSend: function() {},
					success: function(result) {
						opener.html($(result).find(".managed[data-id='" + opener.data("id") + "']").html());
					}
				});
			}
		});
	});

	// And our listener for the content update form
	$("#updateForm").live("submit", function(evt) {
		evt.preventDefault();

		$.ajax({
			type: "POST",
			url: "/admin/content/update.content.php",
			data: $(this).serialize(),
			complete: function() {
				$.fancybox.close();
			}
		});
	});


	// Letter to the editor functions
	$(".tinymce").tinymce({
		script_url : '/tiny_mce/tiny_mce.js',
		theme: "advanced",
		width: 610,
		height: 385,
		plugins: "paste, spellchecker",
		paste_auto_cleanup_on_paste: true,
		paste_remove_spans: true,
		paste_remove_styles: true,
		paste_text_sticky: true,
		theme_advanced_buttons1: "bold, italic, underline, separator, bullist, numlist, separator, spellchecker",
		theme_advanced_buttons2: "",
		theme_advanced_buttons3: ""
	});

	jQuery("#schoolAutoInput").autocomplete({
		source: "/letters/getSchools.php",
		minLength: 3
	})

	// $("#letterForm").validator();


	/*
	 * Sponsor Rotation 
	 */

	sponsors = $("#sponsorLoop p");
	if(sponsors.length > 0) {
		GLOBAL.rotateSponsors();
	}

	// $("#sponsors").append("<p onclick='GLOBAL.rotateSponsors()'>Swap Em</p>");
	

	/*
	 * Activity Rotation
	 */

	activities = $(".resources .box .activityRotator");
	if(activities.length > 0) {
		GLOBAL.rotateActivities();
	}


	/*
	 * Add a Class Button
	 */

	$("#addClassButton").click( function(evt) {
		evt.preventDefault();
		GLOBAL.addClassInputs();
	});

}	// End Event Initialize function


	/*
	 * Convenience Functions outside of startup loop
	 */

	GLOBAL.toggleContentHightlight = function() {
		if($("#cmsHelper").hasClass("active")) {
			$(".managed").addClass("highlighted");
		} else {
			$(".managed").removeClass("highlighted");
		}
	}

	GLOBAL.resetRightRailHeight = function() {
		$("#rightRail").css({
			"min-height": ($("#content").height() + $("#sponsors").height() + 35)
		});
	}

	/*
	 * Sponsor rotation
	 */

	GLOBAL.rotateSponsors = function() {
		sponsors.hide();
		$(sponsors[rotationTicker]).show().position({
			my: "left",
			at: "right",
			of: "#sponsorLoop",
			collision: "none"
		});

		GLOBAL.switchSponsor();
	}

	GLOBAL.animateSponsorIn = function(to) {
		$(this).animate(to, 750, "easeOutCubic");
	}

	GLOBAL.animateSponsorOut = function(to) {
		$(this).animate(to, 500, "easeInBack");
	}

	GLOBAL.switchSponsor = function() {
		$(sponsors[rotationTicker]).position({
			my: "left",
			at: "left",
			of: "#sponsorLoop",
			collision: "none",
			using: GLOBAL.animateSponsorIn
		}).delay(2000).position({
			my: "right",
			at: "left",
			of: "#sponsorLoop",
			collision: "none",
			using: GLOBAL.animateSponsorOut
		});

		rotationTicker++;
		if(rotationTicker > sponsors.length - 1) {
			rotationTicker = 0;
		}

		window.setTimeout(GLOBAL.rotateSponsors, 3500);
	}

	/*
	 * Activity Rotation
	 */

	GLOBAL.rotateActivities = function() {
		activities.addClass("hidden", 250);
		$(activities[activityTicker]).removeClass("hidden", 250);

		activityTicker++;
		if(activityTicker > activities.length - 1) {
			activityTicker = 0;
		}

		window.setTimeout(GLOBAL.rotateActivities, 2500);
	}

	/*
	 * Class Addition
	 */

	GLOBAL.addClassInputs = function() {
		classInputs = $("#classInputBlocks div:first").clone();
		classInputs.find("input").each( function() {
			$(this).val("");
		});

		classInputs.hide().appendTo("#classInputBlocks").fadeIn(250);
		GLOBAL.resetRightRailHeight();
	}

