function isReady() {
    return jsReady;
}
$(document).ready(function(){
	switch($("#plat").val()){
		case 'mixi':
		case 'orkut':
		case 'hi5':
		case 'netlog':
		case '51com':
		case 'fanbox':
		case 'friendster':
		case 'goo':
		case 'yahoo':
		case 'google':
		case 'igoogle':
		case 'hyves':
		case 'linkedin':
		case 'iwiw':
		case 'lonly':
		case 'mail':
		case 'atutor':
		case 'avatars':
		case 'freebar':
		case 'itimes':
		case 'ning':
		case 'phpfox':
		case 'qme':
		case 'quepasa':
		case 'renren':
		case 'socialtext':
		case 'sonico':
		case 'webjam':
		case 'webon':
		case 'xing':
		case 'yiqi':
		case 'yonja':
		case 'studivz':
		case 'meinvz':
		case 'hi5':
		case 'myspace':opensocial = true;break;
	}
	jsReady = true;
	switch($("#uilang").val()){
		case 'en':uilang='en';break;
		case 'ko':uilang='ko';break;
		default:uilang='ja';break;
	}
	if(!$.support.leadingWhitespace){
		id = true;
		hdheight = 200;
		pdheight = 100;
		ieadjust = 2;
		colieadjust = 0;
		colieadjust2 = 1;
		views4 = [25,25,25,100,100,50,50,50,50,50,25,25,25];
		for(i=0;i<views.length;i++){
			viewobj[views[i]]['width'] = views4[i];
		}
	}
	genLangSet();
	platformAdjust();
	$("#fcarea").hide();
	drawPresetTitles();
	if(location.href.match("localhost")){
		local = 'localhost/';
	}
});
function genLangSet(){
	$("#lang-"+uilang).attr("checked",true);
	setLanguage();
}
function platformAdjust(){
	plat = $("#platform").val();
	if(plat == 'jipanglish'){
		jipUnbind();
		jipLogin();
	}else if(opensocial){
		$('.v-top-left').css({width : 35+'%'});
		$('.v-top-center').css({width : 30+'%'});
		$('.v-top-right').css({width : 35+'%', 'padding-top' : 0});
		$('#ad').css({width : 300+'px'});
		isUnbinds = [1,0,0,1,1,1,1,1,1,1,0,0];
		genre5 = [[],[],[],[],[]];
		genre3 = [['All'],['All'],['All'],['All']];
		genre4 = [typejp,{},langs,langs];
		genres = [toh,toh2,ll,ll];
		genres2 = [toh3,toh4,ll2,ll2];
		gpos = [['All'],['All'],['All'],['All']];
		gselected = [[0],[0],[0],[0]];
		gmatch = {pos:0,alpha:1,llang:2,tlang:3};
		genreId = ['pos','alpha','llang','tlang'];
		//genreId2 = ['品詞','頭文字','学習言語','翻訳言語'];
		gadgets.window.adjustHeight(650);
		mixiLogin();
	}else if(plat == 'facebook'){
		$('.v-top-left').css({width : 35+'%'});
		$('.v-top-center').css({width : 30+'%'});
		$('.v-top-right').css({width : 35+'%', 'padding-top' : 0});
		$('#ad').css({width : 250+'px'});
		$('#wfilter').attr("size", 15);
		isUnbinds = [1,0,0,1,1,1,1,1,1,1,0,0];
		genre5 = [[],[],[],[],[]];
		genre3 = [['All'],['All'],['All'],['All']];
		genre4 = [typejp,{},langs,langs];
		genres = [toh,toh2,ll,ll];
		genres2 = [toh3,toh4,ll2,ll2];
		gpos = [['All'],['All'],['All'],['All']];
		gselected = [[0],[0],[0],[0]];
		gmatch = {pos:0,alpha:1,llang:2,tlang:3};
		genreId = ['pos','alpha','llang','tlang'];
		views4 = [20,20,20,75,75,50,50,50,50,50,20,20,20];
		for(i=0;i<views.length;i++){
			viewobj[views[i]]['width'] = views4[i];
		}
		//genreId2 = ['品詞','頭文字','学習言語','翻訳言語'];
		facebookLogin();
	}
}
function genWdialog(){
	var wbuttons = {};
	wbuttons[l.m.login] = function(){logintoIknow();};
	wbuttons[l.m.nologin] = function(){$('#wdialog').dialog('close');};
	$('#wdialog').dialog({
		autoOpen: false,
		minHeight:wdheight,
		height: 150,
		width: 350,
		resizable:false,
		modal: true,
		draggable: false,
		buttons: wbuttons,
		close : function(){startup();}
	});
}
function genMdialog(){
	var name = $("#name"),
	allFields = $([]).add(name),
	tips = $(".validateTips");
	function updateTips(t) {
		tips
		.text(t)
		.addClass('ui-state-highlight');
		setTimeout(function() {
			tips.removeClass('ui-state-highlight', 1500);
		}, 500);
	}
	
	function checkLength(o,n,min,max) {
	
		if ( o.val().length > max || o.val().length < min ) {
			o.addClass('ui-state-error');
			updateTips(l.m.list30);
			return false;
		} else {
			return true;
		}
	
	}
	
	function checkRegexp(o,regexp,n) {
	
		if ( !( regexp.test( o.val() ) ) ) {
			o.addClass('ui-state-error');
			updateTips(n);
			return false;
		} else {
			return true;
		}
	
	}
	var wbuttons = {};
	wbuttons[l.m.create] = function(){
		var bValid = true;
		allFields.removeClass('ui-state-error');
		bValid = bValid && checkLength(name,"username",1,30);
		if (bValid) {
			createNewList(name.val());
		};
	};
	wbuttons[l.m.cancel] = function(){$('#modalform').dialog('close');};
	$('#modalform').dialog({
		autoOpen: false,
		height: 200,
		width: 300,
		modal: true,
		buttons: wbuttons,
		close: function() {
			allFields.val('').removeClass('ui-state-error');
		}
	});
}
function jipLogin(){
	if($('#iusername').val()==""){
		isUnbinds = [0,1,1,1,1,1,1,1,0,0,1,1];
		isin = false;
		genWdialog();
		$('#wdialog').css({visibility : 'visible'});
		$('#wdialog').dialog("open");
	}else{
		isUnbinds = [0,0,0,0,0,0,1,1,0,0,0,0];
		uname=$('#iusername').val();
		startup();
	}
}
function mixiLogin(){
	var req = opensocial.newDataRequest();
	req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), "viewer");
	req.send(function(data) {
		if (!data.hadError()) {
	        var item = data.get("viewer");
	        if (item.hadError()) {
	          var code = item.getErrorCode();
	          isin = false;
	        } else {
		      isin = true;
	          var viewer = item.getData();
	          var id = viewer.getId();
	          var nickname = viewer.getDisplayName();
	          var thumbnailUrl = viewer.getField(opensocial.Person.Field.THUMBNAIL_URL);
	          $('#iusername').val(id);
	          $('#topid').html(nickname);
	          uname = id;
	        }
	    }
		unbindUpEvent();
		startup();
	});
}
function facebookLogin(){
	uname=$('#iusername').val();
	unbindUpEvent();
	startup();
}
function startup(){
	jip();
	if(location.href.match("http://192.168.0.22/") || location.href.match("http://localhost/") || location.href.match("http://127.0.0.1/")){
		keeplog = false;
		$('#jlog').html('Log');
		$('#jlog').click(function(ev){
			$('#jlogbox').css({'visibility' : 'visible','top': ev.pageY+'px','left' : ev.pageX+'px'});
			$("#jlogbox").show("normal");
		});
	}
	$('#pdialog').dialog({
		autoOpen: false,
		minHeight:70,
		height: 70,
		width: 300,
		resizable:false,
		modal: true,
		draggable: false
	});
	dp();
	if(isin){
		$(window).unload(function(){if(savereq){saveMy();/*if(confirm('保存していないデータがあります。保存しますか？')){return false;}else{saveMy();}*/}});
		genMdialog();
	}
	processEnterKey();
	addSearchFocus();
	if(isin){
		bindUpEvent();
	}else{
		$('#upmyitem').attr('title',l.i['upmyitem-sub']);
	}
	unbindUpEvent();
	$("#slider").slider();
	$('#slider').bind('slidestop', function(event, ui) {
		wlength = ui.value;
		emptyColumns();
		drawPlus();
		renderMword();
	});
	$('#slider').bind('slide', function(event, ui) {
		$('#svalue').html(ui.value);
	});
	$("#fcarea").draggable();
	$("#fcarea").bind("dragstop",function(event,ui){fposition = $("#fcarea").position();});
	$(".v-left").resizable({ handles: 'e'});
	$(".v-right").resizable({ handles: 'w', ghost : true, animate : true });
	$("#genreboxes").resizable({ handles: 's' });
	$('#genreboxes').bind('resize', function(event, ui) {
	$('#arrow').css({'top':$('#columntop-'+axitem).offset().top+'px','left':($('#columntop-'+axitem).offset().left + viewobj[axitem].width - 16)+'px'});
	$("#gboxitems").height($("#genreboxes").outerHeight() - $("#giseparater").outerHeight() - $("#gboxtitles").outerHeight());
	$("#itemboxes").height($(".v-middle").innerHeight() - $("#genreboxes").outerHeight());
	$("#v-center-cont").height($("#itemboxes").innerHeight() - $("#v-center-titles").outerHeight());
	$("#v-center-width").width($("#itemboxes").innerWidth());
	$(".gbox").height($("#gboxitems").innerHeight() - 4);
	})
	setPopupMenu();
	$('.v-left,.v-right').bind('resize', function(event, ui) {
		var wwidth = $(window).width();
		var wheight = $(window).height();
		if(ui){
			if($(this).hasClass("v-left")){
				lwidth = ui.size.width;
			}else{
				rwidth = ui.size.width;	
			}
		}else{
			if($(this).hasClass("v-left")){
				lwidth = $(".v-left").width;
			}else{
				rwidth = $(".v-right").width;
			}
		}
		$(".v-center").width(wwidth - $(".v-left").outerWidth() - $(".v-right").outerWidth());
		$('#arrow').css({'top':$('#columntop-'+axitem).offset().top+'px','left':($('#columntop-'+axitem).offset().left + viewobj[axitem].width - 16)+'px'});
		$(".gbox").width($(".v-center").innerWidth() / genres.length - 5);
		$(".gbtitle").width($(".v-center").innerWidth() / genres.length - 5);
		if(showlimg){
			$("#leftimage").height($("#leftcomment").outerWidth()+20);
			var eheight =$("#leftimage").outerHeight();
		}else{
			var eheight = 0;
		}
		$("#leftcomment").height($(".v-left").innerHeight() - eheight);
		$("#limg-img").height($("#limg-img").width());
	});
	resizeWindow();
	$(window).resize(function(){
		resizeWindow();
	})
	$("#v-center-titles").sortable({axis :'x'});
	$("#v-center-titles").bind('sortstop',function(event, ui) {
		event.stopPropagation();
		views = [];
		var skids = $("#v-center-titles li");
		for(i=0;i<skids.length;i++){
			var snumbers = skids[i].id.split('-');
			viewobj[snumbers[1]].order = i;
			views[i] = snumbers[1];
		}
		var diff = views0.diff(views);
		views.merge(diff);
		views0 = views;
		emptyColumns();
		drawPlus();
		renderMword(true);
	});
	for(i=0;i<views2.length;i++){
		if(views2[i] == true){
			$("#view-"+views[i]).attr("checked",true);
			plus(views[i]);
		}else{
			$("#view-"+views[i]).attr("checked",false);
		}
	}
	getMyStudiedIds('my');
	jip2();
}
function dp(){
	jip();
	$('#pdialog').css({visibility : "visible"});	
	$('#pdialog').dialog("open");	
	jip2();
}
function dp2(){
	jip();
	$('#pdialog').dialog("close");	
	jip2();
}
function setPopupMenu(){
	jip();
	$('#m-links,#m-view,#m-lang').click(function(event, ui) {
		var tid = event.target.id.split("-");
		removeMenus(tid[1]);
		if(menunow != tid[1]){
			$('#m-'+tid[1]+'-menu').css({'visibility' : 'visible','top' : ($('#'+event.target.id).position().top + $('#'+event.target.id).outerHeight()) + 'px','left' : $('#'+event.target.id).position().left + 'px'});
			$('#m-'+tid[1]).css({'background-color' : '#000000','color' : '#ffffff'});
			menunow = tid[1];
		}else{
			removeMenus('');
			menunow = '';
		}
			event.stopPropagation();
	})
	$(document).bind("click",function(event,ui){
			removeMenus('');
			menunow = '';
	})
	$('#m-links-menu,#m-view-menu,#m-lang-menu').click(function(event, ui) {
		event.stopPropagation();
	})
	$('#m-links,#m-view,#m-lang').bind('mouseout', function(event, ui) {
		tid = event.target.id.split("-");
	})	
	jip2();
}
function removeMenus(tids){
	jip();
	for(i=0;i<pmenus.length;i++){
		if(tids != pmenus[i]){
			menuOut(pmenus[i]);
		}
	}
	jip2();
}
function menuOut(tids){
	jip();
	$('#m-'+tids+'-menu').css({'visibility' : 'hidden'});
	$('#m-'+tids).css({'background-color' : '','color' : ''});
	jip2();
}
function includeAd(){
	jip();
    $("#googlead").css({"visibility":"visible"});
	var currentTime = new Date();
    $("#googlead").attr("src","php/ad.htm?s=" + currentTime.getTime());
	jip2();
}
function removeAd(){
	jip();
	$("#googlead").css({"visibility":"hidden"});
	jip2();
}
function resizeWindow(Re){
	jip();
	var hAdjust = 0;
	if(plat=='mixi'){
		var wwidth = 945;
		var wheight = 600;
	}else if(opensocial){
		var wwidth = $(window).width();
		$("#container").width(wwidth);
		var wheight = 600;
		if(plat=='friendster'){
			$("#container").height(650);
		}
	}else if(plat=='facebook'){
		var wwidth = $(window).width();
		var wheight = $(window).height();
		$("#container").width(wwidth);
		$("#container").height(wheight);
		hAdjust = 30;
	}else{
		var wwidth = $(window).width();
		var wheight = $(window).height();
		$("body").width(wwidth);
		$("body").height(wheight);
	}
	$(".v-middle").height(wheight - $(".v-top").outerHeight() - $(".v-bottom").outerHeight()-hAdjust);
	$(".v-left").height($(".v-middle").innerHeight());
	if(showlimg){
		$("#leftimage").height($("#leftcomment").outerWidth()+20);
		var eheight =$("#leftimage").outerHeight();
	}else{
		var eheight = 0;
	}
	$("#leftcomment").height($(".v-left").innerHeight() - eheight);
	$(".v-right").height($(".v-middle").innerHeight());
	$(".v-center").height($(".v-middle").innerHeight());
	$(".v-center").width(wwidth - $(".v-left").outerWidth() - $(".v-right").outerWidth());
	$("#itemboxes").height($(".v-middle").innerHeight() - $("#genreboxes").outerHeight());
	$("#v-center-cont").height($("#itemboxes").innerHeight() - $("#v-center-titles").outerHeight());
	$("#v-center-width").width($("#itemboxes").innerWidth());
	$("#gboxitems").height($(".v-middle").innerHeight() - $("#itemboxes").outerHeight() - $("#giseparater").outerHeight() - $("#gboxtitles").outerHeight());
	$(".gbox").height($("#gboxitems").innerHeight() - 4);
	$(".gbox").width($(".v-center").innerWidth() / genres.length - 5);
	$(".gbtitle").width($(".v-center").innerWidth() / genres.length - 5);
    if(plat != 'mixi'){
    	$("#googlead").css({"top":+($("#ad").offset().top+1)+"px","left":+($("#ad").offset().left+1)+"px"});
    	$("#slider").width($("#secondrow").innerWidth() - $("#svalue").outerWidth() - $("#topbuttons").outerWidth() - 50);
    }
	adjustArrow();
	jip2();
}
function adjustArrow(Cont){
	jip();
	if(Cont == undefined){
		Cont = axitem;
	}
	$('#columntop-'+Cont).removeClass("columntop").addClass("columntop2");
	if(updown == 1){
		$('#arrow').html('▼');
	}else{
		$('#arrow').html('▲');
	}
	$('#arrow').css({'top':$('#columntop-'+Cont).offset().top+'px','left':($('#columntop-'+Cont).offset().left + viewobj[Cont].width - 16)+'px'});
	jip2();
}
/*
function ninus(){
	jip();
	if(righton == 0){
		rwidth = 200;
		$(".v-right").css({'visibility' : 'visible','width' : rwidth+'px'});
		righton = 1;
	}else{
		rwidth = 0;
		$(".v-right").css({'visibility' : 'hidden','width' : rwidth+'px'});
		righton = 0;
	}
	resizeWindow();
	jip2();
}*/
function addView(Cont){
	jip();
	if($("#view-"+Cont).attr("checked") == true){
		viewobj[Cont].on = true;
	}else{
		viewobj[Cont].on = false;
	}
	reRender();
	jip2();
}
function createList(){
	jip();
	$('#modalform').css('visibility','visible');
	$('#modalform').dialog('open');
	jip2();
}
function addSearchFocus(){
	jip();
	$('#wfilter').focus(function(event, ui){
		if(searchon == 0){
			searchon = 1;
			$('#wfilter').val('');
			$('#wfilter').unbind("focus");
			$('#wfilter').bind("keyup", function(event, ui){
				if(!$('#wfilter').val().match(/^[s]*$/) && $('#wfilter').val() != preword){
					wREG = new RegExp($('#wfilter').val(),"gi");
					preword=$('#wfilter').val();
					emptyColumns();
					drawPlus();
					renderMword();
				}
			});
		}
		$('#wfilter').blur(function(event, ui){
			if($('#wfilter').val().match(/^[s]*$/)){
				searchon = 0;
				$('#wfilter').unbind("blur");
				$('#wfilter').val(l.i.search+'...');
				addSearchFocus();
				preword = '';
			}
		})
	});
	jip2();
}
function changeLang(lang){
	var olang = uilang;
	uilang = lang;
	setLanguage(olang);
}
function setLanguage(olang){
	l = new L[uilang]();
	for(i in l.t){
		$("#"+i).attr("title",l.t[i]);
	}
	for(i in l.d){
		$("#"+i).html(l.d[i]);
	}
	//object
	langs = l.o.langs;
	genre4[3] = genre4[2] = langs;
	genre4[0] = l.o.typejp
	typejp = l.o.typejp;
	ll = [];
	ll2 = [];
	for(i in langs){
		ll.push(i);
		ll2.push(langs[i]);
	}
	genres[3]=genres[4] = ll;
	genres2[3]=genres2[4] = ll2;
	genres2[0]=l.o.toh3;
	genre4[4] = l.o.tprog3;
	genres[4] = l.o.tprog;
	for(i=0;i<views.length;i++){
		viewobj[views[i]]['title'] =l.o.views3[i];
	}
	genWdialog();
	genMdialog();
	var iniappend = '';
	for(var i=0;i<wordset.length;i++){
		var wsid = wordset[i].lang+'-'+wordset[i].rlang;
		iniappend+='<div class="lefttitle country" id="ltitle-'+wsid+'"><img src="'+$('#base').val()+'img/lang-flags/'+wordset[i].rlang+'.png" /> '+langs[wordset[i].rlang]+' ⇒ <img src="'+$('#base').val()+'img/lang-flags/'+wordset[i].lang+'.png" /> '+langs[wordset[i].lang]+'</div><ul id="'+wsid+'-sq"></ul>';
	}
	$("#preset-sq").html(iniappend);
	renderMLists("basic");
	genreId2 = l.o['genreId2'];
	if(onInit == true || $('#wfilter').val() == sDefault[olang]+'...'){
		$('#wfilter').val(l.i.search+"...");
		
	}
	if(onInit != true){
		reRender();
	}
	onInit = false;
}
function jump(url){
	mixi.util.requestExternalNavigateTo(url);
}
function inviter(){
	opensocial.requestShareApp("VIEWER_FRIENDS", null, function(response) {
		  if (response.hadError()) {
		    var errCode = response.getErrorCode();
		    //alert("もう一度お試しください。");
		  } else {
		    //alert("マイミクに招待状を送りました！");
		  }
		});
}
function facebookInviter(){
	parent.location.href= $("#fiurl").val();
}
function limgSwitch(){
	if(!showlimg){//true
		$("#leftimage").height($("#leftcomment").outerWidth()+20);
		var eheight =$("#leftimage").outerHeight();
	}else{//false
		var eheight = 0;
	}
	$("#leftcomment").height($(".v-left").innerHeight() - eheight);
	if(showlimg == true){
		showlimg = false;
		$("#leftimage").hide("slow");
		$("#limg-arrow").html("▲");
	}else{
		showlimg = true;
		$("#leftimage").show("slow",imgHeight);
		$("#limg-arrow").html("▼");
	}
}
function imgHeight(){
	$("#limg-img").height($("#limg-img").width());
}