$.extend({
    postJSON: function(url, data, callback)
    {
        $.post(url, data, callback, 'json');
    }
});

$.ajaxSetup({
	cache: false,
	global: false,
	type: 'POST',
	dataType: 'json',
	error: function (xhr, s, e) {
		//alert('[error message for request failure]');
		$.jGrowl('Ajax request failed');
	}
});


$(document).delegate('#disable_secret_button', 'click', function() {
	$('#disable_secret').val(1);
	$('#secret_form').submit();
});

$(document)
    .delegate('.contributors_box', 'mouseover', function() {
        $(this).css('background-color', '#f1f1f1');
    }).delegate('.contributors_box', 'mouseout', function() {
        $(this).css('background-color', '#fff');
    });

$(document).delegate('#enable_secret_button', 'click', function() {
	$('#secret_form').submit();
});
// forms with text links as submit buttons
$(document).delegate('.block_follower', 'click', function() {
	var link = $(this);
	$.post(
		'/ajax/block_follower/' + link.attr('id') + '/',
		null,
		function(response){

			if (response.status != 'error') {
				link.html(response.status);
				if (response.status == 'Block')
					$.jGrowl(__('You have been unblocked follower'));
				else
					$.jGrowl(__('You have been blocked follower'));
			} else {
				$.jGrowl('Ajax request failed');
			}
		},
		'json'
	);
	return false;
});


$(document)
	.delegate('.menu_top, .menu_bottom', 'mouseover', function() {
		$('.menu_bottom').show();
		return false;
	}).delegate('.menu_top, .menu_bottom', 'mouseout', function() {
		$('.menu_bottom').hide();
		return false;
	});

// forms with text links as submit buttons
$(document).delegate('form a.link_submits_form', 'click', function() {
	$(this).closest('form').submit();
	return false;
});

// show more followed photos on home page

$(document)
	.delegate('#more_followed_photos', 'click', function() {
		var $link = $(this);
		var offset = $link.attr('offset');
		var ajaxOptions = {
			data: {
				ajax: true,
				offset: offset
			},
			success: function(json) {
				$link.attr('offset', offset + json.count);
				
				if (json.no_more)
					$link.hide();
				
				$('#followed_photos_sec').append(json.photos_html);	
			}
		};
		$.post(
			'/ajax/more_followed_photos',
			ajaxOptions.data,
			ajaxOptions.success
		);
		return false;
	});

//show more comments on member page
$(document)
.delegate('#more-photo-comments', 'click', function() {
	var $link = $(this);
	var offset = $link.attr('offset');
	var userId = $link.attr('user_id');
	var ajaxOptions = {
		data: {
			ajax: true,
			offset: offset,
			user_id: userId
		},
		success: function(json) {
			offset = new Number(offset) + json.count;
			$link.attr('offset', offset);

			if (json.no_more)
				$link.parent().hide();
			
			$('.member-page-last-comments').append(json.photos_html);	
		}
	};
	$.post(
		'/ajax/more_photo_comments',
		ajaxOptions.data,
		ajaxOptions.success
	);
	return false;
});

// follow/unfollow users

$(document)

	.delegate('#follow_user_form', 'submit', function() {
		var $form = $(this);
		var ajaxOptions = {
			data: { ajax: true },
			success: function(json) {
				if (json && json.s == 1) {
					$form
						.attr('action','/ajax/stop_following')
						.attr('id','unfollow_user_form')
						.find('a')
							.text(__('STOP FOLLOWING'))
					
					$.jGrowl(__('You are now following this user'));
				}
			}
		};
		$form.ajaxSubmit(ajaxOptions);
		return false;
	})
	
	.delegate('#add_to_favorites_form', 'submit', function() {
		var $form = $(this);
		var ajaxOptions = {
			data: { ajax: true },
			success: function(json) {
				if (json && json.s == 1) {
					$('.add-favorite').text('Remove Favorite');
				}
				else if (json && json.s == 0)
				{
					$('.add-favorite').text('Favorite');
				}
			}
		};
		$form.ajaxSubmit(ajaxOptions);
		return false;
	})
	
	.delegate('#unfollow_user_form', 'submit', function() {
		var $form = $(this);
		var ajaxOptions = {
			data: { ajax: true },
			beforeSubmit: function() {
				return confirm(__('Stop following this user?'));
			},
			success: function(json) {
				if (json && json.s == 1) {
					$form
						.attr('action','/ajax/start_following')
						.attr('id','follow_user_form')
						.find('a')
							.text(__('START FOLLOWING'))
					
					$.jGrowl(__('You are not longer following this user'));
				}
			}
		};
		$form.ajaxSubmit(ajaxOptions);
		return false;
	});



// photo actions
$(document)
	.delegate('#photo_details_sec div.photo', 'mouseover', function() {
		$('div.photo_actions', this).removeClass('hidden');
	})
	
	.delegate('#photo_details_sec div.photo', 'mouseout', function() {
		$('div.photo_actions', this).addClass('hidden');
	});


$(document).ready(function(){
	// tag management
	$(document)
		.delegate('span.tag', 'mouseover', function() {
			$('a.delete_tag', this).addClass('active');
		})		

		.delegate('span.tag', 'mouseout', function() {
			$('a.delete_tag', this).removeClass('active');
		})

//		.delegate('#photo_details_sec span.tag a.delete_tag', 'mouseover', function() {
//			$('a.tag_link', $(this).parent()).addClass('delete_hover');
//		})
//
//		.delegate('#photo_details_sec span.tag a.delete_tag', 'mouseout', function() {
//			$('a.tag_link', $(this).parent()).removeClass('delete_hover');
//		})

		.delegate('a.delete_tag', 'click', function() {
			var form = $(this).parent().parent();
			var tag = $(this).parent().parent().parent();
			if (confirm(__('Delete this tag?'))){
				var ajaxOptions = {
					data: { ajax: true },
					success: function(json) {
						if (json && json.s == 1) {
							tag.remove();
							if ($('#all_tags').children().length == 0) $('#all_tags').append('<span style="color: rgb(159, 159, 159);">no tags</span>');
							$.jGrowl(__('Tag has been removed'));
						}
					}
				};
				form.ajaxSubmit(ajaxOptions);
			}
			return false;
		})

//		.delegate('#photo_details_sec div.photo_actions a.reveal_add_tag', 'click', function() {
//			$('#photo_details_sec div.add_tags').removeClass('hidden');
//			return false;
//		})
//		
//		.delegate('#photo_title div.manage_menu a.reveal_add_tag', 'click', function() {
//			$('#photo_details_sec div.add_tags').removeClass('hidden');
//			return false;
//		})
//
//		.delegate('#photo_details_sec div.add_tags input.tag_cancel', 'click', function() {
//			$('#photo_details_sec div.add_tags').addClass('hidden');
//			return false;
//		});

		$('#disable_geo').click(function(){
			var value = $(this).attr('disable_geo');
			if (value == 1) value = 0;
			else value = 1;
			var id = $(this).attr('photo_id');
			$.ajax({
				url: '/ajax/change_geo_privacy',
				method: 'POST',
				cache: false,
				data: {value: value, id:id},
				success: function(ajax) {
					if (ajax == 1) {$('#disable_geo').attr('disable_geo', 0); $('#disable_geo span').text('Disable Geo Location');}
					else  {$('#disable_geo').attr('disable_geo', 1); $('#disable_geo span').text('Enable Geo Location');}
				}
			});
			
			$('#photo_header_menu div.manage').removeClass('up');
			$('.manage-menu').hide();
			return false;
		});
		
		$('#photo_header_menu div.manage').click(function(){
			
			if($(this).parent().find('.up').length){
				$(this).removeClass('up');
				$('.manage-menu').hide();
			}
			else{
				$(this).addClass('up');
				$('.manage-menu').css('left',$(this).position().left+3);
				$('.manage-menu').find('.menu-top-border').css('width',$('.manage-menu').width() - $(this).width() - 31);
				$('.manage-menu').show();
			}
		})

		$('.manage-menu').click(function(){
			$('#photo_header_menu div.manage').removeClass('up');
			$('.manage-menu').hide();
		});
					
		$('#is_watermark > *').click(function(){
			if($(this).attr('checked') == true)
				if (confirm(__("This action cannot be undone. Continue?")))
					$(this).attr('checked','true');
				else
					$(this).attr('checked','');
		});
		
		$('#people-search').autocomplete("/people/autocomplete", {
		 	delay:10,
		    minChars:1,
		    matchSubset:1,
		    autoFill:true,
		    matchContains:1,
		    cacheLength:10,
		    selectFirst:true,
		    maxItemsToShow:10
		});
		
		$('.focus').focus();
		
		if(location.href.indexOf("#comments") > 0)
			$('.focus_reply_comment').focus();
		
		$(".photos_list_userpic").live('mouseover',function(){;
			$("#MessageFromStreaming").find("input[name=recipient]").attr('value',$(this).attr('username'));
		});
		
		var isLoading = false;
		
		$(window).scroll(function(){
			if(window.location.pathname == "/") {
				var iebody = (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
				var dsoctop = document.all ? iebody.scrollTop : pageYOffset;
				
				var recentBox = $('.streaming-row-box-recent');
				if(recentBox.offset().top + recentBox.height() <= $(window).height()+dsoctop)
				{
					if (!isLoading){
						isLoading = true;
						
						var count = recentBox.attr('count');
						
						$.ajax({
							url: '/ajax/more_recent_photos',
							method: 'POST',
							cache: false,
							data: {count: count},
							success: function(ajax) {
								if (ajax != null){
									recentBox.append('<div class="recent-skin"><ul class="mycarousel_recent jcarousel-skin">'+ ajax.liHtml +'</ul></div>');
									
//											jQuery(".mycarousel_recent").jcarousel({
//												scroll: 1,
//												buttonNextHTML: null,
//												buttonPrevHTML: null
//											});
//											
											recentBox.attr('count',parseInt(recentBox.attr('count'))+1);
											isLoading = false;
								}
							}
						});
					}  		
					
				}
			}
		});		
		
//		jQuery(".mycarousel_recent").jcarousel({
//			scroll: 1,
//			buttonNextHTML: null,
//			buttonPrevHTML: null
//		});
		
		jQuery(".mycarousel").jcarousel({
	        scroll: 1,
	        
	        itemLoadCallback: {
  				onBeforeAnimation: function (carousel, item, idx, state){
  					var ulElement = carousel.list;
  					
  					var person = ulElement.attr('person');
  					if(person){
  						var count = ulElement.attr('count');
  						var username = ulElement.attr('username');
  						
  						if(carousel.last == carousel.size()) { 						
	  						$.ajax({
								url: '/ajax/more_followed_photos_by_person',
								method: 'POST',
								cache: false,
								data: {count: count, username: username},
								success: function(ajax) {
									if (ajax != null){
										carousel.size(carousel.size()+1);
	  									carousel.add(carousel.size(),ajax.liHtml);
	  									ulElement.attr('count',carousel.size());
									}
								}
	  						});  						
	  					}
  					}
  					else{
	  					var count = ulElement.attr('count');
	  					var timingFrom = ulElement.attr('timingFrom');
	  					var timingTo = ulElement.attr('timingTo');
	  					
	  					
	  					if(carousel.last == carousel.size()) { 						
	  						$.ajax({
								url: '/ajax/more_followed_photos',
								method: 'POST',
								cache: false,
								data: {count: count,timingFrom: timingFrom,timingTo: timingTo},
								success: function(ajax) {
									if (ajax != null){
										carousel.size(carousel.size()+1);
	  									carousel.add(carousel.size(),ajax.liHtml);
	  									ulElement.attr('count',carousel.size());
									}
								}
	  						});  						
	  					}
  					}
  				}
			}

    	});
});


// comment management
$(document)
	.delegate('#comments li.photo_comment', 'mouseover', function() {
		$('span.comment_functions', this).removeClass('hidden');
	})
	
	.delegate('#comments li.photo_comment', 'mouseout', function() {
		$('span.comment_functions', this).addClass('hidden');
	})
	
	.delegate('#comments form.delete_comment_form', 'submit', function() {
		var $form = $(this);
		var $comment = $form.closest('li.photo_comment');
		var $list = $comment.parent();
		// if deleting the only comment, remove entire list
		if ( $list.children().length - 1 == 0 ) $comment = $list.parent();
		var ajaxOptions = {
			data: { ajax: true },
			beforeSubmit: function() {
				return confirm(__('Delete this comment?'));				
			},
			success: function(json) {
				if (json && json.s == 1) {
					$comment.remove();
					$.jGrowl(__('Comment has been successfully removed'));
				}
			}
		};
		$form.ajaxSubmit(ajaxOptions);
		return false;
	});

/*
$('#add_comment_sec form').live('submit', function() {
	var actionUrl = $(this).attr('action');
	var data = $(this).serialize() + '&ajax=true';
	var msg = $('textarea[name="message"]', this).val();
	$.post(actionUrl, data, function(json) {
		if (json.s == 1) {
			// come up with a way to build comment HTML
		}
	}, 'json');
	return false;
});
*/



function editInline($node) {
	var text = $node.text();
	if (text == 'untitled') text = '';
	$('.inline_original', $node).addClass('hidden');
	$('form', $node).removeClass('hidden').find('.inline_input');
}

function stopEditingInline($node) {
	$('.inline_original', $node).removeClass('hidden');
	$('form.inline_form', $node).blur().addClass('hidden');
	$('#delete_photo_form').removeClass('hidden');
}


$(document).ready(function(){
	$('#photo_title form.inline_form').submit(function() {
		var $form = $(this);
		var $node = $('#photo_title');
		var edited = $('.inline_input', $node).val();
		var ajaxOptions = {
			data: { ajax: true },
			success: function(json) {
				if (json && json.s == 1) {
					$('.inline_original', $node).html((edited ? edited : '<span class="empty_title">'+__('Add title')+'</span>'));
					$.jGrowl(__('Photo title has been updated'));
				}
				stopEditingInline($node);
			}
		};
		$form.ajaxSubmit(ajaxOptions);
		return false;
	});

	$('#photo_description form.inline_form').submit(function() {
		var $form = $(this);
		var $node = $('#photo_description');
		var edited = $('.inline_input', $node).val();
		var ajaxOptions = {
			data: { ajax: true },
			success: function(json) {
				if (json && json.s == 1) {
					$('.inline_original', $node).html(edited ? edited : '<span class="empty_title">'+__('Add description')+'</span>');
					$.jGrowl(__('Photo description has been updated'));
				}
				stopEditingInline($node);
			}
		};
		$form.ajaxSubmit(ajaxOptions);
		return false;
	});
	
	$('.add-new-tag form input[name="tagstr"]').click(function() {
		if ($(this).attr('value') == "Add new tag here"){
			$(this).attr('value','');
		}
	});
	
	$('.add-new-tag form input[name="tagstr"]').attr('value',"Add new tag here");
	
	$('.add-new-tag form').submit(function() {
		var $form = $(this)
		var ukey = $('.add-new-tag form input[name="k"]').val();
				
		var ajaxOptions = {
			data: { ajax: true },
			success: function(json) {
				if (json) {
					if (json.length) if($('#all_tags').children().first().attr('class') != "tag") $('#all_tags').html('');
					for (var i=0;i<json.length;i++)
					{
						$('#all_tags').append('<span class="tag"><a title="browse photos with this tag" class="tag_link_new" href="/explore/tags/'+ json[i] +'">' + json[i] + '</a><form class="text_link_form" action="/ajax/delete_photo_tag" method="POST"><input type="hidden" value="' + ukey + '" name="k"><input type="hidden" value="' + json[i] + '" name="tag"><span class="delete_tag_span"><a title="remove tag" href="" class="delete_tag">&nbsp;&nbsp;&nbsp;</a></span></form></span>');
						$('.add-new-tag form input[name="tagstr"]').attr('value',"Add new tag here");
						$.jGrowl(__('Tag ' + json[i] + ' has been added'));
					}
				}
			}
		};
		$form.ajaxSubmit(ajaxOptions);
		return false;
	});

	$('#delete_photo_form').submit(function() {
		return (confirm(__('Delete this photo?')));
	});

	// profile photo upload
	$(document).delegate('#upload_profile_photo_form', 'submit', function() {
		var $form = $(this);
		var ajaxOptions = {
			data: { ajax: true },
			success: function(json) {
				if (json && json.s > 0) { // FIX
					$('input[type="file"]', $form).val('');
					refreshProfilePhoto();
				}
			}
		};
		$form.ajaxSubmit(ajaxOptions);
		return false;
	});

});
// title and description management
$(document)
	.delegate('#photo_details_sec div.photo_actions a.reveal_edit_title', 'click', function() {
		editInline($('#photo_title'));
		return false;
	})
	
	.delegate('#photo_description #reveal_edit_description2', 'click', function() {
		editInline($('#photo_description'));
		return false;
	})
	
	.delegate('#photo_title div.photo_title #reveal_edit_title2', 'click', function() {
		editInline($('#photo_title'));
		return false;
	})
	
	.delegate('.inline_original span.add_tags', 'click', function() {
		editInline($('#photo_tags'));
		return false;
	})
	
	.delegate('.inline_original input.inline_cancel', 'click', function() {
		var $node = $(this).closest('form').parent();
		stopEditingInline($node);
		return false;
	})
	
	.delegate('#photo_details_sec div.photo_actions a.reveal_edit_description', 'click', function() {
		editInline($('#photo_description'));
		return false;
	})
	
	.delegate('#photo_title input.inline_cancel, #photo_description input.inline_cancel', 'click', function() {
		var $node = $(this).closest('form').parent();
		stopEditingInline($node);
		return false;
	});

$(document).ready(function() {
	$('#reveal_edit_title2').hover(function() {
		$('.photo_title')
						.css('background-color', '#FEFFAF')
						.css('opacity', '0.5');
	},
	function() {
		$('.photo_title')
						.css('background-color', '')
						.css('opacity', '1')
						.css('filter', 'alpha(opacity=100)');
	});


	$('#reveal_edit_description2').hover(function() {
		$('.description')
						.css('background-color', '#FEFFAF')
						.css('opacity', '0.5');
		$('.empty_title').css('opacity', '1');
	},
	function() {
		$('.description').css('background-color', '');
		$('.description').css('opacity', '1');
	});
}
);






// profile photo deletion
$(document).delegate('#delete_profile_photo_form', 'submit', function() {
	var $form = $(this);
	var ajaxOptions = {
		data: { ajax: true },
		beforeSubmit: function() {
			return confirm(__('Delete your profile photo?'));				
		},
		success: function(json) {
			if (json && json.s == 1) {
				refreshProfilePhoto();
				$.jGrowl(__('Your profile photo has been removed'));
			}
		}
	};
	$form.ajaxSubmit(ajaxOptions);
	return false;
});

function refreshProfilePhoto() {
	var $photo = $('#profile_photo div.user_image img');
	var $form = $('#delete_profile_photo_form');
	var displayNewPhoto = function(json) {
		if (json && json.url && json.url != '') {
			$photo.attr('src', json.url);
			if (json.url.match('.gif$') == '.gif') $form.addClass('hidden'); // delete shouldn't be displayed with "noimage" profile photo
			else $form.removeClass('hidden');
		}
	};
	$.postJSON('/ajax/get_profile_photo', displayNewPhoto);
}

function showUploadProgress()
{
	var html = 'Your image is now uploading... Please wait'
		+ '<div style="margin-top:10px;text-align:center"><img src="' + image_url('ajax-loader.gif') + '" alt="Upload..." /></div>';
	jInformation(html, 'Upload in action');
}

function reportPhoto(photoUkey)
{
	/*$.post({
		url: "/ajax/report_photo",
		data: {
			ukey: photoUkey
		},
		dataType: "json",

		success: function(response) {
			$.jGrowl(response.code);
		},

		complete: function(xmlHttpRequest, textStatus) {
			//alert(xmlHttpRequest.responseText + ' ' + textStatus);
		},

		error: function(xmlHttpRequest, textStatus, errorThrown) {
			//alert(xmlHttpRequest.responseText + ' ' + textStatus + ' ' + errorThrown);
		}
	});*/
    if (confirm(__('You are about to report that this photo violates the user agreements or is otherwise offensive. Are you sure you would like to proceed?'))){
	$.post(
		'/ajax/report_photo',
		{
			ukey: photoUkey
		},
		function(data) {
			$.jGrowl(data.text);
		},
		'json'
	);
    }
    else
        return false;
}


$(document).ready(function() {
	$('.changeNetwork').click(function(){
		var id = $(this).attr('id');
		$('.networkDetails' + id).hide();
		$('.networkForm' + id).show();
		return false;
	});

	$('.cancelChangeNetwork').click(function(){
		var id = $(this).attr('id');
		$('.networkForm' + id).hide();
		$('.networkDetails' + id).show();
		return false;
	});

	$('.removeNetwork').click(function(){
		if (confirm(__('Are you sure want to delete this personal network?')))
		{
			var id = $(this).attr('id');
			$('#remove_network_id').val(id);
			$('#remove_network').submit();
		}
		return false;
	});

	$('.chooseNetwork').mouseover(function(){
		var div = $(this).parent().parent().parent();
		div.addClass('over');
		
	}).mouseout(function() {
		var div = $(this).parent().parent().parent();
		div.removeClass('over');
	});
	$('.chooseNetwork input').click(function(){
		$('*:checkbox').parent().parent().removeClass('checked');
		$('.privacyNetworks div').removeClass('selected').removeClass('over');
		$('.chooseNetwork input:checked').parent().parent().parent().parent().addClass('selected');
		$('#following_select_panel_loading').show();
		$('#create-privacy-network').hide();
		$('#network_followings_id').val($(this).parent().attr('id'));
		$('#following_select_panel .message').hide();
		$.get(
			'/ajax/get_network_followings/' + $(this).parent().attr('id'),
			function(response) {
				$('#following_select_box input').attr('checked',0);
				for(var i=0; i<response.followings.length; i++)
					$('#following_select_box input.assign' + response.followings[i]).attr('checked',1);

				$('#following_select_panel_loading').hide();
				$('#following_select_panel').show();
				$('*:checkbox').filter(':checked').parent().parent().addClass('checked');
			},
			'json'
		);
	});
	$('#following_select li.fc').click(function(){
		if ($(this).is('.checked'))
		{
			$(this).removeClass('checked');
			$(this).find('input').attr("checked", "");
		}
		else
		{
			$(this).addClass('checked');
			$(this).find('input').attr("checked", "checked");
		}
		
	});	
	$('#privacy-add-new').click(function(){
		$('.privacyNetworks div').removeClass('selected').removeClass('over');
		$('#following_select_panel').hide();
		$('#create-privacy-network').show();
	});

	$('#check_all').click(function(){
		$('#following_select_box input').attr('checked',1);
		$('li.fc').addClass('checked');
		return false;
	});

	$('#uncheck_all').click(function(){
		$('#following_select_box input').attr('checked',0);
		$('li.fc').removeClass('checked');
		return false;
	});

	$('#following_select_box .user_image a').click(function(){
		var checkbox = $(this).parent().parent().find('.assign');
		if (checkbox.attr('checked'))
			checkbox.attr('checked',0);
		else
			checkbox.attr('checked',1);
		return false;
	});

	$('#network_followings').submit(function(){
		$('#following_select_panel_loading').show();
		var $form = $(this);
		var ajaxOptions = {
			data: { ajax: true },
			success: function(response) {
				$('#following_select_panel_loading').hide();
				$('#following_select_panel .message').show();
			}
		};
		$form.ajaxSubmit(ajaxOptions);
		return false;
	});

	if ($('#network_followings_id').val() > 0)
	{
		$('#following_select_panel').show();
		$('#following_select_panel_loading').hide();
	}
});

// .photo_network ul li

$(document).ready(function() {
	$('.photo_network ul li').mouseover(function(){
		$(this).addClass('over');
	}).mouseout(function(){
		$(this).removeClass('over');
	}).click(function(){
		var li = $(this);
		$.get(
			'/ajax/change_private_network/' + $('.photo_network').attr('id') + '/' + $(this).attr('id') + '/',
			function(response) {
				$('.photo_network ul li').removeClass('selected');
				li.addClass('selected');
				$.jGrowl(__('Personal network has been changed'));
			},
			'json'
		);
		return false;
	});

	$('.photo_network ul, .reveal_edit_network').mouseover(function(){
		$('.photo_actions').removeClass('hidden');
		$('.photo_network').show();
	}).mouseout(function(){
		$('.photo_actions').addClass('hidden');
		$('.photo_network').hide();
	});

	$('.reveal_edit_network').click(function(){
		return false;
	});
	
	$('.message_subject_reply a').click(function(){
		if($('#'+$(this).attr('message_id')+':hidden').length){
			$('#'+$(this).attr('message_id')).show('slow');
			
				if($(this).attr('folder') == 'inbox')
			$('#reply').attr('value','Re: '+$(this).html());
		}
		else
		$('#'+$(this).attr('message_id')).hide('slow');
			
		return false;
	});

});


function enable_dayselect()
{
	if ($("#days-of-week input:checkbox").attr("disabled"))
		$("#days-of-week input:checkbox").attr('disabled', false);
	else 
		$("#days-of-week input:checkbox").attr('disabled', true);
}

//--------------------
//Private messages
$(document).ready(function() {
	$("#selectAllMessagesCheckbox").click(function() {
		$('.messagebox input:checkbox').attr('checked', $(this).attr('checked'));
	});
	
//	$("#deleteSelectedInbox").click(function() {
//		$("#messageActionForm").attr('action', '/messages/deleteselectedinbox');
//		$("#messageActionForm").submit();
//	});

	$("#deleteSelected").click(function() {
		
		if ($(".messagebox input:checkbox:checked").length < 1)
		{
			alert(__('Please, select messages'));
			return false;
		}
		if (confirm(__('Do you really want to delete selected messages')))
		{
			$("#messageActionForm").attr('action', '/messages/deleteselected');
			$("#messageActionForm").submit();
		}
		return false;
	});
	
	$("#deleteAll").click(function() {
	
		if (confirm(__('Do you really want to delete all messages?')))
		{
			$("#messageActionForm").attr('action', '/messages/deleteall/' + $(this).attr('folder'));
			$("#messageActionForm").submit();
		}
		return false;
//		if ($(".messagebox input:checkbox:checked").length < 1)
//		{
//			alert(__('Please, select messages'));
//			return false;
//		}
//		if (confirm(__('Do you really want to delete selected messages')))
//		{
//			$("#messageActionForm").attr('action', '/messages/deleteselected');
//			$("#messageActionForm").submit();
//		}
//		return false;
	});
	
	$("#markSelectedAsReaded").click(function() {
		
		if ($(".messagebox input:checkbox:checked").length < 1)
		{
			alert(__('Please, select messages'));
			return false;
		}
			
		if (confirm(__('Do you really want to mark selected messages as read?')))
		{
			$("#messageActionForm").attr('action', '/messages/markselectedasread');
			$("#messageActionForm").submit();
		}
		return false;
	});
	
	$("#newMessageSubmitButton").click(function() {
		$("#newMessageSubmitButton").attr('disabled', true);
		$("#newMessageForm").submit();
	});
	
	$("#replyMessageSubmitButton").click(function() {
		$("#replyMessageSubmitButton").attr('disabled', true);
		$("#replyMessageForm").submit();
	});
});

function deleteMessageConfirm()
{
		if (confirm(__('Do you really want to delete message?')))
			return true;
		else 
			return false;	
}



$(document).ready(function() {
	$('#nav_peoplew').hover(function() {
		$('#nav_people_menu').css('display', 'block');
		$('#nav_people')
			.css('background-image', 'url("'+image_url('people-button.png')+'")')
			.css('background-repeat', 'repeat');
	},
	function() {
		$('#nav_people_menu').css('display', 'none');
		$('#nav_people').css('background-image', 'url("'+image_url('nav-tabs2.png')+'")');
	});
});

$(document).ready(function() {
	$('#nav_explorew').hover(function() {
		$('#nav_explore_menu').css('display', 'block');
		$('#nav_tags')
			.css('background-image', 'url("'+image_url('explore-button.png')+'")')
			.css('background-repeat', 'repeat');
	},
	function() {
		$('#nav_explore_menu').css('display', 'none');
		$('#nav_tags').css('background-image', 'url("'+image_url('nav-tabs2.png')+'")');
		
	});
});

$(document).ready(function() {
	$('#show_invite_fb').click(function() {
		if (jQuery('#invite_form_fb').css('display') == 'block')
		{
			jQuery('#invite_form_fb').hide();
			jQuery('#invite_form_fb').css('display', 'none');
		}
		else if (jQuery('#invite_form_fb').css('display') == 'none')
		{
			jQuery('#invite_form_fb').show();
			jQuery('#invite_form_fb').css('display', 'block');
		}
	})
});


$(document).ready(function() {
	$('.landing_pic').click(function() {
			
	var src = $(this).attr('id');
	var filename = $(this).attr('filename');
	$('.landing_pic').css('outline', 'none');
	$(this).css('outline', '1px solid #FFFFFF');
	$(this).css('padding', '1px');
	$(this).css('margin', '-1px');

	elementId = src;
	src = filename;
	partOfElementId = elementId.toString().split("/").pop().replace(/_/g,' ');
	partOfElementId = partOfElementId.charAt(0).toUpperCase() + partOfElementId.slice(1);

	$("#fadeStreamingImage, #landingpage_photo_title").fadeOut(600, function() {
		//$("#landingpage_photo_title").fadeOut(600);
		var photoImage = new Image();
		$('.landing-page-image-loader').show();
		photoImage.onload = function() {
			$('.landing-page-image-loader').hide();
			$(".pic").attr('src', src);
			$('#landingpage_photo_link').attr('href', elementId);
			$('#fadeStreamingImage, #landingpage_photo_title').fadeIn(600);
			$('#landingpage_photo_title').html(partOfElementId);
		};
		photoImage.src = src;
	});

	$('#landingpage_photo_alt').attr('alt', $('#phototitle_'+partOfElementId).html());
		
	});
});

$(document).ready(function() {
	$(".gray_glass_login").focus(function() {
		$(".gray_glass_login").css('background-image', 'url("'+image_url('login-form-gray.png')+'")');
		$(this).css('background-image', 'url("'+image_url('login-form-yellow.png')+'")');
	});
	
});

$(document).ready(function() {
	$(".photos_list_userpic").live('hover',function(){$(this).hoverIntent(function() {
		$(this).find('.popup-wrapper').css('display', 'block');
		var h = $(this).find('.popup-wrapper').height();
		var w = $(this).find('.popup-wrapper').width();
		$(this).find('.popup-wrapper').css('top',33-h/2);
		$(this).find('.popup-wrapper').css('left',33-w/2);		
			
		$(this).find('.popup-wrapper').css('z-index', '1000');
		$(this).find('.popup-wrapper').animate({opacity: 1},500);
		$('#content').css('overflow','visible');
		$('#wrapper').css('overflow','visible');
		
		if (($(this).attr('class') == 'photos_list_userpic')){
			$(this).find('.popup-wrapper').css('top',-10);
			$(this).find('.popup-wrapper').css('left',-5);
		}
		
		if (($(this).attr('class') == 'search_result_border'))
			$(document).find('.search_result_border').css('z-index', '0');
		else
			$(document).find('.photo-block').css('z-index', '0');
		$(this).css('z-index', '10000');
		$(this).css('overflow','visible');
	},
	function() {
		var ua = navigator.userAgent.toLowerCase();
		isIE = (ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1);
		if (isIE == true)
			$(this).find('.popup-wrapper').css('display', 'none');
		$(this).find('.popup-wrapper').animate({opacity: 0},40);
		$(this).css('display', 'block');
		$(this).find('.popup-wrapper').css('z-index', '1');
		$('#content').css('overflow','hidden');
		$('#wrapper').css('overflow','visible');
		$(this).css('z-index', '0');
		$(this).css('overflow','');
	})})});
	
$(document).ready(function() {
	$(".search_result_border, .photo-block, .user_image, .photos_list_userpic").hoverIntent(function() {
		$(this).find('.popup-wrapper').css('display', 'block');
		var h = $(this).find('.popup-wrapper').height();
		var w = $(this).find('.popup-wrapper').width();
		$(this).find('.popup-wrapper').css('top',33-h/2);
		$(this).find('.popup-wrapper').css('left',33-w/2);		
			
		$(this).find('.popup-wrapper').css('z-index', '1000');
		$(this).find('.popup-wrapper').animate({opacity: 1},500);
		$('#content').css('overflow','visible');
		$('#wrapper').css('overflow','visible');
		
		if (($(this).attr('class') == 'photos_list_userpic')){
			$(this).find('.popup-wrapper').css('top',-10);
			$(this).find('.popup-wrapper').css('left',-5);
		}
		
		if (($(this).attr('class') == 'search_result_border'))
			$(document).find('.search_result_border').css('z-index', '0');
		else
			$(document).find('.photo-block').css('z-index', '0');
		$(this).css('z-index', '10000');
		$(this).css('overflow','visible');
	},
	function() {
		var ua = navigator.userAgent.toLowerCase();
		isIE = (ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1);
		if (isIE == true)
			$(this).find('.popup-wrapper').css('display', 'none');
		$(this).find('.popup-wrapper').animate({opacity: 0},40);
		$(this).css('display', 'block');
		$(this).find('.popup-wrapper').css('z-index', '1');
		$('#content').css('overflow','hidden');
		$('#wrapper').css('overflow','visible');
		$(this).css('z-index', '0');
		$(this).css('overflow','');
	});
});

$(document).ready(function() {
	$(".manage_photo_box").hover(function() {
		$(".manage_menu").css('display', 'block');
		$(".manage_gear").css('background', 'url("'+image_url('manage_menu_gears_border.gif')+'") #F5F5F5 no-repeat')
						.css('height', '13px');
		
	},
	function() {
		$(".manage_menu").css('display', 'none');
		$(".manage_gear").css('background', 'url("'+image_url('manage_menu_gears_border2.gif')+'") #F5F5F5 no-repeat')
						.css('height', '20px');
	});
	
});

function changeLanguage(result)
{
	if (result == true)
	{
		var selectedLanguage = $('#language_select input:radio:checked').attr('value');
		if (selectedLanguage != '')
			window.location = '/locale/'+ selectedLanguage;
	}
}

function changeNetwork(result)
{
	if (result == true)
	{
		var selectedNetwork = $('#network_select input:radio:checked').attr('value');
		var selectedGeoPrivacy = $('#geo_privacy input:radio:checked').attr('value');

		if (selectedNetwork != '')
		{
			$.get(
			'/ajax/change_private_network/' + $('.photo_network').attr('id') + '/' + selectedNetwork + '/' + selectedGeoPrivacy + '/',
			function(response) {
				$.jGrowl(__('Settings has been changed'));
			},
			'json'
		);
		return false;
		}		
	}
}

var isMessageCorrect = false;

function validateMessage(){
	if (isMessageCorrect)
		return true;
	var subject = $('#newMessageForm input[name="subject"]').val();
	var message = $('#newMessageForm textarea[name="message"]').val();
	var receiver = $('#newMessageForm input[name="recipient"]').val();
	var error = '';
	$.post(
		'/ajax/check_username',
  		{name : receiver},
  		function(json) {
    		if (json.validate == 0)
    		{
    			error = 'The Recipient field is required.<br/>';
    			if (subject == '') 
					error = error + 'The Subject field is required.<br/>';
				if (message == '') 
					error = error + 'The Message text field is required.<br/>';
    		}
    		else
    		{
    			if (subject == '') 
					error = error + 'The Subject field is required.<br/>';
				if (message == '') 
					error = error + 'The Message text field is required.<br/>';
    		}
    		if (error == '')
			{
				isMessageCorrect = true;
				$('#newMessageForm').submit();
				return true;
			}
			else
			{
				$('.info-block div.message').show();
				$('.message').html(error);
				return false;
			}
  		},
  		'json'
	);
	return false;
}

$(document).ready(function() {
	hideMenu = '';
	hideItemBackground1 = '';
	hideItemColor = '';
	hideItemWeight = '';
	hideMenu1 = '';
	hideItemBackground2 = '';
	hideItemColor1 = '';
	hideItemWeight1 = '';
	hideMenu2 = '';
	hideItemBackground3 = '';
	hideItemColor2 = '';
	hideItemWeight2 = '';
	timeOut = 10;
	hideItemBackground4 = '';
	hideItemBackground5 = '';
	hideItemBackground6 = '';
	var menu_margin = 287;
	var browser = navigator.userAgent.toLowerCase();

	

	
	$(".settings-menu-js").mouseover(function() {
		if (browser.indexOf("msie") != -1 && browser.indexOf("opera") == -1 && browser.indexOf("webtv") == -1){
			menu_margin = (parseInt($(document).width())-1008)/2-10;
		}
		else{
			menu_margin = (parseInt($(document).width())-1008)/2;
		}
		
		$('#settings-menu').addClass('menu-selected-item-new');
		$('#settings-menu span').addClass('menu-selected-item-new-span');
		$('#settings-menu a').css('color', '#cc520a');
//		$('#settings-menu a').css('font-weight', 'bold');
		$(".settings-menu-new").css('margin','-33px 0 0 ' + ($('#settings-menu').position().left - parseInt(menu_margin))+ 'px');
		$('.settings-menu-new .menu-top-border').css('width',142-$("#settings-menu").width());
	
		$(".settings-menu-new").show();
		clearTimeout(hideMenu);
		clearTimeout(hideItemBackground1);
		clearTimeout(hideItemBackground2);
		clearTimeout(hideItemColor);
		clearTimeout(hideItemWeight);
	});
	
	$(".settings-menu-js").mouseout(function() {
		
		hideItemBackground1 = setTimeout(function(){$('#settings-menu').removeClass('menu-selected-item-new')}, timeOut);
		hideItemBackground2 = setTimeout(function(){$('#settings-menu span').removeClass('menu-selected-item-new-span')}, timeOut);
		hideItemColor = setTimeout(function(){$('#settings-menu a').css('color', '#FFF7E0')}, timeOut);
		hideItemWeight = setTimeout(function(){$('#settings-menu a').css('font-weight', 'normal')}, timeOut);
		hideMenu = setTimeout(function(){$(".settings-menu-new").hide()}, timeOut);
	});
	
	$(".people-menu-js").mouseover(function() {
		if (browser.indexOf("msie") != -1 && browser.indexOf("opera") == -1 && browser.indexOf("webtv") == -1){
			menu_margin = (parseInt($(document).width())-1008)/2-10;
		}
		else{
			menu_margin = (parseInt($(document).width())-1008)/2;
		}
		
		
		$('#people-menu').addClass('menu-selected-item-new');
		$('#people-menu span').addClass('menu-selected-item-new-span');
		$('#people-menu a').css('color', '#cc520a');
//		$('#people-menu a').css('font-weight', 'bold');
		$(".people-menu-new").css('margin','-33px 0 0 ' + ($('#people-menu').position().left-parseInt(menu_margin))+ 'px');
		$('.people-menu-new .menu-top-border').css('width',142-$("#people-menu").width());
		$(".people-menu-new").show();

		clearTimeout(hideMenu1);
		clearTimeout(hideItemBackground3);
		clearTimeout(hideItemBackground4);
		clearTimeout(hideItemColor1);
		clearTimeout(hideItemWeight1);
		
	});
	$(".people-menu-js").mouseout(function() {
		hideItemBackground3 = setTimeout(function(){$('#people-menu').removeClass('menu-selected-item-new')}, timeOut);
		hideItemBackground4 = setTimeout(function(){$('#people-menu span').removeClass('menu-selected-item-new-span')}, timeOut);
		hideItemColor1 = setTimeout(function(){$('#people-menu a').css('color', '#FFF7E0')}, timeOut);
		hideItemWeight1 = setTimeout(function(){	$('#people-menu a').css('font-weight', 'normal')}, timeOut);
		hideMenu1 = setTimeout(function(){$(".people-menu-new").hide()}, timeOut);

	});
	
	$(".photos-menu-js").mouseover(function() {
		if (browser.indexOf("msie") != -1 && browser.indexOf("opera") == -1 && browser.indexOf("webtv") == -1){
			menu_margin = (parseInt($(document).width())-1008)/2-10;
		}
		else{
			menu_margin = (parseInt($(document).width())-1008)/2;
		}
		
		$('#photos-menu').addClass('menu-selected-item-new');
		$('#photos-menu span').addClass('menu-selected-item-new-span');
		$('#photos-menu a').css('color', '#cc520a');
//		$('#photos-menu a').css('font-weight', 'bold');
		$(".photos-menu-new").css('margin','-33px 0 0 ' + ($('#photos-menu').position().left-parseInt(menu_margin))+ 'px');
		$('.photos-menu-new .menu-top-border').css('width',142-$("#photos-menu").width());
		$(".photos-menu-new").show();
		clearTimeout(hideMenu2);
		clearTimeout(hideItemBackground5);
		clearTimeout(hideItemBackground6);
		clearTimeout(hideItemColor2);
		clearTimeout(hideItemWeight2);
		
	});
	$(".photos-menu-js").mouseout(function() {
		hideItemBackground5 = setTimeout(function(){$('#photos-menu').removeClass('menu-selected-item-new')}, timeOut);
		hideItemBackground6 = setTimeout(function(){$('#photos-menu span').removeClass('menu-selected-item-new-span')}, timeOut);
		hideItemColor2 = setTimeout(function(){$('#photos-menu a').css('color', '#FFF7E0')}, timeOut);
		hideItemWeight2 = setTimeout(function(){$('#photos-menu a').css('font-weight', 'normal')}, timeOut);
		hideMenu2 = setTimeout(function(){$(".photos-menu-new").hide()}, timeOut);
	});
});

$(document).ready(function() {
	$('.cart_item_quantity').keyup(function() {
		var cartId = this.id;
		var cost = $('#itemCost_' + cartId).html();
		var quantity = new Number(this.value);
		if (isNaN(quantity))
			return false;
		//the discount calculation
		var totalCost = cost * quantity;
		$('#itemAmount_' + cartId).html(totalCost.formatMoney(2, '.', ','));
		$('#cart-error-' + cartId).css('display', 'none');
		var obj = $('.cart-table-main');
		var totalCost = 0;
		for (i = 0; i < $('.cart-table-main').length; i ++)
		{
			var elementId = obj[i].id.substring(7);
			var quantity = $('#' + elementId).attr('value');
			var costPerItem = $('#itemPrice_' + elementId).html();
			var totalItemCost = quantity * costPerItem;
			totalCost = (totalItemCost) + totalCost;
		}
		$('#orderTotal').html(totalCost.formatMoney(2, '.', ','));
	});
});

$(document).ready(function() {
	$('#item_quantity').keyup(function() {
		var cost = $('#item_price').html();
		var quantity = new Number(this.value);
		if (isNaN(quantity))
			return false;
		//the discount calculation
		var totalCost = cost * quantity;
		$('#cart-error-image').css('display', 'none');
		$('#total_price span').html(totalCost.formatMoney(2, '.', ','));
	});
});

function setShowForm()
{
	$.ajax({
		url: '/ajax/writeshowmessageform',
		method: 'GET',
		cache: false,
		async: false,
		success: function() {return true;}});
}

function selectDeliveryType(obj)
{
	if ($(obj).attr('checked') == true)
	{
		$("input[name='delivery_type']").attr('checked', false);
		$(obj).attr('checked', true);
	}
}

function cancelDeactivation()
{
	if (confirm(__('Do you really want activate account?')) == true)
	{
		$("#cancel-deactivation-head").submit();
	}
	else
	{
		return false;
	}	
}

$(document).ready(function() {
	$('#settings-deactivate-account').click(function() {
		return confirm('Do you really want deactivate account');
	});
});

$(document).ready(function(){
	//alert();
	var length = 0;
	var width = $('#centerHeaderPart').width();
	var last_length = $('#centerHeaderPart li.last').width();
	
	$('#centerHeaderPart > *').each(function(){
		length += $(this).width();
	});
	length = length - last_length;
	
	//length = width - length - last_width;
	
	$('#centerHeaderPart li.last').css('width',(width - length - 4) + "px");
});

$(document).ready(function() {
	$('input[name="item_style"]').click(function() {
		var cost = $(this).attr('price');
		$('#item_price').html(cost);
		var quantity = new Number($('#item_quantity').attr('value'));
		if (isNaN(quantity))
			return false;
		//the discount calculation
		var totalCost = cost * quantity;
		$('#total_price span').html(totalCost.toFixed(2));
	});
});

$(document).ready(function() {
	$('#add-and-continue').click(function() {
		$('input[name="continue-browsing"]').attr('value', '1');
		$('#add-to-cart-form').submit();
	});
	
	$('#add-to-cart').click(function() {
		$('input[name="continue-browsing"]').attr('value', '0');
		$('#add-to-cart-form').submit();	
	});
});

$(document).ready(function() {
	$('.cart-remove').click(function() {
		return confirm('Do you really want to remove this item?');
	});
});

function calculatePriorCost()
{
	var price = $('.photo-style-selector label input:checked').attr('price');
	$('#item_price').html(price);
	var totalCost = $('#item_quantity').attr('value') * price;
	$('#total_price span').html(totalCost.formatMoney(2, '.', ','));
}

function calculatePriorTotal()
{	
	var obj = $('.cart-table-main');
	var totalCost = 0;
	for (i = 0; i < $('.cart-table-main').length; i ++)
	{
		var elementId = obj[i].id.substring(7);
		var quantity = $('#' + elementId).attr('value');
		var costPerItem = $('#itemPrice_' + elementId).html();
		var totalItemCost = quantity * costPerItem;
		$('#itemAmount_' + elementId).html(totalItemCost.formatMoney(2, '.', ','));
		totalCost = (totalItemCost) + totalCost;
	}
	$('#orderTotal').html(totalCost.formatMoney(2, '.', ','));
	
}

function numbersOnly(obj, e, dec) {
	var key;
	var keychar;

	if (window.event)
		key = window.event.keyCode;
	else if (e)
		key = e.which;
	else
		return true;
	keychar = String.fromCharCode(key);

	// control keys
	if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13)
			|| (key == 27))
		return true;
	// numbers
	else if ((("0123456789").indexOf(keychar) > -1))
		return true;

	// decimal point jump
	else if (dec && (keychar == ".")) {
		obj.form.elements[dec].focus();
		return false;
	} else
		return false;
}

Number.prototype.formatMoney = function(c, d, t){
	var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
	return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};


