var ajax_urls = {
			'single_campaign':'/index.php/frontend/campaigns_ajax/campaignDetails/',
			'multiple_campaigns':'/index.php/frontend/campaigns_ajax/multipleCampaignDetails/'
};

var registrationInProgress = false;

function bind(scope, fn) {
    return function () {
        return fn.apply(scope, arguments);
    };
}



function Campaign(id, data) {
	this.updateDataFromServer = function (data) {
		this.data = data;
		this.secondsLeftN = data.secondsLeft;
		var dom = $('#content_mid_bottom_bar2');
		//shows progress bar
		
		if (parseInt(data.secondsLeft) == 0) {
			//time is over
			$('a.buy-link').click(function () {return false;});
			if ((parseInt(data.couponsBought)>=parseInt(data.couponsMin))) {
				//campaign was successful
				dom.html('<p class="text">Campaign was successful!</p>');
			} else {
				//campaign failed
				dom.html('<p class="text">Too late!<br/>The deal has ended!</p>');
			}
		} else { 
			//campaign in progress
			dom.html('<p class="text">Campaign in progress</p>');
			
			if ((parseInt(data.couponsBought)<parseInt(data.couponsMin))) {
				//min bought coupon count not reached yet
				dom.html('<div class="cross"></div><p class="text">'+data.couponsBought+' Gekauft</p><div class="bought_bar center"></div><p class="text">noch <em>'+(parseInt(data.couponsMin)-parseInt(data.couponsBought))+'</em> Käufer gebraucht</p>');
				var bar = dom.find('div.bought_bar');
				bar.progressbar({value:Math.round((parseInt(data.couponsBought)/parseInt(data.couponsMin))*100)});
			} else {
				//min bought coupon count reached
				if (parseInt(data.couponsMax) == 0) {
					//no limit
					dom.html(' <strong style="font-size: 18px;"><br /><br />Bereits '+ data.couponsBought + ' Verkauft</strong><br /><br /> <span style="padding: 0 0 0 20px; font-size: 16px; font-weight: bold;">Deal findet statt! <img src="http://www.couponsdeal.de/images/deal_on.png" width:="20" height="20"> <br /><br /></span>');
				} else {
					//is limit
					var couponsLeft = parseInt(data.couponsMax)-parseInt(data.couponsBought);
					if (couponsLeft <= 0) {
						//limit reached
						dom.html('<p class="text">Deal war erfolgreich!</p>');
					} else {
						//limit not reached yet
						dom.html('<strong style="font-size: 18px;"><br /><br />Bereits '+ data.couponsBought + ' Verkauft</strong><br /> <span style="padding-top: 10px; font-size: 14px; font-weight: bold; color: #555;">Noch '+ couponsLeft +' &uuml;brig</span> <br /> <span style="padding: 5px 0 0 20px; font-size: 16px; font-weight: bold;">Deal findet statt! <img src="http://www.couponsdeal.de/images/deal_on.png" width:="20" height="20"> <br /><br /></span>');
					}
				}			
			}
		}
	};
	//methods
	this.updateTimer = function (time) {
		this.secondsLeftN = this.secondsLeftN - (time-this.previousTime);
		
		if (this.secondsLeftN>0) {
			var seconds = Math.round(this.secondsLeftN);
			var days = Math.floor(seconds/86400);
			var hours = Math.floor((seconds-days*86400)/3600);
			var minutes = Math.floor((seconds % 3600)/60);
			seconds = Math.round((seconds % 3600) % 60);
		} else {
			seconds = days = hours = minutes = 0;
		}
		this.daysLeft.innerHTML = days;
		this.hoursLeft.innerHTML = hours;
		this.minutesLeft.innerHTML = minutes;
        this.secondsLeft.innerHTML = seconds;
		this.previousTime = time;
	};
	
	this.id = id;
	this.updateDataFromServer(data);
	this.timeLeftTable = $('div#time_left_table_'+id);
	this.daysLeft = this.timeLeftTable.find('span.days')[0];
	this.hoursLeft = this.timeLeftTable.find('span.hours')[0];
	this.minutesLeft = this.timeLeftTable.find('span.minutes')[0];
    this.secondsLeft = this.timeLeftTable.find('span.seconds')[0];
	var time = new Date().getTime()/1000;
	this.previousTime = time;
	this.updateTimer(time);
}

function CampaignsUpdater() {
	this.campaigns = new Array();
	
	this.fetchData = function () {
		this.campaignIds = campaignIds;
		
		$.getJSON(ajax_urls['multiple_campaigns']+this.campaignIds+'?r='+Math.random(),null, bind(this, function (data) {
			forEach(data, function (item) {
				id = item.id;
				if (typeof(this.campaigns[id])=='undefined') {
					this.campaigns[id] = new Campaign(id, item);
				} else {
					this.campaigns[id].updateDataFromServer(item);
				}
			}, this);
		}));
		
		setTimeout(bind(this, this.fetchData), 10000);
	};
	
	this.timer = function () {
		var time = new Date().getTime()/1000;
		forEach(this.campaigns, function (c) {
			c.updateTimer(time);
		}, this);
		
		setTimeout(bind(this, this.timer), 1000);
	};
	
	this.timer();
	this.fetchData();
}

$(function () {
	if (typeof(campaignIds)!='undefined')
		var cu = new CampaignsUpdater();
});

function check_spam() {
	document.comment_form.tmp.value=document.comment_form.first_name.value;
	document.comment_form.submit();
}

/**
 * Prevents double clicking submit button by saving the state of request in registrationInProgress global variable
 * 
 */
function registerFormClick() {
	if (!registrationInProgress) {
		registrationInProgress = true;
		$('#register_form input[name=tmp]').attr('value', $('#register_form input[name=first_name]').attr('value'));
		return true;
	}
	return false;
}
