/*
 * investorlink-lib.js
 *
 * Library of various utilities for Investorlink ORB website
 *
 * Copyright (c) 2007 Future Medium Pty Ltd - http://www.futuremedium.com.au/
 *
 * @author scampbell
 */

/**
 * Attaches an onclick event to each link with rel="external" that opens the
 * link in a new window.
 */
function initExternalLinks() {
  var as = document.getElementsByTagName("a");
  for (var i = 0; i < as.length; i++) {
    if (as[i].getAttribute("rel") == "external") {
      as[i].onclick = openNewWindow;
    }
  }

  function openNewWindow() {
    window.open(this.href);
    return false;
  }
}

/**
 * Opens the retrieve password window.
 */
function retrievePassword(url) {
  var windowId = "retrievePasswordWin";
  var windowOpts = "width=300,height=364,resizable=no,toolbar=no,menu=no,"+
                   "directories=no,status=no,location=no";

  var w = window.open(url, windowId, windowOpts);
  w.focus();
}

/**
 * Attaches submit handlers to text inputs of the given form, to compensate for
 * pretent submit buttons (i.e. <a> elements).
 *
 * @param form form to attach submit handlers to
 */
function attachSubmitHandlers(form) {
  // find all text-like inputs
  var inputs = form.getElementsByTagName("input");
  for (var i = 0; i < inputs.length; i++) {
    var inputType = inputs[i].getAttribute("type").toLowerCase();
    if (!(inputType == "text" || inputType == "password")) {
      continue;
    }

    attachHandler(inputs[i], form);
  }

  /**
   * Attaches the enter key handler (that submits the given form) to the
   * given input. Uses mootools Event class.
   */
  function attachHandler(i, f) {
    i.onkeypress = function(e) {
      var event = new Event(e);
      if (event.key == "enter") {
        return validateForm(f);
      }
    }
  }
}

/**
 * Initialises toggling of product reports containers.
 *
 * @param containerId ID of outer container element
 */
function initProductReportsContainers(containerId) {
	var container = document.getElementById(containerId);

	var headings = container.getElementsByTagName("dt");
	var bodies = container.getElementsByTagName("dd");

	for (var i = 0; i < headings.length; i++) {
		attachProductReportsContainerEvents(headings[i], bodies[i]);
	}

	/**
	 * Attaches the onclick event to the toggle anchor in the given heading. This
	 * function creates a new scope in which we can assign unique onclick events
	 * to each anchor.
	 *
	 * @param heading element containing the toggle anchor
	 * @param body    element containing report lists
	 */
	function attachProductReportsContainerEvents(heading, body) {
		var toggle = heading.getElementsByTagName("a").item(0);
		toggle.onclick = function() {
      toggleProductReportsContainerVisibility(heading, body);
      return false;
    }
	}

	/**
	 * Toggles the visibility of the given heading/body pair, and hides all other
	 * heading/body pairs within the container.
	 *
	 * @param heading heading element to toggle style of
	 * @param body    contents to hide/reveal
	 */
	function toggleProductReportsContainerVisibility(heading, body) {
		// determine whether to show or hide the given elements
		var show = heading.className.indexOf("current") == -1;
		// hide everything
		for (var j = 0; j < headings.length; j++) {
			headings[j].className = headings[j].className.replace(/ ?current/g, '');
			bodies[j].className = bodies[j].className.replace(/ ?current/g, '');
		}
		if (show) {
			heading.className += " current";
			body.className += " current";
		}
	}
}

/**
 * Pops up the image viewer in a window of the correct size. Parses the given
 * URL to determine image dimensions.
 *
 * @param url image viewer URL
 */
function showImageViewer(url) {
	var winId = "InvestorlinkImageViewer";

  var urlArgs = parseUrlArgs(url);
  var winOpts = "width=" + urlArgs.w + ",height=" + urlArgs.h +
  	",resizable=0,location=0,toolbars=0,menu=0,directories=0,status=0";

	var win = window.open(url, winId, winOpts);
  win.focus();
}

/**
 * Parses GET query args from the given URL into a set of key-value pairs.
 *
 * @param url URL to parse
 *
 * @return associative array object
 */
function parseUrlArgs(url) {
  var urlArgs = {};

  var queryString = url.replace(/^.*\?/, "");
  if (!queryString) {
		return urlArgs;
	}

  var pairs = queryString.split('&');
  for (var i = 0; i < pairs.length; i++) {
		var pair = pairs[i].split('=');
		urlArgs[pair[0]] = pair[1];
	}

	return urlArgs;
}

/**
 * Highlights every second <tr> of the given <table> element, by adding
 * class="highlight".
 *
 * @param table table to process
 */
function highlightEvenTableRows(table) {
  var tbodies = table.getElementsByTagName("tbody");
  for (var i = 0; i < tbodies.length; i++) {
    var trs = tbodies[i].getElementsByTagName("tr");
    for (var j = 0; j < trs.length; j++) {
      if (j % 2 == 0) {
        continue;
      }
      var className = "highlight";
      if (trs[j].getAttribute("class") != null) {
        // preserve existing classname
        className = " " + className;
      }
      trs[j].className += className;
    }
  }
}