Rpc = {
  // Keep in sync with RpcResult::RESULT_SUCCESS
  RESULT_SUCCESS: 1,
  // Keep in sync with RpcResult::RESULT_FAILURE
  RESULT_FAILURE: 0
}

var Localization = {
  Init: function () {
    $('.localized').each(function(e) {
      e.observe('contextmenu',Localization.ShowDialog);
    });
  },
  SetLang: function(lang) {
    Rpc.request({
      params_obj:{req:'RpcApiTranslation_SetLang',
                  lang:lang
                 },
      callback:Rpc.saveMessageAndRefreshPage
    });
    return false;
  },
  ShowDialog: function(e) {
    var span = Event.element(e);
    //check two levels up for a localized element.
    if (!span.hasClassName("localized")) {
      span = $(span.parentNode);
      if (!span.hasClassName("localized")) {
        span = $(span.parentNode);
      }
    }
    //no localized element found, return.
    if (!span.hasClassName("localized")) {
      return false;
    }
    Dialog.offset_parent = span;
    Dialog.horizontal_offset = span.getWidth() * -1 + 50;
    Dialog.vertical_offset = -50;
    Dialog.should_scroll = false;
    var url = '/dialog_edit_translation';
    url += '?translation_pattern_id=' + span.getAttribute('translation_pattern_id');
    url += '&rt=json';
    Dialog.onclick(url);
    Event.stop(e); //dont show context menu
    return false;
  },
  EnableEdit: function() {
    Rpc.request({
      params_obj:{req:'RpcApiTranslation_TurnOn'},
      callback:Rpc.saveMessageAndRefreshPage
    });
    return false;
  },
  DisableEdit: function() {
    Rpc.request({
      params_obj:{req:'RpcApiTranslation_TurnOff'},
      callback:Rpc.saveMessageAndRefreshPage
    });
    return false;
  }
};


var Dialog = {
  class_name:'the-dialog',
  dom_id:'the_dialog',
  offset_parent:null,
  horizontal_offset:null,
  vertical_offset:null,
  should_scroll: null,
  
  onclick: function(url) {
    var dialog = this.getDialog();
    this.open();
    dialog.update('<div class="loading">Loading...</div>');
    Rpc.request({ajax_root:url,params_obj:{},callback:Dialog.loadHtml,method:'get',callback_scope:this});
  },
  
  addClickListeners: function(parent_element) {
    $(parent_element).getElementsBySelector('a').each(Dialog.addClickListener);
  },
  
  addClickListener: function(href) {
    var dialog = href.readAttribute('dialog');
    if (dialog) {
      //cleanup old events
      href.stopObserving('click');
      //add new events
      href.observe('click',function(event) {
        //because Prototype 1.6.0.3 is still broken for Event.isLeftClick...
        if (EventBugFix.isLeftClick(event) && !event.ctrlKey && !event.shiftKey) {
          Event.stop(event);
          var options = dialog.split(',');
          var xoffset = parseInt(options[0]);
          var yoffset = parseInt(options[1]);
          var shouldScroll = options[2] ? !!parseInt(options[2]) : true;
          Dialog.attach(this, xoffset, yoffset, shouldScroll);
        }
      });
    }
  },
  
  addFakeClickListener: function(href) {
    var dialog = href.readAttribute('dialog');
    if (dialog) {
      //cleanup old events
      href.stopObserving('a:open_dialog');
      //add new events
      href.observe('a:open_dialog',function(event) {
  var options = dialog.split(',');
  var xoffset = parseInt(options[0]);
  var yoffset = parseInt(options[1]);
        var shouldScroll = options[2] ? !!parseInt(options[2]) : true;
  Dialog.attach(this, xoffset, yoffset, shouldScroll);
      });
    }
  },
  
  attach: function(href, horizontal_offset, vertical_offset, should_scroll) {   
    this.offset_parent = $(href);
    this.horizontal_offset = horizontal_offset;
    this.vertical_offset = vertical_offset;
    this.should_scroll = should_scroll;
    var url = $(href).getAttribute("href");
      if (url.indexOf('?') == -1) {
          url += '?rt=json';
      } else {
          url += '&rt=json';
      }
    this.onclick(url.show());
    return false;
  },
  
  getDialog: function() {
    var dialog = $(this.dom_id);
    if (!dialog) {
      dialog = document.createElement('DIV');
      $('#page').appendChild(dialog);
      dialog = $(dialog);
      dialog.setAttribute('id',this.dom_id);
      dialog.addClassName(this.class_name);
    }
    return dialog;
  },
  close:function() {
    Event.stopObserving(document,'keydown', Dialog.keypressHandler);
    Effect.Fade(Dialog.dom_id, {duration: .2});
  },
  open:function() {
    var offset = this.offset_parent.cumulativeOffset();
    var dialog = this.getDialog();
    var page_offset = $(dialog.parentNode).cumulativeOffset();
    var viewport_width = document.viewport.getWidth();
    dialog.setStyle({
      'left': (offset.left - page_offset.left + this.offset_parent.getWidth() + this.horizontal_offset) + 'px',
      'top': (offset.top - page_offset.top + this.vertical_offset) + 'px'
    });
    Event.observe(document,'keydown', Dialog.keypressHandler);
    Effect.Appear(Dialog.dom_id, {duration: .2, afterFinish: function() { if(this.should_scroll) Effect.ScrollTo(Dialog.dom_id, {duration: .2, offset: -100});} });
  },
  keypressHandler:function(e) {
    if (e.keyCode == Event.KEY_ESC) {
      Dialog.close();
    }
  },
  loadHtml:function(json) {
    var dialog = this.getDialog();
    var header = '<div class="header clearfix"><div class="close"><a href="javascript:void(0);" onclick="Dialog.close();"></a></div>';
    if (json.data.html_header) {
      header += '<h1>'+json.data.html_header+'</h1>';
    }
    header += '</div>';
    var footer = "";
    if (json.data.html_footer) {
      footer = '<div class="footer clearfix">'+json.data.html_footer+'</div>';
    }
    
    var bubble_html = header + json.data.html + footer;
    bubble_html += '<div class="widget-dropshadow-top"></div><div class="widget-dropshadow-top-right"></div><div class="widget-dropshadow-right"></div><div class="widget-dropshadow-bottom-right"></div>';
    bubble_html += '<div class="widget-dropshadow-bottom"></div><div class="widget-dropshadow-bottom-left"></div><div class="widget-dropshadow-left"></div><div class="widget-dropshadow-top-left"></div>';
    dialog.update(bubble_html);
  },
  formSubmit:function(form,callback) {
    form = $(form);
    if (!callback) {
      callback = Dialog.callbackDisplayMessage;
    }
    form.request({onComplete:callback});
  },
  callbackRedirect:function(transport) {
    var json = transport.responseText.evalJSON();
    if (json.result_code == Rpc.RESULT_SUCCESS) {
      redirect(json.suggested_redirect_url,json.message_list);
    } else {
      json.data.html_header = 'Information';
      json.data.html = '';
      for (var i = 0; i < json.message_list.length; i++) {
        json.data.html += '<div class="message">'+json.message_list[i].message_body_html+'</div>';
      }
      json.data.html_footer = '<div style="text-align:right;margin:8px 0px;"><a class="submitbtn" href="javascript:Dialog.close();">Close</a></div>';
      Dialog.loadHtml(json);
    }
  },
  callbackDisplayMessage:function(transport) {
    var json = transport.responseText.evalJSON();
    if (json.message_list) {
      if (!json.data) {
        json.data = {};
      }
      if (json.result_code == Rpc.RESULT_SUCCESS) {
        json.data.html_header = 'Success';
      } else {
        json.data.html_header = 'Information';
      }
      json.data.html = '';
      for (var i = 0; i < json.message_list.length; i++) {
        json.data.html += '<div class="message">'+json.message_list[i].message_body_html+'<\/div>';
      }
      json.data.html_footer = '<div style="text-align:right;margin:8px 0px;"><a class="submitbtn" href="javascript:Dialog.close();">Close<\/a><\/div>';
      Dialog.loadHtml(json);
    }
  }
}

function resendVerify() {
  $.ajax({
    url:'/ajax/?req=RpcApiWww_SendVerificationMail',
    success:function(json) {
      if (json.result_code == Rpc.RESULT_SUCCESS) {
        alert(json.message_list[0].message_body);
      } else {
        alert("An error occurred.");
      }
    }
  });
  return false;
}


/*--------------------------------------------------
  cookie-related methods
  Taken from http://www.quirksmode.org/js/cookies.html
--------------------------------------------------*/

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+escape(value)+expires+"; path=/; domain=" + DOMAIN;
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function eraseCookie(name) {
  createCookie(name,"",-1);
}



/**
 * Utilities for checking for browser features.
 */
var BrowserCheck = {
  /**
   * Check that the user has cookies. If not, then redirect to the user
   * to the error page.
   */
  'testForCookies' : function () {
    var test_cookie = 'cookie_test';
    var test_value = '1';
    createCookie(test_cookie, test_value, 0);
    if (test_value == readCookie(test_cookie)) {
      eraseCookie(test_cookie);
    } else {
      // redirect to error page
      window.location = '/cookieless';
    }
  }
};


