
(function($) {
  $(window).load(function () {
    GE.mode = 0; // 0-扩展，1-插件
    GE.initExtData = false; //初始化数据
    GE.initPluginData = false; //
    GE.defaultExtid = undefined; 
    window.showCommonModalDlg = function(oParam){
      var caption = oParam.caption;
      var content = oParam.content;
      var cancel_text = oParam.cancel_text;
      var ok_text = oParam.ok_text;
      var id = oParam.id;
      var node = $("#tmpl_common_modal_dlg").tmpl({
        id : id,
        caption : caption,
        content : content,
        cancel_text : cancel_text,
        ok_text : ok_text});
      $.tmpl.complete();
      

      if(!oParam.hasOwnProperty("cancel_text")){
        $("#common_dlg_cancel", node).hide();
      }
      if(!oParam.hasOwnProperty("ok_text")){
        $("#common_dlg_ok", node).hide();
      }
      
      $("#common_dlg_ok", node).click(function(){
        if(typeof(oParam.fnOkCallback) === "function"){
          oParam.fnOkCallback.call();
        }
        node.remove();
      });
      
      $("#common_dlg_cancel", node).click(function(){
        if(typeof(oParam.fnCancelCallback) === "function"){
          oParam.fnCancelCallback.call();
        }
        node.remove();
      });
      
      $("body").append(node);
    };
    
    (function(){
     //get the id  param from url
     var reg = new RegExp("(^|&)"+ "id" +"=([^&]*)(&|$)"); 
     var r = window.location.search.substr(1).match(reg);  
     if (r!=null){
       GE.defaultExtid = unescape(r[2]);
     }
    })();
	
    window.loadShowDetailsFromPrefs = function(show_details) {
      $("#plugin_detail_cb").attr("checked", show_details);
      show_details ? $(".plugin-detail").show() : $(".plugin-detail").hide();
    };
    
    $("#plugin_detail_cb").click(function(){
      var checked = $(this).is(":checked");
      checked ? $(".plugin-detail").show() : $(".plugin-detail").hide();
      chrome.send('saveShowDetailsToPrefs', [String(checked)]);		
    });
    

    function isPluginEnabled(plugin) {
      return plugin.enabledMode == 'enabledByUser' ||
             plugin.enabledMode == 'enabledByPolicy';
    };
    
    function handleEnablePlugin(node, enable, isGroup) {
      // Tell the C++ PluginsDOMHandler to enable/disable the plugin.
      chrome.send('enablePlugin', [String(node.path), String(enable),
              String(isGroup)]);
    }

    window.returnPluginsData = function(pluginsData) {
      $(".plugin-item").remove();
      GE.initPluginData = true;
      if (pluginsData.plugins.length > 0) {
        // Enforce order specified in the data or (if equal) then sort by
            // extension name (case-insensitive).
        pluginsData.plugins.sort(function(a, b) {
          if (a.order == b.order) {
            a = a.name.toLowerCase();
            b = b.name.toLowerCase();
            return a < b ? -1 : (a > b ? 1 : 0);
          } else {
            return a.order < b.order ? -1 : 1;
          }
        });
      }
      
      //开发者模式开关      
      pluginsData.plugins.forEach(function(plugin, index, array1){
        var node = $("#tmpl_plugin_item").tmpl({
          plugin_id : plugin.id,
          plugin_name : plugin.name,
          plugin_ver : plugin.version,
          plugin_detail : plugin.description,
          plugin_full_path : plugin.plugin_files[0].path,
          plugin_mime : plugin.plugin_files[0].mimeTypes[0].mimeType,
          plugin_type : plugin.plugin_files[0].type});
        $.tmpl.complete();
        $(".plugin-content-list").append(node);
        
        if(isPluginEnabled(plugin)){
          $(".exp-font", node).removeClass("fontColor");
          $(".plugin-enable", node).removeClass("blueBg");
          $(".plugin-enable", node).text("停用");
          $(".ico_48", node).css("background-image","url(images/plugins_ico_active.png)");
        }else{
          $(".exp-font", node).addClass("fontColor");
          $(".plugin-enable", node).addClass("blueBg");
          $(".plugin-enable", node).text("启用");
          $(".ico_48", node).css("background-image","url(images/plugins_ico_inactive.png)");
        }
        
        function handleSetPluginAlwaysAllowed(identifier, checked) {
          chrome.send('setPluginAlwaysAllowed', [identifier, checked]);
        }
        
        $(".plugin-enable", node).click(function(){
          //var ext_id =$(this).parent().parent().parent().attr("id");
          var canEnable = $(this).hasClass("blueBg");
          var ico_node = $(".ico_48", $(this).parent().parent());
          if(canEnable){
            $(this).removeClass("blueBg");
            $(this).text("停用");
            $(ico_node).css("background-image","url(images/plugins_ico_inactive.png)");
          }else{
            $(this).addClass("blueBg");
            $(this).text("启用");
            $(ico_node).css("background-image","url(images/plugins_ico_active.png)");
          }
          var path = $(this).attr("plugin_path");
          
          chrome.send('enablePlugin', [String(path), String(canEnable),String(false)]);
        });
        
        $(".ask-when-use", node).change(function(){
          var checked;
          if($(this).val() == "始终允许"){
            checked = true;
          }else{
            checked = false;
          }
          handleSetPluginAlwaysAllowed($(this).attr("iid"), checked);
        });
       
      });
      
      if($(".plugin-content-list").children().length == 0){
        $(".no-results").show();
      }else{
        $(".no-results").hide();
      }
    };
    
    
    function showFileDialog(selectType, operation, callback) {
      handleFilePathSelected = function(filePath) {
        callback(filePath);
        handleFilePathSelected = function() {};
      }
      chrome.send('packExtensionSelectFilePath', [selectType, operation]);
    };
    
	  
	  /**
     * Handles the showing of the extension directory browser.
     * @param {Event} e Change event.
     * @private
    */
    function handleBrowseExtensionDir() {
      showFileDialog('folder', 'load', function(filePath) {
        $("#ext_root_dir").val(filePath);
      });
    };
    
     /**
     * Handles the showing of the extension private key file.
     * @param {Event} e Change event.
     * @private
     */
    function handleBrowsePrivateKey() {
      showFileDialog('file', 'pem', function(filePath) {
        $("#ext_private_perm").val(filePath)
      });
    };

    function SwitchShowTab(mode){
      if(mode === 0){
        if(!GE.initExtData){
         try{
          chrome.send('extensionSettingsRequestExtensionsData');	
         }catch(e){alert(e);}
        }
      
        $("#yfe_extension_module").show();
        $("#yfe_plugin_module").hide();
      }else if(mode === 1){
        if(!GE.initPluginData){
          try{
            chrome.send('requestPluginsData');
            chrome.send('getShowDetails');
          }catch(e){alert(e);}
          
        }
        $("#yfe_extension_module").hide();
        $("#yfe_plugin_module").show();
        chrome.send('getShowDetails');
      }
    };
	

    $(".load-dev-ext").click(function(){
      chrome.send('extensionSettingsLoadUnpackedExtension');
    });

	   var overflowStyle;
    $(".pack-dev-ext").click(function(){
      $("#pack_ext_dlg").show();
	  overflowStyle = $("body").css("overflow");
	  $("body").css("overflow", "hidden");
    });
    
    $("#pack_ext_dlg_cancel").click(function(){
      $("#pack_ext_dlg").hide();
	  $("body").css("overflow", overflowStyle);
    });
    
    
    //开始打包扩展程序
    $("#pack_ext_execute").click(function(){
      var extensionPath = $("#ext_root_dir").val();
      var privateKeyPath = $("#ext_private_perm").val();
      chrome.send('pack', [extensionPath, privateKeyPath, 0]);
      $("#pack_ext_dlg").hide();
    });
    
    //选择私有秘钥文件
    $("#select_private_perm_dir").click(function(){
      handleBrowsePrivateKey();
    });
    
    //扩展程序根目录
    $("#select_ext_root_dir").click(function(){
      handleBrowseExtensionDir();
    });
	

    $(".update-ext").click(function(){
       chrome.send('extensionSettingsAutoupdate');
    });
    
      $(".nav-item-ext").click(function(){
        $(".nav-item").removeClass("select");
      $(this).addClass("select");
      SwitchShowTab(0);
    });

    $(".nav-item-plugin").click(function(){
      $(".nav-item").removeClass("select");
      $(this).addClass("select");
        SwitchShowTab(1);
    });
      
    $(".nav-item-more").click(function(){
      window.open("http://ext.yunfan.com/");
    });
	
    $("#dev_mode_switch").click(function(){
      var checked = $("#dev_mode_chbox").is(":checked");
      if(checked === true){
        $(".ext-dev-mode").show();
      }else{
        $(".ext-dev-mode").hide();
      }
      chrome.send('extensionSettingsToggleDeveloperMode');		
    });
	  
    /**
    * 渲染扩展右部区域
    * @param   {void}
    * @return  {void}
    **/	  
		
		addSingletonGetter(ExtensionSettings);
		ExtensionSettings.getInstance().initialize($);
		addSingletonGetter(PackExtensionOverlay);
		PackExtensionOverlay.getInstance().initialize($);
    this.dragWrapper_ = new DragWrapper(document.documentElement, dragWrapperHandler);
		
    (function(){
  	  SwitchShowTab(GE.mode);
    })();
  });
})(jQuery);

