$(document).ready(function () {
  is = new wv(); // image search

  is.param = {
    results          : 36,
    query            : 0,
    start            : 1,
    weight           : "0:50:50:100:100:0:100",
    weightNoCategory : "0:50:50:100:100:0:0"
  };

  is.init = function () {
    var i;
    // 検索モードの指定
    //wv.prototype.mode = "similar";
       
    // 商品画象表示領域のDOMを作成
    //is.createDispSpace();

    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 {
          is.param[querys[0]] = querys[1];
        }
      }
      $("#price_from")[0].value = wv.prototype.price.from;
      $("#price_to")[0].value = wv.prototype.price.to;
      is.doSearch( this.param.query, "init" );
    }
  };

  is.doSearch = function ( query, from ) {
    // 検索モードの指定
    wv.prototype.mode = "similar";
    this.param.query = query;
    
    //pager 以外から呼ばれたら1から結果を返す
    if ( from != "pager" ) {
      is.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を叩く
    is.getXML();
    sl.selectImageQuery();
    sl.selectPager( is.param.start );
    
    //初期化の場合
    //結果を1つにしてAPIを叩き左上に画像を表示する
    //ただし、必ずしもAPIを叩いたIDが1番目の結果になるとは限らない
    if ( from == "init" ) {
      is.setQuery();
    }
    is.setHash();
  };

  is.setHash = function () {
    //urlの#以降にparamを追加
    location.hash = "!query=" + is.param.query + "&category_id=" + wv.prototype.category_id + "&start=" + is.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;
    }
  }

  is.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 + '&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/getImageSearchResult.php',
      data     : req_data,
      dataType : 'xml',
      cache    : false,
      success  : function ( obj ) {
                   var res, thubUrls=[], imgUrls=[], ids=[], tags=[], extid=[], clickUrl=[], Titles=[], Prices=[], isError = false, 
                       i, l, thub, imgData=[];
                   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 );
                 }
    }); 
  };
  
  //初期化時のみ呼ばれる(最初にURLにqueryがついていた場合のみ)
  is.setQuery = function () {
    var query = this.param.query, w = wv.prototype, data;
    if ( query == 0 ) {
      data = { id : 0,  thub : "./images/random.png", tag : "", imgUrl : "", clickUrl : "" };
      //左上にクエリ画像表示
      is.setQueryImage( data );
      //検索履歴に画像表示
      hs.setImageList( data );
    } else {
      $.ajax({
        url      : '../fn/getImageSearchResult.php',
        data     : 'query=' + this.param.query + '&subquery=' + wv.prototype.category_id + '&weight=' + this.param.weight + '&start=' + this.param.start + '&results=1',
        dataType : 'xml',
        cache    : false,
        success  : function ( obj ) {
                     var res, thubUrl, imgUrl, id, Tag, extid, clickUrl, Title, Price, imgData;
                     thubUrl  = w.getTextContents( obj.getElementsByTagName("Url")[1] );
                     imgUrl   = w.getTextContents( obj.getElementsByTagName("Url")[0] );
                     id       = w.getTextContents( obj.getElementsByTagName("Id")[0] );
                     //extid    = w.getTextContents( obj.getElementsByTagName("ExtId")[0] );
                     clickUrl = w.getTextContents( obj.getElementsByTagName("ClickUrl")[0] );
                     Tag      = w.getTextContents( obj.getElementsByTagName("Tags")[0] );
                     Title    = w.getTextContents( obj.getElementsByTagName("Title")[0]);
                     Price    = w.getTextContents( obj.getElementsByTagName("Price")[0]);

                     data = { id : id, thub : thubUrl, tag : Tag, imgUrl : imgUrl, clickUrl : clickUrl, Title : Title, Price : Price };
                     //左上にクエリ画像表示
                     is.setQueryImage( data );

                     //検索履歴に画像表示
                     hs.setImageList( data );

                     //カテゴリ選択
                     ct.selectCategoryFromTag( Tag );
                   }
      })
    }
  };

  is.setQueryImage = function ( data )  {
    var div, img, linkToDetail, linkToExpand;
    //左上にクエリ画像表示
    $( '#queryImage' ).remove();
    div = document.createElement( "div" );
    div.id = "queryImage";
    linkToDetail = document.createElement( "a" );
    linkToExpand = document.createElement( "a" );
    linkToDetail.innerHTML   = "詳細へ";
    linkToExpand.innerHTML   = "拡大する";
    $(linkToDetail).addClass( "linkToDetailQuery" );
    $(linkToExpand).addClass( "linkToExpandQuery" );
    linkToDetail.setAttribute( "target", "_blank" );
    linkToDetail.setAttribute( "href", data.clickUrl );
    linkToExpand.setAttribute( "href", data.imgUrl );
    $(linkToDetail).hide();
    $(linkToExpand).hide();
    img = document.createElement( "img" );
    img.id = "img_" + data.id;
    img.setAttribute( "src", data.thub );
    img.setAttribute( "name", data.tag );
    $(img).addClass( "Image" );
    
    $(div).append( img );
    if ( data.id != 0 ) {
      $(div).hover(
          function () {
            $(this).css( {backgroundColor : "#FFFFFF" } );
            $(this).children("img").css( {opacity : "0.4"} );
            $(this).children("a").show();
          },
          function () {
            $(this).css( {backgroundColor : "#555555" } );
            $(this).children("img").css( {opacity : "1"} );
            $(this).children("a").hide();
          }
      );
      $(div).append( linkToDetail );
      $(div).append( linkToExpand );
    }
    $( '#queryImageWrap' ).append( div );

    ei.setDataSetQuery( data );
    //拡大のバインド
    ei.bindExpandQuery();
  };

  is.init();
});

