// bbls object is being created in winners_{lang}.js

$(document).ready(function(){
	//$("#opacity_curtain").css('height', $(document).height());
	// chack 800x600 resolution
	if (screen.height < 768){
		$('#wrapper').css({width : 770});
		$('#mainGame').css({width : 510});
		$('object#bubblesGame2010').attr({width : 510, height : 530});
		$('object#bubblesGame2010 embed').attr({width : 510, height : 530});
		$('#mainContent').css({width : 520});
		$('li#facebook').hide();
		$('#footer #bottom_links li').css('padding-right', '27px');
		$('#mainContent #mainGame').css('height', '661px');
		$('#footer #bottom_links').css('background', 'url("../images/new_design/bottom_links_bg_small.png") no-repeat scroll right 0 transparent');
	}

	// open popup window
	//login screen
	$('a#reg_allready').live('click', function(){
		$.ajax({
			type: "POST",
			url: "index.php",
			data: {
			   ajax: 1,
			   no_game: 1,
			   signed_request: signed_request,
			   members_login: 1
			},
			dataType: "json",
			success: parse_ajax
		});
		return false;
	});

	//banner
	$('#banner_start_game').live('click', function(){
		$.ajax({
			type: "POST",
			url: "index.php",
			data: {
			   ajax: 1,
			   signed_request: signed_request,
			   no_game: 1,
			   click_from: "banner"
			},
			dataType: "json",
			success: parse_ajax
		});
		return false;
	});

	//logo
	$('#logo').live('click', function(){
		$.ajax({
			type: "POST",
			url: "index.php",
			data: {
			   ajax: 1,
			   signed_request: signed_request,
			   no_game: 1,
			   click_from: "logo"
			},
			dataType: "json",
			success: parse_ajax
		});
		return false;
	});

	// open mpay iframe
	$("#pay_by_mpay a").live('click', function(){
		$("#cellcom-footer").addClass("cellcom_in_mpay"); // feet cellcom to the mpay iframe
		$('#mpay').show();

		if ($("#submittype").val() == "purchasecode")
		{
			analyticsVirtualPage('purch_mpay-details');
		}
		else
		{
			sendFlowEventToGoogle('reg_mpay-details', $("input#banner_stat").val());
		}

		var url = $('#mpay input').val();
		$('#mpay iframe').attr('src', url);
		return false;
	});

	// init cellcom
	$("a[id^=showhide_menu_]").live('click', function(){
		$("div[id^=showhide_menu_][id!=" + this.id + "_div]").hide();
		$("#" + this.id + "_div").toggle($.hide, $.show);
		return false;
	});

	//init winners roll
	for (i=0 ; i < bbls.winners_data.length ; i++){
		var div = $('<div />');
		var img = $('<img />');
		var span = $('<span />');

		if (!(i >= 0 && i <= 3)){
			div.hide();
		}

		img.attr('src', bbls.path + "images/winners/" + bbls.winners_data[i][0]);
		span.text(bbls.winners_data[i][1]);

		div.append(img);
		div.append(span);
		

		$('ul#winners li').eq(i % 4).append(div);
	}

	//setTimeout(function(){
		$('ul#winners').find('li').show();//.fadeIn();
	//}, 1000);

	setRollImagesInterval(); //Start RollImages





	// ajax
	$('div.close_btn').live('click', function(){
		closePopUp();
	});

	$('#mpay_close_btn').live('click', function(){
		$("#mpay_finish").hide();
	});


	$('#faq').live('click', function(){
		openLinkInNewCenteredWindow('faq.php', 710, 500);
		return false;
	});
	$('#terms').live('click', function(){
		openLinkInNewCenteredWindow('terms.php', 710, 500);
	return false;
	});

	$('#log_out_user').live('click',function(e){
		if ( !confirm(question_approve_request) ) {
			e.preventDefault();
		}
	});
	$('#forget_password_link').live('click', function(){
		$.ajax({
			async: true,
			type: "POST",
			url: "index.php",
			data: {
			   ajax: 1,
			   no_game: 1,
			   forgetpassword: 1
			},
			dataType: "json",
			success: parse_ajax
		});
		return false;
	});

	$('#buy_credits').live('click', function(){
		$.ajax({
			async: true,
			type: "POST",
			url: "index.php",
			data: {
			   ajax: 1,
			   no_game: 1,
			   signed_request: signed_request,
			   buy_now: 1
			},
			dataType: "json",
			success: parse_ajax
		});
		return false;
	});
	$("#language_selector").live('change',function(){
		var answer = confirm(js_change_language);
    	if (answer){
    		window.location = $("#language_selector").val();
        }
	});

	$('#popupContact div.close_btn').live('click', function(){
		$("#opacity_curtain, #popupContact").hide();
		initPopUp();
	});

	$("#contact").live('click',function(e){
		$("#opacity_curtain, #popupContact").show();
		return false;
	});

	var handler = function(e){
		if ((e.which > 31 && e.which < 48) || e.which > 57)
		{
			e.preventDefault();
		}
	};
	var handler2 = handler;
	handler.obj = $("#contact_phone");
	handler2.obj = $("#contact_phone2");
	$("#contact_phone").live('keypress',handler);
	$("#contact_phone2").live('keypress',handler2);
	$("#send_contact_email").live('click',function(){
		var contact = "contact_";
		data1 = {};
		data1.ajax = 1;
		data1.app_language = $("#app_language").val();
		data1.data = {
				name : $("#"+contact+"name").val(),
				subject : $("#"+contact+"subject").val(),
				email : $("#"+contact+"email").val(),
				message : $("#"+contact+"msg").val(),
				phone : $("#"+contact+"phone").val(),
				phone2 : $("#"+contact+"phone2").val()
		};
		if ( ! validateEmail(data1.data.email) ) {
			alert($("#noContact").val());
			return 1;
		}
		if ( data1.data.message.length == 0 ) {
			alert($("#js_empty_petition").val());
			return 1;
		}
		if ( data1.data.name.length == 0 ) {
			alert($("#js_empty_name").val());
			return 1;
		}
		if ( data1.data.phone.length != 10 ) {
			alert($("#js_phone_length").val());
			return 1;
		}
		$.ajax({
			async: true,
			type: "POST",
			url: "send_mail.php",
			data: (data1),
			dataType: "json",
			success: function(){
				$("#popupContact").hide();
				$("#opacity_curtain").hide();
			}
		 });
	});
	$('#main_screen').delegate('form', 'submit', function(){
		switch ($('#submittype').val()){
			case 'phone':
				var joined_phone = validate(this);
				if (joined_phone === false){ // validations_step1.js
					return false;
				}
				$.ajax({
					async: true,
					type: "POST",
					url: "index.php",
					data: {
					   ajax: 1,
					   no_game: 1,
					   phone: joined_phone,
					   username: $("#username").val(),
					   banner_pressed : $("#banner_stat").val(),
					   userdoc: $("#userdoc").val()
					},
					dataType: "json",
					success: parse_ajax
				 });
				 break;
			case 'pin':
				if (!validatePincode(this)){ // validations_step2.js
					 return false;
				}
				$.ajax({
					async: true,
					type: "POST",
					url: "index.php",
					data: {
					   ajax: 1,
					   no_game: 1,
					   phone: $("#phone").val(),
					   pid: $("#pid").val(),
					   pin: $("#pin").val(),
					   is_show_success: $("#is_show_success").val(),
					   affiliate: affiliate,
					   banner_pressed : $("#banner_stat").val(),
					   userdoc: $("#userdoc").val()
					},
					dataType: "json",
					success: function(data){
						parse_ajax(data);
					}
				 });
				 break;
			case 'recover_password':
				var joined_phone = validate(this);
				if (joined_phone === false){ // validations_step1.js
					return false;
				}
				$.ajax({
					async: true,
					type: "POST",
					url: "index.php",
					data: {
					   ajax: 1,
					   no_game: 1,
					   recover_phone: joined_phone
					},
					dataType: "json",
					success: function(data){
						parse_ajax(data);
					}
				 });
				 break;
			case 'password':
				var joined_phone = validate(this);
				if (joined_phone === false){ // validations_step1.js
					return false;
				}
				$.ajax({
					async: true,
					type: "POST",
					url: "index.php",
					data: {
					   ajax: 1,
					   no_game: 1,
					   login_phone: joined_phone,
					   password: $("#password").val(),
					   banner_pressed : $("#banner_stat").val()
					},
					dataType: "json",
					success: parse_ajax
				 });
				break;

			case 'offerpurchasecode':
				$.ajax({
					async: true,
					type: "POST",
					url: "index.php",
					data: {
					   ajax: 1,
					   no_game: 1,
					   signed_request: signed_request,
					   buy_now: 1,
					   banner_pressed : $("#banner_stat").val()
					},
					dataType: "json",
					success: parse_ajax
				});
				break;

			case 'purchasecode':
				$.ajax({
					async: true,
					type: "POST",
					url: "index.php",
					data: {
					   ajax: 1,
					   no_game: 1,
					   buy_now_submit: 1,
					   signed_request: signed_request,
					   purchase_code: $("#password").val(),
					   is_show_success: $("#is_show_success").val(),
					   banner_pressed : $("#banner_stat").val()
					},
					dataType: "json",
					success: parse_ajax
				 });
				break;

			case 'setusername':
				$.ajax({
					async: true,
					type: "POST",
					url: "index.php",
					data: {
					   ajax: 1,
					   no_game: 1,
					   setusername: $("#username").val(),
					   signed_request: signed_request,
					   banner_pressed : $("#banner_stat").val()
					},
					dataType: "json",
					success: parse_ajax
				 });
				break;

			case 'userpassword':
				$.ajax({
					async: true,
					type: "POST",
					url: "index.php",
					data: {
					   ajax: 1,
					   no_game: 1,
					   userpassword: $("#userpassword").val(),
					   userpasswordconfirm: $("#userpasswordconfirm").val(),
					   signed_request: signed_request,
					   banner_pressed : $("#banner_stat").val()
					},
					dataType: "json",
					success: parse_ajax
				 });
				break;

			case 'play':
				closePopUp();
				$("#banner_stat").val(0);
				break;
		}
	});

	document.write = function(string) {
		$("#pixelHolder").append(string);
	}

	initPopUp();

	setInterval("keepAlive()", 40000);
});

function validateEmail(elementValue){
   var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
   return emailPattern.test(elementValue);
}

function parse_ajax(data){
	if (data.phonepopup != null){
		$("#phonepopup").html(data.phonepopup);
		if ($("#submittype").val() == 'getpaidgame' || $("#submittype").val() == 'userpassword'){
			signed_request = data.query.signed_request;
		}
		initPopUp(data.query.is_show_success);
		if ($('#submittype').val() == 'phone' || $('#submittype').val() == 'password'){
			openPopUp();
		}
	}
	if ( data.mainGame != null && data.mainGame.search("^[\t\r\n ]*$") < 0){
		$("#mainGame").html(data.mainGame);
	}

	if (data.errorpopup != null){
		alert($.trim(data.errorpopup));
	}
	parse_alive(data);
}

function parse_alive(data){
	if (data.time_remain != null){
		$("#time_remain").html(data.time_remain);
	}
	if (data.login != null){
		$("#login").html(data.login);
	}
	if ( data.logobar != null ){
		$("#logobar").html(data.logobar);
	}
	if ( data.banner != null ){
		$("#banner").html(data.banner);
	}
	if (data.popupmessage != null){
		$("#popupmessage").html(data.popupmessage);
	}
	if ($("#popuplevel").val() > parse_alive.popup_level) {
		parse_alive.popup_level = $("#popuplevel").val();
		if ($("#main_screen:visible").length == 0){
			$.ajax({
				type: "POST",
				url: "index.php",
				data: {
				   ajax: 1,
				   signed_request: signed_request,
				   no_game: 1,
				   click_from: "score_popup"
				},
				dataType: "json",
				success: parse_ajax
			});
		}
	}
}
parse_alive.popup_level = 0;

function initPopUp(is_show_success){
	switch ($("#analytics_message").val()){
		case "homepage":
			analyticsVirtualPage("homepage");
			break;

		case "insert-phone_banner":
			sendFlowEventToGoogle("insert-phone", true);
			break;

		case "insert-phone_popup":
			sendFlowEventToGoogle("insert-phone", false);
			break;

		case 'reg_pincode-link':
			sendFlowEventToGoogle('reg_pincode-link', $("input#banner_stat").val()); // case 1
			break;

		case 'reg_mpay-done':
			sendFlowEventToGoogle('reg_mpay-done', $("input#banner_stat").val()); // case 8, if (isset($_GET['is_show_success']))
			break;

		case 'reg_cell-done':
			sendFlowEventToGoogle('reg_cell-done', $("input#banner_stat").val()); // case 8,  if (!isset($_GET['is_show_success']))
			break;



		case 'purch_no-creadits-left':
			analyticsVirtualPage('purch_no-creadits-left'); // case 4
			break;

		case 'purch_pincode-link':
			analyticsVirtualPage('purch_pincode-link'); // case 5
			break;

		case 'purch_mpay-details':
			analyticsVirtualPage('purch_mpay-details'); // not set yet
			break;

		case 'purch_mpay-done':
			analyticsVirtualPage('purch_mpay-done'); // not set yet
			analyticsVirtualPage('purch_done_gen'); // not set yet
			break;

		case 'purch_cell-done':
			analyticsVirtualPage('purch_cell-done'); // not set yet
			analyticsVirtualPage('purch_done_gen'); // not set yet
			break;
	}

	switch ($("#submittype").val()){
		case 'phone':
			if ($('#playwin').length > 0) {
				openPopUp();
			}
			break;
		case 'pin':
		case 'purchasecode':
			openPopUp();
			if ($("form input[type=submit]:hidden").length > 0) {
				waitForPincode();
			}
			break;
		case 'getpaidgame':
			closePopUp();
			$("#mainGame").html('');
			if (typeof is_show_success !== 'undefined') {
				if (is_show_success === "true") {
					openPopUp();
					is_show_success = 2;
				} else {
					is_show_success = 1;
				}
			}
			else if ($("#is_show_success").length > 0 && $("#is_show_success").val() == 2) {
				openPopUp();
				is_show_success = 2;
			} else {
				is_show_success = 1;
			}
			$.ajax({
				async: true,
				type: "POST",
				url: "index.php",
				data: {
				   ajax: 1,
				   get_paid_game: 1,
				   is_show_success: is_show_success,
				   signed_request: signed_request
				},
				dataType: "json",
				success: parse_ajax
			 });
			break;
		case 'getpaidgame_manual':
			closePopUp();
			break;
		case 'setusername':
		case 'userpassword':
			openPopUp();
			break;
		case 'play':
			closePopUp();
			if (typeof is_show_success !== 'undefined') {
				if (is_show_success === "true") {
					openPopUp();
					$("#register_screen, #banner-data").hide();
					is_show_success = 2;
				} else {
					is_show_success = 1;
				}
			}
			break;
		case 'goto':
			location.href = $("#gototarget").val();
			break;
		default:
			openPopUp();
	}
}

function openPopUpContact() {
	$("#popupContact, #opacity_curtain").show();
}

function openPopUp(){
	$("#opacity_curtain, #main_screen").show();

	var mynum_text = $('#phonenumber').val();
	
	// focus + blur phone number
	if($('#phonenumber').length != 0){
		$('#phonenumber').focus();
		$('#phonenumber').live('click', function(){
			if (isNaN($('#phonenumber').val())) {
				$('#phonenumber').val('');
			}
		});
		
		$('#phonenumber').blur(function(){
			if ($('#phonenumber').val() == '') {
				$('#phonenumber').val(mynum_text);
			}
		});
	}
	
	$('#phonenumber').keypress(function(e){
		if(e.which == 8 && $('#phonenumber').val() == mynum_text){ // if backspace and the text is המספר שלי
			$('#phonenumber').val('');
			return false
		}

		var key_pressed = String.fromCharCode(e.which);

		//allow chars a-z act
		if(/^[a-zA-Zא-ת0-9ا-ن]$/.test(key_pressed) && $(document.activeElement).attr('id') == 'phonenumber' && $('#phonenumber').val() == mynum_text){ // if chars a-z act AND focused on #phonenumber element AND the value is "my number" text
			$('#phonenumber').val(key_pressed);
			return false
		}
	});
}

function closePopUp(){
	$("#opacity_curtain, #main_screen").hide();
	switch ($("#submittype").val())
	{
		case 'setusername':
		case 'userpassword':
			$("#mainGame").html('');
			$.ajax({
				async: true,
				type: "POST",
				url: "index.php",
				data: {
				   ajax: 1,
				   get_paid_game: 1,
				   signed_request: signed_request
				},
				dataType: "json",
				success: parse_ajax
			 });
			break;
	}
}

function get_val(tag) {
	return $("#"+tag).val();
}

function keepAlive(){
	$.ajax({
		async: true,
		type: "POST",
		url: "index.php",
		data: {
		   ajax: 1,
		   free_game: $("#free_game").val(),
		   no_game: 1,
		   game_id: $("#game_id").val(),
		   signed_request: signed_request
		},
		dataType: "json",
		success: parse_alive
	});
}

function openLinkInNewCenteredWindow(url, w, h) {
	var myWin;
    var left = parseInt((screen.availWidth/2) - (w/2));
    var top = parseInt((screen.availHeight/2) - (h/2));
    var features = "width=" + w + ", height=" + h + ", left=" + left + ",top=" + top + "screenX=" + left + ",screenY=" + top + "status=no, resizable=no, scrollbars=yes";
    myWin = window.open(url, "_blank", features);
	myWin.focus();
}

function analyticsVirtualPage(page) {
	_gaq.push(['_trackPageview', page]);
	if(window.console){
		console.info("analytics virtual: " + page);
	}
}

/* sendFlowEventToGoogle():
 * sends virtual pages to analytics by the brife that descrabed on bbls_analytics_new_funnels_flow.odg
 * @param string step - gets which phase the user is in e.g insert-phone, reg_pincode-link, reg_mpay-details,
 * @param bool or string-  gets which path the user takes. a banner path or a popup path.
 * 							we gets this information in normal cases via global variable bbls.popup_type.and sand true or false.
 * 							in other case, after page is beening refreshed we use hidden input value $("input#banner_stat").val() which includes "0" for popup or "1" for banner. in this function we also converting it to integer 1 or 0
 */
function sendFlowEventToGoogle(step, condition){
	if(typeof(condition) == 'string'){
		condition = parseInt(condition);
	}

	if (condition){ // user got window from banner
		analyticsVirtualPage(step + '_banner');
	}
	else { // user got window from popup
		analyticsVirtualPage(step + '_popup');
	}
	analyticsVirtualPage(step + '_gen');
}

function gameEvent_LevelFinished(score, levels) {
}

function gameEvent_GameOver(score, levels, colors) {
}

function gameEvent_PixelCalled(score, levels, colors) {
	setTimeout("keepAlive()", 1000);
}

function waitForPincode(){
	$("#pincode_section").hide();
	$(".please_wait").show();
	$(".submit").hide();
	setTimeout(function(){
		$(".please_wait").hide();
		$("#pincode_section").show();
		$("#pin").focus();
		$(".submit").show();
		setTimeout(function(){
			$('#pay_by_mpay').show();
		}, 10000);
	}, 5000);
}

function setRollImagesInterval(){
	setInterval(function(){
		showCorrentWinner($('ul#winners li:eq(0)'));
	}, 10500);
	setInterval(function(){
		showCorrentWinner($('ul#winners li:eq(1)'));
	}, 8000);
	setInterval(function(){
		showCorrentWinner($('ul#winners li:eq(2)'));
	}, 9500);
	setInterval(function(){
		showCorrentWinner($('ul#winners li:eq(3)'));
	}, 7000);
}//setRollImagesInterval

function showCorrentWinner(li){
	var current = li.children('div:visible').index();
	li.children('div').eq(current).fadeOut(200, function(){
		if (current + 1 == $(li).children().length){
			current = -1;
		}
		current++;

		$(li).children().eq(current).fadeIn(200);
	});	
}
