function $(id) {return document.getElementById(id)};

function gridReload(table_name,qs) {

  var typeByFeed = [];
  typeByFeed ['closeouts']    = 'CLOSEOUT';
  typeByFeed ['expired_name'] = 'EXPIRE_NAME';
  type = (typeByFeed [table_name] ? typeByFeed [table_name] : table_name).toUpperCase();

  if (g_tableName != table_name) {
     tracker ('selectNewDataFeed&DF=' + type);
     g_tableName = table_name;
     }
  else if (g_qs != qs) {
     tracker ('selectNewQuickFilter&DF=' + type);
     g_qs = qs;
     }
  else {
     tracker ('reloadDataFeed&DF=' + type);
     }

  reload_grid(g_tableName, g_qs);

//    if (g_sort!="")
//        myGrid.setSortImgState(true,g_sortColInd,g_sortDir);
}

/**********************************************************/
function doFilter() {   
    var startsWith  = getElVal("filt_start");
    var contains    = getElVal("filt_cont");
    var endsWith    = getElVal("filt_end");
    var pattern     = getElVal("filt_pattern");
    var hyphens     = getElVal("ex_hyphen");
    var numbers     = getElVal("ex_num");
    var www     = getElVal("ex_www");
    var minChars    = getElVal("char_from");
    var maxChars    = (getElVal("char_to"));
    
    var minPR   = getElVal("filt_pagerank_from");
    var maxPR   = getElVal("filt_pagerank_to");
    var fake    = getElVal("filt_fake_pr");
    var dmoz    = getElVal("filt_dmoz");
    var ydir    = getElVal("filt_ydir");
    var gdir    = getElVal("filt_gdir");
    var minAge  = getElVal("filt_whois_age_from");
    var maxAge  = getElVal("filt_whois_age_to");
    var minGR   = getElVal("filt_gr_from");
    var maxGR   = getElVal("filt_gr_to");
    var minGRN  = getElVal("filt_grn_from");
    var maxGRN  = getElVal("filt_grn_to");
    var minGIDX = getElVal("filt_gidx_from");
    var maxGIDX     = getElVal("filt_gidx_to");
    var minOVTN     = getElVal("filt_ovtn_from");
    var maxOVTN     = getElVal("filt_ovtn_to");
    var minYBL      = getElVal("filt_ybl_from");
    var maxYBL      = getElVal("filt_ybl_to");
    var minGBL      = getElVal("filt_gbl_from");
    var maxGBL      = getElVal("filt_gbl_to"); 
    var minABL      = getElVal("filt_abl_from");
    var maxABL      = getElVal("filt_abl_to");      
    var minEDU      = getElVal("filt_edu_from");
    var maxEDU      = getElVal("filt_edu_to");
    var minGOV      = getElVal("filt_gov_from");
    var maxGOV      = getElVal("filt_gov_to");
    var minWBR      = getElVal("filt_wbr_from");
    var maxWBR      = getElVal("filt_wbr_to");
    var minAPOP     = getElVal("filt_apop_from");
    var maxAPOP     = getElVal("filt_apop_to");
    var minALR      = getElVal("filt_alr_from"); 
    var maxALR      = getElVal("filt_alr_to");
    var afake       = getElVal("filt_afake");
    var minQTR      = getElVal("filt_qtr_from");
    var maxQTR      = getElVal("filt_qtr_to");
    var minRegc     = getElVal("filt_regc_from");
    var maxRegc     = getElVal("filt_regc_to");
    var minPrice    = getElVal("filt_price_from"); 
    var maxPrice    = getElVal("filt_price_to"); 
        var minDays     = getElVal("filt_day_from");
    var maxDays     = getElVal("filt_day_to");      
    
    
    var extCheckBoxes = document.getElementsByTagName("input");
    var extArray = [];      
            
    g_requestStr = "&filter=true&startsWith="+startsWith+"&contains="+contains+"&endsWith="+endsWith+"&pattern="+pattern+"&hyphens="+hyphens+"&numbers="+numbers+"&www="+www+"&minChars="+minChars+"&maxChars="+maxChars+"&minDays="+minDays+"&maxDays="+maxDays+"&minAge="+minAge+"&maxAge="+maxAge+"&fake="+fake+"&minPR="+minPR+"&maxPR="+maxPR+"&dmoz="+dmoz+"&ydir="+ydir+"&gdir="+gdir+"&minGR="+minGR+"&maxGR="+maxGR+"&minGRN="+minGRN+"&maxGRN="+maxGRN+"&minGIDX="+minGIDX+"&maxGIDX="+maxGIDX+"&minOVTN="+minOVTN+"&maxOVTN="+maxOVTN+"&minYBL="+minYBL+"&maxYBL="+maxYBL+"&minGBL="+minGBL+"&maxGBL="+maxGBL+"&minABL="+minABL+"&maxABL="+maxABL+"&minEDU="+minEDU+"&maxEDU="+maxEDU+"&minGOV="+minGOV+"&maxGOV="+maxGOV+"&minWBR="+minWBR+"&maxWBR="+maxWBR+"&minAPOP="+minAPOP+"&maxAPOP="+maxAPOP+"&minALR="+minALR+"&maxALR="+maxALR+"&afake="+afake+"&minQTR="+minQTR+"&maxQTR="+maxQTR+"&minRegc="+minRegc+"&maxRegc="+maxRegc+"&minPrice="+minPrice+"&maxPrice="+maxPrice;
    
    for (var i=0;i<extCheckBoxes.length;i++)
        if (extCheckBoxes[i].type=="checkbox")
        if (extCheckBoxes[i].getAttribute("name")&&extCheckBoxes[i].getAttribute("name").indexOf("tld_")!=-1&&extCheckBoxes[i].checked)
            extArray.push(extCheckBoxes[i].getAttribute("name").substr(4));
//          g_requestStr += "&"+extCheckBoxes[i].getAttribute("name")+"="+extCheckBoxes[i].checked;
        g_requestStr +="&domainsExt="+extArray.join(",");
    

    gridReload(g_tableName,g_qs);

}   

function selectDataFeed(obj,table_name) {
    var jobj=$$(obj);
    $$('#df, #df_my').each(function(){
      $$('div.button_selected', this).removeClass('button_selected').addClass('button');
      $$('div.buttonPro_selected', this).removeClass('buttonPro_selected').addClass('buttonPro');
      $$('div.button, div.buttonPro', this).attr('name',null);
    });

/*
    var DF = $("df");
    for (var i=0;i<DF.childNodes.length;i++) {
        if (DF.childNodes[i].nodeName == 'DIV'&&DF.childNodes[i].getAttribute("name")=="current"&&DF.childNodes[i]!=obj) {
            DF.childNodes[i].setAttribute("name",null);
            DF.childNodes[i].className = DF.childNodes[i].className.replace("_selected","");
        }
    }
*/

    obj.setAttribute("name","current");
    if ( jobj.is('.button') ){
       jobj.removeClass('button').addClass('button_selected');
    }else{
       jobj.removeClass('buttonPro').addClass('buttonPro_selected');
    }
    
    reload_grid(table_name, g_qs);
}

function selectQuickFilter(obj,qs) {
    var QF = $("qf");
    for (var i=0;i<QF.childNodes.length;i++)
        if (QF.childNodes[i].nodeName == 'DIV'&&QF.childNodes[i].getAttribute("name")=="current"&&QF.childNodes[i]!=obj) {
            QF.childNodes[i].setAttribute("name",null);
            QF.childNodes[i].className = QF.childNodes[i].className.replace("_selected","");
        }
    obj.setAttribute("name","current");
    
    reload_grid(g_tableName, qs);
}


/********Work with filtres***********/
function showFilter(mode) {
    if (!mode) {
        $("middel-middel-3-1").onclick = function() {showFilter(true);};
        $("middel-middel-3-2").style.display = "none";
        $("gridbox").style.width = "850px";
        $("fenye-1").style.width = "850px";
        $("find").style.width = "850px";                   
        
        myGrid.setSizes();
    } else {
        $("middel-middel-3-1").onclick = function() {showFilter(false);};
        $("middel-middel-3-2").style.display = "block";
        $("gridbox").style.width = "675px";
        $("fenye-1").style.width = "675px";
        $("find").style.width = "675px";                        
        myGrid.setSizes();
    }
    
        
}

//Reset values to default for all filters
function resetAllFilters () {
  checkAll1 (true);
  checkAll2 (true);
  resetRanges ();
  clearAll ();
  checkExAll (false);
  resetChar ();
}

function checkAll1(check){
    var extCheckBoxes = document.getElementsByTagName("input");
    for (var i=0;i<extCheckBoxes.length;i++)
        if (extCheckBoxes[i].type=="checkbox" && extCheckBoxes [i].getAttribute("name") && extCheckBoxes [i].getAttribute("name").indexOf("tld_1")!=-1)
            extCheckBoxes[i].checked = check;
}

function checkAll2(check){
    var extCheckBoxes = document.getElementsByTagName("input");
    for (var i=0;i<extCheckBoxes.length;i++)
        if (extCheckBoxes[i].type=="checkbox" && extCheckBoxes [i].getAttribute("name") && extCheckBoxes [i].getAttribute("name").indexOf("tld_2")!=-1)
            extCheckBoxes[i].checked = check;
}

function resetRanges(){
      $("filt_pagerank_from").value='0';
      $("filt_pagerank_to").value='10';
      $("filt_fake_pr").value='All';      
      $("filt_dmoz").value='All';
      $("filt_ydir").value='All';
      $("filt_gdir").value='All';
      $("filt_whois_age_from").value='0';      
      $("filt_whois_age_to").value='23';            
      $("filt_gr_from").value=''; 
      $("filt_gr_to").value=''; 
      $("filt_grn_from").value=''; 
      $("filt_grn_to").value='';       
      $("filt_gidx_from").value=''; 
      $("filt_gidx_to").value='';        
      $("filt_ovtn_from").value=''; 
      $("filt_ovtn_to").value=''; 
      $("filt_ybl_from").value=''; 
      $("filt_ybl_to").value='';       
      $("filt_gbl_from").value=''; 
      $("filt_gbl_to").value=''; 
      $("filt_abl_from").value=''; 
      $("filt_abl_to").value='';   
      $("filt_edu_from").value=''; 
      $("filt_edu_to").value='';             
      $("filt_gov_from").value=''; 
      $("filt_gov_to").value='';       
      $("filt_wbr_from").value=''; 
      $("filt_wbr_to").value=''; 
      $("filt_apop_from").value=''; 
      $("filt_apop_to").value='';       
      $("filt_alr_from").value=''; 
      $("filt_alr_to").value='';       
      $("filt_afake").value='All';      
      $("filt_qtr_from").value='';
      $("filt_qtr_to").value='';
      $("filt_price_from").value=''; 
      $("filt_price_to").value=''; 
      $("filt_regc_from").value='0'; 
      $("filt_regc_to").value='6'; 
      $("filt_day_from").value='0';      
      $("filt_day_to").value='Max';      
}

function clearAll(){
      $("filt_start").value='';
      $("filt_cont").value='';
      $("filt_end").value='';
      $("filt_pattern").value='';
}

function checkExAll(check){
      $("ex_hyphen").checked = check;
      $("ex_num").checked = check;
      $("ex_www").checked = check;
}

function resetChar(){
      $("char_from").value='1';
      $("char_to").value='Max';
}


function Mouse_Fly(obj){
    obj.className = obj.className.split("_") [0] + "_selected"; 
}

function Mouse_Go(obj){
  if (obj.getAttribute('name')!="current")
        obj.className = obj.className.split("_") [0];  
}


function getElVal(id) {     
    if ($(id).type=="checkbox")
        return $(id).checked;
    else
        return $(id).value;
}

function setCommas (str) {
    var c = 0;
    str = str.toString ();
    for (var i=str.length;i>0;i--) {
        if (c==3) {
             str = str.substr(0,i)+","+str.substr(i);
             c=0; 
        }
        (str.substr(i-1,1)!=","?c++:c=0);
                    
    }
    return str;
}


function changeTitle(id,title) {
    var titleObj = $(id);
        title
      ?
        titleObj.childNodes[0].nodeValue = title
        :
      titleObj.childNodes[0].nodeValue = titleObj.getAttribute("curText");
}

function mediaControl1(type, autoSwitch) {
    if ( !$$('.panel_middle', '#meadiBox1').children().size() ) return;

    var mediaTitle  = $("media_title1");
    
    var newsDot     = $("dot_news1");
    var blogsDot    = $("dot_blogs1");
    var forumsDot   = $("dot_forums1");
    var videoDot    = $("dot_video1");
    var adsDot  = $("dot_ads1");
    
    var newsMedia   = $("media_news1");
    var blogsMedia  = $("media_blogs1");
    var forumsMedia = $("media_forums1");
    var videoMedia  = $("media_video1");
    var adsMedia    = $("media_ads1");

    newsDot.className = blogsDot.className = forumsDot.className = videoDot.className = adsDot.className = "white_dot";
    newsMedia.style.display = blogsMedia.style.display = forumsMedia.style.display = videoMedia.style.display = adsMedia.style.display = "none";
    g_mediaType1    = type;

    if (type=="news") {
        newsDot.className = "blue_dot";
        newsMedia.style.display = "block";
        mediaTitle.setAttribute("curText","Latest News");
        if (!autoSwitch)
            adsSwitcher ('ads');
    } else if (type=="blogs") {
        blogsDot.className = "blue_dot";
        blogsMedia.style.display = "block";        
        mediaTitle.setAttribute("curText","Forums");             
    } else if (type=="forums") {
        forumsDot.className = "blue_dot";
        forumsMedia.style.display = "block";        
        mediaTitle.setAttribute("curText","Forums");            
    } else if (type=="video") {
          $('videosticker1').src = 'http://www.freshdrop.tv/vid_plugin/index.php';
        videoDot.className = "blue_dot";
        videoMedia.style.display = "block";     
        mediaTitle.setAttribute("curText","Videos");
    } else if (type=="ads") {
        adsDot.className = "blue_dot";
        adsMedia.style.display = "block";
        mediaTitle.setAttribute("curText","Sponsors");
    }   
}

function mediaControl2(type, autoSwitch) {
    if ( !$$('.panel_middle', '#meadiBox2').children().size() ) return;

    var mediaTitle  = $("media_title2");
    
    var newsDot     = $("dot_news2");
    var blogsDot    = $("dot_blogs2");
    var forumsDot   = $("dot_forums2");
    var videoDot    = $("dot_video2");
    var adsDot  = $("dot_ads2");
    
    var newsMedia   = $("media_news2");
    var blogsMedia  = $("media_blogs2");
    var forumsMedia = $("media_forums2");
    var videoMedia  = $("media_video2");
    var adsMedia    = $("media_ads2");

    newsDot.className = blogsDot.className = forumsDot.className = videoDot.className = adsDot.className = "white_dot";
    newsMedia.style.display = blogsMedia.style.display = forumsMedia.style.display = videoMedia.style.display = adsMedia.style.display = "none";
    g_mediaType2    = type;

    if (type=="news") {
        newsDot.className = "blue_dot";
        newsMedia.style.display = "block";
        mediaTitle.setAttribute("curText","Latest News");
        if (!autoSwitch)
            adsSwitcher ('ads');    
    } else if (type=="blogs") {
        blogsDot.className = "blue_dot";
        blogsMedia.style.display = "block";        
        mediaTitle.setAttribute("curText","Forums");             
    } else if (type=="forums") {
        forumsDot.className = "blue_dot";
        forumsMedia.style.display = "block";        
        mediaTitle.setAttribute("curText","Forums");            
    } else if (type=="video") {
        $('videosticker2').src = 'http://www.freshdrop.tv/vid_plugin/index.php';
        videoDot.className = "blue_dot";
        videoMedia.style.display = "block";     
        mediaTitle.setAttribute("curText","Videos");
    } else if (type=="ads") {
        adsDot.className = "blue_dot";
        adsMedia.style.display = "block";
        mediaTitle.setAttribute("curText","Sponsors");
    }   
}

var g_adsTO = null;
function adsSwitcher(type) {
  clearTimeout (g_adsTO);
    if (type=='news')
        g_adsTO = setTimeout(function() {mediaControl('news',true); changeTitle('media_title');adsSwitcher('ads');},15*1000);
    else if (type=='ads')
        g_adsTO = setTimeout(function() {mediaControl('ads',true); changeTitle('media_title');adsSwitcher('news')},5*60*30*1000);
}

function colapseSection(obj) {
    if (obj.className == "filter_colapsible")
        obj.className = "filter_expandable";
    else
        obj.className = "filter_colapsible";
}

function tracker (task) {
    //If user logged in track him actions
    // if (/userlogin=/.test (document.cookie))
      $('tracker').src = 'tracker.php?task=' + task + '&K=midas';
}

function addDomainToWatchlist (domainName, tableName) {
    var watchlist = $("watchlist_body");
    var existFlag = false;
    var typeByFeed = [];
    typeByFeed ['closeouts']        = 'CLOSEOUT';
    typeByFeed ['expired_name'] = 'EXPIRE_NAME';
    type = (typeByFeed [tableName] ? typeByFeed [tableName] : tableName).toUpperCase();
    
  var url = "actions.php?task=addToWatchList&domainName=" + domainName + "&type=" + tableName;
  var ajaxSender = new ajax ();
  
    ajaxSender.onSuccessHandler(function() {
      //Get time from response
      var datetime = this.getResponse ().split ('|') [1];
      var extraStyle = this.getResponse ().split ('|') [2];
    g_watchlist[g_watchlist.length] = domainName;
        var watchlistItem = document.createElement("div");
        watchlistItem.className = "item";
        watchlistItem.style.cssText = extraStyle;

    watchlistItem.innerHTML =  "<a target=\"_blank\" href=\"opendomain.php?type="+ type +"&domain="+ domainName +"\" onClick=\"tracker('buy&DF="+ type +"&buy=YES')\">"+ domainName +"</a>"
                                                 + "\n  <span class=\"timeItem\">"+ datetime+ " PST</span><span style='cursor:pointer;' onClick=\"delDomainFromWatchList (this.parentNode, '"+ domainName +"');\";> (X)</span>";
    watchlist.appendChild(watchlistItem);
    });

    for (var i=0;i<g_watchlist.length;i++)
        if (g_watchlist[i]==domainName)
            existFlag = true;
    if (!existFlag)
        ajaxSender.send (url);
}

function delDomainFromWatchList (obj, domainName) {
  var url = "actions.php?task=delFromWatchList&domainName=" + domainName;
  var ajaxSender = new ajax ();
    ajaxSender.onSuccessHandler(function() {
      var tmpAr = [];
      for (var i = 0; i < g_watchlist.length; i++)
        if (g_watchlist [i] != domainName)
            tmpAr [tmpAr.length] = g_watchlist [i];
      g_watchlist = tmpAr;
    obj.parentNode.removeChild (obj);
    });
    ajaxSender.send (url);
}

function setDataFeed (value, type) {
  g_tableName = value;
  isPro = type;
}

function moveOnDotClick(firstDotObj,secondDotObj,moveObj,mode,direction,size) {
    if (firstDotObj.className=="white_dot"){
        firstDotObj.className="blue_dot";
        secondDotObj.className="white_dot";
        animatedMove(moveObj,mode,direction,size,0,(_isIE?100:20));
    } 

}

function animatedMove(obj,mode,direction,size,times,speed) {
    if (size<=0) return;
    var speed = speed || 100;
    var times = times || 0;
    size = Math.round(size);
    
    if (size-speed<0)
        speed=size;
        
    obj.onclick = null;
    if (mode == "move") {
        if (direction == "left") {
            obj.style.left = (obj.offsetLeft-speed)+"px";
            setTimeout(function(){animatedMove(obj,mode,direction,size-speed,1)},50);
        } else if (direction == "right") {
            obj.style.left = (obj.offsetLeft+speed)+"px";
            setTimeout(function(){animatedMove(obj,mode,direction,size-speed,1)},50);
        } 
    }
}

function getAbsolutePos(el) {
    var r = { x: el.offsetLeft, y: el.offsetTop };
    if (el.offsetParent) {
        var tmp = getAbsolutePos(el.offsetParent);
        r.x += tmp.x;
        r.y += tmp.y;           
    }
    return r;
}

function changeSections(mode) {
//      var gridMiddle  = $("grid_middle");
    var filterBox   = $("filter_box");
    var filterTitle = $("filter_title_text");
    var gridBox     = $("gridbox");
    var watchlist   = $("watchlist");
    var dot1        = $("gf_dot1");
    var dot2        = $("gf_dot2");
    var dot3        = $("gf_dot3");     
    
    if (mode=="grid") {
        filterBox.style.display = "none";
        watchlist.style.display = "none";
        dot1.className = "white_dot";
        dot2.className = "blue_dot";
        dot3.className = "white_dot";               
        filterTitle.setAttribute("curText","Extend grid");
        $('gridbox').style.width =  $('grid').offsetWidth - 6 + 'px';
    } else if (mode=="filter") {
        filterBox.style.display = "block";
        watchlist.style.display = "none";       
        dot1.className = "blue_dot";
        dot2.className = "white_dot";
        dot3.className = "white_dot";       
        filterTitle.setAttribute("curText","Filter box");
        $('gridbox').style.width = '100%';
    } else if (mode=="watchlist") {
        filterBox.style.display = "none";
        watchlist.style.display = "block";
        dot1.className = "white_dot";
        dot2.className = "white_dot";
        dot3.className = "blue_dot";        
        filterTitle.setAttribute("curText","Watchlist");
        $('gridbox').style.width = '100%';
    }

  resize_grid();
}

function gridAutoHeight (type) {

  if (type) {
    $$('#grid_long').addClass('grid_long_selected').removeClass('grid_long');
    $$('#grid_compact').addClass('grid_compact').removeClass('grid_compact_selected');
    autoheight_grid();
  } else {
    $$('#grid_long').addClass('grid_long').removeClass('grid_long_selected');
    $$('#grid_compact').addClass('grid_compact_selected').removeClass('grid_compact');
    $('gridbox').style.height = '480px';
  }

  resize_grid();
}

function setRecordsPerPage (value) {
    g_recordsPerPage = value-0;
    g_cur_page=1;

    reload_grid(g_tableName, g_qs, 1);
}


//***************************
function saveFilter2(){
  var F=$$('#filter_boxF');

  var params={};

  $$('input, select',F).each(function(){
    var n=this.id?this.id:this.name;
    var v=this.value;

    if (this.type=="checkbox") v=this.checked;

//    console.log(this, this.id, this.name, ',n=',n, ',v=', v);
    params[ 'f['+n+']' ] = v;
  });

  params['f[save_filter_name]']=$$('#save_filter_name').val();
  params['task']='addFilter';
//  console.log(params);

  $$('#saved_filters_list').load('actions.php',params,function(data){
//     console.log('received',data);
  });

  $$('#save_filter_name').val('');

  hideForm('filterForm');
}

//***************************
function loadFilter(id){
  var params={};
  params['task']='loadFilter';
  params['id']=id;

  $$.getJSON('actions.php',params,function(data){
     var F=$$('#filter_boxF');

     $$('input, select',F).each(function(){
       var j=$$(this);
       var n=this.id?this.id:this.name;
       if (n>'') {
          var v=data.f[ n ];
          if ( typeof(v)!='undefined' ){
             if (this.type=="checkbox") {
                this.checked= (v=='true'||v=='1')?true:false;
             }else{
                j.val( v );
             }
          }else{
//            console.log('warn! no data for '+n);
          }
       }
     });

     doFilter();
  });

  return false;
}

//***************************
function delFilter(id){
  if (!confirm('ARE YOU SURE to remove filter?')) return false;

  var params={};
  params['task']='delFilter';
  params['id']=id;

  $$('#saved_filters_list').load('actions.php',params);
  return false;
}

function loadAds(){
 $$('.panel_middle', '#meadiBox1').load('index/ads1.php');
 $$('.panel_middle', '#meadiBox2').load('index/ads2.php');
 //clear iframe scrs???
// $('videosticker2').src = $('videosticker1').src = '';

}

