var promotionServices = {
	facebookButton: null,
	twitterButton: null,
	appUrl: null,
	sessId: null,
	facebookEnabled: false,
	twitterEnabled: false,
	facebookWindow: null,
	twitterWindow: null,
	windowCloseTimeout: null,
	selectedService: null,
	initialized: false,
	facebookFanPageUrl: null,
	facebookWallPostMessage: null,
	twitterScreenName: null,
	canClick: true,
	logoutAction: false,
	init: function(config) {
		if (config['logout_action'])
			promotionServices.logoutAction = config['logout_action'];
		promotionServices.appUrl = config['app_url'];
		promotionServices.sessId = config['session_id'];
		promotionServices.facebookFanPageUrl = config['facebook_fan_page'];
		promotionServices.twitterScreenName = config['twitter_screen_name'];
		promotionServices.facebookWallPostMessage = config['facebook_wallpost_message'];
		if (config['facebook_enabled'])
		{
			promotionServices.facebookEnabled = true;
			promotionServices.facebook.init()
		}
		if (config['twitter_enabled'])
		{
			promotionServices.twitterEnabled = true;
			promotionServices.twitter.init()
		}
		promotionServices.initialized = true;
	},
	reinit: function() {
		if (promotionServices.initialized)
		{
			if ($('#promotion-twitter-service'))
				$('#promotion-twitter-service').unbind('click');
			if ($('#promotion-facebook-service'))
				$('#promotion-facebook-service').unbind('click');
			$('#promotion-services-container').html('');
			$('#promotion_service_unavailalble_message').hide();
			$('#promotion-services-container').show();
			if (promotionServices.facebookEnabled)
			{
				promotionServices.facebook.init()
			}
			if (promotionServices.twitterEnabled)
			{
				promotionServices.twitter.init()
			}
		}
	},
	facebook: {
		init: function() {
			$('#promotion-facebook-service').bind('click', function(){
				promotionServices.facebook.clickFunction();
				return false;
			});
		},
		clickFunction: function() {
			if (!promotionServices.canClick)
			{
				return false;
			}
			promotionServices.canClick = false;
			promotionServices.setService('facebook');
			promotionServices.startLoading();
			var url = promotionServices.appUrl+'facebook/?sess='+promotionServices.sessId;
			if (promotionServices.logoutAction)
			{
				url += '&action=logout';
			}
			promotionServices.facebookWindow = window.open(url, 'facebookwin', 'width=800,height=400,status=0,directories=0,location=0');
			promotionServices.facebookWindow.focus();
			promotionServices.checkingWindowIsClosed();			
		},
		image: 'facebook.png'
	},
	twitter: {
		init: function() {
			$('#promotion-twitter-service').bind('click', function(){
				promotionServices.twitter.clickFunction();
				return false;
			});
		},
		clickFunction: function() {
			if (!promotionServices.canClick)
			{
				return false;
			}
			promotionServices.canClick = false;
			promotionServices.setService('twitter');
			promotionServices.startLoading();
			promotionServices.twitterWindow = window.open(promotionServices.appUrl+'twitter/?sess='+promotionServices.sessId, 'twitterwin', 'width=800,height=400,status=0,directories=0,location=0');
			promotionServices.twitterWindow.focus();
			promotionServices.checkingWindowIsClosed();			
		},
		image: 'twitter.png'
	},
	setService: function(serviceType) {
		if (promotionServices.windowCloseTimeout != null)
		{
			clearTimeout(promotionServices.windowCloseTimeout);
			promotionServices.windowCloseTimeout = null;
		}
		if (serviceType == 'facebook')
		{
			promotionServices.selectedService = 'facebook';
			if (promotionServices.twitterWindow != null && promotionServices.twitterWindow.closed == false)
			{
				promotionServices.twitterWindow.close();
			}			
		}
		if (serviceType == 'twitter')
		{
			promotionServices.selectedService = 'twitter';
			if (promotionServices.facebookWindow != null && promotionServices.facebookWindow.closed == false)
			{
				promotionServices.facebookWindow.close();
			}
		}
	},
	checkingWindowIsClosed: function() {
		if ((promotionServices.facebookWindow != null && promotionServices.facebookWindow.closed == false) || 
			(promotionServices.twitterWindow != null && promotionServices.twitterWindow.closed == false))
		{
			promotionServices.windowCloseTimeout = setTimeout(promotionServices.checkingWindowIsClosed, 100)
		} 
		else
		{
			clearTimeout(promotionServices.windowCloseTimeout);
			promotionServices.windowCloseTimeout = null;
			promotionServices.servicesCallback();
		}
	},
	startLoading: function() {
		$('#promotion-social-error').hide();
		$('#promotion_service_unavailalble_message').hide();
		$('#promotion-social-loader').show()
	},
	stopLoading: function() {
		$('#promotion-social-loader').hide()
	},
	servicesCallback: function() {
		promotionServices.checkIsLoggedIn()
	},
	checkIsLoggedIn: function() {
		$('#promotion-social-error').hide();
		$.ajax({type: "GET",
			url: window.location.href.replace(/#/gi, ''),
			data: {check_is_logged_in:1,fan_or_follower:1,service:promotionServices.selectedService},
			context: $('#promotion-services-container'),
			dataType: 'json',
			success: function(response) {
				if (response.is_logged == 'true')
        		{
					if (response.is_fan_or_follower == 'true')
	        		{
						if (response.already_used == 'true')
						{
							$('#promotion-services-container').html('');
							$('#promotion-services-container').html(response.already_used_message);
						}
						else
						{
							$('#promotion-services-container').css({'text-align': 'center'});
							$('#promotion-services-container').html('');
							$('#promotion-services-container').html('<div><strong>'+response.promotion_code_info_message+'</strong></div><div class="promoTxt">'+response.promotion_code+'</div>');
						}
						document.onkeydown = "";
						document.onkeyup = "";
						document.onkeyup = function(e){ 	
							if (e == null) { // ie
								keycode = event.keyCode;
							} else { // mozilla
								keycode = e.which;
							}
							if(keycode == 27){ // close
								window.location.reload();
								return false;
							}	
						};
						$("#TB_closeWindowButton").unbind('click');
						$("#TB_closeWindowButton").click(function(){window.location.href = window.location.href; return false;});
						promotionServices.stopLoading();
						promotionServices.canClick = true;
						$('#TB_ajaxContent').height(145);
						$('#promotion-link-get-discount').attr('href', $('#promotion-link-get-discount').attr('href').replace(/height=200/gi, 'height='+($('#TB_ajaxContent').height()+5)));
	        		}
					else
					{
	        			promotionServices.buildPromotionIframe();
	        			promotionServices.stopLoading();
	        			promotionServices.canClick = true;
					}
        		}
				else
				{
					if (typeof(response.logoutBeforeLogin) != "undefined")
					{
						promotionServices.logoutAction = true;
					}
					else
					{
						promotionServices.logoutAction = false;
					}
					$('#promotion-social-error').html(response.message);
					$('#promotion-social-error').show();
					promotionServices.stopLoading();
					promotionServices.canClick = true;
				}
			},
			error: function() {
				promotionServices.stopLoading();
				$('#promotion_service_unavailalble_message').show();
				$('#promotion-services-container').hide();
				promotionServices.canClick = true;
			}
		});
	},
	buildPromotionIframe: function() {
		var promoServicesHeight = $('#promotion-services-container').height()
		$('#promotion-twitter-service').unbind('click');
		$('#promotion-facebook-service').unbind('click');
		$('#promotion-services-container').css({'text-align':'left'});
		if (promotionServices.selectedService == 'facebook')
		{
			var data = new Array();
			data['source'] = promotionServices.appUrl+'facebook/fan/?fan_page='+promotionServices.facebookFanPageUrl;
			var templateEngine = new xtTemplate({
				'template'	: $('#promotion-services-facebook-template').html(),
				'tv'		: data
			})
			var html = templateEngine.parse()
			$('#promotion-services-container').html('');
			$('#promotion-services-container').append(html);
			$('#do_promotion_wallpost').bind('click', promotionServices.doPromotionPost);			
		}
		if (promotionServices.selectedService == 'twitter')
		{
			
			var data = new Array();
			data['source'] = promotionServices.appUrl+'twitter/follow/?sess='+promotionServices.sessId + '&screen_name=' + promotionServices.twitterScreenName;
			var templateEngine = new xtTemplate({
				'template'	: $('#promotion-services-twitter-template').html(),
				'tv'		: data
			})
			var html = templateEngine.parse()
			$('#promotion-services-container').html('');
			$('#promotion-services-container').append(html);
		}
		var newHeight = $('#TB_ajaxContent').height() - promoServicesHeight + $('#promotion-services-container').height();
		if ((window.outerHeight / 2  - 50) < newHeight)
		{
			newHeight = window.outerHeight / 2 - 50;
		}
		$('#TB_ajaxContent').height(newHeight);
		$('#promotion-link-get-discount').attr('href', $('#promotion-link-get-discount').attr('href').replace(/height=180/gi, 'height='+($('#TB_ajaxContent').height()+5))); 
		$('#promotion-get-coupon').bind('click', promotionServices.checkIfFanOrFollower);
	},
	checkIfFanOrFollower: function() {
		if (!promotionServices.canClick)
		{
			return false;
		}
		if (promotionServices.selectedService == 'facebook' || promotionServices.selectedService == 'twitter')
		{
			promotionServices.canClick = false;
			$('#promotion-social-error').hide();
			promotionServices.startLoading();
			$.ajax({type: "GET",
				url: window.location.href.replace(/#/gi, ''),
				data: "get_coupon&service="+promotionServices.selectedService,
				context: $('#promotion-services-container'),
				dataType: 'json',
				success: function(response) {
					if (response.is_fan_or_follower == 'true')
	        		{
						$('#promotion-services-container').css({'text-align': 'center'});
						$('#promotion-services-container').html('');
						$('#promotion-services-container').html('<div><strong>'+response.promotion_code_info_message+'</strong></div><div class="promoTxt">'+response.promotion_code+'</div>');
						document.onkeydown = "";
						document.onkeyup = "";
						document.onkeyup = function(e){ 	
							if (e == null) { // ie
								keycode = event.keyCode;
							} else { // mozilla
								keycode = e.which;
							}
							if(keycode == 27){ // close
								window.location.reload();
								return false;
							}	
						};
						$("#TB_closeWindowButton").unbind('click');
						$("#TB_closeWindowButton").click(function(){window.location.href = window.location.href; return false;});
						promotionServices.stopLoading();
						promotionServices.canClick = true;
						$('#TB_ajaxContent').height(145);
						$('#promotion-link-get-discount').attr('href', $('#promotion-link-get-discount').attr('href').replace(/height=200/gi, 'height='+($('#TB_ajaxContent').height()+5))); 
	        		}
					else
					{
						promotionServices.stopLoading();
						$('#promotion-social-error').html(response.message);
						$('#promotion-social-error').show();
						promotionServices.canClick = true;
					}
				},
				error: function() {
					promotionServices.stopLoading();
					$('#promotion_service_unavailalble_message').show();
					$('#promotion-services-container').hide();
					promotionServices.canClick = true;
				}
			})
		}
		return false
	},
	doPromotionPost: function () {
		if (!promotionServices.canClick)
		{
			return false;
		}
		promotionServices.canClick = false;
		$('#promotion-social-error').hide();
		promotionServices.startLoading();
		$.ajax({type: "GET",
			url: window.location.href.replace(/#/gi, ''),
			data: "promotion_post",
			context: $('#promotion-services-container'),
			dataType: 'json',
			success: function(response) {
				if (response.is_fan_or_follower == 'true')
        		{
					$('#promotion-services-container').css({'text-align': 'center'});
					$('#promotion-services-container').html('');
					$('#promotion-services-container').html('<div><strong>'+response.promotion_code_info_message+'</strong></div><div class="promoTxt">'+response.promotion_code+'</div>');
					$('#TB_ajaxContent').height(145);
					document.onkeydown = "";
					document.onkeyup = "";
					document.onkeyup = function(e){ 	
						if (e == null) { // ie
							keycode = event.keyCode;
						} else { // mozilla
							keycode = e.which;
						}
						if(keycode == 27){ // close
							window.location.reload();
							return false;
						}	
					};
					$("#TB_closeWindowButton").unbind('click');
					$("#TB_closeWindowButton").click(function(){window.location.href = window.location.href; return false;});	
					promotionServices.stopLoading();
					promotionServices.canClick = true;
        		}
				else
				{
					promotionServices.stopLoading();
					$('#promotion-social-error').html(response.message);
					$('#promotion-social-error').show();
					promotionServices.canClick = true;
				}
			},
			error: function() {
				promotionServices.stopLoading();
				$('#promotion_service_unavailalble_message').show();
				$('#promotion-services-container').hide();
				promotionServices.canClick = true;
			}
		})
	}
}
