eWarrant.prototype.extend({
	initialize:function(options){
		this.extend(options);
		this.recperpage = 100;
		this.ds = {};
		if(!this.data.mode)
			this.data.mode = this.query.prdPricingModel?this.query.prdPricingModel[0].value:this.defaultMode||"OPT";
		if(!this.query.prdPricingModel)
			this.query.prdPricingModel = this.data.mode.split("_")[0];
		if(this.query.undQuickCode)
			this.data.underlyer = this.query.undQuickCode[0].value;
		if(this.query.prdPutCall)
			this.data.putcall={C:1,P:2}[this.query.prdPutCall[0].value];
		this.ctrls = {};
		var ew = this;
		this.searchForm.find(".mode").click(function(){
			var elm = $(this);
			var mode = elm.attr("title");
			if(ew.query.prdPricingModel&&elm.hasClass("selected")) return;
			elm.addClass("selected").siblings().removeClass("selected");
			var model = mode.split("_")[0];
			for(var name in ew.ctrls)
				ew.ctrls[name].val("");
			ew.ctrls["q.prdPricingModel"].val(model);
			if(ew.ctrls.mode){
				ew.ctrls.mode.val(mode);
				ew.searchForm.find(":submit").click();
			}else{
				ew.ds.catitems = ew.ds[model].items;
				ew.setCombo(ew.ctrls.category,"");
			}
		}).filter("[title="+this.data.mode+"]").addClass("selected");
		this.template = $("#"+ew.data.mode).clone();
		this.template.children().each(function(){
			var elm = $(this);
			$("#"+elm.attr("class")).html(elm);
		});
		this.grid = $("#grid table.grid");
		this.subgrid = $("#subgrid table.subgrid");
		this.option = $("#option .option");
		this.searchForm.find("input[name],select[name]").each(function(){
			var elm = $(this);
			var name = elm.attr("name");
			var key = name.replace("q\.","");
			ew.ctrls[name] = elm;
			elm.val(ew.query[key]?(ew.query[key] instanceof Array?ew.query[key][0].value:ew.query[key]):ew.data[name]||elm.val());
		});
		this.option.find(">div").each(function(){
			var elm = $(this);
			elm.find("span:eq("+(ew.data[elm.attr("class")]||0)+")").addClass("on").siblings().removeClass("on");
		});
		this.option.find("span").click(function(){
			var elm = $(this);
			elm.addClass("on").siblings().removeClass("on");
			(function(name,index){
				return {
					putcall:function(index){
						ew.data.putcall = index;
						ew.query.prdPutCall = [{oper:"=", value:["","C","P"][index]}];
					},
					period:function(index){
						ew.data.period = index;
						ew.query.expiry = [];
						var today = new Date();
						var year = today.getFullYear();
						var month = today.getMonth();
						var date = today.getDate();
						var period = [{},{to:1},{from:1,to:3},{from:3,to:6},{from:6}][index];
						for(var key in period)
							ew.query.expiry.push({oper:{from:">=", to:"<"}[key],value:ew.formatter.date2str1(new Date(year,month+period[key],date))});
					}
				}[name](index);
			})(elm.parent().attr("class"),elm.index());
			ew.search(1);
		});
		this.grid.find("th[title]").click(function(){
			var elm = $(this);
			ew.data.k = elm.attr("title");
			ew.data.s = Number(elm.hasClass("descending"));
			ew.search(1);
		});
		var now = new Date();
		this.doSearch = true;
		if(this.data.mode&&this.data.mode.indexOf("LIST")+1){
			this.data.f = "id,currencyEncoded,prdPutCall,undName,undQuickCode,series,prdStrike,expiry,crbAsk,crbBid,bidMoveRate,prdStatus,effectiveGearing,priceSprd,effectivePriceSprd,option,optionMoveRate,histUndLevel,undLevelMoveRate,prdPricingModel";
			this.data.k = "optionMoveRate";
			this.data.s = 1;
			this.ctrls.underlyer.find("option:first").text("---選択してください---");
			this.searchForm.find(":submit").val("この条件で試算");
			var simparams = {
				offset:this.vopts.unsigned,
				und:this.vopts.positive,
				fx:this.vopts.positive
			};
			this.searchForm.find("input[type=text]").each(function (i,elm){ 
				ew.validator(elm,simparams);
			}).filter("[name=offset]").change(function(){
				var elm = $(this);
				var fordate = new Date(now.getFullYear(),now.getMonth(),now.getDate()+Number(elm.val()));
				ew.query.expiry = [{oper:">=",value:ew.formatter.date2str1(fordate)}];
				ew.searchForm.find(".fordate").text(ew.formatter.date2str3(fordate));
			}).change();
			this.doSearch &= Boolean(this.query.undQuickCode && this.query.undQuickCode[0].value);
			for(var name in simparams){
				if(!(this.doSearch &= Boolean(this.data[name]&&this.data[name].match(simparams[name].exp))))
					break;
			}
			var fxctrl = this.searchForm.find("#fxctrl");
			var divctrl = this.searchForm.find("#divctrl");
			this.ctrls.underlyer.change(function(){
				var elm = $(this);
				fxctrl.hide();
				divctrl.hide();
				if(elm.val()){
					var unditem = ew.ds.unditems[elm.val()];
					if(!ew.query.undQuickCode || ew.query.undQuickCode[0].value!=elm.val()){
						ew.query.undQuickCode = [{value:elm.val()}];	
						ew.data.und = unditem.undLevel||0;
						ew.data.fx = 1;
					}
					ew.ctrls.und.val(ew.data.und);
					ew.ctrls.fx.val(ew.data.fx);
					if(unditem.undCurrency!="JPY")
						fxctrl.show();
					if(!Number(unditem.isFuture)){
						divctrl.show();
					}
				}
			});
		}
	},
	search:function(page){
		if(!this.doSearch) return;
		this.data.page = page || this.data.page;
		var from = (this.data.page-1)*this.recperpage;
		this.data.n = (from+1)+"-"+(from+this.recperpage);
		this.data.q = "";
		for(var key in this.query){
			if(this.query[key] instanceof Array){
				for(var i=0; i<this.query[key].length;i++)
					if(this.query[key][i].value != ""){
						if(this.data.q)
							this.data.q += ",";
						this.data.q += key+this.query[key][i].oper+this.query[key][i].value;
					}
			}else{
				if(this.data.q)
					this.data.q += ",";
				this.data.q += key+"="+this.query[key];
			}
		}
		$("#contents").activity();
		var ew = this;
		$.ajax({
			url:"/apps/InformationService",
			data:this.data,
			dataType:"json",
			cache: false,
			success:function(res,textStatus,XMLHttpRequest){
				ew.timestamp = new Date(XMLHttpRequest.getAllResponseHeaders().match("Date: (.*)")[1]);
				$("#grid tr:gt(1),#subgrid tr:gt(0),.pager>*").remove();
				var th = ew.grid.find("th[title="+ew.data.k+"]");
				th.toggleClass("descending");
				th.addClass("sorted").siblings().removeClass("sorted");
				th.parent().next().find("td:eq("+th.index()+")").html("<span style='display:inline-block;background:url(/images/common.png) -180px -"+((ew.data.s?0:1)*15)+"px;height:13px;width:35px;'></span>")
					.addClass("sorted").siblings().empty().removeClass("sorted");
				var ids = res.data.ids;
				var recs = res.data.recs;
				var tr = ew.grid.find("tr:eq(1)");
				var rate = {min:0,max:0};
				var scale;
				if(ew.data.mode.indexOf("LIST")+1){
					for(var key in recs){
						if(!rate.min||rate.min>recs[key].optionMoveRate) rate.min = recs[key].optionMoveRate;
						if(rate.max<recs[key].optionMoveRate) rate.max = recs[key].optionMoveRate;
					}
					scale = ew.grid.find("th[title=optionMoveRate]").width()/(rate.max-Math.min(0,rate.min));
				}
				var undhash = {};
				for(var i=0;i<ids.length;i++){
					var rec = recs[res.data.ids[i]];
					var row = tr.clone();
					if($("#subgrid .subgrid").length && !undhash[rec.undQuickCode] && rec.undLevelMoveRate){
						undhash[rec.undQuickCode] = 1;
						ew.subgrid.append("<tr><td>"+rec.undName+"</td><td>"+(ew.formatter.decimal(rec,"histUndLevel")||"-")+"</td><td>"+(ew.formatter.percentage(rec,"undLevelMoveRate")||"-")+"</td></tr>");
					}
					rec.priceSprdRate = rec.priceSprdRate*100; 
					rec.effectivePriceSprd = rec.effectivePriceSprd*100;
					row.find("td").each(function(){
						var elm = $(this);
						var key = elm.attr("title");
						var text = ew.format(elm,rec,key);
						if(key=="optionMoveRate"){
							text = ew.formatter.percentage(rec.optionMoveRate)+"<div align=left style='height:10px'><span style='postion:static;display:inline-block;height:100%;background:"
								+(rec.optionMoveRate>0?"red":"blue")+";width:"+(Math.abs(rec.optionMoveRate)*scale)
								+"px;margin-left:"+((rec.optionMoveRate>0?-Math.min(0,rate.min):rec.optionMoveRate-rate.min)*scale)+"px'></span></div>";
						}
						elm.html(text||rec[key]||"-");
					});
					ew.grid.append(row);
				}
				$("#msg-norecord").css("display",ids.length?"none":"block");
				if(res.metadata.count>ew.recperpage)
					ew.createPager($(".pager"),Math.ceil(res.metadata.count/ew.recperpage));
				$("#rescount").text(res.metadata.count);
				$("#dspcount").text(ids.length);
				$("#contents").activity(false);
			}
		});
	},
	createPager:function(elm,lastIndex){
		if (this.data.page > 1) elm.append(this.getPager(this.data.page-1,'&lArr;'));
		for (var i=1; i<=lastIndex; i++) elm.append(this.getPager(i,i));
		if (this.data.page < lastIndex) elm.append(this.getPager(this.data.page+1,'&rArr;'));	
	},
	getPager:function(num,text){
		var a = $(document.createElement("a"));
		a.html(text);
		var ew = this;
		if(num === this.data.page)
			a.css("color","red");
		else
			a.click(function(){ew.search(num);});
		return a;
	},
	setSearchForm:function(async){
		var ew = this;
		$.ajax({
			url:"/apps/InformationService",
			data:{f:"type,undQuickCode,sectorCode,category,undName,pinFlag,undCurrency,isFuture,prdPricingModel,kanaNameEncoded,expiry,undLevel,series,crbBid,crbAsk,prdStrike,vol,volUpperStrike,volLowerStrike,prdContractSize,npStrikeRange,undCurrency,prdPutCall,webNameEncoded3"},
			dataType:"json",
			cache: false,
			async: async==null?true:async,
			success:function(res){
				ew.ds.recs = res.data.recs;
				var order = ["FRX","IDX","FSS","BSK","CMD","JSS"];
				var types = {};
				for(var index in order)
					types[order[index]] = index;
				for(var id in ew.ds.recs){
					var rec = ew.ds.recs[id];
					var mod = rec.prdPricingModel;
					var catname = "";
					var label = "";
					var cat = rec.type;
					var und = rec.undQuickCode;
					var sec = rec.sectorCode;
					if(rec.type === "JSS"){
						cat += sec;
						catname += "国内:";
						label += und+":";
					}
					if(!types[rec.type])types[rec.type]=1;
					catname += rec.category;
					if(!ew.ds[mod])
						ew.ds[mod] = {items:{}};
					if(!ew.ds[mod].items[cat])
						ew.ds[mod].items[cat] = {
							items:{},
							label:catname,
							sectorCode:rec.type=="CMD"?"":rec.sectorCode,
							type:rec.type,
							key:types[rec.type]+rec.sectorCode,
							value:cat
						};
					if(!ew.ds[mod].items[cat].items[und]){
						rec.label = label+rec.undName;
						rec.key = types[rec.type]+rec.undQuickCode+rec.kanaNameEncoded;
						rec.value = rec.undQuickCode;
						ew.ds[mod].items[cat].items[und] = rec;
					}
					if(rec.type=="JSS"){
						if(!ew.ds[mod].items["JSS"])
							ew.ds[mod].items["JSS"] = {
								items:{},
								label:"国内:全業種",
								type:rec.type,
								key:types[rec.type],
								value:rec.type
							};
						if(!ew.ds[mod].items["JSS"].items[und]){
							rec.label = label+rec.undName;
							rec.key = types[rec.type]+rec.undQuickCode+rec.kanaNameEncoded;
							rec.value = rec.undQuickCode;
							ew.ds[mod].items["JSS"].items[und] = rec;
						}
					}
				}
				ew.ds.catitems = ew.ds[ew.data.mode.split("_")[0]].items;
				function getUnditems(){
					var unditems = {};
					for(var key1 in ew.ds.catitems)
						for(var key2 in ew.ds.catitems[key1].items)
							unditems[key2] = ew.ds.catitems[key1].items[key2];
					return unditems;
				};
				ew.ds.unditems = getUnditems();
				ew.ctrls.category.change(function(){
					ew.data.category = $(this).val();
					ew.setCombo(ew.ctrls.underlyer,ew.data.underlyer,ew.data.category?ew.ds.catitems[ew.data.category].items:getUnditems());
					ew.ctrls["q.sectorCode"].val(ew.data.category?ew.ds.catitems[ew.data.category].sectorCode:"");
					ew.ctrls["q.type"].val(ew.data.category?ew.ds.catitems[ew.data.category].type:"");
				});			
				ew.ctrls.underlyer.change(function(){
					ew.data.underlyer = $(this).val();
					ew.ctrls["q.undQuickCode"].val(ew.data.underlyer);
				});
				ew.setCombo(ew.ctrls.category,ew.data.category);
			}
		});
	},
	setCombo:function(combo,selected,optItems){
		var items = optItems||this.ds.catitems;
		var arr = [];
		for(var key in items)
			arr.push(items[key]);
		arr.sort(function (a, b){return a.key>b.key?1:-1;});
		combo.find("option:gt(0)").remove();
		for(var i=0;i<arr.length;i++)
			combo.append("<option value='"+arr[i].value+"'>"+arr[i].label+"</option>");
		setTimeout(function(){combo.val(selected).change();},0);  //FIXME: walkaround for IE6's Unspecified error.  
	}
});

