jQuery(function($) {	
	
	var xmlUrl 				 = $("#xml_url").html(),
		isHome 				 = $("#header").hasClass("h_499"),
	
		// KSS logo
		$KSS_SQUARE			 = $("#kss_square"),

		// Dropdown menu
		$DD_HOLDER      	 = $("#ddm_holder"),
		$DD_TRIGGER     	 = $("#ddm > li.trigger"),
		$DD_MENUITEM    	 = $('#ddm > li > ul > li > a'),
		
		// Slideshow
		$SS_INNER			 = $("#slideshow_inner"),
		$SS_BUTTONS			 = $('.ss_button'),
		SS_CLASS_SLIDE 		 = "slide",
		SS_CLASS_DUPE  		 = "dupe",
		SS_SLIDES_SEL  	 	 = "#slideshow_inner > ." + SS_CLASS_SLIDE,
		SS_DUPES_SEL   	 	 = "#slideshow_inner > ." + SS_CLASS_DUPE,
		SS_DIMMED	  		 = isHome ? 0.07 : 0.18,
		SS_ANIM_SPEED 		 = 600,	
		SS_FADE_SPEED 		 = 600,
		SS_ANIM_EASING  	 = "easeOutQuint",
		SS_FADE_EASING  	 = "easeOutQuint",
		SS_MAX_IMAGE_WIDTH   = 690,
		
		// Left-side big headline
		$PAGE_HEADLINE  	 = $("#headline_holder > h1"),
		
		// Right-side opacity filter
		$OPACITY_FILTER  	 = $("#opacity_filter"),
		
		// Some page headlines not supplied in xml, so they're determined by the php filename
		PAGE_HEADLINE_FALLBACKS = {
			"press_release_images.php": "KSS PRESS",
			"blog_images.php": 			"KSS BLOG",
			"mmm_images.php": 			"KSS MMM"
		},

		// Right-side text/buttons
		$HEADER_TEXT     	 = $("#header_text > DIV"),
		$HEADER_TEXT_NAME    = $("#header_text_name"),
		$HEADER_TEXT_CAPTION = $("#header_text_caption"),
		$HEADER_TEXT_COUNTER = $("#header_text_counter"),
		$HEADER_TEXT_MAX	 = $("#header_text_max"),
		$HEADER_TEXT_NEXT	 = $("#header_text_next"),
		$HEADER_TEXT_PREV	 = $("#header_text_prev"),
		$HEADER_TEXT_EXPLORE = $("#header_text_explore"),

		MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],

		PATH_PREFIX  = "http://www.kssarchitects.com",

		// Grab page color
		pageColor = $("#kss_square").css("background-color"),
		
		// Browser-specific determinations
		_is_ie78 = ($.browser.msie && $.browser.version < 9),
		_is_iOS = navigator.userAgent.match(/Android/i) ||
            navigator.userAgent.match(/webOS/i) ||
            navigator.userAgent.match(/iPhone/i) ||
            navigator.userAgent.match(/iPad/i) ||
            navigator.userAgent.match(/iPod/i),
		deviceClick = _is_iOS ? "touchstart" : "click",



	 	Header = {
	
			init: function(xml){
			
				// Initialize dropdown menu
				Dropdown.init();
				$HEADER_TEXT.css("opacity", 0);

				// Parse images from xml and determine whether to init slideshow
				var imageData = this.parseImageData(xml);
				if(imageData.length > 0) { 
					Slideshow.init(imageData);
				}
						
				// Get other data from xml
				var headline    = $(xml).find("client:first").text(),
					active      = $(xml).find("active:first").text(),
					titleColor  = $(xml).find("titleColor:first").text().replace("0x", "#"),
					orderNum    = $(xml).find("order_num:first").text(),
					whitePapers = $(xml).find("white_papers:first").attr("issue_id");
			
				// If xml doesn't supply headline, figure out what it should be
				if(!headline) {
					$.each(PAGE_HEADLINE_FALLBACKS, function(k, v){
						if(xmlUrl.indexOf(k) > -1) { headline = v; }
					});
				}
			
				// Transparent = invisible
				if(titleColor === "#-1") { headline = ""; }
			
				// Custom headline color?
				if(titleColor){ $PAGE_HEADLINE.removeClass("col").css("color", titleColor); }
			

				// Fade in headline
				setTimeout(function(){
					$PAGE_HEADLINE.html(headline).fadeIn(1000);				
				}, 100);
				
				// Set it to fadeout if it should
				if(active){ 
					setTimeout(function(){
						$PAGE_HEADLINE.fadeOut(400);
					}, 6500);
				}
				
				
				// If there are images, fade in right-side text
				if(imageData.length > 0) { 
					setTimeout(function() {

						// This crazy structure prevents fade problems in IE and older versions of Firefox
						if(!_is_ie78) {
							if(!($.browser.mozilla && $.browser.version.slice(0,3) > "4")) {
								$HEADER_TEXT.css('opacity', 1);
							}
							$HEADER_TEXT.fadeIn(800);
						} else {
							$HEADER_TEXT.css('filter', 'alpha(opacity=100)');
							$HEADER_TEXT.fadeIn(1, function(){
								if(_is_ie78) { $HEADER_TEXT.css('filter', ''); }
							});
						}

					}, 1000);

				}

				// Homepage-specific layout
				if(isHome) { 
					
					if(_is_ie78) { 
						$HEADER_TEXT_EXPLORE.show(); 
					} else {
						$HEADER_TEXT_EXPLORE.fadeIn(1000); 
					}
					var addZero = orderNum < 10 ? "0" : "";
					$HEADER_TEXT_MAX.html(addZero + orderNum);
					
					// whitePapers == link to full text of article featured on homepage
					if(whitePapers && !_is_iOS) {
						Slideshow.whitePapers(whitePapers);
					}
				}

				// Other fancy initial fades
				$DD_HOLDER.fadeIn(750);
				$KSS_SQUARE.slideDown(500, "linear");
			},
		
		
			// Iterate through xml and create ImageObjs
			parseImageData: function(xml) {

				var imageData = [];
			
				$(xml).find("imagelist:first > image").each(function () {
				
					var t = this;
					var o = $.extend({}, ImageObj, {
						path:    PATH_PREFIX + $(t).find("file_location").text(),					
						width:   $(t).find("width").text(),
						height:  $(t).find("height").text(),
						caption:  $(t).find("title").text()
					});
					imageData.push(o);
			    });
				return imageData;
			}		
		
		},




		Slideshow = {
		
			images:  [],  		// Array of Image objs
			current: 0,   		// Currently displayed image
			count: 	 0,   		// Image count (minus dupes)
		
			init: function(imageData){
						
				var totalWidth = 0, i = 1, caption, t = this;
						
				// Iterate through images, determine placement/order, add to DOM
				$.each(imageData, function(n, o){
				
					Slideshow.images.push(o.init());
					o.setX(totalWidth).setNum(i++).appendTo($SS_INNER);
				
					// Cut images that are too large so they don't mess the layout
					if(!isHome && imageData.length > 1) { o.checkWidth(); }

					// Set to faded if not the first one
					if(totalWidth > 0) { o.dim(); }

					// Increment total width
					totalWidth += parseInt(o.width, 10);
				});

				// Note number of images
				this.count = this.images.length;



				// HOMEPAGE / SINGLE IMAGE ::

				// Set caption, or date if not available
				caption = this.images[0].caption;
				if(isHome || (caption === "" && this.count === 1)) {
					caption = this.getDate();
				}
				$HEADER_TEXT_CAPTION.html(caption);
								
				if(isHome) { $OPACITY_FILTER.show(); }
				
				// Show the "KSS Architects" right-side text, remove prev/next buttons, and be done
				if(this.count === 1 || isHome) { 
					$HEADER_TEXT_NAME.show();	
					$SS_BUTTONS.remove();
					return; 
				}


				// SLIDESHOW OF MULTIPLE IMAGES ::
			
				// Set text for current/max image #s, remove name element
				$HEADER_TEXT_COUNTER.html("1");
				$HEADER_TEXT_MAX.html("/" + this.count);
				$HEADER_TEXT_NAME.remove();	
			
				// Create duplications of first 2 images to wrap slideshow
				for(i=0; i<2; i++){
					o = $.extend({}, this.images[i]);
					o.init(true).setX(o.x += totalWidth).dim().appendTo($SS_INNER);
					this.images.push(o);
					$SS_INNER.append(o.$el);
				}

				// Set width of slideshow div to total width of images
				$SS_INNER.css("width", totalWidth);

				if(!_is_iOS) { this.createRightNextButton(); }
				
				this.bindButtons();
			
			},
		
		
			// Click events
			bindButtons: function() {
			
				$HEADER_TEXT_NEXT.bind(deviceClick, Slideshow.next);
				$HEADER_TEXT_PREV.bind(deviceClick, Slideshow.prev);

				if(!_is_iOS) {
					$SS_BUTTONS.hover(function(){
						$(this).animate({ "color": pageColor }, 130);
					}, function(){
						$(this).stop().animate({ "color": "#636363" }, 130);
					});						
				}
			},
		
			// Large home-page link to full text of featured article
			whitePapers: function(issue) {
			
			    if(!_is_iOS){
    				var h = this.images[0].height, w = 690,
    					url = "http://www.kssarchitects.com/content/issue.php?id=" + issue;
    					div = $("<div class='click_area click_featured'><a href='" + url + "'><span></span></a></div>");
								
    				$(div).css("height", h).css("width", w).appendTo($("#header"));
    				$(div).bind(deviceClick, function(){
    					window.location = "http://www.kssarchitects.com/content/issue.php?id=" + issue;
    				});
    			}
			},
		
			// Date text for right-side display
			getDate: function(){
				var d = new Date();
				return MONTHS[d.getMonth()] + " " + d.getDate() + ", " + d.getFullYear();
			},

			// Make the right side of the header a "next" button
			createRightNextButton: function() {
				var div = $("<div/>");
				$(div).addClass("click_area click_right").appendTo($("#header"));
				$(div).bind(deviceClick, function(){
					Slideshow.next();
				});				
			},

			// Move left or right
			move: function(direction) {
			
				var t = Slideshow;
			
				// This var is used to look ahead/behind and determine when to wrap
				var checkNum = direction === 1 ? 2 : -1;

				// Stop any motion already going
				$SS_INNER.stop(true,true);
				$(SS_SLIDES_SEL).stop(true,true);
				$(SS_DUPES_SEL).stop(true,true);

				// Need to wrap around?
				if(!t.images[t.current + checkNum]){
					Slideshow.warpTo((t.current) - (direction * t.count), direction);
				}

				// Determine new image to be highlighted
				var target = (t.current + direction) % t.images.length;

				// Determine where to get distance to move from
				var distSource = direction === 1 ? t.current : target;

				// Get distance to move, in pixels
				var dist = t.images[t.current + (direction === -1 ? -1 : 0)].width * (-1 * direction);
				
				// Animate the slideshow
				$SS_INNER.animate({
					left: "+=" + dist
				}, SS_ANIM_SPEED, SS_ANIM_EASING);
			
				// Fade prev/target images
				t.images[t.current].fadeOut(dist);					
				t.images[target].fadeIn(dist);

				// Update text display
				$HEADER_TEXT_CAPTION.html(t.images[target].caption);
				$HEADER_TEXT_COUNTER.html(t.images[target].num);
			
				t.current = target;
			},
		
			next: function (){
				Slideshow.move(1);
			},

			prev: function(){
				Slideshow.move(-1);
			},
		
			// Teleport to duplicate images when wrapping around
			warpTo: function(num, direction){

				var t = Slideshow;

				// Brighten destination image
				setTimeout(function(){ t.images[num].highlight(); }, 1);

				// Set slideshow to new location (which will look exactly the same)
				$SS_INNER.css("left", t.images[num].x * -1);

				// Dim other images which might be left highlighted
				// This targets a class of images, instead of just the previously 
				// displayed image, to safeguard against browser bugs
				var dimClass = direction === 1 ? SS_CLASS_DUPE : SS_CLASS_SLIDE;
				setTimeout(function(){ $("." + dimClass).css("opacity", SS_DIMMED); }, 5);

				t.current = num;
			}
		
		},




		// Image objs used by slideshow
		ImageObj = {
		
			caption: null,
			width:   null,
			height:  null,
			path:    null,
			$el:     null,
			x:       null,

			init: function(dupe){

				// Duplicate or "original" image?
				var c = dupe ? SS_CLASS_DUPE : SS_CLASS_SLIDE;
			
				// Create DOM objects
				var div = $("<div class=\"" + c + "\"/>");
				var img = $("<img src=\"" + this.path + "\">");
			
				// Create curtain for the initial reveal
				var curtain = $("<div class=\"curtain\"/>").css("width", this.width);
			
				this.$el = $(div).css("width", this.width).css("height", this.height).append(img).append(curtain);
			
				// Set up initial reveal anim
				$(img).load(function(){
					setTimeout(function(){
						$(curtain).animate({ height: 0 }, 750);
					}, 150);
				});
				return this;
			},
		
			fadeOut: function(x){
				this.$el.animate({ opacity: SS_DIMMED }, SS_FADE_SPEED, SS_FADE_EASING);
				return this;
			},

			fadeIn: function(x){
				this.$el.animate({ opacity: 1 }, SS_FADE_SPEED, SS_FADE_EASING);
				return this;
			},
		
			dim: function(){
				this.$el.css("opacity", SS_DIMMED);
				return this;
			},
		
			highlight: function(){
				this.$el.css("opacity", 1);
				return this;
			},
		
			setX: function(x){
				this.x = x;
				this.$el.css("left", x);
				return this;
			},
		
			// Number for right-side text display (num/max). Duplicates have the same as originals
			setNum: function(n){
				this.num = n;
				return this;
			},
		
			appendTo: function(target){
				$(target).append(this.$el);
				return this;
			},
		
			// Force width to a max to prevent larger images from messing things up
			checkWidth: function(){
				if(this.width > SS_MAX_IMAGE_WIDTH) { 
					this.width = SS_MAX_IMAGE_WIDTH; 
					this.$el.css("width", SS_MAX_IMAGE_WIDTH); 
				}
				return this;
			}
		
		},
	
	
	
	
		Dropdown = {
		
			// Currently open menu category
			$menu: 0,
		
			init: function(){
			
				if(_is_iOS) {
					$DD_TRIGGER.bind(deviceClick, Dropdown.open);
					$(document).bind(deviceClick, Dropdown.close);
					
					// Prevent iPad 2 bug in which <a> events don't take
					// precedence over bubbling events bound to their parent elements
					$DD_MENUITEM.bind(deviceClick, function(e){
						e.stopPropagation();
					});
					
				} else {
					$DD_TRIGGER.hover(Dropdown.open, Dropdown.close);

					$DD_MENUITEM.hover(function(){
						$(this).animate({ "color": "#cccccc" }, 130);
					}, function(){
						$(this).stop().animate({ "color": "#ffffff" }, 130);
					});				

					$(document).bind("click", Dropdown.close);					

				}
			},
		
			open: function(e){
				Dropdown.close();
				Dropdown.$menu = null;
				Dropdown.$menu = $(this).find('ul').eq(0).css('visibility', 'visible');				
				return false;
			},
		
			close: function(){
				if(Dropdown.$menu) { Dropdown.$menu.css('visibility', 'hidden'); }
			}
		};




	// Get xml data, init header
	$.ajax({
	    type:     "GET",
		url:      xmlUrl,
		dataType: "xml",
		complete:  function(response) { 
			var xml = response.responseText ? $.parseXML(response.responseText) : "";
			Header.init(xml); 
		}
	});

});

