var crw_targetClass="coneco_ranking_widget";
var crw_replaceClass="crw_replaced_widget";
var crw_apikey="b9b8b855c554442c60514b07eadab62b";
var crw_url_top = "http://api.coneco.net/";
var crw_cateApiUrl = crw_url_top + "cws/v1/SearchCategories_json";
var crw_img_dir = "http://www.coneco.net/widget/image/";

function crw_requestJsonpAPI(url,id){
	var objScript = document.createElement("script");
	objScript.setAttribute("type", "text/javascript");
	objScript.setAttribute("charset", "utf-8");
	objScript.setAttribute("src", url);
	objScript.setAttribute("id", id);
	document.getElementsByTagName("head").item(0).appendChild(objScript);
}

var crw_ComRequest = function(hash,boxId){
	this.apiUrl = crw_url_top + "cws/v1/SearchProducts_json";
	this.priceListUrl = "http://www.coneco.net/PriceList.asp";
	this.topUrl = "http://www.coneco.net/";
	this.clubImgDir = "http://www.coneco.net/images/club/";
	this.imgDir = crw_img_dir;
	this.apiKey = crw_apikey;
	this.partsWidth = hash["width"] || 160;
	this.cate8RankUrl = "http://www.coneco.net/masterranking/";
	this.widgetUrl = "http://www.coneco.net/widget/";

	this.catid = hash["category_id"];
	this.templateType = hash["template"] || 0;
	this.boxId = boxId;
	this.count = 3;
	this.nameMaxLen = 50;
	this.descMaxLen = 40;
	this.tmplSep = '<hr align="center" style="clear:left;width:130px;margin:4px 10px;" noshade color="#CCC">';
	if(String(hash["count"]).replace(/\d/g,"")=="" && hash["count"] > 0){
		this.count = hash["count"];
		if(this.count > 20){
			this.count = 20;
		}
	}
	if(this.templateType > 0){
		eval("crw_setTemplate"+this.templateType)(this);
	}
	this.tmplAll = this.frameTemplate();

	var err = "";
	err += '<div style="width:' + this.partsWidth + 'px; height:30px;">';
	err += '<img src="' + this.imgDir + 'error.png" border="0" alt="表示する情報が見つかりません。レビューが存在しないか、ブログパーツの設定に誤りがあります。" style="height:30px;width:' + this.partsWidth + 'px" />';
	err += '</div>\n';

	this.tmplErr = err;
}

crw_ComRequest.prototype.getItems = function(catId){
	var div = document.getElementById(this.boxId+'_list')
	div.innerHTML = "<div style='text-align:center;'><img src='"+this.imgDir+"loading.gif'></div>";

	var url = this.apiUrl+"?apikey="+this.apiKey+"&sort=ranking&available=1&count="+this.count;
	if(String(catId) != "undefined"){
		url+="&categoryId="+catId;
	}
	url += "&callback=crw_objCategory['"+this.boxId+"'].showItems";
	crw_requestJsonpAPI(url,"crwjs_catid_"+catId);
}
crw_ComRequest.prototype.showCategoryList = function(json){
	var box = document.getElementById(this.boxId);
	if(!box){
		return;
	}
	var listBox = document.getElementById(this.boxId+"_list");
	var err = false;
	if(json.Header.Count > 0 && json.Current){
		this.tmplAll = this.tmplAll.replace(/%category_name%/g,json.Current.Name);
		this.tmplAll = this.tmplAll.replace(/%category_id%/g,json.Current.Id);
		this.tmplAll = this.tmplAll.replace("%error%","");
	} else if(json.Header.Status != "Success"){
		this.tmplAll = this.tmplAll.replace(/%error%/g,this.tmplErr);
		err = true;
	} else if(json.Category.length <= 0){
		this.tmplAll = this.tmplAll.replace(/%error%/g,this.tmplErr);
		err = true;
	} else {
		this.tmplAll = this.tmplAll.replace(/%error%/g,this.tmplErr);
		err = true;
	}
	document.getElementById(this.boxId).innerHTML = this.tmplAll;
	this.select = document.getElementById(this.boxId).getElementsByTagName("SELECT")[0];

	if(err){
		document.getElementById(this.boxId+"_catebox").style.display = "none";
		return;
	}

	var sele = this.select;
	var len = json.Category.length;
	sele.style.display = "inline";
	sele.options.length = len+1;

	var opt = sele.options[0];
	opt.value = "0";
	opt.innerHTML = "coneco.net 全体";
	var optFontSize = "8px";
	var intSt = 1;
	if(json.Current.Id == "0"){
		optFontSize = "12px";
		opt.selected = true;
	} else {
		var opt = sele.options[1];
		opt.value = json.Current.Id;
		opt.innerHTML = "└ " + json.Current.Name + " 全体";
		opt.selected = true;
		intSt = 2;
		sele.options.length = len+intSt;
	}
	opt.style.fontSize = optFontSize;
	for(var i=0;i<len;i++){
		var opt = sele.options[i+intSt];
//console.log((i+intSt)+":"+opt);
//		if(json.Category[i].Id == this.catid){
//			opt.selected = true;
//		}
		opt.value = json.Category[i].Id;
		opt.innerHTML = (((len-1)==i)?"　└":"　├")+" "+json.Category[i].Name;
		opt.style.fontSize = optFontSize;
	}
	sele.style.fontSize = optFontSize;

	this.getItems(this.catid);
}

crw_ComRequest.prototype.showItems = function(json){
	var listBox = document.getElementById(this.boxId+"_list");
	var strReadMoreUrl = "";
	if(json.Header.Condition.Category.Id.length >= 7){
		strReadMoreUrl = this.cate8RankUrl + ((json.Header.Condition.Category.Id.length==7)?'0':'')+json.Header.Condition.Category.Id + ".html";
	}

	this.CurrentCategoryId = json.Header.Condition.Category.Id;

	var tmplItem = this.itemTemplate();

	var arrItems = new Array();
x=json;
	var len = json.Item.length;
	for(var i=0;i<len;i++){
		arrItems.push(this.showItem(json.Item[i],tmplItem,i));
	}
	if(strReadMoreUrl != ""){
		arrItems.push("<p style='text-align:right;font-size:11px;margin:4px 0 0;'><a href='"+strReadMoreUrl+"' target='_blank'>ランキングの続きを見る</a></p>");
	} else {
		arrItems.push("<p style='text-align:right;font-size:11px;margin:4px 0 0;'><a href='"+json.Header.Condition.Category.Url+"' target='_blank'>このカテゴリを見る</a></p>");
	}
//alert(box.id);
	listBox.innerHTML = arrItems.join(this.tmplSep);

}
crw_ComRequest.prototype.showItem = function(item,tmplItem,idx){
	var strItem = tmplItem;
	if(item.Category){
		strItem = strItem.replace(/%category_name%/g,item.Category.Name);
		strItem = strItem.replace(/%category_id%/g,item.Category.Id);
	}
	strItem = strItem.replace("%com_id%",item.ComId);
	var strName = item.Name;
	if(strName.length>this.nameMaxLen){
		strName = strName.substr(0,this.nameMaxLen)+"...";
	}
	strItem = strItem.replace("%com_name%",strName);
	var strImgUrl = item.SmallImageUrl;
	var strImgStyle = "display:none;";
	if(strImgUrl.indexOf("noimg") == -1){
		strImgStyle = "display:inline;";
	}
	strItem = strItem.replace("%s_img_url%",strImgUrl);
	strItem = strItem.replace("%s_img_style%",strImgStyle);
	var strPriceStyle = "display:none;";
	var strPrice = String(item.LowestPrice);
	if(item.LowestPrice > 0){
		strPriceStyle = "display:block;";
		while(strPrice != (strPrice = strPrice.replace(/^(-?\d+)(\d{3})/, "$1,$2")));
	}
	var strRevUrl = item.Review.ReviewListUrl || "http://www.coneco.net/Pricelist.asp?COM_ID=" + item.ComId;
	if(parseInt(item.Review.ReviewCount) > 0 && String(item.Review.OverallRating) != "undefined"){
		strItem = strItem.replace(/%rating%/g,item.Review.OverallRating);
		strItem = strItem.replace(/%review_url%/g,strRevUrl);
		strItem = strItem.replace(/%review_count%/g,item.Review.ReviewCount);
	} else {
		strItem = strItem.replace(/%rating%/g,"");
		strItem = strItem.replace(/%review_count%/g,"0");
		strItem = strItem.replace(/%review_url%/g,strRevUrl);
//		strItem = strItem.replace("%rating_style%","text-decoration:none;vertical-align:top;");
	}
	strItem = strItem.replace("%rating_style%","text-decoration:none;vertical-align:middle;");
	var strDesc = item.Description;
	if(strDesc.length>this.descMaxLen){
		strDesc = item.Description.substr(0,this.descMaxLen) + "...";
	}

	if(idx<3){
		strItem = strItem.replace("%idx%","<img src='"+this.imgDir+"prize"+(idx+1)+".gif' style='vertical-align:middle' height='18' width='18' />");
	} else {
		strItem = strItem.replace("%idx%",(idx+1)+".");
	}
	strItem = strItem.replace(/%rank%/g,item.Ranking);
	strItem = strItem.replace(/%url%/g,item.Url);
	strItem = strItem.replace("%s_img_url%",item.SmallImageUrl);
	strItem = strItem.replace("%img_url%",item.ImageUrl);
	strItem = strItem.replace(/%com_name%/g,item.Name);
	strItem = strItem.replace("%description%",strDesc);
	strItem = strItem.replace("%lowest_price%",strPrice);
	var strMaker = item.Manufacturer;
	if(strMaker.indexOf("/") >= 0){
		strMaker = strMaker.split("/")[0];
	}
	strItem = strItem.replace("%maker%",strMaker);

	return strItem;
}
var crw_objCategory = new Array;
crw_ComRequest.prototype.loadCategory = function(areaId){
	var url = crw_cateApiUrl;
	url += "?categoryId="+this.catid;
	url += "&callback=crw_objCategory['"+areaId+"'].showCategoryList";
	url += "&apikey="+crw_apikey;
	crw_requestJsonpAPI(url,"crwjs_parcatid_"+this.catid);
}

crw_ComRequest.prototype.frameTemplate = function(){
	var tmpl = "";
	tmpl += '<div style="width:' + this.partsWidth + 'px; height:60px;">';
	tmpl += '<a href="' + this.topUrl + '" target="_blank"><img src="' + this.imgDir + 'bp-head.png" border="0" alt="価格比較サイト「coneco.net（コネコネット）」" style="height:60px;width:' + this.partsWidth + 'px" /></a>';
	tmpl += '</div>';

	tmpl += '<div style="width:' + this.partsWidth + 'px; background-image:url(' + this.imgDir + 'bp-middle.png); padding-top:4px; text-align:center;">\n';
	tmpl += '<select onchange="var val=this.options[this.selectedIndex].value;crw_objCategory[\''+this.boxId+'\'].getItems(val);" style="width:' + (this.partsWidth-10) + 'px;font-size:8px;background-color:orange;border:1px solid silver">\n';
	tmpl += '</select>\n';
	tmpl += '<p style="background-image:url('+this.imgDir+'cate_bg.png);background-repeat:repeat-x;width:' + (this.partsWidth-10) + 'px;text-align:center;margin:0px auto;padding:2px 0;font-size:11px;">';
	tmpl += '人気ランキング';
	tmpl += '</p>';
	tmpl += '</div>\n';

	tmpl += '%error%\n';

	tmpl += '<div style="width:' + this.partsWidth + 'px; background-image:url(' + this.imgDir + 'bp-middle.png); padding-top:4px; text-align:center;overflow-x:hidden">\n';
	tmpl += '<div style="width:90%;text-align:left;margin-left:auto;margin-right:auto;padding:3px 0;overflow-x:hidden" id="'+this.boxId+'_items">\n';
	tmpl += '<div id="'+this.boxId+'_list">\n';
	tmpl += '</div>\n';
	tmpl += '<p style="margin:6px 0 0;text-align:center;"><a style="text-decoration:none;font-size:10px;color:#130775" href="http://www.coneco.net/" target="_blank">価格比較サイト「coneco.net」</a></p>\n';
	tmpl += '</div>\n';
	tmpl += '</div>\n';
	tmpl += '<div style="clear:left;width:' + this.partsWidth + 'px; height:30px;"><a href="'+crw_url_top+'" target="_blank"><img src="' + this.imgDir + 'bp-foot30.png" border="0" alt="coneco.net Web Services" style="width:' + this.partsWidth + 'px;height:30px;" /></a></div>\n';
	tmpl += '<div style="text-align:center;font-size:10px;width:' + this.partsWidth + 'px;">\n';
	tmpl += '<a href="'+this.widgetUrl+'" style="text-decoration:none;" target="_blank">ブログパーツに新色登場!</a>\n';
	tmpl += '</div>\n';
	tmpl += '</div>\n';
	return tmpl;
}

crw_ComRequest.prototype.itemTemplate = function(){
	var tmplItem = "<div class='crw_review-item' style='margin:0;width:100%;'>";
	tmplItem += "	<p class='review_title' style='margin:4px 0px 0px ;font-size:12px;'>";
	tmplItem += "	<span title='全商品中 %rank%位'>%idx%</span>&nbsp;<a href='%url%' target='_blank' title='%com_name%' class='no-price'><span style='color:blue;'>%com_name%</span></a><span style='font-size:11px;'> / %maker%</span>";
	tmplItem += "	</p>\n";
	tmplItem += "	<div style='margin:4px 4px 0;'>";
	tmplItem += "		<a href='%url%' target='_blank' title='%com_name%' class='no-price'><img src='%s_img_url%' style='margin:0 0.5em 0 2px;%s_img_style%' align='left' border='0'></a>";
	tmplItem += "		<p style='margin:0;'><a href='%url%' target='_blank' style='text-decoration:none;color:#F00;'><span style='font-size:10px;%buy_price_style%'>最安:</span><span style='font-size:10px;%buy_price_style%'>&yen;%lowest_price%</span></a></p>";
	tmplItem += "		<p style='margin:0;font-size:10px;color:#444;'>%description%</p>";
	tmplItem += "	</div>";
	tmplItem += "	<p style='clear:left;margin:1px 0 0px 4px;font-size:12px;'><a href='%review_url%' target='_blank' style='%rating_style%'>評価:<img src='" + this.clubImgDir + "star_s%rating%.gif' alt='満足度：%rating%' border='0' height='12' />(%review_count%件)</a></p>";
	tmplItem += "</div>\n";
	return tmplItem;
}

function conecoRankingWidget_loadArea(area){
	var tit = area.title;
	area.title = "";

	var hash = new Object;
	var arrParams = tit.split(";");
	for(var i=0;i<arrParams.length;i++){
		var arrParam = arrParams[i].split("=");
		if(arrParam.length==2){
			hash[arrParam[0]] = arrParam[1];
		}
	}
	if(String(hash["category_id"]) == "undefined"){
		hash["category_id"] = "0";
	}
	area.title = "";
	if(!area.id || String(area.id) == "undefined"){
		var baseId = "crw_"+hash["category_id"];
		var idCount = 1;
		var newId = baseId;
		while(crw_objCategory[newId]){
			newId = baseId + "_" + idCount;
			idCount++;
		}
		area.id = newId;
	}
	crw_objCategory[area.id] = new crw_ComRequest(hash,area.id);
	crw_objCategory[area.id].loadCategory(area.id);
}

function generateConecoWidget(){
	var divs = document.getElementsByTagName("DIV");
	var len = divs.length;
	for(var i=0;i<len;i++){
		if(String(divs[i].className+" ").indexOf(crw_targetClass+" ") >= 0){
			if(String(divs[i].className).indexOf(crw_replaceClass)<0){
				conecoRankingWidget_loadArea(divs[i]);
//				divs[i].className += " " + crw_replaceClass;
			}
		}
	}
}


(function(){
	generateConecoWidget();
})();
