App = function (opts){
	if(opts){
		this.initSettings(opts);
	}
};

App.settings = {
	
}

App.initSettings = function(opts){
	App.settings = App.extend(opts, App.settings);
}

App.file = function(path){	
	var site_dir = App.settings.site_host + '/';
	path = '/' + App.settings.FILE_DIR + site_dir + path;
	return path;
}

App.mscript = function(con, met){
	var path = '/'+ App.settings.lang_id + '/' + con + (met ? '/' + met : '');
	return path;
}

App.script = function(obj){
	obj = App.extend(obj, App.settings);
	var ret = obj.proto + '://' + obj.site_host + '/' + obj.lang_id + '/' + obj.con + (obj.met ? '/' + obj.met : '');
	if(obj.vars){
		for (var v in obj.vars){
			ret += '/' + v + '/' + obj.vars[v];
		}
	}
	return ret;
}

App.dic = function(dic, h, func){	
	(h) ? h = 1 : h = 0;
	$.post(App.mscript('sys', 'get_dic'), {'ajax_dic' : dic, 'h_dic' : h}, function(data){
		if(func){
			func(data.dic);
		} else {
			return data.dic;
		}
	}, 'json');
}
App.log = function(log){
	if((App.settings.is_home || App.settings.is_dev) && !App.checkIE) console.log(log);
}

// check if IE AND less then need_ver
App.checkIE = function(need_ver) {
	var rv = false;
	if (navigator.appName == 'Microsoft Internet Explorer')
	{
		var ua = navigator.userAgent;
		var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
		if (re.exec(ua) != null) {
			var ver = parseFloat( RegExp.$1 );
			rv = ver;
		}
	}
	return rv;
}

App.fb = {
	work: false,
	queue: [],
	appi: function(url, callback){
		//console.log(url);
		if (App.settings.proto=='https') url = url+(url.indexOf('?')>0 ? '&' : '?')+'return_ssl_resources=1';
		this.checkConnect(function(){
			FB.api(url, function(response){
				callback(response);
			});	
		});
	},
	ui: function(opts, callback) {
		//if (App.settings.proto=='https' && App.checkIE(8)) opts.display = 'popup';
		this.checkConnect(function(){
			opts.access_token = App.fb.token();
			FB.ui( opts, function(response){
				callback(response);
			});
		});	
	},
	checkConnect: function(func){
		if (this.work) {
			this.queue.push(func);
		} else {
			App.fb.work = true;
			FB.getLoginStatus(function(response) {
				if (response.status === 'connected') {
					func();
					App.fb.doQueue();
					App.fb.work = false;
				} else {
					App.fb.fbLogin(func);
				}
			}, true);
		}
	},
	token: function(){
		var token = FB.getAccessToken()
		return token;	
	},
	doQueue: function(){
		if(this.queue && this.queue.length > 0){
			var func = App.fb.queue.shift();
			func();
		}	
	},
	fbLogin: function(func){
		FB.login(function(response) {
			App.fb.work = false;
			if (response.authResponse) {							   
				func();
				App.fb.doQueue();
			} else {
				//FIXME send errors in log
				//console.log('Login failed');
			}
		}, {scope: App.settings.fb_perm});
	}
}

App.fb_token = function(){	
	var token = FB.getAccessToken()
	return token
}

App.extend = function (child, parent){
	for (key in child){
		if(child[key] != undefined){
			parent[key] = child[key];
		}
	}
	return parent;
}

function win(url, w, h, params)
{
	if (w==0 || typeof(w)=='undefined') w=screen.availWidth;
	if (h==0 || typeof(h)=='undefined') h=screen.availHeight;
	if (typeof(params)=='undefined') params = "titlebar=1,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1";
	if (params.length>0) params += ',';
	params += "top"+"="+h+",lef"+"t="+h+",hei"+"ght="+(h)+",wid"+"th="+(w);
	var wh = window.open(url, "win"+Math.round(Math.random()*10000), params);
        if (wh) {
		wh.moveTo((screen.availWidth-w)/2, (screen.availHeight-h)/2);
		wh.resizeTo(w, h);
		if (wh.focus) wh.focus();
	}
	return false;
}
function win0(url, w, h, params) {win(url, w, h, params);}

function winchat(url) {return win(url, 615, 400);}

function set_f() {if (document.forms['f'] && document.forms['f'].qvlogin) document.forms['f'].qvlogin.focus();}

function sel(fn, pref)
{
	if (!pref || pref=='') pref='chk';
	var f = document.forms[fn];
	for (var i=0; i<f.elements.length; i++) 
		if (f.elements[i].name.substring(0, pref.length)==pref) f.elements[i].checked = !f.elements[i].checked;
	return false;
}

function xenc(s) {
	var re = /\W/;
	if (s && s.match(re)) {
		sn = escape(s);
		sn = sn.replace(/\//g, '%2F');
		sn = sn.replace(/_/g, '%5F');
		sn = sn.replace(/\%/g, '_');
		if (sn!=s) s = 'XENC'+sn;
	} 
	return s;
}
function xdec(s) {
	if (s && s.indexOf('XENC')==0) {
		s = s.substring(4);
		s = s.replace(/_/g, '%');
		s = unescape(s);
	}
	return s;
}

function signup_login() {window.scroll(0,0);document.forms['lf'].login.focus();return false;}

function update_enter_cnt(obj, size_min, size_max, tname)
{
	if (!obj) return;
	if (!tname) return;
	var t = document.getElementById(tname);
	if (!t) return;
	if (size_min>0 && obj.value.length < size_min) t.innerHTML = '<font color="red">'+obj.value.length+'</font>';
	else if (size_max>0 && obj.value.length > size_max) t.innerHTML = '<font color="red">'+obj.value.length+'</font>';
	else t.innerHTML = '<font color="green">'+obj.value.length+'</font>';
}

function by_name(name) {var e = document.getElementsByName(name);if (e.length==0) return undefined;return e[0];}
function by_id(id) {return document.getElementById(id);}
function edisplay(e, on) {if (e) {e.style.display = on ? '' : 'none';return true;}return false;}
function display(id, on) {var e = by_id(id);return edisplay(e, on);}

function print_email(u, h, subj)
{
	var e=u+'@'+h;
	if (! subj) subj = 'SUPPORT REQUEST (MAIL)';
	document.write("<a href=\"mailto:"+e+"?subject="+subj+"\">"+e+"</a>");
}

// 2.0 addons

function time_zone()
{
	var tms = new Date(Date.UTC(2005, 6, 30, 0, 0, 0, 0));
	var so = -1 * tms.getTimezoneOffset();
	var tmw = new Date(Date.UTC(2005, 12, 30, 0, 0, 0, 0));
	var wo = -1 * tmw.getTimezoneOffset();
	var tmn = new Date(Date.UTC());
	var wn = -1 * tmw.getTimezoneOffset();
	var r = '';

	return new Array(wn, so, wo, r);
}

function host()
{
	var s = document.domain;
	if (s.substr(0, 4)=='www.') s = s.substr(4);
	return s;
}

function setcookie(name, value, expire_sec)
{
	var now=new Date();
	if (! expire_sec) expire_sec = 365*86400*1000;
	expire_date = new Date(now.getTime() + (expire_sec));
	var expires = ((expire_date==null) ? null : expire_date.toGMTString());
	var path = '/';
	var domain = host();
	if (domain.indexOf('.')<0) domain = null; else domain = '.'+domain;
	var secure = null;
	var s = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires : "" ) +
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
	document.cookie = s;
	return 1;
}
function set_cookie(name, value, expire_sec) {return setcookie(name, value, expire_sec);}

function getcookie(name)
{
	if (document.cookie.length>0) {
		start=document.cookie.indexOf(name + "=");
		if (start!=-1) { 
			start=start + name.length+1; 
			end=document.cookie.indexOf(";", start);
			if (end==-1) end=document.cookie.length;
			return unescape(document.cookie.substring(start, end));
		} 
	}
	return '';
}
function get_cookie(name) {return getcookie(name);}

function save_time_zone()
{
	tz = time_zone();
	setcookie('base_tz', tz.join('.'));
}

function save_load_time()
{
	if (getcookie('base_lt')!='') return; // save only first hit
	start_time = new Date();
	window.onload = function(){
		var tm = Math.floor((new Date()-start_time)/1)/1000;
		//alert('page loaded in '+tm);
		setcookie('base_lt', tm);
	};
}

function bookmark(url, title) {
	if (window.sidebar) // firefox
		window.sidebar.addPanel(title, url, "");
	else if(window.opera && window.print){ // opera
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	}
	else if(document.all)// ie
		window.external.AddFavorite(url, title);
	return false;
}

function homepage()
{
	var url = window.location;
	var ret;
	if (document.all)
	{
		document.body.style.behavior='url(#default#homepage)';
		document.body.setHomePage(url);
		ret = true;
	} else if (window.sidebar) {
		if(window.netscape) {
			try
			{  
				netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");  
			} catch(e) {  
				alert("This action was blocked by your browser，Please type about:config in your address bar and change the value of signed.applets.codebase_principal_support to 'true'"); 
				ret = false;
			}
		}
		var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components. interfaces.nsIPrefBranch);
		prefs.setCharPref('browser.startup.homepage', url);
		ret = true;
	}
	return ret;
}

function do_toggle(name) {
	//clear_toggle(name);
	$('a#show_'+name).toggle();
	$('a#hide_'+name).toggle();
	$('div[id^="div_'+name+'"]').each(function() {
		if ($(this).is(':hidden')) {
			var n = $(this).attr('id').substring(4);
			var v = $('div#div_'+n).first();
			var d = $('div#def_'+n).first();
			if (v.length && d.length) {
				v.html(d.html());
			}
		}
	});
	if (eval('typeof cb_'+name) == 'function') eval('cb_'+name+'('+$('a#show_'+name).is(':hidden')+');');
	
	$('div[id^="div_'+name+'"]').slideToggle('slow', function() {
		if ($(this).is(':visible')) $('a[id^="url_'+name+'"]').each(function(){
			var n = $(this).attr('id').substring(4);
			var v = $('div#div_'+n).first();
			var u = $('a#url_'+n).first();
			if (v.length && u.length && v.is(':visible')) {
				if (1) $.ajax({
					url: u.attr('href'),
					success: function(data) {
						v.html(data);
					},
					error: function(data, text) {
						alert('error: '+data+':'+text)
					}
					});
			}
		});
	});
	//set_toggle(name);
	return false;
}

function check_flash() {
	var ch = get_cookie('flash_checked');
	if (! ch) {
		var div = document.getElementById('need_flash');
		if (div) {
			set_cookie('flash_checked', '1', 86400);
			p = confirm('You need to install or upgrade Adobe Flash Player\nin order to use Live Video Chat.\n\nClick OK to download.');
			if (p) {
				win('http://get.adobe.com/flashplayer/');
			}
		}
	}
}

function clear_toggle(name) {
	$('#show_'+name).click(function(){return false;});
	$('#hide_'+name).click(function(){return false;});
}

function set_toggle(name) {
	$('#show_'+name).click(function(){return do_toggle(name);});
	$('#hide_'+name).click(function(){return do_toggle(name);});
}

function face_update() {
	document.forms['f'].submit();
}
function cb_search_ext(is_open) {
	var ch = (is_open ? '1' : '0');
	$('input[name="is_ext"]').val(ch);
	$('a#[id^="next_"]').each(function(){
		var url = $(this).attr('href');
		var pat = 'is_ext'+'/';
		var p = url.indexOf(pat);
		if (p>=0) url = url.substr(0, p+pat.length)+ch;
		$(this).attr('href', url);
	});
}

if (typeof $ !== 'undefined') {
	$(function() {
		set_toggle('search_ext');
	});
}

