if (typeof YFW_SETTING == 'undefined') YFW_SETTING = {};
if (/lh/.test(location.host)) {
  YFW_SETTING.host = 'lh/php.bear/yfw';
} else {
  YFW_SETTING.host = location.host;
}
(function($) {
$.fn.dump = function(obj) {
  var msgs = [], obj = obj || this;
  for (var i in obj) { if (! $.isFunction(obj[i])) msgs.push(i + ' : ' + obj[i]); }
  alert(msgs.join("\n"));
};
$(function(){
  $('#yohoo_bookmarker').parent('a').click(function(event) {
    event.preventDefault();
    window.open($(this).attr('href'), 'popup',
      'width=550px,height=480px,status=1,'
        + 'location=0,resizable=1,scrollbars=0,left=100,top=50', 0);
  });
  $('#google_bookmarker').parent('a').click(function(event) {
    event.preventDefault();
    window.open($(this).attr('href'));
  });

  $('input[type=text],textarea').focus(function(){
    var self = $(this);
    setTimeout(function(){ self.select() }, 0);
  });

  var pickers = [];
  $('.color_picker').each(function() {
    var self = $(this)
      , same = $('input[name=' + self.attr('name') + ']')
      , target = $('<div />')
        .css({display: 'none', 'text-align': 'center', 'font-weight': 'bold'})
      , hidden = $('<input type="hidden" value="" />')
        .attr('name', self.attr('name'))
      , close = $('<span>閉じる</span>')
        .css({'background-color': 'white', 'border': '1px #000000 solid',
              'padding': '0.2em 0.5em 0.2em 0.5em',
              'cursor': 'pointer', 'white-space': 'nowrap', 'margin': '0.5em'})
        .click(function(ev) { target.hide('fast'); ev.stopPropagation(); })
        .prepend($('<img />').attr({'alt': 'Close', 'src': 'img/close.png'}));
    self.parent().after(target);
    
    function positioning() {
      var pos = self.position();
      target.css({position: 'absolute',
        top: pos.top, left: pos.left + self.outerWidth() + 1});
    }

    target.farbtastic(self.parent(), function(color) {
      hidden.val(color).change();
    }).data('farbtastic').setColor(same.filter(':checked').val());
    pickers.push(target);
    target.prepend(close).append(hidden);
    same.click(function() { target.hide('fast'); });
    self.click(function() {
      $.each(pickers, function() { this.hide('fast'); });
      target.show('fast');
      hidden.change();
      positioning();
    });
  });

  var misc_star = $('input[name=misc:star]'),
      misc_star_default_text = misc_star.val();
  if (misc_star_default_text) {
    if (! YFW_SETTING.misc) YFW_SETTING.misc = {};
    function __misc_star() {
      var color = misc_star.css('color'),
          f = misc_star.data('EVENT_focus_return_color');
      if (f) {
        f();
        misc_star.unbind('focus', f);
      }
      misc_star.bind('focus', inner);
      misc_star.data('EVENT_focus_return_color', inner);
      misc_star.css('color', '#888888');
      function inner() {
        misc_star.val('');
        misc_star.css('color', color);
        misc_star.unbind('focus', misc_star.data('EVENT_focus_return_color'));
      }
    }
    __misc_star();
    $('input[name=misc:star]').change(function() {
      var self = $(this), v = self.val();
      if (v == misc_star_default_text) return;
      YFW_SETTING.misc.star = v; update();
    }).blur(function() {
      var v = misc_star.val();
      if (! v || v == misc_star_default_text) {
        __misc_star();
        misc_star.val(misc_star_default_text);
      }
    });
  }
  $('input,select').filter(function() {
    var name = $(this).attr('name');
    if (misc_star_default_text && name == 'misc:star') return false;
    return name.indexOf(':') > 0;
  }).each(function() {
    var name = $(this).attr('name');
    var names = name.split(/:/), key = names.pop(), object = YFW_SETTING;
    $.each(names, function(i) {
      if (! object[this]) object[this] = {};
      object = object[this];
    });
    switch ($(this).attr('type')) {
    case 'checkbox':
      $(this).click(function() {
        if ($(this).attr('checked')) object[key] = $(this).val();
        else { delete object[key]; };
        update();
      });
      if ($(this).attr('checked')) {
        if ($(this).attr('checked')) object[key] = $(this).val();
        else { delete object[key]; };
        update();
      }
    break;
    case 'radio':
      $(this).click(function() {
        var val = $(this).val();
        if (val == '') return;
        object[key] = val;
        update();
      });
      if ($(this).attr('checked')) $(this).click();
    break;
    default:
      $(this).change(function() { object[key] = $(this).val(); update(); });
      if ($(this).attr('selected')) $(this).change();
    break;
    }
    $('label[for=' + $(this).attr('id') + ']')
      .click(function(ev) { ev.stopPropagation() });
    $(this).click(function(ev) { ev.stopPropagation() });
  });
  $('input[name^=size]').change();

  var labels = $('#zodiac .icon');
  labels.each(function() {
    var label = $(this);
    if ($.browser.msie) { // normalize clicking behavior.
      label.children('img,span').click(function() {
        var input = $(this).siblings('input');
        switch (input.attr('type')) {
        case 'radio': input.click(); break;
        case 'ckeckbox': input.click(); break;
        default: /* do nothing */ }
      });
    }
    var parent = label.parent()
      , other_labels = labels.filter(function() { return label[0] != this; })
      , more = $('<a>&gt;&gt; 他の星座</a>')
        .attr({ href: "#zodiac", id: "more_zodiac" });
    label.children('input').click(function(e) {
      if ($('#more_zodiac').length > 0) return;
      other_labels.hide();
      label.addClass('selected');
      parent.append(more.clone().click(function() {
        label.removeClass('selected');
        other_labels.show();
        $(this).remove();
      }));
      update($(this).val());
    });
  });
  var icon_imgs = $('#zodiac .icon img');
  $('#zodiac #icon_selecter select').change(function() {
    var dir = $(this).val();
    icon_imgs.each(function() {
      var self = $(this)
        , src = self.attr('src')
        , file = 'img/icons/' + dir + src.substring(src.lastIndexOf('/'));
      self.attr('src', file);
    });
  }).change();

  $('.shading').each(function() {
    var self = $(this), display = $(this).css('display');
    var title = $('<a />').attr('class', 'legend')
      .css('display', display).text($(this).attr('title') + ' .... >');
    (self.hasClass('noauto')? title: self).css('display', 'none');

    title.click(function() { 
      title.animate({ opacity: 0, height: 'hide' }, 300, function() {
        title.css({'display': 'none', 'height': 'auto', 'opacity': 1});
        self.css('display', display);
      });
    });
    self.before(title).find('> legend').click(function() { 
      self.animate({ opacity: 0, height: 'hide' }, 500, function() {
        self.css({'display': 'none', 'height': 'auto', 'opacity': 1});
        title.css('display', display);
      });
    });
  });

  $('a[rel=up]'  ).each(ordering);
  $('a[rel=down]').each(ordering);
  function ordering() {
    $(this).click(function() {
      var self = $(this), name = self.attr('href').slice(1),
          i = YFW_SETTING.order[name], target,
          delta = (self.attr('rel')=='up'? -1: 1);
      $.each(YFW_SETTING.order, function(key) {
        if (this == i+delta) target = key;
      });
      if (! target) return;
      var tr = self.closest('tr');
      if (delta < 0) {
        tr.insertBefore(tr.prev());
      } else {
        tr.insertAfter(tr.next());
      }
      YFW_SETTING.order[name] = YFW_SETTING.order[target];
      YFW_SETTING.order[target] = i;
      update();
    });
  }

  var zodiac=false, q = location.search+'&', pos = q.indexOf('zodiac=');
  if (pos > 0) zodiac = q.substring(pos + 7, q.indexOf('&', pos + 7));
  if (zodiac) $('#zodiac input[value=' + zodiac + ']').click();
  else update('taurus');
});
function update(zodiac) {
  zodiac = zodiac || $('#yfw_container').attr('zodiac');
  if (!zodiac) return;
  yfw_initialize(zodiac);

  var path = absolutePath(document.location.pathname),
      dir = path.substring(0, path.lastIndexOf('/'));
  var doc = [
    '<script type="text/javascript" charset="UTF-8" ' +
       'src="' + dir + '/js/s/load.js?' + (new Date().getTime()) +'"><' + '/script>',
    '<script type="text/javascript"> // <![CDATA[',
    'YFW_SETTING=__JSON__; // ',
    'jQuery(function() {yfw_initialize("' + zodiac + '")}); // ',
    '// ]]> <' + '/script>',
    '<div id="yfw_container">',
    '<a href="' + location.href + '">12星座占いブログパーツ</a>',
    '<a href="http://www.gt-agency.co.jp/">GT-Agency</a>',
    '</div>'
  ].join("\n");
  $('#code').val(doc.replace(/__JSON__/, $.toJSON(YFW_SETTING)));
}
function absolutePath(path){
  var e = document.createElement('span');
  e.innerHTML = '<a href="' + path + '" />';
  return e.firstChild.href;
}
})(jQuery);
