$(function() {
	var cs = function(val) {
		if (val == '') {
			val = '0';
		}
		$('.college_specification-option').each(function(){
			var meta = $(this).metadata();
			var i;
			for (i = 0; i < meta.value.length; i++) {
				if (meta.value[i] == val) {
					$(this).css('display', '');
					return;
				}
			}
			$(this).css('display', 'none');
			$('input', this).val('');
		});
	}
	$('#user-college_specification').click(function (){
		cs($(this).val());
		$('#user-college_name').flushCache();
	});
	if ($('#user-college_specification')) {
		cs($('#user-college_specification').val());
	}
	else {
		cs('');
	}
	var address_cb = function(me, it) {
		return function () {
			if (this.checked) {
				$('#user-' + me).removeAttr('disabled');
				$('#user-' + it).attr('disabled', 'disabled').val('').parent().removeClass('error-input');
			}
			else {
				$('#user-' + me).attr('disabled', 'disabled').parent().removeClass('error-input');
				$('#user-' + it).removeAttr('disabled').val('');
			}
		};
	};
	$('#user-address_isjp-1').click(address_cb('address_pref', 'address_country'));
	$('#user-address_isjp-0').click(address_cb('address_country', 'address_pref'));
	if ($('#user-address_isjp-1').attr('checked')) {
		address_cb('address_pref', 'address_country').apply($('#user-address_isjp-1').get(0));
	}
	else {
		address_cb('address_country', 'address_pref').apply($('#user-address_isjp-0').get(0));
	}

	$('#user-from_isjp-1').click(address_cb('from_pref', 'from_country'));
	$('#user-from_isjp-0').click(address_cb('from_country', 'from_pref'));
	if ($('#user-from_isjp-1').attr('checked')) {
		address_cb('from_pref', 'from_country').apply($('#user-from_isjp-1').get(0));
	}
	else {
		address_cb('from_country', 'from_pref').apply($('#user-from_isjp-0').get(0));
	}

	if ($.autocomplete) {
		$('#user-college_name').autocomplete(BASE_PATH + 'ajax/college', {
			dataType: 'json',
			extraParams: {college_specification: function(){ return $('#user-college_specification').val(); }},
			parse: function (data) {
				var parsed = [];
				var row;
				for	(var i = 0; i < data.length; i++) {
					row = data[i];
					parsed[i] = {
						data: row,
						value: row.college_name,
						result: row.college_name
					};
				}
				return parsed;
			},
			max: 100,
			formatItem: function (row) {
				return row.college_name;
			}
		});
	}

	var scale = ['E', 'D', 'C', 'B', 'A'];
//	var directions = ['n','ne','se','s','sw','nw'];
	var directions = ['n','ne','se','s'];
	var getGraphValue = function (value) {
//alert(value);
		var v = (value - 1) * 25;
		if (v == 0) {
			return 5;
		}
		else {
			return v;
		}
	};


	var google_chart_url = function (val, small, color_type) {
//alert(val);
		var size;
		var chco;
		var chm_color;
		if (small) {
			size = '150x150';
		}
		else {
			size = '200x200';
		}
		if (color_type === 'blue') {
			chco = '72C6FF';
			chm_color = '7ACEFF';
		}
		else {
			chco = 'FF9300';
			chm_color = 'FF9900';
		}
		return 'http://chart.apis.google.com/chart?cht=r&chs=' + size + '&chls=3,0,0&chco=' + chco + '&chm=B,' + chm_color + '80,0,0,5&chma=20,20,12,20&chxt=x,y&chxl=0:|%20|%20|%20|%20|1:|E|D|C|B|A&chd=t:' + val;
	};

	var show_chart = function (chart, small, color_type) {
		var val = '';
		var pre = '';
		var meta;
		$(directions).each(function(i, dir){
			val += pre + getGraphValue($('.chart-label-' + dir, chart).metadata().value);
			pre = ',';
		});
		val += pre + getGraphValue($('.chart-label-n', chart).metadata().value);
		$(chart).css('background-image', 'url(' + google_chart_url(val, small, color_type) + ')');
	}

	$('.chart').each(function (i, chart) {
		var meta = $(this).metadata();
		var color_type;
		if (meta.color_type) {
			color_type = meta.color_type;
		}
		else {
			color_type = 'orange';
		}
		show_chart(chart, true, color_type);
	});

	$('#chart').each(function (i, chart) {
		show_chart(chart, false);
	});

	$('#sliders').each(function() {
		var meta = $(this).metadata();
		var callback = function() {
			if (meta.func == 'search') {
				search();
			}
			else if (meta.func == 'gen_graph') {
				gen_graph();
			}
		};

		var get_slider_val = function(i) {
			var $input = $('#score-tag-' + i + '-value');
			var j;
			if ($input.attr('type') == 'text') {
				return $input.val();
			}
			else {
				for (j = 1; j < 6; j++) {
					if ($('#score-tag-' + i + '-value-' + j).attr('checked')) {
						return j;
					}
				}
				return 0;
			}
		};

		var slider_values = [];
		var search = function(){
			var params = {};
			var i;
			var tag;
			var j = 0;
			for (i = 0; i < 3; i++) {
				tag = $('#score-tag-' + i + '-tag').val();
				if (tag != '') {
					params['tag[' + j + '][value]'] = get_slider_val(i);
					params['tag[' + j + '][tag]'] = tag;
					j++;
				}
			}
			$.get(
				BASE_PATH + 'score/ajax',
				params,
				function(data) {
					$('#slider-result').html(data);
					$('#slider-result .chart').each(function (i, chart) {
						show_chart(chart, true);
					});
				},
				'html'
			);
		};

		var gen_graph = function(){
			var i;
			var val = '';
			var pre = '';
			var label = '';
			var temp;
//			for (i = 0; i < 6; i++) {
			for (i = 0; i < 4; i++) {
				val += pre + getGraphValue(get_slider_val(i));
//alert("val2= "+ val);
				pre = ',';
			}
			val += pre + getGraphValue(get_slider_val(0));
			pre = '';
//			for (i = 0; i < 6; i++) {
			for (i = 0; i < 4; i++) {
				temp = $('#score-tag-' + i + '-tag').val();
				if (temp == '') {
					temp = '未設定';
				}
				$('#chart-label-' + directions[i]).html(temp);
			}
			$(chart).css('background-image', 'url(' + google_chart_url(val, false, 'orange') + ')');
		};

		$(".slider input", $(this)).each(function(i, slider){
			var index = $(slider).attr('id').substring(11,12);
			$(slider).slider({
				from: 1,
				to: 5,
				step: 0.1,
				dimension: '',
				scale: scale,
				limits: false,
				onstatechange: function(a) {
					if (slider_values[index] == null) {
						slider_values[index] = a;
					}
					else if (slider_values[index] != a) {
						slider_values[index] = a;
						callback();
					}
				},
				calculate: function(value) {
					return scale[Math.round(value) - 1];
				}
			});
		});
		$("input:radio", $(this)).each(function(){
			$(this).click(function(){
				callback();
			});
		});

		//hover states on the static widgets
		$('.icon').hover(
			function() { $(this).addClass('ui-state-hover'); }, 
			function() { $(this).removeClass('ui-state-hover'); }
		).each(function(){
			var meta = $(this).metadata();
			var target = $(meta.target).dialog({
				'autoOpen':false,
				width:550,
				modal: false
			});
			$('a', target).focus(function(){ $(this).blur(); return false;});
		}).click(function(){
			var meta = $(this).metadata();
			$(meta.target).dialog('open');
		});

		$('.tags a').click(function(){
			var elem = $(this).parent().parent().parent();
			var meta = elem.metadata();
			$(meta.target).val($(this).html());
			elem.dialog('close');
			callback();
			return false;
		});
		callback();
	});

	$('#lightbox').lightBox({
		imageLoading: JS_DIR + 'jquery-lightbox/images/lightbox-ico-loading.gif',		// (string) Path and the name of the loading icon
		imageBtnPrev: JS_DIR + 'jquery-lightbox/images/lightbox-btn-prev.gif',			// (string) Path and the name of the prev button image
		imageBtnNext: JS_DIR + 'jquery-lightbox/images/lightbox-btn-next.gif',			// (string) Path and the name of the next button image
		imageBtnClose: JS_DIR + 'jquery-lightbox/images/lightbox-btn-close.gif',		// (string) Path and the name of the close btn
		imageBlank: JS_DIR + 'jquery-lightbox/images/lightbox-blank.gif'			// (string) Path and the name of a blank image (one pixel)
	});
	$('#show-lightbox').click(function(){
		$('#lightbox').click();
		return false;
	});

	$('#score-admin-form').each(function() {
		var auth_password;
		var authtype_changed = function() {
			var meta = $(this).metadata();
			if (meta.password) {
				$('#auth-password').removeAttr('disabled');
				$('#auth-password').val(auth_password);
			}
			else {
				auth_password = $('#auth-password').val();
				$('#auth-password').attr('disabled', 'disabled');
				$('#auth-password').val('');
			}
		};
		$("input:radio[@name='auth[authtype_id]']").click(authtype_changed).each(function(){
			if ($(this).attr('checked')) {
				authtype_changed.apply(this);
			}
		});
	});

	$('#score-form').each(function () {
		var cur_scroll = function(){
			return {
				x: document.body.scrollLeft || document.documentElement.scrollLeft,
				y: document.body.scrollTop  || document.documentElement.scrollTop
			};
		};
		var XOR = function(a,b) {
			return ( a || b ) && !( a && b );
		};
		var inkare = function () {
			$('.inkare').each(function(i, obj){
				var meta = $(obj).metadata();
				var display = XOR($('#score-inkare-1').attr('checked'), meta.value == '0');
				$(obj).css('display', display ? '' : 'none');
			});
		};
		$('#score-inkare-1').click(inkare);
		inkare();
		var saved_scroll;
		var saved_title;
		var target;
		var full_screen_editor = function() {
			var meta;
			var sample;
			saved_scroll = cur_scroll();
			meta = $(this).metadata();
			target = meta.target;
			$('#contents').toggle();
			$('#sub').toggle();
			$('#screen').toggle();
			$('#screen-editor').val($(target).val()).focus();
			$('#screen-title').html(meta.prop);
			sample = $('.example-body', $(this).parent().parent()).html();
			if (sample == null) {
				$('#screen-sample').html('');
				$('#screen-sample').toggle();
				$('#screen-sample-title').toggle();
			}
			else {
				$('#screen-sample').html(sample);
			}
			return false;
		};
		$('.full-screen-editor input').click(function(){
			full_screen_editor.apply(this);
		});
		$('#screen .close-me').click(function(){
			$(target).val($('#screen-editor').val());
			$('#contents').toggle();
			$('#sub').toggle();
			$('#screen').toggle();
			if ($('#screen-sample').html() == '') {
				$('#screen-sample').toggle();
				$('#screen-sample-title').toggle();
			}
			window.scroll(saved_scroll.x, saved_scroll.y);
			return false;
		});
		$('#score-cancel').click(function() {
			var meta = $(this).metadata();
			if (meta.id) {
				if (confirm('編集内容を破棄します。\nよろしいですか？')) {
					location.href = BASE_PATH + "score/view/" + meta.id;
				}
			}
		});
		var toggle_topic = function(context, options) {
			$(context).each(function () {
				var topic = this;
				$(options.body, this).hide();
				$(options.title, this).append(' [<a href="#">表示</a>]').find('a').click(function(){
					if ($(this).html() == '表示') {
						$(this).html('非表示');
					}
					else {
						$(this).html('表示');
					}
					$(options.body, topic).toggle();
					return false;
				});
			});
		};
		toggle_topic('.form-example', {title: '.example-title', body: '.example-body'});
	});

	$('#score-history-form').each(function() {
		var rev_filter = function(elems, min, max) {
			$(elems).each(function(){
				var val = $(this).val();
				if ((min == -1 || val >= min) && (max == -1 || val <= max)) {
					$(this).css('display', '');
				}
				else {
					$(this).css('display', 'none');
				}
			});
		};
		var max = -1;
		var min = 1;
		$('input[name=rev1]').each(function(){
			max = Math.max(max, $(this).val());
			min = Math.min(min, $(this).val());
		});
		$('input[name=rev1]').click(function(){
			rev_filter('input[name=rev2]', parseInt($(this).val()) + 1, -1);
		});
		$('input[name=rev2]').click(function(){
			rev_filter('input[name=rev1]', -1, parseInt($(this).val()) - 1);
		});
		$('input[name=rev1][value=' + (max-1) + ']').click();
		$('input[name=rev2][value=' + (max) + ']').click();
	});

});

