var _coupons_timer_id;
var _coupons_timers;

$(document).ready(function() {
	$('#about a').dropdown({
		url: 'ConstantContact/paypal/about.php',
		type: 'ajax'
	});

	$('#rewards a').dropdown({
		url: 'ConstantContact/paypal/rewards.php',
		type: 'iframe',
		width: 640,
		height: 480
	});

	$('#coupons a').dropdown({
		url: 'ConstantContact/paypal/coupons.php',
		type: 'ajax',
		width: 640
	});

	$('#community a').dropdown({
		url: 'community.htm',
		type: 'iframe',
		width: 400,
		height: 340
	});

	$('#login a').dropdown({
		url: 'login.php',
		type: 'ajax',
		onshow: function() {
			$('#username').focus();

			FB.XFBML.Host.parseDomTree();

			$('#form1').submit(function() {
				$(this).ajaxSubmit({
					dataType: 'json',
					success: function(data) {
						if (data.result == 'success') {
							if (data.show_fb_assoc) {
								$('#login a').hideDropdown();
								show_connect_to_fb_popup();
							} else {
								location.href = 'index.php';
							}
						} else {
							$('#form-errors').html(data.errors);
						}
					}
				});

				return false;
			});
		}
	});

	$('#logout a').click(function() {
		location.href = 'login.php?action=logout';
	});

	$('#fblogout a').click(function() {
		FB.Connect.logoutAndRedirect('login.php?action=logout');
	});

	$('.more-offers a').dropdown({
		type: 'html',
		width: '300px',
		onshow: function() {
			$('#smoc ul').clone(true).appendTo('.dropdown-container');
		}
	});

	$('#form_add_contact').submit(function() {
		$(this).ajaxSubmit({
			success: function(data) {
				alert(data);
			}
		});

		return false;
	});

	$('#coda-slider-1').codaSlider({
		dynamicArrows: false,
		dynamicTabs: false,
		autoHeight: false,
		onSlide: function(panel) {
			$('.more-offers a').hideDropdown();
		}
	});

	var d = $('.survey-info').height() - 40;
	$('.survey-info').css('bottom', '-' + d + 'px').show();
	$('.survey-module .wrap').hover(
		function() {
			$('.survey-info').animate({'bottom': '+=' + d + 'px'}, 200);
		},
		function() {
			$('.survey-info').animate({'bottom': '-=' + d + 'px'}, 200);
		}
	);

	// iframes fix
	var panelCount = $(".panel").size();
	for (var i = 1; i <= panelCount; i++) {
		$('#panel-wrapper-' + i).append('<iframe src="' + offerwall_urls[i - 1] + '" id="owi' + offerwall_ids[i - 1] + '" frameborder="0" width="100%" height="1750" scrolling="auto"></iframe>');
	}
});

function show_popup(b) {
	var a = {
		url: false,
		onshow: null,
		onclose: null,
		position: null
	};

	close_popup();
	$('*').hideDropdown();

	$.extend(a, b);

	if (!a.url) {
		return;
	}

	$.ajax({
		type: 'GET',
		url: a.url,
		success: function(data) {
			$.modal(data, {
				opacity: 71,
				escClose: false,
				onShow: a.onshow,
				onClose: a.onclose,
				position: a.position,
				maxHeight: 550
			});
		}
	});
}

function close_popup() {
	$.modal.close();
}

function show_login_popup() {
	close_signup_popup(false);
	close_popup();

	$('#login a').click();
}

function show_signup_popup(type) {
	$('#signup-form')[0].reset();

	$('#adv-popup').hide();
	$('#lp-popup').show();
	$('#lp-container').show();
	center_signup_popup();
	$(window).resize(function() {
		center_signup_popup();
	});

	$('#signup-form').submit(function() {
		$(this).ajaxSubmit({
			dataType: 'json',
			success: function(data) {
				if (data.result == 'success') {
					_gaq.push(['_trackEvent', 'Registration', 'Completed']);
					setTimeout(function() {	// timeout for ga
						location.href = 'index.php?action=show_overview';
					}, 300);
				} else {
					$('#signup-form-errors').html(data.errors);
				}
			}
		});

		return false;
	});

	var typename;
	switch (type) {
		case 0:typename = 'default';break;
		case 1:typename = 'success';break;
		case 2:typename = 'failed';break;
		case 3:typename = 'over limit';break;
		case 4:typename = 'no longer available';break;
		case 5:typename = 'wrong place';break;
	}
	_gaq.push(['_trackEvent', 'Registration', 'Open', typename]);
}

function close_signup_popup(track_ga) {
	$(window).unbind('resize');
	$('#lp-container').hide();

	if (track_ga) {
		_gaq.push(['_trackEvent', 'Registration', 'Close']);
	}

	if (show_pc) {
		show_popup_campaign_popup(5357);
	}
}

function center_signup_popup() {
	var top = ($(window).height() - $('.bubble_wide').height()) / 2;
	var left = ($(window).width() - $('.bubble_wide').width()) / 2;

	if (top < 20) {
		top = 20;
	}

	$('.bubble_wide')
		.css('top', top + 'px')
		.css('left', left + 'px');
}

function show_connect_to_fb_popup() {
	show_popup({
		url: 'facebook_prompt.php',
		onshow: function() {
			FB.XFBML.Host.parseDomTree();
		},
		onclose: function() {
			if ($('#dont_show_fbconnect:checked').val() != undefined) {
				$.get('fb_dont_show_prompt.php', function(data) {
					location.href = 'index.php';
				});
			} else {
				location.href = 'index.php';
			}
		}
	});
}

function show_unsubscribe_popup(userid, mid) {
	show_popup({
		url: 'unsubscribe.php?id=' + userid + '&mid=' + mid,
		onshow: function() {
			$('#form1').submit(function() {
				$(this).ajaxSubmit({
					dataType: 'json',
					success: function(data) {
						$('#form_block').hide();
						$('#ty_block').show();

						setTimeout(function() {
							location.href = 'index.php';
						}, 5000);
					}
				});

				return false;
			});
		}
	});
}

function show_wb_popup(a) {
	show_popup({
		url: 'welcome_back.php',
		onclose: function() {
			close_popup();
			if (!a) {
				show_signup_popup(0, 'CD5357', null);
			}
		}
	});
}

function show_forgot_password_popup() {
	show_popup({
		url: 'forgot_password.php',
		onshow: function() {
			$('#email').focus();

			$('#form1').submit(function() {
				$(this).ajaxSubmit({
					dataType: 'json',
					success: function(data) {
						if (data.result == 'success') {
							$('.forg_pass .graybox').html(data.content);
						} else {
							$('#form-errors').html(data.errors);
						}
					}
				});

				return false;
			});
		}
	});
}

function show_change_password_popup(userid, mid) {
	show_popup({
		url: 'change_password.php?id=' + userid + '&mid=' + mid,
		onshow: function() {
			$('#form1').submit(function() {
				$(this).ajaxSubmit({
					dataType: 'json',
					success: function(data) {
						if (data.result == 'success') {
							show_login_popup();
						} else {
							$('#form-errors').html(data.errors);
						}
					}
				});

				return false;
			});
		}
	});
}

function fb_login_button() {
	FB.Connect.requireSession(function() {
		$.getJSON('check_fb_associated.php', function(data) {
			if (data.valid) {
				location.href = 'login.php?action=fb_login';
			} else {
				alert(data.message);
			}
		});
	});
}

function associate_facebook() {
	$.getJSON('fb_associate.php', function(data) {
		if (data.valid) {
			location.href = 'index.php';
		} else {
			alert(data.message);
		}
	});
}

function unsubscribe() {
	if ($('#chkb_confirm').is(':checked')) {
		$('#form1').submit();
	}
}

function show_privacy() {
	show_popup({
		url: 'privacy.php',
		position: [20],
		onshow: on_pt_show
	});
}

function show_terms() {
	show_popup({
		url: 'terms.php',
		position: [20],
		onshow: on_pt_show
	});
}

function show_program_overview_popup(is_hmpw) {
	var cs = false;

	show_popup({
		url: 'program_overview.php?is_hmpw=' + (is_hmpw ? '1' : '0'),
		onshow: function() {
			$('#coda-slider-2').codaSlider({
				dynamicArrows: false,
				dynamicTabs: false,
				autoHeight: false,
				continuous: false,
				slideEaseDuration: 500,
				onSlide: function(panel) {
					$('.top_header2').text(secondaryTitles[panel - 1]);
					$('.slider-tabs li').removeClass('current');
					$('.slider-tabs li.tab' + panel).addClass('current');
					if (panel == 5 && !last && !is_hmpw && !cs) {		// bad
						$.get('program_overview.php?completed=1', function(data) {
							cs = true;
						});
					}

					if (panel == 5 && last) {
						if (is_hmpw) {
							close_popup();
						} else {
							show_connect_to_fb_popup();
						}
					}

					last = panel == 5;
				}
			});

			$('#tab1-lnk-no').click(function () {
				if (is_hmpw) {
					close_popup();
				} else {
					show_connect_to_fb_popup();
				}
			});
		}
	});
}

function on_pt_show() {
	$('.text_container').height($(window).height() - 50 - $('.wp_top').height() - $('.wp_bottom').height());

	$(window).resize(function() {
		$('.text_container').height($(window).height() - 50 - $('.wp_top').height() - $('.wp_bottom').height());
	});
}

function show_validate_paypal_popup() {
	show_popup({
		url: 'validate_paypal.php',
		onshow: function() {
			$('#email').focus();

			$('#form1').submit(function() {
				$(this).ajaxSubmit({
					dataType: 'json',
					success: function(data) {
						if (data.result == 'success') {
							$('.validate_paypal .graybox').html(data.content);
						} else {
							$('#form-errors').html(data.errors);
						}
					}
				});

				return false;
			});
		}
	});
}

function showCoupons(page, category) {
	var url = 'ConstantContact/paypal/coupons_list.php?pageID=' + page;

	if (category) {
		url += '&category=' + category;
	}

	$('#deals_container').load(url);
}

function showEmails(page) {
	var url = 'user_dashboard/emails_list.php?pageID=' + page;

	$('#emails_container').load(url);
}

function showOffers(page) {
	var url = 'user_dashboard/offer_history_list.php?pageID=' + page;

	$('#offers_container').load(url);
}

function showPayments(page) {
	var url = 'user_dashboard/payment_history_list.php?pageID=' + page;

	$('#payments_container').load(url);
}

function calculateTime(seconds) {
	var time = '';
	var hours = 0;
	var minutes = 0;
	var original_seconds = seconds;

	if (seconds > 86400) {
		time = Math.floor(seconds / 86400) + ' days';
	} else {
		if (seconds >= 3600) {
			hours = Math.floor(seconds / 3600);
			seconds = Math.floor(seconds - (3600 * hours));
		}
		if (seconds >= 60) {
			minutes = Math.floor(seconds / 60);
			seconds = Math.floor(seconds - (60 * minutes));
		}

		time = hours + ' hours ' + minutes + ' min ' + seconds + ' s';

		if (original_seconds == 0) {
			time = 'Expired';
		}
	}

	return time;
}

function setupTimers() {
	clearInterval(_coupons_timer_id);
	_coupons_timer_id = setInterval(function() {
		updateTimers();
	}, 1000);

	updateTimers();
}

function updateTimers() {
	for (var item in _coupons_timers) {
		if (_coupons_timers[item] > 0 && _coupons_timers[item] < 31536000 /* seconds in year */) {
			_coupons_timers[item]--;
			$('#timer_' + item).html(calculateTime(_coupons_timers[item]));
		}
	}
}

function track_dt_click(type, label, url) {
	_gaq.push(['_trackEvent', type, 'Click', label]);
	
	setTimeout(function() {
		var newWindow = window.open(url, '_blank');
		
		if(newWindow) {
			newWindow.focus();
		} else {			
			lang = 'en';
			if (navigator.userLanguage) // Explorer
				lang = navigator.userLanguage;
			else if (navigator.language) // FF
				lang = navigator.language;
			else
				lang = "en";
			switch (lang) {				
				case 'ru':
					message = 'Чтото не позволяет Pointdoubler открыть новое окно. Пожалуйста, проверьте настройки браузера и попробуйте еще раз.';
					break;
				case 'zh':
					message = '東西是無法開啟一個新窗口PointDoubler。請檢查您瀏覽器的設置，然後再試一次。';
					break;
				case 'es':
					message = 'Algo impide PointDoubler de abrir una nueva ventana. Por favor, compruebe la configuración del navegador y vuelva a intentarlo.';
					break;
				case 'ja':
					message = '何かが新しいウィンドウを開いてからPointDoublerを防いでいます。ブラウザの設定を確認し、もう一度やり直してください。';
					break;
				case 'fr':
					message = "Quelque chose empêche PointDoubler d'ouvrir une nouvelle fenêtre. S'il vous plaît vérifier vos paramètres de navigateur et essayez de nouveau.";
					break;
				case 'pt':
					message = 'Algo está impedindo PointDoubler de abrir uma nova janela. Verifique as configurações do seu navegador e tente novamente.';
					break;
				case 'de':
					message = 'Etwas ist zu verhindern PointDoubler aus Öffnen eines neuen Fensters. Bitte überprüfen Sie Ihre Browser-Einstellungen und versuche es erneut.';
					break;
				case 'ar':
					message = 'شيء يمنع PointDoubler من فتح نافذة جديدة. يرجى التحقق من إعدادات المتصفح والمحاولة مرة أخرى.';
					break;
				case 'ko':
					message = '무언가가 새 창을 열지 PointDoubler되지 않습니다. 브라우저 설정을 확인하고 다시 시도해보십시오.';
					break;
				default:
					message = "Something is preventing PointDoubler from opening a new window. Please check your browser settings and try again.";
					break;
			}  

			alert(message);

		}
	}, 300);

	return false;
}

function show_popup_campaign_popup(affiliate_id) {
	show_popup({
		url: 'popup_campaign.php?affiliate_id=' + affiliate_id,
		position: [40]
	});
}

function show_user_dashboard_popup(obj) {
	show_popup({
		url: 'user_dashboard',
		position: [100],
		onshow: function() {
			$('#ud_menu a').click(function () {
				$('#ud_menu a').removeClass('active');
				$(this).addClass('active');

				var page = $(this).attr('id').substr(8);
				$.get('user_dashboard/' + page + '.php', function (data) {
					$('#ud-content-continer').html(data);

					FB.XFBML.Host.parseDomTree();

					switch (page) {
						case 'myaccount':
							$('#form1').submit(function() {
								$(this).ajaxSubmit({
									dataType: 'json',
									success: function(data) {
										if (data.result == 'success') {
											$('#form-errors').html('');
										} else {
											$('#form-errors').html(data.errors);
										}
									}
								});

								return false;
							});
							break;

						case 'emails':
							$('#form1').submit(function() {
								$(this).ajaxSubmit({
									dataType: 'json',
									success: function(data) {}
								});

								return false;
							});
							break;
					}

				});
			});
			if(obj) {
				$(obj).click();
			} else {
				$('#ud-menu-myaccount').click();
			}
		}
	});
}

function show_adv_popup() {
	$('#lp-popup').hide();
	$('#adv-popup').show();
}

function set_step_shown(user_id) {	
	$.ajax({
		type: 'GET',
		url: 'steps.php?action=set_step_shown&user_id=' + user_id,
		success: function(data) {			
		}
	});
}
