var choiceType = 'radio';
// background title choice border image
var sampleStyles = [
  ['#E7F6F8', '#FA6B3E', '#3A555C', '#65C3E0', null],
  ['#FFFFFF', '#008DC2', '#3A555C', '#CCCCCC', null],
  ['#F8E7F7', '#A87AFA', '#3A555C', '#F87CE1', null],
  ['#6BCFEE', '#1049BD', '#09265F', '#0F78E0', '/images/designs/blue_bubble.png'],
  ['#FBFFB2', '#FF7C00', '#3A555C', '#DBDC30', '/images/designs/yellow_star.png'],
  ['#4A4A4A', '#82BFFF', '#FFFFFF', '#000000', null],
  ['#FA876C', '#FFFFFF', '#000000', '#FA3527', '/images/designs/red_diagonal_up_stripe.png']
];
var currentImageChoice = null;
var currentQuestion = null;

function EscapeHTML(Str)
  /* returns Str with all characters with special HTML meanings converted to
    entity references. */
  {
    var Escaped = ""
    for (var i = 0; i < Str.length; ++i)
      {
        var ThisCh = Str.charAt(i)
        if (ThisCh == "&")
          {
            ThisCh = "&amp;"
          }
        else if (ThisCh == "<")
          {
            ThisCh = "&lt;"
          }
        else if (ThisCh == "\"")
          {
            ThisCh = "&quot;"
          }
        else if (ThisCh == ">")
          {
            ThisCh = "&gt;"
          } /*if*/
        Escaped += ThisCh
      } /*for*/
    return Escaped
  } /*EscapeHTML*/

function finishedUploadingImage(id, url) {
  $.fn.fancybox.close();
  if(currentImageChoice != null) {
    var choice = currentImageChoice;
    choice.find('input[name="choice_image_urls[]"]').val(url);
    choice.find('input[name="choice_images[]"]').val(id);
    choice.find('img').attr('src', '/images/create/image_delete.png');
  
    choice.find('a').unbind('click');
    choice.find('a').click(function() {
      choice.find('input[name="choice_image_urls[]"]').val('');
      choice.find('input[name="choice_images[]"]').val('');
      choice.find('img').attr('src', '/images/create/image_add.png')
      updatePreviewChoices();
    
      fancybox(choice.find('a'));
      //so we know which thing an image was added to
      choice.find('a').click(function() {
        currentImageChoice = choice;
        currentQuestion = null;
      })
      return false; // don't navigate away
    })
    updatePreviewChoices();
  } else {
    var question = currentQuestion;
    question.find('input[name="question_image_url"]').val(url);
    question.find('input[name="question_image"]').val(id);
    question.find('img').attr('src', '/images/create/image_delete.png');
  
    question.find('a').unbind('click');
    question.find('a').click(function() {
      question.find('input[name="question_image_url"]').val('');
      question.find('input[name="question_image"]').val('');
      question.find('img').attr('src', '/images/create/image_add.png')
      updatePreviewTitle();
    
      fancybox(question.find('a'));
      //so we know which thing an image was added to
      question.find('a').click(function() {
        currentImageChoice = null;
        currentQuestion = question;
      })
      return false; // don't navigate away
    })
    updatePreviewTitle();
  }
  
}

function updatePreviewTitle() {
  var question = $('#question');
  //TODO: escape this
  var questionText = $('#poll_question').val();
  var imageUrl = question.find('input[name="question_image_url"]').val();
  if(imageUrl !== '') {
    var imageText = '<img src="' + imageUrl + '" />';
    if(questionText !== '') {
      imageText = '<br />' + imageText;
    }
    questionText += imageText;
  }
  $('#title').html(questionText);
}

function addNextChoiceIfNeeded() {
  var empty = $('#choices li').filter(function() {
    return $(this).find('input[name="choices[]"]').val() === '' && $(this).find('input[name="choice_images[]"]').val() === '';
  }).size();
  if(empty == 0) {
    var index = $("#choices li").size() - 1;
    addNewChoice(index)
  }
}

function updatePreviewChoices() {
  var str = '';
  var i = 0;
  $('#choices li').each(function() {
    var text = $(this).find('input[name="choices[]"]').val();
    var image = $(this).find('input[name="choice_image_urls[]"]').val();
    if(text !== '' || image !== '') {
      if(image !== '') {
        image = '<img src="' + image + '" />'
        if(text !== '') {
          image = '<br />' + image
        }
      }
      str += '<div class="preview_choice"><div class="preview_radio"><input type="' + choiceType + '" class="preview_radio" name="preview" id="preview_choice_' + i + '" /></div><div class="preview_text"><p><label for="preview_choice_' + i + '">' + text + image + '</label></p></div></div>';      
    }
    i++;
  });
  $('#answers').html(str);
  // update preview choice colors again since i guess we erased them
  // updateChoiceColor($('#poll_choice_color').val())
  
  addNextChoiceIfNeeded();
}

function bindQuestionUpdates() {
  $('#poll_question').keyup(updatePreviewTitle).blur(updatePreviewTitle);
}

function bindChoiceUpdates() {
  $('#choices :text').keyup(updatePreviewChoices).blur(updatePreviewChoices);
}

function addNewChoice(index) {
  var choice = '<li id="choice' + (index + 1) + '"><p><input class="answer text" name="choices[]" type="text" /></p></li>';
  $('#choices ol').append(choice);
  var choiceElement = $('#choice' + (index + 1))
  setupImageLink(choiceElement);
  setupChoice(choiceElement);
  bindChoiceUpdates();
}

function setupImageLink(choice) {
  choice.find(':text').after(' <a href="/images/new" class="image_link iframe"><img class="add_image" src="/images/create/image_add.png" /></a><input name="choice_images[]" type="text" style="display: none;" /><input name="choice_image_urls[]" type="text" style="display: none;" disabled="disabled" />');
  fancybox(choice.find('a'));
  //so we know which thing an image was added to
  choice.find('a').click(function() {
    currentImageChoice = choice;
    currentQuestion = null;
  });
}

function setupQuestionImageLink() {
  var question = $('#question');
  question.find(':text').after(' <a href="/images/new" class="image_link iframe"><img class="add_image" src="/images/create/image_add.png" /></a><input name="question_image" type="text" style="display: none;" /><input name="question_image_url" type="text" style="display: none;" disabled="disabled" />');
  fancybox(question.find('a'));
  //so we know which thing an image was added to
  question.find('a').click(function() {
    currentImageChoice = null;
    currentQuestion = question;
  })
}

function fancybox(element) {
  element.fancybox({
    'frameWidth': 420,
    'frameHeight': 350
  })
}

function setupChoices() {
  $("#choices li").each(function(i) {
    if($(this).find(':text').val() !== '') {
      setupChoice($(this));
      setupImageLink($(this));
    } else if(i != 0) {
      //remove all empty text choices except first one
      $(this).remove();
    }
  });
  if($('#choices li').size() == 1) {
    //one element
    $("#choices li:first").each(function() {
      setupChoice($(this));
      setupImageLink($(this));
    });
  } else {
    addNextChoiceIfNeeded();
  } 
}

function setupChoice(choice) {
  // setupChoiceImageLink(choice);
  choice.find(':text').focus(highlight).focus(addNextChoiceIfNeeded).blur(removeHighlight).blur(addNextChoiceIfNeeded);
}

function setPreviewBackgroundColor(color) {
  $('#poll_background_color').val(color);
  $('#poll_background_color_image').css('background-color', color);
  $('#preview').css('backgroundColor', color);
}

function setPreviewQuestionColor(color) {
  $('#poll_title_color').val(color);
  $('#poll_title_color_image').css('background-color', color);
  $('#title').css('color', color);
}

function setPreviewChoiceColor(color) {
  $('#poll_choice_color').val(color);
  $('#poll_choice_color_image').css('background-color', color);
  $('.preview_choice').css('color', color);
}

function setPreviewBorderColor(color) {
  $('#poll_border_color').val(color);
  $('#poll_border_color_image').css('background-color', color);
  $('#preview').css('border', '1px solid ' + color);
}

function setPreviewBackgroundImage(image) {
  if(image != null) {
    $('#preview').css('backgroundImage', "url(" + image + ")");
    $('#design_swatch').css('backgroundImage', "url(" + image + ")");
    var parts = image.split('/');
    $('#poll_style').val(parts[parts.length - 1]);
  } else {
    $('#preview').css('backgroundImage', '');
    $('#design_swatch').css('backgroundImage', '')
    $('#poll_style').val('');
  }
}

function setupStyleButtons() {
  $("#styles input:button").each(function(i) {
    $(this).click(function() {
      setPreviewBackgroundColor(sampleStyles[i][0]);
      setPreviewQuestionColor(sampleStyles[i][1]);
      setPreviewChoiceColor(sampleStyles[i][2]);
      setPreviewBorderColor(sampleStyles[i][3]);
      setPreviewBackgroundImage(sampleStyles[i][4]);
    });
  });
}

function highlight() {
  $(this).addClass("selected");
}

function removeHighlight() {
  $(this).removeClass('selected')
}

function setupFocusBackgrounds() {
  $(":text").focus(highlight).blur(removeHighlight);
}

function setupSubmit () {
  $('#create_form').submit(function() {
    $('#create_button').attr('disabled', 'disabled');
  });
}

function setupAllowsMultipleChoicesOption() {
  $("#poll_allows_multiple_choices").click(function() {
    if($(this).is(':checked')) {
      choiceType = 'checkbox'
    } else {
      choiceType = 'radio'
    }
    updatePreviewChoices();
  });
}

function updateColors() {
  setPreviewBackgroundColor($('#poll_background_color').val());
  setPreviewQuestionColor($('#poll_title_color').val());
  setPreviewChoiceColor($('#poll_choice_color').val());
  setPreviewBorderColor($('#poll_border_color').val());
}

function setupColorPickers() {
  $('#colors tr:not(:last)').each(function() {
    // $(this).find('td:last').hide();
    $(this).prepend('<td style="width: 20px; height: 24px;"><img src="/images/create/swatch.gif" width="24" height="20" id="' + $(this).find('input').attr('id') + '_image' + '" /></td>');
    var input = $(this).find('input').get(0);
    var img = $(this).find('img').get(0);
    var myPicker = new jscolor.color(img, {
      valueElement: input,
      styleElement: img,
      hash: true
    });
    myPicker.visible = false;
    
    // update colors whenever color is exported
    myPicker.oldExport = myPicker.exportColor;
    myPicker.exportColor = function(flags) { 
      myPicker.oldExport(flags);
      updateColors();
    }
    
    $(this).find('img').click(function() {
      if(myPicker.visible) {
        myPicker.hidePicker();
      } else {
        myPicker.importColor();
        myPicker.showPicker();
      }
      myPicker.visible = !myPicker.visible;
    });
    $(this).find('input').focus(updateColors).blur(updateColors).change(updateColors);
  })
}

function setupDesignPicker() {
  var designs = [
    ["blue_horizontal_stripe.png", "green_horizontal_stripe.png", "pink_horizontal_stripe.png", "purple_horizontal_stripe.png", "red_horizontal_stripe.png", "yellow_horizontal_stripe.png"], 
    ["yellow_vertical_stripe.png", "red_vertical_stripe.png", "purple_vertical_stripe.png", "pink_vertical_stripe.png", "green_vertical_stripe.png", "blue_vertical_stripe.png"], 
    ["blue_diagonal_up_stripe.png", "green_diagonal_up_stripe.png", "pink_diagonal_up_stripe.png", "purple_diagonal_up_stripe.png", "red_diagonal_up_stripe.png", "yellow_diagonal_up_stripe.png"], 
    ["yellow_diagonal_down_stripe.png", "red_diagonal_down_stripe.png", "purple_diagonal_down_stripe.png", "pink_diagonal_down_stripe.png", "green_diagonal_down_stripe.png", "blue_diagonal_down_stripe.png"], 
    ["blue_bubble.png", "green_bubble.png", "pink_bubble.png", "purple_bubble.png", "red_bubble.png", "yellow_bubble.png"], ["yellow_star.png", "red_star.png", "purple_star.png", "pink_star.png", "green_star.png", "blue_star.png"]
  ]
  
  
  $('#colors tr:last').prepend('<td style="width: 20px; height: 24px;"><img src="/images/create/swatch.gif" width="24" height="20" id="design_swatch" /></td><td><label>Pattern</label></td>')
  
  var designSwatch = $('#colors tr:last img');
  
  var table = '<table id="design_images" style="display: none; border: 1px solid #838383; background-color: #EEE; border-spacing: 2px; position: absolute;">';
  for(var row in designs) {
    table += '<tr style="margin: 0; padding: 0;">';
    for(var col in designs[row]) {
      table += '<td style="padding: 0; margin: 0; border:1px solid #838383; width:20px; height: 20px;"><img width="20" height="20" style="vertical-align: bottom;" src="/images/designs/' + designs[row][col] + '" /></td>';
    }
    table += '</tr>';
  }
  table += '<tr><td colspan="6"><input style="width: 100%;" type="button" value="None" /></td></tr>';
  table += '</table>';
  $('body').append(table);
  
  $('#design_images input').click(function() {
    $('#design_images').hide();
    setPreviewBackgroundImage(null);
  });
  
  $('#design_images img').each(function() {
    $(this).click(function() {
      $('#design_images').hide();
      setPreviewBackgroundImage($(this).attr('src'));
    }).hover(function() {
      $(this).parent().attr('style', 'padding: 0; margin: 0; border: 1px solid blue;');
    }, function() {
      $(this).parent().attr('style', 'padding: 0; margin: 0; border: 1px solid #838383');
    })
  })
  
  designSwatch.click(function() {
    // alert($('#design_images').visible());
    if($('#design_images:visible').size()) {
      $('#design_images').hide();
    } else {
      var x = $(this).position().left;
      var y = $(this).position().top + $(this).height() + 1;
      $('#design_images').css({'top': y, 'left': x});
      $('#design_images').show();
    }
  });
}

$(document).ready(function() {
  bindQuestionUpdates();
  bindChoiceUpdates();
  
  setupFocusBackgrounds();
  setupChoices();
  setupQuestionImageLink();
  setupStyleButtons();
  setupColorPickers();
  setupDesignPicker();
  setupSubmit();
  setupAllowsMultipleChoicesOption();
  
  updatePreviewChoices();
  updatePreviewTitle();
  
  // in case they paste some text with the mouse and are waiting for the next choice to appear
  setInterval("addNextChoiceIfNeeded()", 1000);
});