
// collections browser
browser = {	
		
	settings : {
		'scroll_speed' : 500, // milliseconds 
		'thumb_scroll_increment' : 250, // pixels
		'mouse_wheel_increment' : 50 // pixels		
	},
		
	init : function() { 		
		$.historyInit(browser.parse_params);					
		browser.fix_ie(); 		
		browser.thumbnails_browsing();		
		browser.preloader(data);	
		browser.reset_image_container();
	},
	
	parse_params : function() {
		current_location = document.location;
		
			// restore ajax loaded state
		hash = current_location['hash'].replace(/^#/, '');
		hash = hash.split('/');

		params = hash.length;			
		switch(params) {
			case 1:
				browser.category = hash[0];
				browser.position = null;				
			  break;    
			case 2:
				browser.category = hash[0];
				browser.position = hash[1];
			  break;					
			default :
				browser.category = null;
				browser.position = null;
			  break;
		}
		
		// check if current hash is a page or a category_id - extra condition when hash is null
		var pages = null;
		$.each(data, function(i) {
			if(this['Category']['id'] == hash[0] || !browser.category) {
				pages = false;
			}
		})	
		
		if(pages == false) {		
			if(browser.category && browser.category != $('input#category_id').val()) {
				browser.display_collectons_thumbnails(browser.category);
				browser.highlight_category(browser.category);	
				browser.display_collection_images(browser.category);							
			}		

			if(browser.position) {
				browser.side_scroll_to(browser.position);
				browser.highlight_thumbnail(browser.position);
			}	

			// default view load randomly choose picture
			if(!browser.category) {						
				browser.clean_up_history();				
				$('#menu').hide();			
				// browser.display_splash_image(splash_photo);				
				browser.display_splash_page();
			} else {
				$('#menu').show();
			}
		} else { 
			// displaying content page if hash[0] was not found in json data
			browser.display_page(hash[0]);
			browser.highlight_category(hash[0]);	
			browser.clean_up_history();
		}
		      
    // unbind events on arrows
    $('a.arrow').unbind('click');
    $('a.arrow').unbind('mouseover');    
    $('a.arrow').unbind('mouseout');     
		
		// navigation arrows
		$('a.arrow').click(function() {
		  browser.arrow_change_picture(this);
		  return false;
		});
		
		$('a.arrow').mouseover(function() { $(this).animate({opacity: 0.2}, 350); }); 		
		$('a.arrow').mousedown(function() { $(this).css('opacity', 0.35); });                              
		$('a.arrow').mouseup(function()   { $(this).css('opacity', 0.20); });		
		$('a.arrow').mouseout(function()  { $(this).animate({opacity: 0}, 350); });

    // show/hide arrows
		browser.toggle_arrows();	
			
	},
	
	// empty history fields
	clean_up_history : function() {		
		$('#slider_images').hide();
		$('#content #images ul').css('left', '0px');
		$('#content #images ul').empty();
		$('#thumbnails div ul').empty();	
		$('p#pdf').hide();
		$('input#category_id').val('');
		$('input#position').val('');		
	},
	
	// preloading all images
	preloader : function(data) {					
		// looping categories
		$.each(data, function(){			
			// looping collections within categories
			$.each(this['Collection'], function() {
				collection_id = this['id'];				
				//looping photos within collection
				$.each(this['Photo'], function() {					
					t = new Image(); 
					i = new Image(); 
					t.src = "files/collections/" + collection_id + "/" + this['thumb_filename'];					
					i.src = "files/collections/" + collection_id + "/" + this['image_filename'];	
				});		
			});			
		});
	},
	
	arrow_change_picture : function(e) {
	  var d = $(e).attr('rel');
	  var li = $("#thumbnails li.active");

    if(d == 'next') {      
      var next = $(li).next();
      if(next.length > 0) {
        var a = $(next).find('a');
        var url = a.attr('href');        
      } 
    }                    

    if(d == 'prev') {
      var prev = $(li).prev(); 
      if(prev.length > 0) {
        var a = $(prev).find('a');
        var url = a.attr('href');        
      }
    }  
        
    // change location 
    if(url != undefined) {
      window.location = url;     
    }
	}, 
	
	toggle_arrows : function() {
	  var left = parseInt($('#images ul').css('left'));
	  var max_left = ($('#images ul').width() - $('#images').width()) * -1;
	  
	  if(left > max_left) {
      $('#arrows a.next').removeClass('hide');
	  } else {
      $('#arrows a.next').addClass('hide');
	  }
	  
	  if(left < 0) {
      $('#arrows a.prev').removeClass('hide');	    
	  } else {
      $('#arrows a.prev').addClass('hide');
	  }	  
	},
	
	display_page : function(page) {
		// empty the containers
		$('#thumbnails ul').empty();
		$('#thumbnails ul').css('left', '0px');
		$('#content #images ul').css('left', '0px');
		$('#content #images ul').empty();
		
		$.ajax({
		  type: "GET",
		  url: 'pages/' + page,
		  dataType: "html",
		  success: function(msg) {
				$('#content #images ul').append('<li>' + msg + '</li>');
				$('#content #images ul li:first').addClass('content');
			}
 		});
		
		// hide slider
		$('#slider_images').hide();
	},
	
	display_collectons_thumbnails : function(category_id) {		
		// change input value
		$('input#category_id').val(category_id);		
		
		img_width = 50;			
		
		// empty the containers
		$('#thumbnails div ul').empty();
		$('#thumbnails div ul').css('left', '0px');		
		// empty full sized images only when we switch categories
		if(browser.collection == null) {
			$('#content #images ul').empty();
		}

		// assign data from main JSON dump 'data' in index page
		category = data[category_id];		

		// thumbnails position initial value
		position = -1;
		
		// creating thubms
		$.each(category['Collection'], function(i){			
			// looping images wihtin a collection					
			$.each(category['Collection'][i]['Photo'], function(j) {
				// variables
				cat_id = category['Category']['id'];				
				collection_id = category['Collection'][i]['id'];
				src = category['Collection'][i]['Photo'][j]['thumb_filename'];
				photo_id = category['Collection'][i]['Photo'][j]['id'];
				position++;
				
				// build image
				img = '<li class="'+position+'"><a href="#'+cat_id+'/'+position+'" name="'+cat_id+'" class="'+position+'"><div><img src=\"files/collections/'+ collection_id +'/'+ src +'\" /></div></a></li>';		
				
				// append thumbnails
				$('#thumbnails div ul').append(img);			
				
			});			
		});	

		// binding on click events on each thumbnails
		ahref = $("#thumbnails div ul li a");
		$.each(ahref, function(){
			$(this).bind('mousedown', function(){
				// return false and slide scroll to if current collection_id equal parsed hash
				if($('input#category_id').val() == this.name) {
					browser.side_scroll_to(this.className);
					$('input#position').val(this.className);
					// return false;
				} else {
					if($.browser.safari == false) {
						browser.display_collection_images(this.name);
					}
				}
			})			
		});
				
		if(category['Category']['pdf']) {
			$("p#pdf").show();
			$("p#pdf a").attr('href', "files/categories/" + category_id + "/" + category['Category']['pdf']);
		} else {
			$("p#pdf").hide();
		}
		
		// display thumbs navigation
		browser.thumbnails_browsing();				
	},
	
	// hightlight the current collection thumbnails
	highlight_category : function(category_id) {
		ahref = $("ul#menu li a");
		$.each(ahref, function(){
			$(this).removeClass('active');
			if(this.name == category_id) {
				$(this).addClass('active');
			}			
		});
	},

	// hightlight the current thumbnails
	highlight_thumbnail : function(position) {
		ahref = $("#thumbnails ul li");
		$.each(ahref, function(){			
			$(this).removeClass('active');
			if(this.className == position) {
				$(this).addClass('active');
			}			
		});
	},	
	
	thumbnails_browsing : function() {
		// calculatin actual width of thumbnails
		new_width = 0;
		thumbs = $('#thumbnails ul li');
		$.each(thumbs, function(i) {
			// increment new_width
			new_width += $(this).width();
		});		
		// hide or show based on #wrap width
		if(new_width > ($('#wrap').width() - 150)) {
			$('a.thumbs_nav').show();
		} else {
			$('a.thumbs_nav').hide();	
			$('#thumbnails ul').animate({ 
			        left: '0px'
			}, 500);
		}		
	},		
	
	// ugly as hell but it works
	scroll_thumbs: function(direction) {
		increment = this.settings.thumb_scroll_increment; // increment value	
		
		if(direction == 'left') {				
			left = parseInt($('#thumbnails div ul').css('left'));
			if(left < 0) {
				new_left = (left + increment);							
			}	else {
				new_left = 0;
			}
		} else if (direction == 'right') {
			increment = increment * -1;
			left = parseInt($('#thumbnails div ul').css('left'));
			max = $('#thumbnails div ul').width() + left;
			
			if(max < $('#thumbnails').width() - 150) {
				new_left = left;	
			} else {
				new_left = left + increment;				
			}			
		}		

		// $('#thumbnails ul').css('left', new_left + 'px');		
		$('#thumbnails ul').animate({ 
		        left: new_left
		}, this.settings.scroll_speed);
		
	},
			
	// display collection image into #container
	display_collection_images : function(category_id) {		
		// empty container
		$('#content #images ul').empty();

		// set data for current collection
		photos = data[category_id];
		
		// parsing JSON data and loading large image
		browser.parse_large_image(photos);		
	},

	parse_large_image: function(category, collection) {	
		new_width = 0;
		
		$.each(category['Collection'], function(i){						
			// looping images wihtin a collection					
			$.each(category['Collection'][i]['Photo'], function(j) {
				// name is the picture parent collectionId, id is picture_id							
				cat_id = category['Category']['id'];				
				collection_id = category['Collection'][i]['id'];
				collection_description = category['Collection'][i]['name'];
				collection_year = category['Collection'][i]['year'];				
				src = category['Collection'][i]['Photo'][j]['image_filename'];
				photo_id = category['Collection'][i]['Photo'][j]['id'];
				photo_width = category['Collection'][i]['Photo'][j]['width'];
				img = '<li style="float:left; width:'+photo_width+'px;"><img src=\"files/collections/'+collection_id+'/'+src+'\" width="'+photo_width+'" desc="'+collection_description+'" year="'+collection_year+'" /></li>';
				$('#content #images ul').append(img);			
				
				// increment image container width
				new_width += parseInt(photo_width) + 5;
			});
		});	
		
		// remove 5 px (last picture should be flush with the edge of the container right side)
		new_width -= 5;	
		
		// remove border on last image
		$('#content #images ul li:last').css('margin', '0');
		$('#content #images ul li img:last').css('border', '0');			
			
		// setting new width to slidable container
		new_images = $('#content #images ul li img');
		$.each(new_images, function() {
			$(this).bind('mouseover', function() {
				$('p#title').text($(this).attr('desc'));
				$('p#year').text($(this).attr('year'));				
			}).bind('mouseout', function() {
				$('p#title').text('');
				$('p#year').text('');
			})
		});
		
		// fadeIn container
		$('#content #images ul').css('opacity', '0').animate({ 
			opacity: 1
		}, 250);							
		
		// adjust container width and reset position
		$('#content #images ul').css('width', new_width).css('left', '0');
    // $('#content #images ul');            
				
		// toggle slider visibility and activation
		browser.toggle_images_slider();				
	},
	
	reset_image_container : function() {
	  $('#content #images ul').css('left', '0');
	},
	
	display_splash_image: function(data) {		
		cat_id = data['Collection']['category_id'];				
		collection_id = data['Photo']['collection_id'];
		src = data['Photo']['image_filename'];
		photo_id = data['Photo']['id'];
		photo_width = data['Photo']['width'];
		img = '<li style="float:left; width:'+photo_width+'px; margin-right: 5px;"><img src=\"files/collections/'+collection_id+'/'+src+'\" width="'+photo_width+'" /></li>';
		$('#content #images ul').append(img);
		
		// fadeIn container
		$('#content #images ul').css('opacity', '0');							
		$('#content #images ul').animate({ 
		        opacity: 1
		}, 500);
		
		// center image
		new_pos = browser.center_image('#images', '#images ul li:first', 0);
		$('#images ul li:first').css('marginLeft', new_pos + "px");
		
		// bind click on splash image
		$('#images ul li:first img').css('cursor', 'pointer').attr('title', 'Click to enter').bind('mousedown', function() {
			window.location = $("#menu li a:first").attr('href');
			browser.parse_params(); // fixing IE7
			$('#menu').show();
		})			
	},
	
	display_splash_page : function() {
		$('#slider_images').hide();
		
		splash = $("<div/>").attr('id', 'splash');
		$(splash).appendTo("body");
		
		$.get('/app/webroot/splash/card.html', null,
			function(data){
				$(splash).html(data);
				$('a.enter').mousedown(function() {
					window.location = $("#menu li a:first").attr('href');
					browser.parse_params(); // fixing IE7
					$('#menu').show();
					$("#splash").remove();
				});
			}
		);

	},

	toggle_images_slider : function() {
		// show or hide the images slider	if contain is narrower than container
		if($('#images ul').width() < $('#images').width()) {
			$('#slider_images').hide();
			
			// center image(s) within container
			available_width = $('#images').width();
			images_width = $('#images ul').width();	
			$('#images ul').css('left', (available_width - images_width) / 2 + "px");			
		} else {
			$('#slider_images').show();		
						
			// init slider
			$("#slider_images .ui-slider-handle").css('left', '0px');
			$('#slider_images').slider({			
				slide : function(e, ui) {
					browser.slide_images(e, ui, '#content #images ul', '#content #images');
				}			
			});	
			
			// attach mouseWheel on image container
			$('#images').mousewheel(function(event, delta) {
				browser.mouse_wheel_images(event, delta);
			});
			
		}		
	},
	
	// slide function
	slide_images : function(e, ui, el, container) {						
		// containerSize
		content_width = $(el).width() - $(container).width();				

		// calculating new position
		new_pos = parseInt(((content_width * ui['value']) / 100) * -1) + 'px';

		// setting new position
		$(el).css('left', new_pos);
	},
		
	mouse_wheel_images : function(event, delta) {
		increment = this.settings.mouse_wheel_increment;
		left = parseInt($('#images ul').css('left'));
					
		if(delta > 0) { // up scrolling
			new_left = (left + delta) + increment;
			// apply new position
			$('#images ul').css('left', new_left + "px");
			
			// stop scrolling if needed
			if(parseInt($('#images ul').css('left')) >= 0) {
				$('#images ul').css('left', '0px');
			}
		} else if (delta < 0) { // down scrolling
			new_left = (left + delta) - increment;
			
			// apply new position
			$('#images ul').css('left', new_left + "px");						
			
			// stop scrolling if needed
			max_value = ($('#images ul').width() - $('#images').width());
			if(parseInt($('#images ul').css('left')) <= max_value * -1) {
				$('#images ul').css('left', max_value * -1 + 'px');
			}			
		}
		
		//console.log(left);		
		browser.adapt_scroller(parseInt($('#images ul').css('left')));
		
	},
		
	side_scroll_to : function(target) {
		if($('#images ul').width() > $('#images').width()) {
			var new_pos = 0;
			var right_gap = 0;

			// get all images widths in JSON data object
			li = [];
			for (var i=0; i < data[browser.category].Collection.length; i++) {
				for (var j=0; j < data[browser.category].Collection[i].Photo.length; j++) {
					li.push(parseInt(data[browser.category].Collection[i].Photo[j].width));       
				};
			};
			
			max = li.length;
			last = max - 1;

			for (i = 0; i < target; i++) {
				new_pos += li[i] + 5;
			}

			// calculate right gap
			for (i = target; i < max; i++) {
				right_gap += li[i] + 5;
			}			
			right_gap -= 5;

			// adding gap if it's the last picture in collection
			if(right_gap < $('#images').width()) {
				end_gap = $('#images').width() - right_gap;
				new_pos = new_pos - end_gap;
			}

			// transform into a negative value
			new_pos = new_pos * -1;

			// scroll image to
			$('#content #images ul').animate({ 
			        left: new_pos
						},
						this.settings.scroll_speed,
						function() { browser.toggle_arrows() },
						browser.adapt_scroller(new_pos)
			);
		}		  
	},
	
	// will return a (P)osition value for centering anyelement within a container
	center_image : function(container, target, offset) {		
		p = Math.round(($(container).width() - ($(target).width() + offset)) / 2)		
		return p;  
	},
	
	adapt_scroller : function(pos) {		  
		// calculate percent for scroller position	
		percent = (pos * -1) * 100 / ($('#images ul').width() - $('#images').width());
		
		// adapt scroller position
		//scroller_left = Math.round((($('#slider_images').width() + $('#slider_images div.ui-slider-handle').width()) * pos) / $('#images ul').width());	
		scroller_left = Math.round(percent * (($('#slider_images').width() - 5) - $('#slider_images div.ui-slider-handle').width()) / 100);
		
		// apply new left position
		$('#slider_images div.ui-slider-handle').css('left', scroller_left);		
	},
	
	fix_ie : function() {
		if($.browser.msie && $.browser['version'] >= '6.0') {
			links = $('a');
			$.each(links, function() {
				$(this).bind('click', function() {
					window.location = this.href;
					browser.parse_params();					
				})
			});
		}
	}	
}


