$(document).ready(function () {
  cs = new wv(); // color search

  cs.param = {
    results          : 36,
    query            : "255.0.0",
    start            : 1,
    weight           : "0:5:0:0:0:0:100",
    weightNoCategory : "0:100:0:0:0:0:0"
  };

  cs.init = function () {
    var i, selectedColor;
    // 検索モードの指定
    wv.prototype.mode = "color";
       
    // 商品画象表示領域のDOMを作成
    // isのinitで行っている
    cs.createDispSpace();

    //初期の色を取得
    var selectedColor = $("#selectedColor").css( "background-color" ).slice( 4, -1 ).replace( /,/g, ".").replace( / /g, "" );
    cs.param.query = selectedColor;
    
    //hashの値を取得
    var q = window.location.hash.replace("#!", "");
    if (q) {
      var queryStr = q.split("&");
      for (var i = 0; i < queryStr.length; i++) {
        var querys = queryStr[i].split("=");
        if ( querys[0] == "query" ) {
          if ( !querys[1].match(/^[0-9]+\.[0-9]+\.[0-9]+$/) ) {
            return;
          }
        }
      }
      for ( i = 0; i < queryStr.length; i++ ) {
        querys = queryStr[i].split("=");
        if ( querys[0] == "category_id" ) {
          wv.prototype.category_id = querys[1];
        } else if ( querys[0] == "price_from" ) {
          wv.prototype.price.from = querys[1];
        } else if ( querys[0] == "price_to" ) {
          wv.prototype.price.to = querys[1];
        } else {
          cs.param[querys[0]] = querys[1];
        }
      }
    }
   
    sl.selectCategorySearch();
    $("#price_from")[0].value = wv.prototype.price.from;
    $("#price_to")[0].value = wv.prototype.price.to;

    cs.doSearch( this.param.query, "init" );
    $("#selectedColor").css( "background-color", "rgb(" + cs.param.query.replace( /\./g, "," ) + ")");
  };

  cs.doSearch = function ( query, from ) {
    // 検索モードの指定
    wv.prototype.mode = "color";
    this.param.query = query;
    
    //pager 以外から呼ばれたら1から結果を返す
    if ( from != "pager" ) {
      cs.param.start = 1;
    }

    //既存の結果を消す
    $( ".productImg" ).remove();
    $( ".zeromatch" ).remove();
    $( ".serverError" ).remove();

    //loading animation
    clearInterval( wv.prototype.loadingTimer );
    $( "#dispLoadingWrap" ).show();
    wv.prototype.loadingTimer = setInterval( wv.prototype.doLoading, 66 );

    //APIを叩く
    cs.getXML();
    sl.selectColorQuery();
    sl.selectPager( cs.param.start );

    if ( from == "colorPicker" || from == "colorPallet" || from == "init") {
      hs.setImageList( { id : this.param.query } );
    }
    cs.setHash();
  };

  cs.setHash = function () {
    //urlの#以降にparamを追加
    location.hash = "!query=" + cs.param.query + "&category_id=" + wv.prototype.category_id + "&start=" + cs.param.start;
    if ( wv.prototype.price.from.length != 0 ) {
      location.hash += '&price_from=' + wv.prototype.price.from;
    }
    if ( wv.prototype.price.to.length != 0 ) {
      location.hash += '&price_to=' + wv.prototype.price.to;
    }
  }

  cs.getXML = function () {
    // カテゴリIDの指定がない場合はweigthを切り替える
    var queryWeight = (wv.prototype.category_id) ? this.param.weight : this.param.weightNoCategory ;

    var myObj = this, w = wv.prototype;
    var req_data = 'query=' + this.param.query + ':100&subquery=' + wv.prototype.category_id + '&weight=' + queryWeight + '&start=' + this.param.start + '&results=' + ( this.param.start + this.param.results - 1 );
    if ( wv.prototype.price.from.length != 0 ) {
      req_data += '&price_from=' + wv.prototype.price.from;
    }
    if ( wv.prototype.price.to.length != 0 ) {
      req_data += '&price_to=' + wv.prototype.price.to;
    }
    $.ajax({
      url      : '../fn/getColorSearchResult.php',
      data     : req_data,
      dataType : 'xml',
      cache    : false,
      success  : function ( obj ) {
                   var res, thubUrls=[], imgUrls=[], ids=[], tags=[], extid=[], clickUrl=[], Titles=[], Prices=[],
                       i, l, thub, imgData=[], isError = false;
                   res = obj.getElementsByTagName("Result");
                   for (i = 0,l = res.length; i < l; i++) {
                     thub        = res[i].getElementsByTagName("Thumbnail");
                     thubUrls[i] = w.getTextContents(thub[0].getElementsByTagName("Url")[0]);
                     imgUrls[i]  = w.getTextContents(res[i].getElementsByTagName("Url")[0]);
                     ids[i]      = w.getTextContents(res[i].getElementsByTagName("Id")[0]);
                     tags[i]     = w.getTextContents(res[i].getElementsByTagName("Tags")[0]);
                     extid[i]    = w.getTextContents(res[i].getElementsByTagName("ExtId")[0]);
                     clickUrl[i] = w.addRedirectURL(w.getTextContents(res[i].getElementsByTagName("ClickUrl")[0])); // 先頭にリダイレクトURLを付加
                     Titles[i]   = w.getTextContents(res[i].getElementsByTagName("Title")[0]);
                     Prices[i]   = w.getTextContents(res[i].getElementsByTagName("Price")[0]);
                     imgData[i]  = {
                                    thub : thubUrls[i].replace("/c/","/g/"),
                                    imgUrl : imgUrls[i],
                                    id : ids[i],
                                    tag : tags[i],
                                    extid : extid[i],
                                    clickUrl : clickUrl[i],
                                    title : Titles[i],
                                    price : Prices[i]
                                   };
                   } 

                   // サーバーの負荷判定
                   if ( imgData.length == 0 && obj.getElementsByTagName("Error")[0] ) {
                        isError = true;
                   }

                   myObj.createDom( imgData, isError );
                   ei.setDataSet( imgData );
                 }
    }); 
  };

  cs.init();

});

