$(document).ready(function()
{
	// Hover input - text out
	$('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});

  // Inputs in annot-box
  $('.admin .edit-annot h1').each(function(){
  	$(this).hover(function(){
			$(this).css('background-color', '#faf09c');			
			$(this).css('cursor', 'text');
		},function(){
			var el = $(this);
			setTimeout(function(){$(el).highlightFade({start:'#faf09c', end:'#f3f3f3', speed:1000, complete: function(){$(el).css('background-color', '');}})},500);			
		});
  	
		$(this).click(function(){
			var height = $(this).height();
			height = height-2
			var content = $(this).text();
      $(this).hide().after('<span class="control-buttons"><textarea cols="20" row="1" class="w-630 h1 int-text" style="height:'+height+'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>');

			var blur = function(){
					var content2 = $(this).attr('value');
					$('#annot-box h1').show().text(content2);
					$('.control-buttons').remove();
	        $.post(
						"/ajax/edit",
						{'name': content2, id: $('#annot-box h1').attr('id')},
						function(data)
						{
							$('#breadcrumb span').text( $('#annot-box h1').text() );
						}
					);
			}


				$('#annot-box .h1').focus().bind('blur', blur);
				
				$('#annot-box .delete').hover(function(){
					$('#annot-box .h1').unbind('blur');
				 }
				, function(){
					$('#annot-box .h1').bind('blur', blur);
					
				}).click(function(){
					$('#annot-box h1').show().text(content);
					$('.control-buttons').remove();
				});
		});
	});
	
	$('.admin #annot-box.edit-annot .desc').each(function(){
  	$(this).hover(function(){
			$(this).css('background-color', '#faf09c');
			$(this).css('cursor', 'text');
		},function(){
			var el = $(this);
			setTimeout(function(){$(el).highlightFade({start:'#faf09c', end:'#f3f3f3', speed:1000, complete: function(){$(el).css('background-color', '');}})},500);			
		});
  	
		$(this).click(function(){
			var height = $(this).height();
			height = height-2
			var content = $(this).text();
      $(this).hide().after('<span class="control-buttons"><textarea cols="20" row="1" class="w-630 desc-int int-text" style="height:'+height+'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>');

			var blur = function(){
					var content2 = $(this).attr('value');
					$('#annot-box .desc').show().text(content2);
					$('.control-buttons').remove();
	        $.post(
						"/ajax/edit",
						{'preview': content2, id: $('#annot-box h1').attr('id')},
						function(data)
						{
						}
					);
			}

				$('#annot-box .desc-int').focus().bind('blur', blur);
				
				$('#annot-box .delete').hover(function(){
					$('#annot-box .desc-int').unbind('blur');
				 }
				, function(){
					$('#annot-box .desc-int').bind('blur', blur);
					
				}).click(function(){
					$('#annot-box .desc').show().text(content);
					$('.control-buttons').remove();
				});
		});
	});
	
	$('.admin #annot-box .edit-annot .desc').each(function(){
  	$(this).hover(function(){
			$(this).css('background-color', '#faf09c');
			$(this).css('cursor', 'text');
		},function(){
			var el = $(this);
			setTimeout(function(){$(el).highlightFade({start:'#faf09c', end:'#f3f3f3', speed:1000, complete: function(){$(el).css('background-color', '');}})},500);			
		});
  	
		$(this).click(function(){
			var height = $(this).height();
			height = height-2
			var content = $(this).text();
      $(this).hide().after('<span class="control-buttons"><textarea cols="20" row="1" class="w-630 desc-int int-text" style="height:'+height+'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>');

			var blur = function(){
					var content2 = $(this).attr('value');
					$('#annot-box .desc').show().text(content2);
					$('.control-buttons').remove();
	        $.post(
						"/ajax/forum-description",
						{'content': content2, id: $('#annot-box h1').attr('id')},
						function(data)
						{
						}
					);
			}

				$('#annot-box .desc-int').focus().bind('blur', blur);
				
				$('#annot-box .delete').hover(function(){
					$('#annot-box .desc-int').unbind('blur');
				 }
				, function(){
					$('#annot-box .desc-int').bind('blur', blur);
					
				}).click(function(){
					$('#annot-box .desc').show().text(content);
					$('.control-buttons').remove();
				});
		});
	});


	// 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 a.pswd').click(function(){
		$('#login-box .spc form.openID, #login-box .spc form.clasic').hide();
		$('#login-box .spc form.pswd').show();
	});
	$('#login-box .spc a.openID').click(function(){
		$('#login-box .spc form.clasic, #login-box .spc form.pswd').hide();
		$('#login-box .spc form.openID').show();
	});*/

	// Last reply
	$('.last-reply').each(function(){
        var option = {
            rotateTime: 5000,
            animateTime: 800
        };
        var time = null;
        var elements = {
            main: $(this),
            wrapbox: $('ul.reset', this),
            item: $('ul.reset li', this),
            itemEq: 0,
            next: $('.next', this),
            prev: $('.prev', this)
        }

        elements.main.addClass('js');

        function next(){
            time = clearTimeout(time);
            elements.next.unbind('click', next);
            elements.next.bind('click', function(){return false});
            elements.item.eq(elements.itemEq).animate({
                marginLeft : -760 + 'px'
            }, option.animateTime, function(){
                $(this).css('margin-left', '0').appendTo(elements.wrapbox);
                if(elements.itemEq+1 < elements.item.size())
                    elements.itemEq++;
                else{
                    elements.itemEq = 0;
                }
                elements.next.bind('click', next);
                time = setTimeout(function(){next()}, option.rotateTime);
            });
            return false;
        };

        function prev(){
            time = clearTimeout(time);
            elements.prev.unbind('click', prev);
            elements.prev.bind('click', function(){return false});
            if(elements.itemEq-1 >= 0)
                elements.itemEq--;
            else{
                elements.itemEq = elements.item.size() - 1;
            }
            elements.item.eq(elements.itemEq).css('margin-left', '-760px').prependTo(elements.wrapbox);
            elements.item.eq(elements.itemEq).animate({
                marginLeft : 0 + 'px'
            }, option.animateTime, function(){
                elements.prev.bind('click', prev);
                time = setTimeout(function(){next()}, option.rotateTime);
            });
        };

        elements.next.bind('click', next);
        elements.prev.bind('click', prev);

        time = setTimeout(function(){next()}, option.rotateTime);
    });

    // ZEBRA
    $('.topic ul:not(.admin) li:not(:first-child):odd, .forum ul li:not(:first-child):odd, #discussion .reset li:odd').addClass('even');
		//$('#discussion li blockquote:only-child').addClass('dark').addClass('dark');
		
            
		// Drag & Drop
    //$('ul.admin li:odd').addClass('odd');
    $('.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');
			//alert( $('#newForum form').attr('action') + '#newForum')
			$('#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();
			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();
			$(document).bind('click', function(e){
				e = e || window.event;
				if ($(e.target).parents('#login-box').size() <= 0) {
					$('#login-box .spc').hide();
					$(document).unbind('click');
				}
				//alert($(e.target).offsetParent()[0].tagName )
				//alert($(e.target).parents('#login-box').size())
			});
			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>');
            
            var blur = function(){
							content = $(this).val();
              $.post("/ajax/reply-content-save", { id: $(el).attr('class'), content: content},
                  function (content){
                  $('.text', el).text('').append('<p>'+content+'</p>');
              });
						}						
						$('.desc-int', el).focus().bind('blur', blur);					
						$('.delete', el).hover(function(){
							$('.desc-int', el).unbind('blur');
						 }
						, function(){
							$('.desc-int', el).bind('blur', blur);							
						}).click(function(){
							$('.text', el).show().text(content);
							$('.control-buttons', el).remove();
						});
        });
				return false;
			});
		});
		
		$('#discussion li .reply').click(function(){
			$('#newReply textarea').attr('value', '').focus();
			return false;
		});
		
		
		// IMOTICONS
		$('#newReply .preview .emoticon img').css('cursor', 'pointer').click(function(){
			var smile = $(this).attr('alt');			
			var content = $('#newReply textarea').attr('value');
			$('#newReply textarea').attr('value', content+' '+smile).focus();
		});

		// 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);}
		    }
		  });
	  });
	  
	$('#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');
			}
		});
	});
	

});













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');
	});

});




