(function($) {

	var settings = jQuery.extend({
    	size: '20'
    	, 'ajaxloader': 'gfx/ajax-loader.gif'
		, queryURL : "photoGallery_view.cfm"
  	});
	
	var PG_loader = new Image();
		PG_loader.src = settings.ajaxloader;
	
	
	// START INIT BY URL
	$(function(){
		var doit = $(document).getUrlHashParam("do");
		var imageid = $(document).getUrlHashParam("imageid");
		if (doit == 'photogallery' && (typeof parseFloat(imageid) == 'number'))
		{
			openPhotoGallery(imageid);
		}
	 });
	 
	setQueryURL = function(url) {
		jQuery.extend(settings,{
			queryURL : url
		});
	}
	
	 
	openPhotoGallery = function(imageid){
		jQuery.getJSON(
			settings.queryURL
			, { imageid: imageid }
			, function(json){
				// Get html template
				jQuery.get(
					json.html
					, function(data){
						// Create the modal window
						//h = data.replace(new RegExp('\{album\}'),'hola');
						//alert(h);
						//alert(data);
						data = translatePage(data,json.rb);
						
						createModal(data);
						// Fix png if pngfix exists
						if ( $.fn.pngfix ) {
							$('.PG_prev, .PG_next, .PG_first, .PG_last, .PG_close').pngfix();
						}
						// We call this trigger so we can attach a  
						// job after the html is called.
						$('body').trigger("PG_onload");
						// Fill it with content
						createContent(json);
						// select current
						PG_move('PG_' + imageid);
						
						//
						PG_json = json;
					}
				);
			}
		);
	}

	var translatePage = function(data,rb){
		var ret = data;
		for(key in rb) {
		 	ret = ret.replace(new RegExp('\{' + key + '\}'),rb[key]);
		}
		return ret;
	}

	var getContent = function(famid){
		jQuery.getJSON(
			"index.cfm?event=pa"
			, { famid: famid}
			, function(json){
				createContent(json);
				PG_move('PG_' + famid);
			}
		);
	}
	
	var createModal = function(content){
		
		$(document.createElement('div'))
		.css({
			'position': 'fixed'
			, 'top': '0'
			, 'left': '0'
			, 'width': '100%'
			, 'height': '100%'
			, 'z-index': '2999'
			, 'opacity': '0.5'
			, 'background': 'white'})
		.addClass('PG_overlay')
		.prependTo('body')
		.after( $(content).css({"z-index": '3000' }) )
		.click(function(){
			PG_close();
		});
		
		// IF IE6
		if ($.browser.msie && ($.browser.version < 7))
		{
			fixIE(
				$('#PG')
				, $('.PG_overlay')
			);
		}
		return content;
	}
	
	PG_close = function (){
		$('.PG_overlay').remove();
		$('#PG').remove();
		$(document).writeUrlHashParams("");
	}
	var fixIE = function (modal,overlay) {
			var wHeight = $(document.body).height() + 'px';
			var wWidth = $(document.body).width() + 'px';

			// position hacks
			overlay.css({position: 'absolute', height: wHeight, width: wWidth});
			modal.css({position: 'absolute'});

			// add an iframe to prevent select options from bleeding through
			iframe = $('<iframe src="javascript:false;">')
				.css({
					opacity: 0, 
					position: 'absolute',
					height: wHeight,
					width: wWidth,
					zIndex: 2998,
					width: '100%',
					top: 0,
					left: 0
				})
				.hide()
				.appendTo('body');
	}
	

	
	var createContent = function(json){
		var template =  $(".PG_main_template").clone();
		var newElement = 0;
		var i = 0;
		template
			.removeClass("PG_main_template")
			.addClass("PG_main");
		createCarousel(json);
		while (i < json.imagecount)
		{
			var unique = 'PG_' + json.data[i].id;
			var newElement = template.clone();
			newElement.attr("PG_id",unique);
			newElement.find(".PG_image").append(PG_loader);
			newElement = loadImage(newElement,json.data[i]);
			newElement.find("h2").html(json.data[i].title);
			newElement.find(".PG_text").html(json.data[i].description);
			//newElement.find(".PG_photographer").append(json.data[i].photographer);
			newElement.addClass("PG_main_hide");
			newElement.appendTo(".PG_wrap");
			i = i + 1;
		}
	
	}
	
	var createCarousel = function(json) {
		var jc = $(document.createElement("ul"));
		var i = 0;
		var tmp = 0;
		while (i < json.imagecount)
		{
			$(document.createElement("li"))
				.attr("PG_id",'PG_' + json.data[i].id)
				.append('<img src="' + json.data[i].file_thumb + '" />')
				.click(function(){
					PG_move($(this).attr("PG_id"));
				})
				.appendTo(jc);
			i = i + 1;
		}
		jc.appendTo(".PG_thumb").addClass("PG_controller");
		tmpli = $(".PG_controller").find("li");
		
		// set width
		$(".PG_controller").width( tmpli.siblings(":first").width() * tmpli.length  );
	}

	var loadImage = function(ele,json){
		var objImage = new Image();
		objImage.onload = function(){
			img = scaleImage(this);
			ele.find(".PG_image").html(this);
			objImage.onload = null;
		}
		objImage.src=json.file_orig;
		return ele;
	}
	
	var scaleImage = function(img){
		var maxwidth = 600;
		var maxheight = 400;	
		var width = img.width;
		var height = img.height;
		var ratio = 1;
		
		if (Math.round(width) == 0 || Math.round(height) == 0 )
		{ return img; }
		else { ratio = width / height; }
		if (height > maxheight )
		{
			height = maxheight;
			width = height * ratio; 
		}
		if ( width > maxwidth )
		{
			width = maxwidth;
			height = width / ratio;
		}
		if ( Math.round(width) > 0 )
			img.width = Math.round(width);
		if ( Math.round(height) > 0 )
			img.height = Math.round( height);
	
		return img;
	}
	
	PG_move = function(where){
		var where_to = 0;
		var selected = $(".PG_main:not('.PG_main_hide')").attr("PG_id");
		var imageList = getArrayIdList(".PG_wrap"); 
		var selected_pos = jQuery.inArray(selected,imageList);
		
		switch(typeof where){
			case 'number':
				where_to = selected_pos + where;
				break;
			case 'string':
				if ( where == 'start') { 
					where_to = 0; 
				} 
				else if (where == 'end') { 
					where_to = imageList.length - 1; 
				}
				else {
					where_to = jQuery.inArray(where,imageList);
				}
			break;
		}
		
		if ( where_to >= 0 && where_to < imageList.length && selected_pos != where_to )
		{ 
			PG_move_to("[PG_id="+ imageList[where_to] + "]");
			PG_set_selected(imageList[where_to]);
			moveToSequence(imageList,imageList[where_to]);
			$(document).writeUrlHashParams("do:photoGallery&imageid:" + imageList[where_to].split('_')[1] );
		}	
	}
	/*
	PG_togglePlay = function () {
		var selected = $(".PG_main:not('.PG_main_hide')").attr("PG_id");
		var imageList = getArrayIdList(".PG_wrap"); 
		var selected_pos = jQuery.inArray(selected,imageList);
		var intid = setInterval ( "PG_move(1)", 3000 );

	}
	*/
	// this shoukld
	//currentSequence  = 1
	var moveToSequence = function(imageArray,imageId){
		var cs = typeof currentSequence == 'undefined' ?  1 : currentSequence;
		//var imagePerPage = 5; // global ?
		var sn = 1;
		var i = 1;
		// find sequence
		while ( i <= jQuery.inArray(imageId,imageArray) ){
			if ( (i % settings.size) == 0)
				sn = sn + 1;
			i = i + 1;
		} 
		// now we would know the sequence we are going to $sn	 
		elementwidth = $(".PG_controller").find("li:first").width();
		if (sn > cs || sn < cs){
			move = (elementwidth * settings.size) * (sn - cs) ;
			$(".PG_controller").animate({
				"left": "-=" + move + "px"
			},500 * Math.abs(sn - cs));
			currentSequence = sn;
		}
	}
	
	
	var PG_move_to = function(newid){
		var current = $(".PG_main:not('.PG_main_hide')")
		if (current.length)	{
			current.fadeOut("fast",function(){
				$(this)
					.addClass("PG_main_hide")
					.siblings(newid)
					.css("display","none")
					.removeClass("PG_main_hide")
					.fadeIn("fast");
			});	
		}
		else {
			$(newid)
				.css("display","none")
				.removeClass("PG_main_hide")
				.fadeIn("fast");	
		}		
	}
	
	var PG_set_selected = function(id){
		$(".PG_controller")
			.find(".PG_selected")
			.removeClass("PG_selected")
			.end()
			.find("[PG_id="+ id +"]")
			.addClass("PG_selected");
	}
	var getArrayIdList = function(selector){
		var ret = [];
		$(selector).find(".PG_main").each(function(i){
			ret.push($(this).attr("PG_id"));
		});
		return ret;
	}
	
	// public functions
	
	PG_getImageUrl = function(){
		//var selected = $(".PG_main:not('.PG_main_hide')").attr("PG_id");
		//var imageList = getArrayIdList(".PG_wrap");
		
		var imageid = $(document).getUrlHashParam("imageid");
		var json = PG_json;
		var data = json.data;
		for (i = 0; i < data.length; i = i + 1)
		{
			if (data[i].id == imageid)
			{
				var image_src = data[i].file_orig;
			}
		}
		return image_src;
	}
	
})(jQuery);

/*
$(function(){
	openPhotoGallery(24775);
});
*/