/**
* NewsTrust general JS
*/

// switch on one-click meta reviews
$(document).ready(function() {
	$('.source_review_input .rating_input, .meta_review_input .rating_input').rating_input({submit_on_click: true, disable_overall_rating: true});
});

$(document).ready(function() {
  // $('.main_column_box').supersleight({shim: '/images/ui/spacer.gif'}); // IE6 PNG fix.
  // $(document).pngFix(); // IE6 PNG fix. doesn't treat background images very nicely, commenting out!
});

/**
* Apply proper styles/handlers to story links on cached pages,
* where we can't just burn this user-specific logic into the cached HTML fragment.
*/
$(document).ready(function() {
    // Set up the appropriate badge to show based on visitor!  
  var badge_div = $('.rotating_badge_div');
  if (badge_div.length > 0) {
    var badge_image_urls;
    var badge_target_urls;
    if (!member_is_logged_in) {
        // Guest
      badge_image_urls = typeof(guest_badge_image_urls) == "undefined" ? [] : guest_badge_image_urls;
      badge_target_urls = typeof(guest_badge_target_urls) == "undefined" ? [] : guest_badge_target_urls;
    }
    else if (!member_is_active_reviewer) {
        // Logged in member who is not an active reviewer
      badge_image_urls = typeof(member_badge_image_urls) == "undefined" ? [] : member_badge_image_urls;
      badge_target_urls = typeof(member_badge_target_urls) == "undefined" ? [] : member_badge_target_urls;
    }
    else {
        // Logged in member who is an active reviewer
      badge_image_urls = typeof(active_member_badge_image_urls) == "undefined" ? [] : active_member_badge_image_urls;
      badge_target_urls = typeof(active_member_badge_target_urls) == "undefined" ? [] : active_member_badge_target_urls;
    }

    var num_badges = badge_image_urls.length;
    badge_div.each(function(i) {
      var rand = Math.ceil(Math.random()*num_badges);
      $(this).find("img").attr('src', badge_image_urls[rand-1]);
      $(this).find("a").attr('href', badge_target_urls[rand-1]);
    });
  }

  // All this js code should be factored out into a function that triggers only
  // for story listings or story overview pages.  So, for now, we are backing out
  // if is_story_listing is undefined!
  if ((typeof(is_story_listing) == "undefined") || !is_story_listing)
    return;

  if (member_is_editor) $('.story_edit_link').show();
  if (member_is_editor) $('.edit_link').show().attr("title","Edit this story");
  
  if (cached_stories_state) {
    $.each(cached_stories_state, function(id, state) {
      var $story_links = $('#story_links_'+id);
      // NOTE: copy changes here must be made in ReviewsHelper#link_to_new_review & StoriesHelper#save_link_text as well!!!
      if (state.reviewed) $story_links.find('a.review_link').addClass('on').attr("title","Edit your review");
      if (state.saved) $story_links.find('a.save_link').text("Unlike").addClass('on').attr("title","Click here to stop liking this story");
      $story_links.find('a.save_link').attr('onclick', '').click(function() {
        var save_link = this; 
        $(save_link).pulse(true); 
        var ajax_params = {
          url      : '/stories/' + id + '/save.js?',
          type     : 'post', 
          data     : 'authenticity_token=' + encodeURIComponent(AUTH_TOKEN),
          dataType : 'script', 
          complete : function(request) {
            update_save_link(save_link, request);
          }
        }
        $.ajax(ajax_params);
        return false;
      });
    });
  }
});

/**
* Used above and in StoriesHelper.save_link_function_options
*/
function update_save_link(save_link, request) {
  var new_link_text = eval(request.responseText);
  var liked = (new_link_text != "Like");
  var new_link_title = liked ? 'Click here to like this story' : 'Click here to stop liking this story';
  $(save_link).pulse(false, new_link_text).toggleClassAbsolute('on', liked).attr('title', new_link_title);
}

// Automatically insert the authtoken to outgoing requests
$(document).ajaxSend(function(event, request, settings) {
  if (typeof(AUTH_TOKEN) == "undefined"){ return false; }
  // settings.data is a serialized string like "foo=bar&baz=boink" (or null)
  settings.data = settings.data || "";
  settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
  return this;
});

function add_textile_support_links() {
    $('.textile_support_link').bind("click.forComments",
    function(event) {
        var p = $(event.target).parent().get(0);
        $(p).next().toggle("fast");
        event.preventDefault();
    });
    $('.close_textile_support_link').bind("click.forComments",
    function(event) {
        var p = $(event.target).parent().get(0);
        while (p.tagName !== 'DIV') {
            p = $(p).parent().get(0);
        }
        $(p).hide();
        event.preventDefault();
    });
}

$(document).ready(function() {
  add_textile_support_links();
});

function format_send_to_friend_post(){
return "message[body]=" + encodeURIComponent($("#message_body").val()) +
       "&message[to]=" + $("#message_to").val() +
       "&message[template]="+send_to_friend_params.template +
       "&message[page]="+send_to_friend_params.page +
       "&message[record_id]="+send_to_friend_params.record_id +
       "&message[from]=" + $("#message_from").val();
}

function handle_response(response) {
  if(response.flash) {
      var status_types = ["error", "notice", "warning"];
      for(var x in status_types) {
          if(response.flash[status_types[x]]) {
              var type = status_types[x];
              $("#" + type + "_results").html(response.flash[type]);
              $("#" + type + "_results").show();
              $("#" + type + "_results").click(function () {
                  $(this).fadeOut(1000, function () {
                      $(this).remove();
                  });
              });
          }    
      }   
  }
}
// Ensure the we can't double click an ajax link and submit it more than once.
function blockAjax(element, callback) {
    if (!$(element).hasClass('in_use')) {
        $(element).addClass('in_use');
        callback();
    }
}

function unblockAjax(element) {
    $(element).removeClass('in_use');
}

/*
  Function: assignFlags
  This method will assign the flaggable actions to any hyperlinks with the .flaggable and .unflaggable classes
*/
function doflag(event, flag_url) {
  var params = {
      flaggable_type: $(event.target).attr('flaggable_type'),
      flaggable_id: $(event.target).attr('flaggable_id'),
      reason: $(event.target).attr('reason')
  };
  blockAjax($(event.target),function(){
      $(event.target).pulse(true);
      $.ajax({
          dataType: 'json',
          type: "POST",
          data: params,
          url: flag_url,
          success: function(data) {
              $("#server_result_" + data.id).html(data.flash.notice);
              $(event.target).unbind('click');
              $(event.target).bind('click', function(e){ undoflag(e, flag_url); });
              updateComment(data.flaggable);
              update_flag_trigger($(event.target).attr('reason'), event.target, false);
          },
          complete: function(data) {
            unblockAjax($(event.target));
            $(event.target).pulse(false);
          }
      });
  });

  event.preventDefault();
}

function undoflag(event, flag_url) {
  var params = {
      _method: 'delete',
      flaggable_type: $(event.target).attr('flaggable_type'),
      reason: $(event.target).attr('reason')
  };
  blockAjax($(event.target),function(){
      $(event.target).pulse(true);
      $.ajax({
          dataType: 'json',
          type: "POST",
          data: params,
          url: "/flags/" + $(event.target).attr('flaggable_id') + '.json',
          success: function(data) {
              update_flag_trigger($(event.target).attr('reason'), event.target, true);
              $("#server_result_" + data.id).html(data.flash.notice);
              $(event.target).unbind('click');
              $(event.target).bind('click', function(e){ doflag(e, flag_url); });
              updateComment(data.flaggable);
          },
          complete: function(data) {
            $(event.target).pulse(false);
            unblockAjax($(event.target));
          }
      })
  });

  event.preventDefault();
}

function update_flag_trigger(reason, e, flaggable) {
    switch (reason) {
    case 'flag':
        $(e).text((flaggable) ? "Flag" : "Unflag");
        break;
    case 'like':
        $(e).text((flaggable) ? "Like" : "Unlike");
        break;
    }
    if (flaggable) {
        $(e).removeClass('unflaggable');
        $(e).addClass('flaggable');
    } else {
        $(e).removeClass('flaggable');
        $(e).addClass('unflaggable');
    }
}

function assignFlags(flag_url) {
    $(".flaggable").bind('click', function(event){ doflag(event, flag_url); });
    $(".unflaggable").bind('click', function(event){ undoflag(event, flag_url); });
}

$(document).ready(function() {

    $("#email_this_page").bind('click', function () {
        $(this).toggleClassAbsolute('on', (!$('#form_container').is(':visible')));
        var link_pos = $(this).position();
        $('#send_to_friend_form').css({top: link_pos.top + 45, left: link_pos.left});
        $('#send_to_friend_form .wrapper').toggle();
        return false;
    });

    $("#send_to_friend_form_submit").click(
        function() {
            $.ajax({
                type: "POST",
                url: send_to_friend_params.url,
                dataType: "json",
                data: format_send_to_friend_post(),
                success: function(msg) {
                   handle_response(msg);
                   $('#form_container').slideToggle("slow");
                   $('#form_results').slideToggle("slow");
                   $('#form_results').click(function () {
                         $(this).fadeOut(180, function () { $(this).remove(); });
                   });
                   $('#collapse_all').click(function() {
                      $('#form_results').html('');
                      $('#form_container').show();
                      $('#collapse_all').hide();
                      $('#send_to_friend_form .wrapper').hide();
                   }).show();
                   $('#form_results').html(
                       function(){r = "<dl>";
                       if(msg.sent.length > 0) {
                         r += "<dt>Delivered</dt>";
                         r +="<dd>" + msg.sent.join(', ') + "</dd>";
                       }
                       if(msg.unsent.length > 0) {
                         r += "<dt>Unsent</dt>";
                         r += "<dd>"+ msg.unsent + "</dd>";
                       }
                       if(msg.undeliverable.length > 0) {
                         r += "<dt>Undeliverable</dt>";
                         r += "<dd>" + msg.undeliverable + "</dd>";
                       }
                       r +="<dl>";
                       return r;}()
                   );
                },
                error: function(msg) {
                    switch (msg.status) {
                    case 406:
                        response = new Function("return " + msg.responseText)();
                        handle_response(response);
                        break;
                    }
                }
            });
            return false;
        }
    );
});

/**
* Pulse opacity on ajax links to visualize processing
*/
jQuery.fn.pulse = function(go, link_text, hideUpdated) {
  function do_pulse(pulse_link) {
    if (pulse_link.attr('pulsing') == 1) {
      var fade_to = (pulse_link.css('opacity') == 1 ? 0.2 : 1);
      pulse_link.removeClass('updated').fadeTo(600, fade_to, function() {
        do_pulse($(this));
      });
    } else {
      pulse_link.fadeTo(100, 1);
      if (typeof(hideUpdated) == "undefined" || !hideUpdated) pulse_link.addClass('updated');
      if (pulse_link.attr('link_text') != "") pulse_link.html(pulse_link.attr('link_text'));
    }
  };
  if (go) {
    $(this).attr('pulsing', 1);
    do_pulse($(this));
  } else {
    $(this).attr('pulsing', 0);
    if (!link_text) link_text = "";
    $(this).attr('link_text', link_text);
  }
  return $(this);
};

/**
* For fancy NT buttons
* gray out button in UI, submit form, debounce form (disable 2nd submission)
*/
function submit_form_button(button, debounce) {
  $(button).addClass('formButtonProcessing')
  if (debounce) $(button).parents('form').submit().submit(function() {return false});
}

/** Facebook Connect JS code here **/
function record_fb_published_review(member_id, review_id) {
    $.ajax({
      url  : '/members/' + member_id + '/fb_review_published.js',
      type : 'POST', 
      data : 'authenticity_token=' + encodeURIComponent(AUTH_TOKEN) + "&review_id=" + review_id
    })
}

/**
* Show/hide parts of reviews on story detail page
*/
function show_review_part(review_part, button) {
  if (review_part) {
    $('div.review_part').not('.'+review_part).slideUp(150).end().filter('.'+review_part).slideDown(150);
  } else {
    $('div.review_part').slideDown(150);
  }
  $('.show_activity_part a').removeClass();
  $(button).addClass('sel');
}

/**
* Show/hide parts of member activity on member page
*/
function show_member_activity(activity, button) {
  if (activity) {
    $('div.member_activity').not('.'+activity).slideUp(150).end().filter('.'+activity).slideDown(150);
  }
  else {
    $('div.post').hide();
    $('div.like').hide();
    $('div.review').hide();
    $('div.all_activity').slideDown(50);
  }
  $('.show_activity_part a').removeClass();
  $(button).addClass('sel');
}

/**
* More Info boxes. apply to whole white bar?
*/
$(document).ready(function() {
  $('.more_info_box .wrapper').click(function(event) {
    $('#more_info').slideToggle(180);
    $(this).find('span').toggleClass('more').toggleClass('less');
  });
});

/**
* Must do tricky slide for Ratings Boxes on detail pages
*/
var RATINGS_BOX_MINIMIZED_HEIGHT = 60;
function slide_ratings_box($more_button, $itemized_holster) {
  var high_tide = $itemized_holster.height() > RATINGS_BOX_MINIMIZED_HEIGHT;
  var tide_marks = $itemized_holster.find('.itemized').map(function(i, div) {return $(div).height()}); // two divs
  var high_tide_mark = Math.max(tide_marks[0], tide_marks[1]); // not pretty, sorry world
  var tide = high_tide ? RATINGS_BOX_MINIMIZED_HEIGHT : high_tide_mark;
  $itemized_holster.animate({height: tide}, 150);
  $more_button.text(high_tide ? 'more' : 'less').toggleClassAbsolute('on', !high_tide);
}

/**
* JavaScript doesn't fire onSubmit event when you call submit() on a form.
* With a little jQuery hackmagic, we can get around that though. (pop onSubmit into jQuery submit handler.)
* This is so we can use handy jRails helpers like remote_form_for, etc.
*/
var submit_with_onsubmit = function($form) {
  return $form.submit(function() {
    eval($(this).attr('onsubmit').replace('return false;', ''));
    return false;
  }).submit();
}

/**
* helper method
*/
jQuery.fn.toggleClassAbsolute = function(className, on) {
  if (on) $(this).addClass(className);
  else $(this).removeClass(className);
};


/**
*
* Popup.js - NT popup window code, mostly legacy, some new stuff
*
*/


/**
* jQuery tie-ins; manipulate the DOM as necessary before opening widow
*/
function open_popup(url, link) {
  if (link) $(link).pulse(true);
  /* SSS: Added this check Aug 22nd to not add popup=true url param to submits! */
  /* SSS: Added 2nd check Sep 23rd to not add duplicate popup=true url param to toolbar popus! */
  if (url.match(/\/submit\?/) || url.match(/popup=true/)) {
    Popup.open(url);
  }
  else {
    Popup.open(add_popup_querystring(url));
  }
  return true;
};
function add_popup_querystring(url) {
  var url_components = new RegExp(/([^#]+)(#.+)?/).exec(url);
  return url_components[1] + "?popup=true" + ((url_components.length>2 && url_components[2]) ? url_components[2] : "");
};

$(document).ready(function() {
  // insert popup query string into url for FAQs, etc.; submit can go this path, too
	$('a.popup_link').click(function() {
	  Popup.open(add_popup_querystring($(this).attr('href')), !$(this).hasClass('info_popup'));
		return false;
	});
	if (expand_window) Popup.expand();
});


/**
* Popup class does your window creating/resizing
*/
var Popup = {
  // constants
  popupWidth: 430, // can't go below 430 or FF Mac throws the scrollbar out
  popupHeight: 750,
  defaultFullWindowWidth: 990, // 950 + 40?
  defaultFullWindowHeight: 800,
  
  /**
  * Open a new popup window
  */
  open: function(url, saveScreenDimensions) {
    if (saveScreenDimensions) this.saveScreenDimensions()
    
  	// determine popup window location
  	var reviewPaneX = this.getWindowLeft() + this.getWindowWidth(); // have it sit alongside if possible
  	if (reviewPaneX + this.popupWidth > this.getScreenWidth()) { // otherwise, stick it where it will fit
  		reviewPaneX = this.getScreenWidth() - this.popupWidth
  	}
  	var reviewPaneY = this.getWindowTop()
    
    // open the popup
    // note that IE6 alone treats these dimensions as browser window w/ chrome... tough luck.
    window.open(url, "_blank",
      "width=" + this.popupWidth + "," +
      "height=" + this.popupHeight + "," +
      "left=" + reviewPaneX + "," +
      "top=" + reviewPaneY + "," +
      "scrollbars=yes,resizable=yes,status=yes,directories=yes,location=yes");
  },
  
  /**
  * Expand current ostensibly popup-sized window to full dimensions, from user's prefs if possible.
  */
  expand: function() {
    var fullWindowWidth = this.getIntCookie("NewsTrustWinW") || this.defaultFullWindowWidth
    var fullWindowHeight = this.getIntCookie("NewsTrustWinH") || this.defaultFullWindowHeight
    
    // resize window (& scootch left if falling off the screen)
    var windowXOverflow = (this.getWindowLeft() + fullWindowWidth) - this.getScreenWidth()
    if (windowXOverflow > 0) self.moveBy(-windowXOverflow, 0)
    self.resizeTo(fullWindowWidth, fullWindowHeight)
  },
  
  /**
  * Save user's current window size so we can try to expand back to that later
  */
  saveScreenDimensions: function() {
  	setCookie("NewsTrustWinW", this.getWindowWidth(), "", "/")
  	setCookie("NewsTrustWinH", this.getWindowHeight(), "", "/")
  },
  
  // cookie helper
  getIntCookie: function(name) {
    var val = getCookie(name)
    return val ? parseInt(val) : null
  },
  
  /**
  * Screen dimension helpers ("cross-platform")
  */
  // screenX/screenY (Saf/FF only) are preferred, as they give us the top of the _window_ (incl. browser chrome),
  // not just the render canvas, which is what screenLeft/screenTop (IE) give us
  getWindowLeft: function() {return parseInt(window.screenX || window.screenLeft)},
  getWindowTop: function() {return parseInt(window.screenY || window.screenTop)},
  
  // Likewise, outerWidth/outerHeight (Saf/FF only) give us the dimensions of the window w/ chrome,
  // while the document.documentElement values give us the render canvas dims again.
  // (The document.body values return what you'd expect in all browsers: not useful for windowing.)
  // To "be cool" to IE saps, add a fudge factor to these dims so it feels more sane.
  getWindowWidth: function() {return parseInt(window.outerWidth || (document.documentElement.clientWidth + 40))},
  getWindowHeight: function() {return parseInt(window.outerHeight || (document.documentElement.clientHeight + 140))},
  
  // For once, IE behaves like a normal browser.
  getScreenWidth: function() {return parseInt(self.screen.width)}
}


/**
* Cookie helpers
*/

/*
   name - name of the cookie
   value - value of the cookie
   [expires] - expiration date of the cookie
     (defaults to end of current session)
   [path] - path for which the cookie is valid
     (defaults to path of calling document)
   [domain] - domain for which the cookie is valid
     (defaults to domain of calling document)
   [secure] - Boolean value indicating if the cookie transmission requires
     a secure transmission
   * an argument defaults when it is assigned null as a placeholder
   * a null placeholder is not required for trailing omitted arguments
*/
function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}

/*
  name - name of the desired cookie
  return string containing value of specified cookie or null
  if cookie does not exist
*/
function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

/*
   name - name of the cookie
   [path] - path of the cookie (must be same as path used to create cookie)
   [domain] - domain of the cookie (must be same as domain used to
     create cookie)
   path and domain default if assigned null or omitted if no explicit
     argument proceeds
*/
function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}


/**
* "Post a Story" form: submit on paste, display status, etc.
*
* A lot of this is redundant with jquery.story_lookup.js, so they should perhaps be combined.
*/

var PROMPT_STRING = "http://";

$(document).ready(function() {
  var $status = $('#post_story .status div');
  
  function post_story() {
    $status.removeClass().addClass('loading');
    submit_with_onsubmit($('#post_story form'));
  }
  
  $('#post_story input[name=url]').keydown(function(event) {
    if (event_is_paste(event)) setTimeout(post_story, 1);
  }).focus(function(event) {
    if ($(this).val() == PROMPT_STRING) $(this).val('').removeClass('prompt');
  }).blur(function(event) {
    if ($(this).val() == '') $(this).val(PROMPT_STRING).addClass('prompt');
  }).blur();
  
  $status.click(post_story);
});

/**
* Server reponse after Post Story (= 'autopopulate')
*/
function post_story_response(request, error) {
  if (!request.error && !request.validation_errors.length) {
    this.location = request.toolbar_path;
  } else {
      // We COULD sift through all error messages & display them.
      // var error_message = $.map(request.validation_errors, function(message_parts, i) { return message_parts.join(" ") }).join("<br/>");
      // just use this message, since that's the only field on the form!
    if (request.validation_errors.length) {
      var error_message = "INVALID URL (email help@newstrust.net if incorrect)";
      $('#post_story p.response').html(error_message).show();
      $('#post_story input').css({'background-color': '#ffc'});
    }
    $('#post_story .status div').removeClass().addClass('post');
  }
}
