$(document).ready(function()
{
	$('#login_area').load("/loginArea/time_"+Math.random(),function()
	{
		$("#nav_login_btn").css("cursor","pointer").live("click",function()
		{	var errmsg = '';
				if($("input[name=nav_user]").val()==''){
					errmsg += 'ログインIDをご入力ください\n';
				}
				if($("input[name=nav_password]").val()==''){
					errmsg += 'パスワードを入力してください\n';
				}
				if(errmsg != '')
				{
					alert(errmsg);
				}else{
					var options = {
						url:'/loginArea_doLogin',
						type:'POST',
						dataType:'json',
						success: function(data){
							if(data.err)
							{
								alert(data.err);
							}else{
								//$('#login_area').empty();
								//$('#login_area').load("/loginArea");
								window.location.reload();
							}
						}
					};
					$('#nav_login_form').ajaxSubmit(options);
				}
		 });
		$('form').live("keypress",function(event){
		if(event.keyCode == 13){
			var nx, me = event.target;
			if(me.type == 'text' || me.type == 'password' || me.type == 'checkbox'){
				var i = 0;
				if(!this.key13first){
					var index = 0, stack = [];
					while(i < this.elements.length){
						nx = this.elements[i++];
						if(nx.tabIndex){
							if(nx.tabIndex == 1)this.firstElement = nx;
							if(index < nx.tabIndex)index = nx.tabIndex;
						}else{
							stack.push(nx);
						}
					}
					while(nx = stack.shift())nx.tabIndex = ++index;
					if(!this.firstElement)this.firstElement = this.elements[0];

					i = 0;
					this.key13first = 1;
				}
				while(i < this.elements.length){
					nx = this.elements[i++];
					if(nx.tabIndex == me.tabIndex + 1){
						nx.type == 'button' || nx.type == 'submit' || nx.type == 'image' ? nx.click() : nx.focus();
						break;
					}
				}
				if(i >= this.elements.length)this.firstElement.focus();
			}
		}
	});
		 $("#nav_register_btn").css("cursor","pointer").live("click",function()
		 {
			 window.open("/member/register");
		 });

	});

	$.getJSON("/ajaxGetNav_GameList/time_"+Math.random(), null, function(items){
		initOptions($('#gamename'), items);
		initOptions($('#gamename2'), items)}
	);

	$('#gamename').add($('#gamename2')).change(function(){
		var value = parseInt($(this).val()), select = $('#gamedivision' + (this.id.slice(-1) != '2' ? '' : '2')),
			cache = select.data('cache') || {}, items = value ? cache[value] : [];
		initAllValues();
		items ? initOptions(select, items) :
			$.getJSON("/ajaxGetNav_PartitionList/gid_" + value + "/time_"+Math.random(), null, function(items){
				cache[value] = items;
				select.data('cache', cache);
				initOptions(select, items);
		});

	});
	$('#gamedivision').add($('#gamedivision2')).change(function(){
		var gid = $("#gamename" +(this.id.slice(-1) != '2' ? '' : '2')).val(),
			key = gid + '/' + $(this).val(), id = this.id, select = $(this), cache = select.data('cache') || {}, $rs = cache[key];
		!this.selectedIndex || $rs ? initAllValues($rs) :
			$.getJSON("/ajaxGetNav_QuoteTotal/gid_"+ gid +"/pid_"+$(this).val()+"/time_"+Math.random(), null, function($rs){
				cache[key] = $rs;
				select.data('cache', cache);
				initAllValues($rs, id.slice(-1) != '2');
			});
	});

	function initOptions(select, items){
		var i = 0, select = select[0];
		if(!select)return false;
		select.options.length = 1;
		while(i < items.length){
			var item = new Option(items[i].title || items[i].fulltitle, items[i].id);
			item.setAttribute('seo', items[i++].seo);
			select.options[i] = item;
		}
	}
	function initAllValues($rs, f){
		$rs = $rs || {};
		var quote = $rs.quote, total = $rs.total;
		if(f){
			$('#nav_quote').html(
				'<li><strong class="orange" id="gamermprice">' + (quote ? quote[0].price : 0) + ' </strong>円</li>'
				+ '<li><strong class="orange" id="gamecrprice">' + (quote ? quote[1].price : 0) + ' </strong>円</li>'
				+ '<li><strong class="orange" id="gamewmprice">' + (quote ? quote[5].price : 0) + ' </strong>WM</li>'
				+ '<li><strong class="orange" id="gameintotal">' + (total ? total.front_stock : 0) + ' </strong> 口</li>'
			);
		}else{
			$('#nav_quote2').html(
				'<li><span>RM./コンビニ：</span><strong class="orange" id="gamermprice">' + (quote ? quote[0].price : 0) + '</strong> 円</li>'
				+ '<li><span>クレジット/ちょコム：</span><strong class="orange" id="gamecrprice">' + (quote ? quote[1].price : 0) + '</strong> 円</li>'
				+ '<li><span>WM/購入価格：</span><strong class="orange" id="gamewmprice">' + (quote ? quote[5].price : 0) + '</strong> 円</li>'
				+ '<li><span>在庫：</span><strong class="orange" id="gameintotal">' + (total ? total.front_stock : 0) + '</strong> 口</li>'
			);
		}
	}

	$('#search_buy').add($('#btn_buy')).click(function(){
		var f = this.id == 'btn_buy', g = $('#gamename' + (f ? 2 : '')), p = $('#gamedivision' + (f ? 2 : ''));
		if(g.val() > 0 && p.val() > 0)
		{
			window.open("/game/"+g.find('option:selected').attr('seo')+"/buy/pid_"+p.val(), '_self');
		}
	});

	//$('#game_list_left').load("/ajaxGetGameListLeft/time_"+Math.random());
	$('#game_list_bot').load("/ajaxGetGameListBot/time_"+Math.random());


});

	



function alibox(source, target, callback){
	var cac = {};
function cursor(obj, pos, end){
	if(pos == undefined){
		if($.browser.msie){
			var s = document.selection.createRange(),
				a = s.text.length, t = obj.createTextRange();
			s.setEndPoint('StartToStart', t);
			return [s.text.length - a, s.text.length];
		}else{
			return [obj.selectionStart, obj.selectionEnd];
		}
	}else{
		if($.browser.msie){
			var t = obj.createTextRange();
			t.collapse(true);
			t.moveStart('character', pos);
			end != undefined && t.moveEnd('character', end - pos);
			t.select();
		}else{
			obj.selectionStart = pos;
			obj.selectionEnd = end == undefined ? pos : end;
		}
	}
}
function keypress(event){
	var f, a = event.which,
		arg = $(this).data('arg');
	if(a == 32)return false;
	var v = $(this).val(), p = cursor(this), l = v.length + p[0] - p[1];

	if(a && !event.metaKey){
		if(a == 8){
			//del char
			if(event.davis && p[1]){
				var o = p[0] == p[1] ? p[0] - 1 : p[0];
				$(this).val(v.slice(0, o) + v.slice(p[1]));
				cursor(this, o);
			}
		}else if((f = l >= arg.len - 1) && l < arg.len){
			$(this).val(v.slice(0, p[0]) + String.fromCharCode(a) + v.slice(p[1]));
			cursor(this, p[0] + 1);
		}
		var x = '';
		source.each(function(){x += $(this).val()});

		if(target && target.val()){
			target.data('val', '').val('');
		}
		if(x.length < cac.max){
			if(f && l == p[0]){
				v = source.eq(arg.idx + 1).focus()[0];
				v && cursor(v, arg.len);
			}
		}else{
			target && target.val(x);
		}
		if(callback)try{callback(x)}catch(e){}
		if(a == 8 || f)return false;
	}
}
function keypdown(event){
	var arg = $(this).data('arg');
	switch(event.which){
	case 35:
		cursor(source.eq(source.length - 1).focus()[0], cac.max);
		break;
	case 36:
		cursor(source.eq(0).focus()[0], 0);
		break;
	case 8:
		var actv;
		if(cursor(this)[1]){
			actv = this;
		}else{
			cursor(actv = source.eq(arg.idx ? arg.idx - 1 : 0).focus()[0], cac.max);
		}
		return keypress.call(actv, {which : 8, davis : 1});
		break;
	case 37:
		if(!arg.idx)break;
		if(!cursor(this)[0]){
			cursor(source.eq(arg.idx - 1).focus()[0], cac.max);
			return false;
		}
		break;
	case 39:
		if(arg.idx == source.length - 1)break;
		var b = cursor(this)[1];
		if(arg.len == b || $(this).val().length == b){
			source.eq(arg.idx + 1).focus();
			try{
			cursor(source.eq(arg.idx + 1)[0], 0);
			}catch(e){alert(e.message)}
			return false;
		}
		break;
	case 46://del
		var p = cursor(this);
		if(p[0] != $(this).val().length){
			if(p[0] == p[1])cursor(this, p[0] + 1);
			return keypress.call(this, {which : 8, davis : 1});
		}
	}
}
function paste(){
	var p = cursor(this), me = $(this),
		val = me.val(), arg = $(this).data('arg');
	me.val('');
	me.attr('maxlength', cac.max + source.length - 1);
	setTimeout(function(){
		me.attr('maxlength', arg.len);
		var i, l, x, z, m = me.val().split(/-| /g);
		if(m.length == 1){
			i = x = 0; l = m[0].length;
			if(l >= 16){
				while(i < l){
					z = cac[x++];
					m.push(m[0].substr(i, z));
					i += z;
				}
				m.shift();
			}else{
				return me.val(
					val.slice(0, p[0]) +
					m[0].slice(0, arg.len - val.length - p[0] + p[1]) +
					val.slice(p[1])
				);
			}
		}else{
			i = x = 0; l = m.length;
			while(i < l){
				z = cac[x++];
				if(m[i].length > z)m[i] = m[i].slice(0, z);
				i++;
			}
		}
		source.each(function(i){$(this).val(m[i] || '');m[i] && (me = this)});
		cursor(me = $(me).focus()[0], cac.max);
		keypress.call(me, {which : 8});
	},20);
}

cac.max = 0;
source.keypress(keypress).keydown(keypdown)
	.bind('paste', paste).each(function(i){
		var arg = {
			idx : i,
			len : parseInt($(this).attr('maxlength'))
		};
		$(this).data('arg', arg);
		cac.max += cac[i] = arg.len;
	});
}


function addfavorite(url, title){
	try{
		window.external.addfavorite(url, title);
	}catch (e){
		try{
			window.sidebar.addPanel(title, url, '');
		}catch (e){
			alert('ブラウザがそっぽをご使用くださいctrl + d收藏!');
		}
	}
}
