var activeArea = false;

function dom_init() {

	$('a.lightbox').lightBox().prepend('<span class="lupe"></span>');
	$('.hidden').hide();
	$('#switch-subpage1').click(function(){
		$('#subpage1').slideToggle(500);
		return false;
	});
	$("textarea").autogrow().keypress(update).mouseup(update).scroll(update);
	
	$('#uploader').click(function(event){
		if(jQuery(event.target).is("a.fillme")) {
			var file = "\n#image("+$(event.target).next().text()+")";
			insertimage(file);
			return false;
		}
	});
	
	$('#coauthors > div:not(.coauthor_set)').addClass("hidden").hide();
	
	$('#coauthors').append('<input id="addauthor" type="submit" value="Add Co-Author" class="spacetop">');
	$('#addauthor').click(function(){
		$('#coauthors > div.hidden').eq(0).removeClass('hidden').slideDown(200);
		return false;
	});
	
	// $('#imagelist').hide();
	$('#filechooser').click(function(){
		$('#imagelist').slideToggle(400);
		return false;
	});
	
	$('#imagelist').click(function(event){
	  if(event.target.className.indexOf("delete") == -1) return;
	  
		$(event.target).parent().hide(400, function(){
      jQuery(this).remove();
		return false;
		});
		return false;
	});
	
	jQuery("#uploader").swfupload();
}

/* ------------------------------------ */


function insertimage(myValue) {
	if (activeArea != false) {
		var myField = activeArea;
		//IE support
		if (document.selection) {
			myField.focus();
			sel = document.selection.createRange();
			sel.text = myValue;
		}
		//MOZILLA/NETSCAPE support
		else if (myField.selectionStart || myField.selectionStart == '0') {
			myField.focus();
			var startPos = myField.selectionStart;
			var endPos = myField.selectionEnd;
			myField.value = myField.value.substring(0, startPos)
			+ myValue
			+ myField.value.substring(endPos, myField.value.length);
		} else {
			myField.value += myValue;
		}

	} else { 
		alert('To insert an image, you must set a cursor position first!');
	}
}

function showTip(x, y) {       
	y = y-58;         
	$('#uploader').css("top", y+"px")
}

function update() {
  activeArea = this;
  var oPosition = $(this).position();
  var sContent = $(this).val();

  var bGTE = jQuery.browser.mozilla || jQuery.browser.msie;

  if ($(this).css('font-family') == 'monospace'           // mozilla
  ||  $(this).css('font-family') == '-webkit-monospace'   // Safari
  ||  $(this).css('font-family') == '"Courier New"') {    // Opera
      var lineHeight   = $(this).css('line-height').replace(/[^0-9]/g, '');
          lineHeight   = parseFloat(lineHeight);
      var charsPerLine = this.cols;
      var charWidth    = parseFloat($(this).innerWidth() / charsPerLine);


      var iChar = 0;
      var iLines = 1;
      var sWord = '';

      var oSelection = $(this).getSelection();
      var aLetters = sContent.split("");
      var aLines = [];

      for (var w in aLetters) {
          if (aLetters[w] == "\n") {
              iChar = 0;
              aLines.push(w);
              sWord = '';
          } else if (aLetters[w] == " ") {    
              var wordLength = parseInt(sWord.length);


              if ((bGTE && iChar + wordLength >= charsPerLine)
              || (!bGTE && iChar + wordLength > charsPerLine)) {
                  iChar = wordLength + 1;
                  aLines.push(w - wordLength);
              } else {                
                  iChar += wordLength + 1; // 1 more char for the space
              }

              sWord = '';
          } else if (aLetters[w] == "\t") {
              iChar += 4;
          } else {
              sWord += aLetters[w];     
          }
      }

      var iLine = 1;
      for(var i in aLines) {
          if (oSelection.end < aLines[i]) {
              iLine = parseInt(i) - 1;
              break;
          }
      }

      if (iLine > -1) {
          var x = parseInt(oSelection.end - aLines[iLine]) * charWidth;
      } else {
          var x = parseInt(oSelection.end) * charWidth;
      }
      var y = (iLine + 1) * lineHeight - this.scrollTop; // below line


      showTip(oPosition.left + x, oPosition.top + y);
  }
}


$.fn.autogrow = function(options) {

  this.filter('textarea').each(function() {
    
      var $this       = $(this),
          minHeight   = $this.height(),
          lineHeight  = $this.css('lineHeight');
    
      var shadow = $('<div></div>').css({
          position:   'absolute',
          top:        -10000,
          left:       -10000,
          width:      $(this).width() - parseInt($this.css('paddingLeft')) - parseInt($this.css('paddingRight')),
          fontSize:   $this.css('fontSize'),
          fontFamily: $this.css('fontFamily'),
          lineHeight: $this.css('lineHeight'),
          resize:     'none'
      }).appendTo(document.body);
    
      var update = function() {

          var times = function(string, number) {
              var _res = '';
              for(var i = 0; i < number; i ++) {
                  _res = _res + string;
              }
              return _res;
          };
        
          var val = this.value.replace(/</g, '&lt;')
                              .replace(/>/g, '&gt;')
                              .replace(/&/g, '&amp;')
                              .replace(/\n$/, '<br/>&nbsp;')
                              .replace(/\n/g, '<br/>')
                              .replace(/ {2,}/g, function(space) { return times('&nbsp;', space.length -1) + ' ' });
        
          shadow.html(val);
          $(this).css('height', Math.max(shadow.height() + 20, minHeight));
    
      }
    
      $(this).change(update).keyup(update).keydown(update);
    
      update.apply(this);
    
  });

  return this;

}


jQuery.fn.swfupload = function(options) {
  if(this.length == 0) return;
  
	_this = jQuery(this);
	
	options = options || {	};
	
	var trigger = this.find("input[type=submit]");
	
	swfu = new SWFUpload({
		upload_url: "/esho2009/upload.php",
		file_size_limit: "20MB",
		file_types: "*.*",
		flash_url: "/esho2009/js/SWFUpload/Flash/swfupload.swf",
		
		post_params: {"PHPSESSID" : UPLOAD_SESSION},
		
		// Button Settings
		button_image_url : "/esho2009/js/SWFUpload/XPButtonUploadText_61x22.png",	// Relative to the SWF file
		button_placeholder_id : "filechooser",
		button_width: 61,
		button_height: 22,
		button_action : SWFUpload.BUTTON_ACTION.SELECT_FILE,    
		
		
		file_queue_limit : "10",
		file_upload_limit : "10",
		
		// Backend settings
    file_post_name: "images",

		// Flash file settings
		file_types_description : "Choose Images Files",

		// Event handler settings
		swfupload_loaded_handler : swfUploadLoaded,
		
		file_dialog_start_handler: fileDialogStart,
		file_queued_handler : fileQueued,
		file_queue_error_handler : fileQueueError,
		file_dialog_complete_handler : fileDialogComplete,
		
		//upload_start_handler : uploadStart,	// I could do some client/JavaScript validation here, but I don't need to.
		upload_progress_handler : uploadProgress,
		upload_error_handler : uploadError,
		upload_success_handler : uploadSuccess,
		upload_complete_handler : uploadComplete,


		custom_settings : {
			progress_target : "fsUploadProgress",
			upload_successful : false
		},
		
		// Debug settings
		debug: false
	});

	return this;
};