/*****************************************************************************\
* commonFunction.js     Various functions from phpBB's pages pulled together
*                       one file.
 *****************************************************************************
* 01.04.2005   J.Tremmel    cleanup
* 10.06.2005   J.Tremmel    added newer scripts of mod "super quick reply"
* 12.06.2005   J.Tremmel    fixed emoticon insert (at caret position) for
*                           Mozilla browsers
* 23.03.2006   J.Tremmel    added code snippet for admin user list
* 09.10.2006   J.Tremmel    added shrinkOversizedImages()
* 18.12.2009   J.Tremmel    quick workaround for annoying IE misbehaviour
*                           with existing caret positioning code
\*****************************************************************************/
addLoadEvent( shrinkOversizedImages );
function shrinkOversizedImages() {
  var imgs = document.images;
  for (i = 0; i < imgs.length; i++) {
    if (imgs[i].width > 800) {
       imgs[i].onclick = toggleSize
       toggleImageSize(imgs[i]);
    }
  }
}

/**
* Toggles the size of the given image between 100% and <= 640px width
* Parameters: image   -   an image object
* Returns: -
*/
function toggleImageSize(image) { //{{{
  if (!image.width) { return; }
  if (typeof image.origWidth == 'undefined') {
    image.origWidth  = image.width;
    image.origHeight = image.height;
    image.shrinkFactor = Math.ceil(image.origWidth / 640);

    image.className = [image.className, 'toggleSize'].join(' ');
  }
  if (image.width == image.origWidth) {
    image.width = image.origWidth / image.shrinkFactor ;
    image.height = image.origHeight / image.shrinkFactor ;
    image.title = "vergrößern ("+image.origWidth+"x"+image.origHeight+")";
  } else {
    image.width   = image.origWidth;
    image.height  = image.origHeight;
    image.title = "verkleinern (1/"+image.shrinkFactor+")";
  }
  //}}}
}
function toggleSize() { toggleImageSize(this); return false; }

/**
* bbCode control by
* subBlue design
* www.subBlue.com
*/
// Startup variables
var imageTag = false;
var theSelection = false;
// Check for Browser & Platform for PC & IE specific bits
// More details from: http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html
var clientPC = navigator.userAgent.toLowerCase(); // Get client info
var clientVer = parseInt(navigator.appVersion);   // Get browser version

var is_ie   = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
var is_win   = ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));

// Helpline messages
// variables will get filled w/ parsed-in values (L10N'd)
// in posting_body.tpl and viewtopic_quickreply.tpl [mod_sqr])
var b_help, i_help, u_help, q_help,
    c_help, l_help, o_help, p_help,
    w_help, a_help, s_help, f_help;
// "empty fields" message
var _formErrorsMessage;

// Define the bbCode tags
bbcode = new Array();
bbtags = new Array(
  '[b]','[/b]','[i]','[/i]','[u]','[/u]',
  '[quote]','[/quote]','[code]','[/code]',
  '[list]','[/list]','[list=]','[/list]',
  '[img]','[/img]','[url]','[/url]'
);


/**
* Shows the help messages in the helpline window
*/
function helpline(help) {
  document.post.helpbox.value = eval(help + "_help");
}

/**
* Replacement for arrayname.length property
*/
function getarraysize(thearray) { //{{{
  for (i = 0; i < thearray.length; i++) {
    if ((thearray[i] == "undefined") || (thearray[i] == "") || (thearray[i] == null))
      return i;
    }
  return thearray.length;
  //}}}
}

/**
* Replacement for arrayname.push(value) not implemented in IE until version 5.5
* Appends element to the array
*/
function arraypush(thearray,value) { //{{{
  thearray[ getarraysize(thearray) ] = value;
  //}}}
}

/**
* Replacement for arrayname.pop() not implemented in IE until version 5.5
* Removes and returns the last element of an array
*/
function arraypop(thearray) { //{{{
  thearraysize = getarraysize(thearray);
  retval = thearray[thearraysize - 1];
  delete thearray[thearraysize - 1];
  return retval;
  //}}}
}

/**
* Checks if the message textarea is filled
*/
function checkForm() { //{{{
  formErrors = false;
  if (document.post.message.value.length < 2) {
    formErrors = _formErrorsMessage
  }

  if (formErrors) {
    alert(formErrors);
    return false;
  } else {
    bbstyle(-1);
    //formObj.preview.disabled = true;
    //formObj.submit.disabled = true;
    return true;
  }
  //}}}
}

/**
*
*/
function bbfontstyle(bbopen, bbclose) { //{{{
  var txtarea = document.post.message;
  if ((clientVer >= 4) && is_ie && is_win) {
    theSelection = document.selection.createRange().text;
    if (!theSelection) {
      txtarea.value += bbopen + bbclose;
      txtarea.focus();
      return;
    }
    document.selection.createRange().text = bbopen + theSelection + bbclose;
    txtarea.focus();
    return;
  } else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0)) {
    mozWrap(txtarea, bbopen, bbclose);
    txtarea.focus();
    return;
  } else {
    // fall-back: just add both bbtags at the end
    txtarea.value += bbopen + bbclose;
    txtarea.focus();
  }
  storeCaret(txtarea);
  //}}}
}

/**
*
*/
function bbstyle(bbnumber) { //{{{
  var txtarea = document.post.message;
  txtarea.focus();
  donotinsert = false;
  theSelection = false;
  bblast = 0;

  if (bbnumber == -1) { // Close all open tags & default button names
    while (bbcode[0]) {
      butnumber = arraypop(bbcode) - 1;
      txtarea.value += bbtags[butnumber + 1];
      buttext = eval('document.post.addbbcode' + butnumber + '.value');
      eval('document.post.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
    }
    imageTag = false; // All tags are closed including image tags :D
    txtarea.focus();
    return;
  }

  if ( (clientVer >= 4) && is_ie && is_win ) {
    theSelection = document.selection.createRange().text; // Get text selection
    if (theSelection) {
      // Add tags around selection
      document.selection.createRange().text = bbtags[bbnumber] + theSelection + bbtags[bbnumber+1];
      txtarea.focus();
      theSelection = '';
      return;
    }
  } else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0)) {
    mozWrap(txtarea, bbtags[bbnumber], bbtags[bbnumber+1]);

    return;
  }

  // Find last occurance of an open tag the same as the one just clicked
  for (i = 0; i < bbcode.length; i++) {
    if (bbcode[i] == bbnumber+1) {
      bblast = i;
      donotinsert = true;
    }
  }

  if (donotinsert) {		// Close all open tags up to the one just clicked & default button names
    while (bbcode[bblast]) {
        butnumber = arraypop(bbcode) - 1;
        txtarea.value += bbtags[butnumber + 1];
        buttext = eval('document.post.addbbcode' + butnumber + '.value');
        eval('document.post.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
        imageTag = false;
      }
      txtarea.focus();
      return;
  } else { // Open tags

    if (imageTag && (bbnumber != 14)) {		// Close image tag before adding another
      txtarea.value += bbtags[15];
      lastValue = arraypop(bbcode) - 1;	// Remove the close image tag from the list
      document.post.addbbcode14.value = "Img";	// Return button back to normal state
      imageTag = false;
    }

    // Open tag
    txtarea.value += bbtags[bbnumber];
    if ((bbnumber == 14) && (imageTag == false)) imageTag = 1; // Check to stop additional tags after an unclosed image tag
    arraypush(bbcode,bbnumber+1);
    eval('document.post.addbbcode'+bbnumber+'.value += "*"');
    txtarea.focus();
    return;
  }
  storeCaret(txtarea);
  //}}}
}


/**
* Wraps the current selection in "open" and "close" tag strings
* (for Mozilla browsers).
* From http://www.massless.org/mozedit/
*/
function mozWrap(txtarea, open, close) { //{{{
  var selLength = txtarea.textLength;
  var selStart  = txtarea.selectionStart;
  var selEnd    = txtarea.selectionEnd;
  if (selEnd == 1 || selEnd == 2) {
    selEnd = selLength;
  }
  var s1 = (txtarea.value).substring(0,selStart);
  var s2 = (txtarea.value).substring(selStart, selEnd)
  var s3 = (txtarea.value).substring(selEnd, selLength);
  txtarea.value = s1 + open + s2 + close + s3;
  return;
  //}}}
}

/**
* Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1052/fid/130
*/
function storeCaret(textEl) { //{{{
  //if (textEl.createTextRange) {
  //  textEl.caretPos = document.selection.createRange().duplicate();
  //}
  //}}}
}


/**
* Inserts text (at caret position if possible) into
* the "message input" textarea
*
* Parameters:   text  -  text string to insert
* Returns: -
*
* Used in     posting_body.tpl
*             posting_smilies.tpl
*             viewtopic_quickreply.tpl (mod_sqr)
*/
function emoticon(text) { //{{{
  text = ' ' + text + ' ';
  // determine target document for insert operation:
  // opener.document for "additional smilies"-popup (posting_smilies.tpl)
  // document        for normal "post reply"-page and for mod_sqr
  targetDoc = ( (opener && opener.document.forms['post']) ? opener.document : document);
  var txtarea = targetDoc.forms['post'].message;
  if (!txtarea) { return; }

  //if (txtarea.createTextRange && txtarea.caretPos) {
  if (document.selection && txtarea.createTextRange) {
      // IE-style caret position access
      //var caretPos = txtarea.caretPos;
      txtarea.focus();
      var caretPos = document.selection.createRange().duplicate();

      // replace current selection (if any) w/ text:
      caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;

    } else if (typeof(txtarea.selectionStart) != 'undefined') {
      // Mozilla-style caret position access
      var startPos  = txtarea.selectionStart;
      var endPos    = txtarea.selectionEnd;
      // replace current selection (if any) w/ text:
      txtarea.value = txtarea.value.substring(0, startPos)
                    + text
                    + txtarea.value.substring(endPos, txtarea.value.length);
      // place cursor after inserted text
      txtarea.selectionStart = txtarea.selectionEnd = endPos + text.length;

    } else {
      // fall-back: Just append emoticon to the end...
      txtarea.value  += text;
    }
    txtarea.focus();
  //}}}
}

/**
* Selects/deselects all checkboxes
*
* Parameters:   status    -   new status for "checked"
* Returns: -
*
* Used in       uacp_body.tpl
*               admin/attach_cp_attachments.tpl
*               privmsgs_body.tpl
*               admin/attach_shadow.tpl [mod_attach]
*/
function select_switch(status) { //{{{
  //  uacp_body.tpl, admin/attach_cp_attachments.tpl
  if (document.attach_list) {
    for (i = 0; i < document.attach_list.length; i++) {
      document.attach_list.elements[i].checked = status;
    }
  }
  // privmsgs_body.tpl
  if (document.privmsg_list) {
    for (i = 0; i < document.privmsg_list.length; i++) {
      document.privmsg_list.elements[i].checked = status;
    }
  }
  // admin/attach_shadow.tpl
  if (document.shadow_list) {
    for (i = 0; i < document.shadow_list.length; i++) {
      document.shadow_list.elements[i].checked = status;
    }
  }
  //}}}
}

/**
* Toggles display of Quick Reply form [mod_sqr]
*/
function sqr_show_hide() { //{{{
  var id = 'sqr';
  var item = null;
  if (document.getElementById)   {
    item = document.getElementById(id);
  } else if (document.all) {
    item = document.all[id];
  } else if (document.layers) {
    item = document.layers[id];
  }

  if (item && item.style) {
    if (item.style.display == "none") {
      item.style.display = "";
    } else {
      item.style.display = "none";
    }
  } else if (item) {
    item.visibility = "show";
  }
  //}}}
}


/** Toggles display of user info [mod_admin_user_list] */
function aul_toggleUser(id) { return toggleDisplay(id); }
/** Toggles display of search data [mod searchdata] */
function sd_toggle(id)      { return toggleDisplay(id); }

/**
* Toggles display of the supplied object
*/
function toggleDisplay(id) { //{{{
  try {
    style = document.getElementById(id).style;
    style.display = (style.display != 'none' ? 'none' : '');
  } catch(e) {
    return 1;
  }
  //}}}
}

/**
* search_username.tpl
*/
function refresh_username(selected_username) { //{{{
  opener.document.forms['post'].username.value = selected_username;
  try { opener.focus(); } catch(e) {}
  try { window.close(); } catch(e) {}
  //}}}
}

/**
* Safely adds a load event to the window.onload handler
* See: http://simon.incutio.com/archive/2004/05/26/addLoadEvent
* NOTE: A direct <body onload="..."> assignment will overwrite everything!
*/
function addLoadEvent( func ) { //{{{
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() { oldonload(); func(); }
  }
  //}}}
}



