window.VectorFinder = new function() {

    this.options     = {};
    this.api_url     = "/search/";
    this.callbacks   = [];
    this.count = 100;
    
    this.reset = function() {
      this.callbacks = [];
    }
    
    this.setOptions = function(options) {
      this.options = options;
    }
    
    this.search = function(placeHolder, term) {
      this.searchApi("searchResults", "istockphoto", term);
      this.searchApi("searchResults", "shutterstock", term);
    	this.searchApi("searchResults", "dreamstime", term);
    	this.searchApi("searchResults", "envato", term);
    	this.searchApi("searchResults", "fotolia", term);
    }

    this.searchApi = function(placeHolder, api, term) {
      var request = this.prepareRequest(api, term, placeHolder);
      this.execute(request);
    }
    
    /* creates a request object to identify the response when it arrives
     */
    this.prepareRequest = function(api, term, placeHolder) {

        var request = {
            api         : api,
            term        : term,
            url         : this.api_url + api + "/" + term,
            placeHolder : placeHolder,
            script      : null,
            id          : null
        };    

        var callback = function(json) {
            window.VectorFinder.handleResponse(request, json);
        }; 

        return {
            requestObject : request, 
            callbackFunction : callback
        };
    }

    /* this method decides if the request should go ahead.
     */
    this.execute = function(request) {
        var callbackId = this.callbacks.length;
        
        request.requestObject.id = callbackId;
        this.callbacks[callbackId] = request.callbackFunction;
        
        this.injectScript(request.requestObject);
    }
    
    /* implements cross deomain scripting.
     */
    this.injectScript = function(request) {

        with (request) {
            script       = document.createElement("script");
            script.type  = "text/javascript";
            script.src   = url + "?callback=window.VectorFinder.callbacks[" + id + "]";
            script.defer = "defer";
            script.id    = id;
        }    
        
        head = document.getElementsByTagName("head")[0];
        head.appendChild(request.script);
    }

    /* event listener for when a request is complete.
     */
    this.handleResponse = function(request, json) {
        var data = json;
        
        this.callbacks[request.id] = null;
        request.script.parentNode.removeChild(request.script);

        if (data) {
          this.render(request, data, request.placeHolder);
        } else {
          return this.noResults();
        }
    }
    
    this.noResults = function() {
      for(var i = 0; i < this.callbacks.length; i++) {
        if( this.callbacks[i] != null ) {
          return;
        }
      }
      
      if (this.options['noResults']) {
        this.options['noResults']();
      }
    }
    
    /* renders the html of the result.
     */
    this.render = function(request, dataArray, placeHolderId) {

        if (!dataArray || dataArray.length == 0)
            return this.noResults();

        var placeHolder = document.getElementById(placeHolderId);
        if (!placeHolder) 
          return this.noResults();

        for(var i = 0; i < dataArray.length && i < this.count; i++) {
          var entry = this.renderEntry(request.api, dataArray[i]);
          placeHolder.appendChild(entry);
        }

        if (this.options['results']) {
          this.options['results']();
        }
    }
        
    /* renders the html of a single item.
     */
    this.renderEntry = function(api, item) {
        var result = document.createElement("div");
        var url    = item["url"];

        var html = ""; 

        if( item['image_width'] && item['image_height'] ) {
          html += '<a title="' + item['description'] + '" target="_blank" href="' + url + '">';
          html += '<div class="image" style="width:' + item['image_width'] + 'px;">';
          html += '<img src="' + item['image_url'] + '" style="height:144px !important;" alt="' + item['description'] + '"/>';
          html += '</div></a>';
          
        } else {
          html += '<a title="' + item['description'] + '" target="_blank" href="' + url + '">';
          html += '<div class="image">';
          html += '<img src="' + item['image_url'] + '" alt="' + item['description'] + '"/>';
          html += '</div></a>';
        }
        
        result.innerHTML = html;
        result.className = "searchResult";
        result.setAttribute("data-api", api);
        
        return result;
    }
}

