$(document).ready(function()
{
	// INPUT HOVER
	$('input#search').each(function(){
		var btntext = $(this).attr('value');
		$(this).focus(function(){
            text = $(this).attr('value');
            if( text == btntext ){
                $(this).attr('value', '');
            }
		}).blur(function(){
            var text2 = $(this).attr('value');
            if( text2 == '' || text2 == undefined ){
                $(this).attr('value', btntext);
            }
		});
	});
  
	// VERTICAL ALIGN
	$('.avatar').each(function(){
		var imgBoxH = $(this).height();
		$('img', this).each(function (){
			$(this).bind('load', function(){
				var imgH = $(this).height();
				$(this).css('margin-top', (imgBoxH - imgH) / 2 + 'px');
			}).attr('src', this.src);
		});
	});
  
	// TABS CALL
    $('.tabs-box:not(.show-openID)').pdTabs({});
    $('.tabs-box.show-openID').pdTabs({defTab : 1});

	// CHANGE TEXT IN ANNOT BOX 
	$('.admin .edit-annot h1, .admin #annot-box.edit-annot .desc, .admin #annot-box .edit-annot .desc').each(function(){
		if ( $('.admin #annot-box .edit-annot .desc').size() == 1 ) {
			var $homepage = true;
		}
		var $this = $(this);
		var $parent = $(this).parent();	
			
		// hover
	  	$this.hover(function(){
			$this.css({
				'background-color': '#faf09c',
				'cursor': 'text'
			});			
		},function(){
			setTimeout(function(){
				$this.highlightFade({
					start:'#faf09c', 
					end:'#f3f3f3', 
					speed:250, 
					complete: function(){
						$this.css('background-color', '');
					}
				})
			},500);			
		});
		
		// start change texts
		$this.click(function(){
			$('#annot-box, #content').css('zoom', '1');
			$('.admin .edit-annot h1, .admin #annot-box.edit-annot .desc, .admin #annot-box .edit-annot .desc').show();
			$('.control-buttons').remove();
			var elTagName = $this[0].tagName;
			var elHeight = $this.height()-2;
			var elWidth = $this.width()-2;
			var content = $this.text();
			if ( elTagName == 'H1' ) {
				$this.hide().after('<span class="control-buttons" style="width:'+elWidth+'px;"><textarea cols="20" row="1" class="h1 int-text" style="height:'+elHeight+'px; width:'+elWidth+'px;">'+content+'</textarea><span class="save"><img src="/img/ico/save.png" alt="Uložit" /></span><span class="delete"><img src="/img/ico/delete.png" alt="Zrušit" /></span></span></span>');
			}
			else {
				$this.hide().after('<span class="control-buttons" style="width:'+elWidth+'px;"><textarea cols="20" row="1" class="desc-int int-text" style="height:'+elHeight+'px; width:'+elWidth+'px;">'+content+'</textarea> <span class="save"><img src="/img/ico/save.png" alt="Uložit" /></span><span class="delete"><img src="/img/ico/delete.png" alt="Zrušit" /></span></span></span>');				
			}
			
			$('.control-buttons textarea', $parent).focus();
			
			// delete button
			$('.control-buttons .delete', $parent).click(function(){
				$this.show().text(content);
				$('.control-buttons', $parent).remove();
			});
			
			// save button
			$('.control-buttons .save', $parent).click(function(){
				var contentNew = $('.control-buttons textarea', $parent).attr('value');
				$this.show().text(contentNew);
				$('.control-buttons', $parent).remove();
				if ( elTagName == 'H1' ) {
			        $.post(
						"/ajax/edit",
						{
							'name': contentNew, 
							id: $('h1', $parent).attr('id')
						},
						function(data)
						{
							$('#breadcrumb span').text( $('#annot-box h1').text() );
						}
					);
				}
				else if ( $homepage ) {
					$.post(
						"/ajax/forum-description",
						{'content': contentNew, id: $('#annot-box h1').attr('id')}
					);
				}
				else {
					$.post(
						"/ajax/edit",
						{
							'preview': contentNew, 
							id: $('h1', $parent).attr('id')
						}
					);
				}
			});
		});
	});

	// LOGIN BOX TABS
	$('#login-box .spc a.clasic').click(function(){
		$('#login-box .spc form.openID, #login-box .spc form.pswd').hide();
		$('#login-box .spc form.clasic').show();
		$('#login-box .spc input#log_nick').focus();
	});
	$('#login-box .spc a.pswd').click(function(){
		$('#login-box .spc form.openID, #login-box .spc form.clasic').hide();
		$('#login-box .spc form.pswd').show();
		$('#login-box .spc input#log_nick').focus();
	});
	$('#login-box .spc a.openID').click(function(){
		$('#login-box .spc form.clasic, #login-box .spc form.pswd').hide();
		$('#login-box .spc form.openID').show();
	});

    // ZEBRA
    $('.topic ul:not(.admin) li:not(:first-child):odd, .forum ul li:not(:first-child):odd, #discussion .reset li:odd').addClass('even');		
            
	// DRAG & DROP
    $('.topic ul.admin').drag({dragSelector: 'li:not(:first-child)'}, function(){
        var arr = [];
        $('ul.admin li:not(:first-child)').each(function(){
            arr.push($(this).attr('id').substr(6));
        });
        $.post(
			"/ajax/order",
			{'order[]': arr},
			function(data)
			{

				$('#preview').removeClass('loading').empty();

				var fn = function(){ $('#preview').html(data).css('height', 'auto'); }
				setTimeout( fn , 10);
				// $('#preview').html(data).css('height', 'auto');
			}
		);
    });

    // SHOW BOXS OR HIDE THINGS
	if (!$('#login-box .spc').is('.show'))
	{
		$('#login-box .spc').addClass('hidden');
	}

    $('#newForum:not(.show), #newReply, .list-buttons .move-to, .no-desc .move-to, #preview, .created').addClass('hidden');
    $('#discussion #newReply').show();

	$('#boxNewReply a.open').click(function(){
		$('#newReply').slideDown('slow');
		$('.create-tema a.open').hide();
		$('.create-tema a.close').show();
		return false;
	});
	$('#boxNewReply a.close').click(function(){
		$('#newReply').slideUp('slow');
		$('.create-tema a.open').show();
		$('.create-tema a.close').hide();
		return false;
	});
	$('#boxNewForum a.open').click(function(){
		$('#newForum').slideDown('slow');
		$('#newForum .int-text').val('');
		$('input[name="idForum"]').val('');
		$('#newForum .inline-btn').addClass('hidden');
		$('#newForum .create').removeClass('hidden');
		$('#newForum form').attr('action', $('#newForum form').attr('action') + '#newForum');
		$('.create-tema a.open').hide();
		$('.create-tema a.close').show();
		return false;
	});
	$('#boxNewForum a.close').click(function(){
		$('#newForum').slideUp('slow');
		$('.create-tema a.open').show();
		$('.create-tema a.close').hide();
		$('#newForum form').attr('action', '/');
		return false;
	});
	$('#boxNewUser a.open').click(function(){
		$('#NewUser').slideDown('slow');
		$('.create-tema a.open').hide();
		$('.create-tema a.close').show();
		return false;
	});
	$('#boxNewUser a.close').click(function(){
		$('#NewUser').slideUp('slow');
		$('.create-tema a.open').show();
		$('.create-tema a.close').hide();
		return false;
	});
	$('.forum-list a.delete').click(function(){
		var name = $('h3 a', $(this).parents('.wrap')).text();
		if (!confirm ("Chcete opravdu smazat fórum '"+name+"' ?"))
		{
			return false;
		}
	});

	$('#login-box .login').click(function(){
		$('#login-box .spc').show();
		$('#login-box .spc input#log_nick').focus();
		$(document).bind('click', function(e){
			e = e || window.event;
			if ($(e.target).parents('#login-box').size() <= 0) {
				$('#login-box .spc').hide();
				$(document).unbind('click');
			}
		});
		return false;
	});
	$('#login-box .spc .close').click(function(){
		$('#login-box .spc').hide();
		return false;
	});

	$('.list-buttons #action, .no-desc #action').change(function(){
		if ( $('option.move', this).is(':selected') ){
			$('.list-buttons .move-to, .no-desc .move-to').show();
		}
		else {
			$('.list-buttons .move-to, .no-desc .move-to').hide();
		}
	});

	// DISCUSSION ANCHORS
	$('#discussion li').each(function(){
		var el = $(this);
		$('.cite', this).click(function(){
			$.post(
				"/ajax/reply-content", 
				{ id: $(el).attr('class')},
				function(cont){
					var number = $(el).attr('class');
					var user = $('.user .name', el).text();
					content = '[quote='+user+'] '+cont+' [/quote]';
					$('#newReply textarea').attr('value', content+'\n').focus();
				}
			);
		});
		$('.edit-discussion', this).click(function(){
			$.post(
				"/ajax/reply-content", 
				{ id: $(el).attr('class')},
				function(cont){
					var number = $(el).attr('class');
					var user = $('.user .name', el).text();
					content = cont;
					$('.text', el).text('').append('<p><span class="control-buttons"><textarea cols="10" class="w-full desc-int int-text" rows="10">'+content+'</textarea><span class="save"><img src="/img/ico/save.png" alt="Uložit" /></span><span class="delete"><img src="/img/ico/delete.png" alt="Zrušit" /></span></span></span></p>');
					
					$('.desc-int', el).focus();	
					
					// delete				
					$('.delete', el).click(function(){
						$('.text', el).show().text(content);
						$('.control-buttons', el).remove();
					});
					
					// save
					$('.save', el).click(function(){
						content = $('.desc-int', el).val();
						$.post(
							"/ajax/reply-content-save", 
							{ id: $(el).attr('class'), content: content},
							function (content){
								$('.text', el).text('').append('<p>'+content+'</p>');
							}
						);
					});
				}
			);
			return false;
		});
	});
		
		$('#discussion li .reply').click(function(){
			$('#newReply textarea').attr('value', '').focus();
		});
		
		
		// IMOTICONS		
		var textarea = function(change, id){
			var element = $('#'+id+' textarea')[0];
			var changeText = element.value;
			if($.browser.msie){
				element.focus();
				var help = document.selection.createRange();
				help.text = change;		
			} 
			else{
				var startPointText = element.selectionStart;
				var finishPointText = element.selectionEnd;
				var beforeChangeText = changeText.substr(0, startPointText);
				var afterChangeText = changeText.substr(finishPointText, changeText.length); 
				changeText = changeText.substr(startPointText, finishPointText - startPointText);
				element.value = beforeChangeText + change + afterChangeText;
				element.focus();
				element.selectionStart = element.selectionEnd = finishPointText + change.length;
			}
		}
		
		$('#newReply .preview .emoticon img').css('cursor', 'pointer').click(function(){
			var smile = $(this).attr('alt');
			textarea(' '+smile+' ', 'newReply');
		});

		$('#NewUser .emoticon img').css('cursor', 'pointer').click(function(){
			var smile = $(this).attr('alt');
			textarea(' '+smile+' ', 'NewUser');
		});

		// Mail control
		$('#newReply').each(function(){
			var el =  $(this);
			if ( $('#email', this).hasClass('int-text') ){
				$('#send_notice', this).click(function(){

					var email = $('#email', el).attr('value');
					var regex = new RegExp('(.+)@([^@]+)');

					if( email == '' ){
						alert('Zadejte email');
						$(this).attr('checked', false);
						return false;
					}

					if (email.match(regex) == null) {
						alert('Zadaný e-mail nemá správný tvar');
						return false;
					}
				});
			}
		});

		// Select all checkboxs
		$('#topic').each(function(){
			var el = $(this);
			$(':checkbox', this).bind('click', function(){
		    if($(this).is('#select_all')){
		    	if ( $('#select_all').is(':checked') ){
			      $(':checkbox:not(#select_all)', el).attr('checked', true);
			      $(this).attr('checked', true);
		    	}
		    	else {
			      $(':checkbox:not(#select_all)', el).attr('checked', false);
			      $(this).attr('checked', false);
					}
		    }
		    else{
		    	var count = $(':checkbox:not(#select_all)', el).size();
		      var check = $(':checkbox:not(#select_all):checked', el).size();

		      if (check == count) {$(':checkbox#select_all', el).attr('checked', true);}
					else {$(':checkbox#select_all', el).attr('checked', false);}
		    }
		  });
	  });

          $('#discussion').each(function(){
			var el = $(this);
			$(':checkbox', this).bind('click', function(){
		    if($(this).is('#select_all')){
		    	if ( $('#select_all').is(':checked') ){
			      $(':checkbox:not(#select_all)', el).attr('checked', true);
			      $(this).attr('checked', true);
		    	}
		    	else {
			      $(':checkbox:not(#select_all)', el).attr('checked', false);
			      $(this).attr('checked', false);
					}
		    }
		    else{
		    	var count = $(':checkbox:not(#select_all)', el).size();
		      var check = $(':checkbox:not(#select_all):checked', el).size();

		      if (check == count) {$(':checkbox#select_all', el).attr('checked', true);}
					else {$(':checkbox#select_all', el).attr('checked', false);}
		    }
		  });
	  });
	  
	$('#openID').attr( "autocomplete", "off" );

	$('#discussion li').each(function(){
		var size = $('blockquote', this).size();
		$('blockquote', this).each(function(i){
			if(i%2==1){
				$(this).addClass('dark');
			}
		});
	});
	
	
	$('#newReply').each(function(){
		  if ( $('.login-form').hasClass('showHide') ) {
		  
		  }
		  else {
		  	$('.login-form').addClass('hidden');
		  }
		  $('h2', this).bind('click', function(e){
	  	  	if ((e.target).tagName != 'H2') {
	  	    	$(this).parent().toggleClass('collapsed');
	    	
	    	if($(this).parent().hasClass('collapsed')){
	          
	          var parent = $(e.target).parent().get(0);
	          
	          
	          if (parent.tagName != 'H2') {
	            parent = $(parent).parent().get(0);
	          }
	          var parent2 = $(parent).parent().get(0);
	              
	          
	          if ($(parent2).hasClass('collapsed')) {
	          
	            $('.login-form',parent2).removeClass('hidden');
	            $('input', parent).attr('checked', true);
	          }
	           
	        }  
	        else
	        {        
	          var parent = $(e.target).parent().get(0);
	          if (parent.tagName != 'H2') {
	            parent = $(parent).parent().get(0);
	          }
	          var parent2 = $(parent).parent().get(0);
	          $('.login-form', parent2).addClass('hidden');        
	          $('input', parent2).attr('checked', false);
	        }
	      
	      if ((e.target).tagName=='INPUT') return true;
	      else return false;
	      }
	    });
	    
	  });	

});













function updateImageUploadLink()
{
	var uploadList = $('.file-upload-list');
	var imagesCount = $('p', uploadList).size() + $('.edit-images li').size();
	var isProduct = $('.edit-images.product-images').size() != 0;
	$('#add_file').remove();
	if(imagesCount < (isProduct ? 1 : 4))
	{
		var addText = imagesCount == 0 ? 'Přidat obrázek' : 'Přidat další obrázek';
		uploadList.after('<p><a href="#" id="add_file" class="ico-image-add" >' + addText + '<a/></p>');
		$('#add_file').bind('click', function()
		{
			var uploadList = $('.file-upload-list');
			var number = $('p', uploadList).size() + 1;
			uploadList.append('<p><label for="file' + number + '">Obrázek' + (isProduct ? '' : ' č.  <span class="img-no">' + number + '</span>') + ':</label><br /><input type="file" name="file[]" id="file' + number + '" class="sizeFull" /></p> ');
			updateImageUploadLink();
			return false;
		});
	}
	var imagesCount = $('.edit-images li').size();
	$('.file-upload-list label').each(function(i){
		$('.img-no',this).html(i + imagesCount + 1);
	});
};

$(document).ready(function()
{
	// Init pdBox
	$('.thickbox').pdBox({minWidth: 400});

	// Create zebra-style tables
	$("tr:nth-child(even)").addClass("evenrow");

	// Activate popup links:
	$('a.popup').bind('click', function(){
		return !window.open(this.href);
	});


	// In user section (review edit or product review page) init image deleting JS helpers
	$('.edit-images input.img-del').each(function(){
		var inpName = $(this).attr('name');
		$(this).before('<a href="#" class="ico-delete">smazat</a>').prev().bind('click', function()
		{
			$(this).parent().parent().remove();
			$('.edit-images').append('<input type="hidden" name="' + inpName + '" value="1" />');

			$('.edit-images li').each(function(i){
				$('.img-no',this).html(i + 1);
			});
			updateImageUploadLink();
			return false;
		});
		$('label[@for=' + $(this).attr('id') + ']').remove();
		$(this).remove();
	});

	// In user section (review edit or product review page) init image uploading JS helpers
	var uploadList = $('.file-upload-list').empty();
	updateImageUploadLink();
	// $('#add_file').trigger('click');

	// In user section - review edit page - init AJAX textile preview/edit modes
	$('#newReply a.edit').bind('click', function(){
		$('#content2, .emoticon, #newReply a.preview').show();
		$('#preview, #newReply a.edit').hide();
		return false;
	})
	$('#newReply a.preview').bind('click', function()
	{
		var reviewContent = $('#content2');
		var preview = $('#preview');
		$('#newReply a.edit').show();
		$('.emoticon, #newReply a.preview').hide();
		preview.css('height', reviewContent[0].offsetHeight - 34 + 'px');
		reviewContent.hide();
		preview.show().addClass('loading').html('Nahrávám náhled…');
		$.post(
			"/ajax/preview",
			{ content: reviewContent.val() },
			function(data)
			{

				$('#preview').removeClass('loading').empty();

				var fn = function(){ $('#preview').html(data).css('height', 'auto'); }
				setTimeout( fn , 10);
				// $('#preview').html(data).css('height', 'auto');
			}
		);
		return false;
	});


	/*
	if($('.edit-preview-links .edit').size() !== 0) {
		$('a[@href]').not('.thickbox').not('[@href^=#]').bind('click', function(){
			return window.confirm("Odchodem z této stránky se ztratí rozepsaná data z formuláře.\r\nOpravdu chcete pokračovat?");
		});
	}
	*/

	/*
	$(window).bind('unload', function(){
		alert('haf');
		return false;
	});
	*/

	/*
	$('.cattree a').bind('click', function()
	{
		$('.cattree a.active').removeClass('active');
		$(this).addClass('active');
		if(	$('.user-section .col-h-r').size() == 0) $('.user-section .col-h-l').after('<div class="col-h-r"><h3><label for="select-product">B. Vyberte produkt ze seznamu:</label></h3><p id="ajax-select-hook"></p><p id="ajax-loading-hook"></p></div>');
		$('#ajax-loading-hook').addClass('loading').html('Nahrávám seznam produktů…');
		$('.order-buttons.r input').attr('disabled', 'disabled');
		$('#ajax-select-hook').load('/tpl/product-finder.html' + $(this).attr('href'), null, function(){
			$('#ajax-loading-hook').removeClass('loading').empty();
			$('#continue').removeAttr('disabled');
			$('.user-section .col-h-r').animateColor(2000, {backgroundColor:['#F9F900','#FFFFFF']});
		});
		return false;
	});
	*/

	$('.navrhnout').click(function()
	{
		$('#new_product').toggle();
	});

	$('.close').click(function()
	{
		$('#ok_send_product').css('display','none');
		$('#error_send_product').css('display','none');
		$('#new_product').css('display','none');
	});

});





