// Globals variables
	var inviteLetterText = '';
// end

	$(document).ready(function() {

	    animateLeafes();
	    
	    // Fix png img 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-btn").livequery(function() { $(this).click(chooseGirl); });
	    // end

	    // Choose Lady Message
	    $(".girls-pages .next a").click(function() {
	        // Для финала конкурса
	        return;

	        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

	    // Add Friend
	    $('a[href="#add-friend"]').click(anotherFriendClick);
	    // end

	    // Remove Friend
	    $('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() > 2) {
					        $(this).find('a[href="#remove-friend"]').css('display', 'block');
					    }
					},
					function() {
					    $(this).find('a[href="#remove-friend"]').hide(300);
					}
				);
	    });
	    // 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');
	        $('.loading_photo').css('display', 'none');
	        $('#profile-' + ladyNumber).show();
	        return false;
	    });
	    // end

	    // View Photos in Profile
	    $('.girl-profile .photos li a').click(function() {
	        var bigPhoto = $(this).parents('.girl-profile').find('.big-photo');

	        $('.loading_photo').css('display', 'block');

	        $(bigPhoto).attr('src', $(this).children('img').attr('src').replace("s-", "b-")).each(function() {
	            if (this.complete) $('.loading_photo').css('display', 'none');
	        });

	        $(bigPhoto).load(function() {
	            $('.loading_photo').css('display', 'none');
	        });
	    });
	    // 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 = 600;
	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).hasClass('voted'))
		return false;

	var girlNumber = ($(this).attr('value') - 1) % 3 + 1;

	var vote = $('#profile-' + girlNumber + ' .vote-btn, ' + '#girl-' + girlNumber + ' .vote-btn');
	
	if (vote.hasClass('voted')) return false;
	
	vote.hide();
	
	var spinner = $('#girl-' + girlNumber + ' .loading, #profile-' + girlNumber + ' .loading');
	
	spinner.css('display', 'block');
	
	var self = $(this);
	
	$.ajax({
		type: "POST",
		url: "/vote",
		data: ({ "contestant-id": self.attr('value') }),
		dataType: "html",
		success: function(data, textStatus) {
			var voted = $('.voted:not(#profile-' + girlNumber + ' .voted)');
			voted.addClass('vote-btn');
			voted.removeClass('voted');

			spinner.css('display', 'none');

			$('#girl-' + girlNumber + ' .girl-profile .voting span').addClass('voted');

			vote.addClass('voted');
			vote.removeClass('vote-btn');
			vote.show();

			$('.extra').css('display', 'none');

		$.ajax({
			type: "POST",
			url: "/getvotes",
			data: ({ "contestant-id": self.attr('value') }),
			dataType: "html",
			success: function(data, textStatus) {
				$('#profile-' + girlNumber + ' .extra strong,'
				+ ' #girl-' + girlNumber + ' .extra strong').html(data);
				$('#profile-' + girlNumber + ' .extra,' 
				+ ' #girl-' + girlNumber + ' .extra').css('display', 'block');
				}
			});
		}
	});

	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();
	}
	
	// Validation
		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;
};

function animateLeafes() {
    if (!($.browser.msie && $.browser.version <= 6.0)) {
        wd = document.body.clientWidth;

        $("body").mousemove(function(e) {
            $(".bg-right").css("right", wd / 960 - 20 - (e.pageX - wd / 2) / 128);
            $(".bg-right-b").css("right", wd / 960 - 20 + (e.pageX - wd / 2) / 64);
            $(".bg-left-1").css("left", wd / 960 - 20 - (e.pageX - wd / 2) / 128);
            $(".bg-left-2").css("left", wd / 960 + 100 + (e.pageX - wd / 2) / 128);
            $(".bg-left-2").css("left", wd / 960 + 100 + (e.pageX - wd / 2) / 128);
        });
    }
};
