jQuery.noConflict();

var KoreanTwitters = {
    init: function() {
        KoreanTwitters.bindButtons();

        jQuery('.go').click(function() {
            var location = '/ktwitter/tags/' + this.form.enter_category.value.replace('#', '') + '/tags';
            window.location = location;
            return false;
        });

    },
    unBindButtons: function() {
        jQuery('.a-info').unbind().click(function() {
            return false;
        });
        jQuery('.b-info').unbind().click(function() {
            return false;
        });
        jQuery('.school-info').unbind().click(function() {
            return false;
        });
        jQuery('.favorite_tweet').unbind().live('click', function() {
            return false;
        });
        jQuery('.favorite_tweet2').unbind().live('click', function() {
            return false;
        });
        jQuery('.reply_tweet').unbind().live('click', function() {
            return false;
        });
        jQuery('.retweet_tweet').unbind().live('click', function() {
            return false;
        });
        jQuery('.retweet_tweet2').unbind().live('click', function() {
            return false;
        });
        jQuery('.newretweet_tweet').unbind().live('click', function() {
            return false;
        });
        jQuery('.newretweet_tweet2').unbind().live('click', function() {
            return false;
        });
        jQuery('.delete_tweet').unbind().live('click', function() {
            return false;
        });
        jQuery('.userlist_follow').unbind().live('click', function() {
            return false;
        });
        jQuery('.in_reply_to').unbind().live('click', function() {
            return false;
        });
        jQuery('.in_reply_to_hover').unbind().live('click', function() {
            return false;
        });
    },
    bindButtons: function() {
        jQuery('.a-info').click(function() {
            KoreanTwitters.unBindButtons();
            jQuery('.more-info:not(#info-' + this.id + ')').hide('fast');
            jQuery('#info-' + this.id).toggle('fast', KoreanTwitters.bindButtons);
            return false;
        });
        jQuery('.b-info').click(function() {
            KoreanTwitters.unBindButtons();
            jQuery('.more-info-lg:not(#info-' + this.id + ')').hide('fast');
            jQuery('#info-' + this.id).toggle('fast', KoreanTwitters.bindButtons);
            return false;
        });
        jQuery('.school-info').click(function() {
            KoreanTwitters.unBindButtons();
            jQuery('#more-school').toggle('fast', KoreanTwitters.bindButtons);
            return false;
        });
        jQuery(".favorite_tweet").live('click', function() {
          var aObj = jQuery(this);
          KoreanTwitters.unBindButtons();
          var tweet = aObj.attr('id');
          var tweets = tweet.split("_");
          var fav_url = ""
          var fav_title = ""
          var this_id = ""
          if(tweets[1] == "create") {
            fav_url = "/twit/favorite_create"
            fav_title = "Remove favorite"
            this_id = tweets[0] + "_destroy"
          } else {
            fav_url = "/twit/favorite_destroy"
            fav_title = "Make favorite"
            this_id = tweets[0] + "_create"
          }
          jQuery.ajax({
            url: fav_url,
            type: 'post',
            dataType: 'script',
            data: { '_method': 'post', id: tweets[0] },
            success: function(data) {
              aObj.find("img").attr("src", data).attr("title", fav_title);
              aObj.attr("id", this_id);
            }
          });
          KoreanTwitters.bindButtons();
          return false;
        });
        jQuery(".favorite_tweet2").live('click', function() {
          var aObj = jQuery(this);
          KoreanTwitters.unBindButtons();
          var tweet = aObj.attr('id');
          var tweets = tweet.split("_");
          var fav_url = ""
          var fav_title = ""
          var this_id = ""
          if(tweets[1] == "create") {
            fav_url = "/twit/favorite_create"
            fav_title = "Remove favorite"
            this_id = tweets[0] + "_destroy"
          } else {
            fav_url = "/twit/favorite_destroy"
            fav_title = "Make favorite"
            this_id = tweets[0] + "_create"
          }
          jQuery.ajax({
            url: fav_url,
            type: 'post',
            dataType: 'script',
            data: { '_method': 'post', id: tweets[0] },
            success: function(data) {
              aObj.find("img").attr("src", data).attr("title", fav_title);
              aObj.attr("id", this_id);
            }
          });
          KoreanTwitters.bindButtons();
          return false;
        });
        jQuery(".reply_tweet").live('click', function() {
          var aObj = jQuery(this);
          tmp_status_id = aObj.attr('id');
          var reply_id_name = tmp_status_id.split("_");
          var reply_id = reply_id_name[0];
          reply_id_name.shift();
          var reply_name = reply_id_name.join("_");
          cUrl = "/" + jQuery('.this_is_mine').attr("id");
          cTweet = "@" + reply_name;
          KoreanTwitters.unBindButtons();
          if (jQuery('.is_this_mine').attr("id") == '0') {
            jQuery('textarea#tweet_content').val(cTweet);
            jQuery('#in_reply_to_status_id').val(reply_id);
            jQuery('#in_reply_to').val(reply_name);
            jQuery('textarea#tweet_content').focus();
            KoreanTwitters.bindButtons();
            return false;
          } else {
            var myForm = document.createElement("form");
            myForm.method="post";
            myForm.action = cUrl;
            var myInput1 = document.createElement("input");
            var myInput2 = document.createElement("input");
            var myInput3 = document.createElement("input");
            myInput1.setAttribute("name", "status");
            myInput1.setAttribute("value", cTweet);
            myInput2.setAttribute("name", "in_reply_to_status_id");
            myInput2.setAttribute("value", reply_id);
            myInput3.setAttribute("name", "in_reply_to");
            myInput3.setAttribute("value", reply_name);
            myForm.appendChild(myInput1);
            myForm.appendChild(myInput2);
            myForm.appendChild(myInput3);
            document.body.appendChild(myForm);
            myForm.submit();
            document.body.removeChild(myForm);
            KoreanTwitters.bindButtons();
          }
        });
        jQuery(".retweet_tweet").live('click', function() {
          var aObj = jQuery(this);
          tmp_status_id = aObj.attr('id');
          var reply_id_name = tmp_status_id.split("_");
          var reply_id = reply_id_name[0];
          reply_id_name.shift();
          var reply_name = reply_id_name.join("_");
          cUrl = "/" + jQuery('.this_is_mine').attr("id");
          cTweet = "RT @" + reply_name + " " + aObj.parent().parent().parent().find(".tweet_text").text();
          KoreanTwitters.unBindButtons();
          if (jQuery('.is_this_mine').attr("id") == '0') {
            jQuery('textarea#tweet_content').val(cTweet);
            jQuery('#in_reply_to_status_id').val("");
            jQuery('#in_reply_to').val("");
            jQuery('#tweet_content').focus();
            KoreanTwitters.bindButtons();
            return false;
          } else {
            var myForm = document.createElement("form");
            myForm.method="post";
            myForm.action = cUrl;
            var myInput = document.createElement("input");
            myInput.setAttribute("name", "status");
            myInput.setAttribute("value", cTweet);
            myForm.appendChild(myInput);
            document.body.appendChild(myForm);
            myForm.submit();
            document.body.removeChild(myForm);
            KoreanTwitters.bindButtons();
          }
        });
        jQuery(".retweet_tweet2").live('click', function() {
          var aObj = jQuery(this);
          tmp_status_id = aObj.attr('id');
          var reply_id_name = tmp_status_id.split("_");
          var reply_id = reply_id_name[0];
          reply_id_name.shift();
          var reply_name = reply_id_name.join("_");
          cUrl = "/" + jQuery('.this_is_mine').attr("id");
          cTweet = "RT @" + reply_name + " " + aObj.parent().parent().find("#tweet_text").text();
          KoreanTwitters.unBindButtons();
          var myForm = document.createElement("form");
          myForm.method="post";
          myForm.action = cUrl;
          var myInput = document.createElement("input");
          myInput.setAttribute("name", "status");
          myInput.setAttribute("value", cTweet);
          myForm.appendChild(myInput);
          document.body.appendChild(myForm);
          myForm.submit();
          document.body.removeChild(myForm);
          KoreanTwitters.bindButtons();
        });
        jQuery(".newretweet_tweet").live('click', function() {
          var aObj = jQuery(this);
          tmp_status_id = aObj.attr('id');
          var reply_id_name = tmp_status_id.split("_");
          var reply_id = reply_id_name[0];
          KoreanTwitters.unBindButtons();
          if ( confirm("리트윗을 하시면 모든 follower분들께도 전달이 됩니다.") ) {
            jQuery.ajax({
              url: '/twit/retweet',
              type: 'post',
              dataType: 'script',
              data: { '_method': 'post', id: reply_id },
              success: function(data) {
              }
            });
          }
          KoreanTwitters.bindButtons();
        });
        jQuery(".newretweet_tweet2").live('click', function() {
          var aObj = jQuery(this);
          tmp_status_id = aObj.attr('id');
          var reply_id_name = tmp_status_id.split("_");
          var reply_id = reply_id_name[0];
          KoreanTwitters.unBindButtons();
          if ( confirm("리트윗을 하시면 모든 follower분들께도 전달이 됩니다.") ) {
            jQuery.ajax({
              url: '/twit/retweet',
              type: 'post',
              dataType: 'script',
              data: { '_method': 'post', id: reply_id },
              success: function(data) {
              }
            });
          }
          KoreanTwitters.bindButtons();
        });
        jQuery(".delete_tweet").live('click', function() {
          var aObj = jQuery(this);
        });
        jQuery(".delete_tweet").live('click', function() {
          var aObj = jQuery(this);
          tmp_status_id = aObj.attr('id');
          var reply_id_name = tmp_status_id.split("_");
          var reply_id = reply_id_name[0];
          KoreanTwitters.unBindButtons();
          if ( confirm("정말 이글을 삭제 하시겠습니까?") ) {
            jQuery.ajax({
              url: '/twit/delete_tweet',
              type: 'post',
              dataType: 'script',
              data: { '_method': 'post', id: reply_id },
              success: function(data) {
                if (data == "ok") {
                  jQuery('#'+reply_id).remove();
                } else {
                  alert("Failed to delete this tweet!!!");
                }
              }
            });
          }
          KoreanTwitters.bindButtons();
        });
        jQuery('.userlist_follow').live('click', function() {
            var aObj = jQuery(this);
            KoreanTwitters.unBindButtons();
            if ( jQuery(this).find("a").attr("id") == "userlist_following_"+this.id ) {
              if ( confirm(this.id + "님을 언팔로우하시겠습니까?") ) {
                jQuery.ajax({
                  url: '/twit/unfriendship',
                  type: 'post',
                  dataType: 'script',
                  data: { '_method': 'post', id: this.id, loc: 'userlist' },
                  success: function(data) {
                    aObj.html(data);
                    KoreanTwitters.bindButtons();
                  }
                });
              }
            } else if ( jQuery(this).find("a").attr("id") == "userlist_follow_"+this.id ) {
              jQuery.ajax({
                url: '/twit/friendship',
                type: 'post',
                dataType: 'script',
                data: { '_method': 'post', id: this.id, loc: 'userlist' },
                success: function(data) {
                  aObj.html(data);
                  KoreanTwitters.bindButtons();
                }
              });
            } else {
              window.location.href = "/ktwitter/signin";
            }
            return false;
        });
        jQuery('.in_reply_to').live('click', function() {
            KoreanTwitters.unBindButtons();
            tmp_status_id = jQuery(this).attr('id');
            var reply_oid_id = tmp_status_id.split("_");

            if ( !jQuery("#reply_"+reply_oid_id[1]).length ) {
              jQuery.post("/twit/get_reply", { id: reply_oid_id[1], oid: reply_oid_id[0] }, function(data) {
                jQuery('#'+reply_oid_id[0]).append(data);
              });
            }
            KoreanTwitters.bindButtons();
            return false;
        });
        jQuery('.in_reply_to_hover').live('click', function() {
            KoreanTwitters.unBindButtons();
            tmp_status_id = jQuery(this).attr('id');
            var reply_oid_id = tmp_status_id.split("_");

            if ( !jQuery("#reply_"+reply_oid_id[1]).length ) {
              jQuery.post("/twit/get_reply_hover", { id: reply_oid_id[1], oid: reply_oid_id[0] }, function(data) {
                jQuery('#'+reply_oid_id[0]).append(data);
              });
            }
            KoreanTwitters.bindButtons();
            return false;
        });

    }
};

jQuery(document).ready(function() {
  KoreanTwitters.init();

  var keyFix   = new hangulInput.fix("main_tags");
  var keyFix1  = new hangulInput.fix("tag-1");
  var keyFix2  = new hangulInput.fix("tag-2");
  var keyFix3  = new hangulInput.fix("tag-3");
  var keyFix4  = new hangulInput.fix("tag-4");
  var keyFix5  = new hangulInput.fix("tag-5");
  var keyFix6  = new hangulInput.fix("tag-6");
  var keyFix7  = new hangulInput.fix("school-1");
  var keyFix8  = new hangulInput.fix("school-2");
  var keyFix9  = new hangulInput.fix("school-3");
  var keyFix10 = new hangulInput.fix("company-1");
  var keyFix11 = new hangulInput.fix("company-2");
  var keyFix12 = new hangulInput.fix("company-3");
  var keyFix13 = new hangulInput.fix("main_search");
  var keyFix14 = new hangulInput.fix("twt_search");

  function log(event, data, formatted) {
    jQuery("<li>").html( !data ? "No match!" : "Selected: " + formatted).appendTo("#result");
  }

  function findValue(li) {
    if( li == null ) return alert("No match!");
    if( !!li.extra ) var sValue = li.extra[1];
    else var sValue = li.selectValue;

    location.href = "/ktwitter/tags/" + sValue + "/1/tags";
//    alert("The value you selected was: " + sValue);
  }

  function selectItem(li) {
    findValue(li);
  }

  function formatItem(row) {
    return row[0] + " (" + row[1] + "명)";
  }
  function formatResult(row) {
    return row[0].replace(/(<.+?>)/gi, '');
  }

  jQuery("#main_tags").autocomplete('/php/autocomplete.php', {
      minChars: 1, 
      width: 247,
      delay: 10, 
      autoFill:false,
      maxItemsToShow:40,
      extraParams: {type:0},
      formatItem: formatItem,
      onItemSelect: selectItem
  });

  jQuery("#main_tags").autocomplete('/php/autocomplete.php', {
      minChars: 1, 
      width: 247,
      delay: 10, 
      autoFill:false,
      maxItemsToShow:40,
      extraParams: {type:0},
      formatItem: formatItem,
      onItemSelect: selectItem
  });

  jQuery("#tag-1").autocomplete('/php/autocomplete.php', {
      minChars: 1,
      width: 338,
      delay: 10,
      maxItemsToShow:40,
      extraParams: {type:1},
      formatItem: formatItem
  }); 

  jQuery("#tag-2").autocomplete('/php/autocomplete.php', {
      minChars: 1,
      width: 338,
      delay: 10,
      maxItemsToShow:40,
      extraParams: {type:0},
      formatItem: formatItem
  });

  jQuery("#tag-3").autocomplete('/php/autocomplete.php', {
      minChars: 1,
      width: 338,
      delay: 10,
      maxItemsToShow:40,
      extraParams: {type:0},
      formatItem: formatItem
  });

  jQuery("#tag-4").autocomplete('/php/autocomplete.php', {
      minChars: 1,
      width: 338,
      delay: 10,
      maxItemsToShow:40,
      extraParams: {type:0},
      formatItem: formatItem
  });

  jQuery("#tag-5").autocomplete('/php/autocomplete.php', {
      minChars: 1,
      width: 338,
      delay: 10,
      maxItemsToShow:40,
      extraParams: {type:0},
      formatItem: formatItem
  });

  jQuery("#tag-6").autocomplete('/php/autocomplete.php', {
      minChars: 1,
      width: 338,
      delay: 10,
      maxItemsToShow:40,
      extraParams: {type:0},
      formatItem: formatItem
  });

  jQuery("#school-1").autocomplete('/php/autocomplete.php', {
      minChars: 1,
      width: 338,
      delay: 10,
      maxItemsToShow:40,
      extraParams: {type:2},
      formatItem: formatItem
  });

  jQuery("#school-2").autocomplete('/php/autocomplete.php', {
      minChars: 1,
      width: 338,
      delay: 10,
      maxItemsToShow:40,
      extraParams: {type:2},
      formatItem: formatItem
  });

  jQuery("#school-3").autocomplete('/php/autocomplete.php', {
      minChars: 1,
      width: 338,
      delay: 10,
      maxItemsToShow:40,
      extraParams: {type:2},
      formatItem: formatItem
  });

  jQuery("#company-1").autocomplete('/php/autocomplete.php', {
      minChars: 1,
      width: 338,
      delay: 10,
      maxItemsToShow:40,
      extraParams: {type:3},
      formatItem: formatItem
  });

  jQuery("#company-2").autocomplete('/php/autocomplete.php', {
      minChars: 1,
      width: 338,
      delay: 10,
      maxItemsToShow:40,
      extraParams: {type:3},
      formatItem: formatItem
  });

  jQuery("#company-3").autocomplete('/php/autocomplete.php', {
      minChars: 1,
      width: 338,
      delay: 10,
      maxItemsToShow:40,
      extraParams: {type:3},
      formatItem: formatItem
  });

  jQuery('#up_down img').tooltip({
      track: true,
      delay: 0,
      showURL: false,
      fade: 250
  });

  jQuery('.clearField').clearField({
    blurClass: 'clearFieldBlurred',
    activeClass: 'clearFieldActive'
  });

  jQuery.get("/twit/top_login_logout", function(data) {
    jQuery(".tabs_right").html(data);
  });

  /* for image lazzy load 
  jQuery('.tweet_media img').lazyload({
    container: jQuery(this),
    placeholder : "/img/grey.gif",
    effect : "fadeIn"
  });
  */

  /* add for curved corner */

});

function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }

function letme_search() {
  var kword = document.getElementById("main_search").value;

  if (kword == "태그, 이름과 Bio 검색") {kword = "";}

  var value = kword;
  var value_length = value.length;
  var value_bytes = 0;
  var ls_one_char = "";
  var i = 0;
  for (i=0; i<value_length; i++) {
    ls_one_char = value.charAt(i);
    if ( escape(ls_one_char).length > 4) {
      value_bytes += 2;
    } else {
      value_bytes++;
    }
  }

  if ( value_bytes < 2 ) {
    alert("검색할 키워드를 2자이상 입력해주세요 !!!");
    return false;
  } else {
    location.href = "/ktwitter/search?kword=" + kword;
  }
}

function twt_search() {
  var kword = document.getElementById("twt_search").value;

  var value = kword;
  var value_length = value.length;
  var value_bytes = 0;
  var ls_one_char = "";
  var i = 0;
  for (i=0; i<value_length; i++) {
    ls_one_char = value.charAt(i);
    if ( escape(ls_one_char).length > 4) {
      value_bytes += 2;
    } else {
      value_bytes++;
    }
  }

  if ( value_bytes < 2 ) {
    alert("검색할 키워드를 2자이상 입력해주세요 !!!");
    return false;
  } else {
    location.href = "/ktwitter/twtsearch?kword=" + kword;
  }
}

function search_all() {
  var kword = document.getElementById("main_search").value;

  if (kword == "태그, 이름과 Bio 검색") {kword = "";}

  var value = kword;
  var value_length = value.length;
  var value_bytes = 0;
  var ls_one_char = "";
  var i = 0;
  for (i=0; i<value_length; i++) {
    ls_one_char = value.charAt(i);
    if ( escape(ls_one_char).length > 4) {
      value_bytes += 2;
    } else {
      value_bytes++;
    }
  }

  if ( value_bytes < 2 ) {
    alert("검색할 키워드를 2자이상 입력해주세요 !!!");
    return false;
  } else {
    location.href = "/ktwitter/searchall?kword=" + kword;
  }
}

function xGetElementById(e)
{
  if (typeof(e) == 'string') {
    if (document.getElementById) e = document.getElementById(e);
    else if (document.all) e = document.all[e];
    else e = null;
  }
  return e;
}

function overTab(obj) {
    var tab_id = obj.id;
    var cObj = obj.parentNode.firstChild;
    while(cObj) {
        if(cObj.nodeName == "DIV" && cObj.id) {
            var cTabID= cObj.id;
            if(cTabID.indexOf('tab')<0) {
                cObj = cObj.nextSibling;
                continue;
            }
            var cContentID = cTabID.replace(/^tab/,'tabcontent');
            if(tab_id == cTabID) {
                cObj.className = "tab on";
                xGetElementById(cContentID).className = "tabContent show";
            } else {
                cObj.className = "tab";
                xGetElementById(cContentID).className = "tabContent hide";
            }
        }
        cObj = cObj.nextSibling;
    }
}

function updatePublished() {
  var currDate = new Date();
  var currDateUTC = new Date(currDate.getUTCFullYear(), currDate.getUTCMonth(), currDate.getUTCDate(), currDate.getUTCHours(), currDate.getUTCMinutes(), currDate.getUTCSeconds());
  var currDateSecs = currDateUTC.getTime();
  currDateSecs = parseInt(currDateSecs/1000);
  jQuery('.published').each(function(){
    tmpdata = jQuery(this).attr('data');
    var tD = tmpdata.split(" ");
    tmpDate = tD[0].split("-");
    tmpTime = tD[1].split(":");

    pubDate = new Date(tmpDate[0], tmpDate[1]-1, tmpDate[2], tmpTime[0], tmpTime[1], tmpTime[2]);
    pubDateSecs = pubDate.getTime();
    pubDateSecs = parseInt(pubDateSecs/1000);
    periodSec = currDateSecs - pubDateSecs;

    years = months = days = hours = mins = secs = 0;
    if ( periodSec >= 31536000 ) {
      years = parseInt(periodSec / 31536000);
      periodSec = periodSec % 31536000;
    } 
    if ( periodSec >= 2592000 ) {
      months = parseInt(periodSec / 2592000);
      periodSec = periodSec % 2592000;
    } 
    if ( periodSec >= 86400 ) {
      days = parseInt(periodSec / 86400);
      periodSec = periodSec % 86400;
    } 
    if ( periodSec >= 3600 ) {
      hours = parseInt(periodSec / 3600);
      periodSec = periodSec % 3600;
    } 
    if ( periodSec >= 60 ) {
      mins = parseInt(periodSec / 60);
      periodSec = periodSec % 60;
    }
    secs = periodSec;

    howlong = "약 ";
    if (years > 0) {
      howlong = howlong + years + "년 ";
    } else if (months > 0) {
      howlong = howlong + months + "개월 ";
    } else if (days > 0) {
      howlong = howlong + days + "일 ";
    } else if (hours > 0) {
      howlong = howlong + hours + "시간 ";
    } else if (mins > 0) {
      howlong = howlong + mins + "분 ";
    } else if (secs > 30) {
      howlong = howlong + "30초 "
    } else if (secs > 10) {
      howlong = howlong + "10초 "
    } else {
      howlong = "방금"
    }
    howlong = howlong + "전에"

    jQuery(this).text(howlong);

  });
}

