/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
window.bool_isFBSession = false;
if(typeof(isLoggedIn)=="undefined") var isLoggedIn = false;



function get_key(key){

    val = $.cookie(key);
  
    return val;
}

function set_key(value, key){

    return($.cookie(key, value,{
        expires:7,
        path:'/',
        domain:'.'+document.domain
        }));

}

function sha_getAuthToken() {
    try {
        var tk = get_key('authTk');

        if(tk.length>10) {
            return tk;
        } else {
            return '';
        }
    } catch (e) {
        return ''; 
    }
}

function sha_setAuthToken(val) {

    var res = set_key(val,'authTk');
}

function sha_removeAuthToken() {

    $.cookie('authTk','',{
          expires:7,
        path:'/',
        domain:'.'+document.domain
        });

}

function sha_frontendError(errmsg) {
    sha_frontendMessage(errmsg,'red');
}


 function sha_frontendMessage (s_msg,s_className) {
           alert(s_msg);
}

function getUserIsLoggedIn() {
    try {
    tk = sha_getAuthToken();
  
            if(tk.length>0) {
                return true;
            } else {
                return false;
            }
            
    } catch (e) {
        return false;
    }
}

function init_loginForm() { 
     //$('#loginForm input[type="submit"]').click() = function() {submit();
}

function handle_LoginResponse(data) {

    var state = data['pL']['rq.state'];

    if(state==0&&data['pL']['authTk']!=undefined) {
         
        setUserLoggedIn(data['pL']['authTk']);
        return true;
    } else {
        sha_frontendError(data['pL']['rq.stateTxt']);
        return false;
    }
}
 

function setUserLoggedOut() {
    try {

           undisplay_fbConnectedState();

           $.getJSON('/listener.php',{path:'reset'},function(){FB.logout(function(){});sha_removeAuthToken();});




    } catch (e) {
          document.location.href = 'http://www.beoble.me';
    }
}

function setUserLoggedIn(token) {
  
    sha_setAuthToken(token);
    hideCommunityFeed();
    hideVideo();

    $('#registerArea').fadeOut();
    $('#loginArea').fadeOut();
    $('#wrp_joinNow').fadeOut();
    $('#menu_loggedOut').hide();
    $('#menu_loggedIn').show();

    if(typeof(window.pgTarget)!="undefined") {
        targetPage = window.pgTarget;
    } else {
        targetPage = '/start';
    }

   $('#beobleContent').attr('src',getCommunityBaseUrl()+'#'+targetPage).fadeIn();
}

function getCommunityBaseUrl() {
    return 'http://e.beoble.me/pc.html';
}


function feeder(){
    var stamp = 0;
    var aData = new Array();
    var curId = 0;
    var bool_StreamStarted = false;
    var intervalId = 0;

    this.start = function() {
    oDate = new Date();
        stamp = oDate.getTime();
      
        $.getJSON('listener.php?path=community/feed&ts='+stamp,function(data){
            window.oCommFeeder.addData(data.pL.community.feed);
            
             initStream();
             rotator();
        });

        

        
    }
    
    this.stop = function() {
        clearInterval(intervalId);
        try {
        delete window.oCommFeeder
        } catch (e) {

            try {
                delete oCommFeeder;
            } catch (e) {
                window.oCommFeeder = null;
            }

        }
    }

    this.addData = function(aNewData) {
       
        elements = (aNewData.length);
        

        for(i=0;i<elements;i++) {
           
            aData.push(aNewData[i]);
        }

        
    }

    function build_row(oData) {
        var row;
        row = '<li class="arrow light full stdEl"><a ><div class="genRImg"><img alt="" src="'+oData.img_url+'" /></div><span class="elHdr">'+oData.s_title+'</span><br/><span class="sm subTxt">'+oData.s_subtext+'</span> <br/><span class="sm smm subHdr">'+oData.s_address+'</span></a></li>';
        return row;
    }

    function initStream() {
          elements = (aData.length);
         for(i=0;i<7;i++) {

            $('#com_feed').append(build_row(aData[i]));
        }
        curId = 7;
    }

    function rotate(){
    
      if(typeof(aData[curId])=="undefined") {
          curId = 0;
          $.getJSON('listener.php?path=community/feed/more&ts='+stamp,function(data){window.oCommFeeder.addData(data.pL.community.feed)});
      }

      $('#com_feed').prepend(build_row(aData[curId]));

      curId++;
    }

    function rotator(){
      intervalId = setInterval(rotate,15000);
    }

    this.applyContentToStream = function() {
        elements = aData.length;
      for(i=(elements-1);i>=0;i--) {

            $('#com_feed').append(build_row(aData[i].img_url));
        }

    }
}


function init() {

   isLogged = getUserIsLoggedIn();
   
    if( isLogged==true) {
       initCommunity();
        $('#menu_loggedOut').hide();
        $('#menu_loggedIn').show();
    } else {
       initCommunityFeed();

    }
}

function initCommunityFeed() {
     if(typeof(window.oCommFeeder)=="undefined"||(window.oCommFeeder!="undefined"&&window.oCommFeeder!=null))  {
            window.oCommFeeder = new feeder();
             window.oCommFeeder.start();
     }
      $('#comm_feed').show();
      hideCommunity();
      hideVideo();
}

function hideCommunityFeed() {
    try {
     if(typeof(window.oCommFeeder)=="undefined"||(window.oCommFeeder!="undefined"&&window.oCommFeeder!=null)) window.oCommFeeder.stop();
    } catch (e) {
        //ie go home!
    }
     $('#comm_feed').hide();
}

function hideVideo(){
    try {
    if(typeof($f(0))!="undefined") $f(0).stop();
    $('#playerWrp').hide();
    } catch (e) {
      
    }
}

function initCommunity(e) {
    hideCommunityFeed();
    hideVideo();

    $('#beobleContent').removeClass('invisible').show();
     
    if(typeof(e)!="undefined") {
        e.preventDefault();
    }
    setUserLoggedIn(sha_getAuthToken());

    return false;
}

function displayCommunityFeed() {
    initCommunityFeed();
}

function displayCommunity() {
    hideCommunityFeed();
    hideVideo();
 
    $('#beobleContent').fadeIn('slow');
}

function hideCommunity(e) {
    $('#beobleContent').hide();
    if(typeof(e)!="undefined") e.preventDefault();
    return false;
}

function getCurrentTimestamp() {
    oDate = new Date();
    return oDate.getTime();
}

function restore_top() {
   $('#registerArea').hide();
   $('#loginArea').hide()
   $('#wrp_joinNow').fadeIn();
}

function community_login(e) {
     /*$('#menu_loggedOut').hide();*/
     $('#loginArea').fadeIn('fast');
     $('#wrp_joinNow').fadeOut();
     $('#registerArea').hide();
       if(typeof(e)!="undefined") e.preventDefault();
}

 function community_register(e) {
     /*$('#menu_loggedOut').hide();*/
     $('#wrp_joinNow').fadeOut();
     $('#registerArea').fadeIn('fast');
     $('#loginArea').hide();
     if(typeof(e)!="undefined") e.preventDefault();
}

function community_login_hide(e) {
     /*$('#menu_loggedOut').hide();*/
     $('#loginArea').fadeOut();
    $('#wrp_joinNow').fadeIn();
      if(typeof(e)!="undefined")  e.preventDefault();
}

function community_logout(e) {

    setUserLoggedOut();
    hideCommunity(e);
    $('#menu_loggedIn').hide();
    $('#menu_loggedOut').show();
    initCommunityFeed();
}

function video_display(e) {
 
    hideCommunity();
    hideCommunityFeed();
    shaInstallPlayer(true);
    
    $('#playerWrp').show();
    if(typeof(e)!="undefined")e.preventDefault();
    return false;
}

function display_iphone(e) {
    $('#download_iphone').fadeIn();
     if(typeof(e)!="undefined")e.preventDefault();
}
function display_android(e) {
    $('#download_android').fadeIn();
     if(typeof(e)!="undefined")e.preventDefault();
}

function display_others(e) {
    $('#download_others').fadeIn();
     if(typeof(e)!="undefined")e.preventDefault();
}

function display_360(e) {
    $('#download_360').fadeIn();
     if(typeof(e)!="undefined")e.preventDefault();
}



function handleCommunityLinkTarget(e) {
    try {
        if(getUserIsLoggedIn()==true) {
            displayCommunity();
        } else {
            displayCommunityFeed();
        }
        if(typeof(e)!="undefined") e.preventDefault();
    } catch (e) {
         
    }
}
 
jQuery.log = function(message) {

		if(typeof(console)!="undefined" && console.log) {
			console.log(message);
		}

        };

function init_fbUserLogin() {
    $.getJSON('/listener.php?path=login&do=fbl',function(data){
        
        if(typeof(data.pL.authTk)!="undefined" && data.pL.authTk.length>10){

             window.bool_isFBSession = true;
             handle_LoginResponse(data)

         } else {

             var fbSession;
             fbSession = FB.getSession();
          
             if(typeof(fbSession.access_token)!="undefined") {
                $('#loginForm').append('<input type="hidden" name="fb_uid" value="'+fbSession.uid+'" /> <input type="hidden" name="fb_accTk" value="'+fbSession.access_token+'" />');
             }

             if(typeof(fbSession.access_token)!="undefined"&&fbSession.uid==window.oFBBeoble.fbuid) {
                
                 check_isConnectedFb(fbSession.access_token);
             }  



         }
    });
}

function check_isConnectedFb(accessTk) {
     $.getJSON('/listener.php',{path:'login','do':'fbl',accTk:accessTk},function(data){
                display_fbConnectedState('#fbLoginWrp',data.pL.fb_uid);

                    if(typeof(data.pL.authTk)!="undefined" && data.pL.authTk.length>10){
                        window.bool_isFBSession = true;
                        handle_LoginResponse(data)
                    } else {
                         community_register();
                    }
                
             });
     return false;
}

function setFbUidToLoginForm(fbuid) {
    $('#loginForm').append('<input type="hidden" name="fbuid" value="'+fbuid+'" />');
}

         function display_fbConnectedState(where,fbuid) {

             $('#fbloginBtn').hide();
             $('#fblogin').hide();
             $(where+' IMG.fbpicture').attr('src','http://graph.facebook.com/'+fbuid+'/picture');
             $(where).show();
        }

        function undisplay_fbConnectedState() {
             $('#fbloginBtn').show();
             $('#fblogin').show();
             $('#fbLoginWrp').hide();
             $('#fbRegWrp').hide();
             $('#loginForm input[name="fb_uid"]').attr('value','');
             $('#loginForm input[name="fb_accTk"]').attr('value','');
             $('#registerForm input[name="fb_uid"]').attr('value','');
             $('#registerForm input[name="fb_accTk"]').attr('value','');
        }

         function handle_FbAuth(response) {
 
          if(response.perms=="") {
              //have problem?
          } else {


             $('#registerForm').append('<input type="hidden" name="fb_uid" value="'+response.session.uid+'" /> <input type="hidden" name="fb_accTk" value="'+response.session.access_token+'" />');

             FB.api('/me',function(response){

                 
                 aTmp = response.link.split('/');
                 if(typeof(aTmp[(aTmp.length-1)])!="undefined") {
                     nickname = aTmp[(aTmp.length-1)];
                 } else {
                     nickname = '';
                 }


                 //find out + handle gender

                 switch(response.gender.charAt(0)) {

                     case 'm':
                       $('#sex_m').attr('checked','checked');
                     break;

                     case 'f':
                     case 'w':
                     default:
                         $('#sex_w').attr('checked','checked');

                     break;

                 }
                 $('#fbAdvice').show();
                 $('#registerForm input[name="usr"]').val(nickname);
                 $('#registerForm input[name="email"]').val(response.email);


                 $('#fblogin').hide();
                 display_fbConnectedState('#fbRegWrp',response.id);
                 display_fbConnectedState('#fbLoginWrp',response.id);


             });

          }

      }
 

/* flash part */


function shaInstallPlayer(doPlay) {
    flowplayer("player", {src:'flwp/flowplayer.commercial-3.1.5.swf',wmode:'transparent'}, {
    key: '#$26ee9eda58c2e2f33bf',
    logo: {
        top:0,
        opacity:0.5
    },


    clip: {
    autoPlay:false,
    autoBuffering:true,
    url: 'http://beoble.me/bme_final.flv'
    ,onStart:function(){

        var plugC = this.getPlugin('controls');
        plugC.css({'opacity':1});
        $('#playerWrp').css({'z-index':'104','outline':'none'});
        $('#player').css({'z-index':'105','outline':'none'});

    }


    }
    ,
    plugins: {

        controls: {
        autoHide:'always',


        bottom:0,
        opacity:0.0,
        hideDelay:2000
        }

    }
    ,
    canvas: {
        backgroundGradient:'none'
    }
});

    $('#player').fadeIn('fast');
    if(typeof(doPlay)!="undefined"&&doPlay==true) $f(0).play();
}


// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Functions/encodeURIComponent#Description
function urlEncode ( s ) {
  return encodeURIComponent( s ).replace( /\%20/g, '+' ).replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' ).replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /\~/g, '%7E' );
} 


 function fb_wait() {
        FB.Event.subscribe('auth.login', function(response) {
                          var res;
                         
                          handle_FbAuth(response);
                          res = check_isConnectedFb(response.session.access_token);


                      });
}

