function offerCheckboxHandler(elm) {
	if (elm.checked) {
		// $(elm).addClass('option_highlight');
		$(elm).parents('.option_row').addClass('option_highlight');
	} else {
		$(elm).parents('.option_row').removeClass('option_highlight');
	}
}
function toggleOfferOptions() {
	$('.extra_params').slideToggle();
}
function toggleAdvanced() {
	$('.advanced').slideToggle();
}
function populateOfferFromXrate(xrate) {
	if (xrate.value && xrate.value > 0) {
		$('.offer_option_amount').each( function() {
			$('#offer_option_value_'+$(this).attr('xratekey')).val($(this).val() * xrate.value);
		});
	}
}
function expandControl(control,expandingElementId) {
	$('#'+expandingElementId).slideToggle();
	if ($(control).hasClass('closed')) {
		$(control).removeClass('closed');
		$(control).addClass('open');
	} else {
		$(control).removeClass('open');
		$(control).addClass('closed');
	}
}
function capture_email(email) {
  $.ajax({
     type: "POST",
     url: "/socialgold/capture_email",
     data: ({ "email" : email }),
     dataType: "json",
     success: function(msg){
       var $wrapper = $('#capture_email');
       $wrapper.fadeOut(750,function() {
         $wrapper.empty();
         $wrapper.append(
          $('<h3>').text('Thank you for your interest in Social Gold!')
         );
         $wrapper.fadeIn();
       });

     }
   });}
function S4() {
   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
function generateGUID() {
  return (S4()+S4()+S4()+S4()+S4()+S4()+S4()+S4());
}

function toggle_help_highlight(elm) {
	$('.fieldgroup').removeClass('highlighted');
	var fieldgroup = $(elm).parents('.fieldgroup');
	fieldgroup.addClass('highlighted');
}
function show_help_content(elm) {
	var help_content_id = $(elm).attr('key') + '_help';
	$('.help_content').hide();
	$('#' + help_content_id).show();
}
function position_help_container(elm) {

	var fieldgroup = $(elm).parents('.fieldgroup');

	var topOffset = parseInt(fieldgroup.position().top);

	var bottomOfHelp = parseInt(topOffset - (topOffset < 100 ? topOffset : 100)) + parseInt($('#help_pane').height());

	// see if the bottom cuts into the footer, move it up if it does
	var newPosition = ( bottomOfHelp > $('#form_content').height()) ?
										 topOffset - (topOffset < 100 ? topOffset : 100) -
										(bottomOfHelp - $('#form_content').height()) - 30
										: topOffset - (topOffset < 100 ? topOffset : 100);

	$('#help_pane').css( 'top', newPosition );

}
function initOfferForm() {
	$('.highlightable').focus(
		function() {
			show_help_content(this);
			toggle_help_highlight(this);
			position_help_container(this);
	});
	$('.help_button').click(
		function() {
			show_help_content(this);
			toggle_help_highlight(this);
			position_help_container(this);
	});
	$('#use_template_button').click(
		function() {
			$('#show_copy_form').slideToggle();
			if ($('#show_copy_form').css('display') != 'none') {
				$('#id').trigger('focus');
			}
	});

}

/***** Analytics *****/

var Analytics = {
  Utilities: {
    DateToHour: function (milliseconds) {
      var date = new Date(parseInt(milliseconds));
      return "" + date.getUTCMonth() + "/" + date.getUTCDate() + " " + date.getUTCHours() + ":00:00";
    }
  },
  DataPointFormatters: {
    sources_v_sinks: function (label, data_x, data_y) {
      return Analytics.Utilities.DateToHour(data_x) + ": " + parseInt(data_y) + " " + label;
    },
    total_transactions: function (label, data_x, data_y) {
      return Analytics.Utilities.DateToHour(data_x) + ": " + parseInt(data_y) + " " + label;
    },
    unique_users: function (label, data_x, data_y) {
      return Analytics.Utilities.DateToHour(data_x) + ": " + parseInt(data_y) + " " + label;
    },
    unmapped: function (label, data_x, data_y) {
      return Analytics.Utilities.DateToHour(data_x) + ": " + data_y + " " + label;
    }
  }
};

Date.fromYmd = function(ymd) { // expects ymd to be a 6-character string or 6-digit number like "20101215"
  ymd = ymd.toString();
  var year = ymd.substr(0,4);
  var month = parseInt(ymd.substr(4,2)) - 1; // months are 0-indexed in JavaScript
  var day = ymd.substr(6,2);
  return new Date(year, month, day);
};

Date.prototype.getYmd = function() {
  var year = this.getFullYear();
  var month = parseInt(this.getMonth() + 1); // months are 0-indexed in JavaScript
  var day = this.getDate();

  // pad with a leading zero if necessary
  if (month < 10) { month = '0' + month; }
  if (day < 10) { day = '0' + day; }

  return [ year, month, day ];
};

Date.prototype.toYmd = function() {
  var ymd   = this.getYmd();
  return ymd[0] + '-' + ymd[1] + '-' + ymd[2];
};

Date.prototype.toDisplayString = function() {
  var ymd   = this.getYmd();
  var year  = ymd[0];
  var month = ymd[1];
  var day   = ymd[2];
  var months = [
    "Jan", "Feb", "Mar", "Apr", "May", "Jun",
    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  ];
  return months[month - 1] + " " + day + ", " + year;
};

function refreshAnalytics(start_time, end_time, time_interval, offer_id) {
  var self = this;

  $.get(
    "/socialgold/developer/analytics/xhr_graph_data",

    {
      // set at end of drawGoogleChart function
      'graph_id'        : self.graph_id,
      'width'           : self.width,
      'height'          : self.height,
      'graph_type'      : self.graph_type,
      'statistic'       : self.statistic,
      'statistic_extra' : self.statistic_extra,

      // passed in to this AJAX call
      'offer_id'        : offer_id,
      'start_time'      : start_time,
      'end_time'        : end_time,
      'time_interval'   : time_interval
    },

    function(data) {
      var graph_data = data[0];
      var graph_data_table = data[1];

      // update the range shown by the date picker, in case the server had to
      // restrict the date range (eg, because of too many data points)
      var formatted = [
        Date.fromYmd(graph_data["start_time"]).toDisplayString(),
        Date.fromYmd(graph_data["end_time"]).toDisplayString()
      ];
      $('#widgetField span')[0].innerHTML = formatted.join(' - ');

      if ("Statistic" == graph_data["graph_type" ]) {
        $("#" + graph_data["id"]).text(graph_data["data"]);
      }
      else {
        drawGoogleChart(graph_data);
        drawGoogleChart(graph_data_table);
        $("#" + graph_data_table["id"]).stop().fadeTo("fast", 1); // only for graphs
      }

      $("#" + graph_data["id"]).stop().fadeTo("fast", 1); // for both graphs and stats
    },

    'json'
  );
};

function addDatePickerCompatibility(graphObj, graph_id, statistic, statistic_extra) {
  if (window.graphs == undefined) window.graphs = [];

  // check whether we've already seen this graph id
  if (graphObj.graph_id) return;

  graphObj.graph_id = graph_id;
  graphObj.refreshAnalytics = refreshAnalytics;

  // optional; used for single-value statistics, not for graphs
  graphObj.statistic = statistic || '';
  graphObj.statistic_extra = statistic_extra || '';

  window.graphs.push(graphObj);
}

function emptyGoogleChart(graph) {
  if (!graph || !graph["id"]) return;

  // skip data tables; will be updated with their paired graph
  if (graph["id"].match(/_table$/)) return;

  var chartDiv = document.getElementById(graph["id"]);
  if (!chartDiv) return;
  addDatePickerCompatibility(chartDiv, graph["id"]);
}

function drawGoogleChart(graph) {

  // return true if graph should have time on its x-axis
  function timeOnXAxis(graph) {
    var chartTypesWithoutTime = [ "GeoMap", "PieChart" ];
    var chartIdsWithoutTime = [ "transaction_count_by_geo_table", "transaction_revenue_by_geo_table" ];
    return ($.inArray(graph["graph_type"], chartTypesWithoutTime) == -1) && ($.inArray(graph["id"], chartIdsWithoutTime) == -1);
  }

  // return -1 if no column to format
  function formatCurrencyColumn(chartId) {
    switch (chartId) {
      case "transaction_revenue_by_geo":
        return 1;
      case "transaction_revenue_by_geo_table":
        return 1;
      case "gross_revenue":
      case "gross_revenue_table":
      case "net_revenue":
      case "net_revenue_table":
        return 1;
      default:
        return -1;
    }
  }

  // return -1 if no column to format
  function formatPercentColumn(chartId) {
    switch (chartId) {
      case "conversion":
        return 1;
      case "conversion_table":
        return 3;
      default:
        return -1;
    }
  }

  function exportDataTable(dataTable) {
    var exportButton = $("#export_csv_button");
    var exportData   = $("#export_csv_data");
    var startTime    = $("#export_start_time");
    var endTime      = $("#export_end_time");

    if (!exportButton || !exportData || !startTime || !endTime) return;

    var csv_data = [];
    var cols = dataTable.getNumberOfColumns();
    var rows = dataTable.getNumberOfRows();

    // header row
    var headers = [];
    for (var c = 0; c < cols; c++) {
      var header = dataTable.getColumnLabel(c);
      headers.push(header);
    }
    csv_data.push(headers);

    // data rows
    for (var r = 0; r < rows; r++) {
      var row = [];
      for (var c = 0; c < cols; c++) {
        // always export exactly how the UI displayed it to the user
        var val =  dataTable.getFormattedValue(r, c);
        row.push(val);
      }
      csv_data.push(row);
    }

    // update export form with new data and reveal the "export" button
    startTime.val(graph["start_time"]);
    endTime.val(graph["end_time"]);
    exportData.val(JSON.stringify(csv_data));
    exportButton.removeClass("hidden");
  }

  /* NOTE on why hack is being used:
   *
   *  Google Charts API does not give us any control over the formatting of the
   *  axis labels, as it does with the data within the graph or table itself.
   *
   *  If we want to add a prefix/suffix to the labels, we have to hack it into
   *  the DOM after the svg element has been returned by Google. :(
   */
  function formatAxes(prefix, suffix) {
    // because this is a hacky method, do more paranoid checks than usual
    var chartDiv = $("#" + graph["id"]);          if (!chartDiv) return;
    var iframe = $("iframe", chartDiv);           if (!iframe) return;
    var iframeId = iframe.attr("id");             if (!iframeId) return;
    var iframeElem = frames[iframeId];            if (!iframeElem) return;
    var iframeBody = iframeElem.document.body;    if (!iframeBody) return;

    // IE uses "textpath" instead, but it doesn't resize the label elements when
    // prefixes or suffixes are added. So DON'T add "textpath" to this selector
    // and the formatting won't be applied to IE, which is (unfortunately) what
    // we want.
    var axisLabels = $("text[text-anchor]", iframeBody);
    if (!axisLabels.length) return;

    var xAxisLabels = [];
    var yAxisLabels = [];

    // the only way to reliably distinguish x- and y-axis labels is by their positions :(
    var xAxisTop = $(axisLabels[0]).offset().top;
    $.each(axisLabels, function(index, label) {
      xAxisTop == $(label).offset().top ? xAxisLabels.push(label) : yAxisLabels.push(label);
    });

    $.each(yAxisLabels, function(index, label) {
      label = $(label);
      label.text( prefix + label.text() + suffix );
      if (index == 0) label.hide();
    });
  }


  if (!graph || !graph["id"]) return;
  emptyGoogleChart(graph);

  // if there's no container on the page, bail early
  var chartDiv = document.getElementById(graph["id"]);
  if (!chartDiv) return;

  // if there's no actual data, tell the merchant so and bail
  if (!graph["data"] || graph["data"].length == 0) {
    if (graph["id"].match(/_table$/)) {
      $("#export_csv_button").addClass("hidden");
      $(chartDiv).empty();
    }
    else {
      $("#graph_type_selection, .graph_footnotes").hide();
      $(chartDiv).empty();
      $(".empty_data_block").show();
    }
    return;
  }

  $("#graph_type_selection, .graph_footnotes").show();
  $(".empty_data_block").hide();

  // create columns
  var columns = $.map(graph["headers"], function(header) {
    var capitalized = header.charAt(0).toUpperCase() + header.substring(1, header.length)
    return { id:header, label:capitalized, type:"number" };
  });

  // add invariant first column header
  if (timeOnXAxis(graph)) {
    columns.unshift( { id:"date", label:"Date", type:"date" } );
  }
  else {
    columns.unshift( { id:"region", label:"Region", type:"string" } );
  }

  // create rows
  var rows = $.map(graph["data"], function(data) {
    var timestamp;
    if (timeOnXAxis(graph))
      timestamp = data.shift() * 1000;

    // map all the data points
    var values = $.map(data, function(count) {
      if (count == null) count = ''; // Google sometimes breaks if given a null in the dataTable
      return { v:count };
    });

    if (timeOnXAxis(graph))
      values.unshift( { v:new Date(timestamp) } );

    return { c:values };
  });

  // create and populate the data table
  var GOOGLE_CHART_VERSION = 0.6;
  var dataTable = new google.visualization.DataTable( { cols: columns, rows: rows }, GOOGLE_CHART_VERSION );

  var graphType = ($.inArray(graph["graph_type"].toLowerCase(), supportedGoogleCharts /* defined in view */) == -1 ? "AreaChart" : graph["graph_type"]);
  var chartOptions = {};

  if (graphType != "Table") {
    // set up default graph options
    chartOptions = {
      width: graph["width"],
      height: graph["height"],
      min: 0,
      max: graph["max"],
      colors: ["#BAD061", "#EDC857", "#AF62D0", "#6283D0", "#7A8D2A", "#D0AF62", "#D06283", "#62BAD0" ],
      borderColor: "#545454",
      legend: (graphType == "PieChart" ? "right" : "bottom"),
      axisFontSize: 13,
      legendFontSize: 13,
      titleFontSize: 13,
      tooltipFontSize: 13,
      pieJoinAngle: 8
    };
  }

  if (typeof graph["tooltips"] != "undefined") {
    chartOptions.enableTooltip = graph["tooltips"];
  }

  // sort by time...
  if (timeOnXAxis(graph)) {
    chartOptions.sortColumn = 0;
    chartOptions.sortAscending = true;
  }
  // ...or else sort by the last column, largest values first
  else {
    chartOptions.sortColumn = (columns.length - 1);
    chartOptions.sortAscending = false;
  }

  // set any graph-specific options
  if (graphType == "ImageSparkLine") {
    chartOptions.fill = true;
    chartOptions.showAxisLines = false;
  }
  else if (graphType == "ImageAreaChart") {
    chartOptions.showCategoryLabels = false;
    chartOptions.showValueLabels = false;
  }
  else if (graphType == "GeoMap") {
    chartOptions.showLegend = false;
    chartOptions.dataMode = "regions";
    chartOptions.colors = [0xE0FFD4, 0xA5EF63, 0x50AA00, 0x267114];
  }
  else if (graphType == "ColumnChart") {
    chartOptions.isStacked = true;
  }

  // format data
  var column;
  if (timeOnXAxis(graph)) {
    var timeInterval = graph["time_interval"];
    var dateFormats = [
      "M/d/yy h:mm a",    // 0 == hourly
      "M/d/yy",           // 1 == daily
      "'Ww",              // 2 == weekly
      "MMM"               // 3 == monthly
    ];
    var dateFormatter = new google.visualization.DateFormat({ pattern: dateFormats[timeInterval] });
    dateFormatter.format(dataTable, 0); // always format first column
  }
  if (-1 != (column = formatCurrencyColumn(graph["id"]))) {
    var currencyFormatter = new google.visualization.NumberFormat({ prefix: "$" });
    currencyFormatter.format(dataTable, column);
  }
  if (-1 != (column = formatPercentColumn(graph["id"]))) {
    var percentFormatter = new google.visualization.NumberFormat({ suffix: "%" });
    percentFormatter.format(dataTable, column);
  }

  // create and draw the graph
  chart = new google.visualization[graphType](chartDiv);
  chart.draw(dataTable, chartOptions);

  if (!graph["id"].match(/_table$/)) {
    var waitForIframe = 1000; // TODO: calling iframe.ready() didn't work, why?
    var prefix = (1 == formatCurrencyColumn(graph["id"]) ? "$" : "");
    var suffix = (1 == formatPercentColumn(graph["id"])  ? "%" : "");
    setTimeout(function() { formatAxes(prefix,suffix) }, waitForIframe);
  }

  // make table or graph data available for download as CSV
  exportDataTable(dataTable);

  // save width and height, so it's available when date picker refreshes graphs
  $.each(window.graphs, function(index, saved_graph) {
    if (saved_graph.graph_id == graph["id"]) {
      saved_graph.width = graph["width"];
      saved_graph.height = graph["height"];
      saved_graph.graph_type = graph["graph_type"];
    }
  });

} // end drawGoogleChart callback function


/***** jQuery Plugins Here *****/

(function ($) {
  $.fn.initialize_merchant_notification_signups = function () {
    var $selector = this;

    $selector.click(function () {
      var $link = $(this).blur();
      var $parent = $link.parent();
      var subject = $link.attr('data-notification-subject');
      var success_message = $link.attr('data-success-message');
      var error_message = $link.attr('data-error-message');

      $.ajax({
        'url':'/socialgold/merchant_notification_request/create',
        'data': {'notification_subject':subject},
        'dataType': 'json',
        'method':'post',
        'success': function (response) {
          $link.remove();

          if ( response.status === true ) {
            $parent.text(success_message);
          } else {
            $parent.text(error_message);
          }
        },
        'error': function () {
          $link.remove();
          $parent.text(error_message);
        }
      });

      return false;
    });

    return $selector;
  };

  $.fn.initialize_change_view_type = function() {
    var $selector = this;
    // <span class="fakelink" id="change_view_type" data-change-view-type="<%= change_view %>">
    
    var offer_id = $selector.attr('data-offer-id');
    
    $selector.click(function(){
      var old_view_type = $('#current_view_type').text();
      var view_type = $selector.text();
      
      $.ajax({
        'url' : '/socialgold/admin/merchant/change_view_type',
        'data' : { 'offer_id' : offer_id, 'view_type' : view_type},
        'dataType' : 'json',
        'method' : 'post',
        'success': function() {
          $('#current_view_type').text(view_type);
          $selector.text(old_view_type);
          alert('view type changed to ' + view_type);
        },
        'error':function() {
          alert('that didn\'t work');
        }
      });
    });
    return $selector;
  };
  $.fn.initialize_css_skinning_toggle = function () {
    var $selector = this;
    var enable_label = 'Enable CSS Skinning';
    var disable_label = 'Disable CSS Skinning';

    $selector.text($selector.attr('data-is-css-skinning-enabled') == 'false' ? enable_label : disable_label);

    $selector.click(function () {
      var $button = $(this).blur();
      var offer_id = $selector.attr('data-offer-id');
      var is_css_skinning_enabled = $selector.attr('data-is-css-skinning-enabled') == 'true';
      var new_is_css_skinning_enabled_state = !(is_css_skinning_enabled);

      $.ajax({
        'url':'/socialgold/admin/merchant/toggle_offer_css_skinning',
        'data': {'offer_id':offer_id, 'is_css_skinning_enabled':new_is_css_skinning_enabled_state},
        'dataType':'json',
        'method':'post',
        'success': function (response) {
          if ( response.is_css_skinning_enabled === true ) {
            $button.text(disable_label);
          } else {
            $button.text(enable_label);
          }

          $button.attr('data-is-css-skinning-enabled', response.is_css_skinning_enabled.toString());
        },
        'error': function () {
          alert(arguments);
        }
      });

      return false;
    });

    return $selector;
  };

  $.fn.initialize_offer_cache_buster = function () {
    var $selector = this;

    $selector.click(function () {
      var $button = $(this).blur();
      var offer_id = $selector.attr('data-offer-id');

      $.ajax({
        'url':'/socialgold/admin/merchant/offer_cache_buster',
        'data': {'offer_id':offer_id},
        'dataType':'json',
        'method':'post',
        'success': function (response) {
          if ( response.busted === true ) {
            alert('Offer ID = ' + offer_id + ' has been busted');
          } else {
            alert('Could not bust ' + offer_id + ' out of cache!!!');
          }
        },
        'error': function () {
          alert('Could not bust ' + offer_id + ' out of cache!!!');
        }
      });

      return false;
    });

    return $selector;
  };


  $.fn.initialize_offer_amount_iso_currency_code_control = function () {
    var $selector = this;

    $selector.click(function () {
      var $button = $(this).blur();
      var offer_id = $selector.attr('data-offer-id');
      var offer_amount_iso_currency_code = $selector.siblings('select').val();

      $.ajax({
        'url':'/socialgold/admin/merchant/set_offer_amount_iso_currency_code',
        'data': {'offer_id':offer_id, 'offer_amount_iso_currency_code':offer_amount_iso_currency_code},
        'dataType':'json',
        'method':'post',
        'success': function (response) {
          if ( response.status == 'success' ) {
            window.location.reload();
          } else {
            alert('Could not set ' + offer_amount_iso_currency_code + ' for ' + offer_id);
          }
        },
        'error': function () {
          alert('Could not set ' + offer_amount_iso_currency_code + ' for ' + offer_id);
        }
      });

      return false;
    });

    return $selector;
  };


  $.fn.initialize_hangman_swf = function () {
    var $selector = this;

    $selector.each(function (index, container) {
      var $container = $(container).css({'height':'500px'});

      var so = new SWFObject($container.attr('data-swf-path'), "swf", "100%", "100%", "9.0.0", "#ffffff", []);
      so.addVariable("userId", $container.attr('data-user-id'));
      so.addVariable("offerId", $container.attr('data-offer-id'));
      so.addVariable("signingKey", $container.attr('data-signing-key'));
      so.addVariable("host", $container.attr('data-host'));
      so.addVariable("uiHost", $container.attr('data-ui-host'));
      so.write($container.attr('id'));
    });

    return $selector;
  };

  $.fn.initialize_flot_grid_points = function (formatter_name) {
    var $selector = this;
    var data_point_formatter = (Analytics.DataPointFormatters[formatter_name] === undefined ? Analytics.DataPointFormatters.unmapped : Analytics.DataPointFormatters[formatter_name]);

    var show_tool_tip = function (x, y, label, data_x, data_y) {
      $('<div id="tooltip">' + data_point_formatter.call(null, label, data_x, data_y) + '</div>').css({
        position: 'absolute',
        display: 'none',
        top: y - 25,
        left: x + 5,
        border: '1px solid #fdd',
        padding: '2px',
        'background-color': '#fee',
        opacity: 0.80
      }).appendTo("body").fadeIn(200);
    };

    var previous_point = null;

    $selector.each(function (index, container) {
      var $container = $(container);

      $container.bind("plothover", function (event, pos, item) {
        $("#x").text(pos.x.toFixed(2));
        $("#y").text(pos.y.toFixed(2));

        if (item) {
          if (previous_point != item.datapoint) {
            previous_point = item.datapoint;

            $("#tooltip").remove();
            var x = item.datapoint[0].toFixed(2), y = item.datapoint[1].toFixed(2);

            show_tool_tip(item.pageX, item.pageY, item.series.label, x, y);
          }
        } else {
          $("#tooltip").remove();
          previous_point = null;
        }
      });
    });

    return $selector;
  };
})(jQuery);

