$loginForm = '<form  action="#" name="signin">'+
            '<label>Email</label>'+
            '<input type="text" name="email"/>'+
            '<label>Password</label>'+
            '<input type="password" name="pwd"/>'+
            '<input type="submit" value="Login" class="button login-btn"/>'+
        '</form><br/>'+
        '<div class="fbSignIn dropDownFb"></div>';

function waitingAnimation($height,$width){
    $waitingAnimation =
    '<div class="waitingContainerJS">'+
            '<table class="waitingTable">'+
                '<tr>'+
                    '<td class="wait" id="wait1"></td>'+
                    '<td class="wait" id="wait2">L</td>'+
                    '<td class="wait" id="wait3">O</td>'+
                    '<td class="wait" id="wait4">A</td>'+
                    '<td class="wait" id="wait5">D</td>'+
                    '<td class="wait" id="wait6">I</td>'+
                    '<td class="wait" id="wait7">N</td>'+
                    '<td class="wait" id="wait8">G</td>'+
                    '<td class="wait" id="wait9"></td>'+
                    '<td class="wait" id="wait10"></td>'+
                '</tr>'+
            '</table>'+
        '</div>';
    return $waitingAnimation;
}
function setOpacity($ID,$opacity){
        $($ID).css("opacity",$opacity);
}
function loadingPage($block,$start){
      $blockID = "#wait"+$block;
      $1blockBeforeID = "#wait"+($block-1);
      $2blockBeforeID = "#wait"+($block-2);
      $3blockBeforeID = "#wait"+($block-3);
      $4blockBeforeID = "#wait"+($block-4);
      $5blockBeforeID = "#wait"+($block-5);
      $6blockBeforeID = "#wait"+($block-6);
      $7blockBeforeID = "#wait"+($block-7);

      //first check to see if any of these blocks have the same opacity
      //if they do, we should stop this instance of loadingPage from running
      // because it has been called again (only valid if not the first time ran)
      if($start!=1){
          var $opacity = new Array(6);
          $opacity[0] = $($blockID).css("opacity");
          $opacity[1] = $($1blockBeforeID).css("opacity");
          $opacity[2] = $($2blockBeforeID).css("opacity");
          $opacity[3] = $($3blockBeforeID).css("opacity");
          $opacity[4] = $($4blockBeforeID).css("opacity");
          $opacity[5] = $($5blockBeforeID).css("opacity");
          $opacity[6] = $($6blockBeforeID).css("opacity");
          $opacity[7] = $($7blockBeforeID).css("opacity");
          for(var $check1=0;$check1<=7;$check1++){
              for(var $check2=0;$check2<=7;$check2++){
                  if($opacity[$check1] && $opacity[$check2]){
                    if($opacity[$check1]==$opacity[$check2] && $check1!=$check2 && $opacity[$check2]!=0){
                        $(".wait").css("opacity","0");
                        return;
                    }
                  }
              }
          }
      }

      setOpacity($blockID,1);
      setOpacity($1blockBeforeID,.8);
      setOpacity($2blockBeforeID,.6);
      setOpacity($3blockBeforeID,.4);
      setOpacity($4blockBeforeID,.2);
      setOpacity($5blockBeforeID,0);


    if($block==15){
        var t= setTimeout("loadingPage(1,0)",300);
    }else{
        $next = $block+1;
        var t= setTimeout("loadingPage("+$next+","+$start+")",50);
    }
}
/*
 * gets the base url of the current website
 */
function getURLBase(){
	var $base = window.location.host;
	return 'http://'+$base;
}
function startLoading(){
    $("#crazyDiv").html(waitingAnimation(50,50));
    $("#crazyDiv").fadeIn();
    loadingPage(1,1);
}
function stopLoading(){
    $("#crazyDiv").html("");
}
/*
 *for auto clearing text field inputs
 */
function clearText(){
    $(".clearText").focus(function(){
        if($(this).hasClass('done')){
            $(this).removeClass('done');
            $(this).css("color","black")
            $(this).val("");
        }
    });
}
/*
 * 
 */
function dialogHTML($content){
    return '<div id=dialog>'+$content+'</div>';
}

/*
 * the html for prompting sign in
 */
function promptLoginPopUp($message){
    $('#crazyDiv').html(
        '<div id="dialog">'+
            '<h3>'+$message+'</h3><br />'+
            '<form id="step-one" class="steps" action="#" name="signin">'+
			'<div class="column">'+
                    
                    '<label>Email/Username</label>'+
                    '<input class="steps-4" type="text" name="email"/>'+
                    '<label>Password</label>'+
                    '<input class="steps-4" type="password" name="pwd"/><br/>'+
                    '<input type="submit" value="Sign in"/>'+
                '</div>'+
			'<a href="#" class="sign-in fbSignIn">Sign in with Facebook</a>'+
                
                '<span class="or" style="margin:100px 0 0 50px;">or</span>'+
                '<div id="signup-text" class="column">'+
                    '<em>Don\'t have an account<br>'+
             'with us yet?</em><br>'+
                '<a id="showSignup" href="showSignup">Sign Up &rarr;</a>'+
                '</div>'+
                '<hr />'+
            '</form>'+
        '</div>'
    );
    showSignUpPopup();
    $(".fbSignIn").click(function(){
        facebookLogin();
        return false;
    });
    emailSignIn();
}
function showSignUpPopup(){
       $("#showSignup").click(function(){
       $('#dialog').css('display','none');
       $('#dialog').css('width','900px');
       $('#dialog').html('<form id="home-form" name="register" action="#" method="post" style="float:right;">'+
'<!--            <h2 style="margin-right:40px;">Email Sign Up</h2>-->'+
'<a href="#" class="sign-in fbSignIn">Sign in with Facebook</a>'+
            '<input type="hidden" name="form" value="emailSignup" />'+
            '<div class="column">'+
                
            '</div>'+
            '<div class="column">'+
                '<h1>-- or --</h1>'+
            '</div>'+
            '<div class="column">'+
                '<label>Enter Email</label>'+
                '<input class="home-input" name="email" type="text" maxlength="30"/><br />'+
                '<label>Enter Your Name</label>'+
                '<input class="home-input" name="name" type="text" maxlength="30"/><br />'+
            '</div>'+
            '<div class="column">'+
                '<label>Make a Password</label>'+
                '<input class="home-input" id="pwd1" name="pwd" type="password" maxlength="30"/><br />'+
                '<label>Confirm Password</label>'+
                '<input class="home-input" id="pwd2"name="pwd1" type="password" maxlength="30"/><br />'+
            '</div>'+
            '<div style="position:relative;left: 390px;width: 340px; height:10px;">'+
                'I agree to the <a href="Terms.php">Terms & Conditions of Splittr</a> <input id="terms" type="checkbox">'+
                '<input type="hidden" name="action" value="emailSignup"/><br/>'+
                '<input type="submit" id="home-submit" value="submit"/>'+
            '</div>'+
        '</form>');
        $('#dialog').fadeIn();
        emailRegister();
        $(".fbSignIn").click(function(){
            facebookLogin();
            return false;
        });
        return false;
   });

}
/*
 * runs the ajax for logging in
 */
function emailSignIn(){
    $("form[name=signin]").submit(function(){
        $email=$(this).find("input:text[name=email]").val();
        $pwd=$(this).find("input:password[name=pwd]").val();
        $.post(getURLBase()+"/general/control/signin.php",{form:"signin",email:$email,pwd:$pwd},function(data){
//                alert(data);
            if(data){
                if(data.search('success')!=-1){
                    window.location.reload();
                }else if(data.search('pwd')!=-1){
                    $("form[name=signin]").find("input:password[name=pwd]").css("background-color","red");
                    $('.loginResponse').html('<a href="/static/forgottenPwd.php" style="color:white;">Forgot your password? Click here.</a>');
                }else if(data.search('user')!=-1){
                    $("form[name=signin]").find("input:text[name=email]").css("background-color","red");
                    $('.loginResponse').html('No user with that email.');
                }
            }
        });
        return false;
    });

}
/*
 * check to see if the current user is logged in
 */
function checkLoggedIn(){
    return $.ajax({
      url: getURLBase()+'/general/control/checkLoggedIn.php',
      async: false
    }).responseText;

}
function emailRegister(){
        $("form[name=register]").submit(function(){
            $email=$(this).find("input:text[name=email]").val();
            $name=$(this).find("input:text[name=name]").val();
            $pwd=$(this).find("input:password[name=pwd]").val();
            $pwd1=$(this).find("input:password[name=pwd1]").val();
            $.post(getURLBase()+"/general/control/register.php",{form:"emailSignup",
                email:$email,name:$name,pwd:$pwd,pwd1:$pwd1,action:"emailSignup"},function(data){
                alert(data);
                if(data.search('success')!=-1){
                    window.location.reload();
                }else if(data=='already_exists'){
                    alert('A user with that email already exists.');
                }
            });
            return false;
        });

    }
/*
 *this function logs a user our when he hits the log out div
 */
function logout(){
    $(".logout").click(function(){
//        alert('wtf');

        $.post(getURLBase()+"/general/control/logout.php",{somedata:"nothing"},function(data){
            //alert(data);
            if(data.search('success')!=-1){
                window.location.reload();
            }else{
                alert("HOLY @#%^$! This is a bug, please let us know about it."+"\n"+"\n"+data)
            }
        });
        return false;
    });
}








    /*
     *standard facebook login button
     */
function facebookLogin(){
//      FB.getLoginStatus(function(response) {
            FB.login(function(response) {
                if (response.session) {
                    checkLogin();
                } else {
                // user cancelled login
                }
            },{perms:'email, user_birthday, friends_birthday, publish_stream,offline_access'});
//          }
//     });
}


function facebookLogin2(){
      FB.getLoginStatus(function(response) {
          if (response.session) {
                         FB.api(
              {
                method: 'fql.query',
                query: 'SELECT friends_birthday FROM permissions WHERE uid=me()'
              },
              function(response) {
                if(response[0].friends_birthday==1){
                    checkLogin2();
                }else{
                    FB.login(function(response) {
                        if (response.session) {
                            checkLogin2();
                        } else {
                        // user cancelled login
                        }
                    },{perms:'email, user_birthday, friends_birthday'});
                }
              }
            );
          } else {
//                            alert('or here');
            // no user session available, someone you dont know
//                alert('stranger');
            FB.login(function(response) {
                if (response.session) {
                    checkLogin2();
                } else {
                // user cancelled login
                }
            },{perms:'email, user_birthday, friends_birthday, publish_stream'});
          }
     });
}
function facebookLoginLanding(){
      FB.getLoginStatus(function(response) {
          if (response.session) {
//              alert('doing ok');
                         FB.api(
              {
                method: 'fql.query',
                query: 'SELECT friends_birthday FROM permissions WHERE uid=me()'
              },
              function(response) {
                if(response[0].friends_birthday==1){
                    checkLoginLanding();
                }else{
                    FB.login(function(response) {
                        if (response.session) {
                            checkLoginLanding();
                        } else {
                        // user cancelled login
                        }
                    },{perms:'email, user_birthday, friends_birthday,offline_access'});
                }
              }
            );
          } else {
//                            alert('or here');
            // no user session available, someone you dont know
//                alert('stranger');
            FB.login(function(response) {
                if (response.session) {
                    checkLoginLanding();
                } else {
                // user cancelled login
                }
            },{perms:'email, user_birthday, friends_birthday, publish_stream, offline_access'});
          }
     });
}
/*
 * 
 */
function checkLogin(){
    $.post(getURLBase()+"/general/control/facebookSignin.php", {toto:"ss"}, function(data){
//        alert("Data Loaded: " + data);
        if(data=="green_light"){
            window.location.reload();
        }else if(data=="no_fb"){
            //should never get here
            alert('OH SNAP! This is a bug. Please let us know about it.');
        }
    });
}
function checkLoginLanding(){
    $.post(getURLBase()+"/general/control/facebookSignin.php", {toto:"ss"}, function(data){
//        alert("Data faLoaded: " + data);
        if(data=="green_light"){
            window.location=getURLBase()+'/getStarted/';
        }else if(data=="no_fb"){
            //should never get here
            alert('OH SNAP! This is a bug. Please let us know about it.');
        }
    });
}
function checkLogin2(){
    $.post(getURLBase()+"/general/control/facebookSignin.php", {toto:"ss"}, function(data){
//        alert("Data Loaded: " + data);
//        if(data=="green_light"){
            window.location.reload();
//        }else if(data=="no_fb"){
            //should never get here
//            alert('OH SNAP! This is a bug. Please let us know about it.');
//        }
    });
}

function showLogin(){
    $('#sign-in').click(function(){
		$('.dropDownWrapper').hide();
		//$('.dropDownWrapper').css('background-color', '#ffffff');
        $('.dropDownWrapper').html($loginForm+
        '<span class="rollUpLogin">Hide&uarr;</span>');
		$('.dropDownWrapper').slideDown();
    emailSignIn();
    $(".dropDownFb").click(function(){
        facebookLogin();
        return false;
    });
    $(".rollUpLogin").click(function(){
		$('.dropDownWrapper').slideUp(500, function(){
	    	//$('.dropDownWrapper').css('background-color', '#f7f7f7');
        	$(".dropDownWrapper").html('');});
		
        return false;
    });
    return false;
    });
}

/*
 * checks to see if input contains any characters other than integers, one
 * decimal and one dollar sign. Returns an array in which
 */
function validateFloat(input){
      numbers = ['1','2','3','4','5','6','7','8','9','0'];
    var length = input.length;
    var rString = "";
    //if valid return true
    var rBool   = new Boolean(true);
    var dollarSign = new Boolean(false);
    var decimal    = new Boolean(false);
    rBool = new Boolean(true);
    for(position=0;position<length;position++){
        Char = input.charAt(position);
        if(Char in numbers){
            //other wise the character is an int so just add it to the rString and
            // move on.
            rString+=Char;
        }else{
            //if the current character is a period
            if(Char=="."){
                //check to see if we have already come across a period. If we
                // have then indicate the number is not valid
                if(decimal==false){
                    decimal=true;
                    rString += Char;
                }else{
                    rBool = new Boolean(false);
                }
            }else if(Char=="$"){
                //do the same for the dollar sign
                if(dollarSign==false){
                    dollarSign=true;
                }else{
                    rBool = new Boolean(false);
                }
            }else{
                //otherwise the character is totally fucked up, and we dont want
                //any part of that
                rBool = new Boolean(false);
            }
        }
    }
    rVal = [rBool, rString];
    //alert(rVal[0]+" | "+rVal[1]);
    return rVal;
}

/*
 * this function displays some info in teh class .bubbleInfo, when the mouse rolls
 * over the div
 *
 */
function bubbleInfo(){
    $('.bubbleInfo').each(function () {
    // options
    var distance = 5;
    var time = 250;
    var hideDelay = 00;

    var hideDelayTimer = null;

    // tracker
    var beingShown = false;
    var shown = false;

    var trigger = $('.trigger', this);
    var popup = $('.popup', this).css('opacity', 0);

    // set the mouseover and mouseout on both element
    $([trigger.get(0), popup.get(0)]).mouseover(function () {
      // stops the hide event if we move from the trigger to the popup element
      if (hideDelayTimer) clearTimeout(hideDelayTimer);

      // don't trigger the animation again if we're being shown, or already visible
      if (beingShown || shown) {
        return;
      } else {
        beingShown = true;

        // reset position of popup box
        popup.css({
          top: -80,
          left: -33,
          display: 'block' // brings the popup back in to view
        })

        popup.css('z-index', 2)
        // (we're using chaining on the popup) now animate it's opacity and position
        .animate({
          top: '-=' + distance + 'px',
          opacity: 1
        }, time, 'swing', function() {
          // once the animation is complete, set the tracker variables
          beingShown = false;
          shown = true;
        });
      }
    }).mouseout(function () {
      // reset the timer if we get fired again - avoids double animations
      if (hideDelayTimer) clearTimeout(hideDelayTimer);

      // store the timer so that it can be cleared in the mouseover if required
      hideDelayTimer = setTimeout(function () {
        hideDelayTimer = null;
        popup.animate({
          top: '-=' + distance + 'px',
          opacity: 0
        }, time, 'swing', function () {
          // once the animate is complete, set the tracker variables
          shown = false;
          // hide the popup entirely after the effect (opacity alone doesn't do the job)
          popup.css('display', 'none');
        });
      }, hideDelay);
    });
  });
}

/*
 * this is the que for all the JS functions that should be executed after the
 * doc has loaded
 */
$(document).ready(function () {
    emailSignIn();
    emailRegister();
    logout();
    showLogin();
    $('.dropDownWrapper').hide();
    clearText();
});
