/***************************************************************************
*        Developer: Atom Ltd
*        Copyright: (C)2009 http://www.atom-mc.com
*        Copyright: (C)2009 http://www.coach-assistant.com
*
*        The Software is a copyrighted work of authorship and is protected by
*        applicable national and international laws and/or contains proprietary
*        information protected by law.
*
*        Contact support@coach-assistant.com if any conditions are not clear.
*
*        This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
*        THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
*        PURPOSE. This and all others in the download package can only be
*        redistributed with written permission from Atom Ltd!
*
*        You may run one instance (a single installation) of the Software
*        on one Server and one Web site on one domain. For each installed
*        instance of the Software, a separate license is required.
*
***************************************************************************/


function HideContent(d) {
  document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
  document.getElementById(d).style.display = "block";
}
function ReverseDisplay(d)
{
  if(document.getElementById(d).style.display == "none")
    document.getElementById(d).style.display = "block";
  else
    document.getElementById(d).style.display = "none";
}



function toggleBox(szDivID, iState) // 1 visible, 0 hidden
{
   var obj = document.layers ? document.layers[szDivID] :
   document.getElementById ?  document.getElementById(szDivID).style :
   document.all[szDivID].style;
   obj.visibility = document.layers ? (iState ? "show" : "hide") :
   (iState ? "visible" : "hidden");
}


function insertQuote(username)
{
  var username_str='';
  if(username!='undefined' && username!=undefined) {
    username_str = '='+username+'';
  }

  var sel_text = getSelectedText();

  if(document.getElementById('alien_new_reply_hidden')) {
    document.getElementById('alien_new_reply_hidden').style.display='block';

    if(document.getElementById('post_text')) {
      var NewLine = "";
      var Text = document.getElementById('post_text').value;
      if(Text && Text != '') {
        NewLine = "\n";
      }
      document.getElementById('post_text').value = Text + NewLine + "[quote" + username_str + "]" + sel_text + "[/quote]";
      document.getElementById('post_text').focus();
    }
  }
}

function getSelectedText()
{
  var selection = '';
  if (window.getSelection)
  {
      selection = window.getSelection().toString();
  }
  else if (document.getSelection)
  {
      selection = document.getSelection();
  }
  else if (document.selection)
  {
      selection = document.selection.createRange().text;
  }
  return selection;
}

//========= Functions: On load run multiple functions =========>>
window.onload = WSCOnLoadStart;

var WSCOnLoadFuncArr=new Array();
function WSCOnLoadAdd(f_name)
{
  WSCOnLoadFuncArr.push(f_name);
}

function WSCOnLoadStart()
{
  for(func_i in WSCOnLoadFuncArr)
    eval(WSCOnLoadFuncArr[func_i]);
}
//========= Functions: On load run multiple functions <<=========



// User Reputation PopUp
var alien_reputation_window;
function alien_reputation_open(alien_reputation_url)
{
  if(alien_reputation_window) alien_reputation_window.close();
  var w=450;
  var h=450;
  alien_reputation_window=window.open(alien_reputation_url,'alien_reputation','left=300,top=150,height='+h+',width='+w+',resizable=yes,scrollbars=yes')
  if(window.focus){alien_reputation_window.focus()}
}




// Community Members list PopUp
var alien_community_members_window;
function alien_community_members_open(url)
{
  if(alien_community_members_window) alien_community_members_window.close();
  var w=450;
  var h=450;
  alien_community_members_window=window.open(url,'alien_community_members','left=300,top=150,height='+h+',width='+w+',resizable=yes,scrollbars=yes')
  if(window.focus){alien_community_members_window.focus()}
}


function view_profile_open(user_id)
{
 var newwindow=window.open('wsc.php?mod=view_profile&uid='+user_id,'view_profile','height=440,width=500,resizable=no,scrollbars=yes');
 if ( newwindow.focus ) {
   newwindow.focus();
 }
}



// Attachments Managment PopUp
var alien_attach_window;
function alien_attach_open(alien_attach_url)
{
  if(alien_attach_window) alien_attach_window.close();
  var w=600;
  var h=500;
  alien_attach_window=window.open(alien_attach_url,'alien_attach','statusbar=no,left=300,top=150,height='+h+',width='+w+',resizable=yes,scrollbars=yes')
  if(window.focus){alien_attach_window.focus()}
}


function AlienPrepareText(text_to_prepare)
{
  text_to_prepare=text_to_prepare.replace(/\n/g,"<br />");
  return text_to_prepare;

}

function addNewreplyShow()
{
  if(document.getElementById('alien_new_reply_hidden').style.display=='none')
  {
    document.getElementById('alien_new_reply_hidden').style.display='block';
  }
  else
  {
    document.getElementById('alien_new_reply_hidden').style.display='none';
    //document.getElementById('reply_preview').style.display='none'
  }
}


function addNewTopicShow()
{
  if(document.getElementById('alien_new_topic_hidden').style.display=='none')
  {
    document.getElementById('alien_new_topic_hidden').style.display='block';
  }
  else
  {
    document.getElementById('alien_new_topic_hidden').style.display='none';
   // document.getElementById('topic_preview').style.display='none'
  }
}


function AlienQuickEditPost(post_id)
{
  document.getElementById('post_text_'+post_id).style.display="none";
  document.getElementById('post_text_edit_'+post_id).style.display="";
}

function AlienQuickEditPostCancel(post_id)
{
  document.getElementById('post_text_'+post_id).style.display="";
  document.getElementById('post_text_edit_'+post_id).style.display="none";
}


function expand(elem) {
    if(!elem) elem='post_text';
    e = document.getElementById(elem).style.height;
    e = parseInt(e.replace("px",""));
    if (isNaN(e)) {
        e = 150;
    }
    e += 120;
    document.getElementById(elem).style.height = e + "px";
}
function contract(elem) {
    if(!elem) elem='post_text';
    e = document.getElementById(elem).style.height;
    e = parseInt(e.replace("px",""));
    if (isNaN(e)) {
        e = 150;
    }
    if (e > 150) {
        e -= 120;
        document.getElementById(elem).style.height = e + "px";
    }
}





// The call of this function is: EqualCols('div','classname1','div','classname2');
function EqualCols(outer_tag,Outer_Class_Name,inner_tag,Inner_Class_Name)
{
  Outer_tags = document.getElementsByTagName(outer_tag);
  for(i=0;i<Outer_tags.length;i++)
  {
    Outer_Classes_Arr=Outer_tags[i].className.split(" ");
    if(IsInArray(Outer_Classes_Arr,Outer_Class_Name))
    {
      Inner_tags = Outer_tags[i].getElementsByTagName(inner_tag);
      Outer_Height=Outer_tags[i].offsetHeight;
      for(j=0;j<Inner_tags.length;j++)
      {
        Inner_Classes_Arr=Inner_tags[j].className.split(" ");
        if(!Inner_Class_Name || IsInArray(Inner_Classes_Arr,Inner_Class_Name))
        {
          Tag_Offcets =getStylePropertyValue(Inner_tags[j],'paddingTop','padding-top')+getStylePropertyValue(Inner_tags[j],'paddingBottom','padding-bottom');
          Tag_Offcets+=getStylePropertyValue(Inner_tags[j],'marginTop' ,'margin-top') +getStylePropertyValue(Inner_tags[j],'marginBottom' ,'margin-bottom');
          Inner_tags[j].style.height=(Outer_Height-Tag_Offcets)+'px';
        }
      }
    }
  }

  function IsInArray(array,value)
  {
    for(k=0;k<array.length;k++)
      if(array[k]===value) return 1;
    return 0;
  }

  function getStylePropertyValue(Object,PropertyJS,PropertyCSS)
  {
    if(Object.currentStyle) //IE
      PropertyValue = Object.currentStyle[PropertyJS];
    else if(window.getComputedStyle)
      PropertyValue = document.defaultView.getComputedStyle(Object,null).getPropertyValue(PropertyCSS);
    PropertyValue=parseInt(PropertyValue);
    if(PropertyValue=="" || isNaN(PropertyValue)) PropertyValue=0;
    return PropertyValue;
  }
}



function LimitText(LimitFieldObj, CounterFieldName, LimitNum)
{
  if(CounterFieldName==undefined) CounterFieldName = 'countdown';
  if(LimitNum==undefined || LimitNum==0) LimitNum = 300;

  if(typeof(LimitFieldObj) != 'object')
    var LimitFieldObj = document.getElementById(LimitFieldObj);
  var CounterDisplay = document.getElementById(CounterFieldName);
  if (LimitFieldObj.value.length > LimitNum) {
    LimitFieldObj.value = LimitFieldObj.value.substring(0, LimitNum);
    CounterDisplay.value = 0;
  } else {
    CounterDisplay.value = LimitNum - LimitFieldObj.value.length;
  }
}

//================= BBCode =====================







var imageTag=false;
//var theSelection=false;
var BBCodeTextAreaElem=0;
var clientPC=navigator.userAgent.toLowerCase();
var clientVer=parseInt(navigator.appVersion);
var is_ie=((clientPC.indexOf("msie")!=-1)&&(clientPC.indexOf("opera")==-1))
var is_nav=((clientPC.indexOf('mozilla')!=-1)&&(clientPC.indexOf('spoofer')==-1)&&(clientPC.indexOf('compatible')==-1)&&(clientPC.indexOf('opera')==-1)&&(clientPC.indexOf('webtv')==-1)&&(clientPC.indexOf('hotjava')==-1))
var is_moz=0
var is_win=((clientPC.indexOf("win")!=-1)||(clientPC.indexOf("16bit")!=-1))
var is_mac=(clientPC.indexOf("mac")!=-1)
b_help="Bold text: [b]text[/b]  (alt+b)"
i_help="Italic text: [i]text[/i]  (alt+i)"
u_help="Underline text: [u]text[/u]  (alt+u)"
q_help="Quote text: [quote]text[/quote]  (alt+q)"
c_help="Code display: [code]code[/code]  (alt+c)"
p_help="Insert image: [img]http://image_url[/img]  (alt+p)"
w_help="Insert URL: [url]http://url[/url] or [url=http://url]URL text[/url]  (alt+w)"
a_help="Close all open bbCode tags"
s_help="Font color: [color=red]text[/color]  Tip: you can also use color=#FF0000"
f_help="Font size: [size=x-small]small text[/size]"
s_help="Show/Hide Smiles"
y_help="Insert YouTube video: [YTube] Full URL to video[/YTube]"
intro_help="Intro: [intro]some text[/intro] will be shown in list (alt+n)"
h_help="Text displayed only for registred users: [hide]some text[/hide] (alt+h)"
rt_help="Insert RuTube video:  [RuTube] Full URL to video [/RuTube]"
ms_help="Insert MySpace video: [MySpace] Full URL to video [/MySpace]"
gv_help="Insert Google video:   [GoogleVid] Full URL to video [/GoogleVid]"
yhv_help="Insert Yahoo video:  [YahooVid] Full URL to video [/YahooVid]  "
mflv_help="Insert FLV videos uploaded by FTP:  [MyFLV] file name [/MyFLV]  "


bbcode=new Array()
bbtags=new Array('[b]','[/b]','[i]','[/i]','[u]','[/u]','[quote]','[/quote]','[code]','[/code]','[YTube]','[/YTube]','[list=]','[/list]','[img]','[/img]','[url]','[/url]','[intro]','[/intro]','[hide]','[/hide]','[RuTube]','[/RuTube]','[MySpace]','[/MySpace]','[GoogleVid]','[/GoogleVid]','[YahooVid]','[/YahooVid]','[MyFLV]','[/MyFLV]')

function helpline(help)
{
  document.post.help_line.value=eval(help+"_help");
}

function getarraysize(thearray)
{
  for(i=0;i<thearray.length;i++)
  {
    if((thearray[i]=="undefined")||(thearray[i]=="")||(thearray[i]==null))
      return i;
  }
  return thearray.length;
}

function arraypush(thearray,value)
{
  thearray[getarraysize(thearray)]=value;
}

function arraypop(thearray)
{
  thearraysize=getarraysize(thearray);
  retval=thearray[thearraysize-1];
  delete thearray[thearraysize-1];
  return retval;
}

function bbfontstyle(bbopen,bbclose)
{
  var txtarea=BBCodeGetTextarea();
  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);
    return;
  }
  else
  {
    txtarea.value+=bbopen+bbclose;
    txtarea.focus();
  }

  storeCaret(txtarea);
}

function emoticon(text)
{
  var txtarea=BBCodeGetTextarea();
  text = ' ' + text + ' ';
  if (txtarea.createTextRange && txtarea.caretPos)
  {
    var caretPos = txtarea.caretPos;
    caretPos.text= caretPos.text.charAt(caretPos.text.length-1)==' '?caretPos.text+text+' ':caretPos.text+text;
    txtarea.focus();
  }
  else if(!document.all)
  {
    mozWrap(txtarea,text,'');
  }
  else
  {
    txtarea.value+=text;
    txtarea.focus();
  }
}

function show_smiles(elem)
{
  smiles_elem=document.getElementById(elem);
  if(!smiles_elem) return;
  if(smiles_elem.style.display=='none')
    smiles_elem.style.display='block';
  else
    smiles_elem.style.display='none';
}

function bbstyle(bbnumber)
{
  var txtarea=BBCodeGetTextarea();
  txtarea.focus();
  donotinsert=false;
  theSelection=false;
  bblast=0;

  if(bbnumber==-1)
  {
    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;
    txtarea.focus();
    return;
  }

  if((clientVer>=4)&&is_ie&&is_win)
  {
    theSelection=document.selection.createRange().text;
    if(theSelection)
    {
      document.selection.createRange().text=bbtags[bbnumber]+theSelection+bbtags[bbnumber+1];
      txtarea.focus();
      theSelection='';
      return;
    }
    /*
    else if(txtarea.createTextRange && txtarea.caretPos)
    {
      var caretPos = txtarea.caretPos;
      caretPos.text= caretPos.text.charAt(caretPos.text.length-1)==' '?bbtags[bbnumber]+bbtags[bbnumber+1]+' ':bbtags[bbnumber]+bbtags[bbnumber+1];
      txtarea.focus();
      return;
    }
    */

  }
  else if(txtarea.selectionEnd&&(txtarea.selectionEnd-txtarea.selectionStart>0))
  {
    mozWrap(txtarea,bbtags[bbnumber],bbtags[bbnumber+1]);
    return;
  }



  for(i=0;i<bbcode.length;i++)
  {
    if(bbcode[i]==bbnumber+1)
    {
      bblast=i;
      donotinsert=true;
    }
  }



  if(donotinsert)
  {
    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
  {

    if(imageTag&&(bbnumber!=14))
    {
      txtarea.value+=bbtags[15];
      lastValue=arraypop(bbcode)-1;
      document.post.addbbcode14.value="Img";
      imageTag=false;
    }

    txtarea.value+=bbtags[bbnumber];
    if((bbnumber==14)&&(imageTag==false))
      imageTag=1
    arraypush(bbcode,bbnumber+1);
    eval('document.post.addbbcode'+bbnumber+'.value += "*"');
    txtarea.focus();
    return;
  }
  storeCaret(txtarea);
}

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;
}

function storeCaret(textEl)
{
  if(textEl.createTextRange)
      textEl.caretPos=document.selection.createRange().duplicate();
}

function BBCodeGetTextarea()
{
  return BBCodeTextAreaElem;
}


var BBCodeOldElem=0;
function BBCodeSetElem(elem)
{
  if(!elem) return;

  if(typeof elem!="object")
    elem=document.getElementById(elem);

  if(elem.nodeName!='TEXTAREA') return;
  storeCaret(elem);

  var bbcode_text_id=elem.getAttribute("id")+'_bbcode';

  if(document.getElementById(bbcode_text_id)) return; //== The BBCode already exists

  if(!document.getElementById('wsc_bbcode_enabled')) return;//== There are no BBCode controll

  if(!bbcode_text_id || bbcode_text_id=='')
  {
    alert('Textarea has no id');
    return;
  }

  if(BBCodeOldElem && BBCodeOldElem.getAttribute("id")!=bbcode_text_id)
  {//== removing the old BBCode controll

    BBCodeNewElem=BBCodeOldElem;
    if(BBCodeOldElem.parentNode && BBCodeOldElem.parentNode.removeChild(BBCodeOldElem))
    {
      ;//nothing
    }
    BBCodeNewElem.setAttribute("id",bbcode_text_id);
    elem.parentNode.insertBefore(BBCodeNewElem,elem);
    BBCodeOldElem=BBCodeNewElem;
    BBCodeTextAreaElem=elem;
    return;
  }

  BBCodeTextAreaElem=elem;

  var new_bbcode_div=document.createElement('div');
  new_bbcode_div.setAttribute("id",bbcode_text_id);
  new_bbcode_div.innerHTML=document.getElementById('wsc_bbcode_enabled').innerHTML;

  document.getElementById('wsc_bbcode_enabled').innerHTML='';
  BBCodeOldElem=new_bbcode_div;
  elem.parentNode.insertBefore(new_bbcode_div,elem);
}




//== Insert attachment images into textarea
function alien_insert_img(text)
{
  var txtarea=BBCodeGetTextarea();
  if(!txtarea) return;

  if(text.toLowerCase().indexOf('.gif')==-1 && text.toLowerCase().indexOf('.jpg')==-1 && text.toLowerCase().indexOf('.png')==-1)
  {
     alert('Only images can be inserted');
     return;
  }

  if (txtarea.createTextRange && txtarea.caretPos)
  {
    var theSelection=document.selection.createRange().text;
    if(theSelection)
    {
      theSelection = text;
    }
    else
    {
      var caretPos = txtarea.caretPos;
      caretPos.text=text;
    }
  }
  else if(!document.all && (txtarea.selectionStart || txtarea.selectionStart=='0'))
  {
    var startPos = txtarea.selectionStart;
    var endPos = txtarea.selectionEnd;
    txtarea.value = txtarea.value.substring(0, startPos) + text + txtarea.value.substring(endPos, txtarea.value.length);
  }
  else
  {
    txtarea.value+=text;
  }
}



//---==============================---\\
//====== Autocomplete Usernames ======\\




var AlienAutocompleteID="autocomplete";
var AlienInputID="username";
var AlienAutocompleteElem;

function NamesAutocomplete(elem)
{
  elem.setAttribute("autocomplete","off");
  var AlienURL="wsc.php";
  var name=elem.value;
  if(name.length<2)
  {
    AlienAutocompleteClose();
    return;
  }
  AlienSendReqPost(AlienURL,'mod=ajax_request&alien_ajax=1&usernames=1&username_str='+name);
}

function AlienAutocompleteCreate(response)
{
  if(!response || response=="")
  {
    AlienAutocompleteClose();
    return;
  }
  if(!AlienAutocompleteElem)
    AlienAutocompleteElem = document.createElement("DIV");

  AlienAutocompleteElem.innerHTML=response;
  document.getElementById(AlienAutocompleteID).appendChild(AlienAutocompleteElem);
}

function AlienAutocompleteClose()
{
  if(AlienAutocompleteElem)
  {
    document.getElementById(AlienAutocompleteID).removeChild(AlienAutocompleteElem);
    AlienAutocompleteElem=0;
  }

}

function AutocompleteInsert(elem)
{
  var AlienName=elem.innerHTML;
  AlienName=AlienName.replace("&amp;","&");
  document.getElementById(AlienInputID).value=AlienName;
  AlienAutocompleteClose();
}

//===================== AJAX REQUEST

var AlienRequest;

function AlienSendReqPost(action_link,parameters)
{
  AlienRequest = AlienCreateRequestObject();
  if(!AlienRequest) return false;

  AlienRequest.onreadystatechange = AlienHandleResponse;
  AlienRequest.open('post', action_link, true);
  AlienRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  AlienRequest.setRequestHeader("Content-length", parameters.length);
  AlienRequest.send(parameters);
}

function AlienCreateRequestObject()
{
      AlienRequest = false;
      if (window.XMLHttpRequest)
      { // Mozilla, Safari,...
         AlienRequest = new XMLHttpRequest();
         if (AlienRequest.overrideMimeType) {
            AlienRequest.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            AlienRequest = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               AlienRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!AlienRequest) {
         alert('Cannot use Ajax for sending request');
         return false;
      }
     return AlienRequest;
}

function AlienHandleResponse()
{
   if(AlienRequest.readyState == 4)
   {
      var response = AlienRequest.responseText;
      AlienAutocompleteCreate(response)
   }
}

