/*
    +-----------------------------------------------------------------------+
    | Copyright (c) 2006-2009 Napalm Riot Inc.								|
    +-----------------------------------------------------------------------+
    | This source file is bound by United States copyright law.				|
    +-----------------------------------------------------------------------+
*/

Napalm_Tags = {

    component: 'Component_Tags',
    componentHook: 'hook',
    componentUnhook: 'unhook',
    componentTooltip: 'tooltip',
    
    urls: {},
    
    contentId: false,
    contentType: false,
    type: false,
    visibility: false,

    adding: false,
    addBackup: '',

    minLength: 2,
    maxLength: 20,

	/* Startup */
	init: function( _contentId, _contentType, _type, _visibility ) {		
	    var self = this;
	    
	    /* URL Setup */
	    //this.urls[512] = $j( 'link[rel="forumurl"]' ).attr( 'href' ) + '/t:%s'; /* Forum */
	    this.urls[16384] = $j( 'link[rel="gamesurl"]' ).attr( 'href' ) + '/browse/t:%s'; /* Game */

	    this.contentId = _contentId;
	    this.contentType = _contentType;
	    this.type = _type;
	    this.visibility = _visibility;

        this.bindRemoveButtons( false, function( _id ) {
            self.removeTag( _id );
            Napalm_UI.NotificationBar.add( 'Removed <strong>5</strong> achievement points!', 'warning' );
        });

        if ( typeof( this.urls[this.contentType] ) !== 'undefined' ) {
            self.bindButtonClicks();
        }

        self.bindAddButton( '#tag-add-button', _contentType, _contentId, _type, _visibility,
            function( data ) {
                var $tagAddButton = $j( '#tag-add-button' );
                $tagAddButton.before( '<span id="tag-item-' + data.tagid + '" style="display:none;" class="tag-item-owner tag-item"><span class="x">x</span> ' + data.content + ' </span>');
                $j( '#tag-item-' + data.tagid ).fadeIn( 500 );
                if ( typeof( this.urls[this.contentType] ) !== 'undefined' ) {
                    self.bindButtonClicks( '#tag-item-' + data.tagid );
                }
                self.bindRemoveButtons( '#tag-item-' + data.tagid, function( _id ) {
                    self.removeTag( _id );
                    Napalm_UI.NotificationBar.add( 'Removed <strong>5</strong> achievement points!', 'warning' );
                });
                
                Napalm_UI.NotificationBar.add( '<strong>+5</strong> achievement points!', 'positive' );

                $j( '#tag-add-button' ).click();
            }
        );
    },

    removeTag: function( _id ) {
        var self = this;
        $j( '#tag-item-' + _id ).fadeOut( 500, function() {
            $j( this ).remove();
        });
    },

    bindButtonClicks: function( _element ) {
        var self = this;
        if ( typeof( _element ) !== 'undefined' ) {
            $element = $j( _element );
            $element.click( function() {
                $clone = $j( this ).clone();
                $clone.find( '.x' ).remove();
                var tag = $j.trim( $clone.text() );
                document.location = sprintf( self.urls[self.contentType], tag );
            } );
        } else {
            $j('span.tag-item').click(function() {
                $clone = $j(this).clone();
                $clone.find('.x').remove();
                var tag = $j.trim($clone.text());
                document.location = sprintf( self.urls[self.contentType], tag );
            });
        }
    },

    bindRemoveButtons: function( _element, _callback ) {
        var self = this;
        if ( typeof( _element ) !== 'undefined' && _element !== false ) {
            $element = $j( _element );
            $removeButton = $j( 'span.x', $element );

            var id = $element.attr( 'id' ).split( '-' )[2];
            $removeButton.click( function( e ) {
                self.removeItem( $j( this ).closest( '.tag-item' ).attr( 'id' ).split( '-' )[2], function( data ) {
                    if ( data ) {
                        _callback( data.tagid );
                    } else {
                        _callback( false );
                    }
                });
                e.cancelBubble = true;
                if ( e.stopPropagation() ) { e.stopPropagation() };
            } );
        } else {
            $j( 'span.tag-item' ).each( function() {
                var $item = $j( this );
                var id = $item.attr( 'id' ).split( '-' )[2];
                var $removeButton = $j( '#' + $item.attr( 'id' ) + ' span.x' );

                $removeButton.click( function( e ) {
                    self.removeItem( id, function( data ){
                        if ( data ) {
                            _callback( data.tagid );
                        } else {
                            _callback( false );
                        }
                    });
                    e.cancelBubble = true;
                    if ( e.stopPropagation() ) { e.stopPropagation() };
                });
            });
        }
    },

    removeItem: function( _tagId, _callback ) {
        if ( confirm( 'Remove Tag?' ) ) {
            $j.getJSON( window.urls.component + this.component + ';' + this.componentUnhook + ';' + escape( escape( JSON.stringify( {tagid:_tagId} ) ) ),
                function( data ) {
                    if ( data.success ) {
                        _callback( data.response );
                    } else {
                        Napalm_UI.error( data.response );
                        return false;
                    }
                }
            );
            return false;
        }
        return false;
    },

    bindAddButton: function( _element, _hookType, _hookId, _tagType, _tagVisibility, _callback ) {
        if ( typeof( _hookType) === 'undefined' ) { return false; }
        if ( typeof( _hookId) === 'undefined' ) { return false; }
        if ( typeof( _tagType) === 'undefined' ) { return false; }
        if ( typeof( _tagVisibility) === 'undefined' ) { return false; }
        if ( typeof( _callback) !== 'function' ) { return false; }

        var self = this;
        $j( _element ).click( function() {
            $this = $j( this );
            if ( !self.adding ) {
                self.adding = true;
                $this.before( '<input type="text" maxlength="20" class="tag-new-field" />' );
                var $textField = $this.siblings( 'input[class="tag-new-field"]' );
                $textField
                    .bind( 'keydown', function(e) {
                        if ( e.keyCode == 13 ) {
                            var tagLength = $j.trim( $textField.val() ).length;
                            if ( tagLength < 1 ) {
                                $this.val( self.addBackup );
                                $textField.remove();
                            } else if ( tagLength >= self.minLength && tagLength <= self.maxLength ) {
                                self.hook( _hookType, _hookId, _tagType, _tagVisibility, $j.trim( $textField.val() ),
                                    function( data ) {
                                        self.adding = false;
                                        $this.val( self.addBackup );
                                        $textField.remove();
                                        _callback( data );
                                    }
                                );
                            }
                        } else if ( e.keyCode == 27 ) {
                            $this.val( self.addBackup );
                            $textField.remove();
                        }
                    })
                    .fadeIn( 500 )
                    .focus();
                self.addBackup = $this.val();
                $this.val( 'X' );
            } else {
                self.adding = false;
                $this.siblings( 'input[class="tag-new-field"]' ).fadeOut( 250 ).remove();
                $this.val( self.addBackup );
            }
            return false;
        });
    },

    systemPublicHook: function( _hookType, _hookId, _content ) {
        return this.hook( _hookType, _hookId, 'system', 'public', _content );
    },

    systemPrivateHook: function( _hookType, _hookId, _content ) {
        return this.hook( _hookType, _hookId, 'system', 'private', _content );
    },

    userPublicHook: function( _hookType, _hookId, _content ) {
        return this.hook( _hookType, _hookId, 'user', 'public', _content );
    },

    userPrivateHook: function( _hookType, _hookId, _content ) {
        return this.hook( _hookType, _hookId, 'user', 'private', _content );
    },

    hook: function( _hookType, _hookId, _tagType, _tagVisibility, _content, _callback ) {
        if ( typeof( _hookType) === 'undefined' ) { return false; }
        if ( typeof( _hookId) === 'undefined' ) { return false; }
        if ( typeof( _tagType) === 'undefined' ) { return false; }
        if ( typeof( _tagVisibility) === 'undefined' ) { return false; }

        var packet = {  hooktype:_hookType,
                        hookid:_hookId,
                        tagtype:_tagType,
                        tagvisibility:_tagVisibility,
                        content:_content };

        $j.getJSON( window.urls.component + this.component + ';' + this.componentHook + ';' + escape( escape( JSON.stringify( packet ) ) ),
            function( data ) {
                if ( data.success ) {
                    _callback( data.response );
                } else {
                    Napalm_UI.error( data.response );
                    return false;
                }
            }
        );
    },

    unhook: function() {

    }
}