/*
    
    name: historyOptions
    file: jquery.historyOptions.js
    author: gregory tomlinson
    copyright: (c) 2010 bit.ly
    Dual licensed under the MIT and GPL licenses.
    ////////////////////////////////////
    ////////////////////////////////////
    dependencies: jQuery 1.4.2, utilties/ZeroClipboard.js, utilties/getJS.js, jquery.cookie.js
    ////////////////////////////////////
    ////////////////////////////////////            

*/

(function($){
    
    $.fn.historyOptions = function( options ) {
        

        
        var el=this, o = $.extend(true, {}, defaults, options ), 
            clip, hash, copyButton, copyButtonBox, editTitleCounter=0, editTitleSavedCounter = 0;
            options;

        if(el.length <= 0) return this;
        el.bind('hashList', attachOptions);

        ZeroClipboard.setMoviePath('/s/flash/zeroclipboard/ZeroClipboard.swf');

        return this;
        
        // function success(jo) {
        //     
        // }
        

        
        function error(jo) {
            console.log(jo)
        }
        
        function attachOptions(e,data) {
            var box, flashHTML, $copyButtonBox, $elem, hash, clip;
            options = el.find('.optionsDropDownContainer');
            
            el.bind('openSharePanel', function(e,data) {
                url = o.sharePanelUrl + "u=" + encodeURIComponent( data.url ) + "&s=" + encodeURIComponent( data.title || "" );
                getJS( url );
            });
            
            options.each(function(idx, elem) {

               //elem.innerHTML = renderDropDown();
               hash = "http://"+ (data.results[idx].domain || o.host_name) +"/" + data.results[idx]._id
               clip = new ZeroClipboard.Client();

               $elem = $(elem).append( renderDropDown() );
               
               $elem.data('result', data.results[idx])

               $copyButtonBox = $elem.find('.optionsCopyButtonContainer');


               clip.setText( hash );
               clip.glue(  $elem.find('.optionsCopyButton')[0], $elem.find('.optionsCopyButtonContainer')[0], { width : '65px', height: '20px' }, { width : 60, height: 20 } )
               clip.addEventListener( 'complete', function(client, text) {
                    el.find('.openOptionsMenu').trigger('click');
                    el.trigger('successMessage', {
                        text : 'Successfully copied to clipboard'
                    })

               });           

            });    
            
            el.find('.optionsShareButton').bind('click', openSharePanel);
            el.find('.optionsDeleteButton').bind('click', deleteHistoryItem);  
            el.find('.editableTitleButton').bind('click', editHistoryTitle)          
            
            
            $(document).bind('click', function(e) {
                el.find('.openOptionsMenu').trigger('click');
            });            
            
            el.find('.topLevel').toggle(openMenu, closeMenu);        
        }
        
                
        function openMenu(e) {
            e.preventDefault();
            el.find('.openOptionsMenu').trigger('click');            
            $(this).addClass('openOptionsMenu');
        }
        
        
        
        function openSharePanel(e) {
            e.preventDefault();
            e.stopPropagation();
            var $this = $(this), data = $this.parents('.optionsDropDownContainer').data('result');
            
            $this.trigger('openSharePanel', data);        
        }
        
        
        function editHistoryTitle(e) {
            editTitleCounter++;
            var $this = $(this), 
                data = $this.parents('.optionsDropDownContainer').data('result'),
                $p = $this.parents('.resultsItemContainer'),
                $titleContainer = $p.find('.linkTitleContainer'),
                $titleElem = $titleContainer.find('.linkTitle'),
                existing_form = $titleContainer.find('.histOptions_editTitleContainer');
            

            if(existing_form.length > 0 ) {
                $titleElem.css('display', 'block')
                existing_form.remove();
                return;
            }
            
            $this.trigger('track', { 'plugin:historyOptions' : 'Edit Title, this session:' + editTitleCounter } )                                 
            $titleElem.css('display', 'none')
            var $form = renderEditTitleBox( data ).prependTo($titleContainer),
                $input = $form.find('.edit_title_input').focus();
            
            $form.find('form').bind('submit', function(e) {
                
                // 
                e.preventDefault();


                var new_title = $.trim( $input.val() );
                if( new_title  === '') { return; }
                
                if(new_title === data.title) {
                    closeEdit();
                    console.log('existing, same title')
                    return;
                }
                
                // save it here
                // validate the title actually changed... overwise, just end it
                
                // trigger another event
                var title_params = {
                    "user_hash" : data._id,
                    "title" : new_title
                }
                connector(o.update_url, title_params, function(jo) {
                    console.log('success saving new title', $this, jo)
                    //$this.trigger('deleteHistoryItem')
                    if(!jo || jo.status_code !== 200 ) {
                        $this.trigger('errorMessage', {
                            'text' : 'Unable to save that title.'
                        })                        
                        
                        return;
                    }
                    $titleElem.find('a').html( $.escapeHTML( new_title ) );  
                    data.title = new_title;
                    $p.find('.optionsDropDownContainer').data('result', data)                    
                    $this.trigger('successMessage', {
                        'text' : 'Success, title updated'
                    });
                                     
                    closeEdit();
                }, function() {
                    console.log('error')
                    $this.trigger('errorMessage', {
                        'text' : 'Unable to save that title.'
                    })
                    
                    closeEdit()
                });                
                
                // do this on success!

                
            });
            
            function closeEdit() {
                if($titleElem && $form) {
                    $titleElem.css('display', 'block')
                    $form.remove();                    
                }

            }
            
        }
        
        
        
        function deleteHistoryItem(e) {
                
            var $this = $(this), confirm_answer,
                data = $this.parents('.optionsDropDownContainer').data('result');
            
            // todo, consider exchanging this with a custom dialogue box
            //confirm_answer = confirm( o.deleteConfirmationText );
            
            // if(confirm_answer) {
                o.params.user_hash = data._id;

                connector(o.url, o.params, function(jo) {
                    console.log('success deleting', $this)
                    $this.trigger('deleteHistoryItem')
                }, error);                
            // } 
            
        }
        
        
        
        function closeMenu(e) {
            console.log('close')
            e.preventDefault();            
            var $this = $(this);
            if( $this.hasClass('openOptionsMenu') ) $(this).removeClass('openOptionsMenu')
        }
        
        
        function renderEditTitleBox( data ) {
            var display_title_value = $.escapeHTML( data.title || data.url )
            var html = '<div class="histOptions_editTitleContainer">';
                    html += '<img alt="" border="0" class="editable_title_favicon" width="16" height="16" src="/favicon/'+data.global_hash+'.png" />'
                    html += '<div class="histOptions_editTitleFormBx">'
                        html += '<form action="#" method="get" accept-charset="utf-8">'
                            html += '<div class="edit_title_input_box">'
                            html += '<input type="text" class="edit_title_input" name="edit_title_input" value="'+display_title_value+'" id="some_name">'
                            html += '</div><div class="edit_title_save_box">'
                            html += '<input class="edit_title_save saveEditableTitle" type="submit" name="" value="Save" />'
                            html += '</div>'
                            html += '<div class="hr"><hr /></div>'
                        html += '</form>';
                    html += '</div>'
                html += '</div>'
            
            var $html = $(html)
            return $html
        }
        
        function renderDropDown() {
            
            var html = "";
            
            html += '<ul class="toolsDropList">'
                html += '<li class="topLevel">'
                        html += '<div class="optionsToolPanel">'
                            html += '<b class="topLeft"></b>';
                            html += '<b class="topRight"></b>'
                            html += '<span>Options</span>'
                        html += '</div>'
                    html += '<ul class="toolsList">';
                        html += '<li class="toolsListShare"><a class="optionsShareButton" href="#">Share</a></li>';
                        html += '<li class="optionsCopyButtonContainer">';
                                html += '<a class="optionsCopyButton" href="#">Copy</a>';
                        html += '</li>';
                        //html += '<li><a href="">Tag</a></li>';
                        if(o.showDelete) html += '<li class="toolsListDelete"><a class="optionsDeleteButton" href="#">Archive</a></li>';                                
                        html += '<li class="editableTitleListItem"><a class="editableTitleButton" href="#">Edit</a></li>';                        
                    html += '</ul>';
                html += '</li>';
            html += '</ul>'            
            
            return $(html);
        }
    }
    
    var defaults = {
        url : '/data/delete',
        update_url : '/data/update_title',
        params : {
            user_hash : ''
        },
        host_name : 'bit.ly',
        showDelete : true,
        deleteConfirmationText : 'Are you sure you want to delete this?',
        sharePanelUrl : '/bookmarklet/load.js?ls=1&'
    }, $bod
    
    function connector(url, params, callback, error) {
        params._xsrf = $.cookie.get("_xsrf");
        var str = $.param( params );
        $.ajax({
            dataType: 'json', 
            type : 'POST',                   
            'url' : url, 
            data : str,
            success : callback,
            'error' : error
        });
    }    
    
})(jQuery);