function setSliderValue(slider, value) {
  if (value == '') {
    return;
  }
  if (isNaN(value)) {
    slider.setValue(0);
  } else {
    slider.setValue(value/100);
  }
}

function makeActive(txt, id, type) {
  // Change class of list item
  var div = $("item_" + type + "_" + id);
  div.className = "disabled";
  // Remove all children
  removeChildrenFromNode(div);
  // Create new disabled static text
  var new_txt = document.createTextNode(txt);
  div.appendChild(new_txt);
  // Create active item
  createActive(txt, id, type);
}

function removeActive(txt, id, type) {
  // Remove div from active
  removeItem("active_item_" + type + "_" + id);
  // Remove hidden input
  removeItem("hidden_item_" + type + "_" + id);
  // Change class back to active and add link
  var div = $("item_" + type + "_" + id);
  div.className = "enabled";
  // Create element
  div.innerHTML = "<a href='#' onclick=\"makeActive('" + txt + "', '" + id + "', '" + type + "'); return false;\">" + txt + "</a>";
}

function createActive(txt, id, type) {
  // Create element
  var new_el = document.createElement("a");
  var new_txt = document.createTextNode(txt);
  new_el.appendChild(new_txt);
  new_el.setAttribute('id', "active_item_" + type + "_" + id);
  new_el.setAttribute('className', 'token'); /* IE */
  new_el.setAttribute('class', 'token');
  new_el.setAttribute('href', '#');
  new_el.onclick = function() { removeActive(txt, id, type); return false; }; /* IE */

  // Add to parent
  var div = $(type + "Active");
  div.appendChild(new_el);
  // Creat hidden field for search
  createHiddenField(txt, id, type);
}

function createHiddenField(txt, id, type) {
  // Create element
  var new_el = document.createElement("input");
  new_el.setAttribute('value', txt);
  new_el.setAttribute('name', type + "[]");
  new_el.setAttribute('type', 'hidden');
  new_el.setAttribute('id', "hidden_item_" + type + "_" + id);
  // Add to parent
  var div = $("hiddenFields");
  div.appendChild(new_el);
}

function removeItem(id) {
  var el = $(id);
  var div = el.parentNode;
  div.removeChild(el);
}

function removeChildrenFromNode(node) {
  var len = node.childNodes.length;
  while (node.hasChildNodes()) {
    node.removeChild(node.firstChild);
  }
}


function updateTransaction(value, spent_coins, unspent_coins) {
  $('total-website-coins').value = Math.round(spent_coins + value);
  $('total-account-coins').innerHTML = Math.round(unspent_coins - value);
}

function updateDailyTransaction(value, spent_coins, unspent_coins) {
  $('total-daily-website-coins').value = Math.round(spent_coins + value);
  $('total-daily-coins').innerHTML = Math.round(unspent_coins - value);
}

function changeTabs(num, active) {
  for (i = 1; i <= num; i++) {
    document.getElementById('menu_' + i).style.display = 'none';
  }
  document.getElementById('menu_' + active).style.display = 'block';

  for (i = 1; i <= num; i++) {
    document.getElementById('tab_' + i).className = '';
  }
  document.getElementById('tab_' + active).className = 'active';
}

function getBrowserWidth() {
  if (window.innerWidth) {
    return window.innerWidth;
  } else if (document.documentElement && document.documentElement.clientWidth != 0) {
    return document.documentElement.clientWidth;
  } else if (document.body) {
    return document.body.clientWidth;
  }
  return 0;
}
function clearUsernamePrompt() {
  var username = document.getElementById("email");
  if (username.value == "Email") {
    username.value = "";
  }
}
function setUsernamePrompt() {
  var username = document.getElementById("email");
  if (username.value == "") {
    username.value = "Email";
  }
}
function clearPasswordPrompt() {
  var password = document.getElementById("password");
  password.style.display = "inline";
  password.focus();
  var passwordPrompt = document.getElementById("passwordPrompt");
  passwordPrompt.style.display = "none";
}
function setPasswordPrompt() {
  var password = document.getElementById("password");
  if (password.value == "") {
    password.style.display = "none";
    var passwordPrompt = document.getElementById("passwordPrompt");
    passwordPrompt.style.display = "inline";
  }
}

function setCookie(c_name,value,expiredays) {
  var exdate=new Date();
  exdate.setDate(exdate.getDate()+expiredays);
  document.cookie=c_name+ "=" +escape(value)+
  ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

document.observe("dom:loaded", function() {
  function hide_circle_text() {
    $$('#circle div').each(function(div) {
      div.hide();
    });
  }
  
  if ($('circle')) {
    Event.observe('find_link', "mouseover", function() {
      hide_circle_text();
      $('find_text').setStyle('display: block');
    });
    Event.observe('share_link', "mouseover", function() {
      hide_circle_text();
      $('share_text').setStyle('display: block');
    });
    Event.observe('value_link', "mouseover", function() {
      hide_circle_text();
      $('value_text').setStyle('display: block');
    });
  }
  

  // Today feature
  if ($("today")) {
    var excerpts = $$("#today #excerpts li > a");
    var articles = $$("#today #article .article_text");
    var max_height = 0;
    articles.each(function(article) {
      height = article.getHeight();
      if (height > max_height) {
        max_height = height;
      }
    });
    articles.each(function(article) {
      article.setStyle({height: max_height + 22 + 'px'});
    });
    var excerpts_length = excerpts.length;

    Event.observe("excerpts", 'click', function(event) {
      Event.stop(event);
    });

    Event.observe("excerpts", 'mouseover', function(event) {
      var elem = Event.element(event);
      while (elem.id != 'excerpts') {
        if (elem.nodeName.toUpperCase() == 'A') {
          var position = 0;
          for (i = 0; i < excerpts_length; ++i) {
            if (excerpts[i] == elem) {
              elem.addClassName('current');
              position = i;
            } else {
              excerpts[i].removeClassName('current');
            }
          }

          articles.each(function(x) {
            x.removeClassName('current');
          });
          articles[position].addClassName('current');

          break;
        } else {
          elem = elem.parentNode;
        }
      }
    });
  }

  // Results, overheard, bulletins, history home page tabs
  $$("#content_tabs a").each(function(link) {
    var tab_link = $(link);
    tab_link.observe('click', function(event) {
      // remove current from all tabs and bodies
      $$("#content .current").each(function(e) {
        $(e).removeClassName('current');
      });

      // add current to appropriate tab and body, loading body content if empty
      $$("#tab_bodies #" + tab_link.className + "_tab").each(function(div) {
        var tab = $(div);
        tab.addClassName('current');
        if (tab.empty()) {
          var content_url = tab_link.href;
          // console.debug('loading content from: ' + content_url);
          new Ajax.Updater(tab, content_url, {
                             method: 'get',
                             onCreate: function() {
                               tab.insert({
                                 top: "<img src='images/ajax-loader-round.gif' style=\'margin:0 auto;display:block;'/>"
                               });

                             },
                             onComplete: function(){
                               FB.XFBML.Host.parseDomTree();
                             }
                           });
        }
      });
      tab_link.addClassName("current");

      Event.stop(event);
    });
  });

  // Pagination links in home page tabs
  Event.observe('tab_bodies', 'click', function(event) {
    var anchor = event.findElement();
    var tab_body = anchor.up('.tab_body');
    // console.debug(anchor);
    if (anchor.up('.pagination')) {
      var content_url = anchor.href;
      // console.debug('loading content from: ' + content_url);
      new Ajax.Updater(tab_body, content_url, {
                         method: 'get',
                         onCreate: function() {
                           tab_body.update("<img src='images/ajax-loader-round.gif' style=\'margin:0 auto;display:block;'/>");
                           $('content_tabs').scrollTo();
                         },
                          onComplete: function(){
                            FB.XFBML.Host.parseDomTree();
                          }
      });
      event.stop();
    }
  });


  // .category_list
  var category_list_width = 0;
  $$('#category_list li').each(function(li) {
    category_list_width += li.getWidth();
  });
  category_list_width = category_list_width + 40; // add padding
  var category_width = $('category_list').getWidth();
  var category_list_ul = $$('#category_list ul').first();
  $$('#category_list ul').first().setStyle({width: category_list_width + 'px'});
  var container_width = $('float').getWidth();
  var category_wrapper = $("category_list_wrapper");

  // if there is a current category and it's not the first, enable the left scroll arrow
  var cur_category = $('category_list').down('li.current');
  if (cur_category && !cur_category.hasClassName('first')) {
    $('category_list_left').removeClassName('disabled');
  }

  function move_category_list() {
    new PeriodicalExecuter(function(pe) {
      var left = category_list_ul.getStyle('marginLeft').replace(/px/, '');
      var new_left = (Number(left) + Number(move_by));
      var max_left = category_list_width - Math.abs(new_left) - category_width + 10;

      if (move_by != 0 && new_left <= 0 && max_left >= 0) {
        if (new_left <= 0) {
          enable_both_arrows();
          category_list_ul.setStyle({marginLeft: new_left + 'px'});
          var current_left = new_left - move_by;
        }
      } else {
        if (new_left - move_by >=0 || max_left <= 0) {
          if (new_left - move_by >= 0) {
            disable_left_arrow();
          }
          if (max_left <= 0) {
            disable_right_arrow();
          }
        } else {
          enable_both_arrows();
        }
        move_by = 0;
        pe.stop();
      }}, 0.05
    );
  }

  function disable_left_arrow() {
    $('category_list_left').addClassName('disabled');
    $('category_list_right').removeClassName('disabled');
  }
  function disable_right_arrow() {
    $('category_list_right').addClassName('disabled');
    $('category_list_left').removeClassName('disabled');
  }
  function enable_both_arrows() {
    $('category_list_left').removeClassName('disabled');
    $('category_list_right').removeClassName('disabled');
  }

  Event.observe('category_list_left', 'mouseup', function() {
    if (!$('category_list_left').hasClassName('disabled')) {
      current_offset = parseInt(category_list_ul.getStyle('margin-left').replace(/px/, ''));
      new_x = 0;
      $$('#category_list li').reverse().each(function(li) {
        li_x = li.positionedOffset().first() + current_offset;
        if (li_x < 0 && Math.abs(li_x) + 20  <= category_width) {
          new_x = li_x;
        }
      });
      move_to = -(Math.abs(current_offset) - Math.abs(new_x));
      category_list_ul.setStyle({marginLeft: move_to + "px"});
      if (Math.abs(get_category_list_offset()) <= 0) {
        disable_left_arrow();
      } else {
        enable_both_arrows();
      }
    }
  });

  Event.observe('category_list_right', 'mouseup', function() {
    if (!$('category_list_right').hasClassName('disabled')) {
      current_offset = get_category_list_offset();
      new_x = 0;
      $$('#category_list li').each(function(li) {
        li_x = li.positionedOffset().first() + current_offset;
        if (li_x > 0 && li_x + 20 <= category_width) {
          new_x = li_x;
        }
      });
      move_to = -(Math.abs(current_offset) + Math.abs(new_x));
      category_list_ul.setStyle({marginLeft: move_to + "px"});
      if (Math.abs(get_category_list_offset()) + category_width >= category_list_width) {
        disable_right_arrow();
      } else {
        enable_both_arrows();
      }
    }
  });
  
  function get_category_list_offset() {
    return parseInt(category_list_ul.getStyle('margin-left').replace(/px/, ''));
  }  
  
  // Filters
  function select_query_string(checkbox_id, select_id) {
    checkbox = $$("#filters #" + checkbox_id).first();
    select = $$("#filters #" + select_id).first();
    name = select.readAttribute('name');
    if (checkbox && checkbox.checked) {
      // alert(select.options[select.selectedIndex].value);
      // value = select.options[select.selectedIndex].readAttribute('value');
      value = select.options[select.selectedIndex].value;
    } else {
      value = "";
    }
    if (new_pairs[name]) {
      new_pairs[name].push(value);
    } else {
      new_pairs[name] = [value];
    }
    // console.debug($H(new_pairs).inspect());
  }

  function build_query_string(url) {
    if (url) {
      qs = url.toString().split("?")[1];
      pairs = {};
      if (qs && qs.length > 0) {
        keys_values = qs.split("&");
        keys_values.each(function(kv) {
          kv_split = kv.split("=");
          if (pairs[kv_split[0]]) {
            pairs[kv_split[0]].push(kv_split[1]);
          } else {
            pairs[kv_split[0]] = [kv_split[1]];
          }
        });
      }
      // console.debug($H(pairs).inspect());

      new_pairs = {};

      // for checkboxes
      $$("#filters input[type=checkbox], #filters input[type=hidden]").each(function(input) {
        name = input.readAttribute('name');
        if ((input.readAttribute('type') == 'checkbox' && input.checked) || input.readAttribute('type') == 'hidden') {
          value = input.readAttribute('value');
        } else {
          value = "";
        }
        if (new_pairs[name]) {
          new_pairs[name].push(value);
        } else {
          new_pairs[name] = [value];
        }
      });
      
      select_query_string("_country", "state");
      select_query_string("_ages", "start_age");
      select_query_string("_ages", "end_age");

      new_qs_nodes = [];
      $H(pairs).merge(new_pairs).each(function(pair) {
        pair[1].each(function(value) {
          if (value != "") {
            new_qs_nodes.push(pair[0] + "=" + value);
          }
        });
      });
      // console.debug($A(new_qs_nodes).inspect());
      new_qs = new_qs_nodes.join("&");

      // console.debug(location.protocol + location.host + location.pathname + "?" + new_qs);
      window.location = (location.pathname + "?" + new_qs).replace(/\?$/, '');
    }
  }

  Event.observe('apply_filters', 'click', function() {
    build_query_string(location);
  });
  Event.observe("category_list", "click", function(event) {
    element = Event.element(event);
    build_query_string(element.readAttribute('href'));
    Event.stop(event);
  });

  //// Highlight Category Filter
  var current_category = $$("#category_list li.current").first();
  var current_category_h_pos = Element.positionedOffset(current_category).first();
  $$("#category_list ul").first().setStyle({marginLeft: "-" + current_category_h_pos + "px"});

  function close_anonymous_banner() {
    alert('close me');
  }
  
});

// Today arrows
function today_next() {
  $('today_prev').removeClassName('disabled');
  var excerpts = $("excerpts");
  var height = excerpts.getHeight();
  var top = get_today_top();
  var step_size = 102;
  if (top + step_size < height) {
    var new_top = top + step_size;
    $('current_today_page').innerHTML = parseInt($('current_today_page').innerHTML) + 1;
    excerpts.setStyle({top: "-" + new_top + 'px'});
    var next_top = get_today_top() + step_size;
    if (next_top >= height) {
      $('today_next').addClassName('disabled');
    }
  }
}

function today_prev() {
  $('today_next').removeClassName('disabled');
  var excerpts = $("excerpts");
  var height = excerpts.getHeight();
  var top = get_today_top();
  var step_size = 102;
  if (top > 0) {
    var new_top = top - step_size;
    $('current_today_page').innerHTML = parseInt($('current_today_page').innerHTML) - 1;
    excerpts.setStyle({top: "-" + new_top + 'px'});
    var next_top = get_today_top() - step_size;
    if (next_top < 0) {
      $('today_prev').addClassName('disabled');
    }
  }
}

function get_today_top() {
  return Math.abs(parseInt($('excerpts').getStyle('top').replace(/px/, '')));
}

