<%# encoding: utf-8 %>
$.extend($.expr[':'], {
	'containsi': function (elem, i, match, array) {
		return (elem.textContent || elem.innerText || '').toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
	}
});
var custom_galleryAPI = function(){
	g = this;
	this.urlVars = rcom.getUrlVars();
	this.custom_albumArea = $("#orbit_custom_gallery");
	this.loadArea = null;
	this.tagList = $("ul#custom_gallery_tag_list");
	this.loading = $("#loading");

	this.fullscreen_mode = false;
	
	this.loadTheater = function(id){
		
		g.loadstart();
		var imageArray = [];
		var imagecount = 0;
		var picHeight = 0;
		var bindHandlers = function(){
			var $slidelist = $('.slidelist'),
				$rslide = $('.rslide'),
				$rslidenav = $('.rslidenav'),
				$img = $("#main_pic img"),
				wHeight = $(window).height();

				$("#main_pic").height(picHeight);
				$img.height("100%");
			
			$('.bt-tag').click(function(){
				if(!$(this).hasClass("active"))
					updatePhotoTag();
				$(this).toggleClass("active");
				var $tag_panel = $('#tag_panel'),
					tag_panel_position = 0;

				if( $tag_panel.css('right') == '0px' ){
					tag_panel_position = -200;
				}
				$tag_panel.animate({'right':tag_panel_position}, 300);

				g.custom_albumArea
					.delay(200)
					.animate({'margin-right':tag_panel_position+200},300);
				return false;
			});
			var updatePhotoTag = function(){
				var tags = imageArray[imagecount].tag_ids;
				if(tags.length > 0 && g.tagList.find("li").length == 0){
					var tagnames = imageArray[imagecount].tag_names;
					g.tagList.empty();
					for(i in tagnames){
						$li = $("<li><label>"+tagnames[i]+"</label><span style='display:none;'>"+tagnames[i]+"</span></li>");
						g.tagList.append($li);
					}
				}else if(tags.length > 0 && g.tagList.find("li").length > 0) {
					g.tagList.find("input").attr("checked",false);
					for(tag in tags){
						g.tagList.find("li[data-content="+tags[tag]+"] input").attr("checked",true);
					}
				}else if(tags.length == 0){
					if(g.tagList.find("input").length == 0)
						g.tagList.empty();
					else
						g.tagList.find("input").attr("checked",false);
				}
			}
			g.custom_albumArea.find("#tag_search_box").keyup(function(e){
				sval = $(this).val();
				if(sval == "<%= I18n.t('custom_gallery.search_tags') %>")
						sval = "";
				sval = sval.replace(/(^\s*)|(\s*$)/g,'');
				if(sval){
					var re1 = new RegExp("^[\u4E00-\uFA29]*$"); //Chinese character range 
					var re2 = new RegExp("^[\uE7C7-\uE7F3]*$");
					if ((re1.test(sval) && (re2.test(sval)))){
						$("#custom_gallery_tag_list li span:not(:contains("+sval+"))").parent().slideUp();
					}else{
						$("#custom_gallery_tag_list li span:not(:containsi("+sval+"))").parent().slideUp();
					}
						
				}else{
					$("#custom_gallery_tag_list li").slideDown();
				}
			})
			g.custom_albumArea.find("#tag_panel .bt-save").click(function(){
				g.saveTags(imageArray[imagecount]._id,"pic",function(tagids){
					imageArray[imagecount].tag_ids = tagids;					
				})
			})
			$(".slidectrl a.togglelist").click(function(){
				var rslide_h = $rslide.outerHeight();
				if ( $slidelist.height() < 1 ){
					$slidelist.stop().animate({'height':rslide_h - 30}, 300);
					$slidelist.find("ul").show();
				} else {
					$slidelist.stop().animate({'height':'0px'}, 300);
					$slidelist.find("ul").hide();
				}
			})
			$(".slidectrl .togglescreen").click(function(){
				toggleFullscreen();
			})
			$(".slidectrl .browserfullscreen").click(function(){
				browserFullScreen();
			})
			$slidelist.find(".list_element").click(function(){
				imagecount = parseInt($(this).parent().attr("for"));
				changeImage($(this));
			})
			$rslidenav.find(".navN").click(function(){
				nextpic($(this));
			})
			$rslidenav.find("a.navP").click(function(){
				prevpic($(this));
			})
			$("#nextpic").click(function(){
				nextpic($(this));
			})

			$(document).keydown(function(e){
			    if (e.keyCode == 37){ 
			    	prevpic($rslidenav.find(".navP"));
			       return false;
			    }
			    if(e.keyCode == 39){
			    	nextpic($rslidenav.find(".navN"));
			    	return false;
			    }
			    if(e.keyCode == 27){
			    	toggleFullscreen();
			    	$rslide.removeClass('browserFullScreen');
			    	return false;
			    }
			    if(e.keyCode == 70 || e.keyCode == 102){
			    	if($rslide.hasClass("fullscreen"))
			    	 browserFullScreen();
			    }
			});
			var browserFullScreen = function(){
				if(g.fullscreen_mode==false){
					var el = document.documentElement,
      				rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen;
    			rfs.call(el);
    			g.fullscreen_mode = true;
				}else{
					var el = document,
      				rfs = el.exitFullscreen || el.msExitFullscreen || el.webkitExitFullscreen || el.mozCancelFullScreen;
    			rfs.call(el);
    			g.fullscreen_mode = false;
				}
			}
			$(window).resize(function(){
				if(window.innerWidth == screen.width && window.innerHeight == screen.height) {
					$rslide.addClass('browserFullScreen');
				} else {
					$rslide.removeClass('browserFullScreen');
				}
			})
			var nextpic = function(dom){
				if(imagecount == imageArray.length - 1)
					imagecount = 0;
				else
					imagecount++;
				changeImage(dom);
			}
			var prevpic = function(dom){
				if(imagecount == 0)
					imagecount = imageArray.length - 1
				else
					imagecount--;
				changeImage(dom);
			}
			var toggleFullscreen = function(){
				if($rslide.hasClass("fullscreen")){
					$rslide.css("position","relative");
					$rslide.removeClass("fullscreen");
					$(".slidectrl .browserfullscreen").hide();
					$img.css({"padding":""})
					$("#main_pic").height(picHeight );
				}else{
					 $("#main_pic").height(wHeight);
					// $img.height("100%");
					$rslide.css("position","");
					$rslide.addClass("fullscreen");
					$img.css({"padding":($rslide.height()-$img.height())/2})
					$(".slidectrl .browserfullscreen").show();
				}
			}
			window.onpopstate = function(){
				var image_id = document.URL.split('/')[document.URL.split('/').length-1];
				var image = imageArray.filter(function(a){return a._id == image_id})[0];
				imagecount = imageArray.indexOf(image);
				changeTheaterImage(image.file.theater.url);
			}
			var changeImage = function(dom){
				var pageurl = dom.attr('href');

				if(rcom.getInternetExplorerVersion() == -1){
				    if(pageurl!=window.location){
				      window.history.pushState({path:pageurl},'',pageurl);
				    }
				}else{
			   		window.location.hash = pageurl;
			   	}

			   	changeTheaterImage(dom.attr("data-content"));
			}
			var changeTheaterImage = function(url){
				$img.fadeOut(200,function(){
					g.loadstart();
					$img.attr("src","");
					$img.attr({"src":url,"height":picHeight+"px"}).load(function(){
						$img.fadeIn(200);
						g.loadcomplete();
					});
					
	 				if($rslide.hasClass("fullscreen")){
	 					$img.css({"padding":($rslide.height()-$img.height())/2})
	 				}
	 				$slidelist.stop().animate({'height':'0px'}, 300);
					$slidelist.find("ul").hide();
				    // $(".slideinfo b.info").text(imageArray[imagecount].title);
				    if($('.bt-tag').hasClass("active"))
				    	updatePhotoTag();
				    if(imageArray[imagecount].description)
				    	$(".slideinfo .info").text(imageArray[imagecount].description);
				    else
				    	$(".slideinfo .info").text("");
				    if(imageArray.length > 1)
				    	updateNavigation();
			    })
			}
			var updateNavigation = function(){
				var next, prev;
				if(imagecount == 0){
					next = 1;
					prev = imageArray.length - 1; 
				}else if(imagecount == imageArray.length - 1){
					next = 0
					prev = imageArray.length - 2;
				}else{
					next = imagecount + 1;
					prev = imagecount - 1;
				}
				$(".navN").attr({"href":imageArray[next]._id,"data-content":imageArray[next].file.theater.url});
				$(".navP").attr({"href":imageArray[prev]._id,"data-content":imageArray[prev].file.theater.url});
			};
			if(imageArray.length > 1)
				updateNavigation();
		}
		
		var preparestage = function(custom_albumid){
			$.getJSON("../custom_galleries/"+custom_albumid+"/imgs",function(custom_album){
				// imageArray = eval(custom_album.images);
				$.each(custom_album.images,function(i,image){
					imageArray.push(image)
					if(image._id == id)
						imagecount = i;
				})
				bindHandlers();
			})
		}
		
		if(rcom.getInternetExplorerVersion()!=-1){
			var photo_id = window.location.hash.replace("#","");
			if(photo_id){
				var url = window.location.href;
				var params = url.split("/");
				// params[params.length-1] = photo_id;
				url = url.replace(params[params.length-1],photo_id);

				window.location.href = url;
			}
		}
		
		var custom_albumid = $("#main_pic").attr("data-content");
		g.custom_albumArea.find(".bt-back").attr("href",'/'+g.locale+"/admin/custom_galleries/"+custom_albumid);
		g.custom_albumArea.find(".bt-edit").attr("href","../custom_albums/"+custom_albumid+"/edit");	
		g.custom_albumArea.css("margin-bottom","0");
		picHeight = $(window).height() - ($("#orbit-bar").outerHeight() + $("#orbit_custom_gallery .form-actions").outerHeight());
		preparestage(custom_albumid);
		
	}
	this.loadcomplete = function(){
		g.loading.hide();
	}
	this.loadstart = function(){
		g.loading.show();
	}
	
}
  custom_galleryAPI.prototype.locale = "<%= I18n.locale %>";