(function($) {
$(window).load(function () {
  addSingletonGetter(SettingsCommandList);
  SettingsCommandList.getInstance().initialize($);
  addSingletonGetter(ClearBrowserDataOverlay);
  ClearBrowserDataOverlay.getInstance().initialize($);
  addSingletonGetter(SearchEngineManager);
  SearchEngineManager.getInstance().initialize($);

  window.BrowserOptions = function() {
  };

  BrowserOptions.updateDefaultBrowserState = function(status_string, is_default, can_be_default){
    if(is_default){
      $(".def-browser-tips").show();
      $(".no-def-browser-tips").hide();
    }else{
      $(".def-browser-tips").hide();
      $(".no-def-browser-tips").show();
    }
    if(!can_be_default || is_default){
      $(".set-default-browser").hide();
    }
  };

  BrowserOptions.updateSearchEngines = function(engines, defaultValue, defaultManaged){
    $("#default_search_engine").empty();
    $("#default_search_engine").attr("disabled", defaultManaged);
    if (defaultManaged && defaultValue == -1){
      return;
    }
    var engineCount = engines.length;
    var defaultIndex = -1;
    for (var i = 0; i < engineCount; i++) {
      var engine = engines[i];
      var node = $("#search_engine_item").tmpl({
        name : engine.name,
        value : engine.index
      });
      $.tmpl.complete();
      if(engine.index == defaultValue){
        $(node).attr("selected", true);
      }
      $("#default_search_engine").append(node);
    }
  };

  BrowserOptions.setFontSize = function(font_size_value){
    debugger;
  };
  var prefsMap = [
    "download.prompt_for_download",
    "head_menu.enable_boss_key",
    "browser.check_default_browser",
    "download.default_directory",
    "head_menu.boss_key",
    "ssl.rev_checking.enabled",
    "background_mode.enabled",
    "hardware_acceleration_mode.enabled",
    "profile.password_manager_enabled",
    "autofill.enabled",
    "bookmark_bar.show_on_all_tabs",
    "browser.show_home_button",
    "profile.enable_show_browser_close_prompt",
    "session.restore_on_startup",
    "homepage"
  ];

  var prefsFuncsMap = {
    "homepage" : function(value){
      $("#cur_mainpage").val(value.value);
     },
    "profile.password_manager_enabled" : function(value){
      $("#password_manager_enabled_cb").attr("checked",value.value);
    },
    "autofill.enabled" : function(value){
      $("#form_auto_fill_cb").attr("checked",value.value);
    },
    "download.prompt_for_download" : function(value){
      $("#ask_save_before_dl").attr("checked",value.value);
    },

    "head_menu.enable_boss_key" : function(value){
      $("#switch_boss_key").attr("checked",value.value);
    },

    "browser.check_default_browser" : function(value){
      $("#check-def-browser-startup").attr("checked", value.value);
    },

    "download.default_directory" : function(value){
      $("#cur_dl_location").val(value.value);
    },

    "ssl.rev_checking.enabled" : function(value){
      $("#sslCheckRevocation").attr("checked",value.value);
    },

    "head_menu.boss_key" : function(value){
      SettingsCommandList.getInstance().updateCurBossKey(value.value);
    },
    "background_mode.enabled" : function(value){
      $("#backgroundModeCheckbox").attr("checked",value.value);
    },
    "hardware_acceleration_mode.enabled" : function(value){
      $("#gpu_mode_checkbox").attr("checked",value.value);
    },
    "bookmark_bar.show_on_all_tabs" : function(value){
      $("#show-bmb-always").attr("checked", value.value);
    },
    "browser.show_home_button" : function(value){
      $("#show_home_page_btn").attr("checked", value.value);
    },
    "profile.enable_show_browser_close_prompt" : function(value){
      $("#ask_on_close").attr("checked", value.value);
    },
    "session.restore_on_startup" : function(value){
      $("#" + value.value).attr("checked", true);
    }
  };

  function tranverseProperty(dict, peeding_key){
    for(var key in dict){
      var temp = peeding_key;

      if(temp != ""){
        temp +=".";
      }

      temp += key;
      if((typeof prefsFuncsMap[temp]) == "function"){
        prefsFuncsMap[temp](dict[key]);
      }
      if((typeof dict[key]) == "object"){
        tranverseProperty(dict[key], temp);
      }
    }
  };

  window.fetctPrefCallback = function(dict){
    tranverseProperty(dict, "");
  };

  window.prefChangeNotifyCallback = function(list){
    if((typeof list == "undefined") || (list.length == 0)){
      return;
    }
    prefsFuncsMap[list[0]](list[1]);
  };

  (function(){
    var tempArray = ["prefChangeNotifyCallback"];
    for(var prefName in prefsFuncsMap){
      tempArray.push(prefName);
    }
    chrome.send("observePrefs", tempArray);
    Preferences.getInstance().fetchPrefs(prefsMap,"fetctPrefCallback");
    chrome.send("checkDefaultBrowser");
  })();

  $("#clear_browser_data_btn").click(function(){
    ClearBrowserDataOverlay.getInstance().showModalDialog();
  });

  $("#reset_def_startup_page").click(function(){
    Preferences.getInstance().setBooleanPref("homepage_changed", false, true);
    Preferences.getInstance().setIntegerPref("session.restore_on_startup", -1, true);
    $(".rb-startup-def-page").attr("checked", false);
  });

  $("#certificatesManageButton").click(function(){
    chrome.send('showManageSSLCertificates');
  });

  $(".nav-item-left").click(function(){
    $(".nav-item-left").removeClass("select");
    $(this).addClass("select");
    if($(this).attr("id") == "basic_setting"){
      $("#basic_setting_page").show();
      $("#advanced_setting_page").hide();

    }else if($(this).attr("id") == "advance_setting"){
      $("#advanced_setting_page").show();
      $("#basic_setting_page").hide();
      setTimeout(function(){
        chrome.send("FetchSearchEngineTemplUrls");
      }, 200);
    }
  });

  $(".rb-mainpage-cfg").click(function(){
    var value = $(this).val();
    if(value == "hao123"){
    }else if(value == "yunfan"){
      alert("yunfan");
    }
  });

  $(".set-default-browser").click(function(){
    chrome.send('becomeDefaultBrowser');
  });

  $("#custom-change-mainpage").click(function(){
    var value = $(".custom-site").val();
    if(value =="输入网址"){
      return;
    }
  });

  $("#proxies_cfg").click(function(){
    chrome.send('showNetworkProxySettings');
  })

  $(".rb-startup-def-page").click(function(){
    var value = $(this).val();
    Preferences.getInstance().setIntegerPref("session.restore_on_startup", value, true);
  });

  $("#check-def-browser-startup").click(function(){
    var checked = $(this).is(":checked");
    Preferences.getInstance().setBooleanPref("browser.check_default_browser", checked, true);
  });

  $("#show-bmb-always").click(function(){
    Preferences.getInstance().setBooleanPref("bookmark_bar.show_on_all_tabs", $(this).is(":checked"), true);
  });

  $("#ask_save_before_dl").click(function(){
    var checked = $(this).is(":checked") ? true : false;
    Preferences.getInstance().setBooleanPref("download.prompt_for_download", checked, true);
  });

  $("#switch_boss_key").click(function(){
    var checked = $(this).is(":checked");
    Preferences.getInstance().setBooleanPref("head_menu.enable_boss_key", checked, true);
  });

  $("#show_home_page_btn").click(function(){
    var checked = $(this).is(":checked");
    Preferences.getInstance().setBooleanPref("browser.show_home_button", checked, true);
  });

  $("#defaultFontSize").change(function(event) {
    debugger;
    var SIZE_DIFFERENCE_FIXED_STANDARD = 3;
    var fontid = $(this).val();
    Preferences.getInstance().setIntegerPref('webkit.webprefs.default_fixed_font_size', fontid - SIZE_DIFFERENCE_FIXED_STANDARD, true);
    chrome.send('defaultFontSizeAction', [String(fontid)]);
  });

  $("#defaultZoomFactor").change(function(event) {
    var zoom_factor = $(this).val();
    chrome.send('defaultZoomFactorAction',[String(zoom_factor)]);
  });

  $("#ask_on_close").change(function(event){
    var checked = $(this).is(":checked");
    Preferences.getInstance().setBooleanPref("profile.enable_show_browser_close_prompt", checked, true);
  });

  $("#cfg_boss_key").click(function(){
    var node = $("#cfg_boss_key_dlg").tmpl({});
    $.tmpl.complete();
    $("#boss_key_cfg_cancel", node).click(function(){
      SettingsCommandList.getInstance().resetBosskeyCfgSession_();
      $(this).parent().parent().parent().remove();
      chrome.send('setShortcutHandlingSuspended', [false]);
    });

    $("#boss_key_cfg_ok", node).click(function(){
      $(this).parent().parent().parent().remove();
      chrome.send('setShortcutHandlingSuspended', [false]);
    });

    $("#boss_key_close_btn", node).click(function(){
      SettingsCommandList.getInstance().resetBosskeyCfgSession_();
      $(this).parent().parent().remove();
      chrome.send('setShortcutHandlingSuspended', [false]);
    });

    $("body").append(node);

    SettingsCommandList.getInstance().initNodeForCommand_($("#boss_key_input"));
  });

  $("#change_dl_pos").click(function(){
    chrome.send('selectDownloadLocation');
  });

  $("#custom_change_mainpage").click(function(){
    var new_url = $("#cur_mainpage").val();
    if(!CheckUrl(new_url)){
      alert("请输入合法的url");
      Preferences.getInstance().fetchPrefs(["homepage"],"fetctPrefCallback");
      return;
    }
    Preferences.getInstance().setStringPref("homepage", new_url, true);
    Preferences.getInstance().setBooleanPref("homepage_changed", true, true);
  });

  $("#default_search_engine").change(function(){
    var temp = $(this).val();
    chrome.send('managerSetDefaultSearchEngine', [temp]);
    Preferences.getInstance().setBooleanPref("default_search_provider.userChanged", true, true);
  });

  $("#manager_search_engine").click(function (){
    SearchEngineManager.getInstance().showSearchEngineMgrDlg_();
  })

  $("#backgroundModeCheckbox").click(function(){
    var checked = $(this).is(":checked");
    Preferences.getInstance().setBooleanPref("background_mode.enabled", checked, true);
  });

  $("#gpu_mode_checkbox").click(function(){
    var checked = $(this).is(":checked");
    Preferences.getInstance().setBooleanPref("hardware_acceleration_mode.enabled", checked, true);
  });

  $("#form_auto_fill_cb").click(function(){
    var checked = $(this).is(":checked");
    Preferences.getInstance().setBooleanPref("autofill.enabled", checked, true);
  });

  $("#password_manager_enabled_cb").click(function(){
    var checked = $(this).is(":checked");
    Preferences.getInstance().setBooleanPref("profile.password_manager_enabled", checked, true);
  });

  (function(){
    if(window.location.href.match("clearBrowserData") != null){
      $("#clear_browser_data_btn").trigger("click");
    };
  })();

})
})(jQuery);

