var hiJackSignInLink, hiJackSignInForm, signInAjax, createSignInForm, signInFormBoxes, createSuccessLightBox, showLoadingBox, hiJackSendToFriendForm,
  hiJackSignOutLink, signOutAjax, hiJackLostPasswordLink, createForgotPasswordBox,
  hiJackForgotPasswordForm, forgotPassworkFormBoxes, hiJackBackToLogin,
  showLightBox, closeLightBox, createErrorBox, facebookLogin,
  loginCallback;

$(document).ready(function () {

  if($('#button_sign-in').size() === 1) {
    hiJackSignInLink();
  }

  if($('#signin_form').size() === 1) {
    hiJackSignInForm();
  }

  if($('#button_sign-out').size() === 1) {
    hiJackSignOutLink();
  }
});

hiJackSignInLink = function() {
  var sign_in = $('#button_sign-in');

  sign_in.click(function(event) {
    event.preventDefault();
		$('.video_wrapper iframe').hide();
    //siteOverlay();
    createSignInForm();
  });
};

signInAjax = function() {
  var submitButton = $("#signin_form button[type='submit']");
  submitButton.attr("disabled", "disabled");

  if($("#isAjax").size() > 0) {
    //fade out box
    $("#lightbox_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
      showLoadingBox("Signing in. Please wait...");
      //grab the url from the action attribute
      var action_url = $("#signin_form").attr("action");
      //var action_url = "test_login.php";
      $.ajax({
        type: "POST",
        url: action_url,
        data: $("#signin_form").serialize(),
        dataType: "json",
        success: function(json){
          //alert( "Data Saved: " + json.success );
          if(json.success === "true") {
            //remove sign in box
            $("#lightbox_wrapper").remove();
            $("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
              $("#loading_wrapper").remove();

              if (window.location.href === '#share-pledge') { // Prevent pledge sharing for re-opening
                window.location = window.location.protocol+'//'+window.location.hostname+window.location.pathname+window.location.search;
              } else {
                window.location.reload();
              }
            });
          } else {
            //alert('error!');
            //fade out the loading box and remove it after fade out
            $("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
              $("#loading_wrapper").remove();
              var msg = [json.message];
              createErrorBox(msg, false);
            });
          }
        },
        error: function(msg) {
          //alert('error!');
          //fade out the loading box and remove it after fade out
          $("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
            $("#loading_wrapper").remove();
            var msg = ["There was a problem connecting to the server. Please try again."];
            createErrorBox(msg, false);
          });
        }
      });
    });
  } else {
    //if normal form
    showLoadingBox("Signing in. Please wait...");
    //grab the url from the action attribute
    var action_url = $("#signin_form").attr("action");

    $.ajax({
      type: "POST",
      url: action_url,
      data: $("#signin_form").serialize(),
      dataType: "json",
      success: function(json){
        //alert( "Data Saved: " + json.success );
        if(json.success === "true") {
          $("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
            $("#loading_wrapper").remove();
            window.location = subdir+"/connectory.php";
          });
        } else {
          //alert('error!');
          //fade out the loading box and remove it after fade out
          $("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
            $("#loading_wrapper").remove();
            var msg = [json.message];
            createErrorBox(msg, true);
            var submitButton = $("#signin_form button[type='submit']");
            submitButton.attr("disabled","");
          });
        }
      },
      error: function(msg) {
        //alert('error!');
        //fade out the loading box and remove it after fade out
        $("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
          $("#loading_wrapper").remove();
          var msg = ["There was a problem connecting to the server. Please try again."];
          createErrorBox(msg, true);
          var submitButton = $("#signin_form button[type='submit']");
          submitButton.attr("disabled","");
        });
      }
    });
  }
  return false;
};

createSignInForm = function () {
  $("body").append('<div id="lightbox_wrapper" class="lightbox"></div>');
  $("#lightbox_wrapper").append('<div id="signin_box" class="acct_lightbox"></div>');
  //set HTML for the sign in box via Ajax call
  $("#signin_box").load("/form_login.php", null, function() {
    //add special ajax hidden input in the form
    var isAjax = '<input id="isAjax" name="isAjax" type="hidden" value="true" />';
    $('#signin_form > fieldset:first').prepend(isAjax);

    hiJackSignInForm();
    hiJackLostPasswordLink();
    signInFormBoxes();

    showLightBox($("#signin_box"));

    $('button.sign_in').click(function (){
      form = $('#signin_form')[0];
      form.fb_id.value = '';
    });


    if ($.browser.webkit) {
      $('input.text').css({
        fontSize: '13px'
      });
    }

  });
};

signInFormBoxes = function() {
  var zipLabel = "Email";
  var keywordLabel = "Password";

  var zipInput = $("input[name='email']");
  zipInput.val(zipLabel);

  zipInput.focus(function() {
    if(this.value === zipLabel) {
      this.value = "";
    }
  });

  zipInput.blur(function() {
    if(this.value === "") {
      this.value = zipLabel;
    }
  });

  var keywordsInput = $("#signin_box input[name='password']:first");
  //alert(keywordsInput.attr("type"))
  // rename element to simple HTML element (non jQuery so I can change the type to text)
  // not working using the jQuery attr() method;
  if(keywordsInput.size() > 0) {
    var newkeywordsInput = keywordsInput[0];
    //ie browser die when you try to change an
    //input from password to text
    if (!jQuery.browser.msie) {
      newkeywordsInput.type = "text";
      newkeywordsInput.value = keywordLabel;
    }
  }

  //reselect element as jQuery object to apply focus and blurs
  keywordsInput = $("#signin_box input[name='password']:first");
  //keywordsInput = keywordsInput[0];

  keywordsInput.focus(function() {
    if(this.value === keywordLabel) {
      if (!jQuery.browser.msie) {
        this.value = "";
        this.type = "password";
      }
    }
    //alert(this.type)
  });

  keywordsInput.blur(function() {
    //alert(this.type)
    if(this.value === "") {
      if (!jQuery.browser.msie) {
        this.type = "text";
        this.value = keywordLabel;
      }
    }
  });
};

/* SIGN OUT */
hiJackSignOutLink = function() {
  var sign_out = $('#button_sign-out');

  sign_out.click(function(event) {
    event.preventDefault();
    signOutAjax();
  });
};

signOutAjax = function() {
  //siteOverlay();
  showLoadingBox("Signing out. Please wait...");
  //grab the url from the action attribute
  var action_url = "/actions/logout.php";
  //var action_url = "test_login.php";
  $.ajax({
       type: "GET",
       url: action_url,
    dataType: "json",
       success: function(json){
        //alert( "Data Saved: " + json.success );
      if(json.success === "true") {
        $("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
          $("#loading_wrapper").remove();
          //fade back in the form box and re-enabled the submit button after fade in
          //
              if (window.location.href === '#share-pledge') { // Prevent pledge sharing for re-opening
                window.location = window.location.protocol+'//'+window.location.hostname+window.location.pathname+window.location.search;
              } else {
                window.location.reload();
              }
        });
      } else {
        //alert('error!');
        //fade out the loading box and remove it after fade out
        $("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
          $("#loading_wrapper").remove();
          var msg = [json.message];
          createErrorBox(msg, false);
        });
      }
    },
    error: function(msg) {
      //alert('error!');
      //fade out the loading box and remove it after fade out
      $("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
        $("#loading_wrapper").remove();
        var msg = ["There was a problem connecting to the server.. Please try again."];
        createErrorBox(msg, false);
      });
    }
  });

};

/* LOST PASSWORD */
hiJackLostPasswordLink = function() {
  var forgot_pass_link = $('#forgot_password_link');

  forgot_pass_link.click(function(event) {
    event.preventDefault();
    $("#signin_box").animate({"opacity":"0"}, 200, "linear", function(){
      $(".lightbox").remove();
      createForgotPasswordBox();
    });
  });
};

createForgotPasswordBox = function() {
  $("body").append('<div id="lightbox_wrapper" class="lightbox"></div>');
  $("#lightbox_wrapper").append('<div id="forgot_password_box" class="acct_lightbox"></div>');
  //set HTML for the sign in box
  $("#forgot_password_box").load("/form_forgot_password.php", null, function() {
    forgotPassworkFormBoxes();
    hiJackBackToLogin();
    hiJackForgotPasswordForm();

    //add special ajax hidden input in the form
    var isAjax = '<input id="isAjax" name="isAjax" type="hidden" value="true" />';
    $('#lost_password_form > fieldset:first').prepend(isAjax);

    showLightBox($("#forgot_password_box"));
  });
};

hiJackForgotPasswordForm = function() {
  //alert("hiJackForgotPasswordForm")

  $('#lost_password_form').submit(function(event){
    event.preventDefault();

    var submitButton = $("#lost_password_form button[type='submit']");
    submitButton.attr("disabled","disabled");

    //if modal box
    if($("#isAjax").size() > 0) {
      //fade out box
      $("#lightbox_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
        showLoadingBox("Looking up account. Please wait...");
        //grab the url from the action attribute
        var action_url = $("#lost_password_form").attr("action");
        //var action_url = "test_login.php";
        $.ajax({
             type: "POST",
             url: action_url,
             data: $("#lost_password_form").serialize(),
          dataType: "json",
             success: function(json){
              //alert( "Data Saved: " + json.success );
            if(json.success === "true") {
              //remove forgot password box
              $("#lightbox_wrapper").remove();
              $("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
                $("#loading_wrapper").remove();
                createSuccessLightBox("<p>"+json.message+"</p>");
              });
            } else {
              //alert('error!');
              //fade out the loading box and remove it after fade out
              $("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
                $("#loading_wrapper").remove();
                var msg = [json.message];
                createErrorBox(msg, false);
              });
            }
          },
          error: function(msg) {
            //alert('error!');
            //fade out the loading box and remove it after fade out
            $("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
              $("#loading_wrapper").remove();
              var msg = ["There was a problem connecting to the server. Please try again."];
              createErrorBox(msg, false);
            });
          }
        });
      });

    } else {
      //if normal form
      showLoadingBox("Looking up account. Please wait...");
      //grab the url from the action attribute
      var action_url = $("#lost_password_form").attr("action");

      $.ajax({
           type: "POST",
           url: action_url,
           data: $("#lost_password_form").serialize(),
        dataType: "json",
           success: function(json){
            //alert( "Data Saved: " + json.success );
          if(json.success === "true") {
            $("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
              $("#loading_wrapper").remove();
              createSuccessLightBox("<p>"+json.message+"</p>");
            });
          } else {
            //alert('error!');
            //fade out the loading box and remove it after fade out
            $("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
              $("#loading_wrapper").remove();
              var msg = [json.message];
              createErrorBox(msg, true);
              var submitButton = $("#lost_password_form button[type='submit']");
              submitButton.attr("disabled","");
            });
          }
        },
        error: function(msg) {
          //alert('error!');
          //fade out the loading box and remove it after fade out
          $("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
            $("#loading_wrapper").remove();
            var msg = ["There was a problem connecting to the server. Please try again."];
            createErrorBox(msg, true);
            var submitButton = $("#lost_password_form button[type='submit']");
            submitButton.attr("disabled","");
          });
        }
      });
    }

  });
};

forgotPassworkFormBoxes = function() {
  var label = "E-mail Address";

  var input = $("input[name='email']");
  input.val(label);

  input.focus(function() {
    if(this.value === label) {
      this.value = "";
    }
  });

  input.blur(function() {
    if(this.value === "") {
      this.value = label;
    }
  });
};

hiJackBackToLogin = function() {
  var sign_in = $('#back_to_login');

  sign_in.click(function(event) {
    event.preventDefault();
    $("#forgot_password_box").animate({"opacity":"0"}, 200, "linear", function(){
      $(".lightbox").remove();
      createSignInForm();
    });
  });
};

/* LIGHTBOX FUNCTIONS */
function siteOverlay(hasCloseButton) {
  //alert("siteOverlay "+hasCloseButton)
  hasCloseButton = typeof(hasCloseButton) !== 'undefined' ? hasCloseButton : true;
  //remove overlay on click
  if(hasCloseButton) {
    $(".overlay").click(function(event){
      event.preventDefault();
      closeLightBox(event);
    });
    $(".overlay").css("cursor","pointer");
  }

  if($('.overlay').size() > 0) {
    return false;
  }

  $("body").append('<div class="overlay"></div>');
  if(hasCloseButton) {
    $(".overlay").click(function(event){
      event.preventDefault();
      closeLightBox(event);
    });

    $(".overlay").css("cursor","pointer");
  }

  if (jQuery.browser.msie) {
    if(parseInt(jQuery.browser.version, 10) === 6) {
      //alert("overlay height: "+$("body").height())
      $(".overlay").css({
        "position":"absolute"//,
        // "height":$("wrapper").height()
      });

      $("#wrapper select[class!=hide][class!=hidden]").css({"display":"none"});

    }
  }
  $(".overlay").animate({"opacity":"0.7"}, 200, "linear");

}

showLightBox = function(innerBox, hideAll, hasCloseButton) {
  //alert("showLightBox")

  hideAll = typeof(hideAll) !== 'undefined' ? hideAll : true;
  hasCloseButton = typeof(hasCloseButton) !== 'undefined' ? hasCloseButton : true;
  var box = innerBox.parent();
  //alert(box.attr("id"))
  if(hasCloseButton) {
    box.append('<a id="btn_close_lightbox" class="btn_close sprite_button" href="#">Close</a>');
  }
  //set the css for positioning to center on screen
  var boxWidth = box.width();
  var boxHeight = box.height();
  var windowHeight = $(window).height();

  //clip off lightbox if it's too tall still
  if(boxHeight > windowHeight) {
    boxHeight = windowHeight - 200;
  }

  // if (innerBox.attr("id") === "href_modal_box") {
  //   innerBox.css({"min-width":"425px"});
  //   innerBox.css({"width":"auto !important"});
  //   innerBox.css({"width":"425px"});
  // }

  //set close button(s)
  var closeBtnWidth, closeBtnHeight;

  if(hasCloseButton) {
    $(".btn_close").click(function(event){
      closeLightBox(event, hideAll);
    });

    // Escape closes lightbox
    $(document).keydown(function (event) {
      if (event.keyCode === '27')  {
        event.preventDefault();
        window.location = '#all';
        closeLightBox(event, hideAll);
      }
    });
/*
    $(".btn_close").click(function(event){
      closeLightBox(event, hideAll);
    });*/

    //get width and height of close button
    closeBtnWidth = $("#btn_close_lightbox").width();
    closeBtnHeight = $("#btn_close_lightbox").width();
    //move the inner box down and right to shift for close button
    innerBox.css({
        "margin-top": closeBtnHeight/2,
        "margin-left":closeBtnWidth/2
      });
  } else {
    closeBtnWidth = 0;
    closeBtnHeight = 0;
  }

  //for IE6
  if (jQuery.browser.msie) {
    if(parseInt(jQuery.browser.version, 10) === 6) {

      $(".sprite_button, button.sprite").mouseover(function(event){
        //$(this).addClass("ie6_hover");
        $(this).css({"background-position" : "bottom left", "cursor" : "pointer"});

      });

      $(".sprite_button, button.sprite").mouseout(function(event){
        //$(this).removeClass("ie6_hover");
        $(this).css({"background-position" : "top left", "cursor" : "default"});
      });

      box.css({
          "position": "absolute"
      });
      pngfix();
      move_box();
      scrollInterval = window.setInterval("move_box()", 100);
    } else {
      box.css({
          "width": boxWidth,
          "height": boxHeight,
          "margin-top": -(boxHeight/2)-20,
          "margin-left":-(boxWidth/2)-(closeBtnWidth/4) //to position it in the middle (using offset for closebutton)
      });
    }
  } else {
    box.css({
        "width": boxWidth,
        "height": boxHeight,
        "margin-top": -(boxHeight/2)-50,
        "margin-left":-(boxWidth/2)-(closeBtnWidth/4) //to position it in the middle (using offset for closebutton)
    });
  }

  //fade form in
  siteOverlay(hasCloseButton);
  box.animate({"opacity":"1"}, 200, "linear");

  if($("#swf_replace").size() === 1) {
    thisMovie("swf_replace").deactivateFlash();
  }

  if($("#discuss").size() === 1) {
    thisMovie("discuss").deactivateFlash();
  }
};

closeLightBox = function(event, hideAll) {
  //alert("closeLightbox")
  if(event !== undefined) {
    if(event.preventDefault() !== undefined) {
      event.preventDefault();
    }
  }

	$('.video_wrapper iframe').show();

	hideAll = typeof(hideAll) !== 'undefined' ? hideAll : true;
  //hide all boxes with class of lightbox and the overlay
  if(hideAll) {
    $(".lightbox").animate({"opacity":"0"}, 200, "linear");
    $(".overlay").animate({"opacity":"0"}, 200, "linear", function(){
      $(".overlay").remove();
      $(".lightbox").remove();

      //for IE6 to kill scroll interval for lightbox overlay div
      if (jQuery.browser.msie) {
        if(parseInt(jQuery.browser.version, 10) === 6) {
          //alert("i am IE6 and closing the lightbox")
          $("#wrapper select[class!=hide][class!=hidden]").css({
            "display":"block"
          });

          clearInterval(scrollInterval);
          //alert(scrollInterval);
        }
      }

      if($("#swf_replace").size() === 1) {
        thisMovie("swf_replace").activateFlash();
      }

      if($("#discuss").size() === 1) {
        thisMovie("discuss").activateFlash();
      }

    });
  } else {
    //will fade and remove only itself
    //drill back up to the first parent div with the class of 'lightbox'
    var currentLightBox = $(event.target).parents('.lightbox');
    currentLightBox.animate({"opacity":"0"}, 200, "linear", function(){
      currentLightBox.remove();
      //bring back any other boxes with lightbox class
      $(".lightbox").animate({"opacity":"1"}, 200, "linear", function() {
        //re-enable any submit buttons after fade in
        var submitButton = $(".lightbox button[type='submit']");
        submitButton.attr("disabled","");
        if (jQuery.browser.msie) {
          if(parseInt(jQuery.browser.version, 10) === 6) {
            $(".lightbox select").each(function(idx,item){
              $(item).removeClass("hide");
            });
          }
        }

      });
    });

  }
};

function createPromptBox(msg, url) {
  $("body").append('<div id="promptBox_wrapper" class="lightbox"></div>');

  var html = '<div id="externalLink_box" class="acct_lightbox">';
  html += '<div class="lightbox_inner">';
  html += '<h2 id="title_attention">Attention</h2>';
  html += '<p class="message">'+msg+'</p>';
  html += '<div class="modal_buttons">';
  html += '<p><a id="btn_no" class="sprite_button" href="#">No</a></p>';
  html += '<p><a id="btn_ok" class="sprite_button" href="'+url+'">OK</a></p>';
  // html +=  '<div class="clear"></div>';
  html += '</div>';
  html += '</div>';
  html += '</div>';
  $("#promptBox_wrapper").append(html);

  $("#btn_no").click(function(event) {
    closeLightBox(event);
  });
  //siteOverlay();
  showLightBox($("#externalLink_box"));
}

createErrorBox = function(errors, hideAll) {
  hideAll = typeof(hideAll) !== 'undefined' ? hideAll : true;
  var html;
  if(typeof(errors) === "object" && $.inArray('We see that you have already used this e-mail address to pledge to Connect a Million Minds. To add to your number of "pledgees," log into the site with your username and password and visit The Pledge page.', errors) !== -1) {
    html = "<h2 id=\"title_error_repledge\">Looks like you&rsquo;ve already pledged!</h2>";
    html += '<p>'+errors+'</p>';
    html += '<p><a id="btn_return_to_login" type="submit" class="btn_login sprite_button loginButton" href="#">Login</a></p>';
  } else {
    html = "<h2 id=\"title_error\">Oops!</h2>";
    html += "<p>We’ve found an issue with your entry:</p>";
    if(typeof(errors) === "object") {
      var i, totalErrors = errors.length;
      html += "<ul>";
      for(i=0;i<totalErrors;i++) {
        html+="<li>"+errors[i]+"</li>";
      }
      html += "</ul>";
    } else {
      html += errors;
    }
    html += '<p><a id="btn_return_to_form" type="submit" class="btn_close sprite_button" href="#">Return To Form</a></p>';
  }
  $("body").append('<div id="error_wrapper" class="lightbox"></div>');
  $("#error_wrapper").append('<div id="error_msg_box" class="acct_lightbox"></div>');
  $("#error_msg_box").append('<div class="lightbox_inner">'+html+'</div>');
  //siteOverlay();

  if($('a.login').length) {
    $('a.login').click( function(event){
      event.preventDefault();
      setTimeout('createSignInForm()', 250);
      closeLightBox(event);
    });
  }

  if($('a.loginButton').length) {
    $('a.loginButton').click( function(event){
      event.preventDefault();
      setTimeout('createSignInForm()', 250);
      closeLightBox(event);
    });
  }

  //put mouse focus on the return to form button.
  $('#btn_return_to_form').focus();

  showLightBox($("#error_msg_box"), hideAll);
};

createSuccessLightBox = function(html) {
  //alert("createSuccessLightBox")
  var boxTitle = "<h2 id=\"title_success\">Thank You!</h2>";
  var returnToPage = '<p><a id="btn_return_to_page" type="submit" class="btn_close sprite_button" href="#">Return To Page</a></p>';

  $("body").append('<div id="generic_wrapper" class="lightbox"></div>');
  $("#generic_wrapper").append('<div id="generic_box" class="acct_lightbox"></div>');
  $("#generic_box").append('<div class="lightbox_inner">'+boxTitle+html+returnToPage+'</div>');
  //siteOverlay();

  //put mouse focus on the return to form button.
  $('#btn_return_to_form').focus();

  showLightBox($("#generic_box"));
};

function createGenericLightBox(html) {
  //alert("createGenericLightBox")
  $("body").append('<div id="generic_wrapper" class="lightbox"></div>');
  $("#generic_wrapper").append('<div id="generic_box" class="acct_lightbox"></div>');
  $("#generic_box").append('<div class="lightbox_inner">'+html+'</div>');
  //siteOverlay();
  showLightBox($("#generic_box"));
}

function createTermsLightBox() {
  //alert("createGenericLightBox")

  if ($.browser.webkit) {
    window.open('/legal/terms_conditions.php');
  } else {

    showLoadingBox("<p>Loading Terms</p>");

    var boxTitle = "<h2 class='terms_lightbox_h2'>Connect a Million Minds: Website Terms of Use</h2>";
    var returnToPage = '<p><a id="btn_return_to_page" type="submit" class="btn_close sprite_button" href="#">Return To Page</a></p>';


    $("body").append('<div id="generic_wrapper" class="lightbox"></div>');
    $("#generic_wrapper").append('<div id="generic_box" class="acct_lightbox"></div>');
    $("#generic_box").append('<div class="lightbox_inner">'+boxTitle+'</div>');
    $("#generic_box div").append('<div id="scrollBox"></div>');
    $("#generic_box div").append(returnToPage);
    $("#generic_box").css("width","400px");

    $("#scrollBox").load('/_includes/terms_conditions.php', null, function() {
      $("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
        $("#loading_wrapper").remove();
        //fade back in the form box and re-enabled the submit button after fade in
        showLightBox($("#generic_box"));
      });
    });
  }





}

function createThankYouLightBox() {
  //alert("createThankYouLightBox")


  var boxTitle = "<h2 id=\"title_thank_you_pledge\">Thank you for pledging!</h2>";
  var html = '<p>Now taking you to <em>The Connectory...</em></p>';

  $("body").append('<div id="loading_wrapper" class="lightbox"></div>');
  $("#loading_wrapper").append('<div id="loading_box" class="acct_lightbox"></div>');
  $("#loading_box").append('<div class="lightbox_inner">'+boxTitle+html+'</div>');
  //siteOverlay();
  $("#loading_box").css("text-align","left");
  $("#loading_box").css("width","250px");
  showLightBox($("#loading_box"), false, false);
}

showLoadingBox = function(msg) {
  //alert("showLoadingBox");
  // var html = '<div class="loading_wrapper">';
  var html = '<img src="/_media/ajax-loader.gif" alt="loading bar" class="loading_image" />';
  html += '<h3>'+msg+'</h3>';
  // html += '</div>';

  $("body").append('<div id="loading_wrapper" class="lightbox"></div>');
  $("#loading_wrapper").append('<div id="loading_box" class="acct_lightbox"></div>');
  $("#loading_box").append('<div class="lightbox_inner">'+html+'</div>');

  var innerBox = $("#loading_box");
  var box = innerBox.parent();//$('#lightbox_wrapper');

  //set the css for positioning to center on screen
  var boxWidth = box.width();
  var boxHeight = box.height();
  var windowHeight = $(window).height();

  //clip off lightbox if it's too tall still
  if(boxHeight > windowHeight) {
    boxHeight = windowHeight - 200;
  }

  //for IE6
  if (jQuery.browser.msie) {
    if(parseInt(jQuery.browser.version, 10) === 6) {
      box.css({
          "position": "absolute"
      });
      pngfix();
      move_box();
      scrollInterval = window.setInterval("move_box()", 100);
    } else {
      box.css({
          "width": boxWidth,
          "height": boxHeight,
          "margin-top": -(boxHeight/2)-50,
          "margin-left":-(boxWidth/2) //to position it in the middle (using offset for closebutton)
      });
    }
  } else {
    box.css({
        "width": boxWidth,
        "height": boxHeight,
        "margin-top": -(boxHeight/2)-50,
        "margin-left":-(boxWidth/2) //to position it in the middle (using offset for closebutton)
    });
  }

  if($("#swf_replace").size() === 1) {
    thisMovie("swf_replace").deactivateFlash();
  }

  if($("#discuss").size() === 1) {
    thisMovie("discuss").deactivateFlash();
  }

  siteOverlay(false);
  //fade form in
  box.animate({"opacity":"1"}, 200, "linear");

};

//this takes certain content from the HTML and displays it inside an lightbox
function createHiJackLightBox(item) {
  var jQueryItem = $(item);
  //get its id and remove "lightbox_" prefix from it
  var id = jQueryItem.attr("id").substring(9);
  //find any element that has the same id but with lightbox_content_ prefix to use as the lightbox content
  var html, lightBoxContent = $('#lightbox_content_'+id);

  if(lightBoxContent.size() === 1) {
    html = lightBoxContent.html();
  } else {
    html = "<p>There is no content available.</p>";
  }
  createGenericLightBox(html);
}

function createHREFLightBox(url) {
  //url = typeof(url) !== 'undefined' ? url : "http://www.connectamillionminds.com";
  showLoadingBox("Loading content...");
  $("body").append('<div id="generic_wrapper" class="lightbox"></div>');
  $("#generic_wrapper").append('<div id="href_modal_box" class="acct_lightbox"></div>');
  $("#href_modal_box").load(url, null, function() {
    $("#loading_wrapper").animate({"opacity":"1"}, 200, "linear", function() {
      $("#loading_wrapper").remove();
    });
    //alert("loaded!");
    showLightBox($("#href_modal_box"));
    HREFcallback();
  });
}


function createSendToFriendBox(url) {
  url = typeof(url) !== 'undefined' ? url : "http://www.connectamillionminds.com";
  $("body").append('<div id="send_to_friend_wrapper" class="lightbox"></div>');
  $("#send_to_friend_wrapper").load("/send_to_friend.php", null, function() {
    $("#send_to_friend_form fieldset:first").append('<p><a id="btn_cancel" type="submit" class="btn_close sprite_button" href="#">Cancel</a></p>');
    $("#send_to_friend_form").append('<input id="url" name="url" type="hidden" value="'+url+'" />');
    $("#send_to_friend_form").append('<input id="isModal" name="isModal" type="hidden" value="true" />');
    $("#send_to_friend_form").append('<input id="action" name="action" type="hidden" value="invite" />');
    checkForToolTips("#send_to_friend");

    shareEmailFormBoxes();
    hiJackSendToFriendForm();
    showLightBox($("#send_to_friend"));
  });
}

hiJackSendToFriendForm = function() {
  $("#send_to_friend_form").submit(function(event){

    event.preventDefault();
    //alert("submitted!");
    //disable submit button

    var form = $(this);

    //disable submit button
    var submitButton = $("#send_to_friend_form button[type='submit']");
    submitButton.attr("disabled","disabled");

    //fade out form
    $("#send_to_friend_wrapper").animate({"opacity":"0"}, 200, "linear");

    if(form.attr("errors") !== undefined) {
      if(form.attr("errors").length > 0) {
        // $("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
        //   $("#loading_wrapper").remove();
        //   //createErrorBox(errors, false);
        // });
        return false;
      }
    }

    //fade out box
    $("#send_to_friend_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
      showLoadingBox("Sending message. Please wait...");
      //grab the url from the action attribute
      var action_url = $("#send_to_friend_form").attr("action");
      //alert("action url: "+action_url);
      $.ajax({
           type: "POST",
           url: action_url,
           data: $("#send_to_friend_form").serialize(),
        dataType: "json",
           success: function(json){
            //alert( "Data Saved: " + msg );
          //remove send to friend box
          if(json.success === "true") {
            $("#send_to_friend_wrapper").remove();
            $("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
              $("#loading_wrapper").remove();
              //fade back in the form box and re-enabled the submit button after fade in
              var msg = json.message;
              createSuccessLightBox("<p>"+msg+"</p>");

            });

          } else {
            $("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
              $("#loading_wrapper").remove();
              var msg = [json.message];
              createErrorBox(msg, false);
            });
          }

          //omniture
          if(s !== undefined) {
            s.eVar5 = "send email to friend";
            trackLinkClick("event6");
          }
        },
        error: function(json) {
          //alert('error!');
          //fade out the loading box and remove it after fade out
          $("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
            $("#loading_wrapper").remove();
            var msg = ["There was a problem connecting to the server. Please try again."];
            createErrorBox(msg, false);
          });
        }
      });
    });
  });
};

facebookLogin = function(callback) {
  FB.getLoginStatus(function (response) {
    if (response.authResponse) {
      callback();
    }
    else {
      FB.login(
        function (response) {
          if (response.authResponse) { callback(); }
        },
        {scope:'user_birthday,email,user_location'}
      );
    }
  });
};

loginCallback = function() {
  FB.getLoginStatus(function (response) {
    if(response.authResponse) {
      // Get facebook ID of user and redirect site.
      FB.api('/me', function(response) {
        form = $('#signin_form')[0];
        form.fb_id.value = FB.getAuthResponse().userID;
        $(form).submit();
      });
    } else {
      facebookLogin(loginCallback);
    }
  });
};

hiJackSignInForm = function() {
  $('#signin_form').submit(function(event){
    event.preventDefault();
    signInAjax();
  });
  $('#button_facebook_login').click(function () {
    facebookLogin(loginCallback);
    //console.log(1);
    return false;
  });
};
