YAHOO.util.Event.onDOMReady(function() {
	
	/* Regisitration Dialog */
	var handleRegSubmit = function() {
        var firstname = YAHOO.lang.trim(YAHOO.util.Dom.get("firstname").value);
        var lastname  = YAHOO.lang.trim(YAHOO.util.Dom.get("lastname").value);
        var address   = YAHOO.lang.trim(YAHOO.util.Dom.get("address").value);
		var city      = YAHOO.lang.trim(YAHOO.util.Dom.get("city").value);
		var state     = YAHOO.lang.trim(YAHOO.util.Dom.get("state").value);
		var zip       = YAHOO.lang.trim(YAHOO.util.Dom.get("zip").value);
		var phone     = YAHOO.lang.trim(YAHOO.util.Dom.get("phone").value);
		var email     = YAHOO.lang.trim(YAHOO.util.Dom.get("email").value);
		var crumb     = YAHOO.lang.trim(YAHOO.util.Dom.get("crumb2").value);
		
        
        if (firstname === '' || lastname === '') {
            alert('Please provide a valid name!');
            return false;
        } else if (address === '') {
            alert('Please provide a valid address!');
            return false;
        } else if (city === '') {
            alert('Please provide a valid city!');
            return false;
        } else if (state === '') {
            alert('Please provide a valid state!');
            return false;
        } else if (zip === '') {
            alert('Please provide a valid zip code!');
            return false;
        } else if (phone === '') {
            alert('Please provide a valid phone number!');
            return false;
        } else if (email === '') {
            alert('Please provide a valid email address!');
            return false;
        }
		
		var postData = "firstname=" + firstname + "&lastname=" + lastname + "&address=" + address +
						"&city=" + city + "&state=" + state + "&zip=" + zip + "&phone=" + phone + 
						"&email=" + email + "&crumb=" + crumb;
		var request = YAHOO.util.Connect.asyncRequest('POST', 'registration.php', submitRegCallbacks, postData);
	};
	var handleRegCancel = function() {
		this.cancel();
	};
	
	var submitRegCallbacks = {
        success : function (o) {
			YAHOO.bugsy.regdialog.hide(); //Hide the form
			alert('Thank you for registering!');
		},
		failure : function (o) {
			if(o.responseText !== undefined){
				alert("Registration failed: " + o.status);
			}
		}
    };

	// Instantiate the Dialog
	YAHOO.bugsy.regdialog = new YAHOO.widget.Dialog("registration_dialog", 
							{ width : "25em",
							  fixedcenter : true,
							  visible : false,
							  draggable : false,
                              close : true,
							  constraintoviewport : true,
							  modal : true,
							  buttons : [ { text:"Submit", handler:handleRegSubmit, isDefault:true },
								      { text:"Cancel", handler:handleRegCancel } ]
							});
	
	// Render the Dialog
	YAHOO.bugsy.regdialog.render();
	YAHOO.util.Event.addListener("doreg", "click", YAHOO.bugsy.regdialog.show, YAHOO.bugsy.regdialog, true);
	/* End Dialog */
	
	var ffEff, 
		crtFunFact = 1, //First is already there onload
		funFactNode = YAHOO.util.Dom.get("facts"),
		funFacts = [
		"In 2010, there will be more TVs in the U.S. than people.",
		"Old TVs contain up to 8 pounds of lead.",
		"Adjusting brightness settings on your TV saves up to 30% energy.",
		"22 million TVs will potentially become obsolete without converters.",
		"Plasma TVs use twice as much electricity as LCDs.",
		"Some TVs can suck up as much electricity as a refrigerator.",
		"A plasma TV will cost $200 more to operate than an LCD TV.",
		"The 275 million TVs in the U.S. use enough electricity to power all the homes in New York state for a year."
		];
		
	function swapFunFact() {
		if (crtFunFact < (funFacts.length - 1)) {
			crtFunFact = crtFunFact + 1;
		} else {
			//Start over
			crtFunFact = 0;
		}
		
		ffEff = new YAHOO.widget.Effects.Fade('facts', {seconds: 2});	
		ffEff.onEffectComplete.subscribe(function() {
	        //Update with new content
	        funFactNode.innerHTML = funFacts[crtFunFact];
	        //Show the new content
	        ffEff = new YAHOO.widget.Effects.Appear(funFactNode, { seconds: 0.5 });
			ffEff.animate();
		});
		
		ffEff.animate();
		
	}
		
	//Handles swapping of TV content
    var getShowCallbacks = {
        //Successful XHR response handler
        success : function (o) {
            var messages = [],
				tvContent = YAHOO.util.Dom.get('comments');

            //Use the JSON Utility to parse the data returned from the server
            try {
                messages = YAHOO.lang.JSON.parse(o.responseText);
				tvText   = messages.message;
            }
            catch (x) {
                alert("JSON Parse failed!");
                return;
            }
			
			//Fade out old content
		    var eff = new YAHOO.widget.Effects.Fade(tvContent, { seconds: 2 });
		    eff.onEffectComplete.subscribe(function() {
		        //Update with new content
		        tvContent.innerHTML = tvText;
		        //Show the new content
		        eff = new YAHOO.widget.Effects.Appear(tvContent, { seconds: 0.5 });
		    });
		
		    eff.animate();
        }
    };

    function getTVShowComments(){
		var r = Math.random();
    	var request = YAHOO.util.Connect.asyncRequest('GET', 'get_messages.php?t=' + r, getShowCallbacks);
    }
	
	//XHR response handler for submitTVShowComment
	var submitTVShowCallbacks = {
        success : function (o) {},
		failure : function (o) {
			if(o.responseText !== undefined){
				alert("Error: " + o.statusText);
			}
		}
    };

	function submitTVShowComment() {
		var commenterName = YAHOO.lang.trim(YAHOO.util.Dom.get("name").value);
		var userComment   = YAHOO.lang.trim(YAHOO.util.Dom.get("comment").value);
		var crumb         = YAHOO.lang.trim(YAHOO.util.Dom.get("crumb1").value);
		
		
		//Clear out the inputs
		YAHOO.util.Dom.get("name").value = '';
		YAHOO.util.Dom.get("comment").value = '';
		
		var postData = "name=" + commenterName + "&comment=" + userComment + "&crumb=" + crumb;
		var request = YAHOO.util.Connect.asyncRequest('POST', 'add_message.php', submitTVShowCallbacks, postData);
	}
	
	//Events and Event Handlers
	//Handle new show comment submission
	YAHOO.util.Event.addListener("frm_comment", "submit", function(e) {
		YAHOO.util.Event.preventDefault(e);
		
		var commenterName = YAHOO.lang.trim(YAHOO.bugsy.util.stripTags(YAHOO.util.Dom.get("name").value));
		var userComment   = YAHOO.lang.trim(YAHOO.bugsy.util.stripTags(YAHOO.util.Dom.get("comment").value));
		if (commenterName === '' || userComment === '') {
			alert('A valid name and comment must be provided!  Please try again.');
			return false;
		}
		
		var tvContent = YAHOO.util.Dom.get('comments');
		
		//Stop the current show comment fetcher
		clearInterval(tvSchedule);
		
		//Fade out old content
	    var eff = new YAHOO.widget.Effects.Fade(tvContent, { seconds: 2 });
	    eff.onEffectComplete.subscribe(function() {
	        //Update with new content
			var tvText = commenterName + ": " + userComment;
			
	        tvContent.innerHTML = tvText;
	        //Show the new content
	        eff = new YAHOO.widget.Effects.Appear(tvContent, { seconds: 0.5 });
	    });
	
	    eff.animate();
		
		submitTVShowComment(); //Save
		
		//Re-schedule the processing of TV messages
		tvSchedule = setInterval(function() {
							getTVShowComments();
						}, 6000);
	});
	
	//Handle hide and show of answer sections
	var answerLinks = YAHOO.util.Dom.getElementsByClassName("answer-link");
	YAHOO.util.Event.addListener(answerLinks, "click", function(e) {
		YAHOO.util.Event.preventDefault(e);
		
		//Find the local span and expand/contract
		var target, answerSpan, answerEff;
		target = YAHOO.util.Event.getTarget(e);
		answerSpan = YAHOO.util.Dom.getNextSibling(YAHOO.util.Dom.getNextSibling(target));
		
		if(YAHOO.util.Dom.getStyle(answerSpan, 'display') == 'block'){
			answerEff = new YAHOO.widget.Effects.BlindUp(answerSpan, {seconds: 0.5});
		} else{
			answerEff = new YAHOO.widget.Effects.Appear(answerSpan, {seconds: 0.5});
			YAHOO.util.Dom.setStyle(answerSpan, 'height', 'auto');
		}
		
		answerEff.animate();
	});
	
	//Schedule swapping of fun facts
	setInterval(function() {
		swapFunFact();
	}, 6000);
	
	//Schedule the processing of TV messages
	var tvSchedule = setInterval(function() {
						getTVShowComments();
					}, 6000);
});