jQuery.fn.shake = function(intShakes, intDistance, intDuration) {
   this.each(function() {
      var jqNode = $(this);
      jqNode.css({position: "relative"});

      for (var x=1; x<=intShakes; x++) {
         jqNode.animate({ left: (intDistance * -1) },(((intDuration / intShakes) / 4)))
         .animate({ left: intDistance },((intDuration/intShakes)/2))
         .animate({ left: 0 },(((intDuration/intShakes)/4)));
      }
   });
   return this;
}


new function($) {
  $.fn.setCursorPosition = function(pos) {
    if ($(this).get(0).setSelectionRange) {
      $(this).get(0).setSelectionRange(pos, pos);
    } else if ($(this).get(0).createTextRange) {
      var range = $(this).get(0).createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  }
}(jQuery);

function setSelectionRangeX(input, selectionStart, selectionEnd) {
   // IE
   if (input.createTextRange) {
      var range = input.createTextRange();
      range.collapse(true);
      range.moveEnd('character', selectionEnd);
      range.moveStart('character', selectionStart);
      range.select();
    // real browsers :)
    } else if (input.setSelectionRange) {
      input.focus();
      input.setSelectionRange(selectionStart, selectionEnd);
    }
}


$(document).ready(function() {
    $('#main').supersleight();

   var timer = 0;
   var subMenuOpen = false;

    $('#searchSubmit').click(function(){

    	//$('.ajaxloaderlogin').show();
		var what = $('#searchField').attr("value");
		 window.location = absoluteURL + 'search/' + what + '/1';
	});

    $('.link_hide').live('click', sortLoad);

    $('#searchField').click(function() {
       $(this).attr('value', '');
    });

    $('#searchField').bind( "keyup", function(e) {
    	if(e.keyCode === 13) {
            var what = $('#searchField').attr("value");
            window.location = absoluteURL + 'search/' + what + '/1';
    	}

    });

    $('#menu > li').mouseover(function() {
        var hasSubmenu = $('#submenu-' + $(this).attr('class')).length;

        $('.submenu').hide();
        subMenuOpen = false;

        window.clearTimeout(timer);

        if (hasSubmenu) {
            $('#submenu-' + $(this).attr('class')).show();

            subMenuOpen = true;
        }

    });

    $('#menu > li').mouseout(function() {
      timer = window.setTimeout(function() {
                                 $('.submenu').hide();
                                 subMenuOpen = false;
                             }, 500);
    });

    var login = attachLogin();

    attachPagination();
    attachCommentsBehaviour();
    attachGalleryBehaviour(login);
    attachFrontpageBehaviour(login);
    attachQuizzesProfileBehaviour(login);

    // listanje kvizova
    attachQuizzesBehaviour(login);

    // radjenje kviza
    attachQuizBehaviour(login);

    attachProfileBehaviour(login);
});

function attachFrontpageBehaviour(login) {
    if ($('#muskaracMesecaUp').length < 1) { // not on the frontpage
        return;
    }

    var noticeForm = '<div class="overlay" id="notice">' +
                        '<div id="noticeMessage"> Hvala što ste glasali! <br />' +
                        '<input type="image" src="' + absoluteURL + 'static/themes/frontpage/images/loginSubmit.png" id="noticeSubmit" />' +
                          '</div>' +
                      '</div>';


   $(noticeForm).insertAfter('#main');

   var notice = $('#notice').overlay({'api' : true, 'finish' : {
                                                               top: 'center',
                                                               left: 'center',
                                                               absolute: false
                                                               },
                                        'fadeInSpeed': 10});

   $('#noticeSubmit').click(function() {
      notice.close();
   });

    $('#muskaracMesecaUp a').click(function() {
      $.post(absoluteURL + 'bmk/king/vote', {'vote' : 'up', 'king_id' : $(this).attr('value')},
               function(content) {
                    content = parseInt(content);

                    if (content == 0) { // session expired
                        login.load();

                        return;;
                    }

                    $('#muskaracMesecaUp').hide();
                    $('#muskaracMesecaDown').hide();

                    notice.load();
                }
      );

        return false;
   });

   $('#muskaracMesecaDown a').click(function() {
      $.post(absoluteURL + 'bmk/king/vote', {'vote' : 'down', 'king_id' : $(this).attr('value')},
               function(content) {
                    content = parseInt(content);

                    if (content == 0) { // session expired
                        login.load();

                        return;;
                    }

                    $('#muskaracMesecaUp').hide();
                    $('#muskaracMesecaDown').hide();

                    notice.load();
                }
        );

        return false;
   });
}

function attachLogin() {
   var loginForm = '<div class="overlay" id="login">' +
                        '<div id="loginForm">' +
                              '<input type="text" name="username" id="loginUsername" /> <br />' +
                              '<input type="password" name="password" class="password" id="loginPassword" />' +
                              '<br />' +
                              '<input type="image" src="' + absoluteURL + 'static/themes/frontpage/images/loginSubmit.png" id="loginSubmit" />' +
                          '</div>' +
                      '</div>';
    var gotoURL = '';

   $('#login').remove();

   $(loginForm).insertAfter('#main');

   var login = $('#login').overlay({'api' : true, 'finish' : {
                                                               top: 'center',
                                                               left: 'center',
                                                               absolute: false
                                                               },
                                        'fadeInSpeed': 10});

   $('#loginPassword').bind( "keyup", function(e) {
    	if(e.keyCode === 13) {
            submitLoginForm();
    	}
    });

   $('#loginSubmit').click(function() {
        submitLoginForm();
   });

   $('a[rel]').click(function() {
        login.load();

        gotoURL = $(this).attr('value');

        return false;
    });

   function submitLoginForm() {
      $.post(absoluteURL + 'user/login', {'username' : $('#loginUsername').attr('value'), 'password' : $('#loginPassword').attr('value')},
                function(content) {
                    content = parseInt(content);

                    if (content > 0) {
                        login.close();

                        if (!gotoURL) {
                            window.location = absoluteURL + 'profil/' + content;

                            return;
                        }

                        if (gotoURL.indexOf(absoluteURL) == -1) {
                           gotoURL = absoluteURL + gotoURL;
                        }

                        window.location = gotoURL;
                   } else {
                        $('#loginPassword').attr('value', '').css('border', '1px solid red').shake(2,10,400);
                   }
                 }
         );
   }

   return login;
}

function attachGalleryBehaviour(login) {
   if ($('#albumId').length < 1) { // not on the profile page
        return;
    }

   $('#galleryImages').serialScroll({
      items:'li', // Selector to the items ( relative to the matched elements, '#sections' in this case )
      prev:'img.galleryNavPrev',// Selector to the 'prev' button (absolute!, meaning it's relative to the document)
      next:'img.galleryNavFF',// Selector to the 'next' button (absolute too)
      axis:'x',
      navigation:'.galleryNav',
      duration:700,
      force:true, // Force a scroll to the element specified by 'start' (some browsers don't reset on refreshes)

      onBefore:function( e, elem, $pane, $items, pos ){
          e.preventDefault();
          if( this.blur )
              this.blur();
      },
      onAfter:function( elem ){
      }
   });
}


function attachProfileBehaviour(login) {
    if ($('#editAboutForm').length < 1) { // not on the profile page
        return;
    }

   var editProfile = $('#editAccount').overlay({'api' : true, 'finish' : {
                                                             top: 'center',
                                                             left: 'center',
                                                             absolute: false
                                                             },
                                      'fadeInSpeed': 10});

   var editAbout = $('#editAbout').overlay({'api' : true, 'finish' : {
                                                             top: 'center',
                                                             left: 'center',
                                                             absolute: false
                                                             },
                                      'fadeInSpeed': 10});

   var uploadPhoto = $('#uploadPhoto').overlay({'api' : true, 'finish' : {
                                                             top: 'center',
                                                             left: 'center',
                                                             absolute: false
                                                             },
                                      'fadeInSpeed': 10});

   $('#openEditAccount').click(function() {
      var userId = $('#userId').attr('value');

      $('#editAccountForm').html('<br /> Vaši podaci se učitavaju, molim vas sačekajte...');
      $('#uploadPhotoForm').html('<br /> Molimo vas sačekajte...');
      $('#editAboutForm').html('<br /> Vaši podaci se učitavaju, molim vas sačekajte...');

      editProfile.load();

      $('#editAccountForm').load(absoluteURL + 'bmk/profile/edit-account/user_id/' + userId, function() {
         attachEditProfileBehaviour('#editAccountForm', editProfile, userId);
      })

      return false;
   });

   $('#openEditAccountAvatar').click(function() {
      var userId = $('#userId').attr('value');

      $('#editAccountForm').html('<br /> Vaši podaci se učitavaju, molim vas sačekajte...');
      $('#uploadPhotoForm').html('<br /> Molimo vas sačekajte...');
      $('#editAboutForm').html('<br /> Vaši podaci se učitavaju, molim vas sačekajte...');

      editProfile.load();

      $('#editAccountForm').load(absoluteURL + 'bmk/profile/edit-account/user_id/' + userId, function() {
         attachEditProfileBehaviour('#editAccountForm', editProfile, userId);
      })

      return false;
   });

   $('#openEditAbout').click(function() {
      var userId = $('#userId').attr('value');

      $('#editAccountForm').html('<br /> Vaši podaci se učitavaju, molim vas sačekajte...');
      $('#uploadPhotoForm').html('<br /> Molimo vas sačekajte...');
      $('#editAboutForm').html('<br /> Vaši podaci se učitavaju, molim vas sačekajte...');

      editAbout.load();

      $('#editAboutForm').load(absoluteURL + 'bmk/profile/edit-about/user_id/' + userId, function() {
         attachEditProfileBehaviour('#editAboutForm', editAbout, userId);

         $('#about').change(function() {
            if (this.value.length > 250) {
               this.value = this.value.substring(0, 250);
            }
         });

         $('#about').keyup(function() {
            if (this.value.length > 250) {
               this.value = this.value.substring(0, 250);
            }
         });
      })

      return false;
   });

   $('#openUploadPhoto').click(function() {
      var userId = $('#userId').attr('value');

      $('#editAccountForm').html('<br /> Vaši podaci se učitavaju, molim vas sačekajte...');
      $('#uploadPhotoForm').html('<br /> Molimo vas sačekajte...');
      $('#editAboutForm').html('<br /> Vaši podaci se učitavaju, molim vas sačekajte...');

      uploadPhoto.load();

      $('#uploadPhotoForm').load(absoluteURL + 'bmk/profile/upload-image/user_id/' + userId, function() {
         attachEditProfileBehaviour('#uploadPhotoForm', uploadPhoto, userId);
      })

      return false;
   });

   $('#galleryImages').serialScroll({
		items:'li', // Selector to the items ( relative to the matched elements, '#sections' in this case )
		prev:'img.galleryNavPrev',// Selector to the 'prev' button (absolute!, meaning it's relative to the document)
		next:'img.galleryNavFF',// Selector to the 'next' button (absolute too)
		axis:'x',
		navigation:'.galleryNav',
		duration:700,
		force:true, // Force a scroll to the element specified by 'start' (some browsers don't reset on refreshes)

		onBefore:function( e, elem, $pane, $items, pos ){
			e.preventDefault();
			if( this.blur )
				this.blur();
		},
		onAfter:function( elem ){
		}
	});

   $('#commentText').change(function() {
      if (this.value.length > 500) {
         this.value = this.value.substring(0, 500);

         $(this).setCursorPosition(499);
      }
   });

   $('#commentText').keyup(function() {
      if (this.value.length > 500) {
         this.value = this.value.substring(0, 500);

         setSelectionRangeX($('#commentText')[0], 500, 500);
      }
   });

   $('#deleteComment').click(function() {
        var gotoURL = $(this).attr('href');
        var userId = $('#userId').attr('value');

        $.post(gotoURL,
               function(content) {
                    if (content == 0) { // session expired
                        login.load();

                        return;
                    }

                    content = $('<div>' + content + '</div>');
                    var commentsArea = $('#commentsArea', content).html();

                    $('#commentsArea').remove();
                    $('.commentsNav').before('<div id="commentsArea">' + commentsArea + '</div>');

                    if ($('.commentsNav', content).is(':visible')) {
                        $('.commentsNav').show();
                    }

                    $('#commentText').attr('value', '');

                    attachProfileBehaviour();
                }
        );

        return false;
    });

   $('#sendButton').click(function() {
        var comment = $('#commentText').attr('value');
        var userId = $('#userId').attr('value');

        if ($('#private').is(':checked')) {
            var privateMessage = 1;
        } else {
          var privateMessage = 0;
        }

        $.post(absoluteURL + 'bmk/profile/post-comment', {'comment' : comment, 'user_id' : userId, 'private' : privateMessage},
               function(content) {
                    if (content == 0) { // session expired
                        login.load();

                        return;;
                    }

                    content = $('<div>' + content + '</div>');
                    var commentsArea = $('#commentsArea', content).html();

                    $('#commentsArea').remove();
                    $('#newComment').before('<div id="commentsArea">' + commentsArea + '</div>');

                    $('#commentText').attr('value', '');

                    attachPagination();
                }
        );

        return false;
    });
}

function attachEditProfileBehaviour(id, dialog, userId) {
   $(id + ' form').ajaxForm({target: id,
                             beforeSubmit: function() {
                                 $('#formErrors').html('<span style="color: black">Molimo vas sačekajte...</span>');
                              },
                              success: function(responseText, statusText) {
                                        if (responseText == '') {
                                           dialog.close();
                                           window.location = absoluteURL + 'profil/' + userId;
                                        } else {
                                            attachEditProfileBehaviour(id, dialog, userId);
                                        }

                                        return false;
                                      }
  });
}

function attachQuizzesBehaviour(login) {
    if ($('#kvizoviTabelaLoggedIn').length < 1) { // we are not on the tests page
        return;
    }

    var noticeForm = '<div class="overlay" id="notice">' +
                        '<div id="noticeMessage"> <img src="' + absoluteURL + 'static/themes/testovi/images/solved.png" /> <br />' +
                        '<input type="image" src="' + absoluteURL + 'static/themes/frontpage/images/loginSubmit.png" id="noticeSubmit" />' +
                          '</div>' +
                      '</div>';


   $(noticeForm).insertAfter('#main');

   var notice = $('#notice').overlay({'api' : true, 'finish' : {
                                                               top: 'center',
                                                               left: 'center',
                                                               absolute: false
                                                               },
                                        'fadeInSpeed': 10});

    var loggedIn = $('#kvizoviTabelaLoggedIn').attr('value');

   $('#videoContent a').click(function() {
      var target = $(this).attr('href');

      if (loggedIn == 0) {
         $('a[rel=#login]').attr('value', target);

         login.load();

         return false;
      }

      $.get(target, function(content) {
         if (content == 'Ovaj test ste već položili.') {
            notice.load();
         } else {
            window.location = target;
         }
      });

      return false;
   });

   $('#noticeSubmit').click(function() {
      notice.close();
   });
}

function attachQuizzesProfileBehaviour(login) {
    if ($('#kviz').length < 1) { // we are not on the profile page
        return;
    }

    var noticeForm = '<div class="overlay" id="notice" style="display:none;">' +
                        '<div id="noticeMessage"> <img src="' + absoluteURL + 'static/themes/testovi/images/solved.png" /> <br />' +
                        '<input type="image" src="' + absoluteURL + 'static/themes/frontpage/images/loginSubmit.png" id="noticeSubmit" />' +
                          '</div>' +
                      '</div>';

   $(noticeForm).insertAfter('#main');

   var notice = $('#notice').overlay({'api' : true, 'finish' : {
                                                               top: 'center',
                                                               left: 'center',
                                                               absolute: false
                                                               },
                                        'fadeInSpeed': 10});

    var loggedIn = $('#loggedIn').attr('value');

   $('#kvizProfil').click(function() {
      var target = $(this).attr('href');

      if (loggedIn == 0) {
         $('a[rel=#login]').attr('value', target);

         login.load();

         return false;
      }

      $.get(target, function(content) {
         if (content == 'Ovaj test ste već položili.') {
            notice.load();
         } else {
            window.location = target;
         }
      });

      return false;
   });


   $('#noticeSubmit').click(function() {
      notice.close();
   });
}


function attachQuizBehaviour(login) {
    if ($('#testForm').length < 1) { // we are not on the tests page
        return;
    }

    if ($('#hasSlide').attr('value')) {
       $('.forwardButton').show();
    } else {
       $('#sendButton').show();
    }

   var noticeForm = '<div class="overlay" id="notice">' +
                        '<div id="noticeMessage"> <p>Ovaj test ste već položili</p> <br />' +
                        '<input type="image" src="' + absoluteURL + 'static/themes/frontpage/images/loginSubmit.png" id="noticeSubmit" />' +
                          '</div>' +
                      '</div>';


   $(noticeForm).insertAfter('#main');

   var notice = $('#notice').overlay({'api' : true, 'finish' : {
                                                               top: 'center',
                                                               left: 'center',
                                                               absolute: false
                                                               },
                                        'fadeInSpeed': 10});

    $('#testForm').serialScroll({
      items:'ul > li', // Selector to the items ( relative to the matched elements, '#sections' in this case )
      prev:'img.backButton',// Selector to the 'prev' button (absolute!, meaning it's relative to the document)
      next:'img.forwardButton',// Selector to the 'next' button (absolute too)
      axis:'x',
      navigation:'.quizNav',
      duration:700,
      force: false, // Force a scroll to the element specified by 'start' (some browsers don't reset on refreshes)
      start: 0,
      cycle: false,

      onBefore:function( e, elem, $pane, $items, pos ){
          e.preventDefault();
          if( this.blur )
              this.blur();

          if (pos == 1) {
             $('.forwardButton').hide();
             $('.backButton').show();
             $('#sendButton').show();
          } else {
             $('.forwardButton').show();
             $('.backButton').hide();
             $('#sendButton').hide();
          }
      },
      onAfter:function( elem ){
      }
    });

    $('#content2 form').ajaxForm({target: '#noticeMessage p', success: function() { notice.load(); }});

    $('#noticeSubmit').click(function() {
      notice.close();
      window.location = absoluteURL + 'profil/' + $('#userId').attr('value');
   });
}

function attachCommentsBehaviour() {
   if ($('#commentsList').length < 1) { // we are not on the tests page
        return;
    }

   $('#submit_comment').click(function(){
      $('#successText').hide();
      $('#errorText').hide();

      var commentator_name = $('#commentatorName').attr('value');
      var commentator_email = $('#commentatorEmail').attr('value');
      var comment = $('#comment').attr('value');
      var imageId = $('#imageId').attr('value');
      var contentId = $('#contentId').attr('value');
      var contentType = $('#contentType').attr('value');

      if (($('#commentator_name').length > 0 && !commentator_name) || !comment) {
          $('#errorText').show();

          return false;
      }

      if (imageId) {
          var data = '&imageId=' + imageId;
      } else {
          var data = '&contentId=' + contentId + '&contentType=' + contentType;
      }

      $.ajax({
          type: "POST",
          url: absoluteURL + 'comments/index/add',
          data: "commentator_name=" + commentator_name + "&commentator_email=" + commentator_email + "&comment=" + comment + data,
          success: function(content) {
                      //content = $('<div>' + content + '</div>');

                      $('#scroll').fadeOut();
                      $('#scroll').html($('#scroll', content).html());
                      $('#scroll').fadeIn();

                      $('#successText').fadeIn();
                      $('#commentator_name').attr('value','');
                      $('#commentator_email').attr('value','');
                      $('#comment').attr('value','');
                  }
         });

      return false;
   });


   $('#succesText').click(function(){
   $('#succesText').fadeOut();
   });
}

function attachPagination() {
    var paginationControlDiv = $('#paginationControl');

    if (paginationControlDiv.length > 0) {
        var currentItem = $('.current', paginationControlDiv).html();

        paginationControlDiv.data('currentItem', currentItem);
        $('a[href=#' + currentItem + ']', paginationControlDiv).css('font-weight', 'bold');

        $('a.pag_pagenb', paginationControlDiv).click(function() {
            var page = $(this).attr('href').replace('#', '');
            page = page.replace(absoluteURL, '');

            var url =  $(this).attr('value');

            paginationControlDiv.data('currentItem', page);

            $('.ajaxloaderlogin').css({top:"170px",left:"725px"});
            $('.ajaxloaderlogin').show();

            $.ajax({
                async: true,
                type: 'GET',
                url:   url,
                dataType: 'html',
                success: function(content) {
                    // if it exists, remove it first
                    content = $('<div>' + content + '</div>');
                    var paginationControlDiv = $('#paginationControl');

                    $('.admin_table').fadeOut();
                    $('#scroll').html($('#scroll', content).html());
                    $('.admin_table').fadeIn();

                    $('.ajaxloaderlogin').hide();

                    paginationControlDiv.html($('#paginationControl', content).html());

                    $('.current', paginationControlDiv).html(page);
                    $('a', paginationControlDiv).css('font-weight', 'normal');
                    $('a[href=#' + page + ']', paginationControlDiv).css('font-weight', 'bold');

                    attachPagination();

                    delete paginationControlDiv;
                }
            });
        });


        // Page link event
        $('#paginationControl .arrows').live('click', paginationControl);

        delete paginationControlDiv;
    }
}

function paginationControl(event) {
    var linkClass = $(this).attr("class");
    var currentItem =  parseInt($('#paginationControl').data('currentItem'));

    var backId = currentItem - 1;
    var nextId = currentItem + 1;
    var total = parseInt($('#paginationControl .total').html());

    //we are scrolling next element
    if (linkClass.indexOf("pagback") != -1 && backId > 0) {
        $('#paginationControl a[href=#' + backId + ']').trigger('click');
    } else if (linkClass.indexOf("pagnext") != -1 && nextId <= total) {
        $('#paginationControl a[href=#' + nextId + ']').trigger('click');
    }

    return false;
}

function sortLoad(event) {
    var title = $(this).attr("name");

    $('.ajaxloaderlogin').css({top:"170px",left:"725px"});
    $('.ajaxloaderlogin').show();

    $('.admin_table').fadeOut();

    $.get(absoluteURL + $(this).attr("value"),function(content) {
        $('.ajaxloaderlogin').fadeOut();

        content = $(content);
        $('#scroll').html($('#scroll', content).html());

        attachPagination();
    });

    return false;
}

function paginacija(brStrane, location) {
	$.ajax({
		type: "POST",
		url: location,
		data: "br_strana="+brStrane,
		success: function(msg){
			$('#content2').html(msg);

            return false;
		}
	});

    return false;
}

function prikaziVest(idVesti, type) {

	$('.title').fadeOut();
	$('#datum').fadeOut();
	$('.mainDiv').fadeOut();

    var url = "/bmk/news/index/news_id/" + idVesti;

    if (type == 'next' || type == 'prev') {
        url += '/type/' + type;
    }

	$.ajax({
		type: "GET",
		url: url,
		success: function(msg){
            msg = $('<div>' + msg + '</div>');

			var rez = $('.mainDiv', msg).html();
			var rezDatum = $('#datum', msg).html();
			var rezTitle = $('.title', msg).html();
            var topNav =  $('.topNav', msg).html();

			$('.title').empty();
			$('#datum').empty();
			$('.mainDiv').empty();
            $('.topNav').empty();

			$('.title').append(rezTitle);
			$('#datum').append(rezDatum);
			$('.mainDiv').append(rez);
             $('.topNav').append(topNav);

			$('.title').fadeIn();
			$('#datum').fadeIn();
			$('.mainDiv').fadeIn();
            $('.topNav').fadeIn();

            $('#comments').html($('#comments', msg).html());
            attachCommentsBehaviour();

            return false;
		}
	});

    return false;
}

function prikaziIntervju(id, type) {

	$('.title').fadeOut();
	$('#datum').fadeOut();
	$('.mainDiv').fadeOut();

    var url = "/bmk/news/intervju/intervju_id/" + id;

    if (type == 'next' || type == 'prev') {
        url += '/type/' + type;
    }

	$.ajax({
		type: "GET",
		url: url,
		success: function(msg){
            msg = $('<div>' + msg + '</div>');

			var rez = $('.mainDiv', msg).html();
			var rezDatum = $('#datum', msg).html();
			var rezTitle = $('.title', msg).html();
            var topNav =  $('.topNav', msg).html();

			$('.title').empty();
			$('#datum').empty();
			$('.mainDiv').empty();
            $('.topNav').empty();

			$('.title').append(rezTitle);
			$('#datum').append(rezDatum);
			$('.mainDiv').append(rez);
             $('.topNav').append(topNav);

			$('.title').fadeIn();
			$('#datum').fadeIn();
			$('.mainDiv').fadeIn();
            $('.topNav').fadeIn();

            $('#comments').html($('#comments', msg).html());
            attachCommentsBehaviour();

            return false;
		}
	});

   return false;
}

function prikaziTekst(id, type) {

	$('.title').fadeOut();
	$('#datum').fadeOut();
	$('.mainDiv').fadeOut();

    var url = "/bmk/news/tekstovi/tekst_id/" + id;

    if (type == 'next' || type == 'prev') {
        url += '/type/' + type;
    }

	$.ajax({
		type: "GET",
		url: url,
		success: function(msg){
            msg = $('<div>' + msg + '</div>');

			var rez = $('.mainDiv', msg).html();
			var rezDatum = $('#datum', msg).html();
			var rezTitle = $('.title', msg).html();
            var topNav =  $('.topNav', msg).html();

			$('.title').empty();
			$('#datum').empty();
			$('.mainDiv').empty();
            $('.topNav').empty();

			$('.title').append(rezTitle);
			$('#datum').append(rezDatum);
			$('.mainDiv').append(rez);
             $('.topNav').append(topNav);

			$('.title').fadeIn();
			$('#datum').fadeIn();
			$('.mainDiv').fadeIn();
            $('.topNav').fadeIn();

            $('#comments').html($('#comments', msg).html());
            attachCommentsBehaviour();
		}
	});

   return false;
}

function prikaziOBmk(id, type, lang) {

	$('.title').fadeOut();
	$('#datum').fadeOut();
	$('.mainDiv').fadeOut();

    var url = "/bmk/news/obmk/bmk_id/" + id;

    if (type == 'next' || type == 'prev') {
        url += '/type/' + type;
    }
    
    if(lang != ''){
    	url += '/language/' + lang;
    }

	$.ajax({
		type: "GET",
		url: url,
		success: function(msg){
            msg = $('<div>' + msg + '</div>');

			var rez = $('.mainDiv', msg).html();
			var rezDatum = $('#datum', msg).html();
			var rezTitle = $('.title', msg).html();
            var topNav =  $('.topNav', msg).html();

			$('.title').empty();
			$('#datum').empty();
			$('.mainDiv').empty();
            $('.topNav').empty();

			$('.title').append(rezTitle);
			$('#datum').append(rezDatum);
			$('.mainDiv').append(rez);
             $('.topNav').append(topNav);

			$('.title').fadeIn();
			$('#datum').fadeIn();
			$('.mainDiv').fadeIn();
            $('.topNav').fadeIn();

            $('#comments').html($('#comments', msg).html());
            attachCommentsBehaviour();

            return false;
		}
	});

   return false;
}

function nextImage(curImg){
   var albumId = $('#albumId').attr('value');

   $('#centralPicture').hide();

   $.ajax({
       type: "POST",
       url: absoluteURL + "galerija/album/" + albumId,
       data: "curImg=" + curImg,
       success: function(msg){
               msg = $('<div>' + msg + '</div>');

               $('#centralPicture').html($('#centralPicture', msg).html());

               $('#centralPicture').fadeIn(800);

               $('#comments').html($('#comments', msg).html());

               attachCommentsBehaviour();
       }
   });
}

