/*$(window).load( function() {
	if ($('BODY.popup').size() == 0) {
		if (top.location != self.location) {
			top.location = self.location.href;
		}
	}
});*/

$(document).ready( function() {

	//replace english titles on addthis toolbar
	setTimeout( function() {
		$('.addthis_toolbox A').each( function() {
			$(this).attr('title', $(this).attr('title').replace('Send to', 'Wyślij do'));
			$(this).attr('title', $(this).attr('title').replace('Tweet This', 'Tweetuj'));
		});
	}, 1000);
	
	
	
	//generic hints
	var QTIP_DEFAULT = {
		api: {
			beforeShow: function(e){
				tooltipText = this.elements.content.html();
				
				if (tooltipText.length > 0) {
				
					if (tooltipText.indexOf('%0D%0A') > -1){
						re_nlchar = /%0D%0A/g ;
					}
					else if (tooltipText.indexOf('%0A') > -1){
						re_nlchar = /%0A/g ;
					}
					else if (tooltipText.indexOf('%0D') > -1){
						re_nlchar = /%0D/g ;
					}
					else {
						re_nlchar = /\n/g ;
					}
					
					this.elements.content.html( tooltipText.replace(re_nlchar,'<br />') );
					return true;
				}
				
				return false;
			}
		},
		style: { 
			name: 'dark',
	    	border: {
	        	width: 2,
	        	color: '#FFF'
	    	},
	    	width: 200
		},
		position: {
			corner: {
				target: $('BODY.popup').size()>0?'topLeft':'topRight',
				tooltip: $('BODY.popup').size()>0?'bottomRight':'bottomLeft'
			}
		},
		hide: {
			delay: 500,
			fixed: true
		}
	};
	
	
	$('.hint').qtip( QTIP_DEFAULT );
	
	$('div.form :input').qtip( $.extend(true, {}, QTIP_DEFAULT,
		{
			api: {
				beforeShow: function(e){
					if (this.elements.target.next().hasClass('tooltip')) {
						this.elements.content.html( this.elements.target.next().html() );
						return true;
					}
					
					return false;
				}
			},
			show: {
				delay: 0,
				when: {
					event: 'focus'
				}
			},
			hide: {
				delay: 100,
				when: {
					event: 'blur'
				}
			},
			position: {
				adjust: {
					y: 5
				}
			}
		}
	));
	
	$('div.form :checkbox,div.form :radio').mouseover( function() { $('div.form :input').blur(); $(this).focus();} );
	$('div.form :checkbox,div.form :radio').mouseout( function() {$(this).blur();} );
	
	$('div.form .group LABEL').mouseover( function() { $('div.form :input').blur(); $(this).prevAll(':radio,:checkbox,:input').slice(0,1).focus();} );
	$('div.form .group LABEL').mouseout( function() { $('div.form :input').blur();} );
	
	$('div.thumb IMG').qtip( $.extend(true, {}, QTIP_DEFAULT,
		{
			api: {
				beforeShow: function(e){
					tooltipDiv = this.elements.target.parents('div.thumb').find('div.tooltip');
					
					if (tooltipDiv.size()>0) {
						this.elements.content.html( tooltipDiv.html() );
						return true;
					}
					
					return false;
				}
			},
			position: {
				corner: {
					target: 'topRight',
					tooltip: 'bottomLeft'
				},
				adjust: {
					y: 5,
					x: -5
				}
			}
		}
	));
	
	$('div.badges UL LI.withHint').qtip( $.extend(true, {}, QTIP_DEFAULT,
		{
			api: {
				beforeShow: function(e){
					tooltipDiv = this.elements.target.find('div.tooltip');
					
					if (tooltipDiv.size()>0) {
						this.elements.content.html( tooltipDiv.html() );
						return true;
					}
					
					return false;
				}
			},
			position: {
				corner: {
					target: 'topRight',
					tooltip: 'bottomLeft'
				},
				adjust: {
					y: -3,
					x: -40
				}
			}
		}
	));
	
	
	//form autosubmit on select option
	$('.jqSelectSubmit').change( function() {
		$(this).parents('form').submit();
	});
	
	
	//homepage slider
	if ($('BODY.home .slider').size() > 0) {
		$('.slider .sliderContent LI:gt(0)').hide();
		
		$('.slider .sliderLinks A').click( function(e) {
			e.preventDefault();
			
			$(this).parents('UL').find('LI').removeClass('on');
			$(this).parent().addClass('on');
			
			index = $('.slider .sliderLinks A').index(this);
			$('.slider .sliderContent LI.on').fadeOut('slow').removeClass('on');
			$('.slider .sliderContent LI:eq('+index+')').fadeIn('slow').addClass('on');
		});
		
		var timerId;
		
		$('.slider').mouseover( function(e) {
			clearTimeout(timerId);
		});
		$('.slider').mouseout( function(e) {
			timerId = setTimeout(ticker, 2000);
		});
		
		function ticker() {
			nextLI = $('.slider .sliderLinks LI.on').next();
			
			if (nextLI.size() > 0) {
				nextLI.find('A').click();
			}
			else {
				$('.slider .sliderLinks LI:first A').click();
			}

			
			timerId = setTimeout(ticker, 4000);
		}
		
		timerId = setTimeout(ticker, 8000);
	}
		
	
	//file progress
	$('#progress_key').each( function() {
		$(this).parents('form').submit( function(e) {
			$(".progressBar").fadeIn();

			var i = setInterval(function() { 
				$.getJSON("/fileProgress.php?progress_key=" + $('#progress_key').val(), function(data) {
					if (data.finished) {
						clearInterval(i);
						$(".progressBar .bar").progressBar(100);
						$(".progressBar .info").text('');
						return;
					}
					else {
						$(".progressBar .bar").progressBar(data.percent);
						$(".progressBar .info").text(data.text);
					}
				});
			}, 1000);

			return true;
		});
	});
	
	$('.progressBar .bar').progressBar( { 
		boxImage: '/assets/img/bg/progressbar.gif',
		barImage: '/assets/img/bg/progressbg_orange.gif'
	});
	
	
	//image cropping
	var ratio = $('#jcropCurrentWidth').val() / 400;
	
	$('.imageResize IMG').Jcrop( {
		aspectRatio: 1,
		minSize: [40,40],
		setSelect: [$('#jcropX').val()/ratio,$('#jcropY').val()/ratio,$('#jcropW').val()/ratio,$('#jcropH').val()/ratio],
		onChange: showPreview,
		onSelect: showPreview
	});
	
	$('.formEditProfile #privacy').change( function() {
		$('.formEditProfile .privacy LI').hide();
		$('.formEditProfile .privacy .'+$(this).val()).show();
	});
	
	$('.formEditProfile #privacy').change();
	
	
	//rating
	$('.rating').mousemove( function(e) {
		itemInfo = $(this).attr('id').split('-');
		if (itemInfo[0]!='word' && itemInfo[0]!='quote' && itemInfo[0]!='question' && itemInfo[0]!='answer' && itemInfo[0]!='comment') {
			return;
		} 		
				
				
		//hide selection
		$('.selection', this).hide();
		
		if ($('.selectionEdit', this).size() == 0) {
			//create edit selection
			selection = $('<span class="selectionEdit"></span>');
			
			selection.mousemove( function(e) {
				relativeX = Math.floor(((e.pageX - $(this).offset().left)+15)/15.8)*15.8;
				$(this).css('width', relativeX);
			});
			
			selection.click( function(e) {
				//send rating info
				relativeX = Math.floor(((e.pageX - $(this).offset().left)+15)/15.8);
				
				//get parent as it contains info about type and id
				itemInfo = $(this).parent().attr('id').split('-');
				
				switch (itemInfo[0]) {
					case 'word':
						url = '/dictionary/rate/format/json';
						break;
					case 'quote':
						url = '/quotes/rate/format/json';
						break;
					case 'question':
						url = '/parentsquestions/rateQ/format/json';
						break;
					case 'answer':
						url = '/parentsquestions/rateA/format/json';
						break;
					case 'comment':
						alert('not implemented');
						break;
					default:
						alert('not implemented');
						break;
				}
				
				if (url) {
					var type = itemInfo[0];
					var id = itemInfo[1];
					
					$.post( url, {id:id,rating:relativeX,type:type}, function(data, textStatus) {
						
						if (data.loginRedirect) {
							window.location = '/moje-konto/logowanie?back='+escape(window.location);
							return;
						}
						
						var itemId = type+'-'+id;
						
						$('#'+itemId).append('<p class="ratingReturnInfo">'+data.message+'</p>');
						if (!data.error) {
							try {
								pageTracker._trackEvent('Rating', 'New', null, parseInt(data.rating));
							} catch(err) {}
						}
						 
						setTimeout( function() {
							$('#'+itemId+' .ratingReturnInfo').fadeOut('slow', function() { $(this).remove() });
						}, 2000);
						
					}, 'json');
				}
			});
			
			//selection.qtip( QTIP_DEFAULT );
			$(this).append(selection);
		}
		else {
			selection = $('.selectionEdit', this);
		}
		
		relativeX = Math.floor(((e.pageX - $(this).offset().left)+15)/15.8)*15.8;
		selection.css('width', relativeX);
		
		$(this).css('cursor','pointer');//.attr('title','');
	});
	
	$('.rating').mouseleave( function (e) {
		$('.selection', this).show();
		$('.selectionEdit', this).remove();
		
		$(this).css('cursor','default');//.attr('title', 'średnia ocen');
	});
	
	
	//text area character counter
	$('TEXTAREA.charCounter').keyup( function() {
		counterName = $(this).attr('name')+'-Counter';
		
		if ($('#'+counterName).size()==0) {
			$(this).after('<span id="'+counterName+'" class="charCounter"></span>');
		}
		
		$('#'+counterName).html( $(this).val().length );
	});
	
	
	//quiz form - word counter
	if ($('.formQuiz').size()>0) {
	
		$('.formQuiz :checkbox').click( function() {
		
			$('.formQuiz .wordCounter SPAN.wleft').text( (5 > $('.formQuiz FORM :checked').size()?5-$('.formQuiz FORM :checked').size():0) );
			$('.formQuiz .wordCounter SPAN.wcount').text( $('.formQuiz FORM :checked').size() );
		
		});
	}
	
	
	//moderation
	$('P.moderate A, A.moderate').colorbox({width:"520px", height:"540px", iframe:true});
	
	
	//choose first form field after 1s
	/*setTimeout( function() {
		$('.formRegister form[method="post"] :input:first, .formLogin form[method="post"] :input:first').focus();
	}, 1000);*/
	
	
	//autoresize textareas
	$('textarea').not('.noresize').autoResize({
		animateDuration: 300,
		limit: 450
	});
	
});

//helper for image cropping
function showPreview(coords) {
	// the '400' represents an IMG tag attribute
	var ratio = $('#jcropCurrentWidth').val() / 400;
	
	// the '150' represents a preview image container size
	var rx = 150 / coords.w;
	var ry = 150 / coords.h;

	$('.preview IMG').css({
		width: Math.round(rx * $('#jcropCurrentWidth').val() / ratio) + 'px',
		height: Math.round(ry * $('#jcropCurrentHeight').val() / ratio) + 'px',
		marginLeft: '-' + (Math.round(rx * coords.x)) + 'px',
		marginTop: '-' + (Math.round(ry * coords.y)) + 'px'
	});
	
	$('#jcropX').val(Math.round(coords.x*ratio));
	$('#jcropY').val(Math.round(coords.y*ratio));
	$('#jcropW').val(Math.round(coords.w*ratio));
	$('#jcropH').val(Math.round(coords.h*ratio));
};

