$(document).ready(function(){

	hover_tabs();
	click_tabs();
	click_tab_links();
	load_rules();
	click_kastai();
	show_more_register();
	load_write_sms();
	upload_photo();
	ask_delete();
	fancy_box();
	fancy_ajax();
	reply_post();
//	ajax_loading();
	ajax_stop();
	load_online_help();
	slidingSms2();
	search_posts();
	search_users();
	animate_background();
	
	update_unread();
	
	toggle_cities();
	
	save_without_crop();
});

function save_without_crop(){
	$('#save_without_crop').click(function(){
		$('#ResizePhotoForm').submit();
		return false;
	});
}

function toggle_cities() {
	$('#city_select_link').click(function(){
		$('#city_select').hide();
		$('#city_select_input').attr('name','data[User][city_bad]');
		$('#city_text_input').attr('name','data[User][city]');
		$('#city_text_input').val('');
		$('#city_text').show();
		$('#city_text_input').focus();
		return false;
	});
	
	$('#city_text_link').click(function(){
		$('#city_text').hide();
		$('#city_select_input').attr('name','data[User][city]');
		$('#city_text_input').attr('name','data[User][city_bad]');
		$('#city_select').show();
		$('#city_select_input').focus();
		return false;
	});
}

var document_title = 'arprisimeni.lt';
var original_title = document.title;
var blink_on = 0;
var stop_blinking = 0;

function update_unread() {
	$.ajax({
		type: "POST",
		url: base_url+"received_messages/check_unread",
		success: function(msg){
			var msg_count = 0;
			if(msg) {
				msg_count = parseInt(msg);
			}
			if(msg_count > 0) {
				stop_blinking = 0;
				$('#unread_msg_span').html('(<span class="blink_span">'+msg+'</span>)');
				var got_text = 'Gauta';
				var new_message_text = 'nauja žinutė';
				if(msg_count == 1 || msg_count == 21 || msg_count == 31 || msg_count == 41 || msg_count == 51 || msg_count == 61 || msg_count == 71 || msg_count == 81 || msg_count == 91) {
					got_text = 'Gauta';
					new_message_text = 'nauja žinutė';
				} else {
					if((msg_count > 9 && msg_count < 21) || msg_count == 20 || msg_count == 30 || msg_count == 40 || msg_count == 50 || msg_count == 60 || msg_count == 70 || msg_count == 80 || msg_count == 90){
						got_text = 'Gauta';
						new_message_text = 'naujų žinučių';
					} else {
						got_text = 'Gautos';
						new_message_text = 'naujos žinutės';
					}
				}
				document_title = got_text+' '+msg+' '+new_message_text;
				if(blink_on == 0){
					blink_on = 1;
					begin_blinking();
				}
			} else {
				if(msg_count == 0) {
					$('#unread_msg_span').html('');
					stop_blinking = 1;
				}
			}
		}
	});
	setTimeout( "update_unread()" , 30000);
}

function begin_blinking() {
	document.title = document_title;
	if(stop_blinking != 1) {
		setTimeout( "hide_title()" , 1000);
	} else {
		document.title = original_title;
	}
}
function hide_title() {
	document.title = original_title;
	setTimeout( "begin_blinking()" , 500);
}


var clouds_left = 0;
var birds_left = 0;
var birds_top = 1;
var birds_up_down = 'down';
var rand_no = 33;

function animate_background(){
	if (jQuery.browser.msie) {
	  if(parseInt(jQuery.browser.version) < 7) {
	  	//cia sugalvosim ka padaryt
	  } else {
	  	animate_birds();
		animate_clouds();
	  }
	} else {
		animate_birds();
		animate_clouds();
	}
	
}

function animate_birds() {
	$('.top2').css('background-position', birds_left+'px '+birds_top+'px');
	birds_left += 2;
	if(birds_top == rand_no) {
		birds_up_down = 'up';
		rand_no = Math.ceil(55*Math.random()); //between 1 and 55
	}
	if(birds_top == 0) {
		birds_up_down = 'down';
	}
	if(birds_up_down == 'up') {
		birds_top--;
	} else {
		if(birds_up_down == 'down') {
			birds_top++;
		}
	}
	setTimeout( "animate_birds()" , 70);
	
}

function animate_clouds() {
	$('.top').css('background-position', clouds_left+'px 0px');
	clouds_left--;
	setTimeout( "animate_clouds()" , 70);
}

function search_users() {
	$('#extended_link').click(function(){
		$('#extended_users_search').slideDown('normal');
		return false;
	});
	$('#close_extended').click(function(){
		$('#extended_users_search').slideUp('normal');
		return false;
	});
	
	$('#users_search_button').click(function(){
		var chars = $('#UserSearch').val().length;
		if(chars > 2) {
			$('#SearchUserForm').submit();
		} else {
			alert('Įvesk bent 3 simbolius');
		}
		return false;
	});
	
// Patikrina ar ant enter spaudimo ivesta ne maziau 3 simboliai
	$('#SearchUserForm').keypress(function(e) {
		if (e.keyCode == 13) {
 			var chars = $('#UserSearch').val().length;
			if(chars < 3) {
				alert('Įvesk bent 3 simbolius');
				return false;
			}	
		}
	});

}

function search_posts() {
	$('#search_button').click(function(){
		var chars = $('#PostsSearch').val().length;
		if(chars > 2) {
			$('#SearchPostsForm').submit();
		} else {
			alert('Įvesk bent 3 simbolius');
		}
		return false;
	});
	
// Patikrina ar ant enter spaudimo ivesta ne maziau 3 simboliai
	$('#SearchPostsForm').keypress(function(e) {
		if (e.keyCode == 13) {
 			var chars = $('#PostsSearch').val().length;
			if(chars < 3) {
				alert('Įvesk bent 3 simbolius');
				return false;
			}	
		}
	});

}


var top = 0;			//pradinis top-margin smsu
var countDiv = 0;		//divu counteris (kelintas divas)
var divs = 0;			//kiek is viso rado divu
var animationTime = 500;	//skirtas paskaiciuoti per kiek divus atstumti atgal iki pirmo (priklauso nuo divu kiekio)
var sms_height = 40;	//vienai zinutei skirtas aukstis, per tiek paslenkam
var symbols_const = 60; //dauginama is sibmoliu kiekio, ir tiek rodoma zinute

function hide_online_sms() {
	$("#inner_sms_online").animate({ 
		marginTop: sms_height+"px"
	}, animationTime, function() {slide_sms_table()});
}

function slide_sms_table() {
	countDiv++;			//divu counteris - kad zinot ties kelintu divu yra
	
	if(countDiv < divs) {	// jeigu dar nepasiekem paskutinio divo
		top = top - sms_height;		//per tiek paslenkam sms'u table i virsu
	} else {
		countDiv = 0;
		top = 0;
	}
	$("#sms_online_table").css('margin-top', top+"px");
	
	setTimeout("slidingSms2()", 200);
}

function slidingSms2() {
	if(divs == 0) {
		divs = $("#sms_online_table .online_sms_div").length;	// surandam kiek divu
	}

	$("#inner_sms_online").animate({ 
		marginTop: "0px"
	}, animationTime, function() {show_online_sms()});
}

function show_online_sms() {
	var symbols = $('#online_sms_nr_'+countDiv).html().length;
	symbols = parseInt(symbols);
	if(symbols > 80) {
		symbols = 80;
	}
	var show_time = symbols*symbols_const; // symbols imam tam kad zinotume kiek laiko daugmaz rodyt zinute, priklausomai nuo teksto ilgio
	
//	$("#inner_sms_online").animate({ 
//		marginTop: "0px"
//	}, 100);
	
	setTimeout("hide_online_sms()", show_time);
}


function load_online_help() {
	$('.load_online_help').click(function(){
		var url = $(this).attr('href');
		var load = window.open(url,'SMSonline','scrollbars=no,menubar=no,height=660,width=500,resizable=yes,toolbar=no,location=no,status=no,left=100,top=20');
		if (window.focus) {load.focus()};
		return false;
	});
}

//function ajax_loading(){
//	$("#ajax_loading_div").ajaxStart(function(){
//	  $(this).show();
//	  var scroll_top = document.documentElement.scrollTop;
//	  if(!scroll_top || scroll_top == 0) {
//	  	scroll_top = document.body.scrollTop;
//	  }
//	  $(this).css('margin-top', scroll_top+'px');
//	});
//	
//	$("#ajax_loading_div").ajaxStop(function(){
//	  $(this).hide();
//	});
//}

function ajax_start(){
	  $("#ajax_loading_div").show();
	  var scroll_top = document.documentElement.scrollTop;
	  if(!scroll_top || scroll_top == 0) {
	  	scroll_top = document.body.scrollTop;
	  }
	  $("#ajax_loading_div").css('margin-top', scroll_top+'px');
}
function ajax_stop(){
	$("#ajax_loading_div").ajaxStop(function(){
	  $(this).hide();
	});
}
function unbind_ajax_loading(){
	$("#ajax_loading_div").unbind();
//	$("#ajax_loading_div").unbind();
}

function reply_post() {
	
//	$('.reply_to_post').ajaxForm(function() {
////		alert('Žinutė išsiųsta!');		
//	});

	$('.reply_to_post').submit(function() {
//		unbind_ajax_loading();
//		ajax_start();

		var msg = $(this).children('textarea').val();
		msg = removeSpaces(msg);
		if(msg.length < 1) {
			alert('Nieko neįvedei!');
		} else {
			$(this).ajaxSubmit();
			var content = '<div style="padding-top:55px;padding-bottom:55px;" align="center">Žinutė išsiųsta!</div>';
			$(this).parent().html(content);
		}
		
		return false;	
	}); 
	
//	$('.reply_to_post_button').click(function(){
//		var content = '<div style="padding-top:55px;padding-bottom:55px;" align="center">Žinutė išsiųsta!</div>';
//		$(this).parent().parent().html(content);
//		$(this).parent().parent().ajaxSubmit();
//		return false;
//	});
}

function fancy_box() {
	/* This is basic - uses default settings */
	$(".fancy_box").fancybox({
		'zoomSpeedIn': 600,
		'zoomSpeedOut': 500,
		'easingIn' : 'easeOutBack',
		'easingOut' : 'easeInBack'
	});
	/* Using custom settings */
//	$("a#inline").fancybox({
//		'hideOnContentClick': true
//	}); 
//	
//	$("a.group").fancybox({
//		'zoomSpeedIn': 300,
//		'zoomSpeedOut': 300,
//		'overlayShow': false
//	});
	
}

function load_on_fancy(img_width) {
//	alert(img_width);

	load_write_sms();
//	disable_button();
	send_message_ajax();
	
	
	load_max_length();
	$('#SentMessageText').focus();
	
	if($('#fancy_outer').width() == '720') {
		reduce_photo();
	}
	
	set_height();
}

function reduce_photo() {
	$('#user_info_div').children().children('img').css('width', '270px');
}

function disable_button() {
	$('.disable_button').click(function() {
		$(this).parent().prepend('<div class="hide_button">Siunčiama...</div>');
	});
}

function load_max_length() {
	maxKeyPress();
	maxKeyUp();
	maxPaste();
}

function load_write_sms(){
	$('.load_write_sms').click(function(){
		var url = $(this).attr('href');
		var load = window.open(url,"RašytiSMS",'scrollbars=no,menubar=no,height=615,width=540,resizable=yes,toolbar=no,location=no,status=no,left=100,top=50');
		if (window.focus) {load.focus()};
		return false;
	});
}

function set_height() {
	$('#fancy_outer').height($('#user_info_div').height()+20);
}

function send_message_ajax() {
	$('#SentMessageSendForm').submit(function() {
		var msg = $(this).children('textarea').val();
		msg = removeSpaces(msg);
		if(msg.length < 1) {
			alert('Nieko neįvedei!');
		} else {
			$('.disable_button').parent().prepend('<div class="hide_button">Siunčiama...</div>');
			$(this).ajaxSubmit();
			$('#fancy_close').trigger('click');
			$('#flashMessage').hide();
			$('#flashMessage').removeClass('padaryti_orange');
			$('#flashMessage').html('Žinutė sėkmingai išsiųsta.');
			$('#flashMessage').show();
		}
		
		return false;	
	}); 
	
//	$('#SentMessageSendForm').ajaxForm(function() {
//		$('#fancy_close').trigger('click');
//		$('#flashMessage').hide();
//		$('#flashMessage').html('Žinutė sėkmingai išsiųsta.');
//		$('#flashMessage').show();
//	});
	 
}

function fancy_ajax() {
	/* This is basic - uses default settings */
	var img_width = 520;
	var img_height = 300;
	
	$(".fancy_ajax").click(function(){
		ajax_start();
		if( $(this).next().html()) {
			img_width = $(this).next().html();
			img_width = parseInt(img_width);
			img_width += 430;
		}
		if( $(this).next().next().html()) {
			img_height = $(this).next().next().html();
			img_height = parseInt(img_height);
		}
		if(img_width > 700) {
			img_width = 700;
		}
		$(this).fancybox({
			'frameWidth': img_width,
			'frameHeight': img_height,
			'callbackOnShow': load_on_fancy,
			'hideOnContentClick': false,
			'zoomSpeedIn': 600,
			'zoomSpeedOut': 500,
			'easingIn' : 'easeOutBack',
			'easingOut' : 'easeInBack'
		});
		$(this).trigger('click');
		return false;
	});
	
	/* Using custom settings */
//	$("a#inline").fancybox({
//		'hideOnContentClick': true
//	}); 
//	
//	$("a.group").fancybox({
//		'zoomSpeedIn': 300,
//		'zoomSpeedOut': 300,
//		'overlayShow': false
//	});
	
}

function upload_photo() {
	$('#photo_input').change(function(){
		$('#flashMessage').html('Nuotrauka įkeliama! Prašome palaukti! <br />Nuotraukos įkėlimas gali užtrukti, jeigu jūsų interneto ryšys nėra spartus.');
		$('#flashMessage').removeClass('padaryti_orange');
		$('#flashMessage').show();
		$('#UserUploadPhotoForm').submit();
	});
	
	
}



function show_more_register(){
	$('#UserEmail').focus(function(){
		$('.no_display').show();
	});
}

function click_kastai() {

	$("#top_right").click(function(){
    	$("#div_kas_tai").slideDown(300);
	});
	
	$('#close_kastai').click(function() {
		$("#div_kas_tai").slideUp(300);
	});
}

function load_rules() {
	$('.load_rules').click(function(){
		$('#register_button').attr('disabled', '');
		$('.okastaisykles').unbind('click');
		$('#register_button').removeClass('okastaisykles');
		var url = $(this).attr('href');
		var load = window.open(url,'Taisyklės','scrollbars=yes,menubar=no,height=700,width=800,resizable=no,toolbar=no,location=no,status=no,left=50,top=10');
		if (window.focus) {load.focus()};
		return false;
	});
	
	$('.okastaisykles').click(function(){
		alert('O kodėl neperžvelgei taisyklių? Pirmiau peržiūrėk taisykles.');
		return false;
	});
}

function click_tab_links(){
	$('.tab1_link').click(function(){
		$(this).parent().trigger('click');
		$(this).blur();
		return false;
	});
	$('.tab2_link').click(function(){
		$(this).parent().trigger('click');
		$(this).blur();
		return false;
	});
	$('.tab3_link').click(function(){
		$(this).parent().trigger('click');
		$(this).blur();
		return false;
	});
	
}

function hover_tabs() {

	$('.tab1').hover(function(){
		$(this).addClass('active_hover_tab');
	},function(){
		$(this).removeClass('active_hover_tab');
	});
	$('.tab2').hover(function(){
		$(this).addClass('active_hover_tab');
	},function(){
		$(this).removeClass('active_hover_tab');
	});
	$('.tab3').hover(function(){
		$(this).addClass('active_hover_tab');
	},function(){
		$(this).removeClass('active_hover_tab');
	});
	
}

function click_tabs() {

	$('.tab1').click(function(){
		$(this).next().removeClass('active_tab');
		$(this).next().next().removeClass('active_tab');
		$(this).parent().removeClass('a_tab2');
		$(this).parent().removeClass('a_tab3');
		$(this).parent().addClass('a_tab1');
		$(this).addClass('active_tab');
		$(this).parent().next().next().children('.write_answer').hide();
		$(this).parent().next().next().children('.about_me').hide();
		$(this).parent().next().next().children('.message').show();
	});
	
	$('.tab2').click(function(){
		$(this).prev().removeClass('active_tab');
		$(this).next().removeClass('active_tab');
		$(this).parent().removeClass('a_tab1');
		$(this).parent().removeClass('a_tab3');
		$(this).parent().addClass('a_tab2');
		$(this).addClass('active_tab');
		$(this).parent().next().next().children('.message').hide();
		$(this).parent().next().next().children('.write_answer').hide();
		$(this).parent().next().next().children('.about_me').show();
	});
	
	$('.tab3').click(function(){
		$(this).prev().removeClass('active_tab');
		$(this).prev().prev().removeClass('active_tab');
		$(this).parent().removeClass('a_tab1');
		$(this).parent().removeClass('a_tab2');
		$(this).parent().addClass('a_tab3');
		$(this).addClass('active_tab');
		$(this).parent().next().next().children('.about_me').hide();
		$(this).parent().next().next().children('.message').hide();
		$(this).parent().next().next().children('.write_answer').show();
	});

}

function ask_delete() {
	$('.ask_delete').click(function(){
		var item = '';
		if($(this).attr('name')){
			item = ': '+$(this).attr('name');
		}
		
		var answer = confirm('Ar tikrai norite ištrinti'+item+'?');
		if(!answer) {
			return false;
		}
	});
	
}

function getLeft(el) {
    xPos = el.offsetLeft;
    tempEl = el.offsetParent;
    while (tempEl != null) {
        xPos += tempEl.offsetLeft;
          tempEl = tempEl.offsetParent;
    }
    return xPos;
}
function getTop(el) {
    yPos = el.offsetTop;
    tempEl = el.offsetParent;
    while (tempEl != null) {
        yPos += tempEl.offsetTop;
          tempEl = tempEl.offsetParent;
    }
    return yPos;
}

function maxKeyPress(){
	$('textarea').keydown(function(evt){
		var obj = this;
		var maxLength = obj.getAttribute("maxlength");
		var e = window.event ? event.keyCode : evt.which;
	    if ( (e == 32) || (e == 13) || (e > 47)) { //IE
	        if(maxLength && (obj.value.length > maxLength-1)) {
	            if (window.event) {
	                window.event.returnValue = null;
	            } else {
	                evt.cancelDefault;
	                return false;
	            }
	        }
	    }
	});
}

function maxKeyUp(){
	$('textarea').keyup(function(evt){
		var obj = this;
	    var maxLength = obj.getAttribute("maxlength");
	     if(maxLength && obj.value.length > maxLength){
	           obj.value = obj.value.substr(0,maxLength);
	     }
	    sr = obj.getAttribute("showremain");
	    if (sr) {
	        document.getElementById(sr).innerHTML = maxLength-obj.value.length;
	    }
	});
}

function maxPaste(){
	$('textarea').keyup(function(evt){
		var obj = this;
		var maxLength = obj.getAttribute("maxlength");
		if(maxLength){
			var value = $(this).val();
			var count = $(this).val().length;
			 if(count > maxLength) {
			 	$(this).val(value.substr(0,maxLength))
			 }
		}
	});
}

function removeSpaces(string) {
 return string.split(' ').join('');
}
