var commtarget;
var resubmitf;

jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
(function($){
    $.fn.extend({
        ltSubmit: function(action,success) {
            return this.each(function() {
            var post={action: action};
            var value='';
            $(this).find('*').each(function(){
                
                var name=$(this).attr('name');
                if (name){
                    if ($(this).is("input[type='checkbox']")) {
                        value=this.checked;
                    } else {
                        value = $(this).val();                        
                    }
                    post[name]=value;
                }
            });
            url=$(this).attr( 'action' );
            post.doclocation = escape(document.location);
            $(this).addClass('btprogress');
            $('button', this).attr('disabled', 'disabled');
            var form=this;
            $.post( url, post ,
                function( data) {
                    $(form).removeClass('btprogress');
                    $('button', form).removeAttr('disabled');
                    var obj=$.parseJSON(data);
                    if (obj.jsredirect)
                        window.location=obj.jsredirect;
                    if (obj.script)
                        $.getScript(obj.script);
                    if (obj.error){
                        setError(obj.error);
                    }
                    if (obj.html) {
                        success(obj.html);
                    }
                }
                );
            return false;
            });
        }
    });
})(jQuery);

function lt_globalclass(name){
    this.onlyAnon=true;
    this.domain = "xxx";
    this.pagename=name;
    this.getDomain = function() {
        return this.domain;
    }

    this.getNameInForm = function (){
        if (this.onlyAnon){
            return 'Name:<br><input type="text" name="name"><br />';
        } else return '';
    }

    this.getCommForm = function(parentid){
    $('#lt_commForm').remove();
    //if (this.domain) url='http://'+this.domaincall; else url='';
    url='/api.php';
    return '<br><form action="'+url+'" id="lt_commForm" onSubmit="lt_obj.submit(this);return false;" >'+this.getNameInForm()+
        'Comment:<br><textarea name="body" rows="10" cols="80"></textarea><input type="hidden" name="subject" value=""><input type="hidden" name="action" value="addComm" /><input type="hidden" name="parentid" value="'+parentid+
        '" /><br /><br /><input type="submit" value="Submit" /><div id="lt_errormsg"></div></form>';
    }

    this.getStmtForm = function (parentid){
    $('#lt_commForm').remove();
    return '<form action="/api.php" id="lt_commForm" onSubmit="lt_obj.submit(this);return false;">'+this.getNameInForm()+'Subject:<br><input type="text" name="subject" /><input type="hidden" name="action" value="addtopic" /><input type="hidden" name="parentid" value="'+parentid+'" /><br />Body:<br /><textarea name="body"></textarea><br /><input type="submit" value="Submit" /><div id="result"></div></form>';
    }

    this.setErrorMsg = function (str){
        t=$( "#lt_errormsg" );
        if (t.length>0){
            $( "#lt_errormsg" ).html(str);
        }
        else {
            $(commtarget).html('<div id="lt_errormsg">'+str+'</div>');
        }
    }


    this.vote = function (vote,msgid){
    resubmitf=new Function("lt_obj.vote("+vote+","+msgid+")");
    $.post( '/api.php', {action:'vote', msgid:msgid, vote: vote, domain:this.domain} ,
      function( data ) {
          var obj=$.parseJSON(data);
          if (obj.script)
              $.getScript(obj.script);
          
          if (obj.error) $(commtarget).html( obj.error);
          else {
           $(commtarget).html(obj.html);
           $( "#lt_errormsg" ).remove();
          }
      }
    );
    }



    this.submit = function (form){
resubmitf=new Function("lt_obj.submit(document.forms[\"lt_commForm\"]);");
        subject = form.elements['subject'].value;
        action = form.elements['action'].value;
        parentid = form.elements['parentid'].value;
        body = form.elements['body'].value;
        url=$(form).attr( 'action' );
        location1 = escape(document.location);
        post={action:action, parentid: parentid, subject: subject, body: body, domain:this.domain, doclocation:location1,   pagename:this.pagename};
        if (form.elements['name']) post.name=form.elements['name'].value;
    // Send the data using post and put the results in a div
    $.post( url, post ,
      function( data) {

          //var content = $( data ).find( "#content" );
          //alert(data);
          var obj=$.parseJSON(data);
          if (obj.script)
              $.getScript(obj.script);
          if (obj.error)
            $( "#lt_errormsg" ).html(obj.error);
          if (obj.html) {
              //objreplace(form,obj.html);
              commtarget.append(obj.html);
              commtarget.show();
              $(form).remove();
              $( "#lt_errormsg" ).remove();
          }
          //datatype=data.substr(0,1);
          //if ('e' == datatype)
          //$( "#result" ).html( data.substr(1) );
          //else objreplace(form,data.substr(1));
      }
    );
return false;

    }


this.showOIDform = function(obj){
    $('#oiddiv').remove();
     $(obj).after('<br><div id="oiddiv"><form action="/api.php" id="oidform" target="_blank">'+
        'Enter Your OpenID Url:<br><input type="text" name="oid"><input type="submit" value="Sign in" style="width: 60px">'+
        '<input type="hidden" name="domain" value="'+this.domain+'">'+
        '<input type="hidden" name="action" value="login"><input type="hidden" name="method" value="oid"></form></div>');
    $('#oidform').children(':input')[0].focus();
}

this.showAnonform = function(obj){
    $('#oiddiv').remove();
     $(obj).after('<br><div id="oiddiv"><form action="/api.php" id="oidform" target="_blank">'+
        'Enter Your Name:<br><input type="text" name="name"><input type="submit" value="Sign in" style="width: 60px">'+
        '<input type="hidden" name="domain" value="'+this.domain+'">'+
        '<input type="hidden" name="action" value="login"><input type="hidden" name="method" value="anonymous"></form></div>');
    $('#oidform').children(':input')[0].focus();
}

}










function getStmtForm(parentid){
    $('#commForm').remove();
    return '<form action="/api.php" id="commForm" onSubmit="submitHandler(this);return false;">Subject:<br><input type="text" name="subject" /><input type="hidden" name="action" value="addtopic" /><input type="hidden" name="parentid" value="'+parentid+'" /><br />Body:<br /><textarea name="body"></textarea><br /><input type="submit" value="Submit" /><div id="result"></div></form>';
}
function getYellForm(parentid,vote){
    $('#commForm').remove();
    return '<form action="/api.php" id="commForm" onSubmit="submitHandler(this);return false;">'+vote+
        '<input type="hidden" name="action" value="addYell" /><input type="hidden" name="parentid" value="'+parentid+
        '" /><input type="hidden" name="subject" value="'+vote+'" /><br /><textarea name="body" rows="10" cols="80"></textarea><br /><input type="submit" value="Submit" /><div id="result"></div></form>';
}
function getCommForm(parentid){
    $('#commForm').remove();
    return '<br><form action="/api.php" id="commForm" onSubmit="submitHandler(this);return false;" >'+
        'Comment:<br><textarea name="body" rows="10" cols="80"></textarea><input type="hidden" name="subject" value=""><input type="hidden" name="action" value="addComm" /><input type="hidden" name="parentid" value="'+parentid+
        '" /><br /><br /><input type="submit" value="Submit" /><div id="result"></div></form>';
}





function submitHandler(form){
resubmitf=new Function("submitHandler(document.forms[\"commForm\"]);");
        subject = form.elements['subject'].value;
        action = form.elements['action'].value;
        parentid = form.elements['parentid'].value;
        body = form.elements['body'].value;
        domain=form.elements['domain'].value;
        url=$(form).attr( 'action' );
    // Send the data using post and put the results in a div
    $.post( url, {action:action, parentid: parentid, subject: subject, body: body, domain:domain} ,
      function( data) {
          //var content = $( data ).find( "#content" );
          //alert(data);
          var obj=$.parseJSON(data);
          if (obj.script)
              $.getScript(obj.script);
          if (obj.error)
            $( "#result" ).html(obj.error);
          if (obj.html) {
              commtarget.append(obj.html);
              commtarget.show();
              $(form).remove();
          }
          //datatype=data.substr(0,1);
          //if ('e' == datatype)
          //$( "#result" ).html( data.substr(1) );
          //else objreplace(form,data.substr(1));
      }
    );
return false;
}


//function test(obj){
//var aa=$(obj.parentNode);
////alert(aa.next().html('lala'));
//}
function showY(obj,msgid,filter){
    // Send the data using post and put the results in a div
    $.get( '/api.php', {action:'getyells', msgid: msgid, filter: filter} ,
      function( data) {
          //var content = $( data ).find( "#content" );
          datatype=data.substr(0,1);
          //if ('e' == datatype)
          $( obj ).next().html( data.substr(1) );
          //else objreplace(obj,data.substr(1));
      }
    );
return false;
}

function showcform(btn){
$(btn).before(getStmtForm());
$(btn).remove();
}

function objreplace(obj,replace){
$(obj).before(replace);
$(obj).remove();
}


function objtoggle(obj){
    $(obj).toggle();
}






function getid(obj){
    return $(obj).parents('.lt_topic')[0].id;
}

//$('.yellspan').click(function(e){
$('.yellspan').live('click',function(e){
    var me=$(this);
    me.next().show();
    me.hide();
}
);




//$('.lt_button').live('click',function(e){
//   var id=getid(this);
//   commtarget=$(this).parents('.lt_votepanel')[0];
//   var i = this.className.search('lt_votesplus');
//   if (-1 != i) i=1;
//   lt_obj.vote(i,id);
//});

$('.lt_closeSubj').live('click',function(e){
    var id=getid(this);
    $('#a'+id).toggle();
    //var oo=$(this).parents('.topic').get(0);
    var comm=$('#c'+id);
    comm.scrollTop(comm.attr("scrollHeight"));
    checkcomments(comm);
});

$('.lt_addcomment').live('click',function(e){
     var id=getid(this);
     commtarget=$(this).parent().children('.lt_comments');
     objreplace(this,lt_obj.getCommForm(id));
     $('#lt_commForm').children(':input')[0].focus();
});

$('.lt_faq').live('click',function(e){
   $(this).after('<div onclick="$(this).remove();" style="padding:10px;background-color:white; position:absolute; right:30%; width:200px; border-style:solid; border-width:1px; border-color:#06c; text-align: left;"><div class="lt_link"  >close</div><br><li>Use "<strong>say word of truth</strong>" if you want to ask a question or want to share your opinion</li><li>Use "<strong>add comment</strong>" for discussion</li></div>');
   e.stopPropagation();
});

$('.lt_addtruth').live('click',function(e){
    var id=getid(this);
    commtarget=$(this).parent().children('.lt_truth');
    objreplace(this,lt_obj.getStmtForm(id));
    $('#lt_commForm').children(':input')[0].focus();
});



$('#zaza').live('click',function(e){
    $('#zaza').hide();
    $('#lala').show();
});



$(".lt_comments").scroll(function () {
    var i=$(this).attr("scrollTop");
    if (0 == i && 0<$(this).attr("maxid")){
        //$(this).prepend('<div>zaza</div>');
        //$(this).prepend('<div>zaza</div>');
        //$(this).prepend('<div>zaza</div>');
        //$(this).attr( {maxid: 10});
        loadcomms(this);
        //$(this).attr({ scrollTop: 114 });
        
    }
});

//function test2(){
//    alert(2);
//    alert(this);
//}

function loadcomms(obj){
    var maxid=$(obj).attr("maxid");
    var limit=20;
    var msgid=getid(obj);
    $.getJSON( '/api.php', {action:'getcomms', msgid: msgid, maxid: maxid, limit: limit} ,
      function( data) {
          var oldh=$(obj).attr("scrollHeight");
          $(obj).prepend(data.html);
          $(obj).attr( {maxid: data.maxid});
          var newh =$(obj).attr("scrollHeight");
          $(obj).attr({scrollTop: newh-oldh});
          //var content = $( data ).find( "#content" );
          //datatype=data.substr(0,1);
          //if ('e' == datatype)
          //$( obj ).next().html( data.substr(1) );
          //else objreplace(obj,data.substr(1));
      }
    );
return false;
}


function checkcomments(obj){
if (obj.scrollTop()>0 && obj.nextAll('.lt_commsES').length===0){
    obj.after('<div class="lt_commsES" >expand</div>');
}
}

$('.lt_commsES').live('click',function(e){
    //var me=$(this);
    var obj=$(this).prevAll('.lt_comments');
    if (obj.css('height')=='500px'){
        obj.css('height',80);
        $(this).html('expand');
    } else {
        obj.css('height',500);
        $(this).html('shrink');
        loadcomms(obj);
    }
});

// *********************************************************************************
lt=new function(){
this.formhandler=function(form){
    var formaction=$(form).attr('lt-action');
    switch(formaction){
        case 'addComm':
            setError=function(str){
                $(form).children('.lt-err-msg').html(str);
            }
            resubmitf=function(){
                setError('');
                $(form).ltSubmit(formaction,function(data){
                    $(form).prev().append(data);
                    $(form).children('textarea').val('');
                });
                
            }
            
            auth();
break;
        case 'updateProfile':
            setError=function(str){
                $(form).children('.lt-err-msg').html(str);
            }
            resubmitf=function(){
                $(form).ltSubmit(formaction,function(data){
                    document.cookie=data;
                    window.location.reload();
                });
                

            }
            auth();
break;
        case 'addtopic':
            setError=function(str){
                $($(form).children('div:last')[0]).html(str);
            }
            resubmitf=function(){
                $(form).ltSubmit(formaction,function(data){
                    $(form).html(data);
                });
            }
            auth();
break;
    }
    return false;
}

function getid(obj){
    return $(obj).parents('.lt_topic')[0].id;
}

function auth(){
    var hashid=$.cookie('lt_user');
    if (!hashid) $.getScript('http://lesstalks.com/api.php?action=getlogin&doclocation='+escape(document.location));
    else resubmitf();
}
$('.lt-new-comment textarea').live('focusin',function(event){
    switch (event.type){
        case 'focusin':
            var obj=$(event.currentTarget);
//            obj.height(36);
//            obj.parent().children('div').show();
            obj.parent().addClass('active');
    var arr=obj.val().split('\n');
    obj.height(arr.length*17+17);
            //obj.css('color','black !important');
            break;
//        case 'focusout':
//            var obj=$(event.currentTarget);
//            obj.parent().removeClass('active');
//            obj.height(22);
//
////            obj.parent().children('div').hide();
//            break;
    }
});
$(document).ready(function() {
$('.lt-new-comment textarea').keyup(function(event){
    var obj=$(event.currentTarget);
    var arr=obj.val().split('\n');
    obj.height(arr.length*17+17);
    obj.attr('rows',10);

})
});

$('.lt_action').live('click',function(event){
var action=$(event.currentTarget).attr('lt_action');
switch (action){
    case 'voteplus':
    case 'voteminus':
//       prepare data for setError and resubmitf
       var msgid=getid(event.currentTarget);
       var doclocation=escape(document.location);
       var out=$(event.currentTarget).parent();
       if ('voteplus' == action) vote=+1; else vote=-1;
       setError=function(str){
           out.html(str);
       }
       resubmitf=function(){
    $.post( '/api.php', {action:'vote', msgid:msgid, vote: vote, doclocation:doclocation } ,
      function( data ) {
          var obj=$.parseJSON(data);
          if (obj.script)
              $.getScript(obj.script);

          if (obj.error) out.html( obj.error);
          else {
           out.html(obj.html);
          }
      }
    );
       };
       
       auth();
        break;

    case 'showProfile':
        $.get('/api.php',{action:'showProfile'},function (data){
            var obj=$.parseJSON(data);
            $(event.currentTarget).append('<div id="lt_profile" title="Profile">'+obj.html+'</div>');
            $('#lt_profile').dialog({
                modal: true,
                close: function(){
                    $('#lt_profile').remove();
                }
            });
        });
    break;

}

});

};


