// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function load() {
	/* 
	 * expect to be defined in some special pages which need manually load sth after body loaded
	 * e.g. google maps, picasa album, youtube movie 
	 */
	if(typeof kload != "undefined")
		kload();
	
	/* 
	 * the following task need to process on every page
	 */
	initLinks();
	loadGTracker();
	if(typeof geoip_country_code == "function" && geoip_country_code() == 'CN') {
		proxyImages(document.images);
		if(typeof photos != "undefined")
			proxyImages(photos);
	}
}

function unload() {
	if(typeof kunload != "undefined")
		kunload();

	/** Google Maps **/
	if(typeof GUnload != "undefined")
		GUnload();
}

/** proxy picasa images **/
function proxyImages(_images) {
	for(i in _images) {
		_img = _images[i];
		if(_img && _img.src) {
			index = _img.src.indexOf(".ggpht.com");
			if(index > 0)
				_img.src = "/proxy/" + _img.src.substring(index + 11);
		}
	}
}

/** setup links to proper target **/
function initLinks() {
	for (i in document.links) {
		link = document.links[i];
		if (typeof link != "undefined" && link.href && getDomain(link.href) != getDomain(window.location.href)) {
			link.onclick = openExternalLink;
			link.onkeypress = openExternalLink;
		}
	}
}

function openExternalLink() {
	window.open(this.href);
	return false;
}

/** Google Analytics **/
function loadGTracker() {
	try { 
		if(_ga_account.length > 0) {
			var pageTracker = _gat._getTracker(_ga_account);
			pageTracker._initData();
			pageTracker._trackPageview();
		}
	} catch(e) {}
}


/** helpers **/
//link status
var open_status = {};
function swap(element_id, link_id) {
	if(open_status[element_id] = !open_status[element_id]) {
		$(element_id).show();
		$(link_id).innerHTML = '«';
	} else {
		$(element_id).hide();
		$(link_id).innerHTML = '»';
	}
}

function safeHTML(src) {
	return src.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

function getDomain(link) {
	return link.slice(link.indexOf('://') + 3, link.indexOf('/', 8));
}
