// ================= Menu function =================
function menuFix() {
			var sfEls = document.getElementById("nav").getElementsByTagName("li");
			for (var i=0; i<sfEls.length; i++) {
				sfEls[i].onmouseover=function() {
					this.className+=(this.className.length>0? " ": "") + "sfhover";
				}
				sfEls[i].onMouseDown=function() {
					this.className+=(this.className.length>0? " ": "") + "sfhover";
				}
				sfEls[i].onMouseUp=function() {
					this.className+=(this.className.length>0? " ": "") + "sfhover";
				}
				sfEls[i].onmouseout=function() {
					this.className=this.className.replace(new RegExp("( ?|^)sfhover\\b"), "");
				}
			}
		}
		window.onload=menuFix;
		
// ================= Prototype function =================
/**
 * trim blank characters at the start and the end of a string.
 */
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g, "");
}

/**
 * trim blank characters at the start of a string.
 */
String.prototype.ltrim = function() {
	return this.replace(/^\s+/, "");
}

/**
 * trim blank characters at the end of a string.
 */
String.prototype.rtrim = function() {
	return this.replace(/\s+$/, "");
}

/**
 * check whether a string starts with a specified sub string.
 */
String.prototype.startWith = function(needle) {
	return this.substr(0, needle.length) == needle;
}

/**
 * check whether a string ends with a specified sub string.
 */
String.prototype.endWith = function(needle) {
	return this.substr(this.length - needle.length, needle.length) == needle;
}

// ================= Util function =================
function isEmail(string) {
	reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	return reg.test(string);
}

/**
 * create error msg: not empty
 * 
 * @param string
 *            key - the element that should be not empty
 * @return string - not empty error msg
 */
function msgNotEmpty(key) {
	return key + " should not be empty.";
}

/**
 * create error msg: length between
	 *
	 * @param string key - the element
	 * @param string min - min length
	 * @param string max - max length
	 * @return string - error msg
 */
function msgLengthBetween(key, min, max) {
	//@todo uppercase the first letter
	return key + " should be between " + min + " and " + max + " characters in length";
}

/**
 * create error msg: msg too long
 * 
 * @param key
 * @param max
 * @return
 */
function msgTooLong(key, max) {
	return key + " is too long (should not exceed " + max + " chars)";
	// return "The length of " + key + "should not exceed " + max + " chars.";
}
/**
 * @return string - error msg
 */
function msgNotValidLink() {
	return "Not a valid web address";
}

/**
 * @return string - error msg
 */
function msgNotValidEmail() {
	return "Not a valid email address";
}

function msgAnonyInfo() {
	 return 'Please either sign in or provide us with a few extra details';
 }

function msgNotGreaterThan(obj1, obj2) {
	return obj1 + ' should not be greater than ' + obj2;
}

function msgInvalidUname() {
	return "The username can only include a-z, A-Z and 0-9 characters";
}

function msgInvalid(obj) {
	return obj + " is invalid";
}

function msgNotValid(obj, type) {
	if(type != null && type != "") {
		return obj + " is not a valid " + type;
	} else {
		return obj + " is not valid";
	}
}

function updateSimilar(url){
	var myAjax = new Ajax.Request(url, {method: 'get', parameters: {}});
}

// ================= Application function =================
var gVoteId = '';
var cVoteId = '';
var gNewsId = '';

/**
 * Vote action.
 *
 */
function vote(url, isVote, voteId) {
	if(isVote == null)
		isVote = true; // default value;
	
	if(voteId == null) {
		gVoteId = '';
	} else {
		gVoteId = voteId;
	}
	// set 'vote it' to 'voted'.
	document.getElementById("voteLink" + gVoteId).innerHTML = "voted";
	// send ajax request
	var myAjax = new Ajax.Request(url, {method: 'get', parameters: {}, onComplete: updateVote});
}

/**
 * Update vote info when the ajax gets the result from server.
 * 
 * @param result
 * @return null
 */
function updateVote(result) {
	if(result.responseText == '"error"') {
		alert('Your vote could not be processed. It is possible that this item has been removed.');
	} else {
		document.getElementById("voteStrong" + gVoteId).innerHTML = result.responseText;
		if(result.responseText != "1"){
		     document.getElementById("votes").innerHTML = "votes";
		}else{
		//if 1 show
			var speed = 3;
			var moveBy = Math.round(speed); 
			o = document.getElementById("voteNum" + gVoteId);
			var intId = setInterval(function() { 
				var curHeight = o.offsetHeight;
				var newHeight = curHeight + moveBy; 
				if(newHeight < 52){
					o.style.height = newHeight + 'px';
				}else{
					o.style.height = '52px';
					clearInterval(intId); 
				}
			},30);
		
		}
		document.getElementById("voteNumSpan" + gVoteId).innerHTML = result.responseText;
	}
}

/**
 * Comment score action.
 */
function commentVote(url, isVote, voteId) {
	if(voteId == null) {
		cVoteId = '';
	} else {
		cVoteId = voteId;
	}
	document.getElementById("commentvotebuttons1_" + cVoteId).innerHTML = "";
	document.getElementById("commentvotebuttons2_" + cVoteId).innerHTML = "";
	// send ajax request
	var myAjax = new Ajax.Request(url, {method: 'get', parameters: {}, onComplete: updateCommentVote});
}

/**
 * Update comment vote info when the ajax gets the result from server.
 *
 * @param result
 * @return null
 */
function updateCommentVote(result) {
	if(result.responseText == '"error"') {
		alert('Your vote could not be processed. It is possible that this item has been removed.');
	} else {
		document.getElementById("commentscore" + cVoteId).innerHTML = result.responseText;
	}
}


/* Send comment.
 *
 * @param id The ID of the item we comment on.
 * @return null
 */
var paperid='';
var postuser='';
function addComment(url,id,user){
	var comment = encodeURIComponent(document.getElementById("content").value);
	var username = encodeURIComponent(document.getElementById("username").value);
	var password = encodeURIComponent(document.getElementById("password").value);
	var captcha = encodeURIComponent(document.getElementById("captcha").value);
	if(id!=null){
		paperid=id;
	}
	if(user!=null){
	    postuser=user;
	}
    if(comment == ''){
        alert("Comment should not be empty");
        return;
    }
	var myAjax = new Ajax.Request(url, {method: 'post', parameters: {comment: comment,username:username,password:password,captcha:captcha}, onComplete: updateComments});;
}
function addblogComment(url,id,user){
	var comment = encodeURIComponent(document.getElementById("content").value);
	var username = encodeURIComponent(document.getElementById("username").value);
	var captcha = encodeURIComponent(document.getElementById("captcha").value);
	if(id!=null){
		paperid=id;
	}
	if(user!=null){
	    postuser=user;
	}
    if(comment == ''){
        alert("Comment should not be empty");
        return;
    }
	var myAjax = new Ajax.Request(url, {method: 'post', parameters: {comment: comment,username:username,captcha:captcha}, onComplete: updateComments});;
}
/**
 * Update comments after adding a new one.
 *
 * @param result
 * @return null
 */
function updateComments(result) {
    if(result.responseText == '"notloggedin"'){
        alert("Your session has expired. Please log back in again.");
        /* TODO: redirection to the login page? We have to know the url, though.
                 Use a ../ relative path maybe? */
    }else if(result.responseText == '"emptymessage"'){ // This should never happen
        alert("Your message must not be empty, or the message you import is not correct.");
    }else if(result.responseText == '"newLogin"'){
        window.location.href=window.location.href;
    }else{
        document.getElementById("comments").innerHTML += result.responseText;
        document.getElementById("content").value = '';
        document.getElementById("guestUser").className = "hidden"
        var r= result.responseText;
        if(paperid!=''){
    	var myAjax = new Ajax.Request("/econophysics/paper/sendnotifiedemail/id/"+paperid, {method: 'post', parameters: {result:r,postuser:postuser}});
        }
    }
}

/**
 * Refresh captcha.
 * 
 * @return null
 */
function refreshCaptcha() {
    /* TODO: using relative url similar to the url() Zend function */
	var myAjax = new Ajax.Request('/econophysics/user/captcha', {method: 'get', parameters: {}, onComplete: updateCaptcha});
}

/**
 * Update captcha when ajax get result from server.
 * 
 * @param result
 * @return
 */
function updateCaptcha(result) {
    /* TODO: using relative url similar to the url() Zend function */
	var newImg = '/econophysics/papers/code/' + result.responseText.substr(1, result.responseText.length - 2);
	document.getElementById("imgCaptcha").src = newImg;
}
 
 /**
  * Refresh captcha.
  * 
  * @return null
  */
 function refreshCaptcha2() {
    /* TODO: using relative url similar to the url() Zend function */
 	var myAjax = new Ajax.Request('/econophysics/user/captcha', {method: 'get', parameters: {}, onComplete: updateCaptcha2});
 }

 /**
  * Update captcha when ajax get result from server.
  * 
  * @param result
  * @return
  */
 function updateCaptcha2(result) {
    /* TODO: using relative url similar to the url() Zend function */
 	var newImg = '/econophysics/papers/code/' + result.responseText.substr(1, result.responseText.length - 2);
 	document.getElementById("imgCaptcha2").src = newImg;
 }

function focusComment() {
	$('guestUser').className='visible';
	//alert(document.getElementById("imgCaptcha").src);
	//alert(location.href);
	if( document.getElementById("imgCaptcha").src.indexOf('NULL') >=0 ) refreshCaptcha();
}
/**
 * Log out the system.
 * 
 * @return
 */
function logout() {
	var myAjax = new Ajax.Request('../auth/logout', {method: 'get', parameters: {}, onComplete: updateLogout});
}

/**
 * Update user login status.
 * 
 * @param result
 * @return null
 */
function updateLogout(result) {
	if(result.responseText == 1) {
		document.getElementById('TopUserInfo').innerHTML = '<a href="../user/register">Join us!</a> | <a href="../auth/login">Sign in</a>';
	}
}

/**
 * Check comment form.
 * 
 * @param f The form of comment.
 * @return ture: legal; false illegal
 */
function checkComment(f) {
	f.content.value = f.content.value.trim();
	if (f.content.value == "") {
		alert(msgNotEmpty("Comment"));
		f.content.focus();
		return false;
	}
	if (f.content.value.length > 500) {
		alert(msgTooLong("Comment", 500));
		f.content.focus();
		return false;
	}
	// check guest user form
	return checkCommemtGuestUserForm(f);
}

/**
 * Check the search form.
 * 
 * @param f the search form
 * @return ture: legal; false illegal
 */
function shcheckSearchForm(f) {
	if(f.w.value.trim() == "" || f.w.value.trim() == "search keywords...") {
		return false;
	}
}

/**
 * Check the claim form.
 * 
 * @param f the claim form
 * @return ture: legal; false illegal
 */
function checkClaimForm(f) {
	f.email.value = f.email.value.trim();
	if(f.email.value == '') {
		alert(msgNotEmpty('Email'));
		return false;
	} else if(!isEmail(f.email.value)) {
		alert(msgNotValidEmail());
		return false;
	}
	return true;
}

/**
 * Check legality of guest user form when posting items anonymously.
 * 
 * @param f the guest user form
 * @return ture: legal; false: illegal
 */
function checkGuestUserForm(f) {
	// first check chether these form elements exist.
	if(!f.username) return true;
	
	f.username.value = f.username.value.trim();
	f.name.value = f.name.value.trim();
	f.email.value = f.email.value.trim();
	
	uname = f.username.value;
	pass = f.password.value;
	name = f.name.value;
	email = f.email.value;
	
	if(uname == "" && pass != "") {
		alert(msgNotEmpty("Username"));
		return false;
	} else if(uname != "" && pass == "") {
		alert(msgNotEmpty("Password"));
		return false;
	} else if(uname == "" && pass == "") {
		if (name == "" && email == "") {
			alert(msgAnonyInfo());
			return false;
		} else if (name == "") {
			alert("Please enter your name/nickname.");
			return false;
		}
		if(email != "" && !isEmail(email)) {
			alert(msgNotValidEmail());
			return false;
		}
	}
	return true;
}

/**
 * Check legality of guest user form when commenting anonymously.
 * 
 * @param f the guest user form
 * @return ture: legal; false: illegal
 */
function checkCommemtGuestUserForm(f) {
	// if user logged in, directly return true.
	if(f.username == null) {
		return true;
	}
	
	f.username.value = f.username.value.trim();
	f.name.value = f.name.value.trim();
	f.email.value = f.email.value.trim();
	
	uname = f.username.value;
	pass = f.password.value;
	name = f.name.value;
	email = f.email.value;
	
	if(uname == "" && pass != "") {
		alert(msgNotEmpty("Username"));
		return false;
	} else if(uname != "" && pass == "") {
		alert(msgNotEmpty("Password"));
		return false;
	} else if(uname == "" && pass == "") {
		if (name == "" && email == "") {
			alert(msgAnonyInfo() );
			return false;
		} else if (name == "") {
			alert("Please enter your name/nickname.");
			return false;
		}
		if(email != "" && !isEmail(email)) {
			alert(msgNotValidEmail());
			return false;
		}
	}
	return true;
}

/**
 * Check whether a valid day which is not earlier then current date.
 * 
 * @param year
 * @param month
 * @param day
 * @return Ture: valid; Flase: invalied.
 */
function isValidDate(year, month, day) {
	//try {
		d = new Date(year, month - 1, day, 23, 59, 59);
		if(day != d.getDate() || month != d.getMonth() + 1 || year != d.getFullYear()) {
			return false;
		}
		if(d < new Date()) {
			return false;
		}
	//} catch(e) {
	//	return false;
	//}
	return true;
}

function showFullAbstract(i) {
	document.getElementById('abstract' + i).className='AbsVisible';
	document.getElementById('fullAbs' + i).className='hidden';
	document.getElementById('partAbs' + i).className='visible';
}

function hideAbstract(i) {
	document.getElementById('abstract' + i).className='AbsHidden';
	document.getElementById('fullAbs' + i).className='visible';
	document.getElementById('partAbs' + i).className='hidden';
}
function showFullComment(i) {
	document.getElementById('comment' + i).className='AbsVisible';
	document.getElementById('fullCom' + i).className='hidden';
	document.getElementById('partCom' + i).className='visible';
}

function hideComment(i) {
	document.getElementById('comment' + i).className='AbsHidden';
	document.getElementById('fullCom' + i).className='visible';
	document.getElementById('partCom' + i).className='hidden';
}
function PopByVote(){
    document.getElementById('vote').className='listsVisible';
    document.getElementById('download').className='listsHidden';
    document.getElementById('view').className='listsHidden';
    document.getElementById('byvote').className='optionlink optionlinkon';
    document.getElementById('bydownload').className='optionlink optionlinkoff';
    document.getElementById('byview').className='optionlink optionlinkoff';
}
function PopByDown(){
    document.getElementById('vote').className='listsHidden';
    document.getElementById('download').className='listsVisible';
    document.getElementById('view').className='listsHidden';
    document.getElementById('byvote').className='optionlink optionlinkoff';
    document.getElementById('bydownload').className='optionlink optionlinkon';
    document.getElementById('byview').className='optionlink optionlinkoff';
}
function PopByView(){
    document.getElementById('vote').className='listsHidden';
    document.getElementById('download').className='listsHidden';
    document.getElementById('view').className='listsVisible';
    document.getElementById('byvote').className='optionlink optionlinkoff';
    document.getElementById('bydownload').className='optionlink optionlinkoff';
    document.getElementById('byview').className='optionlink optionlinkon';
}
function notified(url){
	var check;
	if(document.getElementById('notified').checked){
		check=1;
	}else{
		check=0;
	}
	var myAjax = new Ajax.Request(url, {method: 'post', parameters: {check: check}});
}
function arxivupdate(url){
	var myAjax = new Ajax.Request(url, {method: 'post', parameters: {}});
}

/* resize image */
function resize_image(obj, MaxW, MaxH){
	var imageObject = obj;
	var state = imageObject.readyState;
	if(state!='complete'){
		//setTimeout("resizeImage("+imageObject+","+MaxW+","+MaxH+")",50);
		//return;
	}
	var oldImage = new Image();
	oldImage.src = imageObject.src;
	var dW = oldImage.width;
	var dH = oldImage.height;
	a = dW/MaxW; b = dH/MaxH;
	if( b>a ) a = b;
	dW = dW/a; dH = dH/a;
	
	if(dW > 0 && dH > 0){
		imageObject.width = dW;
		imageObject.height = dH;
	}
}
