if (typeof Photozou == 'undefined') Photozou = {}

Photozou.Photoshow = {}
Photozou.Photoshow.is_photo_map_shown = false;

Photozou.Photoshow.edit_comment = function(comment_id) {
  if (typeof page == 'undefined') {
    return
  }
  var self = this
  var dialog = new Photozou.Dialog
  var pc = new Photozou.Model.PhotoComment
  var content = '<div id="comment_edit_area"><img src="/img/now_loading_circle.gif" class="loading_icon">' + msg('Now loading') + '...</div><div id="comment_edit_progress" style="display: none"><img src="/img/now_loading_circle.gif" class="loading_icon">' + msg('Saving...') + '</div>'
  dialog.confirm(content, {
    escapeText: false,
    width: 450,
    height: 200,
    okText: msg('Save'),
    cancelText: msg('Cancel'),
    onOk: function() {
      var comment_edit_text = $('comment_edit_text')
      if (comment_edit_text.value == '') {
        comment_edit_text.style.border = 'solid 3px #f00'
        new Effect.Highlight(comment_edit_text, {startcolor: '#ffcccc'})
        return ''
      }
      $('dbutton_ok').disabled = true
      $('dbutton_cancel').disabled = true
      comment_edit_text.readOnly = true
      comment_edit_text.style.color = '#9e9e9e'
      comment_edit_text.style.backgroundColor = '#f4f4f4'

      $('dbutton_ok').hide()
      $('dbutton_cancel').hide()

      var saving_message = document.createElement('div')
      saving_message.id = 'saving_message'
      saving_message.innerHTML = '<img src="/img/now_loading_circle.gif" class="loading_icon">' + msg('Saving...')
      $('dbuttons').appendChild(saving_message)

      var reloader = PH.reload_page.later(20000)()
      pc.update(comment_id, comment_edit_text.value, page.ott, {
        callback: function(comment) {
          reloader.cancel()
          $('comment_text_' + comment_id).innerHTML = comment.html_comment
          dialog.close()
          new Effect.Highlight('comment_' + comment_id, {startcolor: '#ffdddd'})
        },
        errback: function(req) {
          reloader.cancel()
          comment_edit_text.style.border = 'solid 3px #f00'
          new Effect.Highlight(comment_edit_text, {startcolor: '#ffcccc'})
          $('dbutton_ok').disabled = false
          $('dbutton_cancel').disabled = false
          comment_edit_text.readOnly = false
          comment_edit_text.style.color = '#333'
          comment_edit_text.style.backgroundColor = '#fff'
          $('saving_message').hide()
          $('dbutton_ok').show()
          $('dbutton_cancel').show()
          return ''
        }
      });
    }
  });
  $('dbutton_ok').disabled = true
  pc.find_by_comment_id(page.photo_id, comment_id, {
    callback: function(comment) {
      if (typeof comment.error_message != 'undefined') {
        $('comment_edit_area').innerHTML = '<p>' + comment.error_message + '</p>';
        return;
      }
      var comment_date = $('comment_time_' + comment_id).innerHTML;
      $('comment_edit_area').innerHTML = '<textarea id="comment_edit_text">' + comment.comment + '</textarea>';
      $('dbutton_ok').disabled = false
    }
  });
}

Photozou.Photoshow.add_comment = function() {/*{{{*/
  // validation
  var comment_form_text = $('comment_form_text')
  if (comment_form_text.value == '') {
    comment_form_text.style.border = 'solid 3px #f00'
    new Effect.Highlight(comment_form_text, {startcolor: '#ffcccc'})
    return ''
  }

  var btn = $('add_comment')
  var color = btn.style.color
  var border = btn.style.border

  btn.disabled = true
  btn.style.color = '#ccc'

  var dialog = new Photozou.Dialog
  dialog.wait(
    '<img src="/img/now_loading_circle.gif" class="loading_icon">'+msg('Adding...'), {
      'height': 60
    }
  )

  var reloader = PH.reload_page.later(20000)()

  pc = new Photozou.Model.PhotoComment
  pc.save(page.user_id, page.photo_id, $F('comment_form_text'), location, page.ott, {
    'callback':function(comment) {

      if ($("noCommentMessage") != null) {
        $("noCommentMessage").hide()
      }

      var comment_html = TrimPath.processDOMTemplate('media_comment_template', {'comment': comment})
      var html = $('media_comments').innerHTML
      $('media_comments').innerHTML = html + comment_html

      var comments_length = $('media_comment_count').innerHTML
      $('media_comment_count').innerHTML = parseInt(comments_length) + 1
      reloader.cancel()
      btn.disabled = false
      btn.style.color = color
      comment_form_text.value = ''
      comment_form_text.style.border = 'solid 1px #bbb'
      dialog.close()
      new Effect.Highlight('media_comment_count', {startcolor: '#ffcccc'})
      new Effect.Highlight('comment_' + comment.photo_comment_id, {startcolor: '#ffdddd'})
    },
    'errback':function(req) {
      reloader.cancel()
      $('comment_form_text').style.border = 'solid 3px #f00'
      btn.disabled = false
      btn.style.color = color
      dialog.close()
      new Effect.Highlight(comment_form_text, {startcolor: '#ffcccc'})
    }
  })
}/*}}}*/

Photozou.Photoshow.remove_comment = function(comment_id) {/*{{{*/
  var self = this
  var pd = new Photozou.Dialog
  pd.confirm(msg('Is this comment deleted'), {
    cancelText: msg('Cancel'),
    onOk: function() {
      $('dmsg').innerHTML = '<img src="/img/now_loading_circle.gif" class="loading_icon">' + msg('Deleting...')
      $('dbutton_ok').disabled = true
      $('dbutton_cancel').disabled = true

      var reloader = PH.reload_page.later(20000)()

      var pc = new Photozou.Model.PhotoComment
      pc.remove_by_commenter(comment_id, page.ott, {'callback':function(){
        reloader.cancel()
        $('comment_' + comment_id).style.display = 'none'
        var comments_length = $('media_comment_count').innerHTML
        $('media_comment_count').innerHTML = parseInt(comments_length) - 1
        pd.close()
        new Effect.Highlight('media_comment_count', {startcolor: '#ffcccc'})
      }})
    }
  })
}/*}}}*/

Photozou.Photoshow.observe_tag_input = function() {/*{{{*/
  Event.observe('media_tag_input', 'keypress', function(evt) {
    document.forms['thisform'].onsubmit = function(){ return false }
  })
}/*}}}*/

Photozou.Photoshow.add_tag = function() {/*{{{*/
  // validation
  var media_tag_input = $('media_tag_input')
  if (media_tag_input.value == '') {
    media_tag_input.style.border = 'solid 3px #f00'
    new Effect.Highlight(media_tag_input, {startcolor: '#ffcccc'})
    return ''
  }

  var btn = $('add_tag')
  var color = btn.style.color

  btn.disabled = true
  btn.style.color = '#ccc'

  var dialog = new Photozou.Dialog
  dialog.wait(
    '<img src="/img/now_loading_circle.gif" class="loading_icon">'+msg('Adding...'), {
      'height': 60
    }
  )

  var reloader = PH.reload_page.later(20000)()

  var pt = new Photozou.Model.PhotoTag
  pt.save(page.user_id, page.photo_id, $('media_tag_input').value, page.ott, {
    'callback': function(res) {

      var tags = res.tags

      for (var k in tags) {
        tags[k]['delete_title'] = sprintf(msg('Delete the tag "%s"'), tags[k]['html_name'])
      }

      var tags_html = TrimPath.processDOMTemplate('media_tags_template', {'tags': tags, 'login_id': res.login_id})

      var html = $('media_tags').innerHTML
      $('media_tags').innerHTML = html + tags_html

      reloader.cancel()
      btn.disabled = false
      btn.style.color = color
      media_tag_input.value = ''
      media_tag_input.style.border = 'solid 1px #bbb'
      dialog.close()
      new Effect.Highlight('media_tags', {startcolor: '#ffcccc'})
    },
    'errback':function(req) {
      reloader.cancel()
      btn.disabled = false
      btn.style.color = color
      dialog.close()
      media_tag_input.style.border = 'solid 3px #f00'
      new Effect.Highlight(media_tag_input, {startcolor: '#ffcccc'})
    }
  })
}/*}}}*/

Photozou.Photoshow.remove_tag = function(tag_id) {/*{{{*/
  var pd = new Photozou.Dialog
  pd.confirm(msg('Is this tag deleted'), {
    cancelText: msg('Cancel'),
    'onOk': function() {
      $('dmsg').innerHTML = '<img src="/img/now_loading_circle.gif" class="loading_icon">' + msg('Deleting...')
      $('dbutton_ok').disabled = true
      $('dbutton_cancel').disabled = true

      var reloader = PH.reload_page.later(20000)()

      var pt = new Photozou.Model.PhotoTag
      pt.remove(tag_id, page.ott, {
        callback: function() {
          reloader.cancel()
          $('tag_' + tag_id).style.display = 'none'
          pd.close()
          new Effect.Highlight('media_tags', {startcolor: '#ffcccc'})
        },
        errback: function() {
          alert(msg("Failed to delete."))
          reloader.cancel()
          pd.close()
        }
      })
    }
  })
}/*}}}*/

Photozou.Photoshow.editize_title = function() {/*{{{*/
  new Ajax.InPlaceEditor('media_title', '/xml/photo_title_edit/'+page.user_id+'/'+page.photo_id, {
    cols: 36,
    okText: 'OK',
    cancelText: msg('Cancel'),
    savingText: msg('Saving...'),
    clickToEditText: msg('Click to edit'),
    highlightcolor: '#FEE8E7',
    onComplete: function(transport, element) {
      if (typeof transport != 'undefined') {
        if (transport.responseText) {
          element.innerHTML = transport.responseText;
        }
        var photo_title = element.innerHTML
        photo_title = photo_title.unescapeHTML()
        document.title = photo_title + document.title.substring(document.title.lastIndexOf(' - '))
        new Effect.Highlight(element, {startcolor: this.options.highlightcolor});
      }
    },
    showEmptyText: false
  })
}/*}}}*/

Photozou.Photoshow.editize_description = function() {
  desc_editor = new Ajax.InPlaceEditor('media_description', '/xml/photo_description_edit/' + page.user_id + '/' + page.photo_id, {
    cols: 100,
    rows: 3,
    formId: 'media_description_form',
    okText: 'OK',
    cancelText: msg('Cancel'),
    savingText: msg('Saving...'),
    clickToEditText: msg('Click to edit'),
    highlightcolor: '#FEE8E7',
    emptyText: msg('Click here to add a description'),
    emptyClassName: 'media_description_empty',
    onComplete: function(transport, element) {
      if (typeof transport != 'undefined') {
        if (transport.responseText) {
          element.innerHTML = transport.responseText;
          new Effect.Highlight(element, {startcolor: this.options.highlightcolor});
        } else {
          element.innerHTML = '';
          this._checkEmpty();
        }
      }
    }
  });
};

Photozou.Photoshow.autocompletize_tag = function() {/*{{{*/
  new Suggest.LocalMulti(
    'media_tag_input',
    'tag_completion_list',
    user_tag_names,
    {dispMax: 20, interval: 500, prefix: true}
  );
}/*}}}*/

Photozou.Photoshow.show_fav_user_name = function(targetId, userId) {

  var nameplateId = 'user_nameplate_' + userId;

  if (Photozou.Window.ready(nameplateId)) {
    Photozou.Window.restore(nameplateId);
    return;
  }

  var pos = Position.cumulativeOffset($(targetId));
  var top = pos[1] + 15;
  var left = pos[0] + 15;

  // for IE
  $(targetId).alt = '';

  Photozou.Window.open(nameplateId, '<img src="/img/now_loading_circle.gif">', {
    top: top + 'px',
    left: left + 'px',
    padding: '5px 5px 3px 5px',
    textAlign: 'center'
  }, 'user_nameplate');

  var user = new Photozou.Model.User;
  user.find(userId, function(userInfo) {

    // mypic
    var mypicImg = document.createElement('img');
    mypicImg.className = 'user_nameplate_mypic';
    mypicImg.src = userInfo.my_pic_thumbnail_url;
    mypicImg.width = 40;
    mypicImg.height = 40;

    // name
    var name = document.createElement('div');
    name.className = 'user_nameplate_name';
    name.appendChild(document.createTextNode(userInfo.nick_name));

    $(nameplateId).removeChild($(nameplateId).lastChild);
    $(nameplateId).appendChild(mypicImg);
    $(nameplateId).appendChild(name);
  });
};

Photozou.Photoshow.hide_fav_user_name = function(userId) {
  var nameplateId = 'user_nameplate_' + userId;
  Photozou.Window.close(nameplateId);
};

Photozou.Photoshow.toggle_favorite = function() {
  if ($('fav_controller').src.match(/unstarred_\.gif$/)) {
    Photozou.Photoshow._remove_favorite();
  } else {
    Photozou.Photoshow._add_favorite();
  }
};

Photozou.Photoshow._add_favorite = function() {
  var dialog = new Photozou.Dialog;
  dialog.wait('<img src="/img/now_loading_circle.gif" class="loading_icon">' + msg('Adding...'), { height: 60 });
  var reloader = PH.reload_page.later(20000)();
  var fav = new Photozou.Model.PhotoFavorite;
  fav.add(page.user_id, page.photo_id, {
    callback: function(res) {
      reloader.cancel();
      var html = $('favorite_list').innerHTML;
      var star = TrimPath.processDOMTemplate('favorite_star', {user_id: res.user_id});
      $('favorite_list').innerHTML = html + star;
      $('fav_controller').src = is_english ? '/img/en/unstarred_.gif' : '/img/unstarred_.gif';
      $('fav_controller').alt = msg('unstarred_.gif');
      var favNum = $('favorite_num').innerHTML;
      favNum++;
      $('favorite_num').innerHTML = favNum;
      if (favNum == 1) {
        $('photo_fav_msg').show();
      }
      dialog.close();
      new Effect.Highlight('photo_fav_' + res.user_id, {startcolor: '#ffcccc', duration: 3});
    },
    errback: function(req) {
      alert(msg("Failed to regist."));
      reloader.cancel();
      dialog.close();
    }
  });
};

Photozou.Photoshow._remove_favorite = function() {

  var dialog = new Photozou.Dialog;
  dialog.confirm(msg('Are you sure you want to remove this artwork from your favorite list?'), {
    cancelText: msg('Cancel'),
    onOk: function() {

      $('dmsg').innerHTML = '<img src="/img/now_loading_circle.gif" class="loading_icon">' + msg('Deleting...');
      $('dbutton_ok').disabled = true;
      $('dbutton_cancel').disabled = true;

      var reloader = PH.reload_page.later(20000)();
      var fav = new Photozou.Model.PhotoFavorite;
      fav.remove(page.user_id, page.photo_id, {
        callback: function(res) {
          reloader.cancel();
          var p = $('photo_fav_' + res.user_id).parentNode;
          p.removeChild($('photo_fav_' + res.user_id));
          $('fav_controller').src = is_english ? '/img/en/starred_.gif' : '/img/starred_.gif';
          $('fav_controller').alt = msg('starred_.gif');
          var favNum = $('favorite_num').innerHTML;
          favNum--;
          if (favNum == 0) {
            $('photo_fav_msg').hide();
          }
          $('favorite_num').innerHTML = favNum;
          dialog.close();
        },
        errback: function() {
          alert(msg("Failed to delete."));
          reloader.cancel();
          dialog.close();
        }
      });
    }
  });
};

Photozou.Photoshow.show_map = function(targetId, userId, photoId, lat, lng) {
  if (typeof GMap2 == "undefined") {
    return;
  }
  var map = new GMap2($(targetId));
  map.setCenter(new GLatLng(lat, lng, 8));
  var point = new GLatLng(lat, lng);
  var marker = new GMarker(point);
  map.addOverlay(marker);
  map.setMapType(G_NORMAL_MAP);
  map.setZoom(10);
  map.addControl(new GSmallMapControl());
  GEvent.addListener(marker, "click", function() {
    location.href = "/photo/show/" + userId + "/" + photoId;
  });
  GEvent.addListener(map, "click", function() {
    location.href = "/photo/mapshow/" + userId + "/" + photoId;
  });
};

/**
 * extends Ajax.InPlaceEditor
 */
Ajax.InPlaceEditor.prototype.__initialize = Ajax.InPlaceEditor.prototype.initialize;
Ajax.InPlaceEditor.prototype.__onComplete = Ajax.InPlaceEditor.prototype.onComplete;
Ajax.InPlaceEditor.prototype = Object.extend(Ajax.InPlaceEditor.prototype, {
  initialize: function(element, url, options) {
    this.__initialize(element, url, options);
    this.setOptions(options);
    if (this.options.showEmptyText) {
      this._checkEmpty();
    }
  },
  setOptions: function(options) {
    this.options = Object.extend(Object.extend(this.options, {
      emptyText: 'click to edit...',
      emptyClassName: 'inplaceeditor-empty',
      showEmptyText: true,
      evalScripts: true
    }), options || {});
  },
  _checkEmpty: function() {
    if (this.element.innerHTML.length == 0) {
      var emptyTextElement = document.createElement('span');
      emptyTextElement.className = this.options.emptyClassName;
      emptyTextElement.innerHTML = this.options.emptyText;
      this.element.appendChild(emptyTextElement);
    }
  },
  getText: function() {
    document.getElementsByClassName(this.options.emptyClassName, this.element).each(function(child) {
      this.element.removeChild(child);
    }.bind(this));
    var text = this.element.innerHTML;
    text = text.replace(/<BR _extended="true">/g, "\n"); // for IE...
    text = text.replace(/&gt;/g, '>');
    text = text.replace(/&lt;/g, '<');
    text = text.replace(/&quot;/g, '"');
    text = text.replace(/&#039;/g, "'");
    text = text.replace(/&amp;/g, '&');
    text = this.convertHTMLLineBreaks(text);
    text = text.replace(/<a [^>]+>/gi, '');
    text = text.replace(/<\/a>/gi, '');
    return text;
  },
  onComplete: function(transport) {
    if (this.options.showEmptyText) {
      this._checkEmpty();
    } else {
      if (typeof transport != 'undefined' &&
          (transport.responseText == null || transport.responseText == '')) {
        if (this.oldInnerHTML) {
          // restore
          this.element.innerHTML = this.oldInnerHTML;
          this.oldInnerHTML = null;
        }
      }
    }
    this.__onComplete(transport);
  },
  observeEvents: function() {
    this.onclickListener = this.enterEditMode.bindAsEventListener(this);
    this.mouseoverListener = this.enterHover.bindAsEventListener(this);
    this.mouseoutListener = this.leaveHover.bindAsEventListener(this);
    Event.observe(this.element, 'click', this.onclickListener);
    Event.observe(this.element, 'mouseover', this.mouseoverListener);
    Event.observe(this.element, 'mouseout', this.mouseoutListener);
    if (this.options.externalControl) {
      Event.observe(this.options.externalControl, 'click', this.onclickListener);
      Event.observe(this.options.externalControl, 'mouseover', this.mouseoverListener);
      Event.observe(this.options.externalControl, 'mouseout', this.mouseoutListener);
    }
  }
});

Photozou.DOM.addOnLoadListener('content_footer', function() {

  page = Photozou.Photoshow
  var q = location.pathname.split('/').slice(1)
  page.user_id = q[2]
  page.photo_id = q[3]
  page.ott = $F('ott')

  if (login) {

    if ($('media_tag_form') != null) {
      page.observe_tag_input()
      page.autocompletize_tag()
    }

    if (page_type == 'home') {
      page.editize_title()
      page.editize_description();
    }
  }

  if (!page.is_photo_map_shown) {
    page.show_map("map", page.user_id, page.photo_id, pos_lat, pos_lng);
    page.is_photo_map_shown = true;
  }

})


