// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

$(function() {
  $(".date").datepicker({
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true
  });
});

$(function() {
 $("td:empty").html("&nbsp;");
});            

// Nested Table Rows
$(function() {
	$('.toggle_children')
		.click(function(event){
		  var parent_row = $(event.target).closest("tr.parent");
		  parent_row.nextAll().each(function() {
		    var current = $(this);
		    // Break out of the loop if we reach the next parent row
		    if (current.is("tr.parent")) return false;
		    
		    // Skip this row it's not a child class 
		    if (!current.is("tr.child")) return true;
		    current.toggle();
		  })
		});
});

// Nested Forms Start

function insertFields(link, method, content) {
	var new_id = new Date().getTime();
	var regexp = new RegExp("new_" + method, "g")
	$(link).before(content.replace(regexp, new_id));
	
	// Execute any page specific callbacks if defined
	if(typeof insertFieldsCallback == 'function') {
	  insertFieldsCallback(link);
	}
}

function remove_fields(link) {
	var field_div = $(link).closest(".fields");
	var hidden_field = field_div.find(":hidden");
  if (hidden_field) {
    hidden_field.val('1');
  }
  field_div.hide();
}

// Nested Forms End

function select_color_scheme(id, value) {
  $('.color_scheme').html("");
  $(id).html("<img src='/images/checkmark.png' />");
  $('#website_website_theme_id').val(value);
  return false;
}

function select_site_layout(id, value) {
  $('.site_layout').html("");
  $(id).html("<img src='/images/checkmark.png' />");
  $('#website_site_layout_name').val(value);
  return false;
}

function populate_response(canned_response){
  var body = $('#ticket_reply_body').val();
  body = body + canned_response;
  $('#ticket_reply_body').val(body);
  $('#ticket_reply_body').focus();
}

$(function() {
  if ($("#canned_response_response_topic_id").val() == "") {
    $("#response_topic_tr").show();
  } else {
    $("#response_topic_tr").hide();
  }

  $("#canned_response_response_topic_id").livequery('change', function(event){
    if ($("#canned_response_response_topic_id").val() == "") {
      $("#response_topic_tr").show();
    } else {
      $("#response_topic_tr").hide();
    }
  });
});

// this counter is used for the form elements for the search filter
updateCounter = function(){
  if (!this.counter) {
    this.counter = 1;
  }
  this.counter += 1;
  return this.counter;
}

$(function() {
  $('a.remove_filter').livequery('click',function(event){
    if ($('p.searchbar').length == 1) {
      // don't remove the searchbar if there is only one left!
      return false;
    } else {
      $(this).parent().parent().remove();
      return false;
    }
  });
});

function toggle_sub_nav_tab(tab_id) {
  // Remove any flash notifications
  $("h1.flash").remove();
  
  $('.sub_nav_tab').each( function (){
    if(this.id == tab_id) {
      $('#' + this.id).show();
      $('#' + this.id + '_tab').addClass('active');
    } else {
      $('#' + this.id).hide();
      $('#' + this.id + '_tab').removeClass('active');
    }
  });
}

function toggle_poker_room_affiliates(id) {
  $("#" + "hide_toggle_" + id).toggle();
  $("#" + "show_toggle_" + id).toggle();
  $("." + id).toggle();
}

function toggle_nested_rows(id) {
  $("#" + "hide_toggle_" + id).toggle();
  $("#" + "show_toggle_" + id).toggle();
  $("." + id).toggle();
}

// Promotions
$(function() {
	$('#promotion_form').change($.delegate({
		'.promotion_type_selector': function(e){
	    switch(e.val()) {
				case 'RakeRace':
					$('#promotion_prize_container').show();
					$('#promotion_prize_structure').html('1st Prize, 2nd Prize, 3rd Prize ...')
					break;
				case 'RakeChase':
					$('#promotion_prize_container').show();
					$('#promotion_prize_structure').html('MGR, Prize, Number of Slots<br/>MGR, Prize, Number of Slots')
					break;
				case 'Freeroll':
					$('#promotion_prize_container').hide();
					break;
			}
	  }
	}));
});



// Nested Models
$(function() {
	$('#content').click($.delegate({
		'.remove': function(e){
	    	target = e.attr('href').replace(/.*#/, '.');
			parent = e.parents(target + ":first");
			if($(target + ":visible").size() == 1) return;
			parent.remove();
			
			if(e.attr('href') == "#level_setting"){
			  normalize_level_settings();
			}
	  },
	  	'.destroy': function(e){
	    	target = e.attr('href').replace(/.*#/, '.');
			parent = e.parents(target + ":first");
			if($(target + ":visible").size() == 1) return;
			parent.hide();
			if(hidden_input = e.prev(":hidden")) {
			  hidden_input.val('1');
			}
			
			if(e.attr('href') == "#level_setting"){
			  normalize_level_settings();
			}
	  },
	  '.add_nested_item': function(e) {
			// Fetch the template from the link's 'href' attribute, replace ID for a newly generated one
			template = eval(e.attr('href').replace(/.*#/, '')).replace(/NEW_RECORD/g, new Date().getTime());
			
			// Append newly generated element from template, into the element found in the links 'rel' attribute
			$(e.attr('rel')).append(template);
			
			if(e.attr('href') == "#level_setting"){
			  normalize_level_settings();
			}
		}
	}));
});

function normalize_level_settings() {
  var level = 1
  
  $(".level_setting:visible").each(function() { $(this).find(".disabled_level_field").val(level); level++; });
}

// Member MGR Charts
$(function() {
  $('.mgr_chart').each(function() {
    var chart = new EJSC.Chart(this, {
      show_legend: false, 
      show_titlebar: false, 
      axis_bottom: {
        caption: "", hint_caption: "Day:",
        formatter: new EJSC.DateFormatter({ format_string: 'MMM D' }),
        grid: { show: false }
      }, 
      axis_left:   {
        caption: 'MGR', hint_caption: "MGR:",
        formatter: new EJSC.NumberFormatter({ currency_symbol: "$", forced_decimals: 0, variable_decimals: 0 }),
        major_ticks: { min_interval: 5 }
      }, 
      allow_zoom: false, 
      show_mouse_position: false 
    });
    $(this).data('chart', chart);
    var data = $(this).data('data')
    chart.addSeries(new EJSC.BarSeries(new EJSC.ArrayDataHandler(data), {
      title: 'MGR',
      y_axis_formatter: new EJSC.NumberFormatter({ currency_symbol: "$", forced_decimals: 2, variable_decimals: 2 }),
      lineOpacity: 100, lineWidth: 2,
      opacity: 70, color: '5085b5',
      padding: { y_axis_min: 0, y_axis_max: 10 }
    }));
  });
});