
//============================================================================
// ** Core functions
//============================================================================


//----------------------------------------------------------------------------
// ** Get element by id
//----------------------------------------------------------------------------
// @param <string> id : The id of the element
// @return <element> : an element with this id
//----------------------------------------------------------------------------
function $(id){
	return document.getElementById(id);
}

//----------------------------------------------------------------------------
// ** Create a new element
//----------------------------------------------------------------------------
// @param <string> tagName : the tag name of element to create
// @return <element> : an new element with this tag name
//----------------------------------------------------------------------------
function $new(tagName) {
	return document.createElement(tagName);
}

//----------------------------------------------------------------------------
// ** Do nothing. Often used to instead a existed function for removing it
//----------------------------------------------------------------------------
function $null() {
}

//----------------------------------------------------------------------------
// ** Create a random string with the certain length
//----------------------------------------------------------------------------
// @param <int> l : the length of random string
// @return <string> : random string with the certain length
//----------------------------------------------------------------------------
function $anychar(l)	{
	var x='0123456789qwertyuioplkjhgfdsazxcvbnm';
	var tmp='';
	for(var i=0; i < l; i++)	{
		tmp += x.charAt(Math.ceil(Math.random()*100000000)%x.length);
	}
	return tmp;
}

//----------------------------------------------------------------------------
// ** Clear the space characters in a String
//----------------------------------------------------------------------------
// @return <string> : result string without spaces
//----------------------------------------------------------------------------
String.prototype.trim = function(){
	return this.replace(/^\s+|\s+$/g,'');
}


//============================================================================
// ** Lite interfaces (by SiC)
//============================================================================
if(!Lite) {
	var Lite = {};
}



//============================================================================
// ** UTIL Lite interfaces
//============================================================================
Lite.UTIL = {
	// get document size
	docSize:function(){
		var xScroll, yScroll;
		if (window.innerHeight && window.scrollMaxY) {
			xScroll = document.body.scrollWidth;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (
			document.body.scrollHeight > document.body.offsetHeight
		){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}

		var winS = Lite.UTIL.winSize();
		var windowWidth = winS.w, windowHeight = winS.h;
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else {
			pageHeight = yScroll;
		}

		// for small pages with total width less then width of the viewport
		pageWidth = xScroll;

		return {w: pageWidth, h: pageHeight};
	},
	// get window size
	winSize:function(){
		var windowWidth, windowHeight;
		if (self.innerHeight) { // all except Explorer
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
		} else if (
			document.documentElement &&
			document.documentElement.clientHeight
		) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}
		return {w:windowWidth,h:windowHeight};
	},
	// get element position
	dimensions: function(obj) {
		if (!obj)
			return {'x': 0, 'y': 0};
		var left = 0;
		var top = 0;
		while(obj) {
			left += obj.offsetLeft;
			top += obj.offsetTop;
			obj = obj.offsetParent;
		}
		return {'x': left, 'y': top};
	},
	// copy string to clipboard
	copy: function(strCode) {
		if(window.clipboardData) {
			window.clipboardData.clearData();
			window.clipboardData.setData('Text', strCode);
		}
		else if(navigator.userAgent.indexOf('Opera') != -1) {
			window.location = strCode;
		}
		else if (window.netscape) {
			try {
				netscape.security.PrivilegeManager
					.enablePrivilege('UniversalXPConnect');
			}
			catch (e) {
				alert('something was not allowed. you should set ' +
					'"signed.applets.codebase_principal_support" to "true"' +
					' value through "about:config" for your firefox');
				return false;
			}
			var clip = Components.classes['@mozilla.org/widget/clipboard;1']
				.createInstance(Components.interfaces.nsIClipboard);
			if (!clip)
				return;
			var trans = Components.classes['@mozilla.org/widget/transferable;1']
				.createInstance(Components.interfaces.nsITransferable);
			if (!trans)
				return;
			trans.addDataFlavor('text/unicode');
			var str = new Object();
			var len = new Object();
			var str = Components.classes['@mozilla.org/supports-string;1']
				.createInstance(Components.interfaces.nsISupportsString);
			var copytext = strCode;
			str.data = copytext;
			trans.setTransferData('text/unicode',str,copytext.length*2);
			var clipid = Components.interfaces.nsIClipboard;
			if (!clip)
				return false;
			clip.setData(trans,null,clipid.kGlobalClipboard);
		}
	},
	// add as a bookmark to browser
	bookmark:function (url,title) {
		if (window.sidebar) {
			window.sidebar.addPanel(title, url,'');
		} else if( document.all ) {
			window.external.AddFavorite( url, title);
		} else if( window.opera && window.print ) {
			alert('no method support this action [addBookMark]');
			return true;
		}
	},
	// set url to browser homepage
	homepage:function(url){
		 if (document.all){
			document.body.style.behavior='url(#default#homepage)';
			document.body.setHomePage(url);
		}else if (window.sidebar){
			if(window.netscape){
				try{
					netscape.security.PrivilegeManager
						.enablePrivilege('UniversalXPConnect');
					var prefs = Components
						.classes['@mozilla.org/preferences-service;1']
						.getService(Components. interfaces.nsIPrefBranch);
					prefs.setCharPref('browser.startup.homepage',url);
				}catch (e){
					alert('该操作被浏览器拒绝，如果想启用该功能，请在地址栏内输入' +
						' about:config,然后将项' +
						' signed.applets.codebase_principal_support 值该为true');
				}
			}
		}
	}
};


//============================================================================
// ** Basic API for <passport.mx>
//============================================================================

//============================================================================
// ** Avatar API
//============================================================================
var avatarAssister = {
	// update avatar from avatar list
	updateAvatar: function (obj) {
		window['avatarSource'] = obj.firstChild.src;
		if (!avatarSource) return;
	
		var myAvatarSource = $('my-avatar').src;
		if (
			myAvatarSource.indexOf('avatar-demo') == -1 &&
			myAvatarSource.indexOf('avatars/') == -1 &&
			!window.confirm(changeAvatarConfirm)
		) return;
	
		var src = avatarSource.substr(avatarSource.lastIndexOf('/') - (-1));
		Lite.IO.ajaxPost(
			'avatar.html',
			'type=ajax&src='+encodeURIComponent(src),
			avatarAssister.changeMyAvatar
		);
	},
	// get response for avatar updating
	changeMyAvatar: function (req) {
		var text = req.responseText;
		$('avatar-warning').style['display'] = 'none';
		if (text == -1) // not login
			window.location.href = 'login.html?ReturnUrl=avatar.html';
		else { // succeed
			$('my-avatar').src = avatarSource;
            $('my-avatar-preview').src = avatarSource;	
		}
	}
};



//============================================================================
// ** User's Location API
//============================================================================
var locationAssister = {
	// set location info for the selects
	initLocation: function(strCountry, needDetail, numProvince, numCity) {
		if (!window['locationInfo']) {
			window['locationInfo'] = {
				country: $('country'),
				province: $('province'),
				city: $('city')
			};
		}
		formAssister.setSelectValue(window.locationInfo.country, strCountry);
		this.buildProvinceSelection(null, strCountry);
		window.locationInfo.country.onchange = this.buildProvinceSelection;
		window.locationInfo.province.onchange = this.buildCitySelection;
		if (needDetail) {
			formAssister.setSelectValue(window.locationInfo.province, numProvince);
			this.buildCitySelection(null, numProvince);
			formAssister.setSelectValue(window.locationInfo.city, numCity);
		}
	},
	// build province select by country info
	buildProvinceSelection: function(evt, strCountry) {
		strCountry = strCountry || window.locationInfo.country.value;
		if(strCountry == 'cn')
			window.locationInfo.province.style['display'] =
				window.locationInfo.city.style['display'] = '';
		else {
			window.locationInfo.province.style['display'] =
				window.locationInfo.city.style['display'] = 'none';
			window.locationInfo.province.selectedIndex = 0;	 
			window.locationInfo.city.selectedIndex = 0;
		}
	},
	// build city select by province info
	buildCitySelection: function(evt, numProvince) {
		numProvince = numProvince || window.locationInfo.province.value;
		window.locationInfo.country.selectedIndex = 1; // choose china
		window.locationInfo.city.options.length = 0;
		window.locationInfo.city.options.add(new Option('',0));
		for (var i = 0; i < subcat.length; i++)
			if(subcat[i][2] == numProvince)
				window.locationInfo.city.options
					.add(new Option(subcat[i][0],subcat[i][1]));
	}
}


//============================================================================
// ** Security Questions API
//============================================================================
var securityAssister = {
	// init for security questions
	initQuestions: function() {
		if (!window['questions']) {
			window['questions'] = [
				$('security-question-1'),
				$('security-question-2'),
				$('security-question-3')
			];
		}
		var length = questions.length;
		for (var i = 0; i < length; i++) {
			var objSelect = questions[i];
			objSelect.onchange = securityAssister.resetSelectOptions;
		}
		securityAssister.resetSelectOptions();
	},
	// reset options for each select when value of one of them changed
	resetSelectOptions: function() {
		if (!window['questions']) return;
		var selectedValues = {};
		var length = questions.length;
		for (var i = 0; i < length; i++) {
			var value = questions[i].value;
			if (value == 0) continue;
			selectedValues[questions[i].value] = i;
		}
		for (var i = 0; i < length; i++) {
			var objSelect = questions[i];
			var options = {};
			for (var j in questionOptions) {
				var tempOption = questionOptions[j];
				if (
					!isNaN(selectedValues[j]) && 
					selectedValues[j] != i
				) {
					continue;
				}
				options[j] = tempOption;
			}
			formAssister.initSelectOptions(objSelect, options, objSelect.value);
		}
	}
};

//============================================================================
// ** Account API
//============================================================================
var accountAssister = {
	// init for account preview
	initPreview: function() {
		if (!window['account']) {
			window['account'] = {};
			account['buttons'] = $('passport');
			account['preview'] = $('account-preview');
		}
		account.buttons.onmousemove = this.showPreview;
	},
	// show account preview when mouse move onto the buttons
	showPreview: function() {
		if (!window['account']) return;
		if (account.preview.style['display'] == 'block') return;
		var dimensions = Lite.UTIL.dimensions(account.buttons);
		account.preview.style['right'] =
			document.body.offsetWidth -
			dimensions.x - (account.buttons.offsetWidth) + 'px';
		account.preview.style['top'] =
			dimensions.y - (-account.buttons.offsetHeight - 1) + 'px';
		account.preview.style['display'] = 'block';
		document.body.onmousemove = accountAssister.hidePreview;
	},
	// hide account preview when mouse move out of the buttons
	hidePreview: function(evt) {
		if (!window['account']) return;
		evt = evt || window.event;
		var target = evt.target || evt.srcElement;
		while (target) {
			if (target == account.buttons) return;
			target = target.parentNode;
		}
		account.preview.style['display'] = 'none';
		document.body.onmousemove = $null;
	}
};



