var suffixes = {};
var endings = {};

function number_format(num, lttf)
{
  //Estimated value    Show as
  //0                  0 (literal text)
  //1-10               <10  (literal text)
  //11-99              number to 1 s.f. in format "n0" e.g. 20
  //100-999            number to 2 s.f. in format "nn0" e.g. 120
  //1000-999999        number to 2 s.f.  e.g.   1.2K  12K   120K
  //1M+                number in millions to 2 s.f. with letter "M" e.g. 1.2M, 12M, 120M

  num = parseInt(num);

  if (isNaN(num))
  {
    return 0;
  }

  numstr = num.toString();

  switch (true)
  {
    case (num <= 0) :
      return "0";
      break;

    case (num < 10) :
      return "<10";
      break;

    case (num >= 10 && num <= 100) :
      return numstr.replace(/(\d}\d)/, '$10');
      break;

    case (num > 100 && num <= 1000) :
      var sub = num.toString().substring(0, 2);
      numstr = numstr.replace(/./g, "0").replace("00", sub);
      return numstr;
      break;

    case (num > 1000) :
      th = false;
      var mil = (num / 1000000);
      if (mil < 1)
      {
        th = true;
        mil = (num / 1000);
      }
      var numstr = num.toString().replace(/./g, '0').replace(th ? (/\d{4,5}$/) : (/\d{7,8}$/), th ? "K" : "M")
      return mil.toString().replace(/^(\d\.?\d).*/, '$1') + numstr;
      break;

    default:
      return "";
      break;
  }


  return num.toString();
}

function _paint_rows(param, cls)
{
  rows = jQuery('#' + param).find('tbody.keyword_pages tr');
  if (rows.length == 0)
    {
      rows = jQuery('#' + param).find('tbody tr');
    }
  var sw = false;
  jQuery.each(rows, function(){
    e = jQuery(this);
    if (e.attr('id') != 'noListItemsMsg')
    {
      cls = cls == null ? 'row' : cls;
      e.removeClass( sw ? cls + "0" : cls + "1");
      e.addClass( sw ? cls + "1" : cls + "0");
      sw = !sw;
    }

  });
}

function error_pro(message)
{
  jQuery('#create_project_notice').append("<br>" + message);
}

function hide_error_pro()
{
  jQuery('#create_project_notice').html("&nbsp;");
}

function open_popup(url, custom_css)
{
  if (jQuery('#popup_div').length == 0)
  {
    Big = jQuery('<div id="screen_fader"></div>');
    Popup = jQuery('<div id="popup_div"></div>');
    Popup.css('cursor', 'wait');

    if (custom_css != null)
    {
      for (property in custom_css)
      {
        Popup.css(property, custom_css[property]);
      }
    }

    jQuery('body').append(Popup);
    jQuery('body').append(Big);
    Popup.append(jQuery('<div></div>').append(jQuery('<a href="javascript:;" onclick="close_popup(); return false;">Close</a>')).css('width', (Popup.width() - 16) + 'px').css('position', 'fixed').css('background', '#fff').css('padding', '20px 0 3px 0').css('margin-top', '-20px')  );
    //.css('position', 'fixed').css('background', '#fff').css('padding', '2px 20px')
   //   .css('left', (parseInt(Popup.css('left')) + 1 ) + 'px' )
     // .css('right', (parseInt(Popup.css('right')) + 17) + 'px')
      //.css('top', (parseInt(Popup.css('top') + 1 ) + 'px' )));

    Popup.append(jQuery('<br>'));
    Popup.append(jQuery('<div id="popup_div_'+url.replace(/\W/g, "")+'"></div>'));
  }

  jQuery.get(url, null, function(data)
  {
    pdc = (jQuery('#popup_div_'+this.url.replace(/\W/g, "")));
    if (pdc.length == 1)
    {
      jQuery('#popup_div').css('background-image', 'none');
      jQuery('#popup_div').css('cursor', 'default');
      pdc.html(data);
    }
  }
  );
  return false;
}

function close_popup()
{
  jQuery('#popup_div').remove();
  jQuery('#screen_fader').remove();
}

function _confirm(msg, ok_function, cancel_function)
{
  if (jQuery('#confirm_div').length == 0)
  {
    Big = jQuery('<div id="screen_fader"></div>');
    Alert = jQuery('<div id="confirm_div"></div>');
    Alert.append(jQuery('<div>' + msg.replace("\n", "<br>") + '</div>'));
    InputDiv = jQuery('<div></div>')
    Alert.append(InputDiv);
    InputDiv.append(jQuery('<input type="button" value="OK" class="button_fb">').click(function(){try{ok_function();} catch(e){ } jQuery('#screen_fader').remove();jQuery('#confirm_div').remove(); return false;}));
    InputDiv.append(jQuery('<input type="button" value="Cancel" class="button_fb">').click(function(){try{cancel_function();} catch(e){ } jQuery('#screen_fader').remove();jQuery('#confirm_div').remove(); return false;}));
    jQuery('body').append(Big);
    jQuery('body').append(Alert);
  }
}

function _alert(msg, ok_function)
{
  if (jQuery('#alert_div').length == 0)
  {
    Big = jQuery('<div id="screen_fader"></div>');
    Alert = jQuery('<div id="alert_div"></div>');
    Alert.append(jQuery('<div>' + msg.replace("\n", "<br>") + '</div>'));
    Alert.append(jQuery('<input type="button" value="OK" class="button_fb">').click(function(){try{ok_function();} catch(e){ } jQuery('#screen_fader').remove();jQuery('#confirm_div').remove(); return false;}));
    jQuery('body').append(Big);
    jQuery('body').append(Alert);
  }

}

function _wait(msg, w, h)
{
  if (jQuery('#wait_div').length == 0)
  {
    Big = jQuery('<div id="screen_fader"></div>');
    Alert = jQuery('<div id="wait_div"></div>');
    Alert.append(jQuery('<div>' + msg.replace("\n", "<br>") + '</div>'));
    Alert.css('width', parseInt(w) + 'px');
    Alert.css('height', parseInt(h) + 'px');
    Alert.css('margin-left', - parseInt(w) / 2 + 'px');
    Alert.css('margin-top', - parseInt(h) / 2 + 'px');
    jQuery('body').append(Big);
    jQuery('body').append(Alert);
  }
}

function _hide_wait()
{
  jQuery('#screen_fader').remove();
  jQuery('#wait_div').remove();
}

function _is_en(tp, id)
{
  return (jQuery('#' + tp + '_' + id).length > 0) ? true : false;
}

function _en(tp, message, id)
{
  errs = jQuery('.flash_' + tp + ' p');
  jQuery.each(errs, function() {
    if (!Boolean(jQuery(this).attr('id')))
    {
      jQuery(this).remove();
    }
  })

  if (!_is_en(tp, id))
  {
    err = jQuery('.flash_' + tp);
    err.fadeIn(500);
    err.append('<p id="' + tp + '_' + id + '">' + message + '</p>').css("opacity", "1");
  }
}

function _hide_en(tp, id)
{
  if (_is_en(tp, id))
  {
    err_div = jQuery('.flash_' + tp);
    err_div.slideUp(100);
    err = jQuery('#' + tp + '_' + id);
    err.remove();
  }
}

function notice(message, id)
{
  _en("notice", message, id);
}

function error(message, id)
{
  _en("error", message, id);
}

function hide_error(id)
{
  _hide_en("error", id);
}

function hide_notice(id)
{
  _hide_en("notice", id);
}

function delete_project(href)
{
  hide_notice("deleted");
  _confirm("Are you sure? Deleted projects cannot be recovered.", function() {
    cd = jQuery('#confirm_div');
    _wait("deleting...", jQuery('#confirm_div').width(), jQuery('#confirm_div').height());
    jQuery.ajax({
        type: "GET",
        url: href,
        data: {},
        dataType: "json",
          success: function(data) {
            _hide_wait();
            if (data != null && data.status != null && data.status == "ok")
              {
                jQuery('#project_tr' + data.project_id).remove();
                projects_count--;
                _paint_rows('projects_list', 'default-table-row-');
                hide_error('max');
                notice("Project was deleted", "deleted");
              }
            else
              {
                this.error();
              }
          },
          error: function(data){
            _hide_wait();
            error("Error", "deleted");
          }
        }
      );

  }, null);
}

  function iframe_post(iframe_element, action, params, method)
  {
    request = action;
    iframe_document = iframe_element.contentWindow.document;
    ex_form_ = iframe_document.createElement("form");
    ifr_body = iframe_document.getElementsByTagName("body");
    if (ifr_body.length == 0)
    {
        iframe_document.getElementsByTagName("html")[0].appendChild(iframe_document.createElement("body"));
    }
    iframe_document.getElementsByTagName("body")[0].appendChild(ex_form_);

    ex_form_.action = action;
    ex_form_.method = method == null ? "POST" : method;
    ex_form_.style.display = 'none';

    for (var key in params)
    {
        var val = params[key];
        request += key + '=' + val + '&';
        curr_input = iframe_document.createElement('input');
        curr_input.type = 'hidden';
        curr_input.name = key;
        curr_input.value = val;
        ex_form_.appendChild( curr_input );
    }
    if (AUTH_TOKEN != null)
      {
        auth_input = iframe_document.createElement('input');
        auth_input.type = 'hidden';
        auth_input.name = 'authenticity_token';
        auth_input.value = AUTH_TOKEN;
        ex_form_.appendChild( auth_input );
      }
    ex_form_.submit();
    iframe_document.getElementsByTagName("body")[0].removeChild(ex_form_);
  }

function toS (obj) {
    if (obj == null)
      {
        return 'null';
      }
    var con = obj.constructor;
    if(con == String) {
        return '"' + obj + '"';
    } else if(con == Boolean) {
        return (obj ? 'true' : 'false');
    } else if(con == Number) {
        return obj;
    } else if(con == Array) {
        var res = '[';
        for(var i=0,len=obj.length;i<len;i++) {
            if(i == len-1)
                res += toS(obj[i]) + ']';
            else
                res += toS(obj[i]) + ', ';
        }
        return res;
    } else if(con == RegExp) {
        return obj;
    } else if(con == Object) {
        var res = '{';
        var i=0;
        for(var j in obj) {
            if(j != 'toS') {
                if(i == 0) {
                    res += "'" + j + "'" + ':' + toS(obj[j]);
                } else {
                    res += ", '" + j + "' :" + toS(obj[j]);
                }
                i++;
            }
        }
        res += '}';
        if(arguments.length) {
            return res;
        } else {
            return '(' + res + ')';
        }
    }
}



function get_domain_root(url)
{
    top2level = url.replace(/((https?|ftp)\:\/\/)?([^\.\/]*\.)*([^\/]+\.[^\/\:]+)(\:\d{1,5})?\/?.*/, "$4");
    t2 = (top2level in suffixes) ? top2level : false;

    dom_re = /((https?|ftp)\:\/\/)?(.*\.)*([^\/]+)(\.[^\/:]+)(\:\d{1,5})?\/?.*/;
    if (t2)
    {
      dom_re = new RegExp('((https?|ftp)\\:\/\/)?(.*\\.)*([^\/]+)\\.(' + t2.replace(".", "\\.") + ')(\\:\\d{1,5})?\\/?.*');
    }
    return url.replace(dom_re, '$4');
}

jQuery(function() {

  jQuery.get("/suffixes.xml", {}, function(data, textStatus) {
    jQuery.each(jQuery(data).find("s"), function()
    {
      suffixes[jQuery(this).attr("d")] = true;
    })
    jQuery.each(jQuery(data).find("e"), function()
    {
      endings[jQuery(this).attr("d")] = true;
    })
    if (typeof(url_list) !== 'undefined' && url_list != null)
    {
      jQuery.each(url_list, function()
      {
        add_url_to_list(this.url, this.tp);
      });
    }
  }, "xml");

  jQuery('#top_menu a[href="'+ window.location.pathname +'"]').parent().addClass("selected");
  jQuery('#AddProject_add_new_project').click(function() {
    if (projects_count >= projects_max_allowed)
    {
      error('The beta is limited to ' + projects_max_allowed + ' projects. If you want to create a new project, delete a project first ', 'max');
      return false;
    }
  });
  jQuery('#project_getlistfromfile').click(function() {
    hide_error_pro();
    var file_upload = jQuery('#file_upload_step2');
    if (file_upload.length == 0){
      file_upload = jQuery('#file_upload_step3');
    }

    if (file_upload.css('display') == "none")
    {
      file_upload.slideDown(1000);
    }
    else
    {
      file_upload.slideUp(1000);
    }
  });

  jQuery('.view_keywords_link').click(function() {
        open_popup(this.href, {position: 'fixed', top: '50%', left: '50%', width: '600px', height: '400px', margin: '-200px 0 0 -300px'});
        return false;
        }
      );
  jQuery('.signal_change').click(function() {
        jQuery('#' + this.id.replace('change', 'content')).attr('disabled', !jQuery(this).attr('checked'));
		jQuery('#' + this.id.replace('change', 'advanced')).attr('disabled', !jQuery(this).attr('checked'));
  });

  jQuery('#play_video_icon').click(function() {
    Big = jQuery('<div id="screen_fader"></div>');
    Popup = jQuery('<div id="popup_div"></div>');
    jQuery('body').append(Big);
    jQuery('body').append(Popup);
    Video = jQuery('#video_container_popup');
    Popup.append(Video);
    Video.show();
    jQuery('body').append(Close = jQuery('<img src="/images/close_video.png" class="close_video_button">').click(function() {
      jQuery('#video_container_popup').hide().appendTo(jQuery('body'));
      jQuery('#popup_div').remove();
      jQuery('.close_video_button').remove();
      jQuery('#screen_fader').remove();
    }))

    Popup.css('background-image', 'none');
    Popup.css('left', '50%');
    Popup.css('top', '50%');
    Popup.css('margin-top', '-' + Video.height() / 2 + 'px');
    Popup.css('margin-left', '-' + Video.width() / 2 + 'px');
    Close.css('margin-top', '-' + (Video.height() / 2 + 10) + 'px');
    Close.css('margin-left', (Video.width() / 2 + 30) + 'px');
    Popup.css('overflow', 'hidden');
    Popup.css('width', Video.width() + 'px');
    Popup.css('height', Video.height() + 'px');
  })
});