/*global DGS, OT, actions, jQuery, $, $$, addEventListener, alert, blur, clearInterval, clearTimeout, close, closed, confirm, console, Debug, defaultStatus, document, window, event, events, focus, frames, getComputedStyle, history, Image, length, location, moveBy, moveTo, name, navigator, onblur: true, onerror: true, onfocus: true, onload: true, onresize: true, onunload: true, open, opener, opera, Option, parent, print, prompt, resizeBy, resizeTo, screen, scroll, scrollBy, scrollTo, setInterval, setTimeout, status, top, XMLHttpRequest */


/**  DGS : Digitas Javascript Object, version 0.1.0
 *--------------------------------------------------------------------------*/
/**
 *  Create the DGS namespace, on which framework's elements will be based 
 *  @type {function}
 *  @author Vincent Desbarres, Philippe Lecocq, Laurent Leborgne
 *  @version 0.1.0
 *  @constructor
 */
var DGS = (function DGS(params){
	//to avoid error if the new word has been forgotten when creating instance
	 if (!(this instanceof arguments.callee)) { 
        return new DGS(params); 
    } 
	this.id = "DGS Javascript Object";	
	this.loaderImg=	"/media/img/loader.gif";
	this.version = {		
		major: 0, 
		minor: 1,
		patch: 0,
		flag: "",
		toString: function(){
			with (d.version) {
				return major + "." + minor + "." + patch + flag; // String
			}
		}
	};	
	// manage rendering and calculation time to see if something's going too long	
   	this.t = new Date().getTime();
	this.calcTime = "Calculation time: " + ((new Date().getTime() - this.t) / 1000.0) + "s";
	/**
	 * array for all local variables associated to the instance
	 */
	this.elmts = [];
	// create a few global framework settings 
	// choose using google.load or not
	// if using it, choose loading a specific js library from google CDN or not
	/**
	 *  settings object
	 *	@name defaults
	 *  @type {object}
	 */
	 /*
	 *  @param {boolean} settings.useGoogleLoad
	 *  @param  {string} settings.jsLib  name of js library to load through google load
	 *  @param  {string} settings.jsLibVersion version of js library to load through google load
	 *  @param  {boolean} settings.jsLibIsloaded true/false flag to indicate if the js library has been loaded
	 *  @param  {boolean} settings.useJsLibLocalLoad  true/false to use the js local library or not
	 *  @param  {string} settings.jsLibLocalUrl local url for js library
	 *  @param  {string} settings.jsPluginPath path for all DGS plugins
	 *  @param  {string} settings.loadedJsListing will contain a list of external js file loaded through the DGS loading module
	 *  @param  {boolean} settings.debugMode true/false to activate the debug mode
	 *  @param	{Object} pluginList contains a listing for all DGS plugins available, so that they can be loaded easily
	 *  @param  {string} settings.ieFirebugLiteUrl url for firebug lite debugging tool
	 *  
	 */
	
	this.defaults = {
		useGoogleLoad : false,										// true/false to use google load for js library
		jsLib : "jquery",											// name of js library to load through google load
		jsLibVersion: "1.3.2",										// version of js library to load through google load
		jsLibIsloaded : false,										// true/false flag to indicate if the js library has been loaded		
		useJsLibLocalLoad : false,									// true/false to use the js local library or not
		jsLibLocalUrl: "/scripts/lib/Jquery/jquery-1.3.2.min.js",	// local url for js library
		jsPluginPath : "/scripts/lib/ottawan/",						// path for all DGS plugins
		loadedJsListing : '',										// will contain a list of external js file loaded through the DGS loading module
		debugMode : false, 											// true/false to activate the debug mode
		/** 
		 * {object} list DGS plugin with external javascript files associated : "settings.jsPluginPath" will be used as path to find these plugins
		 * @property {object} 
		 */
		pluginList : {
			selector	: 'selector.js',	// add a getElementsBySelector method
			thumbnails 	: 'thumbnails.js',	// in a product page, manage thumbnails and big image behaviors
			modimodo 	: 'modimodo.js',	// test for a popin/modal box manager (still in development for several features)
			browser		: 'browser.js',		// manage tests on browser name, version and os
			tabs		: 'tabs.js',		// manage tabs menus
			cookies		: 'cookie.js',		// will manage cookies (create, read, delete) : to be implemented
			gmap		: 'gmap.js', 		// manage google map and points mapping + behavior : implementation in progress
			rounded		: 'rounded-shadows.js',		// create rounded boxes, with shadows and borders (optionals) : implementation 
			roundedLight: 'rounded-simple.js',	// create rounded boxes only : implementation and tests in progressand tests in progress
			select		: 'select.js',		// will generate an ul+li list with behavior to replace unobtrusively a select menu : not implemented yet
			carousel	: 'carousel.js',	// will manage carousel features : not implemented yet
			accordians 	: 'accordians.js', 	// manage horizontal and vertical accordians, click or mouseover based : implementation in progress
			toggles 	: 'toggles.js', 	// toggle things...
			modals 	: 'modals.js' 	// Modal things...
		},
		ieFirebugLiteUrl : 'http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js' // url for firebug lite debugging tool
	};
	/**
	 *  settings object that will use either specifics settings given to the constructor, or defaults
	 *	@name settings
	 *  @type {object}
	 */
	 /*
	 *  @param {boolean} settings.useGoogleLoad
	 *  @param  {string} settings.jsLib  name of js library to load through google load
	 *  @param  {string} settings.jsLibVersion version of js library to load through google load
	 *  @param  {boolean} settings.jsLibIsloaded true/false flag to indicate if the js library has been loaded
	 *  @param  {boolean} settings.useJsLibLocalLoad  true/false to use the js local library or not
	 *  @param  {string} settings.jsLibLocalUrl local url for js library
	 *  @param  {string} settings.jsPluginPath path for all DGS plugins
	 *  @param  {string} settings.loadedJsListing will contain a list of external js file loaded through the DGS loading module
	 *  @param  {boolean} settings.debugMode true/false to activate the debug mode
	 *  @param	{Object} pluginList contains a listing for all DGS plugins available, so that they can be loaded easily
	 *  @param  {string} settings.ieFirebugLiteUrl url for firebug lite debugging tool
	 *  
	 */
		this.settings={
		useGoogleLoad 			: (params && params.useGoogleLoad)?params.useGoogleLoad:this.defaults.useGoogleLoad,
		jsLib 					: (params && params.jsLib)?params.jsLib:this.defaults.jsLib,
		jsLibVersion			: (params && params.jsLibVersion)?params.jsLibVersion:this.defaults.jsLibVersion,
		jsLibIsloaded 			: (params && params.jsLibIsLoaded)?params.jsLibIsLoaded:this.defaults.jsLibIsLoaded,		
		useJsLibLocalLoad		: (params && params.useJsLibLocalLoad)?params.useJsLibLocalLoad:this.defaults.useJsLibLocalLoad,
		jsLibLocalUrl			: (params && params.jsLibLocalUrl)?params.jsLibLocalUrl:this.defaults.jsLibLocalUrl,
		jsPluginPath 			: (params && params.jsPluginPath)?params.jsPluginPath:this.defaults.jsPluginPath,
		loadedJsListing 		: this.defaults.loadedJsListing,
		debugMode				: (params && params.debugMode)?params.debugMode:(window.location.hash.indexOf('debugmode=true')!=-1)?true:this.defaults.debugMode,
		/** 
		 * {object} list DGS plugin with external javascript files associated : "settings.jsPluginPath" will be used as path to find these plugins
		 * @property {object} 
		 */
		pluginList : (params && params.pluginList)?params.pluginList:this.defaults.pluginList,
		ieFirebugLiteUrl : (params && params.ieFirebugLiteUrl)?params.ieFirebugLiteUrl:this.defaults.ieFirebugLiteUrl		
	};
	
	// all actions
	this.actions = {
		that : this,
		pluginUrl : function(obj,name){
			return obj.settings.jsPluginPath+obj.settings.pluginList[name];
		},
		/**
		* log
		*
		* @classDescription	This function dispatch error messages through console or alert
		* @type {function}
		* @param {string} message : the message to be logged 
		*/		
		// log feature that will display the console.log or an alert if non available
		log: function(message){			
			if (window.instance && window.instance.settings.debugMode) {			
				try {
					console.log.apply(console, arguments);
				} 
				catch (e) {
					try {
						opera.postError.apply(opera, arguments);
					} 
					catch (e) {
						alert(Array.prototype.join.call(arguments, " "));
					}
				}
			}
		},
		/**
		* debug
		*
		* @classDescription	This function is a debugging tool to trap errors
		* @type {function}
		* @param {string} object : error in itself
		* @param {string} message : the file in which error is located 
		* @param {string} number :line number 
		*/			
		debug : function(object,message,number) {	
		//use globale variable because we lost track for the current instance with the onerror
			window.instance.actions.log("DGS.debug(): Error \n -> " + object+"\n -> line "+number+" \n -> in file "+message);		
			return true;
		},		
		/**
		 * initLogMode
		 * 
		 * @classDescription	This function will check if the current browser has an internal debugger and will load firebug lite if it doesn't
		 * @type {function}
		 * @param {Object} obj will receive the current instance of DGS class
		 */ 	 
		initLogMode : function(obj){
			if(!window.console){
				//if no window.console, let inactivate potential errors if a window.console is left in the code
				(function ()
				{
					var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
					"group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
					
					window.console = {};
					for (var i = 0; i < names.length; ++i)
					{
				    	window.console[names[i]] = function() {};
				    }
				})();
			}
			if(obj.settings.debugMode && !window.console && obj.browser.IE){		
			
				// then load an external debugger if needed
				this.jsLoader(obj.settings.ieFirebugLiteUrl,function(){	
					firebug.env.height = 150;
				},'firebuglite');
			}	
		},		
		/**
		* external js loader
		*
		* @classDescription	This function acts as an external js loader.
		* @type {function}
		* @param {string} file : url of the javascript file to be loaded
		* @param {function} callback : name of the function to executed after the external load
		* @param {String} id : non mandatory, will give an id for the script tag to be write
		*/		
		jsLoader : function(file,callback,id){
				var s = document.createElement("script");
				s.type = "text/javascript";
				if(id)s.id = "script-"+id;
				if (s.readyState) { //IE
					s.onreadystatechange = function(){
						if (s.readyState == "loaded" || s.readyState == "complete") {
							s.onreadystatechange = null;
							if (callback) {	callback();}
						}
					};
				}
				else { //Others
					s.onload = function(){
						if (callback) {callback();}
					};
				}
				s.src = file;
				//on teste si le script a déjà été loadé, et si c'est le cas, on efface l'ancien tag script du dom, et on écrit le nouveau, pour que le callback s'effectue correctement
				for(i=0;i<document.getElementsByTagName("head")[0].getElementsByTagName("script").length;i++){
					if(document.getElementsByTagName("head")[0].getElementsByTagName("script")[i].src==s.src){
						document.getElementsByTagName("head")[0].removeChild(document.getElementsByTagName("head")[0].getElementsByTagName("script")[i]);
					}
				}
				document.getElementsByTagName("head")[0].appendChild(s);		
		},
		imagePreload:function(imgUrl,id,obj){
			obj.elmts[id] = new Image();
			obj.elmts[id].src=imgUrl;
		},
		attachEvent: function(elm, type, handle){
			if (elm.addEventListener) {
				elm.addEventListener(type, handle, false);
			}
			else if (elm.attachEvent){
				elm.attachEvent("on" + type, handle);
			}
		}
	};	
	/**
	* init all the library and its error handling
	*
	* @classDescription	This function inits all the library and its error handling
	* @type {function}
	* @param {object} obj : the current instance to be initialized
	*/	
	this.init = function(obj){
		//set a global variable to keep track of current DGS instance in onerror
		window.instance = obj;
		obj.prototype = DGS.prototype;
		// debug mode + non compatible browser (IE), load firefug lite to allow console
		obj.actions.initLogMode(obj);	
		// preload an ajax loader image
		obj.actions.imagePreload(obj.loaderImg,"preload",obj);
		
		// error catching
		//window.onerror = obj.actions.debug;		
	};
});
// init DGS framework generic instance to be used (here, "OT" will be used)
	var OT = new DGS();
	//initialize the instance
	OT.init(OT);


// ----------------------------
// ! ///// DEBUGG START //////////
// ----------------------------
(function($) {
    /* ! Warning !!! set debugg to false in production mode */
    var debugg = false;

    if ((debugg)) {
        jQuery(document).ready(function() {
            $("body").prepend('<div id="debugg" class="box"><h2><a href="#logger" id="toggle-logger">Logger</a></h2><ol id="logger"></ol></div>');
        });
    }
    jQuery.fn.debug = function() {
        return this.each(function() {
            jQuery.log(this);
        });
    };
    jQuery.log = function(message) {
        if ((window.console) && (window.console.debug) && (debugg)) {
         	window.console.debug(message);
            jQuery("#debugg h2").empty().text("Debugg on");
        }
        else {
            jQuery("#debugg ol").append("<li>" + message + "</li>");
        }
    };
} (jQuery));


// ----------------------------
// ! ///// DEBUGG END //////////
// ----------------------------


jQuery(window).load(function(event) {
	jQuery.log(OT); 

// ----------------------------
// ! ///// EXTERNAL INTERFACE START //////////
// ---------------------------- 
	jQuery("#flash-JS").click(function(event){
		event.preventDefault();
		document.getElementById("flashSample").myASFunction('External interface (JS TO AS)');
	});
// ----------------------------
// ! ///// EXTERNAL INTERFACE END //////////
// ----------------------------    

});

