var FOLLOWG = new function() {
   // represent which follow tabs is clicked e.g. (following, followed by, people, words)
   // set default to 'follow_by'
    this.tab_id = 'follow_by';
    this.current_viewing_page = 0;
    this.has_prev_arrow = 0;
    this.has_next_arrow = 0;
}

function Follow() {
  this.file_path = 'ajax';
  this.dm = this.getDomain();
  this.follow = 'UFOLLOW';
  this.user = '';
  this.edit_my_profile = document.getElementById('edit_my_profile') || document.getElementById('view_own_profile');
  this.words = '/WORDS/1';

  // BFOLLOW - this is default, maybe change later
  // make sure to set the css defaut in template: default_member_profile
  this.doOnready('UFOLLOW');
  this.setFollow();
  this.setFollowBy();
  this.setFollowPeople();
  this.setFollowWord();
 }


// inheritance extend parent General
Follow.prototype = new General();

// Summary: Set follow events 
Follow.prototype.setFollow = function() {
    var tmp = this;
    var url = this.setURL('UFOLLOW');

    $("#follow").click(function() {
                     FOLLOWG.tab_id = $(this).attr('id');
                     $('#follow_people_word').show();
                     // toggle the link colors
                     $('#follow_chart_people').attr('class', 'follow_chart_pw_blk');
                     $('#follow_chart_words').attr('class', 'follow_chart_pw');
                     tmp.setFollowTab();
                     tmp.turnoffFollowByTab(); 
                     tmp.ajaxCall(url, ['setFollowDIV'], { evntObj : this,
                                                           first_page : 1} );
                     });
}

// Summary: Set Follow People
Follow.prototype.setFollowPeople = function() {
    var tmp = this;
    var url = this.setURL('UFOLLOW');

    $("#follow_chart_people").bind('click',function() {
                                  FOLLOWG.tab_id = $(this).attr('id');
                                  $(this).attr('class','follow_chart_pw_blk');
                                  $('#follow_chart_words').attr('class', 'follow_chart_pw');
                                  tmp.ajaxCall(url, ['setFollowDIV'], { evntObj : this,
                                                                        first_page: 1});
                                  return false;
                                  });
}

// Summary: Set the follow word 
Follow.prototype.setFollowWord = function() {
    var tmp = this;
    var url = this.setURL('USER');
    // indicate get words
    url += this.words;

    $("#follow_chart_words").bind('click', function() {
                                 FOLLOWG.tab_id = $(this).attr('id');
                                 $(this).attr('class','follow_chart_pw_blk');
                                 $('#follow_chart_people').attr('class', 'follow_chart_pw');
                                 tmp.ajaxCall(url, ['buildSetWordHTML'], { evntObj : this,
                                                                           first_page: 1});
                                 return false;
                                 });
}

// Summary: Wrapper to call ajax to invoke 'buildSetWordHTML'
//          used to determine if word exist
Follow.prototype.checkWordWrapper = function() {
    var tmp = this;
    var url = this.setURL('USER');
    // indicate get words
    url += this.words;

    tmp.ajaxCall(url, ['buildSetWordHTML'],{ 'initial' : 1});
}

// Summary : Build the set word html
Follow.prototype.buildSetWordHTML = function(msg, args) {

  if (args.reload_page) {
        window.location.reload( false );
   }

  
  $('#follow_chart_container').html('');

  var unfollow_word = "/WORDUNFOLLOW/";
  var dm = this.dm;
  var url = this.dm + unfollow_word;
  var tmp = this;
  var view_own_profile = '';
  var initial = args['initial'] || 0;
 

  if (args['evntObj']) {
     view_own_profile = $(args['evntObj']).attr('view_own_profile');
  }

  var user_url = this.setURL('USER') + unfollow_word;

  var cnt = 0;
  for (var i in msg) {

      // create pagination
      if (i == 'start_paginate_smeti') {
         this.setPagination(msg[i]);
         continue; 
      }

      cnt++;
      var word = msg[i];
      var url_follow = url + word;
      var div = $("<div></div>");
      var word_url = dm + "/default/word/" + word;
      var a_word = $("<a></a>").attr({ 'href' : word_url }).text(word);
      // when viewing own profile
      if (this.edit_my_profile) {
          var a_unfollow = $("<a></a>").attr({ 'href' : url_follow,
                                             'class' : 'unfollow_word',
                                              'word' : word}).text('unfollow');
          // create event when unfollow link is clicked to recreate page
          a_unfollow.bind('click', function() {
                          //var unfollow_ajax_url = dm + "/ajax" + unfollow_word + word
                          var unfollow_ajax_url = user_url + $(this).attr('word'); 
                          tmp.ajaxCall(unfollow_ajax_url, ['buildSetWordHTML'], { evntObj : this, 'reload_page' : 1});
                          return false;
                          });
          $('#follow_chart_container').append(div.append(a_word).append(a_unfollow));
      } else {
          $('#follow_chart_container').append(div.append(a_word));
      }
  }

  // initial - user clicked on the profile link
  // this is the final check to determine to either show following or follow by tab
  if (initial) {
      if (!cnt) { // when no word is present
          this.turnoffFollowTab();
          this.setFollowByTab();
          $('#follow_people_word').hide();
      } else { // when word is present
          this.turnoffFollowByTab();
          this.setFollowTab();
          $('#follow_chart_people').attr('class', 'follow_chart_pw');
          $('#follow_chart_words').attr('class', 'follow_chart_pw_blk');
      }
  }

}

// Summary: Set follow by
Follow.prototype.setFollowBy = function() {
     var tmp = this;
     var url = this.setURL('BFOLLOW');

     // hide this div for default
     //$('#follow_people_word').hide();
   
     $("#follow_by").click(function() {
                        FOLLOWG.tab_id = $(this).attr('id');
                        $('#follow_people_word').hide();
                        tmp.setFollowByTab();
                        tmp.turnoffFollowTab();
                        tmp.ajaxCall(url, ['setFollowDIV'], { evntObj : this,
                                                              first_page: 1 });
                        });
}


// Summary: Set pagination html
// params: pagination - object that holds data for logic parsing
Follow.prototype.setPagination = function(pagination) {
  var spacer = "http://origin.wordeze.com/images/word/spacer.gif";
  

  // clear previous pagination
  $('#next').html('');
  $('#prev').html('');
  var next = document.getElementById('next');
  var prev = document.getElementById('prev');

  var prev_cpage = pagination['prev_cpage'];
  var next_cpage = pagination['next_cpage'];

  var has_prev_arrow = 0;
  var has_next_arrow = 0;

  for (var x in pagination) {
 //     var span = $("<span></span>").attr({'class' : 'op50'});
      var img = $("<img>").attr({ "src" : spacer});

      if(x == 'next_arrow') {
          if(pagination[x] == 'r') {
              has_next_arrow = 1;
              $('#next').attr({'class' : '',
                               'cpage' : next_cpage});
              
              // create the next event. did not use jquery binds because everytime i create paginator
              // hold the events. thus using associateObjWithEvent
              next.onclick = associateObjWithEvent(this, 'paginateCalls'); 
              $(img).attr('class', 'sp1 fpgnarrowr');
          }
         $('#next').append(img);
      } else if (x == 'prev_arrow') {
          if ( pagination[x] == '1' || pagination[x] == 'l') {
              has_prev_arrow = 1;
              $('#prev').attr({'class' : '',
                               'cpage' : prev_cpage});
              // create the next event. did not use jquery binds because everytime i create paginator
              // hold the events. thus using associateObjWithEvent
              prev.onclick = associateObjWithEvent(this, 'paginateCalls'); 

              $(img).attr('class', 'sp1 fpgnarrowl');
          } 
          $('#prev').append(img);
      }
   }

  // This is used to display the arrows that is dimmed out
  // e.g. When there are no more "next", the ">" arrow is dimmed out
  if(!has_next_arrow && has_prev_arrow) {
      $('#next').attr({'class': 'op50',
                      'cpage' : ''});
      $(img).attr('class', 'sp1 fpgnarrowr');
      next.onclick = function() {
          return false;
      }
      $('#next').append(img);

  } 
  if (!has_prev_arrow && has_next_arrow) {
      $('#prev').attr({'class': 'op50',
                      'cpage' : ''});
      prev.onclick = function() {
          return false;
      }
      $(img).attr('class', 'sp1 fpgnarrowl');
      $('#prev').append(img);
  }


  if (!has_prev_arrow && !has_next_arrow) {
      var no_arrows = { 'class' : 'op50',
          'cpage' : '' };
      $('#prev').attr(no_arrows);
      $('#next').attr(no_arrows);
  }

  


  return 1;
}

// Summary: Sent out the proper ajax calls
Follow.prototype.paginateCalls = function(e, evntObj) {
    var tab = FOLLOWG.tab_id;
    var cpage = $(evntObj).attr('cpage');

    var objHash = { 'follow' : 'UFOLLOW',
                    'follow_by' : 'BFOLLOW',
                    'follow_chart_people' : 'UFOLLOW',
                    'follow_chart_words' : 'USER' };

    var url = this.setURL(objHash[tab]); 
    url += "/CPAGE/" + cpage;

    if(tab == 'follow_chart_words') {
        url += this.words;
        this.ajaxCall(url, ['buildSetWordHTML'], { 'evntObj' : evntObj,
                                                   'id' : 'arrow'});
    } else {
        this.ajaxCall(url, ['setFollowDIV'], { 'evntObj' : evntObj,
                                               'id' : 'arrow'});
    }
}

// Summary: Set the proper div for the follow and follow by
// params: msg -json object
//         args - object with data infor
Follow.prototype.setFollowDIV = function(msg,args) {
  var handle = '';
  var src = '';
  var html_s = '';
  var gender = '';
  var cls = '';
  var html = '';
  var tmpThis = this;
  var initial = args.initial || 0;
  var cnt_users = 0; 

  // reset, clear the previous data
  $('#follow_chart_container').html('');

  for (var x in msg) {
      // create pagination
      if (x == 'start_paginate_smeti') {
          this.setPagination(msg[x]);
          // need to skip this
          continue; 
      }

      if (x != 'start_paginate_smet') {
          // keep count of users
          cnt_users++;
      }

    handle = x;
    src = msg[x]['src'];
    gender = msg[x]['gender'];
    cls = 'sp1 sppic' + gender;
    // do not alter this string, very precise spacing and formatting
    var ahref = $("<a></a>").attr({ href: "/profile/member/" + handle});
    //ahref.click(function() { return true;});
    var ahref_uname = $("<a></a>").attr({ href: "/profile/member/" + handle}).text(handle);

    var img_out_div = $("<div></div>").attr({ 'class' : 'userbox'});

    var img = $("<img>").attr({ 'src': src, 'alt': handle, 'title': handle, 'class' : cls, 'gender' : gender, 'handle': handle});

    if(args['evntObj']) {
       var id_ele = $(args['evntObj']).attr('id');
    }

    if (this.edit_my_profile) {
        // only go into this condition when the "following" or "people" or "edit_my_profile" tab is clicked
        if (initial || id_ele == 'follow' || id_ele == 'follow_chart_people' || ( (id_ele == 'prev' || id_ele == 'next') && FOLLOWG.tab_id != 'follow_by') ) {
            img.bind('mouseover',function(event) {
                     var next_node = $(this).parent().next();
                     var first_child = $(next_node).children(':first');
                     $('#follows_popup').html('');
                     var org_src = $(this).attr('src');
                     var org_handle = $(this).attr('handle');
                     var org_gender = $(this).attr('gender');
                     var new_cls = "sp1 sppic" + org_gender;
                     // create the nested <img> for <div id="follows_popup">
                     var b_img = $("<img>").attr({ 'src' : org_src,
                                                   'handle': org_handle,
                                                   'class' : new_cls,
                                                   'title' : org_handle });


                     var a_img = $("<a>").attr({ 'href' : '/profile/member/' + org_handle}); 

                     var b_form = $("<form></form>").attr({ 'method' : 'post',
                                                            'name' : 'follows_popup_form',
                                                            'id' : 'follows_popup_form' });
                     // create the unfollow link
                     var login_user = $('#rated_chart_small').attr('user');
                     var unfollow = $('<span></span>').attr({ 'login_user' : login_user,
                                                              'following' : org_handle}).text('unfollow');

                     // create  unfollow event link
                     unfollow.bind('click', function() { 
                                   tmpThis['unFollowPeople'](this);
                                   // comment this out for ajax
                                   // tmpThis['unFollowLinkURL'](this); 
                                   $('#follows_popup').hide();
                                   });

                     var pos = $(this).offset();
                     var pos_width = 0; //$(this).width(); 

                     $('#follows_popup').css({left: (pos.left + pos_width) + 'px', 'top': pos.top + 'px', 'z-index' : 1000});
                     $('#follows_popup').append(a_img.append(b_img)).append(b_form.append(unfollow));

                     // set event, when an event has occurred for "follows_popup", set touched attribute to indicate
                     // this is used for "mouseout" event when user mouseout of the box
                     $('#follows_popup').show();

            });

            // use "mouseleave" some reason using "mouseover" when clicking on nested image will invoke hide()
            $('#follows_popup').bind('mouseleave',function(event) {
                                     $(this).hide(); 
                                     });
        }
    }
   // $('#follow_chart_container').append(ahref.append(img)); 
   //$('#follow_chart_container').append(img_out_div.append(ahref.append(img).append(ahref_uname)));
   $('#follow_chart_container').append(img_out_div.append(ahref.append(img)).append(ahref_uname));
  }

  // if there are no users then call the followby tab only on the initial profile view page
  // e.g. User clicks on profile
  if (!cnt_users && initial) {
      this.checkWordWrapper();
  }

}

// Summary: Unfollow people
// params: evntObj - event Object 
Follow.prototype.unFollowPeople = function(evntObj) {
  var dm = this.dm;
  var file = this.file_path;
  var url = dm + "/unfollow/user/" + $(evntObj).attr('following');
  // redirect, for unfollow.php, has code to jump to current browser
  $('#follows_popup_form').attr('action', url);
  $('#follows_popup_form').submit();

  //window.location = url;
}

// Summary: Unfollow link
// params: evntObj - the event object
Follow.prototype.unFollowLinkURL = function(evntObj) {
  var dm = this.dm;
  var file = this.file_path;
  // USERPROFILE 
  var unfollowing_user = 'USER/' + $(evntObj).attr('login_user');
  // person that is following
  var unfollow_person = 'UNFOLLOWING/' + $(evntObj).attr('following');
  
  var url = dm + "/" + this.file_path + "/" + unfollowing_user + "/" + unfollow_person;

  this.ajaxCall(url,['setFollowDIV']); 
}

// Summary: Set the proper div for the follow and follow by
Follow.prototype.setFollowDIV_ = function(msg) {
  var handle = '';
  var src = '';
  var html_s = '';
  var gender = '';
  var cls = '';

  for (var x in msg) {
    handle = x;
    src = "'" + msg[x]['src'] + "'";
    gender = msg[x]['gender'];
    cls = "class='sp1 sppic" + gender + "'";
    // do not alter this string, very precise spacing and formatting
    html_s += "<a href='" + "/profile/member/" + handle + "' >" + "<img src=" + src + " " + cls + " alt=" + handle + " title=" + "'" + handle + "' /></a> ";
  }
    $('#follow_chart_container').html(html_s);   
}

// Summary: Set follow class to on
Follow.prototype.setFollowTab = function() {
  $('#follow_img').attr('class', 'sp1 tab_follow');
}

// Summary: Set FollowBy to off
Follow.prototype.turnoffFollowByTab = function() {
  $('#follow_by_img').attr('class', 'sp1 tab_followby_off');
}

// Summary: Set Follow By
Follow.prototype.setFollowByTab = function() {
  $('#follow_by_img').attr('class', 'sp1 tab_followby');
}


// Summary: Set the Follow By
Follow.prototype.turnoffFollowTab = function() {
  $('#follow_img').attr('class', 'sp1 tab_follow_off');
}

// Summary: Invoke the follow, or follow by users
// params: txt - UFOLLOW, or BFOLLOW
Follow.prototype.doOnready = function(txt) {
    var tmp = this;
    var url = this.setURL(txt);
    var follow_by_img = document.getElementById('follow_by_img');
    var follow_img = document.getElementById('follow_img');
    // only make ajax if those two ids exist meaning they are on that page
    if (follow_by_img && follow_img) {
        // initial: indicate, user viewing profile via clicking on profile link
        this.ajaxCall(url, ['setFollowDIV'], {'initial' : 1} );
    }
}

// Summary: Set url for the follow type
// params: ftype - 'UFOLLOW' or 'BFOLLOW'
Follow.prototype.setURL = function(ftype) {
  var handle = $('#phndl').attr('handle'); 
  var url = this.dm + "/" + this.file_path + "/" +  ftype + "/" + handle;
  return url;
}

try {
    $(document).ready(function(){
                   new Follow();
                    });

} catch (e) {
    alert ('ERROR WITH JQUERY ONREADY STATE ' + e );

}



