/**
 * @version $Rev: 437 $
 */

/**
 * @namespace
 */
var DML = DML || {};

// eCOM Loader Configuration for AJL
DML.LoaderConfig = DML.LoaderConfig || {};
DML.LoaderConfig.ecomUrl = 'http://ecom0.dmclub.net/'; // In future, this will be determined by client failover logic

// -------------------------------------------------------------------------------------------------
/* Dealers: Don't change anything below here */
// -------------------------------------------------------------------------------------------------

// Make sure all the console functions we are using are defined,
// but don't overwrite any existing ones (e.g. Opera)
var f = function() {};
var u = 'undefined';
var c = typeof console == u ? {} : console;
if (typeof c.log 	== u) c.log 	= f;
if (typeof c.dir 	== u) c.dir 	= f;
if (typeof c.assert == u) c.assert 	= f;
if (typeof console  == u) console = c;

var FastInit;

/*
*
* Copyright (c) 2007 Andrew Tetlaw
*
* 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.
* *
*
*
* FastInit
* http://tetlaw.id.au/view/javascript/fastinit
* Andrew Tetlaw
* Version 1.4.1 (2007-03-15)
* Based on:
* http://dean.edwards.name/weblog/2006/03/faster
* http://dean.edwards.name/weblog/2006/06/again/
* Help from:
* http://www.cherny.com/webdev/26/domloaded-object-literal-updated
*
*/
/**
 * Module providing onDOMReady event
 *
 * @namespace
 */
DML.FastInit = DML.FastInit || function()
{
	return {
		/**
		 * Executues a series of user-attached callback functions, when onLoad fires
		 *
		 * @name onLoad
		 * @methodOf DML.FastInit
		 */
		onLoad : function() {
			// Do not execute if called once already
			if (this.done) { return; }
			// Call every function in the function queue
			for(var x = 0, al = this.f.length; x < al; x++) {
				this.f[x]();
			}
			this.done = true; // Flag that onload has been called
		},

		/**
		 * Add a callback function to the stack of functions that will be called when onLoad fires
		 *
		 * Function expects one or more functions as arguments
		 *
		 * @name addOnLoad
		 * @methodOf DML.FastInit
		 */
		addOnLoad : function() {
			var a = arguments;
			// Iterate over function arguments
			for(var x = 0, al = a.length; x < al; x++) {
				// Check that argument is a function
				if(typeof a[x] === 'function') {
					if (this.done) {
						// OnLoad has already fired, call immediately
						a[x]();
					} else {
						// Queue function for execution when onLoad fires
						this.f.push(a[x]);
					}
				}
			}
		},

		/**
		 * Attach a callback, which calls onLoad, to the brower event that fires when the DOM is ready
		 *
		 * @name listen
		 * @methodOf DML.FastInit
		 */
		listen : function() {
            var module = this;
            var callback = function() { module.onLoad(); };
			if (/WebKit|khtml/i.test(navigator.userAgent)) {
				// Safari, Chrome, Konquerer
				this.timer = setInterval(function() {
					if (/loaded|complete/.test(document.readyState)) {
						clearInterval(this.timer);
						delete this.timer;
						callback();
					}}, 10);
			} else if (document.addEventListener) {
				// Firefox - or any standards compliant modern browser
				document.addEventListener('DOMContentLoaded', callback, false);
			} else if(!this.iew32) {
				// Bad browsers
				if(window.addEventListener) {
					window.addEventListener('load', callback, false);
				} else if (window.attachEvent) {
					return window.attachEvent('onload', callback);
				}
			}
		},

        f:[],
        done:false,
        timer:null,
        iew32:false
	};
	/*@cc_on @*/
	/*@if (@_win32)
	FastInit.iew32 = true;
	document.write('<script id="__ie_onload" defer src="' + ((location.protocol == 'https:') ? '//0' : 'javascript:void(0)') + '"><\/script>');
	document.getElementById('__ie_onload').onreadystatechange = function(){if (this.readyState == 'complete') { DML.FastInit.onLoad(); }};
	/*@end @*/
}();

// -------------------------------------------------------------------------------------------------
// Library Loader class

/**
 * Class to assist loading javascript libraries from javascript.
 * In the future this will also do failover.
 *
 * @constructor
 * @param {String} baseURL The base URL from which an instance of this class will load libraries
 */
DML.Loader = DML.Loader || function(baseURL) {

    var my = {
        'baseUrl': baseURL
    };

    var obj = {

        /**
         * Loads a library
         *
         * @methodOf DML.Loader#
         * @name loadLib
         * @param {String} libName The path to the library (relative to baseURL)
         */
        loadLib: function(libName)
        {
			console.log('Attempting to load ' + my.baseUrl + libName);
            document.write("\n" + '<script type="text/javascript" src="'  + my.baseUrl + libName + '"></scr');
			document.writeln("ipt>");
        }
   }

   return obj;
};

// -------------------------------------------------------------------------------------------------
// eComponent Activator class

/**
 * Activates eComponents.
 *
 * @constructor
 */
DML.Activator = DML.Activator || function() {
    var my = {
        'ecomUrl': DML.LoaderConfig.ecomUrl,
        'cookiesEnabled': null
    };

    return {

        /**
         * Activates all the eComs on a host page
         *
         * @methodOf DML.Activator#
         * @name activateAllEcoms
         */
        activateAllEcoms : function()
        {
            this.checkCookiesEnabled();
            var ecoms = this.findEcoms();
            for (var i = 0; i < ecoms.length; i++)
            {
                console.log('Activating ecom ' + i);
                this.activateEcom(i, ecoms[i]);
            }
        },

        /**
         * Finds the eComponents in a host page
         *
         * @methodOf DML.Activator#
         * @name findEcoms
         */
        findEcoms: function()
        {
            var iframes = document.getElementsByTagName('iframe');
            var ecoms = [];
            for (var i = 0; i < iframes.length; i++)
            {
                if (iframes[i].getAttribute('ecom_src') != null) ecoms.push(iframes[i]);
            }
            return ecoms;
        },

        /**
         *
         * @methodOf DML.Activator#
         * @name activateEcom
         */
        activateEcom : function(index, ecom)
        {
            if (my.cookiesEnabled)
            {
                var char = String.fromCharCode(98 + index); // 98 is ascii for b
                var origecomsrc = ecom.getAttribute('ecom_src') + '&c.sessref=' + DML.Track.getStep() + '_' + char;
                var ecomsrc = origecomsrc;
                ecomsrc = ecomsrc.replace('self.name', self.name);
                ecom.setAttribute('src', ecomsrc);
                ecom.removeAttribute('ecom_src'); // Prevent verbose code when 'Show code' is clicked in the DMR Showcase
                console.log('changing ecom.src to ' + ecomsrc);
            }
            else
            {
               ecom.src = my.ecomUrl + 'cookiewarning.php'; // Fills the eCom iFrame with a warning message
            }
        },

        checkCookiesEnabled: function() {
            document.cookie = "test=Y";
            my.cookiesEnabled = (document.cookie.indexOf("test=Y") != -1);
        }

   }
};

// -------------------------------------------------------------------------------------------------
// ECC module

DML.ECC = DML.ECC || function() {

    var my = {
        'ecomUrl': DML.LoaderConfig.ecomUrl,
        'initialized': false
    };

    return {
        // Initializes the module
        initialize: function()
        {
            if (my.initialized) return; // Only initialise once

			console.log('INITIALISING SESSION: This loads libs and gets a session reference');
			console.log('------------------------------------------------------------------');
            var loader = DML.Loader(my.ecomUrl);
            loader.loadLib('js/core.js');
            loader.loadLib('js/track.js');
            loader.loadLib('js/track_check.js'); // This is not reliable in IE8
            DML.FastInit.listen();
            DML.FastInit.addOnLoad(function() { DML.ECC.activateEComponents(); });
			my.initialized = true;
        },

        activateEComponents: function()
        {
			console.log(' ');
			console.log('ACTIVATING ECOMPONENTS');
			console.log('----------------------');
            console.assert(DML.Track);
            var activator = DML.Activator();
            activator.activateAllEcoms();
        }

    }
}();

// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// RUN THE FOLLOWING...

var SUPPRESS_INITIALIZE;
if (SUPPRESS_INITIALIZE) {} else {
    DML.ECC.initialize();
}
