function isExternal(url) {
    return url.indexOf("http") == 0 && url.indexOf(window.location.host) == -1;
}

/* This is so you can set the text of elements without worrying about XSS or
 * text with embedded html. $("whatever").strippedHtml("<i>Hello</i> World!") sets
 * the html to "Hello World!" You can also specify a maxLength, in which case we'll
 * show some dots if the text is too long and let the user click to see the rest.*/
jQuery.fn.strippedHtml = function(text, maxLength) {
        var tags = /<[^>]*>/gi;
        // Nobody uses this, I'm just doing it to be consistent with jQuery.
        if (typeof text == "undefined") {
            return this.html().replace(tags, '');
        }
        text = text.replace(tags, '');
        var dotsText = "...";
        if (maxLength && text.length > maxLength) {
            if (maxLength <= dotsText.length) {
                return this.text(text.substring(0, maxLength));
            }
            var toggled = false;
            var visible = $("<span/>").html(text.substring(0, maxLength - dotsText.length));
            var dots = $("<span/>").html(dotsText);
            var remaining = $("<span/>").html(text.substring(maxLength - dotsText.length, text.length)).css({display: "none"});
            var setup = function(e) {
                    e.css({cursor: "pointer"}).click(function() {
                            if (toggled) {
                                dots.css({display: "inline"});
                                remaining.css({display: "none"});
                            } else {
                                remaining.css({display: "inline"});
                                dots.css({display: "none"});
                            }
                            toggled = !toggled;
                        });
                };
            setup(visible);
            setup(dots);
            setup(remaining);
            return this.empty().append(visible).append(dots).append(remaining);
        } else {
            return this.html(text);
        }
    };

jQuery.fn.truncateToHeight = function(text, maxHeight) {
        var element = $(this);
        var tags = /<[^>]*>/gi;
        text = text.replace(tags, '');
        var newText = "";
        var i = -1;
        element.html("");
        while (++i < text.length && element.height() <= maxHeight) {
            newText += text.charAt(i);
            element.html(newText);
        }
        while (element.height() > maxHeight && newText.length >= 1) {
            newText = newText.substring(0, newText.length - 1);
            element.html(newText + "...");
        }
    }

$(document).ready(function() {
        $("a").each(function(i) {
                var a = $(this);
                if (a.attr("href") && isExternal(a.attr("href")) && !a.attr("target")) {
                    a.attr("target", "_blank");
                }
            });
        if ((typeof item_pk != "undefined" && item_pk) && (typeof item_content_type != "undefined" && item_content_type)) {
            $.get("/api/most/view/" + item_content_type + "/" + item_pk + "/");
        }
        jQuery("a#logout").click(function(e) {
                e.preventDefault();
                $.ajax({url: "/accounts/logout/", cache: false, success: function(data){
                        $(".login").html("<span>you have been logged out</span>");
                        document.location.reload();
                    }});
            });
    });

/* from  http://getfirebug.com/firebug/firebugx.js */
if (!window.console || !console.firebug)
{
  var _names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

  window.console = {};
  for (var i = 0; i < _names.length; ++i) {
    window.console[_names[i]] = function() {};
  }
}

function IE6() {
    return jQuery.browser.msie && jQuery.browser.version.match(/6/);
}


function embed_video(video, id, width, height) {
  var url_jpg=video.replace(/\.[a-z]+$/, ".png");
  var flashvars = false;
  var params = {
    wmode: "transparent",
    allowscriptaccess: "always",
    showfsbutton: "true",
    allowfullscreen:"true", 
    flashvars: "file="+video+"&showfsbutton=true&stretching=exactfit&image="+url_jpg
  };
  var attributes = {
    id: "videoplayer_"+id,
    name: "videoplayer_"+id
  };
  swfobject.embedSWF(videoPlayerPath(), "videoplayer_"+id+"", width, height, "9.0.0","", flashvars, params, attributes);
};

function create_bookmark(user,pk,content_type,bookmark_url,can_bookmark) {
  if (user != "" && content_type != "" && pk != "" && can_bookmark==true) {
    var data = { user:user, content_type:content_type, pk:pk };
    var args = { type:"POST", 
      url:bookmark_url, 
      data:data, 
      success:function(msg){
        $('li.bookmark').html("Favorited");
      }
               };
    $.ajax(args);
  }
  else if (user !="" && can_bookmark==false){
  }
  else if (user =="")
  {
  }
  return false;
};

function delete_bookmark(bookmark_id,delete_bookmark_url) {
  if (bookmark_id) {
    var data={bookmark_id:bookmark_id};
    var args={type:"POST", 
      url:delete_bookmark_url, 
      data:data,   
      success: function(){
        $('li#bookmark_'+bookmark_id).remove();
      }
             };
    $.ajax(args);
  }
  else {
    return false;
  }
};

function loadEmailForm(ctype, pk) {
  console.log('in loadEmailForm');
  var place=$('#emailthiswrapper');
  if (place.length) {
    console.log("we've found emailthiswrapper");
    place.load('/emailthis/' +  ctype + '/' +pk + '/');
    var pos=$('#emailthislink').position();
    place.css({'top' : pos.top, 'left' : pos.left-250}).show('slow');
  }
  return false;
}

function cancelEmail() {
  $('#emailthiswrapper').slideUp(1000, function() {
     $(this).html('');
  });

}

function encodeURI(unencoded) {
	if (typeof(encodeURIComponent) != "undefined") {
           return encodeURIComponent(unencoded).replace(/\'/g, '%27');
   } else {
           return escape(unencoded
               ).replace(/\+/g, '%2B'
               ).replace(/\"/g,'%22'
               ).rval.replace(/\'/g, '%27');
   }
}

$(document).ready(function($) {
  $("input.clearonfocus").bind("focus", function() {
    if (this.defaultValue==this.value) this.value='';
  });
  jQuery('input.resetonblur').bind('blur', function() {
    if (this.value=='') this.value=this.defaultValue;
  });
})

function localize_npr_links() {
  $('a').each(function(idx) {
    var href=this.href;
    if (href && href.match(/^http\:\/\/(www\.) ?npr\.org/) 
        && (! href.match(/force_localization |\/dmg\//))) {
      var newhref=' http://www.npr.org/stations/force/force_localization.php?station=WNYC_FM&url=' + href;
      this.setAttribute('href', newhref);
    }
  });
}
$(localize_npr_links);
