/*
Number Util
*/
number_regex = /^[+\-]?\d+(\.\d+)?([eE][+\-]?\d+)?$/;    /* Global, is this evil? */

function is_digit(num) {
  return number_regex.test(num);
}


/*
Search
*/
function build_search(protocol, host) {
  var category_text = $("input[name='category_text']");
  var category_button = $("input[name='category_button']");

  // Go to category
  function goto_category(protocol, host, category_text) {
    if(category_text.attr('value') != '') {
      var category = category_text.attr('value').replace(/\W+/, '_');
      window.location = protocol + '://' + category + '.' + host + '/';
    }
  }
  // Via clicking Go
  category_button.click( function() { goto_category(protocol, host, category_text); } );

  // Via enter button
  $(".search").bind('keypress', function(e) {
    if(e.keyCode == 13) { goto_category(protocol, host, category_text); }
  });
}

/*
Text Editor
*/
tiny_mce_global_settings = {
  mode : "textareas",
  theme : "advanced",
  plugins : "media",
  theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,bullist,numlist,|,blockquote,|,link,unlink,image,media,|,cut,copy,paste,|,undo,redo,|,code",
  theme_advanced_buttons2 : "",
  theme_advanced_toolbar_location : "top",
  theme_advanced_toolbar_align : "left"
};

function render_editor(tinyMCE) {
  tinyMCE.init(tiny_mce_global_settings);
}

/*
Votes
*/
function configure_voting(dom_class) {
  var votes_status = $(".votes_status");
  var daily_votes = $(".votes_status").text();

  /* Hide all up/downvote links if users finished all daily votes */
  if(is_digit(daily_votes) && parseInt(daily_votes, 10) <= 0) {
   $(".upvote_link").hide();
   $(".downvote_link").hide();
  }

  $("." + dom_class).click(function(e) {
    var href = $(this).attr("href");

    if(!eval($.cookie('logged_in'))) {
      window.location = '/sessions/login/';
      return;
    }

    if( parseInt(daily_votes, 10) > 0 ) {
      if( daily_votes !== null ) { daily_votes = parseInt(daily_votes, 10) - 1; }

      //Get type of votes: posting or comment
      var type;
      if(href.indexOf("/postings/") > -1) { type = 'postings'; }
      else if(href.indexOf("/comments/") > -1) { type = 'comments'; }

      var split_div_id = this.id.split("_");

      //Get posting_id from clicked DOM
      var obj_id = split_div_id[split_div_id.length - 1];

      //Is it upvote or downvote?
      var up_or_down = split_div_id[0];

      var up_or_down_arrow = this;

      $.ajax({
        type: "GET",
        url: "/api/" + type + "/" + obj_id + "/" + up_or_down + "/",

        success: function(data) {
          var json = eval('(' + data + ')');
          daily_votes = json.daily_votes;

          /* Hide all up/downvote links if running out of daily_votes */
          if(parseInt(daily_votes, 10) <= 0) {
            if(type == 'comments') {
              $(".comment_ballot").hide();
            }
          }

          // Hide the clicked up & down arrow
          $(up_or_down_arrow).parent().hide();

          // Set user's new votes
          $(".votes_status").html(json.daily_votes);
          if( parseInt(json.daily_votes, 10) <= 0) {
            $(".votes_status").css("color", "red");
          }

          if( type && obj_id ) {
            $.get("/api/" + type + "/" + obj_id + "/current_vote/", function(data) {
              if(type == 'postings') { $("#current_vote_" + obj_id).html(data); }
              else if(type == 'comments') { $("#comment_current_vote_" + obj_id).html(data); }
            });
          }
        },
        error: function(msg) {
          if(type == 'postings') { $("#notification_container").html("<div class='notification bad'>Unable to vote for posting with id: " + obj_id + "</div>"); }
          else { $("#notification_container").html("<div class='notification bad'>Unable to vote for comment with id: " + obj_id + "</div>"); }
        }
      });
    }
    return false;
  });
}


/*
Delete Confirmation
*/
function init_delete_confirmation() {
  $(".delete_action").bind("click", function() {
    if (confirm('Are you sure you want to delete?')) {
      window.location = $(this).attr("href");
    }
  });
}

/*
URL utils
*/
function is_url(s) {
  var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
  return regexp.test(s);
}

/*
GeoLocation util
*/
var geo_cookie_settings = { path: '/', expires: 7 };

function fetch_ip_information() {
  if(! $.cookie('loc_ip_address')) {
    $.getJSON("http://jsonip.appspot.com?callback=?", function(data) {
      $.cookie('loc_ip_address', data.ip, geo_cookie_settings);
    });
  }
}

function fetch_geo_information() {
  fetch_ip_information();

  if($.cookie('loc_longitude') && $.cookie('loc_latitude')) {
    // We can do something interesting here
  } else {
    $.getJSON("http://www.geoplugin.net/json.gp?callback=?", function(data) {
      eval(data);
    });
  }
}

function update_database() {
  params = {
    ip_address: $.cookie('loc_ip_address'),
    city: $.cookie('loc_city'),
    region: $.cookie('loc_region'),
    area_code: $.cookie('loc_area_code'),
    dma_code: $.cookie('loc_dma_code'),
    country_code: $.cookie('loc_country_code'),
    country_name: $.cookie('loc_country_name'),
    continent_code: $.cookie('loc_continent_code'),
    latitude: $.cookie('loc_latitude'),
    longitude: $.cookie('loc_longitude'),
    region_code: $.cookie('loc_region_code'),
    region_name: $.cookie('loc_region_name'),
    currency_code: $.cookie('loc_currency_code')
  };

  $.post("/api/geolocations/update/", params, function(data) {
    if(data.indexOf("fail") > -1) { }
    else { $.cookie('geolocation_recorded', 'recorded', geo_cookie_settings); }
  });
}

function geoPlugin(data) {
  $.cookie('loc_city', data.geoplugin_city, geo_cookie_settings);
  $.cookie('loc_region', data.geoplugin_region, geo_cookie_settings);
  $.cookie('loc_area_code', data.geoplugin_areaCode, geo_cookie_settings);
  $.cookie('loc_dma_code', data.geoplugin_dmaCode, geo_cookie_settings);
  $.cookie('loc_country_code', data.geoplugin_countryCode, geo_cookie_settings);
  $.cookie('loc_country_name', data.geoplugin_countryName, geo_cookie_settings);
  $.cookie('loc_continent_code', data.geoplugin_continentCode, geo_cookie_settings);
  $.cookie('loc_latitude', data.geoplugin_latitude, geo_cookie_settings);
  $.cookie('loc_longitude', data.geoplugin_longitude, geo_cookie_settings);
  $.cookie('loc_region_code', data.geoplugin_regionCode, geo_cookie_settings);
  $.cookie('loc_region_name', data.geoplugin_regionName, geo_cookie_settings);
  $.cookie('loc_currency_code', data.geoplugin_currencyCode, geo_cookie_settings);

  if(! $.cookie('geolocation_recorded')) { update_database(); }
}

/*
PageView utils
*/
function record_page_views(href) {
  if(!href) { href = window.location.href; }

  //Remove unwanted part of the urls
  var remove_these = ['http://', 'localhost:5000', 'socialinks.org', '6diagrams.com', 'api'];
  for ( var i=0, len=remove_these.length; i<len; ++i ){
    href = href.replace(remove_these[i], '');
  }

  //Record page views
  $.get("/api" + href + "record_page_views/");
}


/*
Activate javascripts (bindings, etc.)
jQuery must be loaded first
*/
$(document).ready(function() {
  /*
  Perform login when return key is pressed.
  */
  $("form[name='login'] span input[name='email']").focus(function(e) {
    $("form[name='login'] span input[name='email']").val('');
  });

  function do_login(e) {
    e.preventDefault();
    if($("form[name='login'] span input[name='email']").val() != 'email') {
      $("form[name='login']").submit();
    }
  }

  $("form[name='login'] a.button").click(function(e) {
    do_login(e);
  });

  $("form[name='login'] span input").bind("keydown", function(e) {
    var code = e.keyCode || e.which;
    if (code == 13) { do_login(e); }
  });

  /*
  Fetch Geo Information
  */
  fetch_geo_information();

  /*
  Liquid Main Content Area
  */
  function resize_main_content(current_width) {
    var default_wrapper_width = 960;
    var default_wrapper_width_padded = default_wrapper_width + 56;
    var default_main_width = 640;

    if(current_width > default_wrapper_width_padded) {
      var additional_width = Math.floor((default_wrapper_width / default_wrapper_width_padded) * 100);
      $("#wrapper").css("width", default_wrapper_width + additional_width);
      $("#main").css("width", default_main_width + additional_width);
    }
    else {
      // Default
      $("#wrapper").css("width", default_wrapper_width);
      $("#main").css("width", default_main_width);
    }
  }

  resize_main_content($(window).width());     // On load, try to resize
  $(window).resize(function() {
    resize_main_content($(window).width());
  });
});
