
//TODO load dependencies: browserdetect

//onDOMReady Event Extension
//http://clientside.cnet.com/code-snippets/event-scripting/a-dom-ready-extension-for-prototype/
Object.extend(Event, {
  _domReady : function() {
    if (arguments.callee.done) return;
    arguments.callee.done = true;

    if (this._timer)  clearInterval(this._timer);
    
    this._readyCallbacks.each(function(f) { f() });
    this._readyCallbacks = null;
},
  onDOMReady : function(f) {
    if (!this._readyCallbacks) {
      var domReady = this._domReady.bind(this);
      
      if (document.addEventListener)
        document.addEventListener("DOMContentLoaded", domReady, false);
        
        /*@cc_on @*/
        /*@if (@_win32)
            document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
            document.getElementById("__ie_onload").onreadystatechange = function() {
                if (this.readyState == "complete") domReady(); 
            };
        /*@end @*/
        
        if (/WebKit/i.test(navigator.userAgent)) { 
          this._timer = setInterval(function() {
            if (/loaded|complete/.test(document.readyState)) domReady(); 
          }, 10);
        }
        
        Event.observe(window, 'load', domReady);
        Event._readyCallbacks =  [];
    }
    Event._readyCallbacks.push(f);
  }
});


if (typeof(AC) == "undefined") AC = {};

AC.decorateSearchInput = function(field, options) {
	
	var searchField = $(field);
	var standIn = null;

	var results = 0;
	var placeholder = '';
	var autosave = '';

	if(options) {
		
		if(options.results) { results = options.results; }
		if(options.placeholder) { placeholder = options.placeholder; }
		if(options.autosave) { autosave = options.autosave; }
		
	}
	
	if(AC.Detector.isWebKit()) {
		
		searchField.setAttribute('type', 'search');
		if(!searchField.getAttribute('results')) {
			searchField.setAttribute('results', results);
		}
		
		if(null != placeholder) {
			searchField.setAttribute('placeholder', placeholder);
			searchField.setAttribute('autosave', autosave);
		}
		
	} else {
		
		//prevent browser from doing its own autocomplete, threw odd xul 
		//error on reset sometimes, although this feels a little
		//heavy handed
		searchField.setAttribute('autocomplete', 'off');
		
		//replace the field with a standin while we create the wrapper
		//we can't lose the reference to this field as other objects may
		//have already registered listeners on this field
		
		standIn = document.createElement('input');
		searchField.parentNode.replaceChild(standIn, searchField)

		var left = document.createElement('span');
		Element.addClassName(left, 'left');
	
		var right = document.createElement('span');
		Element.addClassName(right, 'right');
		
		var reset = document.createElement('div');
		Element.addClassName(reset, 'reset');
		
		var wrapper = document.createElement('div');
		Element.addClassName(wrapper, 'search-wrapper');
		
		var alreadyHasPlaceholder = field.value == placeholder;
		var isEmpty = field.value.length == 0;
		
		if (alreadyHasPlaceholder || isEmpty) {
			searchField.value = placeholder;
			Element.addClassName(wrapper, 'blurred');
			Element.addClassName(wrapper, 'empty');
		}
	
		wrapper.appendChild(left);
		wrapper.appendChild(searchField);
		wrapper.appendChild(right);
		wrapper.appendChild(reset);
	
		var focus = function() {
			
			var blurred = Element.hasClassName(wrapper, 'blurred');

			//need to check for flag AND placeholder lest somebody need to 
			//search for the placeholder text itself
			if(searchField.value == placeholder && blurred) {
				searchField.value = '';
			}
			
			Element.removeClassName(wrapper, 'blurred');
		}
		Event.observe(searchField, 'focus', focus);
		
		var blur = function() {
			
			if(searchField.value == '') {
				Element.addClassName(wrapper, 'empty');
				searchField.value = placeholder;
			}
			
			Element.addClassName(wrapper, 'blurred');
		}
		Event.observe(searchField, 'blur', blur);
		
		
		var toggleReset = function() {
			
			if(searchField.value.length >= 0) {
				Element.removeClassName(wrapper, 'empty');
			}
		}
		Event.observe(searchField, 'keydown', toggleReset);
	
	
		var resetField = function() {
			return( function(evt) {
				
				var escaped = false;
				
				if(evt.type == 'keydown') {
					if(evt.keyCode != 27) {
						return; //if it's not escape ignore it
					} else {
						escaped = true;
					}
				}
				
				searchField.blur(); //can't change value while in field
				searchField.value = '';
				Element.addClassName(wrapper, 'empty');
				searchField.focus();

			})
		}
		Event.observe(reset, 'mousedown', resetField());
		Event.observe(searchField, 'keydown', resetField());
	
		if (standIn) {
			standIn.parentNode.replaceChild(wrapper, standIn);
		}
		
	}
}

FindOutHow.g_iMinSwapHeight = 480;
FindOutHow.g_iMaxLowerHeight = 310;
FindOutHow.g_iBottomPadding = 70;//includes 1 beveled edge all the way to bottom of the page
function FindOutHow()
{
  this.m_fpOnResize = dojo.lang.hitch(this, "OnResize");
  this.Size();
  this.AttachResizeHandler();
}

FindOutHow.PageLoad = function()
{
  new FindOutHow();
}

FindOutHow.prototype.AttachResizeHandler = function()
{
  Event.observe(
    window, 
    "resize", 
    this.m_fpOnResize);
}

FindOutHow.prototype.DetachResizeHandler = function()
{
  Event.stopObserving(
    window, 
    "resize", 
    this.m_fpOnResize);
}

FindOutHow.prototype.OnResize = function(event)
{
  this.DetachResizeHandler();
  this.Size();
  this.AttachResizeHandler();
}

FindOutHow.prototype.Size = function()
{
  if (!$("subnav")) return;
  $("subnav").style.height = FindOutHow.g_iMaxLowerHeight + "px";

  var oHeights = [];
  var oContentContainer = document.getElementsByClassName("contentContainer")[0];
  var iHeight = dojo.html.getViewport().height;
  iHeight -= oContentContainer.offsetTop;
  iHeight -= FindOutHow.g_iMaxLowerHeight;
  iHeight -= FindOutHow.g_iBottomPadding;//bottom padding
  oContentContainer.style.height = Math.max(
    iHeight, 
    FindOutHow.g_iMinSwapHeight) + "px";
}

/* Dojo methods */
var dojo = {};
dojo.lang = {};
dojo.lang.isString = function(/*anything*/ it){
  // summary: Return true if it is a String.
  return (typeof it == "string" || it instanceof String);
}

dojo.lang.hitch = function(/*Object*/thisObject, /*Function|String*/method){
  // summary: 
  //    Returns a function that will only ever execute in the a given scope
  //    (thisObject). This allows for easy use of object member functions
  //    in callbacks and other places in which the "this" keyword may
  //    otherwise not reference the expected scope. Note that the order of
  //    arguments may be reversed in a future version.
  // thisObject: the scope to run the method in
  // method:
  //    a function to be "bound" to thisObject or the name of the method in
  //    thisObject to be used as the basis for the binding
  // usage:
  //    dojo.lang.hitch(foo, "bar")(); // runs foo.bar() in the scope of foo
  //    dojo.lang.hitch(foo, myFunction); // returns a function that runs myFunction in the scope of foo

  // FIXME:
  //    should this be extended to "fixate" arguments in a manner similar
  //    to dojo.lang.curry, but without the default execution of curry()?
  var fcn = (dojo.lang.isString(method) ? thisObject[method] : method) || function(){};
  return function(){
    return fcn.apply(thisObject, arguments); // Function
  };
}

var dj_currentContext = this;
var dj_currentDocument = this.document;
dojo.global = function(){
  // summary:
  //    return the current global context object
  //    (e.g., the window object in a browser).
  // description:
  //    Refer to 'dojo.global()' rather than referring to window to ensure your
  //    code runs correctly in contexts other than web browsers (eg: Rhino on a server).
  return dj_currentContext;
}

dojo.doc = function(){
  // summary:
  //    return the document object associated with the dojo.global()
  return dj_currentDocument;
}

dojo.html = {};
dojo.html.getViewport = function(){
  //  summary
  //  Returns the dimensions of the viewable area of a browser window
  var _window = dojo.global();
  var _document = dojo.doc();
  var w = 0;
  var h = 0;

  if(dojo.render.html.mozilla){
    // mozilla
    w = _document.documentElement.clientWidth;
    h = _window.innerHeight;
  }else if(!dojo.render.html.opera && _window.innerWidth){
    //in opera9, dojo.body().clientWidth should be used, instead
    //of window.innerWidth/document.documentElement.clientWidth
    //so we have to check whether it is opera
    w = _window.innerWidth;
    h = _window.innerHeight;
  } else if (!dojo.render.html.opera && dojo.exists(_document, "documentElement.clientWidth")){
    // IE6 Strict
    var w2 = _document.documentElement.clientWidth;
    // this lets us account for scrollbars
    if(!w || w2 && w2 < w) {
      w = w2;
    }
    h = _document.documentElement.clientHeight;
  } else if (dojo.body().clientWidth){
    // IE, Opera
    w = dojo.body().clientWidth;
    h = dojo.body().clientHeight;
  }
  return { width: w, height: h }; //  object
}

dojo.render = (function(){
  //TODOC: HOW TO DOC THIS?
  // summary: Details rendering support, OS and browser of the current environment.
  // TODOC: is this something many folks will interact with?  If so, we should doc the structure created...
  function vscaffold(prefs, names){
    var tmp = {
      capable: false,
      support: {
        builtin: false,
        plugin: false
      },
      prefixes: prefs
    };
    for(var i=0; i<names.length; i++){
      tmp[names[i]] = false;
    }
    return tmp;
  }

  return {
    name: "",
    ver: dojo.version,
    os: { win: false, linux: false, osx: false },
    html: vscaffold(["html"], ["ie", "opera", "khtml", "safari", "moz"]),
    svg: vscaffold(["svg"], ["corel", "adobe", "batik"]),
    vml: vscaffold(["vml"], ["ie"]),
    swf: vscaffold(["Swf", "Flash", "Mm"], ["mm"]),
    swt: vscaffold(["Swt"], ["ibm"])
  };
})();

dojo.exists = function(/*Object*/obj, /*String*/name){
  // summary: determine if an object supports a given method
  // description: useful for longer api chains where you have to test each object in the chain
  var p = name.split(".");
  for(var i = 0; i < p.length; i++){
    if(!obj[p[i]]){ return false; } // Boolean
    obj = obj[p[i]];
  }
  return true; // Boolean
}

window.onload = FindOutHow.PageLoad;

function imagePop(imgX)
{
	OpenWindow=window.open("", "newwin", "toolbar=no,menubar=no,location=no,scrollbars=yes");
	OpenWindow.document.write("<TITLE>Image Viewer</TITLE>")
	OpenWindow.document.write("<BODY style='background: #303030;'>")
	OpenWindow.document.write("<img src='img/" + imgX +"' />")
	OpenWindow.document.write("</BODY>")
	OpenWindow.document.write("</HTML>")
	
	OpenWindow.document.close()
	self.name="main"
}

