/**
 * Home page scripts
 *
 * @Henry Postulart
 * @1.0
 */



function initHomeTools() {
	var div = document.getElementsByClassName("photo-module");
	if (div && photoSource) {
		var photos = new photoWidget(div[0], photoSource);
	}
}

if (typeof Class != "undefined") {
	var photoWidget = Class.create();
	photoWidget.prototype = {
		
		imgDir     : "http://img.timeinc.net/golf/static/img/",
		imgPause   : "ico_nav_photo_pause.gif",
		imgPlay    : "ico_nav_photo_play.gif",
		imgCurrent : "",
		photoArray : new Array(),
		photoCount : 0,
		count : 0,
		orientation : "wide",
		delaySeconds : 5,
		min : 0,
		max : 2,
		timePassed : 0,
		cycleStart : null,
		cycleEnd   : null,
		pe         : null,
		prevValue  : -1,
		nextValue  :  1,
		direction  :  1,

		divTarget      : null,
		listMenu       : null,
		listNavTopic   : null,
		listNavGeneric : null,
		genericButtons : null,
		divHeadLine    : null,
		divImage       : null,
		divStatus      : null,
		divStatusBar   : null,
		pCredit        : null,
		pCaption       : null,
		pTagLine       : null,
		imgLink	       : null,
		initialize : function(targ, src) {
			try {
				this.divTarget = targ;
				this.listMenu = document.getElementsByClassName("menu", targ)[0];
				this.listNavTopic = document.getElementsByClassName("photo-nav-topic", targ)[0];
				this.listNavGeneric = document.getElementsByClassName("photo-nav-generic", targ)[0];
				this.imgLink = document.getElementsByClassName("img-link", targ)[0];
				this.divHeadLine = targ.getElementsByTagName("h3")[0];
				this.divStatus = targ.getElementsByTagName("div")[1];
				this.divStatusBar = targ.getElementsByTagName("div")[2];
				this.img = document.getElementsByClassName("photo-image", targ)[0];
				this.pCredit = document.getElementsByClassName("credit", targ)[0];
				this.pCaption = document.getElementsByClassName("caption", targ)[0];
				this.pTagLine = document.getElementsByClassName("tagline", targ)[0];
				this.getData(src);
			} catch(e) {}

		},

		getData: function (url) {
			if (url) {
			this.xmlHTTP = new Ajax.Request(url, {asynchronous: true, onSuccess: (this.handlerFunc).bindAsEventListener(this), onFailure: (this.errFunc).bindAsEventListener(this), method: "get" });
			}
		},

		handlerFunc: function(t) {
			var articles = t.responseXML.getElementsByTagName("articlePhotos");
			if (articles && articles.length == 1) {
				this.orientation = articles[0].getAttribute("orient");
				this.delaySeconds = articles[0].getAttribute("delaySeconds");
				var items = $A(articles[0].getElementsByTagName("article"));
				if (items && items.length) {
					this.count = items.length - 1;
					if (this.count < this.max) this.max = this.count;
					items.each( function(item) {
						var ph = new Object();
						ph.type = item.getAttribute("type")
						ph.headline = safeNodeValue(item.getElementsByTagName("headline")[0], "");
						ph.image = new Object()
						ph.image.src = item.getElementsByTagName("image")[0].getAttribute("src");
						ph.image.width = item.getElementsByTagName("image")[0].getAttribute("width");
						ph.image.height = item.getElementsByTagName("image")[0].getAttribute("height");
						ph.credit = safeNodeValue(item.getElementsByTagName("credit")[0], "");
						ph.caption = safeNodeValue(item.getElementsByTagName("caption")[0], "");
						ph.tagline = safeNodeValue(item.getElementsByTagName("tagline")[0], "");
						ph.linktext = safeNodeValue(item.getElementsByTagName("linktext")[0], "");
						ph.linkhref = safeNodeValue(item.getElementsByTagName("linkhref")[0], "");
						this.photoArray[this.photoCount++] = ph;
						if (this.photoCount > this.max) throw $break;
						}.bind(this)
					);
					this.buildNav();
					this.cycle(this.photoCount, true);
					this.show(true);
				}
			}
		},

		errFunc: function(t) {
    		alert('Error ' + t.status + ' -- ' + t.statusText);
		},

		buildNav: function() {
			if (this.count == 0) {
				Element.hide(this.listMenu);
				return;
			}
			while (this.listNavTopic.childNodes.length) {
				this.listNavTopic.lastChild.parentNode.removeChild(this.listNavTopic.lastChild);
			}

			this.photoArray.each( function(item, i) {
				if (item.type) {
					var a = this.buildAnchor("#");
					a.setAttribute("sequence", i);
					a.appendChild(document.createTextNode(item.type));
					Event.observe(a, "click", (function(e) {
						var el = Event.findElement(e, "a")
						this.cycle(el.getAttribute("sequence"), false); 
						Event.stop(e); } ).bind(this) );
					var li = this.buildLI("");
					li.appendChild(a);
					this.listNavTopic.appendChild(li);
				}
			}.bind(this));
			var listWidth = Element.getDimensions(this.listNavTopic).width;
			var titles = $A(this.listNavTopic.getElementsByTagName("li"));
			var itemWidth = 0;
			var lrPadding = parseInt(Element.getStyle(titles[0], "padding-left"));
			titles.each ( function(li) { itemWidth += Element.getDimensions(li).width; } );
			var remainder = listWidth - itemWidth;
			titles.each ( function(li, i) {
				li.style.paddingLeft = li.style.paddingRight = lrPadding + Math.floor(remainder/(titles.length)/2) + "px" ;
			}.bind(this) );
			this.genericButtons = this.listNavGeneric.getElementsByTagName("li");

/* Fix #: 14.3 HP 2007-02-13 : Adjust pixels to butt controls together - FINICKY BUSINESS */
			var limit = Position.cumulativeOffset(this.listNavGeneric)[0];
			var t = titles[titles.length - 1];
			var stretch = Position.cumulativeOffset(t)[0] + Element.getDimensions(t).width
			var tweaks = [Math.ceil((limit - stretch)/2), (limit - stretch)%2];
			if (limit-stretch > 2) {
				t.style.paddingLeft = parseInt(t.style.paddingLeft) + tweaks[0] + "px"
				t.style.paddingRight = parseInt(t.style.paddingRight) + tweaks[1] + "px"
			} else if (limit-stretch == 2) {
				t.style.paddingLeft = parseInt(t.style.paddingLeft) + 1 + "px"
				t.style.paddingRight = parseInt(t.style.paddingRight) + 1 + "px"
			} else if (limit-stretch == 1) {
				t.style.paddingLeft = parseInt(t.style.paddingLeft) + 1 + "px"
			}

			Event.observe(this.genericButtons[0], "click", (function(e) {
				this.direction = this.prevValue;
				this.cycle(this.photoCount + this.direction, false);
				Event.stop(e);}).bind(this)
			);
			Event.observe(this.genericButtons[1], "click", (function(e) {
				var a = Event.findElement(e, "a");
				var img = a.getElementsByTagName("img")[0];
				var src = img.src;
				src = src.substr(src.lastIndexOf("/") + 1)
				if (src == this.imgPause) {
					this.cycle(this.photoCount, false);
				} else {
					this.cycle(this.photoCount, true);
				}
				Event.stop(e);}).bind(this)
			);
			Event.observe(this.genericButtons[2], "click", (function(e) {
				this.direction = this.nextValue;
				this.cycle(this.photoCount + this.direction, false);
				Event.stop(e);}).bind(this)
			);
		},

		cycle : function(val, bMultiple) {
			try {
				val = parseInt(val);
				switch (this.direction) {
					case -1:
						if (val < this.min) val = this.max;
						break;

					case 1:
						if (val > this.max) val = this.min;
						break;
				}
				var list = $A(this.listNavTopic.getElementsByTagName("li"));
				list.each ( function(li) {
					Element.removeClassName(li, "selected");
				});
				Element.addClassName(list[val], "selected");
				with (this.photoArray[val]) {
					var a1 = this.buildAnchor(linkhref, "more");
// djs - 040906 - commented out and added line below per bug #15830
//					a1.appendChild(document.createTextNode(headline));
					a1.innerHTML = headline;
					this.divHeadLine.innerHTML = "";
					this.divHeadLine.appendChild(a1);
					this.img.src = image.src;
					this.img.setAttribute("width", image.width);
					this.img.setAttribute("height", image.height);
					this.imgLink.setAttribute("href", linkhref);
					this.pCredit.innerHTML = credit;
					this.pCaption.innerHTML = caption;
					this.pTagLine.innerHTML = tagline;
					var a2 = this.buildAnchor(linkhref, "more")
					a2.appendChild(document.createTextNode(linktext));
					this.pTagLine.appendChild(a2);
				}
				this.photoCount = val;

				var img = (this.genericButtons[1]).getElementsByTagName("img")[0];
				if (bMultiple && this.count > 0) {
					this.cycleStart = new Date().getTime();
					this.cycleEnd   = this.cycleStart + (this.delaySeconds * 1000);
					Element.show(this.divStatus);
					img.src = this.imgDir + this.imgPause;
					window.clearInterval(this.pe);
					this.pe = window.setInterval( (this.statusUpdate).bindAsEventListener(this), 100 )
				} else {
					img.src = this.imgDir + this.imgPlay;
					window.clearInterval(this.pe);
					Element.hide(this.divStatus);
				}
			} catch (e) {/* nop */}
		},

		show : function(bVisible) {
			this.divTarget.style.visibility = (bVisible) ? "visible" : "hidden";
		},

		statusUpdate : function() {
			var interval = this.cycleEnd - this.cycleStart;
			var now = new Date().getTime();
			this.timePassed = now - this.cycleStart;
			var ratio = this.timePassed / interval;
			if (ratio >= 1) {
				window.clearInterval(this.pe);
				this.cycle(this.photoCount + this.direction, true);
			} else {
				try { this.divStatusBar.style.width = ratio * 100 + "%"; } catch(e) {}
			}
		},

/*  Utility functions */
		buildAnchor : function(href, className) {
			var a = document.createElement("a");
			if (href) a.href = href;
			if (className) a.className = className;
			return a;
		},

		buildLI : function(className) {
			var li = document.createElement("li");
			if (className) li.className = className;
			return li;
		}
	}
}

Event.observe (window, "load", initHomeTools);
