(function($) {

// onload
$(function(){
    $('.back_button').click(function(){
      history.back()
      return false
    })
    $('.dummy_button').click(function(){
      return false
    })
    $('.datepicker').datepicker({dateFormat: 'yy-mm-dd'})
    $.baseurl = $('#baseurl').attr('href')
    $('form').submit(function() {
        var formId = $('form').attr('id')
        //<form></form>の間に透過PNGがある画面は、IE6でJSErrorを起こしてしまいます。
        //当座、該当フォームは除外して処理を行います。
        //該当フォーム：ログイン / 知人に知人を紹介
        //大東さんに超怒られそうな書き方 FIXME
        if(formId != 'snsLoginForm' && formId != 'bringTogetherForm' && formId != 'estLoginForm'){
            $(':submit, :image', this).click(function(){return false})
        }
    })
    $('.anchorize').anchorize()
    $('.form_clear').click(function(){
      $(this).closest('form')
        .find(':text, :password, textarea').val('').end()
        .find(':checkbox, :radio').attr('checked', false).end()
        .find('select').each(function(){this.selectedIndex = 0}).end()
        return false
    })
    //検索系
    $('.form_search').click(function(){
      $(this).closest('form')
        .find('input:hidden').attr('disabled', true).end()

    })
    $('#allCheck').click(function(){
    	var checked=this.checked;
    	$('.list :checkbox').each(function(){this.checked = checked})
    })
})

// 自動リンク化
$.fn.anchorize = function() {
  this.each(function() {
      $(this).html($(this).html().replace(/(https?|ftp):\/\/[^\s<>"']+/g, '<a href="$&" target="_blank">$&</a>'))
  })
}

// 自分のプロフィール表示切替
$(function() {
    var PROFILE_VIEW = {
        0: '.profile_view_all, .profile_view_friends, .profile_view_friendsOfFriends',
        1: '.profile_view_all',
        2: '.profile_view_all, .profile_view_friends, .profile_view_friendsOfFriends',
        3: '.profile_view_all, .profile_view_friendsOfFriends'
    }
    $('#profile_preview_select').change(function(){
        var height = $('.profile_phot').height()
        var width = $('.profile_phot').width()
        var blink = $('.profile_phot').fadeOut()
        var p = PROFILE_VIEW[$(this).val()]
        $(PROFILE_VIEW[0]).not(p).fadeOut()
        $(p).fadeIn("slow")
        blink.css('height',height)
        blink.css('width',width)
        blink.fadeIn("slow")
    })
})

var deleteImage = function(e, url, tag, params, onSuccess ) {
    if(confirm("画像を削除します。よろしいでしょうか？")){
      $.post(url, params, function(response){
            //プロフィール画像用のNO_PHOTO
            if(onSuccess){
                $(e).closest(tag).empty().append('<img src="'+$.baseurl+'/userSide/images/nophoto.png">')
            // 画像を非表示にする
            } else {
                $(e).closest(tag).empty()
            }
            if (onSuccess) {
                onSuccess(response)
            }
        })
    }
}
// プロフィール画像削除専用
$.deleteImageForProfile = function(e, id, number) {
    var divs = $(e).closest('.profile_column').children('div')
    var url = $.baseurl + '/sns/photo/delete'
    deleteImage(e, url, 'div', {id:id, number:number}, function(nowPicture) {
        // サーバからTOP画像のIndexが返るので、該当ラベルを変換する
        // 会社画像削除以外の場合
        if(nowPicture != 3){
           divs.eq([nowPicture - 1]).find('.nowPicture').text('現在のTOP画像')
        }
    })
}

// 管理からプロフィール画像削除専用
$.deleteImageForProfileAdmin = function(e, id, userId, number) {
	var url = $.baseurl + 'admin/user/delete/' + id + '/' + userId + '/' + number
	var onSuccess = function(nowPicture) {
        // サーバからTOP画像のIndexが返るので、該当ラベルを変換する
        var td = $(e).closest('tr').find('td')[nowPicture - 1]
        //会社画像削除以外の場合
        if(nowPicture != 3){
           $(td).find('#topimg').text('現在のTOP画像')
        }
    }
    if(confirm("画像を削除します。よろしいでしょうか？")){
        $.post(url, {id:id, userId:userId, number:number}, function(response){
              //プロフィール画像用のNO_PHOTO
              if(onSuccess){
                  $(e).closest('div').empty().append('<img src="'+$.baseurl+'managerSide/images/nophoto.png">')
              // 画像を非表示にする
              } else {
                  $(e).closest('div').empty()
              }
              if (onSuccess) {
                  onSuccess(response)
              }
          })
      }
}

//日記画像削除専用
$.deleteImageForDiary = function(e, id, number) {
    var url = $.baseurl + '/sns/diary/deleteImage'
    deleteImage(e, url, 'span', {id:id,number:number})
}

// コミュニティ画像削除用
$.deleteImageForCommunity = function(e, communityId, imageKind) {
    var url = $.baseurl + '/sns/community/imageDelete/' + imageKind
    deleteImage(e, url, 'span', {communityId:communityId})
}

// コミュニティトピック画像削除用
$.deleteImageForCommunityTopic = function(e, communityId, topicId) {
    var url = $.baseurl + '/sns/community/' + communityId + '/topic/imageDelete'
    deleteImage(e, url, 'span', {topicId:topicId})
}

//掲示板画像削除用
$.deleteImageForBoard = function(e, id, number) {
    var url = $.baseurl + '/sns/board/deleteImage'
    deleteImage(e, url, 'span', {id:id,number:number})
}

//オフ会掲示板画像削除用
$.deleteImageForOffBoard = function(e, id, number) {
    var url = $.baseurl + '/sns/offlineMeetingBoard/deleteImage'
    deleteImage(e, url, 'span', {id:id,number:number})
}

//ファイル削除（プレビュー表示なし）
var deleteFile = function(e, url, tag, params, onSuccess ) {
    if(confirm("ファイルを削除します。よろしいでしょうか？")){
      $.post(url, params, function(response){
            if(response){
                $(e).closest(tag).empty()
            }
        })
    }
}

//見積り依頼ファイル削除用
$.deleteEstimateRequestFile = function(e, id) {
    var url = $.baseurl + 'admin/est/deleteFile'
    deleteFile(e, url, 'div', {id:id})
}

//見積りファイル削除用
$.deleteEstimateFile = function(e, estReqId, id, number) {
    var url = $.baseurl + 'admin/est/list/'+ estReqId +'/deleteFile'
    deleteFile(e, url, 'div', {id:id,number:number})
}

$.fn.showCalendar = function(y, m, diaries, diaryUrl) {
    var weekday = ['日', '月', '火', '水', '木', '金', '土']
    var weekImages = ['calendar_sunday.gif', 'calendar_monday.gif', 'calendar_tuesday.gif', 'calendar_wednesday.gif', 'calendar_thursday.gif', 'calendar_friday.gif', 'calendar_saturday.gif']

    var getLastDate = function() {
        var d = new Date(y, m, 1)
        d.setTime(d.getTime() - 1)
        return d.getDate()
    }
    var lastDate = getLastDate()
    var link = function(d) {
        if (diaries.length > 0 && diaries[0] == d) {
            diaries.shift()
            return $('<a>').attr('href', $.baseurl + '/sns/' + diaryUrl + y + '/' + m + '/' +d).html(i)
        } else {
            return d
        }
    }
    var tr = $('<tr>')
    $(weekday).each(function(i, v) {
        var a = '<img height="21" width="21" alt="'+ v + '" src="' + $.baseurl + '/userSide/images/diary/calendar/' + weekImages[i] +'"/>'
        $('<td>').html(a).appendTo(tr)
    })
    var table = $('<table>').append(tr).appendTo(this)

    var thisMonth = new Date(y, m - 1, 1)
    var i = 1 - thisMonth.getDay()
    var nextWeek = 7 - thisMonth.getDay()
    if (nextWeek == 7) nextWeek = 0
    tr = $('<tr>')
    while (true) {
        tr.append($('<td class="days">').html(i > 0 && i <= lastDate ? link(i) : ''))
        if (i%7 == nextWeek) {
            table.append(tr)
            if (i >= lastDate)
                break
            tr = $('<tr>')
        }
        i++
    }
}

$.fn.stopPropagation = function() {
    this.click(function(event) {
        event.stopPropagation()
    })
    return this
}


//今何しようCEO文字カウント
$(function() {
    $("#voice_text").keydown(function countRemainingChars(e){
        if (e.keyCode == 13) {
            return false;
        }
    }).keyup(function() {
        maxchars = 150;
        var counter = $(this).val().length;
        $("#voice_counter").html(maxchars-counter);
    })
})
$(window).load(function(){
    $('#voice_text').formNotifier()
})

$(function() {
  $('.gnav').click(function() {
    $(this).next('.localnav').toggle()
  })
})

var heightChange = function() {
	var leftBoxHeight = $('#left_box').height();
	var rightBoxHeight = $('#right_box').height();
	if (leftBoxHeight < rightBoxHeight) {
		document.getElementById('left_box').style.height = rightBoxHeight+'px';
	}
}

$(function() {
	heightChange();
})

$(function() {
  $('.detail_search_display').click(function() {
    $('.userSearchDetail').show()
    $('.normalSearch').hide()
	document.getElementById('left_box').style.height = 'auto';
  })
  $('.search_display').click(function() {
    $('.userSearchDetail').hide()
    $('.normalSearch').show()
    heightChange();
  })
})

$.fn.lazykeyup = function(callback) {
  var timer = {}
  var target = this
  target.keyup(function() {
    clearTimeout(timer.id)
    timer.id = setTimeout(function(){callback.apply(target)}, 200)
  })
  return this;
}

//管理側掲示板画像削除用
$.deleteImageForAdminBoard = function(e, id, number) {
    var url = $.baseurl + 'admin/board/standard/topic/detail/' + id + '/1'
    deleteImage(e, url, 'div', {deleteImage:true, id:id, number:number})
}

//管理側掲示板トピック画像用（編集画面）
$.deleteImageForAdminBoardTopicEdit = function(e, id, number) {
    var url = $.baseurl + 'admin/board/standard/topic/edit/' + id
    deleteImage(e, url, 'div', {deleteImage:true, id:id, number:number})
}

//管理側イベント掲示板画像削除用
$.deleteImageForAdminOfflineMeetingBoard = function(e, id, number) {
    var url = $.baseurl + 'admin/board/offlineMeeting/topic/detail/' + id + '/1'
    deleteImage(e, url, 'div', {deleteImage:true, id:id, number:number})
}

//管理側イベント掲示板トピック画像用（編集画面）
$.deleteImageForAdminOfflineMeetingBoardTopicEdit = function(e, id, number) {
    var url = $.baseurl + 'admin/board/offlineMeeting/topic/edit/' + id
    deleteImage(e, url, 'div', {deleteImage:true, id:id, number:number})
}

// 管理側コミュニティトピック画像削除用
$.deleteImageForAdminCommunityTopic = function(e, communityId, topicId) {
    var url = $.baseurl + 'admin/community/' + communityId + '/topic/imageDelete'
    deleteImage(e, url, 'div', {topicId:topicId})
}

// 管理側コミュニティ画像削除用
$.deleteImageForAdminCommunity = function(e, communityId, imageKind) {
    var url = $.baseurl + 'admin/community/imageDelete/' + imageKind
    deleteImage(e, url, 'div', {communityId:communityId})
}

// 人一覧の画像BOXの高さをそろえる
$.fn.adjustHeight = function() {
	var adjust = function(boxes) {
		var max=0
		$(boxes).each(function() {
			var top = $(this).offset().top
			max=Math.max(max,$(this).height())
		}).height(max)
	}
	var current = 0;
	var boxes = []
	this.each(function(){
		var top = $(this).offset().top
		if (current != top) {
			if (boxes.length != 0) {
				adjust(boxes)
				// adust後にtopを取り直す
				top = $(this).offset().top
				boxes = []
			}
			current = top
		}
		boxes.push(this)
	})
	adjust(boxes)
	document.getElementById('left_box').style.height = '';
	heightChange();
	return this
}

})(jQuery)

// テンプレートエンジン
T = function(template) {
  return {render: function(data) {
    return template.replace(/{\w+?}/g, function(a) {
      return data[a.substring(1, a.length -1)]
    })
  }}
}

// 表示、非表示切り換え
function display(target) {
      var point = document.getElementById(target);
      if (point.style.display == 'none') {
          point.style.display = '';
      } else {
          point.style.display = 'none';
      }
}

// 友人紹介に使用するPaginator
var userPaginator = function(options) {
  var target = options.target
  var paginator = options.paginator
  var input = options.input

  // 検索
  var members = $('li', target).map(function() {
    return {name: $('label', this).text(), tag: this}
  })
  var matched = members
  var search = function(v) {
    matched = $(members).filter(function() {
      return this.name.indexOf(v) != -1
    })

    var ITEMS_PER_PAGE = 7
    var render = function(index) {
      target.empty()
      $(matched.slice(index, index + ITEMS_PER_PAGE)).each(function() {
        target.append(this.tag)
      })
      return false
    }
    paginator.pagination(matched.length, {
    	// TODO baseurlではなくmediaurlを使う
    	prev_text:'<img height="15" width="38" alt="prev" src="' + $.baseurl +'/userSide/images/friends/introduction/introduction_paging_prev.gif"/>',
		next_text:'<img height="15" width="38" alt="next" src="' + $.baseurl +'/userSide/images/friends/introduction/introduction_paging_next.gif"/>',
        items_per_page:ITEMS_PER_PAGE,
        num_edge_entries: 1,
        num_display_entries: 3,
        callback: render
      });
  }
  options.input.lazykeyup(function(){
    search(this.val())
  })
  search(input.val())
}

// detailがない場合
//<script>
//$(function(){$('.paging_con').postPaginator('#userSearchForm')})
//</script>

//detailがある場合
//	<script>
//	$(function(){$('.paging_con').postPaginator('#userSearchForm', '#userSearchDetail')})
//	</script>

$.fn.postPaginator = function(formName, detailName) {
  // Paginator以下のAタグに引数のformをPOSTするイベントを付加
  this.find('a').css('cursor', 'pointer').click(function(){

      $(formName).find(':text, :password, textarea, :checkbox, :radio, select').attr('disabled', 'true').end()

    // detailNameは省略できる。詳細表示フラグ
    if (detailName)
      var showDetail = $(detailName).css('display') != 'none';
    else
      var showDetail = false;
    $(formName).append(
        $('<input type="hidden" />')
          .attr('name', T('search[{page}][{detail}]')
          .render({page:this.title, detail:showDetail})))
        .submit()
  })
}

//業種設定時の画面制御
$(function() {
  $('.check_biz').click(function() {
	var checkedId = this.id
	$('input[id^='+ checkedId +']').not(this).attr('checked','').attr('disabled', this.checked)
	if(this.checked){
		$('label[id^=l'+ checkedId +']').not('label[id=l'+ checkedId +']').css('color', '#CCCCCC')
	}else{
		$('label[id^=l'+ checkedId +']').not('label[id=l'+ checkedId +']').css('color', '#333333')
	}
  })
  //ユーザ業種
  $('td[class$=selected_userbiz]').each(function(){
		var checkedId = this.id
		$('td[id^='+ checkedId +']').not('td[id='+ checkedId +']').attr('class', 'selected_sub')
	})
  //見積り依頼系業種
  $('td[class$=selected_biz]').each(function(){
		var checkedId = this.id
		$('td[id^='+ checkedId +']').not('td[id='+ checkedId +']').attr('class', 'selected_sub')
		if( checkedId.length > 6 ){
			var checked_parent = checkedId.substr(0, 6)
			$('td[id='+ checked_parent +']').attr('class', 'selected_sub')
		}
		if( checkedId.length > 3 ){
			var checked_g_parent = checkedId.substr(0, 3)
			$('td[id='+ checked_g_parent +']').attr('class', 'selected_sub')
		}
	})
})

//ユーザ階層設定時の画面制御
$(function() {
  $('.check_hier').click(function() {
	var checkedId = this.id
	$('input[id^='+ checkedId +']').not(this).attr('checked','').attr('disabled', this.checked)
	if(this.checked){
		$('label[id^=l'+ checkedId +']').not('label[id=l'+ checkedId +']').css('color', '#CCCCCC')
	}else{
		$('label[id^=l'+ checkedId +']').not('label[id=l'+ checkedId +']').css('color', '#333333')
	}
  })
  //ユーザ業種
  $('td[class$=selected_sethier]').each(function(){
		var checkedId = this.id
		$('td[id^='+ checkedId +']').not('td[id='+ checkedId +']').attr('class', 'selected_sub')
	})
})

// 広告のクリックされた回数を更新します
$.countAdvertisement = function(e, advertisementId) {
    var url = $.baseurl + '/sns/advertisement/countUp'
	$.post(url, {advertisementId:advertisementId})
}

// 指定されたチェックボックス全てを、選択or未選択にします
$.allcheck = function(target, flag) {
	for(n = 0; n < target.length; n++){
		target[n].checked = flag;
	}
}
