/**
 * @author: Miroslav Kvasnica - niwi - miradrda@volny.cz, niwiweb.wz.cz
 * @date: 23.10.2010
 */
var SMALL_THUMB_WIDTH = 55;
var SMALL_THUMB_HEIGHT = 45;

// !!!
// !!! VAR actualizeFunction IS ON THE BOTTOM (must be after actualize definition!!! )
// !!!

$(function()
{
  // for detail and list values
  $(".gsf_thumb img").resize();
  // add control buttons after the input field
  $(".gsfr_file").each(prepareInput);
  $(".gsfr_file").live('change', function(){actualizeFunction($(this).attr('name'), $(this).val());});
  // buttons actions
  $(".gsfr_file_add").live('click', upload);
  $(".gsfr_file_load").live('click', loadImageAndFile);
});

var prepareInput = function ()
{
  var name = $(this).attr('name');
  var path;
  
  // prefix before input if forceDir
  if (gsfrFiles[name][2])
  {
    path = friendlyPath(gsfrFiles[name][1]);
    $(this).before('<strong id="'+name+'_prefix">'+url(gsfrFiles[name][0], path)+'/</strong>');
    $(this).width('150px');
  }
  // icons after
  var string = icon('/images/system/icons/arrow_up.png', '', 'Nahrát nový obrázek', '', 'gsfr_file_add');
  string += icon('/images/system/icons/folder_image.png', '', 'Vložit existující obrázek', '', 'gsfr_file_load');
  $(this).after(string);
  actualizeFunction(name, $("#"+name).val());
}

var upload = function ()
{
  var name = $(this).prev('.gsfr_file').attr('name');
  if (!gsfrFiles)
    return err('Chyba při otevírání souborového dialogu');
  var targetWeb = gsfrFiles[name][0];
  var targetDir = gsfrFiles[name][1];
  var minimizeFilenames = gsfrFiles[name][3];

  // display dialog
    $('html').append('<div id="uploadDialog">\
<iframe id="gsrb_file_iframe" name="gsrb_file_iframe" src="'+ targetWeb +'/ajax/forms-basic/upload_file_dialog.php?targetDir='+ targetDir +'&baseDir='+ targetDir +'&minimizeFilenames='+ minimizeFilenames +'" style="width: 90%; height: 90%"></iframe>\
</div>');
  $('#uploadDialog').data('name', name);  // store dialog's corresponding field name
  $('#uploadDialog').dialog({modal: true, title: 'Nahrát nový soubor', width: 450, height: 400, beforeClose: closeAddDialog, buttons: {"Ok": closeAddDialog}});

  return false;
}


var closeAddDialog = function()
{
  $.get('/ajax/forms-basic/get_last_file.php', finishUploading);
}

var finishUploading = function (data)
{
  if (isError(data))
    return err('Chyba při zjišťování jména právě nahraného souboru.', data);
  var name = $('#uploadDialog').data('name');
  actualizeFunction(name, data['data']);
  $('#uploadDialog').remove();
  return true;
}


var loadImageAndFile = function ()
{
  $('.gsrb_panel_thumb').live('click', selectImage);
  var name = $(this).prevAll('.gsfr_file').attr('name');
  if (!gsfrFiles)
    return err('Chyba při otevírání souborového dialogu');
  var targetWeb = gsfrFiles[name][0];
  var targetDir = gsfrFiles[name][1];

  // load image names
  $.get('/ajax/forms-basic/file_gateway.php?targetWeb='+ targetWeb +'&targetDir=' + targetDir, finishLoading);

  // display dialog
    $('html').append('<div id="loadDialog">\
Soubory ve složce:<br />\
'+ friendlyPath(url(targetWeb, targetDir)) +'\
<p class="gsrb_image_pane center">Načítám...<br /><img src="/images/system/graphics/loading.gif" alt="Načítání" /></p>\
</div>');
  $('#loadDialog').data('name', name);  // store dialog's corresponding field name
  $('#loadDialog').dialog({modal: true, title: 'Vybrat soubor', width: 600, beforeClose: closeLoadDialog, buttons: {"Zavřít": closeLoadDialog}});

  return false;
}



var finishLoading = function (data)
{
  if (isError(data))
    return err('Chyba při zjišťování jména právě nahraného souboru.', data);

  var name = $('#loadDialog').data('name');
  var targetWeb = gsfrFiles[name][0];
  var targetDir = gsfrFiles[name][1];
  
  // fill dialog with images
  var info = data['data']['files'].length ? 'Nalezeno souborů: '+data['data']['files'].length : 'Nenalzeny žádné soubory.'
  $('.gsrb_image_pane').html(info+"<br />\n");
  var key = '';
  var images = data['data']['files'];
  for (key in images)
  {
    $('.gsrb_image_pane').append(displayImage(friendlyPath(url(targetWeb, targetDir)), data['data']['files'][key]));
  }
  $('.gsrb_image_pane img').resize();

  return true;
}



var closeLoadDialog = function()
{
  $('#loadDialog').remove();
}



var actualize = function (name, value)
{
  var file;
  var targetWeb = gsfrFiles[name][0];
  var targetDir = gsfrFiles[name][1];
  var forceDir = gsfrFiles[name][2];
  var path1 = url(targetWeb, targetDir);
  var path2 = friendlyPath(path1);
  
  if (forceDir)
    file = minimizePath(value, targetWeb, targetDir);
  else
    file = friendlyPath(value);
  //file = friendlyPath(url(targetWeb, targetDir, value));

  if (forceDir && file.indexOf('/') != -1)
  {
    err('Zadaná cesta k souboru není povolena. Musíte zadat soubor z umístění '+ path1 +' nebo '+ path2 +'.');
    file = '';
  }
  $('#'+name).val(file);

  $('#'+name+'_thumb').remove();
  if (file && $('#'+name).hasClass('image'))
  {
    var src = forceDir ? url(targetWeb, targetDir, file) : file;
    $('#'+name).parent('td').prepend('<a id="'+name+'_thumb" class="gsf_thumb" href="'+ src +'"><img src="'+src+'" width="'+ SMALL_THUMB_WIDTH +'px" height="'+ SMALL_THUMB_HEIGHT +'px" alt="" /></a>');
    $('.gsf_thumb img').resize();
  }
}


/**
 * Comment
 */
function displayImage (path, name)
{
  return '<a class="gsrb_panel_thumb" href="'+ url(path, name) +'">\n\
<img src="'+ url(path, name) +'" title="'+ name +'" width="'+ SMALL_THUMB_WIDTH +'" height="'+ SMALL_THUMB_HEIGHT +'" />\n\
<br />\n\
<span>' + name +'</span>\
</a>';
}


var selectImage = function ()
{
  var name = $('#loadDialog').data('name');
  actualizeFunction(name, $(this).find('img').attr('src'));
  closeLoadDialog();
  return false;
}



/**
 * Params maxWidth, maxHeight are optional
 */
jQuery.fn.resize = function (maxWidth, maxHeight)
{
  $(this).each(function(){resize($(this), maxWidth, maxHeight)});
}



/**
 * Params maxWidth, maxHeight are optional
 */
function resize (image, maxWidth, maxHeight)
{
  if (!maxWidth)
    maxWidth = SMALL_THUMB_WIDTH;
  if (!maxHeight)
    maxHeight = SMALL_THUMB_HEIGHT;
  var res = {width: 0, height: 0};
  var img = new Image();
  img.src = $(image).attr('src');

  if (!img.complete)
  {
    $(image).load(function(){resize(image, maxWidth, maxHeight)});
    return false;
  }

  width = img.width;
  height = img.height;
  ratio = 1.0*width/height;

  // no change when no dimension found
  if (width == 0 || height == 0)
    return false;

  if (width <= maxWidth && height <= maxHeight)
  {
    res['width'] = width;
    res['height'] = height;
  }
  else if (maxWidth/ratio > maxHeight)
  {
    res['width'] = maxHeight*ratio;
    res['height'] = maxHeight;
  }
  else
  {
    res['width'] = maxWidth;
    res['height'] = 1.0*maxWidth/ratio;
  }

  $(image).attr('width', res['width']);
  $(image).attr('height', res['height']);
  return res;
}

/**
 * Works both with friendly and normal paths
 */
function minimizePath (path, webOrAddress, dir)
{
  // convert to friendly paths
  path = friendlyPath(path);
  webOrAddress = friendlyPath(webOrAddress);
  dir = friendlyPath(dir);

  if (webOrAddress.indexOf('http://') == -1 && webOrAddress.indexOf('http://') == -1)
    webOrAddress = 'http://' + webOrAddress;
  if (path.indexOf(webOrAddress) == 0)
    path = path.substr(webOrAddress.length);

  if (dir)
  {
    dir = friendlyPath(dir);
    if (path.indexOf(dir) == 0)
      path = path.substr(dir.length+1);
  }
  return path;
}

/**
 * Comment
 */
function url ()
{
  var i;
  var out = '';
  for(i = 0; i < arguments.length; i++)
  {
    if (out.length > 0 && out.charAt(out.length-1) != '/' && arguments[i].charAt(0) != '/')
      out += '/';
    out += arguments[i];
  }
  return out;
}

/**
 * Comment
 */
function friendlyPath (path)
{
  var re = new RegExp("^((https?://)?[^/]*)/?modules/([^/]+)/(ajax|css|images|js)/(.*)$");
  // parse int parts
  if (path && path.match(re))
  {
    var match = null;
    while (matches = re.exec(path))
      return matches[1] + '/' + matches[4] + '/' + matches[3] + '/' + matches[5];
  }
  else
    return path;
}

var actualizeFunction = actualize;
