// smClipboardCopy - a tool to gather data from elements and copy to clipboard
// Author - Igor Szyporyn
// Owner - System & Metode A/S
// Requires - jQuery, jQuery.fn.smMarkerTool, jQuery.fn.zclip

(function($) {

    var prefix = 'smClipboardCopy',
        scriptpath = $("script").last().attr("src").split('?')[0].split('/').slice(0, -1).join('/')+'/',
        _methods = {
            addPrefix         : function( name ) {

              return name + '.' + prefix;
            },
            getItems    : function( element, plugins, dataCollection ) {
                $.each( plugins, function( i, v ) {
                
                    // Gather data from the plugin
                    if ( typeof v == 'object' ) {
                        var items = v.getItems( element );
                        dataCollection[v.name] = items;
                    }

                });
                return dataCollection;
            },
            getValues   : function( marker, plugins, dataCollection ) {
                var _values = '',
                    value,
                    i = 0,
                    l = plugins.length,
                    v,
                    len;

                    
                for ( i; i < l; i++ ) {
                    v = plugins[i];
                    len = dataCollection[v.name].length;

                    $.each( dataCollection[v.name], function( p, o ) {
                        value = o.getValue( _methods.isSelected( o.dimensions, marker.dimensions ) );
                        if ( o.preValue && p == 0) {
                            _values += o.preValue;
                        }
                        if ( value ) {
                            _values += value;
                        }
                        if (o.postValue && p == len - 1) {
                            _values += o.postValue;
                        }
                        
                    });
                }

                return _values;
            },
            isSelected  : function( elDim, markerDim ) {
                var withinX = markerDim.left <= elDim.left && ( markerDim.left + markerDim.width ) >= ( elDim.left + elDim.width ),
                    withinY = markerDim.top <= elDim.top && ( markerDim.top + markerDim.height ) >= ( elDim.top + elDim.height );
                return ( withinX && withinY );
            },
            highlight   : function( marker, plugins, dataCollection ) {

                var i = 0,
                    l = plugins.length,
                    v,
                    p;

                for ( i; i < l; i++ ) {
                    v = plugins[i];
                    if ( v.onHighlight ) {
                        $.each( dataCollection[v.name], function( p, o ) {
                            o.onHighlight( _methods.isSelected( o.dimensions, marker.dimensions ) );
                        });
                    }
                }
            },
            highlightClear  : function( plugins, dataCollection ) {
                var i = 0,
                    l = plugins.length,
                    v,
                    p;
                for ( i; i < l; i++ ) {
                    v = plugins[i];
                    if ( v.onHighlight ) {
                        $.each( dataCollection[v.name], function( p, o) {
                            o.onHighlight(false);
                        });
                    }
                }
            },
            copyToPaste     : function( toCopy ) {
                var isMsie = $.browser.msie,
                    copyWindow,
                    copyText,
                    copyButton;

                if ( isMsie ) {

                    window.clipboardData.setData( 'Text', toCopy );

                } else {
                
                  // Custom solution
                  copyWindow = $('<div />')
                    .css({
                      'z-index'   : '9999',
                      'position'  : 'absolute',
                      'padding'   : '10px',
                      'top'       : ( $(window).height() / 2 ) - 40 + 'px',
                      'left'      : ( $(window).width() / 2 ) - 75 + 'px',
                      'background-color'  : '#ffffff',
                      'border'    : '1px solid #ababab'
                    })
                    .appendTo('body');
                    
                  copyText = $('<p />')
                    .text('tryk ok for at kopiere til clipboard')
                    .css({
                      'margin-bottom' : '10px',
                      'font-size'     : '12px'
                    })
                    .prependTo(copyWindow);
                    
                  copyButton = $('<a />')
                    .text('ok')
                    .css({
                      'text-decoration' : 'none',
                      'color'           : '#000',
                      'width'           : '30px',
                      'font-size' : '15px',
                      'display' : 'block',
                      'margin'  : '0 auto',
                      'padding' : '3px 0px 3px 12px',
                      'background-color'  : '#cccccc',
                      'border'  : '1px solid #000000'
                    })
                    .appendTo(copyWindow)
                    .zclip({
                        path:   scriptpath + 'zclip/ZeroClipboard.swf',
                        copy:   toCopy
                    })
                    .bind( 'click', function( event ) {
                      copyWindow.remove();
                    });
                  

                    // Quick solution for IP2 only!!
                    /*
                    var alertWindow = new Ext.Window({
                        width:  300,
                        title:  'Kopier til clipboard',
                        id: 'copyToClipboardWindow',
                        items:  [{
                            xtype:  'panel',
                            html:   '<h3 style="margin:5px 0px;">Tryk OK for at kopiere dette til dit clipboard</h3>'
                        },{
                            xtype:  'button',
                            text:   'OK',
                            id: 'copyToClipboardButtonExt'
                        }]
                    });
                    
                    alertWindow.show();
              
                    var $alertWindowInner = $('#' + alertWindow.el.id + ' .x-window-bwrap');
                    
                    var $extButton = $('#copyToClipboardButtonExt'),
                        $extButtonInner = $extButton.find(':button');

                    var btnW = $extButton.width();
                    var winW = $alertWindowInner.width();
                    var winP = parseFloat($alertWindowInner.children('.x-window-ml').css('padding-left'));

                    $extButton.css('margin-left', ( ( winW - btnW - (winP * 2) ) / 2 ) + 'px');
                        
                    var $button = $('<a />')
                        .attr('id','copyToClipboardButton')
                        .insertBefore($extButtonInner.hide())
                        .text('OK')
                        .css({
                            'text-decoration'   :   'none',
                            'color' :   '#FFFFFF'
                        })
                        .zclip({
                            path:   scriptpath + 'zclip/ZeroClipboard.swf',
                            copy:   toCopy
                        })
                        .bind( 'click', function( event ) {
                          //alertWindow.destroy();
                        });
                        
                    $('.zclip')
                      .css({
                          'left'      :   $extButton.offset().left - $alertWindowInner.offset().left,
                          'top'       :   $extButton.offset().top - $alertWindowInner.offset().top,
                          'height'    :   $extButton.outerHeight(),
                          'width'     :   $extButton.outerWidth()
                      })
                      .bind( 'click', function( event ) {
                        alertWindow.destroy();
                      });
                    */
                }
            }
        },
        methods = {

            init      : function( options ) {

                var settings =  $.extend(true, {}, {
                                    design            : {
                                        borderColor   : '#369',
                                        borderWidth   : '1px',
                                        borderStyle   : 'solid', 
                                        background    : '#def',
                                        opacity       : 0.5
                                    },
                                    plugins     : false,
                                    threshold   : 0.5,
                                    beforeCopy  : true,
                                    afterCopy   : true   
                                }, options);

                return this.each(function() {

                    var $this = $(this),
                        _this = this,
                        dataCollection = {},
                        pluginObject,
                        plugins = [],
                        pluginIds = [];

                    if ( !$this.data( prefix ) ) {
                        
                        // Load zclip if not loaded
                        if ( typeof $.fn.zclip != 'function' ) {
                          $.getScript(scriptpath + "zclip/jquery.zclip.js")
                            .done(function(script, textStatus) {
                            })
                            .fail(function(jqxhr, settings, exception) {
                            });
                        }

                        // Load plugins
                        $.each( settings.plugins, function( i, v ) {
                            

                            if ( typeof v == 'string' ) {
                              $.getScript(scriptpath + "plugins/" + v + ".js")
                                .done(function(script, textStatus) {
                                  var parent = $.fn[prefix],
                                      plugin = parent[v];

                                  if (plugin) {
                                      pluginObject = plugin();
                                      plugins.push( pluginObject );
                                      pluginIds.push( pluginObject.name );
                                  }
                                })
                                .fail(function(jqxhr, settings, exception) {
                                });
                            }

                            if ( typeof v == 'function' ) {
                                pluginObject = v();
                                plugins.push( pluginObject );
                                pluginIds.push( pluginObject.name );
                            }

                        });

                        // Attach marker tool and fire callback events (build dataCollection, highlight dataCollection, output dataCollection)
                        $this.smMarkerTool({
                            design      : {
                                borderColor   : settings.design.borderColor,
                                borderWidth   : settings.design.borderWidth,
                                borderStyle   : settings.design.borderStyle, 
                                background    : settings.design.background,
                                opacity       : settings.design.opacity
                            },
                            beforeDraw  : function( marker ) {

                                _methods.getItems( this, plugins, dataCollection );
                            },
                            onDrawAfter : function( marker ) {

                                 _methods.highlight( marker, plugins, dataCollection );
                            },
                            afterDraw   : function( marker ) {

                                var output = '';

                                _methods.highlightClear( plugins, dataCollection );
                                output = _methods.getValues( marker, plugins, dataCollection );
                                if ( output.length ) {
                                  _methods.copyToPaste(output);
                                }
                            }
                        });

                    $this.data( prefix, true );

                    }

                });

            },
            destroy         : function() {

            },
            removePlugin    : function( pluginName ) {

            },
            createPluginBase    : function ( o ) {

                var $o = $(o),
                    p = $o.offset();

                return {
                    element         : o,
                    dimensions      : {
                        left    : p.left,
                        top     : p.top,
                        width   : $o.outerWidth(),
                        height  : $o.outerHeight()
                    }
                }

            }

        };


    $.fn[prefix] = function( method ) {

        if ( methods[ method ] ) {
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.' + prefix );
        }

    }
  

})(jQuery);