// Global Variables
var slideshows = [];
var winScroller;

window.addEvent('domready', function() {
	//new UvumiDropdown('nav-main');
	if ($$('#rotator-images img').length > 0) { 
		slideshows['content'] = setImageRotator('rotator-images');
	}
	/*
	new Fx.SmoothScroll({
		links: $$('a:contains("#")') 
		,duration: 2000
	},window);
	*/
	winScroller = new Fx.Scroll(
		window
		,{
			duration: 1500
			,offset: {'x': 0, 'y': -10}
			,transition: Fx.Transitions.Sine.easeOut
		}
	);
	setLinkAnchorTargets();
	setFocusAnchorTargets();
	setScrollAnchorTargets();
});

function setImageRotator(target) { 
	try { 
		slideshows.each(function(slideshow) {
			delete slideshow;
		});
		return new SlideShow(
			target
			,{
		        delay: 20000
				,duration: 2000
				,transition: 'fadeThroughBackground'
				,autoplay: true
			}
		);
	} catch(e) { handleException(e); }
}

function setScrollAnchorTargets(filter) { 
	try { 
		var selector = (filter) ? filter + ' a.scroll-anchor' : 'a.scroll-anchor';
		$$(selector).each(function(element, index){
			element.addEvent('click', function(event) {
				//prevent the page from changing
				event.stop();
				anchorIDRegex = new RegExp("#([^#]*)$");
				anchorIDMatches = anchorIDRegex.exec(element.get('href'));
				winScroller.toElement($(anchorIDMatches[1]));
			});
		});
	} catch(e) { handleException(e); }
}

function setFocusAnchorTargets(filter) { 
	try { 
		var selector = (filter) ? filter + ' a.focus-anchor' : 'a.focus-anchor';
		$$(selector).each(function(element, index){
			element.addEvent('click', function(event) {
				//prevent the page from changing
				event.stop();
				anchorIDRegex = new RegExp("#([^#]*)$");
				anchorIDMatches = anchorIDRegex.exec(element.get('href'));
				($(anchorIDMatches[1])).focus();
			});
		});
	} catch(e) { handleException(e); }
}

function setLinkAnchorTargets(filter) {
	var selector = (filter) ? filter + ' a.xhrlink' : 'a.xhrlink';
	$$(selector).each(function(element, index){
		element.addEvent('click', function(event) {
			//prevent the page from changing
			event.stop();
			//make the ajax call
			var jsonRequest = new Request.JSON({
				url: element.get('href') + '?output=xhtmlfragment'
				,method: 'post'
				,onSuccess: function(responseJSON, responseText) {
					try { 
						if (responseJSON !== null) { 
							responseJSON.fragments.each(function(el) { 
								var domEl = $(el.id); 
								if (domEl) { 
									switch (el.id) { 
										case "content":
											var tween = $("content-wrapper").get('tween', {property: 'opacity'});
											tween.start(0).chain(function() {
												try {
													$("content-text").set("html", el.html);
													setLinkAnchorTargets("#content-text");
													setFocusAnchorTargets("#content-text");
													setScrollAnchorTargets("#content-text");
													tween.start(1).chain(function() {
														injectScriptFromResponse(el.html);
													});
												} catch(e) { handleException(e); }
											});
											//fadeXhrXhtml("content-wrapper", "content-text", el.html);
											winScroller.toElement($("nav-main-container"));
											break;
										case "rotator-images":
											// Compare src of all new images to current images
											var matchedImagesCount = 0;
											var imageUrlRegex = /src="[^"]*"/g;
											var originalImages = $("rotator-images").get("html").match(imageUrlRegex);
											var newImages = el.html.match(imageUrlRegex);
											if ((originalImages && newImages) && originalImages.length === newImages.length) {
												for (var index = 0; index < originalImages.length; index++) {
													if (unescape(originalImages[index].substring(5, (originalImages[index].length - 1))) === unescape(newImages[index].substring(5, (newImages[index].length - 1)))) { 
														matchedImagesCount++;
													} else { 
														break;
													}
												}
											}
											// If not all images match, rebuild image rotator
											if ((!originalImages != !newImages) || (originalImages && (matchedImagesCount !== originalImages.length))) { 
												var tween = $("image-rotator-wrapper").get('tween', {property: 'opacity'});
												tween.start(0).chain(function() {
													try { 
														$("image-rotator-wrapper").set("html", '<div id="rotator-images">' + el.html + '</div>');
														if (newImages && newImages.length > 0) { 
															$("content-container").setProperty('class', 'rotator-images');
															tween.start(1).chain(function() {
																slideshows['content'] = setImageRotator('rotator-images');
																injectScriptFromResponse(el.html);
															});
														} else{ 
															delete slideshows['content'];
															$("content-container").setProperty('class', 'no-rotator-images');
														}
													} catch(e) { handleException(e); }
												});
											}
											break;
										default:
											domEl.set("html", el.html); 
											injectScriptFromResponse(el.html);
									}
								}
							});
						} else { 
							handleAjaxException(responseText);
						}
					} catch(e) { handleException(e); }
				}
				,onFailure: function(xhr){
					handleAjaxException(xhr.responseText);
			    }
			}).send();
		});
	});
}

function fadeXhrXhtml(fadeElementID, htmlElementID, html) { 
	$(fadeElementID).set("tween", {
		onComplete: function() {
			$(htmlElementID).set("html", html);
			setLinkAnchorTargets("#" + htmlElementID);
	        this.removeEvents("complete");
	        this.element.fade(1);
	   	}
	}).fade(0);	
}

function injectScriptFromResponse(search) { 
    var script; 
          
    while( script = search.match(/(<script[^>]+javascript[^>]+>\s*(<!--)?)/i)) 
    { 
      search = search.substr(search.indexOf(RegExp.$1) + RegExp.$1.length); 
       
      if (!(endscript = search.match(/((-->)?\s*<\/script>)/))) break; 
       
      block = search.substr(0, search.indexOf(RegExp.$1)); 
      search = search.substring(block.length + RegExp.$1.length); 
      eval(block);
       /*
      var oScript = document.createElement('script'); 
      oScript.text = block; 
      document.getElementsByTagName("head").item(0).appendChild(oScript);
      */ 
    } 
}

function removejscssfile(filename, filetype) {
	var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none"; //determine element type to create nodelist from
	var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none"; //determine corresponding attribute to test for
	var allsuspects=document.getElementsByTagName(targetelement);
	for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
		 if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1) {
			 allsuspects[i].parentNode.removeChild(allsuspects[i]); //remove element by calling parentNode.removeChild()
		 }
	}
}

