function queries_toogle(type, id){
  s = document.getElementById('q'+type+'_'+id).style
  s.display = (s.display != 'block') ? 'block' : 'none'
}

function send_ajax_js(type, url, params)
{
  var data = magic;
  if (params != "")
  {
    data = params + "&" + magic;
  }
  $.ajax({
    type: type,
    url: url,
    data: data,
    dataType: "script",
    'beforeSend': function(xhr) { xhr.setRequestHeader("Accept", "text/javascript") }
  });
}

function init_tiny_mce(selector)
{
  $(selector + 'textarea.tinymce').tinymce({
    // Location of TinyMCE script
    script_url : '/tiny_mce/tiny_mce.js',

    // General options
    theme : "advanced",
    plugins : "safari,style,table,advimage,advlink,inlinepopups,insertdatetime,preview,contextmenu,paste,fullscreen,visualchars,nonbreaking,xhtmlxtras,template",

    // Theme options
    theme_advanced_buttons1 : "newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
    theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
    theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,fullscreen,|,styleprops,|,nonbreaking,template",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    theme_advanced_statusbar_location : "bottom",
    theme_advanced_resizing : true,

    // Example content CSS (should be your site CSS)
    content_css : "/stylesheets/tiny.css",

    // Drop lists for link/image/media/template dialogs
    template_external_list_url : "lists/template_list.js",
    external_link_list_url : "lists/link_list.js",
    external_image_list_url : "lists/image_list.js",
    media_external_list_url : "lists/media_list.js",

    // Replace values for the template plugin
    template_replace_values : {
      username : "Some User",
      staffid : "991234"
    }
  });
}

function jquery_init()
{
  $.fn.media.defaults.flvPlayer = '/samples/mediaplayer.swf'
  $.fn.media.defaults.mp3Player = '/samples/mediaplayer.swf'

  if ($.isFunction($.fn.datepicker)) {
    $('.datepicker').datepicker({
      dateFormat: 'dd MM yy',
      firstDay: 1,
      dayNamesMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб']
    });
  }

  jquery_apply('');
  happy_in_place('.in-place', true);
}

function jquery_apply(selector)
{
  if ($.isFunction($.fn.tooltip)) 
    $(selector + '.tooltip').tooltip();

  if ($.isFunction($.fn.media)) {
    $(selector + 'a.media-audio').media({ width: 300, height: 20 });
    $(selector + 'a.media-video').media();
  }

  if ($.isFunction($.fn.lightbox)) {
    $(".lightbox").lightbox({
      fileBottomNavCloseImage : '/images/jquery/lightbox-closelabel.ru.gif',
      strings : {
        help: '',
        prevLinkTitle: 'предыдущая фотография',
        nextLinkTitle: 'следующая фотография',
        prevLinkText:  '&laquo; Пред',
        nextLinkText:  'След &raquo;',
        closeTitle: 'Закрыть',
        image: 'Фото',
        of: ' из '
      }
    });
  }

}


/************************************
 * in-place editing 
 ***************************************/

function happy_id(elem) {
  var p = $(elem);
  while (p && !p.hasClass('in-place')) p = p.parent();
  return p.attr('id');
}

function happy_context(id)
{
  var j_field = $('#' + id).children('input.context');
  if (j_field.length == 0) {
    j_field = $('#' + id + ' input.context');
  }

  if (j_field.length == 0) {
    alert('Алексей Николаевич, Вы забыли отрендерить контекст, ядрена вошь.');
    return "";
  } else if (j_field.length > 1) {
    alert('Алексей Николаевич, я нашел больше одного конекста.');
    return "";
  } else {
    return j_field.val();
  }
}

function happy_submit(id, url)
{
  var data = magic;
  data += '&context=' + happy_context(id);
  data += '&mode=render2'
  data += '&' + $('#' + id).find('form').serialize();
  $.post(url, data, function(resp){
    $('#' + id).empty();
    $('#' + id).replaceWith(resp);
    happy_in_place('#' + id);
  });
  return false;
}

function happy_in_place(selector, not_apply)
{
  if (selector) 
    selector += " ";
  else 
    selector = '';

  if (!not_apply)
    jquery_apply(selector);

  if (enable_tiny_mce){
    init_tiny_mce(selector);
  }

  // normal edit link
  $(selector + 'a.edit').click(function(){
    var id = happy_id(this);
    $.get('/admin/form', $.param({context: happy_context(id)}) + '&mode=edit', function(resp){
      $('#' + id).empty();
      $('#' + id).replaceWith(resp);
      happy_in_place('#' + id);
    });
    return false;
  });

  // normal cancel link
  $(selector + 'a.cancel').click(function(){
    var id = happy_id(this);
    $.get('/admin/form', $.param({context: happy_context(id)}) + '&mode=render2', function(resp){
      $('#' + id).empty();
      $('#' + id).replaceWith(resp);
      happy_in_place('#' + id);
    });
    return false;
  });

  // normal submit button
  $(selector + 'input.btn_save').click(function(){
    var id = happy_id(this);
    return happy_submit(id, '/admin/model_update');
  });

  // hash submit button
  $(selector + 'input.btn_save-hash').click(function(){
    var id = happy_id(this);
    return happy_submit(id, '/admin/model_hash_update');
  });

  // chunk submit button
  $(selector + 'input.btn_save-chunk').click(function(){
    var id = happy_id(this);
    return happy_submit(id, '/admin/chunk_update');
  });

  // normal submit form
  $(selector + 'form.self-submit').submit(function(){
    var id = happy_id(this);
    return happy_submit(id, '/admin/model_update');
  });

  // checkbox submit form
  $(selector + 'input.checkbox-submit').click(function(){
    var id = happy_id(this);
    return happy_submit(id, '/admin/model_update');
  });

  if($(selector + '.happy_upload').length > 0)
  {
    $(selector + '.happy_upload').each(function(i){
      var html_id = $(this).attr('id');
      var id = happy_id(this);
      var data = {};
      data[magic_key] = magic_value;
      data['context'] = happy_context(id);
      new AjaxUpload(html_id, {
        action: '/admin/ajax_upload_file',
        data: data,
        name: 'attach',
        onComplete: function(file, resp){
          $('#' + id).empty();
          $('#' + id).replaceWith(resp);
          happy_in_place('#' + id);
        }
      });
      $('#' + html_id).click();
    });
  }

  if($(selector + '.in-place-field').length > 0) {
    $(selector + '.in-place-field').focus();
  }

  // arr_keys add row link
  $(selector + 'a.add_row_arr_keys').click(function(){
    var next = $(selector + '.arr_keys_row').length;
    $(selector + '.happy_arr_keys_edit_area').append('<div class="arr_keys_row">' +
        '<form>' +
          '<input id="key_' + next + '" name="keys[' + next + ']" type="text" value="" /> ' +
          '<input id="value_' + next + '" name="values[' + next + ']" type="text" value="" />' + 
        '</form>' + 
      '</div>');
    return false;
  });

  // arr_keys submit
  $(selector + 'input.arr_keys_btn_save').click(function(){
    var id = happy_id(this);
    return happy_submit(id, '/admin/arr_keys_update');
  });
}




/* original tiny mce
function init_tiny_mce()
{
  $('textarea.tinymce').tinymce({
    // Location of TinyMCE script
    script_url : '/tiny_mce/tiny_mce.js',

    // General options
    theme : "advanced",
    plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

    // Theme options
    theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
    theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
    theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
    theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    theme_advanced_statusbar_location : "bottom",
    theme_advanced_resizing : true,

    // Example content CSS (should be your site CSS)
    content_css : "/stylesheets/screen.css",

    // Drop lists for link/image/media/template dialogs
    template_external_list_url : "lists/template_list.js",
    external_link_list_url : "lists/link_list.js",
    external_image_list_url : "lists/image_list.js",
    media_external_list_url : "lists/media_list.js",

    // Replace values for the template plugin
    template_replace_values : {
      username : "Some User",
      staffid : "991234"
    }
  });
}
*/
