var companySelected = 0;
var productSelected = 0;
var reasonSelected = 0;
var consumerSelected = 0;
var hasEdited = 0; //this flags whether a user has edited the letter or not, at which point, we can no longer use the automated clicking
var allSelected = 0; //this flags whether all of the options have been selected and whether we can start editing
var nameClear = 0; //flags whether we've already cleared the name once so that once they type something it doesn't clear again

$(document).bind('keydown', 'return', function(){inputChecker();});

function inputChecker(){ //called by hotkey - checks each field and collapses if it has text in it
	var prodName = $("#left_col form fieldset ul#main_parameters li#select_product ul li input#product_name").val();
	var consumerName = $("#left_col form fieldset ul#main_parameters li#input_name ul li input#first_name").val();
	var altProduct = $("#left_col form fieldset ul#main_parameters input#altProduct").val();
	var altReason = $("#left_col form fieldset ul#main_parameters input#altReason").val();
	var updatedAlready = 0;
	
	if(prodName != '' && $("#left_col form fieldset ul#main_parameters li#select_product ul").css("display") != 'none'){
		updateProduct();
		updatedAlready = 1;
	}
	if(consumerName != 'First Name' && consumerName != 'First Name Last Name' && $("#left_col form fieldset ul#main_parameters li#input_name ul").css("display") != 'none'){
		updateConsumer();
		updatedAlready = 1;
	}
	
	if(altReason != ''){
		
		if($("#left_col form fieldset ul#main_parameters li.#reason_select ul.secondaryInfo").css("display") != 'none'){
			$("#left_col form fieldset ul#main_parameters li.#reason_select ul.secondaryInfo").hide("slide");
		}
		
		if(updatedAlready == 0){
			updateLetter();
		}
	}
	
	if(altProduct != ''){
		
		if($("#left_col form fieldset ul#main_parameters li.#action_select ul.secondaryInfo").css("display") != 'none'){
			$("#left_col form fieldset ul#main_parameters li.#action_select ul.secondaryInfo").hide("slide");
		}
		
		if(updatedAlready == 0){
			updateLetter();
		}
	}
}

function sendLetter(){
	if($("#right_col #letter_output #freeEdit p#startEditing").css("display")== "none"){
		saveEdits();
	};

	var letterContent = $("#right_col #letter_output #letter_content").html();
	var sendType = $("#left_col form#mainform li#send_options span.code_holder").html();
	$("#left_col form#mainform input#send_type").val(sendType);
	$("#left_col form#mainform input#letter_text").val(letterContent);
	$("#left_col form#mainform").submit();
}

function editLetter(){
	var letterContent = $("#right_col #letter_output #letter_content").html();
	$("#right_col #letter_output #freeEdit p#startEditing").css("display","none");
	$("#right_col #letter_output #freeEdit p#stopEditing").css("display","block");
	letterContent = letterContent.replace(/\<\/p\>/gi,'\n\n');
	letterContent = letterContent.replace(/\<p\>/gi,'');
	
	letterContent = letterContent.replace(/\<br\/\>/gi,'\n'); //if they've inserted their own below, we need it to work again
	letterContent = letterContent.replace(/\<br\>/gi,'\n'); //if they've inserted their own below, we need it to work again
	
	var editBox = "<textarea id=\"letterEdit\">" + letterContent + "</textarea>";
	$("#right_col #letter_output #letter_content").html(editBox);
	hasEdited = 1; //set the flag that the user has edited
}

function saveEdits(){
	var letterContent_final = $("#right_col #letter_output #letter_content textarea#letterEdit").val();
	$("#right_col #letter_output #freeEdit p#startEditing").css("display","block");
	$("#right_col #letter_output #freeEdit p#stopEditing").css("display","none");
	letterContent_final = '<p>' + letterContent_final; //we need to seed it with that first paragraph that was stripped out.
	letterContent_final = letterContent_final.replace(/\n\n$/i,""); //strip off any trailing newlines that would occur with repeated edit/save cycles
	letterContent_final = letterContent_final.replace(/\n\n/gi,'</p><p>');
	letterContent_final = letterContent_final.replace(/\r\n\r\n/gi,'</p><p>'); //account for IE newlines
	
	//Now that we've done the double ones, we need to account for if they insert their own singles,etc...
	letterContent_final = letterContent_final.replace(/\r\n/gi,'<br/>'); //account for IE newlines
	letterContent_final = letterContent_final.replace(/\n/gi,'<br/>');
	
	$("#right_col #letter_output #letter_content").html(letterContent_final);
}

function editAlert(){
	alert("You have already edited this lettter manually and can no longer use the selections in the left bar (except the delivery method selecter). To make changes, please use the 'Edit Letter' button again.");
}

function updateLetter(){
	
	if(hasEdited == 1){
		check_sendEditEnable();
		return;
	}
	
	allSelected = 0;
	
	var letterContent = '';
	var action_code = $("#left_col form fieldset ul#main_parameters li#action_select.completed span.code_holder").html();
	
	if(companySelected == 1){
		var comName = $("#left_col form fieldset ul#main_parameters li#select_company span#company_name").html();
		letterContent = '<p>' + comName + '</p><p>To Whom It May Concern,</p>';
		allSelected++;
	}
	
	if(productSelected == 1){
		var productName = $("#left_col form fieldset ul#main_parameters li#select_product span#product_name_span").html();
		if(action_code == 3){ //if they bought it this time
			letterContent += '<p>After buying you product, ' + productName + ' I am writing to inform you that I will not buy it again';
		}else{ //if we don't know whether they bought it or not
			letterContent += '<p>I am writing to inform you that I did not buy your product, ' + productName + ', today';
		}
		allSelected++;
	}
	
	var reason_code = $("#left_col form fieldset ul#main_parameters li#reason_select.completed span.code_holder").html()
	
	if(productSelected == 1 && reason_code > 0){ //if the product is already selected and they have also selected a reason_code
	
		if(reason_code == 1){
			letterContent += ' because it had too much packaging.';
		}else if(reason_code == 2){
			letterContent += ' because it contains chemicals harmful to humans and the environment.';
		}else if(reason_code == 3){
			letterContent += ' because it is packaged with non-recyclable materials.';
		}else if(reason_code == 4){
			letterContent += ' because your company is, on the whole, not environmentally friendly.';
		}else if(reason_code == 5){
			letterContent += ' because it is a wasteful and unnecessary product.';
		}else{
			var other_reason = $("#left_col form fieldset ul#main_parameters li#reason_select.completed ul.secondaryInfo li input#altReason").val()
			letterContent += ' because ' + other_reason + '.';
		}
		allSelected++;
		$("input#reason_code").val(reason_code);
	
	}else if(reasonSelected != 1 && productSelected != 1){
		letterContent += 'Building your letter...';
	}
	
	//action_code defined above
	var alt_product = $("#left_col form fieldset ul#main_parameters li#action_select.completed ul li input#altProduct").val();
	$("input#competitor").val(action_code); //set the input value for the db
	
	if(action_code == 1){
		letterContent += '</p><p>Instead, I chose to purchase your competitor\'s product, ' + alt_product + '.';
		allSelected++;
	}else if(action_code == 2){
		letterContent += '</p><p>Instead, I chose to do without your product.';
		allSelected++;
	}else if(action_code == 3){
		letterContent += '</p><p>';
		allSelected++;
	}
	
	var buy_again = $("#left_col form fieldset ul#main_parameters li#buyagain_select.completed span.code_holder").html();
	$("input#buy_again").val(buy_again); //set the input value for the db
	if(buy_again == 1){
		letterContent += ' I have no plans to resume buying your product.</p>';
		allSelected++;
	}else if(buy_again == 2){
		letterContent += ' I will reconsider buying your product when you address my concerns.</p>';
		allSelected++;
	}
	
	var consumerName = $("#left_col form fieldset ul#main_parameters li#input_name ul li input#consumer_name").val();

	if(consumerSelected == 1){
		letterContent += '<p>Thank you for your time,</p><p>' + consumerName + '</p>';
		allSelected++;
	}
	
	check_sendEditEnable();

	$("#right_col #letter_output #letter_content").html(letterContent);
}

function check_sendEditEnable(){
	if(allSelected > 5){ //if everything is selected, show the submit and edit buttons
		if($("#left_col form fieldset ul#main_parameters li#send_options.completed span.code_holder").html() > 0){ //check that a send method is specified
			$("#right_col #letter_output div#submit_letter").css("display","block");
		}
		
		$("#right_col #letter_output div#freeEdit p#startEditing").css("display","block");
	}
}

function updateCompany(comName,comID){

	if(hasEdited == 1){
		editAlert();
		event.preventDefault();				
		return;
	}
	
	$("#left_col form fieldset ul#main_parameters li#select_company span#company_name").html(comName);
	$("#left_col form fieldset ul#main_parameters li#select_company span#company_name").css("color","#272");
	$("#left_col form fieldset ul#main_parameters li#select_company").addClass("completed");
	$("#left_col form fieldset ul#main_parameters li#select_company").css("border-top","4px solid #272");
	$("#left_col form fieldset ul#main_parameters li#select_company input#company_id").val(comID);
	tb_remove();
	companySelected = 1;
	updateLetter();
}

function updateProduct(){

	if(hasEdited == 1){
		editAlert();
		event.preventDefault();
		return;
	}
	
	var prodName = $("#left_col form fieldset ul#main_parameters li#select_product ul li input#product_name").val();
	if(prodName != ''){ //make sure it's not empty since that will make it all disappear
		$("#left_col form fieldset ul#main_parameters li#select_product span#product_name_span").html(prodName);
		$("#left_col form fieldset ul#main_parameters li#select_product span#product_name_span").css("color","#272");
		$("#left_col form fieldset ul#main_parameters li#select_product").addClass("completed");
		$("#left_col form fieldset ul#main_parameters li#select_product ul").hide("slide");
		productSelected = 1;
		updateLetter();
	}
}

function updateConsumer(){
	
	if(hasEdited == 1){
		editAlert();
		event.preventDefault();
		return;
	}
	var firstName = $("#left_col form fieldset ul#main_parameters li#input_name ul li input#first_name").val();
	var lastName = $("#left_col form fieldset ul#main_parameters li#input_name ul li input#last_name").val();
	
	var consumerName = firstName + " " + lastName;
	$("#left_col form fieldset ul#main_parameters li#input_name ul li input#consumer_name").val(consumerName);
	
	$("#left_col form fieldset ul#main_parameters li#input_name span#name_span").html(consumerName);
	$("#left_col form fieldset ul#main_parameters li#input_name span#name_span").css("color","#272");
	$("#left_col form fieldset ul#main_parameters li#input_name").addClass("completed");
	$("#left_col form fieldset ul#main_parameters li#input_name ul").hide("slide");
	consumerSelected = 1;
	updateLetter();
}

function companyUrl(){

	var company_name = " ";
	var company_id;

	/** Extracts the users query from the URL. Code from Google Custom Search (Thanks!)	**/ 
	var url = '' + window.location;
	var queryStart = url.indexOf('?') + 1;
	if (queryStart > 0) {
		var parts = url.substr(queryStart).split('&');
		for (var i = 0; i < parts.length; i++) {
			if (parts[i].substr(0, 12) == 'company_name') {
				company_name = unescape(parts[i].split('=')[1].replace(/\+/g, ' '));
			}
			if (parts[i].substr(0, 10) == 'company_id') {
				company_id = unescape(parts[i].split('=')[1].replace(/\+/g, ' '));
			}
		}
	}
	
	if(company_name.length > 1){
		updateCompany(company_name,company_id);
	}
}

$(document).ready(function(){

	$("#loading").toggle();
	$("#left_col").fadeIn("slow");
	
	companyUrl(); /* run this to see if we already have a company specified */
	
	$("#left_col form fieldset ul#main_parameters li#select_product a#product_toggle").click(function(event){
		$("#left_col form fieldset ul#main_parameters li#select_product ul").toggle("slide");	
		event.preventDefault();
	});
	
	$("#left_col form fieldset ul#main_parameters li#input_name a#name_toggle").click(function(event){
		$("#left_col form fieldset ul#main_parameters li#input_name ul").toggle("slide");	
		event.preventDefault();
	});

	$("#left_col form fieldset ul#main_parameters li.selection_expanders a.button_link span.change_text").click(function(event){
		$(this).parent().parent().children("ul.selection_list").toggle("slide");
		event.preventDefault();
	});

	$("#left_col form fieldset ul#main_parameters li.selection_expanders ul li.clickShowSecondary a").click(function(event){
		$(this).parent().parent().parent().children("ul.secondaryInfo:hidden").css("display","block");
		event.preventDefault();
	});

	$("#left_col form fieldset ul#main_parameters li.selection_expanders ul li.clickHideSecondary a").click(function(event){
		$(this).parent().parent().parent().children("ul.secondaryInfo").css("display","none");
		event.preventDefault();
	});			
	
	$("#left_col form fieldset ul#main_parameters li.selection_expanders ul.secondaryInfo li a").click(function(event){
		$(this).parent().parent().css("display","none");
	});
	
	$("input.name").focus(function () { // this function clears the name fields on the first click in them
		if($(this).val() == "First Name" || $(this).val() == "Last Name"){
			$(this).val('');
		}
    });
	
	$("input#altReason").autocomplete("autocomplete_reasons.pl");
	
	$("#left_col form fieldset ul#main_parameters li.selection_expanders ul li a.selectLink").click(function(event){ /* This controls basic click functions */
		
		var editContinue = 0;
		
		if($(this).children("span.send_code").html() == 1 || $(this).children("span.send_code").html() == 2 || $(this).children("span.send_code").html() == 3){
			editContinue = 1;
		}
		
		if(hasEdited == 1 && editContinue != 1){
			editAlert();
			event.preventDefault();
			return;
		}
	
		var code = $(this).children('span.text').html();
		var code_insert = $(this).children('span.code').html(); /*code insert is for the actual numbered code */
		$(this).parent().parent().parent().children("a.button_link").children("span.change_text").html(code);
		$(this).parent().parent().parent().children("a.button_link").children("span.code_holder").html(code_insert);
		$(this).parent().parent().parent().addClass("completed");
		$(this).parent().parent().toggle("slide");
		event.preventDefault();
		updateLetter();
	});
	
 });