$(document).ready(function()
{
init_page();
var all_categories = new Array();

//hide unselected divs for INDEX
$("#sign_up_2,#sign_up_3,#sign_up_4,#sign_up_5,#sign_up_complete,#js_spinner").hide();

//hover pointers
$(".tag_container,.tag_container_sel,.nav_tab,.nav_tab_sel,.cat_box_u,cat_box_s").hover(
  function(){document.body.style.cursor="pointer";},function(){document.body.style.cursor="auto";}
);

//tab selection for INDEX
//$(".action_tab").click(function(){action_tab_switch(this);});

//load categories
ajax_load_all_categories();

 function action_tab_switch(tab_obj){
   $(".action_tab_sel").attr('class',tab_obj.className="action_tab");
  jQuery(tab_obj).attr('class',tab_obj.className="action_tab_sel");
  //show the selected content
  switch(jQuery(tab_obj).attr("id")){
    case("reg_one"):
      $("#sign_up_1").show();
      $("#sign_up_2").hide();
      $("#sign_up_3").hide();
      $("#sign_up_4").hide();
      $("#sign_up_5").hide();
      break;
    case("reg_two"):
      $("#sign_up_1").hide();
      $("#sign_up_2").show();
      $("#sign_up_3").hide();
      $("#sign_up_4").hide();
      $("#sign_up_5").hide();
      break;
    case("reg_three"):
      $("#sign_up_1").hide();
      $("#sign_up_2").hide();
      $("#sign_up_3").show();
      $("#sign_up_4").hide();
      $("#sign_up_5").hide();
      break;
    case("reg_four"):
      $("#sign_up_1").hide();
      $("#sign_up_2").hide();
      $("#sign_up_3").hide();
      $("#sign_up_4").show();
      $("#sign_up_5").hide();
      break;
    case("reg_five"):
      $("#sign_up_1").hide();
      $("#sign_up_2").hide();
      $("#sign_up_3").hide();
      $("#sign_up_4").hide();
      $("#sign_up_5").show();
      user_categories();
      break;
  }
 }
 
//select the first tab for INDEX
$("#tab_category,#reg_one").attr('class',this.className="action_tab_sel");

//category tab user selection
$(".tag_container").click(function(){
  $(".tag_container_sel").attr('class',this.className="tag_container");
  jQuery(this).attr('class',this.className="tag_container_sel");
 });

//message from hash function
hash_message();
function hash_message(){
  if(document.location.hash=="#requre_login"){
    response_message("#response_message_login","you must log-in to do that");
  }
}

//INDEX user log out_____________________________________________________________________________________________________________
$("#logout").click(function(){
  //destroy session !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1
  ajax_logout_user()
});
  
function ajax_logout_user(){
  $.get("account_logout.php",
    function(data2){
      response_message("#response_message_login","Logged out.");
      $("input[name='uuid']").attr('value','');
    });
}


//INDEX user log in_______________________________________________________________________________________________________
//bind the enter key for login
$("#js_login_email").keyup(function (e) {
  if (e.keyCode == 13){
    $("#js_login_password").focus();
  }
});
$("#js_login_password").keyup(function (e) {
  if (e.keyCode == 13){
    login_init();
  }
});
$("#log_in_button").click(function(){
  login_init();
});
function login_init(){
  var user_email = $("input[name='email']").attr('value');
  var user_password = $("input[name='password']").attr('value');
  if ($("input[name='uuid']").attr('value')==""){
    $("#js_spinner").show();
    ajax_login_user(user_email,user_password, true);
  }else{
    ajax_logout_user();
    $("#js_spinner").show();
    ajax_login_user(user_email,user_password, true);
  }    
}
function ajax_login_user(email, password, redirect_control){
  
  var url = "crossdomain.php?http://identityshare.appspot.com/901bcc678021c0e12f1583085cafda1d/user/login/"+escape(email)+"/"+escape(password);
  //send request to app engine
  $.get(url,
    function(data){
      //put data in JSON ready form
      var response = eval('(' + data + ')');
      //Error
      if (response.error==true){
        $("#js_spinner").hide();
        response_message("#response_message_login",response.message);
      }
      else{
        //login and set the uuid
        $.post("account_login.php", { uuid: response.message[0].user_id, key: response.message[0].user_key },
        function(data2){
          $("#js_spinner").hide();
          //var response2 = eval('(' + data2 + ')');
          response_message("#response_message_login",data2.message);
          $("input[name='uuid']").attr('value',response.message[0].user_id);
          $("input[name='key']").attr('value',response.message[0].user_key); 
          //redirect to profile
          if (redirect_control && data2.message=='Logged in.') {
            redirect("profile.php");
          }
        }, "json");
      }
    },"json");
}
//INDEX page 1_______________________________________________________________________________________________________
//bind enter keys
$("#js_new_email").keyup(function (e) {
  if (e.keyCode == 13){
    $("#js_new_password").focus();
  }
});
$("#js_new_password").keyup(function (e) {
  if (e.keyCode == 13){
    $("#js_new_password2").focus();
  }
});
$("#js_new_password2").keyup(function (e) {
  if (e.keyCode == 13){
    $("#sign_up_button_1").focus();
  }
});
$("#sign_up_button_1").click(function(){
  var new_email = $("input[name='new_email']").attr('value');
  var new_password = $("input[name='new_password']").attr('value');
  var new_password2 = $("input[name='new_password2']").attr('value');
  $(".response_message").remove();
  if (new_email=="" || new_password=="" || new_password2==""){
    response_message("#js_signup_form_1","You have left a field blank.");
  }else{
    new_user(new_email,new_password,new_password2);
  }
});

//INDEX 
function new_user(email, password1, password2){
  if (password1==password2){
    ajax_new_user(email, password1);
  }
  else{
    response_message("#js_signup_form_1","The passwords do not match.");
    $("#js_new_password").attr('value','');
    $("#js_new_password2").attr('value','');
    $("#js_new_password").focus();
  }
}
//INDEX 
function ajax_new_user(email, password){
  var url = "crossdomain.php?http://identityshare.appspot.com/901bcc678021c0e12f1583085cafda1d/user/new/"+escape(email)+"/"+escape(password);
  $.get(url,
    function(data){
      var response = eval('(' + data + ')');
      if (response.error==true){
        response_message("#js_signup_form_1",response.message);
        //set the focus to the error spot
        $("#js_new_email").focus();
      }
      else{
        response_message("#js_signup_form_1",response.message);
        ajax_login_user(email, password, false);
        //redirect the tab
        action_tab_switch($("#reg_two"));
      }
    },"json");
}

//INDEX New Category
function new_category(category, parent, relation, tag){ 
  var uuid = $("input[name='uuid']").attr('value');
  
  if (uuid != ""){
    ajax_new_category(uuid, category, parent, relation, tag);
  }else{
    response_message("#response_message_login","Not logged-in.");
  }    
}

//INDEX Ajax new Category
function ajax_new_category(user_id, category, parent, relation, tag){
  var url = "crossdomain.php?http://identityshare.appspot.com/901bcc678021c0e12f1583085cafda1d/category/new/"+user_id+"/"+escape(category)+"/"+escape(parent)+"/"+escape(relation)+"/"+escape(tag);
  //alert("901bcc678021c0e12f1583085cafda1d/category/new/"+user_id+"/"+category+"/"+parent+"/"+relation+"/"+tag);
  $.get(url,
    function(data){
      var response = eval('(' + data + ')');
      response_message("#response_message_login",unescape(category));
    },"json");
}

//INDEX PAGE 2____________________________________________________________________________________________________________
//sorting function for category array
function category_sort(a,b){
  return b.count - a.count;
}
function ajax_load_all_categories(){ //INDEX load categories pg 2
  //clear js_cat_list
  $("#js_cat_list").html('');
  //add title to js_cat_list
  $("#js_cat_list").append('<div class="cat_box_title">All categories:</div><div id="js_spinner_pg2"><img src="resources/spinner.gif" alt="spinner" /></div>');
  var url = "crossdomain.php?http://identityshare.appspot.com/901bcc678021c0e12f1583085cafda1d/category/list/";
  //send request to app engine
  $.get(url,
    function(data){
      //put data in JSON ready form
      var response = eval('(' + data + ')');
      //hide spinner
      $("#js_spinner_pg2").hide();
      //loop through the json and append items to div
      for(i=0; i<response.categories.length; i++) {
        //sort the array by usage count
        response.categories.sort(category_sort);
        //weed out unneccesary categories
        var this_response = unescape(response.categories[i].category);
        if(this_response!="identityshare"){
          //append the categories to the list
          $("#js_cat_list").append('<div class="cat_box_u">'+this_response+'</div>');
          //add categories to autocomplete**********************************************************8
          all_categories[all_categories.length] = this_response;
        }
      }
    //initialize autocomplete on pg 4***************************************************************
    $("#js_input1_pg4").autocomplete(all_categories);
    cat_box_click();
    },"json");
}

function cat_box_click(){
  //cat_box click
  $(".cat_box_u").click(function(){
    if(jQuery(this).attr('class')=="cat_box_u"){
      jQuery(this).attr('class',this.className="cat_box_s");
    }else{
      jQuery(this).attr('class',this.className="cat_box_u");
    }
  });
  //hover pointers
  $(".cat_box_u,.cat_box_s").hover(
    function(){document.body.style.cursor="pointer";},function(){document.body.style.cursor="auto";}
  );
}

//js_move_rt click
$("#js_move_rt").click(function(){
  $("#js_cat_list > .cat_box_s").appendTo("#js_cat_list_2").attr('class',this.className="cat_box_u");
});

//js_move_left click
$("#js_move_left").click(function(){
  $("#js_cat_list_2 > .cat_box_s").appendTo("#js_cat_list").attr('class',this.className="cat_box_u");
});

//sign_up_button_2 click Add selected categories as inputs.
$("#sign_up_button_2").click(function(){
  var category_count=0;
  //get a category count
  $("#js_cat_list_2 > .cat_box_s, #js_cat_list_2 > .cat_box_u").each(function(){
    category_count++;
  });
  $(".response_message").remove();
  if (category_count>4){
    $("#js_sel_cats").empty();
    $("#js_cat_list_2 > .cat_box_s, #js_cat_list_2 > .cat_box_u").each(function(){
        var myname = $(this).text();
        $("#js_sel_cats").append('<div class="form_item">'+myname+':<input type="text" id="type_ahead_'+md5(myname)+'" name="'+myname+'" value="" size="13" /></div>');
        ajax_get_tags(myname);
    });
    action_tab_switch($("#reg_three"));
  }else{
    response_message("#js_signup_form_2","You must choose at least 5 categories.");
  }
});

function ajax_get_tags(sel_category){
  var all_tags = new Array();
  var url = "crossdomain.php?http://identityshare.appspot.com/901bcc678021c0e12f1583085cafda1d/category/tag/"+escape(sel_category);
  //send request to app engine
  $.get(url,
    function(data){
      //put data in JSON ready form
      var response = eval('(' + data + ')');
      //loop through the json and append items to div
      for(i=0; i<response.tags.length; i++) {
        all_tags[all_tags.length]=unescape(response.tags[i].tag);
      }
      $("#type_ahead_"+md5(sel_category)).autocomplete(all_tags);
      //alert("#type_ahead_"+escape(sel_category));
  },"json");
}

//INDEX PAGE 3____________________________________________________________________________________________________________
//sign_up_button_3_click 

$("#sign_up_button_3").click(function(){
  var loop_count=0;
  var category_count=0;
  var error_3=false;
  //clear any messages
  $(".response_message").remove();
  //loop through the form items
  $("#js_sel_cats > .form_item").each(function(){
    category_count++;
    if($(this).children().attr('value')==""){
      error_3=true;
    }else{
      loop_count++;
    }
  });

  if (error_3){  
    response_message("#js_signup_form_3","You have left a description empty.");
  }
  if (loop_count==category_count){
    //loop through the form items again
    $("#js_sel_cats > .form_item").each(function(){
      var new_cat_name = $(this).text().replace(":",""); //remove colon
      var new_cat_value = $(this).children().attr('value');
      //add the categories to the database
      new_category(new_cat_name, "identityshare", "is", new_cat_value)
      action_tab_switch($("#reg_four"));
    });
  }
});

//INDEX PAGE 4____________________________________________________________________________________________________________
//bind the enter key for page 4
$("#js_input1_pg4").keyup(function (e) {
  if (e.keyCode == 13){
    $("#js_input2_pg4").focus();
  }
});
$("#js_input2_pg4").keyup(function (e) {
  if (e.keyCode == 13){
    $("#add_custom_cat").focus();
  }
});
//add custom category button
$("#add_custom_cat").click(function(){
  //clear any messages
  $(".response_message").remove();
  //get the values of the new category
  var new_cat = $("input[name='new_cat_1']").attr('value');
  var new_tag = $("input[name='new_tag_1']").attr('value');
  if (new_cat=="" || new_tag==""){
    //the user didn't input anything
    response_message("#js_signup_form_4","You did not enter enough information.");
  }else{
    //send the data via ajax
    new_category(new_cat, "identityshare", "is", new_tag);
    //add the reated category to the form
    $("#js_custom_cat").prepend('<div class="form_item">'+new_cat+':'+new_tag+'</div>');
    //clear the old inputs
    $("input[name='new_cat_1']").attr('value','');
    $("input[name='new_tag_1']").attr('value','');
  }
});

//sign_up_button_4_click 
$("#sign_up_button_4").click(function(){
  action_tab_switch($("#reg_five"));
});
//INDEX PAGE 5____________________________________________________________________________________________________________
//load the categories that this user has selected
function user_categories(){
  var user_key = $("input[name='key']").attr('value'); 
  var url = "crossdomain.php?http://identityshare.appspot.com/901bcc678021c0e12f1583085cafda1d/category/user/"+user_key;
  //show spinner
  $("#js_cat_list_5").append('<div id="js_spinner_pg5"><img src="resources/spinner.gif" alt="spinner" /></div>');
  //send request to app engine
  $.get(url,
    function(data){
      //hide spinner
      $("#js_spinner_pg5").hide();
      //put data in JSON ready form
      var response = eval('(' + data + ')');
      //loop through the json and append items to cat_box
      var select_cat = '';
      for(i=0; i<response.categories.length; i++) {
        //weed out unneccesary categories
        var this_cat = unescape(response.categories[i].category);
        var this_tag = unescape(response.categories[i].category_tag);
        if(this_cat!="identityshare"){
          //append the categories to the list
          select_cat +=  '<div class="form_item">'+this_cat+': '+this_tag+'<input type="checkbox" name="'+this_cat+'" id="'+this_tag+'" /></div>';
        }
      }
      //append the categories
      $("#js_cat_list_5").append(select_cat);
  },"json");
}
  
$("#sign_up_button_5").click(function(){
  var check_box_count=0;
  //clear any messages
  $(".response_message").remove();
  //loop through the categories and make sure five are selected
  $("#js_cat_list_5 > .form_item").each(function(){
    //alert($(this).children().attr("checked"));
    if ($(this).children().attr("checked")==true)
      check_box_count++;
  });
  if (check_box_count==5){
    //send to database
    var uuid = $("input[name='uuid']").attr('value'); 
    $("#js_cat_list_5 > .form_item").each(function(){
      var check_category = $(this).children().attr('name');
      var check_parent = "identityshare";
      var check_tag = $(this).children().attr('id');
      var check_relation = "is";
      if ($(this).children().attr("checked")==true){
        var url = "crossdomain.php?http://identityshare.appspot.com/901bcc678021c0e12f1583085cafda1d/category/primary/"+uuid+"/"+escape(check_category)+"/"+escape(check_parent)+"/"+escape(check_relation)+"/"+escape(check_tag)+"/True";
        //send request to app engine
        $.get(url,
          function(data){
            response_message("#response_message_login",check_category+" set to Primary.");
            //redirect to profile
            redirect("profile.php");
          },"json");
      }
    });
    //change page
    //$("#sign_up_5").hide();
    //$("#sign_up_complete").show();
  }else{
    response_message("#js_signup_form_5","You must select 5 categories.");
  }
});

//verify incoming email addresses ____________________________________________________________________________________________
  var verify_id = $("input[name='verify']").attr('value');
  if (verify_id != null){
    var v_url = 'crossdomain.php?http://identityshare.appspot.com/901bcc678021c0e12f1583085cafda1d/user/verify/'+verify_id;
    $.get(v_url,
      function(data){
        //put data in JSON ready form
        var response = eval('(' + data + ')');
        response_message("#response_message_login",response.message);
    },"json");
  }
});