var markinfo_issue = 0;

$(document).ready( function () {

  /*

    Common  

  */

  // Add issue -parameter to local links/forms
  var localRx = new RegExp('^/');
  var issueRx = new RegExp('issue=');
  var queryRx = new RegExp('\\\?');

  $("a").each( function () {
    var href = $(this).attr("href");
    if (localRx.exec(href) && !issueRx.exec(href)) 
    {
      var urlDelim = "?";
      if (queryRx.exec(href)) urlDelim = "&";
      href += urlDelim +"issue="+ markinfo_issue;
      $(this).attr("href", href);
    }
  });

  $("form").each( function () {
    var action = $(this).attr("action");
    if (localRx.exec(action) && !issueRx.exec(action)) 
    {
      var urlDelim = "?";
      if (queryRx.exec(action)) urlDelim = "&";
      action += urlDelim +"issue="+ markinfo_issue;
      $(this).attr("action", action);
    }
  });


  // Add form styles
  $("input:text, input:password").addClass("text");
  $("input:submit, input:button").addClass("button");


  /*

    Header search form

  */

  $("#searchform .keyword").click( function () {
    $(this).val("");
  });

  $("#searchform .keyword").blur( function () {
    if (!$(this).val())
      $(this).val( $(this).attr("title") );
  });


  /*

    Gallup form

  */

  $("#gallup").submit( function (e) {
    e.preventDefault();

    var gallup = $("#gallup"); 
    var gallupId = gallup.find("input[name=gallupId]").val();
    var vote = gallup.find("input:checked").val();

    var field = "";
    if (vote == 1) field = 8;
    if (vote == 2) field = 9;
    if (vote == 3) field = 10;
    if (vote == 4) field = 11;
    if (vote == 5) field = 12;

    if (!vote || !field) 
    {
      return false;
    }
    
    var params = {
      "gallup" : gallupId,
      "cmf_pids" : gallupId,
      "cmf_op" : "edit"
    };
    params[ "cmm_0_"+ field ] = "inc";
    params[ "cmmo_0_"+ field ] = 1;

    $.get(
      "/gallup_ajax", 
      params,
      function () {
        $.cookie("markinfo_gallup_"+ gallupId, 1, { "expires": 90 });
        window.location.href = "?issue="+ markinfo_issue;
      }
    );
  });


  /*
    
    Gallup results  

  */

  var total = 0;
  $("#results div.result").each( function () { 
    total += parseInt($(this).text());
  });

  var resultWidth = 300;

  $("#results div.result").each( function () { 

    var votes = parseInt($(this).text());
    var percent = parseInt(votes / (total / 100));
    var width = parseInt(votes / (total / resultWidth));

    $(this)
      .text(votes +" ("+ percent +"%)")
      .before(
        $(document.createElement("div"))
          .css("width", width)
          .addClass("bar")
      )
  });

  $("#results div.bar:even").addClass("odd");
  $("#results div.bar:odd").addClass("even");


  /*

    Preview form

  */

  $("#preview").css("opacity", 0.95);
  $("#preview select").change( function () {
    $("#preview").submit();
  });

});
