/**
 * Dealised.Deal Namespace
 *
 * LICENSE: Please email info@dealised
 * for more information
 *
 */

/**
 * Dealised.Deal
 */
Dealised.Deal = {}

/**
 * Deal Rating Object
 */
Dealised.Deal.Rating = function( element )
{
  var self = this;
  this.ratingElement = element.find('input');
  var match = element.find('input:eq(0)').attr('name').match("([0-9]+)-([0-9]+)?");

  this.element = element;

  // If no deal then return as there isnt anything to rate
  if( null == match )
  {
    return;
  }

  // Set dealId
  this.dealId = match[1];

  // Set purchaseId
  if( undefined != match[2] )
  {
    this.purchaseId = match[2];
  }

  this.ratingElement.rating(
  {
    callback: function( rating )
    {
      self.rating = rating;
      self.submitRating(true);
    }
  });

  // If already rated then diable the widget
  if (this.element.hasClass('rated') || this.element.hasClass('pending')) {
    this.ratingElement.rating('readOnly', true);
  }
};

/**
 * Rating element ontainer
 */
Dealised.Deal.Rating.prototype.element = null;

/**
 * Rating element
 */
Dealised.Deal.Rating.prototype.ratingElement = null;

/**
 * Deal id
 */
Dealised.Deal.Rating.prototype.dealId = null;

/**
 * Purchase Id
 */
Dealised.Deal.Rating.prototype.purchaseId = null;

/**
 * Rating
 */
Dealised.Deal.Rating.prototype.rating = null;

/**
 * Comment
 */
Dealised.Deal.Rating.prototype.comment = '';

/**
 * Submit rating
 */
Dealised.Deal.Rating.prototype.submitRating = function(openFeedbackForm)
{
	var self = this;
	var openFeedbackForm = openFeedbackForm;

	// Submit rating
	$.ajax({
		url: '/deal/ratingsubmit/' + this.dealId + '?format=json',
		dataType: 'json',
		data: {
			'purchaseId': this.purchaseId,
			'rating': this.rating,
			'anonymous': this.anonymous,
			'comment': this.comment
		},
		success: function(data) {
			if (data.status) {
				if (openFeedbackForm ) {
					self.openFeedbackForm();
				} else {
					Dealised.Ui.Message('Thank you for your rating');

					self.element.addClass('rated');
					self.element.find('span:eq(0)').html('Rate your experience:');
					self.ratingElement.rating('readOnly', true);
				}
			} else {
				Dealised.Ui.Message('Your rating could not be submitted at this time');
			}
		},
		error: function(xhr, testStatus, error) {
			Dealised.Ui.Message('Your rating could not be submitted at this time');
		}
	});
}

/**
 * Open feedback form
 *
 * @param link
 */
Dealised.Deal.Rating.prototype.openFeedbackForm = function()
{
  var self = this;

  // update the block message
  $.blockUI(
  {
    //message: '<div class="ui-hover"><a class="close"></a></div>',
	message: '<div class="ui-hover"><h2 class="header">Rate your experience<a class="close"></a></h2></div>',
    css:
    {
      width: '600px',
      height: '500px',
      top: '10%',
      left: '30%',
      'text-align': 'left'
      //'overflow-y': 'auto'
    }
  });

  $.get('/deal/ratingform/' + this.dealId + '?format=hover', function(data)
  {
    $('.ui-hover .close').after(data);

    $('#dealFeedback .rating input').rating(
    {
      callback: function( rating )
      {
        self.rating = rating;
      }
    });

    $('#dealFeedback .rating input').rating('select', self.rating);

    $('#dealFeedback input#submit').click(function()
    {
      self.comment = $('#comment').val();
      if ($('#chkanonymous').is(':checked')) {
    	  self.anonymous = 1;
      } else {
    	  self.anonymous = 0;
      }
      self.submitRating(false);

      return false;
    });

    $('#dealFeedback input#nothanks').click(function()
    {
      self.closeFeedbackForm();
      return false;
    });
  });

  $('.blockOverlay').click(self.closeFeedbackForm);

  $('.ui-hover .close').click(self.closeFeedbackForm);
}

/**
 * Close edit/create form
 */
Dealised.Deal.Rating.prototype.closeFeedbackForm = function()
{
  $.unblockUI();
}

/**
 * Rating init
 *
 */
Dealised.Deal.RatingInit = function()
{
  var self = this;

  // Init rating plugin on vouchers
  $('.deal-rating').each(function(i, data)
  {
    new Dealised.Deal.Rating($(this));
  });
};


/**
 * Dealised.Deal.CountDown
 */
Dealised.Deal.CountDown =
{
    /**
    * Get server time (from attribute in HTML, saves an ajax call)
    *
    */
    getServerTime: function()
    {
        return new Date($('.deal-countdown').attr('dealDate'));
    },

    /**
    * Countdown timer for deal
    *
    */
    init: function()
    {
        var self = this;

        var dealDate = $('.deal-countdown').attr('dealDate');

        if (dealDate) {
            finishedDate = new Date(dealDate);
            finishedDate = finishedDate.addHours($('.deal-countdown .hour').html());
            finishedDate = finishedDate.addMinutes($('.deal-countdown .minute').html());
            finishedDate = finishedDate.addSeconds($('.deal-countdown .second').html());

            $('.deal-countdown').countdown(
                {
                    until: finishedDate,
                    serverSync: self.getServerTime,
                    //timezone: Dealised.Config.Environment.gmtDifference,
                    compact: true,
                    format: 'HMS',
                    description: '',
                    expiryText: 'Deal Finished'
                }
            );
        }
    }
};
