if(!$.clientCoords) {
  $.clientCoords = function() {
    var dimensions = {width: 0, height: 0,scrollLeft:0, scrollTop:0};
    if (window.innerWidth && window.innerHeight) {
      dimensions.width = window.innerWidth;
      dimensions.height = window.innerHeight;
    } else if (document.documentElement) {
      dimensions.width = document.documentElement.offsetWidth;
      dimensions.height = document.documentElement.offsetHeight;
    }
    if($.browser.msie) {
      var agt=navigator.userAgent.toLowerCase();
      if(agt.indexOf("msie 7.")==-1) {
        dimensions.width = dimensions.width-20;
        dimensions.height = dimensions.height-4;
      }
    }
    var iebody = (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
    dimensions.scrollLeft = document.all ? iebody.scrollLeft : window.pageXOffset;
    dimensions.scrollTop  = document.all ? iebody.scrollTop  : window.pageYOffset;
    return dimensions;
  }
}

Drupal.researchPopUp = {

  caller: null,
  valueField: null,
  handlers: new Object(),
  checkInt: null,
  lastMove: 0,

  checkPos: function() {
    var coords = $.clientCoords();
    var margin = new String($('#pop-up').css('margin-top'));
    var m = margin.match(/(\d+).*/);
    margin = m[1];
    lastMove = parseInt(margin) - 10;
    var offSet = coords.scrollTop - lastMove;
    if(offSet != 0) {
      lastMove = (lastMove + offSet) + 10;
      $('#pop-up').css('margin-top', lastMove+'px');
    }
  },

  select: function(symbol) {
    //$('#edit-symbols').val(symbol);
    if(symbol.match(/[a-zA-Z]+/)) {
      document.getElementById(Drupal.researchPopUp.valueField).value = symbol;
      Drupal.researchPopUp.hide();
      var data = {destination: document.getElementById(Drupal.researchPopUp.valueField), symbolSelected: symbol};
      Drupal.researchPopUp.invokeHandlers(data);
    }
  },

  show: function(caller) {
    Drupal.researchPopUp.checkInt = window.setInterval(Drupal.researchPopUp.checkPos, 20);
    Drupal.researchPopUp.caller = caller;
    Drupal.researchPopUp.valueField = caller.id+'-value';

    var coords = $.clientCoords();
    if(coords.height < $('table.main').height()) {
      coords.height = $('table.main').height();
    }
    var h = coords.height+'px';
    var w = coords.width+'px';

    var div = document.createElement('DIV');
    div.id = 'popup-background';
    $(div)
    .width(w)
    .height(h)
    .css({width:w,height:h,position:'absolute', 'background-color':'#000',opacity:0.45,left:'0px',top:'0px'})
    div.innerHTML = '&nbsp;';

    var popup = document.createElement('DIV');
    $(popup).addClass('symbol-search');
    popup.id = 'pop-up';

    $('body').append(div);
    $('body').append(popup);

    var pos = Drupal.absolutePosition(popup);

    $(popup).css({position:'absolute',top:'0px',left:pos.x+'px',opacity:0.95}).hide();

    if($.browser.msie) {
      var agt=navigator.userAgent.toLowerCase();
      if(agt.indexOf("msie 7.")==-1) {
        $('select').each(
        function() {
          $(this).hide();
        }
        );
      }
    }
    $(popup).show(250, function(){Drupal.researchPopUp.loadData();});
    return false;
  },

  hide: function() {
    window.clearInterval(Drupal.researchPopUp.checkInt);
    $('#pop-up').hide(250, function(){
      $('div#popup-background').hide(250, function(){
        $('div#popup-background').remove();
        if($.browser.msie) {
          var agt=navigator.userAgent.toLowerCase();
          if(agt.indexOf("msie 7.")==-1) {
            $('select').each(
            function() {
              $(this).show();
            }
            );
          }
        }
      });
      $('#pop-up').remove();
    });
  },

  onDataReceived: function(json) {
    if(json) {
      Drupal.researchPopUp.setContent(json);
    } else {
      Drupal.researchPopUp.setContent('<div class="messages error">Content could not be loaded. We apologize for the inconvenience.</div>');
    }
  },

  loadData: function() {
    Drupal.researchPopUp.setContent('<div class="messages status loading">تحميل ...  الرجاء الانتظار...  </div>');
    $.getJSON("index.php?q=json/research-tool/get-all-symbols", function(json){Drupal.researchPopUp.onDataReceived(json)});;
  },

  constructCloseButton: function() {
    var btn = document.createElement('A');
    btn.href = 'javascript:void(0);'
    btn.innerHTML = 'close';
    $(btn).css({display:'block','text-align':'right'}).click(Drupal.researchPopUp.hide);
    var btn2 = document.createElement('A');
    btn2.href = 'javascript:void(0);'
    btn2.innerHTML = 'close';
    $(btn2).css({display:'block','text-align':'right'}).click(Drupal.researchPopUp.hide);
    $('#pop-up').append(btn);
    $('#pop-up').prepend(btn2);
  },

  setContent: function(content) {
    $('#pop-up').empty().append(content);
    Drupal.researchPopUp.adjustHeight();
    if(Drupal.autocompleteAutoAttach) Drupal.autocompleteAutoAttach();
    if(Drupal.textareaAttach) Drupal.textareaAttach();
    if(Drupal.fieldsetAutoAttach) Drupal.fieldsetAutoAttach();
    Drupal.researchPopUp.constructCloseButton();
    Drupal.researchPopUp.initSearchForm();
  },
  adjustHeight: function() {
    var coords = $.clientCoords();
    var offset = 100;
    $('#pop-up').height('auto').css({height:'auto'});
    if($('#pop-up').height() > (coords.height-offset)) {
      $('#pop-up').height((coords.height-offset)+'px').css({height:(coords.height-offset)+'px',overflow:'auto'});
    } else {
      $('#pop-up').height('auto').css({height:'auto'});
    }
  },
  performSearch: function() {
    var sectors = document.getElementById('edit-sectors');
    var sectorId = sectors.options[sectors.selectedIndex].value;

    var search = document.getElementById('edit-search-field').value;
    search = search.replace(/^\s+|\s+$/g,"");
    if(search.length <= 0) search = 'null';
      var searchBtn = document.getElementById('edit-search');
      searchBtn.disabled = true;
      searchBtn.value = 'Searching...';
      $.getJSON('index.php?q=json/research-tool/get-symbols-search/'+search+'/'+sectorId, function(json){Drupal.researchPopUp.searchResult(json);});
    //}
    return false;
  },
  initSearchForm: function() {
    $('#pop-up form').submit(Drupal.researchPopUp.performSearch);
    //$('#edit-search').click(Drupal.researchPopUp.performSearch);
  },
  searchResult: function(JSON) {
    var searchBtn = document.getElementById('edit-search');
    searchBtn.disabled = false;
    searchBtn.value = 'Search';
    if(JSON) {
      var i = 0;
      var rows = $('#research-tool-search-table tbody tr');
      for(x in JSON) {
        if(rows[i]) {
          /*$($(rows[i]).find('a')).unbind('click').removeAttr('onclick').click(function(){
          Drupal.researchPopUp.select(String(x));
          }).empty().append(JSON[x]);*/
          //$($(rows[i]).find('a')).attr('onclick', "alert('???');").empty().append(JSON[x]);
          $($(rows[i]).find('a')).removeAttr('onclick').attr('href', "javascript:Drupal.researchPopUp.select('"+String(x)+"')").empty().append(JSON[x]);
        } else {
          var cssclass = (i % 2 == 0) ? 'odd' : 'even';
          var tr = document.createElement('tr');
          $(tr).addClass(cssclass).append('<td><a href="">'+JSON[x]+'</a></td>');
          $('#research-tool-search-table tbody').append(tr);
          $(tr).find('a').attr('href', "javascript:Drupal.researchPopUp.select('"+String(x)+"')");
        }
        i++;
      }
      if(i == 0) {
        if(!document.getElementById('no-rows-div')) {
          var d = document.createElement('DIV');
          d.id = 'no-rows-div';
          d.innerHTML = 'No companies found';
          $(d).addClass('messages').addClass('status');
          $('#research-tool-search-table').parent().append(d);
        }
      } else {
        $('#no-rows-div').remove();
      }
      if(i < rows.length) {
        for(x = i; x< rows.length; x++) {
          $(rows[x]).remove();
        }
      }

      Drupal.researchPopUp.adjustHeight();
    }
  },
  addHandler: function(handler) {
    if(!Drupal.researchPopUp.handlers[String(handler)]) {
      Drupal.researchPopUp.handlers[String(handler)] = handler;
    }
  },

  invokeHandlers: function(data) {
    for(x in Drupal.researchPopUp.handlers) {
      Drupal.researchPopUp.handlers[x](data);
    }
  }
};
