//Image Upload

var image_upload=
{
    fileList: new Array(),
    totalSize: 0,
    totalLoaded: 0,
    in_upload: false,
    done: false,
    uploadURL:"",
    editURL:"",
    nid:0,
    uploadMode: 0,
    flashSupport: 0,
    getFlash: function(movieName){
        var isIE = navigator.appName.indexOf("Microsoft") != -1;
        //return (isIE) ? window[movieName] : document[movieName];
        return document[movieName];
    },
    addFile: function(){
        if (this.in_upload)
        {
            return;
        }
        if (this.done)
        {
            return;
        }
        this.getFlash("FileUpload").openFileDialog(1);    
    },
    fileSelected: function(fname, fsize, ftype){
        var obj=$('#fileTemplate').clone(true);
        obj.removeAttr("id");
        obj.find('div.filename').html(fname);
        obj.find('div.filesize').html(this.getFileSize(fsize));
        obj.css("display", "block");
        $('#fileList').append(obj);
        this.fileList.push({name: fname, size: fsize, type: ftype, loaded: 0, error: 0});
        this.totalSize=this.totalSize + fsize;
        this.updateSummary();
    },
    removeFile: function(obj){
        if (this.in_upload)
        {
            return;
        }
        if (this.done)
        {
            return;
        }
        var row=obj.parent().parent();
        var index=0;
        while (true)
        {
            var prev_row=row.prev();
            if (prev_row)
            {
                if (prev_row.attr("id")=="fileTemplate")
                {
                    break;
                }
                index++;
                row=prev_row;
            }
            else
            {
                break;
            }
        }
        var row=obj.parent().parent().remove();
        this.getFlash("FileUpload").removeFile(index);
        var f=this.fileList[index];
        this.totalSize=this.totalSize - f.size;
        this.fileList.splice(index, 1);
        this.updateSummary();    
    },
    uploadError: function(index, code, extra)
    {
        this.fileList[index].error=1;
        var li=$('#fileList li:not(#fileTemplate)').eq(index);
        li.find('div.progress').html('<span class="error">Lỗi</span>');
        if (index==this.fileList.length-1)
        {
            $('#pbar').css("width", "100%");
            $('#pbar_text').html('100%');
            this.in_upload=false;
            this.done=true;
        }
    },
    updateSummary: function()
    {
        $('#file_count').html(this.fileList.length.toString());
        var mb=Math.round(this.totalSize/(1024*1024)*100)/100;
        if (mb==0)
        {
            $('#file_size').html("0");
        }
        else
        {
            $('#file_size').html(mb);
        }
    },
    getFileSize: function(size){
        if (size<1024)
        {
            return size.toString() + " B";
        }
        var kb=Math.round(size/1024*10)/10;
        if (kb<1024)
        {
            return kb.toString() + " K";
        }
        var mb=Math.round(kb/1024*10)/10;
        return mb.toString() + " M";
    },
    uploadStart: function(index){
        if (!this.in_upload)
        {
            this.in_upload=true;
        }        
        if (index>7)
        {
            var li=$('#fileList li:not(#fileTemplate)').eq(index);
            li.get(0).scrollIntoView();
        }        
    },
    uploadCompleted: function(index){
        if (this.fileList[index].error!=1)
        {
            this.fileList[index].loaded=this.fileList[index].size;
            var li=$('#fileList li:not(#fileTemplate)').eq(index);
            li.find('div.progress').html('100%');
        }        
        var completed=true;
        for (i=0; i<this.fileList.length; i++)
        {
            if (this.fileList[i].error!=1 && this.fileList[i].loaded<this.fileList[i].size)
            {
                completed=false;
                break;
            }
        }
        if (completed)
        {
            $('#pbar').css("width", "100%");
            $('#pbar_text').html('100%');
            this.in_upload=false;
            this.done=true;
            window.location.href= '/photo/view/' + this.nid;
            //$('#upload_progress').html('Album của bạn đã được gửi lên tamtay.vn. Bạn có thể tiếp tục <a href="' + this.editURL + this.nid + '">chỉnh sửa album</a>');
        }
    },
    uploadProgress: function(index, loaded, total){
        var delta=loaded-this.fileList[index].loaded;
        this.totalLoaded=this.totalLoaded + delta;
        this.fileList[index].loaded=loaded;
        var filePercent=Math.round(this.fileList[index].loaded/this.fileList[index].size*100);
        if (filePercent>=100)
        {
            filePercent=99;
        }
        var li=$('#fileList li:not(#fileTemplate)').eq(index);
        li.find('div.progress').html(filePercent + '%');
        var percent=Math.round(this.totalLoaded/this.totalSize*100);
        if (percent>=100)
        {
            percent=99;
        }
        $('#pbar').css("width", percent  + '%');
        $('#pbar_text').html(percent + '%');
    },
    doUpload: function(){
        if (!this.in_upload && !this.done)
        {
            if (this.fileList.length==0)
            {
                alert("Bạn phải chọn file ảnh trước khi upload");
                return;
            }
            $('#link_open').toggle();
            this.getFlash("FileUpload").uploadFile();
        }
        else
        {
            return;
        }
    },
    readCookie: function(cname){
        var c=document.cookie;
        var ca=c.split(";");
        for (var i=0; i<ca.length; i++)
        {
            var st=jQuery.trim(ca[i]);
            var ar=st.split("=");
            if (ar.length>1)
            {
                st=jQuery.trim(ar[0]);
                if (st==cname)
                {
                    return jQuery.trim(ar[1]);
                }
            }
        }
        return "";
    },
    setKey: function(nid)
    {
        this.getFlash("FileUpload").setKey(nid);
        this.nid=nid;
    },
    formSerialize: function(id)
    {
        var elem=document.forms[id].elements;
        var a=[];
        for (var i=0; i<elem.length; i++)
        {
            var e=elem[i];
            var st=e.nodeName.toLowerCase();
            if (e.name!="")
            {
                if (st=="select" || st=="textarea" || e.type=="text" || e.type=="hidden" || e.type=="password" || e.type=="checkbox" || e.checked)
                {
                    a.push({name: e.name, value: e.value})
                }
            }
        }
        var s = [];
        for (var i=0; i<a.length; i++)
        {
            var e=a[i];
            s.push( encodeURIComponent(e.name) + "=" + encodeURIComponent( e.value ) );
        }
        return s.join("&").replace(/%20/g, "+");
    },
    extractFileName: function(path)
    {
        var arr  = path.split("\\");
        var l    = arr.length-1;
        return  arr[l];
    },
    checkExtension:    function(path)
    {
        var ext = new Array('jpg', 'jpeg','png', 'gif');
        path=path.toLowerCase();
        var f=this.extractFileName(path);
        var e = f.split(".");
        for (var i=0; i<ext.length; i++)
        {
            if (ext[i] == e[e.length-1])
            {
                return true;
            }
        }
        return false;
    },
    checkBasicUpload: function()
    {
        var empty_count=0;
        var invalid_ext=false;
        $('input[@type=file]').each(function(){
            if ($(this).val()=='')
            {
                empty_count++;
            }
            else
            {
                if (!image_upload.checkExtension($(this).val()))
                {
                    invalid_ext=true;
                    alert('Bạn chọn ảnh không đúng định dạng được phép');
                    return false;
                }
            }
        });
        if (!invalid_ext && empty_count==5)
        {
            alert('Bạn phải chọn ít nhất 1 ảnh để upload');
            return false;
        }

        return (!invalid_ext);
    },
    checkUploadData: function()
    {
        if (this.uploadMode==0 && !this.checkBasicUpload())
        {
            return false;
        }
        if ($('#album_name').val()=='')
        {
            alert('Bạn phải nhập tên album');
            return false;
        }
        
        if ($('#album_cat_id').val()=='0')
        {
            alert('Bạn phải chọn thể loại của album');
            return false;
        }
        
        if ($('#tags').val()=='')
        {
            alert('Bạn phải nhập từ khóa cho album');
            return false;
        }
        
        if (this.fileList.length==0 && this.uploadMode==1)
        {
            alert("Bạn phải chọn ít nhất 1 ảnh để upload");
            return false;
        }
        return true;
    },
    upload: function()
    {
        if (!this.checkUploadData())
        {
            return false;
        }
        if (this.flashSupport==1 && this.uploadMode==1)
        {
            $.ajax({
               type: "POST",
               url: image_upload.uploadURL + "?adv=1",
               //data: image_upload.formSerialize("upload_form"),
               data: $("#upload_form").serialize(),
               beforeSend: function(req){
                      $('#album_info').toggle();
                      $('#upload_progress').toggle();
                      $('#upload_album').attr("disabled", true);
                      $('#upload_cancel').attr("disabled", true);
               },
               error: function(req, status, info){
                      alert("Có lỗi trong quá trình upload album của bạn. Xin vui lòng thử lại lần khác\n");
               },
               success: function(nid){
                    if (nid>0)
                    {
                         $('#progress_bar').toggle();
                         image_upload.setKey(nid);
                         image_upload.doUpload();
                    }
                    else
                    {
                         alert("Có lỗi trong quá trình upload album của bạn. Xin vui lòng thử lại lần khác");
                    }
               }
            });
        }
        else
        {
            $("#upload_form").attr("action", this.uploadURL);
            document.getElementById("upload_form").submit();
            $(this).attr('disabled', 'true');
            $("#upload_progress").show();
        }
    },
    toggleUI: function()
    {
        if (!this.flashSupport)
        {
            return;
        }
        if (this.in_upload || this.done)
        {
            return;
        }
        $('#basic_upload').toggle();
        $('#adv_upload').toggle()
        if (this.uploadMode==0)
        {
            this.uploadMode=1;
            $('#toggle_ui').html("Sử dụng hệ thống upload cũ");
               $('#help_container').load("/misc/help_image_upload_adv.html");
        }
        else
        {
            this.uploadMode=0;
            $('#toggle_ui').html("Sử dụng hệ thống upload mới (beta)");
            $('#help_container').load("/misc/help_image_upload_basic.html");
        }
    }
}

//Image Tagging
image_tag =
{        
    aid: 0,
    minX: 200,
    minY: 200,
    canTag: 0, 
    isOwner: 0,   
    tagPosting: false,
    tagsLoading: false, 
    init: function(aid, minX, minY, canTag, isOwner)    
    {  
        this.aid = aid;
        this.minX = minX;
        this.minY = minY;
        this.canTag = canTag;  
        this.isOwner = isOwner;               
        this.loadAllTags(aid);     
        $(window).resize(function () {
            $(".tag_list").html('');      
            image_tag.loadAllTags(image_tag.aid);
        }); 
    },    
    loadAllTags: function(aid)
    {
        $(".tag").remove();  
        $(".tag_text").remove(); 
        if (image_tag.tagsLoading == true){
            return false;
        }   
        $.ajax({
           type: "GET",
           url: "/tagging/getall/" + aid + "?format=json",
           beforeSend: function(req){                   
                image_tag.tagsLoading = true;
           },
           complete: function(res, s){                
                tags = eval(res.responseText);                
                $(tags).each(function(){
                    image_tag.appendTag(this);
                });  
                image_tag.tagsLoading = false;
                $(".image_tag").each(function(){
                    image_tag.addTagEvents(this);
                });                  
                if (typeof f == "function") f();
            }       
        });    
    },
    appendTag: function(tag){                             
        imgOffset = $("#" + tag.fid).offset();                      
        tag_left  = parseInt(imgOffset.left) + parseInt(tag.tag_x1);
        tag_top   = parseInt(imgOffset.top) + parseInt(tag.tag_y1);
        tag_p_top = tag_top + parseInt(tag.tag_height)+5;                            
        tag_area_div = $('<div class="tag tag_' + tag.fid + '" id="tid_' + tag.tid + '"></div>').css({ left: tag_left + 'px', top: tag_top + 'px', width: tag.tag_width + 'px', height: tag.tag_height + 'px' });                
        tag_text_div = $('<div class="tag_text tag_text_' + tag.fid + '">'+tag.tag_text+'</div>').css({ left: tag_left + 'px', top: tag_p_top + 'px'});   
        $('body').append(tag_area_div);
        $('body').append(tag_text_div);        
        var editLink = '';
        if (image_tag.isOwner == '1'){            
            editLink = '<a href="javascript:void(0)" class="btn-del-tag" onclick="image_tag.deleteTag(' + tag.tid +', ' + tag.fid + ')" title="Xóa tag"><img src="/images/spacer.gif" alt="Xóa tag" /></a>';
        }                                                       
        var link = '<a href="javascript:void(0)" class="view-tag" onmouseover="image_tag.toggleTag(' + tag.tid +  ')" onmouseout="image_tag.toggleTag(' + tag.tid +')">' + tag.tag_text + '</a>' + editLink;
        tagList = "#tag_list_" + tag.fid;
        if ($(tagList).html() == ''){
            $(tagList).append('Tags: ' + link);                  
        } else {
            $(tagList).append(', ' + link);                  
        }
    },   
    toggleTag: function(tid)
    {           
        $('#tid_' + tid).toggleClass('tag_border');    
    },     
    addTagEvents: function(image) 
    {           
        $('.tag_' + $(image).attr('id')).hover(
            function(){     
                //e.stopPropagation();                                   
                $(this).next('.tag_text').show();
                $(this).next('.tag_text').css("z-index", 10000);                 
            },
            function(){                
                //e.stopPropagation();                                   
                $(this).next('.tag_text').hide();
                $(this).next('.tag_text').css("z-index", 0);
            }
        );
        fid = $(image).attr('id');
        width = parseInt($('#image_width_' + fid).val());                
        height = parseInt($('#image_height_' + fid).val());                   
        if (width > image_tag.minX) {                                                    
            if (image_tag.canTag == 1) {
                $(image).imgAreaSelect({handles: true, onSelectChange: image_tag.showAddTag});    
            }                                                                                                                          
        }                          
    },
    showAddTag: function(img, area){
        imgOffset = $(img).offset();
        form_left  = parseInt(imgOffset.left) + parseInt(area.x1);
        form_top   = parseInt(imgOffset.top) + parseInt(area.y1) + parseInt(area.height) + 5;     
        $('#tagForm').css({ left: form_left + 'px', top: form_top + 'px'});       
        $('#tagForm').show();         
        $('#tagForm').css("z-index", 10000);
        $('#tagX1').val(area.x1);
        $('#tagY1').val(area.y1);
        $('#tagHeight').val(area.height);
        $('#tagWidth').val(area.width);    
        $('#fid').val($(img).attr('id'));            
    },                      
    cancelAddTag: function(){
        fid = $('#fid').val();        
        $('img#' + fid).imgAreaSelect({ hide: true });
        $('#tagForm').hide();    
    },
    addTag: function(fid){
        $('img#' + fid).imgAreaSelect({ onSelectChange: image_tag.showAddTag, x1: 120, y1: 90, x2: 280, y2: 210 });
        return false;
    },
    saveTag: function(){        
        $('#tagAddForm').submit(function () {
            return false;
        }); 
        fid = $('#fid').val(); 
        text = $('#tagText').val();
        if (text == '') {
            alert('Bạn phải nhập nội dung tag');
            return false;
        } else if (text.length > 20) {
            alert('Tag quá dài. Tag chỉ có thể chứa ít hơn 20 ký tự');
            return false;
        } 
        $.ajax({
               type: "POST",
               url: "/tagging/add",
               data: $("#tagAddForm").serialize(),
               beforeSend: function(req){                   
                   image_tag.tagPosting=true;
               },
               error: function(req, status, info){
                      alert("Có lỗi khi cập nhật tag của bạn");
               },                                  
               complete: function(res, s){                          
                   image_tag.tagPosting = false;  
                   image_tag.loadTag($('#' + fid), function(){
                       $('#' + fid).imgAreaSelect({ hide: true });
                       $('#tagForm').hide();                   
                       //$('.tag_' + fid).show();     
                   }); 
               }
        });          
    },     
    loadTag: function(image, f)
    {               
        if (image_tag.tagsLoading == true){
            return false;
        }   
        fid = $(image).attr('id');     
        $.ajax({
           type: "GET",
           url: "/tagging/get/" + fid + "?format=json",   
           beforeSend: function(req){                   
                image_tag.tagsLoading = true;
           },        
           complete: function(res, s){    
                $('.tag_' + fid).remove();  
                $('.tag_text_' + fid).remove();                                                            
                $("#tag_list_" + fid).html('');                                    
                tags = eval(res.responseText);                
                $(tags).each(function(){
                    image_tag.appendTag(this);
                }); 
                image_tag.addTagEvents($(image));
                image_tag.tagsLoading = false;
                if (typeof f == "function") f();
            }       
        });       
    },
    deleteTag: function(tid, fid)
    {
        confirm('Bạn chắc chắn muốn xóa tag này?');
        if ( ! confirm){
            return false;
        }
        $.ajax({
            type: "POST",
            url: "/tagging/delete/" + tid,
            complete: function(res, s){
                image_tag.loadTag($('#' + fid), function(){
                   $('#' + fid).imgAreaSelect({ hide: true });
                   $('#tagForm').hide(); 
               });     
            }
        });
    }
}


//Image Note
var image_note=
{
    postURL:"/note/save",
    inprogress: false,
    delNote: function(id)
    {
        if (!confirm('Bạn chắc chắn xóa ghi chú của ảnh này'))
        {
            return;
        }
        $('#image_note_content_' + id).val("");
        image_note.saveNote(id);
    },
    showEdit: function(id)
    {
        if (this.inprogress)
        {
            return;
        }
        $('#note_' + id).toggle();
        $('#edit_note_' + id).toggle();
    },
    cancelEdit: function(id)
    {
        $('#note_' + id).toggle();
        $('#edit_note_' + id).toggle();
    },
    saveNote: function(id)
    {
        if (this.inprogress)
        {
            return;
        }
        this.inprogress=true;
        var url=this.postURL + "/" + id;
        $.ajax({
               type: "POST",
               url: url,
               data: $('#image_note_content_' + id).serialize(),
               beforeSend: function(req){
                      $('#edit_note_' + id).hide();
                      $('#note_' + id).show();
               },
               error: function(req, status, info){
                      alert("Có lỗi trong quá trình cập nhật chú thích cho ảnh. Xin vui lòng thử lại lần khác");
                      image_note.inprogress=false;
               },
               success: function(note, status){
                    image_note.inprogress=false;
                    if (note=="-1")
                    {
                     alert("Có lỗi trong quá trình cập nhật chú thích cho ảnh. Xin vui lòng thử lại lần khác");
                     return;
                    }
                    if (note!="")
                    {
                    $('#note_view_' + id).html(note);
                    }
                    else
                    {
                     $('#note_view_' + id).html("<i>Bạn có thể thêm chú thích cho ảnh (tối đa 300 ký tự)</i>");
                    }
                    if (note=="")
                    {
                     $('#note_del_' + id).hide();
                    }
                    else
                    {
                     $('#note_del_' + id).show();
                    }
               }
            });
    }
}


//Mod Comment
var mod_comment=
{
    postURL: "/admin/comment",
    inprogress: false,
    selectAll: function()
    {
        var status=$('#selAll').get(0).checked;
        $("input.chk_comment").each(function(){
            this.checked=status;
        });
    },
    checkDelete: function()
    {
        var ok=false;
        $("input.chk_comment").each(function(){
            if (this.checked)
            {
                ok=true;
                return false;
            }
        });
        if (!ok)
        {
            alert('You have to select at least a comment to delete');
            return;
        }
        if (!confirm('Are you sure to delete the selected comments'))
        {
            return;
        }
        $('#act').val('delete');
        document.forms['mod_comment'].submit();
    },
    deleteComment: function()
    {
        this.checkDelete();
    },
    mark_time: function()
    {
        if (!confirm('Are you sure to mark the last review time'))
        {
            return;
        }
        $('#action').val('mark_time');
        document.forms['mod_comment'].submit();
    },
    editComment: function(cid)
    {
        if (this.inprogress)
        {
            return;
        }
        $('#comment_view_' + cid).hide();
        $('#comment_edit_' + cid).show();
    },
    cancelEdit: function(cid)
    {
        $('#comment_edit_' + cid).hide();
        $('#comment_view_' + cid).show();
    },
    saveComment: function(cid)
    {
        if (this.inprogress)
        {
            return;
        }
        if ($('#comment_content_' + cid).val()=="")
        {
            alert('The comment content is empty. Please enter something');
            return;
        }
        
        this.inprogress=true;
        var url=this.postURL + "?act=update&cid=" + cid;
        $.ajax({
               type: "POST",
               url: url,
               data: $('#comment_content_' + cid).serialize(),
               beforeSend: function(req){
                          $('#comment_edit_' + cid).hide();
                    $('#comment_view_' + cid).show();
               },
               error: function(req, status, info){
                      alert("Có lỗi trong quá trình cập nhật comment. Xin vui lòng thử lại lần khác");
                      mod_comment.inprogress=false;
               },
               success: function(comment, status){
                    mod_comment.inprogress=false;
                    if (comment=="-1")
                    {
                        alert("Có lỗi trong quá trình cập nhật comment cho ảnh. Xin vui lòng thử lại lần khác");
                         return;
                    }
                       $('#comment_view_' + cid).html(comment);
               }
            });
    }
}

//Mod Tag
var mod_tag=
{
    postURL: "/admin/tag",
    inprogress: false,
    selectAll: function()
    {
        var status=$('#selAll').get(0).checked;
        $("input.chk_comment").each(function(){
            this.checked=status;
        });
    },
    checkDelete: function()
    {
        var ok=false;
        $("input.chk_comment").each(function(){
            if (this.checked)
            {
                ok=true;
                return false;
            }
        });
        if (!ok)
        {
            alert('You have to select at least a tag to delete');
            return;
        }
        if (!confirm('Are you sure to delete the selected tags'))
        {
            return;
        }
        $('#act').val('delete');
        document.forms['mod_tag'].submit();
    },
    deleteTag: function()
    {
        this.checkDelete();
    },
    mark_time: function()
    {
        if (!confirm('Are you sure to mark the last review time'))
        {
            return;
        }
        $('#action').val('mark_time');
        document.forms['mod_tag'].submit();
    },
    editTag: function(tid)
    {
        if (this.inprogress)
        {
            return;
        }
        $('#tag_view_' + tid).hide();
        $('#tag_edit_' + tid).show();
    },
    cancelEdit: function(tid)
    {
        $('#tag_edit_' + tid).hide();
        $('#tag_view_' + tid).show();
    },
    saveTag: function(tid)
    {
        if (this.inprogress)
        {
            return;
        }
        if ($('#tag_content_' + tid).val()=="")
        {
            alert('The tag content is empty. Please enter something');
            return;
        }
        
        this.inprogress=true;
        var url=this.postURL + "?act=update&tid=" + tid;
        $.ajax({
               type: "POST",
               url: url,
               data: $('#tag_content_' + tid).serialize(),
               beforeSend: function(req){
                          $('#tag_edit_' + tid).hide();
                    $('#tag_view_' + tid).show();
               },
               error: function(req, status, info){
                      alert("Có lỗi trong quá trình cập nhật tag. Xin vui lòng thử lại lần khác");
                      mod_tag.inprogress=false;
               },
               success: function(tag, status){
                    mod_tag.inprogress=false;
                    if (tag=="-1")
                    {
                        alert("Có lỗi trong quá trình cập nhật tag cho ảnh. Xin vui lòng thử lại lần khác");
                         return;
                    }
                       $('#tag_view_' + tid).html(tag);
               }
            });
    }
}


//My Album
var myalbum=
{
    checkSelection: function()
    {
        var ok=false;
        $("input.selected_album").each(function(){
            if (this.checked)
            {
                ok=true;
                return false;
            }
        });
        return ok;
    },
    preSubmit: function(a)
    {
        var ok=this.checkSelection();
        if (!ok)
        {
            alert("Bạn phải chọn ít nhất một album");
            return false;
        }
        if (a!="trash")
        {
            msg="Bạn chắc chắn muốn xóa những album được chọn"; 
        }
        else
        {
            msg="Bạn chắc chắn muốn khôi phục những album được chọn"; 
        }    
        return confirm(msg);
    },
    addAlbumToCategory: function()
    {
        if ( ! this.checkSelection()) {
            alert("Bạn phải chọn ít nhất một album");
            return false;
        }    
        $category = $('#category :selected').text();
        if ( ! confirm('Bạn có chắc chắn muốn chuyển các album đã chọn đến danh mục "' + $category + '"')) {
            return false;
        }
        $('#command').val('add');
        $('#albumForm').submit();
    },
    doSubmit: function(a)
    {
        if (this.preSubmit(a)) {
            $('#albumForm').submit();            
        }                                            
    }
}


//Photo Comment
photo_comment=
{
    commentLoading: false,
    commentPosting: false,
    commentPage: 0,
    firstTime: true,
    insertSymbol: function(symbol)
    {
        var obj=$('#comment_content').get(0);
        if (document.selection)
        {
            obj.focus();
            sel = document.selection.createRange();
            sel.text = symbol;
        }
        else if (obj.selectionStart || obj.selectionStart == 0)
        {
            var startPos = obj.selectionStart;
            var endPos = obj.selectionEnd;
            obj.value = obj.value.substring(0, startPos)
                        + symbol
                        + obj.value.substring(endPos, obj.value.length);
        } 
        else
        {
            obj.value += symbol;
        }
    },
    loadComment:  function(aid, p)
     {
         if (this.commentLoading)
         {
             return false;
         }
         $.ajax({
               type: "GET",
               url: "/comment/view/" + aid + "?page=" + p,
               beforeSend: function(req){
                   $("#cmt_loader").show();
                   photo_comment.commentLoading=true;
               },
               complete: function(res, s){
                   $("#comment_area").html(res.responseText);
                   $("#cmt_loader").hide();
                   photo_comment.commentLoading=false;
                   photo_comment.commentPage=p;
                   if (!photo_comment.firstTime)
                   {
                        location.href='#comment_section';
                   }
                   else
                   {
                        photo_comment.firstTime=false;
                   }
                   
                }       
            });
         return false;
     },
     deleteComment: function(cid)
     {
         if (!confirm("Bạn chắc chắn xóa bình luận này"))
             return false;
         $.ajax({
               type: "POST",
               url: "/comment/delete/" + cid + "?page=" + this.commentPage,
               error: function(req, status, info){
                      alert("Có lỗi khi xóa bình luận. Hãy thử lại lần khác");
               },
               success: function(comment, status){
                      $("#comment_area").html(comment);
                      location.href='#comment_section';
               }
        });
        return false;
     },
    saveComment: function(aid, cid) 
    {
        if (cid == '') {
            textAreaID = "#comment_content";
        } else {            
            textAreaID = "#comment_content_" + cid;
        }
        if ($(textAreaID).val()=="")
            return;
        if (photo_comment.commentPosting)
            return;                        
        $.ajax({
               type: "POST",
               url: "/comment/save/" + aid + "/" + cid,
               data: $(textAreaID).serialize(),
               beforeSend: function(req){
                   $("#cmt_loader").show();
                   photo_comment.commentPosting=true;
               },
               error: function(req, status, info){
                      alert("Có lỗi khi cập nhật bình luận của bạn");
               },
               success: function(comment, status){
                      $("#comment_area").html(comment);
                      $(textAreaID).val("");
               },
               complete: function(res, s){
                   $("#cmt_loader").hide();
                   photo_comment.commentPosting=false;
                   photo_comment.commentPage=0;
                   location.href='#comment_section';
                }
        });
        return false;
    },
    showReplyBox: function(cid)
    {
        $("#reply_hint_" + cid).hide();
        $("#reply_box_" + cid).show();
        return false;
    },
    showReply: function(cid)
    {
        $('.reply_comment_' + cid).show();
        $('#display_reply_' + cid).hide();
        return false;
    }
}

//Photo Home
var photo_home=
{
    cache_feature: new Array(),
    cache_last: new Array(),
    doing_feature: false,
    doing_last: false,
    switchFeatureTab: function(path, p, tab)
    {
        if (photo_home.doing_feature)
        {
            return false;
        }
        var obj=$("#album_feature_tab > .item_name").get(tab);
        if ($(obj).hasClass("tabItemS"))
        {
            return false;
        }
        if (photo_home.cache_feature[tab]!=undefined)
        {
            $("#" + p).html(photo_home.cache_feature[tab]);
            photo_home.changeActivedTab("#album_feature_tab > .item_name", tab);
            return false;
        }
        $.ajax({
            type: "GET",
            url: path,
            beforeSend: function(req){
                photo_home.changeActivedTab("#album_feature_tab > .item_name", tab);
                $("#newest_albums").hide();
                /*$("#" + p).html('');*/
                $("#newest_loader").show();
                photo_home.doing_feature=true;
            },
            complete: function(res, s){
                $("#newest_loader").hide();
                $("#" + p).html(res.responseText);
                photo_home.cache_feature[tab]=res.responseText;
                $("#newest_albums").show();
                /*photo_home.changeActivedTab("#album_feature_tab > .item_name", tab);*/                
                photo_home.doing_feature=false;
            }
        });
        return false;
    },
    switchTab: function(pb, path, p, tab, anim)
    {
        if (photo_home.doing_last)
        {
            return false;
        }
        if (pb=="album_promoted_1")
        {
            index=0;
        }
        else
        {
            index=1;
        }
        
        pb="#" + pb + " > .item_name";
        var obj=$(pb).get(tab);
        if ($(obj).hasClass("tabItemS"))
        {
            return false;
        }
        
        if (photo_home.cache_last[index]==undefined)
        {
            photo_home.cache_last[index]=new Array();
        }
        if (photo_home.cache_last[index][tab]!=undefined)
        {
            $("#" + p).html(this.cache_last[index][tab]);
            photo_home.changeActivedTab(pb, tab);
            return false;
        }
        
        $.ajax({
            type: "GET",
            url: path,
            beforeSend: function(req){
                $("#" + anim).show();
                photo_home.doing_last=true;
            },
            complete: function(res, s){
                $("#" + p).html(res.responseText);
                photo_home.cache_last[index][tab]=res.responseText;
                photo_home.changeActivedTab(pb, tab);
                $("#" + anim).hide();
                photo_home.doing_last=false;
            }
        });
        return false;
    },
    changeActivedTab: function(pb, tab)
    {
        $(pb).each(function(){
            if ($(this).hasClass("tabItemS"))
            {
                $(this).removeClass("tabItemS");
                $(this).addClass("tabItem");
            }
        });
        var obj=$(pb).get(tab);
        $(obj).removeClass("tabItem");
        $(obj).addClass("tabItemS");
    }
}

//Photo View
photo_view=
{
    current_view: 0,
    showCode: function(t, code, e)
    {
        $(e).val(code);
        return false;
    },
    showAllCode: function(code)
    {
        if (this.current_view==0)
        {
            $('#share_all_code').show();
        }
        if (code=='bb_code' && this.current_view==1)
        {
            this.current_view=0;
            $('#share_all_code').hide();
            return;
        }
        
        if (code=='html_code' && this.current_view==2)
        {
            this.current_view=0;
            $('#share_all_code').hide();
            return;
        }
        
        if (code=='bb_code')
        {
            $('#all_code').val($('#bb_code').text());
            this.current_view=1;
        }
        
        if (code=='html_code')
        {
            $('#all_code').val($('#html_code').text());
            this.current_view=2;
        }
    },
    shareAlbum: function()
    {
        $('#share_dialog').jqm().jqmShow();
        return false;
    },
    sendMail: function()
    {
        $('#share_dialog').jqmHide();
    },
    addBookmark: function(aid)
    {
        if (!confirm('Bạn chắc chắn thêm album này vào nhà mình'))
        {
            return false;
        }
        $.post('/bookmark', 'aid=' + aid, function(data, status){
            if (status=='success' && (data=="1" || data=="0"))
            {
                alert('Album đã được thêm vào nhà bạn');
            }
            else
            {
                alert('Có lỗi khi thêm album vào nhà bạn. Hãy thử lại lần khác');
            }
        });
        return false;
    },
    alertLogin: function()
    {
        alert('Bạn cần đăng nhập để sử dụng chức năng này');
        return false;
    },
    alertViolence: function(aid)
    {
        var width = 500;
        var height = 220;
        var left = parseInt((screen.availWidth/2) - (width/2));
        var top = parseInt((screen.availHeight/2) - (height/2));
        var windowFeatures = "width=" + width + ", height=" + height + ", left=" + left + ", top=" + top + ", screenX=" + left + ",screenY=" + top + ", resizable=no, status=no, menubar=no, scrollbars=no";
        window.open("/alert/" + aid, "subWind", windowFeatures);
        return false;
    },
    slidePreview: function(aid)
    {
        var width = 570;
        var height = 440;
        var left = parseInt((screen.availWidth/2) - (width/2));
        var top = parseInt((screen.availHeight/2) - (height/2));
        var windowFeatures = "width=" + width + ", height=" + height + ", left=" + left + ", top=" + top + ", screenX=" + left + ",screenY=" + top + ", resizable=no, status=no, menubar=no, scrollbars=no";
        window.open("/slide/preview/" + aid, "subWind", windowFeatures);
        return false;
    },
    getThank: function(uid, aid)
    {
        $.ajax({
               type: "GET",
               url: "/thank/get?uid=" + uid + "&aid=" + aid,
               complete: function(res, s){
                   if (s!="success")
                   {
                    $("#user_thank").html("Social networking service error");
                   }
                   else
                   { 
                    $("#user_thank").html(res.responseText);
                   }
                }       
            });
    },
    setThank: function(aid, val)
    {
        $.ajax({
               type: "POST",
               url: "/thank/set?aid=" + aid + "&val=" + val,
               beforeSend: function(req){
                    $("#user_thank").html("Sending...");
               },
               complete: function(res, s){
                    if (s=="success")
                    {
                        $("#user_thank").html(res.responseText);
                    }
                    else
                    {
                        $("#user_thank").html("Social networking service error");
                    }
                }
            });
    },
    makeFriend: function(uid, uname){
        if (confirm("Bạn chắc chắn muốn kết bạn với " + uname)) {
            $.getJSON("http://www.tamtay.vn/myfriend/makeFriend/" + uid + "?jsoncallback=?", function(data){alert("Yêu cầu kết bạn đã được gửi đến " + uname);});
        }
    }
}


//SNS
var sns=
{
    group_cache: "",
    event_cache: "",
    place_holder: "",
    aid: 0,
    uid: 0,
    listGroup: function(id, type)
    {
        if (this.place_holder=="")
        {
            this.place_holder=$('#sns_place').html();
        }
        var url_="/sns/" + type + "group/";
        if (type=='add')
        {
            this.aid=id;//album id
        }
        else
        {
            this.uid=id;//invited uid
        }
        $.ajax({
            type: "GET",
            url: url_,
            beforeSend: function(req){
                $('#sns_place').html("Đang tải...");
            },
            complete: function(res, s){
                group_cache=res.responseText;
                $('#sns_place').html(res.responseText);
            }
        });
        return false;
    },
    addGroup: function()
    {
        if (!confirm('Bạn chắc chắn thêm album nào vào nhóm'))
        {
            return false;
        }

        $.ajax({
            type: "POST",
            url: "/sns/addgroup",
            data: $("#gid").serialize() + "&aid=" + this.aid,
            beforeSend: function(req){
                $('#sns_place').html("Đang gửi...");
            },
            complete: function(res, s){
                $('#sns_place').html(res.responseText);
            }
        });
        return false;
    },
    inviteGroup: function()
    {
        if (!confirm('Bạn chắc chắn mời người đăng vào nhóm'))
        {
            return false;
        }

        $.ajax({
            type: "POST",
            url: "/sns/invitegroup",
            data: $("#gid").serialize() + "&uid=" + this.uid,
            beforeSend: function(req){
                $('#sns_place').html("Đang gửi...");
            },
            complete: function(res, s){
                $('#sns_place').html(res.responseText);
            }
        });
        return false;        
    },
    listEvent: function(id, type)
    {
        if (this.place_holder=="")
        {
            this.place_holder=$('#sns_place').html();
        }
        var url_="/sns/" + type + "event/";
        if (type=='add')
        {
            this.aid=id;//album id
        }
        else
        {
            this.uid=id;//invited uid
        }
        $.ajax({
            type: "GET",
            url: url_,
            beforeSend: function(req){
                $('#sns_place').html("Đang tải...");
            },
            complete: function(res, s){
                group_cache=res.responseText;
                $('#sns_place').html(res.responseText);
            }
        });
        return false;
    },
    addEvent: function()
    {
        if (!confirm('Bạn chắc chắn thêm album nào vào sự kiện'))
        {
            return false;
        }

        $.ajax({
            type: "POST",
            url: "/sns/addevent",
            data: $("#eid").serialize() + "&aid=" + this.aid,
            beforeSend: function(req){
                $('#sns_place').html("Đang gửi...");
            },
            complete: function(res, s){
                $('#sns_place').html(res.responseText);
            }
        });
        return false;        
    },
    inviteEvent: function()
    {
        if (!confirm('Bạn chắc chắn mời người đăng vào sự kiện'))
        {
            return false;
        }

        $.ajax({
            type: "POST",
            url: "/sns/inviteevent",
            data: $("#eid").serialize() + "&uid=" + this.uid,
            beforeSend: function(req){
                $('#sns_place').html("Đang gửi...");
            },
            complete: function(res, s){
                $('#sns_place').html(res.responseText);
            }
        });
        return false;        
    },
    restore: function()
    {
        $('#sns_place').html(this.place_holder);
        return false;
    }
}