var mount = $('<div id="mount" class="overlay" /><div id="cont-overlay" class="overlay" />');
var inviteLetterText;
var bearMessage = 1;

function showInvite(href) {
	wd = 670;
	hg = 890;
 	var lf = screen.availWidth/2 - wd/2;
	var tp = screen.availHeight/2 - hg/2;
	
	window.open(href,'_blank','width='+wd+',height='+hg+',top='+tp+',left='+lf+',toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,directories=no,status=no');
};

function removeVote(girlNum) {
    $("#girl-" + girlNum + " .vote_me_cont").html("");
    setTimeout("generateVote()", 200);
};

function generateVote() {
    var randomVar = Math.floor((Math.random() * 5) + 1);
    $("#girl-" + randomVar + " .vote_me_cont").html("<div id=\"vote_me\"></div>");
    setTimeout("removeVote(" + randomVar + ")", 1500);
};

$(document).ready(function() {

    generateVote();

    inviteLetterText = $('.letter').val();

    $("div#main-second").hide();
    $("div#main-first").addClass("active");

    $("img.cont-pic").livequery(contPicLiveClick);
    $("input.vote").livequery(voteLiveClick);
    $("input#send-comment").livequery(sendCommentLiveClick);
    $("input#getemail").livequery(getEmailLiveClick);
    $("input#sendemail-automaticaly").livequery(sendEmailAutoLiveClick);
    $("input#sendemail-manualy").livequery(sendEmailManLiveClick);

    $('#another-friend').livequery(anotherFriendLiveClick);
    $('a#remove-friend').livequery(removeFriendLiveClick);

    $('#close-bear-message').click(function() {
        $.ajax({
            type: "GET",
            url: "/hidebearmessage"
        });

        $("#bear-message").fadeOut("slow");
    });

    $("div#oldmap-container .close-popup a").livequery(function() {
        $(this).click(function() {
            mount.eq(0).remove();
            mount.eq(1).remove();
            document.location.href = '#' + $(this).attr("href").substr(1);
            return false;
        });
    });

    $(".choose-girl").livequery(function() {
        $(this).click(function() {
            var self = $(this);
            if (self.hasClass('voted')) return false;
            self.hide();

            var girlNumber = (self.attr('value') - 1) % 5 + 1;
            var spinner = $('#girl-' + girlNumber + ' span.wait');
            spinner.show();

            $.ajax({
                type: "POST",
                url: "/vote",
                data: ({ "contestant-id": self.attr('value') }),
                dataType: "html",
                success: function(data, textStatus) {
                    var voted = $("span.choose-girl.voted");
                    voted.removeClass('voted');
                    voted.addClass('vote');
                    spinner.hide();
                    self.removeClass('vote');
                    self.addClass('voted');
                    self.show();
                }
            });

            return false;
        });
    });

    $(".beaches .next a").livequery(function() {
        $(this).click(function() {
            var girls = $('.choose-girl.voted');
            //if (girls.length < 1) {
            //    $('#choose-girl-message-popup').show();
            //    return false;
            //}
        });
    });

    $("input.invite-name").change(inviteLetterChange);
    $("input.invite-name").keyup(inviteLetterChange);

    $("a#hide-comment-popup").livequery(function() {
        $(this).click(function() {
            $('div#choose-girl-message-popup').hide();
            return false;
        });
    });

    $('.close').livequery(function() {
        $(this).click(function() {
            $('#choose-girl-message-popup').hide();
            return false;
        });
    });

    $('a.show-invite').livequery(function() {
        $(this).click(function() {
            showInvite($(this).attr('href'));
            return false;
        });
    });

    $("a#show-comment-popup").livequery(function() {
        $(this).click(function() {
            $('div#comment-popup').show();
            return false;
        });
    });

    $("a#hide-comment-popup").livequery(function() {
        $(this).click(function() {
            $('div#comment-popup').hide();
            $('div.form').show();
            $('p.result').hide();
            return false;
        });
    });

    $("a.invite-automaticaly-link").livequery(function() {
        $(this).click(function() {
            $('div#invite-automaticaly-container').show();
            $('div#invite-manualy-container').hide();
            return false;
        });
    });

    $("a.invite-manualy-link").livequery(function() {
        $(this).click(function() {
            $('div#invite-manualy-container').show();
            $('div#invite-automaticaly-container').hide();
            return false;
        });
    });

    $('a.video-img').livequery(function() {
        $(this).click(function() {
            $(this).hide();
            $('div.video').show();
            return false;
        });
    });

    $('a.invite-service').livequery(function() {
        $(this).click(function() {
            var value = $(this).attr('value');
            var select = $('select.invite-service');
            select.find('option').eq(value).attr('selected', 'selected');
            return false;
        });
    });

    $('input#select-all-contacts').change(function() {
        $('input.checkbox-friend')
			.attr('checked', $(this).attr('checked'));
    });

    $('div.close-form .close').livequery(function() {
        $(this).click(function() {
            window.close();
            return false;
        });
    });
});

function inviteLetterChange() {
	$('.letter').val(inviteLetterText.replace('[%%FirstName%%]', $(this).val()));
};

function dynLiveClick() {
	var right = $(this).hasClass("right");

	$(this).click(function() {
		var href = $(this).attr("href");
		document.location.href = '#' + href.substr(1);

		var oldContainer = $("div#main-first");
		var newContainer = $("div#main-second");

		if (!oldContainer.hasClass("active")) {
			oldContainer = $("div#main-second");
			newContainer = $("div#main-first");
		}

		if (!oldContainer.hasClass("active"))
			alert("Old div has not active class!");

		oldContainer.removeClass("active");
		newContainer.addClass("active");

		newContainer.load(href, null, function() {
			$('div#overlay-spinner').hide();
			if (right) {
				newContainer.show('slide', { direction: 'left' }, 1000);
				oldContainer.hide('slide', { direction: 'right' }, 1000);
			}
			else {
				newContainer.show('slide', { direction: 'right' }, 1000);
				oldContainer.hide('slide', { direction: 'left' }, 1000);
			}
			oldContainer.empty();
		});

		$('div#overlay-spinner').show();
		return false;
	});
};

function girlLiveClick() {
	$(this).click(function() {
		var c = new $.cookie();
		c.voted = voted;
		c.cookieID = 'voted';
		c.set();
		
		alert(beachNumber);
		return false;
	});
}

function contPicLiveClick() {
	$(this).click(function() {
		$("div.main img").attr("src", $(this).attr("src").replace("_prev", ""));
		return false;
	});
};

function voteLiveClick() {
	$(this).click(function() {
		var self = $(this);
		self.hide();
		self.removeClass('vote');

		var divSel = $('div.vote-spinner');
		divSel.show();

		$.ajax({
			type: "POST",
			url: "/vote",
			data: ({ "contestant-id": $("input#contestant-id").val() }),
			dataType: "html",
			success: function(data, textStatus) {
				divSel.hide();
				self.addClass("voted");
				self.attr("disabled", "disabled");
				self.show();
			}
		});

		return false;
	});
};

function sendCommentLiveClick() {
	$(this).click(function() {

		var data = $('form#send-comment-form').serialize();

		var valid = true;

		if ($('#comment-email').attr('value') == '') {
			valid = false;
			$('#email-validataion').show();
		}

		if (valid == true) {
			$.ajax({
				type: "POST",
				url: "/comment",
				data: data,
				success: function(data, textStatus) {
					$('div.form').hide();
					$('p.result').show();
				}
			});
		}

		return false;
	});
}

function getEmailLiveClick() {
	$(this).click(function() {
		$('.name-validation, .login-validation, .password-validation').hide();
		var error = $('#invite-error');
		var spinner = $('#friends-spinner');
		var initText = $('#friends-init-text');
		var inputs = $('div#invite-automaticaly-container input#invite-name,' +
			' input#invite-login, input#invite-password, select.invite-service');
		error.hide();

		var valid = true;

		if ($('#invite-name').attr('value') == '') {
			valid = false;
			$('.name-validation').show();
		}

		if ($('#invite-login').attr('value') == '') {
			valid = false;
			$('.login-validation').show();
		}

		if ($('#invite-password').attr('value') == '') {
			valid = false;
			$('.password-validation').show();
		}

		if (valid) {
			var table = $('div#invite-automaticaly-container div form#send-email table#friends-content');
			var row = $('<tr><td class="col-1"><input type="checkbox" class="checkbox-friend" name="contactId" value="" /></td>' +
									'<td class="col-2"></td>' +
									'<td></td></tr>');

			var self = $(this);
			var formdata = $('div#invite-automaticaly-container div form#get-email').serialize();

			initText.hide();
			spinner.show();

			$.ajax({
				type: "POST",
				url: "/getemail",
				data: formdata,
				dataType: "json",
				success: function(data) {
					for (i = 0; i < data.length; i++) {
						row.find('td').eq(0).find('input').attr('value', data[i].Id);
						row.find('td').eq(1).html(data[i].Name);
						row.find('td').eq(2).html(data[i].Email);
						table.append(row.clone());
					}

					$("input#sendemail-automaticaly").removeAttr('disabled');
					$("input#sendemail-automaticaly").attr('src', '/img/invite-friends-form/invite-friends-active.jpg');
				},
				error: function() {
					error.show();
					self.attr("src", "/img/invite-friends-form/chose-btn-active.gif");
					self.removeAttr("disabled");
					inputs.removeClass('waiting');
					inputs.removeAttr("disabled");
				},
				complete: function() {
					spinner.hide();
				}
			});

			inputs.addClass('waiting');
			inputs.attr('disabled', 'disabled');
			self.attr("src", "/img/invite-friends-form/chose-btn.gif");
			self.attr("disabled", "disabled");
		}

		return false;
	});
};

function sendEmailAutoLiveClick() {
	$(this).click(function() {
		if($('input.checkbox-friend:checked').length < 1 )
			return false;

		var formdata = $('div#invite-automaticaly-container form#send-email').serialize();
		var self = $(this);

		$.ajax({
			type: "POST",
			url: "/sendemail",
			data: formdata,
			success: function(data) {
				showInviteFormClose();
			}
		});

		self.attr('src', "/img/invite-friends-form/invite-friends.jpg");
		self.attr("disabled", "disabled");
		return false;
	});
};

function sendEmailManLiveClick() {
	$(this).click(function() {
		$('.name-validation').hide();
		$('.email-validation').hide();
		var formdata = $('div#invite-manualy-container div.form-content form').serialize();
		var self = $(this);
		var valid = true;

		if ($('ul.form.manual #invite-name').attr('value') == '') {
			valid = false;
			$('.name-validation').show();
		}

		var re = /\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b/gi;

		if ($('ul.form.manual #invite-email').val() == '' ||
			!$('ul.form.manual #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();
				}
			});
		}
		
		if (valid) {
			$.ajax({
				type: "POST",
				url: "/sendemail",
				data: formdata,
				success: function(data) {
					showInviteFormClose();
				}
			});

			self.attr('src', "/img/invite-friends-form/invite-friends.jpg");
			self.attr("disabled", "disabled");
		}

		return false;
	});
};

function showInviteFormClose() {
	$('div.form-content').hide();
	$('div.close-form').show();
}

function anotherFriendLiveClick() {
	$(this).click(function() {
		var row = $('<tr class="last"><td><input type="text" class="txt" name="name" value="" />' +
			'</td><td><input type="text" class="txt email" name="email" value="" /><a href="" title="Delete" id="remove-friend">' +
			'<img src="/img/invite-friends-form/delete.gif" alt="Delete" /></a></td></tr>');

		$('#invite-manualy-container form#send-email table.friends tr:last a').remove();

		$('#invite-manualy-container form#send-email table.friends').append(row);

		return false;
	});
};

function removeFriendLiveClick() {
	$(this).click(function() {
		var deleteBtn = '<a href="" title="Delete" id="remove-friend">' +
			'<img src="/img/invite-friends-form/delete.gif" alt="Delete" /></a>';

		$('#invite-manualy-container form#send-email table.friends tr:last').remove();

		$('#invite-manualy-container form#send-email table.friends tr:last td:last').append(deleteBtn);

		return false;
	});
};
