$(window).ready(function() {
	
		// window stuff =========================================================
		function vertical_align() {
			padding = ($(window).height() - $('#wrapper').height()) / 2;
			$('body').css({ 'padding-top': padding });
			$('#wrapper').show();
		} vertical_align(); 
	
		window.onresize = function() {
			vertical_align();
		}
});


$(document).ready(function() {
						
	    /*
		if ($(window).width() < 1312) { var _width = '780'; } 
		else { var _width = '900'; }
        */
        var _width = '900';
        
		// flickr ==============================================================				
		set = window.location.search;
		setID = set.replace('?set=', '');			
		
		// set default as home page set
		if (setID == '' ) {
		    setID = '72157627126408160';
		    $("ul a:contains('home')").addClass('selected');
		};
                        
		// projects
		// ---------------------------------------------------------------------------
		if (window.location.pathname == "/projects.php") { // whenever there is a project
			$("a:contains('projects')").addClass('selected');
			
              $('li.projects').css({ left: '250px' }, 900);
              $('li.about').css({ left: '154px' }, 900);
              $('<span> :</span>').appendTo($('li.projects a'));                  			
			
			$('ul.projects').fadeIn();
			
			// console.log(set);
			var the_category = $('.clients a[href="/projects.php'+ set +'"]').parent().parent().attr('id').replace(/-/g, ', ');            
			$('ul.categories li a:contains('+ the_category +')').css({color: '#4C514D'}).parent().parent().addClass('faded');
						
			// console.log($('.clients a[href="/projects.php'+ set +'"]').parent());
			$('.clients a[href="/projects.php'+ set +'"]').parent().addClass('selected');
			$('<span></span>').prependTo($('.clients a[href="/projects.php'+ set +'"]').parent());
			
			$('.clients a[href="/projects.php'+ set +'"]').parent().parent().show();
			$('.clients a[href="/projects.php'+ set +'"]').css({color: '#4C514D'}).parent().next().show();
		};
		
		
		// about
		// ---------------------------------------------------------------------------
		if (window.location.pathname == "/about.php") { // whenever there is a project
			$("a:contains('about us')").addClass('selected');
			
              $('li.about').css({ left: '240px' }, 900);
              $('li.projects').css({ left: '154px' }, 900);
              $('<span> :</span>').appendTo($('ul li.about a'));                  			
              			
			$('ul.about').fadeIn();
			
			// console.log($('.about li a[href="/about.php'+ set +'"]'));
			$('.about li a[href="/about.php'+ set +'"]').css({color: '#4C514D'}).parent().parent().addClass('faded');
			
			
			// var the_category = $('.clients a[href="/about.php'+ set +'"]').parent().parent().attr('id').replace(/-/g, ', ');            
			// console.log(the_category);
			// $('ul.categories li a:contains('+ the_category +')').css({color: '#4C514D'}).parent().parent().addClass('faded');
						
			// console.log($('.clients a[href="/projects.php'+ set +'"]').parent().parent());
			// $('<span></span>').prependTo($('.clients a[href="/projects.php'+ set +'"]').parent());
			
			// $('.clients a[href="/projects.php'+ set +'"]').parent().parent().show();
			// $('.clients a[href="/projects.php'+ set +'"]').css({color: '#4C514D'}).parent().next().show();
		};		
		
		
		
		
			
		// assign your api key equal to a variable		
		// user id : 63816332@N0
		var apiKey = '86ae807559b81a0c5e98c83e8a8d95e4';
		
			var jqxhr = $.getJSON('http://api.flickr.com/services/rest/?&method=flickr.photosets.getPhotos&api_key=' + apiKey + '&photoset_id=' + setID + '&format=json&jsoncallback=?', 
			function(data){
				// console.log(data);
				$.each(data.photoset.photo, function(i,item) {
															
					// the photo id is { item.id }
					var thumbnail = 'http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_t.jpg';
					var original = 'http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_b.jpg';

                    // if is home page 
                    if (window.location.search == "") {
    					// if ($('#content-home img').length == 0) { // load first image and description
                        //     $('#content-home').hide();
    					// 	$('<img width="1252" height="356" src="' + original + '" alt="" />').appendTo("#content-home");
    					// 	$('#content-home').fadeIn();
    					// }
    					// preload all home page images
    					if (i <= 5) {
							$('<img width="' + 1245 + '" height="356" src="' + original + '" alt="" />').appendTo("#content-home");
    					}
						if (i == 5) {						
							$('#content-home img:first').fadeIn(3000, function() {
								$('#content-home').cycle({	speed:  2000, 
															timeout: 4000 });
							});
						};
						// console.log(i);
    					    					
                    } else {                    
    					if ($('#content img').length == 0) { // load first image and description
    						$('<img width="' + _width + '" height="356" src="' + original + '" alt="" />').appendTo("#content");
    						get_tags(item.id);
    					}
    					// construct thumbnails section
    					// add item.id to class attr to keep the photo id for additional request ( get tags );
    					if (i <= 8) { // index 0 - limit to 9 max
    						$('<a class="' + item.id + '" href="' + original + '"><img width="90" src="' + thumbnail + '" alt="' + item.title + '" /></a>').appendTo("#thumbnails");
    					}    					
                    }                    
				});
			});
			
			jqxhr.complete(function() { 
    			// $('<img src="' + window.large[0] + '" />').appendTo("#contanier");
    			$("#thumbnails a:first-child img").css({ opacity: 0.3 });
				$("#thumbnails a:first-child").addClass('selected');
				$('.sidenav').fadeIn('slow');	
				
                // hide thumbnails if only one            
                // console.log($('#thumbnails a:last-child').index());
                if ( $('#thumbnails a:last-child').index() == 0 ) {
					$('.sidenav').hide();	
                    $('#thumbnails a:last-child').hide();
                }
			});
			
			// use another ajax request to get the tags of the image
			
			function get_tags(element_id) {
				$.getJSON('http://api.flickr.com/services/rest/?&method=flickr.photos.getInfo&api_key=' + apiKey + '&photo_id=' + element_id + '&format=json&jsoncallback=?',
					function(data) {
						// console.log(data);
						// $("h1").html(data.photo.title._content);
						// $("#content-info p").html(data.photo.description._content);
				});
			} 
					
			// back and next keys =========================================================
  			$('body').keyup(function (event) {
				if (event.keyCode == 37) { $('.back').click(); }
				else if (event.keyCode == 39) { $('.next').click(); }
			});
			
			// back and next ==============================================================			
			$('.back').click(function() { // understand what image is current on display
				// if is the first one
				if ( $('#thumbnails a:first').hasClass('selected') ) {					
					// console.log($('#content-info dt.selected').next().next('dt').children('a'));
					var k = $('#content-info dt.selected').prev().prev('dt').children('a').attr('href');
					// console.log(k);
					if (k !== undefined) { window.location = k; }
				};

				// console.log($('#content img').attr('src'));
				var k = $('#content img').attr('src');
				$('#thumbnails a[href="'+ k +'"]').prev().click();
			});
			
			$('.next').click(function() { // understand what image is current on display				
				// if is the last one
				if ( $('#thumbnails a:last-child').hasClass('selected') ) {					
					// console.log($('#content-info dt.selected').next().next('dt').children('a'));
					var k = $('#content-info dt.selected').next().next('dt').children('a').attr('href');
					// console.log(k);
					if (k !== undefined) { window.location = k; }
				};				
				// console.log($('#content img').attr('src'));
				var k = $('#content img').attr('src');
				$('#thumbnails a[href="'+ k +'"]').next().click();
				
			});			
			
			
			// other ==============================================================
			// swap images
			$('#thumbnails a').live('click', function(event) {
				event.preventDefault();
				$(this).siblings().removeClass('selected');				
				$(this).addClass('selected');
				var selected	= $(this).attr('href');
				var element		= $('#content img');
				var element_id	= $(this).attr('class');
				
				// get image tags based on id
				get_tags(element_id);
				
				// console.log(element);
				element.fadeOut("normal", function(){				
					element.attr('src', selected).load(function() {
						element.fadeIn('slow');
					});
				});


				$(this).parent().find('img').css({ opacity: 1 });
				$(this).children().css({ opacity: 0.3 });				
			});

			// remove last span with pipe dividers
			$('ul.sub li:last-child span').hide();

            function display_sub_nav(element) {
        	    $('ul.sub').hide();
                $('ul.main li span').remove();
        			
        			$(element).addClass('selected');
        			$(element).parent().siblings().children('a').removeClass('selected');

                    var _this = element.html();
                    _this == 'about us' ? _this = 'about' : false;
                    $('ul.'+ _this +'').fadeIn();


              if ( _this == 'about') { 
                  $(element).parent().animate({ left: '240px' }, 900);
                  $(element).parent().siblings().not('.home').animate({ left: '154px' }, 900);                
                  $('<span> :</span>').appendTo($(element));
                  
                } else {
                  $(element).parent().animate({ left: '250px' }, 900);
                  $(element).parent().siblings().not('.home').animate({ left: '154px' }, 900);                                                
                  $('<span> :</span>').appendTo($(element));                  
                }  
                                  
            }
                        
			// display projects categories
			$("a:contains('projects')").click(function() {
			    display_sub_nav($(this));
			});			
			// display about us
			$("a:contains('about us')").click(function() {
			    display_sub_nav($(this));
			});						
			
			// toggle project categories
			$('.categories a').click(function() {								
				var category = $(this).text();
                $.cookie('the_category', category);
			});			
            
            // load category name
            // $('#content-info h2').html($.cookie("the_category"));
            
            // # prevent default
			$('a[href="#"]').click(function(event) {
				event.preventDefault();
			});
			
            // about us
            if ($('p.limit').length) {             	
                $('<span><a href="#">More</a></span>').appendTo($('#content-info'));            			
			    $('#content-info p.limit').addClass('off').nextAll('p').addClass('off');			    
    			$('#content-info span a').click(function(){
                    $('#content-info p').toggleClass('off');
                    if ( $(this).text() == 'More' ){
                        $(this).text('Back');
                    } else {
                        $(this).text('More');
                    }
    			});
            }		
						
});
