dojo.require("dijit._Widget");

(function() {
	// Shorthand reference variables
	var d = dojo;
	
	d.declare("te.industry.Marquee", [dijit._Widget], {
		
		constructor : function(args) {
			this.marquee = d.byId(args.marquee);
			this.isSolutionsMarquee = (args.marqueeType == "industry_solutions") ? true : false;
			if (this.isSolutionsMarquee) {
				this.content = d.query(".Image-text", this.marquee)[0];
				this.header = d.query('div.title', this.marquee)[0];
				this.leftArrow = dojo.query(".leftPlay")[0];
				d.connect(this.leftArrow, "onclick", this, this.movePrev);
				this.rightArrow = dojo.query(".rightPlay")[0]; 
				d.connect(this.rightArrow, "onclick", this, this.moveNext);
				this.controls = createNode("span", {
						"class" : "te-clearfix"
					}, dojo.query("#te-heroControl")[0]);
				this.span2 = createNode("span", {}, this.controls);
				this.ul = createNode("ul", {}, this.span2);
				this.linkClassName = "te-btn te-global-orange-btn";
				this.screen = createNode("div", {
						"className" : "te-bannerScreen"
					}, this.marquee);				
			} else {
				this.content = d.query(".te-marqueeContent", this.marquee)[0];	
				this.header = d.query('h3', this.marquee)[0];
				this.controls = createNode("span", {
						"id" : "te-heroControl"
					}, this.marquee);
							d.style(this.controls, {
				"opacity" : 0,
				"display" : "block"
				});
				this.span2 = createNode("span", {}, this.controls);
				this.span3 = createNode("span", {}, this.span2);
				this.ul = createNode("ul", {}, this.span3);
				createNode("div", {
					"className" : "clear-div"
				}, this.span3);
				this.linkClassName = "te-btn te-orange-btn";
				this.screen = createNode("div", {
						"className" : "te-marqueeScreen"
					}, this.marquee);
			}
			
			this.paragraph = d.query('p', this.marquee)[0];
			this.link = d.query('.te-btn', this.marquee)[0];
			this.b = d.query('b', this.link)[0];
			this.data = args.data;
			this.index = 0;
			this.change = true;
			this.links = [];
			this.images = [];
			this.duration = 250;
			

			
			d.forEach(this.data, function(o, i) {
				var li = createNode("li", {}, this.ul);
					
				this.links[this.links.length] = createNode("a", {
					"href" : "javascript:void(0);",
					"title" : o.image.title,
					"text" : i + 1,
					"className" : i === 0 ? "selected" : ""
				}, li);
					
				d.connect(this.links[this.links.length - 1], "onclick", this, function() {
					this.move(i);
				});
					
				this.images[this.images.length] = new Image();
				this.images[this.images.length - 1].src = o.image.src;
					
				li = null;
			}, this);
				
			d.fadeIn({
				"node" : this.controls,
				"duration" : this.duration
			}).play();
			
			if (args.rotationInterval) {
				this.rotateTimer = setInterval(dojo.hitch(this, function() {
						this.moveNext();
					}), args.rotationInterval);
				
				d.forEach(
					this.links,
					function(link){
						d.connect(link, "onclick", this, this.stopRotation);
					},
					this
				);
				
				if (this.leftArrow) {
					d.connect(this.leftArrow, "onclick", this, this.stopRotation);
				}
				
				if (this.rightArrow) {
					d.connect(this.rightArrow, "onclick", this, this.stopRotation);
				}
			}
		},
		
		move : function(index) {
			if(this.change && index !== this.index) {
				this.change = false;
					
				d.style(this.screen, {
					"display" : "block",
					"opacity" : 0
				});
					
				d.fx.chain([
					d.fadeIn({
						"node" : this.screen,
						"duration" : this.duration,
						"onEnd" : d.hitch(this, function() {
							d.style(this.content, {
								color : this.data[index].color,
								left : this.data[index].position == 'L' ? '22px' : 'auto',
								right : this.data[index].position == 'R' ? '22px' : 'auto'
							});
							this.marquee.title = this.data[index].image.title;
							this.header.innerHTML = this.data[index].title;
							this.paragraph.innerHTML = this.data[index].text;
							if(typeof this.data[index].link != "undefined") {
								if(typeof this.link == "undefined") {
									this.link = createNode("a", {
										className : this.linkClassName,
										innerHTML : "<span><b></b></span>"
									});
									d.place(this.link, this.paragraph, "after");
									this.b = d.query("b", this.link)[0];
								}
								
								d.style(this.link, { display : "block" });
								
								this.link.href = this.data[index].link.url;
								
								this.b.innerHTML = this.data[index].link.text;
								
							} else if (typeof this.link != "undefined") {
								d.style(this.link, { display : "none" });
							}
							
							d.style(this.marquee, {
								"backgroundImage" : "url(" + this.data[index].image.src + ")"
							});
							
							d.forEach(this.links, function(o, i) {
								if(i === index) {
									d.addClass(o, "selected");
								} else {
									d.removeClass(o, "selected");
								}
							}, this);
						})
					}),
					d.fadeOut({
						"node" : this.screen,
						"duration" : this.duration,
						"onEnd" : d.hitch(this, function() {
							d.style(this.screen, {
								"display" : "none"
							});
							this.change = true;
						})
					})
				]).play();
					
				this.index = index;
			}
		},
		
		stopRotation: function () {
			clearInterval(this.rotateTimer);
			this.rotateTimer = null;
		},
		
		moveNext : function () {
			if ((this.index + 1) > (this.data.length - 1)) {
				this.move(0);
			} else {
				this.move(this.index + 1);
			}
		},
		
		movePrev : function () {
			if ((this.index - 1) >= 0) {
				this.move(this.index - 1);
			} else {
				this.move(this.data.length - 1);
			}
		}
	});
	
	// Declare the te.industry.MiniMarquee class
	d.declare("te.industry.MiniMarquee", [dijit._Widget], {
		
		// Member variables
		_widget : null,
		_countContainer : null,
		_marquee : null,
		_imgLink : null,
		_img : null,
		_header : null,
		_paragraph : null,
		_learnMore : null,
		_data : null,
		_current : null,
		_images : null,
		_count : null,
		
		// constructor method
		constructor : function(cfg) {
			this._widget = d.byId(cfg.widget);
			this._countContainer = d.query(".te-mini-marquee-count-current", this._widget)[0];
			this._marquee = d.query(".te-mini-marquee", this._widget)[0];
			this._imgLink = d.query(".te-mini-marquee-image-link", this._marquee)[0];
			this._img = d.query("img", this._imgLink)[0];
			this._header = d.query(".te-mini-marquee-sub-header", this._widget)[0];
			this._paragraph = d.query("p", this._widget)[0];
			this._learnMore = d.query(".te-mini-marquee-learn-more", this._widget)[0];
			this._data = cfg.data;
			this._current = 0;
			this._images = [];
			this._count = this._data[this._current].count;
			this.titleLength = cfg.titleLength;
			this.bodyLength = cfg.bodyLength;
		},
		
		//  postscript method
		postscript : function(args) {
			d.connect(d.query(".te-previous-control", this._marquee)[0], "onclick", this, function() { this.update("prev"); });
			d.connect(d.query(".te-next-control", this._marquee)[0], "onclick", this, function() { this.update("next"); });
			
			d.forEach(this._data, function(o) {
				this._images[this._images.length] = new Image();
				this._images[this._images.length - 1].src = o.image;
			}, this);
		},
		
		// update method
		update : function(dir) {
			if(dir == "next") {
				this._current = this._current === this._count - 1 ? 0 : this._current + 1;
			} else {
				this._current = this._current === 0 ? this._count - 1 : this._current - 1;
			}
			
			this._countContainer.innerHTML = (this._current + 1);
			this._imgLink.href = this._data[this._current].url;
			this._img.src = this._data[this._current].image;
			this._img.alt = this._img.title = this._header.title = this._data[this._current].name.replace(/"/g, "'");
			this._header.innerHTML = this.trim(this._data[this._current].name, this.titleLength);
			this._header.href = this._data[this._current].url;
			this._paragraph.innerHTML = this.trim(this._data[this._current].desc, this.bodyLength);
			this._learnMore.href = this._data[this._current].url;
		},
		
		// trim method
		trim : function(str, max) {
			var newStr = "";
			
			if(str.length > max) {
				newStr = str.substring(0, max);
				newStr = newStr.substring(0, newStr.lastIndexOf(' ')) + "...";
			} else {
				newStr = str;
			}
			
			return newStr;
		}
		
	});
	
	// Declare the te.industry.Overlay class
	d.declare("te.industry.Overlay", [dijit._Widget], {
		
		// Member variables
		_link : null,
		_listItem : null,
		_overlay : null,
		_a : null,
		_show : null,
		_visible : null,
		_handles : null,
		
		// constructor method
		constructor : function(link, overlay, a) {
			this._link = link;
			this._listItem = this._link.parentNode;
			this._overlay = overlay;
			this._a = a;
			this._show = [false, false];
			this._visible = false;
			this._handles = [];
		},
		
		// postscript method
		postscript : function() {
			// Wire-up event handles
			this._handles.push(d.connect(this._link, "onmouseover", this, function() {
				this._show[0] = true;
				
				this.show();
			}));
			this._handles.push(d.connect(this._link, "onmouseout", this, function() {
				this._show[0] = false;
				
				this.hide();
			}));
			this._handles.push(d.connect(this._link, "onclick", function(e) {
				d.stopEvent(e);
			}));
			this._handles.push(d.connect(this._overlay, "onmouseover", this, function() {
				this._show[1] = true;
				
				this.show();
			}));
			this._handles.push(d.connect(this._overlay, "onmouseout", this, function() {
				this._show[1] = false;
				
				this.hide();
			}));
			this._handles.push(d.connect(this._a, "onclick", this, function(e) {
				this._visible = this._show[1] = false;
				
				d.removeClass(this._listItem, "active");
				
				d.style(this._overlay, {
					display : "none"
				});
			}));
		},
		
		// show method
		show : function() {
			if ((this._show[0] || this._show[1]) && !this._visible) {
				this._visible = true;
				
				d.addClass(this._listItem, "active");
				
				d.style(this._overlay, {
					display : "block"
				});
			}
		},
		
		// hide method
		hide : function() {
			if (!this._show[0] && !this._show[1] && this._visible) {
				this._visible = false;
				
				d.removeClass(this._listItem, "active");
				
				d.style(this._overlay, {
					display : "none"
				});
			}
		}
	});
	
	d.declare("te.industry.NewsRotator", [dijit._Widget, dijit._Templated], {
		data: [{featureText:"", featureURL:""}],
		titleText: "", //Get/Set with .attr to change node text ... defined in attributemap
		rotateInterval: 0, //Get/Set with .attr to change speed of rotation ... defined by custom getter
		transitionSpeed: 0, //Get/Set with .attr to change speed of fade 
		isFullLength: false, //3/4 length of page by default, but can be full length
		_containerStyle: "",
		_contentStyle: "",
		_curFeatIndex: 0,
		_initialData: null,
		_titleNode: null,
		_featureNode: null,
		_featureContainerNode: null,
		_rotateTimer: null,
		
		postMixInProperties: function(){
			this._initialData = this.data[0];
			this._curFeatIndex = 0;
			this._containerStyle = (this.isFullLength === true) ? "headline-news-container-full" : "headline-news-container";
			this._contentStyle = (this.isFullLength === true) ? "headline-news-content-full" : "headline-news-content";
		},
		
		//Specifying attach points here automatically create the corresponding variables with the corresponding node as a value.
		templateString: 
		"<div class=\"${_containerStyle}\">" + 
			"<div class=\"${_contentStyle}\">" + 
				"<span class=\"title\" dojoAttachPoint=\"_titleNode\"></span>" + 
				"<span class=\"feature\" dojoAttachPoint=\"_featureContainerNode\"><a href=\"${_initialData.featureURL}\" dojoAttachPoint=\"_featureNode\">${_initialData.featureText}</a></span>" + 
			"</div>" +
		"</div>",
		
		//Because we specify this here, populating the this.titleText variable either by passing as param or using .attr will update the corresponding nodes automatically, no custom setter required.
		attributeMap: {
			titleText: {node:"_titleNode", type:"innerHTML"}
		},
		
		_rotate: function(){
			if ((this._curFeatIndex + 1) > (this.data.length - 1)) {
				this._move(0);
			} else {
				this._move(this._curFeatIndex + 1);
			}
		},
		
		_move: function(/*int*/index){
			dojo.fadeOut({
				node: this._featureContainerNode, 
				duration: this.transitionSpeed,
				onEnd: dojo.hitch(this, function()
				{
					d.attr(this._featureNode, "href", this.data[index].featureURL);
					d.attr(this._featureNode, "innerHTML", this.data[index].featureText);
					this._curFeatIndex = index;
					dojo.fadeIn({node: this._featureContainerNode, duration: this.transitionSpeed}).play();
				})
				}).play();
		},
		
		_createTimer: function(/*int*/ rotateInterval)
		{
			this._rotateTimer = setInterval(dojo.hitch(this, function() {
					this._rotate();
				}), rotateInterval);
		},
		
		//Custom getter, dojo automatically calls this during widget creation and any time someone calls .attr. Custom setters are only needed for anything attributeMap can't handle.
		_setRotateIntervalAttr: function(/*int*/ rotateInterval)
		{
				this.rotateInterval = rotateInterval;
				if (this._rotateTimer)
				{
					clearInterval(this._rotateTimer);
					this._rotateTimer = null;
				}
				this._createTimer(rotateInterval);
		}

	});
	
	function createNode(node, attr) {
		var node = document.createElement(node);
			
		for(var i in attr) {
			if(i == "text") {
				node.appendChild(document.createTextNode(attr[i]));
			} else {
				node[i] = attr[i];
			}
		}
			
		if(typeof arguments[2] != "undefined") {
			dojo.byId(arguments[2]).appendChild(node);
		}
			
		return node;
	}
	
	
})();

// Function to initialize the overlays and their corresponding <a> & <li> tags
function initOverlays() {
	var d = dojo, links = d.query("a", "solutionList"), overlays = d.query(".te-industry-overlay"), inst = [];
	
	// Loop through the overlays
	d.forEach(overlays, function(overlay) {
		var h5 = d.query("h5", overlay)[0], a = d.query("a", h5)[0];
		
		// Loop through the <a> elements
		d.forEach(links, function(link) {
			
			// If the <a> element's text is the same as the title of the overlay
			if (new RegExp(eval("/" + link.innerHTML + "/gi")).test(h5.innerHTML)) {
				
				// Instantiate 
				inst.push(new te.industry.Overlay(link, overlay, a));
				
			}
		});
	});
}

function validateRequiredField(field) { 
	var isValid = true;
	var req = dojo.query("#" + field + " ~ div.indus-form-required");
	var node = dojo.byId(field);
	
	if (dojo.query("select#" + field)[0] != null) {
		if (node.selectedIndex == 0) {
			isValid = false;
		}
	} else {
		// remove leading/trailing whitespace
		node.value = node.value.replace(/^\s+|\s+$/g, '');
	
		if (node.value.length == 0) {
			isValid = false;
		}
	}
		
	if (isValid) {
		if (req[0]) {
			req.orphan();
		}
	} else {
		if (!req[0]) {
			var reqNode = document.createElement("div");
			dojo.addClass(reqNode, "indus-form-required");
			reqNode.appendChild(document.createTextNode("This is a required field."));
			node.parentNode.appendChild(reqNode);
		}
	}
	
	return isValid;
}
