SEO_RANK_URL_LOCAL = "http://localhost/seo-agent/order/med.php?location=313&ritual=2&type=1&";
SEO_RANK_URL = "http://seo.fiverworks.com/order/med.php?location=313&ritual=2&type=1&";
CLYMENE_URL = "http://www.seo-agent.info/3gen_ocean/clymene?location=313&ritual=2&";
KW_HIST_URL = CLYMENE_URL + "type=3&";
ASSOC_KW_URL = CLYMENE_URL + "type=4&";
ABACUS_URL = "http://www.seo-agent.info/3gen_ocean/abacus?location=313&type=1&ritual=2&";
ORDER_URL = "https://ss1.coressl.jp/seo.fiverworks.com/order/";
ITEM_NAME = new Array("item=STT_V", "item=STT_VF");
ORDER_FILE = new Array("memOrder0.php", "order0.php");
SEO_AGENT_DEBUG = false;
LOCAL = true;
SRM = "/20";
var mlist;
var seo_rank_obj, cost_obj;
$(function($){
	$.ajaxSetup({
		scriptCharset:'utf-8'
	});
	$('#res').click(function() {
		res_kw();
	});
	map = getQueryMap();
	kw1 = map['kw1'];
	kw2 = map['kw2'];
	/*if (kw1 == null && kw2 != null) {
		alert("主キーワードを入力してください。");
	}*/
	kw1 = kw1 == null ? "" : kw1;
	kw2 = kw2 == null ? "" : kw2;
	if (kw1 != "" || kw2 != "") {
		$('#kw1').val(decodeURI(kw1));
		$('#kw2').val(decodeURI(kw2));
		res_kw();
		//showSeoRank(decodeURI(kw1) + " " + decodeURI(kw2));
	}
});

function getQueryMap() {
	query = window.location.search.substring(1);
	params = query.split('&');
	ret = new Array();
	for (var i = 0; i < params.length; i++) {
		var pos = params[i].indexOf('=');
		if (pos > 0) {
			var key = params[i].substring(0,pos);
			var val = params[i].substring(pos + 1);
			ret[key] = val;
		}
	}
	return ret;
}

function res_kw() {
	kw1 = $('#kw1').val();
	// kw = $('#kw1').val() + " " + $('#kw2').val();
	if (kw1.length == 0) {
		alert("主キーワードを入力してください。");
	} else {
		showSeoRank(kw1 + " " + $('#kw2').val());
	}
}

function add_kw(btobj) {
	kw = $(btobj).parent().parent().children('.kw').html();
	showSeoRank(kw);
}

function del_item(btobj) {
	$(btobj).parent().parent().remove();
	showOrder();
}


function showSeoRank(kwp){
	kw = $.trim(kwp);
	kwlen = kw.length;
	if (kwlen == mb_length(kw)) {
		alert("半角文字だけのキーワードは調べられません");
		return;
	}

	$('._kw').empty().append('「' + kw + '」&nbsp;');
	try {
		setAjaxEvent();
		kw_enc = encodeURIComponent(kw);
		var url = (LOCAL ? SEO_RANK_URL_LOCAL : SEO_RANK_URL) + "keyword=" + kw_enc + "&callback=?";
		$.getJSON(url, function(res){
			if(res.status >= 1){
				ret = seo_rank_obj = res.result;
				mlist = getResultStr(ret);
				showCost(ret.seo_rank);
				showKwHist(kw_enc);
				showAssocKw(kw_enc);
			} else if(res.status == 0 || res.status == -1){
				alert("キーワードが不正または長すぎます(50文字以下)");
			} else if(res.status == -2){
				alert("内部エラー\n現在利用できません。時間をおいてからご利用ください。");
			}
		});
	} catch (e) {
		if (SEO_AGENT_DEBUG) alert(e);
	} finally {
	}
}

function wait(mtime) {
    var timeStart = new Date().getTime();
    var timeNow = timeStart;
    while(timeNow > (timeStart + mtime)) {
        timeNow = new Date().getTime();
    }
    return;
}

/**
 * Ajax event
 */
function setAjaxEvent() {
	$('body').ajaxStart(function(){
		$.blockUI({
			message: '<p>処理中・・・</p>'
		});
	});
	$('body').ajaxStop(function(){
		$.unblockUI();
		showOrder();
	});
}
function setAjaxEvent2() {
	$('body').ajaxStart(function(){
		$.blockUI({
			message: '<p>処理中・・・</p>'
		});
	});
	$('body').ajaxStop(function(){
		$.unblockUI();
	});
}
/*function endAjax() {
	$.unblockUI();
	showOrder();

}*/

function showOrder() {
	var ttr = $('tr','#mlist');
	if (ttr.length >= 1) {
		// SEOランク14以上のkwがあるときは、定額制はdisenable
		teigaku = false;
		for(i = 1;i < ttr.length; i++) {
			var sr = $('._sr',ttr[i]).text();
			//alert(sr.slice(0, SRM.length - 1));
			if (sr.indexOf(SRM) < 0) continue;
			if (sr.slice(0, SRM.length - 1) >= 14) {
				teigaku = true;
				break;
			}
		}
		$('.teigaku').attr("disabled", teigaku);
		$('#morder').show();
	}
	else $('#morder').hide();
}

function getResultStr(ret) {
	return '<tr><td class="kw">' + ret.keyword + "</td><td>" + ret.needs_rank + "/100<br />" + ret.conflict_rank + "/100</td>" + '<td class="_sr">' + ret.seo_rank + SRM + "</td>";
}

function getButton(fn, disp) {
	// return '<td><button onclick="showSeoRank(\'' + ret.keyword + '\')">' +
	// disp + '</button></td></tr>';
	return '<td><button onclick="' + fn + '(this)">' + disp + '</button></td></tr>';
}

function getButtonWithObj(fn, disp) {
	var orObj = {
		keyword: seo_rank_obj.keyword,
		seo_rank: seo_rank_obj.seo_rank,
		beginning_cost: cost_obj.beginning_cost,
		g1_cost: cost_obj.google_ranked_cost[0],
		g20_cost: cost_obj.google_ranked_cost[ret.google_ranked_num -　1],
		y1_cost: cost_obj.yahoo_ranked_cost[0],
		y20_cost: cost_obj.yahoo_ranked_cost[ret.yahoo_ranked_num -　1]
	};

	return '<td><button onclick="' + fn + '(this)">' + disp + '</button>' +
	'<p class="_nd">' + $.toJSON(orObj) + '</p></td></tr>';
}

/**
 * Comment
 */
function getMonthly(seo_rank) {
	if (seo_rank >= 1 && seo_rank <= 6) {
		return 7800;
	} else if (seo_rank >= 7 && seo_rank <= 11) {
		return 10800;
	} else if (seo_rank == 12 || seo_rank == 13) {
		return 15800;
	} else {
		return "---";
	}
}

function showCost(seo_rank){
	setAjaxEvent();
	var url = ABACUS_URL + "seo_rank=" + seo_rank + "&callback=?";
	$.getJSON(url, function(res){	// only jquery
		ret = cost_obj = res.result;
		mlist += "<td>" +  ret.beginning_cost + " 円</td><td>" + getMonthly(seo_rank) + " 円</td><td>";
		// alert(mlist);
		cost = "";
		//if (ret.term == 1) cost += "(日別)";
		//else if (ret.term == 2) cost += "(月別)";
		//cost += "<br />";
		if (ret.reason == 1) {
			if (ret.google_ranked_cost != undefined) {
				cost += "Google<br />&nbsp;&nbsp;&nbsp;1位:" + ret.google_ranked_cost[0]+"円<br />&nbsp;&nbsp;&nbsp;" +
				ret.google_ranked_num + "位:" + ret.google_ranked_cost[ret.google_ranked_num -　1]　+　"円 ";
				cost += "<br />";
			}
			if (ret.yahoo_ranked_cost != undefined) {
				cost += "Yahoo<br />&nbsp;&nbsp;&nbsp;1位:" + ret.yahoo_ranked_cost[0]+"円<br />&nbsp;&nbsp;&nbsp;" +
				ret.yahoo_ranked_num + "位:" + ret.yahoo_ranked_cost[ret.yahoo_ranked_num -　1]　+　"円 ";
				cost += "<br />";
			}
		}
		mlist += cost + "</td>" + getButtonWithObj("del_item","削除");
		$('#mlist').append(mlist);
	});
}
function showAssocKw(kw){
	setAjaxEvent2();
	var url = ASSOC_KW_URL + "keyword=" + kw + "&callback=?";
	$('#assoc').empty();
	$.getJSON(url, function(res) {
		if(res.status >= 2) {
			CNT = 1;
			if (local) max = 35;
			else max = 15;
			$.each(res.result, function(key, val) {
				if (CNT >= res.result.length - 1 || CNT >= max) {
					return false;
				}
				CNT++;
 				setAjaxEvent2();
 				kw_enc = encodeURIComponent(val);
				var url1 = SEO_RANK_URL + "keyword=" + kw_enc + "&callback=?";
				$.getJSON(url1, function(res){
					if(res.status >= 1){
						ret = res.result;
						hl = getResultStr(ret) + getButton("add_kw", "追加");
						$('#assoc').append(hl);
					}
				});
			});
		}
	});
}

function showKwHist(kw){
	setAjaxEvent2();
	var url = KW_HIST_URL + "keyword=" + kw + "&callback=?";
	$('#hlist').empty();
	$.getJSON(url, function(res){
		if(res.status >= 2){
			$.each(res.result, function(key, val) {
				hl = getResultStr(val) + getButton("add_kw", "追加");
				$('#hlist').append(hl);
			});
		}
	});
}

// order
function wopen(mem, type) {
	var items = $('#mlist').children('tr');
	if (items.length <= 0) return false;

	ourl = LOCAL ? "http://localhost/seo-agent/order/" : ORDER_URL;
	ourl += ORDER_FILE[mem];
	//ourl += "test.php"
	ourl += "?" + ITEM_NAME[type];

	for (i = 0; i < items.length; i++) {
		ival = encodeURIComponent(items.eq(i).find('._nd').text());
		$('#fmtemp').append($('<input type="hide" value="' + ival + '" name=order' + i + ' />')); //注：input tagにはIEの制限がある
		//$('#fmtemp').append($('<input type="hide" />').val(ival).attr("name", "itemtemp" + i)); //value設定できない?
	}
	$('#fmtemp').attr("target","_blank").attr("action", ourl);
	$('#fmtemp').submit();

	$('#fmtemp').children().remove();
  return false;
}

/**
 * チェック対象文字列のバイト数を取得
 *
 * @param argValue チェック対象文字列
 * @return 文字列のバイト数

HALF_SIZE_KANA = "ｧｱｨｲｩｳｪｴｫｵｶｷｸｹｺｻｼｽｾｿﾀﾁｯﾂﾃﾄﾅﾆﾇﾈﾉﾊﾋﾌﾍﾎﾏﾐﾑﾒﾓｬﾔｭﾕｮﾖﾗﾘﾙﾚﾛﾜｦﾝｰﾟﾞ";
function getByteLength(argValue) {
	var i = 0;
	var count = 0;
	for (i = 0; i < argValue.length; i++) {
		if (0 <= HALF_SIZE_KANA.indexOf(argValue.charAt(i))) {
			// 半角カタカナの場合は1バイトとして計算します
			count++;
		} else if (escape(argValue.charAt(i)).length >= 4) {
			count+=2;
		} else {
			count++;
		}
	}
	return count;
}*/
function mb_length(str) {
	var r = 0;
	for (var i = 0; i < str.length; i++) {
		var c = str.charCodeAt(i);
		// Shift_JIS: 0x0 ～ 0x80, 0xa0 , 0xa1 ～ 0xdf , 0xfd ～ 0xff
		// Unicode : 0x0 ～ 0x80, 0xf8f0, 0xff61 ～ 0xff9f, 0xf8f1 ～ 0xf8f3
		if ( (c >= 0x0 && c < 0x81) || (c == 0xf8f0) || (c >= 0xff61 && c < 0xffa0) || (c >= 0xf8f1 && c < 0xf8f4)) {
			r += 1;
		} else {
			r += 2;
		}
	}
	return r;
}

