var app={};

app.regExp={
	'classSearchPattern':'(^|[ ])(%s)($|[ ])'
};

/**
* Appel la methode en param si le scroll a atteint le bas de page
*/
app.isWindowBottom=function(fn){
	$(document).ready(function(){
		$(window).scroll(function(){
			if($(window).scrollTop() >= ($(document).height() - $(window).height())-180){
				fn();
			}
		});
	});
}

// conf du scrolling loading
app.isLastAlbum=false;
app.currentAlbumPage=1;
app.isLoading=false;
app.pagePattern='';
app.stopLoading=false;

/**
* gestion de l'ajout des pages de photos
*/
app.albumExplorer=function(hash,maxPage){
	if(!app.isLastAlbum && !app.isLoading && !app.stopLoading){
		app.currentAlbumPage++;
		if(maxPage==app.currentAlbumPage){
			app.isLastAlbum=true;
		}
		$('#loading').show();
		app.isLoading=true;
		$.ajax({
			url:'/ajax.php',
			type:'POST',
			data:({0:'explorer',1:hash,2:app.currentAlbumPage}),
			success:function(msg){
				app.isLoading=false;
				$('#loading').hide();
				if(msg==''){
					app.isLastAlbum=true;
				}else{
					var pattern=app.sprintf(app.pagePattern,app.currentAlbumPage);
					$('#albumPictures').append(pattern+msg);
					app.initFancyGallery();
				}
			}			
		});
	}
}

/**
* gestion de l'ajout des albums public
*/
app.nextPublicAlbums=function(maxPage){
	if(!app.isLastAlbum && !app.isLoading){
		app.currentAlbumPage++;
		if(maxPage==app.currentAlbumPage){
			app.isLastAlbum=true;
		}
		$('#loading').show();
		app.isLoading=true;
		$.ajax({
			url:'/ajax.php',
			type:'POST',
			data:({0:'publicAlbums',1:app.currentAlbumPage}),
			success:function(msg){
				app.isLoading=false;
				$('#loading').hide();
				if(msg==''){
					app.isLastAlbum=true;
				}else{
					var pattern=app.sprintf(app.pagePattern,app.currentAlbumPage);
					$('#albums').append(pattern+msg);
					app.albumsTooltip(app.currentAlbumPage);
				}
			}			
		});
	}
}

/**
* Met un tooltip sur les albums
*/
app.albumsTooltip=function(pageNumber){
	$("div#page"+pageNumber).nextAll('div.item').each(function(){
		$(this).find('a').tooltip({
			track: true, 
	    delay: 0, 
	    showURL: false, 
	    fade: 250 
		});
	});
}

/**
* gestion de l'affichage des photos sous forme de popin
*/
app.initFancyGallery=function(){
	$('a.gallery[rel=gallery]').unbind('click');
	$('a.gallery[rel=gallery]').click(function(){
		app.setPictureAnchor($(this).attr('href'));
		return(false);
	});
}

/**
* Chargement de l'url de la photo en ajax
*/
app.pictureLoad=function(pictureUrl){
	app.stopLoading=true;
	$.ajax({
		url:pictureUrl,
		success:function(msg){
			// affichage du contenu de la page dans le div
			$('#picture').html(msg);
			$('#picture').fadeIn();
			// ecouteurs
			app.initClosePicture();
			// bloque le scroll sur le body
			$('body').css('overflow','hidden');
			// listener for next/previous page
			app.pictureNavigation();
			// set img max width
			app.resizePicture();
			// commentaire
			app.initComment();
			// for connect fancybox
			app.initFancybox();
			// title on textarea
			$('div.comment textarea').formLabels();
		}			
	});
}

app.initFancybox=function(){
	$('a.fancybox').fancybox({
		'overlayColor':'#333',
		'overlayOpacity':'0.7',
		'centerOnScroll':true,
		'titleShow':false
	});
	$('a.fancyboxAjax').fancybox({
		'overlayColor':'#333',
		'overlayOpacity':'0.7',
		'centerOnScroll':true,
		'titleShow':false,
		'type':'ajax'
	});
	$('a.fancyGallery').fancybox({
		'overlayColor':'#333',
		'overlayOpacity':'0.7',
		'centerOnScroll':true,
		'titleShow':false
	});
}

app.accountManage=function(){
	$('a.accountSelect').click(function(){
		$('input.checkbox').attr('checked',true);
		return(false);
	});
	$('a.accountUnselect').click(function(){
		$('input.checkbox').attr('checked',false);
		return(false);
	});
	$('a.accountAddPicture').fancybox({
		'overlayColor':'#333',
		'overlayOpacity':'0.7',
		'centerOnScroll':true,
		'titleShow':false,
		'type':'ajax',
		'hideOnOverlayClick':false,
		'enableEscapeButton':false,
		'autoDimensions':false,
		'width':600,
		'height':'70%',
		'onCleanup':function(){
			if($('.file_upload_progress').length!=0){
				return(confirm("Upload is in progress. If you close the window now, it will be canceled.\n\nDo you want to close it now?"));
			}else if($('img.uploadImg').length!=0){
				window.location.href=window.location.href;
				return(true);
			}else{
				return(true);
			}
		}
	});
	$('a.accountAddVideo').fancybox({
		'overlayColor':'#333',
		'overlayOpacity':'0.7',
		'centerOnScroll':true,
		'titleShow':false,
		'type':'ajax',
		'hideOnOverlayClick':false,
		'enableEscapeButton':false
	});
	$('a.accountDelete').click(function(){
		var n=$('input.checkbox:checked').length;
		if(n>0){
			if(confirm('Are you sure you want to delete '+n+' item(s)?')){
				$('form#accountManageForm').submit();
			}
		}else{
			alert('Please select at least one item.');
		}
		return(false);
	});
	// hide empty sentence if needed
	if($('.item').length!=0){
		$('#empty').hide();
	}
}

/**
* Pose les ecouteurs pour la saisie de commentaires
*/
app.initComment=function(){
	$('#commentSubmit').unbind('click');
	$('#commentSubmit').bind('click',function(){
		var comment=$('#comment').val();
		if(comment.length>3){
			$.ajax({
				url:'/ajax.php',
				type:'POST',
				data:({0:'addComment',1:comment,2:$('#photoNumberId').val()}),
				success:function(msg){
					$('#commentsContent').append(msg);
					$('#comment').val('');
				}			
			});
		}else{
			alert('Please write a comment before submitting');
		}
		return(false);
	});
}

/**
* Met à jour la taille de la photo et des liens de navigation
*/
app.resizePicture=function(){
	$('#picture img.pix').hide();
	$('#picture div#author').hide();
	var maxHeight=$(window).height()-180;
	if(maxHeight<550) maxHeight=550;
	var maxWidth=1014;
	if($('#picture img.pix').length==1){
		$('#picture img.pix').load(function(){
			// calcul des tailles
			if($(this).height()<maxHeight){
				maxHeight=$(this).height();
			}
			if($(this).width()<maxWidth){
				maxWidth=$(this).width();
			}
			// calcul des hauteurs et largeurs en homotetie
			var h=$(this).height();
			var w=$(this).width();
			if($(this).height()>maxHeight){
				var h = maxHeight;
				var w = Math.ceil($(this).width() / $(this).height() * maxHeight);
			}else if($(this).width()>maxWidth){
				var w = maxWidth;
				var h = Math.ceil($(this).height() / $(this).width() * maxWidth);
			}
		  // affichage et redimensionnement
			$(this).css({ height: h, width: w });
			$('#picture div#author').css({ width: w-6 });
			$(this).show();
			$('#picture div#author').show();
			$('#picture #picturePrevious,#picture #pictureNext,#picture #pictureLoading').css({height: h});
		});
	}else{
		var h=parseInt($('#video').attr('height'));
		$('#picture #picturePrevious,#picture #pictureNext,#picture #pictureLoading').css({height: h});
	}
}

/**
* Pose les ecouteurs pour la navigation d'une picture a une autre
*/
app.pictureNavigation=function(){
	$('#pictureNext, #picturePrevious').unbind('click');
	$('#pictureNext, #picturePrevious').bind('click',function(){
		app.setPictureAnchor($(this).attr('href'));
		return(false);
	});
}

/**
* Retourne l'url sans l'ancre
*/
app.urlWithoutAnchor=function(url){
	var pos=url.indexOf('#');
	if(pos!=-1){
		url=url.substring(0,pos);
	}
	return(url);
}

/**
* Pose une ancre pour permettre le copier coller d'url
*/
app.setPictureAnchor=function(pictureHref){
	var url=pictureHref.replace(/^\/picture.php\?h=([0-9a-zA-Z]+)&p=([0-9a-zA-Z]+)$/,'picture-$1-$2');
	$.history.load(url);
}

/**
* Check si la page doit ouvrir directement la photo
*/
app.currentUrl='';
app.checkOpeningPicture=function(){
	$.history.init(function(url) {
		if(url!=app.currentUrl){
			app.currentUrl=url;
			if(url.match(/^picture-([0-9a-zA-Z]+)-([0-9a-zA-Z]+)$/)){
				url=url.replace(/^picture-([0-9a-zA-Z]+)-([0-9a-zA-Z]+)$/,'/picture.php?h=$1&p=$2');
				app.pictureLoad(url);
			}else if(url=='root'){
				app.closePictureProcess();
			}
		}
	});
}

/**
* Pose l'ecouteur necessaire a la fermeture de la popin picture
*/
app.initClosePicture=function(){
	$('a.closePicture').unbind('click');
	$('a.closePicture').click(function(){
		$.history.load('root');
		return(false);
	});
}

app.closePictureProcess=function(){
	// hide content
	$('#picture').fadeOut();
	// unset hidden overflow on body
	$('body').css('overflow','auto');
	// permet de nouveau le loading via scroll
	app.stopLoading=false;
}

/**
* Check si le navigateur est ie7
*/
app.isIE7=function(){
	var rv=false;
	var intSplitStart = navigator.userAgent.indexOf("(",0);
	var intSplitEnd = navigator.userAgent.indexOf(")",0);
	var strChStart = navigator.userAgent.substring(0,intSplitStart);
	var strChMid = navigator.userAgent.substring(intSplitStart, intSplitEnd);
	var strChEnd = navigator.userAgent.substring(strChEnd);
	if(strChMid.indexOf("MSIE 7") != -1) rv=true;
	return(rv);
}

/**
* Initialise les check sur les formulaires
*/
app.initFormCheck=function(){
	$('form.formCheck').submit(function(){
		var t='';
		// hash
		var hash=$(this).find('input[name="h"]').val();
		if(hash!=undefined){
			if(!hash.match(/[a-zA-Z0-9]{10}/)) t+="\n   - Private key";
		}
		// pseudo
		var pseudo=$(this).find('input[name="pseudo"]').val();
		if(pseudo!=undefined){
			if(!pseudo.match(/[a-zA-Z0-9]{3,20}/)) t+="\n   - Pseudo";
		}
		// email
		var email=$(this).find('input[name="email"]').val();
		if(email!=undefined){
			if(!app.isValidEmail(email)) t+="\n   - Email address";
		}
		// pass
		var pass=$(this).find('input[name="pass"]').val();
		if(pass!=undefined){
			var passRegExp=new RegExp('^[\\S]{2,20}$','i');
			if(!pass.match(passRegExp)) t+="\n   - Password";
		}
		// passConfirm
		var passConfirm=$(this).find('input[name="passConfirm"]').val();
		if(passConfirm!=undefined && pass!=passConfirm){
			t+="\n   - Password confirmation";
		}
		// city
		var city=$(this).find('input[name="city"]').val();
		if(city!=undefined){
			if(city.length<3) t+="\n   - City";
		}
		// firstname
		var firstname=$(this).find('input[name="firstname"]').val();
		if(firstname!=undefined){
			if(firstname.length<3) t+="\n   - First name";
		}
		// lastname
		var lastname=$(this).find('input[name="lastname"]').val();
		if(lastname!=undefined){
			if(lastname.length<3) t+="\n   - Last name";
		}
		// birthDate
		var birthDate=$(this).find('input[name="birthDate"]').val();
		if(birthDate!=undefined){
			var r=new RegExp('^[0-9]{2}/[0-9]{2}/[0-9]{4}$')
			var fc=false;
			if(birthDate.match(r)){
				var tmp=birthDate.split('/');
		    fc=(tmp.length==3&&app.dateCheck(tmp[2],tmp[0],tmp[1]));
			}
			if(!fc) t+="\n   - Birthday date";
		}
		// address
		var address=$(this).find('input[name="address"]').val();
		if(address!=undefined){
			if(address.length<3) t+="\n   - Address";
		}
		// zipcode
		var zipcode=$(this).find('input[name="zipcode"]').val();
		if(zipcode!=undefined){
			if(zipcode.length<3) t+="\n   - Zipcode";
		}
		// country
		var country=$(this).find('select[name="country"]').val();
		if(country!=undefined){
			if(parseInt(country)==0) t+="\n   - Country";
		}
		// object
		var object=$(this).find('input[name="object"]').val();
		if(object!=undefined){
			if(object.length<3) t+="\n   - Object";
		}
		// message
		var message=$(this).find('textarea[name="message"]').val();
		if(message!=undefined){
			if(message.length<5) t+="\n   - Message";
		}
		// albumName
		var albumName=$(this).find('input[name="albumName"]').val();
		if(albumName!=undefined){
			if(albumName.length<3) t+="\n   - Album name";
		}
		// albumDate
		var albumDate=$(this).find('input[name="albumDate"]').val();
		if(albumDate!=undefined){
			var r=new RegExp('^[0-9]{4}-[0-9]{2}-[0-9]{2}$')
			var fc=false;
			if(albumDate.match(r)){
				var tmp=albumDate.split('-');
		    fc=(tmp.length==3&&app.dateCheck(tmp[0],tmp[1],tmp[2]));
			}
			if(!fc) t+="\n   - Album date";
		}
		// visible in public
		var isPublic=$(this).find('select[name="isPublic"]').val();
		if(isPublic!=undefined){
			if(isPublic=='') t+="\n   - Visible in public";
		}
		// email[]
		var count=1;
		$(this).find('input[name="email[]"]').each(function(){
			var v=$(this).val();
			if(v!='' || count==1){
				if(!app.isValidEmail(v)) t+="\n   - Email address #"+count;
			}
			count++;
		});
		if(t!=''){
			alert("Please check:"+t);
			return(false);
		}
	});
}

app.dateCheck=function(year,month,day){
	var rv=false;
	if(month&&this.isString(month)) month=parseInt(month.replace(/^0/,''));
	if(day&&this.isString(day)) day=parseInt(day.replace(/^0/,''));
	var d=new Date();
	d.setFullYear(year,(month-1),day);
	rv=(month>=1&&month<=12&&year>=1&&year<=32767&&(d.getMonth()+1)==month&&day<32);
	return rv;
};

app.isString=function(str){
	var rv=(typeof(str)=='string');
	return rv;
};

app.isValidEmail=function(email){
	email=email.toLowerCase();
	return(email.match(/^([a-z0-9])+([\.]?[_a-z0-9-]+)*@([a-z0-9]{1})([\.]?[a-z0-9-]+)+[\.]{1}[a-z]{2,6}$/));
}

app.sprintf=function(str){
	var rv=str;
	var argv=arguments;
	var i,r;
	for(i=1;i<argv.length;i++){
		r=new RegExp('%'+i+'\\$s','g');
		rv=rv.replace(r,argv[i]);
	}
	return(rv);
}

app.photoViewerClose=function(){
	$('#photoViewer').hide();
}

app.getFileSize=function(s){
	s/=1024;
	if(s>1024){
  	s/=1024;
  	s=Math.round(s*100)/100;
  	s+=' MB';
  }else{
  	s=Math.round(s*100)/100;
  	s+=' KB';
  } 
  return(s);
}

app.cropText=function(str,len){
	if(str.length > len) {
		str=str.substring(0,len)+'...';
	}
	return(str);
}
