(function() {
    var ns = jwyre.module("com.hensleycomposites");
    var DEF_PAGE = "main";	
    
	// helper function used to obtain animation intervals, based on current browser
	// (IE 8 requires much larger values to display same behavior)
	function getInterval(time) {
		if (jwyre.isIE(8)) {
			var intvl = parseInt(time * 4);
			return intvl
		}
		return time;
	}
	
	/*
	 *             On-load functionality
	 */
	jwyre.load(function() {
		
		// is NOT possible to view dynamics in < IE7...show message
		var bInfo = jwyre.getBrowserInfo();
		if (bInfo.isIE(6)) {
			var msg = 
			     "This site is not currently supported in Internet Explorer 6; " +
				 "we apologize for the inconvenience and recommend upgrading your " +
				 "browser or the use of Firefox. Thank you.";
			alert(msg);
			return;
		}
		
		/* ****************************************************************** **
		                              FAQ code
		** ****************************************************************** */
        
		// add link to Contact page
        jwyre.addClick("#contactLink", 
			function(event) {
				showPage("contact");
				return jwyre.kill(event);
			}
		);
				
		// used for tracking open FAQs
        var dispFlags = jwyre.array();
        var dispCtr = 0, lastDisp = null;
        // create FAQ display functionality
        jwyre.elements(".faq").each(
            function(item) {
                // question and answer elements
                var q, a;
                jwyre.children(item).each(
                    function(kid) {
                        if (jwyre.attribute(kid, "class") == "faqText") {
                            q = kid;
                        } else if (jwyre.attribute(kid, "class") == "faqAnswer") {
                            a = kid;
                        }                                       
                    }
                );
                var thisCtr = dispCtr++;
                dispFlags.add(false);
                jwyre.addClick(q, 
                    function(event) {
                        jwyre.style(".faqAnswer", "display", "none");
                        if (lastDisp != a) {
                            for (var i = 0; i < dispFlags.size(); i++) {
                                dispFlags[i] = false;
                            }
                        }
                        if (!dispFlags[thisCtr]) {
                            jwyre.style(a, "display", "block");
                        } 
                        dispFlags[thisCtr] = !dispFlags[thisCtr];
                        lastDisp = a;
                        return jwyre.kill(event);
                    }
                );
            }   
        );

        // resets the FAQ page
        function resetFAQ() {
            jwyre.style(".faqAnswer", "display", "none");
            for (var i = 0; i < dispFlags.size(); i++) {
                dispFlags[i] = false;
            }
        }

        /* ****************************************************************** **
	                      Header banner animation code
        ** ****************************************************************** */
		
		// creates the fade-in/fade-out behavior for banner text items
		function createHeaderAnim(element, fadeInDur, fadeOutDur, startDelay, callagain) {
            var anim = jwyre.animator(element);
            var fn = function() {
                anim.fadeIn(fadeInDur, function() {
                    anim.fadeOut(fadeOutDur, 
						function() {
							jwyre.hide(element);
							window.setTimeout(fn, callagain);
						}
					);	                    
                });
            };
            window.setTimeout(fn, startDelay);				
		}
		// object containing animation values for banner text
		var hdrAnimConf = {
			1 : {
				fIn : 1500,
				fOut : 800,
				delay : 0,
				repeat : 4000
			},
	        2 : {
                fIn : 1800,
                fOut : 1000,
                delay : 1000,
                repeat : 5000
            },
            3 : {
                fIn : 2200,
                fOut : 600,
                delay : 3000,
                repeat : 6000
            },
            4 : {
                fIn : 1000,
                fOut : 800,
                delay : 5000,
                repeat : 4000
            },
            5 : {
                fIn : 2200,
                fOut : 800,
                delay : 6000,
                repeat : 5000
            },
            6 : {
                fIn : 1800,
                fOut : 1000,
                delay : 8000,
                repeat : 6000
            }
		};
		
		// create animation for each line of banner text
		jwyre.array(1,2,3,4,5,6).each(
			function(item) {
				var elem = "#animatedHeaderText" + item;
				jwyre.hide(elem);
				var obj = hdrAnimConf[item];
                createHeaderAnim(elem, obj.fIn, obj.fOut, obj.delay, obj.repeat);
			}
		);
        /* ****************************************************************** **
                      Helper code for creating 'Paging' behavior
        ** ****************************************************************** */
		function createPager(page) {
			// need to add a background-masking element for page display function
			var mask = jwyre.create("<div class='_pager_mask'></div>");
			jwyre.styles(mask, {
				"position" : "absolute",
				"top" : "0px",
				"left" : "0px",
				"height" : "60px",
				"width" : "500px",
				"background-color" : "white",
				"z-index" : "4"
			});
			jwyre.append(page, mask);
			
			var pages = jwyre.elements(page + " .innerPage").dualRotator();
			// array of page elements
			var pAry = pages.elements();
			var sz = pages.elements().length;
			// hide all pages but first
			for (var i = 1; i < sz; i++) {
				jwyre.hide(pAry[i]);
			}
			// the currently displayed content id on page
			var currPage = "#" + pAry[0].id;
			
			// helper function used to construct a 'next' or 'back' button
			function nextBackHelper(item, text, click) {
	            var txt = jwyre.create("<div>" + text + "</div>");
				jwyre.disableSelection(txt);
	            jwyre.styles(txt, {
	                "font-style" : "italic",
	                "cursor" : "pointer"
	            });
	            jwyre.addHover(txt, 
	                function(event) {
	                    jwyre.style(txt, "text-decoration", "underline");
	                    return jwyre.kill(event);   
	                },
	                function(event) {
	                    jwyre.style(txt, "text-decoration", "none");
	                    return jwyre.kill(event);                        
	                }
	            );
				jwyre.addClick(txt, click);
				jwyre.append(item, txt);
				return txt;
			}
			// flag indicating if animation is active
			var isPageMoving = false;
			// used to move welcome page content into viewing area
			function movePage(pageId, goUp) {
				if (isPageMoving) {
					return;
				}
				isPageMoving = true;
				var yStart, yStop = 0;
				if (goUp) {
					yStart = 240;
				} else {
	                yStart = -240;
				}
	            jwyre.position(pageId, 0, yStart);
	            jwyre.style(pageId, "z-index", "2");
	            jwyre.style(currPage, "z-index", "1");
				jwyre.show(pageId);
	            var anim = jwyre.animator(pageId).moveTo({
	                x : 0,
	                y : yStop,
	                duration : getInterval(100),
	                callback : function() {
		                isPageMoving = false;
                        jwyre.hide(currPage);
						currPage = pageId;
                   }
	            });			
			}
			
			nextBackHelper(jwyre.element(page + " .next"), "next",
	            function(event) {					
					var pg = "#" + pages.next().id;
					movePage(pg, true);
	                return jwyre.kill(event);
	            }
	        );
			// only add back if more than 2 pages
			if (sz > 2) {
		        nextBackHelper(jwyre.element(page + " .back"), "back",
		            function(event) {
						var pg = "#" + pages.back().id;
	                    movePage(pg, false);
		                return jwyre.kill(event);
		            }
		        );				
			} else {
				jwyre.hide(page + " .back")
			}
		}
		
		createPager("#mainPage");
		createPager("#newsPage");
		
        /* ****************************************************************** **
		                          Page display code
        ** ****************************************************************** */
        
		// used to alternate the page-show behavior
		var flip = 0;
		// the id of the page currently being displayed		
		var currentPage;
		// the Animator object used to display page
		var pageAnim;
		
		/**
		 * Adds 'fancy' behavior to the display of individual pages.
		 * 
		 * @param {string} name
		 */
		function showPage(name) {
			if (pageAnim) {
				window.setTimeout(function() { showPage(name)}, 50);
				return;
			}
			// first, hide all pages
			jwyre.elements(".contentItem").each(
				function(item) {
					jwyre.style(item, "z-index", "1");
				} 
			);			
			var pageId = "#" + name + "Page";
            jwyre.show(pageId);
            jwyre.style(pageId, "z-index", "2");
            // do not hide if clicking same page twice
			var temp = (pageId == currentPage) ? null : currentPage;
			if (flip++ % 2 == 0) {
				jwyre.styles(pageId, 
					{
						"border-bottom" : "2px rgb(200, 200, 200) solid",
						"background-color" : "white"
					}
				);
	            jwyre.position(pageId, 0, -340);
	            pageAnim = jwyre.animator(pageId).move({
					x : 0,
					y : 340,
					duration : getInterval(150),
					callback : function() {
                       jwyre.style(pageId, "border-bottom", "none");
                       if (temp != null) {
	                       jwyre.hide(temp);                           
                       }
					   delete pageAnim;
					   pageAnim = null;
                   }
				});
			} else {
                jwyre.styles(pageId, 
					{
						"border-right" : "2px rgb(200, 200, 200) solid",
                        "background-color" : "white"
					}					
				);
	            jwyre.position(pageId, -515, 0);
	            pageAnim = jwyre.animator(pageId).move({
					x : 515,
					y : 0,
					duration : getInterval(150),
					callback : function() {
                       jwyre.style(pageId, "border-right", "none");                       
                       if (temp != null) {
                           jwyre.hide(temp);                           
						}
                       delete pageAnim;
                       pageAnim = null;
                    }
				});
			}
            // resets the FAQs that may be showing
            resetFAQ();
			currentPage = pageId;
		}	
		// initialize by showing default page
		showPage(DEF_PAGE);
        
		// values for how fast to perform on and off animations
        var onDur = getInterval(80);
		var offDur = getInterval(50);
        // used to create hover behaviors for main menu items
        function makeMenuBehavior(prefix) {
            var obj = {};
			var img = "#" + prefix + "MenuImg";
            var txt = "#" + prefix + "MenuTxt";
			jwyre.style(img, "z-index", "1");
            jwyre.style(txt, "z-index", "2");
			// the animator object for image and text
			var imgAnim = jwyre.animator(img);
            var txtAnim = jwyre.animator(txt);
			var onImg, offImg, onTxt, offTxt;
			function kill() {
				imgAnim.cancel();
				txtAnim.cancel();
			}
			// the absolute positions of the text and image
			var origImgPos = jwyre.position(img, false);
            var origTxtPos = jwyre.position(txt, false);
            // the relative positions of the text and image
            var origImgPosRel = jwyre.position(img, true);
            var origTxtPosRel = jwyre.position(txt, true);
			function reset() {
				jwyre.position(img, origImgPosRel.left, origImgPosRel.top);
                jwyre.position(txt, origTxtPosRel.left, origTxtPosRel.top);
			}
			obj.reset = function() {
				reset();
			};
            var isMoving = false;
			var _callback = null;
			function onCallback(isCancelled) {
	            isMoving = false;
				if (_callback) {
					_callback();
				}				
			}
			function offCallback(isCancelled) {
				isMoving = false;
				if (!isCancelled) {
					reset();
				}
                if (_callback) {
                    _callback();
                }               
			}
			/**
			 * 
			 * @param {function} callback
			 */
			obj.setCallback = function(callback) {
                _callback = callback;				
			};
			/**
			 * 
			 */
			obj.isMoving = function() {
				return isMoving;
			};
			/**
			 * 
			 * @param {Event} event
			 */
            obj.on = function(event) {
				if (isMoving) {
					return jwyre.kill(event);
				}
				kill();
                isMoving = true;
				window.setTimeout(
					function() {
						imgAnim.reset();
		                imgAnim.moveTo({
		                    "x" : origImgPos.left + 40,
		                    "y" : origImgPos.top,
		                    "isRelative" : false,
		                    "duration" : onDur,
		                    "callback" : onCallback
		                });
						txtAnim.reset();
		                txtAnim.moveTo({
		                    "x" : origTxtPos.left - menuConf[prefix].textLeft,
		                    "y" : origTxtPos.top,
		                    "isRelative" : false,
		                    "duration" : onDur,
		                    "callback" : onCallback
		                });						
					},
					10
				);
                return jwyre.kill(event);
            };
			/**
			 * 
			 * @param {Event} event
			 */
            obj.off = function(event) {
				// used to provide IE-specific fix for animation
				var isIEOverride = (arguments.length == 2) ? true : false;
				if (!isIEOverride) {
	                if (isMoving) {
	                    window.setTimeout(obj.off, 50);
	                    return jwyre.kill(event);
	                }
				}
                kill();             
                isMoving = true;                    
				window.setTimeout(
					function() {
						try {
	                        imgAnim.reset();
	                        imgAnim.moveTo({
	                            "x" : origImgPos.left,
	                            "y" : origImgPos.top,
	                            "isRelative" : false,
	                            "duration" : offDur,
	                            "callback" : offCallback
	                        });   
	                        txtAnim.reset();
	                        txtAnim.moveTo({
	                            "x" : origTxtPos.left,
	                            "y" : origTxtPos.top,
	                            "isRelative" : false,
	                            "duration" : offDur,
	                            "callback" : offCallback
	                        });							
						} catch (e) { jwyre._INTERNALS._log(e); }
					},
					10
				);
                return jwyre.kill(event);
            };
            return obj;
        }
		
		// configuration values for menu animations
		var menuConf = {
			main : {
				textLeft : 7
			},
            about : {
                textLeft : 20
            },
            products : {
                textLeft : 20
            },
            support : {
                textLeft : 5
            },
            news : {
                textLeft : 10
            },
            contact : {
                textLeft : 15
            }
		};
		
		// mapping of menu prefixes to the object containing animation functions
		var menuAnims = {};
		
		// add functionality to menu items
		jwyre.elements(".menuItem").each(
			function(item) {
				var id = jwyre.attribute(item, "id");
				var name = id.replace("MenuItem", "");
                var fns = makeMenuBehavior(name);
				menuAnims[name] = fns;
				jwyre.addClick(item,
					function(event) {
						showPage(name);
						fns.off(event);
						return jwyre.kill(event);
					}
				);
				// create a surrogate trigger element
				var trigger = jwyre.create("<div id='trigger_" + name + "'></div>");
				jwyre.styles(trigger, {
					   "position" : "absolute",
					   "top" : "0px",
					   "left" : "0px",
					   "height" : "40px",
					   "width" : "200px",
					   "z-index" : "5"
				});
				jwyre.append(item, trigger);
                
				/*
				================================================================
			                            BUG HACK:
				    DUE TO BROWSER BUG, AM NOT ADDING MENU ANIMATION FOR THE 
		            TIME BEING FOR CERTAIN PLATFORM/BROWSER CONFIGURATIONS; ONCE 
	                      ISOLATED AND CORRECTED, WILL ADD BACK         
                ================================================================
				 */
				function addAnim() {
                    var bInfo = jwyre.getBrowserInfo();
                    if (bInfo.platform.indexOf("Linux") >= 0) {
						return true;
					}
					if (bInfo.isFirefox()) {
						return bInfo.isOlderThan(3.6);
					}
					if (bInfo.isIE()) {
						return bInfo.isOlderThan(8);
					}
					return false;
				}
				if (addAnim()) {
                    jwyre.addHover(trigger, fns.on, fns.off);					
				} else {
	                var txt = jwyre.element("#" + id + " .menuTxt");
	                jwyre.addHover(trigger, 
	                    function() {
	                        jwyre.style(txt, "color", "rgb(180, 180, 200)");
	                    },
	                    function() {
	                        jwyre.style(txt, "color", "white");                     
	                    }
	                );					
				}
                /*
                ================================================================
                                        END BUG HACK
                ================================================================
                 */
				
				if (jwyre.isIE()) {
	                jwyre.styles(trigger, {
						"opacity" : "0",
						"background-color" : "black"
	                });
				}
			}
		);
		// add functionality to header menu items
		jwyre.elements(".headerMenuItem").each(
			function(item) {
				var id = jwyre.attribute(item, "id");
				var name = id.replace("HeaderMenuItem", "");
				jwyre.addClick(item,
					function(event) {
						showPage(name);
						return jwyre.kill(event);
					}
				);
			}
		);
		
		// add functionality to footer menu items
		jwyre.elements(".footerMenuItem").each(
			function(item) {
				var id = jwyre.attribute(item, "id");
				var name = id.replace("FooterMenuItem", "");
				jwyre.addClick(item,
					function(event) {
						showPage(name);
						return jwyre.kill(event);
					}
				);
			}
		);	
	
		// add filter opacity to info panel background
		$(".productInfoPanelTransparent").css({
		    'opacity': .80
		});
		 
		// add functionality to more info link in products panel
		function showPanel(name) {			
			var panelId = "#" + name + "InfoPanel";	
			//TODO: this is where 'fancy' showing code will go
			jwyre.show(".productInfoPanelTransparent");
			jwyre.show(panelId);
		}
		
		// add functionality to more info link in products panel
		jwyre.elements(".moreInfoLink").each(
			function(item) {
				var id = jwyre.attribute(item, "id");
				var name = id.replace("Link", "");
				jwyre.addClick(item,
					function(event) {
						showPanel(name);
						return jwyre.kill(event);
					}
				);
			}
		);
		// add functionality to panel close button
		$(".panelCloseX").click(function(){
			$(".productInfoPanelTransparent").hide();	
			$(".productInfoPanel").hide();			
		});			
	});
})();
