
//############################################################################//
//#                                                                          #//
//#   Copyright (C) 2008 Durk de Vries.                                      #//
//#   Copyright (C) 2009 Durk de Vries.                                      #//
//#   Copyright (C) 2010 Durk de Vries.                                      #//
//#                                                                          #//
//#   durkdevries@renovatiocms.com                                           #//
//#                                                                          #//
//#   ====================================================================   #//
//#                                                                          #//
//#   This file is part of RENOVATIO-CMS.                                    #//
//#                                                                          #//
//#   RENOVATIO-CMS is free software: you can redistribute it and/or         #//
//#   modify it under the terms of the GNU General Public License as         #//
//#   published by the Free Software Foundation, either version 3 of         #//
//#   the License, or (at your option) any later version.                    #//
//#                                                                          #//
//#   RENOVATIO-CMS is distributed in the hope that it will be useful,       #//
//#   but WITHOUT ANY WARRANTY; without even the implied warranty of         #//
//#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the           #//
//#   GNU General Public License for more details.                           #//
//#                                                                          #//
//#   You should have received a copy of the                                 #//
//#   GNU General Public License along with RENOVATIO-CMS.                   #//
//#   If not, see <http://www.gnu.org/licenses/>.                            #//
//#                                                                          #//
//#                                                                          #//
//#                                                                          #//
//############################################################################//

//############################################################################//
//# RENOVATIO JS Functions; globals:                              V 001.081  #//
//# For detailed documentation, visit http://www.renovatiocms.com/ !!        #//
//############################################################################//

//Onload, onresize, onunload arrays..
$OnLoad   = new Array();
$OnResize = new Array();
$OnUnload = new Array();

//Http object array..
$HttpObj = new Array();
$HttpKey = 0;

//Browser detection..
$Browser = new RegExp('Chrome|Opera|Safari|MSIE|Firefox', 'g');
$Browser = 'Browser: ' + $Browser.exec(navigator.userAgent);

//Add and remove slashes & returns..
$SAddSlashes = new RegExp('\\\\|"', 'g');         $RAddSlashes = '\\$&';
$SRemSlashes = new RegExp('(\\\\)(\\\\|")', 'g'); $RRemSlashes = '$2';
$SCleSlashes = new RegExp('(\\\\)(\\\\|")', 'g'); $RCleSlashes = '';
$SRemReturns = new RegExp('\r', 'g');             $RRemReturns = '';


//############################################################################//
//# RENOVATIO JS Functions; event system & JSON:                             #//
//# For detailed documentation, visit http://www.renovatiocms.com/ !!        #//
//############################################################################//

//Onload function..
//############################################################################//
window.onload = function()
{ for (var $key in $OnLoad)
  { if (typeof window[$key] == 'function')
    { if ($OnLoad[$key]) {window[$key]($OnLoad[$key]);}
      else               {window[$key]();}
}}}
//Onresize function..
//============================================================================//
window.onresize = function()
{ for (var $key in $OnResize)
  { if (typeof window[$key] == 'function')
    { if ($OnResize[$key]) {window[$key]($OnResize[$key]);}
      else                 {window[$key]();}
}}}
//Onunload function..
//============================================================================//
window.onunload = function()
{ for (var $key in $OnUnload)
  { if (typeof window[$key] == 'function')
    { if ($OnUnload[$key]) {window[$key]($OnUnload[$key]);}
      else                 {window[$key]();}
}}}
//Convert array to JSON string..
//############################################################################//
function ArrayToJSONString($JSONArray)
{
  //Convert associative arrays to strings with key-value pairs..
  var $JSONString = new Array(); var $i = 0;
  for (var $key1 in $JSONArray)
  {
    $JSONString[$i] = new Array(); var $j = 0;
    for (var $key2 in $JSONArray[$key1]) {$JSONString[$i][$j] = ($key2 + '').replace($SAddSlashes, $RAddSlashes) + '":"' + ($JSONArray[$key1][$key2] + '').replace($SAddSlashes, $RAddSlashes); $j++;}
    $JSONString[$i] = $JSONString[$i].join('","'); $i++;
  }
  //Join array of strings with key-value pairs to JSONString..
  $JSONString = '[{"' + $JSONString.join('"},{"') + '"}]';

  //Return result..
  return $JSONString;
}
//Convert JSON string to array..
//============================================================================//
function JSONStringToArray($JSONString)
{
  //Remove brackets..
  if ($JSONString.indexOf('[{"') != 0 || $JSONString.lastIndexOf('"}]') != $JSONString.length - 3) {return false;}
  var $Convert = $JSONString.substring(3, $JSONString.length - 3);

  //Split JSONString to array of strings with key-value pairs..
  var $JSONArray = new Array();
  $Convert       = $Convert.split('"},{"');
  for (var $i = 0; typeof $Convert[$i] != 'undefined'; $i++)
  {
    //Convert strings with key-value pairs to associative arrays..
    $JSONArray[$i] = new Array();
    $Convert[$i]   = $Convert[$i].split('","');
    for (var $j = 0; typeof $Convert[$i][$j] != 'undefined'; $j++)
    {
      //Split key-value pairs..
      $Convert[$i][$j] = $Convert[$i][$j].split('":"');
      if ($Convert[$i][$j].length != 2) {return false;}

      //Check for unescaped slashes or quotes..
      $Convert[$i][$j][2] = $Convert[$i][$j][0].replace($SCleSlashes, $RCleSlashes) + $Convert[$i][$j][1].replace($SCleSlashes, $RCleSlashes);
      if ($Convert[$i][$j][2].indexOf('\\') != -1 || $Convert[$i][$j][2].indexOf('"') != -1) {return false;}

      //Check for double keys and save pair..
      if (typeof $JSONArray[$i][$Convert[$i][$j][0].replace($SRemSlashes, $RRemSlashes)] != 'undefined') {return false;}
      $JSONArray[$i][$Convert[$i][$j][0].replace($SRemSlashes, $RRemSlashes)] = $Convert[$i][$j][1].replace($SRemSlashes, $RRemSlashes);
    }
  }
  //Return result..
  return $JSONArray;
}
//Send and receive JSON strings..
//############################################################################//
function AJAXPost($Url, $Request, $OnResponse)
{
  //Set input string & create unique HttpObject..
  var $Parameter = 'RVAJX_request=' + encodeURIComponent($Request);
  var $Unique    = $HttpKey = $HttpKey + 1;

  if      (window.XMLHttpRequest) {$HttpObj[$Unique] = new XMLHttpRequest();}
  else if (window.ActiveXObject)  {$HttpObj[$Unique] = new ActiveXObject('Microsoft.XMLHTTP');}
  else                            {return;}

  //Set JS action when ready..
//============================================================================//
  $HttpObj[$Unique].onreadystatechange = function()
  {
    if ($HttpObj[$Unique].readyState == 4)
    {
      //Check string format, call response function and delete $HttpObj[$Unique]..
      if ($HttpObj[$Unique].status == 200) {window[$OnResponse]($HttpObj[$Unique].responseText);}
      $HttpObj.splice($Unique,1);
    }
  }
  //Send request..
  $HttpObj[$Unique].open('POST', $Url, true);
  $HttpObj[$Unique].setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  $HttpObj[$Unique].setRequestHeader('Content-length', $Parameter.length);
  $HttpObj[$Unique].setRequestHeader('Connection', 'close');
  $HttpObj[$Unique].send($Parameter);
}
//Save traffic..
//############################################################################//
function SaveTraffic()
{
  //Create HttpObject..
  if      (window.XMLHttpRequest) {var $HttpObj = new XMLHttpRequest();}
  else if (window.ActiveXObject)  {var $HttpObj = new ActiveXObject('Microsoft.XMLHTTP');}
  else                            {return;}

  //Send request..
  var $Request = '[{"$request":"SaveTraffic"},{"$ploadid":"' + $Page['$ploadid'] + '","$s_width":"' + screen.width + '","$s_height":"' + screen.height + '","$s_depth":"' + screen.colorDepth + '"}]';
  $HttpObj.open('GET', '00_system/traffic.php?RVAJX_request=' + encodeURIComponent($Request), false);
  $HttpObj.send(null);
}
//Save traffic when user leaves..
$OnUnload['SaveTraffic'] = '';


//############################################################################//
//# RENOVATIO JS Functions; popup system:                                    #//
//# For detailed documentation, visit http://www.renovatiocms.com/ !!        #//
//############################################################################//

//Show popup..
//############################################################################//
function ShowPopup($Header, $Content, $Field)
{
  //Get popup & fullscreen elements..
//============================================================================//
  $PContainer  = document.getElementById('pcontainer');
  $PAnchor     = document.getElementById('panchor');
  $PHeader     = document.getElementById('pheader');
  $PContent    = document.getElementById('pcontent');
  $PContour    = document.getElementById('pcontour');
  $PCHeader    = document.getElementById('pcheader');
  $FContainer  = document.getElementById('fcontainer');
  $BContainer  = document.getElementById('bcontainer');
  $BBackground = document.getElementById('bbackground');

  //Activate drag system..
  $PHeader.onmouseover   = function() {$PContour.style.visibility = 'visible';}
  $PCHeader.onmouseout   = function() {$PContour.style.visibility = 'hidden';}
  $PCHeader.style.cursor = 'url(\'03_skins/' + $Page['$skin'] + '/images/move.cur\'), move';
  $PCHeader.onmousedown  = GrabPopup;
  $PCHeader.onmouseup    = ReleasePopup;

  //Fill & align popup..
//============================================================================//
  $PHeader.innerHTML       = $Header + '&nbsp;';
  $PContent.innerHTML      = $Content;
  $PContour.style.height   = ($PAnchor.offsetHeight - 2) + 'px';
  $PContainer.style.height = Math.max(document.documentElement.clientHeight, $PAnchor.offsetHeight) + 'px';
  $PContour.style.left     = $PAnchor.style.left = Math.ceil(($PContainer.clientWidth  - $PAnchor.offsetWidth)  / 2) + 'px';
  $PContour.style.top      = $PAnchor.style.top  = Math.ceil(($PContainer.clientHeight - $PAnchor.offsetHeight) / 3) + 'px';

  //Hide background..
  $FContainer.style.visibility = 'hidden';
  $BContainer.style.visibility = 'hidden';

  //Align background..
//============================================================================//
  $KeepBodyScrollPU = Math.max(document.body.scrollTop, document.documentElement.scrollTop);
  if   ($FContainer.style.display == 'block')
       {$FContainer.style.height = $PContainer.offsetHeight + 'px'; $FContent.style.marginTop    = -$KeepBodyScrollPU + 'px'; ResizeEditor();}
  else {$BContainer.style.height = $PContainer.offsetHeight + 'px'; $BBackground.style.marginTop = -$KeepBodyScrollPU + 'px';}
  document.documentElement.scrollTop = document.body.scrollTop = 0;

  //Show popup & background, focus input field..
  $PContainer.style.visibility = 'visible';
  $FContainer.style.visibility = 'visible';
  $BContainer.style.visibility = 'visible';
  if ($Field) {setTimeout(function() {document.getElementById($Field).focus();}, 200);}
}
//Realign popup..
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@//
function RealignPopup()
{ if (document.getElementById('pcontainer').style.visibility == 'visible')
  {
    //Align popup..
    $PContour.style.height   = ($PAnchor.offsetHeight - 2) + 'px';
    $PContainer.style.height = Math.max(document.documentElement.clientHeight, $PAnchor.offsetHeight) + 'px';
    $PContour.style.left     = $PAnchor.style.left = Math.ceil(($PContainer.clientWidth  - $PAnchor.offsetWidth)  / 2) + 'px';
    $PContour.style.top      = $PAnchor.style.top  = Math.ceil(($PContainer.clientHeight - $PAnchor.offsetHeight) / 3) + 'px';

    //Align background..
//============================================================================//
    if   ($FContainer.style.display == 'block')
         {$FContainer.style.height = $PContainer.offsetHeight + 'px';}
    else {$BContainer.style.height = $PContainer.offsetHeight + 'px';}
  }
}
//Realign popup when window resizes..
$OnResize['RealignPopup'] = '';

//Hide popup..
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@//
function HidePopup()
{ if (document.getElementById('pcontainer').style.visibility == 'visible')
  {
    //Hide popup & background..
    $PContainer.style.height     = '100%';
    $PContainer.style.visibility = 'hidden';
    $PContour.style.visibility   = 'hidden';
    $FContainer.style.visibility = 'hidden';
    $BContainer.style.visibility = 'hidden';

    //Restore background..
//============================================================================//
    var $KeepBodyScrollPU2 = $KeepBodyScrollPU; $KeepBodyScrollPU = 0;
    if   ($FContainer.style.display == 'block')
         {$FContainer.style.height = ''; $FContent.style.marginTop    = -$KeepBodyScrollPU + 'px'; ResizeEditor();}
    else {$BContainer.style.height = ''; $BBackground.style.marginTop = -$KeepBodyScrollPU + 'px';}
    document.documentElement.scrollTop = document.body.scrollTop = $KeepBodyScrollPU2;

    //Show background..
    $FContainer.style.visibility = 'visible';
    $BContainer.style.visibility = 'visible';
  }
}
//Grab popup..
//############################################################################//
function GrabPopup($Mouse)
{ if (document.getElementById('pcontainer').style.visibility == 'visible')
  {
    //Set reference locations..
    if (!$Mouse) {var $Mouse = window.event;}
    $ContourXref = $PContour.offsetLeft;  $MouseXref = $Mouse.clientX;
    $ContourYref = $PContour.offsetTop;   $MouseYref = $Mouse.clientY;

    //Initialize & activate DragPopup..
    $PCHeader.onmouseout   = null;
    $PCHeader.style.cursor = 'url(\'03_skins/' + $Page['$skin'] + '/images/grab.cur\'), move';
    document.onselectstart = function() {return false;}
    document.onmousedown   = function() {return false;}
    document.onmousemove   = DragPopup;
  }
}
//Drag popup..
//============================================================================//
function DragPopup($Mouse)
{ if (document.getElementById('pcontainer').style.visibility == 'visible')
  {
    //Stick contour to mouse..
    if (!$Mouse) {var $Mouse = window.event;}
    $PContour.style.left = ($Mouse.clientX - $MouseXref + $ContourXref) + 'px';
    $PContour.style.top  = ($Mouse.clientY - $MouseYref + $ContourYref) + 'px';
  }
}
//Release popup..
//============================================================================//
function ReleasePopup()
{ if (document.getElementById('pcontainer').style.visibility == 'visible')
  {
    //Move popup to end location..
    $PAnchor.style.left = $PContour.offsetLeft + 'px';
    $PAnchor.style.top  = $PContour.offsetTop + 'px';

    //Deactivate DragPopup..
    $PCHeader.onmouseout   = function() {$PContour.style.visibility = 'hidden';}
    $PCHeader.style.cursor = 'url(\'03_skins/' + $Page['$skin'] + '/images/move.cur\'), move';
    document.onselectstart = null;
    document.onmousedown   = null;
    document.onmousemove   = null;
  }
}


//############################################################################//
//# RENOVATIO JS Functions; login popups & table of contents:                #//
//# For detailed documentation, visit http://www.renovatiocms.com/ !!        #//
//############################################################################//

//Load popups..
//############################################################################//
function LoadLogin($Message, $State)
{ switch ($Message)
  {
//Manual login fail popup..
//============================================================================//
    case 'MLFail':
      var $LMessageContent =
        '<center>'
         +'<table>'
           +'<tr><td>'
             +'<p>' + $Text['$AcPop 12'] + '<\/p>'
             +'<ul>'
               +'<li>' + $Text['$AcPop 13'] + '<\/li>'
               +'<li>' + $Text['$AcPop 14'] + '<\/li>'
             +'<\/ul><br>'
             +'<p>' + $Text['$AcPop 15'] + '<\/p>'
             +'<ul>'
               +'<li>' + $Text['$AcPop 16'] + '<\/li>'
               +'<li>' + $Text['$AcPop 17'] + '<\/li>'
               +'<li>' + $Text['$AcPop 18'] + '&nbsp;<a href="mailto:' + $Page['$helpmail'] + '">' + $Text['$AcPop 19'] + '<\/a>' + $Text['$AcPop 20'] + '<\/li>'
             +'<\/ul>'
           +'<\/td><\/tr>'
         +'<\/table>'
         +'<input type="button" value="' + $Text['$AcPop 21'] + '" class="button" onclick="ShowPopup(\'' + $Text['$AcPop 27'] + '\', $LFormContent, \'RVPST_name\')">'
         +'<input type="button" value="' + $Text['$AcPop 22'] + '" class="button" onclick="HidePopup()">'
       +'<\/center>';
      ShowPopup($Text['$AcPop 11'], $LMessageContent); break;

//Automatic login fail popup..
//============================================================================//
    case 'ALFail':
      var $LMessageContent =
        '<center>'
         +'<table>'
           +'<tr><td>' + $Text['$AcPop 24'] + '<\/td><\/tr>'
         +'<\/table>'
         +'<input type="button" value="' + $Text['$AcPop 25'] + '" class="button" onclick="ShowPopup(\'' + $Text['$AcPop 27'] + '\', $LFormContent, \'RVPST_name\')">'
         +'<input type="button" value="' + $Text['$AcPop 26'] + '" class="button" onclick="HidePopup()">'
       +'<\/center>';
      ShowPopup($Text['$AcPop 23'], $LMessageContent); break;
  }
//Login form popup..
//============================================================================//
  if ($State) {var $LogoutBut = '<input type="submit" value="' + $Text['$AcPop 35'] + '" class="button" onmousedown="document.getElementById(\'RVPST_name\').value = \'\'">';}
  else        {var $LogoutBut = '';}

  $LFormContent =
    '<form action="" method="post">'
     +'<center>'
       +'<table>'
         +'<tr><td>' + $Text['$AcPop 29'] + '<\/td><td><input id="RVPST_name" name="RVPST_name" type="text" maxlength="64" class="text"><\/td><\/tr>'
         +'<tr><td>' + $Text['$AcPop 30'] + '<\/td><td><input id="RVPST_pass" name="RVPST_pass" type="password" maxlength="64" class="text"><\/td><\/tr>'
         +'<tr><td>' + $Text['$AcPop 31'] + '<\/td><td><select id="RVPST_mode" name="RVPST_mode"><option value="s" selected="selected">' + $Text['$AcPop 32'] + '<\/option><option value="l">' + $Text['$AcPop 33'] + '<\/option><\/select><\/td><\/tr>'
       +'<\/table>'
       +'<input id="RVPST_logout" name="RVPST_logout" type="text" value="1" readonly="readonly" style="display:none">' + $LogoutBut
       +'<input type="submit" value="' + $Text['$AcPop 34'] + '" class="button" onmousedown="if (!document.getElementById(\'RVPST_name\').value) {document.getElementById(\'RVPST_name\').value = \' \'}">'
       +'<input type="button" value="' + $Text['$AcPop 36'] + '" class="button" onclick="HidePopup()">'
     +'<\/center>'
   +'<\/form>';
}
//Write table of contents..
//############################################################################//
function WriteTOC()
{
  //Block in case of no toc..
  if (!($TableofC = document.getElementById('table_of_contents')) || $TableofC.tagName != 'DIV') {return;}

  //Set variables..
  $TableofC.className = 'tableofc';
  var $Element = $TableofC;
  var $H1 = 0;
  var $H2 = 0;
  var $H3 = 0;

  //Scan document for H1,2,3 elements..
//============================================================================//
  while ($Element = $Element.nextSibling)
  {
    if ($Element.tagName == 'H1' || $Element.tagName == 'H2' || $Element.tagName == 'H3')
    {
      //Number elements..
      switch ($Element.tagName)
      { case 'H1': $H1++; $H2 = 0; $H3 = 0; break;
        case 'H2': $H2++; $H3 = 0; break;
        case 'H3': $H3++; break;
      }
      var $HNo = $H1; if ($H2) {$HNo += '.' + $H2;} if ($H3) {$HNo += '.' + $H3;}

      //Fill-in contents..
      var $TableofCElement = document.createElement($Element.tagName);
      $TableofC.appendChild($TableofCElement);

      $TableofCElement.innerHTML = '<a href="#' + $HNo + '">' + $HNo + '&nbsp;&nbsp;' + $Element.innerHTML + '<\/a>';
      $Element.innerHTML         = '<a name="' + $HNo + '">' + $HNo + '<\/a>&nbsp;&nbsp;' + $Element.innerHTML;
    }
  }
}
//Write TOC when page loads..
$OnLoad['WriteTOC'] = '';

//############################################################################//
//# For detailed documentation, visit http://www.renovatiocms.com/ !!        #//
//############################################################################//
