function AskWizardPage(page_id) {
	this.page_id = page_id;
	this.edit_mode = false;
};

AskWizardPage.prototype.setup = function(previous, next, confirm, options) {
	this.next = next;
	this.previous = previous;
	this.confirm = confirm;
	this.options = options || {};
	// Pass in a function to do the next or previous
	this.previous_button = $(this.page_id + "_previous");
	this.next_button = $(this.page_id + "_continue");
    this.return_button = $(this.page_id + "_return");
	this.grumpytext = $(this.page_id + "_grumpy");
	
    this.setupNavigation();
	this.ensureNotBlank();
	
}

AskWizardPage.prototype.enterEditMode = function() {
	if (this.return_button) {
		this.edit_mode = true;
        YD.setStyle(this.next_button, "display", "none");
        YD.setStyle(this.previous_button, "display", "none");
        YD.setStyle(this.return_button, "display", "");
	}
}

AskWizardPage.prototype.exitEditMode = function() {
	this.edit_mode = false;
    YD.setStyle(this.return_button, "display", "none");
    YD.setStyle(this.next_button, "display", "");
    YD.setStyle(this.previous_button, "display", "");
}

AskWizardPage.prototype.handlePreview = function(subject_mode) {
    var val = $(this.options['form']).value;
    var text = fluther.fakeSanitize(val, subject_mode);
    $(this.options['summary']).innerHTML = text;
    $(this.options['preview']).innerHTML = text; 
}

AskWizardPage.prototype.setupNavigation = function() {
	if (this.previous) {
		this.setupNavButton(this.previous_button, this.previous);
	}
    
	if (this.next) {
		this.setupNavButton(this.next_button, this.next, this.options['validateFunction']);
	}
    if (this.return_button) {
        this.setupNavButton(this.return_button, this.confirm, this.options['validateFunction']);
    }
};

AskWizardPage.prototype.setupNavButton = function(button_id, show_id, validate_func) {
	YE.on(button_id, "click", Bind(function(e) {
		YE.stopEvent(e);
        if (!validate_func || validate_func()) {
			if (this.edit_mode) {
				this.exitEditMode();
				this.flipPage(this.confirm);
			}
			else {
				// if we haven't got a validate function or we do and it passes
				this.flipPage(show_id);
			}
        }
	}, this));
};

AskWizardPage.prototype.flipPage = function(showPage) {
	YD.setStyle(this.page_id, "display", "none");
	YD.setStyle(showPage.page_id, "display", "");
	YD.setStyle(this.grumpytext, "display", "none");
	YD.setStyle(showPage.grumpytext, "display", "");
	
	var summary_field = $(this.options["summary"]);
	if (summary_field) {
		YD.removeClass(summary_field.parentNode, "active");
		YD.addClass(summary_field.parentNode, "postactive");
	}
	var show_summary_field = $(showPage.options["summary"]);
	if (show_summary_field) {
		YD.addClass(show_summary_field.parentNode, "active");
		YD.removeClass(show_summary_field.parentNode, "inactive");
		YD.removeClass(show_summary_field.parentNode, "preactive");
	}
	
	// Try and blend
	if (showPage.next) {
		var blend_field = $(showPage.next.options["summary"]);
		if (blend_field && !YD.hasClass(blend_field.parentNode, "postactive")) {
			YD.addClass(blend_field.parentNode, "preactive");
			YD.removeClass(blend_field.parentNode, "inactive");
		}
	}
	
	if (showPage.next == this && this.next) {
		// We're going backwards; Make sure that we revert blending
		var blend_field = $(this.next.options["summary"]);
		if (blend_field && YD.hasClass(blend_field.parentNode, "preactive")) {
			YD.addClass(blend_field.parentNode, "inactive");
			YD.removeClass(blend_field.parentNode, "preactive");
		}
	}
	var target_field = $(showPage.options['form']);
	if (target_field) {
		target_field.focus();
	}
	
	FlutherPageTrack(showPage.page_id);
}

AskWizardPage.prototype.ensureNotBlank = function() {
	if (this.options['form'] && this.next_button) {
		var text = $(this.options['form']).value;
		(text == "" ) ? this.next_button.disabled = true : this.next_button.disabled = false;
        if (this.return_button) {
            (text == "" ) ? this.return_button.disabled = true : this.return_button.disabled = false;
        }
	}
};

function toggle_grumpies(show_klass, hide_klass) {
	YD.getElementsByClassName(show_klass, '', 'content-container', function(e) {
		YD.setStyle(e, "display", "");
	});
	YD.getElementsByClassName(hide_klass, '', 'content-container', function(e) {
		YD.setStyle(e, "display", "none");
	});
}

function AskWizard() {
    
    this.motive_page = new AskWizardPage("ask_motive");
	this.subject_page = new AskWizardPage("ask_subject");
	this.details_page = new AskWizardPage("ask_details");
	this.topics_page = new AskWizardPage("ask_topics");
	this.confirm_page = new AskWizardPage("ask_confirm");
	
	this.motive_page.setup(null, this.subject_page, this.confirm_page, {'summary': 'motive_summary'});
    
	this.motive_page.setupNavButton("resolve_button", this.subject_page, function() {
		$('id_motive').value = "resolve";
		$("motive_summary").innerHTML = "Solve a Problem";
		toggle_grumpies("resolve", "discuss");
        return true;
	});
	this.motive_page.setupNavButton("discuss_button", this.subject_page, function() {
		$('id_motive').value = "discuss";
		$("motive_summary").innerHTML = "Start a Discussion";
		toggle_grumpies("discuss", "resolve");
        return true;
	});	
	this.motive_page.setupNavButton("meta_button", this.subject_page, function() {
		$('id_motive').value = "meta";
		$("motive_summary").innerHTML = "Talk about Fluther";
		toggle_grumpies("resolve", "discuss");
        return true;
	});	
	
	this.subject_page.setup(this.motive_page, this.details_page, this.confirm_page,
							{'form': 'id_subject',
							'summary': 'subject_summary',
							'preview': 'subject-preview'});
	this.subject_page.listener = new FormValueListener('id_subject', Bind(function () {
		this.ensureNotBlank();
		this.handlePreview(true);
    }, this.subject_page));
	
	this.details_page.setup(this.subject_page, this.topics_page, this.confirm_page,
							{'form': 'id_details',
							'summary': 'details_summary',	
							'preview': 'description-preview'});
    this.details_page.listener = new FormValueListener('id_details', Bind(function () {
		this.ensureNotBlank();
		this.handlePreview();
    }, this.details_page));
    
   
    var topicValidator = function() {
	    if (!ValidateCommas('id_topics')) {
			if ( confirm("We noticed that you didn't separate the words in your topics with commas.\n\n" +
				    'If "' + $('id_topics').value + '" is one topic, select cancel.\n\n' +
				    "Otherwise, select OK and add commas between your topics." ) ) {
				return false;
			}
	    }
        return true;
    };
	this.topics_page.setup(this.details_page, this.confirm_page, this.confirm_page,
							{'form': 'id_topics',
							'summary': 'topics_summary',	
							'preview': 'taglist-preview',
							'validateFunction': topicValidator});
	this.topics_page.listener = new FormValueListener('id_topics', Bind(function () {
		this.ensureNotBlank();
		var text = $(this.options['form']).value;
		$(this.options['summary']).innerHTML = text;
		$(this.options['preview']).innerHTML = text; 
    }, this.topics_page));
   
	this.confirm_page.setup(this.topics_page, null, null, {'summary': 'confirm_summary'});
	this.confirm_page.subject_page = this.subject_page;
	this.confirm_page.details_page = this.details_page;
	this.confirm_page.topics_page = this.topics_page;
	
	YE.on("subject-preview-container", "click", Bind(function(e){
        YE.stopEvent(e);
        gAsk.subject_page.enterEditMode();
        this.flipPage(this.subject_page);
    }, this.confirm_page));

    YE.on("details-preview-container", "click", Bind(function(e){
        YE.stopEvent(e);
        gAsk.details_page.enterEditMode();
        this.flipPage(this.details_page);
    }, this.confirm_page));
    
    YE.on("topics-preview-container", "click", Bind(function(e){
        YE.stopEvent(e);
        gAsk.topics_page.enterEditMode();
        this.flipPage(this.topics_page);
    }, this.confirm_page));
    
    YE.on("show_login_button", "click", function(e){
        YE.stopEvent(e);
		YD.setStyle("login-form", "display", "");
		YD.setStyle("join-teaser", "display", "");
		
		YD.setStyle("join-form", "display", "none");
		YD.setStyle("login-teaser", "display", "none");

		//clear out join data
		$("id_join_username").value = "";
		$("id_join_email").value = "";
    });
    
    YE.on("show_join_button", "click", function(e){
		YE.stopEvent(e);
		YD.setStyle("join-form", "display", "");
		YD.setStyle("login-teaser", "display", "");
		
		YD.setStyle("login-form", "display", "none");
		YD.setStyle("join-teaser", "display", "none");
		
		//clear out login data
		$("id_login_username").value = "";
		$("id_login_password").value = "";
    });
   
    YE.on("askwizard", "submit", function(e){
	YE.stopEvent(e);
	
	if (YD.getStyle("ask_confirm", "display") == "none") {
		return; // Hack for accidental keybaord submission
	}
	
	//Disable button and add spinner
	$('ask_confirm_submit').disabled = true;
	YD.setStyle('ask_submit_spinner', "display", "");
	
	
	//Clear old errors
	YD.getElementsByClassName('formerror', '', 'content-container', function(e) {
		e.parentNode.removeChild(e);
	});
	
	//Ask the question
	var formdata = YC.setForm("askwizard");
	YC.asyncRequest('POST', HOST_NAME + '/qask/', {
		failure: function(o) {
			$('ask_confirm_submit').disabled = false;
			YD.setStyle('ask_submit_spinner', "display", "none");
		},
		success: function(o) {
			var response = eval('(' + o.responseText + ')');
			if (response.errors) { //there were errors		    
				for (err_key in response.errors) {
					
					var errorDom = YD.create('div', {className:"formerror"}, [
						YD.create('img', {src: MEDIA_URL + "images/v2/alerticon_big.png", alt:"", className:"trans-png"}),
						//put the errortext in here
						response.errors[err_key]
						]);
						
					//Now display it in the proper place
					var error_div = $(err_key+"_error");
					error_div.appendChild(errorDom);
				}

			}
			else if (response.success) {
				window.location = response.success;
			}
			
			if (!response.banned) {
				$('ask_confirm_submit').disabled = false;
				YD.setStyle('ask_submit_spinner', "display", "none");
			}
	    }
	});		
    });

}


YE.onAvailable('DOMReady', function(){
	
    gAsk = new AskWizard();
    
    //Setup the autocompleter
    mynewac = new autocompleteManager('id_topics', 'tag-autocomplete', 'ask-indicator');
    
});
