$(document).ready(function(){

	if(top !== self){
		window.parent.location = 'http://game.hicomm.bg';
	}
	
	if($('#call_friends').length > 0){
		$("#call_friends").fancybox({
			'width'				: '35%',
			'height'			: '75%',
	        'autoScale'     	: false,
	        'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'type'				: 'iframe'
		});	
	}
	
	if($('#send_question').length > 0){
		$("#send_question").fancybox({
			'width'				: '50%',
			'height'			: '100%',
	        'autoScale'     	: false,
	        'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'type'				: 'iframe'
		});	
	}	
	
	
	if($('#confirm_data').length > 0){
		$("#confirm_data a").fancybox({
			'width'				: '45%',
			'height'			: '60%',
	        'autoScale'     	: false,
	        'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'type'				: 'iframe',
			'onClosed': function() {
									  parent.location.reload(true);
									}
		});
		
		$('#wrapper').click(function(){
			$('#confirm_data a').click();
		});
	}
	
	var last_question_id = '';
	
	$('.question ul li').click(function(){
		var exp = $(this).find('a').attr('id').split('_');		
		if(last_question_id != exp[0]){
			$.get(xhr_url,{'method':'save_answer','id': $(this).find('a').attr('id')}, function(data){
				if(data.length > 0){
					$('#'+ data).css({
						'background': 'url('+ _root +'web/images/public/layout/correct.png) no-repeat',
						'color': '#000'
					});
				}else{
					setInterval(function(){
						$('#'+ exp[0] +'_'+ exp[1]).fadeOut('slow').fadeIn('slow');
					}, 100);
				}
				
				// get help
				$.get(xhr_url,{'method': 'get_help','id': exp[0]}, function(data){
					if(data.length > 0){
						$('#question_help').fadeIn('slow').find('span').append(data);
					}
				});
			});	
		}
		last_question_id = exp[0];
	});
	
	window.fbAsyncInit = function() {
			FB.init({appId: '229618087089500', status: true, cookie: true, xfbml: true});
	};


	if($('#fb_log').length > 0){
		FB.Event.subscribe('auth.login', function(response) {
			login();
		});
		
//		FB.Event.subscribe('auth.authResponseChange', function(response){
//			console.log(response.status);
//		});
//		
//		FB.Event.subscribe('auth.logout', function(response) {
//			init_set = false;
//		    window.location.replace(home +'?logout=1');
//		});		

		$('#fb_button_style').live('click', function(){
			FB.logout(function(response){
				init_set = false;
			    window.location.replace(home +'?logout=1');	
			});		    		
		});
		
		function login(){
			FB.api('/me', function(response) {
				if(strpos(window.location.href,'fb_connect') === false){
					//var birthday = response.birthday.substr(-4) +'-'+ response.birthday.substr(3,2) +'-'+ response.birthday.substr(0,2);
					if(typeof(cur_url) != 'undefined'){
						window.location = cur_url +'?fb_connect=true&username='+ response.username +'&email='+response.email + '&name='+ response.name +'&birthday='+ response.birthday +'&first_name='+ response.first_name;
					}
				}
			});
		}
		
		
		if(typeof(cur_url) != 'undefined'){
			FB.getLoginStatus(function(response) {
			  if (response.status == 'connected') {
			  		login();
			  }
			});
		}
	}

	if($('input.date-input').length > 0){
		$('input.date-input').datepicker({
			dateFormat: 'yy-mm-dd',
			yearRange: '-51:+5',
			monthNamesShort: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
			showOtherMonths: true,
			changeMonth: true,
			changeYear: true,
			constrainInput: true,
			firstDay: 1,
			showAnim: 'fadeIn'
		 });
	}
});

function strpos (haystack, needle, offset) {
    var i = (haystack + '').indexOf(needle, (offset || 0));
    return i === -1 ? false : i;
}

function post_to_fb(score){
	var params = {};
	params['message'] = 'Играе в играта на HiComm и към този момент има '+ score +' точки!';
	params['name'] = 'HiComm 2011';
	params['description'] = 'Играй в играта на HiComm и спечели лаптоп Samsung Series 3 300V';
	params['link'] = home;
	params['picture'] = 'http://hicomm.bg/web/images/public/logo.jpg';
	params['caption'] = 'HiComm 2011';
	  
	FB.api('/me/feed', 'post', params, function(response) {
	  if (!response || response.error) {
	    alert('Възникнал е проблем. Опитайте по-късно!');
	  } else {
	    alert('Успешно се похвали във Фейсбук!');
	  }
	});
}

function share_with_friends(){
  FB.ui({method: 'apprequests',
    message: 'HiComm Game 2011',
  });
}

function post_comment(question){
	var set_msg = $('#question_help span').text() +' <b>Играй и спечели 15,6" лаптоп Samsung и още награди!</b>';
     FB.ui(
       {
         method: 'stream.publish',
           message: '',
           name: 'Интересен факт от играта на HiComm',
           caption: 'HiComm Game 2011',
           picture: 'http://hicomm.bg/web/images/public/logo.jpg',
           link: home,
           description: (
             set_msg
           )
       },
       function(response) {
         if (response && response.post_id) {
           //alert('Post was published.');
         } else {
          // alert('Възникнал е проблем. Моля опитайте отново!');
         }
       }
     );  	
}
