var our_tab=true;
var ie_version = false;
$(document).ready(function(){
	mainpage_basics();
	myship_basics();
	//setInterval(refreshClock, 60000);
	scroll();
	$('#feedback').css('top', $(window).height()/2-50+'px');
	$("#select_rank_cancel").live("click", function(){
		$("#modal_window").dialog("close"); 
	});
	
	$("#feedback").parent().click(function(){
		var url = $(this).attr('href');
		$.get(url, function(data){
			$(data).sendMessage();
		});
		return false;
	});
    
        $('.help_button').live('click',function(){
	    $(this).siblings('.help_message').toggle();
	});
    
	$('.help_message').live('mouseleave', function(){
	    $(this).hide();
	});
	
	/*
	$("#report-error > form").submit(function(){
		var data = $(this).serialize();
		var url = $(this).attr('action');
		var f = $(this);
		$(this).find('input,textarea,button').attr('disabled', 'disabled');
		$.ajax({
			url: url,
			data: data,
			dataType: 'json',
			type: 'POST',
			success: function(d){
				if(d['success']){
					f.parent().html('<span style="color:#1A9B00;font-size: 13px;">OK</span>');
				}
			}
		});
		return false;
	});*/
	
	$('#report-error-show').click(function(){
		    var new_report = $(this).next().clone();
		    
		    $(new_report).confirmBox({

			    okCondition: function()
			    {
				var message = $(new_report).find('textarea[name=report_content]').val();
				if ((message=='')||(message=='Tell us what is problem'))
				{
				    $(new_report).find('textarea[name=report_content]').animate({
				    borderTopColor: "red", borderLeftColor:"red", borderRightColor:"red", borderBottomColor:"red"
				    }, 100);
				    return false;
				}
				else
				    return true;
			    },
			    callback: function(){
				var f = $(new_report).find('form');
				var data = $(f).serialize();
				var url = $(f).attr('action');
				$(f).find('input,textarea,button').attr('disabled', 'disabled');
				$.ajax({
				    url: url,
				    data: data,
				    dataType: 'json',
				    type: 'POST',
				    success: function(d){
					if(d['success'])
					{
					    q=$('.ok-box').clone();
					    q.confirmBox({
						callback: function(){
						q.remove();
						}
					}
				    );
				}
			    }
			    });
			    return false;
			}
		    });

	});
	
	//$('#logout-info').css('right', ($('body').width()/2 - $('#navigation').width()/2)+'px');
}); 

function myship_basics(){
    
    if (/*@cc_on!@*/false) { // check for Internet Explorer
	document.onfocusin = function(){our_tab=true;};
	document.onfocusout = function(){our_tab=false;};
    } else {
	window.onfocus = function(){our_tab=true;};
	window.onblur = function(){our_tab=false;};
    }
    
    ie_version = 999; // we assume a sane browser
    if (navigator.appVersion.indexOf("MSIE") != -1)
      // bah, IE again, lets downgrade version number
      ie_version = parseFloat(navigator.appVersion.split("MSIE")[1]);  
    
    $('.text_input').hint().focus(function(){
    	$(this).addClass('text_input_clicked');
    });
    
    $('.text_input').blur(function(){
    	$(this).removeClass('text_input_clicked');
    });  

    $("#rank_proposition, #shiptype_proposition, #url_proposition").live('click', function(){
        var box = $(this).siblings('.confirm_box').clone();
        box.confirmBox({
	    callback : function(){
	        $.post('/main/proposition', {
		    subject : box.find('input[type=hidden]').val(),
		    content : box.find('input[type=text]').val()
		}, function(response){
		    $(response).confirmBox();
	        });
	    },
		okCondition : function() {
		    return box.find('input[type=text]').val().length > 0;
		}
	});
	return false;
    });
    
    $('input').filter(function(index){
	    	return  $(this).attr('type') == 'button' || $(this).attr('type') == 'submit';
	    }).css('cursor', 'pointer');
    
    $('textarea').autoResize();
    
    $('#passrec_dialog').dialog({
    	autoOpen: false,
    	modal: true,
    	width: 800,
    	height: 500,
    	dialogClass: "pass_rec_dialog",
    	resizable: false,
    	title: $('#passrec_title').val(),
	close: function(){
	    var log_in = $(this).find('input[id="force_reload"]').val();
	    if(log_in=="intro")
		window.location.replace("/info/supercrewing");  //default wall page
	    if(log_in=="true")
		window.location.replace("/");  //default wall page
	}
    });
    
    $('.pass_forgot').click(function(){
    	$('#passrec_dialog').dialog('open');
    	return false;
    });

    $('#passrec_dialog > .close_dialog').live('click',function(){
	$('#passrec_dialog').dialog("close");
    })
    
    $('#passrec_form').live('submit',function(){
    	var valid = true;
    	if($("#passrec_newpass").length > 0)
    	{
	    	$("#passrec_newpass").keyup();
			$("#passrec_retypepass").keyup();
			
			var valid = ($("#passrec_newpass").val().length >= 6 && $("#passrec_retypepass").val() == $("#passrec_newpass").val());
			if( ! valid)
				$('#change-pass').prev().show();
    	}
    	else if($('#login_or_id').length > 0)
    	{
    		valid = $('#login_or_id').val().length > 0;
    	}
    	 	

    	if(valid)
    	{
	    	$.post(
	    		$(this).attr('action'),
	    		$(this).serialize(),
	    		function(data){
	    			$('#passrec_dialog').html($(data).html());
				setTimeout(function(){
				    $('#passrec_dialog').delay(2000).dialog("close");
				}, 3000);		
	    		}
	    	);
    	}
    	return false;
    });
    
    if($('#passrec_open').length && $('#passrec_open').val() == "1")
    	$('#passrec_dialog').dialog("open");
    
    $('#new-comment textarea').live('focus', function(){
		if($(this).val() == $(this).attr('hint'))
		{
			$(this).val('');
			$(this).siblings('p').show();
			$(this).css('color', '#000000');
		}
	});	
	$('#new-comment textarea').live('blur', function(){
		if($(this).val().length == 0)
		{
			$(this).val($(this).attr('hint'));
			$(this).siblings('p').hide();
			$(this).css('color', '#0d7fbd');
			$(this).height(25);
		}
	});	
    
    $('#new-comment input[type=button]').live('click', function(){
		var f = $(this).parents('form:first');
		f.append($('#wall_type').clone());
		var d = $(f).serialize();
		f.find('#wall_type').remove();
		var new_comment = $(this).parents('#new-comment');
		$.post(
			$(f).attr('action'),
			$(f).serialize(),
			function(data){
				data = $(data);
				console.log(data.length);
				if(data.length > 1) {
				    var box = data[0];
				    data = data[1];
				    console.log(box);
				    $(box).confirmBox();
				} 
				if($(data).is('.confirm_box')) {
					$(data).confirmBox();
				} else {
					var old_first = $('.comment:first'); 
					$(new_comment).siblings('.comment:first').css('margin-top', '1px').children('img').hide();
					if($(new_comment).siblings('.comment:first').length)
						$(new_comment).siblings('.comment:first').before($(data));
					else
						$(new_comment).before($(data));
					var h = $(data).height();
					$(data).height(0).css('display', 'block').animate({height: h+"px"}, 100, function(){$(data).css('height', 'auto');});
					if($('#comments').length == 1)
						$('html, body').animate({scrollTop:$('#comments').offset().top}, 300);
					old_first.height(old_first.height()+1);
					old_first.height(old_first.height()-1);
				}
			}
		);
		
		f.find('textarea').val('');
		
		return false;
	});
    
    $('.delete-profile-comment').live('click', function(){
    	var link = $(this);
    	var q = $(this).parents('.comment').siblings('.delete-comment-question').clone();
    	q.msgBox('create', {
    		title: q.find('input[name=title]').val()
    	});
    	q.msgBox('open',{
    		okCallback: function(){
    			$.get(
			   		$(link).attr('href'),
			   		function(){
			   			var parent = $(link).parents('.comment:first');
		   				$(parent).remove();
		   				$('.comment:first').css('margin-top', '13px').children('img').show();
			   		}
    			);
    		}
    	});
    	
    	return false;
    });
    
    //$('.delete_comment_question').msgBox('create', {
    //	title: $(this).find('input[name=title]').val()
    //});
    
    $('.comment-blocked').siblings('textarea').focus(function(){
    	window.location = $(this).parents('form').attr('action');
    	$(this).parents('form').find('textarea, input, button').attr('disabled', 'disabled');
    });
    
    if($('.comment-blocked').length == 0 && $('.new-comment-action').length > 0){
    	$.scrollTo('#comments', 500);
    	$('.new-comment-action').siblings('textarea').focus();
    }
    
    $('.unban-request-link').live('click', function(){
    	$.get($(this).attr('href')); 
    	$(this).parents('.confirm_box').find('.yes-btn').click();
    	return false;
    });
}


function clientHeight() {
    var height = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
	    	//Non-IE
	    	height = window.innerHeight;
    	}
    	else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    		//IE 6+ in 'standards compliant mode'
    		height = document.documentElement.clientHeight;
    	}
    	else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    		//IE 4 compatible
    		height = document.body.clientHeight;
    	} 
    return height;
}

function refreshClock()
{
	$.getJSON($('#footer-right_select > input:eq(2)').val(), function(data){
		$('#footer-datetime > span:eq(0)').text(data.time);
		$('#footer-datetime > span:eq(1)').text(data.date);
	});
}

function mainpage_basics()
{
	var images_amount = 5;
	var hilighted_image = Math.ceil(images_amount/2)-1;
	scroller_left = 0;
	
	update_active_photo(hilighted_image);
	scroll();
	
	$("#scroller-left").click(function(){
		clearTimeout(scroller_timer);
		scroller_timer = setTimeout(scroll, scroller_timeout);
		$("#scroller").stop(true, true);
		update_last_photo(hilighted_image);
		var elem = $(".slider-sailors:last").clone();
		$(".slider-sailors:first").before(elem);
		$(".slider-sailors:last").remove();
		$('#scroller').css("left", "-190px");
		$('#scroller').animate({left : 0}, {complete: function(){
			update_active_photo(hilighted_image);
		}, duration:"slow"});
	});
	
	$("#scroller-right").click(function(){
		clearTimeout(scroller_timer);
		scroller_timer = setTimeout(scroll, scroller_timeout);
		$("#scroller").stop(true, true);
		update_last_photo(hilighted_image);
		var elem = $(".slider-sailors:first").clone();
		$(".slider-sailors:last").after(elem);
		$('#scroller').animate({left : -190}, {complete: function(){
			$(".slider-sailors:first").remove();
			$('#scroller').css("left", "0px");
			update_active_photo(hilighted_image);
		}, duration:"slow"});
	});
	
	$('.top-btn').live('click',function(){
		window.location.href="#header";
	});
	
	$('#joinustop a').hover(function(){
		$(this).find('img').css('margin-top', '-46px');
	}, function(){
		$(this).find('img').css('margin-top', '0px');
	});
	
	$('.hidden-email').live('click', function(){
	    var mail = $(this).attr('part') + "@myship.com";
	    $(this).html(mail)
		.removeAttr('part').removeClass('hidden-email')
		.attr('href', 'mailto:' + mail);
	    return false;
	});
}

function update_active_photo(image_no)
{
	var elem = $(".slider-sailors:eq("+image_no+")");
	$(elem).find('.slider-sailor-photo').animate({'width':'100px','height':'100px'});
	$(elem).find('.slider-sailor-photo').find('img').animate({'width':'100px','height':'100px'});
	$(elem).find('.slider-sailor-background').animate({'width':'112px','height':'112px'});
	$(elem).find('.slider-sailor-background').find('img').animate({'width':'112px','height':'112px'});
	$(elem).find('.slider-sailor-photo').css('right', '14px');
	if($(elem).find('input').length && $(elem).find('input').val().length){
		$('.scroller-cloud-middle').text($(elem).find('input').val());
		$('#scroller-cloud').show();
	}
}

function update_last_photo(image_no)
{
	var elem = $(".slider-sailors:eq("+image_no+")");
	$(elem).find('.slider-sailor-background').stop(true, true);
	$(elem).find('.slider-sailor-background').find('img').stop(true, true);
	$(elem).find('.slider-sailor-photo').stop(true, true);
	$(elem).find('.slider-sailor-photo').find('img').stop(true, true);
	$(elem).find('.slider-sailor-background').css('width', '57px').css('height', '57px');
	$(elem).find('.slider-sailor-background').find('img').css('width', '57px').css('height', '57px');
	$(elem).find('.slider-sailor-photo').css('width', '50px').css('height', '50px');
	$(elem).find('.slider-sailor-photo').find('img').css('width', '50px').css('height', '50px');
	$(elem).find('.slider-sailor-photo').css('right', '10px');
	$('#scroller-cloud').hide();
}


var scroller_timer = 0;
var scroller_timeout = 3000;

function scroll()
{
	$("#scroller-left").trigger('click');
	clearTimeout(scroller_timer);
	scroller_timer = setTimeout(scroll, scroller_timeout);
}

