DEVMODE = false;
BASEURL = $('head base').attr('href') + '/';
PAGELANG = $('head meta[name=lang]').attr('content');



function reportError (msg, data){
  var report = [];
  report.push(msg);
  if (data)
    report.push(data);
  if (DEVMODE) {
    alert($.dump(report));
  } else {
    report.push("url: " + document.location.href);
    report.push("Browser CodeName: " + navigator.appCodeName);
    report.push("Browser Name: " + navigator.appName);
    report.push("Browser Version: " + navigator.appVersion);
    report.push("Cookies Enabled: " + navigator.cookieEnabled);
    report.push("Platform: " + navigator.platform);
    report.push("User-agent header: " + navigator.userAgent);
    $.post(BASEURL + 'json.php?controller=general&action=reporterror', {
      report : report
    });
  }
}

function updateSecondsInUploadinprogress(selector, sec) {
  if (selector && $(selector).get(0)) {
    $(selector).text(sec);
    sec++;
    setTimeout("updateSecondsInUploadinprogress('" + selector + "', " + sec + ")", 1000);
  }
}

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=/";
}



function getOffsets (el) {
  var o = {
    x : el.offsetLeft,
    y : el.offsetTop
    };
  if (el.offsetParent != null) {
    var po = getOffsets(el.offsetParent);
    o.x += po.x;
    o.y += po.y;
  }
  return o;
}
(function($){
  $.extend($.expr[':'],{
    name: function(a, i, m) {
      var result = false, name = $(a).attr('name');
      if (name) {
        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;
    }
  });
})(jQuery);
(function($) {
  $.loadingIndicator = (function ($) {
    var
    self = $('#loading_indicator'),
    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;
      }
    }
    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 (DEVMODE) {
      $.post(BASEURL + 'json.php?controller=general&action=translate', {
        path : path,
        word : word
      });
    }
    return translation;
  };

  $.showmessage = function(type, message, removePrev, hideTimeout) {
    if (removePrev == 'error')
      $('div.msg_error').remove();
    else if (removePrev == 'success')
      $('div.msg_success').remove();
    else if (removePrev)
      $('div.msg_error,div.msg_success').remove();

    var uid = $.uniqId(),  html = '<div class="msg_' + type + '" id="' + uid + '"><a href="" class="close"></a><p>' + message + '</p></div>', selectors = ['.TB_contentClass h2', '#maincontent h1 div.tabs', '#maincontent h1'], found = false, i, l = selectors.length;
    for (i = 0; 0 <= l; i++) {
      if (found = $(selectors[i]).get(0))
        break;
    }
    if (found) {
      $(html)
      .insertAfter(found)
      .find('a.close').click(function(e){
        e.preventDefault();
        $(this).parent().slideUp('fast', function(){
          $(this).remove();
        });
      });
           
    } else {
      alert(type + "\n" + message);
    }
    if (hideTimeout && (hideTimeout = parseInt(hideTimeout)))
      setTimeout ("$('#" + uid + "').slideUp().remove();", hideTimeout);
    return $('#' + uid);
  }
    
  $.reloadPage = function(error){
    $(
      '<form action="' + BASEURL + PAGELANG + '/generalredirecturl" method="post">' +
      '<input type="hidden" name="redirecturl" value="' + document.location.href + '" />' +
      (error? '<input type="hidden" name="error" value="' + error + '_reload" />' : '') +
      '</form>'
      )
    .appendTo('body')
    .submit();
    //            document.location.href = document.location.href;
    return false;
  }

  $.json = (function($) {
    var timeout = null;
    return function() {
      var arg = $.makeArray(arguments), controller = arg.shift(), action = arg.shift(), data = {}, callback = function(){}, showMessage = true;
      for (var i = 0; i<= 3; i++) {
        switch (typeof arg[i]) {
          case 'function':
            callback = arg[i];
            break;
          case 'object':
            data = arg[i];
            break;
          case 'boolean':
            showMessage = arg[i];
            break;
        }
      }
      $.loadingIndicator.init(true);
      if (timeout)
        clearTimeout(timeout);
      timeout = setTimeout("$.showmessage('error', $.translate('error_loading_data', 'general.error'));$.loadingIndicator.stop();", 5000);
      $.post(BASEURL + 'json.php?controller=' + controller + '&action=' + action, data, function(j, textStatus) {

        var status = 'success', message = null;
        var mes = 'success';
        try {
          if (textStatus != 'success')
            throw new Error (textStatus);
          else if (j.status == 'failure' || j.error)
            throw new Error (j.error);
          if (j.success)
            message = j.success
        } catch(e) {
          if (e.message == 'no_auth')
            return $.reloadPage(e.message);
          message = e.message;
          status = 'error';
          if (e.message == 'illegal_request') {
            showMessage = false;
            if ($.isFunction($.TBshowLogin))
              $.TBshowLogin();
            else
              return $.reloadPage(e.message);
          }
                    
        }
                
        if (showMessage && message)
          $.showmessage(status, message, true, 10000);
        clearTimeout(timeout);
        $.loadingIndicator.stop();
        callback(j, status, message);
      }, 'json');
    };
  })(jQuery);




  $.uniqId = function() {
    return ((new Date()).getTime() + "" + Math.floor(Math.random() * 1000000)).substr(0, 18);
  };

  $.allow_only_symbols = function(val, symbols){
    var result = '';
    if (val == '')
      return;

    for (var i = 0; i < val.length; i++) {
      temp = "" + val.substring(i, i+1);
      if (symbols.indexOf(temp) != '-1')
        result += temp;
    }
    return result;
  }


})(jQuery);

function replaceURLWithHTMLLinks(text) {
  var e = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  return text.replace(e,"<a target='blank' href='$1'>$1</a>");
}

