/*******************************************************************************
* 2/17/2005                                                                    *
* D. Kadrioski                                                                 *
*                                                                              *
* Various utility functions from the DomAPI library.                           *
* Reproduced here license free.                                                *
*******************************************************************************/

//------------------------------------------------------------------------------
var core      = {};
core._private = {};
core.isIE     = document.all?true:false;
core.isGecko  = !core.isIE;  // for most KHTML functionality as well
core.isMoz    = core.isGecko;
core.isStrict = true;
var u = navigator.userAgent.toUpperCase();
core.isSafari  = (u.indexOf("SAFARI"   )>0);
core.isKHTML   = (u.indexOf("KONQUEROR")>0 || core.isSafari);
core.isFirefox = (u.indexOf("FIREFOX"  )>0);
var t = navigator.platform.toUpperCase().substr(0,3);
core.isWindows = (t=="WIN");
core.isMac     = (t=="MAC");
core.isLinux   = (t=="LIN");
core.isUnix    = (t=="UNI");
//------------------------------------------------------------------------------
core.isNil = function(s)  {return s==null || !String(s).length};  // value is null or blank
//------------------------------------------------------------------------------
core.rVal  = function(s,d){return(core.isNil(s)?(core.isNil(d)?"":d):s)}; // return value if not nil else default
core.rBool = function(v,d){return core.isNil(v)?d:v};
//------------------------------------------------------------------------------
core.rInt  = function(s,d){   // return value if integer else default
  s = parseInt(s);
  if(!isNaN(s))return s;
  return isNaN(d)?0:d;
};
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// array extensions
//------------------------------------------------------------------------------
Array.prototype.indexOf = function(v){for(var i=this.length;i>-1;i--)if((typeof this[i]!='undefined') && (this[i] == v))return i; return -1};
//------------------------------------------------------------------------------
Array.prototype.contains = function(v){return this.indexOf(v) > -1};
//------------------------------------------------------------------------------
Array.prototype.deleteItem  = function(i){
  if(i<0||i>(this.length-1))return; // out of range
  if(i==(this.length-1)){ // drop last item
    this.length--;
    return;
  }
  for(var a=(i+1);a<this.length;a++)
    this[a-1]=this[a];
  this.length--;
};
//------------------------------------------------------------------------------
Array.prototype.deleteValue = function(v){
  for(var i=this.length-1; i>=0; i--)
    if(this[i] == v)this.deleteItem(i);
};
//------------------------------------------------------------------------------
if(!Array.prototype.push)Array.prototype.push = function(v){
  this[this.length] = v;
};
//------------------------------------------------------------------------------
if(!Array.prototype.pop)Array.prototype.pop = function(){
  if(this.length<1)return null;
  var result = this[this.length-1];
  this.deleteItem(this.length-1);
  return result;
};
//------------------------------------------------------------------------------
Array.prototype.insert = function(i,v){
  if (i>-1)this.splice(i,0,v);
  else this.push(v);
};
//------------------------------------------------------------------------------
Array.prototype.swap = function(i,j){
  var t   = [this[i], this[j]];
  this[j] = t[0];
  this[i] = t[1];
};
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
core.addEvent = function(o,t,fn,useCapture){
  if(o.addEventListener){   // NS/MOZ DOMs evt
    o.addEventListener(t,fn, useCapture);
    return true;
  }else if(o.attachEvent){  // IEs DOMs evt
    var _addEvnRt = o.attachEvent("on"+t,fn);
    return _addEvnRt;
  }else
    throw new Error("HANDLER_NO_ATTACH");
};
//------------------------------------------------------------------------------
core.findParent = function(n,k){
  while(n){
    if(n.nodeName  == k)return n;
    if(n.DA_TYPE   == k)return n;
		if(n.className == k)return n;
    if(n           == k)return n;
    n = n.parentNode;
  }
  return null;
};
//------------------------------------------------------------------------------
core.findChild = function(n,k,recurse){
  var e,ee;
  for(var i=0;i<n.childNodes.length;i++){
    e = n.childNodes[i];
    if(e.nodeName == k)return e;
    if(e.DA_TYPE  == k)return e;
    if(e          == k)return e;
    if(recurse){
      ee = core.findChild(e,k,recurse);
      if(ee)return ee;
    }
  }
  return null;
};
//------------------------------------------------------------------------------
core.findChilden = function(n,k,recurse){
	// this method looks like it *should* work, but it doesn't....
  var e;
	var r = [];
  for(var i=0;i<n.childNodes.length;i++){
    e = n.childNodes[i];
    if(e.nodeName == k)r.push(e);
    if(e.DA_TYPE  == k)r.push(e);
    if(e          == k)r.push(e);
    if(recurse)
      r.join( core.findChilden(e,k,recurse));
  }
  return r;
};
//------------------------------------------------------------------------------
core.transferElm = function(e,t){
  var temp = e.parentNode.removeChild(e);
  if(core.isKHTML)
    t.insertAdjacentElement = insert__Adj;  
  t.insertAdjacentElement("beforeEnd",temp);
};
//------------------------------------------------------------------------------
core.getTrueOffset = function(e){
  var x=0; var y=0;
  if(!e)return [x,y];
  while(e !=null && e !=document.body){
    x += e.offsetLeft;
    y += e.offsetTop;
    e = e.offsetParent;
  }
  return [x,y];
};
//------------------------------------------------------------------------------
// See http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/unselectable.asp
// GX SBE
core.setUnselectable = function(element){
  var i;
  if(element.nodeType==1) {
    element.unselectable="on";
    for(i=0; i<element.childNodes.length; i++) {
      core.setUnselectable(element.childNodes[i]);
    }
  }
};
//------------------------------------------------------------------------------
core.disallowSelect = function(e){
  core.addEvent(e, "selectstart", core._nullFunction);
  core.addEvent(e, "mousedown",   core._nullFunction);
  core.addEvent(e, "mousemove",   core._nullFunction);
  e.style.userSelect = "none";
  if(core.isIE)core.setUnselectable(e);
};
//------------------------------------------------------------------------------
core.preventBubble = function(E){
  if(core.isIE){
    event.cancelBubble = true;
    event.returnValue  = false;
  }else{
    if(E.stopPropagation)E.stopPropagation();
    else E.preventBubble();
    // GX SBE
    if(E.preventDefault)E.preventDefault();
  }
};
//------------------------------------------------------------------------------
core._nullFunction = function(E){
  if(core.isGecko)E.preventDefault();
  return false;
};
//------------------------------------------------------------------------------
core.getTarget = function(E){return core.isGecko?E.target:event.srcElement};
//------------------------------------------------------------------------------
// based on the target node of the event passed, searches up the tree for a particular node type (k)
core.findTarget = function(E,k){return core.findParent(core.getTarget(E),k)};
//------------------------------------------------------------------------------
core.getNodeIndex = function(n){
  // returns the index of a childnode in relation to its siblings
  if(!n)return null;
  r = 0;
  var t = n.previousSibling;
  while(t){
    r++;
    t = t.previousSibling;
  }
  return r;
};
//------------------------------------------------------------------------------
core.scrollLeft = function(){return this.isIE?document.documentElement.scrollLeft:pageXOffset};
core.scrollTop  = function(){return this.isIE?document.documentElement.scrollTop :pageYOffset};
//------------------------------------------------------------------------------
core.bodyWidth  = function(){try{return parseInt(core.isIE?(!core.isStrict?document.body.clientWidth: document.documentElement.clientWidth ):window.innerWidth)}catch(e){}};
core.bodyHeight = function(){try{return parseInt(core.isIE?(!core.isStrict?document.body.clientHeight:document.documentElement.clientHeight):window.innerHeight)}catch(e){}};
//------------------------------------------------------------------------------
String.prototype.trim = function(){
  var s = this.replace(new RegExp("^\\s+", "g"),"");
  return s.replace(new RegExp("\\s+$", "g"),"");
};
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
core.hideSelects = function(b){
  var i, e;
  var A = document.getElementsByTagName("SELECT");
  for(i=0;i<A.length;i++){
    e = A[i];
    if(!b){
      if(e._spHidden2){
        e.style.visibility = "visible";
        e._spHidden2 = false;
      }
    }else{
      e.style.visibility = (b?"hidden":"visible");
      e._spHidden2        = b;
    }
  }
};
//------------------------------------------------------------------------------
core.hideSelectsBeneath = function(t,b,onlyOutside){
  var i, e, x1,x2,y1,y1,ex1,ex2,ey1,ey2;
  var A = document.getElementsByTagName("SELECT");
  
  var ex1 = t.offsetLeft;
  var ex2 = t.offsetWidth  + ex1;
  var ey1 = t.offsetTop;
  var ey2 = t.offsetHeight + ey1;

  for(i=0;i<A.length;i++){
    e = A[i];
    x1 = e.offsetLeft;
    x2 = e.offsetWidth  + x1;
    y1 = e.offsetTop;
    y2 = e.offsetHeight + y1;
    if(!b){
      if(e._spHidden){
        if(!onlyOutside || (((x1 > ex2) || (x2 < ex1) || (y1 > ey2) || (y2 < ey1)))){
          e.style.visibility = "visible";
          e._spHidden = false;
        }
      }
    }else{
      if(!((x1 > ex2) || (x2 < ex1) || (y1 > ey2) || (y2 < ey1))){
        e.style.visibility = (b?"hidden":"visible");
        e._spHidden        = b;
      }
    }
  }
};
//------------------------------------------------------------------------------
if(core.isIE){
  core.msXmlValidProgId = "";
  var _msXmlProgIdCollection = ["MSXML2.XMLHTTP", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.5.0",
                                "MICROSOFT.XMLHTTP", "MICROSOFT.XMLHTTP.1.0", "MICROSOFT.XMLHTTP.1"];
  // Iterate xml prog ids in search for the correct one to use
  for (var i=0; i < _msXmlProgIdCollection.length; i++) {
    // Try the iterated engine
    try {
      // Create the object. An error is automatically thrown if it doesn't exist or in any other way isn't allowed to be created
      var _msXmlProgObj = new ActiveXObject(_msXmlProgIdCollection[i]);
      // Still here? Well, then it seems like the activex object was created successfully. Store the current engine and exit the loop.
      core.msXmlValidProgId = _msXmlProgIdCollection[i];
      break;
    } catch (ex) { 
      // Doh! The currently tested engine didn't work. We might still be in the loop though so no despair yet...
    } 
  } 
  if (core.msXmlValidProgId == "") {
    throw new Error(core.getString("ERR_NO_MS_XMLHTTP"));
  }
  _msXmlProgIdCollection = null; delete _msXmlProgIdCollection;
  _msXmlProgObj          = null; delete _msXmlProgObj;
}
//------------------------------------------------------------------------------
core.getContent = function(url, debug){
  try{
    var req;
    var _url = url + ((url.indexOf("?")!=-1)?"&":"?") + "ds=" + new Date().getTime();
    if(core.isIE   )req = new ActiveXObject(core.msXmlValidProgId);
    if(core.isGecko)req = new XMLHttpRequest();
    req.open("GET",_url,false);
    req.send(null);
    if(debug)alert("URL:\n" + url + "\n\nRESULT:\n" + String(req.responseText).trim());
    return req.responseText;
  }catch(e){
    throw new Error(e.message);
    return "";
  }
};
//------------------------------------------------------------------------------
core.postContent = function(url, name, value, skipCacheBuster){
  try{
    var req;
    var _url = url;
    if(!skipCacheBuster)
      _url = _url + ((_url.indexOf("?")!=-1)?"&":"?") + "ds=" + new Date().getTime();
    if(core.isIE   )req = new ActiveXObject(core.msXmlValidProgId);
    if(core.isGecko)req = new XMLHttpRequest();
    req.open("POST",_url,false);
    req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    req.send(name + "=" + value);
    var r = req.responseText;
    req = null; delete req;
    return r;
  }catch(e){
    throw new Error(e.message);
    return "";
  }
};
//------------------------------------------------------------------------------
core.urlToJson = function(url, debug){
  return core.stringToJson(core.getContent(url, debug).trim());
};
//------------------------------------------------------------------------------
core.stringToJson = function(s){//alert(s);return
  try{
    eval("this.__r = " + s);
    return this["__r"];
  }catch(e){
    throw new Error("converting stringToJson\nMessage: " + e.message + "\njson: " + s);
    return {};
  }  
};
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// a collection of routines for manipulating class values containing multiple classNames
// for instance, e.className = "DA_COMPONENT DA_BUTTON"; 
// core.css.removeClass(e, "DA_BUTTON");
//------------------------------------------------------------------------------
core.css = {};
core.css.hasClass = function(e, cname){
  //var re = new RegExp("[^\s]+" + cname + "[$\s]+", "i");
  var re = new RegExp( cname , "i");
  return re.test(e.className);
};
//------------------------------------------------------------------------------
core.css.addClass = function(e, cname, optionalBool){
  if(!e || typeof e.className == "undefined")return;
  this.removeClass(e, cname);
  if(arguments.length == 3 && !optionalBool)return; // just wanted to remove it
//  core.dump([core.css.hasClass(e, cname), e.className]);
  if(core.css.hasClass(e, cname))return; // nothing to add
  var a = String(e.className).split(" ");
  a.push(cname);
  try{
    e.className = String(a.join(" ")).trim();
  }catch(E){ /* safari 1.2 would sometimes choke here */ };
};
//------------------------------------------------------------------------------
core.css.removeClass = function(e, cname){
  if(!e || typeof e.className == "undefined")return;
  if(!core.css.hasClass(e, cname))return; // nothing to remove
  var a = String(e.className).split(" ");
  a.deleteValue(cname);
  try{
    e.className = String(a.join(" ")).trim();
  }catch(E){ /* safari 1.2 would sometimes choke here */ };
};
//------------------------------------------------------------------------------
core.css.replaceClass = function(e, cname1, cname2){
  this.removeClass(e, cname1);
  this.addClass(   e, cname2);
};
//------------------------------------------------------------------------------


//------------------------------------------------------------------------------
core.createIFrameShield = function(){
  var e = document.createElement("IFRAME");
  try{
    e.style.position = "absolute";
    e.style.left     = "0px"; 
    e.style.top      = "0px";
    e.style.width    = "100px";
    e.style.height   = "100px";
    e.frameBorder    = "0";
    e.scrolling      = "no";e.style.backgroundColor="red";
    if(core.isKHTML)
      e.style.setProperty("opacity", 0, "");
    else if(core.isGecko)
			e.style.setProperty("-moz-opacity", 0.5, "");
    else if(core.isIE)
			e.style.filter = "alpha(opacity=0)";

    return e;
  }finally{
    e = null;
  }
};
//------------------------------------------------------------------------------
core.__iframeGetDocument = function(e){
  try{
    /*if(core.isIE && core.major==5)return e.document;
    else*/ return (core.isIE?e.contentWindow.document:e.contentDocument);
  }catch(E){
  }
};
//------------------------------------------------------------------------------
core.loadIframe = function(I,url,doCacheBuster){
  try{
    doCacheBuster = core.rBool(doCacheBuster, false);
    var _url = (doCacheBuster?url.addUrlParam("dacb",new Date().getTime() + Math.random()*1000):url);
    setTimeout(function(){
      try{
        var D = core.__iframeGetDocument(I);
        if(D)
          D.location.replace(_url);
        else
          I.src = _url;
      }catch(E){
        throw new Error(E.message + "\n" + url); 
      }finally{
        D = null;
      }
    },20); // closure
  }catch(E){
    throw new Error(E.message + "\n" + url);
  }
};
//------------------------------------------------------------------------------
core.blinkElement = function(e, fgcolors, bgcolors, count, rate){
	count = core.rInt(count, 5);
	rate  = core.rInt(rate,  200);
	while(fgcolors.length < 3)fgcolors[fgcolors.length] = fgcolors[0];
	while(bgcolors.length < 3)bgcolors[bgcolors.length] = bgcolors[0];
	e._blink = {
		fgcolors : fgcolors,
		bgcolors : bgcolors,
		count    : count,
		index    : 0,
		timer    : setInterval( function(){core._blinkElement( e )}, rate )
	};
};
//------------------------------------------------------------------------------
core._blinkElement = function(e){
	var b = e._blink;
	b.index++;
	if(b.index < b.count){
		e.style.color           = b.fgcolors[ b.index % 2 ];
		e.style.backgroundColor = b.bgcolors[ b.index % 2 ];
	}else{
		clearTimeout(b.timer);
		e.style.color           = b.fgcolors[ 2 ];
		e.style.backgroundColor = b.bgcolors[ 2 ];
	}
};
//------------------------------------------------------------------------------
