/*
 * jQuery Site Index
 * Copyright 2010 www.rakebacknation.com
 */
(function($){
  
  // global settings
  var g = {
    uri_root: 'http://members.rakebacknation.com'
  };
    
  $.fn.site_index = function(){
    
    // common calls to speed up execution
    this.e = {
      sites:            $('#sites tr:gt(0)'),
      game_rate:        $('#game_rate'),
      tables:           $('#tables'),
      hours:            $('#hours'),
      badges:           $('#site_index img'),
      request_dialog:   $('#prop_request_dialog'),
      request_form:     $('#prop_request_dialog form'),
  		response_dialog:  $('#prop_request_response_dialog')
    };
    
    this.prf = {
      rake_back_rate:   $('#prop_request_rake_back_rate'),
		  promotions:       $('#prop_request_promotions'),
		  supported_games:  $('#prop_request_support_games'),
		  network_traffic:  $('#prop_request_network_traffic'),
		  site_id:          $('#prop_request_site_id')
    };
    
    // init
    init.call(this);
    
    return this;
  };
  
  $.fn.site_index.params = {
    link_index: {},
    image_prefix: null
  };
  
  
  // utility functions
  $.swap_link = function(symbol, url){
    $.fn.site_index.params.link_index[symbol] = url;
  };
  
  $.set_image_prefix = function(url){
    $.fn.site_index.params.image_prefix = url;
  };
  
  $.insert_affiliate_link = function(e, e_meta){
    if(e_meta.site_type_id == 1){
      var link = $.fn.site_index.params.link_index[e_meta.symbol];
      if(link){
        $('a', e).attr({href: link, target: '_self'});
      }
    }
  };
  
  $.inject_img_prefixes = function(badges){
    var prefix = $.fn.site_index.params.image_prefix;
    if(prefix){
      badges.each(function(bIndex, b){
        $(b).attr({src: $(b).attr('src').replace(/^http\:\/\/\w+.rakebacknation.com\/assets\/icons\/site_index/, prefix)});
      });
    }
  };
  
  
  // wrappers
  var init = function(){
    var self = this;
    
    // bind listeners
    $('#controls select').change(function(){
      calculate.call(self);
    });
    
    // routines
    inject_img_prefix.call(self);
    inject_affiliate_links.call(self);
    calculate.call(self);
    init_dialogs.call(self);
    
    // style
    $('#sites tr:gt(0):even').addClass('stripe-on');
    $('#sites tr:gt(0):odd').addClass('stripe-off');
    $('#sites tr:last td.rake_back').css({borderBottomWidth: '1px'});
  };
  
  var inject_img_prefix = function(){
    $.inject_img_prefixes(this.e.badges);
  };
  
  var inject_affiliate_links = function(){
    this.e.sites.each(function(sIndex, s){
      var meta = $(s).metadata();
      $.insert_affiliate_link(this, meta);
    });
  };
  
  var calculate = function(){
    this.e.sites.calculate_rake_back(
      {r: this.e.game_rate.val(), t: this.e.tables.val(), h: this.e.hours.val()}
    );
  };
  
  var init_dialogs = function(){
    var self = this;
    
    // request dialog
    self.e.request_dialog.dialog({
	    autoOpen: false,
		  modal: true,
		  resizable: false,
		  width: 400,
		  //height: 400,
		  buttons: {
		    'Request': function(){
          
          // jsonp
		      $.ajax({
            dataType: 'jsonp',
            data: $('#prop_request_dialog form').serialize(),
            url: g.uri_root + '/site_index/ajax_prop_request'
          });
		      
		      // close dialog
		      $(this).dialog('close');
		    },
		    'Cancel': function(){
		      $(this).dialog('close');
		    }
		  }
		});
		
		// request callback
		$.prop_request_response = function(response){
		  var output = response.messages[0]
        ? response.messages[0]
        : response.errors[0]
      ;
      $('p', self.e.response_dialog).html(output);
      self.e.response_dialog.removeClass('hidden').dialog('open');
		};
		
		// response dialog
		self.e.response_dialog.dialog({
		  autoOpen: false,
		  modal: true,
		  resizable: false,
		  buttons: {
		    'Close': function(){
		      $(this).dialog('close');
		    }
		  }
		});
		
		
		// disable enter keypresses in dialog
		$('.dialog input, .dialog textarea').keypress(function(e){
		  if(e.which == 13){
        return false;
      }
		});
		
		// prop info link listener
		$('#sites .site a.prop_info').click(function(){
		  
		  // site
		  var $site = $(this).parents('tr');
		  var s_meta = $site.metadata();
		  
		  // populate site specifics
		  $.each(['rake_back_rate', 'promotions', 'supported_games', 'network_traffic'], function(eIndex, e){
		    self.prf[e].empty();
		    if(!s_meta.form_text[e].length){
		      self.prf[e].hide().prev().hide();
		    }
		    else {
		      $.each(s_meta.form_text[e], function(mIndex, m){
  		      $('<li></li>').text(m).appendTo(self.prf[e]);
  		    });
  		    self.prf[e].show().prev().show();
		    }
		  });
		  
		  // append site id
		  self.prf.site_id.val(s_meta.id);
		  
		  // open dialog
		  self.e.request_dialog
		    .removeClass('hidden')
		    .dialog('option', {title: 'Request info: ' + $(this).text()})
		    .dialog('open')
		    .height(self.e.request_dialog.outerHeight())
		  ;
		  return false;
		});
  };
  
  
})(jQuery);



// calculate rakeback plugin
(function($){
  
  $.fn.calculate_rake_back = function(options){

    params = $.extend({}, {r: 1, t: 1, h: 1}, options || {});
    
    return this.each(function(){
      var s_meta = $(this).metadata();
      var rake_back = Math.round(params.r * params.t * params.h * s_meta.rake_back_rate);
      
      
      // monthly
      $("td.rake_back .monthly span", this) .text(print_payment(rake_back * 30));
      
      // per frequency
      if(s_meta.payment_frequency != 30){
        $("td.rake_back .per_frequency span.payment", this).text(print_payment(rake_back * s_meta.payment_frequency));
      }
    });
    
  };
  
  // helper functions
  var print_payment = function(rake){
    return rake > 0 ? '$'+format_number(rake) : '-';
  };
  
  var format_number = function(n){
  	n += '';
  	var rgx = /(\d+)(\d{3})/;
  	while(rgx.test(n)){
  		n = n.replace(rgx, '$1' + ',' + '$2');
  	}
  	return n;
  };
  
})(jQuery);



// onload
(function($){
  $(document).ready(function(){
	  $('#site_index').site_index();
	});
})(jQuery);