(function($) {
	// GET CURRENT YEAR for copyright
	var time=new Date();
	var date=time.getDate();
	var year_html=time.getYear();
	if (year_html < 2000){
		year_html = year_html + 1900;
	}
	$("#year").html(year_html);
	
		
	// GET XML
	$.ajax({ type: "GET",
		url: "mobile.xml",
		dataType: "xml",
		success: parseXml
  	});
	
	
	// PARSE XML
	function parseXml(xml) {
		// INITIALIZE
		resize($("#image_main").find("img"));
		
		// NAV		
		var nav_html="<ul id='nav' class='top_ul'>";
		$(xml).find("category").each(function() {  
			var c_name=$(this).children("name").text();
			nav_html+="<li class='top_li'><a href='#' title='" + c_name + "'>" + c_name + "</a><ul class='sub_ul'>";
			
			$(this).children("section").each(function(){
					var s_name=$(this).children("name").text();
					var s_url=$(this).children("url").text();

					nav_html+="<li class='sub_li'><a href='#/" + s_url + "' title='" + s_name + "'>" + s_name + "</a></li>";
			});
				
			nav_html+="</ul></li>";
		});
		nav_html+="</ul>";
		$("#nav_container").append(nav_html);
		
		// MAIN NAV HOVER
		// opera fix
		$("#nav ul").css({display: "none"});
		
		// HOVER
		$("#nav li").hover(function(){
			$(this).find("ul:first").css({visibility: "visible", display: "none"}).show();
		},function(){
			$(this).find("ul:first").css({visibility: "hidden"});
		});
		
		// CLICK
		/*var $sub_nav = $("#nav li").find("ul:first");
		$sub_nav.click(function(){
			$(this).css({visibility: "hidden"});
		});
		*/

		// prevent a hrefs in top level nav
		$("#nav li").find("a:first").click(function(event) {
  			event.preventDefault();
		});
		
		// SUBNAV ITEM CLICK
		$last_link = null;
		$("#nav").delegate(".sub_li","click tap",function(){
			// RESET
			var $this=$(this);
			resetStage($this);
			
			// CATEGORY & SECTION VARS
			var c_num = $(this).parent().parent().index();
			var c_node = $(xml).find("category").eq(c_num);
			var s_num = $(this).index();
			var s_node = c_node.children("section").eq(s_num);
			var copy_html = "";
			
			// LOAD GALLERY
			if(c_node.attr("template")=="gallery"){
				loadThumbs(s_node);
				$("#image_container").show();
				$("#thumbs_container").show();
			
			// or LOAD CONTENT PAGE
			} else {
				s_node.children("data").each(function(){
					copy_html += $(this).text();
				});
				$("#copy").html(copy_html);
				$("#copy_container").show();	
			}
    	});
		
		// PLACE RANDOM IMAGE ON HOME
		$imgs = $(xml).find("image");
		$("#logo").bind("click tap", function () {
			loadHome();
		});								   
										   
		loadHome();
	}
	
	// RESET STAGE
	function resetStage($this){
		$("#image_main").empty(); $("#image_container").hide();
		$("#thumbs").empty(); $("#thumbs_container").hide();
		$("#copy").empty(); $("#copy_container").hide();
		
		prev_state = 0; $("#prev").hide();
		next_state = 0; $("#next").hide();
		
		/*if($last_link!=null){
			$last_link.removeClass("selected");
			$last_link=null;
		}*/
		
		// TURN OFF SUBNAV DROPDOWN
		//var $active_link = $(this).find("a");
		var $active_link = $this;
		if($last_link!=$active_link){
			if($last_link!=null){
				$last_link.removeClass("selected");
			}
			$active_link.addClass("selected");	
		}
		$last_link=$active_link;
	}	
	
	// LOAD RANDOM IMAGE ON HOME PAGE
	function loadHome(){
		// RESET
		var $this=$(this);
		resetStage($this);
		$("#image_container").show();
		$("#thumbs_container").show();
		
		var r_num = Math.floor(Math.random()*($imgs.length--))
		var r_img = $imgs.eq(r_num).attr("url");
		
		$loader = $("#loader");
		$loader.show();
		
		$("<img/>").bind("load", function () { 
			resize($(this));
			$(this).fadeIn("slow"); 
			$loader.hide();				
			var $a=$("<a/>");// for swipe
			$("#image_main").append($a.append($(this)));
		}).attr("src",r_img);
	}
	
		
	// LOAD THUMBNAILS
	function loadThumbs(s_node){
		// THUMBNAILS
		p_num = 1;
		p_max = s_node.children("image").length;
		$last_thumb = null;
		var i = 0;
		//var thumb_html = "";
		//s_node.children("image").each(function(){
		//	var p_thumburl=$(this).attr("thumburl");
		//	var p_url=$(this).attr("url");
		//	var p_alt=$(this).attr("alt");	
		//	thumb_html+="<li><a href='#'><img src='../" + p_thumburl + "' alt='" + p_url + "' width='50' height='65' class='inactive'/></a></li>";
		//});
		
		// place thumbnails in html
		//$('#thumbs').html(thumb_html);

		
		s_node.children("image").each(function(){
			
			var p_thumburl=$(this).attr("thumburl");
			var p_url=$(this).attr("url");
			// var p_alt=$(this).attr("alt");	
		
		
			// load all the thumbnails
			$("<img class='inactive'/>").load(function() {  
				var $li=$("<li/>");
				//var $a=$("<a/>");
				var $a=$("<a href='#'/>");
				var $img=$(this);
				
				$("#thumbs").append($li.append($a.append($img)));
				$img.fadeIn("slow");
				
				
				// once all thumbs are loaded
				// load the first main image
				i++;
				if(i==p_max){				
					// LOAD FIRST IMAGE
					var $active_thumb = $("#thumbs li:nth-child(1)").find("img");
					$active_thumb.click();
				}
				
			}).attr({src: p_thumburl, alt: p_url, width: "50", height: "65"});
			/*.attr({src: p_thumburl, alt: p_url, width: "50", height: "65", class: "inactive"});*/
			
		});
	}	
	
	
	// THUMB CLICK    
	$("#thumbs").delegate("li","click tap",function(){
		// HIDE LAST IMAGE
		$("#image_main").empty();
			
		// VARS
		p_num = $(this).index() + 1;
		var $active_thumb = $("#thumbs li:nth-child(" + p_num + ")").find("img");
		
		// LOAD PHOTO
		if(!$active_thumb.length) return;
		loadPhoto($active_thumb);
	});	
	
	
	// LOAD PHOTO
	// alert("load photo code");
	function loadPhoto($active_thumb){
		// alert("loading from thumb: " + $active_thumb.attr("alt"));
		if($last_thumb==null || $last_thumb!=$active_thumb){//last and current differ
			// TOGGLE THUMBS
			if($last_thumb!=null){
				$last_thumb.addClass("inactive");//make last thumb inactive again
			}
			$active_thumb.removeClass();//make current thumb active
			
			// TOGGLE NEXT PREV BUTTONS
			// based on being on first or last photo
			// and current visibility state
			if(p_num==1){ // toggle off for first photo
				$("#prev").fadeOut("fast");
				prev_state = 0;
			} else if(prev_state==0) { // toggle on if not already on
				$("#prev").fadeTo("fast", 0.50);
				prev_state = 1;
			}
				
			if(p_num==p_max){	
				$("#next").fadeOut("fast");
				next_state = 0;
			} else if (next_state==0) { // toggle on if not already on
				$("#next").fadeTo("fast", 0.50);
				next_state = 1;
			}
						
			
			$loader.show();
			
			$("<img/>").bind("load", function () { 
				resize($(this));
				$(this).fadeIn("slow"); 
				$loader.hide();				
				var $a=$("<a/>");// for swipe
				$("#image_main").append($a.append($(this)));
			}).attr("src",$active_thumb.attr("alt"));

		}
		// update state
		$last_thumb = $active_thumb;	
    }	

    
	// NAVIGATE THRU IMAGES
    // thumb has image source in alt attribute
	
	// HOVER
	$("#prev").hover(function() {
		if(prev_state == 1){$(this).fadeTo("fast", 1)}
	}, function() {
		if(prev_state == 1){$(this).fadeTo("fast", 0.50)}
	});
	
	$("#next").hover(function() {
		if(next_state == 1){$(this).fadeTo("fast", 1)}
	}, function() {
		if(next_state == 1){$(this).fadeTo("fast", 0.50)}
	});
	
	// CLICK OR TAP
	$("#next").bind("click tap",function(){ navigateNext(); });
	
    $("#prev").bind("click tap",function(){ navigatePrevious(); });
	
	// SWIPE
	$("#image_main").touchwipe({
		wipeLeft: function() { navigateNext(); },
		wipeRight: function() { navigatePrevious(); },
		min_move_x: 20,
		preventDefaultEvents: true
	});
	
    
	// GO FORWARD
    function navigateNext(){
		// alert("next pressed");
        p_num++;
        var $active_thumb = $("#thumbs li:nth-child(" + p_num + ")").find("img");
        if(!$active_thumb.length) {
            p_num--;
            return;
        }
		$active_thumb.click();
        //loadPhoto($active_thumb);
    }
	
    
	// GO BACK
    function navigatePrevious(){
        // alert("prev pressed");
		p_num--;
        var $active_thumb = $("#thumbs li:nth-child(" + p_num + ")").find("img");
        if(!$active_thumb.length) {
            p_num++;
            return;
        }
		$active_thumb.click();
        //loadPhoto($active_thumb);
    }
	
	
	// ON WINDOW RESIZE
    $(window).bind("resize", function() {
        if($("#image_main").find("img").length){
			resize($("#image_main").find("img"));
		}
    });
	
	
	// RESIZE IMAGE
    function resize($image){
	    var footerH = $("#footer").position().top;
		footerH -= $("#thumbs_container").position().top;
		footerH += $("#footer").height();
		var headerH		= $("#image_container").position().top;
		//var thumbH      = $("#thumbs_container").height()+42;//represents the padding under the image and thumbnails
		//var footerH		= $("#footer").height();
		
		var marginW		= 70; // equal to double prev/next width
        var marginH 	= headerH+footerH;
		
        var windowH      = $(window).height()-marginH;
        var windowW      = $(window).width()-marginW;
		
		var minW		= 300;
		var minH		= 300;
		
		if(windowH < minH){ windowH = minH; }	
		if(windowW < minW){ windowW = minW; }	
		
        var p_src     = new Image();
        p_src.src     = $image.attr("src");
        var p_width     = p_src.width;
        var p_height    = p_src.height;
		
		if((p_width > windowW)||(p_height > windowH)){// image is bigger than window, so make smaller
			if(p_width > p_height){
				var newwidth = windowW;
				var ratio = p_width / windowW;
				var newheight = p_height / ratio;
				p_src.height = newheight;
				p_src.width= newwidth;
				if(newheight>windowH){
					var newnewheight = windowH;
					var newratio = newheight/windowH;
					var newnewwidth = newwidth/newratio;
					p_src.width = newnewwidth;
					p_src.height= newnewheight;
				}
			} else { // image is smaller than window, so make bigger
				var newheight = windowH;
				var ratio = p_height / windowH;
				var newwidth = p_width / ratio;
				p_src.height = newheight;
				p_src.width= newwidth;
				if(newwidth>windowW){
					var newnewwidth = windowW;
					var newratio = newwidth/windowW;
					var newnewheight = newheight/newratio;
					p_src.height = newnewheight;
					p_src.width= newnewwidth;
				}
			}
		}
		
		/* LOOK HERE */
		$("#image_container").css({
            //"width":p_src.width+"px", //100%
            "height":windowH+"px"
        });
		
        $image.css({
            "width":p_src.width+"px",
            "height":p_src.height+"px"
        });
    }
})(jQuery);
