// **********************************************************
// FILE NAME: application.js
// DESCRIPTION: Commonly used JavaScript functions
// **********************************************************



// **********************************************************
// FUNCTION: detectClient
// DESCRIPTION: Redirects to alternate pages based on user agent (mainly for mobile devices)

function detectClient() {

  // detect iPhone & iPod Touch
  if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
    location.replace("/_iPhone/");
  }
}
// **********************************************************


// **********************************************************
// FUNCTION: clearField
// DESCRIPTION: Removes the text from an input field

function clearField(field) {
  field.value = "";
}
// **********************************************************



// **********************************************************
// FUNCTION: hideElement
// DESCRIPTION: Hides the lower lightbox promo, which is unnecessary if the client has JS enabled

function hideElement(hideThis) {
  document.getElementById(hideThis).style.display = 'none';
}
// **********************************************************



// **********************************************************
// FUNCTION: toggleElement
// DESCRIPTION: Switches an element's visibility from hidden to visible, or from visible to hidden
function toggleElement(content_div, control_div){
  new Effect.toggle(content_div, 'blind', {duration:.2});
  Sound.play('/_sounds/click.mp3');
  
    if(control_div.innerHTML == "[-]") {
       control_div.innerHTML = "[+]";
    } else {
       control_div.innerHTML = "[-]";
    }
  
  return false;
  
}
// **********************************************************



// **********************************************************
// FUNCTION: addPopUpLink
// DESCRIPTION: Adds popup window functionality to elements with class name popup

function addPopUpLink() {
  // check that the client supports DOM scripting
  if(!document.getElementById || !document.createTextNode){return;}
		  
  // assets of the link -- the class that indicates which link should get the functionality and the message to add the link text
  var popupClass = 'popup';
  var popupMessage = '';
		  
  // temporary variables to use in a loop
  var pop,t;
		  
  // get all links in the document
  var as=document.getElementsByTagName('a');
  // loop over all links
  for (var i=0; i<as.length; i++) {
    t=as[i].className;

	// check to see if the link has a class and the class is the right one
	if (t && t.toString().indexOf(popupClass)!=-1) {
	  // add the message
	  as[i].appendChild(document.createTextNode(popupMessage));

	  // assign a function when the link is clicked
	  as[i].onclick=function() {
	    // open a new window with
	    pop=window.open(this.href, 'popup', 'width=960', 'height=600');
		// don't follow the link, otherwise the linked doc would be opened in a new window AND in the parent
        return false;
	  }
	}
  }
}
// **********************************************************



// **********************************************************
// FUNCTION: addControls
// DESCRIPTION: Adds visual toggle control to toggled elements for JS-enabled clients

function addControls() {
  // check that the client supports DOM scripting
  if(!document.getElementById || !document.createTextNode){return;}
		  
  // assets of the link -- the class that indicates which link should get the functionality and the message to add the link text
  var controlClass = 'toggleControl';
  var controlMessage = '[+]';
		  
  // temporary variables to use in a loop
  var pop,t;
		  
  // get all links in the document
  var as=document.getElementsByTagName('span');
  // loop over all links
  for (var i=0; i<as.length; i++) {
    t=as[i].className;

	// check to see if the link has a class and the class is the right one
	if (t && t.toString().indexOf(controlClass)!=-1) {
	  // add the message
	  as[i].appendChild(document.createTextNode(controlMessage));
	}
  }
}
// **********************************************************



// **********************************************************
// FUNCTION: createStyleRule
// DESCRIPTION: Allows class elements to be hidden via JS

function createStyleRule(selector, declaration) {
    if (!document.getElementsByTagName ||
      !(document.createElement || document.createElementNS)) return;
    var agt = navigator.userAgent.toLowerCase();
    var is_ie = ((agt.indexOf("msie") != -1) &&  (agt.indexOf("opera") == -1));
    var is_iewin = (is_ie &&  (agt.indexOf("win") != -1));
    var is_iemac = (is_ie &&  (agt.indexOf("mac") != -1));
    if (is_iemac) return; // script doesn't work properly in IE/Mac
    var head = document.getElementsByTagName("head")[0]; 
    var style = (typeof document.createElementNS != "undefined") ?
      document.createElementNS("http://www.w3.org/1999/xhtml", "style") :
      document.createElement("style");
    if (!is_iewin) {
        var styleRule = document.createTextNode(selector + " {" + declaration + "}");
            style.appendChild(styleRule); // bugs in IE/Win
    }
        style.setAttribute("type", "text/css");
    style.setAttribute("media", "screen"); 
    head.appendChild(style);
    if (is_iewin &&  document.styleSheets &&  document.styleSheets.length > 0) {
        var lastStyle = document.styleSheets[document.styleSheets.length - 1];
        if (typeof lastStyle.addRule == "object") {
            lastStyle.addRule(selector, declaration);
        }
    }
}

function setElementStyleByClassName(cl, propertyName, propertyValue) {
    if (!document.getElementsByTagName) return;
    var re = new RegExp("(^| )" + cl + "( |$)");
    var el = document.all ? document.all :
      document.getElementsByTagName("body")[0].getElementsByTagName("*");
      // fix for IE5.x
    for (var i = 0; i < el.length; i++) {
        if (el[i].className &&  el[i].className.match(re)) {
            el[i].style[propertyName] = propertyValue;
        }
    }
}
// **********************************************************



// **********************************************************
// FUNCTION: getxmlhttp
// DESCRIPTION: creates an xmlhttp object

function getxmlhttp() {
  // Create a boolean variable to check for a valid IE instance
  var xmlhttp = false;
  // Check if the client is IE
  try {
    // If the JS version is greater than 5
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
    // If not, then use the older active X object
    try {
      // If the client is IE...
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch(E) {
      // Else the client must be non-IE
      xmlhttp = false;
    }
  }
        
  // If the client is not IE, create a JS instance of the object
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    xmlhttp = new XMLHttpRequest();
  }
  
  return xmlhttp;
}
// **********************************************************



// **********************************************************
// FUNCTION: processajax
// DESCRIPTION: processes an XMLHTTPRequest

function processajax(serverPage, obj, getOrPost, str) {
  // Get an XMLHTTPRequest object for use
  xmlhttp = getxmlhttp();
  if(getOrPost == "get") {
    xmlhttp.open("GET", serverPage);
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        obj.innerHTML = xmlhttp.responseText;
      }
    }
    xmlhttp.send(null);
  } else {
    xmlhttp.open("POST", serverPage, true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4) {
        obj.innerHTML = xmlhttp.responseText;
      }
    }
    xmlhttp.send(str);
  }
}
// **********************************************************



// **********************************************************
// FUNCTION: submitform
// DESCRIPTION: Submits an AJAXy form. Parameters:
//              1) The name of the form to be submitted
//              2) The name of the (.php) server page that processes the form information
//              3) The id of the page element to which the results of the server page are returned
//              4) The name of the function used to validate the form fields (contained within formValidation.js) 

function submitform(theform, serverPage, objID, valfunc) {
  
  var file = serverPage;
  var str = getformvalues(theform,valfunc);
  
  // If the validation is okay...
  if (aok == true) {
    obj = document.getElementById(objID);
    
    // process the form
    processajax(serverPage, obj, "post", str);
    new Effect.Highlight(theform, { startcolor: '#131313', endcolor: '#070707' });
    
    // If validation & processing succeeds, update the glider
    // functionality to be added later
  }
}
// **********************************************************



// **********************************************************
// FUNCTION: getformvalues
// DESCRIPTION: Returns string values of all form elements

function getformvalues (fobj, valfunc){

  var str = "";
  aok = true;
  var val;
		
  //Run through a list of all objects contained within the form.
  for(var i = 0; i < fobj.elements.length; i++){

	if(valfunc) {
	  if (aok == true){
		val = valfunc(fobj.elements[i].value,fobj.elements[i].name); 
		if (val == false){
		  aok = false;
		}
      }
	}
	str += fobj.elements[i].name + "=" + escape(fobj.elements[i].value) + "&";
  }
  //Then return the string values.
  return str;
}
// **********************************************************



// **********************************************************
// FUNCTION: adjustRating
// DESCRIPTION: Increment or decrements the comment rating stored in the database

function adjustRating (serverPage, valfunc){

  var file = serverPage;
  var str = getformvalues(theform,valfunc);
  
}
// **********************************************************



// **********************************************************
// FUNCTION: getRemoteContent
// DESCRIPTION: Grabs content from a remote page
function getRemoteContent(serverPage, objID) {
  var obj = document.getElementById(objID);
  
  // Get an XMLHTTPRequest object for use
  xmlhttp = getxmlhttp();
  
  xmlhttp.open("GET", serverPage);
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      Sound.play('/_sounds/success.mp3');
      var data = xmlhttp.responseText;
      obj.innerHTML = data.slice(data.indexOf('<!-- remote content -->'),data.indexOf('<!-- /remote content -->'));
      Effect.Pulsate(obj, { pulses: 1, duration: 1.0 });
     }
  }
  xmlhttp.send(null);
}
// **********************************************************



// **********************************************************
// GROUP: RUN ON LOAD
// FUNCTIONS: none
// DESCRIPTION: functions to run on page load ... adds progressive enhancements

window.onload=function(){
//detectClient();
addControls();
setElementStyleByClassName('supplement_data', 'display', 'none');
hideElement('lightboxPromo');
addPopUpLink();
}
// **********************************************************
