
/**
 * Provides closing flash messages
 */
$(document).ready(function() {
	$.handleHtmlFlashMessage();
});

/**
 * Provides create event on flash message
 * and will create X for close
 *
 * @return void
 */
$.handleHtmlFlashMessage = function () {
	$('.flash').append('<a href="#" title="close" class="close">x</a>')
	$('.flash a.close').click(function() {
		$(this).parent().fadeOut();
	})
};

/**
 * Will create html flash message
 *
 * @param string text
 * @param string type
 * @return void
 */
$.fn.htmlFlashMessage = function(text, type) {
	if (typeof type == 'undefined') type = 'info';
	$('<div class="flash"></div>').addClass(type).html(text).prependTo(this);
	$.handleHtmlFlashMessage();
};


/**
 * jQuery plugin - loging data to console
 */
jQuery.log = function(message) {
  if(window.console) {
     console.debug(message);
  } else {
     alert(message);
  }
};


/**
 * jQuery plugin - display time left
 * options: year, month, day, hour, minute, second, endtext
 */
jQuery.fn.timeleft = function(settings) {

	var now = new Date();
	var selector = this;
	
	var config = {
		'year':  now.getFullYear(),
		'month': now.getMonth(),
		'day': now.getDate(),
		'hour': 23,
		'minute': 59,
		'second': 59,
		'endtext': 'has finished'
	};
	
	
	if (settings) $.extend(config, settings);
	var end = new Date(config.year, config.month, config.day, config.hour, config.minute, config.second);
	var diff = end - now;
	if(now.getYear() < 1900) yr = now.getYear() + 1900;
	var sec = config.second - now.getSeconds();
	var min = config.minute - now.getMinutes();
	var hr = config.hour - now.getHours();
	//var dy = end.getDate() - now.getDate();
	var dy = parseInt(diff / 3600000 / 24);
	var mnth = end.getMonth() - now.getMonth();
	var yr = end.getFullYear() - yr;
	var daysinmnth = 32 - new Date(now.getYear(),now.getMonth(), 32).getDate();
	
	if (sec < 0) {
		sec = (sec+60)%60;
		min--;
	}
	
	if (min < 0) {
		min = (min+60)%60;
		hr--;	
	}
	
	if (hr < 0) {
		hr = (hr+24)%24;
		dy--;	
	}
	
	if (dy < 0) {
		dy = (dy+daysinmnth)%daysinmnth;
		mnth--;	
	}
	
	if (mnth < 0) {
		mnth = (mnth+12)%12;
		yr--;
	}	
	
	if(now >= end){
		$(selector).html(config.endtext);
		if (typeof timerID != 'undefined') clearTimeout(timerID);
	} else {
		// texts 
		yrtext = (yr == 1) ? ' year ' : ' years ';
		mnthtext = (mnth == 1) ? ' month ' : ' months ';
		dytext = (dy == 1) ? ' day ' : ' days ';
		hrtext = (hr == 1) ? ' hour ' : ' hours ';
		mintext = (min == 1) ? ' minute ' : ' minutes ';
		sectext = (sec == 1) ? ' second ' : ' seconds ';
		

		//$('.days', selector).html(dy + dytext + hr + hrtext + min + mintext + sec + sectext);
		$('.days', selector).html(dy);
		$('.hours', selector).html(hr);
		$('.mins', selector).html(min);
		$('.secs', selector).html(sec);
		timerID = setTimeout(function() { $(selector).timeleft(settings); }, 1000);
	}
}

/**
 * jQuery plugin - handle with deal - purchases
 */
jQuery.dealsLeft = function(url) {

	$.ajax({
		url: url,
		dataType: 'json',
		success: function(data) {
		
			// do fade just on change
			var lastRequest = getLastRequest(data);
			if (lastRequest != null && !compareObject(data, lastRequest)) {
				$('#progressBar').fadeOut('slow', function() {
					$('#progressBar .purchases-count').text(data.purchases + ' sold so far');
					
					if (data.hasFinished == true) {
						text = 'Has Finished';
					} else if (data.dealsIsOn == false) {
						text = data.dealsLeft + ' to go'
					} else {
						text = 'The deal is on!';
					}
					
					$('#progressBar .to-go').text(text);
					$('#progressBar .min-number-of-deals').text(data.minNumberOfDeals + ' (The deal is ON)');
					$("#progressbar").progressbar('destroy').progressbar({ value: data.progress });
					$('#progressBar').fadeIn('slow');
					
					if (data.hasFinished == false) {
						setTimeout(
							function() { 
								jQuery.dealsLeft(url)
							}, 
							5000
						);
					} 
				});
			} else {
				setTimeout(
					function() { 
						jQuery.dealsLeft(url)
					}, 
					5000
				);
			}
		}
	})
}

/**
 * Provide set new request and return previous one
 *
 * @param object newLastRequest
 * @return object
 */
function getLastRequest(newLastRequest) {
    if (typeof getLastRequest.lastRequest == 'undefined') {
        getLastRequest.lastRequest = null;
    }
    var lastRequest = getLastRequest.lastRequest;
    getLastRequest.lastRequest = newLastRequest;
    return lastRequest; 
}

/**
 * Checks if objects are the same
 *
 * @param object o1
 * @param obect o2
 * @return boolean
 */
function compareObject(o1, o2){
	for(var p in o1){
		if(o1[p] !== o2[p]){
			return false;
		}
	}
	for(var p in o2){
		if(o1[p] !== o2[p]){
			return false;
		}
	}
	return true;
}

