function getUserPluginFolder(objApp)
{
        return  objApp.DataStore + 'Plugins';
}


$(document).ready(function() {

    // Make sure the scroll-bar will display at correct place
    $(window).resize(function() {

        height = $(window).height();

        $('#plugin-list').height(height - 62);
        $('#option-wrap').height(height - 70);

    });


    height = $(window).height();

    $('#plugin-list').height(height - 62);
    $('#option-wrap').height(height - 70);


    // WizExplorerApp
    objApp = window.external,

    // get current Plugin path
    pluginPath = objApp.GetHtmlDocumentPath(WizChromeBrowser),

    // check LCID to help us get the correct localization language
    lcid = objApp.LoadStringFromFile(pluginPath + 'plugin.ini', 'LCID_CHECK'),
    font = objApp.LoadStringFromFile(pluginPath + 'plugin.ini', 'FONT_SET'),

    // take WizSettings & WizCommonUI object
    objSet = objApp.CreateWizObject("WizKMCore.WizSettings"),
    objCUI = objApp.CreateWizObject('WizKMControls.WizCommonUI'),

    // take file system object

    // set plugin root folder object
    pluginRoot = {
        'knowledge': getUserPluginFolder(objApp),
        'base': objApp.AppPath + 'Plugins'
    },

    // DOM template
    itemTmpl = $('.plugin-item'),
    panelWrap = $('#panel-wrap'),
    optionWrap = $('#option-wrap')
    ;


    $('body, input#searchBar').css('font-family', font);
    $('#searchBar').val('');


    // Localisation language function
    window._s = function(stringName, paras) {
        return ((txt = objApp.LoadStringFromFile(pluginPath + 'plugin.ini', stringName)).indexOf('%') < 0 || !paras) ? txt : txt.replace('%', paras);
    }

    window._i = function(path, stringName) {
        return ((txt = objCUI.GetValueFromIni(path + 'plugin.ini', 'common', stringName + lcid)) == '') && lcid != '' ? objCUI.GetValueFromIni(path + 'plugin.ini', 'common', stringName) : txt;
    };

    objApp.LocalizeHtmlDocument2(pluginPath + 'plugin.ini', WizChromeBrowser, function (text) {
       
        $('.active-panel-wrap').trigger('click');
    });
    //

    window.currentWrap = '';
    window.panelReinit = true;

    //handle Panel-Wrap display      
    $('.active-panel-wrap').click(function () {

        if (currentWrap == 'active-panel-wrap')
            return;

        if (!window.panelReinit) {
            return unloadAllWrap(false) && panelWrap.show();
        }

        else
            unloadAllWrap(true);


        /*
        * Go display
        *
        */
        $('#loading').show();

        // create all plugin objects
        setTimeout(function () {

            var match = null, pluginKeyArr = [], pluginArr = [], groupDisplay = (_get('groupMode') == 1);

            for (type in pluginRoot) {
                if (pluginRoot[type] == null)
                    continue;
                //
                var pluginPath = pluginRoot[type];
                var objPluginFolders = objCUI.EnumFolders2(pluginPath);
                var folders = objPluginFolders.split("\n");

                for (var i = 0; i < folders.length; i++) {
                    var folder = folders[i];
                    //
                    var hidden = _i(folder + "\\", 'HiddenPlugin');
                    if ('1' == hidden)
                        continue;
                    //
                    var guid = _i(folder + "\\", 'AppGUID');
                    if (guid == "" || guid == null)
                        continue;
                    //
                    if (-1 == guid.toLowerCase().indexOf("f022cbe2-296a-4faf-820f-c4e744a2f593")
                        && -1 == guid.toLowerCase().indexOf("11e7ec35-a748-415f-bd1e-a39a95adb873")) {
                        //
                        pobj = { guid: guid, type: type, version: _i(folder + '\\', 'AppVersion'), folder: folder + '' };

                        // if group mode on, merge plugin when GUID in same
                        if (groupDisplay && (idx = $.inArray(guid, pluginKeyArr)) > 0)
                            pluginArr[idx].push(pobj);

                        else {
                            pluginKeyArr.push(guid);
                            pluginArr.push([pobj]);
                        }
                    }
                }
            }

            wizplugin = null;

            function vsort(a, b) { return (b = parseInt(b.version)) > (a = parseInt(a.version)) ? 1 : (b < a ? -1 : 0); }
            function esort(a, b) { return (a.plugin && a.plugin.isEnable) ? (b.plugin && b.plugin.isEnable ? 0 : -1) : (b.plugin && b.plugin.isEnable ? 1 : 0); }

            for (_k in pluginArr) {

                pGroup = pluginArr[_k];

                if (pGroup.length > 1)
                    pGroup = pluginArr[_k].sort(vsort);

                for (_sk in pGroup) {

                    wizplugin = $(pGroup[_sk].guid).wizPluginLoad({

                        objApp: objApp,
                        objCUI: objCUI,
                        objSet: objSet,

                        type: pGroup[_sk].type,
                        lcid: lcid,
                        tmpl: itemTmpl.clone(),

                        group: pGroup.length <= 1 ? false : pGroup.length,
                        append: _sk > 0,
                        folder: pGroup[_sk].folder

                    });

                    if (wizplugin) {
                        wizplugin.tmpl.data('plugin', wizplugin)
              .find('a').each(function () { $(this).data('plugin', wizplugin); })
              .filter('.enable').click(function (event) { event.stopPropagation(); $(this).data('plugin').enable(); }).end()
              .filter('.disable').click(function (event) { event.stopPropagation(); $(this).data('plugin').disable(); }).end()
              .filter('.uninstall').click(function (event) { event.stopPropagation(); $(this).data('plugin').uninstall(); }).end().end()
              .bind((_get('clickMode') == 0 ? 'dblclick' : 'click'), function () { $(this).data('plugin').openLocation(); })
              .appendTo($('#plugin-list ul'));

                        wizplugin.update();
                    }
                    else {
                        console.log('pGroup[%d].folder is %s', _sk, pGroup[_sk].folder);
                    }

                    pluginArr[_k][_sk]['plugin'] = wizplugin;
                }

                if (pluginArr[_k].length > 1) {
                    pluginArr[_k].reverse();
                    pluginArr[_k].sort(esort);
                    pluginArr[_k].reverse();
                }

                for (_sk in pluginArr[_k]) {
                    if (pluginArr[_k][_sk].plugin)
                        pluginArr[_k][_sk].plugin.checkState();
                }
            }

            $('.plugin-item').not('.group').show();

            setTimeout(function () { $('#loading').fadeOut('slow'); }, 400);


            //
            // handle Intime search-bar
            //
            var base = [], search = $('#searchBar'), searchToken = null, textbase = [];

            $('#go-search').click(function () {
                return true;
            });

            $('#go-clean').click(function () {
                search.val('').trigger('keyup').focus();
            });


            $('#search-event').click(function () { makeSearch($this); });

            $('.plugin-item').not('.group').each(function (index) {

                var p = $(this).data('plugin');

                textbase.push(index + '__###__' + p.AppName + ' ' + p.AppCaptions);

            });

            window._key = '';
            window.pluginSearch = function () {

                if (_key == search.val())
                    return;

                _key = search.val();

                _key != ''
          ? $('#go-clean').show().prev().hide()
          : $('#go-search').show().next().hide();

                if (searchToken)
                    clearTimeout(searchToken);

                searchToken = setTimeout('pluginFiltering()', 20);
            }

            window.pluginFiltering = function () {

                var _slice = search.val().split(' '), _s = null, _k = null, _set = {}, _tb = textbase;

                for (_s in _slice) {

                    if (!_tb)
                        break;

                    _k = new RegExp('^([0-9]*)__###__.*(' + _slice[_s] + ').*$', 'img');
                    _tb = _tb.join("\n").match(_k);
                }

                _tb = _tb ? _tb.join("\n").match(/^([0-9]*)/mg) : [];

                for (i = 0; i < pluginArr.length; i++) {
                    _set[i] = false;
                }

                for (i = 0; i < _tb.length; i++)
                    _set[_tb[i]] = true;

                for (i = 0; i < pluginArr.length; i++) {

                    if (_set[i]) {
                        var vtmpl = pluginArr[i][0].plugin.tmpl;
                        if (!vtmpl) {
                            alert(i);
                        }
                        pluginArr[i][0].plugin.tmpl.show();
                    }
                    else
                        pluginArr[i][0].plugin.tmpl.hide();
                }
            }

            search.keyup(pluginSearch);

            // Browser compatible for IE6(-)
            if ($.browser.msie && parseInt($.browser.version) < 7) {

                $('img, a, span').each(function () {

                    if ($(this).attr('src') && $(this).attr('src').indexOf('_ge.png') > 0)
                        $(this).attr('src', $(this).attr('src').replace('_ge.png', '_ie.png'));

                    else if ($(this).css('background-image') && $(this).css('background-image').indexOf('_ge.png') > 0)
                        $(this).css('background-image', $(this).css('background-image').replace('_ge.png', '_ie.png'));

                });

                $('span.disabled').css('background-image', 'url("images/wizplugin_pin_ie.png")');

                $('#navigator > ul > li.button, #plugin-list > ul > li')
          .hover(function () { $(this).toggleClass('hover'); })
          .each(function () { if ($(this).children('a').size() > 0) { $(this).click(function () { $(this).children('a')[0].click(); }); } });
            }

            panelWrap.show();

            window.panelReinit = false;

        }, 500);

    });


    //
    // handle Option-Wrap display
    //
    $('.active-option-wrap').click(function () {

        if (currentWrap == 'active-panel-wrap')
            return;

        unloadAllWrap();

        //panelWrap.after (optionWrap);

        for (k in option) {
            $('input.' + k + '[value="' + (option[k] = _get(k)) + '"]', optionWrap).attr('checked', true);
        }

        /*
        * Go display
        *
        */
        optionWrap.show();


        // I don't know why `option-wrap`'s layout will be broken after open the first plugin folder on panel-wrap
        // it (div-height) needs to fix each time when option-wrap show
        $('.option-list').each(function () {

            $(this).height(parseInt($('div', $(this)).height()) + 16);

        });

    });


    $('input.Submit', optionWrap).click(function () {

        for (k in option)
            _set(k, option[k]);

        window.panelReinit = true;

        alert(_s('optionSubmitComplete'));

    });


    $('.option-list input', optionWrap).click(function () {

        $(this).attr('checked')
      ? option[$(this).attr('name')] = $(this).val()
      : option[$(this).attr('name')] = 0;

    });


    var option = {
        openMode: 0,
        clickMode: 0,
        groupMode: 0
    }


    function unloadAllWrap(removeDOM) {

        if (removeDOM == true)
            $('.plugin-item').remove();

        panelWrap.hide();
        optionWrap.hide(); //.remove ();

        return true;
    };


    function _get(stringName) {
        return objCUI.GetValueFromIni(pluginPath + '\\plugin.ini', 'PluginConfig_0', stringName);
    }


    function _set(stringName, value) {
        objCUI.SetValueToIni(pluginPath + '\plugin.ini', 'PluginConfig_0', stringName, value);
    }
	$('#buttonGetMorePlugins').click(function(){
		objApp.ExecuteCommand('OpenURLInDefaultBrowser', "http://app.wiz.cn", null);
	});
});