/* scripts.js
 *
 * Copyright 2008 Hubert Chathi <hubert@uhoreg.ca>
 *
 *   This program 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.
 *
 *   This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

//                                                              ______________
// ____________________________________________________________/ Image Albums \_

images = new Array(0);

function image(width, height)
{
  this.width = width;
  this.height = height;
}

function loadImage(num)
{
  var req;

  // clear the container
  container = document.getElementById('imagecontainer');
  while (container.length > 0)
  {
    container.remove(0);
  }

  permalink = document.getElementById('imagepermalink');
  permalink.href = images[num];

  // load document
  // branch for native XMLHttpRequest object
  if (window.XMLHttpRequest)
  {
    req = new XMLHttpRequest();
  }
  // branch for IE/Windows ActiveX version
  else if (window.ActiveXObject)
  {
    req = new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (req)
  {
    function processImageReqChange()
    {
      if (req.readyState == 4)
      {
	if (req.status == 200)
	{
	  container = document.getElementById('imagecontainer');
	  container.innerHTML = req.responseText;
	}
	else
	{
	  alert("Error retrieving document:\n" + req.statusText);
	}
      }
    }

    req.onreadystatechange = processImageReqChange;
    req.open('GET', images[num] + '?mode=body', true);
    req.send(null);
    //container.innerHTML = 'loading...';

    link = document.getElementById('imageprev');
    if (num > 0)
    {
      link.setAttribute('href', 'javascript:loadImage(' + (num - 1) + ')');
    }
    else
    {
      link.setAttribute('href', 'javascript:;');
    }
    link = document.getElementById('imagenext');
    if (num < images.length)
    {
      link.setAttribute('href', 'javascript:loadImage(' + (num + 1) + ')');
    }
    else
    {
      link.setAttribute('href', 'javascript:;');
    }
  }
  else
  {
    window.location = images[num];
  }
}

function loadImageNull(num)
{
  loadImage(num);
  return false;
}

function imageTestUnsupported(redirect)
{
  if (window.XMLHttpRequest || window.ActiveXObject)
  {
    document.getElementById('unsupported').style.display='none';
  }
  else
  {
    window.location = redirect;
  }
}

//                                                         __________________
// _______________________________________________________/ Previewing edits \_

function smcmsEditPreview()
{
  form = document.forms[0];
  queryString = formData2QueryString(form) + '&_do=preview&_mode=js';

  req = false;

  function processEditPreview()
  {
    if (req.readyState == 4)
    {
      if (req.status == 200)
      {
	container = document.getElementById('preview');
	container.innerHTML = req.responseText;
      }
      else
      {
	alert("Error retrieving preview:\n" + req.statusText);
      }
    }
  }

  if (window.XMLHttpRequest)
  {
    req = new XMLHttpRequest();
  }
  // branch for IE/Windows ActiveX version
  else if (window.ActiveXObject)
  {
    req = new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (req)
  {
    req.onreadystatechange = processEditPreview;
    req.open('POST', form.action, true);
    req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    req.send(queryString);

    return false;
  }
  else
  {
    alert('false');
    return true;
  }
}

//                                                        ___________________
// ______________________________________________________/ AJAX form posting \_

// The following copyright notice applies to the formData2QueryString function.
// formData2QueryString was downloaded from:
//   http://www.fleegix.org/pages/downloads
/*
 * Copyright 2005 Matthew Eernisse (mde@fleegix.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Original code by Matthew Eernisse (mde@fleegix.org), March 2005
 * Additional bugfixes by Mark Pruett (mark.pruett@comcast.net), 12th July 2005
 * Multi-select added by Craig Anderson (craig@sitepoint.com), 24th August 2006
 *
 * Version 1.3
*/

/**
 * Serializes the data from all the inputs in a Web form
 * into a query-string style string.
 * @param docForm -- Reference to a DOM node of the form element
 * @param formatOpts -- JS object of options for how to format
 * the return string. Supported options:
 *    collapseMulti: (Boolean) take values from elements that
 *    can return multiple values (multi-select, checkbox groups)
 *    and collapse into a single, comman-delimited value
 *    (e.g., thisVar=asdf,qwer,zxcv)
 * @returns query-string style String of variable-value pairs
 */
function formData2QueryString(docForm, formatOpts) {

  var opts = formatOpts || {};
  var str = '';
  var formElem;
  var lastElemName = '';

  for (i = 0; i < docForm.elements.length; i++) {
    formElem = docForm.elements[i];

    switch (formElem.type) {
      // Text fields, hidden form elements
      case 'text':
      case 'hidden':
      case 'password':
      case 'textarea':
        str += formElem.name + '=' + encodeURI(formElem.value) + '&'
        break;

      // Single-option select
      case 'select-one':
	str += formElem.name + '=' + escape(formElem.options[formElem.selectedIndex].value) + '&'
        break

      // Multi-option select
      case 'select-multiple':
        var isSet = false;
        for(var j = 0; j < formElem.options.length; j++) {
          var currOpt = formElem.options[j];
          if(currOpt.selected) {
            if (opts.collapseMulti) {
              if (isSet) {
                str += ',' + encodeURI(currOpt.value);
              }
              else {
                str += formElem.name + '=' + encodeURI(currOpt.value);
                isSet = true;
              }
            }
            else {
              str += formElem.name + '=' + encodeURI(currOpt.value) + '&';
            }
          }
        }
        if (opts.collapseMulti) {
          str += '&';
        }
        break;

      // Radio buttons
      case 'radio':
        if (formElem.checked) {
          str += formElem.name + '=' + encodeURI(formElem.value) + '&'
        }
        break;

      // Checkboxes
      case 'checkbox':
        if (formElem.checked) {
          // Collapse multi-select into comma-separated list
          if (opts.collapseMulti && (formElem.name == lastElemName)) {
            // Strip of end ampersand if there is one
            if (str.lastIndexOf('&') == str.length-1) {
              str = str.substr(0, str.length - 1);
            }
            // Append value as comma-delimited string
            str += ',' + encodeURI(formElem.value);
          }
          else {
            str += formElem.name + '=' + encodeURI(formElem.value);
          }
          str += '&';
          lastElemName = formElem.name;
        }
        break;

    }
  }
  // Remove trailing separator
  str = str.substr(0, str.length - 1);
  return str;
}


// end of scripts.js

