// Globals variables
	var inviteLetterText = '';
// end

$(document).ready(function() {
	// Ротация девушек на главной странице
		var
			selectorItem = $('#main-page .lady-selector ul li div'),
			ladyBlockItem = $('#main-page #lady-block li');
		
		var randomItem = Math.floor(Math.random() * ladyBlockItem.size());
		$('#main-page #lady-block li:eq(' + randomItem + ')').fadeIn(500);

		selectorItem.mouseenter(function() {
		
			var lady = $(this).parent().attr('class');

			$('#main-page #lady-block li:not(.' + lady + ')').hide();
			$('#main-page #lady-block').find('.' + lady).fadeIn(300);
		});
	// end
	
	// Обработка png изображений в ie6
		$(function() {
			if ($.browser.msie) {
				var pix = '/img/transparent.gif';

				$.fn.fixpng = function() {
					return this.each(function() {
						var image = this.src ? this.src : this.style.backgroundImage.substring(4, this.style.backgroundImage.length - 1);
						this.style.backgroundImage = 'none';
						this.src = pix;
						this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + image + "',sizingMethod='scale')";
					});
				};

				$('img.png').fixpng().each(function() {
					$(this).bind('load readystatechange', function(e) {
						if (this.complete || (this.readyState == 'complete' && e.type == 'readystatechange')) {
							if (!this.src.match(/\.png$/i))
								return;

							$(this).fixpng();
						}
					});
				});

				// ie6 flickering fix
				document.execCommand('BackgroundImageCache', false, true);
			}
		});
	// end
	
	// Voting
		$(".vote-cont").livequery(function() { $(this).click(chooseGirl); });
	// end
	
	// Choose Lady Message
		$("a.vote-blockable").click(function() {
			
			if ($('.voted').length <= 0) {
				$('#choose-girl-message').show();
				return false;
			}
		});
	// end

	// Winner's video overlay
		$('a[href="#view-winner-video"]').click(function() {
			$('#winner-video').show();
			return false;
		});

		$('a[href="#view-first-runner-up-video"]').click(function() {
			$('#video-second').show();
			return false;
		});

		$('a[href="#view-second-runner-up-video"]').click(function() {
			$('#video-third').show();
			return false;
		});
	// end

	// Invites
		// Open Invite popup
			$('.invite-popup-link').click(function() {
				showInvite($(this).attr('href'));
				return false;
			});
		// end

		// добавление адресата
			$('a[href="#add-friend"]').click(anotherFriendClick);
		// end
		
		// удаление адресата
			$('a[href="#remove-friend"]').livequery(function() {
				$(this).click(removeFriendClick);
			});
		// end
		
		// Delete Icon
			$('#invite-block .friends tr').livequery(function() {
				$(this).hover(
					function(){
						if ($('#invite-block .friends tr').size() > 3 )
						{
							$(this).find('a[href="#remove-friend"]').show();
						}
					},
					function(){
						$(this).find('a[href="#remove-friend"]').hide();
					}
				);
			});
		// end
		
		$("input#invite-name").change(inviteLetterChange).keyup(inviteLetterChange);
		
		inviteLetterText = $("#invite-block textarea.letter").val();
		
		$("input#sendemail-manualy").click(sendEmailManClick);
	// end

	// View Profile
		// Open Profile
			$('a[href="#view-profile"]').click(function() {
				var ladyNumber = $(this).attr('value');
				$('#profile-' + ladyNumber).show();
				return false;
			});
		// end

		// View Photos in Profile
			$('.girl-profile .photos-list li a').click(function() {
				var bigPhoto = $(this).parents('.girl-profile').find('.big-photo');
				$(bigPhoto).attr('src', $(bigPhoto).attr('src').replace(/([/\\\w\s]*\/)([\w\s]+)(.[\w\d]{2,4})/i, "$1" + $(this).attr('value') + "$3"));
			});
		// end
	// end

	// Hide Overlay Content
		$("body").keyup(function(event) {
			if (event.keyCode == 27) {
				HideOverlayContent();
			}
		});

		$('.overlay, .overlay-content a[href="#close-overlay"]').click(function() {
			HideOverlayContent();
		});
	// end
	
	// Close Popup Window
		$('a[href="#close-popup"]').click(function() {
			window.close();
		});
	// end
});

function HideOverlayContent() {
	$('.overlay-content').hide();
	return false;
};

function inviteLetterChange() {
	$('textarea.letter').val(inviteLetterText.replace("%%user's name%%", $(this).val()));
};

function showInvite(href) {
	wd = 600;
	hg = 650;
	var lf = screen.availWidth / 2 - wd / 2;
	var tp = screen.availHeight / 2 - hg / 2;

	window.open(href, 'invite', 'width=' + wd + ',height=' + hg + ',top=' + tp + ',left=' + lf + ',toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,directories=no,status=no');
};


function chooseGirl() {
	if ($(this).parent('span').hasClass('voted'))
		return false;

	var girlNumber = ($(this).attr('value') - 1) % 5 + 1;

	var vote = $('#profile-' + girlNumber + ' .vote-cont, ' + '#lady-' + girlNumber + ' .vote-cont').parent('span');
	if (vote.hasClass('voted')) return false;
	vote.removeClass('vote voting voted').addClass('voting');

	var spinner = $('#lady-' + girlNumber + ' .loading, #profile-' + girlNumber + ' .loading');
	spinner.show();
	
	var self = $(this);
	
	$.ajax({
		type: "POST",
		url: "/vote",
		data: ({ "contestant-id": self.attr('value') }),
		dataType: "html",
		success: function(data, textStatus) {
			var voted = $('.voted');
			voted.addClass('vote');
			voted.removeClass('voted');

			spinner.hide();

			//$('#lady-' + girlNumber + ' .voting span').addClass('voted');

			vote.removeClass('voting');
			vote.addClass('voted');


			$.ajax({
				type: "POST",
				url: "/getvotes",
				data: ({ "contestant-id": self.attr('value') }),
				dataType: "html",
				success: function(data, textStatus) {
				}
			});
		}
	});

	return false;
}

function sendEmailManClick() {
	$('.name-validation').hide();
	$('.email-validation').hide();
	var formdata = $('.form-content form').serialize();
	var self = $(this);
	var valid = true;

	if ($('ul.form #invite-name').attr('value') == '') {
		valid = false;
		$('.name-validation').show();
	}

	var re = /\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b/gi;

	if ($('ul.form #invite-email').val() == '' ||
		!$('ul.form #invite-email').val().match(re)) {
		valid = false;
		$('.email-validation').show();
	}
	
	// Валидация полей таблицы с друзьями
		if ($('table.friends input.email[value!=]').length == 0) {
			valid = false;
			$('#emails-validation').show();
		} else {
			$.each($('table.friends input.email[value!=]'), function() {
				if (!$(this).val().match(re)) {
					valid = false;
					$('#emails-validation').show();
				}
			});
		}
	// end

	if (valid) {
		$.ajax({
			type: "POST",
			url: "/sendemail",
			data: formdata,
			success: function(data) {
				showInviteFormClose();
			}
		});
	}

	return false;
};

function showInviteFormClose() {
	$('.form-content').hide();
	$('.result-block').show();
}

function anotherFriendClick() {
	$('#invite-block table.friends tr.template').clone().removeAttr('class').appendTo('#invite-block table.friends');

	return false;
};

function removeFriendClick() {
	$(this).parents('#invite-block table.friends tr').remove();

	return false;
};
