﻿(function($){
	
	var _resizeTimeout;
	
	$(function(){
		 _adjustHeadlineHeight();
		 $.ToutImageManager.init();
		 new $.ToutImage($("#toutHeadline1"));
		 $("#displayList div.displayContainer a.fadeLink").each(function(){
		    new $.ToutImage($(this));
		 });
		 $.ToutImageManager.adjustSize();
	});
	
	$(window).resize(function(){
		clearTimeout(_resizeTimeout);
		_resizeTimeout = setTimeout(function(){
			_adjustHeadlineHeight();
		},250);
	});
	
	
	function _adjustHeadlineHeight(){
		var 
			headlines = $("#rgaHeadlinesTwitter"),
			headlineTexts = headlines.find("div.headlineText, div.twitterText"),
			maxHeight = 0;
			
		headlineTexts.each(function(){
			var 
				$this = $(this),
				height;
				
			$this.height("auto")
			height = $this.outerHeight();
			
			if (height > maxHeight) maxHeight = height;
			
		}).each(function(){
			$(this).height(maxHeight);
		});
		
	}
	
	$.ToutImageManager = {
	    reg : /(small|medium|large)/,
	    size : null,
	    imgArr : [],
	    init : function(){
	        this.bindEvents();
	    },
	    
	    bindEvents : function(){
	        var self = this;
	        $(document).bind("resizeComplete", function(){self.adjustSize()});
	    },
	    
	    add : function(toutImg){
	        this.imgArr.push(toutImg);
	    },
	    
	    adjustSize : function(){
	        var c = $("html").get(0).className;
	        var size = this.reg.exec(c)[0];
	        if (size != this.size){
	            this.size = size;
	            for (var i = 0, l = this.imgArr.length; i<l; i++){
	                this.imgArr[i].adjust();
	            }
	        }
	    }
	};
	
	$.ToutImage = function($cont){
	    this.cont = $cont;
	    this.image = $cont.find("img").get(0);
	    this.path = this.image.src.replace(/_[a-zA-Z]{2}$/, ''); //src is http://[host]/doc/[pid]/HP_FEAT_[size]
	    $.ToutImageManager.add(this);
	};
	$.ToutImage.prototype = {
	    versions : {
	        "small" : "_SM",
	        "medium" : "_ME",
	        "large" : "_LG"
	    },
	    
	    adjust : function(){
	        var size = $.ToutImageManager.size;
	        if (size != null){
	            if (!this.cont.find("img." + size).length){
	                this.add(size);
	            }
	        }
	    },
	    
	    add : function(size){
	        var img = ["<img id=\"", this.image.id, "\" class=\"" , size , "\" src=\"" , this.path , this.versions[size] , "\" alt=\"" , this.image.alt , "\" />"];
	        this.cont.append($(img.join('')));
	    }
	};
	
})(jQuery);