(function(){

var freq_unloads = {};
var restore = {};
var is_gecko = ((window.Components + '') == '[object nsXPCComponents]');
var cehp_xpi = window['cehp_xpi'] ? window['cehp_xpi'] : 'http://download.firefox.com.cn/chinaedition/addons/cehomepage/cehomepage-latest.xpi';
var history_done = false;
//at_load(do_history);

var prompt_timer = null;
var _s_t = function() {
	log('focus');
	window.removeEventListener('focus', _s_t, false);		// invoke only once
	if (!window['cehomepage']) {
		/**
		 * make sure addon has been loaded when firefox first time start.
		 */
		prompt_timer = window.setTimeout(show_noaddon_tip, 6000);
	}
}

if(typeof tip_switch != 'undefined' && tip_switch && is_gecko) {
	window.addEventListener('focus', _s_t, false);
}

function show_noaddon_tip(show) {
	log('show: ' + show);
	if(false === show) {
		window.clearTimeout(prompt_timer);
		el('addon-prompt').style.display = 'none';
	} else {
		_t = PREF.get('hide_addon_prompt');
		if (!_t || new Date().getTime() - _t > 1209600)
			el('addon-prompt').style.display = 'block';
	}
}

var do_history_called = false;
function do_history(from_page) {
	if (history_done == true) {
		return;
	}
	history_done = true;
	if(typeof tip_switch != 'undefined' && tip_switch && !is_gecko && from_page) {
		_t = PREF.get('hide_ff_prompt');
		if (!_t || new Date().getTime() - _t > 1209600)
			el('ff-prompt').style.display = 'block';
	}
	
	log('Call from page: ' + !!from_page);
	if (from_page) {
		do_history_called = true;
	} else {
		/*
		 * called by addon, as a locationChanged event
		 * if this function has been called from page,
		 * we should continue and update the cehp state
		 * else, we should return since it will be called soon
		 */
		if (!do_history_called) {
			return;
		}
	}
	render_homepage();
	if (window['cehomepage']) {
		do_render();
	} else if (is_gecko && from_page) {
		/*
		 * There is the hack of cehomepage addon BUG
		 * The addon before 0.4 inject cehomepage object during window.load event,
		 * which made do_history invoked in inline script could not detect the injected object.
		 * Therefore, I try to detect it again after the window.load.
		 * Notice, non-firefox will not have this overhead.
		 *
		 * For cehp-0.4, cehp can still be null if it were in background tab
		 * The addon will call do_history once locationChanged
		 * Because calling from addon always waits for calling from page
		 * and we cannot assume the existence of addon before cehp injected
		 * Just do register if and only if called from page

		 * If there were both indeed do_render callback and do_history from addon
		 * Page state can still be OK
		 * Because the later always see right cehp state
		 */
		window.addEventListener('load', function() {
			if (window['cehomepage']) {
				do_render();
			} else {
				do_lack('history_noaddon');
				// FIXME hack for LM3
				if (document.cookie && document.cookie.match(/inlivemargin=ture/) != null) {
					el('history_noaddon').style['height'] = '144px';
				}
			}
		}, false);
	} else {
		do_lack('history_noff');
	}
	function do_render() {
		show_noaddon_tip(false);
		hideall();
		CSS.find('column_history', el('links-history'))[0].style['display'] = 'block';
		render_frequent();
		render_last();
	}
	function do_lack(id) {
		hideall();
		el(id).style['display'] = 'block';
	}
	function hideall() {
		CSS.find('column_history', el('links-history'))[0].style['display'] = 'none';
		el('history_noaddon').style['display'] = 'none';
		el('history_noff').style['display'] = 'none';
	}
/*	{
		return;
		var ceffdl = el('links-history').querySelector('a.ceff-download-link');
		ceffdl.setAttribute('href', get_chinaedition_download_link());
		ceffdl.addEventListener('click', function() {
			var iframe = document.createElement('iframe');
			iframe.src = ceffdl.href;
			iframe.style['display'] = 'none';
			document.documentElement.appendChild(iframe);
		}, true);
		var alter = el('links-history').querySelector(is_gecko ? 'div.history-no-cehp' : 'div.history-no-ff');
		var node = alter.parentNode.firstChild;
		while (node) {
			if (node.nodeType == 1) {
				node.style['display'] = node == alter ? 'block' : 'none';
			}
			node = node.nextSibling;
		}
	}*/
};
window['do_history'] = do_history;

function render_homepage() {
	var sethp = el('set_homepage');
	var show = false;
	var sethp_handler = null;
	if (is_gecko) {
		if (window.cehomepage) {
			var startup = window.cehomepage.startup;
//			if (!startup.page_changed() || startup.page() == 1) {
			if ((startup.homepage() == startup.cehomepage() || startup.homepage() == 'http://i.firefoxchina.cn/' || startup.homepage() == 'about:cehome') && startup.page() == 1) {
				if (!startup.homepage_changed() || startup.homepage() == startup.cehomepage() || startup.homepage() == 'http://i.firefoxchina.cn/' || startup.homepage() == 'about:cehome') {
					log('Welcome back, we miss you!');
				} else {
					log('Why not use me as your homepage?');
					show = true;
					sethp_handler = set_reset_homepage;
				}
			} else {
				log('Well, I won\'t disturb you unless necessary.');
				show = true;
				sethp_handler = set_reset_homepage;
			}
		} else {
			window.addEventListener('load', function() {
				if (window['cehomepage']) {
					var startup = window.cehomepage.startup;
		//			if (!startup.page_changed() || startup.page() == 1) {
					if ((startup.homepage() == startup.cehomepage() || startup.homepage() == 'http://i.firefoxchina.cn/' || startup.homepage() == 'about:cehome') && startup.page() == 1) {
						if (!startup.homepage_changed() || startup.homepage() == startup.cehomepage() || startup.homepage() == 'http://i.firefoxchina.cn/' || startup.homepage() == 'about:cehome') {
							show = false;
							log('Welcome back, we miss you!');
						} else {
							log('Why not use me as your homepage?');
							show = true;
							sethp_handler = set_reset_homepage;
						}
					} else {
						log('Well, I won\'t disturb you unless necessary.');
						show = true;
						sethp_handler = set_reset_homepage;
					}
				} else {
					log('Install CEHomePage addon for histories and session recovery!');
					show = true;
					sethp_handler = set_non_cehomepage;
				}
				sethp.style['visibility'] = show ? 'visible' : 'hidden';
				if (sethp_handler) {
					if (sethp.addEventListener)
						sethp.addEventListener('click', sethp_handler, true);
				}
			}, false);
		}
	} else {
		log('Use Firefox for best experiences!');
		show = true;
		sethp_handler = set_nonff_homepage;
	}

	sethp.style['visibility'] = show ? 'visible' : 'hidden';
	if (sethp_handler) {
		if (sethp.addEventListener)
			sethp.addEventListener('click', sethp_handler, true);
	}
}

function set_nonff_homepage(evt) {
	evt = __event__(evt);
	var sethp = evt.target;
	if (document.documentElement.style.behavior != undefined) {
		// this is IE
		sethp.style.behavior = 'url(#default#homepage)';
		sethp.setHomePage(window.location);
	} else if (window.external && external.max_version) {
		// this is Maxthon
		try {
			var ver = external.max_version;
			if (ver >= '2.5.2.2801') {
				if (external.max_setAsHomePage)
					external.max_setAsHomePage();
			}
		} catch (ex) {
			log(['maxthon set homepage', ex]);
		}
	}
	NOTIFY.confirm('您已经将本页设为主页。您是否需要安装火狐浏览器，帮您记录您最常访问的网站，还可享受更多便捷服务？', function (ret) {
		if (ret) {
			install_firefox();
		}
	});
}

function get_chinaedition_download_link() {
	var os = window.navigator.platform;
//	var osext = null;
	if (os.match(/win/i) != null) {
	//	osext = 'exe';
		log(['download for windows', os]);
		return 'http://download.firefox.com.cn/releases/webins3.0/official/zh-CN/Firefox-latest.exe';
	} else if (os.match(/mac/i) != null) {
	//	osext = 'dmg';
		log(['download for mac os x', os]);
		return 'http://download.firefox.com.cn/releases/firefox/zh-CN/Firefox-latest.dmg';
	} else {
	//	osext = 'tar.bz2';
		log(['download for linux', os]);
		return 'http://download.firefox.com.cn/releases/firefox/zh-CN/Firefox-latest.tar.bz2';
	}
//	return 'http://dl1.g-fox.cn/chinaedition/releases/zh-CN/FirefoxChinaEdition-latest.' + osext
}

function set_non_cehomepage(evt) {
	try {
		netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
		var prefs = Component.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch2);
		prefs.setCharPref('browser.startup.homepage', window.location);
		prefs.setIntPref('browser.startup.page', 1);
	} catch (ex) {
		log([ex, 'signed.applets.codebase_principal_support']);
	}
	NOTIFY.confirm('您希望将本页设为默认主页吗？选择确定，我们将为您安装火狐官方提供的主页附加组件。', function(ret) {
		if (ret) {
			install_addon(xpi_install_callback);
		}
	});
}

// FIXME Crash on IE 8, seems has a relationship with QQ download
function install_firefox() {
	var iframe = document.createElement('iframe');
	iframe.id = '__download_firefox__';
	iframe.src = get_chinaedition_download_link();
	var old = el(iframe.id);
	if (old && old.nodeType == 1)
		old.parentNode.removeChild(old);
	document.getElementsByTagName('body')[0].appendChild(iframe);
}
window['install_firefox'] = install_firefox;

function install_addon(cb) {
	try {
		InstallTrigger.install({
			'火狐定制主页' : {
				URL: cehp_xpi
			}
		}, cb);
	} catch(ex) {
		alert(ex);
		var ifr = document.createElement('iframe');
		ifr.id = '__download_addon__';
		ifr.src = cehp_xpi;
		ifr.style['display'] = 'none';
		var old = el(iframe.id);
		if (old && old.nodeType == 1)
			old.parentNode.removeChild(old);
		document.getElementsByTagName('body')[0].appendChild(ifr);
	}
}
window['install_addon'] = install_addon;

function xpi_install_callback(url, status) {
	log(['install callback', url, status]);
	if (url == xpi && status == 0) {
		el('set_homepage').style.visibility = 'hidden';
	}
}

function set_reset_homepage(evt) {
	window.cehomepage.startup.setHome(window.location.href);
	window.alert('您已经将' + document.location.host +'设为主页。');
	window.location.reload();
}

function render_frequent() {
	var cnt = CSS.find('panel-content', el('history_frequent'))[0];
	var cur = CSS.find('float-history', cnt)[0];
	cur.innerHTML = '';
	var freq = window.cehomepage.frequent.query(8);
	for (var i in freq) {
		var node = mk_link(freq[i]);
		cur.appendChild(node);
	}
}

function mk_link(node) {
	var li = document.createElement('li');
	li.innerHTML = ['<span>&nbsp;</span><a href="', node.uri , '" title="', node.title , '" rel="external" target="_blank">', (node.title || node.uri) , '</a>'].join('');
	li.firstChild.addEventListener('click', rm_link, false);
	return li;
}

function rm_link(evt) {
	evt = __event__(evt);
	var span = evt.target;
	var li = span.parentNode;
	var a = li.getElementsByTagName('a')[0];
	window.cehomepage.frequent.remove(a.href);
	render_frequent();
}

function render_last() {
	var blk = CSS.find('panel-content', el('history_last'))[0].getElementsByTagName('ul')[0];
	var last = window.cehomepage.last.query();
	for (var i in last) {
		if ((last[i].url == location.href) ||
			(last[i].url.match(/^about:/))) {
			continue;
		}
		blk.appendChild(mk_tab(last[i]));
	}
	if (blk.firstChild == null) {
		el('history_last_ra').style['display'] = 'none';
	}
}

window['history_restore_all'] = function() {
	for (var i in restore) {
		if (restore[i] != null) {
			window.cehomepage.last.restore(restore[i], false);
		}
	}
};

function mk_tab(tab) {
	var li = document.createElement('li');
	var span = document.createElement('span');
	var a = document.createElement('a');
	a.href = tab.url;
	a.title = tab.title || tab.url;
	a.appendChild(document.createTextNode(tab.title || tab.url));
	restore[a] = tab.data;
	a.addEventListener('mousedown', function(evt) {
		evt.preventDefault();
		evt.stopPropagation();
	}, true);
	a.addEventListener('click', function(evt) {
		window.cehomepage.last.restore(restore[a], true);
		evt.preventDefault();
		evt.stopPropagation();
	}, false);
	span.addEventListener('click', function(evt) {
		restore[a] = null;
		window.cehomepage.last.remove(tab);
		li.parentNode.removeChild(li);
		evt.preventDefault();
		evt.stopPropagation();
	}, true);
	li.appendChild(span);
	li.appendChild(a);
	return li;
}
}());
