
function ImageUrl(isize,iiid,iindex){
	iurl = 'http://globaldyn.ipnstock.com/'+dynimagesname+ '/' + isize + '/' + iiid + '.JPG';
	
	// remote url detect
	if(typeof(iindex)=='undefined')
	{                  
		// seek the index of this particular id if it isn't already known
	        for(iii=0;iii<id.length;iii++)
		{
			if(id[iii] == iiid)
	                       iindex =iii;
	        }
	}
	
	/* 
         test for remote size available and that we're not already in a safety mode of not available at remote location
	 imagesafetymode is local "sense there is a problem with remote hosting failover";
	 if url has http it's absolute otherwise use the base path
        */

	//imagesafetymode=0;
	if(typeof(primary_turl) != 'undefined' && typeof(imagesafetymode)=='undefined' && typeof(primary_turl[iindex]) !='undefined' && primary_turl[iindex].indexOf(isize)>=0)
	{
 		iurl = (primary_turl[iindex].indexOf('http') >=0 ? '' :  remotemediaprefix1.split('|')[primary_turl[iindex].split('~')[0]]) + '/' + isize + '/' + iiid.substr(0,2) + '/' + iiid.substr(0,iiid.length-5) + '/' + iiid + '.JPG';
	}
	
	return iurl;
}

function InitSafetyCheck(isize){
        //seek first remote media id for this isize
        if(typeof(testLoadImage)=='undefined')
        {
                this.remoteAssetLoad = function(){
//                                        alert('We are Sorry. We have detected that something is wrong with you being able to view our images.'
  //                                      + this.src + ' We will now switch you to an alternate image location. We are sorry for the delay.');
                                        imagesafetymode=1; // temporarily changes to safety mode and reverts to default hosting location
                                        currentpage();
                                        };

		if(typeof(primary_turl) == 'undefined')
                {
                	        testLoadImage=new Image ();
                        	remoteAssetLoad();
                }
		else
		{

 	               var iii=0;
        	        while( (iii < primary_turl.length) && (primary_turl[iii].indexOf(isize)<1) )
                	{        // seek the first id for this specific size
                        	iii++;
                	}


	                if(iii >= primary_turl.length)
        	        {
                	        testLoadImage=new Image ();
                        	remoteAssetLoad();
                	}
                	else
			{
 	                       testLoadImage=new Image ();
        	                testLoadImage.src= (primary_turl[iii].indexOf('http') >=0 ? '' : remotemediaprefix1.split('|')[primary_turl[[iii]].split('~')[0]] + '/' + isize + '/' + id[iii].substr(0,2) + '/' + id[iii].substr(0,id[iii].length-5) + '/' + id[iii] + '.JPG');

 	                       testLoadImage.onload = function(){
                                                  if(this.height==0 || this.width==0)
                                                  {
                                                        remoteAssetLoad();
                                                  }
                                                };

 	                       testLoadImage.onerror= remoteAssetLoad;
        	                testLoadImage.onabort= remoteAssetLoad;

 	               }
		}
        }
}







/*  Prototype JavaScript framework, version 1.5.1.1
 *  (c) 2005-2007 Sam Stephenson
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://www.prototypejs.org/
 *
/*--------------------------------------------------------------------------*/

var Prototype = {
  Version: '1.5.1.1',

  Browser: {
    IE:     !!(window.attachEvent && !window.opera),
    Opera:  !!window.opera,
    WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
    Gecko:  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1
  },

  BrowserFeatures: {
    XPath: !!document.evaluate,
    ElementExtensions: !!window.HTMLElement,
    SpecificElementExtensions:
      (document.createElement('div').__proto__ !==
       document.createElement('form').__proto__)
  },

  ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
  JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,

  emptyFunction: function() { },
  K: function(x) { return x }
}

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}

var Abstract = new Object();

Object.extend = function(destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }
  return destination;
}

Object.extend(Object, {
  inspect: function(object) {
    try {
      if (object === undefined) return 'undefined';
      if (object === null) return 'null';
      return object.inspect ? object.inspect() : object.toString();
    } catch (e) {
      if (e instanceof RangeError) return '...';
      throw e;
    }
  },

  toJSON: function(object) {
    var type = typeof object;
    switch(type) {
      case 'undefined':
      case 'function':
      case 'unknown': return;
      case 'boolean': return object.toString();
    }
    if (object === null) return 'null';
    if (object.toJSON) return object.toJSON();
    if (object.ownerDocument === document) return;
    var results = [];
    for (var property in object) {
      var value = Object.toJSON(object[property]);
      if (value !== undefined)
        results.push(property.toJSON() + ': ' + value);
    }
    return '{' + results.join(', ') + '}';
  },

  keys: function(object) {
    var keys = [];
    for (var property in object)
      keys.push(property);
    return keys;
  },

  values: function(object) {
    var values = [];
    for (var property in object)
      values.push(object[property]);
    return values;
  },

  clone: function(object) {
    return Object.extend({}, object);
  }
});

Function.prototype.bind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($A(arguments)));
  }
}

Function.prototype.bindAsEventListener = function(object) {
  var __method = this, args = $A(arguments), object = args.shift();
  return function(event) {
    return __method.apply(object, [event || window.event].concat(args));
  }
}

Object.extend(Number.prototype, {
  toColorPart: function() {
    return this.toPaddedString(2, 16);
  },

  succ: function() {
    return this + 1;
  },

  times: function(iterator) {
    $R(0, this, true).each(iterator);
    return this;
  },

  toPaddedString: function(length, radix) {
    var string = this.toString(radix || 10);
    return '0'.times(length - string.length) + string;
  },

  toJSON: function() {
    return isFinite(this) ? this.toString() : 'null';
  }
});

Date.prototype.toJSON = function() {
  return '"' + this.getFullYear() + '-' +
    (this.getMonth() + 1).toPaddedString(2) + '-' +
    this.getDate().toPaddedString(2) + 'T' +
    this.getHours().toPaddedString(2) + ':' +
    this.getMinutes().toPaddedString(2) + ':' +
    this.getSeconds().toPaddedString(2) + '"';
};

var Try = {
  these: function() {
    var returnValue;

    for (var i = 0, length = arguments.length; i < length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }

    return returnValue;
  }
}

/*--------------------------------------------------------------------------*/

var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;

    this.registerCallback();
  },

  registerCallback: function() {
    this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  stop: function() {
    if (!this.timer) return;
    clearInterval(this.timer);
    this.timer = null;
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.callback(this);
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
}
Object.extend(String, {
  interpret: function(value) {
    return value == null ? '' : String(value);
  },
  specialChar: {
    '\b': '\\b',
    '\t': '\\t',
    '\n': '\\n',
    '\f': '\\f',
    '\r': '\\r',
    '\\': '\\\\'
  }
});

Object.extend(String.prototype, {
  gsub: function(pattern, replacement) {
    var result = '', source = this, match;
    replacement = arguments.callee.prepareReplacement(replacement);

    while (source.length > 0) {
      if (match = source.match(pattern)) {
        result += source.slice(0, match.index);
        result += String.interpret(replacement(match));
        source  = source.slice(match.index + match[0].length);
      } else {
        result += source, source = '';
      }
    }
    return result;
  },

  sub: function(pattern, replacement, count) {
    replacement = this.gsub.prepareReplacement(replacement);
    count = count === undefined ? 1 : count;

    return this.gsub(pattern, function(match) {
      if (--count < 0) return match[0];
      return replacement(match);
    });
  },

  scan: function(pattern, iterator) {
    this.gsub(pattern, iterator);
    return this;
  },

  truncate: function(length, truncation) {
    length = length || 30;
    truncation = truncation === undefined ? '...' : truncation;
    return this.length > length ?
      this.slice(0, length - truncation.length) + truncation : this;
  },

  strip: function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  },

  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },

  stripScripts: function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },

  extractScripts: function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(matchOne) || ['', ''])[1];
    });
  },

  evalScripts: function() {
    return this.extractScripts().map(function(script) { return eval(script) });
  },

  escapeHTML: function() {
    var self = arguments.callee;
    self.text.data = this;
    return self.div.innerHTML;
  },

  unescapeHTML: function() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? (div.childNodes.length > 1 ?
      $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
      div.childNodes[0].nodeValue) : '';
  },

  toQueryParams: function(separator) {
    var match = this.strip().match(/([^?#]*)(#.*)?$/);
    if (!match) return {};

    return match[1].split(separator || '&').inject({}, function(hash, pair) {
      if ((pair = pair.split('='))[0]) {
        var key = decodeURIComponent(pair.shift());
        var value = pair.length > 1 ? pair.join('=') : pair[0];
        if (value != undefined) value = decodeURIComponent(value);

        if (key in hash) {
          if (hash[key].constructor != Array) hash[key] = [hash[key]];
          hash[key].push(value);
        }
        else hash[key] = value;
      }
      return hash;
    });
  },

  toArray: function() {
    return this.split('');
  },

  succ: function() {
    return this.slice(0, this.length - 1) +
      String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
  },

  times: function(count) {
    var result = '';
    for (var i = 0; i < count; i++) result += this;
    return result;
  },

  camelize: function() {
    var parts = this.split('-'), len = parts.length;
    if (len == 1) return parts[0];

    var camelized = this.charAt(0) == '-'
      ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
      : parts[0];

    for (var i = 1; i < len; i++)
      camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);

    return camelized;
  },

  capitalize: function() {
    return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  },

  underscore: function() {
    return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
  },

  dasherize: function() {
    return this.gsub(/_/,'-');
  },

  inspect: function(useDoubleQuotes) {
    var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
      var character = String.specialChar[match[0]];
      return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
    });
    if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
    return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  },

  toJSON: function() {
    return this.inspect(true);
  },

  unfilterJSON: function(filter) {
    return this.sub(filter || Prototype.JSONFilter, '#{1}');
  },

  isJSON: function() {
    var str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
    return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
  },

  evalJSON: function(sanitize) {
    var json = this.unfilterJSON();
    try {
      if (!sanitize || json.isJSON()) return eval('(' + json + ')');
    } catch (e) { }
    throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
  },

  include: function(pattern) {
    return this.indexOf(pattern) > -1;
  },

  startsWith: function(pattern) {
    return this.indexOf(pattern) === 0;
  },

  endsWith: function(pattern) {
    var d = this.length - pattern.length;
    return d >= 0 && this.lastIndexOf(pattern) === d;
  },

  empty: function() {
    return this == '';
  },

  blank: function() {
    return /^\s*$/.test(this);
  }
});

if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, {
  escapeHTML: function() {
    return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  },
  unescapeHTML: function() {
    return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
  }
});

String.prototype.gsub.prepareReplacement = function(replacement) {
  if (typeof replacement == 'function') return replacement;
  var template = new Template(replacement);
  return function(match) { return template.evaluate(match) };
}

String.prototype.parseQuery = String.prototype.toQueryParams;

Object.extend(String.prototype.escapeHTML, {
  div:  document.createElement('div'),
  text: document.createTextNode('')
});

with (String.prototype.escapeHTML) div.appendChild(text);

var Template = Class.create();
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
Template.prototype = {
  initialize: function(template, pattern) {
    this.template = template.toString();
    this.pattern  = pattern || Template.Pattern;
  },

  evaluate: function(object) {
    return this.template.gsub(this.pattern, function(match) {
      var before = match[1];
      if (before == '\\') return match[2];
      return before + String.interpret(object[match[3]]);
    });
  }
}

var $break = {}, $continue = new Error('"throw $continue" is deprecated, use "return" instead');

var Enumerable = {
  each: function(iterator) {
    var index = 0;
    try {
      this._each(function(value) {
        iterator(value, index++);
      });
    } catch (e) {
      if (e != $break) throw e;
    }
    return this;
  },

  eachSlice: function(number, iterator) {
    var index = -number, slices = [], array = this.toArray();
    while ((index += number) < array.length)
      slices.push(array.slice(index, index+number));
    return slices.map(iterator);
  },

  all: function(iterator) {
    var result = true;
    this.each(function(value, index) {
      result = result && !!(iterator || Prototype.K)(value, index);
      if (!result) throw $break;
    });
    return result;
  },

  any: function(iterator) {
    var result = false;
    this.each(function(value, index) {
      if (result = !!(iterator || Prototype.K)(value, index))
        throw $break;
    });
    return result;
  },

  collect: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      results.push((iterator || Prototype.K)(value, index));
    });
    return results;
  },

  detect: function(iterator) {
    var result;
    this.each(function(value, index) {
      if (iterator(value, index)) {
        result = value;
        throw $break;
      }
    });
    return result;
  },

  findAll: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (iterator(value, index))
        results.push(value);
    });
    return results;
  },

  grep: function(pattern, iterator) {
    var results = [];
    this.each(function(value, index) {
      var stringValue = value.toString();
      if (stringValue.match(pattern))
        results.push((iterator || Prototype.K)(value, index));
    })
    return results;
  },

  include: function(object) {
    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
        throw $break;
      }
    });
    return found;
  },

  inGroupsOf: function(number, fillWith) {
    fillWith = fillWith === undefined ? null : fillWith;
    return this.eachSlice(number, function(slice) {
      while(slice.length < number) slice.push(fillWith);
      return slice;
    });
  },

  inject: function(memo, iterator) {
    this.each(function(value, index) {
      memo = iterator(memo, value, index);
    });
    return memo;
  },

  invoke: function(method) {
    var args = $A(arguments).slice(1);
    return this.map(function(value) {
      return value[method].apply(value, args);
    });
  },

  max: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value >= result)
        result = value;
    });
    return result;
  },

  min: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value < result)
        result = value;
    });
    return result;
  },

  partition: function(iterator) {
    var trues = [], falses = [];
    this.each(function(value, index) {
      ((iterator || Prototype.K)(value, index) ?
        trues : falses).push(value);
    });
    return [trues, falses];
  },

  pluck: function(property) {
    var results = [];
    this.each(function(value, index) {
      results.push(value[property]);
    });
    return results;
  },

  reject: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (!iterator(value, index))
        results.push(value);
    });
    return results;
  },

  sortBy: function(iterator) {
    return this.map(function(value, index) {
      return {value: value, criteria: iterator(value, index)};
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a < b ? -1 : a > b ? 1 : 0;
    }).pluck('value');
  },

  toArray: function() {
    return this.map();
  },

  zip: function() {
    var iterator = Prototype.K, args = $A(arguments);
    if (typeof args.last() == 'function')
      iterator = args.pop();

    var collections = [this].concat(args).map($A);
    return this.map(function(value, index) {
      return iterator(collections.pluck(index));
    });
  },

  size: function() {
    return this.toArray().length;
  },

  inspect: function() {
    return '#<Enumerable:' + this.toArray().inspect() + '>';
  }
}

Object.extend(Enumerable, {
  map:     Enumerable.collect,
  find:    Enumerable.detect,
  select:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray
});
var $A = Array.from = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0, length = iterable.length; i < length; i++)
      results.push(iterable[i]);
    return results;
  }
}

if (Prototype.Browser.WebKit) {
  $A = Array.from = function(iterable) {
    if (!iterable) return [];
    if (!(typeof iterable == 'function' && iterable == '[object NodeList]') &&
      iterable.toArray) {
      return iterable.toArray();
    } else {
      var results = [];
      for (var i = 0, length = iterable.length; i < length; i++)
        results.push(iterable[i]);
      return results;
    }
  }
}

Object.extend(Array.prototype, Enumerable);

if (!Array.prototype._reverse)
  Array.prototype._reverse = Array.prototype.reverse;

Object.extend(Array.prototype, {
  _each: function(iterator) {
    for (var i = 0, length = this.length; i < length; i++)
      iterator(this[i]);
  },

  clear: function() {
    this.length = 0;
    return this;
  },

  first: function() {
    return this[0];
  },

  last: function() {
    return this[this.length - 1];
  },

  compact: function() {
    return this.select(function(value) {
      return value != null;
    });
  },

  flatten: function() {
    return this.inject([], function(array, value) {
      return array.concat(value && value.constructor == Array ?
        value.flatten() : [value]);
    });
  },

  without: function() {
    var values = $A(arguments);
    return this.select(function(value) {
      return !values.include(value);
    });
  },

  indexOf: function(object) {
    for (var i = 0, length = this.length; i < length; i++)
      if (this[i] == object) return i;
    return -1;
  },

  reverse: function(inline) {
    return (inline !== false ? this : this.toArray())._reverse();
  },

  reduce: function() {
    return this.length > 1 ? this : this[0];
  },

  uniq: function(sorted) {
    return this.inject([], function(array, value, index) {
      if (0 == index || (sorted ? array.last() != value : !array.include(value)))
        array.push(value);
      return array;
    });
  },

  clone: function() {
    return [].concat(this);
  },

  size: function() {
    return this.length;
  },

  inspect: function() {
    return '[' + this.map(Object.inspect).join(', ') + ']';
  },

  toJSON: function() {
    var results = [];
    this.each(function(object) {
      var value = Object.toJSON(object);
      if (value !== undefined) results.push(value);
    });
    return '[' + results.join(', ') + ']';
  }
});

Array.prototype.toArray = Array.prototype.clone;

function $w(string) {
  string = string.strip();
  return string ? string.split(/\s+/) : [];
}

if (Prototype.Browser.Opera){
  Array.prototype.concat = function() {
    var array = [];
    for (var i = 0, length = this.length; i < length; i++) array.push(this[i]);
    for (var i = 0, length = arguments.length; i < length; i++) {
      if (arguments[i].constructor == Array) {
        for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
          array.push(arguments[i][j]);
      } else {
        array.push(arguments[i]);
      }
    }
    return array;
  }
}
var Hash = function(object) {
  if (object instanceof Hash) this.merge(object);
  else Object.extend(this, object || {});
};

Object.extend(Hash, {
  toQueryString: function(obj) {
    var parts = [];
    parts.add = arguments.callee.addPair;

    this.prototype._each.call(obj, function(pair) {
      if (!pair.key) return;
      var value = pair.value;

      if (value && typeof value == 'object') {
        if (value.constructor == Array) value.each(function(value) {
          parts.add(pair.key, value);
        });
        return;
      }
      parts.add(pair.key, value);
    });

    return parts.join('&');
  },

  toJSON: function(object) {
    var results = [];
    this.prototype._each.call(object, function(pair) {
      var value = Object.toJSON(pair.value);
      if (value !== undefined) results.push(pair.key.toJSON() + ': ' + value);
    });
    return '{' + results.join(', ') + '}';
  }
});

Hash.toQueryString.addPair = function(key, value, prefix) {
  key = encodeURIComponent(key);
  if (value === undefined) this.push(key);
  else this.push(key + '=' + (value == null ? '' : encodeURIComponent(value)));
}

Object.extend(Hash.prototype, Enumerable);
Object.extend(Hash.prototype, {
  _each: function(iterator) {
    for (var key in this) {
      var value = this[key];
      if (value && value == Hash.prototype[key]) continue;

      var pair = [key, value];
      pair.key = key;
      pair.value = value;
      iterator(pair);
    }
  },

  keys: function() {
    return this.pluck('key');
  },

  values: function() {
    return this.pluck('value');
  },

  merge: function(hash) {
    return $H(hash).inject(this, function(mergedHash, pair) {
      mergedHash[pair.key] = pair.value;
      return mergedHash;
    });
  },

  remove: function() {
    var result;
    for(var i = 0, length = arguments.length; i < length; i++) {
      var value = this[arguments[i]];
      if (value !== undefined){
        if (result === undefined) result = value;
        else {
          if (result.constructor != Array) result = [result];
          result.push(value)
        }
      }
      delete this[arguments[i]];
    }
    return result;
  },

  toQueryString: function() {
    return Hash.toQueryString(this);
  },

  inspect: function() {
    return '#<Hash:{' + this.map(function(pair) {
      return pair.map(Object.inspect).join(': ');
    }).join(', ') + '}>';
  },

  toJSON: function() {
    return Hash.toJSON(this);
  }
});

function $H(object) {
  if (object instanceof Hash) return object;
  return new Hash(object);
};

// Safari iterates over shadowed properties
if (function() {
  var i = 0, Test = function(value) { this.key = value };
  Test.prototype.key = 'foo';
  for (var property in new Test('bar')) i++;
  return i > 1;
}()) Hash.prototype._each = function(iterator) {
  var cache = [];
  for (var key in this) {
    var value = this[key];
    if ((value && value == Hash.prototype[key]) || cache.include(key)) continue;
    cache.push(key);
    var pair = [key, value];
    pair.key = key;
    pair.value = value;
    iterator(pair);
  }
};
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
  initialize: function(start, end, exclusive) {
    this.start = start;
    this.end = end;
    this.exclusive = exclusive;
  },

  _each: function(iterator) {
    var value = this.start;
    while (this.include(value)) {
      iterator(value);
      value = value.succ();
    }
  },

  include: function(value) {
    if (value < this.start)
      return false;
    if (this.exclusive)
      return value < this.end;
    return value <= this.end;
  }
});

var $R = function(start, end, exclusive) {
  return new ObjectRange(start, end, exclusive);
}

var Ajax = {
  getTransport: function() {
    return Try.these(
      function() {return new XMLHttpRequest()},
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')}
    ) || false;
  },

  activeRequestCount: 0
}

Ajax.Responders = {
  responders: [],

  _each: function(iterator) {
    this.responders._each(iterator);
  },

  register: function(responder) {
    if (!this.include(responder))
      this.responders.push(responder);
  },

  unregister: function(responder) {
    this.responders = this.responders.without(responder);
  },

  dispatch: function(callback, request, transport, json) {
    this.each(function(responder) {
      if (typeof responder[callback] == 'function') {
        try {
          responder[callback].apply(responder, [request, transport, json]);
        } catch (e) {}
      }
    });
  }
};

Object.extend(Ajax.Responders, Enumerable);

Ajax.Responders.register({
  onCreate: function() {
    Ajax.activeRequestCount++;
  },
  onComplete: function() {
    Ajax.activeRequestCount--;
  }
});

Ajax.Base = function() {};
Ajax.Base.prototype = {
  setOptions: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      encoding:     'UTF-8',
      parameters:   ''
    }
    Object.extend(this.options, options || {});

    this.options.method = this.options.method.toLowerCase();
    if (typeof this.options.parameters == 'string')
      this.options.parameters = this.options.parameters.toQueryParams();
  }
}

Ajax.Request = Class.create();
Ajax.Request.Events =
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
  _complete: false,

  initialize: function(url, options) {
    this.transport = Ajax.getTransport();
    this.setOptions(options);
    this.request(url);
  },

  request: function(url) {
    this.url = url;
    this.method = this.options.method;
    var params = Object.clone(this.options.parameters);

    if (!['get', 'post'].include(this.method)) {
      // simulate other verbs over post
      params['_method'] = this.method;
      this.method = 'post';
    }

    this.parameters = params;

    if (params = Hash.toQueryString(params)) {
      // when GET, append parameters to URL
      if (this.method == 'get')
        this.url += (this.url.include('?') ? '&' : '?') + params;
      else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
        params += '&_=';
    }

    try {
      if (this.options.onCreate) this.options.onCreate(this.transport);
      Ajax.Responders.dispatch('onCreate', this, this.transport);

      this.transport.open(this.method.toUpperCase(), this.url,
        this.options.asynchronous);

      if (this.options.asynchronous)
        setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);

      this.transport.onreadystatechange = this.onStateChange.bind(this);
      this.setRequestHeaders();

      this.body = this.method == 'post' ? (this.options.postBody || params) : null;
      this.transport.send(this.body);

      /* Force Firefox to handle ready state 4 for synchronous requests */
      if (!this.options.asynchronous && this.transport.overrideMimeType)
        this.onStateChange();

    }
    catch (e) {
      this.dispatchException(e);
    }
  },

  onStateChange: function() {
    var readyState = this.transport.readyState;
    if (readyState > 1 && !((readyState == 4) && this._complete))
      this.respondToReadyState(this.transport.readyState);
  },

  setRequestHeaders: function() {
    var headers = {
      'X-Requested-With': 'XMLHttpRequest',
      'X-Prototype-Version': Prototype.Version,
      'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
    };

    if (this.method == 'post') {
      headers['Content-type'] = this.options.contentType +
        (this.options.encoding ? '; charset=' + this.options.encoding : '');

      /* Force "Connection: close" for older Mozilla browsers to work
       * around a bug where XMLHttpRequest sends an incorrect
       * Content-length header. See Mozilla Bugzilla #246651.
       */
      if (this.transport.overrideMimeType &&
          (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
            headers['Connection'] = 'close';
    }

    // user-defined headers
    if (typeof this.options.requestHeaders == 'object') {
      var extras = this.options.requestHeaders;

      if (typeof extras.push == 'function')
        for (var i = 0, length = extras.length; i < length; i += 2)
          headers[extras[i]] = extras[i+1];
      else
        $H(extras).each(function(pair) { headers[pair.key] = pair.value });
    }

    for (var name in headers)
      this.transport.setRequestHeader(name, headers[name]);
  },

  success: function() {
    return !this.transport.status
        || (this.transport.status >= 200 && this.transport.status < 300);
  },

  respondToReadyState: function(readyState) {
    var state = Ajax.Request.Events[readyState];
    var transport = this.transport, json = this.evalJSON();

    if (state == 'Complete') {
      try {
        this._complete = true;
        (this.options['on' + this.transport.status]
         || this.options['on' + (this.success() ? 'Success' : 'Failure')]
         || Prototype.emptyFunction)(transport, json);
      } catch (e) {
        this.dispatchException(e);
      }

      var contentType = this.getHeader('Content-type');
      if (contentType && contentType.strip().
        match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i))
          this.evalResponse();
    }

    try {
      (this.options['on' + state] || Prototype.emptyFunction)(transport, json);
      Ajax.Responders.dispatch('on' + state, this, transport, json);
    } catch (e) {
      this.dispatchException(e);
    }

    if (state == 'Complete') {
      // avoid memory leak in MSIE: clean up
      this.transport.onreadystatechange = Prototype.emptyFunction;
    }
  },

  getHeader: function(name) {
    try {
      return this.transport.getResponseHeader(name);
    } catch (e) { return null }
  },

  evalJSON: function() {
    try {
      var json = this.getHeader('X-JSON');
      return json ? json.evalJSON() : null;
    } catch (e) { return null }
  },

  evalResponse: function() {
    try {
      return eval((this.transport.responseText || '').unfilterJSON());
    } catch (e) {
      this.dispatchException(e);
    }
  },

  dispatchException: function(exception) {
    (this.options.onException || Prototype.emptyFunction)(this, exception);
    Ajax.Responders.dispatch('onException', this, exception);
  }
});

Ajax.Updater = Class.create();

Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
  initialize: function(container, url, options) {
    this.container = {
      success: (container.success || container),
      failure: (container.failure || (container.success ? null : container))
    }

    this.transport = Ajax.getTransport();
    this.setOptions(options);

    var onComplete = this.options.onComplete || Prototype.emptyFunction;
    this.options.onComplete = (function(transport, param) {
      this.updateContent();
      onComplete(transport, param);
    }).bind(this);

    this.request(url);
  },

  updateContent: function() {
    var receiver = this.container[this.success() ? 'success' : 'failure'];
    var response = this.transport.responseText;

    if (!this.options.evalScripts) response = response.stripScripts();

    if (receiver = $(receiver)) {
      if (this.options.insertion)
        new this.options.insertion(receiver, response);
      else
        receiver.update(response);
    }

    if (this.success()) {
      if (this.onComplete)
        setTimeout(this.onComplete.bind(this), 10);
    }
  }
});

Ajax.PeriodicalUpdater = Class.create();
Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(container, url, options) {
    this.setOptions(options);
    this.onComplete = this.options.onComplete;

    this.frequency = (this.options.frequency || 2);
    this.decay = (this.options.decay || 1);

    this.updater = {};
    this.container = container;
    this.url = url;

    this.start();
  },

  start: function() {
    this.options.onComplete = this.updateComplete.bind(this);
    this.onTimerEvent();
  },

  stop: function() {
    this.updater.options.onComplete = undefined;
    clearTimeout(this.timer);
    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  },

  updateComplete: function(request) {
    if (this.options.decay) {
      this.decay = (request.responseText == this.lastText ?
        this.decay * this.options.decay : 1);

      this.lastText = request.responseText;
    }
    this.timer = setTimeout(this.onTimerEvent.bind(this),
      this.decay * this.frequency * 1000);
  },

  onTimerEvent: function() {
    this.updater = new Ajax.Updater(this.container, this.url, this.options);
  }
});
function $(element) {
  if (arguments.length > 1) {
    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if (typeof element == 'string')
    element = document.getElementById(element);
  return Element.extend(element);
}

if (Prototype.BrowserFeatures.XPath) {
  document._getElementsByXPath = function(expression, parentElement) {
    var results = [];
    var query = document.evaluate(expression, $(parentElement) || document,
      null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    for (var i = 0, length = query.snapshotLength; i < length; i++)
      results.push(query.snapshotItem(i));
    return results;
  };

  document.getElementsByClassName = function(className, parentElement) {
    var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]";
    return document._getElementsByXPath(q, parentElement);
  }

} else document.getElementsByClassName = function(className, parentElement) {
  var children = ($(parentElement) || document.body).getElementsByTagName('*');
  var elements = [], child, pattern = new RegExp("(^|\\s)" + className + "(\\s|$)");
  for (var i = 0, length = children.length; i < length; i++) {
    child = children[i];
    var elementClassName = child.className;
    if (elementClassName.length == 0) continue;
    if (elementClassName == className || elementClassName.match(pattern))
      elements.push(Element.extend(child));
  }
  return elements;
};

/*--------------------------------------------------------------------------*/

if (!window.Element) var Element = {};

Element.extend = function(element) {
  var F = Prototype.BrowserFeatures;
  if (!element || !element.tagName || element.nodeType == 3 ||
   element._extended || F.SpecificElementExtensions || element == window)
    return element;

  var methods = {}, tagName = element.tagName, cache = Element.extend.cache,
   T = Element.Methods.ByTag;

  // extend methods for all tags (Safari doesn't need this)
  if (!F.ElementExtensions) {
    Object.extend(methods, Element.Methods),
    Object.extend(methods, Element.Methods.Simulated);
  }

  // extend methods for specific tags
  if (T[tagName]) Object.extend(methods, T[tagName]);

  for (var property in methods) {
    var value = methods[property];
    if (typeof value == 'function' && !(property in element))
      element[property] = cache.findOrStore(value);
  }

  element._extended = Prototype.emptyFunction;
  return element;
};

Element.extend.cache = {
  findOrStore: function(value) {
    return this[value] = this[value] || function() {
      return value.apply(null, [this].concat($A(arguments)));
    }
  }
};

Element.Methods = {
  visible: function(element) {
    return $(element).style.display != 'none';
  },

  toggle: function(element) {
    element = $(element);
    Element[Element.visible(element) ? 'hide' : 'show'](element);
    return element;
  },

  hide: function(element) {
    $(element).style.display = 'none';
    return element;
  },

  show: function(element) {
    $(element).style.display = '';
    return element;
  },

  remove: function(element) {
    element = $(element);
    element.parentNode.removeChild(element);
    return element;
  },

  update: function(element, html) {
    html = typeof html == 'undefined' ? '' : html.toString();
    $(element).innerHTML = html.stripScripts();
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  },

  replace: function(element, html) {
    element = $(element);
    html = typeof html == 'undefined' ? '' : html.toString();
    if (element.outerHTML) {
      element.outerHTML = html.stripScripts();
    } else {
      var range = element.ownerDocument.createRange();
      range.selectNodeContents(element);
      element.parentNode.replaceChild(
        range.createContextualFragment(html.stripScripts()), element);
    }
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  },

  inspect: function(element) {
    element = $(element);
    var result = '<' + element.tagName.toLowerCase();
    $H({'id': 'id', 'className': 'class'}).each(function(pair) {
      var property = pair.first(), attribute = pair.last();
      var value = (element[property] || '').toString();
      if (value) result += ' ' + attribute + '=' + value.inspect(true);
    });
    return result + '>';
  },

  recursivelyCollect: function(element, property) {
    element = $(element);
    var elements = [];
    while (element = element[property])
      if (element.nodeType == 1)
        elements.push(Element.extend(element));
    return elements;
  },

  ancestors: function(element) {
    return $(element).recursivelyCollect('parentNode');
  },

  descendants: function(element) {
    return $A($(element).getElementsByTagName('*')).each(Element.extend);
  },

  firstDescendant: function(element) {
    element = $(element).firstChild;
    while (element && element.nodeType != 1) element = element.nextSibling;
    return $(element);
  },

  immediateDescendants: function(element) {
    if (!(element = $(element).firstChild)) return [];
    while (element && element.nodeType != 1) element = element.nextSibling;
    if (element) return [element].concat($(element).nextSiblings());
    return [];
  },

  previousSiblings: function(element) {
    return $(element).recursivelyCollect('previousSibling');
  },

  nextSiblings: function(element) {
    return $(element).recursivelyCollect('nextSibling');
  },

  siblings: function(element) {
    element = $(element);
    return element.previousSiblings().reverse().concat(element.nextSiblings());
  },

  match: function(element, selector) {
    if (typeof selector == 'string')
      selector = new Selector(selector);
    return selector.match($(element));
  },

  up: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return $(element.parentNode);
    var ancestors = element.ancestors();
    return expression ? Selector.findElement(ancestors, expression, index) :
      ancestors[index || 0];
  },

  down: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return element.firstDescendant();
    var descendants = element.descendants();
    return expression ? Selector.findElement(descendants, expression, index) :
      descendants[index || 0];
  },

  previous: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
    var previousSiblings = element.previousSiblings();
    return expression ? Selector.findElement(previousSiblings, expression, index) :
      previousSiblings[index || 0];
  },

  next: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
    var nextSiblings = element.nextSiblings();
    return expression ? Selector.findElement(nextSiblings, expression, index) :
      nextSiblings[index || 0];
  },

  getElementsBySelector: function() {
    var args = $A(arguments), element = $(args.shift());
    return Selector.findChildElements(element, args);
  },

  getElementsByClassName: function(element, className) {
    return document.getElementsByClassName(className, element);
  },

  readAttribute: function(element, name) {
    element = $(element);
    if (Prototype.Browser.IE) {
      if (!element.attributes) return null;
      var t = Element._attributeTranslations;
      if (t.values[name]) return t.values[name](element, name);
      if (t.names[name])  name = t.names[name];
      var attribute = element.attributes[name];
      return attribute ? attribute.nodeValue : null;
    }
    return element.getAttribute(name);
  },

  getHeight: function(element) {
    return $(element).getDimensions().height;
  },

  getWidth: function(element) {
    return $(element).getDimensions().width;
  },

  classNames: function(element) {
    return new Element.ClassNames(element);
  },

  hasClassName: function(element, className) {
    if (!(element = $(element))) return;
    var elementClassName = element.className;
    if (elementClassName.length == 0) return false;
    if (elementClassName == className ||
        elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
      return true;
    return false;
  },

  addClassName: function(element, className) {
    if (!(element = $(element))) return;
    Element.classNames(element).add(className);
    return element;
  },

  removeClassName: function(element, className) {
    if (!(element = $(element))) return;
    Element.classNames(element).remove(className);
    return element;
  },

  toggleClassName: function(element, className) {
    if (!(element = $(element))) return;
    Element.classNames(element)[element.hasClassName(className) ? 'remove' : 'add'](className);
    return element;
  },

  observe: function() {
    Event.observe.apply(Event, arguments);
    return $A(arguments).first();
  },

  stopObserving: function() {
    Event.stopObserving.apply(Event, arguments);
    return $A(arguments).first();
  },

  // removes whitespace-only text node children
  cleanWhitespace: function(element) {
    element = $(element);
    var node = element.firstChild;
    while (node) {
      var nextNode = node.nextSibling;
      if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
        element.removeChild(node);
      node = nextNode;
    }
    return element;
  },

  empty: function(element) {
    return $(element).innerHTML.blank();
  },

  descendantOf: function(element, ancestor) {
    element = $(element), ancestor = $(ancestor);
    while (element = element.parentNode)
      if (element == ancestor) return true;
    return false;
  },

  scrollTo: function(element) {
    element = $(element);
    var pos = Position.cumulativeOffset(element);
    window.scrollTo(pos[0], pos[1]);
    return element;
  },

  getStyle: function(element, style) {
    element = $(element);
    style = style == 'float' ? 'cssFloat' : style.camelize();
    var value = element.style[style];
    if (!value) {
      var css = document.defaultView.getComputedStyle(element, null);
      value = css ? css[style] : null;
    }
    if (style == 'opacity') return value ? parseFloat(value) : 1.0;
    return value == 'auto' ? null : value;
  },

  getOpacity: function(element) {
    return $(element).getStyle('opacity');
  },

  setStyle: function(element, styles, camelized) {
    element = $(element);
    var elementStyle = element.style;

    for (var property in styles)
      if (property == 'opacity') element.setOpacity(styles[property])
      else
        elementStyle[(property == 'float' || property == 'cssFloat') ?
          (elementStyle.styleFloat === undefined ? 'cssFloat' : 'styleFloat') :
          (camelized ? property : property.camelize())] = styles[property];

    return element;
  },

  setOpacity: function(element, value) {
    element = $(element);
    element.style.opacity = (value == 1 || value === '') ? '' :
      (value < 0.00001) ? 0 : value;
    return element;
  },

  getDimensions: function(element) {
    element = $(element);
    var display = $(element).getStyle('display');
    if (display != 'none' && display != null) // Safari bug
      return {width: element.offsetWidth, height: element.offsetHeight};

    // All *Width and *Height properties give 0 on elements with display none,
    // so enable the element temporarily
    var els = element.style;
    var originalVisibility = els.visibility;
    var originalPosition = els.position;
    var originalDisplay = els.display;
    els.visibility = 'hidden';
    els.position = 'absolute';
    els.display = 'block';
    var originalWidth = element.clientWidth;
    var originalHeight = element.clientHeight;
    els.display = originalDisplay;
    els.position = originalPosition;
    els.visibility = originalVisibility;
    return {width: originalWidth, height: originalHeight};
  },

  makePositioned: function(element) {
    element = $(element);
    var pos = Element.getStyle(element, 'position');
    if (pos == 'static' || !pos) {
      element._madePositioned = true;
      element.style.position = 'relative';
      // Opera returns the offset relative to the positioning context, when an
      // element is position relative but top and left have not been defined
      if (window.opera) {
        element.style.top = 0;
        element.style.left = 0;
      }
    }
    return element;
  },

  undoPositioned: function(element) {
    element = $(element);
    if (element._madePositioned) {
      element._madePositioned = undefined;
      element.style.position =
        element.style.top =
        element.style.left =
        element.style.bottom =
        element.style.right = '';
    }
    return element;
  },

  makeClipping: function(element) {
    element = $(element);
    if (element._overflow) return element;
    element._overflow = element.style.overflow || 'auto';
    if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
      element.style.overflow = 'hidden';
    return element;
  },

  undoClipping: function(element) {
    element = $(element);
    if (!element._overflow) return element;
    element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
    element._overflow = null;
    return element;
  }
};

Object.extend(Element.Methods, {
  childOf: Element.Methods.descendantOf,
  childElements: Element.Methods.immediateDescendants
});

if (Prototype.Browser.Opera) {
  Element.Methods._getStyle = Element.Methods.getStyle;
  Element.Methods.getStyle = function(element, style) {
    switch(style) {
      case 'left':
      case 'top':
      case 'right':
      case 'bottom':
        if (Element._getStyle(element, 'position') == 'static') return null;
      default: return Element._getStyle(element, style);
    }
  };
}
else if (Prototype.Browser.IE) {
  Element.Methods.getStyle = function(element, style) {
    element = $(element);
    style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
    var value = element.style[style];
    if (!value && element.currentStyle) value = element.currentStyle[style];

    if (style == 'opacity') {
      if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
        if (value[1]) return parseFloat(value[1]) / 100;
      return 1.0;
    }

    if (value == 'auto') {
      if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
        return element['offset'+style.capitalize()] + 'px';
      return null;
    }
    return value;
  };

  Element.Methods.setOpacity = function(element, value) {
    element = $(element);
    var filter = element.getStyle('filter'), style = element.style;
    if (value == 1 || value === '') {
      style.filter = filter.replace(/alpha\([^\)]*\)/gi,'');
      return element;
    } else if (value < 0.00001) value = 0;
    style.filter = filter.replace(/alpha\([^\)]*\)/gi, '') +
      'alpha(opacity=' + (value * 100) + ')';
    return element;
  };

  // IE is missing .innerHTML support for TABLE-related elements
  Element.Methods.update = function(element, html) {
    element = $(element);
    html = typeof html == 'undefined' ? '' : html.toString();
    var tagName = element.tagName.toUpperCase();
    if (['THEAD','TBODY','TR','TD'].include(tagName)) {
      var div = document.createElement('div');
      switch (tagName) {
        case 'THEAD':
        case 'TBODY':
          div.innerHTML = '<table><tbody>' +  html.stripScripts() + '</tbody></table>';
          depth = 2;
          break;
        case 'TR':
          div.innerHTML = '<table><tbody><tr>' +  html.stripScripts() + '</tr></tbody></table>';
          depth = 3;
          break;
        case 'TD':
          div.innerHTML = '<table><tbody><tr><td>' +  html.stripScripts() + '</td></tr></tbody></table>';
          depth = 4;
      }
      $A(element.childNodes).each(function(node) { element.removeChild(node) });
      depth.times(function() { div = div.firstChild });
      $A(div.childNodes).each(function(node) { element.appendChild(node) });
    } else {
      element.innerHTML = html.stripScripts();
    }
    setTimeout(function() { html.evalScripts() }, 10);
    return element;
  }
}
else if (Prototype.Browser.Gecko) {
  Element.Methods.setOpacity = function(element, value) {
    element = $(element);
    element.style.opacity = (value == 1) ? 0.999999 :
      (value === '') ? '' : (value < 0.00001) ? 0 : value;
    return element;
  };
}

Element._attributeTranslations = {
  names: {
    colspan:   "colSpan",
    rowspan:   "rowSpan",
    valign:    "vAlign",
    datetime:  "dateTime",
    accesskey: "accessKey",
    tabindex:  "tabIndex",
    enctype:   "encType",
    maxlength: "maxLength",
    readonly:  "readOnly",
    longdesc:  "longDesc"
  },
  values: {
    _getAttr: function(element, attribute) {
      return element.getAttribute(attribute, 2);
    },
    _flag: function(element, attribute) {
      return $(element).hasAttribute(attribute) ? attribute : null;
    },
    style: function(element) {
      return element.style.cssText.toLowerCase();
    },
    title: function(element) {
      var node = element.getAttributeNode('title');
      return node.specified ? node.nodeValue : null;
    }
  }
};

(function() {
  Object.extend(this, {
    href: this._getAttr,
    src:  this._getAttr,
    type: this._getAttr,
    disabled: this._flag,
    checked:  this._flag,
    readonly: this._flag,
    multiple: this._flag
  });
}).call(Element._attributeTranslations.values);

Element.Methods.Simulated = {
  hasAttribute: function(element, attribute) {
    var t = Element._attributeTranslations, node;
    attribute = t.names[attribute] || attribute;
    node = $(element).getAttributeNode(attribute);
    return node && node.specified;
  }
};

Element.Methods.ByTag = {};

Object.extend(Element, Element.Methods);

if (!Prototype.BrowserFeatures.ElementExtensions &&
 document.createElement('div').__proto__) {
  window.HTMLElement = {};
  window.HTMLElement.prototype = document.createElement('div').__proto__;
  Prototype.BrowserFeatures.ElementExtensions = true;
}

Element.hasAttribute = function(element, attribute) {
  if (element.hasAttribute) return element.hasAttribute(attribute);
  return Element.Methods.Simulated.hasAttribute(element, attribute);
};

Element.addMethods = function(methods) {
  var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;

  if (!methods) {
    Object.extend(Form, Form.Methods);
    Object.extend(Form.Element, Form.Element.Methods);
    Object.extend(Element.Methods.ByTag, {
      "FORM":     Object.clone(Form.Methods),
      "INPUT":    Object.clone(Form.Element.Methods),
      "SELECT":   Object.clone(Form.Element.Methods),
      "TEXTAREA": Object.clone(Form.Element.Methods)
    });
  }

  if (arguments.length == 2) {
    var tagName = methods;
    methods = arguments[1];
  }

  if (!tagName) Object.extend(Element.Methods, methods || {});
  else {
    if (tagName.constructor == Array) tagName.each(extend);
    else extend(tagName);
  }

  function extend(tagName) {
    tagName = tagName.toUpperCase();
    if (!Element.Methods.ByTag[tagName])
      Element.Methods.ByTag[tagName] = {};
    Object.extend(Element.Methods.ByTag[tagName], methods);
  }

  function copy(methods, destination, onlyIfAbsent) {
    onlyIfAbsent = onlyIfAbsent || false;
    var cache = Element.extend.cache;
    for (var property in methods) {
      var value = methods[property];
      if (!onlyIfAbsent || !(property in destination))
        destination[property] = cache.findOrStore(value);
    }
  }

  function findDOMClass(tagName) {
    var klass;
    var trans = {
      "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
      "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
      "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
      "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
      "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
      "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
      "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
      "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
      "FrameSet", "IFRAME": "IFrame"
    };
    if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
    if (window[klass]) return window[klass];
    klass = 'HTML' + tagName + 'Element';
    if (window[klass]) return window[klass];
    klass = 'HTML' + tagName.capitalize() + 'Element';
    if (window[klass]) return window[klass];

    window[klass] = {};
    window[klass].prototype = document.createElement(tagName).__proto__;
    return window[klass];
  }

  if (F.ElementExtensions) {
    copy(Element.Methods, HTMLElement.prototype);
    copy(Element.Methods.Simulated, HTMLElement.prototype, true);
  }

  if (F.SpecificElementExtensions) {
    for (var tag in Element.Methods.ByTag) {
      var klass = findDOMClass(tag);
      if (typeof klass == "undefined") continue;
      copy(T[tag], klass.prototype);
    }
  }

  Object.extend(Element, Element.Methods);
  delete Element.ByTag;
};

var Toggle = { display: Element.toggle };

/*--------------------------------------------------------------------------*/

Abstract.Insertion = function(adjacency) {
  this.adjacency = adjacency;
}

Abstract.Insertion.prototype = {
  initialize: function(element, content) {
    this.element = $(element);
    this.content = content.stripScripts();

    if (this.adjacency && this.element.insertAdjacentHTML) {
      try {
        this.element.insertAdjacentHTML(this.adjacency, this.content);
      } catch (e) {
        var tagName = this.element.tagName.toUpperCase();
        if (['TBODY', 'TR'].include(tagName)) {
          this.insertContent(this.contentFromAnonymousTable());
        } else {
          throw e;
        }
      }
    } else {
      this.range = this.element.ownerDocument.createRange();
      if (this.initializeRange) this.initializeRange();
      this.insertContent([this.range.createContextualFragment(this.content)]);
    }

    setTimeout(function() {content.evalScripts()}, 10);
  },

  contentFromAnonymousTable: function() {
    var div = document.createElement('div');
    div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
    return $A(div.childNodes[0].childNodes[0].childNodes);
  }
}

var Insertion = new Object();

Insertion.Before = Class.create();
Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
  initializeRange: function() {
    this.range.setStartBefore(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment, this.element);
    }).bind(this));
  }
});

Insertion.Top = Class.create();
Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(true);
  },

  insertContent: function(fragments) {
    fragments.reverse(false).each((function(fragment) {
      this.element.insertBefore(fragment, this.element.firstChild);
    }).bind(this));
  }
});

Insertion.Bottom = Class.create();
Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.appendChild(fragment);
    }).bind(this));
  }
});

Insertion.After = Class.create();
Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
  initializeRange: function() {
    this.range.setStartAfter(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment,
        this.element.nextSibling);
    }).bind(this));
  }
});

/*--------------------------------------------------------------------------*/

Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
  initialize: function(element) {
    this.element = $(element);
  },

  _each: function(iterator) {
    this.element.className.split(/\s+/).select(function(name) {
      return name.length > 0;
    })._each(iterator);
  },

  set: function(className) {
    this.element.className = className;
  },

  add: function(classNameToAdd) {
    if (this.include(classNameToAdd)) return;
    this.set($A(this).concat(classNameToAdd).join(' '));
  },

  remove: function(classNameToRemove) {
    if (!this.include(classNameToRemove)) return;
    this.set($A(this).without(classNameToRemove).join(' '));
  },

  toString: function() {
    return $A(this).join(' ');
  }
};

Object.extend(Element.ClassNames.prototype, Enumerable);
/* Portions of the Selector class are derived from Jack Slocumâ€™s DomQuery,
 * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
 * license.  Please see http://www.yui-ext.com/ for more information. */

var Selector = Class.create();

Selector.prototype = {
  initialize: function(expression) {
    this.expression = expression.strip();
    this.compileMatcher();
  },

  compileMatcher: function() {
    // Selectors with namespaced attributes can't use the XPath version
    if (Prototype.BrowserFeatures.XPath && !(/\[[\w-]*?:/).test(this.expression))
      return this.compileXPathMatcher();

    var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
        c = Selector.criteria, le, p, m;

    if (Selector._cache[e]) {
      this.matcher = Selector._cache[e]; return;
    }
    this.matcher = ["this.matcher = function(root) {",
                    "var r = root, h = Selector.handlers, c = false, n;"];

    while (e && le != e && (/\S/).test(e)) {
      le = e;
      for (var i in ps) {
        p = ps[i];
        if (m = e.match(p)) {
          this.matcher.push(typeof c[i] == 'function' ? c[i](m) :
    	      new Template(c[i]).evaluate(m));
          e = e.replace(m[0], '');
          break;
        }
      }
    }

    this.matcher.push("return h.unique(n);\n}");
    eval(this.matcher.join('\n'));
    Selector._cache[this.expression] = this.matcher;
  },

  compileXPathMatcher: function() {
    var e = this.expression, ps = Selector.patterns,
        x = Selector.xpath, le,  m;

    if (Selector._cache[e]) {
      this.xpath = Selector._cache[e]; return;
    }

    this.matcher = ['.//*'];
    while (e && le != e && (/\S/).test(e)) {
      le = e;
      for (var i in ps) {
        if (m = e.match(ps[i])) {
          this.matcher.push(typeof x[i] == 'function' ? x[i](m) :
            new Template(x[i]).evaluate(m));
          e = e.replace(m[0], '');
          break;
        }
      }
    }

    this.xpath = this.matcher.join('');
    Selector._cache[this.expression] = this.xpath;
  },

  findElements: function(root) {
    root = root || document;
    if (this.xpath) return document._getElementsByXPath(this.xpath, root);
    return this.matcher(root);
  },

  match: function(element) {
    return this.findElements(document).include(element);
  },

  toString: function() {
    return this.expression;
  },

  inspect: function() {
    return "#<Selector:" + this.expression.inspect() + ">";
  }
};

Object.extend(Selector, {
  _cache: {},

  xpath: {
    descendant:   "//*",
    child:        "/*",
    adjacent:     "/following-sibling::*[1]",
    laterSibling: '/following-sibling::*',
    tagName:      function(m) {
      if (m[1] == '*') return '';
      return "[local-name()='" + m[1].toLowerCase() +
             "' or local-name()='" + m[1].toUpperCase() + "']";
    },
    className:    "[contains(concat(' ', @class, ' '), ' #{1} ')]",
    id:           "[@id='#{1}']",
    attrPresence: "[@#{1}]",
    attr: function(m) {
      m[3] = m[5] || m[6];
      return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
    },
    pseudo: function(m) {
      var h = Selector.xpath.pseudos[m[1]];
      if (!h) return '';
      if (typeof h === 'function') return h(m);
      return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
    },
    operators: {
      '=':  "[@#{1}='#{3}']",
      '!=': "[@#{1}!='#{3}']",
      '^=': "[starts-with(@#{1}, '#{3}')]",
      '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
      '*=': "[contains(@#{1}, '#{3}')]",
      '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
      '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
    },
    pseudos: {
      'first-child': '[not(preceding-sibling::*)]',
      'last-child':  '[not(following-sibling::*)]',
      'only-child':  '[not(preceding-sibling::* or following-sibling::*)]',
      'empty':       "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",
      'checked':     "[@checked]",
      'disabled':    "[@disabled]",
      'enabled':     "[not(@disabled)]",
      'not': function(m) {
        var e = m[6], p = Selector.patterns,
            x = Selector.xpath, le, m, v;

        var exclusion = [];
        while (e && le != e && (/\S/).test(e)) {
          le = e;
          for (var i in p) {
            if (m = e.match(p[i])) {
              v = typeof x[i] == 'function' ? x[i](m) : new Template(x[i]).evaluate(m);
              exclusion.push("(" + v.substring(1, v.length - 1) + ")");
              e = e.replace(m[0], '');
              break;
            }
          }
        }
        return "[not(" + exclusion.join(" and ") + ")]";
      },
      'nth-child':      function(m) {
        return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
      },
      'nth-last-child': function(m) {
        return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
      },
      'nth-of-type':    function(m) {
        return Selector.xpath.pseudos.nth("position() ", m);
      },
      'nth-last-of-type': function(m) {
        return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
      },
      'first-of-type':  function(m) {
        m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
      },
      'last-of-type':   function(m) {
        m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
      },
      'only-of-type':   function(m) {
        var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
      },
      nth: function(fragment, m) {
        var mm, formula = m[6], predicate;
        if (formula == 'even') formula = '2n+0';
        if (formula == 'odd')  formula = '2n+1';
        if (mm = formula.match(/^(\d+)$/)) // digit only
          return '[' + fragment + "= " + mm[1] + ']';
        if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
          if (mm[1] == "-") mm[1] = -1;
          var a = mm[1] ? Number(mm[1]) : 1;
          var b = mm[2] ? Number(mm[2]) : 0;
          predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
          "((#{fragment} - #{b}) div #{a} >= 0)]";
          return new Template(predicate).evaluate({
            fragment: fragment, a: a, b: b });
        }
      }
    }
  },

  criteria: {
    tagName:      'n = h.tagName(n, r, "#{1}", c);   c = false;',
    className:    'n = h.className(n, r, "#{1}", c); c = false;',
    id:           'n = h.id(n, r, "#{1}", c);        c = false;',
    attrPresence: 'n = h.attrPresence(n, r, "#{1}"); c = false;',
    attr: function(m) {
      m[3] = (m[5] || m[6]);
      return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}"); c = false;').evaluate(m);
    },
    pseudo:       function(m) {
      if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
      return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
    },
    descendant:   'c = "descendant";',
    child:        'c = "child";',
    adjacent:     'c = "adjacent";',
    laterSibling: 'c = "laterSibling";'
  },

  patterns: {
    // combinators must be listed first
    // (and descendant needs to be last combinator)
    laterSibling: /^\s*~\s*/,
    child:        /^\s*>\s*/,
    adjacent:     /^\s*\+\s*/,
    descendant:   /^\s/,

    // selectors follow
    tagName:      /^\s*(\*|[\w\-]+)(\b|$)?/,
    id:           /^#([\w\-\*]+)(\b|$)/,
    className:    /^\.([\w\-\*]+)(\b|$)/,
    pseudo:       /^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|\s|(?=:))/,
    attrPresence: /^\[([\w]+)\]/,
    attr:         /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\]]*?)\4|([^'"][^\]]*?)))?\]/
  },

  handlers: {
    // UTILITY FUNCTIONS
    // joins two collections
    concat: function(a, b) {
      for (var i = 0, node; node = b[i]; i++)
        a.push(node);
      return a;
    },

    // marks an array of nodes for counting
    mark: function(nodes) {
      for (var i = 0, node; node = nodes[i]; i++)
        node._counted = true;
      return nodes;
    },

    unmark: function(nodes) {
      for (var i = 0, node; node = nodes[i]; i++)
        node._counted = undefined;
      return nodes;
    },

    // mark each child node with its position (for nth calls)
    // "ofType" flag indicates whether we're indexing for nth-of-type
    // rather than nth-child
    index: function(parentNode, reverse, ofType) {
      parentNode._counted = true;
      if (reverse) {
        for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
          node = nodes[i];
          if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++;
        }
      } else {
        for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
          if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++;
      }
    },

    // filters out duplicates and extends all nodes
    unique: function(nodes) {
      if (nodes.length == 0) return nodes;
      var results = [], n;
      for (var i = 0, l = nodes.length; i < l; i++)
        if (!(n = nodes[i])._counted) {
          n._counted = true;
          results.push(Element.extend(n));
        }
      return Selector.handlers.unmark(results);
    },

    // COMBINATOR FUNCTIONS
    descendant: function(nodes) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        h.concat(results, node.getElementsByTagName('*'));
      return results;
    },

    child: function(nodes) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        for (var j = 0, children = [], child; child = node.childNodes[j]; j++)
          if (child.nodeType == 1 && child.tagName != '!') results.push(child);
      }
      return results;
    },

    adjacent: function(nodes) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        var next = this.nextElementSibling(node);
        if (next) results.push(next);
      }
      return results;
    },

    laterSibling: function(nodes) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        h.concat(results, Element.nextSiblings(node));
      return results;
    },

    nextElementSibling: function(node) {
      while (node = node.nextSibling)
	      if (node.nodeType == 1) return node;
      return null;
    },

    previousElementSibling: function(node) {
      while (node = node.previousSibling)
        if (node.nodeType == 1) return node;
      return null;
    },

    // TOKEN FUNCTIONS
    tagName: function(nodes, root, tagName, combinator) {
      tagName = tagName.toUpperCase();
      var results = [], h = Selector.handlers;
      if (nodes) {
        if (combinator) {
          // fastlane for ordinary descendant combinators
          if (combinator == "descendant") {
            for (var i = 0, node; node = nodes[i]; i++)
              h.concat(results, node.getElementsByTagName(tagName));
            return results;
          } else nodes = this[combinator](nodes);
          if (tagName == "*") return nodes;
        }
        for (var i = 0, node; node = nodes[i]; i++)
          if (node.tagName.toUpperCase() == tagName) results.push(node);
        return results;
      } else return root.getElementsByTagName(tagName);
    },

    id: function(nodes, root, id, combinator) {
      var targetNode = $(id), h = Selector.handlers;
      if (!nodes && root == document) return targetNode ? [targetNode] : [];
      if (nodes) {
        if (combinator) {
          if (combinator == 'child') {
            for (var i = 0, node; node = nodes[i]; i++)
              if (targetNode.parentNode == node) return [targetNode];
          } else if (combinator == 'descendant') {
            for (var i = 0, node; node = nodes[i]; i++)
              if (Element.descendantOf(targetNode, node)) return [targetNode];
          } else if (combinator == 'adjacent') {
            for (var i = 0, node; node = nodes[i]; i++)
              if (Selector.handlers.previousElementSibling(targetNode) == node)
                return [targetNode];
          } else nodes = h[combinator](nodes);
        }
        for (var i = 0, node; node = nodes[i]; i++)
          if (node == targetNode) return [targetNode];
        return [];
      }
      return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
    },

    className: function(nodes, root, className, combinator) {
      if (nodes && combinator) nodes = this[combinator](nodes);
      return Selector.handlers.byClassName(nodes, root, className);
    },

    byClassName: function(nodes, root, className) {
      if (!nodes) nodes = Selector.handlers.descendant([root]);
      var needle = ' ' + className + ' ';
      for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
        nodeClassName = node.className;
        if (nodeClassName.length == 0) continue;
        if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
          results.push(node);
      }
      return results;
    },

    attrPresence: function(nodes, root, attr) {
      var results = [];
      for (var i = 0, node; node = nodes[i]; i++)
        if (Element.hasAttribute(node, attr)) results.push(node);
      return results;
    },

    attr: function(nodes, root, attr, value, operator) {
      if (!nodes) nodes = root.getElementsByTagName("*");
      var handler = Selector.operators[operator], results = [];
      for (var i = 0, node; node = nodes[i]; i++) {
        var nodeValue = Element.readAttribute(node, attr);
        if (nodeValue === null) continue;
        if (handler(nodeValue, value)) results.push(node);
      }
      return results;
    },

    pseudo: function(nodes, name, value, root, combinator) {
      if (nodes && combinator) nodes = this[combinator](nodes);
      if (!nodes) nodes = root.getElementsByTagName("*");
      return Selector.pseudos[name](nodes, value, root);
    }
  },

  pseudos: {
    'first-child': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        if (Selector.handlers.previousElementSibling(node)) continue;
          results.push(node);
      }
      return results;
    },
    'last-child': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        if (Selector.handlers.nextElementSibling(node)) continue;
          results.push(node);
      }
      return results;
    },
    'only-child': function(nodes, value, root) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
          results.push(node);
      return results;
    },
    'nth-child':        function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root);
    },
    'nth-last-child':   function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root, true);
    },
    'nth-of-type':      function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root, false, true);
    },
    'nth-last-of-type': function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root, true, true);
    },
    'first-of-type':    function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, "1", root, false, true);
    },
    'last-of-type':     function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, "1", root, true, true);
    },
    'only-of-type':     function(nodes, formula, root) {
      var p = Selector.pseudos;
      return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
    },

    // handles the an+b logic
    getIndices: function(a, b, total) {
      if (a == 0) return b > 0 ? [b] : [];
      return $R(1, total).inject([], function(memo, i) {
        if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
        return memo;
      });
    },

    // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type
    nth: function(nodes, formula, root, reverse, ofType) {
      if (nodes.length == 0) return [];
      if (formula == 'even') formula = '2n+0';
      if (formula == 'odd')  formula = '2n+1';
      var h = Selector.handlers, results = [], indexed = [], m;
      h.mark(nodes);
      for (var i = 0, node; node = nodes[i]; i++) {
        if (!node.parentNode._counted) {
          h.index(node.parentNode, reverse, ofType);
          indexed.push(node.parentNode);
        }
      }
      if (formula.match(/^\d+$/)) { // just a number
        formula = Number(formula);
        for (var i = 0, node; node = nodes[i]; i++)
          if (node.nodeIndex == formula) results.push(node);
      } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
        if (m[1] == "-") m[1] = -1;
        var a = m[1] ? Number(m[1]) : 1;
        var b = m[2] ? Number(m[2]) : 0;
        var indices = Selector.pseudos.getIndices(a, b, nodes.length);
        for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
          for (var j = 0; j < l; j++)
            if (node.nodeIndex == indices[j]) results.push(node);
        }
      }
      h.unmark(nodes);
      h.unmark(indexed);
      return results;
    },

    'empty': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        // IE treats comments as element nodes
        if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue;
        results.push(node);
      }
      return results;
    },

    'not': function(nodes, selector, root) {
      var h = Selector.handlers, selectorType, m;
      var exclusions = new Selector(selector).findElements(root);
      h.mark(exclusions);
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (!node._counted) results.push(node);
      h.unmark(exclusions);
      return results;
    },

    'enabled': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (!node.disabled) results.push(node);
      return results;
    },

    'disabled': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (node.disabled) results.push(node);
      return results;
    },

    'checked': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (node.checked) results.push(node);
      return results;
    }
  },

  operators: {
    '=':  function(nv, v) { return nv == v; },
    '!=': function(nv, v) { return nv != v; },
    '^=': function(nv, v) { return nv.startsWith(v); },
    '$=': function(nv, v) { return nv.endsWith(v); },
    '*=': function(nv, v) { return nv.include(v); },
    '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
    '|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); }
  },

  matchElements: function(elements, expression) {
    var matches = new Selector(expression).findElements(), h = Selector.handlers;
    h.mark(matches);
    for (var i = 0, results = [], element; element = elements[i]; i++)
      if (element._counted) results.push(element);
    h.unmark(matches);
    return results;
  },

  findElement: function(elements, expression, index) {
    if (typeof expression == 'number') {
      index = expression; expression = false;
    }
    return Selector.matchElements(elements, expression || '*')[index || 0];
  },

  findChildElements: function(element, expressions) {
    var exprs = expressions.join(','), expressions = [];
    exprs.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
      expressions.push(m[1].strip());
    });
    var results = [], h = Selector.handlers;
    for (var i = 0, l = expressions.length, selector; i < l; i++) {
      selector = new Selector(expressions[i].strip());
      h.concat(results, selector.findElements(element));
    }
    return (l > 1) ? h.unique(results) : results;
  }
});

function $$() {
  return Selector.findChildElements(document, $A(arguments));
}
var Form = {
  reset: function(form) {
    $(form).reset();
    return form;
  },

  serializeElements: function(elements, getHash) {
    var data = elements.inject({}, function(result, element) {
      if (!element.disabled && element.name) {
        var key = element.name, value = $(element).getValue();
        if (value != null) {
         	if (key in result) {
            if (result[key].constructor != Array) result[key] = [result[key]];
            result[key].push(value);
          }
          else result[key] = value;
        }
      }
      return result;
    });

    return getHash ? data : Hash.toQueryString(data);
  }
};

Form.Methods = {
  serialize: function(form, getHash) {
    return Form.serializeElements(Form.getElements(form), getHash);
  },

  getElements: function(form) {
    return $A($(form).getElementsByTagName('*')).inject([],
      function(elements, child) {
        if (Form.Element.Serializers[child.tagName.toLowerCase()])
          elements.push(Element.extend(child));
        return elements;
      }
    );
  },

  getInputs: function(form, typeName, name) {
    form = $(form);
    var inputs = form.getElementsByTagName('input');

    if (!typeName && !name) return $A(inputs).map(Element.extend);

    for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
      var input = inputs[i];
      if ((typeName && input.type != typeName) || (name && input.name != name))
        continue;
      matchingInputs.push(Element.extend(input));
    }

    return matchingInputs;
  },

  disable: function(form) {
    form = $(form);
    Form.getElements(form).invoke('disable');
    return form;
  },

  enable: function(form) {
    form = $(form);
    Form.getElements(form).invoke('enable');
    return form;
  },

  findFirstElement: function(form) {
    return $(form).getElements().find(function(element) {
      return element.type != 'hidden' && !element.disabled &&
        ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
    });
  },

  focusFirstElement: function(form) {
    form = $(form);
    form.findFirstElement().activate();
    return form;
  },

  request: function(form, options) {
    form = $(form), options = Object.clone(options || {});

    var params = options.parameters;
    options.parameters = form.serialize(true);

    if (params) {
      if (typeof params == 'string') params = params.toQueryParams();
      Object.extend(options.parameters, params);
    }

    if (form.hasAttribute('method') && !options.method)
      options.method = form.method;

    return new Ajax.Request(form.readAttribute('action'), options);
  }
}

/*--------------------------------------------------------------------------*/

Form.Element = {
  focus: function(element) {
    $(element).focus();
    return element;
  },

  select: function(element) {
    $(element).select();
    return element;
  }
}

Form.Element.Methods = {
  serialize: function(element) {
    element = $(element);
    if (!element.disabled && element.name) {
      var value = element.getValue();
      if (value != undefined) {
        var pair = {};
        pair[element.name] = value;
        return Hash.toQueryString(pair);
      }
    }
    return '';
  },

  getValue: function(element) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    return Form.Element.Serializers[method](element);
  },

  clear: function(element) {
    $(element).value = '';
    return element;
  },

  present: function(element) {
    return $(element).value != '';
  },

  activate: function(element) {
    element = $(element);
    try {
      element.focus();
      if (element.select && (element.tagName.toLowerCase() != 'input' ||
        !['button', 'reset', 'submit'].include(element.type)))
        element.select();
    } catch (e) {}
    return element;
  },

  disable: function(element) {
    element = $(element);
    element.blur();
    element.disabled = true;
    return element;
  },

  enable: function(element) {
    element = $(element);
    element.disabled = false;
    return element;
  }
}

/*--------------------------------------------------------------------------*/

var Field = Form.Element;
var $F = Form.Element.Methods.getValue;

/*--------------------------------------------------------------------------*/

Form.Element.Serializers = {
  input: function(element) {
    switch (element.type.toLowerCase()) {
      case 'checkbox':
      case 'radio':
        return Form.Element.Serializers.inputSelector(element);
      default:
        return Form.Element.Serializers.textarea(element);
    }
  },

  inputSelector: function(element) {
    return element.checked ? element.value : null;
  },

  textarea: function(element) {
    return element.value;
  },

  select: function(element) {
    return this[element.type == 'select-one' ?
      'selectOne' : 'selectMany'](element);
  },

  selectOne: function(element) {
    var index = element.selectedIndex;
    return index >= 0 ? this.optionValue(element.options[index]) : null;
  },

  selectMany: function(element) {
    var values, length = element.length;
    if (!length) return null;

    for (var i = 0, values = []; i < length; i++) {
      var opt = element.options[i];
      if (opt.selected) values.push(this.optionValue(opt));
    }
    return values;
  },

  optionValue: function(opt) {
    // extend element because hasAttribute may not be native
    return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
  }
}

/*--------------------------------------------------------------------------*/

Abstract.TimedObserver = function() {}
Abstract.TimedObserver.prototype = {
  initialize: function(element, frequency, callback) {
    this.frequency = frequency;
    this.element   = $(element);
    this.callback  = callback;

    this.lastValue = this.getValue();
    this.registerCallback();
  },

  registerCallback: function() {
    setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  onTimerEvent: function() {
    var value = this.getValue();
    var changed = ('string' == typeof this.lastValue && 'string' == typeof value
      ? this.lastValue != value : String(this.lastValue) != String(value));
    if (changed) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  }
}

Form.Element.Observer = Class.create();
Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.Observer = Class.create();
Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});

/*--------------------------------------------------------------------------*/

Abstract.EventObserver = function() {}
Abstract.EventObserver.prototype = {
  initialize: function(element, callback) {
    this.element  = $(element);
    this.callback = callback;

    this.lastValue = this.getValue();
    if (this.element.tagName.toLowerCase() == 'form')
      this.registerFormCallbacks();
    else
      this.registerCallback(this.element);
  },

  onElementEvent: function() {
    var value = this.getValue();
    if (this.lastValue != value) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  },

  registerFormCallbacks: function() {
    Form.getElements(this.element).each(this.registerCallback.bind(this));
  },

  registerCallback: function(element) {
    if (element.type) {
      switch (element.type.toLowerCase()) {
        case 'checkbox':
        case 'radio':
          Event.observe(element, 'click', this.onElementEvent.bind(this));
          break;
        default:
          Event.observe(element, 'change', this.onElementEvent.bind(this));
          break;
      }
    }
  }
}

Form.Element.EventObserver = Class.create();
Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.EventObserver = Class.create();
Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});
if (!window.Event) {
  var Event = new Object();
}

Object.extend(Event, {
  KEY_BACKSPACE: 8,
  KEY_TAB:       9,
  KEY_RETURN:   13,
  KEY_ESC:      27,
  KEY_LEFT:     37,
  KEY_UP:       38,
  KEY_RIGHT:    39,
  KEY_DOWN:     40,
  KEY_DELETE:   46,
  KEY_HOME:     36,
  KEY_END:      35,
  KEY_PAGEUP:   33,
  KEY_PAGEDOWN: 34,

  element: function(event) {
    return $(event.target || event.srcElement);
  },

  isLeftClick: function(event) {
    return (((event.which) && (event.which == 1)) ||
            ((event.button) && (event.button == 1)));
  },

  pointerX: function(event) {
    return event.pageX || (event.clientX +
      (document.documentElement.scrollLeft || document.body.scrollLeft));
  },

  pointerY: function(event) {
    return event.pageY || (event.clientY +
      (document.documentElement.scrollTop || document.body.scrollTop));
  },

  stop: function(event) {
    if (event.preventDefault) {
      event.preventDefault();
      event.stopPropagation();
    } else {
      event.returnValue = false;
      event.cancelBubble = true;
    }
  },

  // find the first node with the given tagName, starting from the
  // node the event was triggered on; traverses the DOM upwards
  findElement: function(event, tagName) {
    var element = Event.element(event);
    while (element.parentNode && (!element.tagName ||
        (element.tagName.toUpperCase() != tagName.toUpperCase())))
      element = element.parentNode;
    return element;
  },

  observers: false,

  _observeAndCache: function(element, name, observer, useCapture) {
    if (!this.observers) this.observers = [];
    if (element.addEventListener) {
      this.observers.push([element, name, observer, useCapture]);
      element.addEventListener(name, observer, useCapture);
    } else if (element.attachEvent) {
      this.observers.push([element, name, observer, useCapture]);
      element.attachEvent('on' + name, observer);
    }
  },

  unloadCache: function() {
    if (!Event.observers) return;
    for (var i = 0, length = Event.observers.length; i < length; i++) {
      Event.stopObserving.apply(this, Event.observers[i]);
      Event.observers[i][0] = null;
    }
    Event.observers = false;
  },

  observe: function(element, name, observer, useCapture) {
    element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
      (Prototype.Browser.WebKit || element.attachEvent))
      name = 'keydown';

    Event._observeAndCache(element, name, observer, useCapture);
  },

  stopObserving: function(element, name, observer, useCapture) {
    element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (Prototype.Browser.WebKit || element.attachEvent))
      name = 'keydown';

    if (element.removeEventListener) {
      element.removeEventListener(name, observer, useCapture);
    } else if (element.detachEvent) {
      try {
        element.detachEvent('on' + name, observer);
      } catch (e) {}
    }
  }
});

/* prevent memory leaks in IE */
if (Prototype.Browser.IE)
  Event.observe(window, 'unload', Event.unloadCache, false);
var Position = {
  // set to true if needed, warning: firefox performance problems
  // NOT neeeded for page scrolling, only if draggable contained in
  // scrollable elements
  includeScrollOffsets: false,

  // must be called before calling withinIncludingScrolloffset, every time the
  // page is scrolled
  prepare: function() {
    this.deltaX =  window.pageXOffset
                || document.documentElement.scrollLeft
                || document.body.scrollLeft
                || 0;
    this.deltaY =  window.pageYOffset
                || document.documentElement.scrollTop
                || document.body.scrollTop
                || 0;
  },

  realOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.scrollTop  || 0;
      valueL += element.scrollLeft || 0;
      element = element.parentNode;
    } while (element);
    return [valueL, valueT];
  },

  cumulativeOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return [valueL, valueT];
  },

  positionedOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
      if (element) {
        if(element.tagName=='BODY') break;
        var p = Element.getStyle(element, 'position');
        if (p == 'relative' || p == 'absolute') break;
      }
    } while (element);
    return [valueL, valueT];
  },

  offsetParent: function(element) {
    if (element.offsetParent) return element.offsetParent;
    if (element == document.body) return element;

    while ((element = element.parentNode) && element != document.body)
      if (Element.getStyle(element, 'position') != 'static')
        return element;

    return document.body;
  },

  // caches x/y coordinate pair to use with overlap
  within: function(element, x, y) {
    if (this.includeScrollOffsets)
      return this.withinIncludingScrolloffsets(element, x, y);
    this.xcomp = x;
    this.ycomp = y;
    this.offset = this.cumulativeOffset(element);

    return (y >= this.offset[1] &&
            y <  this.offset[1] + element.offsetHeight &&
            x >= this.offset[0] &&
            x <  this.offset[0] + element.offsetWidth);
  },

  withinIncludingScrolloffsets: function(element, x, y) {
    var offsetcache = this.realOffset(element);

    this.xcomp = x + offsetcache[0] - this.deltaX;
    this.ycomp = y + offsetcache[1] - this.deltaY;
    this.offset = this.cumulativeOffset(element);

    return (this.ycomp >= this.offset[1] &&
            this.ycomp <  this.offset[1] + element.offsetHeight &&
            this.xcomp >= this.offset[0] &&
            this.xcomp <  this.offset[0] + element.offsetWidth);
  },

  // within must be called directly before
  overlap: function(mode, element) {
    if (!mode) return 0;
    if (mode == 'vertical')
      return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
        element.offsetHeight;
    if (mode == 'horizontal')
      return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
        element.offsetWidth;
  },

  page: function(forElement) {
    var valueT = 0, valueL = 0;

    var element = forElement;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;

      // Safari fix
      if (element.offsetParent == document.body)
        if (Element.getStyle(element,'position')=='absolute') break;

    } while (element = element.offsetParent);

    element = forElement;
    do {
      if (!window.opera || element.tagName=='BODY') {
        valueT -= element.scrollTop  || 0;
        valueL -= element.scrollLeft || 0;
      }
    } while (element = element.parentNode);

    return [valueL, valueT];
  },

  clone: function(source, target) {
    var options = Object.extend({
      setLeft:    true,
      setTop:     true,
      setWidth:   true,
      setHeight:  true,
      offsetTop:  0,
      offsetLeft: 0
    }, arguments[2] || {})

    // find page position of source
    source = $(source);
    var p = Position.page(source);

    // find coordinate system to use
    target = $(target);
    var delta = [0, 0];
    var parent = null;
    // delta [0,0] will do fine with position: fixed elements,
    // position:absolute needs offsetParent deltas
    if (Element.getStyle(target,'position') == 'absolute') {
      parent = Position.offsetParent(target);
      delta = Position.page(parent);
    }

    // correct by body offsets (fixes Safari)
    if (parent == document.body) {
      delta[0] -= document.body.offsetLeft;
      delta[1] -= document.body.offsetTop;
    }

    // set position
    if(options.setLeft)   target.style.left  = (p[0] - delta[0] + options.offsetLeft) + 'px';
    if(options.setTop)    target.style.top   = (p[1] - delta[1] + options.offsetTop) + 'px';
    if(options.setWidth)  target.style.width = source.offsetWidth + 'px';
    if(options.setHeight) target.style.height = source.offsetHeight + 'px';
  },

  absolutize: function(element) {
    element = $(element);
    if (element.style.position == 'absolute') return;
    Position.prepare();

    var offsets = Position.positionedOffset(element);
    var top     = offsets[1];
    var left    = offsets[0];
    var width   = element.clientWidth;
    var height  = element.clientHeight;

    element._originalLeft   = left - parseFloat(element.style.left  || 0);
    element._originalTop    = top  - parseFloat(element.style.top || 0);
    element._originalWidth  = element.style.width;
    element._originalHeight = element.style.height;

    element.style.position = 'absolute';
    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.width  = width + 'px';
    element.style.height = height + 'px';
  },

  relativize: function(element) {
    element = $(element);
    if (element.style.position == 'relative') return;
    Position.prepare();

    element.style.position = 'relative';
    var top  = parseFloat(element.style.top  || 0) - (element._originalTop || 0);
    var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);

    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.height = element._originalHeight;
    element.style.width  = element._originalWidth;
  }
}

// Safari returns margins on body which is incorrect if the child is absolutely
// positioned.  For performance reasons, redefine Position.cumulativeOffset for
// KHTML/WebKit only.
if (Prototype.Browser.WebKit) {
  Position.cumulativeOffset = function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      if (element.offsetParent == document.body)
        if (Element.getStyle(element, 'position') == 'absolute') break;

      element = element.offsetParent;
    } while (element);

    return [valueL, valueT];
  }
}

Element.addMethods();// script.aculo.us scriptaculous.js v1.7.1_beta3, Fri May 25 17:19:41 +0200 2007

// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// 
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// For details, see the script.aculo.us web site: http://script.aculo.us/

var Scriptaculous = {
  Version: '1.7.1_beta3',
  require: function(libraryName) {
    // inserting via DOM fails in Safari 2.0, so brute force approach
    document.write('<script type="text/javascript" src="'+libraryName+'"></script>');
  },
  REQUIRED_PROTOTYPE: '1.5.1',
  load: function() {
    function convertVersionString(versionString){
      var r = versionString.split('.');
      return parseInt(r[0])*100000 + parseInt(r[1])*1000 + parseInt(r[2]);
    }
 
    if((typeof Prototype=='undefined') || 
       (typeof Element == 'undefined') || 
       (typeof Element.Methods=='undefined') ||
       (convertVersionString(Prototype.Version) < 
        convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE)))
       throw("script.aculo.us requires the Prototype JavaScript framework >= " +
        Scriptaculous.REQUIRED_PROTOTYPE);
    
    $A(document.getElementsByTagName("script")).findAll( function(s) {
      return (s.src && s.src.match(/scriptaculous\.js(\?.*)?$/))
    }).each( function(s) {
      var path = s.src.replace(/scriptaculous\.js(\?.*)?$/,'');
      var includes = s.src.match(/\?.*load=([a-z,]*)/);
      (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each(
       function(include) { Scriptaculous.require(path+include+'.js') });
    });
  }
}

Scriptaculous.load();// script.aculo.us builder.js v1.7.1_beta3, Fri May 25 17:19:41 +0200 2007

// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/

var Builder = {
  NODEMAP: {
    AREA: 'map',
    CAPTION: 'table',
    COL: 'table',
    COLGROUP: 'table',
    LEGEND: 'fieldset',
    OPTGROUP: 'select',
    OPTION: 'select',
    PARAM: 'object',
    TBODY: 'table',
    TD: 'table',
    TFOOT: 'table',
    TH: 'table',
    THEAD: 'table',
    TR: 'table'
  },
  // note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken,
  //       due to a Firefox bug
  node: function(elementName) {
    elementName = elementName.toUpperCase();
    
    // try innerHTML approach
    var parentTag = this.NODEMAP[elementName] || 'div';
    var parentElement = document.createElement(parentTag);
    try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
      parentElement.innerHTML = "<" + elementName + "></" + elementName + ">";
    } catch(e) {}
    var element = parentElement.firstChild || null;
      
    // see if browser added wrapping tags
    if(element && (element.tagName.toUpperCase() != elementName))
      element = element.getElementsByTagName(elementName)[0];
    
    // fallback to createElement approach
    if(!element) element = document.createElement(elementName);
    
    // abort if nothing could be created
    if(!element) return;

    // attributes (or text)
    if(arguments[1])
      if(this._isStringOrNumber(arguments[1]) ||
        (arguments[1] instanceof Array) ||
        arguments[1].tagName) {
          this._children(element, arguments[1]);
        } else {
          var attrs = this._attributes(arguments[1]);
          if(attrs.length) {
            try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
              parentElement.innerHTML = "<" +elementName + " " +
                attrs + "></" + elementName + ">";
            } catch(e) {}
            element = parentElement.firstChild || null;
            // workaround firefox 1.0.X bug
            if(!element) {
              element = document.createElement(elementName);
              for(attr in arguments[1]) 
                element[attr == 'class' ? 'className' : attr] = arguments[1][attr];
            }
            if(element.tagName.toUpperCase() != elementName)
              element = parentElement.getElementsByTagName(elementName)[0];
          }
        } 

    // text, or array of children
    if(arguments[2])
      this._children(element, arguments[2]);

     return element;
  },
  _text: function(text) {
     return document.createTextNode(text);
  },

  ATTR_MAP: {
    'className': 'class',
    'htmlFor': 'for'
  },

  _attributes: function(attributes) {
    var attrs = [];
    for(attribute in attributes)
      attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) +
          '="' + attributes[attribute].toString().escapeHTML().gsub(/"/,'&quot;') + '"');
    return attrs.join(" ");
  },
  _children: function(element, children) {
    if(children.tagName) {
      element.appendChild(children);
      return;
    }
    if(typeof children=='object') { // array can hold nodes and text
      children.flatten().each( function(e) {
        if(typeof e=='object')
          element.appendChild(e)
        else
          if(Builder._isStringOrNumber(e))
            element.appendChild(Builder._text(e));
      });
    } else
      if(Builder._isStringOrNumber(children))
        element.appendChild(Builder._text(children));
  },
  _isStringOrNumber: function(param) {
    return(typeof param=='string' || typeof param=='number');
  },
  build: function(html) {
    var element = this.node('div');
    $(element).update(html.strip());
    return element.down();
  },
  dump: function(scope) { 
    if(typeof scope != 'object' && typeof scope != 'function') scope = window; //global scope 
  
    var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " +
      "BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " +
      "FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+
      "KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+
      "PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+
      "TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/);
  
    tags.each( function(tag){ 
      scope[tag] = function() { 
        return Builder.node.apply(Builder, [tag].concat($A(arguments)));  
      } 
    });
  }
}
// script.aculo.us effects.js v1.7.1_beta3, Fri May 25 17:19:41 +0200 2007

// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// Contributors:
//  Justin Palmer (http://encytemedia.com/)
//  Mark Pilgrim (http://diveintomark.org/)
//  Martin Bialasinki
// 
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/ 

// converts rgb() and #xxx to #xxxxxx format,  
// returns self (or first argument) if not convertable  
String.prototype.parseColor = function() {  
  var color = '#';
  if(this.slice(0,4) == 'rgb(') {  
    var cols = this.slice(4,this.length-1).split(',');  
    var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);  
  } else {  
    if(this.slice(0,1) == '#') {  
      if(this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();  
      if(this.length==7) color = this.toLowerCase();  
    }  
  }  
  return(color.length==7 ? color : (arguments[0] || this));  
}

/*--------------------------------------------------------------------------*/

Element.collectTextNodes = function(element) {  
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue : 
      (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
  }).flatten().join('');
}

Element.collectTextNodesIgnoreClass = function(element, className) {  
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue : 
      ((node.hasChildNodes() && !Element.hasClassName(node,className)) ? 
        Element.collectTextNodesIgnoreClass(node, className) : ''));
  }).flatten().join('');
}

Element.setContentZoom = function(element, percent) {
  element = $(element);  
  element.setStyle({fontSize: (percent/100) + 'em'});   
  if(Prototype.Browser.WebKit) window.scrollBy(0,0);
  return element;
}

Element.getInlineOpacity = function(element){
  return $(element).style.opacity || '';
}

Element.forceRerendering = function(element) {
  try {
    element = $(element);
    var n = document.createTextNode(' ');
    element.appendChild(n);
    element.removeChild(n);
  } catch(e) { }
};

/*--------------------------------------------------------------------------*/

Array.prototype.call = function() {
  var args = arguments;
  this.each(function(f){ f.apply(this, args) });
}

/*--------------------------------------------------------------------------*/

var Effect = {
  _elementDoesNotExistError: {
    name: 'ElementDoesNotExistError',
    message: 'The specified DOM element does not exist, but is required for this effect to operate'
  },
  tagifyText: function(element) {
    if(typeof Builder == 'undefined')
      throw("Effect.tagifyText requires including script.aculo.us' builder.js library");
      
    var tagifyStyle = 'position:relative';
    if(Prototype.Browser.IE) tagifyStyle += ';zoom:1';
    
    element = $(element);
    $A(element.childNodes).each( function(child) {
      if(child.nodeType==3) {
        child.nodeValue.toArray().each( function(character) {
          element.insertBefore(
            Builder.node('span',{style: tagifyStyle},
              character == ' ' ? String.fromCharCode(160) : character), 
              child);
        });
        Element.remove(child);
      }
    });
  },
  multiple: function(element, effect) {
    var elements;
    if(((typeof element == 'object') || 
        (typeof element == 'function')) && 
       (element.length))
      elements = element;
    else
      elements = $(element).childNodes;
      
    var options = Object.extend({
      speed: 0.1,
      delay: 0.0
    }, arguments[2] || {});
    var masterDelay = options.delay;

    $A(elements).each( function(element, index) {
      new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
    });
  },
  PAIRS: {
    'slide':  ['SlideDown','SlideUp'],
    'blind':  ['BlindDown','BlindUp'],
    'appear': ['Appear','Fade']
  },
  toggle: function(element, effect) {
    element = $(element);
    effect = (effect || 'appear').toLowerCase();
    var options = Object.extend({
      queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
    }, arguments[2] || {});
    Effect[element.visible() ? 
      Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
  }
};

var Effect2 = Effect; // deprecated

/* ------------- transitions ------------- */

Effect.Transitions = {
  linear: Prototype.K,
  sinoidal: function(pos) {
    return (-Math.cos(pos*Math.PI)/2) + 0.5;
  },
  reverse: function(pos) {
    return 1-pos;
  },
  flicker: function(pos) {
    var pos = ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
    return (pos > 1 ? 1 : pos);
  },
  wobble: function(pos) {
    return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
  },
  pulse: function(pos, pulses) { 
    pulses = pulses || 5; 
    return (
      Math.round((pos % (1/pulses)) * pulses) == 0 ? 
            ((pos * pulses * 2) - Math.floor(pos * pulses * 2)) : 
        1 - ((pos * pulses * 2) - Math.floor(pos * pulses * 2))
      );
  },
  none: function(pos) {
    return 0;
  },
  full: function(pos) {
    return 1;
  }
};

/* ------------- core effects ------------- */

Effect.ScopedQueue = Class.create();
Object.extend(Object.extend(Effect.ScopedQueue.prototype, Enumerable), {
  initialize: function() {
    this.effects  = [];
    this.interval = null;    
  },
  _each: function(iterator) {
    this.effects._each(iterator);
  },
  add: function(effect) {
    var timestamp = new Date().getTime();
    
    var position = (typeof effect.options.queue == 'string') ? 
      effect.options.queue : effect.options.queue.position;
    
    switch(position) {
      case 'front':
        // move unstarted effects after this effect  
        this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
            e.startOn  += effect.finishOn;
            e.finishOn += effect.finishOn;
          });
        break;
      case 'with-last':
        timestamp = this.effects.pluck('startOn').max() || timestamp;
        break;
      case 'end':
        // start effect after last queued effect has finished
        timestamp = this.effects.pluck('finishOn').max() || timestamp;
        break;
    }
    
    effect.startOn  += timestamp;
    effect.finishOn += timestamp;

    if(!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
      this.effects.push(effect);
    
    if(!this.interval)
      this.interval = setInterval(this.loop.bind(this), 15);
  },
  remove: function(effect) {
    this.effects = this.effects.reject(function(e) { return e==effect });
    if(this.effects.length == 0) {
      clearInterval(this.interval);
      this.interval = null;
    }
  },
  loop: function() {
    var timePos = new Date().getTime();
    for(var i=0, len=this.effects.length;i<len;i++) 
      this.effects[i] && this.effects[i].loop(timePos);
  }
});

Effect.Queues = {
  instances: $H(),
  get: function(queueName) {
    if(typeof queueName != 'string') return queueName;
    
    if(!this.instances[queueName])
      this.instances[queueName] = new Effect.ScopedQueue();
      
    return this.instances[queueName];
  }
}
Effect.Queue = Effect.Queues.get('global');

Effect.DefaultOptions = {
  transition: Effect.Transitions.sinoidal,
  duration:   1.0,   // seconds
  fps:        100,   // 100= assume 66fps max.
  sync:       false, // true for combining
  from:       0.0,
  to:         1.0,
  delay:      0.0,
  queue:      'parallel'
}

Effect.Base = function() {};
Effect.Base.prototype = {
  position: null,
  start: function(options) {
    function codeForEvent(options,eventName){
      return (
        (options[eventName+'Internal'] ? 'this.options.'+eventName+'Internal(this);' : '') +
        (options[eventName] ? 'this.options.'+eventName+'(this);' : '')
      );
    }
    if(options.transition === false) options.transition = Effect.Transitions.linear;
    this.options      = Object.extend(Object.extend({},Effect.DefaultOptions), options || {});
    this.currentFrame = 0;
    this.state        = 'idle';
    this.startOn      = this.options.delay*1000;
    this.finishOn     = this.startOn+(this.options.duration*1000);
    this.fromToDelta  = this.options.to-this.options.from;
    this.totalTime    = this.finishOn-this.startOn;
    this.totalFrames  = this.options.fps*this.options.duration;
    
    eval('this.render = function(pos){ '+
      'if(this.state=="idle"){this.state="running";'+
      codeForEvent(options,'beforeSetup')+
      (this.setup ? 'this.setup();':'')+ 
      codeForEvent(options,'afterSetup')+
      '};if(this.state=="running"){'+
      'pos=this.options.transition(pos)*'+this.fromToDelta+'+'+this.options.from+';'+
      'this.position=pos;'+
      codeForEvent(options,'beforeUpdate')+
      (this.update ? 'this.update(pos);':'')+
      codeForEvent(options,'afterUpdate')+
      '}}');
    
    this.event('beforeStart');
    if(!this.options.sync)
      Effect.Queues.get(typeof this.options.queue == 'string' ? 
        'global' : this.options.queue.scope).add(this);
  },
  loop: function(timePos) {
    if(timePos >= this.startOn) {
      if(timePos >= this.finishOn) {
        this.render(1.0);
        this.cancel();
        this.event('beforeFinish');
        if(this.finish) this.finish(); 
        this.event('afterFinish');
        return;  
      }
      var pos   = (timePos - this.startOn) / this.totalTime,
          frame = Math.round(pos * this.totalFrames);
      if(frame > this.currentFrame) {
        this.render(pos);
        this.currentFrame = frame;
      }
    }
  },
  cancel: function() {
    if(!this.options.sync)
      Effect.Queues.get(typeof this.options.queue == 'string' ? 
        'global' : this.options.queue.scope).remove(this);
    this.state = 'finished';
  },
  event: function(eventName) {
    if(this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
    if(this.options[eventName]) this.options[eventName](this);
  },
  inspect: function() {
    var data = $H();
    for(property in this)
      if(typeof this[property] != 'function') data[property] = this[property];
    return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';
  }
}

Effect.Parallel = Class.create();
Object.extend(Object.extend(Effect.Parallel.prototype, Effect.Base.prototype), {
  initialize: function(effects) {
    this.effects = effects || [];
    this.start(arguments[1]);
  },
  update: function(position) {
    this.effects.invoke('render', position);
  },
  finish: function(position) {
    this.effects.each( function(effect) {
      effect.render(1.0);
      effect.cancel();
      effect.event('beforeFinish');
      if(effect.finish) effect.finish(position);
      effect.event('afterFinish');
    });
  }
});

Effect.Event = Class.create();
Object.extend(Object.extend(Effect.Event.prototype, Effect.Base.prototype), {
  initialize: function() {
    var options = Object.extend({
      duration: 0
    }, arguments[0] || {});
    this.start(options);
  },
  update: Prototype.emptyFunction
});

Effect.Opacity = Class.create();
Object.extend(Object.extend(Effect.Opacity.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    if(!this.element) throw(Effect._elementDoesNotExistError);
    // make this work on IE on elements without 'layout'
    if(Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
      this.element.setStyle({zoom: 1});
    var options = Object.extend({
      from: this.element.getOpacity() || 0.0,
      to:   1.0
    }, arguments[1] || {});
    this.start(options);
  },
  update: function(position) {
    this.element.setOpacity(position);
  }
});

Effect.Move = Class.create();
Object.extend(Object.extend(Effect.Move.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    if(!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      x:    0,
      y:    0,
      mode: 'relative'
    }, arguments[1] || {});
    this.start(options);
  },
  setup: function() {
    // Bug in Opera: Opera returns the "real" position of a static element or
    // relative element that does not have top/left explicitly set.
    // ==> Always set top and left for position relative elements in your stylesheets 
    // (to 0 if you do not need them) 
    this.element.makePositioned();
    this.originalLeft = parseFloat(this.element.getStyle('left') || '0');
    this.originalTop  = parseFloat(this.element.getStyle('top')  || '0');
    if(this.options.mode == 'absolute') {
      // absolute movement, so we need to calc deltaX and deltaY
      this.options.x = this.options.x - this.originalLeft;
      this.options.y = this.options.y - this.originalTop;
    }
  },
  update: function(position) {
    this.element.setStyle({
      left: Math.round(this.options.x  * position + this.originalLeft) + 'px',
      top:  Math.round(this.options.y  * position + this.originalTop)  + 'px'
    });
  }
});

// for backwards compatibility
Effect.MoveBy = function(element, toTop, toLeft) {
  return new Effect.Move(element, 
    Object.extend({ x: toLeft, y: toTop }, arguments[3] || {}));
};

Effect.Scale = Class.create();
Object.extend(Object.extend(Effect.Scale.prototype, Effect.Base.prototype), {
  initialize: function(element, percent) {
    this.element = $(element);
    if(!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      scaleX: true,
      scaleY: true,
      scaleContent: true,
      scaleFromCenter: false,
      scaleMode: 'box',        // 'box' or 'contents' or {} with provided values
      scaleFrom: 100.0,
      scaleTo:   percent
    }, arguments[2] || {});
    this.start(options);
  },
  setup: function() {
    this.restoreAfterFinish = this.options.restoreAfterFinish || false;
    this.elementPositioning = this.element.getStyle('position');
    
    this.originalStyle = {};
    ['top','left','width','height','fontSize'].each( function(k) {
      this.originalStyle[k] = this.element.style[k];
    }.bind(this));
      
    this.originalTop  = this.element.offsetTop;
    this.originalLeft = this.element.offsetLeft;
    
    var fontSize = this.element.getStyle('font-size') || '100%';
    ['em','px','%','pt'].each( function(fontSizeType) {
      if(fontSize.indexOf(fontSizeType)>0) {
        this.fontSize     = parseFloat(fontSize);
        this.fontSizeType = fontSizeType;
      }
    }.bind(this));
    
    this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
    
    this.dims = null;
    if(this.options.scaleMode=='box')
      this.dims = [this.element.offsetHeight, this.element.offsetWidth];
    if(/^content/.test(this.options.scaleMode))
      this.dims = [this.element.scrollHeight, this.element.scrollWidth];
    if(!this.dims)
      this.dims = [this.options.scaleMode.originalHeight,
                   this.options.scaleMode.originalWidth];
  },
  update: function(position) {
    var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
    if(this.options.scaleContent && this.fontSize)
      this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
    this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
  },
  finish: function(position) {
    if(this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
  },
  setDimensions: function(height, width) {
    var d = {};
    if(this.options.scaleX) d.width = Math.round(width) + 'px';
    if(this.options.scaleY) d.height = Math.round(height) + 'px';
    if(this.options.scaleFromCenter) {
      var topd  = (height - this.dims[0])/2;
      var leftd = (width  - this.dims[1])/2;
      if(this.elementPositioning == 'absolute') {
        if(this.options.scaleY) d.top = this.originalTop-topd + 'px';
        if(this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
      } else {
        if(this.options.scaleY) d.top = -topd + 'px';
        if(this.options.scaleX) d.left = -leftd + 'px';
      }
    }
    this.element.setStyle(d);
  }
});

Effect.Highlight = Class.create();
Object.extend(Object.extend(Effect.Highlight.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    if(!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || {});
    this.start(options);
  },
  setup: function() {
    // Prevent executing on elements not in the layout flow
    if(this.element.getStyle('display')=='none') { this.cancel(); return; }
    // Disable background image during the effect
    this.oldStyle = {};
    if (!this.options.keepBackgroundImage) {
      this.oldStyle.backgroundImage = this.element.getStyle('background-image');
      this.element.setStyle({backgroundImage: 'none'});
    }
    if(!this.options.endcolor)
      this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
    if(!this.options.restorecolor)
      this.options.restorecolor = this.element.getStyle('background-color');
    // init color calculations
    this._base  = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
    this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
  },
  update: function(position) {
    this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
      return m+(Math.round(this._base[i]+(this._delta[i]*position)).toColorPart()); }.bind(this)) });
  },
  finish: function() {
    this.element.setStyle(Object.extend(this.oldStyle, {
      backgroundColor: this.options.restorecolor
    }));
  }
});

Effect.ScrollTo = Class.create();
Object.extend(Object.extend(Effect.ScrollTo.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    this.start(arguments[1] || {});
  },
  setup: function() {
    Position.prepare();
    var offsets = Position.cumulativeOffset(this.element);
    if(this.options.offset) offsets[1] += this.options.offset;
    var max = window.innerHeight ? 
      window.height - window.innerHeight :
      document.body.scrollHeight - 
        (document.documentElement.clientHeight ? 
          document.documentElement.clientHeight : document.body.clientHeight);
    this.scrollStart = Position.deltaY;
    this.delta = (offsets[1] > max ? max : offsets[1]) - this.scrollStart;
  },
  update: function(position) {
    Position.prepare();
    window.scrollTo(Position.deltaX, 
      this.scrollStart + (position*this.delta));
  }
});

/* ------------- combination effects ------------- */

Effect.Fade = function(element) {
  element = $(element);
  var oldOpacity = element.getInlineOpacity();
  var options = Object.extend({
  from: element.getOpacity() || 1.0,
  to:   0.0,
  afterFinishInternal: function(effect) { 
    if(effect.options.to!=0) return;
    effect.element.hide().setStyle({opacity: oldOpacity}); 
  }}, arguments[1] || {});
  return new Effect.Opacity(element,options);
}

Effect.Appear = function(element) {
  element = $(element);
  var options = Object.extend({
  from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
  to:   1.0,
  // force Safari to render floated elements properly
  afterFinishInternal: function(effect) {
    effect.element.forceRerendering();
  },
  beforeSetup: function(effect) {
    effect.element.setOpacity(effect.options.from).show(); 
  }}, arguments[1] || {});
  return new Effect.Opacity(element,options);
}

Effect.Puff = function(element) {
  element = $(element);
  var oldStyle = { 
    opacity: element.getInlineOpacity(), 
    position: element.getStyle('position'),
    top:  element.style.top,
    left: element.style.left,
    width: element.style.width,
    height: element.style.height
  };
  return new Effect.Parallel(
   [ new Effect.Scale(element, 200, 
      { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), 
     new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], 
     Object.extend({ duration: 1.0, 
      beforeSetupInternal: function(effect) {
        Position.absolutize(effect.effects[0].element)
      },
      afterFinishInternal: function(effect) {
         effect.effects[0].element.hide().setStyle(oldStyle); }
     }, arguments[1] || {})
   );
}

Effect.BlindUp = function(element) {
  element = $(element);
  element.makeClipping();
  return new Effect.Scale(element, 0,
    Object.extend({ scaleContent: false, 
      scaleX: false, 
      restoreAfterFinish: true,
      afterFinishInternal: function(effect) {
        effect.element.hide().undoClipping();
      } 
    }, arguments[1] || {})
  );
}

Effect.BlindDown = function(element) {
  element = $(element);
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({ 
    scaleContent: false, 
    scaleX: false,
    scaleFrom: 0,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makeClipping().setStyle({height: '0px'}).show(); 
    },  
    afterFinishInternal: function(effect) {
      effect.element.undoClipping();
    }
  }, arguments[1] || {}));
}

Effect.SwitchOff = function(element) {
  element = $(element);
  var oldOpacity = element.getInlineOpacity();
  return new Effect.Appear(element, Object.extend({
    duration: 0.4,
    from: 0,
    transition: Effect.Transitions.flicker,
    afterFinishInternal: function(effect) {
      new Effect.Scale(effect.element, 1, { 
        duration: 0.3, scaleFromCenter: true,
        scaleX: false, scaleContent: false, restoreAfterFinish: true,
        beforeSetup: function(effect) { 
          effect.element.makePositioned().makeClipping();
        },
        afterFinishInternal: function(effect) {
          effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
        }
      })
    }
  }, arguments[1] || {}));
}

Effect.DropOut = function(element) {
  element = $(element);
  var oldStyle = {
    top: element.getStyle('top'),
    left: element.getStyle('left'),
    opacity: element.getInlineOpacity() };
  return new Effect.Parallel(
    [ new Effect.Move(element, {x: 0, y: 100, sync: true }), 
      new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
    Object.extend(
      { duration: 0.5,
        beforeSetup: function(effect) {
          effect.effects[0].element.makePositioned(); 
        },
        afterFinishInternal: function(effect) {
          effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
        } 
      }, arguments[1] || {}));
}

Effect.Shake = function(element) {
  element = $(element);
  var oldStyle = {
    top: element.getStyle('top'),
    left: element.getStyle('left') };
    return new Effect.Move(element, 
      { x:  20, y: 0, duration: 0.05, afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x:  40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x:  40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -20, y: 0, duration: 0.05, afterFinishInternal: function(effect) {
        effect.element.undoPositioned().setStyle(oldStyle);
  }}) }}) }}) }}) }}) }});
}

Effect.SlideDown = function(element) {
  element = $(element).cleanWhitespace();
  // SlideDown need to have the content of the element wrapped in a container element with fixed height!
  var oldInnerBottom = element.down().getStyle('bottom');
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({ 
    scaleContent: false, 
    scaleX: false, 
    scaleFrom: window.opera ? 0 : 1,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makePositioned();
      effect.element.down().makePositioned();
      if(window.opera) effect.element.setStyle({top: ''});
      effect.element.makeClipping().setStyle({height: '0px'}).show(); 
    },
    afterUpdateInternal: function(effect) {
      effect.element.down().setStyle({bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' }); 
    },
    afterFinishInternal: function(effect) {
      effect.element.undoClipping().undoPositioned();
      effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
    }, arguments[1] || {})
  );
}

Effect.SlideUp = function(element) {
  element = $(element).cleanWhitespace();
  var oldInnerBottom = element.down().getStyle('bottom');
  return new Effect.Scale(element, window.opera ? 0 : 1,
   Object.extend({ scaleContent: false, 
    scaleX: false, 
    scaleMode: 'box',
    scaleFrom: 100,
    restoreAfterFinish: true,
    beforeStartInternal: function(effect) {
      effect.element.makePositioned();
      effect.element.down().makePositioned();
      if(window.opera) effect.element.setStyle({top: ''});
      effect.element.makeClipping().show();
    },  
    afterUpdateInternal: function(effect) {
      effect.element.down().setStyle({bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' });
    },
    afterFinishInternal: function(effect) {
      effect.element.hide().undoClipping().undoPositioned().setStyle({bottom: oldInnerBottom});
      effect.element.down().undoPositioned();
    }
   }, arguments[1] || {})
  );
}

// Bug in opera makes the TD containing this element expand for a instance after finish 
Effect.Squish = function(element) {
  return new Effect.Scale(element, window.opera ? 1 : 0, { 
    restoreAfterFinish: true,
    beforeSetup: function(effect) {
      effect.element.makeClipping(); 
    },  
    afterFinishInternal: function(effect) {
      effect.element.hide().undoClipping(); 
    }
  });
}

Effect.Grow = function(element) {
  element = $(element);
  var options = Object.extend({
    direction: 'center',
    moveTransition: Effect.Transitions.sinoidal,
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.full
  }, arguments[1] || {});
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
    opacity: element.getInlineOpacity() };

  var dims = element.getDimensions();    
  var initialMoveX, initialMoveY;
  var moveX, moveY;
  
  switch (options.direction) {
    case 'top-left':
      initialMoveX = initialMoveY = moveX = moveY = 0; 
      break;
    case 'top-right':
      initialMoveX = dims.width;
      initialMoveY = moveY = 0;
      moveX = -dims.width;
      break;
    case 'bottom-left':
      initialMoveX = moveX = 0;
      initialMoveY = dims.height;
      moveY = -dims.height;
      break;
    case 'bottom-right':
      initialMoveX = dims.width;
      initialMoveY = dims.height;
      moveX = -dims.width;
      moveY = -dims.height;
      break;
    case 'center':
      initialMoveX = dims.width / 2;
      initialMoveY = dims.height / 2;
      moveX = -dims.width / 2;
      moveY = -dims.height / 2;
      break;
  }
  
  return new Effect.Move(element, {
    x: initialMoveX,
    y: initialMoveY,
    duration: 0.01, 
    beforeSetup: function(effect) {
      effect.element.hide().makeClipping().makePositioned();
    },
    afterFinishInternal: function(effect) {
      new Effect.Parallel(
        [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
          new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
          new Effect.Scale(effect.element, 100, {
            scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, 
            sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
        ], Object.extend({
             beforeSetup: function(effect) {
               effect.effects[0].element.setStyle({height: '0px'}).show(); 
             },
             afterFinishInternal: function(effect) {
               effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle); 
             }
           }, options)
      )
    }
  });
}

Effect.Shrink = function(element) {
  element = $(element);
  var options = Object.extend({
    direction: 'center',
    moveTransition: Effect.Transitions.sinoidal,
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.none
  }, arguments[1] || {});
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
    opacity: element.getInlineOpacity() };

  var dims = element.getDimensions();
  var moveX, moveY;
  
  switch (options.direction) {
    case 'top-left':
      moveX = moveY = 0;
      break;
    case 'top-right':
      moveX = dims.width;
      moveY = 0;
      break;
    case 'bottom-left':
      moveX = 0;
      moveY = dims.height;
      break;
    case 'bottom-right':
      moveX = dims.width;
      moveY = dims.height;
      break;
    case 'center':  
      moveX = dims.width / 2;
      moveY = dims.height / 2;
      break;
  }
  
  return new Effect.Parallel(
    [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
      new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
      new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
    ], Object.extend({            
         beforeStartInternal: function(effect) {
           effect.effects[0].element.makePositioned().makeClipping(); 
         },
         afterFinishInternal: function(effect) {
           effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
       }, options)
  );
}

Effect.Pulsate = function(element) {
  element = $(element);
  var options    = arguments[1] || {};
  var oldOpacity = element.getInlineOpacity();
  var transition = options.transition || Effect.Transitions.sinoidal;
  var reverser   = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) };
  reverser.bind(transition);
  return new Effect.Opacity(element, 
    Object.extend(Object.extend({  duration: 2.0, from: 0,
      afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
    }, options), {transition: reverser}));
}

Effect.Fold = function(element) {
  element = $(element);
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    width: element.style.width,
    height: element.style.height };
  element.makeClipping();
  return new Effect.Scale(element, 5, Object.extend({   
    scaleContent: false,
    scaleX: false,
    afterFinishInternal: function(effect) {
    new Effect.Scale(element, 1, { 
      scaleContent: false, 
      scaleY: false,
      afterFinishInternal: function(effect) {
        effect.element.hide().undoClipping().setStyle(oldStyle);
      } });
  }}, arguments[1] || {}));
};

Effect.Morph = Class.create();
Object.extend(Object.extend(Effect.Morph.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    if(!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      style: {}
    }, arguments[1] || {});
    if (typeof options.style == 'string') {
      if(options.style.indexOf(':') == -1) {
        var cssText = '', selector = '.' + options.style;
        $A(document.styleSheets).reverse().each(function(styleSheet) {
          if (styleSheet.cssRules) cssRules = styleSheet.cssRules;
          else if (styleSheet.rules) cssRules = styleSheet.rules;
          $A(cssRules).reverse().each(function(rule) {
            if (selector == rule.selectorText) {
              cssText = rule.style.cssText;
              throw $break;
            }
          });
          if (cssText) throw $break;
        });
        this.style = cssText.parseStyle();
        options.afterFinishInternal = function(effect){
          effect.element.addClassName(effect.options.style);
          effect.transforms.each(function(transform) {
            if(transform.style != 'opacity')
              effect.element.style[transform.style] = '';
          });
        }
      } else this.style = options.style.parseStyle();
    } else this.style = $H(options.style)
    this.start(options);
  },
  setup: function(){
    function parseColor(color){
      if(!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
      color = color.parseColor();
      return $R(0,2).map(function(i){
        return parseInt( color.slice(i*2+1,i*2+3), 16 ) 
      });
    }
    this.transforms = this.style.map(function(pair){
      var property = pair[0], value = pair[1], unit = null;

      if(value.parseColor('#zzzzzz') != '#zzzzzz') {
        value = value.parseColor();
        unit  = 'color';
      } else if(property == 'opacity') {
        value = parseFloat(value);
        if(Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
          this.element.setStyle({zoom: 1});
      } else if(Element.CSS_LENGTH.test(value)) {
          var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/);
          value = parseFloat(components[1]);
          unit = (components.length == 3) ? components[2] : null;
      }

      var originalValue = this.element.getStyle(property);
      return { 
        style: property.camelize(), 
        originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0), 
        targetValue: unit=='color' ? parseColor(value) : value,
        unit: unit
      };
    }.bind(this)).reject(function(transform){
      return (
        (transform.originalValue == transform.targetValue) ||
        (
          transform.unit != 'color' &&
          (isNaN(transform.originalValue) || isNaN(transform.targetValue))
        )
      )
    });
  },
  update: function(position) {
    var style = {}, transform, i = this.transforms.length;
    while(i--)
      style[(transform = this.transforms[i]).style] = 
        transform.unit=='color' ? '#'+
          (Math.round(transform.originalValue[0]+
            (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() +
          (Math.round(transform.originalValue[1]+
            (transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() +
          (Math.round(transform.originalValue[2]+
            (transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() :
        transform.originalValue + Math.round(
          ((transform.targetValue - transform.originalValue) * position) * 1000)/1000 + transform.unit;
    this.element.setStyle(style, true);
  }
});

Effect.Transform = Class.create();
Object.extend(Effect.Transform.prototype, {
  initialize: function(tracks){
    this.tracks  = [];
    this.options = arguments[1] || {};
    this.addTracks(tracks);
  },
  addTracks: function(tracks){
    tracks.each(function(track){
      var data = $H(track).values().first();
      this.tracks.push($H({
        ids:     $H(track).keys().first(),
        effect:  Effect.Morph,
        options: { style: data }
      }));
    }.bind(this));
    return this;
  },
  play: function(){
    return new Effect.Parallel(
      this.tracks.map(function(track){
        var elements = [$(track.ids) || $$(track.ids)].flatten();
        return elements.map(function(e){ return new track.effect(e, Object.extend({ sync:true }, track.options)) });
      }).flatten(),
      this.options
    );
  }
});

Element.CSS_PROPERTIES = $w(
  'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' + 
  'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
  'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
  'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
  'fontSize fontWeight height left letterSpacing lineHeight ' +
  'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
  'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
  'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
  'right textIndent top width wordSpacing zIndex');
  
Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;

String.prototype.parseStyle = function(){
  var element = document.createElement('div');
  element.innerHTML = '<div style="' + this + '"></div>';
  var style = element.childNodes[0].style, styleRules = $H();
  
  Element.CSS_PROPERTIES.each(function(property){
    if(style[property]) styleRules[property] = style[property]; 
  });
  if(Prototype.Browser.IE && this.indexOf('opacity') > -1) {
    styleRules.opacity = this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1];
  }
  return styleRules;
};

Element.morph = function(element, style) {
  new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || {}));
  return element;
};

['getInlineOpacity','forceRerendering','setContentZoom',
 'collectTextNodes','collectTextNodesIgnoreClass','morph'].each( 
  function(f) { Element.Methods[f] = Element[f]; }
);

Element.Methods.visualEffect = function(element, effect, options) {
  s = effect.dasherize().camelize();
  effect_class = s.charAt(0).toUpperCase() + s.substring(1);
  new Effect[effect_class](element, options);
  return $(element);
};

Element.addMethods();//init
document.ajaxLoaded = false;
document.TEXTresp = null;
document.currentUser = eatCookie('username');


Ajax.currentLightboxRequests = $H({}); //to hold all lightbox-type requests
Ajax.cacheHash = new Object();
Ajax.cacheDex = new Array(); //to track the assoc object...
Ajax.activeLightboxCount = 0;
Ajax.activeLightboxSaveCount = 0;


var bWait = {
	generic: function(e) {
		if (Ajax.activeLightboxSaveCount > 0)
		{
			var event = e || window.event;
			event.returnValue = 'Your changes are still saving... ('+Ajax.activeLightboxSaveCount+')\nIf you click OK you may lose changes.';
			if (  event.preventDefault )
				event.preventDefault();
			else
				new Event(event).preventDefault();
		}
	}
};


//create responder monitor to count active requests
Ajax.Responders.register({
  onCreate: function(request) {
    if (request.options.furl && request.options.furl.match(/\/(Lightbox|Share|R\?)/) ) {
	if ($('view_exp_link')) //view expanded is synchronous, so need to wait for all saves before viewing expanded
	{
		$('view_exp_link').onclick = "alert('Your lightbox is still updaing.  This link will be re-enabled as soon as it is complete'); return false";
		$('view_exp_link').style.color = '#E1E1E1';
	}

        Ajax.activeLightboxCount++;
	if ( request.options.furl.match(/\/(LightboxSave|ShareSet)/) )
	{	
		if (Ajax.activeLightboxSaveCount == 0) //your first..
			Event.observe(window, 'beforeunload', bWait.generic.bindAsEventListener(bWait));
		Ajax.activeLightboxSaveCount++;
	}

	if( ! request.options.furl.match(/\/(Lightbox(Info|Save)|ShareSet)/) )  
        {
	    Ajax.currentLightboxRequests[request.options.furl] = request; 
	    //then serialize and save...
	    var tstr = $A(Ajax.currentLightboxRequests.keys()).toJSON();
	    bakeCookie('lightbox_queue.'+document.currentUser, tstr, 1);
        }
    }

  },
  onComplete: function(request) {
    if (request.options.furl && request.options.furl.match(/\/(Lightbox|Share|R\?)/) ) {

	if (! request.options.furl.match(/\/(Lightbox(Info|Save)|ShareSet)/) )
    	{	
           delete Ajax.currentLightboxRequests[request.options.furl];
           var tstr = $A(Ajax.currentLightboxRequests.keys()).toJSON();
           bakeCookie('lightbox_queue.'+document.currentUser, tstr, 1);
    	}

        if ( request.options.furl.match(/\/(LightboxSave|ShareSet)/) )
        {
		Ajax.activeLightboxSaveCount--;
		if (Ajax.activeLightboxSaveCount == 0) //your last..
			Event.stopObserving(window, 'beforeunload', bWait.generic.bindAsEventListener(bWait));

	}
        Ajax.activeLightboxCount--;

	if (Ajax.activeLightboxCount == 0)
        	if ($('view_exp_link'))
		{
                	$('view_exp_link').onclick = '';
			$('view_exp_link').style.color = '#666666';
		}

    }
  }
});


//shortcuts;
var $GKW;
var $GID;

//object caching
CacheDecider=Class.create();
CacheDecider.prototype = {
    initialize: function(rng){
        //How long do we want to
        //keep the associated data, in seconds?
        this.secondsToCache=rng;
        this.lastFetched=new Date();

    },
    keepData: function(){
        var now = new Date();
        //Get the difference in seconds between the current time
        //and the lastFetched property value
        var secondsDif = parseInt((now.getTime() - 
        this.lastFetched.getTime()) / 1000);
        //If the prior computed value is less than
        //the specified number of seconds to keep
        //a value cached, then return true
        if (secondsDif < this.secondsToCache)  { return true;}
        //the data in the cache will be refreshed or re-fetched,
        //therefore reset the lastFetched value to the current time
        this.lastFetched=new Date();
        return false;
    },
    theData: null
}

localJSONobj = Class.create();
localJSONobj.prototype = {
	initialize: function (rt) {
		try {
			//this.oJSON = eval('('+ rt +')'); //rObj.responseText
			var tsrt = rt + " ";
			this.oJSON = tsrt.evalJSON();
		} catch (e) { console.log('Parse Error: '+e); }

		if (this.oJSON.error)
			alert(this.oJSON.error);
	
		if (this.oJSON.keywords)
			if (this.oJSON.keywords.keywords)
				if (this.oJSON.keywords.keywords.length == 1)
					this.oJSON.keywords.keywords = this.oJSON.keywords.keywords[0].split(", ");


	},
	//then do a quick check on keywords, in case they come as one string	
	getKeywords: function () { 
		//keywords is nested, so 
		if (this.oJSON.keywords.keywords)
			return this.oJSON.keywords.keywords;
		else 
			return;
	},
	getCartDat: function (attrName,count){
		if ( this.oJSON.item && this.oJSON.item[count])
		{ 
			if (this.oJSON.total == 'undefined') //init count on empty cart
                                this.oJSON.total = 0;


                        if (this.oJSON.item[count][attrName])
                                return this.oJSON.item[count][attrName];
                        else
                                return;
		}
		else if (attrName.match(/total/i))
		{
			return this.oJSON.total;
		}
		else
		{
			return;
		}

	},
	getLbDat: function (attrName,count){
		if ( this.oJSON[attrName] ) //single image data
		{
			return this.oJSON[attrName];
		}
		else
		{
			return '';
		}
	},
	getImgDat: function (attrName,count) {
		if ( this.oJSON.item && this.oJSON.item[count]) // looking for an image in the cart 
		{
			if (this.oJSON.total == 'undefined') //init count on empty cart
				this.oJSON.total = 0;

			if (this.oJSON.item[count].image)
				if (this.oJSON.item[count].image[attrName])
					return this.oJSON.item[count].image[attrName];
				else
					return;
		}
		else if ( this.oJSON[attrName] ) //single image data
		{
			return this.oJSON[attrName];
		}
		else
		{
			return '';
		}
		//filter out other site's cart images if this is a cart object
		if (this.oJSON.total && this.oJSON.sphotog)
		{
			var splArr = new Array;
			var siteTotal = 0;
			for (cti=0;cti<this.oJSON.total;cti++)
			{
				if (this.oJSON.sphotog == this.oJSON.item[cti].S_Photog)
				{
					splArr.push(this.oJSON.item[cti]);
				}
			}
			this.oJSON.total = splArr.length;
			this.oJSON.item = splArr;
		}
	},
	oJSON: null
}


function ajax_HTML (oTarget, url, meth, prams) { //takes a target object, url, and method.. optionally params
	if (! oTarget)
		return;
	if(url.match(/\/bin\/Cart\?op\=/))//set cartflasg.. and add a random pram.  Here's why:  Firefox won't POST this properly
	{										// and IE caches it on a GET
		cartdispcheck = 1;
		if (! url.match(/\&drk\=/))
			url += '&drk='+Math.random(10);
	}
	var myAjax = new Ajax.Updater(
		oTarget,
		url, 
		{
                        //evalScripts: true,
			method: meth,
			parameters: prams,
			onComplete: function (oReq) { cartdispcheck = 0; },  //oTarget.innerHTML = oReq.responseText;
			onFailure: function () { /*alert('communications error');*/ }
		}
	);

}

function ajax_TEXT ( url, meth, prams ) {
	document.TEXTresp = false;
	var myAjax = new Ajax.Request(
		url, 
		{
			method: meth, 
			parameters: prams,
			onComplete: function (oReq) { document.TEXTresp = oReq.responseText; },
			onFailure: function () { /*alert('communications error');*/ }
		}
	);
} 

function ajax_JSON (url, meth, prams, synch) {	//last param is DANGEROUS (force to synchronous call..)

  var callbackCode = undefined;

  if (prams && prams != null)
   {
    callbackCode = (typeof(prams.callback) == 'function' ? prams.callback : undefined) ; // allow to pass a callback function - Milan Adamovsky 06/18/2009
   }

	document.ajaxLoaded = false;

	var cachesize = 32;
	var nocache = 0;

	var curl = url;
	if(url.match(/Cart|Lightbox|Share/))//NOCACHE!  //Here's the thing.  Urls for blah.json should never have args, they are arg-less handlers
	{				//so now the AJAXHandler this talks to will totally toss anything it finds after the '?'
					// so just append it here w/ leading ? if it's a cart item
		if ( ! url.match(/(\&|\?)drk\=/)) // don't re-add prams to call that already has them...
		{
			curl += '?drk='+Math.random(10);
			var apprams = prams;
			if (typeof(prams) == 'object' && prams != null )
				apprams = $H(prams).toQueryString();
	                if (apprams && apprams.toString().length < 500)
			{
				curl += '&'+apprams;
				if (meth.match(/GET/i))
					prams = '';
			}
			else if (prams) //must be above..
				meth = 'POST'; //necessarily
		}
		nocache = 1;
	}
        else if (prams && prams != null)
	{
		if (prams.toString().length < 500) 
		{
			curl += '?'+prams;
			if (meth.match(/GET/i))
				prams = '';
		}
		else if (prams)
			meth = 'POST';
	}

	var cacher = Ajax.cacheHash[curl];

	if (! cacher || ! cacher.theData || ! cacher.keepData() || nocache) //nocache forces load every time..
	{
		if(! nocache)
		{
			cacher = new CacheDecider(60*15); //w/i 15 mins...
			Ajax.cacheHash[curl] = cacher; //put empty cacheob in tree..., if ob has no data just overwrite
			Ajax.cacheDex.push(curl);
			//need to check  length of cache and trim out oldest...
			if (Ajax.cacheDex.length > cachesize)
			{
				var furl = Ajax.cacheDex.shift(); //first item in list popped from dex...
				if(furl)
					delete Ajax.cacheHash[furl];
			}
		}
		var myAjax = new Ajax.Request(
			curl, 
			{
				method: meth,
				parameters: prams, 
				furl: curl,
				asynchronous: (synch ? false : true),  //LightboxSave is special.. we want it logged as a responder, but not wait for callback..
				onComplete: function (oBj) { if(! url.match(/LightboxSave/)) { document.ajaxLoaded = true; mkObj(oBj, curl); !callbackCode || callbackCode() } },
				onFailure: function () { /*alert('communications error');*/ }
			});
	}
	else //have it cached
	{
		document.JSONobj = Ajax.cacheHash[curl].theData;
		document.ajaxLoaded = true;
		//SO KEY: Lastly, fire a requested callback if it exists as a 0 level item in the object
		if ( document.JSONobj.oJSON.callback) //( document.JSONobj.oJSON && document.JSONobj.oJSON.callback  && document.JSONobj.oJSON.callback != null)
			eval( document.JSONobj.oJSON.callback );
	}
	

}

/*
JSONobj prototype: 
	JSONobj.keys -> list of child items
	JSONobj.length -> length of child items list...
	JSONobj
if n is object
	JSONobj.n.keys
	JSONobj.n.length
	JSONobj.n
else
	JSONobj.n
...
.....
recurses to a depth of 32...

cart calls: ipnstock.ipndev.com/AjaxHandlers/CartInfo/open.json

*/
function mkObj (rObj, url) {
	var rt = rObj.responseText;
	document.JSONobj = new localJSONobj(rt);
	//and cache, maybe
	if ( Ajax.cacheHash[url] && ! url.match(/Cart|Lightbox|Share/))
		Ajax.cacheHash[url].theData = document.JSONobj;
	//SO KEY: Lastly, fire a requested callback if it exists as a 0 level item in the object
	if ( document.JSONobj.oJSON.callback )
		eval( document.JSONobj.oJSON.callback );		
}

function bakeCookie(name,value,hours) {
	if (hours) {
		var date = new Date();
		date.setTime(date.getTime()+(hours*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function eatCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function tossCookie(name) {
	bakeCookie(name,"",1);
}

//next check if we have any lightbox type requests pending...
if ( document.currentUser )
{
	var ltstr = eatCookie('lightbox_queue.'+document.currentUser);
	if (ltstr)
	{
		var tltstr = ltstr + " ";
		var actions = $A(tltstr.evalJSON());

		if (actions.length)
		{
			var last_action = actions.pop();
			actions.each(function(lurl) {
				ajax_JSON(lurl, 'GET', null);
			});
			tossCookie('lightbox_queue.'+document.currentUser);
                  if (last_action.indexOf('callback=lightbox_mod_act(0)') < 0)
                    last_action = last_action+'&callback=lightbox_mod_act(0)';

                  ajax_JSON(last_action, 'GET', null);
		}
	}
}
/*
Copyright (c) 2008, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.5.2
*/
if(typeof YAHOO=="undefined"||!YAHOO){var YAHOO={};}YAHOO.namespace=function(){var A=arguments,E=null,C,B,D;for(C=0;C<A.length;C=C+1){D=A[C].split(".");E=YAHOO;for(B=(D[0]=="YAHOO")?1:0;B<D.length;B=B+1){E[D[B]]=E[D[B]]||{};E=E[D[B]];}}return E;};YAHOO.log=function(D,A,C){var B=YAHOO.widget.Logger;if(B&&B.log){return B.log(D,A,C);}else{return false;}};YAHOO.register=function(A,E,D){var I=YAHOO.env.modules;if(!I[A]){I[A]={versions:[],builds:[]};}var B=I[A],H=D.version,G=D.build,F=YAHOO.env.listeners;B.name=A;B.version=H;B.build=G;B.versions.push(H);B.builds.push(G);B.mainClass=E;for(var C=0;C<F.length;C=C+1){F[C](B);}if(E){E.VERSION=H;E.BUILD=G;}else{YAHOO.log("mainClass is undefined for module "+A,"warn");}};YAHOO.env=YAHOO.env||{modules:[],listeners:[]};YAHOO.env.getVersion=function(A){return YAHOO.env.modules[A]||null;};YAHOO.env.ua=function(){var C={ie:0,opera:0,gecko:0,webkit:0,mobile:null,air:0};var B=navigator.userAgent,A;if((/KHTML/).test(B)){C.webkit=1;}A=B.match(/AppleWebKit\/([^\s]*)/);if(A&&A[1]){C.webkit=parseFloat(A[1]);if(/ Mobile\//.test(B)){C.mobile="Apple";}else{A=B.match(/NokiaN[^\/]*/);if(A){C.mobile=A[0];}}A=B.match(/AdobeAIR\/([^\s]*)/);if(A){C.air=A[0];}}if(!C.webkit){A=B.match(/Opera[\s\/]([^\s]*)/);if(A&&A[1]){C.opera=parseFloat(A[1]);A=B.match(/Opera Mini[^;]*/);if(A){C.mobile=A[0];}}else{A=B.match(/MSIE\s([^;]*)/);if(A&&A[1]){C.ie=parseFloat(A[1]);}else{A=B.match(/Gecko\/([^\s]*)/);if(A){C.gecko=1;A=B.match(/rv:([^\s\)]*)/);if(A&&A[1]){C.gecko=parseFloat(A[1]);}}}}}return C;}();(function(){YAHOO.namespace("util","widget","example");if("undefined"!==typeof YAHOO_config){var B=YAHOO_config.listener,A=YAHOO.env.listeners,D=true,C;if(B){for(C=0;C<A.length;C=C+1){if(A[C]==B){D=false;break;}}if(D){A.push(B);}}}})();YAHOO.lang=YAHOO.lang||{};(function(){var A=YAHOO.lang,C=["toString","valueOf"],B={isArray:function(D){if(D){return A.isNumber(D.length)&&A.isFunction(D.splice);}return false;},isBoolean:function(D){return typeof D==="boolean";},isFunction:function(D){return typeof D==="function";},isNull:function(D){return D===null;},isNumber:function(D){return typeof D==="number"&&isFinite(D);},isObject:function(D){return(D&&(typeof D==="object"||A.isFunction(D)))||false;},isString:function(D){return typeof D==="string";},isUndefined:function(D){return typeof D==="undefined";},_IEEnumFix:(YAHOO.env.ua.ie)?function(F,E){for(var D=0;D<C.length;D=D+1){var H=C[D],G=E[H];if(A.isFunction(G)&&G!=Object.prototype[H]){F[H]=G;}}}:function(){},extend:function(H,I,G){if(!I||!H){throw new Error("extend failed, please check that "+"all dependencies are included.");}var E=function(){};E.prototype=I.prototype;H.prototype=new E();H.prototype.constructor=H;H.superclass=I.prototype;if(I.prototype.constructor==Object.prototype.constructor){I.prototype.constructor=I;}if(G){for(var D in G){if(A.hasOwnProperty(G,D)){H.prototype[D]=G[D];}}A._IEEnumFix(H.prototype,G);}},augmentObject:function(H,G){if(!G||!H){throw new Error("Absorb failed, verify dependencies.");}var D=arguments,F,I,E=D[2];if(E&&E!==true){for(F=2;F<D.length;F=F+1){H[D[F]]=G[D[F]];}}else{for(I in G){if(E||!(I in H)){H[I]=G[I];}}A._IEEnumFix(H,G);}},augmentProto:function(G,F){if(!F||!G){throw new Error("Augment failed, verify dependencies.");}var D=[G.prototype,F.prototype];for(var E=2;E<arguments.length;E=E+1){D.push(arguments[E]);}A.augmentObject.apply(this,D);},dump:function(D,I){var F,H,K=[],L="{...}",E="f(){...}",J=", ",G=" => ";if(!A.isObject(D)){return D+"";}else{if(D instanceof Date||("nodeType" in D&&"tagName" in D)){return D;}else{if(A.isFunction(D)){return E;}}}I=(A.isNumber(I))?I:3;if(A.isArray(D)){K.push("[");for(F=0,H=D.length;F<H;F=F+1){if(A.isObject(D[F])){K.push((I>0)?A.dump(D[F],I-1):L);}else{K.push(D[F]);}K.push(J);}if(K.length>1){K.pop();}K.push("]");}else{K.push("{");for(F in D){if(A.hasOwnProperty(D,F)){K.push(F+G);if(A.isObject(D[F])){K.push((I>0)?A.dump(D[F],I-1):L);}else{K.push(D[F]);}K.push(J);}}if(K.length>1){K.pop();}K.push("}");}return K.join("");},substitute:function(S,E,L){var I,H,G,O,P,R,N=[],F,J="dump",M=" ",D="{",Q="}";for(;;){I=S.lastIndexOf(D);if(I<0){break;}H=S.indexOf(Q,I);if(I+1>=H){break;}F=S.substring(I+1,H);O=F;R=null;G=O.indexOf(M);if(G>-1){R=O.substring(G+1);O=O.substring(0,G);}P=E[O];if(L){P=L(O,P,R);}if(A.isObject(P)){if(A.isArray(P)){P=A.dump(P,parseInt(R,10));}else{R=R||"";var K=R.indexOf(J);if(K>-1){R=R.substring(4);}if(P.toString===Object.prototype.toString||K>-1){P=A.dump(P,parseInt(R,10));}else{P=P.toString();}}}else{if(!A.isString(P)&&!A.isNumber(P)){P="~-"+N.length+"-~";N[N.length]=F;}}S=S.substring(0,I)+P+S.substring(H+1);}for(I=N.length-1;I>=0;I=I-1){S=S.replace(new RegExp("~-"+I+"-~"),"{"+N[I]+"}","g");}return S;},trim:function(D){try{return D.replace(/^\s+|\s+$/g,"");}catch(E){return D;}},merge:function(){var G={},E=arguments;for(var F=0,D=E.length;F<D;F=F+1){A.augmentObject(G,E[F],true);}return G;},later:function(K,E,L,G,H){K=K||0;E=E||{};var F=L,J=G,I,D;if(A.isString(L)){F=E[L];}if(!F){throw new TypeError("method undefined");}if(!A.isArray(J)){J=[G];}I=function(){F.apply(E,J);};D=(H)?setInterval(I,K):setTimeout(I,K);return{interval:H,cancel:function(){if(this.interval){clearInterval(D);}else{clearTimeout(D);}}};},isValue:function(D){return(A.isObject(D)||A.isString(D)||A.isNumber(D)||A.isBoolean(D));}};A.hasOwnProperty=(Object.prototype.hasOwnProperty)?function(D,E){return D&&D.hasOwnProperty(E);}:function(D,E){return !A.isUndefined(D[E])&&D.constructor.prototype[E]!==D[E];};B.augmentObject(A,B,true);YAHOO.util.Lang=A;A.augment=A.augmentProto;YAHOO.augment=A.augmentProto;YAHOO.extend=A.extend;})();YAHOO.register("yahoo",YAHOO,{version:"2.5.2",build:"1076"});(function(){var B=YAHOO.util,K,I,J={},F={},M=window.document;YAHOO.env._id_counter=YAHOO.env._id_counter||0;var C=YAHOO.env.ua.opera,L=YAHOO.env.ua.webkit,A=YAHOO.env.ua.gecko,G=YAHOO.env.ua.ie;var E={HYPHEN:/(-[a-z])/i,ROOT_TAG:/^body|html$/i,OP_SCROLL:/^(?:inline|table-row)$/i};var N=function(P){if(!E.HYPHEN.test(P)){return P;}if(J[P]){return J[P];}var Q=P;while(E.HYPHEN.exec(Q)){Q=Q.replace(RegExp.$1,RegExp.$1.substr(1).toUpperCase());}J[P]=Q;return Q;};var O=function(Q){var P=F[Q];if(!P){P=new RegExp("(?:^|\\s+)"+Q+"(?:\\s+|$)");F[Q]=P;}return P;};if(M.defaultView&&M.defaultView.getComputedStyle){K=function(P,S){var R=null;if(S=="float"){S="cssFloat";}var Q=P.ownerDocument.defaultView.getComputedStyle(P,"");if(Q){R=Q[N(S)];}return P.style[S]||R;};}else{if(M.documentElement.currentStyle&&G){K=function(P,R){switch(N(R)){case"opacity":var T=100;try{T=P.filters["DXImageTransform.Microsoft.Alpha"].opacity;}catch(S){try{T=P.filters("alpha").opacity;}catch(S){}}return T/100;case"float":R="styleFloat";default:var Q=P.currentStyle?P.currentStyle[R]:null;return(P.style[R]||Q);}};}else{K=function(P,Q){return P.style[Q];};}}if(G){I=function(P,Q,R){switch(Q){case"opacity":if(YAHOO.lang.isString(P.style.filter)){P.style.filter="alpha(opacity="+R*100+")";if(!P.currentStyle||!P.currentStyle.hasLayout){P.style.zoom=1;}}break;case"float":Q="styleFloat";default:P.style[Q]=R;}};}else{I=function(P,Q,R){if(Q=="float"){Q="cssFloat";}P.style[Q]=R;};}var D=function(P,Q){return P&&P.nodeType==1&&(!Q||Q(P));};YAHOO.util.Dom={get:function(R){if(R&&(R.nodeType||R.item)){return R;}if(YAHOO.lang.isString(R)||!R){return M.getElementById(R);}if(R.length!==undefined){var S=[];for(var Q=0,P=R.length;Q<P;++Q){S[S.length]=B.Dom.get(R[Q]);}return S;}return R;},getStyle:function(P,R){R=N(R);var Q=function(S){return K(S,R);};return B.Dom.batch(P,Q,B.Dom,true);},setStyle:function(P,R,S){R=N(R);var Q=function(T){I(T,R,S);};B.Dom.batch(P,Q,B.Dom,true);},getXY:function(P){var Q=function(R){if((R.parentNode===null||R.offsetParent===null||this.getStyle(R,"display")=="none")&&R!=R.ownerDocument.body){return false;}return H(R);};return B.Dom.batch(P,Q,B.Dom,true);},getX:function(P){var Q=function(R){return B.Dom.getXY(R)[0];};return B.Dom.batch(P,Q,B.Dom,true);},getY:function(P){var Q=function(R){return B.Dom.getXY(R)[1];};return B.Dom.batch(P,Q,B.Dom,true);},setXY:function(P,S,R){var Q=function(V){var U=this.getStyle(V,"position");if(U=="static"){this.setStyle(V,"position","relative");U="relative";}var X=this.getXY(V);if(X===false){return false;}var W=[parseInt(this.getStyle(V,"left"),10),parseInt(this.getStyle(V,"top"),10)];if(isNaN(W[0])){W[0]=(U=="relative")?0:V.offsetLeft;}if(isNaN(W[1])){W[1]=(U=="relative")?0:V.offsetTop;}if(S[0]!==null){V.style.left=S[0]-X[0]+W[0]+"px";}if(S[1]!==null){V.style.top=S[1]-X[1]+W[1]+"px";}if(!R){var T=this.getXY(V);if((S[0]!==null&&T[0]!=S[0])||(S[1]!==null&&T[1]!=S[1])){this.setXY(V,S,true);}}};B.Dom.batch(P,Q,B.Dom,true);},setX:function(Q,P){B.Dom.setXY(Q,[P,null]);},setY:function(P,Q){B.Dom.setXY(P,[null,Q]);},getRegion:function(P){var Q=function(R){if((R.parentNode===null||R.offsetParent===null||this.getStyle(R,"display")=="none")&&R!=R.ownerDocument.body){return false;}var S=B.Region.getRegion(R);return S;};return B.Dom.batch(P,Q,B.Dom,true);},getClientWidth:function(){return B.Dom.getViewportWidth();},getClientHeight:function(){return B.Dom.getViewportHeight();},getElementsByClassName:function(T,X,U,V){X=X||"*";U=(U)?B.Dom.get(U):null||M;if(!U){return[];}var Q=[],P=U.getElementsByTagName(X),W=O(T);for(var R=0,S=P.length;R<S;++R){if(W.test(P[R].className)){Q[Q.length]=P[R];if(V){V.call(P[R],P[R]);}}}return Q;},hasClass:function(R,Q){var P=O(Q);var S=function(T){return P.test(T.className);};return B.Dom.batch(R,S,B.Dom,true);},addClass:function(Q,P){var R=function(S){if(this.hasClass(S,P)){return false;}S.className=YAHOO.lang.trim([S.className,P].join(" "));return true;};return B.Dom.batch(Q,R,B.Dom,true);},removeClass:function(R,Q){var P=O(Q);var S=function(T){if(!Q||!this.hasClass(T,Q)){return false;}var U=T.className;T.className=U.replace(P," ");if(this.hasClass(T,Q)){this.removeClass(T,Q);}T.className=YAHOO.lang.trim(T.className);return true;};return B.Dom.batch(R,S,B.Dom,true);},replaceClass:function(S,Q,P){if(!P||Q===P){return false;}var R=O(Q);var T=function(U){if(!this.hasClass(U,Q)){this.addClass(U,P);return true;}U.className=U.className.replace(R," "+P+" ");if(this.hasClass(U,Q)){this.replaceClass(U,Q,P);}U.className=YAHOO.lang.trim(U.className);return true;};return B.Dom.batch(S,T,B.Dom,true);},generateId:function(P,R){R=R||"yui-gen";var Q=function(S){if(S&&S.id){return S.id;}var T=R+YAHOO.env._id_counter++;if(S){S.id=T;}return T;};return B.Dom.batch(P,Q,B.Dom,true)||Q.apply(B.Dom,arguments);},isAncestor:function(P,Q){P=B.Dom.get(P);Q=B.Dom.get(Q);if(!P||!Q){return false;}if(P.contains&&Q.nodeType&&!L){return P.contains(Q);}else{if(P.compareDocumentPosition&&Q.nodeType){return !!(P.compareDocumentPosition(Q)&16);}else{if(Q.nodeType){return !!this.getAncestorBy(Q,function(R){return R==P;});}}}return false;},inDocument:function(P){return this.isAncestor(M.documentElement,P);},getElementsBy:function(W,Q,R,T){Q=Q||"*";R=(R)?B.Dom.get(R):null||M;if(!R){return[];}var S=[],V=R.getElementsByTagName(Q);for(var U=0,P=V.length;U<P;++U){if(W(V[U])){S[S.length]=V[U];if(T){T(V[U]);}}}return S;},batch:function(T,W,V,R){T=(T&&(T.tagName||T.item))?T:B.Dom.get(T);if(!T||!W){return false;}var S=(R)?V:window;if(T.tagName||T.length===undefined){return W.call(S,T,V);}var U=[];for(var Q=0,P=T.length;Q<P;++Q){U[U.length]=W.call(S,T[Q],V);}return U;},getDocumentHeight:function(){var Q=(M.compatMode!="CSS1Compat")?M.body.scrollHeight:M.documentElement.scrollHeight;var P=Math.max(Q,B.Dom.getViewportHeight());return P;},getDocumentWidth:function(){var Q=(M.compatMode!="CSS1Compat")?M.body.scrollWidth:M.documentElement.scrollWidth;var P=Math.max(Q,B.Dom.getViewportWidth());return P;},getViewportHeight:function(){var P=self.innerHeight;
var Q=M.compatMode;if((Q||G)&&!C){P=(Q=="CSS1Compat")?M.documentElement.clientHeight:M.body.clientHeight;}return P;},getViewportWidth:function(){var P=self.innerWidth;var Q=M.compatMode;if(Q||G){P=(Q=="CSS1Compat")?M.documentElement.clientWidth:M.body.clientWidth;}return P;},getAncestorBy:function(P,Q){while(P=P.parentNode){if(D(P,Q)){return P;}}return null;},getAncestorByClassName:function(Q,P){Q=B.Dom.get(Q);if(!Q){return null;}var R=function(S){return B.Dom.hasClass(S,P);};return B.Dom.getAncestorBy(Q,R);},getAncestorByTagName:function(Q,P){Q=B.Dom.get(Q);if(!Q){return null;}var R=function(S){return S.tagName&&S.tagName.toUpperCase()==P.toUpperCase();};return B.Dom.getAncestorBy(Q,R);},getPreviousSiblingBy:function(P,Q){while(P){P=P.previousSibling;if(D(P,Q)){return P;}}return null;},getPreviousSibling:function(P){P=B.Dom.get(P);if(!P){return null;}return B.Dom.getPreviousSiblingBy(P);},getNextSiblingBy:function(P,Q){while(P){P=P.nextSibling;if(D(P,Q)){return P;}}return null;},getNextSibling:function(P){P=B.Dom.get(P);if(!P){return null;}return B.Dom.getNextSiblingBy(P);},getFirstChildBy:function(P,R){var Q=(D(P.firstChild,R))?P.firstChild:null;return Q||B.Dom.getNextSiblingBy(P.firstChild,R);},getFirstChild:function(P,Q){P=B.Dom.get(P);if(!P){return null;}return B.Dom.getFirstChildBy(P);},getLastChildBy:function(P,R){if(!P){return null;}var Q=(D(P.lastChild,R))?P.lastChild:null;return Q||B.Dom.getPreviousSiblingBy(P.lastChild,R);},getLastChild:function(P){P=B.Dom.get(P);return B.Dom.getLastChildBy(P);},getChildrenBy:function(Q,S){var R=B.Dom.getFirstChildBy(Q,S);var P=R?[R]:[];B.Dom.getNextSiblingBy(R,function(T){if(!S||S(T)){P[P.length]=T;}return false;});return P;},getChildren:function(P){P=B.Dom.get(P);if(!P){}return B.Dom.getChildrenBy(P);},getDocumentScrollLeft:function(P){P=P||M;return Math.max(P.documentElement.scrollLeft,P.body.scrollLeft);},getDocumentScrollTop:function(P){P=P||M;return Math.max(P.documentElement.scrollTop,P.body.scrollTop);},insertBefore:function(Q,P){Q=B.Dom.get(Q);P=B.Dom.get(P);if(!Q||!P||!P.parentNode){return null;}return P.parentNode.insertBefore(Q,P);},insertAfter:function(Q,P){Q=B.Dom.get(Q);P=B.Dom.get(P);if(!Q||!P||!P.parentNode){return null;}if(P.nextSibling){return P.parentNode.insertBefore(Q,P.nextSibling);}else{return P.parentNode.appendChild(Q);}},getClientRegion:function(){var R=B.Dom.getDocumentScrollTop(),Q=B.Dom.getDocumentScrollLeft(),S=B.Dom.getViewportWidth()+Q,P=B.Dom.getViewportHeight()+R;return new B.Region(R,S,P,Q);}};var H=function(){if(M.documentElement.getBoundingClientRect){return function(Q){var R=Q.getBoundingClientRect();var P=Q.ownerDocument;return[R.left+B.Dom.getDocumentScrollLeft(P),R.top+B.Dom.getDocumentScrollTop(P)];};}else{return function(R){var S=[R.offsetLeft,R.offsetTop];var Q=R.offsetParent;var P=(L&&B.Dom.getStyle(R,"position")=="absolute"&&R.offsetParent==R.ownerDocument.body);if(Q!=R){while(Q){S[0]+=Q.offsetLeft;S[1]+=Q.offsetTop;if(!P&&L&&B.Dom.getStyle(Q,"position")=="absolute"){P=true;}Q=Q.offsetParent;}}if(P){S[0]-=R.ownerDocument.body.offsetLeft;S[1]-=R.ownerDocument.body.offsetTop;}Q=R.parentNode;while(Q.tagName&&!E.ROOT_TAG.test(Q.tagName)){if(Q.scrollTop||Q.scrollLeft){if(!E.OP_SCROLL.test(B.Dom.getStyle(Q,"display"))){if(!C||B.Dom.getStyle(Q,"overflow")!=="visible"){S[0]-=Q.scrollLeft;S[1]-=Q.scrollTop;}}}Q=Q.parentNode;}return S;};}}();})();YAHOO.util.Region=function(C,D,A,B){this.top=C;this[1]=C;this.right=D;this.bottom=A;this.left=B;this[0]=B;};YAHOO.util.Region.prototype.contains=function(A){return(A.left>=this.left&&A.right<=this.right&&A.top>=this.top&&A.bottom<=this.bottom);};YAHOO.util.Region.prototype.getArea=function(){return((this.bottom-this.top)*(this.right-this.left));};YAHOO.util.Region.prototype.intersect=function(E){var C=Math.max(this.top,E.top);var D=Math.min(this.right,E.right);var A=Math.min(this.bottom,E.bottom);var B=Math.max(this.left,E.left);if(A>=C&&D>=B){return new YAHOO.util.Region(C,D,A,B);}else{return null;}};YAHOO.util.Region.prototype.union=function(E){var C=Math.min(this.top,E.top);var D=Math.max(this.right,E.right);var A=Math.max(this.bottom,E.bottom);var B=Math.min(this.left,E.left);return new YAHOO.util.Region(C,D,A,B);};YAHOO.util.Region.prototype.toString=function(){return("Region {"+"top: "+this.top+", right: "+this.right+", bottom: "+this.bottom+", left: "+this.left+"}");};YAHOO.util.Region.getRegion=function(D){var F=YAHOO.util.Dom.getXY(D);var C=F[1];var E=F[0]+D.offsetWidth;var A=F[1]+D.offsetHeight;var B=F[0];return new YAHOO.util.Region(C,E,A,B);};YAHOO.util.Point=function(A,B){if(YAHOO.lang.isArray(A)){B=A[1];A=A[0];}this.x=this.right=this.left=this[0]=A;this.y=this.top=this.bottom=this[1]=B;};YAHOO.util.Point.prototype=new YAHOO.util.Region();YAHOO.register("dom",YAHOO.util.Dom,{version:"2.5.2",build:"1076"});YAHOO.util.CustomEvent=function(D,B,C,A){this.type=D;this.scope=B||window;this.silent=C;this.signature=A||YAHOO.util.CustomEvent.LIST;this.subscribers=[];if(!this.silent){}var E="_YUICEOnSubscribe";if(D!==E){this.subscribeEvent=new YAHOO.util.CustomEvent(E,this,true);}this.lastError=null;};YAHOO.util.CustomEvent.LIST=0;YAHOO.util.CustomEvent.FLAT=1;YAHOO.util.CustomEvent.prototype={subscribe:function(B,C,A){if(!B){throw new Error("Invalid callback for subscriber to '"+this.type+"'");}if(this.subscribeEvent){this.subscribeEvent.fire(B,C,A);}this.subscribers.push(new YAHOO.util.Subscriber(B,C,A));},unsubscribe:function(D,F){if(!D){return this.unsubscribeAll();}var E=false;for(var B=0,A=this.subscribers.length;B<A;++B){var C=this.subscribers[B];if(C&&C.contains(D,F)){this._delete(B);E=true;}}return E;},fire:function(){this.lastError=null;var K=[],E=this.subscribers.length;if(!E&&this.silent){return true;}var I=[].slice.call(arguments,0),G=true,D,J=false;if(!this.silent){}var C=this.subscribers.slice(),A=YAHOO.util.Event.throwErrors;for(D=0;D<E;++D){var M=C[D];if(!M){J=true;}else{if(!this.silent){}var L=M.getScope(this.scope);if(this.signature==YAHOO.util.CustomEvent.FLAT){var B=null;if(I.length>0){B=I[0];}try{G=M.fn.call(L,B,M.obj);}catch(F){this.lastError=F;if(A){throw F;}}}else{try{G=M.fn.call(L,this.type,I,M.obj);}catch(H){this.lastError=H;if(A){throw H;}}}if(false===G){if(!this.silent){}break;}}}return(G!==false);},unsubscribeAll:function(){for(var A=this.subscribers.length-1;A>-1;A--){this._delete(A);}this.subscribers=[];return A;},_delete:function(A){var B=this.subscribers[A];if(B){delete B.fn;delete B.obj;}this.subscribers.splice(A,1);},toString:function(){return"CustomEvent: "+"'"+this.type+"', "+"scope: "+this.scope;}};YAHOO.util.Subscriber=function(B,C,A){this.fn=B;this.obj=YAHOO.lang.isUndefined(C)?null:C;this.override=A;};YAHOO.util.Subscriber.prototype.getScope=function(A){if(this.override){if(this.override===true){return this.obj;}else{return this.override;}}return A;};YAHOO.util.Subscriber.prototype.contains=function(A,B){if(B){return(this.fn==A&&this.obj==B);}else{return(this.fn==A);}};YAHOO.util.Subscriber.prototype.toString=function(){return"Subscriber { obj: "+this.obj+", override: "+(this.override||"no")+" }";};if(!YAHOO.util.Event){YAHOO.util.Event=function(){var H=false;var I=[];var J=[];var G=[];var E=[];var C=0;var F=[];var B=[];var A=0;var D={63232:38,63233:40,63234:37,63235:39,63276:33,63277:34,25:9};return{POLL_RETRYS:2000,POLL_INTERVAL:20,EL:0,TYPE:1,FN:2,WFN:3,UNLOAD_OBJ:3,ADJ_SCOPE:4,OBJ:5,OVERRIDE:6,lastError:null,isSafari:YAHOO.env.ua.webkit,webkit:YAHOO.env.ua.webkit,isIE:YAHOO.env.ua.ie,_interval:null,_dri:null,DOMReady:false,throwErrors:false,startInterval:function(){if(!this._interval){var K=this;var L=function(){K._tryPreloadAttach();};this._interval=setInterval(L,this.POLL_INTERVAL);}},onAvailable:function(P,M,Q,O,N){var K=(YAHOO.lang.isString(P))?[P]:P;for(var L=0;L<K.length;L=L+1){F.push({id:K[L],fn:M,obj:Q,override:O,checkReady:N});}C=this.POLL_RETRYS;this.startInterval();},onContentReady:function(M,K,N,L){this.onAvailable(M,K,N,L,true);},onDOMReady:function(K,M,L){if(this.DOMReady){setTimeout(function(){var N=window;if(L){if(L===true){N=M;}else{N=L;}}K.call(N,"DOMReady",[],M);},0);}else{this.DOMReadyEvent.subscribe(K,M,L);}},addListener:function(M,K,V,Q,L){if(!V||!V.call){return false;}if(this._isValidCollection(M)){var W=true;for(var R=0,T=M.length;R<T;++R){W=this.on(M[R],K,V,Q,L)&&W;}return W;}else{if(YAHOO.lang.isString(M)){var P=this.getEl(M);if(P){M=P;}else{this.onAvailable(M,function(){YAHOO.util.Event.on(M,K,V,Q,L);});return true;}}}if(!M){return false;}if("unload"==K&&Q!==this){J[J.length]=[M,K,V,Q,L];return true;}var Y=M;if(L){if(L===true){Y=Q;}else{Y=L;}}var N=function(Z){return V.call(Y,YAHOO.util.Event.getEvent(Z,M),Q);};var X=[M,K,V,N,Y,Q,L];var S=I.length;I[S]=X;if(this.useLegacyEvent(M,K)){var O=this.getLegacyIndex(M,K);if(O==-1||M!=G[O][0]){O=G.length;B[M.id+K]=O;G[O]=[M,K,M["on"+K]];E[O]=[];M["on"+K]=function(Z){YAHOO.util.Event.fireLegacyEvent(YAHOO.util.Event.getEvent(Z),O);};}E[O].push(X);}else{try{this._simpleAdd(M,K,N,false);}catch(U){this.lastError=U;this.removeListener(M,K,V);return false;}}return true;},fireLegacyEvent:function(O,M){var Q=true,K,S,R,T,P;S=E[M].slice();for(var L=0,N=S.length;L<N;++L){R=S[L];if(R&&R[this.WFN]){T=R[this.ADJ_SCOPE];P=R[this.WFN].call(T,O);Q=(Q&&P);}}K=G[M];if(K&&K[2]){K[2](O);}return Q;},getLegacyIndex:function(L,M){var K=this.generateId(L)+M;if(typeof B[K]=="undefined"){return -1;}else{return B[K];}},useLegacyEvent:function(L,M){if(this.webkit&&("click"==M||"dblclick"==M)){var K=parseInt(this.webkit,10);if(!isNaN(K)&&K<418){return true;}}return false;},removeListener:function(L,K,T){var O,R,V;if(typeof L=="string"){L=this.getEl(L);}else{if(this._isValidCollection(L)){var U=true;for(O=L.length-1;O>-1;O--){U=(this.removeListener(L[O],K,T)&&U);}return U;}}if(!T||!T.call){return this.purgeElement(L,false,K);}if("unload"==K){for(O=J.length-1;O>-1;O--){V=J[O];if(V&&V[0]==L&&V[1]==K&&V[2]==T){J.splice(O,1);return true;}}return false;}var P=null;var Q=arguments[3];if("undefined"===typeof Q){Q=this._getCacheIndex(L,K,T);}if(Q>=0){P=I[Q];}if(!L||!P){return false;}if(this.useLegacyEvent(L,K)){var N=this.getLegacyIndex(L,K);var M=E[N];if(M){for(O=0,R=M.length;O<R;++O){V=M[O];if(V&&V[this.EL]==L&&V[this.TYPE]==K&&V[this.FN]==T){M.splice(O,1);break;}}}}else{try{this._simpleRemove(L,K,P[this.WFN],false);}catch(S){this.lastError=S;return false;}}delete I[Q][this.WFN];delete I[Q][this.FN];I.splice(Q,1);return true;},getTarget:function(M,L){var K=M.target||M.srcElement;return this.resolveTextNode(K);},resolveTextNode:function(L){try{if(L&&3==L.nodeType){return L.parentNode;}}catch(K){}return L;},getPageX:function(L){var K=L.pageX;if(!K&&0!==K){K=L.clientX||0;if(this.isIE){K+=this._getScrollLeft();}}return K;},getPageY:function(K){var L=K.pageY;if(!L&&0!==L){L=K.clientY||0;if(this.isIE){L+=this._getScrollTop();}}return L;
},getXY:function(K){return[this.getPageX(K),this.getPageY(K)];},getRelatedTarget:function(L){var K=L.relatedTarget;if(!K){if(L.type=="mouseout"){K=L.toElement;}else{if(L.type=="mouseover"){K=L.fromElement;}}}return this.resolveTextNode(K);},getTime:function(M){if(!M.time){var L=new Date().getTime();try{M.time=L;}catch(K){this.lastError=K;return L;}}return M.time;},stopEvent:function(K){this.stopPropagation(K);this.preventDefault(K);},stopPropagation:function(K){if(K.stopPropagation){K.stopPropagation();}else{K.cancelBubble=true;}},preventDefault:function(K){if(K.preventDefault){K.preventDefault();}else{K.returnValue=false;}},getEvent:function(M,K){var L=M||window.event;if(!L){var N=this.getEvent.caller;while(N){L=N.arguments[0];if(L&&Event==L.constructor){break;}N=N.caller;}}return L;},getCharCode:function(L){var K=L.keyCode||L.charCode||0;if(YAHOO.env.ua.webkit&&(K in D)){K=D[K];}return K;},_getCacheIndex:function(O,P,N){for(var M=0,L=I.length;M<L;M=M+1){var K=I[M];if(K&&K[this.FN]==N&&K[this.EL]==O&&K[this.TYPE]==P){return M;}}return -1;},generateId:function(K){var L=K.id;if(!L){L="yuievtautoid-"+A;++A;K.id=L;}return L;},_isValidCollection:function(L){try{return(L&&typeof L!=="string"&&L.length&&!L.tagName&&!L.alert&&typeof L[0]!=="undefined");}catch(K){return false;}},elCache:{},getEl:function(K){return(typeof K==="string")?document.getElementById(K):K;},clearCache:function(){},DOMReadyEvent:new YAHOO.util.CustomEvent("DOMReady",this),_load:function(L){if(!H){H=true;var K=YAHOO.util.Event;K._ready();K._tryPreloadAttach();}},_ready:function(L){var K=YAHOO.util.Event;if(!K.DOMReady){K.DOMReady=true;K.DOMReadyEvent.fire();K._simpleRemove(document,"DOMContentLoaded",K._ready);}},_tryPreloadAttach:function(){if(F.length===0){C=0;clearInterval(this._interval);this._interval=null;return ;}if(this.locked){return ;}if(this.isIE){if(!this.DOMReady){this.startInterval();return ;}}this.locked=true;var Q=!H;if(!Q){Q=(C>0&&F.length>0);}var P=[];var R=function(T,U){var S=T;if(U.override){if(U.override===true){S=U.obj;}else{S=U.override;}}U.fn.call(S,U.obj);};var L,K,O,N,M=[];for(L=0,K=F.length;L<K;L=L+1){O=F[L];if(O){N=this.getEl(O.id);if(N){if(O.checkReady){if(H||N.nextSibling||!Q){M.push(O);F[L]=null;}}else{R(N,O);F[L]=null;}}else{P.push(O);}}}for(L=0,K=M.length;L<K;L=L+1){O=M[L];R(this.getEl(O.id),O);}C--;if(Q){for(L=F.length-1;L>-1;L--){O=F[L];if(!O||!O.id){F.splice(L,1);}}this.startInterval();}else{clearInterval(this._interval);this._interval=null;}this.locked=false;},purgeElement:function(O,P,R){var M=(YAHOO.lang.isString(O))?this.getEl(O):O;var Q=this.getListeners(M,R),N,K;if(Q){for(N=Q.length-1;N>-1;N--){var L=Q[N];this.removeListener(M,L.type,L.fn);}}if(P&&M&&M.childNodes){for(N=0,K=M.childNodes.length;N<K;++N){this.purgeElement(M.childNodes[N],P,R);}}},getListeners:function(M,K){var P=[],L;if(!K){L=[I,J];}else{if(K==="unload"){L=[J];}else{L=[I];}}var R=(YAHOO.lang.isString(M))?this.getEl(M):M;for(var O=0;O<L.length;O=O+1){var T=L[O];if(T){for(var Q=0,S=T.length;Q<S;++Q){var N=T[Q];if(N&&N[this.EL]===R&&(!K||K===N[this.TYPE])){P.push({type:N[this.TYPE],fn:N[this.FN],obj:N[this.OBJ],adjust:N[this.OVERRIDE],scope:N[this.ADJ_SCOPE],index:Q});}}}}return(P.length)?P:null;},_unload:function(Q){var K=YAHOO.util.Event,N,M,L,P,O,R=J.slice();for(N=0,P=J.length;N<P;++N){L=R[N];if(L){var S=window;if(L[K.ADJ_SCOPE]){if(L[K.ADJ_SCOPE]===true){S=L[K.UNLOAD_OBJ];}else{S=L[K.ADJ_SCOPE];}}L[K.FN].call(S,K.getEvent(Q,L[K.EL]),L[K.UNLOAD_OBJ]);R[N]=null;L=null;S=null;}}J=null;if(I){for(M=I.length-1;M>-1;M--){L=I[M];if(L){K.removeListener(L[K.EL],L[K.TYPE],L[K.FN],M);}}L=null;}G=null;K._simpleRemove(window,"unload",K._unload);},_getScrollLeft:function(){return this._getScroll()[1];},_getScrollTop:function(){return this._getScroll()[0];},_getScroll:function(){var K=document.documentElement,L=document.body;if(K&&(K.scrollTop||K.scrollLeft)){return[K.scrollTop,K.scrollLeft];}else{if(L){return[L.scrollTop,L.scrollLeft];}else{return[0,0];}}},regCE:function(){},_simpleAdd:function(){if(window.addEventListener){return function(M,N,L,K){M.addEventListener(N,L,(K));};}else{if(window.attachEvent){return function(M,N,L,K){M.attachEvent("on"+N,L);};}else{return function(){};}}}(),_simpleRemove:function(){if(window.removeEventListener){return function(M,N,L,K){M.removeEventListener(N,L,(K));};}else{if(window.detachEvent){return function(L,M,K){L.detachEvent("on"+M,K);};}else{return function(){};}}}()};}();(function(){var EU=YAHOO.util.Event;EU.on=EU.addListener;
/* DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller */
if(EU.isIE){YAHOO.util.Event.onDOMReady(YAHOO.util.Event._tryPreloadAttach,YAHOO.util.Event,true);var n=document.createElement("p");EU._dri=setInterval(function(){try{n.doScroll("left");clearInterval(EU._dri);EU._dri=null;EU._ready();n=null;}catch(ex){}},EU.POLL_INTERVAL);}else{if(EU.webkit&&EU.webkit<525){EU._dri=setInterval(function(){var rs=document.readyState;if("loaded"==rs||"complete"==rs){clearInterval(EU._dri);EU._dri=null;EU._ready();}},EU.POLL_INTERVAL);}else{EU._simpleAdd(document,"DOMContentLoaded",EU._ready);}}EU._simpleAdd(window,"load",EU._load);EU._simpleAdd(window,"unload",EU._unload);EU._tryPreloadAttach();})();}YAHOO.util.EventProvider=function(){};YAHOO.util.EventProvider.prototype={__yui_events:null,__yui_subscribers:null,subscribe:function(A,C,F,E){this.__yui_events=this.__yui_events||{};var D=this.__yui_events[A];if(D){D.subscribe(C,F,E);}else{this.__yui_subscribers=this.__yui_subscribers||{};var B=this.__yui_subscribers;if(!B[A]){B[A]=[];}B[A].push({fn:C,obj:F,override:E});}},unsubscribe:function(C,E,G){this.__yui_events=this.__yui_events||{};var A=this.__yui_events;if(C){var F=A[C];if(F){return F.unsubscribe(E,G);}}else{var B=true;for(var D in A){if(YAHOO.lang.hasOwnProperty(A,D)){B=B&&A[D].unsubscribe(E,G);}}return B;}return false;},unsubscribeAll:function(A){return this.unsubscribe(A);},createEvent:function(G,D){this.__yui_events=this.__yui_events||{};var A=D||{};var I=this.__yui_events;
if(I[G]){}else{var H=A.scope||this;var E=(A.silent);var B=new YAHOO.util.CustomEvent(G,H,E,YAHOO.util.CustomEvent.FLAT);I[G]=B;if(A.onSubscribeCallback){B.subscribeEvent.subscribe(A.onSubscribeCallback);}this.__yui_subscribers=this.__yui_subscribers||{};var F=this.__yui_subscribers[G];if(F){for(var C=0;C<F.length;++C){B.subscribe(F[C].fn,F[C].obj,F[C].override);}}}return I[G];},fireEvent:function(E,D,A,C){this.__yui_events=this.__yui_events||{};var G=this.__yui_events[E];if(!G){return null;}var B=[];for(var F=1;F<arguments.length;++F){B.push(arguments[F]);}return G.fire.apply(G,B);},hasEvent:function(A){if(this.__yui_events){if(this.__yui_events[A]){return true;}}return false;}};YAHOO.util.KeyListener=function(A,F,B,C){if(!A){}else{if(!F){}else{if(!B){}}}if(!C){C=YAHOO.util.KeyListener.KEYDOWN;}var D=new YAHOO.util.CustomEvent("keyPressed");this.enabledEvent=new YAHOO.util.CustomEvent("enabled");this.disabledEvent=new YAHOO.util.CustomEvent("disabled");if(typeof A=="string"){A=document.getElementById(A);}if(typeof B=="function"){D.subscribe(B);}else{D.subscribe(B.fn,B.scope,B.correctScope);}function E(J,I){if(!F.shift){F.shift=false;}if(!F.alt){F.alt=false;}if(!F.ctrl){F.ctrl=false;}if(J.shiftKey==F.shift&&J.altKey==F.alt&&J.ctrlKey==F.ctrl){var G;if(F.keys instanceof Array){for(var H=0;H<F.keys.length;H++){G=F.keys[H];if(G==J.charCode){D.fire(J.charCode,J);break;}else{if(G==J.keyCode){D.fire(J.keyCode,J);break;}}}}else{G=F.keys;if(G==J.charCode){D.fire(J.charCode,J);}else{if(G==J.keyCode){D.fire(J.keyCode,J);}}}}}this.enable=function(){if(!this.enabled){YAHOO.util.Event.addListener(A,C,E);this.enabledEvent.fire(F);}this.enabled=true;};this.disable=function(){if(this.enabled){YAHOO.util.Event.removeListener(A,C,E);this.disabledEvent.fire(F);}this.enabled=false;};this.toString=function(){return"KeyListener ["+F.keys+"] "+A.tagName+(A.id?"["+A.id+"]":"");};};YAHOO.util.KeyListener.KEYDOWN="keydown";YAHOO.util.KeyListener.KEYUP="keyup";YAHOO.util.KeyListener.KEY={ALT:18,BACK_SPACE:8,CAPS_LOCK:20,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,META:224,NUM_LOCK:144,PAGE_DOWN:34,PAGE_UP:33,PAUSE:19,PRINTSCREEN:44,RIGHT:39,SCROLL_LOCK:145,SHIFT:16,SPACE:32,TAB:9,UP:38};YAHOO.register("event",YAHOO.util.Event,{version:"2.5.2",build:"1076"});YAHOO.register("yahoo-dom-event", YAHOO, {version: "2.5.2", build: "1076"});
/*
Copyright (c) 2008, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.5.2
*/
/**
 * The Browser History Manager provides the ability to use the back/forward
 * navigation buttons in a DHTML application. It also allows a DHTML
 * application to be bookmarked in a specific state.
 *
 * This library requires the following static markup:
 *
 * &lt;iframe id="yui-history-iframe" src="path-to-real-asset-in-same-domain"&gt;&lt;/iframe&gt;
 * &lt;input id="yui-history-field" type="hidden"&gt;
 *
 * @module history
 * @requires yahoo,event
 * @namespace YAHOO.util
 * @title Browser History Manager
 */

/**
 * The History class provides the ability to use the back/forward navigation
 * buttons in a DHTML application. It also allows a DHTML application to
 * be bookmarked in a specific state.
 *
 * @class History
 * @constructor
 */
YAHOO.util.History = (function () {

    /**
     * Our hidden IFrame used to store the browsing history.
     *
     * @property _histFrame
     * @type HTMLIFrameElement
     * @default null
     * @private
     */
    var _histFrame = null;

    /**
     * INPUT field (with type="hidden" or type="text") or TEXTAREA.
     * This field keeps the value of the initial state, current state
     * the list of all states across pages within a single browser session.
     *
     * @property _stateField
     * @type HTMLInputElement|HTMLTextAreaElement
     * @default null
     * @private
     */
    var _stateField = null;

    /**
     * Flag used to tell whether YAHOO.util.History.initialize has been called.
     *
     * @property _initialized
     * @type boolean
     * @default false
     * @private
     */
    var _initialized = false;

    /**
     * List of registered modules.
     *
     * @property _modules
     * @type array
     * @default []
     * @private
     */
    var _modules = [];

    /**
     * List of fully qualified states. This is used only by Safari.
     *
     * @property _fqstates
     * @type array
     * @default []
     * @private
     */
    var _fqstates = [];

    /**
     * location.hash is a bit buggy on Opera. I have seen instances where
     * navigating the history using the back/forward buttons, and hence
     * changing the URL, would not change location.hash. That's ok, the
     * implementation of an equivalent is trivial.
     *
     * @method _getHash
     * @return {string} The hash portion of the document's location
     * @private
     */
    function _getHash() {
        var i, href;
        href = top.location.href;
        i = href.indexOf("#");
        return i >= 0 ? href.substr(i + 1) : null;
    }

    /**
     * Stores all the registered modules' initial state and current state.
     * On Safari, we also store all the fully qualified states visited by
     * the application within a single browser session. The storage takes
     * place in the form field specified during initialization.
     *
     * @method _storeStates
     * @private
     */
    function _storeStates() {

        var moduleName, moduleObj, initialStates = [], currentStates = [];

        for (moduleName in _modules) {
            if (YAHOO.lang.hasOwnProperty(_modules, moduleName)) {
                moduleObj = _modules[moduleName];
                initialStates.push(moduleName + "=" + moduleObj.initialState);
                currentStates.push(moduleName + "=" + moduleObj.currentState);
            }
        }

        _stateField.value = initialStates.join("&") + "|" + currentStates.join("&");

        if (YAHOO.env.ua.webkit) {
            _stateField.value += "|" + _fqstates.join(",");
        }
    }

    /**
     * Sets the new currentState attribute of all modules depending on the new
     * fully qualified state. Also notifies the modules which current state has
     * changed.
     *
     * @method _handleFQStateChange
     * @param {string} fqstate Fully qualified state
     * @private
     */
    function _handleFQStateChange(fqstate) {

        var i, len, moduleName, moduleObj, modules, states, tokens, currentState;

        if (!fqstate) {
            // Notifies all modules
            for (moduleName in _modules) {
                if (YAHOO.lang.hasOwnProperty(_modules, moduleName)) {
                    moduleObj = _modules[moduleName];
                    moduleObj.currentState = moduleObj.initialState;
                    moduleObj.onStateChange(unescape(moduleObj.currentState));
                }
            }
            return;
        }

        modules = [];
        states = fqstate.split("&");
        for (i = 0, len = states.length; i < len; i++) {
            tokens = states[i].split("=");
            if (tokens.length === 2) {
                moduleName = tokens[0];
                currentState = tokens[1];
                modules[moduleName] = currentState;
            }
        }

        for (moduleName in _modules) {
            if (YAHOO.lang.hasOwnProperty(_modules, moduleName)) {
                moduleObj = _modules[moduleName];
                currentState = modules[moduleName];
                if (!currentState || moduleObj.currentState !== currentState) {
                    moduleObj.currentState = currentState || moduleObj.initialState;
                    moduleObj.onStateChange(unescape(moduleObj.currentState));
                }
            }
        }
    }

    /**
     * Update the IFrame with our new state.
     *
     * @method _updateIFrame
     * @private
     * @return {boolean} true if successful. false otherwise.
     */
    function _updateIFrame (fqstate) {

        var html, doc;

        html = '<html><body><div id="state">' + fqstate + '</div></body></html>';

        try {
            doc = _histFrame.contentWindow.document;
            doc.open();
            doc.write(html);
            doc.close();
            return true;
        } catch (e) {
            return false;
        }
    }

    /**
     * Periodically checks whether our internal IFrame is ready to be used.
     *
     * @method _checkIframeLoaded
     * @private
     */
    function _checkIframeLoaded() {

        var doc, elem, fqstate, hash;

        if (!_histFrame.contentWindow || !_histFrame.contentWindow.document) {
            // Check again in 10 msec...
            setTimeout(_checkIframeLoaded, 10);
            return;
        }

        // Start the thread that will have the responsibility to
        // periodically check whether a navigate operation has been
        // requested on the main window. This will happen when
        // YAHOO.util.History.navigate has been called or after
        // the user has hit the back/forward button.

        doc = _histFrame.contentWindow.document;
        elem = doc.getElementById("state");
        // We must use innerText, and not innerHTML because our string contains
        // the "&" character (which would end up being escaped as "&amp;") and
        // the string comparison would fail...
        fqstate = elem ? elem.innerText : null;

        hash = _getHash();

        setInterval(function () {

            var newfqstate, states, moduleName, moduleObj, newHash, historyLength;

            doc = _histFrame.contentWindow.document;
            elem = doc.getElementById("state");
            // See my comment above about using innerText instead of innerHTML...
            newfqstate = elem ? elem.innerText : null;

            newHash = _getHash();

            if (newfqstate !== fqstate) {

                fqstate = newfqstate;
                _handleFQStateChange(fqstate);

                if (!fqstate) {
                    states = [];
                    for (moduleName in _modules) {
                        if (YAHOO.lang.hasOwnProperty(_modules, moduleName)) {
                            moduleObj = _modules[moduleName];
                            states.push(moduleName + "=" + moduleObj.initialState);
                        }
                    }
                    newHash = states.join("&");
                } else {
                    newHash = fqstate;
                }

                // Allow the state to be bookmarked by setting the top window's
                // URL fragment identifier. Note that here, we are on IE, and
                // IE does not touch the browser history when setting the hash
                // (unlike all the other browsers). I used to write:
                //     top.location.replace( "#" + hash );
                // but this had a side effect when the page was not the top frame.
                top.location.hash = newHash;
                hash = newHash;

                _storeStates();

            } else if (newHash !== hash) {

                // The hash has changed. The user might have clicked on a link,
                // or modified the URL directly, or opened the same application
                // bookmarked in a specific state using a bookmark. However, we
                // know the hash change was not caused by a hit on the back or
                // forward buttons, or by a call to navigate() (because it would
                // have been handled above) We must handle these cases, which is
                // why we also need to keep track of hash changes on IE!

                // Note that IE6 has some major issues with this kind of user
                // interaction (the history stack gets completely messed up)
                // but it seems to work fine on IE7.

                hash = newHash;

                // Now, store a new history entry. The following will cause the
                // code above to execute, doing all the dirty work for us...
                _updateIFrame(newHash);
            }

        }, 50);

        _initialized = true;
        YAHOO.util.History.onLoadEvent.fire();
    }

    /**
     * Finish up the initialization of the Browser History Manager.
     *
     * @method _initialize
     * @private
     */
    function _initialize() {

        var i, len, parts, tokens, moduleName, moduleObj, initialStates, initialState, currentStates, currentState, counter, hash;

        // Decode the content of our storage field...
        parts = _stateField.value.split("|");

        if (parts.length > 1) {

            initialStates = parts[0].split("&");
            for (i = 0, len = initialStates.length; i < len; i++) {
                tokens = initialStates[i].split("=");
                if (tokens.length === 2) {
                    moduleName = tokens[0];
                    initialState = tokens[1];
                    moduleObj = _modules[moduleName];
                    if (moduleObj) {
                        moduleObj.initialState = initialState;
                    }
                }
            }

            currentStates = parts[1].split("&");
            for (i = 0, len = currentStates.length; i < len; i++) {
                tokens = currentStates[i].split("=");
                if (tokens.length >= 2) {
                    moduleName = tokens[0];
                    currentState = tokens[1];
                    moduleObj = _modules[moduleName];
                    if (moduleObj) {
                        moduleObj.currentState = currentState;
                    }
                }
            }
        }

        if (parts.length > 2) {
            _fqstates = parts[2].split(",");
        }

        if (YAHOO.env.ua.ie) {

            _checkIframeLoaded();

        } else {

            // Start the thread that will have the responsibility to
            // periodically check whether a navigate operation has been
            // requested on the main window. This will happen when
            // YAHOO.util.History.navigate has been called or after
            // the user has hit the back/forward button.

            // On Safari 1.x and 2.0, the only way to catch a back/forward
            // operation is to watch history.length... We basically exploit
            // what I consider to be a bug (history.length is not supposed
            // to change when going back/forward in the history...) This is
            // why, in the following thread, we first compare the hash,
            // because the hash thing will be fixed in the next major
            // version of Safari. So even if they fix the history.length
            // bug, all this will still work!
            counter = history.length;

            // On Gecko and Opera, we just need to watch the hash...
            hash = _getHash();

            setInterval(function () {

                var state, newHash, newCounter;

                newHash = _getHash();
                newCounter = history.length;
                if (newHash !== hash) {
                    hash = newHash;
                    counter = newCounter;
                    _handleFQStateChange(hash);
                    _storeStates();
                } else if (newCounter !== counter && YAHOO.env.ua.webkit) {
                    hash = newHash;
                    counter = newCounter;
                    state = _fqstates[counter - 1];
                    _handleFQStateChange(state);
                    _storeStates();
                }

            }, 50);

            _initialized = true;
            YAHOO.util.History.onLoadEvent.fire();
        }
    }

    return {

        /**
         * Fired when the Browser History Manager is ready. If you subscribe to
         * this event after the Browser History Manager has been initialized,
         * it will not fire. Therefore, it is recommended to use the onReady
         * method instead.
         *
         * @event onLoadEvent
         * @see onReady
         */
        onLoadEvent: new YAHOO.util.CustomEvent("onLoad"),

        /**
         * Executes the supplied callback when the Browser History Manager is
         * ready. This will execute immediately if called after the Browser
         * History Manager onLoad event has fired.
         *
         * @method onReady
         * @param {function} fn what to execute when the Browser History Manager is ready.
         * @param {object} obj an optional object to be passed back as a parameter to fn.
         * @param {boolean|object} override If true, the obj passed in becomes fn's execution scope.
         * @see onLoadEvent
         */
        onReady: function (fn, obj, override) {

            if (_initialized) {

                setTimeout(function () {
                    var ctx = window;
                    if (override) {
                        if (override === true) {
                            ctx = obj;
                        } else {
                            ctx = override;
                        }
                    }
                    fn.call(ctx, "onLoad", [], obj);
                }, 0);

            } else {

                YAHOO.util.History.onLoadEvent.subscribe(fn, obj, override);

            }
        },

        /**
         * Registers a new module.
         *
         * @method register
         * @param {string} module Non-empty string uniquely identifying the
         *     module you wish to register.
         * @param {string} initialState The initial state of the specified
         *     module corresponding to its earliest history entry.
         * @param {function} onStateChange Callback called when the
         *     state of the specified module has changed.
         * @param {object} obj An arbitrary object that will be passed as a
         *     parameter to the handler.
         * @param {boolean} override If true, the obj passed in becomes the
         *     execution scope of the listener.
         */
        register: function (module, initialState, onStateChange, obj, override) {

            var scope, wrappedFn;

            if (typeof module !== "string" || YAHOO.lang.trim(module) === "" ||
                typeof initialState !== "string" ||
                typeof onStateChange !== "function") {
                throw new Error("Missing or invalid argument");
            }

            if (_modules[module]) {
                // Here, we used to throw an exception. However, users have
                // complained about this behavior, so we now just return.
                return;
            }

            // Note: A module CANNOT be registered after calling
            // YAHOO.util.History.initialize. Indeed, we set the initial state
            // of each registered module in YAHOO.util.History.initialize.
            // If you could register a module after initializing the Browser
            // History Manager, you would not read the correct state using
            // YAHOO.util.History.getCurrentState when coming back to the
            // page using the back button.
            if (_initialized) {
                throw new Error("All modules must be registered before calling YAHOO.util.History.initialize");
            }

            // Make sure the strings passed in do not contain our separators "," and "|"
            module = escape(module);
            initialState = escape(initialState);

            // If the user chooses to override the scope, we use the
            // custom object passed in as the execution scope.
            scope = null;
            if (override === true) {
                scope = obj;
            } else {
                scope = override;
            }

            wrappedFn = function (state) {
                return onStateChange.call(scope, state, obj);
            };

            _modules[module] = {
                name: module,
                initialState: initialState,
                currentState: initialState,
                onStateChange: wrappedFn
            };
        },

        /**
         * Initializes the Browser History Manager. Call this method
         * from a script block located right after the opening body tag.
         *
         * @method initialize
         * @param {string|HTML Element} stateField <input type="hidden"> used
         *     to store application states. Must be in the static markup.
         * @param {string|HTML Element} histFrame IFrame used to store
         *     the history (only required on Internet Explorer)
         * @public
         */
        initialize: function (stateField, histFrame) {

            if (_initialized) {
                // The browser history manager has already been initialized.
                return;
            }

            if (YAHOO.env.ua.opera) {
                // Opera cannot be supported because of several problems that
                // have been reported to the Opera team, but never addressed:
                //   1) Hash changes are not detected (started happening with
                //      recent versions of Opera)
                //   2) The entire DOM gets cached, so when you come back to
                //      a page, the window's onload event does not get fired,
                //      which prevents us from initializing the browser history
                //      manager.
                // As a consequence, the best thing we can do is to throw an
                // exception. The application should catch it, and degrade
                // gracefully. This is the sad state of history management.
            }

            if (typeof stateField === "string") {
                stateField = document.getElementById(stateField);
            }

            if (!stateField ||
                stateField.tagName.toUpperCase() !== "TEXTAREA" &&
                (stateField.tagName.toUpperCase() !== "INPUT" ||
                 stateField.type !== "hidden" &&
                 stateField.type !== "text")) {
                throw new Error("Missing or invalid argument");
            }

            _stateField = stateField;

            if (YAHOO.env.ua.ie) {

                if (typeof histFrame === "string") {
                    histFrame = document.getElementById(histFrame);
                }

                if (!histFrame || histFrame.tagName.toUpperCase() !== "IFRAME") {
                    throw new Error("Missing or invalid argument");
                }

                _histFrame = histFrame;
            }

            // Note that the event utility MUST be included inline in the page.
            // If it gets loaded later (which you may want to do to improve the
            // loading speed of your site), the onDOMReady event never fires,
            // and the history library never gets fully initialized.
            YAHOO.util.Event.onDOMReady(_initialize);
        },

        /**
         * Call this method when you want to store a new entry in the browser's history.
         *
         * @method navigate
         * @param {string} module Non-empty string representing your module.
         * @param {string} state String representing the new state of the specified module.
         * @return {boolean} Indicates whether the new state was successfully added to the history.
         * @public
         */
        navigate: function (module, state) {

            var states;

            if (typeof module !== "string" || typeof state !== "string") {
                throw new Error("Missing or invalid argument");
            }

            states = {};
            states[module] = state;

            return YAHOO.util.History.multiNavigate(states);
        },

        /**
         * Call this method when you want to store a new entry in the browser's history.
         *
         * @method multiNavigate
         * @param {object} states Associative array of module-state pairs to set simultaneously.
         * @return {boolean} Indicates whether the new state was successfully added to the history.
         * @public
         */
        multiNavigate: function (states) {

            var currentStates, moduleName, moduleObj, currentState, fqstate;

            if (typeof states !== "object") {
                throw new Error("Missing or invalid argument");
            }

            if (!_initialized) {
                throw new Error("The Browser History Manager is not initialized");
            }

            for (moduleName in states) {
                if (!_modules[moduleName]) {
                    throw new Error("The following module has not been registered: " + moduleName);
                }
            }

            // Generate our new full state string mod1=xxx&mod2=yyy
            currentStates = [];

            for (moduleName in _modules) {
                if (YAHOO.lang.hasOwnProperty(_modules, moduleName)) {
                    moduleObj = _modules[moduleName];
                    if (YAHOO.lang.hasOwnProperty(states, moduleName)) {
                        currentState = states[unescape(moduleName)];
                    } else {
                        currentState = unescape(moduleObj.currentState);
                    }

                    // Make sure the strings passed in do not contain our separators "," and "|"
                    moduleName = escape(moduleName);
                    currentState = escape(currentState);

                    currentStates.push(moduleName + "=" + currentState);
                }
            }

            fqstate = currentStates.join("&");

            if (YAHOO.env.ua.ie) {

                return _updateIFrame(fqstate);

            } else {

                // Known bug: On Safari 1.x and 2.0, if you have tab browsing
                // enabled, Safari will show an endless loading icon in the
                // tab. This has apparently been fixed in recent WebKit builds.
                // One work around found by Dav Glass is to submit a form that
                // points to the same document. This indeed works on Safari 1.x
                // and 2.0 but creates bigger problems on WebKit. So for now,
                // we'll consider this an acceptable bug, and hope that Apple
                // comes out with their next version of Safari very soon.
                top.location.hash = fqstate;
                if (YAHOO.env.ua.webkit) {
                    // The following two lines are only useful for Safari 1.x
                    // and 2.0. Recent nightly builds of WebKit do not require
                    // that, but unfortunately, it is not easy to differentiate
                    // between the two. Once Safari 2.0 departs the A-grade
                    // list, we can remove the following two lines...
                    _fqstates[history.length] = fqstate;
                    _storeStates();
                }

                return true;

            }
        },

        /**
         * Returns the current state of the specified module.
         *
         * @method getCurrentState
         * @param {string} module Non-empty string representing your module.
         * @return {string} The current state of the specified module.
         * @public
         */
        getCurrentState: function (module) {

            var moduleObj;

            if (typeof module !== "string") {
                throw new Error("Missing or invalid argument");
            }

            if (!_initialized) {
                throw new Error("The Browser History Manager is not initialized");
            }

            moduleObj = _modules[module];
            if (!moduleObj) {
                throw new Error("No such registered module: " + module);
            }

            return unescape(moduleObj.currentState);
        },

        /**
         * Returns the state of a module according to the URL fragment
         * identifier. This method is useful to initialize your modules
         * if your application was bookmarked from a particular state.
         *
         * @method getBookmarkedState
         * @param {string} module Non-empty string representing your module.
         * @return {string} The bookmarked state of the specified module.
         * @public
         */
        getBookmarkedState: function (module) {

            var i, len, idx, hash, states, tokens, moduleName;

            if (typeof module !== "string") {
                throw new Error("Missing or invalid argument");
            }

            // Use location.href instead of location.hash which is already
            // URL-decoded, which creates problems if the state value
            // contained special characters...
            idx = top.location.href.indexOf("#");
            hash = idx >= 0 ? top.location.href.substr(idx + 1) : top.location.href;

            states = hash.split("&");
            for (i = 0, len = states.length; i < len; i++) {
                tokens = states[i].split("=");
                if (tokens.length === 2) {
                    moduleName = tokens[0];
                    if (moduleName === module) {
                        return unescape(tokens[1]);
                    }
                }
            }

            return null;
        },

        /**
         * Returns the value of the specified query string parameter.
         * This method is not used internally by the Browser History Manager.
         * However, it is provided here as a helper since many applications
         * using the Browser History Manager will want to read the value of
         * url parameters to initialize themselves.
         *
         * @method getQueryStringParameter
         * @param {string} paramName Name of the parameter we want to look up.
         * @param {string} queryString Optional URL to look at. If not specified,
         *     this method uses the URL in the address bar.
         * @return {string} The value of the specified parameter, or null.
         * @public
         */
        getQueryStringParameter: function (paramName, url) {

            var i, len, idx, queryString, params, tokens;

            url = url || top.location.href;

            idx = url.indexOf("?");
            queryString = idx >= 0 ? url.substr(idx + 1) : url;

            // Remove the hash if any
            idx = queryString.lastIndexOf("#");
            queryString = idx >= 0 ? queryString.substr(0, idx) : queryString;

            params = queryString.split("&");

            for (i = 0, len = params.length; i < len; i++) {
                tokens = params[i].split("=");
                if (tokens.length >= 2) {
                    if (tokens[0] === paramName) {
                        return unescape(tokens[1]);
                    }
                }
            }

            return null;
        }

    };

})();
YAHOO.register("history", YAHOO.util.History, {version: "2.5.2", build: "1076"});
// many of global vars are set in ajaxhandlers/ajax_searchpage.html

var area, fmstartnumber, grange, optimizemenu, overflowtype, pixperpage, resized, showcaptionview, showphotographer, showfilesize, showrelease, viewmode, winH;        // must be here for backward-compaibility.
var Builder, color, date, MACIE5, method, orient, pagetype, q_args, q_id, scriptname, searchinclude, sort, spec_idx, ucats, vcdbrowse, feat_requestview, mobject_id, similar_to, ukeys, dsplkys;

var global = new Object();
var phrase = new Object();

var afInitObj = new afInit();
var afDateObj = new afDate();   // needed for globally accessible functions backwards compatible.
var afCookieObj = new afCookie();  // needed for globally accessible functions backwards compatible.
var afCartObj = new afCart();
var afLightboxObj = new afLightbox();
var afImageObj = new afImage();
var afHTMLObj = new afHTML();
var afURLObj = new afURL();
var afMouseObj = new afMouse();
var afPreviewObj = new afPreview();
var afSearchObj = new afSearch();
var afSystemObj = new afSystem();
var afLegalObj = new afLegal();
var afInfoObj = new afInfo();
var afWindowObj = new afWindow();
var afDispatchObj = new afDispatch();
var afPageObj = new afPage();
var afReleaseObj = new afRelease();
var afShareObj = new afShare();
var afLoginObj = new afLogin();



//-- [ globally accessible functions ] ---

gfixDate = afDateObj.fixDate; 
setCurrentTime = afDateObj.setCurrentTime;  // not sure this is needed, but added it to be safe.

_handleNonSearch = afURLObj.createNextLink;

make_share_control_string = afShareObj.makeShareControlString;
switch_share_control = afShareObj.toggleShareControlCookie;
share_set_page = afShareObj.shareSetPage;
EAD = afShareObj.checkID;
sos = afShareObj.saveShares;
sor = afShareObj.saveReleaseControl;
validaterad = afShareObj.validateRadioButtons;

gsetCookie = afCookieObj.setCookie;
gsetCookie2 = afCookieObj.setCookie2;
ggetCookie = afCookieObj.getCookie;
gGetCookieDom = afCookieObj.getCookieDomain;
gdeleteCookie = afCookieObj.deleteCookie;
gwhichindex = afCookieObj.setCookieGwhichindex;
greleasedselect = afCookieObj.setCookieGreleasedselect;

cart_addto = afCartObj.addToCart;
cart_build = afCartObj.buildCart;
cart_build_act = afCartObj.cart_build_act;
cart_check_act = afCartObj.cart_check_act;
cart_delete_license = afCartObj.deleteLicenseFromCart;
cart_delete_image = afCartObj.deleteImageFromCart;
cart_display = afCartObj.displayCart;
cart_mod_act = afCartObj.cart_mod_act;
cart_reprice = afCartObj.repriceImagesInCart;
cart_away = afCartObj.awayCart;
cart_check = afCartObj.checkCart;
dispatchCart_display = afCartObj.displayDispatchedCart;
topcartrefresh = afCartObj.refreshTopCart;

lightbox_add2cart = afLightboxObj.addLightboxToCart;
lightbox_addto = afLightboxObj.addImageToLightbox;
lightbox_build = afLightboxObj.buildLightbox;
lightbox_new = afLightboxObj.newLightbox;
lightbox_new_send = afLightboxObj.registerLightbox;
lightbox_email = afLightboxObj.emailConfirmation;
lightbox_email_send = afLightboxObj.emailLightbox;
lightbox_list = afLightboxObj.listLightbox;
lightbox_mod_act = afLightboxObj.lightbox_mod_act;
lightbox_delete = afLightboxObj.deleteLightbox;
lightbox_delete_image_enl = afLightboxObj.deleteLightboxFromEnlargeView;
lightbox_delete_image = afLightboxObj.deleteImageFromLightbox;
lightbox_rename = afLightboxObj.renameLightbox;
lightbox_rename_send = afLightboxObj.registerLightboxRename;
lightbox_change = afLightboxObj.changeLightbox;
make_lightbox_string = afLightboxObj.makeLightboxString;
polllb = afLightboxObj.saveLightbox;
showhideLB = afLightboxObj.toggleLightbox;
simplemessage = afLightboxObj.simpleMessage;
test_valid_name = afLightboxObj.validateLightboxName;
toplightboxrefresh = afLightboxObj.refreshTopLightbox;
switchList = afLightboxObj.switchList;

buildimages = afImageObj.buildImages;
fitMeTo = afImageObj.sizeImageToContainer;
preloadnextimg = afImageObj.preloadNextImage;
price_image_act = afImageObj.price_image_act;
price_image = afImageObj.priceImage;
prloadimg = afImageObj.preLoadImage;
twidle_price_img = afImageObj.twidleImagePrice;
twidle_price_img_delay = afImageObj.twidlePriceImagedelay;

buildpages = afHTMLObj.buildPagination;
center_panel = afHTMLObj.centerPanel;
coveroff = afHTMLObj.hideCoverLayer;
createCoverLayer = afHTMLObj.createCoverLayer;
createDisplayPanel = afHTMLObj.createDisplayPanel;
dispatchBuildimages = afHTMLObj.dispatchBuildImages;
divshim = afHTMLObj.divShim;
hidedisplaypanel = afHTMLObj.hideDisplayPanel;
html_share_con_opts = afHTMLObj.html_share_con_opts;
html_weight_con_opts = afHTMLObj.html_weight_con_opts;
html_combined_con_opts = afHTMLObj.html_combined_con_opts;

htmlit = afHTMLObj.imageProfile;
init_share_radios = afHTMLObj.initShareRadios;
displaypanelshow = afHTMLObj.showDisplayPanel;
footer = afHTMLObj.getFooter;

mouseSnap = afMouseObj.mouseSnap;
pfindmouse = afMouseObj.findMouse;
getMouseXY = afMouseObj.getMouseCoordinates;

hp = afPreviewObj.hp;
hpoff = afPreviewObj.hpoff;
portSize = afPreviewObj.portSize;
previewset = afPreviewObj.previewSet; // variable has s in lowercase for backword capatibility
sp = afPreviewObj.sp;
sp_act = afPreviewObj.sp_act;

checkIt = afSearchObj.checkIt;
expandit = afSearchObj.expandIt; // variable has i in lowercase for backward compatibility
g = afSearchObj.searchType;
g_standard = afSearchObj.standardSearch;
fsearchprefs = afSearchObj.searchPreferences;
narrowit = afSearchObj.narrowIt;  // variable has i in lowercase for backward compatibility
optimize = afSearchObj.optimizeSearch;
popkeys2 = afSearchObj.popKeywords;
writesearch = afSearchObj.writeSearch;                    // this might be more appropriately be put in afHTML
writesimilar = afSearchObj.writeSimilar;                  // this might be more appropriately be put in afHTML
writeStandardSearch = afSearchObj.writeStandardSearch;   // this might be more appropriately be put in afHTML
writesimilar_standard = afSearchObj.writeStandardSimilar; // this might be more appropriately be put in afHTML

hovercopyright = afLegalObj.copyrightNotice;
license = afLegalObj.licenseCostWindow;

enlarge2 = afInfoObj.enlarge2;
dispatchEnlarge2 = afInfoObj.dispatchEnlarge2;
enlarge2_act__generateTierRows = afInfoObj.enlarge2_act__generateTierRows;
enlarge2_act = afInfoObj.enlarge2_act;
MM_preloadImages = afInfoObj.preloadImages;
MM_setTextOfLayer = afInfoObj.setTextOfLayer;

launchwin = afWindowObj.popUp;
displayWindow = afWindowObj.displayWindow;
displayWindow2 = afWindowObj.displayWindow2;
maxscreen = afWindowObj.maximizeScreen;

dispatchAll = afDispatchObj.dispatchAll;
reDispatch = afDispatchObj.reDispatch;

checkpageresize = afPageObj.checkPageResize;
currentpage = afPageObj.currentPage;  //variable has p in lowercase for backward compatibility
gSetBackpage = afPageObj.setBackPage;
setuppagesize = afPageObj.setupPageSize;  //variable has p in lowercase for backward compatibility
nextpage = afPageObj.nextPage;
prevpage = afPageObj.previousPage;
preloadnextpage = afPageObj.preloadNextPage;

save_all_releases = afReleaseObj.saveAllReleases;
release_set_page = afReleaseObj.releaseSetPage;
validatechx = afReleaseObj.validateCheckboxes;
iconstatus = afReleaseObj.iconStatus;


debug = afSystemObj.debug;
debugon = afSystemObj.debugon;
debugoff = afSystemObj.debugoff;

getVars = afSystemObj.getVars;
nada = afSystemObj.empty;
tellme = afSystemObj.screenInfo;

var show_login = afLoginObj.showLogin;
var evaluate_login = afLoginObj.evaluateLogin;
var hide_login = afLoginObj.hideLogin; 


//---

afInitObj.init();            // this calls the init function that initializes all the global variables
                             // and further manipulates them. The end result is then re-assigned to  
                             // the old global variables for backwards compatibility. Eventually these
                             // variables below will gradually get extinct.

//alert('Going to re-assign globals...');
// we need to explicitly globalize some vars for backwards compatibility.
// again, these will eventually need to be phased out.

var MACIE5 = global.macIE5;                                    // MACIE5 used in dispatchBuildimages(); default value = 'false'
var q_args = global.qArgs;                                     // q_args used in init()
var searchinclude = global.searchInclude;                      // searchinclude used in _handleNonSearch()
var color = global.color;                                      // color used in _handleNonSearch()
var method = global.method;                                    // method used in _handleNonSearch()
var orient = global.orient;                                    // orient used in _handleNonSearch()
var sort = global.sort;                                        // sort used in _handleNonSearch()
var todaysDate = global.currentDate;                                 // date used in _handleNonSearch()
                                                           //   Note : all other instances of 'date' are localized in functions
var vcdbrowse = global.VCDBrowse;                              // VCDBrowse used in _handleNonSearch()
var spec_idx = global.specIdx;                                 // spec_idx used in: _handleNonSearch()
                                                           //                   optimize()
                                                           //                   narrowit()
var q_id = global.qID;                                         // q_id used in _handleNonSearch()
                                                           //              g_standard()
var scriptname = global.scriptName;                            // scriptname used in _handleNonSearch()

var nextlink;                                              // nextlink defined in _handleNonSearch()
                                                           //          used in: _handleNonSearch()
                                                           //                   enlarge2_act()
                                                           //                   buildpages()
                                                           //                   dispatchBuildimages()
                                                           //                   prevpage()
var narrowurl;                                             // narrowurl defined in _handleNonSearch()
                                                           //           used globally

ucats = global.uCats;
mobject_id = global.mobjectID;
similar_to = global.similarTo;
dsplkys = global.lightboxsphotog;

// end of backward compatibility

var firstpictureonpage = global.firstPicOnPage;
var snum = global.sNum;
var tset = global.tSet;
var showstartnumber_trap = global.showStartNumberTrap;
var currentlbname = global.currentLbName; 
var currentlblist = global.currentLbList;
var feat_requestview = global.featureRequestView;
var typeoflbaction = global.typeOfLbAction;
var sphotog = global.sphotog;
var pre_q_args = global.preQArgs;
var winW = global.winW;
var baseurl = global.baseURL;
var carnit = global.carnIt;
var currentLbdivMode = global.currentLbdivMode;

var gloCrop = global.gloCrop;
var currentLayer1Mode = global.currentLayer1Mode;

var cartview = global.cartView;
var enlargeview = global.enlargeView;
var viewmode = global.viewMode;

var lightbox_built = global.lightBoxBuilt;

var currMousedOverObj = global.currentMousedOverObject;
var suspendpreviews = global.suspendPreviews;
var scr = global.scr;

var d = global.currentDate;
var currentYear = global.currentYear;
var now = global.currentTime;
var bad = global.bad;

var agt = global.userAgent;
var yourOS = global.userOS;
var yourBrowse = global.userBrowser;

var ver5 = global.netscapeVersion5;

var dynimagesname = global.dynamicImagesName;
document.currentlbstash = '';
var lbexpansionspace= global.lbExpansionSpace;

var pmousedelta = global.pMouseDelta;

var loadImg = new Image();
loadImg.src = global.loadImage;

var detect = global.userAgentLowerCase;
var OS = global.userOSName;
var browser = global.userBrowserName;
var version = global.userBrowserVersion;

var total = global.total;
var thestring;

var getpost = global.getPost;

var pngsupport = global.pngSupport;

//checking for login status
var gsession = global.gSession;
var debugmode = global.gDebugMode;
var gusert = global.gUserT;
var gcartimages = global.gCartImages;
var gusername = global.gUserName;
var gcurrency = global.gCurrency;
var gfirstname = global.gFirstName;

//
//	NON SEARCH PAGES 
//

if (global.scriptName != ''){
 pixperpage= global.pixPerPage;

 //initialize some page variables
 grange= global.gRange;
 winH = global.winH;
 area = global.area;
 resized = global.resized;

 c=-1;
 fmstartnumber = global.fmStartNumber;

 overflowtype = global.overflowType;

 //optional configurations for this page varies from site to site
 optimizemenu = global.optimizeMenu;
 showphotographer = global.showPhotographer;
 showrelease = global.showRelease;
 showfilesize = global.showFileSize;
 showcaptionview = global.showCaptionView;

 var output = _handleNonSearch({color : color,
                                date : todaysDate,
                                enlargeview : enlargeview,
                                method : method,
                                orient : orient,
                                preQArgs : global.preQArgs,
                                q_args : global.qArgs,
                                qID : global.qID,
                                scriptName : global.scriptName,
                                searchInclude : global.searchInclude,
                                sort : global.sort,
                                specIdx : global.specIdx,
                                ucats : ucats,
                                VCDBrowse : global.VCDBrowse})
 nextlink = output['nextlink'];
 narrowurl = output['narrowurl'];

};

var tempW = global.winW;

if (global.featureRequestView)
{
 document.thisIsFeatureView = true;
};

var lbdisplaymode = global.lbDisplayMode;

var nodeTree = global.nodeTree;

		
//******************************* INTERNALS ****************************//


 function _globals() {

  var d = afDateObj.getCurrentDate();

  global = {
            firstPicOnPage : ( typeof(firstpictureonpage) != 'undefined' ? firstpictureonpage : 0 ),
            sNum : ( snum ? snum : 0 ),
            tSet : ( tset ? tset : 'on' ),
            showStartNumberTrap : 0,
            currentLbName : undefined,
            currentLbList : undefined,
            featureRequestView : feat_requestview,  // needs to be here because global var pre_q_args is set on ajax search page.
            typeOfLbAction : undefined,
            sphotog : sphotog,                      // needs to be here because global var pre_q_args is set on ajax search page.
            preQArgs : pre_q_args,                  // needs to be here because global var pre_q_args is set on ajax search page.
            qArgs : typeof(q_args) == 'undefined' ? undefined : q_args,
            baseURL : baseurl,                      // needs to be here because global var pre_q_args is set on ajax search page.
            carnIt : 1,                 //flag to do once on load for cartview
            gloCrop : '',
            currentLayer1Mode : document.currentLayer1Mode ? currentLayer1Mode : 'searchresults',
            currentLbdivMode : undefined,    //when flipping between lb and cart, set this
                                        //to say, "lightbox" or "cart" so that global refreshes in
                                        //subs like checkpageresize will know whether to draw
                                        //lb or cart or whatever else...
            cartView : (cartview ? cartview : ''),  //trip this flag to display cart in main window and draw cart in lightbox
            cartViewLocation : "/bin/Cklb?ref=/SwishSearch?cartview=1",
            enlargeView : (enlargeview ? enlargeview : ''),

            lightBoxBuilt : 0,          //basically this is a check so when polllb comes around, if lightBoxBuilt is 0
                                        //and we're logged in, try and build the box!
            currentMousedOverObject : undefined,
            suspendPreviews : 0,
            scr : '',
            currentDate : d,
            currentTime : d.getTime(),      // Normally it was: setCurrentTime(d),
            currentYear : d.getFullYear(),
            dynamicImagesName : (typeof(dynimagesname) == 'undefined' ? 'dyn_images' : dynimagesname),
            bad : undefined,
            userAgent : navigator.userAgent,
            userAgentLowerCase : navigator.userAgent.toLowerCase(),
            userOS : navigator.userAgent.indexOf("Mac")!=-1 ? 'Mac' : 'PC',
            userOSName : undefined,            //this gets populated by findOS()
            userBrowser : navigator.appName == 'Netscape' ? 'NS' : 'IE',
            userBrowserName : undefined,
            userBrowserVersion : undefined,
            netscapeVersion5 : navigator.appVersion.substr(22,1) >= "5" ? 'Yes' : '',
            lbExpansionSpace : 0,
            pMouseDelta : [20,-30],     //image x,y offsets from cursor position in pixels. Enter 0,0 for no offset
            loadImage : '/graphics/loading.png',
            pngSupport : 1,             //this also may get altered by the checkPNGsupport() function according to the browser.
            getPost : 'POST',           //had reports of IE caching ajax calls with a GET and firefox not able to complete fake POSTS, so..
                                        //this also may get altered by the checkPostGet() function according to the browser.
            gSession : ggetCookie("gmpsess"),
            debugMode : ggetCookie("debugmode"),
            gUserT : ggetCookie("usert"),
            gCartImages : ggetCookie("gcartimages"),
            gUserName : ggetCookie("username") || ggetCookie("gwhichuser"),
            gCurrency : ggetCookie("currency"),
            gFirstName : ggetCookie("firstname"),
            scriptName : typeof(scriptname) == 'undefined' ? undefined : scriptname,
            viewMode : (typeof(viewmode)!='undefined') ? viewmode : ((typeof(scriptname) !="undefined") ? ggetCookie('gviewmode') : ''),
            pixPerPage : (typeof(scriptname) !="undefined") ? 12 : pixperpage,
            gRange : (typeof(scriptname) !="undefined") ? "legal" : grange,
            winW : (typeof(scriptname) !="undefined") ? 700 : winW,
            winH : (typeof(scriptname) !="undefined") ? 460 : winH,
            area : (typeof(scriptname) !="undefined") ? 12 : area,
            resized : (typeof(scriptname) !="undefined") ? 0 : resized,
            fmStartNumber : (typeof(scriptname) !="undefined") ? 0 : fmstartnumber,
            overflowType : (typeof(scriptname) !="undefined") ? 'hidden' : overflowtype,
            macIE5 : ((navigator.userAgent.indexOf("Mac")!=-1) && (navigator.appName.indexOf("Microsoft")!=-1)) ? 'true' : 'false',
            optimizeMenu : (typeof(scriptname) !="undefined") ? 0 : optimizemenu,
            showPhotographer : (typeof(showphotographer) !="undefined") ? showphotographer : 1,
            showRelease : (typeof(scriptname) !="undefined") ? 1 : showrelease,
            showFileSize : (typeof(scriptname) !="undefined") ? 1 : showfilesize,
            showCaptionView : (typeof(scriptname) !="undefined") ? 1 : showcaptionview,
            pageType : typeof(pagetype)=='undefined' ? undefined : pagetype,
            lbDisplayMode : ggetCookie('ghidelightbox'),
            cartPic : '/graphics/cart_enabled_02.gif',
            searchInclude : searchinclude,
            builderClass : Builder,
            nodeTree : undefined,
            color : color,
            method : method,
            orient : orient,
            sort : sort,
            qID : q_id,
            specIdx : spec_idx,
            VCDBrowse : vcdbrowse,
            uCats : ucats,
            mobjectID : mobject_id,
            similarTo : similar_to,
            total : total,
            uKeys : ukeys,
            lightboxsphotog : dsplkys
           };
 };


/*************PHRASES******************************/
 function _phrase() {
	phrase = {
		cart_alert_imagealreadyincart					:'That image is already in your Cart'
	,	lightbox_adding_message					:'Adding image to Shopping Cart <blink>.</blink>'
	,	cart_removing_message					:'Removing License from Image<blink>.</blink>'
	,	cart_deleting_image_message				:'Deleting image from Shopping Cart <blink>.</blink>'
	,	cart_problems_alert						:'There are unlicensed images in your cart, or it is empty.  To license image(s) first click the \'specify usage and calculate fee\' link for each image in your cart and use the Rate calculator. Rates vary based on usage.'
	,	cart_delete_title						:'Remove this image from the cart'
	,	preview_loading_alt						:'Loading...'
	,	cart_tab_switch_to_lb_title				:'SWITCH TO YOUR LIGHTBOX'
	,	cart_view_cart_calc_fees_link			:'View Cart and Calculate Usage Fees'
	,	cart_checkout_link						:'Checkout'
	,	cart_hide_cart_link						:'[x] Hide Cart'
	,	lightbox_name_problem_alert				:'Lightbox names must be between 1 and 100 characters long.'
	,	lightbox_name_problem2_alert			:"Lightbox names may only contain letters, numbers, spaces, hyphens, and underscores."
	,	lightbox_sending_message				:'Sending your lightbox <blink>.</blink>'
	,	lightbox_sent_message					:'Lightbox Sent! <blink>.</blink>'
	,	lightbox_switch_to_cart_title			:'SWITCH TO YOUR CART'
	,	lightbox_change_to_text					:'Change to  '
	,	lightbox_name_suffix					:' Lightbox'
	,	lightbox_minimize_link					:'[+|-]'
	,	lbmenu_new								:'New Lightbox'
	,	lbmenu_expanded							:'View Expanded Lightbox'
	,	lbmenu_email							:'Email Lightbox'
	,	lbmenu_add2cart							:'Add Lightbox to Cart'
	,	lbmenu_delete							:'Delete Lightbox'
	,	lbmenu_rename							:'Rename Lightbox'
	,	lbmenu_makefeature						:'Make LB a Feature'
	,	lbmenu_copytouser						:'Copy LB to User'
	,	lbmenu_resort							:'Resort LB'
	,	lbmenu_new_s							:'New'
	,	lbmenu_expanded_s						:'View'
	,	lbmenu_email_s							:'Email'
	,	lbmenu_add2cart_s						:'Add LB to Cart'
	,	lbmenu_delete_s							:'Delete'
	,	lbmenu_rename_s							:'Rename'
	,	lbmenu_makefeature_s					:'Make Feature'
	,	lbmenu_copytouser_s						:'Copy to User'
	,	lbmenu_resort_s							:'Sort'
	,	lbstrip_enlarge_title					:'Enlarge this image'
	,	lbstrip_remove_image_from_lb_title		:'Remove this image from the lightbox'
	,	login_invalid_username					:'Invalid username. Please enter a valid username.'
	,	login_enter_password					:'Please enter your password'
	,	login_start_message_text				:'Login'
	,	login_success_message					:'Login Successful'
	,	login_error								:'communications error'
	,	phrase_title							:'Release: '
	,	search_enter_query_alert				:'You must first enter search criteria in the field next to the search button.'
	,	search_keyword_field_default_value		:'enter keywords'
	,	phrase_narrow_select_alert				:'please select an item from the list'
	,	enlarge_showkeys_link					:'Show keywords'
	,	enlarge_hidekeys_link					:'Hide keywords'
	,	shopping_cart_text						:'Shopping Cart'
	,	lbstrip_preview_image_from_lb_linktext	:'+'
	,	lbstrip_remove_image_from_lb_linktext	:'x'
	,	lbstrip_preview_image_from_cart_linktext:'+'
	,	lbstrip_remove_image_from_cart_linktext	:'x'
	

	}
}function afCart() {

 this.addToCart = addToCart;
 this.awayCart = awayCart;
 this.buildCart = buildCart;
 this.checkCart = checkCart;
 this.deleteLicenseFromCart = deleteLicenseFromCart;
 this.deleteImageFromCart = deleteImageFromCart;
 this.displayCart = displayCart;
 this.displayDispatchedCart = displayDispatchedCart;
 this.cart_build_act = cart_build_act;
 this.cart_mod_act = cart_mod_act;
 this.cart_check_act = cart_check_act;
 this.refreshTopCart = refreshTopCart;
 this.repriceImagesInCart = repriceImagesInCart;

 function addToCart(id,args){

	if (gsession)//logged in user
	{
	    if( document.JSONobj.getCartDat && typeof(args) == 'undefined' )
	    {
                for (var cti=0;cti<document.JSONobj.getCartDat('total');cti++)
                {
                        if ( id == document.JSONobj.getCartDat('image_id',cti) )
			{
//need to do reprice thing here?
                        	alert(phrase.cart_alert_imagealreadyincart);
				return;
			}
		}
	    }

	    if ( typeof(args) == 'undefined' )
	    {
		args = $H({ callback: 'cart_mod_act(0)' });
	    }
	    else if ( args.callback && args.callback.toString().length > 1)  //allready passed a callback so append..
	    {
		args.callback += ' cart_mod_act(0);';
	    }
	    else
	    {
		args.callback  = 'cart_mod_act(0)';
	    }

	    document.TEXTresp = null;
	    simplemessage(phrase.lightbox_adding_message,'','LB');
            if ( typeof(args) == 'object' && args.Size_opname ) //meaning RF pricing data was sent along..
            {
                Object.extend(args, {
                    calc_rate: 1
                });
            }
	     if(typeof(debugmode) !='undefined'){
		ajax_JSON('/AjaxHandlers/CartAdd/' + id + '.json', 'GET', args);
		} else {
		ajax_JSON('/AjaxHandlers/CartAdd/' + id + '.json', 'POST', args);
		}
	    debug('args to json /AjaxHandlers/CartAdd/' + id,args);
	    //cart_mod_act(-1);
	}
	else //not
	{
		window.location='/bin/Cklb?ref=/SwishSearch%3FKeywords%3D'+escape(ukeys)+'%26cartview%3D1&atct='+id;
	}
 };

 function deleteLicenseFromCart (id,args) { //to remove a particular usage/license from an image...
	//need id, usage, opt id(s)

	if (typeof(args) != 'object')
		return;

	simplemessage(phrase.cart_removing_message,'','LB');
	var pos_opts = $A(args.opts).join('|');
	//only if a join produces results w/ array arg..
	if (pos_opts.toString().length)
		args.opts = pos_opts;

	if ( args.callback && args.callback.toString().length > 1)  //allready passed a callback so append..
        {
            args.callback += ' cart_mod_act(0);';
        }
        else
        {
            args.callback  = 'cart_mod_act(0)';
        }


	ajax_JSON('/AjaxHandlers/CartDelLicense/'+ id + '.json', 'POST', args); 
	
 };

 function deleteImageFromCart(id) {
	simplemessage(phrase.cart_deleting_image_message,'','LB');
	ajax_JSON('/AjaxHandlers/CartDel/' + id + '.json', 'POST', 'callback=cart_mod_act(0)');
 };

 function cart_mod_act (tryCtr){ // just wrap calls to redraw cart once the response is there... for any asynch cart actions
	tryCtr++;
	if ( ! document.JSONobj && ! document.TEXTresp && tryCtr < 10)
	{
		setTimeout("cart_mod_act('"+tryCtr+"')", 500);
	} 
	else
	{
		hidedisplaypanel(1);
		cart_build();
		if (document.currentLayer1Mode == 'cartview') 	// if we're viewing expanded cart, and you modify the cart from the lower panel
			cart_display('view');			// then main layer should immed get redrawn to avoid confusion
	}
 };

 function repriceImagesInCart (args) { //maybe you're sending a promo-code  ..  or something.. this call simply forces you  to reprice images in your cart

            if ( typeof(args) == 'undefined' )
            {
                args = $H({ callback: 'cart_mod_act(0)' });
            }
            else if ( args.callback && args.callback.toString().length > 1)  //allready passed a callback so append..
            {
                args.callback += ' cart_mod_act(0);';
            }
            else
            {
                args.callback  = 'cart_mod_act(0)';
            }

            ajax_JSON('/AjaxHandlers/CartReprice/all.json', 'POST', args);
 };

 function awayCart() { //leave site for universal checkout
        top.location = "/bin/Cart?op=ckout";
 };

 function checkCart(){ //verifys all items in current cart are priced
	simplemessage(Templates.cart_tabulating_cart_message.evaluate({'message':'none'}),'','LB');
	ajax_JSON( '/AjaxHandlers/CartInfo/open.json', 'POST', { 'callback': "cart_check_act(); cart_display();" } );
	//cart_check_act(0);
 };

 function cart_check_act(){
	if( document.JSONobj && typeof(document.JSONobj.getCartDat) == 'function')
	{
		var cart_good = 1;

		if(document.JSONobj.getCartDat('total') > 0){
			for (cti=0; cti < document.JSONobj.getCartDat('total'); cti++)
			{
				if(document.JSONobj.getCartDat('price',cti))
				{
					if(!( document.JSONobj.getCartDat('price',cti) != 'null' && document.JSONobj.getCartDat('price',cti) > 0)) 
						cart_good = 0;
				}
				else
				{
					cart_good = 0;
				}
			}
		}
		else
		{
			cart_good = 0;
		}

		if (cart_good == 1)
		{
			cart_away();	
		}
		else
		{
			alert(phrase.cart_problems_alert);
			refreshTopCart();
		}		
	};
 };

 function displayCart (flip) { // call to load shopcart display into Layer1
	if ( document.cart_display_lock )
		return;
        var section = $H({ showstart:'cartview', snum:firstpictureonpage, viewmode:'cartview', flp:flip }).toJSON();
	//make the call through the YAHOO registry.
	if (flip)
	{
		dispatchAll(section);
	}
	else
	{
        	$('row2').style.display='none';
		try { YAHOO.util.History.navigate("nav", section); } catch (e) { dispatchAll(section); }
	}

 };

 function buildCart(mode) { //wrapper for asynch calls to cart data
	currentLbdivMode = 'cart';
	$('LBdiv').style.height = '130px';
	if(mode == 'changing'){
		simplemessage(Templates.cart_loading_cart_message.evaluate({}),'','LB');
	}
 	ajax_JSON( '/AjaxHandlers/CartInfo/open.json', getpost, 'callback=cart_build_act()' ); 

	currMousedOverObj = 'shop_cart';
 };

 function cart_build_act(){

	if(! $('LBdiv'))
		return;
	
	if ( ! isNaN(document.JSONobj.getCartDat('total')) ) 
	{
		hidedisplaypanel(1)	// clears the message that was saying loading lightbox or any other transition messages
		
		var cartRoot = $A([]); //aka LBdiv
		
		var cartTotal = document.JSONobj.getCartDat('total');

	
          	(new afInit()).handleBuilder({ Builder : global.builderClass,
                                                cartPic : global.cartPic });


		cartRoot.push(
		Builder.node('div', {id:'lbbuttons'}, [
			global.nodeTree.cart_build_act__buttons,
			]),
		Builder.node('div', { className:'lbname', style:'padding:3px 0px 0px 3px; margin:0px;'},[
			Builder.node('b', {}, 'Shopping Cart  '+( cartTotal ? cartTotal : 0 ) + ' images '),
			global.nodeTree.cart_build_act__actions,
		]));
	
		if(document.JSONobj.getCartDat('total')>0){
			
			var tofit = parseInt((winW*0.65)/document.JSONobj.getCartDat('total'));
			if(winH < 340){vlim=25;} else if(winH < 450){vlim=35;} else {vlim=58;}
			if(tofit> vlim){
				tofit=vlim;
			} else if (tofit<18){
				tofit=18;
			}
			
			var cartimages = $A([]);
			for (cti=0;cti<document.JSONobj.getCartDat('total');cti++)
			{
				ctimid = document.JSONobj.getImgDat('id', cti);
				ctid = document.JSONobj.getCartDat('id',cti);				
				
				cartimages.push( Builder.node('div', { 	align:'center', id:'dct'+cti+'s', name:'dct'+cti+'s', valign:'bottom', style:'float:left; height:' + ( tofit + 18 ) + 'px; overflow:hidden;' },[
					Builder.node('a', {	href:'', onclick:'hp(); return false', id:'dct'+cti+'s_cti'},[
						Builder.node('img', { id:'ctimage_'+ctimid, onmouseover:'prloadimg("'+ctimid+'"); sp(this, "'+ctimid+'", "1", "'+tset+'");', onmouseout:'hp();', src: 'http://globaldyn.ipnstock.com/'+dynimagesname+'/135/50/'+ctimid+'.JPG', height: tofit, border: 0, className: 'lbimg', hspace: 2	} )
					]),
					Builder.node('div', { style:'padding:2px'}, [
						Builder.node('a', { href:'', onclick:'cart_delete_image("'+ctid+'"); return false;', className:'ctlink ctlinkDeleteImage', title:phrase.cart_delete_title}, phrase.lbstrip_remove_image_from_cart_linktext)
					])
				]) );
				
			}
			
			cartRoot.push(
				Builder.node('div', {id:'LBimgdiv', style:'padding:6px 0 0 3px; height: 100%'}, [ cartimages, Builder.node('br', {style:'clear:both'}) ])
			);

			//set future cookie for remaining images in cart
			var date = new Date();
        		date.setTime(date.getTime()+(60*24*60*60*1000));
			gsetCookie('gcartimages',cti,date,'/',gGetCookieDom());
			
		}

		$('LBdiv').replace('<DIV id="LBdiv"></DIV>');
		cartRoot.each(function(carta){
			$('LBdiv').appendChild(carta);	
		});


		
	}
 };	

 function displayDispatchedCart ( args ) {
        if ( typeof(args) != 'object' )
                return;

	var flip = args['flp'];

	document.cart_display_lock = 1; // it's pretty much incidental which functions should loop and which should never run concurrently
					// this is one where it hurts to spawm so many loads of itself...
	document.currentLayer1Mode = 'cartview';

        if($('cdheader'))
               $('cdheader').style.display = 'none';


	if(!flip)
		flip='view';

		ajax_HTML('Layer1', '/bin/Cart?op='+flip, 'GET');
		$('Layer1').style.height = truevertHeight + 'px';
		$('Layer1').style.overflow = 'scroll';
		$('Layer1').style.overflowX = 'hidden';
		if($('pagingrow') && document.currentLayer1Mode != 'searchresults')
	                $('pagingrow').innerHTML = '';

	document.cart_display_lock = 0;
 };


 function refreshTopCart() {
	if(gsession){
		self.location.replace(  ( typeof(baseurl) != 'undefined' ? baseurl : '' ) + "/SwishSearch?n=1&cartview=1&random=" + Math.random(100)); // added random to make cart refresh itself if called locally
	} else {
		self.location=( typeof(baseurl) != 'undefined' ? baseurl : '' ) + "/bin/Cklb?ref=%2FSwishSearch?cartview=1";
	}
 };


};

function afCookie() {

 this.setCookie = setCookie;
 this.setCookie2 = setCookie2;
 this.getCookie = getCookie;
 this.deleteCookie = deleteCookie;
 this.getCookieDomain = getCookieDomain;
 this.setCookieGwhichindex = setCookieGwhichindex;
 this.setCookieGreleasedselect = setCookieGreleasedselect;

 function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
 };

 function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
 };

 function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" + 
     ((path) ? "; path=" + path : "/") +
     ((domain) ? "; domain=" + domain : "") +
     "; expires=Thu, 01-Jan-70 00:00:01 GMT";
   }
 };

 function setCookie2(name2,value2) {
  setCookie(name2, value2, '', '/', getCookieDomain());
 };

 function getCookieDomain(){
  var thisdomain = document.domain;
  var domainparts = thisdomain.split(".");
  var end = domainparts.length - 1;
  var start = domainparts.length - 2;
  var domainend = domainparts[end];
  var domainstart = domainparts[start];
//  var setdom = "." + domainstart + "." + domainend;
  var setdom = domainstart + "." + domainend;
  return setdom;
 };

 function setCookieGwhichindex(tset) {	
	gsetCookie("gwhichindex",tset, '', '/', gGetCookieDom());
 };

 function setCookieGreleasedselect(tsetval) {
	gsetCookie("greleasestatus",tsetval, '', '/', gGetCookieDom());
 };

};

function afDate() {

 this.getCurrentDate = getCurrentDate;
 this.setCurrentTime = setCurrentTime;
 this.fixDate = fixDate;

 function getCurrentDate() {
  var d = new Date();
  return (d);
 }

 function setCurrentTime(currDate) {

  var currentDate = currDate || this.getCurrentDate();

   var now = currentDate;
   fixDate(currentDate);
   now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);

  return (now);

 };

 function fixDate(date) {
   var base = new Date(0);
   var skew = base.getTime();
   if (skew > 0)
    date.setTime(date.getTime() - skew);
 };

};

function afDispatch() {

 this.dispatchAll = dispatchAll;
 this.reDispatch = reDispatch;

 function dispatchAll(oContent,init){
        var oC = (typeof(oContent) == 'object' ? oContent : oContent.evalJSON() ); 
	var fpop = ( typeof(firstpictureonpage) != 'undefined' ? firstpictureonpage : 0 );

        if(oC.viewmode == 'ss' ) {
		dispatchEnlarge2(oC);
	} else if ( oC.viewmode == 'cartview' || cartview ) {
                document.currentLbdivMode = 'cart';
                document.currentLayer1Mode = 'cartview';
		viewmode = 'cartview';
                currMousedOverObj = 'shop_cart';
		dispatchCart_display(oC);
        } else if ( oC.snum < fpop ) {
		document.currentLayer1Mode = oC.viewmode;
		viewmode = oC.viewmode;
                //buildimages(oC.snum, 'prev');
		oC['buildmode'] = oC['buildmode'] || 'prev';
		dispatchBuildimages(oC);
        } else if ( oC.snum > fpop ) {
		document.currentLayer1Mode = oC.viewmode;
		viewmode = oC.viewmode;
                //buildimages(oC.snum, 'next');
		oC['buildmode'] = oC['buildmode'] || 'next';
		dispatchBuildimages(oC);
        } else if ( oC.snum == fpop ) {
		document.currentLayer1Mode = oC.viewmode;
		viewmode = oC.viewmode;
		//buildimages(oC.snum,'current');
		oC['buildmode'] = oC['buildmode'] || 'current';
		dispatchBuildimages(oC);
	}
 };

 function reDispatch() {
	dispatchAll(YAHOO.util.History.getCurrentState());
 };

};
function afHTML() {

 this.buildPagination = buildPagination;
 this.imageProfile = imageProfile;
 this.centerPanel = centerPanel;
 this.createCoverLayer = createCoverLayer;
 this.createDisplayPanel = createDisplayPanel;
 this.dispatchBuildImages = dispatchBuildImages;
 this.divShim = divShim;
 this.getFooter = getFooter;
 this.hideCoverLayer = hideCoverLayer;
 this.hideDisplayPanel = hideDisplayPanel;
 this.html_share_con_opts = html_share_con_opts;
 this.html_weight_con_opts = html_weight_con_opts;
 this.html_combined_con_opts = html_combined_con_opts;
 this.initShareRadios = initShareRadios;
 this.showDisplayPanel = showDisplayPanel;

 function centerPanel(x,y,thehtml,tp,args){ 		// sub to center a panel and write the passed html with optional flag for search exp.
  var topX = args ? args.topX : undefined;  		// added args parameter  - Milan Adamovsky 06/18/2009
  var topY = args ? args.topY : undefined;
  var fixed = args ? args['static'] : undefined;

	if (typeof(winH) == 'undefined')
		setuppagesize();
	
	var yoff = ( typeof(popupYoffset) != 'undefined' ) ? popupYoffset : 0;
	
	if ((winW - x) < 0){
			panelx = 0;
	} else {
			panelx = parseInt((winW - x)/2); 		// center it
	}
	if ((winH - y) < 0){
			panely = 41;
	} else {
			panely = parseInt((winH - y)/2); 		//center it
	}

	if(tp){
		var tx = Position.cumulativeOffset($('scontainer'));
		var ty = Position.cumulativeOffset($('row2'));
		panelx = tx[0];
		panely = ty[1];
	}

	createDisplayPanel();
	createCoverLayer();
	$('displaypanellayer').style.top = ( topY == undefined ?  panely + yoff : topY ) + 'px';
	$('displaypanellayer').style.left = ( topX == undefined ? panelx : topX )+ 'px';
	$('displaypanellayer').style.width =x + 'px';
	$('displaypanellayer').style.height =y + 'px';
	if (fixed){
		$('displaypanellayer').style.position = 'fixed';
	}
	$('coverlayer').style.visibility="visible";
	$('displaypanellayer').style.visibility="hidden";
	new Effect.Appear('coverlayer', {duration: 0.3, from:0, to: 0.7 });
	$('displaypanellayer').innerHTML = thehtml;

	setTimeout("displaypanelshow();",320);
 };


 function imageProfile(showid){						// build html for each image depending on viewing mode
	var html='';
	switchpage = false;
	if (id[showid]){
		
		var myrmrftype = rm[showid];
		myid = id[showid];
		if (typeof(suspendsimilars) == 'undefined'){
			mysimilarto=st[showid];
		} else { 
			mysimilarto='';
		}
			
		if (typeof(scp) != 'undefined' && (viewmode == 'list' || viewmode == 'editing') ) {myshortcaption=unescape(scp[showid]);} else {myshortcaption = "n/a";}
		var temp = true;
		var tempshortcaption='';
		var myreleased = '';

		if (! relcon[showid])
			myreleased = rel[showid];

		if (typeof(relcon) != 'undefined' && relcon[showid] && mysimilarto.length < 13) {  //share control style..
			var shortrel = myreleased; ///( $('gRelease'+showid) && $('gRelease'+showid).value ) ? $('gRelease'+showid).value : myreleased;
			shortrel = shortrel.substring(0,16) + (myreleased.length > 16 ? '...' : '');

			myreleased = Templates.results_editing_savereleases.evaluate({'showid':showid,'relcon':relcon[showid],'shortrel':shortrel});
		} 
		else if(showrelease){
			if(! ( myreleased == "MODEL RELEASED" || myreleased == "MODEL AND PROPERTY RELEASED" || myreleased == "PROPERTY RELEASED") ){
				myreleased = "Release: " + myreleased;
			}
			if (typeof(relcon) != 'undefined' && relcon[showid] && mysimilarto.length < 13)
				myreleased ='<br/>'+myreleased;

		} else { myreleased="";}
		//shorten long captions
		if(myshortcaption.length > 90){
			for(z=0; z < 130; z++){
				var c = myshortcaption.charAt(z);
				if(temp == true){
					if((z > 90) && (c == ".")){
						temp = false;
						tempshortcaption+=c + " ...";
					} else if((z > 110) && (c == " ")){
						temp = false;
						tempshortcaption+=" ...";
					} else {
						tempshortcaption+= c;
					}
				}
        		}
        		myshortcaption = tempshortcaption;
    		}
    		var thishassimilars = "yes";
		myphotographer=pho[showid];
		myrglobaldynf = rm[showid];
		myfilesize=fs[showid];
		var myhrdlink = hrdl[showid];

		var mysharestatuses = html_share_con_opts(showid);
		var mysiteweight = html_weight_con_opts(showid);
		var mycombinedcon = html_combined_con_opts(showid);

                var thisisacoverimage_feature = '';
                if(rfcd[showid].match(myid)) //myid is in the info for the link, hence this is the cover image
                {
                        var pm = unescape(rfcd[showid]).match(/SwishSearch\?n\=1\&fn\=(.*)\&supst\=cd/);
                        if(pm != null)
                                thisisacoverimage_feature = pm[1];
                }

		adminheight=0;
		if(myhrdlink){
                        if (viewmode != 'editing')
                                adminheight=11;
		} 
		if(myfilesize < 5){myfilesize='Scan on Demand';} //else {myfilesize+=" Mb";}
		if(myid.length > 9){
			if ( o[showid] ){displayid=o[showid];} else {displayid=myid;}	
				if(viewmode == "editing"){
					var theight = 160 + adminheight;

					var sharesync = unescape(shsync[showid]);
					sharesync=sharesync.split('|');
					//so 0 is type, 1 is if it matchess
					var shbg = 'white';
					if (sharesync[0] == 'shared') {
							shbg = '#77BB33';
					} else if (sharesync[0].toString().match(/notshared|rejected/)) {
							shbg = '#DF0000';
					}
					var shbdr = 'white';
					if ( parseInt(sharesync[1]) )
					{
							shbdr = 'orange';
					}
					if ( mysimilarto.length < 13){

						html += '<span id="cellwrapper'+myid+'" valign=bottom style="float:left;background-color:'+shbdr+'; padding:0 6px; 0 6px">';

						html += '<div id="d'+myid+'" align=center valign=bottom style=" background-color:'+shbg+'; width:288px; height:' + theight + 'px;">';
						html += '<TABLE width=298 cellspacing=2 cellpadding=0 border=0><TR><TD valign=top><div style="position:relative;height:160px;"><a href="javasc' + 'ript:enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\');"><img src="' + ImageUrl('135/50',myid,showid) + '" border=0 class=pimg vspace=2 hspace=3';
						html += " onmouseover=\"prloadimg('"+ myid +"'); sp(this, '" + myid + "','" + showid + "','"+tset+"');";html += '" onmouseout="hp();" id=' + myid + '>';

						html += '</a>';
						html += mycombinedcon + mysharestatuses;
                                        html += '</div></td><td valign="top"><font class=xsmall>ID:' + myid;
                                        if(typeof(suppressrmrftype) == 'undefined'){
                                                html += '  <font class=rmrfindicator>'+rm[showid]+'</font>';
                                        }
                                        html += '<DIV class=icons>';

                                        if ((typeof(pre_q_args) != 'undefined' && pre_q_args.match(/fn=/) ) || (typeof(q_args) != 'undefined' && ( q_args.match(/vmo=/) || q_args.match(/rid=/) || q_args.match(/lb_view=1/) || q_args.match(/fn=/))) )
                                        {
                                                html+='<A href="javascript:lightbox_delete_image_enl(\'' + myid + '\');" class="lblink" TITLE="Remove this image from the lightbox">X</A>';
                                        }

                                        html += '</DIV>';

                                        myphotographer = unescape(myphotographer);
                                        if (myphotographer.length > 18)
                                                myphotographer = myphotographer.substring(0,18) + '...';

                                        if(showphotographer == 1){html +='&copy; '+currentYear+' ' + myphotographer;}
                                        html += '  <nobr>';
                                        if(showfilesize){html += myfilesize;}

                                        html += '</nobr><br/>CAPTION: ' + myshortcaption+'<div>'+myreleased+'</div></font>';

                                        html += mysiteweight;

                                        if(myhrdlink)
                                                html += '<br/><NOBR><a href="'+myhrdlink+'" class="hiresdl_link"><font color="#cc0000">Download Hires</font></a></NOBR>';
                                        html += '<br/><a href="javascript: return false;" ONCLICK="lightbox_addto(\'' + myid + '\'); return false;" class="iconlink" title="Add to your current lightbox">LB+</a>';

                                        html += '</td></tr></table></DIV></span></SPAN>';
                                } else {

                                        html += '<span id="cellwrapper'+myid+'" valign=bottom style="float:left;background-color:'+shbdr+'; padding:0 6px; 0 6px;">';
                                        html += '<div id="d' + myid + '" align=center valign=bottom style=" background-color:'+shbg+'; width:288px; height:' + theight + 'px;">';
                                        html += writesimilar(myid,showid,myphotographer,myshortcaption,'start','editing', myhrdlink, myreleased);
                                        html += '</DIV></span></SPAN>';
                                }

                        }
                        else if(viewmode == "list"){
				var theight = 172 + adminheight;
				if ( mysimilarto.length < 13){	
					
					html += '<span id="cellwrapper'+showid+'" valign=bottom style="float:left;">';
					html += '<div align=center valign=bottom style="width:305px; height:' + theight + 'px;">';
					html += '<table width=298 cellspacing=2 cellpadding=0 border0><tr><td valign=top>';

                                        if(thisisacoverimage_feature) //myid is in the info for the link, hence this is the cover image
                                                html += '<a href="/SwishSearch?n=1&fn='+thisisacoverimage_feature+'&supst=cd" >';
                                        else
						html += '<a href="javascript: return false;" onclick="hp(); enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;">';

					html += '<img src="' + ImageUrl('135/50',myid,showid) + '" border=0 class=pimg vspace=2 hspace=3';
					html += " onmouseover=\"prloadimg('"+ myid +"'); sp(this, '" + myid + "','" + showid + "','"+tset+"');";html += '" onmouseout="hp();" id=' + myid + '>';
					html += '</a><br />';
					if(myhrdlink)
						html += '<center><a href="'+myhrdlink+'" class="hiresdl_link"><font color="#cc0000">Download Hires</font></a></center>';
					html += '</td><td valign="top"><font class=xsmall>ID:' + displayid;
					if(typeof(suppressrmrftype) == 'undefined'){
						html += '  <font class=rmrfindicator>'+rm[showid]+'</font>';
					}
					html += '<DIV class=icons>';

					if (  ! thisisacoverimage_feature && ((typeof(pre_q_args) != 'undefined' && pre_q_args.match(/fn=/) ) || (typeof(q_args) != 'undefined' && ( q_args.match(/vmo=/) || q_args.match(/rid=/) || q_args.match(/lb_view=1/) || q_args.match(/fn=/))) ) )	
					{
						html+='<A href="javascript: return false;" onclick="lightbox_delete_image_enl(\'' + myid + '\'); return false;" class="lblink" TITLE="Remove this image from the lightbox">X</A>';
					}

					html += '<a href="javascript: return false;" ONCLICK="lightbox_addto(\'' + myid + '\'); return false;" class="iconlink" title="Add to your current lightbox">LB+</a>';
					if(gsession){html += '<a href="javascript: return false;" ONCLICK="cart_addto(\'' + myid + '\'); return false;" class="iconlink" title="Add this image to your shopping cart">CART+</a>';}

					html += '<a href="javascript: return false;" ONCLICK="return price_image(\'' + myid + '\',\''+myrmrftype+'\');" class="iconlink" Title="Price Image">$</a>';
					if (! thisisacoverimage_feature )
						html += '<a href="javascript: return false;" ONCLICK="enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;" class=iconlink title="Enlarge image and more info"><font class=eye>i</font></a>';

					html += '</DIV>';
					
					if(showphotographer == 1){html +='<br />&copy; '+currentYear+' ' + myphotographer;}
					html += '  <nobr>';
					if(showfilesize){html += myfilesize;}
					html += '</nobr><br/>CAPTION: ' + myshortcaption + '<div>'+myreleased+'</div></font>';


					html += '</td></tr></table></DIV></SPAN>';
				} else {	
			
	
					html += '<span valign=bottom style="float:left;">';
					html += '<div id="d' + myid + '" align=center valign=bottom style="width:305px; height:' + theight + 'px;">';
					html += writesimilar(myid,showid,myphotographer,myshortcaption,'start','list', myhrdlink, myreleased);
                                        //html += myhrdlink + '<br/>' + myreleased + mysharestatuses;

					html += '</DIV></SPAN>';
				}
				
			
			} else if (viewmode == "tiny"){
				//adminheight += 8;
				var theight = 100 + adminheight;
				if ( mysimilarto.length < 13){	
					
					html += '<span valign=bottom style="float:left;">';
					html += '<div align=center valign=bottom style="width:95px; height:' + theight + 'px; overflow: hidden;">';

                                        if(thisisacoverimage_feature) //myid is in the info for the link, hence this is the cover image
                                                html += '<a href="/SwishSearch?n=1&fn='+thisisacoverimage_feature+'&supst=cd" ';
                                        else
                                                html += '<a href="javascript: return false;" onclick="hp(); enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;"';

					if(document.page.previews.selectedIndex == 1){html +=' TITLE="ID:' + displayid;
						if(showphotographer == 1){html += '\r&copy; ' + myphotographer;}
						if(showfilesize){html += '\rSIZE: '+ myfilesize ;}
						html +=  ' \r' + 'CAPTION: ' + myshortcaption + '"';
					}
					html += '><img src="' +ImageUrl('135/50',myid,showid)+ '" border=0 class=pimg vspace=1 hspace=1 height=55';
					html += " onmouseover=\"prloadimg('"+ myid +"'); sp(this, '" + myid + "', '" + showid + "','"+tset+"');";
					html += '" onmouseout="hp();" id=' + myid + '>';
					
					//sp('','" + myid + "','" + myrglobaldynf + "','" + myphotographer + "','" + myid + "','" + showid + "')
					html += '</a><br />';
					html += '<font class="xxsmall"><DIV class=icons>';

					if (! thisisacoverimage_feature && ((typeof(pre_q_args) != 'undefined' && pre_q_args.match(/fn=/) ) || (typeof(q_args) != 'undefined' && ( q_args.match(/vmo=/) || q_args.match(/rid=/) || q_args.match(/lb_view=1/) || q_args.match(/fn=/))) ) )
					{
						html+='<A href="javascript: return false;" onclick="lightbox_delete_image_enl(\'' + myid + '\'); return false;" class="iconlinktiny" TITLE="Remove this image from the lightbox">X</A>';
					}


					html += '<a href="javascript: return false;" ONCLICK="lightbox_addto(\'' + myid + '\'); return false;" class="iconlinktiny" title="Add to your current lightbox">LB+</a>';
					if(gsession){html += '<a href="javascript: return false;" ONCLICK="cart_addto(\'' + myid + '\'); return false;" class="iconlinktiny" title="Add this image to your shopping cart">CART+</a>';}

					html += '<a href="javascript: return false;" ONCLICK="return price_image(\'' + myid + '\',\''+myrmrftype+'\');" class="iconlinktiny" Title="Price Image">$</a>';
					if (! thisisacoverimage_feature)
						html += '<a href="javascript: return false;" ONCLICK="enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;" class="iconlinktiny" title="Enlarge image and more info"><font class=eye>i</font></a>';

					/*  if(typeof(gusert) != 'undefined' && gusert =='IPN'){
						html += '<A href="javascript: return false;" onclick="ajax_TEXT(\'/bin/KeywordAdjust?good=1&id=' + myid + '&q=' + dsplkys + '\'); return false;"><IMG src=/graphics/rating_enhance.gif width=18 height=12 border=0 style="margin-bottom: -3px;"></a><A href="javascript: return false;" onclick="ajax_TEXT(\'/bin/KeywordAdjust?bad=1&id=' + myid + '&q=' + dsplkys + '\'); return false;"><IMG src=/graphics/rating_discourage.gif width=18 border=0 height=12 style="margin-bottom: -3px;"></a>';
					}  */

					html += '</DIV></font>';
					html += '<DIV class=imidxxsmall>' + displayid;
					if(typeof(suppressrmrftype) == 'undefined'){
						html += '  <font class=rmrfindicator>'+rm[showid]+'</font>';
					}
					html +='</DIV>';

					if (myhrdlink)
						html += '<a href="'+myhrdlink+'" class="hiresdl_link"><font color="#cc0000">Download Hires</font></a>';
					html += '</DIV></SPAN>';

				} else {				
	
					html += '<span valign=bottom style="float:left;">';
					html += '<div id="d' + myid + '" align=center valign=bottom style="width:95px; height:' + theight + 'px; overflow:hidden;">';
					html += writesimilar(myid,showid,myphotographer,myshortcaption,'start','tiny',myhrdlink,myreleased);		
					html += '</DIV></SPAN>';
				}
			
			
			} else if (viewmode == "med"){
				//adminheight += 4; // tweaking adminheight...
				var theight = 130 + adminheight;
				if ( mysimilarto.length < 13){	
				
					html += '<span valign=bottom style="float:left;">';
					html += '<div align=center valign=bottom style="width:140px; height:' + theight + 'px; overflow: hidden;">';

                                        if(thisisacoverimage_feature) //myid is in the info for the link, hence this is the cover image
                                                html += '<a href="/SwishSearch?n=1&fn='+thisisacoverimage_feature+'&supst=cd" ';
                                        else
                                                html += '<a href="javascript: return false;" onclick="hp(); enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;"';


					if(document.page.previews.selectedIndex == 1){html += ' TITLE="ID:' + displayid;
						if(showphotographer == 1){html += '  \r&copy; ' + myphotographer;}
						if(showfilesize){html += '\rSIZE: ' + myfilesize ;}
						html += ' \r' + 'CAPTION: ' + myshortcaption + '"';
					}
					html += '><img src="' + ImageUrl('135/50',myid,showid) + '" border=0 vspace=1 class=pimg hspace=1 height=80';
					html += " onmouseover=\"prloadimg('"+ myid +"'); sp(this, '" + myid + "', '" + showid + "','"+tset+"');";
					html += '" onmouseout="hp();" id=' + myid + '>';
						//sp('','" + myid + "','" + myrglobaldynf + "','" + myphotographer + "','" + myid + "','" + showid + "')
					html += '</a><br />';
					html += '<font class="xsmall"><DIV class=icons>';

					if (! thisisacoverimage_feature && ((typeof(pre_q_args) != 'undefined' && pre_q_args.match(/fn=/) ) || (typeof(q_args) != 'undefined' && ( q_args.match(/vmo=/) || q_args.match(/rid=/) || q_args.match(/lb_view=1/) || q_args.match(/fn=/))) ) )
					{
						html+='<A href="javascript: return false;" onclick="lightbox_delete_image_enl(\'' + myid + '\'); return false;" class="lblink" TITLE="Remove this image from the lightbox">X</A>';
					}

					html += '<a href="javascript: return false;" ONCLICK="lightbox_addto(\'' + myid + '\'); return false;" class="iconlink" title="Add to your current lightbox">LB+</a>';
					if(gsession){html += '<a href="javascript: return false;" ONCLICK="cart_addto(\'' + myid + '\'); return false;" class="iconlink" title="Add this image to your shopping cart">CART+</a>';}

					html += '<a href="javascript: return false;" ONCLICK="return price_image(\'' + myid + '\',\''+myrmrftype+'\');" class="iconlink" Title="Price Image">$</a>';
					if (! thisisacoverimage_feature)
						html += '<a href="javascript: return false;" ONCLICK="enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;" class="iconlink" title="Enlarge image and more info"><font class=eye>i</font></a>';

					if(typeof(gusert) != 'undefined' && gusert =='IPN'){
						html += '<A href="javascript: return false;" onclick="ajax_TEXT(\'/bin/KeywordAdjust?good=1&id=' + myid + '&q=' + dsplkys + '\',getpost); return false;"><IMG src=/graphics/rating_enhance.gif width=18 height=12 border=0 style="margin-bottom: -3px;"></a><A href="javascript: return false;" onclick="ajax_TEXT(\'/bin/KeywordAdjust?bad=1&id=' + myid + '&q=' + dsplkys + '\', getpost); return false;"><IMG src=/graphics/rating_discourage.gif width=18 border=0 height=12 style="margin-bottom: -3px;"></a>';
					}
					html += '</DIV></font>';
					html += '<DIV class=imidxxsmall>' + displayid;
					if(typeof(suppressrmrftype) == 'undefined'){
						html += '  <font class=rmrfindicator>'+rm[showid]+'</font>';
					}
					html +='</DIV>';
					if (myhrdlink)
						html += '<a href="'+myhrdlink+'" class="hiresdl_link"><font color="#cc0000">Download Hires</font></a>';
					
					

					html += '</DIV></SPAN>';

				} else {				
	
					html += '<span valign=bottom style="float:left;">';
					html += '<div id="d' + myid + '" align=center valign=bottom style="width:140px; height:' + theight + 'px;">';
					html += writesimilar(myid,showid,myphotographer,myshortcaption,'start','med',myhrdlink,myreleased);		
					html += '</DIV></SPAN>';
				}
			} else if (viewmode == "ss"){			
				html = '  ';
			} else if (viewmode == "huge"){		
				var theight = 220 + adminheight;
				if ( mysimilarto.length < 13){	
					html += '<span valign=bottom style="float:left;">';
					html += '<div align=center valign=bottom style="width:330px; height:' + theight + 'px; overflow: hidden;">';

                                        if(thisisacoverimage_feature) //myid is in the info for the link, hence this is the cover image
                                                html += '<a href="/SwishSearch?n=1&fn='+thisisacoverimage_feature+'&supst=cd" ';
                                        else
                                                html += '<a href="javascript: return false;" onclick="hp(); enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;" TITLE="ID:' + displayid;

					if(showphotographer == 1){html += '\r&copy; ' + myphotographer;}
					if(showfilesize){html +=   '\rSIZE: ' + myfilesize ;}
					html += ' \r' + 'CAPTION: ' + myshortcaption + '"><img src="' + ImageUrl('420/60',myid,showid) + '" border="0" vspace="1" hspace="3" alt="loading..." height="192"></a><br />';
					html += '<font class="xsmall"><DIV class=icons>';

					if ( ! thisisacoverimage_feature && ((typeof(pre_q_args) != 'undefined' && pre_q_args.match(/fn=/) ) || (typeof(q_args) != 'undefined' && ( q_args.match(/vmo=/) || q_args.match(/rid=/) || q_args.match(/lb_view=1/) || q_args.match(/fn=/))) ) )
					{
						html+='<A href="javascript: return false;" onclick="lightbox_delete_image_enl(\'' + myid + '\'); return false;" class="lblink" TITLE="Remove this image from the lightbox">X</A>';
					}

					html += '<a href="javascript: return false;" ONCLICK="lightbox_addto(\'' + myid + '\'); return false;" class="iconlink" title="Add to your current lightbox">LIGHTBOX+</a>';
					if(gsession){html += '<a href="javascript: return false;" ONCLICK="cart_addto(\'' + myid + '\'); return false;" class="iconlink" title="Add this image to your shopping cart">CART+</a>';}

					html += '<a href="javascript: return false;" ONCLICK="return price_image(\'' + myid + '\',\''+myrmrftype+'\');" class="iconlink" Title="Price Image">$</a>';
					if (! thisisacoverimage_feature)
						html += '<a href="javascript: return false;" ONCLICK="enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;" class="iconlink" title="Enlarge image and more info"><font class=eye>i</font> ENLARGE</a> ';

					if(typeof(gusert) != 'undefined' && gusert =='IPN'){
						html += '<A href="javascript: return false;" onclick="ajax_TEXT(\'/bin/KeywordAdjust?good=1&id=' + myid + '&q=' + dsplkys + '\', getpost); return false;"><IMG src=/graphics/rating_enhance.gif width=18 height=12 border=0 style="margin-bottom: -3px;"></a><A href="javascript: return false;" onclick="ajax_TEXT(\'/bin/KeywordAdjust?bad=1&id=' + myid + '&q=' + dsplkys + '\',getpost); return false;"><IMG src=/graphics/rating_discourage.gif width=18 border=0 height=12 style="margin-bottom: -3px;"></a>';
					}
					html += displayid;
					if(typeof(suppressrmrftype) == 'undefined'){
						html += '  <font class=rmrfindicator>'+rm[showid]+'</font> ';
					}
	                                html += '</DIV></font>';

					if (myhrdlink)
						html += '<a href="'+myhrdlink+'" class="hiresdl_link"><font color="#cc0000">Download Hires</font></a>';

					html += '</DIV></SPAN>';
					
				} else {
					html += '<span valign=bottom style="float:left;">';
					html += '<div id="d' + myid + '" align=center valign=bottom style="width:330px; height:' + theight + 'px; overflow: hidden;">';
					html += writesimilar(myid,showid,myphotographer,myshortcaption,'start','huge', myhrdlink, myreleased);

					html += '</DIV></SPAN>';
				}				
			} else if (viewmode == "large"){
				var theight = 199 + adminheight;
				if ( mysimilarto.length < 13){		
					html += '<span valign=bottom style="float:left;">';
					html += '<div align=center valign=bottom style="width:187px; height:' + theight + 'px; overflow:hidden;">';
                                        if(thisisacoverimage_feature) //myid is in the info for the link, hence this is the cover image
                                                html += '<a href="/SwishSearch?n=1&fn='+thisisacoverimage_feature+'&supst=cd" ';
                                        else
                                                html += '<a href="javascript: return false;" onclick="hp(); enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;"'

					if(document.page.previews.selectedIndex == 1){html += ' TITLE="ID:' + displayid;
						if(showphotographer == 1){html +=  '\r&copy; ' + myphotographer;}
						if(showfilesize){html += '\rSIZE: ' + myfilesize ;}
						html += ' \r' + 'CAPTION: ' + myshortcaption + '"';
					}
					html += '><img src="' + ImageUrl('170/85', myid,showid) + '" class=pimg border="0" vspace="0" hspace="3"';
					html += " onmouseover=\"prloadimg('"+ myid +"'); sp(this, '" + myid + "','" + showid + "','"+tset+"');";
					html += '" onmouseout="hp();" id=' + myid + '>';
					
					html += '</a><br />';
					html += '<font class="xsmall"><DIV class=icons>';

					
					if (! thisisacoverimage_feature && ((typeof(pre_q_args) != 'undefined' && pre_q_args.match(/fn=/) ) || (typeof(q_args) != 'undefined' && ( q_args.match(/vmo=/) || q_args.match(/rid=/) || q_args.match(/lb_view=1/) || q_args.match(/fn=/))) ) )						{
						html+='<A href="javascript: return false;" onclick="lightbox_delete_image_enl(\'' + myid + '\'); return false;" class="iconlink" TITLE="Remove this image from the lightbox">X</A>';
					}

					html += '<a href="javascript: return false;" ONCLICK="lightbox_addto(\'' + myid + '\'); return false;" class="iconlink" title="Add to your current lightbox">LB+</a>';
					if(gsession){html += '<a href="javascript: return false;" ONCLICK="cart_addto(\'' + myid + '\'); return false;" class="iconlink" title="Add this image to your shopping cart">CART+</a>';}
					html += '<a href="javascript: return false;" ONCLICK="return price_image(\'' + myid + '\',\''+myrmrftype+'\');" class="iconlink" Title="Price Image">$</a>';
					if (! thisisacoverimage_feature )
						html += '<a href="javascript: return false;" ONCLICK="enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;" class="iconlink" title="Enlarge image and more info"><font class=eye>i</font></a>&nbsp;';

					if(typeof(gusert) != 'undefined' && gusert =='IPN'){
						html += '<A href="javascript: return false;" onclick="ajax_TEXT(\'/bin/KeywordAdjust?good=1&id=' + myid + '&q=' + dsplkys + '\',getpost); return false;"><IMG src=/graphics/rating_enhance.gif width=18 height=12 border=0 style="margin-bottom: -3px;"></a><A href="javascript: return false;" onclick="ajax_TEXT(\'/bin/KeywordAdjust?bad=1&id=' + myid + '&q=' + dsplkys + '\',getpost); return false;"><IMG src=/graphics/rating_discourage.gif width=18 border=0 height=12 style="margin-bottom: -3px;"></a>';
					}

					html += '</div><div><font class=imid>' + displayid + '</font>';
					if(typeof(suppressrmrftype) == 'undefined'){
						html += '  <font class=rmrfindicator>'+rm[showid]+'</font>';
					}
					html +='</DIV></font>';

					if (myhrdlink)
	                                        html += '<a href="'+myhrdlink+'" class="hiresdl_link"><font color="#cc0000">Download Hires</font></a>';

					html += '</DIV></SPAN>';
		
			
				} else {			
					html += '<span valign=bottom style="float:left;">';
					html += '<div id="d' + myid + '" align=center valign=bottom style="width:187px; height:' + theight + 'px; overflow: hidden;">';
					html += writesimilar(myid,showid,myphotographer,myshortcaption,'start','large', myhrdlink, myreleased);

					html += '</DIV></SPAN>';
				}
			} else {
				var theight = 176 + adminheight;
				if ( mysimilarto.length < 13){		
					html += '<span valign=bottom style="float:left;">';
					html += '<div align=center valign=bottom style="width:152px; height:' + theight + 'px; overflow:hidden;">';
                                        if(thisisacoverimage_feature) //myid is in the info for the link, hence this is the cover image
                                                html += '<a href="/SwishSearch?n=1&fn='+thisisacoverimage_feature+'&supst=cd" ';
                                        else
                                                html += '<a href="javascript: return false;" onclick="hp(); enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;"'


					if(document.page.previews.selectedIndex == 1){html += ' TITLE="ID:' + displayid;
						if(showphotographer == 1){html +=  '\r&copy; ' + myphotographer;}
						if(showfilesize){html += '\rSIZE: ' + myfilesize ;}
						html += ' \r' + 'CAPTION: ' + myshortcaption + '"';
					}
					html += '><img src="' + ImageUrl('135/50', myid,showid) + '" class=pimg border="0" vspace="0" hspace="3"';
					html += " onmouseover=\"prloadimg('"+ myid +"'); sp(this, '" + myid + "','" + showid + "','"+tset+"');";
					html += '" onmouseout="hp();" id=' + myid + '>';
					
					html += '</a><br />';
					html += '<font class="xsmall"><DIV class=icons>';

					
					if (! thisisacoverimage_feature && ((typeof(pre_q_args) != 'undefined' && pre_q_args.match(/fn=/) ) || (typeof(q_args) != 'undefined' && ( q_args.match(/vmo=/) || q_args.match(/rid=/) || q_args.match(/lb_view=1/) || q_args.match(/fn=/))) ) )						{
						html+='<A href="javascript: return false;" onclick="lightbox_delete_image_enl(\'' + myid + '\'); return false;" class="iconlink" TITLE="Remove this image from the lightbox">X</A>';
					}

					html += '<a href="javascript: return false;" ONCLICK="lightbox_addto(\'' + myid + '\'); return false;" class="iconlink" title="Add to your current lightbox">LB+</a>';
					if(gsession){html += '<a href="javascript: return false;" ONCLICK="cart_addto(\'' + myid + '\'); return false;" class="iconlink" title="Add this image to your shopping cart">CART+</a>';}
					html += '<a href="javascript: return false;" ONCLICK="return price_image(\'' + myid + '\',\''+myrmrftype+'\');" class="iconlink" Title="Price Image">$</a>';
					if (! thisisacoverimage_feature)
						html += '<a href="javascript: return false;" ONCLICK="enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\'); return false;" class="iconlink" title="Enlarge image and more info"><font class=eye>i</font></a>&nbsp;';

					if(typeof(gusert) != 'undefined' && gusert =='IPN'){
						html += '<A href="javascript: return false;" onclick="ajax_TEXT(\'/bin/KeywordAdjust?good=1&id=' + myid + '&q=' + dsplkys + '\',getpost); return false;"><IMG src=/graphics/rating_enhance.gif width=18 height=12 border=0 style="margin-bottom: -3px;"></a><A href="javascript: return false;" onclick="ajax_TEXT(\'/bin/KeywordAdjust?bad=1&id=' + myid + '&q=' + dsplkys + '\',getpost); return false;"><IMG src=/graphics/rating_discourage.gif width=18 border=0 height=12 style="margin-bottom: -3px;"></a>';
					}
					 
					html += '</div><div><font class=imid>' + displayid + '</font>';
					if(typeof(suppressrmrftype) == 'undefined'){
						html += '  <font class=rmrfindicator>'+rm[showid]+'</font>';
					}
					html +='</DIV></font>';

					if (myhrdlink)
	                                        html += '<a href="'+myhrdlink+'" class="hiresdl_link"><font color="#cc0000">Download Hires</font></a>';


					html += '</DIV></SPAN>';
		
			
				} else {			
					html += '<span valign=bottom style="float:left;">';
					html += '<div id="d' + myid + '" align=center valign=bottom style="width:152px; height:' + theight + 'px; overflow: hidden;">';
					html += writesimilar(myid,showid,myphotographer,myshortcaption,'start','normal', myhrdlink, myreleased);

					html += '</DIV></SPAN>';
				}

			}
		}
	} 
	return html;
 };

 function initShareRadios(){ //runs with imageProfile -- need to use shsync to remember radio values in javascript..
        for(var cnt = showstartnumber_trap; cnt < endnumber; cnt++)
        {
                var sharesync = unescape(shsync[cnt]);
                sharesync=sharesync.split('|');
		var full_status = sharesync[0] + $F('share_control_view') + $F("share_control_home_sphotog");
		//combined control uses some combo of n,h,r,p,a,1,2,3,4 and are always allnet view, so less scope info needed
		// shsync codes are notshared,hold,rejected,pending,shared

		var comb_status,comb_weight;
		if ( typeof(cocon) == 'object' && cocon[0] )
		{
			comb_weight = sharesync[2];
			comb_status = sharesync[0].toString().substring(0,1);
		}
                var sForm = $('shf'+id[cnt]);
		if (sForm)
                    $A(sForm.elements).each( function(rad) {
                        if ( rad.value == full_status )  //full status goes first
                                rad.checked = true;
			else if ( comb_status && ( rad.value == comb_status || ( comb_status == 's' && rad.value == comb_weight ) ) )
				rad.checked = true;
                        else
                                rad.checked = false;
                    });

        }
 };

 function createDisplayPanel() {  //so functions requiring the display panel can call 1 func to generate it as needed
	if ( $('displaypanellayer') )
		return;
	var dp = document.createElement('div');
	dp.setAttribute('id', 'displaypanellayer');
	document.body.appendChild(dp);
 };

 function createCoverLayer() {  //so functions requiring the display panel can call 1 func to generate it as needed
	if ( $('coverlayer') )
		return;
	var dp = document.createElement('div');
	dp.setAttribute('id', 'coverlayer');
	document.body.appendChild(dp);
 };

 function showDisplayPanel(){
	createDisplayPanel();

	$('displaypanellayer').style.zIndex = '9991001';
	$('displaypanellayer').style.visibility="visible";
	//new Effect.Opacity('displaypanellayer',{duration: 0.01, from: 0.07, to: 1 });
	new Effect.Appear('displaypanellayer', {duration: 0.5})

	setTimeout("divshim(1);", 200);
 };

 function buildPagination(startnumber,endnumber,snum){					//builds pulldown menu for page numbers depending on pixperpage and total pagenumbers
	suspendtrap=1;
	//pagenumbers
	var thehtml = '';
	var prevactive='';
	var prev_link_html = '';
	var next_link_html = '';
	var nextlink_toporbottom = '';
	var showstartnumber = parseInt(startnumber) + parseInt(snum) + 1;
	var showendnumber = parseInt(endnumber) + parseInt(snum);
	var pagehtml = '';
	//conditional previous page
	if(Number(currentpagenum) > 0){
		prevactive='active';
		prev_link_html+= Templates.results_prev_link.evaluate({'prevactive': prevactive});
	} else if (showstartnumber <= results_total){
		prevactive='inactive';
		prev_link_html+= Templates.results_prev_link.evaluate({'prevactive': prevactive});
	}
	if(grange != "outofrange"){
		nextlink_toporbottom='top';
		next_link_html=Templates.results_next_link.evaluate({'nextlink_toporbottom':nextlink_toporbottom});
	}

	if ( showstartnumber <= results_total ){
		totalpages=(  Math.ceil((snum)/( parseInt( $F('pixperpage') ))) +  Math.ceil( (results_total - snum) / ( parseInt( $F('pixperpage') )  ))) ;
		if(Number(currentpagenum) > 52){psn = (Number(currentpagenum) - 50);} else { psn = 1;}
	
		if((Number(totalpages) - Number(currentpagenum)) > 50){ pen = (Number(currentpagenum) + 50);} else {pen = totalpages;}
		if(psn >1 && currentpagenum != 0){
			thehtml+='<OPTION VALUE="' + nextlink + 'snum=' + ((psn - 2) * (parseInt(gpixperpagev))) + '">&lt; ' + (Number(psn) - 1) + '</option>';
		}
	
		for(i=psn;i <= pen;i++){
			if(i == (Number(currentpagenum) + 1)){
				thehtml+='<OPTION VALUE="' + nextlink + 'snum=' + ((i-1) * (parseInt(gpixperpagev))) + '" SELECTED>' + i + '</option>';
			} else {
				thehtml+='<OPTION VALUE="' + nextlink + 'snum=' + ((i-1) * (parseInt(gpixperpagev))) + '">' + i + '</option>';
			}
		}
	
		if(pen != totalpages){
			thehtml+='<OPTION VALUE="' + nextlink + 'snum=' + ((Number(pen)) * (parseInt(gpixperpagev))) + '">&gt; ' + (Number(pen) + 1) + '</option>';
		}

		thehtml+='</select>';
		
		thehtml += '&nbsp;&nbsp;[' + showstartnumber + '-';
		if (showendnumber > parseInt(results_total)){
			thehtml +=  '<span id="lastpgtotal">' + results_total + '</span>' + ']&nbsp;of&nbsp;<span id="imgtotal">' + results_total + '</span>';
		} else {
			thehtml += showendnumber + ']&nbsp;of&nbsp;<span id="imgtotal">' + results_total + '</span>';
		}


		//linkback to feature:
		if (document.thisIsFeatureView){
			thehtml += Templates.results_requests_viewimagesfrom.evaluate({'feat_requestview':feat_requestview});
		}

		if (typeof(shsync) == 'object' && shsync[0] && shsync[0] != ''){
			var lochtml = Templates.results_editing_save_all_releases.evaluate({});
			$('Layerpreviews').innerHTML = lochtml;
		}
		pagehtml=Templates.results_gotopage_form.evaluate({'showstartnumber':showstartnumber,'results_total':results_total,'thehtml':thehtml});

	}


	$('Layerpages').style.overflow = 'visible';
	MM_setTextOfLayer('Layerpages','',Templates.results_pagination.evaluate({'pagehtml':pagehtml,'next_link_html':next_link_html,'prev_link_html':prev_link_html}));
 };

 function divShim (twid) { //simply to have it set-timeoutable..
	if(typeof($) == 'function' && $('DivShim'))//site that has the popup fix for IE6 and below (it can't render form elements behind dom objects)
	{
		if (twid) //on
		{
			createDisplayPanel();
			$('DivShim').style.width = $('displaypanellayer').style.width;
			$('DivShim').style.height = $('displaypanellayer').style.height;
			$('DivShim').style.top = $('displaypanellayer').style.top;
			$('DivShim').style.left = $('displaypanellayer').style.left;
			$('DivShim').style.zIndex = $('displaypanellayer').style.zIndex - 1;
			$('DivShim').style.display = "block";
		}
		else
		{
			$('DivShim').style.display = "none";
		}
	}
 };

 function hideDisplayPanel(mode){

	createCoverLayer();
	divshim(0);
	createDisplayPanel();

	if($('displaypanellayer').style && $('displaypanellayer').style.visibility == 'visible'){
		if(mode==1){
			new Effect.Fade('displaypanellayer', {duration: 0.01})			
		} else {
			new Effect.Fade('displaypanellayer', {duration: 0.3})
		}
	}
	if($('coverlayer').style && $('coverlayer').style.visibility == 'visible'){
		new Effect.Fade('coverlayer', {delay: 0.22, duration: 0.3, from: 0.7, to: 0});
		setTimeout("coveroff();",0.31);
	}
	setTimeout("$('displaypanellayer').style.visibility='hidden';", 0.31);
	
	Event.stopObserving(document, 'mousemove', getMouseXY);
 };

 function hideCoverLayer(){
	createCoverLayer();
	$('coverlayer').style.visibility="hidden";
 };

 // -> function so we only have to do this once.. option box is static...
 function html_share_con_opts(dex) {
        //return 'Status:&nbsp;&nbsp;<select class="editformelem" id="sharecontrol'+dex+'" name="sharecontrol'+dex+'" onchange="sos('+dex+',\'share\')" >'+ unescape(shcon[dex]) + '</select>';

        if(typeof(shcon) == 'object' && shcon[dex] && shcon[dex] != '')
		return '<form id="shf'+id[dex]+'"><span style="font-size:7pt"><NOBR>'+unescape(shcon[dex])+'</NOBR></span><input type="hidden" name="dexer" value="'+dex+'"/></form>';
        else
                return '';
 };

 function html_weight_con_opts(dex) {
	if(typeof(swcon) == 'object' && swcon[dex] && swcon[dex] != '')
                return 'Weight:&nbsp;<select class="editformelem" id="weightcontrol'+dex+'" name="weightcontrol'+dex+'" onchange="sos('+dex+',\'weight\')">'+ unescape(swcon[dex]) + '</select>';
        else
                return '';
 };

 function html_combined_con_opts(dex) {
        if(typeof(cocon) == 'object' && cocon[dex] && cocon[dex] != '')
	{
		return '<form id="shf'+id[dex]+'"><span style="font-size:7pt"><NOBR>'+unescape(cocon[dex])+'</NOBR></span><input type="hidden" name="dexer" value="'+dex+'"/></form>';
	}
	else
		return '';
 };

 function dispatchBuildImages(args) {

	var MacIE5 = global.macIE5;
	var startnumber = args['snum'];
	var mode = args['buildmode'];
	var resized = args['resized'];
	viewmode = args['viewmode'];
	$('Layer1').style.height = winH +'px';
	$('Layer1').style.overflow = 'hidden';

	if($('cdheader')){
		(typeof(dsplkys) != 'undefined' ? ( ( dsplkys.substring(0,6)=='BLDVCD' || dsplkys.match(/ZRFCD$/) ) ? $('cdheader').style.display = 'block' : $('cdheader').style.display = 'none')             : $('cdheader').style.display = 'block' );
	}

	document.currentLayer1Mode='searchresults';
	createCoverLayer();
	if(!MacIE5){var tshown = Element.getOpacity('coverlayer');}
	
	if(tshown > 0.2){
		hidedisplaypanel();
	}
	suspendcheck=1;
	//calculate how many images can be held on the page depending on mode being used
	if(startnumber > 1 || resized==1){setuppagesize();}
	
	//  build the page
	showstartnumber_trap = parseInt(startnumber);  //save for later
	var thehtml=optimize(); // + '<FORM name=activedisplay action=#>';
	grange="legal";
	var results_loading_interstitial_whatisloading='';
	MM_setTextOfLayer('Layer1','',	Templates.results_loading_interstitial.evaluate({'results_loading_interstitial_whatisloading':results_loading_interstitial_whatisloading})	);
	var cnt=startnumber;
	//figureout current range of images to show
	firstpictureonpage=startnumber;
	endnumber = parseInt(gpixperpagev) + parseInt(startnumber);

        if (viewmode != "ss"){
			//loop through images in the array and build html
			if(pagetype=='lb' && (typeof(pre_q_args) != 'undefined' && ! ( pre_q_args.match(/lb_view=1/) || pre_q_args.match(/fn=/) || pre_q_args.match(/vmo=/) ) ) ){
				thehtml += Templates.enlarge2_lb_backtoresults.evaluate({'viewmode':viewmode,'pre_q_args': pre_q_args });
			}
			while(cnt < endnumber) {
				if( id[cnt] ){
					if ( typeof(htmlit_custom) == 'function' )  {
						thehtml += htmlit_custom(cnt);
					} else {
						 thehtml += htmlit(cnt);
					}
				} else if((snum + cnt)>=results_total){
					if (grange != "outofrange"){
						var endtype='';
						if(pagetype=='lb'){
							endtype='lightbox';	
						} else {
							endtype='search';	
						}
						thehtml +=Templates.results_endofrange.evaluate({'endtype':endtype});
					}
		
					grange="outofrange";
		
				} else {
					grange="illegalpage";   //check to see if page numbers are out of the legal range of images
				}
				cnt++;
			} 
			
			if (snum + cnt == results_total){
				grange = 'outofrange';  //basically we have exactly enough images, 
										//so we want to skip adding the nextlink and the [ end of results ] cell
			}
		   //conditions below are for going ahead or behind available imagenumber ranges
			if (grange == "illegalpage"){
				if (mode == "next"){
					var next_snum = ( Number(snum) + Number(startnumber) );
					var section = $H({ showstart:1, snum:0, viewmode:viewmode, resized:resized }).toJSON();
					self.location= nextlink + 'snum=' + next_snum + '#nav='+section; //figure out which should be first picture on next page
					var results_loading_interstitial_whatisloading='next group of results';
					MM_setTextOfLayer('Layer1','',Templates.results_loading_interstitial.evaluate({'results_loading_interstitial_whatisloading': results_loading_interstitial_whatisloading}));
			} else {			
				
				// method b is two screens at a time
				prevtogoto=Number(snum) + Number(startnumber) - parseInt($F('pixperpage')); // go back two pages from start page
				//gsetCookie("gwhichstartpage",parseInt($F('pixperpage')), '', '/', gGetCookieDom());
				// ensure no negative numbers
				if(prevtogoto < 0 ){ 
					prevtogoto=0;
				}
				var section = $H({ showstart:1, snum:0, viewmode:viewmode, resized:resized }).toJSON();
				self.location=nextlink + 'snum=' + prevtogoto + '#nav='+section;
				
			}

		} else {

			//normal page ranges - add lower right next page link
			//thehtml+='</FORM>';
			MM_setTextOfLayer('Layer1','',thehtml);
			if (shsync[0]){
				setTimeout('init_share_radios()', 1);
			}
			
			var results_prev_link='';var results_next_link = '';
			if ((typeof(snum) != 'undefined' && Number(snum) > 1) || ( typeof(startnumber) != 'undefined' && Number(startnumber) > 1)){
					results_prev_link = Templates.results_prev_link.evaluate({'prevactive':'active','prevlink_toporbottom':'bottom'});
			}
			if (grange != "outofrange"){
				results_next_link=Templates.results_next_link.evaluate({'nextactive':'active','nextlink_toporbottom':'bottom'});
			}
			var tempfooter=footer();

			$('pagingrow').innerHTML = Templates.results_bottom_paging_row.evaluate({'results_prev_link':results_prev_link,'footer':tempfooter,'results_next_link': results_next_link});
			// preload next page worth of images
			lastimage=cnt;
			if($('pixperpage')){
				prestart = endnumber - 1;
				preend=(lastimage + parseInt($F('pixperpage')));
				if(startnumber==0){
					var delay=6000 + parseInt($F('pixperpage') * 30);
					 self.setTimeout("preloadnextpage()",delay);
				} else {
					var delay=1000;//delay just a bit to make several next page load requests have time to catch up
					self.setTimeout("preloadnextpage()",delay);
				}
			}
		}
	} else {
		//ss mode
		enlarge2(id[0],0); // new page and slideshow mode
	}
	currentpagenum = Math.ceil(         (      Number(snum) + Number(startnumber)         ) /      parseInt($F('pixperpage'))            );
	buildpages(startnumber,endnumber,snum);
	iconstatus();
 };

 function getFooter(){
	if (typeof(customfooter) != 'undefined')
		return customfooter;
	else
		return Templates.footer__body.evaluate({currentyear: currentYear});
 };

};
function afImage() {

 this.buildImages = buildImages;
 this.priceImage = priceImage;
 this.sizeImageToContainer = sizeImageToContainer;
 this.preloadNextImage = preloadNextImage;
 this.price_image_act = price_image_act;
 this.preLoadImage = preLoadImage;
 this.twidleImagePrice = twidleImagePrice;
 this.twidlePriceImagedelay = twidlePriceImagedelay;

 function sizeImageToContainer(targetid, thar) {
	if (! targetid || ! thar || ! $(targetid))
	return;

	var dems = Element.getDimensions(targetid);

	if (thar.style)
	{
		thar.style.width = (dems['width']+8) + 'px';	
 		thar.style.height = (dems['height']+8) + 'px';
	}
	return 1;
 };

 function priceImage(pid,ttype){
	if (! pid || ! pid.match(/^[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]?$/))  //did this longhand (instead of w/ curly brackets) b/c
		return false;							   //it screws up the compressors otherwise

	//get image info to retrieve pricing tier
	var url = '/AjaxHandlers/ImageInfo/'+ pid + '.json';
	ajax_JSON( url, 'POST', null ); 

	price_image_act(pid, 0, 0);
	return false;
 };

 function price_image_act(pid, tryCtr, force){
	if ( document.ajaxLoaded || force )
	{
		var supst = ( document.JSONobj.getImgDat('tier') || '' );
		launchwin('/bin/Rates?ln='+pid+'&calc_only=1&supst='+supst);	
	}
	else if ( tryCtr < 5 ) 
	{
		tryCtr++;
		setTimeout("price_image_act('"+pid+"','"+tryCtr+"', 0 )", 500);
	}
	else // nothing loaded, pop the page w/ missing data..
	{
		tryCtr++;
		price_image_act(pid,tryCtr,1);
	}
	return;
 };


 function preLoadImage(prid,crop){
	try{
	if (! $("pimid")){
		var pimid_div = document.createElement('div');
		pimid_div.setAttribute('id','pimid');
		//document.body.appendChild('<div id=pimid></div>');
		document.body.appendChild(pimid_div);
	}
	var th='';
	if(winH < 450){
		smallscreen=1;
		if(typeof(crop)!= 'undefined'){//smallscreen using orientation to decide limiter
			if(crop=='panoramic'){
				th='width=420';
			} else if(crop=='vertical'){
				th='height='+((winH - 100) < 180) ? 180 : (winH - 100);
			} else {
				th='height='+((winH - 142) < 160) ? 160 : (winH - 142);
			}
		} else {
			th='height=190';
		}
	} else {
		smallscreen=0;
	}
	$("pimid").innerHTML = '';
	$('pimid').style.visibility="hidden";
	var theNode = Templates.preview_window.evaluate({'prid':prid,'alt':phrase.preview_loading_alt,'dynimagesname':dynimagesname,'sizeoption':th});
	$("pimid").innerHTML = theNode;
	//$("pimid").appendChild(theNode);
	
	/* IE requires that the onload function be defined before the src is defined.
        else IE renders the src before calling the onload function and the onload function
        never gets called. 
        */

        var imgDiv = new Image();
        imgDiv.onload =  function(e) { if($('previewimg_'+prid)){
                                                $('previewimg_'+prid).src = this.src;
                                        }
                                };
	imgDiv.src = ImageUrl('420/60',prid);
        imgDiv.style.display = 'none';

        $('previewpane_metdat_'+prid).appendChild(imgDiv);



	}catch(e){}
	
 };

 function twidleImagePrice(selId, type, price) {
	setTimeout("twidle_price_img_delay("+selId+", '"+type+"', '"+price+"')", 10);
	return false;
 };

 function twidlePriceImagedelay(selId, type, price) {
        var docold = 'lic'+selId;

	if (document[docold].loaded == 'true')
		return;
        if(type == 'RF'){
		var thyimg = new Image();
		thyimg.src = '/graphics/specify_filesize.gif';
                document[docold].src=thyimg.src;
        }

        if(price == '$ 0.00'){
        } else {
		var thyimg = new Image();
		thyimg.src = '/graphics/ready_to_license.gif';
                document[docold].src=thyimg.src;
        }
	document[docold].loaded = 'true';
	return true;
 };

 function buildImages(startnumber,mode,resized){
	if(typeof(cartview) != 'undefined' && cartview)
		return;

	if(typeof(id) == 'undefined')
		return;

        var showstartnumber = parseInt(startnumber) + parseInt(snum) + 1;
        var section = $H({ showstart:showstartnumber, snum:startnumber, viewmode:viewmode, buildmode:mode, resized:resized }).toJSON();
        try { YAHOO.util.History.navigate("nav", section); } catch (e) { dispatchAll(section); }
 };


 function preloadNextImage(){
        preloadcurrent++;
        // preload till the next page's images are loaded and stop preloading if next page is clicked
        if(preloadcurrent < preend && endnumber < preend){
                objImage = new Image();
		Event.observe(objImage, 'load', function() { setTimeout("preloadnextimg();",10) });
                objImage.src=ImageUrl('135/50',id[preloadcurrent]);
        }
 };



};
function afInfo() {

 this.enlarge2 = enlarge2;
 this.dispatchEnlarge2 = dispatchEnlarge2;
 this.enlarge2_act__generateTierRows = enlarge2_act__generateTierRows;
 this.enlarge2_act = enlarge2_act;
 this.preloadImages = preloadImages;
 this.setTextOfLayer = setTextOfLayer;

 function enlarge2 (enid,encount,featuredimage,nocache) { //ajax calls to data for detail/enlarged view of image
		var section = $H({ ssid:enid, ssdex:encount, fimg:featuredimage, nc:nocache, showstart:'ss', snum:firstpictureonpage, viewmode:'ss' }).toJSON();
                try { YAHOO.util.History.navigate("nav", section); } catch (e) { dispatchAll(section); }
 };

 function dispatchEnlarge2 ( args ) {
	if ( typeof(args) != 'object' )
		return;

	var enid = args['ssid'];
	var encount = args['ssdex'];
	var featuredimage = args['fimg'];
	var nocache = args['nc'];
	

	var previousMode = document.currentLayer1Mode;
	document.currentLayer1Mode = 'enlarge';
	var url = '/AjaxHandlers/ImageInfo/'+ 
		( featuredimage ? featuredimage : enid )+
		'.json';
	var drk = '';
	if (nocache)
        	drk = '&drk='+Math.random(10);

	ajax_JSON( url, getpost, "callback=enlarge2_act('"+enid+"','"+encount+"','"+(featuredimage?featuredimage:'')+"','"+previousMode+"')"+drk ); 
	setuppagesize();
	$('Layer1').style.height = truevertHeight + 'px';
        //have to anticipate the header going away when we enlarge..
        var headermod = 0;
        if ( $('cdheader') && $('cdheader').style.display == 'block' )
                headermod = 146;
        $('Layer1').style.height = truevertHeight + headermod + 'px';
 };

 function enlarge2_act__generateTierRows(myratetiers_data,myrmrftype,enid,encount) {
	var myratetiers = '';
        if ( myrmrftype == 'RF' || myrmrftype == 'MS')
        {
                var tieredimgpricing__rfslug_row = '';
                $A(myratetiers_data.tierinfo).each(function(rowi){
                                        Object.extend(rowi,  {
                                                enlargetid: myratetiers_data.image_id,
                                                usage: rowi.subof,
						img_id: enid,
						encount: ( encount ? encount : "''" )
                                        });
                                        tieredimgpricing__rfslug_row += Templates.tieredimgpricing__rfslug_row.evaluate(rowi);
                        });
                myratetiers = Templates.tieredimgpricing__rfslug.evaluate({ 'rows' : tieredimgpricing__rfslug_row });
        }
        else if ( myrmrftype == 'RR' )
        {
                var tieredimgpricing__rrslug_row = '';
                $A(myratetiers_data.tierinfo).each(function(rowi){
                                        Object.extend(rowi, {
                                                enlargetid: myratetiers_data.image_id,
                                                usage: rowi.subof,
						img_id: enid,
						encount: ( encount ? encount : "''" )
                                        });
                                        //if image is priced out, then include remove button..
                                        if (rowi.opt_selected == 1)
                                                rowi.removebutton = Templates.tieredimgpricing__rrslug_row_removebutton.evaluate(rowi);

                                        tieredimgpricing__rrslug_row += Templates.tieredimgpricing__rrslug_row.evaluate(rowi);
                        });
                myratetiers = Templates.tieredimgpricing__rrslug.evaluate({ 'rows' : tieredimgpricing__rrslug_row });
        }
	return myratetiers;
 }

 //CALLBACK ACTion for enlarge2
 function enlarge2_act(enid,encount,featuredimage,preMem) {
	featuredimage = ( featuredimage == 'undefined' ? '' : featuredimage );
	debug('featuredimage',featuredimage);
	hp();//ensure closure the preview window
	var useInPage = 0;
	if ( id[encount] == document.JSONobj.getImgDat('id') || featuredimage.length==10)
			useInPage = 1;
	debug('useInPage',useInPage);

	if (useInPage || ( document.ajaxLoaded && (enid.match( document.JSONobj.getImgDat('id') )) ) )//made it
	{
		//wipe viewmode cookie:
		if(typeof(viewmode) != 'undefined' && viewmode == 'ss')
			gsetCookie("gcurrentview",'', '', '/', gGetCookieDom());

//		if( featuredimage || preMem == 'cartview' || ( useInPage && id[encount] )
//		{
                        if($('cdheader'))
                        	$('cdheader').style.display = 'none';

			//init
			if ( (! document.thisIsFeatureView && useInPage && st[encount] && st[encount].length > 13) || overflowtype == 'hidden' )
				suspendtrap=1;
			//gSetBackpage();		
			if(firstpictureonpage)
				gsetCookie("gwhichstartpage",firstpictureonpage, '', '/', gGetCookieDom());
	
			//set metatdata variables
			var myshortcaption;
			var testshortcaption = document.JSONobj.getImgDat('short_caption');
			testshortcaption = (	testshortcaption	?  testshortcaption : "n/a");
			var testlongcaption = document.JSONobj.getImgDat('long_caption');
			testlongcaption = (	testlongcaption	?  testlongcaption : "n/a");
			if ( typeof(uselongcaption) != 'undefined' && testlongcaption != "n/a" ){
				if ( uselongcaption == 'useboth' ){
					if ( testshortcaption == "n/a" ){ //then just use long
						myshortcaption = testshortcaption;
					} else if(testlongcaption == "n/a" || testshortcaption == testlongcaption){
						myshortcaption = testshortcaption;
					} else {//build switcher			

						myshortcaption = Templates.enlarge2_short_and_long_caption_combo.evaluate({'testshortcaption':testshortcaption, 'testlongcaption':testlongcaption});

					}
				} else {
					myshortcaption = testlongcaption;
				}
			} else {
				myshortcaption = testshortcaption;
			}


			var myrmrftype = document.JSONobj.getImgDat('rmrftype');

			//var myratetiers = document.JSONobj.getImgDat('rfcdimgpricing'); //this is currently preformatted list from templates, could
			//be extended in ajaxhandlers to return a data obj if we need 
			//more granular data
			var myratetiers_data = document.JSONobj.getImgDat('tieredimgpricing'); //myratetiers is a data object now.. so build..
			var myratetiers = enlarge2_act__generateTierRows(myratetiers_data,myrmrftype,enid,encount);
						
			var myphotographer	= document.JSONobj.getImgDat('photographer') +
					((document.JSONobj.getImgDat('agent_name') && document.JSONobj.getImgDat('agent_name') != '') ? '&nbsp;/&nbsp;'+document.JSONobj.getImgDat('agent_name') : '' );
			var myfilesize = (	document.JSONobj.getImgDat('file_size') < 5 ? 'Scan on Demand' : document.JSONobj.getImgDat('file_size') + ' Mb');	
			var myreleased = document.JSONobj.getImgDat('released');
			var myrestrictions = document.JSONobj.getImgDat('image_restrictions');
			var mycompallow = document.JSONobj.getImgDat('comp_allow');
			var mydimensions = ( typeof(showdimensions) != 'undefined' ? document.JSONobj.getImgDat('dimensions') : '');
			var dimensions_value='';
			if (mydimensions && mydimensions !='0' && mydimensions.indexOf('x')>1){ //comes as <XVAL>x<YVAL>
				var dimr = mydimensions.match(/^(\d+)x(\d+)$/);
				if (typeof(dimr) == 'object'){
					mydimensions = '<br/><b>Original Dimensions:</b>&nbsp;'+dimr[1]+'px&nbsp;x&nbsp;'+dimr[2]+'px';
				}
				dimensions_value=dimr[1]+'px&nbsp;x&nbsp;'+dimr[2]+'px';	
			}

			var dimensions_string = (dimensions_value != '' ? Templates.enlarge2_act__dimensions.evaluate({'dimensions_value':dimensions_value}) : '');

			var nextimage = parseInt(encount) + 1;
			var nextimageid = id[nextimage];
			var previmage = parseInt(encount) - 1;
			var previmageid = id[previmage];
			
			//this ifblock becomes template var: themediainsert
			var themediainsert = '';
			if((! document.thisIsFeatureView) && useInPage && v[encount] && (v[encount] == 'H')){
				var temph= + enid.substring(0,2) + '/' + enid.substring(0,5) + '/' + enid;
				themediainsert += '<EMBED SRC="/qtvideo/' + temph + '.MOV" WIDTH=420 HEIGHT=280></EMBED>';

			} else {
				var tarid = '0000000000';
				if(featuredimage){tarid = featuredimage;} else {tarid= enid;}
				debug('tarid',tarid);
				themediainsert += '<A HREF="" onclick="currentpage(); return false;">'
					+'<img src="' + ImageUrl('420/60',tarid) + '" border=1 style="display:inline; clear:none;" id="'+tarid+'">'
					+( (typeof(localwatermark) != 'undefined' && pngsupport) ?
						'<img style="z-index: 300; position:absolute; left:0px; bottom:0px;" src="'+localwatermark+'" border="0" onload="fitMeTo(\''+tarid+'\', this)"/>'
						:
						'');
				themediainsert += '</A>';
			}

			//similarscolumn
			var similarscolumn = '';
			if(! document.thisIsFeatureView && useInPage && st[encount] && st[encount].length > 13){
				var simlist =st[encount];
				var simarray=simlist.split(" ");
				var temparray = simarray[1].split(",");
				if(temparray.length > 1){temparray=simarray[0] + ' ' + temparray.join(' ');simarray=temparray.split(' ');}
				var simcount =simarray.length;
				if(simcount>40){simheight=(70 - simcount/2)} else {simheight=70 - simcount;}

				var simcolinfo = '';				
				for(var i=0;i< simcount;i++){
					simcolinfo += '<span valign=bottom style="float:left;">'
								+'<a href="javasc' + 'ript:enlarge2(\'' + enid + '\'' + ',' + '\'' + encount + '\',\'' + simarray[i] + '\');" TITLE="ID:' + simarray[i];
					if(showphotographer == 1)
						simcolinfo += '  \r&copy; ' + myphotographer;
						
					simcolinfo += ' click image to view similar"><img src="' + ImageUrl('135/50',simarray[i]) + '" border=0 vspace=2 hspace=2 height=' + simheight + ' align=left></a></span>';
				}
				similarscolumn = Templates.enlarge2_act__similars.evaluate({simcolinfo: simcolinfo});
			}
			
			


			//this ifblock becomes var navbacklink
			//will become navenlargedlinks
			var navenlargedlinks = '';
			var enlarge_navback_link = '';var enlarge_nextimage_link = '';var enlarge_previmage_link = '';
			var postprocessfunction=''
			var tcurrentLayer1Mode='searchresults';
			    if (preMem == 'cartview'){
					navbacklink = '<A HREF="" onclick="document.currentLayer1Mode=\'cartview\'; viewmode=\'' + viewmode + '\';gsetCookie(\'gviewmode\',\'' + viewmode + '\', \'\', \'/\', gGetCookieDom());currentpage(); return false;"><font style="font-size:9pt; font-family:Arial;">&#8593;</font> BACK TO CART</A><br /><br />';
					postprocessfunction='currentpage();';
					navbacklinktext = 'Back to Cart';
					tcurrentLayer1Mode='cartview';
			    } else if (document.thisIsFeatureView) {
					navbacklink = '<A HREF="" onclick="document.currentLayer1Mode=\'searchresults\'; viewmode=\'' + viewmode + '\';gsetCookie(\'gviewmode\',\'' + viewmode + '\', \'\', \'/\', gGetCookieDom()); self.location = self.location; return false;"><font style="font-size:9pt; font-family:Arial;">&#8593;</font> BACK TO REQUEST RESULTS</A><br /><br />';
					postprocessfunction='self.location = self.location;';
					navbacklinktext = 'Back to Request Results';
			    } else {
					navbacklink = '<A HREF="" onclick="document.currentLayer1Mode=\'searchresults\'; viewmode=\'' + viewmode + '\';gsetCookie(\'gviewmode\',\'' + viewmode + '\', \'\', \'/\', gGetCookieDom()); currentpage(); return false; "><font style="font-size:9pt; font-family:Arial;">&#8593;</font> BACK TO SEARCH RESULTS</A><br /><br />';
					postprocessfunction='currentpage();';
					navbacklinktext = 'Back to Search Results';
			    }
				if(typeof(Templates.enlarge2_act__navback_link) !='undefined'){
					enlarge_navback_link = Templates.enlarge2_act__navback_link.evaluate({'currentLayer1Mode': tcurrentLayer1Mode, 'viewmode': viewmode, 'postprocessfunction': postprocessfunction,'navbacklinktext': navbacklinktext});
				}
			if ( useInPage ){
			    if(preMem != 'cartview'){
					if((snum + encount) > 0){
						navenlargedlinks+= '<A HREF="" onclick="enlarge2(\'' + previmageid + '\',\'' + previmage + '\'); return false;" TITLE="GO TO THE PREVIOUS IMAGE"><font style="font-size:9pt; font-family: Arial;">&#8592;</font> PREV IMAGE </A>&nbsp;&nbsp;';
					}
					if((Number(snum) + Number(encount) + 1) < Number(results_total)){
						navenlargedlinks+= '<A HREF="" onclick="enlarge2(\'' + nextimageid + '\',\'' + nextimage + '\'); return false;" TITLE="GO TO THE NEXT IMAGE">NEXT IMAGE <font style="font-size:9pt; font-family: Arial;">&#8594;</font></A><br />';
					}
					if(typeof(Templates.enlarge2_act__nextimage_link) !='undefined'){
						enlarge_nextimage_link = Templates.enlarge2_act__nextimage_link.evaluate({'nextimageid':nextimageid, 'previmageid': previmageid, 'previmage': previmage, 'nextimage': nextimage});
					}
					if(typeof(Templates.enlarge2_act__previmage_link) !='undefined'){
						enlarge_previmage_link = Templates.enlarge2_act__previmage_link.evaluate({'nextimageid':nextimageid, 'previmageid': previmageid, 'previmage': previmage, 'nextimage': nextimage});
					}
			    }
			}

			var enlargetid = '';
			if(featuredimage){ enlargetid = featuredimage;} else { 	enlargetid = enid;}
			
			//will become downloadcomplink
			var downloadcomplink = '';
			var downloadcomp_key = '';
			var downloadcomp_link='';
			if(preMem != 'cartview')
			{
				if(typeof(Templates.enlarge2_act__complink) !='undefined'){
					var downloadcomp_username='';
					var downloadcomp_key=cs[encount];
					if(gsession && gusername && mycompallow == 'Y') { 
						downloadcomp_username=gusername;
					} else if(gsession){
						downloadcomp_username='guest';
					}
					var tdata = $H({enlargetid: enlargetid,
						downloadcomp_username: downloadcomp_username,
						downloadcomp_key: downloadcomp_key,
						enlargetid: enlargetid
					});
					downloadcomp_link=Templates.enlarge2_act__complink.evaluate(tdata);

				} else {
					if(gsession && gusername && mycompallow == 'Y') { 
						downloadcomplink = '<a href="Javascr' + 'ipt:displayWindow(\'/comp_view.shtml?' + gusername + '/' + cs[encount] + '/' +
						enlargetid
						+ '.JPG\',\'600\',\'640\');"><img src="/graphics/icon_comp.gif" width=21 height=15 alt="" border="0"> DOWNLOAD COMP</a><br /><br />';
					} else if(gsession) {
						downloadcomplink = '<a href="Javascr' + 'ipt:displayWindow(\'/comp_view.shtml?guest/' + cs[encount] + '/' +
						enlargetid			
						+ '.JPG\',\'600\',\'640\');"><img src="/graphics/icon_comp.gif" width=21 height=15 alt="" border="0"> DOWNLOAD COMP</a><br /><br />';
					}
				}
			}
	
			// META DATA FOR ENLARGED TARGET IMG:
	
			//will become: ratetierinfo
			var ratetierinfo = ( myratetiers ? '<div class="enlargeratetiers">' + myratetiers + '</div>' : '' );
			
			//becomes releaseinfo
			var releaseinfo = ( showrelease ? '<b>Release:</b> ' + myreleased + '<br />' : '' );
			var release_string = ( showrelease ? (myreleased != '' ? Templates.enlarge2_act__release.evaluate({'myreleased':myreleased}) : '') : '');
			
			//becomes photographerinfo
			var linked_photog = myphotographer;
			if(myphotographer.indexOf('/') > 0)
				linked_photog = linked_photog.substring(0, linked_photog.indexOf('/'));
			var photographerinfo = ( (myphotographer && showphotographer) ? '<b>Photographer:</b> <A href="/SwishSearch?Keywords=' + linked_photog + '&spec_idx=ne&method=photographer">' + myphotographer + '</a><br />' : '');
			var photographerinfo_string = ( (myphotographer && showphotographer) ? Templates.enlarge2_act__photographer.evaluate({'linked_photog':linked_photog,'myphotographer':myphotographer }) : '');
	
			//becomes filesizeinfo
			var filesizeinfo = ( (! featuredimage && showfilesize) ? '<b>File Size:</b> ' + myfilesize : '');
			var filesize_string = ( (! featuredimage && showfilesize) ? Templates.enlarge2_act__filesize.evaluate({'myfilesize':myfilesize}) : '');
			//becomes restrictionsinfo
			var restrictionsinfo = (myrestrictions ? '<BR/><span style="color:#990000">'+myrestrictions+'</span>' : '');
			var restrictions_string = (myrestrictions ? Templates.enlarge2_act__restrictions.evaluate({'myrestrictions':myrestrictions}) : '');
			
			//becomes keywordinfo
			var keywordinfo = '';
			var keywordinfoArray = new Array();
			document.JSONobj.getKeywords().each(function (kwd){
				var relink = q_args;
				//e.g. Keywords=shot%20put+haspeople+NOT+imagehasrestrictions
				if(relink.match(/Keywords=[^\+\&]+\+/))
				{
					relink = relink.replace(/Keywords=[^\+]+\+/, 'Keywords='+kwd+'+');
				}
				else if (relink.match(/Keywords=[^\+\&]+\&/))
				{
					relink = relink.replace(/Keywords=[^\+\&]+\&/, 'Keywords='+kwd+'&');
				}
				else if (relink.match(/Keywords=[^\+\&]+$/))
				{
					relink = relink.replace(/Keywords=[^\+\&]+$/, 'Keywords='+kwd);
				}
				else //might be lightbox or request, but so no actual keywords, so append it directly
				{
					relink = relink.replace(/((rid|\&rid)|(vmo|\&vmo)|(lb_view|\&lb_view)|(cartview|\&cartview))=[^\&]+/, '');
					relink = 'Keywords='+kwd+'&'+relink;
					relink = relink.replace(/\&+/, '&');
				}
				relink = relink.replace('&spec_idx=ne', '');
				keywordinfoArray.push('<a href="/SwishSearch?' + relink +'">' + kwd + '</a>');
			});

			keywordinfo = keywordinfoArray.join(', ');
			var displayenlargetid;
			if ( o[encount] ){displayenlargetid=o[encount];} else {displayenlargetid=enlargetid;}

			var dateshot = document.JSONobj.getImgDat('date_shot');
			var dateshot_string =  ((dateshot == '00-00-00') || (dateshot=='00-00-0000') || (dateshot=='0000-00-00') ? '' : Templates.enlarge2_act__dateshot.evaluate({'dateshot':dateshot}));
			var rfcdlinkslug = document.JSONobj.getImgDat('rfcdlink');
			var tempfooter=afHTMLObj.getFooter();			
 			var tdata = $H({
 				copyright_notice: tempfooter,
 				enlargetid: enlargetid,
				rfcdlinkslug: rfcdlinkslug,
				dateshot: dateshot,
				keywordinfo: keywordinfo,
				displayenlargetid: displayenlargetid,
				restrictionsinfo: restrictionsinfo,
				filesizeinfo: filesizeinfo,
				photographerinfo: photographerinfo,
				releaseinfo: releaseinfo,
				ratetierinfo: ratetierinfo,
				downloadcomplink: downloadcomplink,
				navenlargedlinks: navenlargedlinks,
				navbacklinks: navbacklink,
				similarscolumn: similarscolumn,
				themediainsert: themediainsert,
				rmrftype: myrmrftype,
				myshortcaption: myshortcaption,
				dimensions: mydimensions,
				restrictionsinfo: restrictionsinfo,
				
				dateshot_string: dateshot_string,
				restrictions_string: restrictions_string,
				restrictions_value: myrestrictions,
				filesize_value: myfilesize,
				filesize_string: filesize_string,
				photographerinfo_string: photographerinfo_string,
				photographer_value: myphotographer,
				release_string: release_string,
				release_value: myreleased,
				dimensions_string: dimensions_string,
				dimensions_value: dimensions_value,
				downloadcomp_link: downloadcomp_link,
				enlarge_navback_link: enlarge_navback_link,
				enlarge_nextimage_link: enlarge_nextimage_link,
				enlarge_previmage_link: enlarge_previmage_link
			});
			//write html for enlarge page
			$('Layer1').style.overflow = 'auto';
			$('Layerpages').innerHTML= ''; //erase the contents of the page since it doesn't matter here.
			MM_setTextOfLayer('Layer1','', Templates.enlarge2_act__body.evaluate(tdata));
			//auto-show keywords switch
			if(typeof(autoshowkeywords) != 'undefined'){
				setTimeout("popkeys2('enlarge_keywords','','enlarge_keywords_text');",500);
			}
			MM_preloadImages(ImageUrl('135/50', nextimageid));
		} 
		else {
			//alert("This is the last image of the search results.");
			gsetCookie('gviewmode','ss', '', '/', gGetCookieDom());

			self.location= nextlink + 'snum=' + (Number(firstpictureonpage) + Number(snum)); //figure out which should be first picture on next page	
		}//end if id[enid]	

 };

 function preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
 };

 function setTextOfLayer(objName,x,newText) { //v4.01
  var obj = $(objName)
  if (obj != null) 
  {
	//also clear sister 'pagingrow'
	if($('pagingrow') && document.currentLayer1Mode != 'searchresults')
		$('pagingrow').innerHTML = '';

	if (document.layers) {document.write(unescape(newText)); document.close();}
	else { obj.innerHTML = unescape(newText); }
  }
 };


};
function afInit() {

 this.init = init;
 this.handleBuilder = handleBuilder;
 function init() {

 var output;

 _prototype();                          // checks if it should include/load prototype framework
 _globals();                            // initializes various global variables
 _phrase();
 checkStatus();                        // checks some sort of status in Layer1 (need more info?) and alters global variable
 prepareEvents();                      // binds various checks to the window.onload event
 findBrowser();                        // determines user browser
 findOS();                             // determines user OS
 styleSheets();                        // determines proper stylesheets to include based on browser/OS
 checkGetPost();                       // double-checks if browser should be using GET or POST and alters global variable
 checkPNGSupport();                    // double-checks if browser supports PNG format and alters global variable
 handleSession({cartView : global.cartView,                  
                cartViewLocation : global.cartViewLocation,
                gSession : global.gSession,
                pageType : global.pageType,
                pre_q_args : global.preQArgs,
                q_args : global.qArgs
               });                                           // checks if session exists, if not bring to startpage
                                                             // otherwise it will set cookie and continue with script.

 pageTypeEvents({ pageType : global.pageType });             // binds various events based on pagetype
 handleBuilder({ Builder : global.builderClass,
                 cartPic : global.cartPic });                // in case a Builder object exists, handle it (not sure what it does)
 };

 function checkGetPost() {
   if (global.userBrowserName == 'Firefox')
       global.getPost = 'GET';
 };

 function checkPNGSupport() {

  if (global.userBrowserName == 'Explorer' && parseInt(global.userBrowserVersion) < 7)
      global.pngSupport = 0;

 };

 function checkStatus() {

  document.currentLayer1Mode = global.currentLayer1Mode;

  //enlarge shouldn't travel
  if( global.currentLayer1Mode == 'enlarge' ) {
        document.currentLayer1Mode = 'searchresults';
        global.currentLayer1Mode = 'searchresults';
    };
                                       //same thing but for the status of what is in Layer1 values are
                                       //"searchresults", "cartview", or "enlarge" defaults to
                                       //searchresults, as that is default page action

 };
/*
 function findData(data) {

  var place = 0;
  var info = '';

  for (x in data)
   {
    place = global.userAgentLowerCase.indexOf(x) + 1;
    if (place > 0)
     {
      info = data[x];
      break;
     };
   };

  return ({
           data : info,
           place : place
          });

 };
*/
function findData(data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	};
function findVersion(dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
};

 function findBrowser() {

var browsers = [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	];




  global.userBrowserName = findData(browsers) || "An unknown browser";
  global.userBrowserVersion = findVersion(navigator.userAgent) 
				|| findVersion(navigator.appVersion)
				|| "an unknown version";
 //alert(global.userBrowserName+" "+global.userBrowserVersion);	
//  global.userBrowserVersion = detect.charAt(browserData['place'] + x.length);

 };

 function findOS() {

var os = [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	];


  global.userOSName = findData(os) || "An unknown operating system";
 };

 function handleBuilder(args) {

  var Builder = args['Builder'];
  var cartEnabledPic = args['cartPic'];

  if( typeof(Builder) != 'undefined' )
   {
	global.nodeTree = $H({
         cart_build_act__buttons: 
		Builder.node('a', {href:'#',onclick:'lightbox_change(); return false;', title:phrase.cart_tab_switch_to_lb_title, id: 'tab_cart'}),
         cart_build_act__actions:  Builder.node('span', {}, [
			Builder.node('a', {href:'#', onclick:'cart_display(); return false;', className:'lblink', style:'text-decoration:none; cursor:pointer;'}, phrase.cart_view_cart_calc_fees_link),
			' | ',
			Builder.node('a', {href:'#', onclick:'cart_check(); return false;', className:'lblink', style:'text-decoration:none; cursor:pointer;'}, phrase.cart_checkout_link),
			( document.thisIsFeatureView ? ' | ' : '' ),
			( document.thisIsFeatureView ?
						Builder.node('a', {href:'#', className:'lblink', onclick:'$("LBdiv").style.visibility = "hidden"', style:'cursor:pointer;'}, phrase.cart_hide_cart_link) 
					:
					''
			)
	])
	});
   }
  return ({ nodeTree : global.nodeTree });
 };

 function handleSession(args) {
 
  var cartView = args['cartView'];
  var cartViewLocation = args['cartViewLocation'];
  var gsession = args['gSession'];
  var pagetype = args['pageType'];
  var pre_q_args = args['pre_q_args'];
  var q_args = args['q_args'];

  if(typeof(gsession) != 'undefined' && gsession)
   {
   if (cartView)
    {
     document.currentLbdivMode = 'cart';	
     document.currentLayer1Mode = 'cartview';
     global.currentMousedOverObject = 'shop_cart';
    }
	
   if ( (typeof(pagetype) != 'undefined' && pagetype=='lb') || (typeof(pre_q_args) != 'undefined' && ( pre_q_args.match(/lb_view=1/) || pre_q_args.match(/fn=/) )) || (typeof(q_args) != 'undefined' && ( q_args.match(/vmo=/) || q_args.match(/lb_view=1/) )) )
    {
     global.pageType = 'lb';
     gsetCookie('gwhichstartpage', '', '', '/', gGetCookieDom());
    }
  }
  else if (cartView)
  {
   top.location=cartViewLocation;
  };

  return ({currMousedOverObj : global.currentMousedOverObject,
           pagetype : global.pageType
         });

 }

 function pageTypeEvents(args) {

  var pageType = args['pageType'];

  if (typeof(pageType) != "undefined"){
   Event.observe(window, 'load', currentpage);
   Event.observe(window, 'resize', checkpageresize);
   Event.observe(window, 'click', hp);
  };
 
 };

 function prepareEvents() {

  // This is a Prototype framework specific piece of code (e.g. Event.observe)

  if (typeof(Event) != 'undefined' && typeof(Event.observe) == 'function')
   {
     //parse all commandline params into urlParams object, onload
     Event.observe(window, 'load', getVars);
     //set autosave cleanup
     Event.observe(window, 'load', function() {
                if (EAD('share_control_sphotog'))
                        nextlink += 'site='+$F('share_control_sphotog')+'&';
                if (EAD('share_control_status'))
                        nextlink += 'status_view='+$F('share_control_status')+'&';
                if (EAD('share_control_view'))
                        nextlink += 'view='+$F('share_control_view')+'&';
                if (EAD('share_control_release'))
                        nextlink += 'release_view='+$F('share_control_release')+'&';

     });
  };

 };

 function _prototype() {
  if (typeof($) != 'function')
	document.write('<script src="/javascripts/prototype.js" type="text/javascript"></script>');
 };

 function styleSheets() {
   var styleList = document.styleSheets;
   var styleSheetLoaded = false;

   for(i=0;i<styleList.length;i++){
        if(styleList[i].href != null && styleList[i].href.endsWith("/css/main2.css")){
                styleSheetLoaded = true;
        }
   }
   if(!styleSheetLoaded)
           document.write('<liNK rel="stylesheet" href="/css/main2.css" type="text/css">');

   if ((global.userBrowser == "IE" || global.userBrowserName == "Explorer") && (parseInt(global.userBrowserVersion) <5))
     document.write('<liNK rel="stylesheet" href="/css/fixed4ie.css" type="text/css">');

 };
};

function afLegal() {

 this.copyrightNotice = copyrightNotice;
 this.licenseCostWindow = licenseCostWindow;

 function copyrightNotice(){
    if($('copyright')){				
		if (typeof(customhovermessage) != 'undefined' && customhovermessage != '')
			$('copyright').innerHTML = customhovermessage;
		else
		 	$('copyright').innerHTML = Templates.hovercopyright__text.evaluate({
				currentyear: currentYear,
				baseurl: baseurl
			});
    }
 };

 //for CHECK USAGE RATES
 function licenseCostWindow(id) {
	launchwin('/bin/Rates?calc_only=1&usage=1&ln='+id);
 };

};
function afLightbox() {

 this.newLightbox = newLightbox;
 this.registerLightbox = registerLightbox;
 this.emailLightbox = emailLightbox;
 this.emailConfirmation = emailConfirmation;
 this.listLightbox = listLightbox;
 this.lightbox_mod_act = lightbox_mod_act;
 this.simpleMessage = simpleMessage;
 this.addLightboxToCart = addLightboxToCart;
 this.deleteLightbox = deleteLightbox;
 this.renameLightbox = renameLightbox;
 this.buildLightbox = buildLightbox;
 this.validateLightboxName = validateLightboxName;
 this.registerLightboxRename = registerLightboxRename;
 this.changeLightbox = changeLightbox;
 this.addImageToLightbox = addImageToLightbox;
 this.deleteLightboxFromEnlargeView = deleteLightboxFromEnlargeView;
 this.deleteImageFromLightbox = deleteImageFromLightbox;
 this.toggleLightbox = toggleLightbox;
 this.makeLightboxString = makeLightboxString;
 this.refreshTopLightbox = refreshTopLightbox;
 this.saveLightbox = saveLightbox;
 this.switchList = switchList;

 function newLightbox(){ // show the panel to create a new lightbox
	center_panel(290,200,Templates.lightbox_new__body.evaluate());
 };

 function registerLightbox(){ // URL call to make the LB in the database 
	var lbn = '';
	if ($('lightbox_new_name'))
		lbn = $F('lightbox_new_name');	

	if( lbn.length ==0 || lbn.length > 100){
		 alert(phrase.lightbox_name_problem_alert);
		if (lbn)
			lbn='';
	} else {
		if(test_valid_name(lbn)){
			polllb();
			var lbs = make_lightbox_string(gusername,lbn,[{id:1}]);
			currentlbname = lbn;  //must set this to let mod_act know focus has changed
			simplemessage('creating your lightbox ' + lbn + ' <blink>.</blink>', '', 'LB');
			ajax_JSON('/AjaxHandlers/LightboxNew/' + lbs + '.json', getpost, null);
		} 
	}
 };

 function emailLightbox(){ // URL call to send lightbox by email
	var theurl='/bin/Mail';

	var prams = 'ot=2&dsm=1&to_email=' + $('to_email').value + '&mail_text=' + escape($('mail_text').value);
	if($('allow_hrdl') && $('allow_hrdl').checked == true){ prams += (typeof(emaillburladd) != 'undefined' ? emaillburladd : ''); };

	if($('bill_to_customer') && $('bill_to_customer').value.toString().length > 0)
		prams += '&customer_id='+$('bill_to_customer').value;

	if($('email_project') && $('email_project').value.toString().length > 0)
		prams += '&project='+$('email_project').value;

	if($('email_notes') && $('email_notes').value.toString().length > 0)
		prams += '&notes='+$('email_notes').value;
	
	if($('notify').checked == true){ prams +='&notify=1'}; 
	if($('readonly').checked == true){ prams +='&readonly=1'}; 
	ajax_TEXT(theurl+'?'+prams, 'GET');//fire and forget the call to actually make the send...
	simplemessage(phrase.lightbox_sending_message,0);
 };

 //call this after any ajax lightbox call..
 //to wait on response and build the new box from it
 function lightbox_mod_act (cruft){ 

	//console.log( currentLbdivMode );
	if ( currentLbdivMode == 'cart' )
		return false;
			
	var dover = 0;  
	if ( document.JSONobj && document.JSONobj.getLbDat('lbname') ) //otherwise  try again...
	{	
		var currentlb = document.JSONobj.getLbDat('lbname');
		if (currentlbname == currentlb || ! currentlbname)
		{
			hidedisplaypanel(1);
			var lbarray = document.JSONobj.getLbDat('lblist');
			//KEY: still using globals here for this.. (current active lb) although it gets passed first
			var lbl = document.JSONobj.getLbDat('lbnamelist');
			if (typeof(lbarray) != 'array' && typeof(lbarray) != 'object' || ! lbarray.length )
			{
				lbarray = new Array(1);
				lbarray[0] = { id:'1', rfcd: '' };
			}

			document.currentlbstash = lbarray;
			currentlbname = currentlb;	
			currentlblist = lbl;
			dover = 0;
			lightbox_build(lbarray, currentlb, '', lbl);
		}
		else
		{
			dover = 1;
		}
	}
	else
	{	
		dover = 1;
	}

	//people change lightboxes fast, so if you get an OBJ back, but it's not the one you want, 
	//or you got no OBJ at all then start over
	if (dover)
		setTimeout("lightbox_mod_act()", 500);
 };

 function simpleMessage(m,mode,trg){ // Shows transition messages to the LB frame or centered based on param input
	if(trg && $('LBdiv')){
		$('LBdiv').style.height = '100px';
		$('LBdiv').innerHTML = Templates.simplemessage__body_lightbox.evaluate({message: m});
	} else {
		createDisplayPanel();
		if($('displaypanellayer').style.left=='0px'){
			$('displaypanellayer').style.left=parseInt(winW - 200)/2 + 'px';
		}
		if($('displaypanellayer').style.top=='0px'){
			$('displaypanellayer').style.top=parseInt(winH - 100)/2 + 'px';
		}
		if($('displaypanellayer').style.visibility=='hidden'){
			$('displaypanellayer').style.visibility='visible';
		}
		$('displaypanellayer').innerHTML = Templates.simplemessage__body.evaluate({message: m});
	}
	if (!mode){setTimeout("hidedisplaypanel(1);",700);}
 };

 function emailConfirmation(mode){ // control for lightbox email state messages and menu
	if(mode=='sent'){
		simplemessage(phrase.lightbox_sent_message);
	} else if(mode=='close'){
		hidedisplaypanel(1);
	} else {
		var tdata = {	emaillbaddhtml: (typeof(emaillbaddhtml) != 'undefined' ? emaillbaddhtml : ' '),
				currentlbname: currentlbname};
		center_panel(390,280,Templates.lightbox_email__body.evaluate(tdata));
	}
 };

 function switchList(args){ // Displays content in textarea containing image ids - Milan Adamovsky
 
  var images = $('images').value.split(',');
  var origs = $('origs').value.split(',');
  
  var ipnIdCheck = $('ipn_id').checked;
  var origIdCheck = $('orig_id').checked;

  var retVal = '';

  for (var x = 0; x <= images.length - 1; x++)
   {
    if (ipnIdCheck)
     {
      retVal = retVal + images[x];
      if (origIdCheck)
       {
        retVal = retVal + ',';
       }
      else
       {
        retVal = retVal + '\n';
       }
     } 
    if (origIdCheck)
     {
      retVal = retVal + origs[x] + '\n';
     }
   }

  $('lightbox_images').value = retVal;
  

 };

 function listLightbox(args){ // Displays a list of images in a lightbox - Milan Adamovsky

  var mode = args.mode;
  var lb = args.lb;
  var user = args.user;

  if (mode=='close')
   {
    hidedisplaypanel(1);
   } 
  else 
   {
    var d = new Date();  // This overcomes doubleposting constraint in AJAX - Milan Adamovsky 06/28/2009 Mantis # 1157 
    ajax_JSON( '/bin/UserAdmin?lb_list=' + lb + '&user=' + user + '&noise=' + d.getTime(), 'GET', { 'callback' : function() { 

    var images = document.JSONobj.oJSON.images.image_id;
    var originals = document.JSONobj.oJSON.images.orig_id;
    var content = images.join('\n'); 
       
     var tdata = {
                  content: content,
                  images: images,
                  origs: originals,
                  currentlbname: lb
                 };

     center_panel(390,380,Templates.lightbox_list__body.evaluate(tdata),'',{'topX' : (self.innerWidth / 2) - (380 / 2) , 
                                                                            'topY' : (self.innerHeight / 2) - (390 / 2), 
                                                                            'static' : 1});

     }
    });
  }
 };


 function addLightboxToCart(){ 
	simplemessage('Adding lightbox images to Shopping Cart <blink>.</blink>','','LB');
	ajax_JSON('/AjaxHandlers/CartLbAdd/0000000000.json', 'POST', 'callback=cart_mod_act(0)');
 };

 function deleteLightbox(){ 
	simplemessage('Deleting your current lightbox ' + currentlbname,'','LB');
	var mobid = ((typeof(mobject_id) != 'undefined' && mobject_id != '') ? 'mob='+mobject_id : '');	
        var lbs = make_lightbox_string(gusername,currentlbname);
	currentlbname='';  
        ajax_JSON('/AjaxHandlers/LightboxDelete/' + lbs + '.json', getpost, mobid);
 };

 function renameLightbox(){
	var tdata = { currentlbname: currentlbname };
	center_panel(290,200, Templates.lightbox_rename__body.evaluate(tdata));
 };

 function buildLightbox(tlba,lname,secr,lbl){ // major code to build the lightbox area
	if(cartview && carnit)
	{
		carnit = 0;
		document.currentlbstash=tlba;
		cart_build('changing');//preempt initial lightbox build if we've been asked to go direct to cart.
		//cart_display();
		return;
	}

	hidedisplaypanel(1)	// clears the message that was saying loading lightbox or any other transition messages

	//I got called but there is no lightbox data anywhere
	if(typeof(tlba) != 'object' && typeof(document.currentlbstash) == 'undefined') 
		return;
	else if(typeof(document.currentlbstash) == 'object' && typeof(tlba) != 'object' )
		tlba=document.currentlbstash;

	currentLbdivMode = 'lightbox';
	
	if(lname)  // called from the LBframe results routine otherwise, usually we don't need to change lb just rebuild it
		currentlbname=lname;
	
	if(lbl)
		currentlblist=lbl.split('|');
	
	if(secr)
		scr=secr; // secret auth tag passed from server to prevent from an open lightbox security vulnerability

	var lbdPos = $('LBdiv') ? Position.cumulativeOffset($('LBdiv')) : [0,0];

	var lbbgH = winH - lbdPos[1] - 18; //18 being height of lbbuttons	

	document.currentlbstash=tlba;
	
	if($('LBdiv'))
	{
		// acts as the root node.. logical analog to the dom object they'll be apended to
		var thehtmlElements = $A([]); 
	
		thehtmlElements.push(  
		Builder.node('div', {id:'lbbuttons'},[
			Builder.node('a', {href:'javascript: return false;', onclick:"cart_build('changing'); return false;", title:phrase.lightbox_switch_to_cart_title, id:"tab_lightbox"})
		])	
		);
		
		var thehtmlLinkList = $A([]);
		if ( currentlblist && currentlblist.length > 0)
		{
			var hasplaceholder = 0;
			$A(tlba).each( function(lbItem) { if(lbItem.id == 1) hasplaceholder = 1; });
			var displen = ( hasplaceholder ? ( tlba.length - 1 ) : tlba.length );
						
			thehtmlLinkList.push(
			Builder.node('b', {}, currentlbname + phrase.lightbox_name_suffix),
			'  (' + displen + ')  ',
			Builder.node('b', {}, phrase.lightbox_changeto_text)
			);
	
			//build selects longhand.. IE bugs... of course
			var selFix = document.createElement('select');
			selFix.setAttribute('name','n');
			selFix.setAttribute('id','lightbox_menu');
			selFix.setAttribute('class','smallmenu');
			//double IEfix.. must set this programatically (implied eval w/ setAttribute fails in IE7)
			selFix.onchange = function () { lightbox_change(this.options[this.selectedIndex].value); };
			
			for(var i=0;i<currentlblist.length;i++){
				if (currentlblist[i] != '')
				{
					var theOpt;
					theOpt = document.createElement('option');
					theOpt.setAttribute('value', currentlblist[i]);
					theOpt.appendChild(document.createTextNode(currentlblist[i].substring(0,25) 
						+ (currentlblist[i].length > 25 ? '...' : '')));
	
					if(currentlblist[i]==currentlbname)
						theOpt.setAttribute('selected', 'selected');
	
					selFix.appendChild(theOpt);
				}
			}
	
			thehtmlLinkList.push(selFix);
		}
	
		var tlb1 = '';
		var tlb2 = '';
		var tlb3 = '';
		var tlb4 = '';
		var tlb5 = '';
		var tlb6 = '';
		var tlb7 = '';
		var tlb8 = '';
		var tlb9 = '';
		if(winW>832){
			tlb1 = phrase.lbmenu_new;//'New Lightbox'
			tlb2 = phrase.lbmenu_expanded;//'View Expanded Lightbox';
			tlb3 = phrase.lbmenu_email;//'Email Lightbox';
			tlb4 = phrase.lbmenu_add2cart;//'Add Lightbox to Cart';
			tlb5 = phrase.lbmenu_delete;//'Delete Lightbox';
			tlb6 = phrase.lbmenu_rename;//'Rename Lightbox';
			tlb7 = phrase.lbmenu_makefeature;//'Make LB a Feature';
			tlb8 = phrase.lbmenu_copytouser;//'Copy LB to User';
			tlb9 = phrase.lbmenu_resort;//'Resort LB';
		} else {
			tlb1 = phrase.lbmenu_new_s;//'New Lightbox'
			tlb2 = phrase.lbmenu_expanded_s;//'View Expanded Lightbox';
			tlb3 = phrase.lbmenu_email_s;//'Email Lightbox';
			tlb4 = phrase.lbmenu_add2cart_s;//'Add Lightbox to Cart';
			tlb5 = phrase.lbmenu_delete_s;//'Delete Lightbox';
			tlb6 = phrase.lbmenu_rename_s;//'Rename Lightbox';
			tlb7 = phrase.lbmenu_makefeature_s;//'Make LB a Feature';
			tlb8 = phrase.lbmenu_copytouser_s;//'Copy LB to User';
			tlb9 = phrase.lbmenu_resort_s;//'Resort LB';
		}
	
		thehtmlLinkList.push(
  		Builder.node( "a", { 'href': "javascript: return false;", 'class': "lblink", 'onclick': "lightbox_new(); return false;" }, tlb1),
		' | ',
  		Builder.node( "a", { 'href': "javascript: return false;", 'onclick':"var d = new Date(); d.setMinutes(d.getMinutes()+5); gsetCookie('gprewhichstartpage', showstartnumber_trap, d, '/', gGetCookieDom()); toplightboxrefresh(); return false;", 'class': "lblink"}, tlb2),
		' | ',
  		Builder.node( "a", { 'href': "javascript: return false;", 'class': "lblink", 'onclick':"lightbox_email(); return false;"}, tlb3),
		' | ',
  		Builder.node( "a", { 'href': "javascript: return false;", 'class': "lblink", 'onclick':"lightbox_add2cart(); return false;"}, tlb4),
		' | ',
  		Builder.node( "a", { 'href': "javascript: return false;", 'class': "lblink", 'onclick':"lightbox_delete(); return false;"}, tlb5),
		' | ',
  		Builder.node( "a", { 'href': "javascript: return false;", 'class': "lblink", 'onclick':"lightbox_rename(); return false;"}, tlb6) 	
		);
	
		if(typeof(makelightboxfeature) != 'undefined')
		{
			thehtmlLinkList.push(
   			' | ',
			Builder.node('a', {'href':'javascript: return false;', 'class':'lblink', 'onclick':"launchwin('"+makelightboxfeature + currentlbname+"', 'make feature', 500, 400, 100, 100); return false;"}, tlb7)
			);
		}
	
		if(typeof(copylightboxtouser) != 'undefined')
		{
			thehtmlLinkList.push(
   			' | ',
			Builder.node('a', {href:'javascript: return false;', 'class':'lblink', 'onclick':"launchwin('" + copylightboxtouser + "', 'copy_lightbox', 300, 300, 300, 400); return false;"},tlb8)
			);
		}

		if(typeof(enlargedlbsort) != 'undefined')
		{
                        thehtmlLinkList.push(
                        ' | ',
                        Builder.node('a', {href:'javascript: return false;', 'class':'lblink', 'onclick':"if(pagetype=='lb') { center_panel(390,120, '<div style=\"background:#F7E6A9;height:120px;font-size:6pt;text-align:center;padding:20px 10px 0 10px;\"><br/><h1>Your display will be refreshed once you close the Lightbox Sort popup window.</h1></div>'); } launchwin('" + enlargedlbsort + currentlbname + "', 'resort_lightbox', 450, 750, 200, 300); return false;"},tlb9)
                        );

		}

//	        if (viewmode == 'editing')
//		{
			thehtmlLinkList.push(
			' | ',
       			Builder.node('a', {'href':'javascript: return false;', 'class':"lblink", 'onclick':"showhideLB(); return false;", style:"cursor:pointer"},phrase.lightbox_minimize_link)
			);
//		}

		var lbdisplaymode_style = 'block';
	      	if ( lbdisplaymode && viewmode == 'editing')
	        {
	                lbdisplaymode_style = 'none';
	        }
		
		thehtmlElements.push( 
		Builder.node('div', {'id':'lblinks','class':'lbname lbscroll', 'style':'overflow: auto; overflow-y:hidden'},[
			Builder.node('nobr', {}, thehtmlLinkList)
		])
		);
		
		var thehtmlLightboxStrip = $A([]);
		
		var heightOfLbDiv = 30;
		if(tlba.length>0){

			if ( lbdisplaymode_style == 'block')
				heightOfLbDiv = 130;
			else if (lbdisplaymode_style == 'none')
				heightOfLbDiv = 40;

			var scrollins = 'hidden';
			var perrow = parseInt(winW / 79);
			var wishwidth = '100%';
			if ( perrow < tlba.length )
			{
				scrollins = 'scroll';
				wishwidth = 79 * tlba.length;
				wishwidth = wishwidth + 'px';
			}
	
			
			var tofit=50;
			if(truevertHeight < 340){vlim=25;} else if(truevertHeight < 450){vlim=35;} else {vlim=58;}
			for (lbi=0;lbi<tlba.length;lbi++){
				if (tlba[lbi].id == '')
					continue;
	
				lbid=tlba[lbi].id;
				
				if ((lbid == 1 && tlba.length < 2) || lbid != 1){ // hide image 1 from view unless new box...
					var lbLinkArgs = { 'className':'lblink lblinkPreviewImage', 'title':phrase.lbstrip_enlarge_title };
					var lbImgLinkArgs = { 'id': 'dlb'+lbi+'s_lbi' };
                    if (tlba[lbi].rfcd && tlba[lbi].rfcd.toString().length) //myid is in the info for the link, hence this is the cover image
						{
                     	var pm = unescape(tlba[lbi].rfcd.toString()).match(/SwishSearch\?n\=1\&fn\=(.*)\&supst\=cd/);
		             	if(pm != null)
						{
	            			var thisisacoverimage_feature = pm[1];
                            lbLinkArgs.href = '/SwishSearch?n=1&fn='+thisisacoverimage_feature+'&supst=cd';
                            lbImgLinkArgs.href = '/SwishSearch?n=1&fn='+thisisacoverimage_feature+'&supst=cd';
						}
                    } else {
                        lbLinkArgs.href = 'javascript: return false;';
						lbLinkArgs['onclick'] = "hp(); enlarge2('" + lbid + "','" + lbi + "'); return false;";
                        lbImgLinkArgs.href = 'javascript: return false;';
						lbImgLinkArgs.onclick = "if (suspendpreviews==0) { hp(); enlarge2('" + lbid + "', '" + lbi + "'); } return false;";
					}
					var theSlug = ( lbid != 1 ?
						Builder.node('div', {'style':'padding-left: 2px; padding-right: 2px; padding-bottom:6px;'},[
						Builder.node('a', {'onclick':"lightbox_delete_image('" + lbid + "'); return false;", className:'lblink lblinkDeleteImage', 'title':phrase.lbstrip_remove_image_from_lb_title,'href':'javascript: return false;'},phrase.lbstrip_remove_image_from_lb_linktext),

						Builder.node('a', lbLinkArgs,phrase.lbstrip_preview_image_from_lb_linktext)
       					])
						:
		       			''
					);

					thehtmlLightboxStrip.push(
					Builder.node('div', {'id':'dlb_'+lbi, 'name':'dlb_'+lbi, 'style':'float:left; height:' + (tofit + 18) + 'px; overflow:hidden', 'align':'center'}, [
						Builder.node('a', lbImgLinkArgs,[
							Builder.node('img', {'id':'dlb_'+lbid, 'onmouseover':"prloadimg('"+lbid+"'); pmousedelta[1] = -180; sp(this, '" + lbid + "', '" + lbi +  "','" + tset + "');", onmouseout:"hp(); pmousedelta[1] = -30;", 'src':ImageUrl('135/50', lbid), border:0, height:tofit, className:'lbimg', 'hspace':2})
						]),
						Builder.node('br'),
      						theSlug
					])
					);
				}
			}
		}
		else if (currentlbname)
		{
			thehtmlLightboxStrip.push(
			Builder.node('div', {'id':'dlb_0', 'name':'dlb_0', 'style':'float:left; height:' + (tofit + 18) + 'px; overflow:hidden;', 'align':'center'},[
				Builder.node('a',{'href':'javascript: return false;', 'onclick':'return false;', 'id':'dlb0s_lbi', 'onmouseover':"prloadimg('1'); sp(this, '1', '0','" + tset + "');", 'onmouseout':"hp();"},[
					Builder.node('img', {'src':'http://globaldyn.ipnstock.com/'+dynimagesname+'/135/50/1.JPG', border:0, height:tofit, className:'lbimg', 'hspace':2})
				])
			])
			);
		}
		thehtmlElements.push(
		Builder.node('div', {'class':'lbscroll', 'style':'position: relative; overflow:'+scrollins+'; overflow-y:hidden;height:'+(heightOfLbDiv-41)+'px;'},[ 
				Builder.node('div', {'id':'LBimgdiv', 'style':'position:absolute; left:0; top:0; padding: 1px 0 0 0; height:'+(heightOfLbDiv-40)+'px; width:'+wishwidth+'; display:'+lbdisplaymode_style+';'},[
				thehtmlLightboxStrip
			])	
		])
		);
 
		//write the lb to the div
		$('LBdiv').replace('<div id="LBdiv"></div>');
		$('LBdiv').innerHTML = '';
		$('LBdiv').style.height = heightOfLbDiv+'px';


		thehtmlElements.each(function(domer){
			$('LBdiv').appendChild(domer);	
		});

                if ( lbdisplaymode == 1 && viewmode == 'editing') //minimize
                        $('LBimgdiv').hidden = 1;

   		//Mini Sortable used to go here.  Moved to expanded sort.

    }

      global.lightBoxBuilt = 1;
	lightbox_built = global.lightBoxBuilt;  // backward compatibility
	return;
 };

 function validateLightboxName(v){ // validator for new lightbox names
	if(v.match(/[^A-Za-z0-9 \-_]/)){//if it matches NOT the good chars
		alert(phrase.lightbox_name_problem2_alert);
	        return false;
	} else {
		return true;
	}
 };

 function registerLightboxRename(){
   var loclbn = $F('lightbox_new_name');
   var lightboxes = document.getElementById('lightbox_menu').options;

   for (var lb in lightboxes)
    {
     if (loclbn == lightboxes[lb].value) 
      {
       alert("The lightbox " + loclbn + " already exists!");
       return false;
      }
    }

	if( loclbn.length ==0 || loclbn.length > 100 || loclbn === undefined){
		 alert('Lightbox names must be between 1 and 100 characters long.');
		loclbn='';
	} else {
		if(test_valid_name(loclbn)){
			simplemessage('renaming your lightbox ' + loclbn + ' <blink>.</blink>','LB');
			var mobid = ((typeof(mobject_id) != 'undefined' && mobject_id != '') ? 'mob='+mobject_id : '');
	                var lbs = make_lightbox_string(gusername,currentlbname,loclbn);
		        ajax_JSON('/AjaxHandlers/LightboxRename/' + lbs + '.json', getpost, mobid);
			currentlbname = loclbn;
		} 
	}
 };

 function changeLightbox(newlb){
	currentLbdivMode="lightbox"; 
	cartview=""; 
	document.currentLbdivMode="lightbox"; 

	var lbs = '';
	if (typeof(newlb) != 'undefined' && newlb.toString().length > 0)
	{
		simplemessage('Changing to Lightbox: ' + newlb + '<blink>.</blink>','','LB');
		polllb();//make sure and save changes
		currentlbname=newlb;
		lbs = make_lightbox_string(gusername,newlb);
	}
	
        ajax_JSON('/AjaxHandlers/LightboxInfo/' + lbs + '.json', getpost, null);
 };

 function addImageToLightbox(id) { // adding an image to the current lightbox

	if (gsession)
	{
		var clb_exists = ( typeof(document.currentlbstash) == 'object' ? 1 : 0 );
		var temp= ( clb_exists ? document.currentlbstash.pluck('id').join(" ") : '');
		if(temp.indexOf(id)>=0){
			alert('That image is already in your Lightbox');
		} else {
			if (! currentlbname)
				currentlbname = 'newlb';

			if (!document.currentlbstash.push)
				document.currentlbstash = new Array();

			document.currentlbstash.unshift({id: id, rfcd: ''});
	
			var mobid = ((typeof(mobject_id) != 'undefined' && mobject_id != '') ? 'mob='+mobject_id : '');
			var lbs = make_lightbox_string(gusername,currentlbname,id);
			ajax_JSON('/AjaxHandlers/LightboxAddTo/' + lbs + '.json', getpost, mobid);

			if(clb_exists)
				lightbox_build(document.currentlbstash);
		}
	}
	else //not
	{
		self.location='/bin/Cklb?ref=/SwishSearch%3F'+escape(pre_q_args)+'&atlb='+id;
	}

 };

 //deleting lightbox from exlarge view (as opposed to local lb).
 function deleteLightboxFromEnlargeView(locid,callback) {
	var targetlb;
	var loc_mobj = '';
	var owner = gusername;

	if(typeof(mobject_id) != 'undefined' && mobject_id != '') //always sent in as a page var by template on VMO links
	{
		var pargs = new Array;
		pargs = mobject_id.match(/^([^.]+)\.([^.]+)\.([^.]+)$/);
		targetlb = pargs[3];
		owner = pargs[2];
		loc_mobj = mobject_id;
	}
	else if (typeof(pagetype) != 'undefined' && pagetype == 'lb' ) //viewing local lightbox
	{
		targetlb = dsplkys;//so needs to also update lower lb
	}
	else if(typeof(q_args) == 'undefined' || ! q_args.match(/rid=/)) //if viewing requests, don't die
	{
		return; //do nothing if we can't find the full id of the lightbox viewed
	}

	//ajax call to delete lb image directly, since it may or not be the user's lb.
	if (document.thisIsFeatureView && typeof(feat_requestview) != 'undefined' && feat_requestview.toString().length > 0) //features already have an ajax-y handler for this
	{
		ajax_JSON('/R?del_id='+locid+'&rid='+feat_requestview, 'GET', null);
	}
	else
	{
		ajax_TEXT('/bin/CreateLightbox?delid='+locid+'&vmo='+loc_mobj+'&uname='+owner+'&lbname='+targetlb, 'GET', null);
	}
	
	//for removing images from lightbox viewed in enlarge mode, which may, or may not be also viewed in the lower panel.
	for(var tt=0; tt < id.length; tt++) // if we're in lbview need to also splice the image out
	{					//the display arrays
		if(id[tt] == locid)
		{
			cs.splice(tt,1);
			fs.splice(tt,1);
			o.splice(tt,1);
			rm.splice(tt,1);
			id.splice(tt,1);
			st.splice(tt,1);
			hrdl.splice(tt,1);
			rel.splice(tt,1);
			sw.splice(tt,1);
			pho.splice(tt,1);
			scp.splice(tt,1);

			//buildimages(0,0); don't register the build, just dispatch

						//LS20081104 Changed viewmode from 'lb' to cookie-saved gviewmode.
						//Should fix issue where image size changed to medium when images is deleted from lightbox.
        		var section = $H({ showstart:showstartnumber_trap+1, snum:showstartnumber_trap, viewmode:viewmode, buildmode:'', resized:'' }).toJSON();
        		dispatchAll(section);

		}
	}

	//need nameof this viewed lightbox to compare against currentlbname
	//to see if we need to update the lightbox tray too
	if(targetlb == currentlbname && (typeof(callback == 'undefined') || callback != 1 ))
		lightbox_delete_image(locid,1);

	//LS20081105 Need to update the lightbox results_total on the fly instead of regenerating fullpage
	if ( $("imgtotal") ) {
		$("imgtotal").innerHTML = id.length;
	}
	if ( $("lastpgtotal") ) {
		$("lastpgtotal").innerHTML = id.length;
	}
	if ( $("nav_total_images") )
		$("nav_total_images").innerHTML = id.length;
	results_total = id.length;

 };

 function deleteImageFromLightbox(locid,callback) {// removing an image locally and updating status to save ad periodical update
	var nlb = new Array();
	var targetlb = '';
	var targetowner = '';
	for(var temp=0;temp<document.currentlbstash.length;temp++){
		if(document.currentlbstash[temp].id == locid){
			var tolightbox_delete_image=temp;
			if(typeof(mobject_id) != 'undefined' && mobject_id != '') //always sent in as a page var by template on VMO links
			{
				var pargs = new Array;
				pargs = mobject_id.match(/^([^.]+)\.([^.]+)\.([^.]+)$/);
				targetlb = pargs[3];
			}
			else if (typeof(pagetype) != 'undefined' && pagetype == 'lb' ) //viewing local lightbox
			{
				targetlb = dsplkys;//so needs to also update lower lb
			}

		}
		else
		{
			nlb.push(document.currentlbstash[temp]);
		}
	}

	document.currentlbstash = nlb;
	
	if(targetlb && targetlb != '' && targetlb == currentlbname && callback != 1 ) //need to refresh expanded view too if we're viewing expanded local lb
		lightbox_delete_image_enl(locid,1);

	if (typeof(document.currentlbstash) != 'undefined' && document.currentlbstash.length == 0) //kill the lightbox if it is empty
	{
		lightbox_delete();
	}
	else
	{
		var mobid = ((typeof(mobject_id) != 'undefined' && mobject_id != '') ? 'mob='+mobject_id : '');
		var lbs = make_lightbox_string(gusername,currentlbname,locid);
		ajax_JSON('/AjaxHandlers/LightboxDelFrom/' + lbs + '.json', getpost, mobid);
		lightbox_build(document.currentlbstash);
	}
 };

 function toggleLightbox () {
        if($('LBimgdiv').hidden == 1) {
                $('LBimgdiv').style.display = 'block';

                $('LBdiv').style.height = '130px';

                $('LBimgdiv').hidden = 0 ;
                gsetCookie("ghidelightbox","", "", "/", gGetCookieDom());
        } else {
                $('LBimgdiv').style.display = 'none';
		
		var gh = $('Layer1').getHeight() + 200;
		$('Layer1').style.height = gh + 'px';
	//	alert($('Layer1').style.height);
                $('LBdiv').style.height = '40px';

                $('LBimgdiv').hidden = 1
                gsetCookie("ghidelightbox","1", "", "/", gGetCookieDom());
        }

        currentpage();
 };

 //util function to prep lb save string
 function makeLightboxString(uname,lbname,lbarr) {
	//#lightbox_ownername|||lightboxname||id|id|id|id
	var newlba = '';
	if ( typeof(lbarr) == 'object' )
	{
		 newlba = lbarr.pluck('id');
	}
	else
	{
		newlba = [ lbarr ];
	}

	newlba = newlba.reverse();

	var newlb = newlba.join('|');

	if (newlb && newlb.length > 500) //failsafe
		newlb = '';

	var lb_string = uname + '|||' + lbname + ( newlb ? '||' + newlb : '');
	return lb_string;
 };

 function refreshTopLightbox() {
	if(gsession){
		self.location="/SwishSearch?n=1&lb_view=1";
	} else {
		self.location = '/bin/Cklb?ref=/SwishSearch?lb_view=1';
	}
 };

 //ALL THIS DOES IS SAVE YOUR CURRENT LIGHTBOX
 function saveLightbox(force, synch){ 
	var lbs = make_lightbox_string(gusername,currentlbname,(typeof(document.currentlbstash) != 'undefined' ? document.currentlbstash : 1));

	var mobid = ((typeof(mobject_id) != 'undefined' && mobject_id != '') ? 'mob='+mobject_id : '');

	var meths = getpost;
	if (typeof(document.currentlbstash) == 'object' && document.currentlbstash.length > 50)
	{
		var payload = document.currentlbstash.pluck('id').reverse().join('|');
		if (mobid)
			mobid+='&';
		mobid+= 'payload='+payload;
		meths = 'POST';
	}

	ajax_JSON('/AjaxHandlers/LightboxSave/' + lbs + '.json', meths, mobid );
 };



};
function afLogin(){

this.showLogin = showLogin;
this.hideLogin = hideLogin;
this.evaluateLogin =  evaluateLogin;

function showLogin(){
	$('loginLayer').style.display = "block";
	var mesg = phrase.login_start_message_text;	
	$('loginLayer').innerHTML  = Templates.login.evaluate({message: mesg});
	$('username').focus();
}

function evaluateLogin(form){
	if(isBlank($('username').value)){
		loginMessage(phrase.login_invalid_username_message);
		$('username').focus();
		return false;
	}
	if(isBlank($('password').value)){
		loginMessage(phrase.login_enter_password);
		$('password').focus();
		return false;
	}else{
		return submitLogin();
	}
	return true;
}

function validEmail(val){
	if(val.match(/[A-Za-z][A-Za-z0-9._]+\@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+/))
		return true;

	return false;
}

function isBlank(val){
	if(val.match(/^\s*$/))
		return true;
	
	return false;
}

function hideLogin(){
	$('loginLayer').style.display="none";
}

function submitLogin(){
	var meth = "POST";
	var url = "/AjaxHandlers/LoginAjax/.json";
	
	var params ={ "username"  : $('username').value,
			"password" : $('password').value,
			"sphotog" : $('sphotog').value,
			"login" :  1};

	var myAjax = new Ajax.Request(
                url,
                {
                        method: meth ,
                        parameters: params,
			onSuccess : function(responseObj){
				var responseHsh = responseObj.responseText.evalJSON();
				if(responseHsh.success){
					loginMessage(phrase.login_success_message);
					window.location.reload();
				}else	
					loginMessage(responseHsh.message); 
			 },
                        onFailure: function () {alert(phrase.login_error); }
                }
        );

	return false;
}

function loginMessage(txt){
	$('loginMessage').style.display='block';
	 $('loginMessage').innerHTML = txt; 

}

};

function afMouse() {

 this.mouseSnap = mouseSnap;
 this.findMouse = findMouse;
 this.getMouseCoordinates = getMouseCoordinates;

 function mouseSnap(e) { 
	if (typeof(event) == 'undefined')
	{
		document.mouseLocSnapX = Event.pointerX(e);
		document.mouseLocSnapY = Event.pointerY(e);
	}
	else
	{
		document.mouseLocSnapX = Event.pointerX(event);
		document.mouseLocSnapY = Event.pointerY(event);
	}
 };

 function findMouse(e, sX, sY){
	if($('pimid')) { //pshown!=0 && 
 		var xcoord=pmousedelta[0];
 		var ycoord=pmousedelta[1];

		mouseX = (sX || 0); 
		mouseY = (sY || 0);
		var theTar;
		if (typeof(event) == 'undefined')
		{
			//mouseX = e.pageX || (e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft));
			//mouseY = e.pageY || (e.clientY + (document.documentElement.scrollTop || document.body.scrollTop));
			mouseX = Event.pointerX(e);
			mouseY = Event.pointerY(e);

			theTar = e.target;
		}
		else //IE
		{
			//mouseX = event.pageX || (event.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft));
			//mouseY = event.pageY || (event.clientY + (document.documentElement.scrollTop || document.body.scrollTop));
			mouseX = Event.pointerX(event);
			mouseY = Event.pointerY(event);
			theTar = event.target;
		}

		//check to see if we need to bail out...
		if (Math.abs(mouseX - document.mouseLocSnapX) > 150 || Math.abs(mouseY - document.mouseLocSnapY) > 150)
		{
			hp();
		}
		else
		{

			//keep it in the viewport...

 			var primHt = 60;
 			if(theTar && theTar.nodeName == 'IMG')
 				primHt = Element.getDimensions(theTar)['height'];
		
			if ((mouseX + Element.getDimensions($('pimid'))['width']) > winW)
			{	xcoord = (mouseX - Element.getDimensions($('pimid'))['width'] - pmousedelta[0] - 45);	}
			else
			{	xcoord += mouseX;	}
			if(xcoord < 0 ){xcoord = pmousedelta[0];}

			if ((mouseY - Math.min(primHt, 420) + pmousedelta[1] - 20) < document.body.scrollTop)
			{	ycoord = document.body.scrollTop - pmousedelta[1];			
				
				if ((ycoord + 40) > winH)
				{	ycoord = (ycoord - Math.min(primHt, 420)+ pmousedelta[1]);
					if ( ((ycoord + Math.max(primHt, 420) - document.body.scrollTop) - winH) > 0)
					{
						ycoord = ycoord - (typeof(event) == 'undefined' ? Math.min((primHt+160), 420) : (gloCrop == 'panoramic' || (gloCrop != '' && gloCrop !='vertical') ? 190 : 380));	 //ie can't find heights properly.. so rely on crop..
					}
				}
			
			}
			else if ((mouseY + Math.max(primHt, 420)) > winH)
			{	ycoord = (mouseY - Math.min(primHt, 420)+ pmousedelta[1]);

				if ( ((ycoord + Math.max(primHt, 420) - document.body.scrollTop) - winH) > 0)
				{
					ycoord = ycoord - (typeof(event) == 'undefined' ? Math.min((primHt+160), 420) : (gloCrop == 'panoramic' || (gloCrop != '' && gloCrop !='vertical') ? 190 : 380));	 //ie can't find heights properly.. so rely on crop..
				}

				if (ycoord < document.body.scrollTop)
				{	ycoord = document.body.scrollTop - pmousedelta[1];	}
			 }
			else
			{	ycoord += mouseY;	
				if ((ycoord + 40) > winH)
				{	ycoord = (ycoord - Math.min(primHt, 420)+ pmousedelta[1]);
					if ( ((ycoord + Math.max(primHt, 420) - document.body.scrollTop) - winH) > 0)
					{
						ycoord = ycoord - (typeof(event) == 'undefined' ? Math.min((primHt+160), 420) : (gloCrop == 'panoramic' || (gloCrop != '' && gloCrop !='vertical') ? 190 : 380));	 //ie can't find heights properly.. so rely on crop..
					}
				}
			}


 	 		$('pimid').style.left = parseInt(xcoord) + "px";
  			$('pimid').style.top  = parseInt(ycoord) + "px";
		}
	}
 };

 function getMouseCoordinates(e) {
  if(browser != 'Explorer'){
    msX = e.pageX
    msY = e.pageY
  } else {
    msX = event.clientX + document.body.scrollLeft
    msY = event.clientY + document.body.scrollTop
  }  
	if( msX < panelx || msY > (panely+panelheight)){
		document.isn.Keywords.blur();
                hidedisplaypanel(1);
        }

 };


};
function afPage() {

 this.checkPageResize = checkPageResize;
 this.currentPage = currentPage;
 this.nextPage = nextPage;
 this.preloadNextPage = preloadNextPage;
 this.previousPage = previousPage;
 this.setBackPage = setBackPage;
 this.setupPageSize = setupPageSize;

 function currentPage(){
         if($('cdheader'))
              $('cdheader').style.display = 'block';


	setuppagesize(); 	
	if (document.currentLayer1Mode == 'searchresults')
	{
            	var section = $H({ snum:( firstpictureonpage ? firstpictureonpage : 0 ), viewmode:viewmode, buildmode:'', resized:'' });
            	//we don't want to register a backpage event on resize, so call the worker directly.
            	dispatchBuildimages(section);
	}

	else if (document.currentLayer1Mode == 'cartview')
	{
		
		cart_display();
	}



	createCoverLayer();
	$('coverlayer').style.width = winW + 'px';
	if($('Layer1')){
		if (document.currentLayer1Mode != 'cartview' && document.currentLayer1Mode != 'enlarge' )
			$('Layer1').style.overflow = 'hidden';
		$('Layer1').style.width = '100%';
		$('Layer1').style.height = ( document.currentLayer1Mode == 'cartview' || document.currentLayer1Mode == 'enlarge' ? truevertHeight : winH ) + 'px';

		if($('lbbuttons'))
		{
			$('coverlayer').style.height = 	(Element.getHeight("Layer1") + Element.getHeight("row2") + Element.getHeight("cdheader") ) + ( (covertopadjust) ? covertopadjust : 0) + ( (coverbottomadjust) ? coverbottomadjust : 0) + 'px';
		}
		else
		{
			$('coverlayer').style.height = (winH + 30) + 'px';
		}
		if($('cdheader')){
			if(Position.cumulativeOffset($('cdheader'))[1] > 0){
			//qq('cdheader top' + Position.cumulativeOffset($('cdheader'))[1]);
			$('coverlayer').style.height = 	(Element.getHeight("Layer1") + Element.getHeight("row2") + Element.getHeight("cdheader") ) + ( (covertopadjust) ? covertopadjust : 0) + ( (coverbottomadjust) ? coverbottomadjust : 0) + 'px';
			}
		}
		$('coverlayer').style.width = Element.getWidth("Layer1");
		var co = [];
                if ( $('row2') ){
                        co = Position.cumulativeOffset($('row2'));
		}
		
		if($('cdheader') && Position.cumulativeOffset($('cdheader'))[1]>0){
			co=Position.cumulativeOffset($('cdheader'));
		}
                else if ( $('navContainer') )
                {
                        co = Position.cumulativeOffset($('navContainer'));
                        co[1] += $('navContainer').getHeight();
                }

		$('coverlayer').style.top = (co[1] - ( (covertopadjust) ? covertopadjust : 0)) + (Position.cumulativeOffset($('cdheader'))[1] < 1 ? ( (typeof(covertopadjust) != 'undefined') ? covertopadjust : 0) : 0) + 'px';
		$('coverlayer').style.left = co[0]  + 'px';
		var temptop = (trueh - Element.getHeight("LBdiv") -1);	
	}
 };

 function setupPageSize(){
	adminheight = 0;
	if( typeof(hrdl) != 'undefined' && hrdl[0] && hrdl[0] !=''){
                if (typeof(viewmode) != 'undefined' && viewmode == 'editing')
                        adminheight=0;
                else
			if(typeof(adminheight_custom) != 'undefined'){adminheight=adminheight_custom} else {adminheight=11;}
	} 

	if(typeof(shcon) == 'object' && shcon[0] && shcon[0] !='') {
		adminheight+=11;
	}

	if ( $('Layer1') )
	{
		winW = Element.getWidth('Layer1');
	}
	else if (window.innerWidth)
       	{
              	winW = window.innerWidth;
        }
       	else if(document.documentElement && document.documentElement.clientWidth)
        {
        	winW = document.documentElement.clientWidth;
        }
        else if(document.body && document.body.clientWidth)
        {
        	winW = document.body.clientWidth;
        }
        else if(document.body && document.body.offsetWidth)
        {
        	winW = document.body.offsetWidth;
        }




	if (window.innerHeight)
	{
		trueh = window.innerHeight;
	}
	else if(document.documentElement && document.documentElement.clientHeight)
	{
		trueh = document.documentElement.clientHeight;
	}
	else if(document.body && document.body.clientHeight)
	{
		trueh = document.body.clientHeight;
	}
	else if(document.body && document.body.offsetHeight)
	{
		trueh = document.body.offsetHeight;
	}

/*
            if (document.documentElement.clientHeight && document.documentElement.clientHeight > trueh && (typeof(viewmode) != 'undefined' && (viewmode != 'med' || yourBrowse == 'IE' ) ))
            {
                trueh = document.documentElement.clientHeight - 0;
            }
	*/

	truew = winW;
	safetyspace = 16;
	menuheight = 20;
	winH = parseInt(trueh) - ( $('row2') ? (parseInt(Element.getHeight("row2")) + Position.cumulativeOffset($('row2'))[1]) : 20 );

	//alert(winH);
	if(document.currentLayer1Mode == 'enlarge')
	{
		winH = winH - safetyspace;
	}
	else
	{
	 	winH = winH - safetyspace - menuheight;
	}

	//tweakheight -- if you just can't get it right:
	if (typeof(tweakheight) != 'undefined' && tweakheight != 0)
		winH = winH - tweakheight;

	if(gsession){//logged in
//switched to fixed lb height, 
		if(document.getElementById('LBdiv')){//lightbox is present measure height
			var lbh = parseInt(Element.getHeight("LBdiv"));
			if(lbh < 140 && ! ( lbdisplaymode == 1 && viewmode == 'editing') ){//be safe and leave room unless we're hiding the LB
				winH = winH - 140;
			} else {
				winH = winH - lbh;
			}
		} 
	}
	if (typeof(setuppagesize_cellsizes_custom) == 'function')
	{
		setuppagesize_cellsizes_custom(); //this function must init the same globals as in the base case below:
	}
	else
	{

	    imagerows=Math.floor(winH/(176 + adminheight));
	    imagespaceheight=imagerows * (176 + adminheight);
	    area=imagerows * Math.floor(winW/152);
	    if(! viewmode && imagerows == 1)
	    { 
		viewmode='med';
		gsetCookie('gviewmode','med', '', '/', gGetCookieDom());
	    }

	    if(viewmode){
			if(viewmode == 'table'){
			    if(typeof(InitSafetyCheck)=='function'){InitSafetyCheck('135/50');};
				imagerows=Math.floor(winH/(176 + adminheight));
				if(imagerows == 0)
					imagerows=1;
				imagespaceheight=imagerows * (176 + adminheight);
				area=imagerows * Math.floor(winW/152);
			} else  if(viewmode == 'editing'){
			    if(typeof(InitSafetyCheck)=='function'){InitSafetyCheck('135/50');};
	                        imagerows=Math.floor(winH/(160 + adminheight));
	                        if(imagerows == 0)
	                                imagerows=1;
	                        imagespaceheight=imagerows * (160 + adminheight);
	                        area=imagerows * Math.floor(winW/300.00);
	                } else 	if(viewmode == 'list'){
			    if(typeof(InitSafetyCheck)=='function'){InitSafetyCheck('135/50');};
				imagerows=Math.floor(winH/(172.00 + adminheight));
				if(imagerows == 0)
					imagerows=1;
				imagespaceheight=imagerows * (172 + adminheight);
				area=imagerows * Math.floor(winW/300.00);
			} else 	if (viewmode == 'tiny'){
			    if(typeof(InitSafetyCheck)=='function'){InitSafetyCheck('135/50');};
				imagerows=Math.floor(winH/(106.00 + adminheight));
				if(imagerows == 0)
					imagerows=1;
				imagespaceheight=imagerows * (106 + adminheight);
				area=imagerows * Math.floor(winW/96.00);
			} else if (viewmode == 'med'){
			    if(typeof(InitSafetyCheck)=='function'){InitSafetyCheck('135/50');};
				imagerows=Math.floor(winH/(130.00 + adminheight));
				if(imagerows == 0)
					imagerows=1;
				imagespaceheight=imagerows * (130 + adminheight);
				area=imagerows * Math.floor(winW/140.00);
			} else if (viewmode == 'huge'){
			    if(typeof(InitSafetyCheck)=='function'){InitSafetyCheck('420/60');};
				imagerows=Math.floor(winH/(220.00 + adminheight));
				if(imagerows == 0)
					imagerows=1;
				imagespaceheight=imagerows * (220 + adminheight);
				area=imagerows * Math.floor(winW/330.00);
			} else if (viewmode == 'large'){
			    if(typeof(InitSafetyCheck)=='function'){InitSafetyCheck('170/85');};
			
				imagerows=Math.floor(winH/(199.00 + adminheight));
				if(imagerows == 0)
					imagerows=1;
				imagespaceheight=imagerows * (199 + adminheight);
				area=imagerows * Math.floor(winW/187.00);
			}
				
	    }


	}

/*	if(document.currentLayer1Mode == 'enlarge'){
			imagespaceheight=winH - menuheight;
		} */
	truevertHeight = winH;
	//winH=imagespaceheight + menuheight; // restore it to accomodate narrowbar and footer // it's already limited.. this crop is too close..
	if(winH<450){
		smallscreen=1;
	}
	if(area > 0){
		totalimagesthatcanfit=area;
		gpixperpagev=totalimagesthatcanfit;
                if ($('pixperpage'))  // Mantis #1157 - Needed to guarantee pop-ups show up - Milan Adamovsky 07/06/2009
                 $('pixperpage').value = gpixperpagev;
	} else {
		// load images per page into field
		gpixperpagev = ggetCookie('gpixperpage');
		if(! gpixperpagev)
			gpixperpagev=12;
	}


	//set up coverlayer
        createCoverLayer();
        $('coverlayer').style.width = winW + 'px';

                if($('lbbuttons'))
                {
                        $('coverlayer').style.height =
                        ( Position.cumulativeOffset($('lbbuttons'))[1] - Position.cumulativeOffset($('row2'))[1]  + Element.getHeight("lbbuttons") ) + 'px';// + 'px';//$('Layer1').style.height;
                }
                else
                {
                        $('coverlayer').style.height = (winH + 30) + 'px';
                }

                var co = [];
                if ( $('row2') )
                        co = Position.cumulativeOffset($('row2'));
                else
                {
                   if ($('navContainer'))  // Check why sometimes this doesn't exist - Milan Adamovsky 06/17/2009
                    {
                        co = Position.cumulativeOffset($('navContainer'));
                        co[1] += $('navContainer').getHeight();
                    }
                }


                $('coverlayer').style.top = co[1] + 'px';
                $('coverlayer').style.left = co[0]  + 'px';

 };

 function nextPage(){
        buildimages(lastimage,"next");
 };

 function previousPage(){
        backpagestart=lastimage - ( 2 * parseInt($F('pixperpage')));
        if((backpagestart) < 0){ // past this set of images
                if((backpagestart + snum) < 0){
                        prevtogoto=0;
                } else {
                        prevtogoto=Number(snum) + Number(backpagestart); // go back two pages from start page
                        gsetCookie('gwhichstartpage','0', '', '/', gGetCookieDom());
                        if(prevtogoto < 0 ){ prevtogoto=0;}
                }
                var section = $H({ showstart:1, snum:0, viewmode:viewmode }).toJSON();
                self.location=nextlink + 'snum=' + prevtogoto + '#nav='+section;

        } else { //within this set of images
                buildimages(backpagestart,"prev");
        }
 };

 function checkPageResize(e){
	if(self.innerWidth){
                newW = self.innerWidth - 0;
	} else if (document.body){
		newW = document.body.offsetWidth - 0;
	}

	if (newW != tempW){
		if(self.innerWidth){
			tempW = self.innerWidth - 0;
		} else {
			tempW= document.body.offsetWidth - 0;
		}

		try {
			if (currentLbdivMode == 'lightbox')
				setTimeout("lightbox_build(document.currentlbstash);",1000);
			else if (currentLbdivMode == 'cart')
				setTimeout("cart_build();",1000);
		} catch (e) {}

		setTimeout("currentpage();",1000);
	}
 };

 function preloadNextPage(){
        preloadcurrent=prestart;
        preloadnextimg();
 };

 function setBackPage() {
/*
	var thispage = '';
	if (location.href)
		thispage = location.href;
	gsetCookie('backpage', thispage, '', '/', gGetCookieDom());
*/
 };


};
function afPreview() {

 this.hp = hp;
 this.hpoff = hpoff;
 this.portSize = portSize;
 this.previewSet = previewSet;
 this.sp = sp;
 this.sp_act = sp_act;

 function previewSet(){
	tset = document.page.previews.options[document.page.previews.selectedIndex].value;
        var date = new Date();
        date.setTime(date.getTime()+(60*24*60*60*1000));
        gsetCookie('gpreviews',tset,date, '/', gGetCookieDom());
 };


 
 function sp(oObj, imageid, imagenum, mode) { //was wrapper func to make asynch call before rendering, now just calls sp_act as all info is stored within the page
	if (oObj.id)
		currMousedOverObj = oObj.id;

	if ( currMousedOverObj != id[imagenum] ) //not in page
		ajax_JSON( '/AjaxHandlers/ImageInfo/'+imageid+'.json', getpost, null ); //even if it's off make the call anyway to cache

 	sp_act(oObj.id, imageid, mode, imagenum, 0);
 };


 function sp_act(oObjId, imageid, mode, dex, tryCtr){  //imagename, imagenum, license, photographer, 
	//pshown=1;

	if( (! $('previewsSel').selectedIndex || $('previewsSel').selectedIndex != 1) && suspendpreviews==0)
	if(mode == 'on'){
		//grab current mouse pos quick
		Event.observe(document, 'mousemove', mouseSnap);
		setTimeout("Event.stopObserving(document, 'mousemove', mouseSnap)", 200);
		Event.observe(document, 'mousemove', pfindmouse);
		if (	(oObjId == currMousedOverObj ) &&
			( ( document.ajaxLoaded && imageid == document.JSONobj.getImgDat('id') ) || imageid == id[dex] )	) {

			var temp = true;
			
			gloCrop = ( imageid == id[dex] ? crp[dex] : document.JSONobj.getImgDat('crop') );
			gloCrop = ( gloCrop ? gloCrop : 'horizontal' );
			var crop = gloCrop;
			//SMALL SCREEN HACK
			if(smallscreen=='1' && (crop=='panoramic' || crop=='vertical')){
				prloadimg(imageid,crop);
			}
			
			var file_size = ( imageid == id[dex] ? fs[dex] : document.JSONobj.getImgDat('file_size') );
			if (file_size < 5){file_size='';} else if (! file_size.toString().match(/[A-Za-z]/)){file_size += 'Mb';} //something wrong do not show or it already has size info

			var dimensions = ( typeof(showdimensions) != 'undefined' ? ( imageid == id[dex] ? dim[dex] : document.JSONobj.getImgDat('dimensions') ) : '');
			if (dimensions && dimensions.indexOf('x')>1) //comes as <XVAL>x<YVAL>
			{
				var dimr = dimensions.match(/^(\d+)x(\d+)$/);
				if (dimr != null && dimr.length > 1)
					dimensions = '[&nbsp;'+dimr[1]+'px&nbsp;x&nbsp;'+dimr[2]+'px&nbsp;]';	
			}
			
			var tempshortcaption = ( imageid == id[dex] ? unescape(scp[dex]) : document.JSONobj.getImgDat('short_caption') );	//=spcap;
			if(tempshortcaption && tempshortcaption.length > 130)
			{
				var tsc='';
				for(z=0; z < 170; z++)
				{
					var c = tempshortcaption.charAt(z);
					if(temp == true)
					{
						if((z > 130) && (c == ".")){
							temp = false;
							tsc+=c + " ...";
						} else if((z > 150) && (c == " ")){
							temp = false;
							tsc+=" ...";
						} else {
							tsc+= c;
						}
					}
				}
				tempshortcaption = tsc;
			}
		
			var displayimageid = '';	
			if ( typeof(o) == 'object' && typeof(o[dex]) != 'undefined'){
				displayimageid= ( imageid == id[dex] ? o[dex] : document.JSONobj.getImgDat('orig_id') );
			} else {
				displayimageid=imageid;
			}
			
			var rmrftype = ( imageid == id[dex] ? rm[dex] : document.JSONobj.getImgDat('rmrftype') );
			var photographer = ( imageid == id[dex] ? unescape(pho[dex]) : document.JSONobj.getImgDat('photographer') );
			var image_restrictions = ( imageid == id[dex] ? imr[dex] : document.JSONobj.getImgDat('image_restrictions') );
			image_restrictions = ( image_restrictions ? Templates.preview_restrictions.evaluate({'image_restrictions':image_restrictions}) : '' );
			var tdata = {
				imageid: imageid,
				displayimageid: displayimageid,
				rmrftype: rmrftype,
				filesize: file_size,
				shortcaption: tempshortcaption,
				dimensions: dimensions,
				photographer: photographer,
				imagerestrictions: image_restrictions
			};
			//RENDER!
			$('previewpane_metdat_'+imageid).innerHTML = Templates.preview_metadata.evaluate(tdata);
			$('pimid').style.visibility="visible";
			//pshown=2;
			new Effect.Appear($('pimid'), {duration:0.1});
		} else if (tryCtr < 10){ // effectively, try 10 times to get ajax data... waiting a max of 10 * 250 ms
			tryCtr++;
			setTimeout("sp_act('"+oObjId+"', '"+imageid+"', '"+mode+"', '"+dex+"', '"+tryCtr+"')", 250);
		}
	}
 };

 function hpoff(){	
	if(currMousedOverObj == '' || ! currMousedOverObj){
		if(typeof(mouseX)!='undefined' && mouseX > parseInt(portSize()[0]/2))
			$('pimid').style.left = '-500px';
		else
			$('pimid').style.top = '-750px';
	}
	else // user action has moved to a new location during timeout..
	{
		new Effect.Appear('pimid', {duration:0.1, from:Element.getOpacity($('pimid'))});
	}
 };

 function hp(){
	currMousedOverObj = '';
	Event.stopObserving(document, 'mousemove', pfindmouse);
	if (!$('pimid'))
		return;
	new Effect.Fade('pimid', {duration: 0.3, from:Element.getOpacity($('pimid'))})
	setTimeout("hpoff()",300);
 };
 function portSize() {
	var retY = parseInt(document.body.offsetHeight - 20);
	var retX = parseInt(document.body.offsetWidth - 20);

	var iX = window.innerWidth;
	var iY = window.innerHeight;

	retX = ( iX < retX ? iX : retX);
	retY = ( iY < retY ? iY : retY); //we want smaller of 2 anyway, also pseud-crossbrowser as a result...

	return [retX, retY]; //X x Y
 };


};
function afRelease() {

 this.iconStatus = iconStatus;
 this.releaseSetPage = releaseSetPage;
 this.saveAllReleases = saveAllReleases;
 this.validateCheckboxes = validateCheckboxes;
 
 function saveAllReleases() {  //just save all releases currently on the page..
	for(var cnt = showstartnumber_trap; cnt < endnumber; cnt++)
		sor(cnt);

	return false;	
 };

 function releaseSetPage(release) { //batch actions a page at a time only for separate share_control style
	//MODEL RELEASED
	//NOT APPLICABLE
	//NOT RECOGNIZABLE
	//NOT RELEASED
	//PROPERTY RELEASED
	//MODEL AND PROPERTY RELEASED
//startnumber endnumber
        if (release == '')
                return;

        var shownIds = $A();

        for(var cnt = showstartnumber_trap; cnt < endnumber; cnt++)
        {
            if ( id[cnt] )
            {
                shownIds.push(id[cnt]);

                var sForm = $('releasecontrol'+cnt);

                if (sForm)
                    $A(sForm.elements).each( function(chx) {
			var val = chx.value;
			if ( val && chx.type == "checkbox")
			{
			    if(val == release || ( release == 'MODEL AND PROPERTY RELEASED' && ( val == 'MODEL RELEASED' || val == 'PROPERTY RELEASED' ) ) )
				chx.checked = true;
  			    else
				chx.checked = false;
			}
                    });

        	if ($('shortrel'+cnt)) {
               		var shortrel = release;
                	shortrel = shortrel.substring(0,16) + (release.length > 16 ? '...' : '');
                	$('shortrel'+cnt).innerHTML = phrase.release_title+shortrel;
        	}

		sor(cnt); //this spawns a lot of concurrent ajax requests, so set release call has to be reasonably fast... (currently it is)
            }

        }
        return false;
 };

 function validateCheckboxes(thar) {
	//so we're only checking certain things..
	// MODEL & PROP REL (OK)
	// ^NOT (uncheck all others)
	var cc = 0;
	var grel = '';
	$A(thar.form.elements).each( function(chx) {
		if (chx.checked)
		{
			cc++;
			grel = chx.value;//so if only 1 is checked, we get it prepopulated.. otherwise it gets set later..
		}
	});


	if (cc > 1) {  //more than one checked.. have to check for contradiction
		var keepon = new Object;

		/*if( thar.form.elements['NOT RELEASED'].checked ) { keepon['NOT RELEASED'] = 1; grel = 'NOT RELEASED'; }
		else if (thar.form.elements['NOT RECOGNIZABLE'].checked ) { keepon['NOT RECOGNIZABLE'] = 1; grel = 'NOT RECOGNIZABLE'; }
		else if (thar.form.elements['NOT APPLICABLE'].checked ) { keepon['NOT APPLICABLE'] = 1; grel = 'NOT APPLICABLE'; }
		else if (thar.form.elements['ERROR'].checked ) { keepon['ERROR'] = 1; grel = 'ERROR'; }
		else */
		
		if ( thar.form.elements['MODEL RELEASED'].checked && thar.form.elements['PROPERTY RELEASED'].checked 
			&& thar.name.toString().match(/(MODEL|PROPERTY) RELEASED/) )
		{
			keepon['MODEL RELEASED'] = 1;
			keepon['PROPERTY RELEASED'] = 1;
			grel = 'MODEL AND PROPERTY RELEASED';
		}
		else
		{
			keepon[thar.name] = 1;
			grel = thar.name;
		}

		$A(thar.form.elements).each( function(chx) {
                	if (chx.checked && keepon[chx.value] != 1 )
                        	chx.checked = false;
        	});


	}

	if ($('shortrel'+thar.form.shdex.value))
	{
                var shortrel = grel;
                shortrel = shortrel.substring(0,16) + (grel.length > 16 ? '...' : '');
		$('shortrel'+thar.form.shdex.value).innerHTML = phrase.release_title +shortrel;
	}
	
 };

 function iconStatus(){
 	if(viewmode && typeof(iconbackground) != 'undefined'){
 		//clear them
 		if($('iconlist')){$('iconlist').style.background='none';}
 		if($('iconbig')){$('iconbig').style.background='none';}
 		if($('icontiny')){$('icontiny').style.background='none';}
 		if($('iconmed')){$('iconmed').style.background='none';}
 		if($('iconhuge')){$('iconhuge').style.background='none';}
 		if($('iconlarge')){$('iconlarge').style.background='none';}
                 //set it
 		if(viewmode == 'table'){
 			if($('iconbig')){$('iconbig').style.background=iconbackground;}
                 } else  if(viewmode == 'list'){
 			if($('iconlist')){$('iconlist').style.background=iconbackground;}
                 } else  if (viewmode == 'tiny'){
 			if($('icontiny')){$('icontiny').style.background=iconbackground;}
                 } else if (viewmode == 'med'){
 			if($('iconmed')){$('iconmed').style.background=iconbackground;}
                 } else if (viewmode == 'huge'){
 			if($('iconhuge')){$('iconhuge').style.background=iconbackground;}
                 } else if (viewmode == 'large'){
 			if($('iconlarge')){$('iconlarge').style.background=iconbackground;}
                 }
         }
 };


};
function afSearch() {

 this.checkIt = checkIt;
 this.expandIt = expandIt;
 this.narrowIt = narrowIt;
 this.optimizeSearch = optimizeSearch;
 this.popKeywords = popKeywords;
 this.searchType = searchType;
 this.standardSearch = standardSearch;
 this.searchPreferences = searchPreferences;
 this.writeSearch = writeSearch;
 this.writeSimilar = writeSimilar;
 this.writeStandardSimilar = writeStandardSimilar;
 this.writeStandardSearch = writeStandardSearch;

 function searchType() {
	if (typeof(g_custom) == 'function')
		g_custom();
	else
		g_standard();
 };

 function standardSearch() {
	var url2 = $F('Keywords');
	var uname;
	if ( $('Username') )
		uname = $F('Username');  // for id of query in logs... to assoc with users
	pagetype = 'search';
	
	//SB>> search fix to preserve previous terms:
       	var prev_keys = '';
       	if(typeof(q_args) != 'undefined' && q_args)
       	{
               	prev_keys = q_args.match(/Keywords=(.*?)(\&|$)/);
		if(typeof(prev_keys) != 'undefined' && prev_keys && prev_keys.length > 1)
			prev_keys = prev_keys[1];
		else
			prev_keys = '';

               prev_keys = unescape(prev_keys);
       	}

       	if (url2.length<1 && prev_keys.length<1 && ! ( EAD('share_control_sphotog') || EAD('share_control_status') || EAD('share_control_view') || EAD('share_control_release') ) ){ //	if (url2.length<1){
		alert(phrase.search_enter_query_alert);
	} else {
		if (prev_keys.length>0 && ( url2.length<1 || url2 == 'enter keywords' || url2==phrase.search_keyword_field_default_value) )
		{
			url2 = prev_keys;
                	$('Keywords').value = url2;
		}

		if ( (EAD('share_control_sphotog') || EAD('share_control_status') || EAD('share_control_view') || EAD('share_control_release') ) && url2 == 'enter keywords')
		url2 = '';

		var theurl = '';
		if ($('method') && typeof($('method').value) != 'undefined' && $('method').value=='within'){
			theurl= '/SwishSearch?Keywords=' + q_id + '&ex_keys=' + url2;
		} else {
			theurl= '/SwishSearch?Keywords=' + url2 ;
		}


		if($('displaypanel'))
		{


			if(typeof(suspendWithPeople) == 'undefined' && $('displaypanel').people)
			{	
				if ($('displaypanel').people[1].checked == true){
					theurl += '+haspeople';
				}
				if ($('displaypanel').people[2].checked == true){
					theurl += '+nobody';
				}
				if ($('displaypanel').people[3] && $('displaypanel').people[3].checked == true){
					theurl += '+hascrowd';
				}
			}

//custom a gen purpose that relies on value of form elem
//outline
			if ($('displaypanel').custom)
			{
				$A($('displaypanel').custom).each(function(itm) {
					theurl += '+'+itm.value;
				});
			}

			if ($('displaypanel').outline)
			{
				if ($('displaypanel').outline[0].checked == true) {
					theurl += '+outlinable';
				}
				else if ($('displaypanel').outline[1].checked == true) {
					theurl += '+not+outlinable';
				}
			}

			if(typeof(suspendYesNoRestrictons) == 'undefined' && $('displaypanel').restrictions)
			{
				if ($('displaypanel').restrictions[1].checked == true){
					theurl += '+NOT+imagehasrestrictions';
				}
			}


			if ($('displaypanel').xtrasql && $('displaypanel').xtrasql[1].checked == true){
				theurl += '&xtrasql=(releasedmodel+or+releasedproperty+or+releasednotapplicable+or+releasedmodelandproperty)';
			}
		
			var obypas = 1; //if all orient boxes are checked, include none of them...
			$A($('displaypanel').orient).each(function(itm) {
				if (! itm.checked ) { obypas = 0; }
			});
	

			if (! obypas)
			{
				if ($('displaypanel').orient[0].checked == true){
					theurl += '&orient=horizontal';
				}
				if ($('displaypanel').orient[1].checked == true){
					theurl += '&orient=vertical';
				}
				if ($('displaypanel').orient[2].checked == true){
					theurl += '&orient=panoramic';
				}
				if ($('displaypanel').orient[3].checked == true){
					theurl += '&orient=square';
				}
			}
	
			if($('displaypanel').rmrftype)
			{
				if ($('displaypanel').rmrftype[0].checked == true && $('displaypanel').rmrftype[1].checked == false){
					theurl += '&searchinclude=RM';
				}
				if ($('displaypanel').rmrftype[1].checked == true && $('displaypanel').rmrftype[0].checked == false){
					theurl += '&searchinclude=RF';
				}
			}

			if ( $('displaypanel').color )	
			{
			     if ($('displaypanel').color[1].checked == true){
				theurl += '&color=color';
			    }
			    if ($('displaypanel').color[2].checked == true){
				theurl += '&color=gray';
			    }
			}

			// conditional for Illustation agencies
			if (typeof(showIllusphotog) != 'undefined'){
				if ($('displaypanel').searchinclude[0].checked == true && $('displaypanel').searchinclude[1].checked == false){
					theurl += '&searchinclude=illustration';
				}
				if ($('displaypanel').searchinclude[1].checked == true && $('displaypanel').searchinclude[0].checked == false){
					theurl += '&searchinclude=photography';
				}
			}

		}
		if($('spec_idx'))
		{
			if ($('spec_idx').selectedIndex==1){
				theurl += '&spec_idx=ed';
			}
			if ($('spec_idx').selectedIndex==2){
				theurl += '&spec_idx=ne';
			}
		}

		/* ! share control extra fields from filter header on left ! */
		if (EAD('share_control_sphotog'))
			theurl += '&site='+$F('share_control_sphotog');	
		if (EAD('share_control_status'))
			theurl += '&status_view='+$F('share_control_status');
	        if (EAD('share_control_view'))
        	        theurl += '&view='+$F('share_control_view');
                if (EAD('share_control_release'))
                        theurl += '&release_view='+$F('share_control_release');


		
		if (uname && uname != '')
			theurl += '&Username='+encodeURI(uname);


		gsetCookie("gwhichstartpage","", "", "/", gGetCookieDom());

		if (url2 != 'enter keywords') {
			coveroff();
			hidedisplaypanel(1);
			if(typeof(Templates.results_interstitial) != 'undefined'){
				MM_setTextOfLayer('Layer1','',Templates.results_interstitial.evaluate({'url2': url2}));
			} else {
				MM_setTextOfLayer('Layer1','','<table width=100% height=100%><tr width=100% height=100%><td valign=middle align=center width=100% height=100%><b><font class=header>Searching for ' + url2 + ' <blink>.</blink></font></b></td></tr></table>');
			}
			self.location=theurl;

		} else {
			alert(search_enter_query_alert);
			document.isn.Keywords.focus();
		}
	}
 };

 function searchPreferences(val,mode) {
	var gsearchprefs = ggetCookie('gsearchprefs');
	if(gsearchprefs){
	} else {
		gsearchprefs= new String(" ");
	}
	var buildpref = new String("");
		if(val == 'released' && mode == 'remove'){

		} else {
			if((gsearchprefs.indexOf('a')>=0) || (val == 'released' && mode == 'add')){
				buildpref+='a';
			}			
		}
		if(val == 'norestrictions' && mode == 'remove'){	
		} else {
			if((gsearchprefs.indexOf('b')>=0) || (val == 'norestrictions' && mode == 'add')){
				buildpref+='b';
			}
		}
		if(val == 'people' && mode == 'remove'){
		} else {

			if(((gsearchprefs.indexOf('c')>=0) && (val != 'withpeople') && (val != 'withcrowd'))  || (val == 'nobody' && mode == 'add')){
				buildpref+='c';
			} else if (((gsearchprefs.indexOf('d')>=0) && (val != 'withcrowd') ) || (val == 'withpeople' && mode == 'add')){
				buildpref+='d';
			} else if ((gsearchprefs.indexOf('e')>=0) || (val == 'withcrowd' && mode == 'add')){
				buildpref+='e';
			}
		}

		if (document.displaypanel.orient)
		{
		    if (document.displaypanel.orient[0] && document.displaypanel.orient[0].checked == true){
			buildpref+='f';
		    }
		    if (document.displaypanel.orient[1] && document.displaypanel.orient[1].checked == true){
			buildpref+='g';
		    }
		    if (document.displaypanel.orient[2] && document.displaypanel.orient[2].checked == true){
			buildpref+='h';
		    }
		    if (document.displaypanel.orient[3] && document.displaypanel.orient[3].checked == true){
			buildpref+='i';
		    }
		}

		if(typeof(rmonly) == 'undefined' && document.displaypanel.rmrftype)
		{
			if (document.displaypanel.rmrftype[0] && document.displaypanel.rmrftype[0].checked == true){
				buildpref+='j';
			}
			if (document.displaypanel.rmrftype[1] && document.displaypanel.rmrftype[1].checked == true){
				buildpref+='k';
			}
		}

		if (document.displaypanel.color)
		{
		    if (document.displaypanel.color[0].checked == true){
			buildpref+='m';
		    }
		    if (document.displaypanel.color[1].checked == true){
			buildpref+='n';
		    }
		    if (document.displaypanel.color[2].checked == true){
			buildpref+='o';
		    }
		}

		if (typeof(showIllusphotog) != 'undefined'){ //if adding Illustration / Photography selector checkboxes
			if(document.displaypanel.searchinclude[0].checked == true){
				buildpref+='0';
			}
			if(document.displaypanel.searchinclude[1].checked == true){
				buildpref+='1';
			}
		}

		gsetCookie("gsearchprefs",buildpref, '', '/', gGetCookieDom());
 };

 function writeSearch(){
	if (typeof(writesearch_custom) == 'function')
		writesearch_custom();
	else
		writeStandardSearch();
 };

 function writeStandardSearch () {
	panelheight=340;
	if (typeof(showIllusphotog) != 'undefined'){ //if adding Illustration / Photography selector checkboxes
		panelheight += parseInt(showIllusphotog);
	}
	
	gsearchprefs=ggetCookie('gsearchprefs');
	var temph=' checked';
	var tempv=temph;
	var temps=tempv;
	var tempp=tempv;
	var temprno='';
	var temprany=tempv;
	var temppeopany=tempv;
	var temppeopwith='';
	var temppeopwithout='';
	var temppeopcrowd='';
	var temprelany=tempv;
	var temprelonly='';
	var tempcolany=tempv;
	var tempcolcol='';
	var tempcolbw='';
	var rmc="checked";var rfc=rmc;

	var tempillustration=' checked';
	var tempphotography= tempillustration;

	var tempsearchnew = ' selected';
	var tempsearchwithin = '';


	if(gsearchprefs){
		if(gsearchprefs.indexOf("f")>=0 || gsearchprefs.indexOf("g")>=0 || gsearchprefs.indexOf("h")>=0 || gsearchprefs.indexOf("i")>=0){
			if(gsearchprefs.indexOf("f")>=0){ } else {
				temph=' ';
			}
			if(gsearchprefs.indexOf("g")>=0){ } else {
				tempv=' ';
			}
			if(gsearchprefs.indexOf("h")>=0){ } else {
				tempp=' ';
			}
			if(gsearchprefs.indexOf("i")>=0){ } else {
				temps=' ';
			}
		}

                if (typeof(showIllusphotog) != 'undefined'){ //if adding Illustration / Photography selector checkboxes
			if(gsearchprefs.indexOf("1")<0 && gsearchprefs.indexOf("0")<0){ }
			else
			{
				if(gsearchprefs.indexOf("1")<0){ tempphotography=' '; } 
				if(gsearchprefs.indexOf("0")<0){ tempillustration=' '; } 
			}
                }

		if (typeof(showSearchWithin) != 'undefined'){
			if ( $('method') && $F('method') == 'within')
			{
				tempsearchnew = '';
				tempsearchwithin = 'selected';
			}
			else
			{
				tempsearchnew = 'selected';
				tempsearchwithin = '';
			}
		}

		if(gsearchprefs.indexOf("j")<0 || gsearchprefs.indexOf("k")<0){
			if(gsearchprefs.indexOf("k")<=0 && gsearchprefs.indexOf("j")<=0 ){ }
			else
			{
				if(gsearchprefs.indexOf("k")<=0){// && ! gsearchprefs.indexOf("k")>=0){
					rfc = "";
				}
				if(gsearchprefs.indexOf("j")<=0){// && ! gsearchprefs.indexOf("j")>=0){
					rmc = "";
				}
			}
		}
		if(gsearchprefs.indexOf("b")>=0){ //restrictions
			temprany='';
			temprno='checked';
		}
		if(gsearchprefs.indexOf("c")>=0 || gsearchprefs.indexOf("d")>=0 || gsearchprefs.indexOf("e")>=0)
		{
			if(gsearchprefs.indexOf("c")>=0) //without people
			{
				temppeopany = '';
				temppeopwith = '';
				temppeopwithout = 'checked';
				temppeopcrowd = '';
			}
			if(gsearchprefs.indexOf("d")>=0) //with people
			{
				temppeopany = '';
				temppeopwith = 'checked';
				temppeopwithout = '';
				temppeopcrowd = '';
			}
			if(gsearchprefs.indexOf("e")>=0) //with crowd
			{
				temppeopany = '';
				temppeopwith = '';
				temppeopwithout = '';
				temppeopcrowd = 'checked';
			}
		}
		if(gsearchprefs.indexOf("a")>=0){
			temprelonly = 'checked';
			temprelany = '';
		}
		if(gsearchprefs.indexOf("m")>=0 || gsearchprefs.indexOf("n")>=0 || gsearchprefs.indexOf("o")>=0)
		{
			if(gsearchprefs.indexOf("m")>=0) //any
			{
				tempcolany='checked';
				tempcolcol='';
				tempcolbw='';
			}
			if(gsearchprefs.indexOf("n")>=0) //
			{
				tempcolany='';
				tempcolcol='checked';
				tempcolbw='';
			}
			if(gsearchprefs.indexOf("o")>=0) //
			{
				tempcolany='';
				tempcolcol='';
				tempcolbw='checked';
			}
		}
	}
	var results_droppanel_rmonly='';
	var results_droppanel_showillusphotog='';
	var results_droppanel_suspendYesNoRestrictions='';
	var results_droppanel_suspendWithPeople='';
	var results_droppanel_searchwithin='';

	if (typeof(rmonly) == 'undefined'){
		results_droppanel_rmonly = Templates.results_droppanel_rmonly.evaluate({'rmc':rmc,'rfc': rfc});
	}

	if (typeof(showIllusphotog) != 'undefined'){ 
		results_droppanel_showillusphotog = Templates.results_droppanel_showillusphotog.evaluate({'tempillustration':tempillustration, 'tempphotography':tempphotography});
	}

	if (typeof(suspendYesNoRestrictons) == 'undefined'){
		results_droppanel_suspendYesNoRestrictions = Templates.results_droppanel_suspendYesNoRestrictions.evaluate({'temprany': temprany, 'temprno':temprno});
	}

	if (typeof(suspendWithPeople) == 'undefined'){
		results_droppanel_suspendWithPeople = Templates.results_droppanel_suspendWithPeople.evaluate({'temppeopany':temppeopany, 'temppeopwith':temppeopwith, 'temppeopwithout': temppeopwithout, 'temppeopcrowd':temppeopcrowd});
	}

	if (typeof(showSearchWithin) != 'undefined'){
		results_droppanel_showSearchWithin = Templates.results_droppanel_showSearchWithin.evaluate({'tempsearchnew':tempsearchnew, 'tempsearchwithin': tempsearchwithin })
	}
	
	thehtml = Templates.results_droppanel.evaluate({
		panelheight: panelheight,
		temph: temph,
		tempv: tempv,
		tempp: tempp,
		temps: temps,
		tempcolany: tempcolany,
		tempcolcol: tempcolcol,
		tempcolbw: tempcolbw,
		results_droppanel_rmonly: results_droppanel_rmonly,
		results_droppanel_showillusphotog: results_droppanel_showillusphotog,
		results_droppanel_suspendYesNoRestrictions: results_droppanel_suspendYesNoRestrictions,
		results_droppanel_suspendWithPeople: results_droppanel_suspendWithPeople,
		temprelany: temprelany,
		temprelonly: temprelonly,
		results_droppanel_searchwithin: results_droppanel_searchwithin
	});
	var temp=Position.cumulativeOffset($('tablerow2'));
	center_panel(340,panelheight,thehtml,temp[1]);
	Event.observe(document, 'mousemove', getMouseXY);
 };

 function optimizeSearch() {
        var searchthreshhold = 60;
        var thehtml='';
        if (optimizemenu == 1 && pagetype=='search'){
			if (searchthreshhold < results_total){
				thehtml += Templates.results_optimize_search.evaluate({'results_total':results_total,'searchthreshhold': searchthreshhold});	
			} else {
			}
        }
        return(thehtml);
 };

 function narrowIt(url) {
        if(url == "#"){
                alert(phrase.narrow_select_alert);
        } else {
                var url1 = '/SwishSearch?spec_idx=' + spec_idx + '&Keywords=' + ukeys + '+NOT+' + url;
                self.location=url1;
        }
 };

 function expandIt(url) {
        if(url == "#"){
                alert(phrase.narrow_select_alert);
        } else if (url == "deep" ) {
                var url1 = '/deepsearch.shtml';
                self.location=url1;
        } else {
                var url1 = '/SwishSearch?synsearch=true&spec_idx=ne&Keywords=' + ukeys;
                self.location=url1;
        }
 };

 function checkIt(string){
        place = detect.indexOf(string) + 1;
        thestring = string;
        return place;
 };

 function writeSimilar(myid,showid,myphotographer,myshortcaption,action,mode,myhrdlink,myreleased) { 
	if (typeof(writesimilar_custom) == 'function')
		return writesimilar_custom(myid,showid,myphotographer,myshortcaption,action,mode,myhrdlink,myreleased);
	else
		return writesimilar_standard(myid,showid,myphotographer,myshortcaption,action,mode,myhrdlink,myreleased);

 };

 function writeStandardSimilar(myid,showid,myphotographer,myshortcaption,action,mode,myhrdlink,myreleased) { 
	myhrdlink = ( myhrdlink || '' );
	myreleased = ( myreleased || '' );
        var simlist =st[showid];
        var simarray=simlist.split(" ");
 	var temparray = simarray[1].split(",");
 	if(temparray.length > 1){temparray=simarray[0] + ' ' + temparray.join(' ');simarray=temparray.split(' ');}
 	var simcount =simarray.length;
 	if(mode =='normal' || mode=='huge'){
         	if(parseInt(simcount) < 5 ){simindicator=simcount;} else {simindicator=4;}
 	} else {
         	if(parseInt(simcount) < 4 ){simindicator=simcount;} else {simindicator=3;}
 	}

         var thehtml='';
         var wmyid = myid;
     var setid = myid;
     var iconheight=15;var iconwidth=15;
 
         if (action == 'next'){
 
                 var n=sw[showid];
                 n++;
                 sw[showid] = n;
                 if(sw[showid] >= simcount) { sw[showid]=0;n=0;}
                 wmyid = simarray[n];
 
         } else if (action == 'prev'){
                 var n=sw[showid];
                 n--;
                 sw[showid] = n;
                 if(sw[showid] < 0) { sw[showid]=simcount - 1;n=simcount - 1;}
                 wmyid = simarray[n];
         }
 	//empty array fix for a single image returned which is a similar
 	if ( isNaN((sw[showid] + 1)) )
 		sw[showid] = 0;
 		var theight = 172 + adminheight;
         if (mode == 'list' || mode == 'editing'){
                 thehtml += '<table width=298 cellspacing=2 cellpadding=0 border0 height=' + theight + '><tr><td valign=top width=149 align=center>';
         }
         // similar graphics zzz
         thehtml += '<table cellpadding=0 cellspacing=0 border=0><tr><td colspan=2 align=right valign=bottom bgcolor=#c9c9c9 width=18 height=18>';
         thehtml += '<a href="javasc' + 'ript:enlarge2(\'' + myid + '\'' + ',' + '\'' + showid + '\', \''+wmyid+'\');" TITLE="ID:' + wmyid;
         if(showphotographer == 1){'  \r&copy; ' + myphotographer;}
         if(showfilesize){thehtml += '  \rSIZE: '+ myfilesize;}
         thehtml += '  \r' + 'CAPTION: ' + myshortcaption;
         if (mode == 'huge'){
                 thehtml += '"><img src="' + ImageUrl('420/60',wmyid) + '" border="0" alt="loading..." height="190"></a></td>';
         } else if( mode == 'med'){
                 iconheight=10;iconwidth=14;
                 thehtml += '"><img src="' + ImageUrl('135/50',wmyid) + '" border="0" vspace="0" hspace="0" alt="loading..." height=72></a></td>';
         } else if( mode == 'tiny'){
                 iconheight=8;iconwidth=12;
                 thehtml += '"><img src="' + ImageUrl('135/50',wmyid) + '" border="0" vspace="0" hspace="0" alt="loading..." height=45></a></td>';
 
         } else {
 				iconheight=12;iconwidth=16;
                 thehtml += '"><img src="' + ImageUrl('135/50',wmyid) + '" border="0" vspace="0" hspace="0" alt="loading..."></a></td>';
         }
         //simindicator="";
 
         thehtml += '<td background=/graphics/similars_rc' + simindicator + '.gif valign=top width=9><IMG SRC=/graphics/similars_ru' + simindicator + '.gif width=12 height=9></td></tr><tr height=8>';
         if(mode == 'normal' || mode=='huge' || mode=='large'){
 		thehtml += '<td background=/graphics/similars_ll' + simindicator + '.gif height=8 width=12></td><td background=/graphics/similars_lc' + simindicator + '.gif height=8><div style="width: 18px;height:8px;padding:0;margin:0;"></DIV></td>';
 	} else {
 		thehtml+='<td colspan=2 background=/graphics/similars_lc' + simindicator + '.gif height=8></td>';
 	}
 	thehtml += '<td width=12 height=8 background=/graphics/similars_lr' + simindicator + '.gif></td></tr></table>';
 
         if(mode == 'normal' || mode =='med' || mode == 'tiny' || mode=='large'){
                 thehtml += '<table cellpadding=0 cellspacing=0 border=0><tr><td valign=top align=center>';
         }
         if(mode != 'editing')
         {
        		thehtml += '<DIV class=icons><a href="javascript: return false;" onclick="lightbox_addto(\'' + wmyid + '\'); return false;" class=iconlink title="Add to your current lightbox">LB+</a>';
         	thehtml += '<a href="javascript: return false;" onclick="return price_image(\'' + wmyid + '\',\''+rm[wmyid]+'\');" class=iconlink Title="Price Image">$</a>';
         	thehtml += '<a href="javasc' + 'ript:enlarge2(\'' + wmyid + '\'' + ',' + '\'' + showid + '\');" class=iconlink title="Enlarge image and more info"><font class=eye>i</font></a>';
         	if(mode == 'huge'){
                 	//thehtml += '<font class=xsmall>' + wmyid + '</font>&nbsp;&nbsp;' + (myhrdlink ? '<a href="'+myhrdlink+'" class="hiresdl_link"><font color="#cc0000">Download Hires</font></a>' : '')+'&nbsp;&nbsp;';
 		} else if (mode == 'list') {
 			thehtml += '&nbsp;&nbsp;'+ (myhrdlink ? '<a href="'+myhrdlink+'" class="hiresdl_link"><font color="#cc0000">Download Hires</font></a>' : '')+'</DIV>';
         	} else {
         		thehtml += '</DIV>';
 		}
 	}
 
         /* if(mode == 'normal' || mode =='med' || mode == 'tiny' || mode =='large'){
            thehtml += '<br />';
         } */
 
         if(mode =='med' || mode == 'tiny'){
                 thehtml += '<font class=xsmall>' + wmyid + '</font>';
                 thehtml += '</td><td valign=top align=center width=40><nobr>';
         }
         if (mode == 'list' || mode == 'normal' || mode=='large' || mode == 'editing'){
                 thehtml += '</td><td valign="top">';
         }

         thehtml += '<A HREF="" onclick="writesimilar(\'' + setid + '\',\'' + showid + '\',\'';
         thehtml += myphotographer + '\',\'';
         thehtml += myshortcaption + '\',\'prev\',\'' + mode + '\', \'' + myhrdlink + '\',\'' + myreleased + '\'); return false;" TITLE="show similars">';
         thehtml += '<IMG SRC="/graphics/similars_prev.gif" border="0" hspace="1" height="' + iconheight + '" width="' + iconwidth + '" align="absmiddle"></A>';

         if (mode == 'list' || mode == 'huge' || mode == 'normal' || mode=='large' || mode == 'editing'){
                 thehtml += '<font class=xsmall>' + (sw[showid] + 1) + ' of ' + simcount + '</font>';
         }
 
         thehtml += '<A HREF="" onclick="writesimilar(\'' + setid + '\',\'' + showid + '\',\'';
         thehtml += myphotographer + '\',\'';
         thehtml += myshortcaption + '\',\'next\',\'' + mode + '\', \'' + myhrdlink + '\',\'' + myreleased + '\'); return false;" TITLE="show similars">';
         thehtml += '<IMG src="/graphics/similars_next.gif" border="0" hspace="1" height="' + iconheight + '" width="' + iconwidth + '" align="absmiddle"></A></nobr><br />';


         if (mode =='med' || mode == 'tiny'){
                 thehtml += '<font class=xsmall>' + (sw[showid] + 1) + ' of ' + simcount + '</font>';
         }
 
         if (mode == 'list' || mode == 'editing'){
                 thehtml += '<font class=xsmall>ID:' + wmyid;
                 if(showphotographer == 1){thehtml +='  <br />&copy; '+currentYear+' ' + myphotographer;}
                 if(showfilesize){thehtml += '<nobr>' + myfilesize + '</nobr>';}
                 thehtml += myreleased + '<br />CAPTION: ' + myshortcaption + '</font><br />';
 
                 if (mode == 'editing') {
                 	thehtml += '<br/><a href="javascript: return false;" onclick="launchwin(\'/SwishSearch?show_all=1&similar_to='+wmyid+'\', \'edit sims\', 600, 800, 100, 100); return false;" title="Edit Similar Images">Edit&nbsp;Similar&nbsp;Images</a>';
                 }
 
         }
 	if (mode== 'huge'){
 		thehtml += '</DIV>';
 	}
         thehtml += '</td></tr></table>';
        
	if( myhrdlink ) 
	thehtml += '<a href="'+myhrdlink+'" class="hiresdl_link"><font color="#cc0000">Download Hires</font></a>';
 
         if (action == 'start'){
                 return thehtml;
         }
         if (action == 'prev'){
                 MM_setTextOfLayer( 'd' + setid,'',thehtml);
         }
         if (action == 'next'){
                 MM_setTextOfLayer( 'd' + setid,'',thehtml);
         }
 };
 
 function popKeywords(oId, oLbj,oLbjname) {
	var topop = $(oId);
	if (topop)
	{
		if (topop.style.display == 'none')
		{
			topop.style.display = 'block';
			//top of lbbuttons - top of keyword div
			var toppos;
			if ($('lbbuttons'))
				toppos = Position.cumulativeOffset($('lbbuttons'))[1];
			else
				toppos = winH;
			
			var kwdht = toppos - Position.cumulativeOffset(topop)[1] + 'px'; 
			topop.style.maxHeight = kwdht;
			topop.style.overflowY = 'auto';
		}
		else
			topop.style.display = 'none';
	}
	if(oLbjname){
		oLbj = $(oLbjname);
	}

	if (oLbj)
	{
		if (oLbj.innerHTML == phrase.enlarge_showkeys_link)
			oLbj.innerHTML = phrase.enlarge_hidekeys_link;
		else if (oLbj.innerHTML == phrase.enlarge_hidekeys_link)
			oLbj.innerHTML = phrase.enlarge_showkeys_link;
	}
 };



};
function afShare() {

 this.checkID = checkID;
 this.makeShareControlString = makeShareControlString;
 this.saveReleaseControl = saveReleaseControl;
 this.saveShares = saveShares;
 this.shareSetPage = shareSetPage;
 this.toggleShareControlCookie = toggleShareControlCookie;
 this.validateRadioButtons = validateRadioButtons;

 function makeShareControlString(id,value) {

	if ( typeof id === 'object' && id.length )
		id = id.join('|');

	var sc_string = id + '|||' + value;
	return sc_string;
 };

 function toggleShareControlCookie(type) { //this turns your share control cookie on or off, which trips swishsearch
        var shmode = ggetCookie(gusername+'sc_on');
        if(!shmode || type ){ //turn on
                viewmode='editing';
		shmode = 1;
		
        }
	else //off
	{
		viewmode='';
		shmode = '';
	}

        gsetCookie('gviewmode',viewmode, '', '/', gGetCookieDom());
        gsetCookie(gusername+'sc_on',shmode, '', '/', gGetCookieDom());
	
	if (! type)
	{
		var s = self.location.href;
		self.location.href = s.replace(/\&sc_boot\=1/g, '');
	}

 };

 function checkID(idstring) { //function to check if an id Exists And is Defined as a form value
        if ($(idstring) && $F(idstring) && ! $F(idstring).match(/^\-\- .* \-\-$/))
                return true;
        else
                return false;
 };

 function saveShares(dex,which) { //SAVE OUR SHARES

        if (! which || which == 'share')
        {
                var share = $F('sharecontrol'+dex);
                ajax_JSON('/AjaxHandlers/ShareSetShare/'+make_share_control_string(id[dex], share)+'.json', getpost, '');
        }

        if (! which || which == 'weight')
        {
                var weight = $F('weightcontrol'+dex);
                ajax_JSON('/AjaxHandlers/ShareSetWeight/'+make_share_control_string(id[dex], weight)+'.json', getpost, '');
        }

        if( $('cellwrapper'+dex) )
                $('cellwrapper'+dex).style.backgroundColor = 'orange';
 };

 function saveReleaseControl(dex) { //SAVE RELEASE CONTROL..

	//get release
	var release = $A();
	var relstring = unescape(relcon[dex]).toString().replace(/checked="?checked"?/gi,''); 
	/// $('releasecontrol'+dex).innerHTML.toString().replace(/checked="checked"/gi,'');
	$A($('releasecontrol'+dex)).each( function(itm) {
		if (itm.checked)
		{
			release.push(itm.value);
			var relrex = new RegExp('value="'+itm.value+'"');
			relstring = relstring.replace(relrex, 'value="'+itm.value+'" checked="checked"');
		}
	});
	relcon[dex] = escape(relstring);

	release = release.join('|');
	ajax_JSON('/AjaxHandlers/ShareSetRelease/'+make_share_control_string(id[dex], release)+'.json', getpost, '');

	if( $('cellwrapper'+dex) )
		$('cellwrapper'+dex).style.backgroundColor = 'orange';
 };

 function validateRadioButtons(thar) {
        //radios are self limiting, no need for dex..
        if (! $(thar) && ! $F(thar))
                return;

        //gotta parse the id from name
        var nama = thar.name;
        nama = nama.replace(/(cocon|shcon)/, '');
        var pix = $F(thar);
        //more colors
//        stat            notshared       pending         shared
//        DF0000          red             white           green   77BB33

        var dex = $F($(thar).form.dexer);

        var brd = 'white';
	var status = 'pending';
        if (pix == 'n' || pix == 'r' || pix.match(/^(notshared|rejected)/) )
	{
		if (pix == 'n' || pix == 'notshared')
			status = 'notshared';
		else
			status = 'rejected';

                brd = '#DF0000';
	}
        else if (! isNaN(pix) || pix == 'a' || pix.match(/^shared/) )
	{
		status = 'shared';
                brd = '#77BB33';
	}
	else if ( pix.match(/^hold/) )
	{
		status = 'hold';
	}

        if ($('d'+nama))
                $('d'+nama).style.background = brd;

        var sharesync = unescape(shsync[dex]);
        sharesync=sharesync.split('|');
        shsync[dex] = escape( status + '|' + sharesync[1]);

	var save_str = '';
	if (thar.name.match(/shcon/))
		save_str = 'ShareSetShare';
	else
		save_str = 'ShareSetCombined';
	
        ajax_JSON('/AjaxHandlers/'+save_str+'/'+make_share_control_string(nama, pix)+'.json', getpost, '');

 };

 function shareSetPage(status) { //batch actions a page at a time only for separate share_control style 
//startnumber endnumber
	if (status == '')
		return;

	var shownIds = $A();
	var full_status = status + $F('share_control_view') + $F("share_control_home_sphotog");
        var comb_status = '';
        if ( typeof(cocon) == 'object' && cocon[0] )
        {
                comb_status = status.toString().substring(0,1);
        }


	for(var cnt = showstartnumber_trap; cnt < endnumber; cnt++)
	{
	    if ( id[cnt] )
	    {
		shownIds.push(id[cnt]);
		if (status.match(/pending|hold/))
		{
			$('d'+id[cnt]).style.background = 'white';
		}
		else if (status.match(/notshared|rejected/) )
			$('d'+id[cnt]).style.background = '#DF0000';
		else if (status.match(/^shared/))
			$('d'+id[cnt]).style.background = '#77BB33';

		var sForm = $('shf'+id[cnt]);
                if (sForm)
		    $A(sForm.elements).each( function(rad) {
        		if ( rad.value == full_status )
				rad.checked = true;
                        else if ( comb_status && ( rad.value == comb_status || ( comb_status == 's' && rad.value.match(/^[a1-4]$/ )  ) ) )
                                rad.checked = true;
			else
				rad.checked = false;
		    }); 

                var sharesync = unescape(shsync[cnt]);
                sharesync=sharesync.split('|');
		shsync[cnt] = escape(status + '|' + sharesync[1]);
	    }
		
	}
	ajax_JSON('/AjaxHandlers/ShareSetShare/'+make_share_control_string(shownIds, full_status)+'.json', getpost, '');
	return false;
 };


};
function afSystem() {

 this.debug = debug;
 this.empty = empty;
 this.getVars = getVars;
 this.screenInfo = screenInfo;
 this.debugon = debugon;
 this.debugoff = debugoff;

 function debug(mmm,val){
	if(typeof(debugmode) !='undefined' && debugmode=='yes'){
		alert(mmm + '=' + val);
	}
 };
 function debugon(){
	gsetCookie("debugmode",'yes', '', '/', gGetCookieDom());
	alert('debugmode on'); 
};
 function debugoff(){
	gsetCookie("debugmode",'no', '', '/', gGetCookieDom());
	alert('debugmode off'); 
 };

 function empty(){};

 //call this onload, will create a global object named urlParams.. so you access by urlParams.foo ...
 function getVars() {
	if (! document.location.href.split('?')[1])
		return;

	var varArray = document.location.href.split('?')[1].split('&');

	urlParams = new Object;

	for(var x=0; x<varArray.length; x++)
	{
		var tmp = varArray[x].split('=');
		if (tmp[0])
			urlParams[unescape(tmp[0])] =  unescape(tmp[1]) ;
	}
 };

 function screenInfo(){
        setuppagesize();
        alert($F('pixperpage') + " browser is " + browser + " and os is " + OS + 
				" width=" + document.body.offsetWidth + "," + self.innerWidth + "," + winW +
				" winH="+winH+", truevertHeight="+truevertHeight
				);
 };


};
function afURL() {

 this.createNextLink = createNextLink;

 function createNextLink (args) {

 var enlargeview = args['enlargeview'];
 var method = args['method'];
 var qArgs = args['q_args'];
 var qID = args['qID'];
 var ucats = args['ucats'];

 var color = args['color'];
 var date = args['date'];
 var orient = args['orient'];
 var preQArgs = args['preQArgs'];
 var scriptName = args['scriptName'];
 var searchInclude = args['searchInclude'];
 var sort = args['sort'];
 var specIdx = args['specIdx'];
 var VCDBrowse = args['VCDBrowse'];

 var nextLink = String(scriptName + "?" +
				(color ? "&color=" + color : '' ) + 
				( orient ? "&orient=" + orient : '' ) + 
				(specIdx ? "&spec_idx=" + specIdx : '' ) + 
				(sort ? "&sort=" + sort : '') + 
				(searchInclude ? "&searchinclude=" + searchInclude : '') + 
				((typeof(VCDBrowse) != 'undefined' && VCDBrowse) ? '&VCDBrowse='+VCDBrowse : '' )
			) ;


 if(typeof(qArgs) != 'undefined') 
  {
   if (qArgs.match(/lb_view=1/))         //if viewing lightbox, nextlink is different
    {
     nextLink += '&n=1&lb_view=1';
    }
   else if (qArgs.match(/rid=/))        //if viewing requests, nextlink is also different
    {
     var rid = qArgs.match(/rid=([^\&]+)/);
     if(rid[1])
	nextLink += '&n=1&rid='+rid[1];
    }
   else if (qArgs.match(/fn=/))
    {
     var fid = qArgs.match(/fn=([^\&]+)/);
     if(fid[1])
      nextLink += '&n=1&fn='+fid[1];
    }
  }

 var narrowURL = nextLink + "&snum=0";

 if(typeof(preQArgs) != 'undefined') //append VMO= info for nextlinks on lightboxes
  {
   var vmo_arg = preQArgs.match(/vmo=([^&]+)/);
   if (vmo_arg && vmo_arg[1])
     nextLink += '&vmo='+escape(vmo_arg[1]);
  }

 nextLink +=  "&method=" + method  + "&q_id=" + qID + "&" + ucats;

 if (enlargeview)
   setTimeout("enlarge2('"+enlargeview+"', 0)", 500);

 return ({narrowurl : narrowURL,
          nextlink : nextLink});

 };

};
function afWindow() {

 this.displayWindow = displayWindow;
 this.displayWindow2 = displayWindow2;
 this.maximizeScreen = maximizeScreen;
 this.popUp = popUp;

 function popUp(url, tle, ht, wd, px, py){ // for popups etc (primarily used on cart page)...
	if (!tle)
		tle = "newwindow";
	if (!ht)
		ht = 590;
	if (!wd)
		wd = 550;
	if (!px)
		px = 40;
	if (!py)
		py = 40;

	var newwin = window.open( url, tle, 'height=' + ht + ',width=' + wd + ',alwaysLowered=0,alwaysRaised=0,channelmode=0,dependent=1,directories=0,fullscreen=0,hotkeys=1,location=0,menubar=0,resizable=1,scrollbars=1,status=0,toolbar=0,z-lock=0,screenX=0,screeny=0,left=' + px + ",top=" + py);
	if (!newwin.opener) newwin.opener=( typeof(parent) != 'undefined' ? parent : self );
	if (newwin.focus) newwin.focus();
 };

 function maximizeScreen(){
        window.moveTo(0,0);
        window.resizeTo(screen.availWidth,screen.availHeight);
	if (self.location)
		self.location.href=self.location.href;
 };

/////////admin functions //////////////////////////
 function displayWindow(url, width, height) {
	if (navigator.appName == 'Netscape'){
		height = parseInt(height) + 16;
	}
	var Win = window.open(url,"displayWindow",'width=' + width + ',height=' + height + ',resizable=1,scrollbars=yes,menubar=no,status=no' );
	Win.focus();
 };

 function displayWindow2(url, width, height) {        
	var Win2 = window.open(url,"displayWindow2",'width=' + width + ',height=' + height + ',resizable=0,scrollbars=no,menubar=no,status=no' );
	Win2.focus();
 };

};


