// JavaScript Document
(function ($) {
	
		if( typeof( fx_baseUrl ) == 'undefined' ) { window.fx_baseUrl=location.protocol+'//'+location.host+'/'; }  
		
		if( typeof( cache ) == 'undefined' ) { window.cache = []; }	 
		  // Arguments are image paths relative to the current page.
		  $.preLoadImages = function() {
			var args_len = arguments.length;
			for (var i = args_len; i--;) {
			  var cacheImage = document.createElement('img');
			  cacheImage.src = arguments[i];
			  cache.push(cacheImage);
			}
		  }

		
		$.extend({
		  fxShoppesProductsList : function(category,callbackFnk){
			  
			  
			  window.fx_shoppesProducts={};
			
			$.ajax({
				  dataType: 'jsonp',
				  data: 'currentDate='+currentDate,
				  url: 'http://api.personal-fx.com/shoppesproducts/'+apiKey+'/',
				  success: function (response) {
					 
						$.each(response, function(i, item) { 
				 
							fx_eventList[i]=item;
							
						});
						
					 if(typeof callbackFnk == 'function'){ callbackFnk.call(this); }
					
					},
				  error: function(){
							alert('There was an error processing your request');
					   }
			});
			
			
			
			}
		});
	
		$.fn.fxCalendar = function (params) {
			
			params = $.extend( {minlength: 0, maxlength: 99999}, params);
			
			var $obj = $(this);
			
			return this.each(function() {  
			
				if( typeof( fx_calendar ) == 'undefined' ) { window.fx_calendar={}; }
				
				if( typeof( fx_calDiv ) == 'undefined' ) { window.fx_calDiv=$obj; }
				
				$obj.fadeOut('fast');
				
				$.ajax({
				  dataType: 'jsonp',
				  url: 'http://api.personal-fx.com/calendar/'+apiKey+'/',
				  success: function (response) {
					 
						fx_calendar=response;
						
						$obj.html(fx_calendar.calendar);
						
						$obj.fadeIn('slow');
					
					},
				  error: function(){
							alert('There was an error processing your request');
					   }
				});
			
			});
		
		}
		
		$.extend({
		  fxEventList : function(currentDate, callbackFnk){
			  
			  window.fx_eventList={};
			
			$.ajax({
				  dataType: 'jsonp',
				  data: 'currentDate='+currentDate,
				  url: 'http://api.personal-fx.com/eventlist/'+apiKey+'/',
				  success: function (response) {
					 
						$.each(response, function(i, item) { 
				 
							fx_eventList[i]=item;
							
						});
						
					 if(typeof callbackFnk == 'function'){ callbackFnk.call(this); }
					
					},
				  error: function(){
							alert('There was an error processing your request');
					   }
			});
			
			
			
			}
		});
		
		$.extend({
		  fxAdd2Cart : function(skuId, callbackFnk){
			  
			  if( typeof( fx_cart ) == 'undefined' ) { window.fx_cart=[]; }
			  
			  if(!fx_cart[skuId]) { fx_cart[skuId]=0; }
			  
			  fx_cart[skuId]=fx_cart[skuId] + 1;
			  
			  var params='';
			 
			  
			  for(var index in fx_cart) {
				  
				  if(params!='') { params=params+'&'; }
				  
				 params=params+'item_'+index+'='+fx_cart[index]; 
			
				}
				
				$('#dynamic_page').data("content",{ "html_content": $('#dynamic_page').html() });
				
				$('#dynamic_page').html('loading...');
			
			$.ajax({
				  dataType: 'jsonp',
				  data: params,
				  url: 'http://api.personal-fx.com/cart/'+apiKey+'/',
				  success: function (response) {
					 
					$('#dynamic_page').html(response.html_content);
					
					$('#shopping_url').val(location.protocol+'//'+location.host+'/');
						
					 if(typeof callbackFnk == 'function'){ callbackFnk.call(this); }
					
					},
				  error: function(){
							alert('There was an error processing your request');
					   }
			});
			
			
			
			}
		});
		
		
		$.extend({ 
		
			pfxGetShoppesProduct : function(productId){
				
				$.ajax({
				  dataType: 'jsonp',
				  data: 'productId='+productId,
				  url: 'http://api.personal-fx.com/shoppesproduct/'+apiKey+'/'+productId,
				  success: function (response) {
					  
					  $('#shoppesWrapper').html(response.html_content);
					 
					},
				  error: function(){
							alert('There was an error processing your request');
					   }
				});
				
				
			}
		
		});
		
		
		
		$.extend({
		  fxEventDetail : function(eid, callbackFnk){
			  
			  window.fx_eventList={};
			
			$.ajax({
				  dataType: 'jsonp',
				  data: 'eid='+eid,
				  url: 'http://api.personal-fx.com/eventdetail/'+apiKey+'/',
				  success: function (response) {
					  
					  fx_eventDetail=response;
					 
					  if(typeof callbackFnk == 'function'){ callbackFnk.call(this); }
					
					},
				  error: function(){
							alert('There was an error processing your request');
					   }
			});
			
			
			
			}
		});
		
		
		
		$.fn.fxShareToggle = function(form){
			
			var $obj = $(this);
			
			
			
			
			// $.fxShareSiteInfo();
		/* start: open Flickr Photostream */
			$($obj).toggle(function(){
				
				if(form) {
					
					$('#hiddenShareForm').clearForm();
					$('#shareCaption').val('{*actor*} Thought you\'d like this site'); 
					$('#shareDesc').val($('#'+form+'_description').val());
					$('#shareTitle').val($('#'+form+'_title').val());
					$('#shareActionText').val($('#'+form+'_text').val());
					$('#shareImage').val($('#'+form+'_image').val());
					$('#shareSwfSrc').val($('#'+form+'_swfSrc').val());
					$('#shareImageLink').val($('#'+form+'_iLink').val());
					$('#shareActionLink').val($('#'+form+'_aLink').val());
					$('#shareEntryLink').val($('#'+form+'_eLink').val());
				}
			
					$().fxShare();
				
				},function(){
				
				$('#photobar').stop().animate({'bottom':'-96px'},200,function(){
					$('#images').css('bottom','-125px');
				});
			
			});
			
			
			
		}
		
		$.fn.fxShare = function (response){
    
	
			var $obj = $(this);
			
			if($('#shareTitle').val()=='') { $.fxShareSiteInfo(); }
			
			if(!response) { FB.getLoginStatus($($obj).fxShare); return; }
			
			if(!response.session) { 
			
			  FB.login(function(response) {
			  
				if (response.session) {
				  
				  $('#photobar').stop().animate({'bottom':'0px'},200,function(){
						if($friendsContainer.is(':empty')){
							/*
							if friends not loaded, load them
							*/
							LoadFriends();
						}
					});
				
				} else {
				// user cancelled login
				}
			
			  });
			
			
			} else {
			
			  $('#photobar').stop().animate({'bottom':'0px'},200,function(){
					if($friendsContainer.is(':empty')){
						/*
						if friends not loaded, load them
						*/
						LoadFriends();
					}
				});
			
			}
		  }	
		  
		$('#shareSite').fxShareToggle();
		
		$.refreshCalendar = function (calendar) {
			
				var $obj=fx_calDiv;
			
				$($obj).fadeOut('fast');
				
				$.ajax({
				  dataType: 'jsonp',
				  data: 'calendar='+calendar,
				  url: 'http://api.personal-fx.com/calendar/'+apiKey+'/',
				  success: function (response) {
					 
						fx_calendar=response;
						
						$obj.html(fx_calendar.calendar);
						
						$obj.fadeIn('slow');
					
					},
				  error: function(){
							alert('There was an error processing your request');
					   }
			});
		
		}
		
		$.extend({
		  initService : function(service, callbackFnk, target){
			
			if(target) { if( typeof( fx_target ) == 'undefined' ) { window.fx_target=target; } }
			
			if( typeof( fx_videos ) == 'undefined' ) { window.fx_videos={}; }
			
			if( typeof( fx_twitter ) == 'undefined' ) { window.fx_twitter={}; }
			
			if( typeof( fx_webmenuitems ) == 'undefined' ) { window.fx_webmenuitems={}; }
			
			if( typeof( fx_shoppescategory ) == 'undefined' ) { window.fx_shoppescategory={}; }
			
			
			
			$.ajax({
			  dataType: 'jsonp',
			  url: 'http://api.personal-fx.com/'+service+'/'+apiKey+'/',
			  success: function (response) {
				 
				 $.each(response, function(i, item) { 
				 
					switch(service) {
					
						case "videos":
						
							fx_videos[i]=item;
							
						break;
						
						case "twitter":
						
							fx_twitter[i]=item;
							
						break;
						
						case "webmenuitems":
						
							fx_webmenuitems[i]=item;
							
						break;
						
						case "shoppescategory":
						
							fx_shoppescategory[i]=item;
							
						break;
						
						
						
					}
				 
				 });
				 
				 
				 if(typeof callbackFnk == 'function'){ callbackFnk.call(this); }
				 
	
				},
			  error: function(){
						alert('There was an error processing your request');
				   }
			});
			
			
			
			}
		});
		
		$.extend({
		  getPage : function(pageId, callbackFnk){
			
			$('#'+fx_target).html("Loading...");
			
			if(pageId=='default') {
				
					if($.getUrlVar('page')>0) { pageId=($.getUrlVar('page')); }
				
				}
			
			$.ajax({
			  dataType: 'jsonp',
			  url: 'http://api.personal-fx.com/page/'+apiKey+':::'+pageId+'/',
			  
			  success: function (response) {
				  
				  $('#'+fx_target).html(response.html_content);
				  
				  $('#'+fx_target+' ul.tabs').tabs("div.panes > div");
				  
				  var formId;
				  
				  $('#'+fx_target+' .shareButton').each( function(i){ 
				  
				  		formId=this.id.split('_');
						
						$(this).fxShareToggle(formId[0]+'_'+formId[1]); 
						
				   });
				   var scrollAllow = true;
				   
				   $('#videos').find('.next').bind('click',function(e) {
						var target_id = $(e.target).parent().attr('id');
						
						var $theContainer   = $('#videos').find('ul');
							
						if(scrollAllow){
							scrollAllow		= false;
							spacefit 		= $('#videos').width() -44;
							fit 			= Math.floor(spacefit / 85);
							var left 		= parseFloat($theContainer.css('left'),10);
							var moveleft 	= left - (fit*85);
							if(ul_width - Math.abs(left) < $('#videos').width()){ 
								scrollAllow = true;
								e.preventDefault();
								return;
							}
							$theContainer.animate({'left':moveleft+'px'},1000,function(){
								scrollAllow = true;
								
							});
							e.preventDefault();
						}
					});
				   
				   
				   $('#videos').find('.prev').bind('click',function(e) {
					   
					  
						var target_id = $(e.target).parent().attr('id');
						
						var $theContainer   = $('#videos').find('ul');
							
						if(scrollAllow){
							scrollAllow		= false;
							spacefit 		= $('#videos').width() -44;
							fit 			= Math.floor(spacefit / 85);
							var left = parseFloat($theContainer.css('left'),10);
							var moveleft = left + (fit*85);
							if(left >= 0){ 
								scrollAllow = true;
								e.preventDefault();
								return;
							}
							$theContainer.animate({'left':moveleft+'px'},1000,function(){
								scrollAllow = true;
							});
							e.preventDefault();
							
							
						}
					});
				   
				   if(response.script_content!='') {  $('#'+fx_target).append('<div style="display:none;"><script>'+response.script_content+'</script></div>'); }
				  
				 if(typeof callbackFnk == 'function'){ callbackFnk.call(this); }
				 
				},
			  error: function(){
						alert('There was an error processing your request');
				   }
			});
			
			
			
			}
		});
		
		$.extend({
		  getPageManual : function(pageId, fx_target, callbackFnk){
			
			$('#'+fx_target).html("Loading...");
			
			$.ajax({
			  dataType: 'jsonp',
			  url: 'http://api.personal-fx.com/page/'+apiKey+':::'+pageId+'/',
			  
			  success: function (response) {
				  
				  $('#'+fx_target).html(response.html_content);
				  
				   $('#'+fx_target+' ul.tabs').tabs("div.panes > div");
				  
				 if(typeof callbackFnk == 'function'){ callbackFnk.call(this); }
				 
				},
			  error: function(){
						alert('There was an error processing your request');
				   }
			});
			
			
			
			}
		});
		
		$.extend({
		  fxShowVideo : function(video, fx_target, callbackFnk){
			
			
			$('#prodMedia').html('<object width="500" height="350" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,32,18"><param value="true" name="allowFullScreen"><param value="always" name="allowscriptaccess"><param value="'+$(video).attr('rel')+'" name="src"><embed width="500" height="350" type="application/x-shockwave-flash" src="'+$(video).attr('rel')+'" allowscriptaccess="always" allowfullscreen="true" /></object>');
			
			
			
			}
		});
		
		
		$.extend({
		  initFacebook : function(apiKey, callbackFnk, callbackFnk2){
			
			if( typeof( showFriendSelector ) == 'undefined' ) { window.showFriendSelector=0; }
			
			$('#fb-root').remove();
			
			$('body').append('<div id="fb-root"></div>');
			
			$('body').append('<div id="hiddenShare" style="display:none;"><form id="hiddenShareForm" onSubmit="return false;">'
			
			+'<input type="hidden" id="shareActionText" name="shareActionText" value="" />'
			
			+'<input type="hidden" id="shareDesc" name="shareDesc" value="" />'
			
			+' <input type="hidden" id="shareImage" name="shareImage" value="" />'
			
			+'<input type="hidden" id="shareTitle" name="shareTitle" value="" />'
			
			+'<input type="hidden" id="shareImageLink" name="shareImageLink" value="" />'
			
			+' <input type="hidden" id="shareActionLink" name="shareActionLink" value="" />'
			
			+'<input type="hidden" id="shareEntryLink" name="shareEntryLink" value="" />'
			
			+'<input type="hidden" id="shareCaption" name="shareCaption" value="" />'
			
			+'<input type="hidden" id="shareSwfSrc" name="shareSwfSrc" value="" />'
			
			+' <input type="hidden" id="shareSwfHeight" name="shareSwfHeight" value="" />'
			
			+'<input type="hidden" id="shareSwfWidth" name="shareSwfWidth" value="" />'
			
			+'</form></div>');
			
			if(typeof callbackFnk == 'function'){ callbackFnk.call(this); }
			
			window.fbAsyncInit = function() { 
			
				FB.init({appId: apiKey, status: true, cookie: true, xfbml: true }); 
				
			if(typeof callbackFnk2 == 'function'){ callbackFnk2.call(this); }
				
				 
				
			};
			  
			  (function() {
				var e = document.createElement('script'); 
				e.async = true;
				e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
				document.getElementById('fb-root').appendChild(e);
			  }());
			  
			
			
		  }
		});
		
		$.fn.clearForm = function() {
		  return this.each(function() {
		 var type = this.type, tag = this.tagName.toLowerCase();
		 if (tag == 'form')
		   return $(':input',this).clearForm();
		 if (type == 'text' || type == 'password' || tag == 'textarea' || type == 'hidden')
		   this.value = '';
		 else if (type == 'checkbox' || type == 'radio')
		   this.checked = false;
		 else if (tag == 'select')
		   this.selectedIndex = 0;
		  });
		};
		
		$.trim = function (strng) {
			return strng.replace(/^\s+|\s+$/g,"");
		}
		
		Object.size = function(obj) {
			var size = 0, key;
			for (key in obj) {
				if (obj.hasOwnProperty(key)) size++;
			}
			return size;
		};

		
		$.extend({
		  getUrlVars: function(){
			var vars = [], hash;
			var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
			for(var i = 0; i < hashes.length; i++)
			{
			  hash = hashes[i].split('=');
			  vars.push(hash[0]);
			  vars[hash[0]] = hash[1];
			}
			return vars;
		  },
		  getUrlVar: function(name){
			return $.getUrlVars()[name];
		  }
		});
		
		
		
		
		$.fxShareIt = function (targetUser){
		
			if($('#friend_'+targetUser).hasClass('selected')){ return; }
	
			$('#friend_'+targetUser).addClass('selected');
			
			var a_name=$('#shareTitle').val();
			var a_text=$('#shareActionText').val();
			var a_caption=$('#shareCaption').val();
			var a_desc=$('#shareDesc').val();
			var a_img=$('#shareImage').val();
			var a_swfsrc=$('#shareSwfSrc').val();
			var a_swfheight=$('#shareSwfHeight').val();
			var a_swfwidth=$('#shareSwfWidth').val();
			
			if (a_swfheight=='') { a_swfheight='300'; }
			if (a_swfwidth=='') { a_swfwidth='350'; }
			
			var a_imglink=$('#shareImageLink').val();
			var a_link=$('#shareActionLink').val();
			var a_entrylink=$('#shareEntryLink').val();
			
			if(a_swfsrc!=''){ 
			
				FB.ui(
				   {
					 method: 'stream.publish',
					 target_id : targetUser,
					 attachment: {
					   name: a_text,
					   caption: a_caption,
					   description: ( a_desc ),
					   href: a_link,
					   'media':[{'type': 'flash', 'swfsrc': a_swfsrc, 'imgsrc': a_img, 'width': '90', 'height': '90', 'expanded_width': a_swfwidth, 'expanded_height': a_swfheight }]
					 },
					 action_links:  [{ "text": a_text, "href": a_link}],
					 
					 display:'popup',
					 
					 user_prompt_message: 'Share your thoughts'
				   },
				   function(response) {
					 if (response && response.post_id) {
					   alert('Post was published.');
					 } else {
					   $('#friend_'+targetUser).removeClass('selected');
					 }
				   }
				 );
				 
			}else { 
			
				FB.ui(
				   {
					 method: 'stream.publish',
					 target_id : targetUser,
					 attachment: {
					   name: a_text,
					   caption: a_caption,
					   description: ( a_desc ),
					   href: a_link,
					   'media':[{'type':'image','src':a_img,'href':a_imglink}] 
					 },
					 action_links:  [{ "text": a_text, "href": a_link}],
					 
					 display:'popup',
					 
					 user_prompt_message: 'Share your thoughts'
				   },
				   function(response) {
					 if (response && response.post_id) {
					   alert('Post was published.');
					 } else {
					   $('#friend_'+targetUser).removeClass('selected');
					 }
				   }
				 );
			
			}
			
		}
		
		$.fn.fxFriendSelector = function (response){
			
			if (!response) { var response='Publish this to your profile or with your friends.'; } 
			
			var $obj = $(this);
		
			var friends=$('#myFriends').html();
				
			$($obj).html('<h2>'+response+'</h2><div id="friendselector"><div id="multi_friend_selector"><div  id="multi_friend_selector_wrapper">'+friends+'</div><div class="rButton"></div></div></div>');
			
		}
		
			
		$.fxGetFriends = function(callback) {
			
			$('#myFriends').remove();
			
			
			
			FB.api(
				  {
					method: 'fql.query',
					
					query: 'SELECT first_name,last_name,uid,pic_square FROM user WHERE uid = '+FB.getSession().uid+' or uid IN ( SELECT uid2 FROM friend WHERE uid1 = '+FB.getSession().uid+' )'
					
				  },
				  function(response) {
					
					$('body').append('<div id="myFriends" style="display:none;"></div>');
					
					$.each(response,function(name, value) { 
					
						if(value.pic_square==null) { value.pic_square="http://i849.photobucket.com/albums/ab58/personal-fx/globalresources/unknown-user.gif"; }
											  
						 $('#myFriends').append('<div><a href="#" onclick="$.fxShareIt('+value.uid+');return false;" id="friend_'+value.uid+'"><span class="square" style="background-image:url('+value.pic_square+')"><span></span></span><strong>'+value.first_name+'<br>'+value.last_name+'</strong></a></div>');
						  
						});
						
					if(typeof callback == 'function'){ callback.call(this); }
						
				});
		
		}
		
		$.fxShareSiteInfo= function () { 
		
			$('#hiddenShareForm').clearForm();
			
			$('#shareCaption').val('{*actor*} Thought you\'d like this site'); 

			var propVal=null;

			 window.fx_elements=$('meta').each(function(){   
			 
			 	propVal=$(this).attr('property');
			 	
				switch(propVal){
					
					case 'og:description':
					
						$('#shareDesc').val($(this).attr('content'));
					
					break;
					
					case 'og:title':
					
						$('#shareTitle').val($(this).attr('content'));
						$('#shareActionText').val($(this).attr('content'));
					
					break;
					
					case 'og:image':
					
						$('#shareImage').val($(this).attr('content'));
						
					break;
					
					case 'og:url':
					
						$('#shareImageLink').val($(this).attr('content'));
						$('#shareActionLink').val($(this).attr('content'));
						$('#shareEntryLink').val($(this).attr('content'));
						
					break;
				
				}
			 
			 });
			 
			
		} 
		/*
 * Viewport - jQuery selectors for finding elements in viewport
 *
 * Copyright (c) 2008-2009 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *  http://www.appelsiini.net/projects/viewport
 *
 */
	
	 $.belowthefold = function(element, settings) {
        var fold = $(window).height() + $(window).scrollTop();
        return fold <= $(element).offset().top - settings.threshold;
    };

    $.abovethetop = function(element, settings) {
        var top = $(window).scrollTop();
        return top >= $(element).offset().top + $(element).height() - settings.threshold;
    };
    
    $.rightofscreen = function(element, settings) {
        var fold = $(window).width() + $(window).scrollLeft();
        return fold <= $(element).offset().left - settings.threshold;
    };
    
    $.leftofscreen = function(element, settings) {
        var left = $(window).scrollLeft();
        return left >= $(element).offset().left + $(element).width() - settings.threshold;
    };
    
    $.inviewport = function(element, settings) {
		return !$.rightofscreen(element, settings) && !$.leftofscreen(element, settings) && !$.belowthefold(element, settings) && !$.abovethetop(element, settings);
    };
    
    $.extend($.expr[':'], {
        "below-the-fold": function(a, i, m) {
            return $.belowthefold(a, {threshold : 0});
        },
        "above-the-top": function(a, i, m) {
            return $.abovethetop(a, {threshold : 0});
        },
        "left-of-screen": function(a, i, m) {
            return $.leftofscreen(a, {threshold : 0});
        },
        "right-of-screen": function(a, i, m) {
            return $.rightofscreen(a, {threshold : 0});
        },
        "in-viewport": function(a, i, m) {
			return $.inviewport(a, {threshold : 0});
        }
    });	

var api_key 			= '96cb831abdd3e122354be4f414c96fe4';
	var user_id  			= '8381313@N08';
	
	/*
	use:
	Square,Thumbnail,Small,Medium or Original for the large image size you want to load!
	*/
	var large_image_size 	= 'Medium';
	/*
	the current Set id / the current Photo id
	*/
	var photo_set_id,photo_id;
	var current	= -1;
	var continueNavigation = false;
	/*
	flickr API Call to get List of Sets
	*/
	var sets_service 		= 'http://api.flickr.com/services/rest/?&method=flickr.photosets.getList' + '&api_key=' + api_key;
	var sets_url			= sets_service + '&user_id=' + user_id + '&format=json&jsoncallback=?';
	/*
	flickr API Call to get List of Photos from a Set
	*/
	var photos_service 		= 'http://api.flickr.com/services/rest/?&method=flickr.photosets.getPhotos' + '&api_key=' + api_key;
	/*
	flickr API Call to get List of Sizes of a Photo
	*/
	var large_photo_service = 'http://api.flickr.com/services/rest/?&method=flickr.photos.getSizes' + '&api_key=' + api_key;
	/* 
	elements caching... 
	*/
	var $setsContainer 		= $('#sets').find('ul');
	var $photosContainer 	= $('#images').find('ul');
	var $friendsContainer   = $('#fbfriends').find('ul');
	
	var $photopreview		= $('#flickr_photopreview');
	var $flickrOverlay		= $('#flickr_overlay');
	var $loadingStatus		= $('#shareSite').find('.loading_small');
	
	var ul_width,spacefit,fit;


	
	/* start: open Flickr Photostream */
	$('#photosButton').toggle(function(){
		$('#photobar').stop().animate({'bottom':'0px'},200,function(){
			if($setsContainer.is(':empty')){
				/*
				if sets not loaded, load them
				*/
				LoadSets();
			}
		});
	},function(){
		/*
		minimize the main bar, and minimize the photos bar.
		next time we maximize, the view will be on the sets
		*/
		$('#photobar').stop().animate({'bottom':'-96px'},200,function(){
			$('#images').css('bottom','-125px');
		});
	});
	
	/*
	Load Friends
	*/
	function LoadFriends(){
		var fbfriends=[];
		$loadingStatus.css('visibility','visible');
		FB.api(
				  {
					method: 'fql.query',
					
					query: 'SELECT first_name,last_name,uid,pic_square FROM user WHERE uid = '+FB.getSession().uid+' or uid IN ( SELECT uid2 FROM friend WHERE uid1 = '+FB.getSession().uid+' )'
					
				  },
				  function(response) {
					
					var friends_count = response.length;
					/*
					adapt ul width based on number of results
					*/
					ul_width = friends_count * 85 + 85;
					
					$friendsContainer.css('width',ul_width + 'px');
					
					$.each(response,function(name, value) { 
					
						if(value.uid>0) {
					
							if(value.pic_square==null) { value.pic_square="http://i849.photobucket.com/albums/ab58/personal-fx/globalresources/unknown-user.gif"; }
							
							var photoUrl		= value.pic_square;
							
							var $elem 			= $('<li />');
							var $link 			= $('<a class="toLoad" href="#" onclick="$.fxShareIt('+value.uid+');return false;" />');
							/*
							save the info of the set in the li element,
							we will use it later	
							*/
							$link.data({
								
								'photoUrl'	:photoUrl,
								'friendName' :value.first_name + ' ' + value.last_name,
								'id'		:value.uid
							});
						
							$friendsContainer.append($elem.append($link));
							$link.bind('click',function(e){
								var $this = $(this);
								/*
								save the current Set id in the photo_set_id variable
								and load the photos of that Set
								*/
								
								
								e.preventDefault();
							});
						
						}
				
					});
					
					LoadFriendImages();	
				});
		
		
	
	}
	/*
	loads the images of the sets that are in the viewport
	*/
	function LoadFriendImages(){
		var toLoad = $('.toLoad:in-viewport').size();
		
		if(toLoad > 0)
			$loadingStatus.css('visibility','visible');
			
		var images_loaded 	= 0;
		var x=0;
		$('.toLoad:in-viewport').each(function(i){
			++images_loaded;
				if(images_loaded == toLoad){
					$loadingStatus.css('visibility','hidden');
					$friendsContainer.find('img').fadeIn();
				}	
			++x;
			var $space = $(this);
			
			var $img = $('<img style="display:none;" />').attr('src',$space.data('photoUrl')).attr('alt',$space.data('id')).css('width',75).css('height',75);
			
			var $friend_name		= $('<span />',{'html':$space.data('friendName')});
			
			$(this).append($friend_name).append($img).removeClass('toLoad');
			
		});
		
	}
	/*
	Loads the User Photo Sets
	*/
	function LoadSets(){
		$loadingStatus.css('visibility','visible');
		
		$.getJSON(sets_url,function(data){
			if(data.stat != 'fail') {
				var sets_count = data.photosets.photoset.length;
				/*
				adapt ul width based on number of results
				*/
				ul_width = sets_count * 85 + 85;
				$setsContainer.css('width',ul_width + 'px');
				
				for(var i = 0; i < sets_count; ++i){
					var photoset		= data.photosets.photoset[i];
					var primary 		= photoset.primary;
					var secret			= photoset.secret;
					var server			= photoset.server;
					var farm			= photoset.farm;
					/*
					source for the small thumbnail
					*/
					var photoUrl		= 'http://farm'+farm+'.static.flickr.com/'+server+'/'+primary+'_'+secret+'_s.jpg';
					var $elem 			= $('<li />');
					var $link 			= $('<a class="toLoad" href="#" />');
					/*
					save the info of the set in the li element,
					we will use it later	
					*/
					$link.data({
						'primary'	:primary,
						'secret'	:secret,
						'server'	:server,
						'farm'		:farm,
						'photoUrl'	:photoUrl,
						'setName'	:photoset.title._content,
						'id'		:photoset.id
					});
					
					$setsContainer.append($elem.append($link));
					$link.bind('click',function(e){
						var $this = $(this);
						/*
						save the current Set id in the photo_set_id variable
						and load the photos of that Set
						*/
						$('#images').stop().animate({'bottom':'0px'},200);
						if(photo_set_id!=$this.data('id')){
							photo_set_id = $this.data('id');
							$('#setName').html($this.data('setName'));
							LoadPhotos();
						}
						e.preventDefault();
					});
				}
				/*
				now we load the images 
				(the ones in the viewport)
				*/
				LoadSetsImages();
			}
		});	
	}
	
	/*
	loads the images of the sets that are in the viewport
	*/
	function LoadSetsImages(){
		var toLoad 			= $('.toLoad:in-viewport').size();
		if(toLoad > 0)
			$loadingStatus.css('visibility','visible');
		var images_loaded 	= 0;
		$('.toLoad:in-viewport').each(function(i){
			var $space			= $setsContainer.find('.toLoad:first');
			var $img 			= $('<img style="display:none;" />').load(function(){
				++images_loaded;
				if(images_loaded == toLoad){
					$loadingStatus.css('visibility','hidden');
					$setsContainer.find('img').fadeIn();
				}	
			}).error(function(){
				//TODO
				++images_loaded;
				if(images_loaded == toLoad){
					$loadingStatus.css('visibility','hidden');
					$setsContainer.find('img').fadeIn();
				}	
			}).attr('src',$space.data('photoUrl')).attr('alt',$space.data('id'));
			var $set_name		= $('<span />',{'html':$space.data('setName')});
			$space.append($set_name).append($img).removeClass('toLoad');
		});
	}
	
	/*
	Loads the Set's Photos
	*/
	function LoadPhotos(){
		$photosContainer.empty();
		$loadingStatus.css('visibility','visible');
		var photos_url	= photos_service + '&photoset_id=' + photo_set_id + '&media=photos&format=json&jsoncallback=?';
		
		$.getJSON(photos_url,function(data){
			if(data.stat != 'fail') {
				var photo_count = data.photoset.photo.length;
				/*
				adapt ul width based on number of results
				*/
				var photo_count_total = photo_count + $photosContainer.children('li').length;
				ul_width = photo_count_total * 85 + 85;
				$photosContainer.css('width',ul_width + 'px');
				
				for(var i = 0; i < photo_count; ++i){	
					var photo			= data.photoset.photo[i];
					var photoid			= photo.id;
					
					var secret			= photo.secret;
					var server			= photo.server;
					var farm			= photo.farm;
					
					var photoUrl		= 'http://farm'+farm+'.static.flickr.com/'+server+'/'+photoid+'_'+secret+'_s.jpg';
					
					var $elem 			= $('<li />');
					var $link 			= $('<a class="toLoad" href="#" />');
					
					$link.data({
						'photoid'		:photoid,
						'secret'		:secret,
						'server'		:server,
						'farm'			:farm,
						'photoUrl'		:photoUrl,
						'photo_title'	:photo.title
					});
					$photosContainer.append($elem.append($link));
					
					$link.bind('click',function(e){
						var $this	= $(this);
						current		= $this.parent().index();
						photo_id 	= $this.data('photoid');
						LoadLargePhoto();
						e.preventDefault();
					});
				}
				LoadPhotosImages();
			}
			
		});
	}
	
	/*
	loads the images of the set's 
	photos that are in the viewport
	*/
	function LoadPhotosImages(){
		var toLoad 			= $('.toLoad:in-viewport').size();
		if(toLoad > 0)
			$loadingStatus.css('visibility','visible');
		var images_loaded 	= 0;
		
		$('.toLoad:in-viewport').each(function(i){
			var $space			= $photosContainer.find('.toLoad:first');
			var $img 			= $('<img style="display:none;" />').load(function(){
				++images_loaded;
				if(images_loaded == toLoad){
					$loadingStatus.css('visibility','hidden');
					$photosContainer.find('img').fadeIn();
					/*
					if we were navigating through the large images set:
					*/
					if(continueNavigation){
						continueNavigation 	= false;
						var $thumb 			= $photosContainer.find('li:nth-child(' + parseInt(current + 1) + ')').find('img');
						photo_id 			= $thumb.attr('alt');
						LoadLargePhoto();
					}
				}	
			}).error(function(){
				//TODO
				++images_loaded;
				if(images_loaded == toLoad){
					$loadingStatus.css('visibility','hidden');
					$photosContainer.find('img').fadeIn();
					/*
					if we were navigating through the large images set:
					*/
					if(continueNavigation){
						continueNavigation 	= false;
						var $thumb 			= $photosContainer.find('li:nth-child(' + parseInt(current + 1) + ')').find('img');
						photo_id 			= $thumb.attr('alt');
						LoadLargePhoto();
					}
				}				
			}).attr('src',$space.data('photoUrl'))
			  .attr('alt',$space.data('photoid'));
			
			var $photo_title	= $('<span/>',{'html':$space.data('photo_title')});
			$space.append($photo_title).append($img).removeClass('toLoad');
		});
	}
	
	/*
	loads the main image
	*/
	function LoadLargePhoto(){
		removeLargeImage();
		
		var $theThumb 	= $photosContainer.find('li:nth-child(' + parseInt(current + 1) + ')').find('img');
		var photo_title = $theThumb.parent().data('photo_title');
		
		var $loading	= $photopreview.find('.loading');
		$loading.show();
		$photopreview.show();
		$flickrOverlay.show();
		$('#preview_close').show();
		
		var large_photo_url = large_photo_service + '&photo_id=' + photo_id + '&format=json&jsoncallback=?';
		$.getJSON(large_photo_url,function(data){
			if(data.stat != 'fail') {
				var count_sizes 		= data.sizes.size.length;
				var largest_photo_src;
				for(var i = 0; i < count_sizes; ++i){
					if(data.sizes.size[i].label == large_image_size)
						largest_photo_src 	= data.sizes.size[i].source;
				}
				$('<img />').load(function(){
					var $this = $(this);
					/*
					resize the image to fit in the browser's window
					*/
					resize($this);
					
					$loading.hide();
					/*just to make sure theres no image:*/
					removeLargeImage();
					$photopreview.find('.preview').append($this);
					$('#large_phototitle').empty().html(photo_title);						
				}).attr('src',largest_photo_src);
			}
		});
	}
	
	/*
	close the Large Image View
	*/
	$('#preview_close').bind('click',function(){
		$photopreview.hide();
		$flickrOverlay.hide();
		$('#preview_close').hide();
		$('#large_phototitle').empty()
		removeLargeImage();
	});
	
	/*
	removes the large image from the DOM
	*/
	function removeLargeImage(){
		$photopreview.find('img').remove();
	}
	
	/*
	events to navigate through the Large Images
	*/
	$('#preview_img_next').bind('click',function(e){
		/*
		get the next one
		*/
		++current;
		
		var $link 	= $photosContainer.find('li:nth-child(' + parseInt(current + 1) + ')');
		var $thumb 	= $link.find('img');
		
		/* 
		if the next image is not loaded, 
		we need to scroll the photos container 
		and just then continue with the navigation
		*/
		if(!$thumb.length && $link.length){
			continueNavigation = true;
			removeLargeImage();
			$photopreview.find('.loading').show();
			$('#images').find('.next').trigger('click');
		}
		else if(!$thumb.length && !$link.length){
			--current;
			return;
		}	
		else{	
			photo_id 	= $thumb.attr('alt');
			LoadLargePhoto();
		}	
		e.preventDefault();
	});
	$('#preview_img_prev').bind('click',function(e){
		/*
		get the previous one
		*/
		var $link 	= $photosContainer.find('li:nth-child(' + parseInt(current) + ')');
		--current;
		var $thumb 	= $link.find('img');
		
		/* 
		if the previous image is not in the viewport, 
		we need to scroll the photos container 
		and just then continue with the navigation
		*/
		if(!$thumb.length && !$link.length){
			++current;
			return;
		}
		if(!$thumb.is(':in-viewport') && $link.length){
			$('#images').find('.prev').trigger('click');
		}						
		photo_id 	= $thumb.attr('alt');
		LoadLargePhoto();	
		e.preventDefault();
	});
	
	/*
	events to navigate through the sets / photos containers
	*/
	var scrollAllow = true;
	$('#sets,#images,#fbfriends').find('.next').bind('click',function(e) {
		var target_id = $(e.target).parent().attr('id');
		
		var $theContainer;
		if(target_id == 'sets') {
			$theContainer = $setsContainer; }
		else if(target_id == 'images') {
			$theContainer = $photosContainer; } else if(target_id=='fbfriends') { $theContainer=$friendsContainer }
			
		if(scrollAllow){
			scrollAllow		= false;
			spacefit 		= $(window).width() -44;
			fit 			= Math.floor(spacefit / 85);
			var left 		= parseFloat($theContainer.css('left'),10);
			var moveleft 	= left - (fit*85);
			if(ul_width - Math.abs(left) < $(window).width()){ 
				scrollAllow = true;
				e.preventDefault();
				return;
			}
			$theContainer.animate({'left':moveleft+'px'},1000,function(){
				scrollAllow = true;
				if(target_id == 'sets') {
					LoadSetsImages(); }
				else if(target_id == 'images') {
					LoadPhotosImages(); }  else if(target_id=='fbfriends') { LoadFriends(); }
			});
			e.preventDefault();
		}
	});
	$('#sets,#images,#fbfriends').find('.prev').bind('click',function(e) {
		var target_id = $(e.target).parent().attr('id');
		
		var $theContainer;
		if(target_id == 'sets') {
			$theContainer = $setsContainer; }
		else if(target_id == 'images') {
			$theContainer = $photosContainer; } else if(target_id=='fbfriends') { $theContainer=$friendsContainer }
			
		if(scrollAllow){
			scrollAllow		= false;
			spacefit 		= $(window).width() -44;
			fit 			= Math.floor(spacefit / 85);
			var left = parseFloat($theContainer.css('left'),10);
			var moveleft = left + (fit*85);
			if(left >= 0){ 
				scrollAllow = true;
				e.preventDefault();
				return;
			}
			$theContainer.animate({'left':moveleft+'px'},1000,function(){
				scrollAllow = true;
			});
			e.preventDefault();
		}
	});
	
	/*
	when cliking "Back to Sets"
	minimize photos bar
	*/
	$('#images_toggle').bind('click',function(){
		$('#images').stop().animate({'bottom':'-125px'},200);
	});	
	
	/*
	when resizing the window, resize the main image
	*/
	$(window).bind('resize', function() {
		var $theLargeImage = $photopreview.find('img');
		if($theLargeImage.length)
			resize($theLargeImage);
	});	
	
	/*
	resizes the main image based on the windows sizes
	*/		
	function resize($image){
		var widthMargin		= 10
		var heightMargin 	= 60;
		var windowH      = $(window).height()-heightMargin;
		var windowW      = $(window).width()-widthMargin;
		$photopreview.find('.preview').css({'width':$(window).width()+'px','height':($(window).height()-25)+'px'});
		var theImage     = new Image();
		theImage.src     = $image.attr("src");
		var imgwidth     = theImage.width;
		var imgheight    = theImage.height;

		if((imgwidth > windowW)||(imgheight > windowH)){
			if(imgwidth > imgheight){
				var newwidth 	= windowW;
				var ratio 		= imgwidth / windowW;
				var newheight	= imgheight / ratio;
				theImage.height = newheight;
				theImage.width	= newwidth;
				if(newheight>windowH){
					var newnewheight= windowH;
					var newratio 	= newheight/windowH;
					var newnewwidth = newwidth/newratio;
					theImage.width 	= newnewwidth;
					theImage.height	= newnewheight;
				}
			}
			else{
				var newheight = windowH;
				var ratio = imgheight / windowH;
				var newwidth = imgwidth / ratio;
				theImage.height = newheight;
				theImage.width= newwidth;
				if(newwidth>windowW){
					var newnewwidth = windowW;
					var newratio = newwidth/windowW;
					var newnewheight =newheight/newratio;
					theImage.height = newnewheight;
					theImage.width= newnewwidth;
				}
			}
		}
		$image.css({'width':theImage.width+'px','height':theImage.height+'px'});
	}

		
	})(jQuery);	
	
	

