/* Xoopla tools */
(function(){
	var instance = null;
	function _Tools(){};
	
	_Tools.prototype = {
		/* Stop action/propagation d'un evenement */
		/* @argument - (Obj) evt : evenement */
		/* @return - (Obj) evt : evenement */
		stopEvent: function(evt){
			if(window.event){ //IE
				evt = window.event;
				evt.returnValue = false;
			}
			try {
				evt.cancelBubble = true;
				if(evt.preventDefault) evt.preventDefault();
				if(evt.stopPropagation) evt.stopPropagation();
				if(evt.stopped) evt.stopped = true;
			} catch(e) {
				/* console.log(e.message); */
			}		
			return evt;
		},
		
		/* Retourne l'Url depuis l'Url map */
		getUrl: function(key){
			var url = null;
			if(!xpl.urlmap[key]) throw 'Url: ' + key + ' doesn\'t exist in website url map!';
			else url = xpl.urlmap[key];
			return url;
		},
		
		/* Retourne une traduction dictionaire xoopla */
		translate: function(token){
			var translation;
			if(xpl.labels[token]) translation = xpl.labels[token];
  		else translation = token + '-' + heap.config['current_language'];
			return translation;			
		},
		
		/* Valide un email */
		validateEmail: function(field){
			var isValid = true;
			var $field = $(field);
			var fieldValue = $.trim($(field).val());
			var ereg = new RegExp('.+@.+\\.[a-z]{2,4}');
			if(!fieldValue.match(ereg)) isValid = false;
			else{
				var whiteSpace = fieldValue.split(' ');
				var ereg = new RegExp('[!"#$%&\'()*+,/:;<=>?[\\\]{|}~]');
				if(fieldValue.match(ereg) || whiteSpace.length > 1){					
					isValid = false;
				}
			}
			return isValid;		
		},
		
		/* Valide un numero de telephone */
		validatePhone: function(field){
			var ereg = new RegExp('^(\()?([0-9]{3})(\)|-|.*)?([0-9]{3})(-|.*)?([0-9]{4}|[0-9]{4})$');
			var isValid = true;
			var $field = $(field);
			var fieldValue = $.trim($(field).val());
			if(!fieldValue.match(ereg)) isValid = false;	
			return isValid;	
		},
		
		/* Valide une valeur requise */
		validateRequire: function(field){
			return ($.trim($(field).val()) != '')? true : false;
		},
		
		/* Affiche field error dans un formulaire */
		error: function(field){
			var $parent = $($(field).parents('p').eq(0));
			$parent.addClass('error');
		},
		
		/* Affiche un message dans la page */
		log: function(txt, type, reference, position){
			var msg = txt; 
			var type = (type == 'error')? 'error' : 'success';
			var reference = (reference)? $(reference) : window;
			var positions = reference.offset();
			var left = (position && position.x)? position.x : 0;
			left += positions.left;
			var top = (position && position.y)? position.y : 0;
			top += positions.top;
			var html = '<p class="log ' + type + '" style="top: ' + top + 'px; left: ' + left + 'px; z-index: 10000;">' + msg + '</p>';
			$('.log.error, .log.success', document).remove();			
			$('body').append(html);
		},		
		
		/* Heritage Class */
		extendClass: function(childClass, parentClass){
			var F = function(){};
			F.prototype = parentClass.prototype;
			childClass.prototype = new F();
			childClass.prototype.constructor = parentClass;
			childClass.parentClass = parentClass.prototype;
			if(parentClass.prototype.constructor == Object.prototype.constructor){
				parentClass.prototype.constructor = parentClass;
			}
		}
	};
	
	/* Singleton - getInstance */
	var getInstance = function(){
		instance = (!instance)? new _Tools() : instance;
		return instance;		
	};
	
	window.xpl = window.xpl || {};
	window.xpl.tools = window.xpl.tools || getInstance();		
})();

(function(){
	var instance = null;
	function _Log(){
		this.timeout = null;
		this._options = {type: 'success', reference: window, position: {x: 0, y: 0}, align: {x: 'left', y: 'top'}, alignL: true, alignT: true, alignR: false, alignB: false, delay: 1500};
		this.options = {};
	};
	
	_Log.prototype = {
		execute: function(msg, options){
			this.options = $.extend({}, this._options, options);		
			this.render(msg);			
			var that = this;
			this.timeout = window.setTimeout(function(){
				if(that.timeout) window.clearTimeout(this.timeout);
				$('.log.error, .log.success', document).remove();
			}, this.options.delay);			
		},
		
		getLeftPosition: function(){
			var positions = this.options.reference.offset();
			var left = (this.options.position && this.options.position.x)? this.options.position.x : 0;
			left = (this.options.alignL)? left + positions.left: positions.left - left;
			return left;
		},
		
		getTopPosition: function(){
			var positions = this.options.reference.offset();
			var top = (this.options.position && this.options.position.y)? this.options.position.y : 0;
			top = (this.options.alignT)? top + positions.top : positions.top - top ;
			return top;		
		},
		
		getLeft: function(elt){
			var width = elt.outerWidth();
			var refPositions = this.options.reference.offset();
			var refWidth = this.options.reference.width();
			var left = 0;
			switch(this.options.align.x){
				case 'after':
					left = refPositions.left + refWidth;
					left += this.options.position.x;
				break;
				case 'before':
					left = refPositions.left - width;
					left -= this.options.position.x;					
				break;
				case 'right':
					left = (refWidth > width)? (refWidth - width) + refPositions.left : refPositions.left - (width - refWidth);	
					left -= this.options.position.x;
				break;
				default:
					left = refPositions.left;	
					left += this.options.position.x;
				break;					
			}				
			return left;			
		},
		
		getTop: function(elt){
			var height = elt.outerHeight();
			var refPositions = this.options.reference.offset();
			var refHeight = this.options.reference.height();
			var top = 0;
			switch(this.options.align.y){
				case 'top':
					top = refPositions.top - height;
					top -= this.options.position.y;
				break;
				case 'bottom':
					top = refPositions.top + refHeight;
					top += this.options.position.y;
				break;
				default:
				  //akl refPositions is null
				  if(refPositions){
						var padding = (refHeight > height)? Math.ceil((refHeight - height)/2) : Math.ceil((height - refHeight)/2);
						top = (refHeight > height)? refPositions.top + padding : refPositions.top - padding;
						top += this.options.position.y;
					}
				break;					
			}				
			return top;			
		},
		
		render: function(msg){
			if(this.timeout) window.clearTimeout(this.timeout);
			$('.log.error, .log.success', document).remove();
			var html = '<p class="log ' + this.options.type + '" style="display: none; z-index: 300;">' + msg + '</p>';
			$('body').append(html);
			var msg = $('p.log.error, p.log.success');
			msg.css({top: this.getTop(msg) + 'px', left: this.getLeft(msg) + 'px', display: 'block'});
			return this;
		}
	};
	
	/* Singleton - getInstance */
	var getInstance = function(){
		instance = (!instance)? new _Log() : instance;
		return instance;		
	};
	
	window.xpl = window.xpl || {};
	window.xpl.log = window.xpl.log || getInstance();	
})();

(function(){
	var instance = null;
	
	function _Register(){
		this.register = {};		
	};
	
	_Register.prototype = {
		push: function(event, obj, fn){
			this.register[event] = this.register[event] || {};
			var ID = (!obj.ID)? null : obj.ID;
			if(!ID) return;
			var args = this.getArguments(arguments, 3);
			var params = {obj: obj, fn: fn, args: args};			
			this.register[event][ID] = this.register[event][ID] || new Array();
			this.register[event][ID].push(params);
			return this;			
		},
		
		remove: function(event, obj, fn){
			var ID = (!obj.ID)? null : obj.ID;
			if(!ID) return;
			if(!this.register[event] && !this.register[event][ID]) return;
			for(var i = 0; i < this.register[event].length; i++){
				var record = this.register[event][i];
				if(obj != record.obj || fn != record.fn) continue;
				else this.register[event].splice(i, 1);	
			}
			return this;			
		},
		
		getArguments: function(args){
			var args = new Array();
			var start = (arguments.length > 1)? arguments[1] : 0;
			for(var i = start; i < arguments.length; i++){
				if(!args)	var args = new Array();
				args.push(arguments[i]);
			}
			return args;			
		},
		
		fire: function(event, ID){
			if(!this.register[event]) return;
			var args = this.getArguments(arguments, 2);
			for(var prop in this.register[event]){				
				if(ID != prop) continue;
				else {
					for(var i = 0; i < this.register[event][prop].length; i++){
						var r = this.register[event][prop][i];
						var obj = (r.obj)? r.obj : null;
						var fn = (r.fn)? r.fn : null;
						if(args.length == 0) args = (r.args)? r.args : null;
						(args && args.length)? obj[fn].apply(obj, args) : obj[fn].call(obj); 
					}
				}
			}
			return this;			
		}
	};
	
	/* Singleton - getInstance */
	var getInstance = function(){
		instance = (!instance)? new _Register() : instance;
		return instance;		
	};
	
	window.xpl = window.xpl || {};
	window.xpl.register = window.xpl.register || getInstance();	
})();

xpl.sizes = new Array();
xpl.resizeImages = function(){

  var letters = new Array('a', 'b', 'c', 'd');
  for (i = 0; i < letters.length; i++){
		var width = $("#d_" + letters[i] + " div.content").width();
		if(width){
			$imgs = $("#d_" + letters[i] + " div.content img.media");
			$imgs.each(function(j, elt){      
				var $img = $(elt);
				$img.data('parentWidth', width);
				var _slug = $img.attr('rel');
				var timer = window.setInterval(function(){
					if($img.height() > 0){
						window.clearInterval(timer);
						
						var imgWidth = $img.width();
						
						if(!$img.data('origWidth')) $img.data('origWidth', imgWidth);
						
						if(imgWidth != $img.data('parentWidth') && imgWidth > $img.data('parentWidth')){
							$img.css({width: $img.data('parentWidth')});
							/*var imgHeight = $img.height();
							var ratio = $img.data('parentWidth') / imgWidth;
							$img.height(ratio * imgHeight); */
						}else{
							//console.log("In resizeimages 1");
							if($img.data('origWidth') > $img.data('parentWidth')){
								var newwidth = $img.data('parentWidth');
								newwidth = newwidth + 'px';
								//console.log('width:' + newwidth);
								$img.css('width', newwidth);
							}else{
								$img.css({width: $img.data('origWidth') + 'px'});
							}
						}
					}																													 
				}, 2000);
			});			
		}
  }					
}
