(function(window, undefined){
		  
	if (window.nph){
		return; 
	}
	
	var $ = window.NTES,
        nph = window.nph = {};
		
	function Gallery(sn){
		sn = sn || ""; 
		var t = this,
			ids = ["gallery", "galleryTpl", "galleryRelat", "modePhoto", "modeStream", "modeSearch", "setInfo", "photoType", "streamType", "viewOrig", "", "bar", "thumb", "scrlPrev", "scrlNext", "photo", "photoIndex", "photoDesc", "photoView", "photoPrev", "photoNext", "photoLoading", "stream", "search" ,"searchInput", "searchPhoto", "searchTheme", "searchFound", "searchNotFound"],
			i = ids.length;
		
		while(--i >= 0){
			t["$" + ids[i]] = $("#" + ids[i] + sn);
		}
		
		t.isChangeUrl = sn ? false : true;

		//t.$searchInput.addEvent("focus", function(){NTES.one("> label", this.parentNode).addCss("hidden");})
		//	.addEvent("blur", function(){!this.value && NTES.one("> label", this.parentNode).removeCss("hidden");});
			
		/*t.$searchPhoto.addEvent("submit", function(e){
			e.preventDefault();
			t.changeMode("search");
			t.showSearch(this["q"].value);
		});*/
		
		NTES.ui.Template.load(t.$galleryTpl.$("> div"));
		
		t.streamSize = {};
		
		var pWidth = 670;//t.$photoView.offsetWidth,
			pHeight = 445;//t.$photoView.offsetHeight,
			sHeight = pHeight + 130,
			hash = document.location.hash;
		
		t.streamSize.cols = Math.floor(pWidth / 180);
		t.streamSize.rows = Math.floor(sHeight / 215);
		t.streamSize.size = t.streamSize.cols * t.streamSize.rows;
		document.write(
			'<style type="text/css">#gallery' + sn + ' .nph_list_stream{width:'
			+ pWidth
			+ 'px;height:' 
			+ sHeight
			+ 'px;}#gallery' + sn + ' .nph_list_stream li{width:'
			+ Math.floor(pWidth / t.streamSize.cols)
			+ 'px;height:'
			+ Math.floor(sHeight / t.streamSize.rows)
			+ 'px;}</style>'
		);
		
		if(t.isChangeUrl && t.getQ(hash) !== undefined){
			t.changeMode("search");
			t.showSearch(t.getQ(hash), t.getPage(hash));
			return;
		}
		
		t.photoIndex = {};
		t.photoInfo = [];
		t.$thumbs = t.$thumb.$("> li");
		t.size = t.$thumbs.length;
					
		var tCntWidth = t.$thumb.parentNode.offsetWidth,
			bCntWidth = t.$bar.parentNode.offsetWidth,
			uWidth = t.$thumbs.$(0).offsetWidth,
			tWidth = uWidth * t.size,
			bWidth = Math.max(t.$bar.offsetWidth, Math.min(tCntWidth * bCntWidth / tWidth, bCntWidth));
		
		t.$thumbs.each(function(i) {
			var self = this, mult = i - Math.ceil(tCntWidth / (uWidth * 2)) + 1;
			t.photoIndex[self.id] = i;
			t.photoInfo.push({
				id: self.id,
				title: NTES.one("> p[title=title]", self).attr("innerHTML"),
				desc: NTES.one("> p[title=desc]", self).attr("innerHTML"),
				img: NTES.one("> p[title=img]", self).attr("innerHTML"),
				timg: NTES.one("> p[title=timg]", self).attr("innerHTML"),
				pos: uWidth * mult
			});
		}); 
		
		t.$thumb.addCss({width: tWidth + "px"});
		t.$bar.addCss({width: bWidth + "px"});
		t.$viewOrig.addEvent("click", function(){ window.open(t.$photo.src); });
		//t.$viewStream.addEvent("click", function(event){ event.preventDefault(); t.changeMode("stream"); t.showStream(); });
		$([t.$photoPrev, t.$photoNext, t.$scrlPrev, t.$scrlNext, t.$bar].concat(t.$thumbs.$("> a")))
			.addEvent("click", function(event){ event.preventDefault(); })
			.addEvent("focus", function(){ this.blur(); });
				
		t.bar = new NTES.ui.Scroll(t.$thumb, 'x', t.$bar);
		
		t.$scrlPrev.addEvent("mousedown", function(){ t.bar.start("forward"); }).addEvent("mouseup", function(){ t.bar.stop(); });
		t.$scrlNext.addEvent("mousedown", function(){ t.bar.start("backward"); }).addEvent("mouseup", function(){ t.bar.stop(); });
		
		$([t.$photoPrev, t.$photoNext].concat(t.$thumbs.$("> a"))).addEvent("click", function(){
			t.showPhoto(t.getIndex(this.href));
		});
		
		t.$photo.addEvent("load", function(){
			NTES.browser.msie && NTES.browser.version == 6.0 && t.resize(this, { width: pWidth, height: pHeight });
			t.$photoLoading.addCss("hidden");
			(new Image).src = t.photoInfo[t.getIndex(t.$photoNext.href)].img;
		});
		
		if(t.isChangeUrl && t.getPage(hash)){
			t.changeMode("stream");
			t.showStream(t.getPage(hash));
			return;
		}
		
		t.changeMode("photo");
		t.showPhoto(t.getIndex(hash));
	};
	
	Gallery.prototype = {
		showPhoto: function(index){
			index = isNaN(index) ? 0 : index;
			var t = this, info = t.photoInfo[index], prev = index - 1, next = index + 1;
			prev = prev >= 0 ? prev : t.size - 1;
			next = next < t.size ? next : 0;
			t.$photoLoading.removeCss("hidden");
								
			t.$photoIndex.innerHTML = index + 1;
			t.$photo.src = info.img;
			t.$photoDesc.attr("innerHTML", String.format("<h2>%1</h2><p>%2</p>", info.title, info.desc));
			t.$photoPrev.href = "#p=" + t.photoInfo[prev].id;
			t.$photoNext.href = "#p=" + t.photoInfo[next].id;
			t.bar.onStart = function(){
				t.$thumbs.removeCss("active");
				t.$thumbs.$(index).addCss("active");
			}; 
			t.bar.scrollTo(info.pos);
			t.isChangeUrl && t.changeUrl("#p=" + info.id);
			t.stats();
		},
		showStream: function(page){
			var t = this;
			page = isNaN(page) || page < 1 || page > t.size ? 1 : page;
			var params = {
					stream: t.photoInfo.slice(t.streamSize.size * (page - 1), t.streamSize.size * page),
					page: page,
					total: Math.ceil(t.size / t.streamSize.size)
				};
			t.$stream.innerHTML = NTES.ui.Template.parse("stream", params);
			t.$stream.$("> ul.nph_list_stream a").addEvent("click", function(event){ event.preventDefault(); t.changeMode("photo"); t.showPhoto(t.getIndex(this.href)); });
			t.$stream.$("> div.nph_pages > a").addEvent("click", function(event){ event.preventDefault(); t.showStream(t.getPage(this.href)); });
			t.isChangeUrl && t.changeUrl("#page=" + page);
			t.stats();
		},
		showSearch: function(q, page){
			q = q || "";
			page = isNaN(page) || page < 1 ? 1 : page;
			var t = this,
				channelid = t.channelid || "",
				size = t.streamSize.size,
				start = (page - 1) * size;
			NTES.ajax.importJs(
				String.format("http://uvs.youdao.com/search?site=photogalaxy.163.com&sort=time&q=%1&channelid=%2&length=%3&start=%4", q, channelid, size, start),
				t.buildSearch.bind(t)
			);
			t.isChangeUrl && t.changeUrl("#q=" + q + "&page=" + page);
			t.stats();
		},
		buildSearch: function(){
			var t = this;
			if(!jsonres.availHits){
				t.$searchFound.addCss("hidden");
				t.$searchNotFound.removeCss("hidden");
				NTES.one("> span", t.$searchNotFound).innerHTML = jsonres.q ? '"' + jsonres.q + '"' : '';
				t.$search.innerHTML = "";
				return false;
			}
			t.$searchFound.removeCss("hidden");
			t.$searchNotFound.addCss("hidden");
			NTES.one("> span", t.$searchFound).innerHTML = jsonres.q ? '"' + jsonres.q + '"' : '';
			NTES.one("> span.nph_search_count span", t.$searchFound).innerHTML = jsonres.availHits;
			var params = {
				q: jsonres.q,
				stream: jsonres.hits,
				page: Math.floor(jsonres.start / jsonres.length) + 1,
				total: Math.ceil(jsonres.availHits / jsonres.length)
			}
			
			t.$search.innerHTML = NTES.ui.Template.parse("search", params);
			
			t.$search.$("> div.nph_pages > a").addEvent("click", function(event){ event.preventDefault(); t.showSearch(t.getQ(this.href), t.getPage(this.href)); });
		},
		changeMode: function(mode){
			var	t = this;
			switch(mode){
				case "photo":
					$([t.$modePhoto, t.$photoType]).removeCss("hidden");
					$([t.$modeStream, t.$modeSearch, t.$streamType]).addCss("hidden");
					break;
				case "stream":
					$([t.$modeStream, t.$streamType]).removeCss("hidden");
					$([t.$modePhoto, t.$modeSearch, t.$photoType]).addCss("hidden");
					break;
				case "search":
					$([t.$modeSearch]).removeCss("hidden");
					$([t.$modePhoto, t.$modeStream, t.$setInfo, t.$galleryRelat]).addCss("hidden");
					break;
			}
		},
		resize: function($img, size){
			$img.removeAttribute("width");
      		$img.removeAttribute("height");
			size = size || {};
			var rw = size.width ? $img.width / size.width : 0,
				rh = size.height ? $img.height / size.height : 0;
			if(rw > 1 || rh > 1){
				rw > rh ? $img.width = size.width : $img.height = size.height;
			}
		},
		getIndex: function(url){
			var t = this,
				matchs = url.match(/#([^&]*&)*p=([^&]+)/i),
				id = matchs ? matchs[2] : undefined;
			return t.photoIndex[id];
		},
		getPage: function(url){
			var matchs = url.match(/#([^&]*&)*page=([^&]+)/i),
				page = matchs ? parseInt(matchs[2]) : NaN;
			return page;
		},
		getQ: function(url){
			var matchs = url.match(/#([^&]*&)*q=([^&]+)/i),
				q = matchs ? matchs[2] : undefined;
			return q;
		},
		changeUrl: function (url) {
        	window.location.href = url;
    	},
		stats: function(){
			typeof vjEventTrack === "function" && vjEventTrack();
        	typeof neteaseTracker === "function" && neteaseTracker();
		}
	}	  
	nph.Gallery = Gallery;
})(window);
