var errors = {
  nickname: false,
  mailaddress: false,
  title: false,
  description: false,
  image: false,
  yield: false,
  ingredients: false,
  directions: false,
  categories: false,
  reset: function() {
    var p;
    for (p in this) {
      if (typeof(this[p]) != 'function')
        this[p] = false;
    }
  },
  has_error: function() {
    var p;
    for (p in this) {
      if (typeof(this[p]) != 'function' && this[p] == true) return true;
    }
    return false;
  }
};

var warnings = {
  author: false,
  catchphrase: false,
  description: false,
  point: false,
  difficulty: false,
  calorie: false,
  reset: function() {
    var p;
    for (p in this) {
      if (typeof(this[p]) != 'function')
        this[p] = false;
    }
  },
  has_warning: function() {
    var p;
    for (p in this) {
      if (typeof(this[p]) != 'function' && this[p] == true) return true;
    }
    return false;
  }
};

var formdata = {};
var yield_string;

function validate_author(tab) {
  var t = $('#start input:text'),
  alt = $('#start .alert').eq(0).hide();
  formdata['nickname'] = t.eq(0).attr('value');
  formdata['mailaddress'] = t.eq(1).attr('value');
  t = $('#start iframe').get(0);
  formdata['author'] = t.contentWindow.currentImage;
  if (formdata.nickname.empty()) errors.nickname = true;
  if (formdata.mailaddress.empty()) errors.mailaddress = true;
  if (!formdata.author) {
    warnings.author = true;
    formdata.author = '';
  }
  if (errors.nickname) {
    alt.html('ニックネームを入力してください').show();
    if (tab == 0) $('#nickname').hide().fadeIn();
  }
  else if (errors.mailaddress) {
    alt.html('メールアドレスを入力してください').show();
    if (tab == 0) $('#start :input').eq(1).hide().fadeIn();
  }
  else if (!$('#mailaddress').attr('value').match(/^[a-z0-9._%\-]+@[a-z0-9.\-]+\.[a-z]{2,6}$/i)) {
    alt.html('メールアドレスは半角で正しく入力してください').show();
    if (tab == 0) $('#mailaddress').hide().fadeIn();
    errors.mailaddress = true;
  }
}

function validate_about(tab) {
  var t, texts, textareas, alt;
  alt = $('#about .alert').hide();
  t = $('#about');
  texts = t.find(':text');
  textareas = t.find('textarea');
  formdata['title'] = texts.eq(0).attr('value');
  formdata['catchphrase'] = texts.eq(1).attr('value');
  if (formdata.title.empty()) errors.title = true;
  if (formdata.catchphrase.empty() && textareas.eq(0).attr('value').empty()) errors.description = true;
  if (texts.eq(1).attr('value').empty()) warnings.catchphrase = true;
  $.each(['description', 'point', 'difficulty'], function(i, n){
    formdata[n] = textareas.eq(i).attr('value');
    if (formdata[n].empty()) warnings[n] = true;
  });
  if (errors.title) {
    alt.eq(0).html('レシピの名前を入力してください').show();
    if (tab == 1) texts.eq(0).hide().fadeIn();
  }
  if (errors.description) {
    alt.eq(1).html('キャッチフレーズとレシピの説明の少なくともどちらかには入力してください').show();
  }
}

function validate_image(tab) {
  var t = $('#image iframe').get(0),
  alt = $('#image .alert').eq(0).hide();
  formdata['image'] = t.contentWindow.currentImage;
  if (!formdata.image) errors.image = true;
  if (errors.image) {
    alt.html('レシピの画像は必ず登録してください').show();
  }
}

function validate_ingredients(tab) {
  var t, t2, texts, alt;
  t = $('#ingredients');
  alt = t.find('.alert').hide();
  texts = t.find(':text');
  formdata['yield'] = texts.eq(0).attr('value');
  t2 = t.find('select option:selected').eq(0);
  yield_string = t2.text();
  formdata['yield_type'] = t2.attr('value');
  formdata['calorie'] = texts.eq(1).attr('value');
  if (!formdata['yield'].match(/^\d+\.{0,1}\d?$/)) formdata['yield'] = '';
  if (!formdata['calorie'].match(/^\d+\.{0,1}\d?$/)) formdata['calorie'] = '';
  if (formdata['yield'].empty()) errors.yield = true;
  if (formdata['calorie'].empty()) warnings.calorie = true;

  t2 = t.find('ul li');
  if (t2.length == 0) errors.ingredients = true;
  else {
    t2.each(
      function(j) {
	t3 = t2.eq(j).find('span');
	formdata['ingredients['+j+']'] = t3.eq(0).html();
	formdata['ingredients_unit['+j+']'] = t3.eq(1).html();
      }
    );
  }
  if (errors.yield) {
    alt.eq(0).html('材料は何人分になりますか？').show();
    if (tab == 3) texts.eq(0).hide().fadeIn();
  }
  if (errors.ingredients) {
    alt.eq(2).html('材料は少なくとも一つは入力してください').show();
    if (tab == 3) t.find('form').hide().fadeIn();
  }
}

function validate_directions(tab) {
  var t = $('#steps').find('ul li'),
  alt = $('#steps .alert').eq(0).hide();
  if (t.length == 0) errors.directions = true;
  else {
    t.each(
      function(j) {
	formdata['step_image['+j+']'] = t.eq(j).find('img').attr('src');
	formdata['step_text['+j+']'] = t.eq(j).find('.step_text').html();
      }
    );
  }
  if (errors.directions) {
    alt.html('調理手順を少なくとも一つ入力してください').show();
    if (tab == 4) $('#steps .entry textarea').hide().fadeIn();
  }
}

function validate_categories() {
  var t;
  $.each(['ingredient', 'genre', 'purpose', 'time'], function(i,n) {
    t = $('#category_'+n+'').multiselect_selected();
    if (n == 'ingredient') {
      if (t.length == 0) errors.categories = true;
      else t.each(function(j){ formdata['ingredient['+j+']'] = this.value; });
    } else {
      t.each(function(){ formdata[this.name.replace(/^category_/, '')] = this.value;});
    }
  });
  if (errors.categories) {
    $('#category .alert').eq(0).html('少なくとも一つの食材を選択してください').show();
  }
}

function validate_all() {
  errors.reset();
  warnings.reset();

  validate_author();
  validate_about();
  validate_image();
  validate_ingredients();
  validate_directions();
  validate_categories();

  var rows, keys, t;
  t = $('#preview');
  if (!errors.has_error()) {
    t.find('.errors').hide();
  } else {
    t.find('.errors').show();
    keys = [];
    $.each(errors,function(i,v){ if (typeof(v) != 'function') keys.push(i); });
    rows = t.find('.errors ul li').hide();
    $.each(keys, function(i, v) { if (errors[v]) rows.eq(i).show();});
  }
  if (!warnings.has_warning()) {
    t.find('.warnings').hide();
  } else {
    t.find('.warnings').show();
    keys = [];
    $.each(warnings,function(i,v){ if (typeof(v) != 'function') keys.push(i); });
    rows = t.find('.warnings ul li').hide();
    $.each(keys, function(i, v) { if (warnings[v]) rows.eq(i).show();});
  }
  if (!errors.has_error()) {
    if (!warnings.has_warning())
      $('.preview_results_message > div').eq(0).hide();
    else
      $('.preview_results_message > div').eq(0).show();
    var token = $('.preview_results_message > span');
    token.eq(0).html(formdata['title']);
    token.eq(1).show().find('span').html(formdata['nickname']);
    token.eq(2).html(formdata['yield'] + yield_string);
    $('.preview_results').show();
    form_data = formdata;
  } else
    $('.preview_results').hide();
}

var form_data;

function resetRecipeImage() {
  resetImage($('#image iframe').get(0), 'resetRecipeImage()');
}
function resetAuthorImage() {
  resetImage($('#start iframe').get(0), 'resetAuthorImage()');
}
function resetImage(_iframe, func) {
  if (_iframe.contentWindow.movie().setImage) {
    if (_iframe.contentWindow.currentImage) {
      _iframe.contentWindow.setImageURL(_iframe.contentWindow.currentImage, _iframe.contentWindow.image_width, _iframe.contentWindow.image_height);
    }
  } else {
    setTimeout(func, 100);
  }
}

var r = {author:false, recipe:false, direction:false,
  set: function(v) {
    this.author = this.recipe = this.direction = v;
  }
};

function resetAll() {
  $('iframe').each(function() {
    this.contentWindow.location.reload(true);
  });
  $('#steps').find('ul li').each(function() {
    $(this).find('img').eq(0).attr('src', '/images/none150.jpg').attr('style', '');
  });
  if ($.browser.msie)
    r.set(true);
}

var timeout;

$(document).ready(
  function(){
    if (location.href.indexOf('#') > -1) {
      location.href = location.href.replace(/#.*$/, '');
    }
    if (location.href.indexOf('recipe.php') > -1) { 
    $('#category select:not(select[multiple])').multiselect();
    $('#category select[multiple]').multiselect({defaultMessage:'<食材を選択してください>'}).bind('change', function(){
      if ($(this).multiselect_selected().length == 0)
        $(this).prev().html('少なくとも一つの食材を選択してください').show();
      else $(this).prev().empty().hide();
    });
    timeout = new Date();
    timeout.setHours(timeout.getHours()+3);

    var i;
    $('.main > ul').tabs().bind('tabsselect',
    function(e, ui) {
      if (timeout < new Date()) {
	location.href = 'logout.php';
      }
      if (ui.panel.id == 'preview') {
	validate_all();
      }
      if (ui.panel.id == 'start') {
        if (!$.browser.msie) setTimeout('resetAuthorImage()', 100);
        else if(r.author) {
          $('#start iframe').get(0).contentWindow.location.reload();
        }
      }
      if (ui.panel.id == 'image') {
        if (!$.browser.msie) setTimeout('resetRecipeImage()', 100);
        else if(r.recipe) {
          $('#image iframe').get(0).contentWindow.location.reload();
        }
      }
      if (ui.panel.id == 'category') {
      }
    }
    );
    $('.body').css('visibility', 'visible');

    ingredients_init();
    directions_init();

    $('#start a').eq(0).click(function(e) {
      e.preventDefault();
      $('#start iframe').get(0).contentWindow.location.reload(true);
    });
    $('#mailaddress').blur(function(e) {
      if (!this.value.empty() && !this.value.match(/^[a-z0-9._%\-]+@[a-z0-9.\-]+\.[a-z]{2,6}$/i)) {
        $('#start .alert').eq(0).html('メールアドレスは半角で正しく入力してください').show();
        $('#start :input').eq(1).hide().fadeIn();
      }
    });

    $('a.next').click(nexttab);
    $('a.prev').click(prevtab);
    $('#preview a').click(
      function(e){
	e.preventDefault();
	var m = $(this).attr('href').match(/.?#(.*)$/), s;
	if (m && m.length == 2) {
	  switch (m[1]) {
          case 'start': s = 0;break;
	  case 'about': s = 1;break;
	  case 'image': s = 2;break;
	  case 'ingredients': s = 3;break;
	  case 'steps': s = 4;break;
	  case 'category': s = 5;break;
	  default: s = 6;
	  }
	  $('.main > ul').tabs('select', s);
	}
      }
    );
    $('#preview form').submit(
      function(e){
	e.preventDefault();
	if (timeout < new Date()) {
	  location.href = 'logout.php';
	  return false;
	}
	$(this).find('input:submit').attr('disabled', 'disabled');
	$('.main > ul').tabs('disable', 0).tabs('disable', 1).tabs('disable', 2).tabs('disable', 3).tabs('disable', 4).tabs('disable', 5);
        form_data['s'] = client.s;
        form_data['n'] = client.n;
	$.ajax(
	  {
	    type:'post',
	    url:baseurl + 'make/xrecipe.php',
	    data:form_data,
	    dataType:'json',
	    success:function(json) {
              if (typeof(json.error) != 'undefined') {
                if (json.error == 2) {
                  resetAll();
                  alert('申し訳ありません。レシピの作成を開始してから3時間以上経過したため全ての画像はリセットされました。お手数おかけしますが画像をもう一度設定してください。');
                  $('#preview input:submit').removeAttr('disabled');
                  $('.main > ul').tabs('enable', 0).tabs('enable', 1).tabs('enable', 2).tabs('enable', 3).tabs('enable', 4).tabs('enable', 5).tabs('select', 0);
                } else {
                  location.href = baseurl + 'make/index.php';
                }
              } else {
                $('#preview input:submit').removeAttr('disabled');
                window.onbeforeunload = null;
                location.href = baseurl + 'make/finished.php?recipe='+json.id+'&s='+client.s+'&n='+client.n;
              }
	    },
	    error: function(req) {
	      alert(req.status);
	      $('#preview input:submit').removeAttr('disabled');
	      $('.main > ul').tabs('enable', 0).tabs('enable', 1).tabs('enable', 2).tabs('enable', 3).tabs('enable', 4).tabs('enable', 5);
	    }
	  }
	);
      }
    );
        window.onbeforeunload = function(e) {
          var e = e || window.event;
          if (e)
            e.returnValue = '現在までに入力された内容(画像を含む)が失われます？';
          return '現在までに入力された内容(画像を含む)が失われます？';
        }
    }
});

function nexttab(e) {
  e.preventDefault();
  var tab = $('.main > ul').tabs().data('selected.tabs'), alt, error=true;
  if (tab == 6) return false;
  if (tab < 6) {
    errors.reset();
    switch (tab) {
    case 0: validate_author(tab); break;
    case 1: validate_about(tab); break;
    case 2: validate_image(tab); break;
    case 3: validate_ingredients(tab); break;
    case 4: validate_directions(tab); break;
    case 5: validate_categories(tab); break;
    }
    if (errors.has_error()) return false;
  }
  $('.main > ul').tabs('select', ++tab);
  return true;
}

function prevtab(e) {
  e.preventDefault();
  var tab = $('.main > ul').tabs().data('selected.tabs');
  if (tab == 0) return false;
  $('.main > ul').tabs('select', --tab);
}


function remove_ingredient(e) {
  e.preventDefault();
  var texts = $('#ingredients input:text');
  var values = $(this).parent().find('span');
  texts.eq(2).attr('value', values.eq(0).html());
  texts.eq(3).attr('value', values.eq(1).html());
  $(this).parent('li').remove();
  texts.get(2).focus();
}

function check_num(n){
  if (this.value.length == 0) {
    $(this).nextAll('.alert').eq(0).html('').hide();
    return;
  }
  if (!this.value.match(/^\d+\.{0,1}\d?$/)) {
    $(this).nextAll('.alert').eq(0).html('半角数値を入力してください(小数点(1.5等小数点1桁まで)を付けても構いません)').show();
    this.focus();
    this.select();
  } else {
    $(this).nextAll('.alert').eq(0).html('').hide();
  }
}

function ingredients_init() {
  $('#ingredients input:text').eq(0).blur(check_num);
  $('#ingredients input:text').eq(1).blur(check_num);

  $('#ingredients form').eq(0).submit(
    function(e) {
      e.preventDefault();
      var err = false;
      var texts = $(this).find(':text');
      texts.each(
	function(){
	  if (this.value.strip().length == 0)
	    err = true;
	});
      if (err) {
	if ($('.alert:eq(0)', this).is(':hidden'))
          $('.alert:eq(0)', this).html('両方の項目を入力してください').show();
	return false;
      } else {
	if (!$('.alert:eq(0)', this).is(':hidden'))
          $('.alert:eq(0)', this).hide();
      }
      $('<li></li>').html('<span>'+texts.eq(0).attr('value').strip() + '</span> ・・・ <span>' + texts.eq(1).attr('value').strip() + '</span><a href="#removerow" ><img class="remove" src="/control/images/del.gif" /></a>').appendTo($(this).parent().find('ul')).find('a:eq(0)').click(remove_ingredient).hide().fadeIn();
      $(':text', this).each(function(){this.value = '';});
      return true;
    }
  );

  $('#ingredients ul li a').click(remove_ingredient);
}

function regen_options(rows) {
  var s,i,j;
  for (i=0;i<rows.length;i++) {
    s = $(rows.get(i)).find('select').eq(0);
    s.empty();
    for (j=0;j<rows.length;j++)
      $('<option value="'+j+((i==j)?'" selected>':'">')+(j+1)+'</option>').appendTo(s);
  }
}

function remove_direction(e) {
  e.preventDefault();
  var img = $(this).parents('li').find('img').eq(0);
  if (!img.attr('src').match(/none150\.jpg$/)) {
    $('#steps').find('iframe').get(0).contentWindow.setImageURL(img.attr('src'), parseInt(img.css('width').replace('px','')), parseInt(img.css('height').replace('px','')));
  }
  $('#steps textarea').attr('value', $(this).parents('li').eq(0).find('.step_text').html().unbr());
  $(this).parents('li').eq(0).remove();
  regen_options($('#steps ul li'));
}

function change_position(e){
  var i = parseInt($(this).find('option:selected').get(0).value), j = 0;
  var li = $(this).parents('li').eq(0);
  var ul = $(this).parents('ul').eq(0);
  var rows = ul.find('li');
  for (j = 0;j<rows.length;j++) {
    if (rows.get(j) == li.get(0)) {
      if (i == j) return false;
      break;
    }
  }
  if (i < j) rows.eq(i).before(li);
  else rows.eq(i).after(li);
  regen_options(ul.find('li'));
  return true;
}

function directions_init() {
  $('#steps ul li select').change(change_position);
  $('#steps ul li a').click(remove_direction);
  $('#steps form a').click(
    function(e) {
      e.preventDefault();
      $(this).parents('div.entry').find('iframe').get(0).contentWindow.location.reload(true);
    }
  );
  $('#steps form').eq(0).submit(
    function(e){
      e.preventDefault();
      if ($('textarea', this).eq(0).attr('value').strip().length == 0) return false;
      var _iframe = $(this).parent().find('iframe').get(0);
      var photo = _iframe.contentWindow.currentImage;
      var height=-1, width=-1;
      if (!photo) photo = '/images/none150.jpg';
      else {
	height = _iframe.contentWindow.image_height;
	width = _iframe.contentWindow.image_width;
      }
    _iframe.contentWindow.location.reload(true);
      var entry = $('<li></li>').html('<div class="entry"><div class="image"><img src="'+photo+'" /></div><div class="right"><div class="step_text">'+$('textarea:eq(0)', this).get(0).value.strip().stripHTML().br()+'</div><div class="control"><select></select><a href="#removerow"><img src="/control/images/del.gif" class="remove" /></a></div></div></div>').appendTo($('#steps ul')).hide().fadeIn();
      if (height > -1) {
	entry.find('img').eq(0).css({width:width+'px',height:height+'px',marginTop:parseInt((150-height)/2)+'px'});
      }
      $('select:eq(0)', entry).change(change_position);
      $('a:eq(0)', entry).click(remove_direction);
      regen_options($('#steps ul li'));
      return true;
    }
  );
}

