var i;
var j;
var k;
var temp;
var row = 1;
var choice = 1;
var winner_highlighted = 0;
var row_current_criteria_title_default = '';
var new_comment_counter = 0;
var duplicated = 0;
var duplicatedfrom = ''; // used to identify the unique ID of the original decision another is being duplicated from
var duplicatedfrom_original = ''; // used to identify the unique ID of the original decision another is being duplicated from
var decision_uniqueid;
var maindiv; // the HTML of the main DIV in the middle of the screen
var choice_values, choice_descriptions;

// jquery plugin to remove a column in a table
$.fn.removeCol = function(col) {
  // Make sure col has value
  if (!col) { col = 1; }
  $('tr td:nth-child('+col+'), tr th:nth-child('+col+')', this).remove();
  return this;
};

function activate_center_div(divname) {
	$('#maindiv').hide();
	$('#faqdiv').hide();
	$('#searchdiv').hide();
	$('#' + divname).show();
}

function reset() {
	activate_center_div('maindiv');
  for (i=1;i<row;i++) {
    if ($("#row_td_criteria_title_" + i).html()!='') {
      $("#row_importance_" + i).val(1);
      $("#current_" + i).css({width:0});
      for (j=1;j<choice;j++) {
        $("#choice_slider_" + i + "_" + j).slider('option', 'value', 0);
        $("#choice_slider_handle_" + i + "_" + j).css('background', 'url(http://doocide.com/images/slider_thumb_0.png) no-repeat');
      }
    }
  }
  unhighlightWinner();
}

function duplicate() {
  activate_center_div('maindiv');
  $("#link_duplicate").hide();
  $("#command_save").removeClass('red');
  $("#comments").html('');
  $("#command_save").html('Save New');
  $("#command_save").show('blind', {}, 1500);
  $("#command_save").effect('highlight', {}, 1500);
  $("#decision_title").html('My New Decision');
  $("#decision_title").show('blind', {}, 1500);
  $("#decision_title").effect('highlight', {}, 1500);
  $("#decision_description").html('(click title to edit)');
  $("#decision_description").show('blind', {}, 1500);
  $("#decision_description").effect('highlight', {}, 1500);
  $("#top_userpic").html('');
  $("#msg_saveinfo").html('');
  $("#top_username").html('<a href="#null">@Guest</a>');
  $("#div_decision_private").css('display', 'inline');
  document_changed_needs_saved();
//  duplicatedfrom = decision_uniqueid;
  decision_uniqueid = '';
  duplicated = 1;
}

function search() {
	location.replace('search?q=' + Url.encode($('#search_query').val()));
}

function delete_decision() {
//	if (!decision_uniqueid)
//		return false;
	if (confirm('This will permanently delete this decision. Would you like to continue?'))
		location.replace('http://doocide.com/new?delete=' + decision_uniqueid);
}

function replaceSpecialChars(text) {
  text = text.replace("'", "{apt}"); // apostrophe
  text = text.replace("&", "{and}");
  text = text.replace("|", "{vrb}"); // vertical bar
  text = text.replace("+", "{pls}"); // plus sign
  return text;
}

function save() {
  activate_center_div('maindiv');
  var decision_saved_temp;
  var decision_table = '|||||' + $("#choice_title_0").html() + '|';
  if (duplicated) {
  	$("#decision_title").html('Copy of ' + $("#decision_title").html());
  }
  for (j=1;j<choice;j++) {
    if ($("#choice_title_" + j).html()) {
      var temp_choice_title = replaceSpecialChars($("#choice_title_" + j).html());
      decision_table = decision_table +
        				 '|' + temp_choice_title + '|';
    }
  }
  decision_table = decision_table + "\n";
  for (i=1;i<row;i++) {
    if ($("#row_td_criteria_title_" + i).html()!='') {
      var temp_row_td_criteria_title = replaceSpecialChars($("#row_td_criteria_title_" + i).html());
      decision_table = decision_table +
      				   '|' + temp_row_td_criteria_title + '|' +
      				   '|' + $("#row_importance_" + i).val() + '||0|';
      for (j=1;j<choice;j++) {
        if ($("#choice_title_" + j).html()) {
          var temp_slider_description = replaceSpecialChars($("#slider_description_" + i + "_" + j).val());
          decision_table = decision_table +
        				     '|' + $("#choice_slider_" + i + "_" + j).slider('option', 'value') +
                     '&' + Url.encode(temp_slider_description) +
                     '|';
        }
      }
      decision_table = decision_table + "\n";
    }
  }
  $.ajax({
    type: "POST",
    url: "save.php",
    data: "decision_uniqueid=" + decision_uniqueid + "&decision_title=" + $("#decision_title").html() + "&decision_private=" + $("#decision_private").is(':checked') + "&duplicated=" + duplicated + "&duplicatedfrom=" + duplicatedfrom + "&duplicatedfrom_original=" + duplicatedfrom_original + "&decision_table=" + Url.encode(decision_table),
    success: function(msg) {
      var arr = [];
      arr = msg.toString().split('|');
      $("#msg_saveinfo").html(arr[1]);
      if (!decision_uniqueid) {
        decision_uniqueid = arr[0];
        $("#div_comments").css('display', 'block');
        $("#div_comments").effect('highlight', {}, 1500);
        decision_update_top_info();
        $("#no_saved_decision").hide();
      }
			if ($("#decision_saved_" + decision_uniqueid).length) {
        $("#locked_decision_saved_" + decision_uniqueid).css('display', (($("#decision_private").is(':checked'))?'inline':'none'));
			}
			if ($("#decision_saved_" + decision_uniqueid).html()) {
				decision_saved_temp = $("#decision_saved_div_" + decision_uniqueid).html();
				$("#decision_saved_div_" + decision_uniqueid).remove();
			} else {
				decision_saved_temp = '<div id="locked_decision_saved_' + decision_uniqueid + '" style="display:' + (($("#decision_private").is(':checked'))?'inline':'none') + '">' +
                                '<img style="margin-left:0px;margin-right:5px;" src="images/lock_icon_small.png" align="absmiddle" />' +
                              '</div> ' +
                              '<a id="decision_saved_' + decision_uniqueid + '" class="grey" href="http://doocide.com/' + decision_uniqueid + '">' + $("#decision_title").html() + '</a>';
			}
  		$("#saved_decisions").prepend('<div id="decision_saved_div_' + decision_uniqueid + '" class="links_decisions">' + decision_saved_temp + '</div>');
      $('#command_save').removeClass('red');
      $('#command_save').html('Save');
      $("#div_decision_private").css('display', 'inline');
    }
  });
  duplicated = 0;
}

function slider_change_background(slider_ui_handle) {
  $("#msg_saveinfo").html(slider_ui_handle);
   slider_ui_handle.css('background', 'http://doocide.com/images/thumbs.up.gif');
}

function unhighlightWinner() {
  if (!winner_highlighted) {
    return true;
  }
  var active_choice_col_counter = 0;
  i = 1;
  do {
    if ($("#choice_title_" + i).html()) {
      active_choice_col_counter++;
    }
    $("#choice_score_" + i).removeClass('choice_winner_score_highlight');
    $("#choice_td_" + i).removeClass('choice_winner_title_highlight');
    $("#choice_score_" + i).html('Choice #' + active_choice_col_counter + ' <a href="#null" onclick="$(\'#html_decision_table\').removeCol(' + active_choice_col_counter + ' + 4);unhighlightWinner();"><span class="choice_td_button_remove">X</span></a>');
    for (j=1;j<row;j++) {
      $("#selectbox_td_" + j + "_" + i).removeClass('choice_winner_selectbox_highlight');
    }
  } while (i++<choice);
  $('#link_showhidewinner').html('<img src="images/button_showwinner.gif" border="0" align="absmiddle" />');
  winner_highlighted = 0;
}

function choice_current_set_functions(choice_current) {
  $("#choice_title_" + choice_current).click(function() {
    $("#choice_title_" + choice_current).hide();
    $("#choice_title_input_" + choice_current).val($("#choice_title_" + choice_current).html());
    $("#choice_title_rename_" + choice_current).show();
    $("#choice_title_input_" + choice_current).focus().select();
    });
  $("#choice_title_input_" + choice_current).blur(function() {
    choice_title_change(choice_current);
    });
  $("#choice_title_input_" + choice_current).keydown(function(event) {
    var charCode = (event.which) ? event.which : event.keyCode;
    if (charCode == 13)  {
      choice_title_change(choice_current);
     }
    });
}

function choice_title_change(choice_current) {
  $("#choice_title_rename_" + choice_current).hide();
  if ($("#choice_title_input_" + choice_current).val()!='') {
    $("#choice_title_" + choice_current).html($("#choice_title_input_" + choice_current).val().replace(/\||<\/?[^>]+(>|$)/g, ""));
  } else {
    $("#choice_title_" + choice_current).html('Edit title');
  }
  $("#choice_title_" + choice_current).show();
  document_changed_needs_saved();
}

function set_factor_importance(factor, value) {
	$("#current_" + factor).css({width:18*value});
	$("#row_importance_" + factor).val(value);
}

function row_append(importance_value) {
	var row_current = row;
	var row_has_specific_title = 1;
	if (row_current_criteria_title_default=='') {
		row_current_criteria_title_default = 'Edit decision factor #' + row_current;
		row_has_specific_title = 0;
	}
	$("#html_decision_table").append(
		'<tr class="row_tr" id="row_tr_' + row_current + '" style="display:none;" onmouseover="$(\'#row_tr_' + row_current + '\').addClass(\'row_tr_mouseover\');$(\'#row_td_criteria_' + row_current + '\').addClass(\'row_td_criteria_mouseover\');$(\'#row_td_criteria_title_' + row_current + '\').addClass(\'row_td_criteria_title_mouseover\');" onmouseout="$(\'#row_tr_' + row_current + '\').removeClass(\'row_tr_mouseover\');$(\'#row_td_criteria_' + row_current + '\').removeClass(\'row_td_criteria_mouseover\');$(\'#row_td_criteria_title_' + row_current + '\').removeClass(\'row_td_criteria_title_mouseover\');">' +
			'<td class="row_td_criteria_remove" id="row_td_criteria_remove_' + row_current + '">' +
				'<span class="row_tr_button_remove">X</span>' +
			'</td>' +
			'<td class="row_td_criteria ' + ((row_has_specific_title==1)?'row_td_criteria_title_renamed':'row_td_criteria_title') + '" id="row_td_criteria_' + row_current + '">' +
				'<div id="row_td_criteria_title_' + row_current + '">' + row_current_criteria_title_default + '</div>' +
				'<div id="row_td_criteria_rename_' + row_current + '" style="display:none;">' +
					'<input class="row_td_criteria_title_input" id="row_td_criteria_input_' + row_current + '" type="text" style="width:100%;" value="" />' +
				'</div>' +
			'</td>' +
			'<td id="td_row_td_importance_' + row_current + '" width="10">' +
				'<ul id="row_td_importance_' + row_current + '" class="row_td_importance" style="width:90px;">' +
					'<li id="current_' + row_current + '" class="current" style="width:0px;"></li>' +
					'<li id="li-r1-unit_' + row_current + '"><a id="r1-unit_' + row_current + '" class="r1-unit" href="#null"></a></li>' +
					'<li id="li-r2-unit_' + row_current + '"><a id="r2-unit_' + row_current + '" class="r2-unit" href="#null"></a></li>' +
					'<li id="li-r3-unit_' + row_current + '"><a id="r3-unit_' + row_current + '" class="r3-unit" href="#null"></a></li>' +
					'<li id="li-r4-unit_' + row_current + '"><a id="r4-unit_' + row_current + '" class="r4-unit" href="#null"></a></li>' +
					'<li id="li-r5-unit_' + row_current + '"><a id="r5-unit_' + row_current + '" class="r5-unit" href="#null"></a></li>' +
				'</ul>' +
				'<input type="hidden" id="row_importance_' + row_current + '" value="1" />' +
			'</td>' +
			'<td class="choice_td">' +
				'<span class="basechoice_rows_text">base choice</span>' +
			'</td>' +
		'</tr>'
		);
	if (importance_value>0) {
		$("#current_" + row_current).css({width:18*importance_value});
		$("#row_importance_" + row_current).val(importance_value);
	}
	$("#r1-unit_" + row_current).click(function() {
		$("#current_" + row_current).css({width:18});
		$("#row_importance_" + row_current).val(1);
		unhighlightWinner();
		document_changed_needs_saved();
		});
//    $("#td_row_td_importance_" + row_current).simpletip({
//                content: 'Set factor\'s importance<br />(1 = least important ; 5 = most important)',
//                position: ["100", "-5"],
//                });
	$("#r2-unit_" + row_current).click(function() {
		$("#current_" + row_current).css({width:36});
		$("#row_importance_" + row_current).val(2);
		unhighlightWinner();
		document_changed_needs_saved();
		});
	$("#r3-unit_" + row_current).click(function() {
		$("#current_" + row_current).css({width:54});
		$("#row_importance_" + row_current).val(3);
		unhighlightWinner();
		document_changed_needs_saved();
		});
	$("#r4-unit_" + row_current).click(function() {
		$("#current_" + row_current).css({width:72});
		$("#row_importance_" + row_current).val(4);
		unhighlightWinner();
		document_changed_needs_saved();
		});
	$("#r5-unit_" + row_current).click(function() {
		$("#current_" + row_current).css({width:90});
		$("#row_importance_" + row_current).val(5);
		unhighlightWinner();
		document_changed_needs_saved();
		});
	$("#row_td_criteria_" + row_current).click(function() {
		$("#row_td_criteria_title_" + row_current).hide();
		$("#row_td_criteria_input_" + row_current).val($("#row_td_criteria_title_" + row_current).html());
		$("#row_td_criteria_rename_" + row_current).show();
		$("#row_td_criteria_input_" + row_current).focus().select();
		});
	$("#row_td_criteria_input_" + row_current).blur(function() {
		row_input_change();
		});
	$("#row_td_criteria_input_" + row_current).keydown(function(event) {
		var charCode = (event.which) ? event.which : event.keyCode;
		if (charCode == 13)  {
			row_input_change();
		}
	});

	function row_input_change() {
		$("#row_td_criteria_rename_" + row_current).hide();
		if ($("#row_td_criteria_input_" + row_current).val()!='') {
			$("#row_td_criteria_title_" + row_current).html($("#row_td_criteria_input_" + row_current).val().replace(/\||<\/?[^>]+(>|$)/g, ""));
			$("#row_td_criteria_" + row_current).addClass("row_td_criteria_title_renamed");
		} else {
			$("#row_td_criteria_title_" + row_current).html(row_current_criteria_title_default);
			$("#row_td_criteria_" + row_current).removeClass("row_td_criteria_title_renamed");
		}
		$("#row_td_criteria_title_" + row_current).show();
		document_changed_needs_saved();
	}
	$("#row_td_criteria_remove_" + row_current).click(function() {
		$("#row_td_criteria_" + row_current).effect("highlight", {}, 500);
		$("#row_tr_" + row_current).fadeOut();
		$("#row_importance_" + row_current).val(0);
		i = 1;
		do {
			$("#selectbox_" + i + "_" + row_current).val(0);
		} while (i++<choice);
		$("#row_td_criteria_title_" + row_current).html("");
		document_changed_needs_saved();
		});
	$("#row_tr_" + row_current).fadeIn("slow");
	$("#row_td_criteria_" + row_current).effect("highlight", {}, 500);
	row_current_criteria_title_default = '';
	bulk_add_selectboxes(row_current, 0);
	row++;
//	unhighlightWinner();
}

function choice_append(base, title, choice_value, choice_description) {
	var choice_current = choice;
	if (!title) {
		title = 'Edit Choice Title';
	}
	$("#header_choices_top").append(
		'<td style="padding:0px;vertical-align:top;">' +
			'<img src="http://doocide.com/images/clear.gif?2" style="border:0px;margin:0px;width:150px;height:0px;" />' +
		'</td>'
		);
	$("#header_choices").append(
		'<td class="choice_td_header" id="choice_score_' + choice_current + '" nowrap="nowrap" onmouseover="$(\'#choice_td_' + choice_current + '\').addClass(\'choice_selectbox_mouseover\');" onmouseout="$(\'#choice_td_' + choice_current + '\').removeClass(\'choice_selectbox_mouseover\');">' +
			'Choice #' + choice_current +
			' <a href="#null" onclick="document_changed_needs_saved();$(\'#html_decision_table\').removeCol(choice_current+4);"><span class="choice_td_button_remove">X</span></a>' +
		'</td>'
		);
	$("#header_choices_titles").append(
		'<td class="choice_td" id="choice_td_' + choice_current + '" onmouseover="$(\'#choice_td_' + choice_current + '\').addClass(\'choice_selectbox_mouseover\');" onmouseout="$(\'#choice_td_' + choice_current + '\').removeClass(\'choice_selectbox_mouseover\');">' +
			'<div class="choice_title" id="choice_title_' + choice_current + '">' + title + '</div>' +
			'<div id="choice_title_rename_' + choice_current + '" style="display:none;">' +
				'<input class="choice_title_input" id="choice_title_input_' + choice_current + '" type="text" style="width:100%;" value="" />' +
			'</div>' +
		'</td>'
		);
	$("#choice_td_" + choice_current).simpletip({
							content: '<div id="choice_description_' + choice_current + '">' +
                         'Click to edit choice description.' +
                       '</div>' +
                       '',
							position: ["50", "25"]
							});
	choice_current_set_functions(choice_current);
	$("#choice_td_" + choice_current).fadeIn("slow");
	$("#choice_td_" + choice_current).effect("highlight", {}, 500);
	bulk_add_selectboxes(0, choice_current);
	choice++;
//	unhighlightWinner();
//    window.scroll(9999999999, 0);
}

function bulk_add_selectboxes(rowsb, choicesb) {
	var slider_id;
	if (rowsb==0) {
		i = 1;
		do {
			slider_id = i + '_' + choicesb;
			bulk_add_selectboxes_append(slider_id, i, choicesb);
		} while (i++<row);
	}
	if (choicesb==0) {
		i = 1;
		do {
			if ($("#choice_title_" + i).html()) {
				slider_id = rowsb + '_' + i;
				bulk_add_selectboxes_append(slider_id, rowsb, i);
			}
		} while (i++<choice);
	}
}

function bulk_add_selectboxes_append(slider_id, rowsb, choicesb) {
	$("#row_tr_" + rowsb).append(
			'<td class="choice_td" id="selectbox_td_' + slider_id + '" onmouseover="$(\'#handle_slider_description_' + slider_id + '\').show();$(\'#choice_td_' + choicesb + '\').addClass(\'choice_selectbox_mouseover\');$(\'#slider_description_' + slider_id + '\').addClass(\'choice_description_input_mouseover\');" onmouseout="$(\'#handle_slider_description_' + slider_id + '\').hide();$(\'#choice_td_' + choicesb + '\').removeClass(\'choice_selectbox_mouseover\');$(\'#slider_description_' + slider_id + '\').removeClass(\'choice_description_input_mouseover\');" style="vertical-align:top;">' +
				'<div id="handle_slider_description_' + slider_id + '" style="display:none;float:right;text-align:right;margin-right:0px;margin-top:2px;">' +
					'<a href="#null" onclick="$(\'#div_slider_description_' + slider_id + '\').show();$(\'#slider_description_' + slider_id + '\').focus();">+</a>' +
				'</div>' +
				'<div class="choice_slider" id="choice_slider_' + slider_id + '" style="margin-top:5px;"><a href="#null" id="choice_slider_handle_' + slider_id + '" class="ui-slider-handle"><div style="font-size:0px;display:none;">' + slider_id + '</div></a>' +
				'</div>' +
				'<div id="div_slider_description_' + slider_id + '" style="display:none;margin-top:3px;">' +
					'<input class="choice_description_input" id="slider_description_' + slider_id + '" type="text" onblur="if (!$(this).val()) $(\'#div_slider_description_' + slider_id + '\').hide();document_changed_needs_saved();unhighlightWinner();" />' +
				'</div>' +
			'</td>');
	$("#choice_slider_" + slider_id).slider({
															value: 0, step: 1, min: -6, max: 6,
															slide: function(event, ui) {
																slider_id = $(ui.handle).html().replace(/<\/?[^>]+(>|$)/g, "");
																$("#choice_slider_handle_" + slider_id).css('background', 'url(http://doocide.com/images/slider_thumb_' + ui.value + '.png) no-repeat');
																document_changed_needs_saved();
																unhighlightWinner();
															}
														});
	if (choice_values && choice_values[choicesb+2]) {
		$("#choice_slider_" + slider_id).slider('option', 'value', choice_values[choicesb+2]);
		$("#choice_slider_handle_" + slider_id).css('background', 'url(http://doocide.com/images/slider_thumb_' + choice_values[choicesb+2] + '.png) no-repeat');
	}
	if (choice_descriptions && choice_descriptions[choicesb+2]) {
		$("#slider_description_" + slider_id).val(choice_descriptions[choicesb+2]);
		$("#div_slider_description_" + slider_id).show();
	}
}

// redirect
function javascript_replaceurl(url) {
  var version = parseInt(navigator.appVersion)
  if (version>=4 && window.location.replace)
    window.location.replace(url);
  else
    window.location.href = url;
}
