$(document).ready(function() {


  $('.emoticon img').click(function(){
    var src = $(this).attr('src')
    var name = src.split('/').pop().split('.').shift();
    if ($(this).height() == 20) {
      var i = new Image();
      i.src = src;
      $(this)
      .animate({
        height : i.height,
        marginLeft : (685 - i.width) / 2
      }, function(){
        $(this).attr('title', 'Kliki pildi peitmiseks');
        setCookie('emoticon' + name + 'hidden', 0, -1);
      });
    } else {
      $(this)
      .animate({
        height : 20,
        marginLeft : 625
      }, function(){
        $(this).attr('title', 'Kliki pildi näitamiseks')
        setCookie('emoticon' + name + 'hidden', 1);
      });
    }
  });


  $.loadingIndicator = (function ($) {
    var
    self = $('<img />').attr('src', 'images/base/loading.gif').attr('style', 'left: 50%; margin: -6px 0 0 -6px;	z-index: 1003; top: 50%; display:none; 	position: fixed;'),
    is = (self.length > 0),
    inits = 0,
    isTrack = false,
    track = function(e) {
      self.css({
        'top'  : (e.clientY + 10) + 'px',
        'left' : (e.clientX + 25) + 'px'
      });
    },
    _init = function(boolTrack, initialE){
      self.show();
      if (boolTrack) {
        isTrack = true
        if (initialE && initialE.clientY & initialE.clientX)
          track(initialE);
        $().bind('mousemove', track);
      }
    },
    _stop = function() {
      self.hide().css({
        'top' : '50%',
        'left': '50%'
      });
      if (isTrack) {
        $().unbind('mousemove', track);
        isTrack = false;
      }
    }
    $('body').append(self);
    return {
      init : function(boolTrack, initialE) {
        inits++;
        if (inits == 1)
          _init(boolTrack, initialE);
      },
      stop : function() {
        inits--;
        if (inits == 0)
          _stop()
      }
    };
  })(jQuery);

  $('div#head input')
  .each(function(){
    $(this).data('value', $(this).val());
  })
  .blur(function(){
    if ($(this).val() == '')
      $(this).val($(this).data('value'))
  })
  .focus(function(){
    if ($(this).val() == $(this).data('value'))
      $(this).val('')
  });

  $('#content_head a.history').click(function(e){
    e.preventDefault();
    e.stopPropagation();
    $('#history').stop();
    $('#history').slideToggle('fast');
  });
  var href = $('#history li.selected').next().children('a').attr('href');
  if (href)
    $('a.history_navigate_back').attr('href', href);
  else
    $('a.history_navigate_back').hide();

  $(document).click(function(e){
    $('#history').stop();
    $('#history').slideUp('fast');
  });

  $('#content_head a.help').click(function(e){
    e.preventDefault();
    $('#help').stop();
    $('#help').slideToggle('normal');
  });

  $('#head .login button.worker').click(function(e){
    e.preventDefault();
    $(this).parent().hide();
    $('#head form').show();
  });

  $('#help a').click(function(e){
    e.preventDefault();
    $('#help').slideUp('normal');
  });


  $('#m_menu a.open').click(function(e){
    e.preventDefault();
    $(this).parent().parent().find('li');
    $(this).parent().toggleClass('selected');
    return false;
  });

  $('#mmenu a.open').click(function(e) {
    $(this).next().
    slideDown('fast').
    parent().addClass('selected');
    $('#mmenu a.open').
    not(this).
    next().
    slideUp('fast').
    parent().removeClass('selected');
    return false;
  });

  $('a.btn:not(.noover)')
  .mouseover(function(){
    $(this).addClass('btn_over');
    $(this).removeClass('btn');
  })
  .mouseout(function(){
    $(this).addClass('btn');
    $(this).removeClass('btn_over');
  });

  if ($('.periodinput').length > 0 && typeof $(".periodinput").datepicker == 'function') {

    $.datepicker.setDefaults($.datepicker.regional['et']);
    currentTime = new Date()
    var yearrange = '1950:' + (currentTime.getFullYear() + 10);
    $(".periodinput").datepicker({
      showOn: "button",
      buttonImage: "images/base/calendar.png",
      buttonText : 'vali',
      dateFormat: 'dd.mm.yy',
      firstDay: 1,
      yearRange: yearrange, // Range of years to display in drop-down,
      // either relative to current year (-nn:+nn) or absolute (nnnn:nnnn)
      beforeShow: function() {
        $(this).addClass('nohint')
      }
    });
  }

  $.fn.clearForm = function() {
    return this.each(function() {
      if (!$(this).hasClass('noclear')) {
      var type = this.type, tag = this.tagName.toLowerCase();
      if (tag == 'form')
        return $(':input',this).clearForm();
        else {
      if (type == 'text' || type == 'password' || tag == 'textarea')
        this.value = '';
      else if (type == 'checkbox' || type == 'radio')
        this.checked = false;
      else if (tag == 'select') {
        this.selectedIndex = ($(this).attr('multiple') == false)? 0 : - 1;
      }
        }
      }
    });
  };

  $('img[src*=search.gif]').each(function() {
    $(this).attr('alt', $(this).parent().attr('title'));
  });

  var generatstyle = $('link[href="style/style.css"]');

  $("#content_head a.print").click(function(e) {
    $(generatstyle).attr({
      href : "style/print.css"
    });
    setTimeout(function(){
      window.print()
    }, 100);
    $("#content_head a.cancel").show();

    $("#content_head a.cancel").click(function(e) {
      $("#content_head a.cancel").hide();
      $(generatstyle).attr({
        href : "style/style.css"
      });
      return false;
    });

    return false;
  });


  $('a.accept, a.reject').click(function(e) {
    result = true;
    msg = $(this).attr('title');

    if (msg)
      result = confirm(msg);

    return result;
  })
/*
    $('div.buttons a span:contains(Tagasi)').click(function(e) {
        window.history.back();
        return false;
    })    
     */
});

function gup(href, name ) {
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var tmpURL = href;
  var results = regex.exec( tmpURL );
  if( results == null )    return "";  else    return results[1];
}

function to_html(tstr) {
  var bstr = '';
  for(i=0; i<tstr.length; i++) {
    bstr += (tstr.charCodeAt(i) > 127)? '&#' + tstr.charCodeAt(i) + ';' : tstr.charAt(i);
  }
  bstr = bstr.replace(/\"/g,'&#34;')
  return bstr;
}

function pre(obj) {
  
}


function getCookie(name) {
  var value, p = document.cookie.split(';'), i, l, sp;
  for (i = 0, l = p.length; i < l; i++ ) {
    sp = p[i].split('=');
    if ($.trim(sp[0]) == name) {
      value = unescape($.trim(sp[1]));
      break;
    }
  }
  return value;
}

function setCookie(name, value, days) {
  var expires = ""
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    expires = "; expires="+date.toGMTString();
  }
  document.cookie = name + "=" + value + expires + "; path=/";
}
