/*
 * Global
 */
// $.ajaxSetup({cache: false});

tcp = {};

tcp.ajaxForm = function(url, displaySelector, editSelector, initFunc, successFunc, focus) {
  $.ajax({
    type: "GET",
    url: url,
    success: function(data, status, request){
      $(editSelector).html(data);
      $(displaySelector).hide();
      $(editSelector).show();

      tcp.ajaxFormInit(url, displaySelector, editSelector, initFunc, successFunc, focus);
    }
  });

  return false;
};

tcp.ajaxFormInit = function(url, displaySelector, editSelector, initFunc, successFunc, focus) {
  if (typeof(focus) === "undefined") {
    focus = true;
  }

  if (typeof(initFunc) !== "undefined") {
    initFunc();
  }

  tcp.limitChars(editSelector + " textarea[maxlength]");

  $(editSelector + " .submit").click(function() {
    $.ajax({
      type: "POST",
      url: url,
      data: $(editSelector + " > form").serialize(),
      success: function(data, status, request) {
        data = $.trim(data);
        if (data.indexOf("<form") === 0) {
          $(editSelector).html(data);
          tcp.ajaxFormInit(url, displaySelector, editSelector, initFunc, successFunc, focus);
        }
        else {
          $(displaySelector).html(data);
          $(editSelector).hide();
          $(displaySelector).show();

          if (typeof(successFunc) !== "undefined") {
            successFunc();
          }
        }
      }
    });
  });

  $(editSelector + " .cancel").click(function(){
    $(editSelector).hide();
    $(displaySelector).show();
  });

  if (focus) {
    $(editSelector + " :input:visible:enabled:first").focus();
  }

  Cufon.replace(editSelector + " .cufonize");
};

// Some of our URL's have double slashes in them to represent empty queries,
// but Apache converts them to single slashes, so dump a space in to
// preserve them
// REVIEW: Probably want to start putting this stuff into query strings
//         to completely avoid the problem
tcp.fixUrlForApache = function(url) {
  var new_url = url.replace("//", "/ /");
  while (new_url !== url) {
    url = new_url;
    new_url = new_url.replace("//", "/ /");
  }

  return url;
};

tcp.nextButtonEnterKeyHandler = function(e) {
  if (e.keyCode === 13) {
    d = $(this);

    // Workaround the jquery watermark stuff
    if (d.parent().is("span")) {
      d = d.parent();
    }

    // Workaround layout stuff
    if (d.next().is("br")) {
      d = d.next();
    }

    d.next().click();
  }
};

tcp.required = function(selector, errorSelector) {
  if ($.trim($(selector).val()) === "") {
    $(errorSelector).show();
    return false;
  }
  else {
    $(errorSelector).hide();
    return true;
  }
};

tcp.setPreferredLanguage = function(language_code) {
  $.get("/set_language/" + language_code, function() {
    window.location.reload(true);
  });

  return false;
};

tcp.initGoogleMaps = function() {
  /*
   * Google Maps API Additions
   */

  tcp.maps = {};
  tcp.maps.defaultOptions = {
    zoom: 6,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    scrollwheel: false
  };

  google.maps.Map.prototype.cluster = false;
  google.maps.Map.prototype.markers = [];
  google.maps.Map.prototype.lastInfoWindow = null;

  google.maps.Map.prototype.addMarker = function(marker){
    if (this.cluster && typeof(tcp.maps.mc) === "undefined") {
      tcp.maps.mc = new MarkerClusterer(this, null, { maxZoom: 17, minimumClusterSize: 5 });
    }

    this.markers[this.markers.length] = marker;

    if (this.cluster) {
      tcp.maps.mc.addMarker(marker);
    }
  };

  google.maps.Map.prototype.addInfoWindow = function(marker, info) {
    if (typeof(info.content) === "undefined" && typeof(info.info_url) === "undefined") {
      return;
    }
    var map = this;

    google.maps.event.addListener(marker, 'click', function(){
      if (map.lastInfoWindow !== null) {
        map.lastInfoWindow.close();
      }

      var infowindow = new google.maps.InfoWindow();
      if (typeof(info.content) !== "undefined") {
        infowindow.setContent(info.content);
        infowindow.open(map, marker);
      }
      else {
        $.get(info.info_url, function(data) {
          infowindow.setContent(data);
          infowindow.open(map, marker);
        });
      }

      map.lastInfoWindow = infowindow;
    });
  };

  google.maps.Map.prototype.clearMarkers = function(){
    var i = 0;
    if (this.lastInfoWindow !== null) {
      this.lastInfoWindow.close();
    }

    if (this.cluster && typeof(tcp.maps.mc) === "undefined") {
      tcp.maps.mc = new MarkerClusterer(this, null, { maxZoom: 17, minimumClusterSize: 5 });
    }

    for (i = 0; i < this.markers.length; i++) {
      this.markers[i].setMap(null);
    }
    this.markers = [];

    if (this.cluster) {
      tcp.maps.mc.clearMarkers();
    }
  };

  google.maps.Map.prototype.fitMarkers = function(){
    var bounds = new google.maps.LatLngBounds();
    var markers = this.markers;
    var i = 0;
    for (i = 0; i < markers.length; i++) {
      bounds.extend(markers[i].getPosition());
    }

    this.fitBounds(bounds);

    if (this.getZoom() > 10) {
      this.setZoom(10);
    }
  };

  google.maps.Map.prototype.getMarkers = function(){
    return this.markers;
  };

  google.maps.Map.prototype.processJSON = function(json, callback, emptyCallback) {
    json = json.replace(/[\n\r\t]/g,"");
    var infos = jQuery.parseJSON(json);
    var i = 0;
    if (infos === null || infos.length === 0) {
      if (typeof(emptyCallback) !== "undefined") {
        emptyCallback();
      }
      return;
    }

    for (i = 0; i < infos.length; i++) {
      var info = infos[i];
      this.processMarkerInfo(info);

      if (typeof(callback) !== "undefined") {
        callback(info);
      }
    }

    this.fitMarkers();
    $("#map_loading").hide();
  };

  google.maps.Map.prototype.processMarkerInfo = function(info){
    if (info.latitude === "None" || info.longitude === "None") {
      // Put at 0,0 if we don't have the latitude/longitude
      info.latitude = Math.random() - 0.5;
      info.longitude = Math.random() - 0.5;
    }

    var marker_data = {
      position: new google.maps.LatLng(info.latitude, info.longitude),
      map: this,
      title: info.title
    };

    if (typeof(info.icon) !== "undefined") {
      marker_data.icon = info.icon;
    }

    var marker = new google.maps.Marker(marker_data);
    this.addMarker(marker);

    this.addInfoWindow(marker, info);

    return marker;
  };

  google.maps.Map.prototype.showLoading = function(info) {
    if ($("#map_loading").length === 0) {
      var mapDiv = this.getDiv();
      $(mapDiv).append($("<div id='map_loading' style='font-size:20px; position:absolute; z-index:10000;top:" + ($(mapDiv).height() / 2 - 20) + "px;text-align:center;width:" + $(mapDiv).width() + "px'><div style='margin-left:auto; margin-right: auto; padding: 8px; width:200px; background-color: #ccc; border: solid 1px #999;'>Loading...</div></div>").css("text-align", "center"));
    }
    else {
      $("#map_loading").show();
    }
  };
};

tcp.limitChars = function(selector) {
  if (typeof(selector) === "undefined") {
    selector = "textarea[maxlength]";
  }

  $(selector).limitMaxLength({
    onEdit: function(remaining) {
      $("#" + this.id + "_remaining b").text("" + remaining);
    }
  });
};

tcp.toggleDetails = function(id) {
  $("#hide_" + id).toggle();
  $("#show_" + id).toggle();
  $("#details_" + id).toggle();

  return false;
};

tcp.updateTagFilterStyle = function(sender, new_filter) {
  $("#tags a").attr("style", "font-weight:normal;");

  if (new_filter === "") {
    $(".tag-filter-label").hide();
  }
  else {
    $(".tag-filter-label span").text(sender.text());
    $(".tag-filter-label").show();
    sender.attr("style", "font-weight:bold;");
  }
};

/*
 * Paginator functions
 */

tcp.paginator = {};
tcp.paginator.pageIndex = 0;

tcp.paginator.next = function() {
  return tcp.paginator.page(tcp.paginator.pageIndex + 1);
};

tcp.paginator.page = function(pageIndex) {
  if (typeof(pageIndex) === "undefined") {
    pageIndex = tcp.paginator.pageIndex;
  }

  $(tcp.paginator.config.loadingSelector).show();
  $(tcp.paginator.config.resultsSelector).attr("disabled", "disabled");

  var url = tcp.fixUrlForApache(tcp.paginator.config.urlFunc() + "/" + pageIndex);
  $.get(url, function(data) {
    $(tcp.paginator.config.resultsSelector).html(data);
    $(tcp.paginator.config.resultsSelector).removeAttr("disabled");
    $(tcp.paginator.config.loadingSelector).hide();

    tcp.paginator.pageIndex = pageIndex;

    $("th[sort]").css("cursor", "pointer").click(function(event) {
      tcp.paginator.config.setSort($(this).attr("sort"));
    });

    if (typeof(tcp.paginator.config.callback) !== "undefined") {
      tcp.paginator.config.callback();
    }
  });

  return false;
};

tcp.paginator.prev = function() {
  return tcp.paginator.page(tcp.paginator.pageIndex - 1);
};

/*
 * Infinite Scrolls functions
 */

tcp.infiniteScroll = {};
tcp.infiniteScroll.startIndex = 0;

tcp.infiniteScroll.getMore = function(clear) {
  // If params have changed, fetch from index 0
  if (tcp.infiniteScroll.config.newParamsTestFunc() || typeof(clear) !== 'undefined') {
    tcp.infiniteScroll.startIndex = 0;

    tcp.infiniteScroll.config.resetParamsFunc();

    $(tcp.infiniteScroll.config.resultsSelector).empty();
    $(tcp.infiniteScroll.config.scrollSelector).show();
  }

  var startIndex = tcp.infiniteScroll.startIndex;
  var endIndex = tcp.infiniteScroll.startIndex + tcp.infiniteScroll.config.pageSize;

  tcp.infiniteScroll.startIndex = endIndex;

  return tcp.infiniteScroll.fetch(startIndex, endIndex);
};

tcp.infiniteScroll.getAll = function() {
  return tcp.infiniteScroll.fetch(tcp.infiniteScroll.startIndex, 0);
};

tcp.infiniteScroll.fetch = function(startIndex, endIndex) {
  $(tcp.infiniteScroll.config.loadingSelector).show();

  $.ajax({
    url: tcp.fixUrlForApache(tcp.infiniteScroll.config.urlFunc() + "/" + startIndex + "/" + endIndex),
    success: function(data){
      data = jQuery.trim(data);
      if (data.length > 0) {
        $(tcp.infiniteScroll.config.resultsSelector).show();
        $(tcp.infiniteScroll.config.emptySelector).hide();

        $(tcp.infiniteScroll.config.resultsSelector).append(data);

        if (endIndex === 0 || tcp.infiniteScroll.config.countFunc(data) < (endIndex - startIndex)) {
          $(tcp.infiniteScroll.config.scrollSelector).hide();
        }
      }
      else {
        $(tcp.infiniteScroll.config.scrollSelector).hide();

        if (startIndex === 0) {
          $(tcp.infiniteScroll.config.resultsSelector).hide();
          $(tcp.infiniteScroll.config.emptySelector).show();
        }
      }

      $(tcp.infiniteScroll.config.loadingSelector).hide();

      if (typeof(tcp.infiniteScroll.config.callback) !== "undefined") {
        tcp.infiniteScroll.config.callback(data);
      }
    }
  });

  return false;
};

/*
 * Comments functions
 */
tcp.comments = {};
tcp.comments.commentCountUrl = "";
tcp.comments.reload = false;

tcp.comments.submitComment = function() {
  $.ajax({
    type: "POST",
    url: tcp.comments.commentSubmitUrl,
    data: $("#comment_form").serialize(),
    success: function(data, status, request) {
      if (data.match("Thank you for your comment")) {
        $(".form-errors").hide();

        tcp.comments.loadCommentCount();
        tcp.comments.reload = true;
        tcp.infiniteScroll.getMore();
        tcp.comments.reload = false;

        $("#comment_form_container").hide();
        $("#id_comment").val("");
      }
      else {
        $(".form-errors").show();
      }
    },
    error: function(request, textStatus, errorThrown) {
      $(".recaptcha-error").show();
    }
  });

  return false;
};

tcp.comments.loadCommentCount = function() {
  $.ajax({
    url: tcp.comments.commentCountUrl,
    success: function(data) {
      $("#comment_count").html(data);
    }
  });
};

tcp.comments.init = function(modelId, targetId, commentSubmitUrl, showUnapproved) {
  // Set up infinite scroll
  tcp.infiniteScroll.config = {
    countFunc: function(data) {
      return $(".comment-item", "<div>" + data + "</div>").length;
    },
    emptySelector: "#comments_empty",
    loadingSelector: "#comments_loading",
    resultsSelector: "#comments",
    pageSize: 5,
    newParamsTestFunc: function() {
      return tcp.comments.reload;
    },
    resetParamsFunc: function() {},
    scrollSelector: ".infinite-scroll",
    urlFunc: function() {
      return "/comments/" + modelId + "/" + targetId + "/" + showUnapproved;
    }
  };

  tcp.comments.commentCountUrl = "/comment_count/" + modelId + "/" + targetId + "/" + showUnapproved;
  tcp.comments.commentSubmitUrl = commentSubmitUrl;

  $("#id_comment").attr("maxlength", 1000);
  tcp.limitChars();

  tcp.comments.loadCommentCount();
  tcp.infiniteScroll.getMore();
};

/*
 * JQuery Extensions
 */
jQuery.fn.limitMaxLength = function(options) {

  var settings = jQuery.extend({
    attribute: "maxlength",
    onLimit: function(){},
    onEdit: function(){}
  }, options);

  // Event handler to limit the textarea
  var onEdit = function(){
    var textarea = jQuery(this);
    var maxlength = parseInt(textarea.attr(settings.attribute), 10);

    if(textarea.val().length > maxlength){
      textarea.val(textarea.val().substr(0, maxlength));

      // Call the onlimit handler within the scope of the textarea
      jQuery.proxy(settings.onLimit, this)();
    }

    // Call the onEdit handler within the scope of the textarea
    jQuery.proxy(settings.onEdit, this)(maxlength - textarea.val().length);
  };

  this.each(onEdit);

  return this.keyup(onEdit)
        .keydown(onEdit)
        .focus(onEdit)
        .live('input paste', onEdit);
};

/*
 * Public
 */
tcp.publicPortal = {};

/*
 * presentation_request.html
 */
tcp.publicPortal.presentationRequest = {};

tcp.publicPortal.presentationRequest.updateLocationDate = function(){
  if ($("#flexible").attr("checked")) {
    $("#id_date_flexible").val("True");
    $("#date_container").hide();
    $("#desired_date_container").show();
  }
  else {
    $("#id_date_flexible").val("False");
    $("#date_container").show();
    $("#desired_date_container").hide();
  }
};

tcp.publicPortal.presentationRequest.init = function(presenterAutocompleteUrl) {
  $("#id_date").datepicker({
    dateFormat: "yy-mm-dd"
  });

  if ($("#id_date_flexible").val() === "True") {
    $("#flexible").attr("checked", "checked");
  }

  $("#flexible").change(tcp.publicPortal.presentationRequest.updateLocationDate);

  tcp.publicPortal.presentationRequest.updateLocationDate();

  tcp.limitChars();

  $("#id_preferred_presenter").autocomplete({
    url: presenterAutocompleteUrl,
    paramName: false,
    onItemSelect: function(item) {
      $("#id_preferred_presenter_id").val(item.data[0]);
    },
    onNoMatch: function() {
      $("#id_preferred_presenter_id").val("");
    }
  });
};

/*
 * index.html
 */
tcp.publicPortal.globalLanding = {};

tcp.publicPortal.globalLanding.init = function() {
  $("#masthead").cycle({
    fx: "scrollHorz",
    next: "#next",
    prev: "#prev",
    timeout: 15 * 1000,
    after: function(currentSlideElement, nextSlideElement) {
      $(".masthead-arrow-container > div").attr("title", $(nextSlideElement).attr("title"));
    }
  });

  $(".masthead-container").hover(function() {
    $(" img", this).fadeIn(250);
  }, function() {
    $(" img", this).fadeOut(250);
  });
  $(".masthead-arrow").show();
  $(".masthead-item").show();

  $("#prev").delay(1000).fadeOut(1000);
  $("#next").delay(1000).fadeOut(1000);

  $(".signup-button").click(function() {
    window.location = "/get_involved?email=" + $(".sign-up-input").val();
  });
};

/*
 * presenter_search.html
 */
tcp.publicPortal.presenterSearch = {};
tcp.publicPortal.presenterSearch.lastSearch = "";
tcp.publicPortal.presenterSearch.lastSort = "";
tcp.publicPortal.presenterSearch.map = null;

tcp.publicPortal.presenterSearch.init = function() {
  // Set up infinite scroll
  tcp.infiniteScroll.config = {
    callback: function() {
      tcp.publicPortal.presenterSearch.updateMap();
    },
    countFunc: function(data) {
      var context = "<div>" + data + "</div>";
      return $(".presenter-badge", context).length;
    },
    emptySelector: "#search_results_empty",
    loadingSelector: "#presenters_loading",
    resultsSelector: "#search_results",
    pageSize: 15,
    newParamsTestFunc: function() {
      return $("#sort").val() !== tcp.publicPortal.presenterSearch.lastSort ||
             $("#search").val() !== tcp.publicPortal.presenterSearch.lastSearch;
    },
    resetParamsFunc: function() {
      tcp.publicPortal.presenterSearch.lastSearch = $("#search").val();
      tcp.publicPortal.presenterSearch.lastSort = $("#sort").val();
      tcp.publicPortal.presenterSearch.presenterIds = [];
    },
    scrollSelector: ".infinite-scroll",
    urlFunc: function() {
      return window.location.pathname + "/results/" +
        escape($("#search").val()) + "/" +
        escape($("#sort").val());
    }
  };

  tcp.infiniteScroll.getMore();

  if (window.location.hash === "#view_map") {
    tcp.publicPortal.presenterSearch.toggleMap();
  }
};

tcp.publicPortal.presenterSearch.updateMap = function() {
  if (tcp.publicPortal.presenterSearch.map === null) {
    return;
  }

  $.get(window.location.pathname + "/map_results/" + escape($("#search").val()),
    function(data, status, request){
      tcp.publicPortal.presenterSearch.map.clearMarkers();
      var results = JSON.parse(data);
      if (results.length === 0) {
        $('div#map_loading > div').text("No results found.  Please try a different search.");
      }
      else {
        tcp.publicPortal.presenterSearch.map.processJSON(data);
      }
    }
  );

  tcp.publicPortal.presenterSearch.map.showLoading();
};

tcp.publicPortal.presenterSearch.toggleMap = function() {
  $("#map_view").toggle();
  $("#grid_view").toggle();

  if ($("#map_view").is(":visible")) {
    window.location.hash = "view_map";
    if (tcp.publicPortal.presenterSearch.map === null) {
      // Prep the map
      tcp.initGoogleMaps();

      var myOptions = {};
      $.extend(myOptions, tcp.maps.defaultOptions);
      $.extend(myOptions, {
        center: new google.maps.LatLng(0, 0)
      });

      tcp.publicPortal.presenterSearch.map = new google.maps.Map(document.getElementById("map"), myOptions);
      tcp.publicPortal.presenterSearch.map.cluster = true;

      tcp.publicPortal.presenterSearch.updateMap();
    }
  }
  else {
    window.location.hash = "";
  }

  return false;
};

/*
 * get_involved.html
 */
tcp.publicPortal.getInvolved = {};
tcp.publicPortal.getInvolved.init = function(selectedCountry, selectedState) {
  $(".news-tag-filters a").click(function() {
    window.location = "/news?initial_filter=" + $(this).attr("tag_value");
  });

  $("#country option[value='" + selectedCountry + "']").attr("selected", "selected");

  $("#country").change(tcp.publicPortal.updateStates);
  tcp.publicPortal.updateStates();

  // Restore the state selection if needed
  if (selectedState.length > 0) {
    $("#state_cd_" + selectedCountry + " option[value='" + selectedState + "']").attr("selected", "selected");
  }
};

tcp.publicPortal.updateStates = function(){
  $(".state_cd").each(function(index, value){
    $(value).attr("name", $(value).attr("id"));
    $(value).hide();
  });

  var selected = $("#country").val();
  if ($("#state_cd_" + selected).length === 0) {
    selected = "default";
  }

  $("#state_cd_" + selected).attr("name", "state_cd");
  $("#state_cd_" + selected).show();
};

/*
 * presentation_search.html
 */
tcp.publicPortal.presentationSearch = {};
tcp.publicPortal.presentationSearch.lastEndDate = "";
tcp.publicPortal.presentationSearch.lastSearch = "";
tcp.publicPortal.presentationSearch.lastStartDate = "";
tcp.publicPortal.presentationSearch.presentationIds = [];

tcp.publicPortal.presentationSearch.init = function() {
  $("#start_date").datepicker({
    dateFormat: "yy-mm-dd"
  });
  $("#end_date").datepicker({
    dateFormat: "yy-mm-dd"
  });

  $("#start_date").change(tcp.infiniteScroll.getMore);
  $("#end_date").change(tcp.infiniteScroll.getMore);

  // Prep the map
  tcp.initGoogleMaps();

  var myOptions = {};
  $.extend(myOptions, tcp.maps.defaultOptions);
  $.extend(myOptions, {
    center: new google.maps.LatLng(0, 0)
  });

  var windowHeight = $(window).height();
  if (windowHeight < 600) {
    $("#map").height(windowHeight - 100);
  }

  tcp.publicPortal.presentationSearch.map = new google.maps.Map(document.getElementById("map"), myOptions);
  tcp.publicPortal.presentationSearch.map.showLoading();

  // Set up infinite scroll
  tcp.infiniteScroll.config = {
    callback: function() {
      $("input[type='text']").watermark();
      $(".rsvp-email").keyup(tcp.nextButtonEnterKeyHandler);
      $(".rsvp-email").focus(function() {
        $(this).parent().siblings(".help-text").show();
      });

      tcp.publicPortal.presentationSearch.updateMap();
    },
    countFunc: function(data) {
      var context = "<div>" + data + "</div>";
      return $(".presentation-summary", context).length;
    },
    emptySelector: "#search_results_empty",
    loadingSelector: "#presentations_loading",
    resultsSelector: "#search_results",
    pageSize: 10,
    newParamsTestFunc: function() {
      return $("#end_date").val() !== tcp.publicPortal.presentationSearch.lastEndDate ||
             $("#search").val() !== tcp.publicPortal.presentationSearch.lastSearch ||
             $("#start_date").val() !== tcp.publicPortal.presentationSearch.lastStartDate;
    },
    resetParamsFunc: function() {
      tcp.publicPortal.presentationSearch.lastEndDate = $("#end_date").val();
      tcp.publicPortal.presentationSearch.lastSearch = $("#search").val();
      tcp.publicPortal.presentationSearch.lastStartDate = $("#start_date").val();
      tcp.publicPortal.presentationSearch.presentationIds = [];
    },
    scrollSelector: ".infinite-scroll",
    urlFunc: function() {
      return window.location.pathname + "/results/" +
        escape($("#search").val()) + "/" +
        escape($("#start_date").val()) + "/" +
        escape($("#end_date").val());
    }
  };

  tcp.infiniteScroll.getMore();

  // Make the map follow the window
  var topOffset = $("#map_container").offset().top;
  topOffset -= 20;
  $(window).scroll(function() {
    $("#map_container").stop();

    var newMargin = $(window).scrollTop() - topOffset;
    newMargin = Math.min(newMargin, $(".main-panel").height() - $("#map_container").height() - 100);
    newMargin = Math.max(newMargin, 0);
    $("#map_container").animate(
      {
        marginTop: newMargin
      }, 1000, function() {}
    );
  });
};

tcp.publicPortal.presentationSearch.updateMap = function() {
  var presentationIds = [];
  $(".presentation-summary > input[type='hidden']").each(function() {
    presentationIds.push($(this).val());
  });

  if (presentationIds.length === 0) {
    tcp.publicPortal.presentationSearch.map.clearMarkers();
    return;
  }

  $.post(window.location.pathname + "/map_results", presentationIds.join(","),
    function(data, status, request){
      tcp.publicPortal.presentationSearch.map.clearMarkers();
      tcp.publicPortal.presentationSearch.map.processJSON(data);
      $("input[type='text']").watermark();
    }
  );
};

/*
 * pressroom.html
 */
tcp.publicPortal.pressroom = {};
tcp.publicPortal.pressroom.lastSearch = "";
tcp.publicPortal.pressroom.search = "";

tcp.publicPortal.pressroom.init = function() {
  // Set up infinite scroll
  tcp.infiniteScroll.config = {
    countFunc: function(data) {
      return $(".press-release", "<div>" + data + "</div>").length;
    },
    emptySelector: "#press_releases_empty",
    loadingSelector: "#press_releases_loading",
    resultsSelector: "#press_releases",
    pageSize: 5,
    scrollSelector: ".infinite-scroll",
    newParamsTestFunc: function() {
      return tcp.publicPortal.pressroom.search !==
        tcp.publicPortal.pressroom.lastSearch;
    },
    resetParamsFunc: function() {
      tcp.publicPortal.pressroom.lastSearch = tcp.publicPortal.pressroom.search;
    },
    urlFunc: function() {
      return "/press_releases/" + tcp.publicPortal.pressroom.search;
    }
  };

  tcp.infiniteScroll.getMore();
};

/*
 * news.html
 */
tcp.publicPortal.news = {};
tcp.publicPortal.news.lastFilter = "";
tcp.publicPortal.news.lastSearch = "";
tcp.publicPortal.news.filter = "";
tcp.publicPortal.news.search = "";

tcp.publicPortal.news.filterByTag = function() {
  tcp.publicPortal.news.filter = $(this).attr("tag_value");
  tcp.updateTagFilterStyle($(this), tcp.publicPortal.news.filter);

  return tcp.infiniteScroll.getMore();
};

tcp.publicPortal.news.init = function(initialFilter) {
  // Set up infinite scroll
  tcp.infiniteScroll.config = {
    callback: function() {
      if (initialFilter.length > 0) {
        tcp.publicPortal.news.filterByTag.apply($("#tags a[tag_value='" + initialFilter + "']"));
      }

      delete tcp.infiniteScroll.config.callback;
    },
    countFunc: function(data) {
      return $(".news-item", "<div>" + data + "</div>").length;
    },
    emptySelector: "#news_articles_empty",
    loadingSelector: "#news_loading",
    resultsSelector: "#news_articles",
    pageSize: 5,
    newParamsTestFunc: function() {
      return tcp.publicPortal.news.search !== tcp.publicPortal.news.lastSearch || tcp.publicPortal.news.filter !== tcp.publicPortal.news.lastFilter;
    },
    resetParamsFunc: function() {
      tcp.publicPortal.news.lastSearch = tcp.publicPortal.news.search;
      tcp.publicPortal.news.lastFilter = tcp.publicPortal.news.filter;
    },
    scrollSelector: ".infinite-scroll",
    urlFunc: function() {
      return window.location.pathname + "/articles/" + tcp.publicPortal.news.search + "/" + tcp.publicPortal.news.filter;
    }
  };

  $(".tag-filter-label a").click(tcp.publicPortal.news.filterByTag);
  $("#tags a").click(tcp.publicPortal.news.filterByTag);

  tcp.infiniteScroll.getMore();

  jQuery(document).ready(function($) {
    $("#tweet").tweet({
      join_text: "auto",
      username: "climateproject",
      avatar_size: 0,
      count: 5,
      auto_join_text_default: "",
      auto_join_text_ed: "",
      auto_join_text_ing: "",
      auto_join_text_reply: "",
      auto_join_text_url: "",
      loading_text: "loading tweets..."
    });
  });
};

/*
 * news_article.html
 */

tcp.publicPortal.article = {};

tcp.publicPortal.article.init = function(modelId, articleId, commentSubmitUrl) {
  tcp.comments.init(modelId, articleId, commentSubmitUrl, 0);
};

/*
 * presenter.html
 */
tcp.publicPortal.presenter = {};
tcp.publicPortal.presenter.init = function() {
  // Set up infinite scroll
  tcp.infiniteScroll.config = {
    countFunc: function(data) {
      return $(".presentation-result", "<div>" + data + "</div>").length;
    },
    emptySelector: "#recent_presentations_empty",
    loadingSelector: "#recent_presentations_loading",
    resultsSelector: "#recent_presentations",
    pageSize: 3,
    newParamsTestFunc: function() {
      return false;
    },
    resetParamsFunc: function() {},
    scrollSelector: ".infinite-scroll",
    urlFunc: function() {
      return window.location.pathname + "/recent_presentations";
    }
  };

  tcp.infiniteScroll.getMore();
};

/*
 * presentation_feedback.html
 */
tcp.publicPortal.presentationFeedback = {};

tcp.publicPortal.presentationFeedback.init = function(presenterAutocompleteUrl) {
  tcp.limitChars();
};

/*
 * presentation.html
 */
tcp.publicPortal.presentation = {};

tcp.publicPortal.presentation.init = function(lat, lng) {
  if (lat === "None") {
    lat = 0;
  }
  if (lng === "None") {
    lng = 0;
  }
  tcp.initGoogleMaps();

  var myOptions = {};
  $.extend(myOptions, tcp.maps.defaultOptions);
  $.extend(myOptions, {
    zoom: 2,
    center: new google.maps.LatLng(lat, lng)
  });

  tcp.publicPortal.presentation.map = new google.maps.Map(document.getElementById("location_map"), myOptions);

  if (lat !== 0 || lng !== 0) {
    tcp.publicPortal.presentation.map.processMarkerInfo({
      latitude: lat,
      longitude: lng,
      title: "Presentation Location"
    });
  }

  $("#rsvp_email").keyup(tcp.nextButtonEnterKeyHandler);
};

tcp.publicPortal.presentation.rsvp = function(id) {
  var email = $("#rsvp_container_" + id + " input[type='text']").val();
  var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
  if ((email.length == 0) || !reg.test(email)) {
    $("#rsvp_error_" + id).show();
    return;
  }

  $.ajax({
    type: "GET",
    url: "/presentation/" + id + "/rsvp/" + email,
    success: function(data, status, request) {
      $("#rsvp_container_" + id).html(data);
    }
  });
};

// hook up Enter key for search boxes.  sort of hacky...
$(document).ready(function() {
  $("#search").keyup(tcp.nextButtonEnterKeyHandler);

  $("#brand-header-signup-button").click(function() {
    window.location = "http://forms.climaterealityproject.org/page/s/updates?email=" + $("#brand-header-signup-input").val();
  });

  $("#brand-header-signup-input").keydown(function (e) {
    if (e.keyCode === 13) {
      window.location = "http://forms.climaterealityproject.org/page/s/updates?email=" + $("#brand-header-signup-input").val();
    }
  });

  $("#brand-header-donate-button").click(function() {
    window.location = "http://forms.climaterealityproject.org/donate-tcp";
  });

  if (!$.cookie("header-shown")) {
    $(".brand-header").delay(1000).slideDown(500);
    $.cookie("header-shown", "1");
  }
  else {
    $(".brand-header").show();
  }
});

tcp.urlParams = {};
(function () {
    var e,
        a = /\+/g,  // Regex for replacing addition symbol with a space
        r = /([^&=]+)=?([^&]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
        q = window.location.search.substring(1);

    while (e = r.exec(q)) {
      tcp.urlParams[d(e[1])] = d(e[2]);
    }
})();

