/**
 * 商品検索パーツ
 * @param container
 * @returns {ItemSearchParts}
 */
function ItemSearchParts(container) {
	this.container = container;
	this.base   = jQuery("div.search>p", container);
	this.label  = jQuery("label", this.base);
	this.input  = jQuery("input.q", this.base);
	this.button = jQuery("span.btn", this.base);
}
/**
 * ラベル、入力欄とボタンを親ブロックの幅に応じて
 * 並べ替えます。
 */
ItemSearchParts.prototype.rearrange = function () {
	// 321px以上は今まで通り
	if (this.container.width() > 320) {
		return this;
	}
	this.container.css("position", "relative");
	this.base.append(this.label);
	this.button.css({"position":"absolute","right":"10px","top":"0"});
	this.base.append(this.button);
	this.input.css({"margin":"4px 0 14px"});
	var pad = parseInt(this.base.css("padding-right"));
	var inputWidth = this.container.width() - pad * 2;
	// 元の入力欄との幅の違いが大きくなるため180px以下に抑制
	if (inputWidth > 180) {
		margin = inputWidth - 180;
		inputWidth = 180;
		this.input.css("margin-left", (margin/2) + "px");
	}
	this.input.outerWidth(inputWidth);
	this.base.append("<br/>");
	this.base.append(this.input);
	// clearfix
//	this.container.parent().after(jQuery(document.createElement('div')).css({
//		'clear':'both','height':'0','margin':'0','padding':'0'}));
//	this.container.parent().height(76);// 対IE8互換モード

    var parent = this.container.parent();
    $(document).ready(function(){

        parent.after(jQuery(document.createElement('div')).css({
            'clear':'both',
            'height':'0',
            'margin':'0',
            'padding':'0'
        }));
        parent.height(76);// 対IE8互換モード

    });

	return this;
};

(function(){
    var container = $("script:last").parents("div:first");
    var strId     = "goodsSearch" + $("div").index(container);
    var strHref   = "javascript:app_searchGoods('"+ strId + "');";
    $(container).attr("id", strId);
    $("a", container).attr("href", strHref);
//console.log(container);
	new ItemSearchParts(container).rearrange();
})();

function app_searchGoods(objId) {
    var container = $("#" + objId);
    var value = $("input", container).val();
    // サーバ側で2回デコードが行われるため、2回エンコードする。
    value = encodeURIComponent(encodeURIComponent(toTrim(value)));
    var url = getOriginalHost() + "/search/" + value + "/";
    window.location.replace(url)
}

$("input").keypress(
    function(e){
        var divid = $(e.target).closest("form").closest("div").attr("id");
        if(e.keyCode == 13){
            app_searchGoods(divid);
            return false;
        }
    }
);


