var o = 2;
PLACEHOLDER = ["Richard Sherman","Kam Chancellor","Luke Willson"]
DEBUG = true;

globl_data = {};

var nempty = new Event('nempty'),
    empty = new Event('empty');

window.onload = function(){
  /* Activate bootstrap switch for preview toggles */
  $('[name="multi-select"]').bootstrapSwitch();
  $('[name="anon-select"]').bootstrapSwitch();

  /* Transition between preview and confirm modal */
  document.getElementById('create_prev').onclick = function(){
    $("#preview_modal").modal("hide");
    window.setTimeout(function(){
      $("#create_modal").modal("show").addClass("fade");
    },500);
  };

  /* Transition between confirm and preview modal */
  document.getElementById('back_prev').onclick = function(){
    $("#create_modal").modal("hide");
    window.setTimeout(function(){
      $("#preview_modal").modal("show");
    },500);
  };

  /* Install events for alert boxes */
  document.getElementById('alert_close').onclick = function(){
    document.getElementById('alert').style.display = "none";
  }

  document.getElementById('pwd_alert_close').onclick = function(){
    document.getElementById('pwd_alert').style.display = "none";
  }

  /* Install event handlers for initial elements */
  util.installHandler('click','add_field',addOpt);

  /* Generate poll preview */
  document.getElementById('btn_prev').onclick = function(){
    var q = document.getElementById('question').value;
    if(q === ""){
        document.getElementById('alert').style.display = "";
        return;
    }
    document.getElementById('modal_question').innerHTML = q;
    var new_text = "";
    for(var i=1;i<o+1;i++){
      var text = document.getElementById('r'+i).value;
      if(text === ""){
        document.getElementById('alert').style.display = "";
        return;
      }
      new_text = new_text.concat('<li>'+text+'</li>');
    }
    document.getElementById('modal_options').innerHTML = new_text;
    $('#preview_modal').modal("show");
  };

  /* Action for create poll button */
  document.getElementById('create').onclick = function(){
    //Hide any existing alert message
    document.getElementById('pwd_alert').style.display="none";
    //Validate email
    var re = new RegExp("(.)+(@)+(.)+(\\.)+([a-z]+)"),
        email = document.getElementById('email').value,
        alert_txt = document.getElementById('pwd_alert_msg');
    if(!re.test(email)){
      alert_txt.innerHTML = "Invalid email address.";
      document.getElementById('pwd_alert').style.display="";
      return;
    }
    //If password entered, ensure pwd and confirm match.
    var pwd = document.getElementById('pwd').value;
    if(pwd !== document.getElementById('pwd_confirm').value){
      alert_txt.innerHTML = "Passwords do not match.";
      document.getElementById('pwd_alert').style.display="";
      return;
    }
    
    var create_data = {};
    create_data["question"] = document.getElementById('question').value;
    var responses = [];
    for(var i=1;i<o+1;i++){
      responses.push(document.getElementById('r'+i).value);
    }

    //If password specified, send SHA1 hash. If not, empty string.
    pwd = (pwd === "")?"":CryptoJS.SHA1(pwd).toString();

    create_data["responses"] = responses;
    create_data["email"]=email;
    create_data["password"]=pwd;
    create_data["anon"]=document.getElementById('anon_select').checked;
    create_data["multi"]=document.getElementById('multi_select').checked;

    var request = {
      contentType:"application/json",
      dataType:"json",
      data:JSON.stringify(create_data),
      type:"POST",
      url:"/api/create",

      error:function(){
        var create_btn = document.getElementById('create');
        create_btn.disabled=false;
        create_btn.innerHTML = "Create Poll";
        alert_txt.innerHTML = "Something went wrong. If this error persists, "+
          "contact support@pollster.io.";
        document.getElementById('pwd_alert').style.display="";
      },

      success:function(data){
        document.getElementById('admin_url').innerHTML = data.admin_url;
        document.getElementById('vote_url').innerHTML = data.vote_url;
        $("#create_modal").modal("hide");
        window.setTimeout(function(){
          $("#cont_modal").modal("show").addClass("fade");
        },500);
      },

      //Before sending request, disable create button
      beforeSend:function(){
        var create_btn = document.getElementById('create');
        create_btn.disabled = true;
        create_btn.innerHTML = "Creating...";
      }
    };

    $.ajax(request);
    
  };
  
};

var remOpt = function(){
  if(o == 3){
    document.getElementById('rem_field').remove()
  }
  var el = document.getElementById('r'+o);
  PLACEHOLDER.push(el.placeholder);
  document.getElementById('r_div'+(o--)).remove();
}

var addOpt = function(){
  /* if(o == 4){document.getElementById('add_field').remove();} */
  if(o == 5){return;}
  else if(o == 2){
    var c = document.getElementById('btn_container');
    var el = document.createElement('button');
    el.setAttribute('id','rem_field');
    el.setAttribute('type','button');
    el.setAttribute('class','btn btn-default');

    var el2 = document.createElement('span');
    el2.setAttribute('class','glyphicon glyphicon-minus');
    el2.setAttribute('aria-hidden','true');

    el.appendChild(el2);
    c.appendChild(el);

    el.onclick = remOpt;
    
  }
  var qc = document.getElementById('question_container');
  var qDiv = document.createElement('div');
  qDiv.setAttribute('class','input-group push input-sec input-group-sm');
  qDiv.setAttribute('id','r_div'+(++o));
  var id = 'r'+o;
  var qLab = document.createElement('label');
  qLab.setAttribute('for',id);
  qLab.innerHTML = 'Option '+o;
  qDiv.appendChild(qLab);
  var qIn = document.createElement('input');
  qIn.setAttribute('type','text');
  qIn.setAttribute('id',id);
  qIn.setAttribute('size','500');
  qIn.setAttribute('class','form-control');
  qIn.setAttribute('placeholder',PLACEHOLDER.pop());
  qDiv.appendChild(qIn);
  qc.appendChild(qDiv);
}

