
// dashboard

var dash = {
  
  init: function() {
    $('.dash_box').each( function() {
      $(this).find('.dash_box_tabs a').click( function() {
        dash.tab_click( this ); 
        return false;
      });
      $(this).find('.dash_box_tabs a.current').each( function() {
        // need to grab rel value to initiate dash.trends() for this box
        //$(this).addClass("current");
        var x = $(this).attr('rel').split('|');
        dash.trends( x[0], x[1] );
      });
    });
  },
  
  // can specify a date here if we want to make a one time request for something other than the global dash.date
  tab_click: function( tab, date2 ) {
    var x = tab.rel.split('|');
    var box_id = x[0];
    var box_type = x[1];
    $('#'+box_id).find('.dash_box_tabs a.current').removeClass("current");
    $(tab).addClass("current");
    dash.loading( box_id );
    clicky.log( '#dashboard/tab/'+box_type, 'Dashboard tab: '+box_type );
    $.get( "../ajax/dash_box", { site_id: dash.site_id, date: ( date2 ? date2 : dash.date ), type: box_type, box: box_id }, function( data ) {
      $('#'+box_id).find('.dash_box_content').html(data);
      dash.trends( box_id, box_type );
      if( isset( "iframe" )) links_new_window();
    });
  },
  
  trends: function( box_id, box_type ) {
    $('#'+box_id).find('.dash_box_content a.trend[rel]').click( function() {
      if( !this.rel ) return false;
      dash.loading( box_id );
      clicky.log( '#dashboard/trend/'+box_type, 'Dashboard trend: '+box_type );
      $.get( "../ajax/dash_box", { site_id: dash.site_id, date: dash.date, type: box_type, box: box_id, stat_id: this.rel },  function( data ) {
        $('#'+box_id).find('.dash_box_content').html( data ).find('a.back').click( function(){ dash.refresh( box_id ); return false; });
      });
      return false; 
    });
  },
  
  loading: function( box_id ) {
    $('#'+box_id+' .dash_box_content').html('<center><br><img src="../media/loading-large.gif"><br><br><br></center>');
  },
  
  refresh: function( box ) {
    $('#'+box+' .dash_box_tabs a.current').click();
    return false;
  },
  
  set_date: function( date, box_id, box_type, id ) {
    // this is used to set the date within an individual module, rather than using the global date.
    // the majority of the code is copied from other methods here because they're doing the same type of requests, the original methods just aren't written well to take extra parameters.
    // eventually, we'll re-write the whole thing.
    if( id ) {
      // stats for an individual item
      dash.loading( box_id );
      $.get( "../ajax/dash_box", { site_id: dash.site_id, date: date, type: box_type, box: box_id, stat_id: id },  function( data ) {
        $('#'+box_id).find('.dash_box_content').html( data ).find('a.back').click( function(){ dash.refresh( box_id ); return false; });
      });
    }
    else if( box_id ) {
      $('#'+box_id+' .dash_box_tabs a.current').each( function() {
        dash.tab_click( this, date );
      });
    }
  }
};




// graphs for popular data - trends and pagination

var graphy = {
  
  init: function() {
    graphy.back = $('#graphy').html();
    $('#graphy a.nextpage').click( graphy.nextpage );
    $('#graphy a.trend[rel]').click( function() {
      if( !this.rel ) return false;
      var request = { site_id: graphy.site_id, date: graphy.date, type: graphy.type };
      if( graphy.type_parent ) {
        // if we have a parent, then this.rel is id|parent_id instead of just id, so split those up
        var temp = this.rel.split('|');
        request.stat_id = temp[0];
        request.id_parent = temp[1];
        request.type_parent = graphy.type_parent;
      }
      else {
        request.stat_id = this.rel;
      }
      graphy.loading();
      $.get( "../ajax/graphy", request, function( data ) {
        $('#graphy').html( data ).find('a.back').click( function() { 
          $('#graphy').html( graphy.back );
          graphy.init(); 
          return false; 
        });
      });
      return false; 
    });
    if( isset( "iframe" )) links_new_window();
  },
  
  nextpage: function() {
    graphy.loading();
    $.get( "../ajax/graphy", { site_id: graphy.site_id, date: graphy.date, type: graphy.type, page: ++graphy.page, filter: graphy.filter },  function( data ) {
      $('#graphy').html( data );
      graphy.init();
    });
  },
  
  // just like dash, we need a seperate set_date function here, since it wasn't originally written to have this parameter changeable
  // at some point we will re-write it all and all will be well.
  // also we're not using box_id or box_type here but that's how it's always structured in the PHP so we deal with it.
  set_date: function( date, box_id, box_type, id ) {
    if( date && id ) {
      graphy.loading();
      $.get( "../ajax/graphy", { site_id: graphy.site_id, date: date, type: graphy.type, stat_id: id }, function( data ) {
        $('#graphy').html( data ).find('a.back').click( function() { 
          $('#graphy').html( graphy.back );
          graphy.init(); 
          return false; 
        });
      });
    }
  },
  
  loading: function() {
    $('#graphy').html('<center><br><img src="../media/loading-large.gif"><br><br><br></center>');
  }
};




// flash graphs

function flashy( name ) {
  this.name = name;
  this.url, this.type, this.type2, this.date, this.hourly, this.hourly_vs, this.type_parent;
  
  this.set_type = function( x, wait ) {
    this.type = x;
    if( !wait ) this.get();
  };
  this.set_type2 = function( x, wait ) {
    this.type2 = x;
    if( !wait ) this.get();
  };
  this.set_date = function( x, wait ) {
    this.date = x;
    this.hourly = 0;
    $('#'+this.name+'_compare_display').removeClass('hideme');
    if( !wait ) this.get();
  };
  this.set_hourly = function( x, wait ) {   /* i dont think this is used anymore? */
    this.hourly = x;
    $('#'+this.name+'_compare_display').addClass('hideme');
    if( !wait ) this.get();
  };
  this.set_hourly_vs = function( x, wait ) {
    this.hourly = 1;
    this.hourly_vs = x;
    $('#'+this.name+'_compare_display').addClass('hideme');
    if( !wait ) this.get();
  };
  this.get = function() {
    dropdown.close();
    var url = this.hourly ? this.url.replace(/flashy/i, "flashy_hourly") : this.url;
    document.getElementById( this.name ).reload( url + '&type=' + this.type + '&type2=' + this.type2 + '&type_parent=' + this.type_parent + '&date=' + this.date + '&hourly_vs=' + this.hourly_vs );
  };
}





// dropdown menus

var dropdown = {
  
  opened: 0,
  
  open: function( div, ev, stuff, align ) {
    // if "stuff" comes in, that means we want to set the content of this div before we display it. This is used to "reset" a multi-layer menu
    dropdown.close();
    dropdown.opened = div;
    if( stuff ) $('#'+div).html( stuff );
    
    var item  = $( ev.target || ev.srcElement );
    var pos   = $( item ).position();
    
    if( align == 'left' ) {
      var left = pos.left;
    }
    else {
      var left = pos.left - ( $('#'+div).width() - $( item ).width()) - 2;
    }
    
    $('#'+div).show().css("left", left ).css("top", pos.top + $( item ).height() + 5 );
    
    clicky.log( '#menu/'+div, 'Menu: '+div );
    stopbubble( ev );
    return false;
  },
  close: function() {
    $('#'+dropdown.opened ).hide();
    $('.dropdown').hide();
  },
  content: function( div, stuff ) {
    $('#'+div).html( stuff );
  },
  content_ajax: function( div, options ) {
    dropdown.loading( div );
    $.get( "../ajax/dropdown_menu", options, function( data ) {
      dropdown.content( div, data );
    });
    // must restate that we dont want clicks inside the menu to close the menu!
    $('.dropdown').click(stopbubble);
  },
  loading: function( div ) {
    dropdown.content( div, "<br><img class=mb-3 src='../media/loading.gif'> Loading...<br><br>" );
  }
}




// on pageload

$(function() {
  
  // make forms better
  if( document.forms.length ) {
  
    // auto-disable submit button when clicked. only first one though, because if there is another one we need its value.
    $(document.forms).each( function() {
      $(this).submit( function() {
        $(this).find(':submit:first[name!=no_disable]').attr( { disabled : 'disabled' } );
      });
    });
    
    // auto-focus first text field, if it's empty and visible
    // but don't do this for filter dropdowns (which are hidden) or msie dies
    //$(':text:first:not([name$=custom_value])').each( function() {
    $(':text:visible:first').each( function() {
      if( this.value == '' ) this.focus();
    });
  }
  
  // auto-scroll
  $('a[href^=#]:not([href=#])').click( function() {
    var x = $(this.hash);
    if( x.length ) {
      $('html,body').animate( { scrollTop: x.offset().top }, 500 );
      location.hash = this.hash;
      return false;
     }
  });
  
  // auto-toggle for hidden help boxes
  // auto-focus first form item if there's a form in there
  $('a[rel^="toggle"]').click( function() {
    var id = this.rel.split(':')[1];
    $('#' + id ).toggleClass( "hideme" );
    if( !$('#'+id).hasClass("hideme")) {
      $('#'+id+' :text:first').each( function() {
        if( this.value == '' ) setTimeout( "$('#"+id+" :text:first').focus()", 200);
      });
    }
    clicky.log('#toggle/'+id, id.replace(/(-|_)/g,' '));
    return false;
  });
  
  // close dropdown menu for any click outside of the menu
  //if( location.pathname.match(/\/stats\//)) {
    $('body').click(dropdown.close);
    $('.dropdown').click(stopbubble);
  //}
});




// calendar

function cal_show( div, ev ) {
  dropdown.close();
  var coord = click_xy( ev );
  $('#'+div).show().css("left",coord.x-380).css("top",60);
  clicky.log('#menu/calendar','Menu: calendar'); 
}

function calendar( date_min, date1, date2 ) {
  this.date_min = date_min;
  this.date_max = new Date();
  this.date1 = date1;
  this.date2 = date2 || date1;
  
  this.cal1 = new dhtmlxCalendarObject( 'cal1', false );
  //this.cal1.setSensitive( this.date_min, this.date_max );
  this.cal1.setDate( date1 );
  this.cal1.setOnClickHandler( cal_date1 );
  
  this.cal2 = new dhtmlxCalendarObject( 'cal2', false );
  //this.cal2.setSensitive( this.date_min, this.date_max );
  this.cal2.setDate( date2 );
  this.cal2.setOnClickHandler( cal_date2 );
  
  this.get_date = function() {
    return this.date1 + ( this.date2 && this.date2 != this.date1  ?  "," + this.date2  :  "" );
  }
}

// onclick didn't work right when these functions were part of the calendar class
function cal_date1( date ) {
  cal.cal1.setDate( date );
  cal.date1 = cal.cal1.getFormatedDate( "%Y-%m-%d", date );
}
function cal_date2( date ) {
  cal.cal2.setDate( date );
  cal.date2 = cal.cal2.getFormatedDate( "%Y-%m-%d", date );
}





// other stuff

function clone( a, type ) {
  if( type ) {
    if( type == 'array' ) {
      var x = new Array();
    }
    else if( type == 'object' ) {
      var x = new Object();
    }
    for( var i in a ) x[i] = a[i];
    return x;
  }
  else {
    // being called with "new"
    for( var i in a ) this[i] = a[i];
  }
}


function msiefilter() {
  if( $.browser.msie ) this.style.removeAttribute('filter');
  return true;
}

function isset( x ) {
  return( typeof( window[x] ) != "undefined" );
}

function links_new_window() {
  $("a[href^='http']").attr('target','_blank');
}

function stopbubble( ev ) {
  if( ev.stopPropagation ) {
    ev.stopPropagation();
  }
  else ev.cancelBubble = true;
}

function click_xy( e ) {
  // 100,100 is default for browsers that don't have pagex or clientx, which does not apply to anything modern.
  var posx = 100;
  var posy = 100;
  if( !e ) var e = window.event;
  if( e.pageX ) {
    posx = e.pageX;
    posy = e.pageY;
  }
  else if( e.clientX ) {
    posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
    posy = e.clientY + document.body.scrollTop  + document.documentElement.scrollTop;
  }
  return { x: posx, y: posy };
}

function go( url ) {
  dropdown.close();
  if( url ) {
    $('#loading_goes_here').html("<img class=mb-3 src='../media/loading.gif'> Loading...");
    location.href=url;
  }
}

function url_var( key, value, url ) {
  if( !url ) url = location.href;
  if( !key ) return url;
  url = url.replace( /#.*$/i, "" );
  if( !value ) {
    // if no value is set, we are deleting the variable from the URL
    var x = new RegExp( "(&|\\?)"+key+"=[^&]*" );
    return url.replace( x, "" );
  }
  else {
    // otherwise, we are changing/adding it
    // have to test for both &var and ?var since stupid javascript doesn't support lookbehinds
    var x = new RegExp( "&"+key+"=[^&]*" );
    var y = new RegExp( "\\?"+key+"=[^&]*" );
    if( url.match( x )) {
      return url.replace( x, "&"+key.replace(/(\\)/g,"")+"="+value );
    }
    else if( url.match( y )) {
      return url.replace( y, "?"+key.replace(/(\\)/g,"")+"="+value );
    }
    else {
      return url + "&" + key.replace(/(\\)/g,"") + "=" + value;
    }
  }
}





function flashcheck() {
  
  if( document.cookie.match(/\bno_flash\b/)) return;
  
  var no_flash = 1;

  if( navigator.mimeTypes.length ) {
    if( navigator.mimeTypes["application/x-shockwave-flash"] ) no_flash = 0;
  }
  else if( window.ActiveXObject ) {
    var flash_test;
    for( x = 1; x <= 20; x++ ) {
      try {
        flash_test = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash." + x + "');");
        if( flash_test ) no_flash = 0;
      }
      catch(e){}
    }
  }

  var cookie_expire = new Date();
  cookie_expire.setDate( cookie_expire.getDate() + ( no_flash ? 1 : 365 )); // if they have flash, set it to 1 year, otherwise, 1 day
  document.cookie = "no_flash=" + no_flash + ";expires=" + cookie_expire.toGMTString() + ";path=/";
}
flashcheck();




var clicky = { log: function(){ return; } };