
;(function($) {


    /*
    * wiz plugin.ini structure
    *
    */
    var pluginStruct = {
        AppName: '',
        AppGUID: '',
        AppType: '',
        AppVersion: '',
        PluginCount: ''
    };


    /*
    * Avoid the ERROR when xml file be succession of openning and closing in seconds
    *
    */
    window.xmlFile = '';
    window.xmlFileOpener = null;
    window.xmlFileToken = null;
    window.xmlFileLocker = false;

    $(window).unload(function() {

        if (xmlFileOpener)
            xmlFileOpener.Close();

    });

    window.saveProtecter = function() {

        if (xmlFileLocker)
            setTimeout('saveProtecter()', 1000);

        else {

            if (xmlFileToken)
                clearTimeout(xmlFileToken);

            xmlFileToken = setTimeout('save()', 1000);
        }
    }

    window.save = function() {
        xmlFileLocker = true;
        xmlFileOpener.Close();
        xmlFileOpener.Open(xmlFile);
        xmlFileLocker = false;
    }


    /*
    * JQuery `Wiz Plugin` plugin
    *
    */
    $.fn.wizPluginLoad = function(settings) {

        /*
        * Initialize basic variables
        *
        */
        var _objApp = (!settings || !settings.objApp) ? (window.objApp || window.external) : settings.objApp;
        var _guid = this.selector.match(/\{([\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})\}|([\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/);

        if (!_objApp || !_objApp.DataStore || !_guid)
            return false;

        _guid = _guid[1] || _guid[2];


        /*
        * Default _settings & input settings
        *
        */
        var _settings = $.extend({

            // default setting & function here

            objApp: _objApp,
            objCUI: false,
            objSet: false,

            seid: 'Plugin_' + _guid.replace(/\-/g, '_'),
            type: 'knowledge',
            lcid: 'default',
            tmpl: $('<div />'),

            group: false,
            append: false,
            folder: '',

            update: function() {

                this.pluginUninstall
          ? this.tmpl.wrapInner($('<div />').css({ fontSize: '12px', marginLeft: '-3px' })).css({ overflow: 'hidden', fontSize: 0 }).slideUp('slow', function() { alert(_s('operateUninstallComplete')); })
          : (this.pluginEnable
            ? this.tmpl.removeClass('disable').find('span.icon img').css('opacity', 1).end().find('span.disabled').hide()
            : this.tmpl.addClass('disable').find('span.icon img').css('opacity', 0.4).end().find('span.disabled').show());

                return this;
            },

            onEnable: function() {
                return this.update();
            },

            onDisable: function() {
                return this.update();
            },

            onUninstall: function() {
                return this.update();
            }

        }, settings || {});


        /*
        * Initialize variables under settings
        *
        */
        var _objCUI = (_settings.objCUI ? _settings.objCUI : _objApp.CreateWizObject('WizKMControls.WizCommonUI'))
      , _objSet = (_settings.objSet ? _settings.objSet : _objApp.CreateWizObject('WizKMCore.WizSettings'))
      , _xml = _objApp.SettingsFileName
      , _root = (_settings.type == 'knowledge' ? _objApp.DataStore : _objApp.AppPath)
      , _ds = _objApp.DataStore.slice(-1)
      , _path = _settings.folder != '' ? _settings.folder + '\\' : (_root + 'Plugins' + _ds + '{' + _guid + '}' + _ds)
      , _file = _path + 'plugin.ini'
      , _lcid = _settings.lcid != 'default' ? ('_' + _settings.lcid) : ''
      , _system = _settings.type == 'base'
      ;

        // checke if plugin exists
        if (!_objCUI)
            return;

        //if (_objCUI.GetValueFromIni (_file, 'common', 'AppName') == '')
        // s

        // check if xml setting file opened
        if (!window.xmlFileOpener) {
            (window.xmlFileOpener = _objSet).Open(_xml);
            window.xmlFile = _xml;
        }


        /*
        * Handle template, structure & display
        *
        */
        var _tmpl = _settings.tmpl;

        for (i in pluginStruct) {
            $('.' + i, _tmpl).html(this[i] = _i(i));
        }

        if (this.AppName == '')
            $('.AppName', _tmpl).html('<span class="unnamed">' + (this.AppName = _s('pluginUnnamed')) + '</span>');


        var AppCaptions = Array();

        for (i = 0; i < this.PluginCount; i++) {
            _p(i, 'Caption') == '' || AppCaptions.push(_p(i, 'Caption').replace('...', ''));
        }


        _tmpl.attr('title', txt = this.AppCaptions = AppCaptions.join(', '));


        if (txt.length > 20)
            txt = txt.substr(0, 20) + '...';

        $('.AppCaptions', _tmpl).html(txt);


        /*
        * Event functions
        *
        */
        function isEnable() {
            return _objSet.StringValue('Plugins', _settings.seid) != '0';
        }

        function enable() {

            _objSet.SetStringValue('Plugins', _settings.seid, 1);

            this.pluginEnable = true;
            this.onEnable();

            saveProtecter();
        }

        function disable() {

            _objSet.SetStringValue('Plugins', _settings.seid, 0);

            this.pluginEnable = false;
            this.onDisable();

            saveProtecter();
        }

        function openLocation() {
            _objCUI.RunExe('explorer.exe', _path, false);
        }

        function uninstall() {

            if (this.isSystem && !confirm(_s('operateSystemUninstall')))
                return;

            if (!_objCUI.PathFileExists(_path))
                alert(_s('operateUninstallNotExists'));

            else if (confirm(_s('operateCheckUninstall', this.AppName))) {

                this.tmpl.css({ opacity: 0.4, cursor: 'default' }).unbind('dblclick').find('a').unbind('click');

                _objCUI.DeletePathFile(_path.replace(/[\/\\]$/, ''));

                this.pluginUninstall = true;
                this.onUninstall();
            }
        }

        function checkState() {

            if (_settings.group && !_settings.append) {

                _tmpl.addClass('group-first');

                var eText = _s('groupPluginExpand') /*.replace ('%', _settings.group)*/
          , sText = _s('groupPluginShrink') /*.replace ('%', _settings.group)*/
          ;

                $('span.icon img', _tmpl).attr('src', 'images/wizplugin_pack_ge.png');
                $('a.group', _tmpl)
          .css('visibility', 'visible')
          .data('etext', eText)
          .data('stext', sText)
          .html(eText).toggle(
            function(event) { event.stopPropagation(); $(this).addClass('shrink').html($(this).data('stext')); $('li.' + _guid).slideDown('slow'); },
            function(event) { event.stopPropagation(); $(this).removeClass('shrink').html($(this).data('etext')); $('li.' + _guid).slideUp('slow'); }
          )
          .mouseover(function() { $(this).css('text-decoration', 'underline'); })
          .mouseout(function() { $(this).css('text-decoration', 'none'); });
            }

            else if (_system) {
                $('span.icon img', _tmpl).attr('src', 'images/wizplugin_system_ge.png').parent().next().prepend($('<span class="system">' + _s('systemPlugin') + '</span>'));
            }

            if (_settings.append)
                _tmpl.addClass('group').addClass(_guid);
        }


        /*
        * Language functions
        *
        */
        function _i(stringName) {
            return ((txt = _objCUI.GetValueFromIni(_file, 'common', stringName + _lcid)) == '') && _lcid != '' ? _objCUI.GetValueFromIni(_file, 'common', stringName) : txt;
        };

        function _p(index, stringName) {
            return ((txt = _objCUI.GetValueFromIni(_file, 'Plugin_' + index, stringName + _lcid)) == '') && _lcid != '' ? _objCUI.GetValueFromIni(_file, 'Plugin_' + index, stringName) : txt;
        };


        /*
        * Binding property & function to `this`
        *
        */
        this.tmpl = _tmpl;
        this.settings = _settings;
        this.isSystem = _system;

        this.pluginUninstall = false;
        this.checkState = checkState;
        this.pluginEnable = isEnable();

        this.isEnable = isEnable;
        this.enable = enable;
        this.disable = disable;
        this.uninstall = uninstall;
        this.openLocation = openLocation;

        this.update = _settings.update;
        this.onEnable = _settings.onEnable;
        this.onDisable = _settings.onDisable;
        this.onUninstall = _settings.onUninstall;



        /*
        * Last handle & return self (`this`) for chaning
        *
        */
        return this.update();
    }

})(jQuery);
