

$(document).ready(function(){
	initAjaxForms();
	
	initZoomimage();
	initKeepOnline();
	initDefaultValues();
	initCommentForm();
	initSendMessageForm();
	initMessagesGrid();
	
	initAlbumAjax();
	initDatePicker();
	
	initPrintLink();
	
	initYouTubeOverlay();
	
	initEmailToFriend();
	
	initLoadingForms();
	initZipPreviewForm();
	
	initEventsCalendar();
	
	initInviteFriends();
	
	initReportAbuse();
})

$(window).load(function(){
	initAlbumSlider();
});

var currSlide, currImageId;
function initAlbumAjax(){
	if( !$('#albumimages a').length ) return;
	
	$('#albumimages a').each(function(i,link){
		link.ind = i;
		$(link).click(function(e){
			//e.preventDefault();
			
			$('#album-image-details').html('');
			$('#album-image-details').append('<div class="loading"></div>');
			
			$('#album-image-comments').html('');
			$('#album-image-comments').append('<div class="loading"></div>');
			
			// set active
			$('#albumimages a').removeClass('active');
			$(this).addClass('active');
			
			// ajax load
			var image_url = $(this).attr('href').replace('#image-','/image/');
			
			if($CropBox){
				$CropBox.destroy();
				$CropBox = null;
			}
			
			var id_match = image_url.match(/\/image\/(\d+)/);
			currImageId = id_match[1];
			
			$('#album-image-details').load( 
				image_url, 
				'order=' + (this.ind+1), 
				function(){
					// init prev/next
					$('#album-nav a.prevp,#album-nav a.nextp').click(function(){
						var newIndex = parseInt($(this).attr('rel')) - 1;
						var newImage = $('#albumimages a:eq('+ newIndex +')');
						
						newImage.click();
						window.location.href = newImage.attr('href');
						
						return false;
					})
					
					// init rating start
					var form = $('#image-rate');
					form.rating( 
						form.attr('action'), 
						{
							maxvalue:5, 
							curvalue: $('#image-rate input[name=rating_value]').val(), 
							disabled: parseInt( $('#image-rate input[name=rating_disabled]').val() ), 
							success: function(rating, response){
								if(response != '')
									$('#album-image-details').append('<div class="clear" style="height:10px;"></div>'+response);
							}
						} 
					);
					
					// init tagging
					initImageTagging();

					// init image click
					$('#album-image-details div.jcrop-holder').bind('click', showAlbumNextPic);
					
					// init print
					initPrintLink();
					// init email to friend
					initEmailToFriend();
					// init report abuse buttons
					initReportAbuse();
				}
			);
			$('#album-image-comments').load( 
				image_url.replace('/image/','/image-comments/'), 
				'', 
				function(){
					initDefaultValues(); 
					initCommentForm();
					// init report abuse buttons
					initReportAbuse();
				} 
			);
			
			// reloading banner right 300
			document.getElementById('album-banner-right-300').src='http://www.beiruting.com/album/banner/inside/right/300';
			// reloading banner right 250
			document.getElementById('album-banner-right-250').src='http://www.beiruting.com/album/banner/inside/right/250';
			// reloading banner top 728
			document.getElementById('album-banner-top-728').src='http://www.beiruting.com/album/banner/top/728';
			document.getElementById('album-banner-top-729').src='http://www.beiruting.com/album/banner/top/729';
			//return false;
		});
	});
	
	// get current first image
	var linkID;
	var url_parts = window.location.href.split('#');
	if (url_parts && url_parts.length > 1 && url_parts[1].match(/^image-(\d+)/))
	{
		var img_match = url_parts[1].match(/^image-(\d+)/);
		linkID = '#album-' + img_match[0];
		if( url_parts[1].match(/^image-(\d+)-comments/) )
		{
			$(window).scrollTo('#comments');
		}
	}
	
	if(!linkID || !$(linkID).get(0))
	{
		linkID = '#' + $('#albumimages a:first').attr('id');
	}
	
	// launch loader
	$(linkID).click();
	
	initAlbumKeyboardNavi();
}

function showAlbumNextPic(e){
	var countImages = $('#albumimages a').length;
	var nextIndex = parseInt( $('#albumimages a.active').attr('rel') );
	nextIndex = nextIndex % countImages;
	var nextImage = $('#albumimages a:eq('+ nextIndex +')');
	
	nextImage.click();
	window.location.href = nextImage.attr('href');	
	//alert('show next '+nextIndex);
}

function initAlbumSlider(){
	// single pic album slider
	$('#albumimages').cycle({ 
		fx:     'scrollVert', 
		speed:  'slow', 
		timeout: 0,
		next:   '#gallerynext', 
		prev:   '#galleryprevious'
	});
}

function initAlbumKeyboardNavi(){
	$(window).keypress(function (e) {
		switch(e.keyCode){
			case 37: // left arrow
				$('#album-nav a.prevp').click();
				break;
			case 39: // right arrow
				$('#album-nav a.nextp').click();
				break;
		}
	});
}

/**
 *	zoom image
 */ 
function initZoomimage(){
	$('#slides a.thickbox').zoomcustom({
		width: 350,
		height:262,
		margin:10,
		caption: 'rel'
	});
	$('#gallery_images a.zoomme').zoomimage();
}

/**
 *	keep online
 */ 
function initKeepOnline(){
	if(User.id == 0) return;
	setInterval(keepUserOnline, 30000);
}
function keepUserOnline(){
	$.ajax({url: BasePath + 'ajax/online' });
}

/**
 *	input default values
 */
function initDefaultValues(){
	$('form').submit(function(){
		$(this).find('.with-default').focus();
	})
	$('form .with-default').focus(function(){
		var defID = '#' + $(this).attr('id') + '_default';
		var def = $(defID).val();
		if ( $(this).val() == def ){
			$(this).val('');
		}
		$(this).removeClass('default');
	})

}

function initCommentForm(){
	$('#comments form').submit(function(){
		var comment = $(this).find('textarea').val().replace(/^[\s\t]+/g, '').replace(/[\s\t]+$/, '');
		if ( comment == '' ){
			alert('Comment text is required.');
			return false;
		}
	});
	$('#comments a.delete-comment').click(function(){
		if( confirm('Are you sure you want to delete this comment?') ){
			$.ajax({ url: $(this).attr('href') });
			$(this).parents('div.comment').remove();
		}
		return false;
	});
}

/**
 *	ajax form submitions
 */
function initAjaxForms(){
	$('form.ajax').submit(function(e){
		e.preventDefault;
		
		$(this).find('.with-default').focus();
		
		$(this).ajaxSubmit({
			beforeSubmit: function(formData, jqForm, options){
				showShadow();
				showLoader();
				formData.push( {name:'ajax', value:'1'} );
			},
			success: function(response){
				removeLoader();
				try{ eval("var oResponse = " + response); }
				catch(err){
					showPopup(response);
					return false;
				}
				
				//alert(typeof(oResponse))
				if(!oResponse || typeof(oResponse) != 'object'){
					removeShadow();
					//showPopup(response);
					return false;
				}
				
				if(oResponse.redirect){
					window.location.href = oResponse.redirect;
					if(oResponse.redirect.match(/#/)){
						window.location.reload( true );
					}
					return false;
				}
				
				if(oResponse.popup){
					showShadow();
					showLoader();
					$.ajax({
						url:oResponse.popup,
						success: function(response){
							showPopup( response, false );
							if(oResponse.postprocess)
								oResponse.postprocess();
							removeLoader();
						}
					});
				}
				
				if(oResponse.errors){
					var content = '<div class="messages"><ul class="error">';
					for(var key in oResponse.errors){
						var err = oResponse.errors[key];
						content += '<li>. ' + oResponse.errors[key] + '</li>';
					}
					content += '</ul></div>';
					showPopup(content);
				}
			}
		})
		return false;
	});
	
	if( $('#loginform').get(0) ){
		$('#loginform').append( '<input type="hidden" name="redirect" value="' + window.location.href + '" />' )
	}
}

/**
 *	show fader shadow
 */ 
function showShadow( opacity ){
	if( !$('#fader_bg').get(0) )
		$(document.body).append('<div id="fader_bg"></div>');
	
	if(!opacity) opacity = 0.75;
	$('#fader_bg').css('opacity', opacity).show();
}
function removeShadow(){
	$('#fader_bg').remove()
}

/**
 *	show loading spiner
 */ 
function showLoader(){
	if( !$('#fader_loader').get(0) )
		$(document.body).append('<div id="fader_loader"></div>');
	$('#fader_loader').show();
}
function removeLoader(){
	$('#fader_loader').remove();
}

/**
 *	show popup
 */
function showPopup( content, hide_on_click ){
	if( !$('#fader_message').get(0) ){
		$(document.body).append('<div id="fader_message"><div class="bgtop"></div><div class="bgcontent"><div class="content"></div></div><div class="bgbottom"></div></div>');
	}
	$('#fader_message div.content').html(content);
	$('#fader_message').css({
		left: Math.max(0, ($(window).width() - $('#fader_message').width())/2 ),
		top: Math.max(0, $(window).scrollTop() + ($(window).height() - $('#fader_message').height())/2 )
	});
	$('#fader_message').show();
	
	if(hide_on_click == null) hide_on_click = true;
	
	var close_selector = '#fader_message a.close';
	if( $(close_selector).get(0) && $(close_selector).attr('href').indexOf('http') > -1 ){
    $(close_selector).click(function(e){
		/*
			window.location.href = $(this).attr('href');
			window.location.reload();
		*/
			window.location.href = $(this).attr('href');
			setTimeout( "window.location.reload();" , 1000);
			
		/*
			//e.preventDefault();
			//window.location.replace( $(this).attr('href') );
		*/
			return false;
		})
		close_selector = '';
	}
	if( hide_on_click ){
		if(close_selector != '') close_selector += ',';
		close_selector = '#fader_message,#fader_bg';
	}
	
	if(close_selector != ''){
		$(close_selector).click(function(){
			removePopup();
			removeShadow();
			return false;
		})
	}
}

function removePopup(){
	$('#fader_message').remove();
}

function hidePopup(){
	$('#fader_message').hide();
}


/**
 *	date picker init
 */ 
function initDatePicker(){
	$('form input.datepick').datepicker({ dateFormat: 'dd/mm/yy', firstDay:1 });
}

/**
 *	image tagging
 */
var $CropBox;
function initImageTagging(){
	// init cropbox
	$CropBox = $.Jcrop('#cropbox', {
		bgColor: '#8F1D53',
		bgOpacity: 0.6,
		onChange: function(c){
			if($CropBox.__namePopup)$CropBox.__namePopup.hide();
		},
		onSelect: function(c){
			if(c.w > 0 && c.h > 0){
				$CropBox.__selection = c;
				initImageTagginSaveWnd(c);
			}
		}
	});

	disableCropBox();

	// init tag button
	$('#do-tag').click( enableCropBox );
	$('#cancel-tag').click( disableCropBox );
	
	// init show persons
	$('#album-image-details div.pictag a.tagged, #album-image-details div.pictag a.delete-tag').hover(
		// mouse over
		function(){
			var coord = $(this).attr('rel').split(',');
			for(var i=0; i<coord.length; i++) coord[i] = parseInt( coord[i] );
			
			$CropBox.setSelect(coord); 
		},
		// mouse out
		function(){
			$CropBox.release();
		}
	);
	// prevent clicking on person if it has no page
	$('#album-image-details div.pictag a.tagged').click(function(e){ if($(this).attr('href').match(/#/)){ e.preventDefault(); return false; } })
	// add delete event
	$('#album-image-details div.pictag a.delete-tag').click( deleteCropBoxTag );
}

// show window with autocomplit
function initImageTagginSaveWnd(c){
	if(!$('#album-image-details div.jcrop-name-popup').get(0)){
		var html = [
			'<div class="jcrop-name-popup"><div class="bg1"><div class="bg2">',
				'<a href="#tag-me" id="jcrop-me">It\'s me!</a>',
				'<div class="jcr-box">',
					'<label for="jcrop-name">Friend\'s Name</label><br />',
					'<input type="text" id="jcrop-name" value="" class="jcroptext" size="27" />',
					'<label for="jcrop-email">Friend\'s Email</label><br />',
					'<input type="text" id="jcrop-email" value="" class="jcroptext" size="27" />',
					'<br /><small>* email won\'t appear to other users.</small>',
					'<br /><br />start typing your friend\'s name or email. <br />we\'ll notify your friend that he(she) was tagged.',
					'<br /><br /><input type="checkbox" id="jcrop-share" value="1" /> <label for="jcrop-share">share with <img src="http://b.static.ak.fbcdn.net/rsrc.php/z39E0/hash/ya8q506x.gif" alt="" /></label>',
				'</div>',
				'<div class="jcr-box">',
					'<input type="button" value="Save" id="jcrop-btn-save" />',
					'<input type="button" value="Cancel" id="jcrop-btn-cancel" />',
				'</div>',
			'</div></div></div>'
			];
		$('#album-image-details div.jcrop-holder').append( html.join("\n") );
		$CropBox.__namePopup = $('#album-image-details div.jcrop-name-popup');
		$CropBox.__namePopup.find('#jcrop-btn-save').click( saveCropBoxTag );
		$CropBox.__namePopup.find('#jcrop-btn-cancel').click( disableCropBox );
		$CropBox.__namePopup.inpName = $CropBox.__namePopup.find('#jcrop-name');
		$CropBox.__namePopup.inpEmail = $CropBox.__namePopup.find('#jcrop-email');
		$CropBox.__name = null;
		
		// init autocomplete name
		function finishAutocomplete(event, item){
			$CropBox.__name = {
				user_id: item[0],
				name: item[1],
				email: item[2],
				image_id: currImageId
			}
			$CropBox.__namePopup.inpName.val( item[1] );
			$CropBox.__namePopup.inpEmail.val( item[2] );
		}
		
		// autocomplete for name
		$CropBox.__namePopup.inpName.autocomplete(BasePath + 'ajax/friends-autocomplete', {
		  extraParams: { 'field': 'name', 'image_id': currImageId },
			formatResult: function(item){ $CropBox.__name = null; return item[1]; },
			formatItem: function(item) { return item[1] + '<br />' + item[2]; }
		}).result( finishAutocomplete );
		// autocomplete for email
		$CropBox.__namePopup.inpEmail.autocomplete(BasePath + 'ajax/friends-autocomplete', {
			extraParams: { 'field': 'email', 'image_id': currImageId },
		  formatResult: function(item){ $CropBox.__name = null; return item[2]; },
			formatItem: function(item) { return item[2] + '<br />' + item[1]; }
		}).result( finishAutocomplete );
		
		// init "Me" clicked
		$CropBox.__namePopup.find('#jcrop-me').click( function(e){
			e.preventDefault();
			var item = [ User.id, User.name, User.email ];
			finishAutocomplete(e, item)
			return false;
		});
	}
	// make position near selection box
	$CropBox.__namePopup.css({

		'left':$CropBox.__selection.x2 + 5,
		'top':$CropBox.__selection.y
	});
	// show and focus input
	$CropBox.__namePopup.show();
	$CropBox.__namePopup.inpName.val('');
	$CropBox.__namePopup.inpEmail.val('');
	$CropBox.__namePopup.inpName.focus();
}

// save tag box
function saveCropBoxTag(){
	//$alert($CropBox.__selection);
	// fill data object
	var c = $CropBox.__selection;
	var post = {};
	if($CropBox.__name){
		post = $CropBox.__name;
	}
	else{
		post.user_id = 0;
		post.name = $CropBox.__namePopup.inpName.val();
		post.email = $CropBox.__namePopup.inpEmail.val();
		post.image_id = currImageId;
	}
	post.coord = c.x + ',' + c.y + ',' + c.x2 + ',' + c.y2;
	
			$CropBox.__namePopup.find('div.bg2').css('visibility', 'hidden');
			$CropBox.__namePopup.find('div.bg1').addClass('loading');
	
	$.ajax({
		url: BasePath + 'ajax/image-tag-add',
		type: 'POST',
		data: post,
		success: function(response){
			if(response == 'OK'){
				if( $CropBox.__namePopup.find('#jcrop-share').get(0).checked ){
					// click fbshare button
					$('#album-image-details a.fbshare').get(0).onclick();
				}
				// refresh all content area
				$('#albumimages li a.active').click();
			}
			else{
				alert(response);
				$CropBox.__namePopup.find('div.bg2').css('visibility', 'visible');
				$CropBox.__namePopup.find('div.bg1').removeClass('loading');
				alert('Some error occured. Please check that you entered name and email correctly.');
			}
		}
	})
}

// delete tag
function deleteCropBoxTag(){
	var data = $(this).attr('rel').split(',');
	var tag_id = data[4];
	var tag = $(this).parents('span.imagetag:eq(0)'); //.addClass('deleted');
	tag.addClass('deleted');
	tag.prev('span.separator').addClass('deleted');
	$.ajax({
		url: BasePath + 'ajax/image-tag-delete',
		type: 'POST',
		data: 'id=' + tag_id,
		success: function(response){
			if(response == 'OK'){
				// remove them from html dom structure
				$('#album-image-details div.pictag span.deleted').remove();
				$CropBox.release();
			}
			else{
				alert(response);
			}
		}
	})
	
	return false;
}

function enableCropBox(e){
	$CropBox.enable();
	$('#album-image-details div.jcrop-holder').addClass('jcrop-active');
	$('#album-image-details div.jcrop-holder').unbind('click', showAlbumNextPic);
	
	$('#do-tag').hide();
	$('#cancel-tag').show();
	return false;
}

function disableCropBox(e){
	// disable select function
	$CropBox.disable();
	
	// remove name window
	if($CropBox.__namePopup)$CropBox.__namePopup.hide();
	
	// clear selection
	$CropBox.release();
	
	// hide under buttons bar
	$('#album-image-details div.jcrop-holder').removeClass('jcrop-active');
	
	// change buttons
	$('#cancel-tag').hide();
	$('#do-tag').show();
	return false;
}


/**
 *	send message
 */
function initSendMessageForm(){
	if( !$('#send-to-friend').get(0) ) return;
	
	$('#form_to').autocomplete(BasePath + 'ajax/friends-autocomplete', {
	  extraParams: { 'field': 'name', 'image_id': 0 },
		formatResult: function(item){ return item[1]; },
		formatItem: function(item) { return item[1] + '<br />' + item[2]; }
	})
	.result(function(event, item){
		$('#form_to').val( item[1] );
		$('#to_id').val( item[0] );
	});
}

function initMessagesGrid(){
	if(!$('#inbox-container table.messages').get(0)) return;
	
	$('#inbox-container table.messages #check_all').click(function(){
		var checked = this.checked? 'checked' : '';
		$('#inbox-container table.messages input:checkbox').attr('checked', checked);
	});
	
	//alert($('#bulk_operations').get(0))
	$('#bulk_operations').change(function(){
		var checked = $('#inbox-container table.messages input:checkbox:checked').length;
		if (checked < 1){
			alert('Please check at list one message.');
			this.value = '';
			return;
		}
		
		var $form = $(this).parents('form');
		if( this.value == 'delete' ){
			if(confirm("Are you sure you want to delete selected message(s)?\nThis action can not be undone!"))
				$form.submit()
			else
				this.value = '';
		}
		else if( this.value != '' ){
			$form.submit();
		}
	})
}

/**
 *	print links init
 */ 
function initPrintLink(){
	$('#main a.print').click(function(e){
		var custom_class = $(this).attr('rel');
		if (custom_class != '' && !$(document.body).hasClass('print_'+custom_class)){
			$(document.body).addClass('print_'+custom_class);
		}
		
		window.print();
		return false;
	})
}

/**
 *	youtube home page overlay
 */ 
function initYouTubeOverlay()
{
	$('div.overlay-video').click(function(e){
		e.preventDefault();
		
		$('#slides, #slides_nav').hide().css('visibility','hidden');
		$('#overlay_video_container').show();
		
		var obj_url = $(this).text();
		var obj_html = [
			'<object width="747" height="345">',
				'<param name="movie" value="'+ obj_url + '" />',
				'<param name="allowFullScreen" value="true" />',
				'<param name="allowscriptaccess" value="always" />',
				'<param name="wmode" value="transparent" />',
				'<embed src="'+ obj_url + '" width="747" height="345" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" wmode="transparent"></embed>',
			'</object>'
		];
		
		$('#overlay_video_container').append( obj_html.join('') );
		
		$('#dock-slider-thumb').show();
		$('#dock-video-thumb').hide();
		
		return false;
	});
	
	$('#dock-slider-thumb div.slider-overlay').click(function(e){
		$('#overlay_video_container').hide().html('');
		$('#slides, #slides_nav').show().css('visibility','visible');
		
		$('#dock-slider-thumb').hide();
		$('#dock-video-thumb').show();
		return false;
	});
}

/**
 *	email to friend ajax
 */
function initEmailToFriend(){
	$('a.email-to-friend, #open_forgot_password').click(function(e){
		showShadow();
		showLoader();
		$.ajax({
			url: $(this).attr('href'),
			type: 'POST',
			data: 'ajax=1',
			success: function(response){
				removeLoader();
				showPopup(response, false);
				// init form
				initEmailToFriendSubmit();
			}
		});
		return false;
	});
}

function initEmailToFriendSubmit(){

	$('#email-to-friend, #forgot-password, #user_register_step, #user_register_stepa').ajaxForm({
		beforeSubmit: function(formData, jqForm, options){
			if( !jqForm.find('input:file').get(0) ){
				removePopup();
			}
			else{
				hidePopup();
			}
			showShadow();
			showLoader();
			formData.push( {name:'ajax', value:'1'} );
			//$alert(formData, 200, true);
		},
		dataType:'html',
		success: function(response){
			removeLoader();
			var hide_on_click = false;
			if(!response.match(/\<label/)) 
				hide_on_click = true;
			showPopup(response, hide_on_click);
			initEmailToFriendSubmit();
		}
	});

	/*
	$('#email-to-friend, #forgot-password, #user_register_step').submit(function(e){
		e.preventDefault;
		$(this).ajaxSubmit({
			beforeSubmit: function(formData, jqForm, options){
				removePopup();
				showShadow();
				showLoader();
				formData.push( {name:'ajax', value:'1'} );
				//$alert(formData, 200, true);
			},
			success: function(response){
				removeLoader();
				var hide_on_click = false;
				if(!response.match(/\<label/)) 
					hide_on_click = true;
				showPopup(response, hide_on_click);
				initEmailToFriendSubmit();
			}
		})
		return false;
	});
	*/
}

function initLoadingForms(){
	$('form.progressbar-on-submit').submit(function(){
		$(this).find('div.loading').show();
		$(this).find('ul.form').hide();
	});
}

function initZipPreviewForm(){
	$('#zip-preview input:checkbox').change(function(){
		if(this.checked){
			$(this).parents('li').css('opacity', 0.6).find('textarea').attr('disabled', 'disabled');
		}
		else{
			$(this).parents('li').css('opacity', 1).find('textarea').attr('disabled', '');
		}
	});
}

function initEventsCalendar(){
	$('#ecalendar div.navi a').click(function(){
		var CalendarURL = BasePath + 'club/' + $('#ecalendar_club_id').val() + '/events-calendar?' + $(this).attr('href').split('?')[1];

		$('#ecalendar').css('background', '#f0f0f0').html('<h3 class="month">Loading...</h3><div class="loading" style="width:100%;height:150px;"></div>');
		
		$.ajax({
			url: CalendarURL,
			type: 'POST',
			data: 'ajax=1',
			success: function(response){
				$('#ecalendar').css('background', '#fff').html(response);
				initEventsCalendar();
			}
		});
		
		return false;
	});
}

function initInviteFriends(){
	$('#invite-friends a.invite-select-all').click(function(){
		$(this).parents('ul.personal-info').find('input:checkbox').attr('checked', 'checked');
		return false;
	});
	$('#invite-friends a.invite-deselect-all').click(function(){
		$(this).parents('ul.personal-info').find('input:checkbox').attr('checked', '');
		return false;
	});
}

function initReportAbuse(){
	$('#main > div.splitcontier a.report-abuse').each(function(i,item){
		if( $(item).attr('href').match(/#/) ) return;
		
		$(item).attr('_action', $(item).attr('href'));
		$(item).attr('href', '#report-abuse');
		$(item).click(function(e){
			showShadow();
			showLoader();
			$.ajax({
				url: $(this).attr('_action'),
				type: 'POST',
				data: 'ajax=1',
				success: function(response){
					removeLoader();
					showPopup(response);
				}
			});
			return false;
		}); // end click
	}); // ecn each
}