$(document).ready(function() {
  $('#addVideoLink').click(function() {
    $('#addvideo').fadeIn();
    $('#addslideshow').hide();
    $('#youtubeid', '#addvideo').select();
    return false;
  });

  $('#addSlideshowLink').click(function() {
    $('#addslideshow').fadeIn();
    $('#addvideo').hide();
    $('#photos', '#addslideshow').select();
    return false;
  });

  $('#addVideoForm').submit(function() {
    var youTubeId = '';
    if (this.youtube.value) {
      var matches = /youtube\.com\/watch\?v=([^&]+)/.exec(this.youtube.value);
      if (matches && matches[1]) {
        youTubeId = matches[1];
      } else {
        alert("That doesn't seem to be a valid YouTube link. Please try again.");
        return false;
      }
    }
    $.post(API2_PATH + 'textaddvideophotos', { id: this.textid.value, youtubeid: youTubeId }, function() {
      $('#addvideo').hide();
      $('#youtubeContainer').html('');
      if (youTubeId != '') {
        var embed = document.createElement('embed');
        embed.src = 'http://www.youtube.com/v/' + matches[1] + '&hl=en_US&fs=1&rel=0';
        embed.type = 'application/x-shockwave-flash';
        embed.width = '300';
        embed.height = '240';
        $(embed).attr('allowscriptaccess', 'true');
        $(embed).attr('allowfullscreen', 'true');
        $(embed).attr('wmode', 'opaque');
        $('#youtubeContainer').append(embed);
        $('#youtubeContainer').show();
        $('#addVideoLink #changeVideoText').show();
        $('#addVideoLink #addVideoText').hide();
      } else {
        $('#addVideoLink #changeVideoText').hide();
        $('#addVideoLink #addVideoText').show();
      }
    });
    return false;
  });

  $('#addSlideshowForm').submit(function() {
    var photosUrl = '';
    if (this.photos.value) {
      var matches = /(http:\/\/[\w\d]+\.photobucket\.com\/(?!pbwidget).*?[\w\d]+\.pbw|.*\.jpg$|.*\.jpeg$|.*\.png$|.*\.gif$)/.exec(this.photos.value);
      if (matches && matches[1]) {
        photosUrl = matches[1].replace(/\?action=view&current=/, '');
      } else {
        alert("That doesn't seem to be a valid photo or Photobucket slideshow link. Please try again.");
        return false;
      }
    }
    $.post(API2_PATH + 'textaddvideophotos', { id: this.textid.value, photos: photosUrl }, function() {
      $('#addslideshow').hide();
      $('#slideshow').html('');
      if (photosUrl != '') {
        var photoEl = getPhotoElement(photosUrl);
        $('#slideshow').append(photoEl);
        $('#slideshow').show();
        $('#addSlideshowLink #changeSlideshowText').show();
        $('#addSlideshowLink #addSlideshowText').hide();
      } else {
        $('#addSlideshowLink #changeSlideshowText').hide();
        $('#addSlideshowLink #addSlideshowText').show();
      }
    });
    return false;
  });

  $('#addVideoCancel').click(function() {
    $('#addvideo').fadeOut();
    return false;
  });

  $('#addSlideshowCancel').click(function() {
    $('#addslideshow').fadeOut();
    return false;
  });

	$('#votebox').click(function() {
		$('#votemore').fadeIn();
		return false;
	});

	updateFloatPanel();

	// floating panel scroll/resize detection (not for IE6 and earlier)
	if( !($.browser.msie && parseFloat($.browser.version) < 7)) {
		$(window).scroll(function() { // keep the floating panel visible at all times
			var fp = $('#float_panel');
			var isFixed = fp.css('position')=='fixed';
			if (!isFixed && $(this).scrollTop()>fpTop-10 && $(this).scrollTop()<fpBottom-10) {
				fp.css({
					position: 'fixed',
					top: "10px",
					left: String(fpLeft)+"px"
				});
			}
			else if (isFixed && ($(this).scrollTop()<=fpTop-10 || $(this).scrollTop()>=fpBottom-10)) {
				fp.css('position','absolute');
				updateFloatPanel();
			}
		});

		$(window).resize(function() {
			if ($('#float_panel').css('position')=='fixed') {
				var oldLeft = fpLeft;
				updateFloatPanel();
				if (fpLeft!=oldLeft) {
					$("#float_panel").css({
						position: 'fixed',
						top: "10px",
						left: String(fpLeft)+"px"
					});
				}
			}
			else
				updateFloatPanel();
		});

		$(window).scroll();
	}
	else if ($('#float_panel').offset().top != fpTop) {
		$('#float_panel').offset({
			left: fpLeft,
			top: fpTop
		});
	}

});

function getPhotoElement(url) {
  if (url.match(/pbw$/)) {
    var embed = document.createElement('embed');
    embed.src = 'http://w879.photobucket.com/pbwidget.swf?pbwurl=' + url;
    embed.type = 'application/x-shockwave-flash';
    embed.width = '300';
    $(embed).attr('wmode', 'transparent');
    return embed;
  } else {
    var img = document.createElement('img');
    img.src = url;
    img.width = 300;
    img.height = 240;
    return img;
  }
}

function changeFontSize(set) {
	var oldSize = $("#storyText").css("font-size"), newSize;
	var defaultSize = "12px";

	if (set==0) {
		newSize = defaultSize;
	}
	else {
		newSize = $("#storyText").css("font-size");
		if (newSize==null||newSize=="") {
			newSize = defaultSize;
		}

		var newSize_num = Number(newSize.substring(0,newSize.length-2));

		// min size is 11px
		if (set==-1 && newSize_num>10) {
			newSize = String(newSize_num-1)+"px";
		}
		// max size is 18px
		else if (set==1 && newSize_num<20) {
			newSize = String(newSize_num-(-1))+"px";
		}
	}

	// save font size in a cookie
	var d = new Date();
	d.setTime(d.getTime()+1000*60*60*24*30);
	setCookie("wp_fontSize",newSize,d);

	// update the story div to use new font size
	$("#storyText").css("font-size",newSize);

	// fix the font size of the Kontara ads (IL_AD1, IL_AD2...)
	var i=1;
	while ($("#IL_AD"+i).length>0) {
		$("#IL_AD"+i).css("css-text","font-size:1em !important");
		i++;
	}

	return false;
}

// handle resizing of synopsis box
var bigHeight;
var smallHeight;
var lineHeight;
function updateSynopsisBox() {
	lineHeight = $('#synopsis').css('line-height').substr(0,$('#synopsis').css('line-height').length-2);
	bigHeight = $('#synopsis').height()+'px';
	smallHeight = (8*Number(lineHeight) - 4)+'px'; // # of lines minus padding
	if (parseInt(bigHeight)<parseInt(smallHeight)) {
		$('#synopsis_box').height(bigHeight);
		$('#show_synopsis').hide();
		$('#hide_synopsis').hide();
		return;
	}

	if ($('#synopsis').data('visible'))
		$('#synopsis_box').height(bigHeight);
	else
		$('#synopsis_box').height(smallHeight);
}

function show_synopsis() {
	var next_css = new Object();
	if ($('#synopsis').data('visible')) {
		$('#show_synopsis').show();
		$('#hide_synopsis').hide();
		next_css.height = smallHeight;
	}
	else {
		$('#hide_synopsis').show();
		$('#show_synopsis').hide();
		next_css.height = bigHeight;
	}
	$('#synopsis_box').animate(next_css,'fast',function() {
		$('#synopsis').data('visible',!$('#synopsis').data('visible'));
	});
}

var fpLeft, fpTop, fpBottom;
function updateFloatPanel() {
	var fp = $('#float_panel');
	fpLeft = Math.round($('#storyText').parent().offset().left - fp.outerWidth()+1);
	fpTop = Math.round($('#content').children('div.column_left').children('div.panel').first().offset().top+40);
	var commentDiv = $('#content').find('div.panel').last();
	fpBottom = Math.round(commentDiv.offset().top+commentDiv.outerHeight() - fp.outerHeight()-20);
	var atTop = $(window).scrollTop()<fpBottom-10;
	if (fp.css('position')!='fixed' && (fp.offset().left!=fpLeft || fp.offset().top!=(atTop ? fpTop : fpBottom))) {
		fp.offset({
			left: fpLeft,
			top: atTop ? fpTop : fpBottom
		});
	}
}
