var Core = {};

// W3C DOM 2 Events model
if (document.addEventListener)
{
  Core.addEventListener = function(target, type, listener)
  {
    target.addEventListener(type, listener, false);
  };

  Core.removeEventListener = function(target, type, listener)
  {
    target.removeEventListener(type, listener, false);
  };

  Core.preventDefault = function(event)
  {
    event.preventDefault();
  };

  Core.stopPropagation = function(event)
  {
    event.stopPropagation();
  };
}
// Internet Explorer Events model
else if (document.attachEvent)
{
  Core.addEventListener = function(target, type, listener)
  {
    // prevent adding the same listener twice, since DOM 2 Events ignores
    // duplicates like this
    if (Core._findListener(target, type, listener) != -1) return;

    // listener2 calls listener as a method of target in one of two ways,
    // depending on what this version of IE supports, and passes it the global
    // event object as an argument
    var listener2 = function()
    {
      var event = window.event;

      if (Function.prototype.call)
      {
        listener.call(target, event);
      }
      else
      {
        target._currentListener = listener;
        target._currentListener(event)
        target._currentListener = null;
      }
    };

    // add listener2 using IE's attachEvent method
    target.attachEvent("on" + type, listener2);

    // create an object describing this listener so we can clean it up later
    var listenerRecord =
    {
      target: target,
      type: type,
      listener: listener,
      listener2: listener2
    };

    // get a reference to the window object containing target
    var targetDocument = target.document || target;
    var targetWindow = targetDocument.parentWindow;

    // create a unique ID for this listener
    var listenerId = "l" + Core._listenerCounter++;

    // store a record of this listener in the window object
    if (!targetWindow._allListeners) targetWindow._allListeners = {};
    targetWindow._allListeners[listenerId] = listenerRecord;

    // store this listener's ID in target
    if (!target._listeners) target._listeners = [];
    target._listeners[target._listeners.length] = listenerId;

    // set up Core._removeAllListeners to clean up all listeners on unload
    if (!targetWindow._unloadListenerAdded)
    {
      targetWindow._unloadListenerAdded = true;
      targetWindow.attachEvent("onunload", Core._removeAllListeners);
    }
  };

  Core.removeEventListener = function(target, type, listener)
  {
    // find out if the listener was actually added to target
    var listenerIndex = Core._findListener(target, type, listener);
    if (listenerIndex == -1) return;

    // get a reference to the window object containing target
    var targetDocument = target.document || target;
    var targetWindow = targetDocument.parentWindow;

    // obtain the record of the listener from the window object
    var listenerId = target._listeners[listenerIndex];
    var listenerRecord = targetWindow._allListeners[listenerId];

    // remove the listener, and remove its ID from target
    target.detachEvent("on" + type, listenerRecord.listener2);
    target._listeners.splice(listenerIndex, 1);

    // remove the record of the listener from the window object
    delete targetWindow._allListeners[listenerId];
  };

  Core.preventDefault = function(event)
  {
    event.returnValue = false;
  };

  Core.stopPropagation = function(event)
  {
    event.cancelBubble = true;
  };

  Core._findListener = function(target, type, listener)
  {
    // get the array of listener IDs added to target
    var listeners = target._listeners;
    if (!listeners) return -1;

    // get a reference to the window object containing target
    var targetDocument = target.document || target;
    var targetWindow = targetDocument.parentWindow;

    // searching backward (to speed up onunload processing), find the listener
    for (var i = listeners.length - 1; i >= 0; i--)
    {
      // get the listener's ID from target
      var listenerId = listeners[i];

      // get the record of the listener from the window object
      var listenerRecord = targetWindow._allListeners[listenerId];

      // compare type and listener with the retrieved record
      if (listenerRecord.type == type && listenerRecord.listener == listener)
      {
        return i;
      }
    }
    return -1;
  };

  Core._removeAllListeners = function()
  {
    var targetWindow = this;

    for (id in targetWindow._allListeners)
    {
      var listenerRecord = targetWindow._allListeners[id];
      listenerRecord.target.detachEvent(
          "on" + listenerRecord.type, listenerRecord.listener2);
      delete targetWindow._allListeners[id];
    }
  };

  Core._listenerCounter = 0;
}

Core.addClass = function(target, theClass)
{
  if (!Core.hasClass(target, theClass))
  {
    if (target.className == "")
    {
      target.className = theClass;
    }
    else
    {
      target.className += " " + theClass;
    }
  }
};

Core.getElementsByClass = function(theClass)
{
  var elementArray = [];

  if (document.all)
  {
    elementArray = document.all;
  }
  else
  {
    elementArray = document.getElementsByTagName("*");
  }

  var matchedArray = [];
  var pattern = new RegExp("(^| )" + theClass + "( |$)");

  for (var i = 0; i < elementArray.length; i++)
  {
    if (pattern.test(elementArray[i].className))
    {
      matchedArray[matchedArray.length] = elementArray[i];
    }
  }

  return matchedArray;
};

Core.hasClass = function(target, theClass)
{
  var pattern = new RegExp("(^| )" + theClass + "( |$)");

  if (pattern.test(target.className))
  {
    return true;
  }

  return false;
};

Core.removeClass = function(target, theClass)
{
  var pattern = new RegExp("(^| )" + theClass + "( |$)");

  target.className = target.className.replace(pattern, "$1");
  target.className = target.className.replace(/ $/, "");
};

Core.getComputedStyle = function(element, styleProperty)
{
  var computedStyle = null;

  if (typeof element.currentStyle != "undefined")
  {
    computedStyle = element.currentStyle;
  }
  else
  {
    computedStyle = document.defaultView.getComputedStyle(element, null);
  }

  return computedStyle[styleProperty];
};
/////////////////////////////////////////////////////////////////////////////////////
Core.inStrReplace = function (str,replaceThis,withThis)
{
	/* /////////////////////////////////////////
	Developer : Chayne Walsh
	Date : 14th March 2007
	Copyright : none , please send any improvements to development@chayne.net
	Regexp replacing.
	var regExpProtocols = "(http://|mailto:|ftp://|https://)";
	url = this.inStrReplace(url,regExpProtocols,'');
	////////////////////////////////////////// */
	var replaceThis = new RegExp(replaceThis,"gi");
	str = str.replace(replaceThis,withThis);
	return str;
}

Core.Trim = function(sString) 
{
	while (sString.substring(0,1) == ' ')
	{
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

Core.createXHR = function() 
{
	var request;
	if (window.XMLHttpRequest)// Mozilla, Safari, ...
	{ 
		request = new XMLHttpRequest();
		if (request.overrideMimeType) { request.overrideMimeType('text/xml'); }
	}
	else if (window.ActiveXObject)// IE
	{ 
		try
		{
			request = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){}
		}
	}

	if (!request)
	{
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}
	
	return request;
}

Core.getQueryString = function (q)
{
	/*/////////////////////////////////////////
	Developer : Original Unknown and Chayne Walsh
	Version Date : 2007-03-28-02
	Querystring extractor
	//////////////////////////////////////////*/
	var qs = location.search.substring(1);
	var nv = qs.split('&');
	var url = new Object();
	for(i = 0; i < nv.length; i++)
	{
		eq = nv[i].indexOf('=');
		url[nv[i].substring(0,eq)] = unescape(nv[i].substring(eq + 1));
	}
	return (url[q]) ? url[q] : '' ;
}

Core.getEnv = function (op)
{
	var r='';
	var strPathName = new String(window.location.pathname);
	splitPathName = strPathName.split("/");
	if( op == 'PAGE_NAME_FULL' )
	{
		var pageName = '';
		pageName = splitPathName[splitPathName.length -1].split('?');
		r = pageName[0];
	}
 	if(op == 'SCRIPT_NAME')
	{
		splitPathName.pop();
		r = splitPathName.join("/");
	}
	if(op == 'DOCUMENT_ROOT')
	{
		r = (window.location.hostname=='localhost') 
		? "c:/www/domains/lockforce.com.au/" // document root of your development server 
		: ''; // document root of your deployment server
	}
	if(op == 'HTTP_ROOT')
	{
		r = (window.location.hostname=='localhost') 
		? "http://"+window.location.hostname+'/'+splitPathName[1] + "/" //iis virtual
		: "http://"+window.location.hostname + "/" ;
	}
	
	if(op == 'RELATIVE_ROOT')
	{
		var r = '';
		var directoryDepth = (window.location.hostname=='localhost')
		? splitPathName.length - 3 
		: splitPathName.length -3;
		if(directoryDepth > 0)
		{
			r='';
			for(i = 0; i < directoryDepth; i++)
			{
				r += '../';
			}
		}
	}
	return r;
}

Core.setGrayScale = function (bid,grayscale)
{
	try
	{
		bid = ( typeof bid == 'object' ) ? bid : document.getElementById(bid) ;
		if ( grayscale < 0 || grayscale > 1 ) grayscale = false;
		if (bid.filters)
		{
			if ( grayscale != false ) bid.style.filter='progid:DXImageTransform.Microsoft.BasicImage(grayscale=' + grayscale +')';
		}
	}
	catch (e) {/*do nothing*/};
}
Core.setOpacity = function ( id, opacity )
{
	try
	{
		var object = ( typeof id == 'object' ) ? id.style : document.getElementById(id).style ;
		object.opacity = (opacity / 100); 
		object.MozOpacity = (opacity / 100); 
		object.KhtmlOpacity = (opacity / 100); 
		object.filter = "alpha(opacity=" + opacity + ")"; 
	}
	catch (e) { /*do nothing*/}
} 
Core.opacityFlash = function (id, opacStart, opacEnd, millisec)
{
	try
	{
		var speed = Math.round(millisec / 100); 
		var timer = 0; 
		
		if(opacStart > opacEnd)
		{ 
			for(i = opacStart; i >= opacEnd; i--)
			{ 
				setTimeout("Core.setOpacity('" + id + "'," + i + ")",(timer * speed)); 
				timer++; 
			} 
		}
		else if(opacStart < opacEnd)
		{ 
			for(i = opacStart; i <= opacEnd; i++) 
			{ 
				setTimeout("Core.setOpacity('" + id + "'," + i + ")",(timer * speed)); 
				timer++; 
			} 
		} 
	}
	catch (e) {/*do nothing*/}
} 

Core.start = function(runnable)
{
  Core.addEventListener(window, "load", runnable.init);
};

