
/**
* Toggles the label on the posting form "submit" button.
*/
function toggleSubmitLabel(){

  submit_button = document.getElementById('posting_submit');
  submit_label = document.getElementById('submit_label_storage').value;
  preview_toggle = document.getElementById('preview_toggle');
  
  if(preview_toggle.checked == true){
    submit_button.value = "Preview This Post";
  } else {
    submit_button.value = submit_label;
  }

}

/**
* Inserts an emoticon into the posting form.
*/
function insertEmoticon(code){
  
  insertFormatting(code);

}

/**
* Gets the current cursor position in the posting form.
*/
function getCaretPosition(){
  var posting_content = document.getElementById("posting_content");
	var CaretPos = 0;	
  // If IE - IE is terrible.  Let this have crippled functionality and just return the length if IE.  SHAME ON MICROSOFT!!!
	if (document.selection){
    CaretPos = posting_content.value.length;
	}
	// If Firefox
	else if (posting_content.selectionStart || posting_content.selectionStart == '0'){
		CaretPos = posting_content.selectionStart;
  }
	return (CaretPos);
}

/**
* Sets the current cursor position in the posting form.
*/
function setCaretPosition(pos){
  var posting_content = document.getElementById("posting_content");
	if(posting_content.setSelectionRange)
	{
		posting_content.focus();
		posting_content.setSelectionRange(pos,pos);
	}
	else if (posting_content.createTextRange) {
		var range = posting_content.createTextRange();
		range.collapse(true);
		range.moveEnd('character', pos);
		range.moveStart('character', pos);
		range.select();
	}
}

/**
* Inserts formatting code around selected text in the posting form textarea.
*/
function insertFormatting(code){ 

  var posting_content = document.getElementById("posting_content");
  var begin;
  var selection;
  var end;
  var textselected = false;
  
  // Get the current cursor position;
  var cursor_position = getCaretPosition();
  
  if(navigator.userAgent.toLowerCase().indexOf("firefox") > 0){ 
    if (posting_content.selectionStart != undefined) {  
      begin = posting_content.value.substr(0, posting_content.selectionStart);  
      selection = posting_content.value.substr(posting_content.selectionStart, posting_content.selectionEnd - posting_content.selectionStart);  
      end = posting_content.value.substr(posting_content.selectionEnd); 
      if (selection.length > 0){ 
        textselected = true; 
      } 
    } 
  } else { 
    if (window.getSelection){ 
      selection = window.getSelection(); 
    } else if (document.getSelection){ 
      selection = document.getSelection(); 
    } else if (document.selection){ 
      selection = document.selection.createRange().text; 
    } 
    var startPos = posting_content.value.indexOf(selection); 
    if(startPos >= 0){ 
      var endPos = posting_content.value.indexOf(selection) + selection.length; 
      begin = posting_content.value.substr(0,startPos); 
      end = posting_content.value.substr(endPos, posting_content.value.length);
      if(selection.length > 0){
        textselected = true;
      }
    } 
  }
  
  switch (code){ 

    case "b":
      startTag = "[b]";
      endTag = "[/b]";
    break;

    case "i":
      startTag = "[i]";
      endTag = "[/i]";
    break;

    case "link":
      startTag = "[link]";
      endTag = "[/link]";
    break;
    
    case "image":
      startTag = "[image]";
      endTag = "[/image]";
    break;
    
    case "quote":
      startTag = "[quote]";
      endTag = "[/quote]";
    break;
    
    default:
      startTag = code;
      endTag = '';
    break;
         
  }  
  
  if(textselected == true){     
    // Add formatting / tags around current selection
    posting_content.value = begin + startTag + selection + endTag + end;
    posting_content.focus();
    setCaretPosition(cursor_position + startTag.length + selection.length + endTag.length);
  } else if(cursor_position >= 0){
    cursor_position = parseInt(cursor_position);
    // Add formatting / tags at current cursor position.
    begin = posting_content.value.substr(0,cursor_position); 
    end = posting_content.value.substr(cursor_position, posting_content.value.length);
    posting_content.value = begin + startTag + endTag + end;
    posting_content.focus();
    setCaretPosition(cursor_position + startTag.length + endTag.length);
  } else {
    // Add formatting / tags at end of posting content
    posting_content.value = posting_content.value + startTag + endTag;
    posting_content.focus();
  }
} 

// Be sure to include ajax.js in the HTML <head> section!

//Set the interval for the autoSave on the posting screen.
var asinterval = 10000;  // Every ten seconds.
var as_min_length = 5; // Minimum length, in characters, to trigger autosave.

// Set the interval for refreshing the chat screen.
var chatRefreshInterval = 10000; // Every ten seconds.

//formats minues and seconds to have leading zeros
function checkTime(i){
  if(i<10){
    i = "0" + i;
  }
  return i;
}

// Gets and displays the time
function getAutoSaveTime(){
  var thetime = new Date();
  var h = thetime.getHours();
  var m = thetime.getMinutes();
  var s = thetime.getSeconds();
  m = checkTime(m);
  s = checkTime(s);
  return h + ':' + m + ':' + s;
}

// Double-encodes data for sending via AJAX.  For some reason this has to be done.
function doubleURIEncode(x){
  x = encodeURIComponent(x);
  x = encodeURIComponent(x);
  return x;
}

var previous_autosave = ''; // Place to compare current with previous auto-save.
var chat_post_limit = 255; // Maximum length of a chat post.  Also set in config file.

// Sends a chat message.
function sendChat(){
  o = document.getElementById('posting_content');
  if((o.value.length > 0) && (o.value != "")){
    var url = "ajax";
    data = 'mode=send_chat&content=' + doubleURIEncode(o.value.substring(0,chat_post_limit));
    try{
      var response = AJAX(url,data,false);
    } catch(e) {
      return ajaxError(e);
    }
    setTimeout("refreshChat()",100);
  }
  o.value = '';
  setTimeout("setCaretPosition(0)",100);
}

// Refreshes the chat list.
function refreshChat(){
  o = document.getElementById('chat_list');
  getData('mode=get_chat','chat_list');
  o.scrollTop = o.scrollHeight;
}

// Prevents typing past the chat message limit.
function limitChat(e){
  o = document.getElementById('posting_content');
  var chatLength = o.value.length;
  if(chatLength > chat_post_limit){
    o.value = o.value.substring(0,chat_post_limit);
  }
  if(e.keyCode == 13){
    sendChat();
  }
}

// Records autosave.
function autoSave(){
  posting_content = document.getElementById('posting_content').value;
  if((posting_content.length >= as_min_length) && (posting_content != previous_autosave)){ // Do not auto-save if content is under a certain length threshold, or exactly the same as the previous auto-save. (or empty).
    var url = "ajax";
    data = 'mode=autosave&content=' + doubleURIEncode(document.getElementById('posting_content').value);
    try{
      var response = AJAX(url,data,false); 
      // Display the time of the most recent autosave      
      document.getElementById('autosave_info').innerHTML = "last save at " + getAutoSaveTime();
      previous_autosave = posting_content;
    } catch(e) {
      return ajaxError(e);  
    }
  }
}

// If on the posting screen, autoSave every x seconds (specified in 'asinterval' variable, above)
// Do not auto-save if the current content is less than a certain length (specified in as_min_length, above)
function autoSaveLoop(){
	if(document.getElementById('posting_content')){
		setInterval("autoSave()", asinterval);
	}
}

function refreshChatLoop(){
  setInterval("refreshChat()", chatRefreshInterval);
}

// Retrieves the data from auto-save.
function retrieveAutoSave(){
  getData('mode=autosave_retrieve','posting_content');
  document.getElementById('autosave_info').innerHTML = "autosave retrieved at " + getAutoSaveTime();
}

// Inserts a quote from a previous post in the thread.
function quotePost(username,quote_post_id){
  posting_content = document.getElementById('posting_content');
  var quote = '';
  var content = '';
  content = document.getElementById('quote_post_' + quote_post_id).innerHTML;
  quote = "[i]" + username + " said:[/i]\n[quote]" + content + "[/quote]\n";
  posting_content.value = posting_content.value + quote;
}

function trim(s) {
	return s.replace(/^\s+|\s+$/g,"");
}

// Calculates character and word counts in posting screen.
function getCounts(){
  posting_content = document.getElementById('posting_content').value;
  var wordcount = posting_content.split(/\s+/).length;
  var charcount = posting_content.length;
  var text = '';
  text = "Character Count: " + charcount + " - Word Count: " + wordcount;
  document.getElementById('posting_stats').innerHTML = text;
}

// Gets the time of day from the server.
function getUserTime(){
  getData('mode=get_user_time','user_time_display');
}

// Sets the user's time display once per minute to accurately reflect the server time (adjusted to their time zone).
function getUserTimeLoop(){
	if(document.getElementById('user_time_display')){
		setInterval("getUserTime()", 60000);
	}
}

// Refreshes the "Who Is Online" area.
function getWhoIsOnline(){
  getData('mode=who_is_online','who_is_online');
}

// Refreshes the "Who is Online" area once every two minutes.
function getWhoIsOnlineLoop(){
	if(document.getElementById('user_time_display')){
		setInterval("getWhoIsOnline()", 120000);
	}
}

// Confirms a deletion action
function deletePost(url){
  var choice = confirm('Are you sure you want to delete this post?');
  if(choice){
    parent.location = url;
  }
}

// Confirms a deletion action
function deleteThread(url){
  var choice = confirm('Are you sure you want to delete this entire thread?');
  if(choice){
    parent.location = url;
  }
}

// Confirms a deletion action
function deletePM(url){
  var choice = confirm('Are you sure you want to delete this message?');
  if(choice){
    parent.location = url;
  }
}

// Toggles the enhanced (larger) view in image posts inside threads.
function enhanceView(o){
  var views = o.getAttribute("rel").split('|');
  var larger_view_url = views[0];
  var thumbnail_url = views[1];
  if(o.childNodes[0].src == thumbnail_url){
    o.childNodes[0].src = larger_view_url;
  } else {
    o.childNodes[0].src = thumbnail_url;
  }
}

function textLarger(post_id){
  var o = document.getElementById('post_' + post_id);
  var text_size = parseInt(o.style.fontSize) + 2;
  if(text_size <= 24){
    o.style.fontSize = text_size + 'px';
  }
}

function textSmaller(post_id){
  var o = document.getElementById('post_' + post_id);
  var text_size = parseInt(o.style.fontSize) - 2;
  if(text_size >= 8){
    o.style.fontSize = text_size + 'px';
  }
}

function showHidePost(post_id){
  var o = document.getElementById("post_row_" + post_id);
  if(o.style.display == "table-row"){
    o.style.display = "none";
  } else {
    o.style.display = "table-row";
  }
}

var chatWindowOpen = false;

function showChatBox(){
  var o = '';
  o += "<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0\" width=\"160\" height=\"140\" id=\"chatbox\" align=\"middle\" wmode=\"transparent\" >\n";
	o += "<param name=\"allowScriptAccess\" value=\"sameDomain\" />\n";
	o += "<param name=\"allowFullScreen\" value=\"false\" />\n";
  o += "<param name=\"wmode\" value=\"transparent\" />\n";
	o += "<param name=\"movie\" value=\"swf/chatbox.swf\" /><param name=\"quality\" value=\"high\" />";
  o += "<embed src=\"swf/chatbox.swf\" quality=\"high\" wmode=\"transparent\" width=\"160\" height=\"140\" name=\"chatbox\" align=\"middle\" allowScriptAccess=\"sameDomain\"";
  o += "allowFullScreen=\"false\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.adobe.com/go/getflashplayer\" />\n";
	o += "</object>\n";
  if(!chatWindowOpen){
    document.getElementById('chatbox').style.display = "block";
    document.getElementById('chatbox').innerHTML = o;
    document.getElementById('chat_window_icon').src = "images/buttons/chat_window_icon.gif";
  } else {
    document.getElementById('chatbox').style.display = "none";
    document.getElementById('chat_window_icon').src = "images/buttons/chat_box_icon.gif";
  }
}

function toggleChatWindow(){
  if(!chatWindowOpen){
    var bases = document.getElementsByTagName("base");
    var base_href = bases[0].href;    
    chatWindow = window.open(base_href + "/swf/chatwin.html","chatWindow","status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,scrollbars=0,height=300,width=550");
    document.getElementById("chatbox").style.display = "none";
    document.getElementById('chat_window_icon').src = "images/buttons/chat_box_icon.gif";
    chatWindowOpen = true;
  }
}

var drawingInterface; // Reference to the drawing interface, if onscreen.

function showDrawingInterface(){
  var o = '';
  o += "<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0\" id=\"oekaki_object\" name=\"oekaki_object\" align=\"middle\">";
	o += "<param name=\"allowScriptAccess\" value=\"always\" />";
	o += "<param name=\"allowFullScreen\" value=\"false\" />";
  o += "<param name=\"wmode\" value=\"transparent\" />\n";
	o += "<param name=\"movie\" value=\"swf/oekaki.swf\" />";
  o += "<param name=\"quality\" value=\"high\" />";
  o += "<embed src=\"swf/oekaki.swf\" quality=\"high\" wmode=\"transparent\" name=\"oekaki_embed\" id=\"oekaki_embed\" align=\"middle\" allowScriptAccess=\"always\" ";
  o += "allowFullScreen=\"false\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.adobe.com/go/getflashplayer\" />";
	o += "</object>";
  document.getElementById('drawing_interface_container').innerHTML = o;
  // Set up the reference to the drawing interface Flash object, based on if IE or Standards-compliant browser.
  if(document.getElementById('oekaki_embed')){
    drawingInterface = document.getElementById('oekaki_embed');
  } else if(document.getElementById('oekaki_object')){
    drawingInterface = document.getElementById('oekaki_object');
  }
}

// This function will grab the drawing from the Flash-based drawing interface and submit the drawing / posting form.
function postDrawing(){
  document.getElementById('drawing_image_png_data').value = drawingInterface.getDrawingImage();
  document.getElementById('form_posting_form').submit();
}

// Helper functions for hexidecimal - decimal conversion.
function dec2hex(d) {return d.toString(16);}
function hex2dec(h) {return parseInt(h,16);} 

// Generates the drawing controls for the sidebar in the drawing interface screen.
function showDrawingControls(){
  var o = '';
  // Brush Size Menu
  o += "<label for=\"brush_size\">Brush Size</label>\n";
  o += "<select id=\"brush_size\" onchange=\"drawingInterface.setBrushSize(this.value);\">\n";
  for(i=1;i<=20;i++){
    o += "<option value=\"" + i + "\">" + i + "</option>\n";  }  
  o += "</select>\n";
  // Tools
  o += "<label for=\"drawing_tools\">Tools</label>\n";
  o += "<div class=\"formatting_buttons\">\n";
  o += "<button class=\"button\" onclick=\"drawingInterface.setBrushTool();\">Brush</button>\n";
  o += "<button class=\"button\"onclick=\"drawingInterface.setEraserTool();\">Eraser</button>\n";
  o += "<button class=\"button\"onclick=\"drawingInterface.setFillTool();\">Fill</button>\n";
  o += "<button class=\"button\"onclick=\"drawingInterface.undoTool();\">Undo</button>\n";
  o += "<button class=\"button\"onclick=\"clearDrawing();\">Clear</button>\n";
  o += "</div><br />\n";   
  o += "<label for=\"current_color_indicator\">Current Color</label>\n";
  o += "<div id=\"current_color_indicator\" style=\"background-color: #000000;\"></div>\n";
  // Flash object for HSB sliders, etc.
  o += "<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0\" id=\"oekaki_controls_object\" name=\"oekaki_controls_object\" align=\"middle\">";
	o += "<param name=\"allowScriptAccess\" value=\"always\" />";
	o += "<param name=\"allowFullScreen\" value=\"false\" />";
  o += "<param name=\"wmode\" value=\"transparent\" />\n";
	o += "<param name=\"movie\" value=\"swf/oekaki_controls.swf\" />";
  o += "<param name=\"quality\" value=\"high\" />";
  o += "<embed src=\"swf/oekaki_controls.swf\" quality=\"high\" wmode=\"transparent\" name=\"oekaki_controls_embed\" id=\"oekaki_controls_embed\" align=\"middle\" allowScriptAccess=\"always\" ";
  o += "allowFullScreen=\"false\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.adobe.com/go/getflashplayer\" />";
	o += "</object><br /><br />";
  o += "<label for=\"color_picker\">Colors</label>\n";
  // Generate color picker table. 16777216 341
  o += "<table id=\"color_picker\" class=\"color_picker\">\n";
  var total_colors = 16777216;
  var width = 18;
  // Greyscale Swatches.
  o += "<tr>"
  for(i=0;i<256;i+=15){
    colorvalue = dec2hex(i) + dec2hex(i) + dec2hex(i);
    o += makeColorSwatch(colorvalue);
  }
  o += "</tr>\n";
  for(i=0;i<total_colors;i=i){
    o += "<tr>\n";
    for(k=0;k<width;k++,i+=Math.round(total_colors / 327)){
      colorvalue = dec2hex(i);
      // Pad the color value to make it a valid hex color code
      for(p=colorvalue.length;p<6;p++){
        colorvalue = '0' + colorvalue;
      }
      if(i < total_colors){
        o += makeColorSwatch(colorvalue);
      }
    }
    o += "</tr>\n";
  }
  // Black and white swatches.
  o += "<tr>" + makeColorSwatch('FFFFFF') + makeColorSwatch('000000') + "</tr>\n";
  o += "</table>\n";
  document.getElementById('drawing_controls_container').innerHTML = o;
}

function makeColorSwatch(colorvalue){
  return "<td style=\"background-color: #" + colorvalue + ";\" title=\"Set Color: #" + colorvalue + "\" onclick=\"setColor('" + colorvalue + "');\"></td>\n";
}

function clearDrawing(){
  if(confirm("Are you sure you want to clear your drawing and start over?")){
    drawingInterface.clearDrawing();
  }
}

function setColor(colorvalue){
  document.getElementById('current_color_indicator').style.backgroundColor = '#' + colorvalue;
  drawingInterface.setColor(colorvalue);
}


