$(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);


  $.translate = function(word, path) {
    var translation = word;
    if ($.translations && $.translations[path] && $.translations[path][word]) {
      translation = $.translations[path][word];
    } else if (DEVELOPERREQUEST) {
      $.post('json.php?type=translate', {
        path : path,
        word : word
      });
    }
    return translation;
  };

  $('#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');
  });

  $('#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') {
    var 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;
          }
          $(this).trigger('change');          
        }
      }
    });
  };

  $('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;
    })    
     */
});

$.extend($.expr[':'],{
  name : function(a, i, m) {
    var result = false, name = $(a).attr('name');
    if (name && typeof name == 'string') {
      if(!m[3]) {
        result = true;
      } else {
        var na = m[3].split(',');
        var sel =[na.shift()];
        for (var i = 0, l = na.length; i < l; i++ )
          sel.push('[' + na[i] + ']')
        if (name.indexOf(sel.join('')) == 0) {
          result = true;
        }
      }
    }
    return result;
  },
  nameEnd : function(a, i, m) {
    var result = false, name = $(a).attr('name');
    if (name && typeof name == 'string') {
      if(!m[3]) {
        result = true;
      } else {
        var ss = (name.indexOf(']') != -1)? '[' + m[3] + ']' : m[3];
        if (name.indexOf(ss) != -1 && name.indexOf(ss) == name.length - ss.length)
          result = true;
      }
    }
    return result;
  }
});

function Fieldhelp(marker, fieldselectors) {    
  Fieldhelp.prototype.getFieldHelps(marker, function(fieldhelps){
    if (fieldhelps) {      
      $.each(fieldhelps, function(field, help){
        var label = $((fieldselectors && fieldselectors[field])? fieldselectors[field] : 'label[for="' + field + '"]');
        if (label.size()) {
          $(label).each(function(){
            $('<a />')
            .attr('class', 'helpicon')
            .html('&nbsp;').appendTo(this)
            .click(function(e){
              e.preventDefault();
            })
            .tooltip({
              bodyHandler : function(){
                return help;
              }
            });                             
          });
        }
      });      
    }
  });  
}
Fieldhelp.prototype.getFieldHelps = (function(){
  var helps = {}, queue = {}, status = {};
  return function(marker, callback) {            
    if (!status[marker]) {
      helps[marker] = {};
      queue[marker] = [];
      status[marker] = 'loading';
      $.getJSON('json.php', {
        controller:'general', 
        action:'fieldhelp', 
        marker : marker
      }, function(data){
        status[marker] = 'loaded';
        if (data.marker) {
          if (data.fields) {               
            helps[data.marker] = data.fields;
          }
          while(queue[data.marker].length) {
            (queue[data.marker].shift())(helps[data.marker]);
          }
        }
      });
    } 
    if (status[marker] == 'loading') {
      queue[marker].push(callback);
    } else {     
      callback(helps[marker]);
    }
  }
})();
function gup(href, name ) {
  var r = (new RegExp("[\\?&]"+name+"=([^&#]*)")).exec( href);
  return r == null? "" : r[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) {
  try {
    console.log(obj);
  }catch (e) {
    
  }
}


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=/";
}
DEVELOPERREQUEST = getCookie('DEVELOPERREQUEST');

