ie4 = document.all;
ie = (document.all)? true:false;
nn4 = document.layers;
n4 = nn4;
ie5 = (ie && navigator.appVersion.indexOf('MSIE 5')>0)? true:false;
ie6 = (ie && navigator.appVersion.indexOf('MSIE 6')>0)? true:false;
if(ie6)
	ie5 = true;

ver4 = ie4 || nn4;
currScoreElem = null;
var improc = ver4 || ie5;

function elem(objname)
{
	if(nn4 != null)
		return document.layers[objname];
	else
		return obj(objname);
}

function show(object, mouse) {
	if(!object || !mouse)
		return;
	var p = obj(object);
	var left = mouse.clientX - p.offsetWidth - 10;
	if(left < 0)
		left = mouse.clientX + 10;
	p.style.visibility = 'hidden';
	p.style.left = left + window.document.body.scrollLeft;
	p.style.top = mouse.clientY - 5 + window.document.body.scrollTop;
	p.style.visibility = 'visible';	
}
 
function hide(object) {
	if(!object)
		return;
	obj(object).style.visibility = 'hidden';
}


function checkComment(name, email, comm, commScoreAllowed, useForms){
	emptyBoxes = new String();
	if(!isText(name))
		emptyBoxes += "Name ";
	if(!isEmail(email))
		emptyBoxes += "E-mail ";
	if(!isText(comm))
		emptyBoxes += "Comment ";	
	
	if(emptyBoxes != ""){
		alert("Fill in the following fields: " + emptyBoxes);
		return;
	}
	var form1 = elem("form1");
	if(useForms == 'yes')
		form1.submit();
	else
		doUpdateComment(commScoreAllowed);
}


function doUpdateComment(commScoreAllowed){
	form1.submit1.disabled = true;
	floatMessage("please wait...", tooltip);
	window.setTimeout("updateComment("+commScoreAllowed+")", 10);	
}

function charCounter(){
	var limtext = elem("limtext");
	var form1 = elem("form1");
	var limbox = elem("limbox");
	var textarea1 = elem("textarea1");
	limtext.style.visibility = 'visible';
	limbox.style.visibility = 'visible';
	var txt = textarea1.value;
	l = txt.length;	
	limbox.innerHTML = l;
}

function updateComment(commScoreAllowed){
	try{
		errCode = submitCommentToServer(commScoreAllowed);
	}catch(e){
		msg = "Error occured. If you have this message often\n " +
				"please consider changing your scoring/commenting method \n " +
				" from the 'My PhotoBlink' page ";
		unfloatMessage(tooltip);
		alert(msg);
		return;	
	}
	
	unfloatMessage(tooltip);
	//limtext.style.visibility = 'hidden';
	limbox.style.visibility = 'hidden';
	if(errCode){
		alert("commenting failed");
		form1.submit1.disabled = false;
		return;
	}
	floatMessage("Thank you for participation", tooltip);
	window.setTimeout("unfloatMessage(tooltip)", 1000);
	addCommentDiv();
	form1.textarea1.value = "";
	if(commScoreAllowed == 1)
		updateVoteControls();
	
}

function updateVoteControls(){
	if(form1.anonCheck != null && form1.anonCheck.status){
		return;
	}
		
	for(var i = 1; i < 11; i++){
		temp = eval(elem("cell"+i));
		if(temp.className == 'greyscore'){
			temp.style.backgroundColor = '#02367C';
		}
	}
}

function addCommentDiv(){
	comdiv = document.createElement("div");
	//comdiv.id = "d3";
	//comdiv.style.position = "absolute";
	comdiv.innerHTML = form1.textarea1.value;
	comdiv.style.zIndex = 30;
	comdiv.style.background = 'white';
	comdiv.style.visibility = 'visible';
	var commentEnder = elem("commentEnder");
	commentPlacer.insertBefore(comdiv, commentEnder);
	form1.submit1.disabled = false;
	crop = form1.cropString.value;
	if(crop != ""){
		filename = form1.filename.value;
		w = form1.filewidth.value;
		h = form1.fileheight.value;
		comdiv = document.createElement("a");
		commentPlacer.insertBefore(comdiv, commentEnder);
		comdiv.innerHTML = 'suggested crop >>';
		cropRef = "cropdisplay.asp?photo=" + filename;
		cropRef += "&cropString=" + crop;
		cropRef += "&w=" + w + "&h=" + h;
		comdiv.href= cropRef;
	}
	comdiv = document.createElement("p");
	commentPlacer.insertBefore(comdiv, commentEnder);
}


function submitCommentToServer(commScoreAllowed){
	var form1 = elem("form1");
	var textarea1 = elem("textarea1");
	pageRef = "commentReqNoUI.asp";
	var comm = escape(textarea1.value);
	pageRef += "?comm="+comm;
	subscribeFlag = form1.subscrCheck.status ? "on" : "";

	var anonFlag = "";
	if(form1.anonCheck != null)
		anonFlag = form1.anonCheck.status ? "on" : "";	
	
	pageRef += "&subscr="+subscribeFlag;
	pageRef += "&crop="+form1.cropString.value;
	pageRef += "&imid="+form1.text3.value;
	pageRef += "&anon="+anonFlag;
	
	//source = new ActiveXObject("Microsoft.XMLDOM");
	source = xmldom();
	//source.async = false;		//Don't forget to set this
//alert(pageRef);
//return;	
	source.load(pageRef)
	
	var status, errstat, syserr, conerr, score, rank;

// 	data = source.selectSingleNode("data");	
// 	vals = data.childNodes;
// 	i = 0;
// 	status = vals(i++).text;
// 	errstat = vals(i++).text;
// 	syserr = vals(i++).text;
// 	conerr = vals(i++).text;
// 	errmess = vals(i++).text;
// 	commid = vals(i++).text;
	
	var data = source.getElementsByTagName("data");	
	vals = data[0].childNodes;
	i = 0;
	status = vals[i++].firstChild.nodeValue;	
	errstat = vals[i++].firstChild.nodeValue;
	syserr = vals[i++].firstChild.nodeValue;
	conerr = vals[i++].firstChild.nodeValue;
	errmess = vals[i++].firstChild.nodeValue;
	commid = vals[i++].firstChild.nodeValue;
	
	if(commScoreAllowed)
		elem("voteForm").commentID.value = commid;
	source = null;	
	errCode = status | errstat | syserr | conerr;
	return errCode;
}

function checkVote(myForm, vote){
	if(!isNum(vote))
		alert("Input a number");
	else
		myForm.submit();
}


function subscribe(email, status, hidden){
	var subscribeForm = elem("subscribeForm");
	if(!isEmail(email))
		alert("provide your e-mail");
	else{
		subscribeForm.subscribeFlag.value = status ? 1 : 0;
		subscribeForm.submit();
	}
}

function updateAnonVoteValue(){
	if(elem("anonvotecheck") != null){
		elem("voteForm").anonvote.value = anonvotecheck.status ? 0 : 1;	
	}
}


var voted = false;
function voteBtnClick(useForms) {
	if(voted){
		alert("You have already voted for this image ");
		return;
	}
	if(!currScoreElem)
	{
		alert("Select one of the boxes (10 is highest)");
		return;
	}
	var voteForm = elem("voteForm");
	if(voteForm.imageID.value == "")
	{
		alert("To vote, select image by pressing green button in the table")
		return;
	}
	score = calcScore();
	var voteForm = elem("voteForm");
	var grubbefraction = elem("grubbefraction");
	
	if(score < voteForm.minscore.value || score > voteForm.maxscore.value){
		if(!confirm("Your score will not be anonymous. Are you sure you want to proceed?"+voteForm.minscore.value+"-"+voteForm.maxscore.value))
			return;
	}
	updateAnonVoteValue();
	voteForm.votetext.value = currScoreElem.vote;
	voteForm.votefraction.value = grubbefraction.value;
	if(useForms == 'yes')
		voteForm.submit();
	else
		doUpdateScore();
}

function calcScore(){
	score = Number(currScoreElem.vote);
	var grubbefraction = elem("grubbefraction");
	fraction = grubbefraction.value;
	fraction = getDigitsOnly(fraction);
	grubbefraction.value = fraction;
	score += parseInt(fraction) / (fraction.length == 1 ? 10 : 100);
	return score;
}

function getDigitsOnly(str){
	s = new String(str);
	result = new String();
	for(var i = 0; i < s.length; i++){
		ch = s.charAt(i);
		if(isNum(ch))
			result += ch;
	}
	if(!isNum(result))
		result = "0";
	return result;
}

function doUpdateScore(){
	floatMessage("please wait...", tooltip);
	window.setTimeout("updateScore()", 100);	
}

function updateScore(){
	try{
		s = getScoreFromServer();
	}catch(e){
		msg = "Error occured. If you have this message often\n " +
				"please consider changing your scoring method \n " +
				" from the 'My PhotoBlink' page ";
		unfloatMessage(tooltip);
		alert(msg);
		return;
	}
	unfloatMessage(tooltip);
	if(s == ""){
		alert("voting failed");
		return;
	}
 	ranking.innerHTML = s;
 	voteimage.src = 'design/voteRedBtn.gif';
	voted = true;
//	document.recalc(true);	
	floatMessage("thank you, see score bar for results", tooltip);
	window.setTimeout("unfloatMessage(tooltip)", 1000);
}

function xmldom(){
	var source = null;
	try{
		source = new ActiveXObject("Microsoft.XMLDOM");
		source.async = false;
	}catch(e){
		source = document.implementation.createDocument("","doc",null);
		source.async = false;
	}
	return source;
}

function getScoreFromServer(){
// 	source = new ActiveXObject("Microsoft.XMLDOM");
// 	source.async = false;		//Don't forget to set this

	var source = xmldom();
	var voteForm = elem("voteForm");

	pageRef = "markReqNoUI.asp?votetext="+voteForm.votetext.value;
	pageRef += "&votefraction="+voteForm.votefraction.value;
	pageRef += "&imageID="+voteForm.imageID.value;
	pageRef += "&commentID=" + voteForm.commentID.value;
		
		
	pageRef += "&anonvote=" + voteForm.anonvote.value;
//alert(pageRef);
//return;	
	source.load(pageRef);
	
	var status, errstat, syserr, conerr, score, rank, blinks;

// 	data = source.selectSingleNode("data");	
// 	vals = data.childNodes;
// 	i = 0;
// 	status = vals(i++).text;
// 	errstat = vals(i++).text;
// 	syserr = vals(i++).text;
// 	conerr = vals(i++).text;
// 	score = vals(i++).text;
// 	rank = vals(i++).text;
// 	errmess = vals(i++).text;
// 	errsource = vals(i++).text;	

	var data = source.getElementsByTagName("data");	
	vals = data[0].childNodes;
	i = 0;
	status = vals[i++].firstChild.nodeValue;
	errstat = vals[i++].firstChild.nodeValue;
	syserr = vals[i++].firstChild.nodeValue;
	conerr = vals[i++].firstChild.nodeValue;
	score = vals[i++].firstChild.nodeValue;
	rank = vals[i++].firstChild.nodeValue;
	errmess = vals[i++].firstChild.nodeValue;
	errsource = vals[i++].firstChild.nodeValue;	
	

//alert("score:" + score + " error:" + errmess);
	
	if(status | errstat | syserr | conerr){
		source = null;
		return "";
	}

	numVotes = ++voteForm.numVotes.value;
	blinks = Math.round((parseFloat(score) - 6) * parseFloat(numVotes))


	s = "<table class='insideblocklight' width='100%' style='padding:2;text-align:right;background-color:#888895;color:wheat'>"
 			+ "<tr><td>blinks: " + blinks + "</td>" 
 			+ "<td>score: " + score + "</td><td>voted: " + numVotes + "</td>" 
 			+ "<tr><td>rank: " + rank + "</td><td>comments: " + voteForm.commNum.value + "</td>" 
 			+ "<td>viewed: " + voteForm.timesViewed.value + "</td>"
			+ "</tr></table>"

// 	s = "score: " + score;
// 	s += " | voted: " + numVotes;
// 	s += " | rank: " + rank;
// 	s += " | comments: " + voteForm.commNum.value;
// 	s += " | viewed: " + voteForm.timesViewed.value;

	source = null;	
	return s;
}

 
////////////////////////////////////////////////

 
function sssBtnClick(useForms) {
	var voteForm = elem("voteForm");
	var grubbefraction = elem("grubbefraction");
	if(voteForm.imageID.value == "" || !currScoreElem){
		voteForm.votetext.value = document.all["sssvote"].value;
	}
	else{
		voteForm.votetext.value = currScoreElem.vote;
	}
	voteForm.votefraction.value = grubbefraction.value;
	updateAnonVoteValue();
	
	if(useForms == 'yes')
		voteForm.submit();
	else
		doUpdateScore();
}



function voteRedBtnClick(userAccess, votedScore, compStatus){
	if(compStatus < 2){
		alert("Author disallowed voting")
	}
	else if(userAccess < 4){
		alert("You can only vote for images after registration and submission of 10 photos");
	}
	else{
		alert("You have already voted '" + votedScore + "' for this image. \nIf you didn't vote, then " +
				"you are using a shared IP address with someone who has already voted." + 
				"\nA typical scenario would be your computer is behind a firewall. Another case is when " +
				"your provider assigns a limited set of IPs to a large group of users. \nThen you still have a chance to vote " +
				"later when your floating IP changes. It is not allowed to vote twice from the same IP on PhotoBlink."
			);
	}
}


function cell_onclick(obj, maxscore) {
	elem(obj).style.backgroundColor = 'yellow';
	elem(obj).style.color = 'red';
	var grubbefraction = elem("grubbefraction");
	
	if(currScoreElem && currScoreElem != elem(obj))
	{
		currScoreElem.style.color = '#999999';
		if(currScoreElem.className == "darkscore" || currScoreElem.className == "greyscore")
			currScoreElem.style.backgroundColor = '#02367C';
		else
			currScoreElem.style.backgroundColor = '#225599';
	}
    
    var re = new RegExp("[0-9]+", "gi");
    vote = re.exec(obj);
    vote = Number(vote);
	//vote = elem(obj).vote;
	var voteForm = elem("voteForm");						
	if(vote == maxscore && voteForm.commentID.value == 0 || vote == 10){
		grubbefraction.value = '0';
		grubbefraction.disabled = true;
	}
	else{
		grubbefraction.disabled = false;		
	}

	expl = ["experimenting","experimenting","experimenting","interest unclear","average","interesting","good","very good","excellent","inspirational"];
	currScoreElem = elem(obj);
	currScoreElem.vote = vote;
	elem("scoreHelper").innerHTML = expl[currScoreElem.vote-1];
}

function cell_onclick_greyvote(obj){
	var voteForm = elem("voteForm");
	if(voteForm.commentID.value == 0)
		alert("You can only use grey scores after leaving a comment.\n1. Grey scores are not anonymous\n2. Grey scores will be neutralized if your comment doesn't justify your vote");
	else
		cell_onclick(obj, 10);
}

//// image processing ///

var greyscale = false;

function toggleGreyScale(){
	greyscale = !greyscale;
	elem("imageview").style.filter = "Gray";
	elem("imageview").filters["Gray"].enabled = greyscale;
}



//////// magnifier code ///////////////////
var ie = document.attachEvent;
var fb = document.addEventListener;

div = new Array();
dragActive = false
xoffset=100;
yoffset=50;
diameter=180;
radius=120;
firstTime = true;
currentLense = 0
futureLense = 1
lenses = new Array();
lenses[0] = "lenson.gif"
lenses[1] = "lensoff.gif"

if(ie){
	document.onmousedown = mouseDown
	document.onmousemove = mouseMove 
	document.onmouseup = mouseUp
}else if(fb){
//    	document.addEventListener("mousedown", mouseDown, true);
//     document.addEventListener("mousemove", mouseMove, true);
//     document.addEventListener("mouseup", mouseUp, true);
}

var divsInitialized = false;

function obj(objname){
	return document.getElementById(objname);
}

function initLayers(n) {
	if(!ie) return;
	for (var i = 1; i <= n; i++) {
		div[i] = eval("div" + i);
		div[i].x = offset(div[i], "offsetLeft");
		div[i].y = offset(div[i], "offsetTop") / 2;
		//div[i].y = div[i].offsetTop;
		div[i].w = div[i].offsetWidth;
		div[i].h = div[i].offsetHeight;
	}
	divsInitialized = true;
}

function offset(o, offsetname){
	var p = o;
	var val = 0;
	while(p != null){
		val += eval("p." + offsetname);
		p = p.parentElement;
	}
	return val;
}
 
function mouseDown(e) {
	if(!divsInitialized || !improc)
		return true;
	dragActive = mouseOver(e);
	dragClickX = x - div[5].x;
	dragClickY = y - div[5].y;
	if (dragActive) {
		x = eventXcoord(e);
		y = eventYcoord(e);
		return false
	}
	else 
		return true
}

function mouseMove(e) {
	if (!dragActive) {
		return true
	}

	//<ssser>
	var p = div[1];
	var p = div[1];
	hshift = offset(p, "offsetLeft");
	vshift = offset(p, "offsetTop")/2;	
	//hshift = p.offsetLeft;
	//vshift = p.offsetTop;
	xoffset = hshift * 2;
	yoffset = vshift * 2;
	//</ssser>
	
	x = eventXcoord(e);
	y = eventYcoord(e);
	div[5].x = x - dragClickX;
	div[5].y = y - dragClickY;
	shiftTo(div[5],div[5].x,div[5].y)
	
	clipBy(div[2],	radius + div[5].y * 2 - yoffset, radius + diameter + div[5].x * 2 - xoffset,
					radius + diameter + div[5].y * 2 - yoffset, radius + div[5].x * 2 - xoffset);
	shiftTo(div[2],(xoffset-(radius+div[5].x)),(yoffset-(radius+div[5].y)));

	shiftTo(div[6],div[5].x,div[5].y);
	return false
}

function mouseUp(e) {
	x = eventXcoord(e);
	y = eventYcoord(e);
	dragActive = false
	return true
}

function mouseOver(e) {
	if(!improc)
		return false;
	var hit = false;
	x = eventXcoord(e);
	y = eventYcoord(e);
	if (x>=div[5].x && x<=div[5].x+div[5].w && y>=div[5].y && y<=div[5].y+div[5].h) {
			hit = true;
	}
	return hit;
}


function shiftTo(object,x,y) {
	object.x = x;
	object.y = y;
	object.style.left = object.x;
	object.style.top = object.y;
}

function clipBy(object,t,r,b,l) {
	object.style.clip = "rect(" + t + "px "+ r + "px " + b + "px " + l + "px)";
}

function mouseEvent(e){
	var mouse;
	try{
		mouse = event;
	}catch(e){
		mouse = MouseEvent;
	}
	return mouse;
}

function hideObject(object) {
	object.style.visibility = "hidden";
}

function eventXcoord(e) {
	return mouseEvent(e).x + document.body.scrollLeft;
}

function eventYcoord(e) {
	return mouseEvent(e).y+document.body.scrollTop;
}

function lensIcon_onmouseover() {
	lensIcon.src = "design/" + lenses[currentLense];	
}

function lensIcon_onmouseout() {
	lensIcon.src = "design/" + lenses[futureLense];
}


function toggleLens(){
	currentLense = currentLense == 0 ? 1 : 0;
	futureLense = futureLense == 0 ? 1 : 0;

	if(div5.style.visibility == "visible"){
		hideObject(div2);
		hideObject(div5);
		hideObject(div6);
		return;
	}
	div2.style.visibility = "visible";	
	div5.style.visibility = "visible";
	div6.style.visibility = "visible";

	if(!firstTime){
		return;
	}
	firstTime = false;
	
	//<ssser>
	var p = div[1];
	hshift = offset(p, "offsetLeft");
	vshift = offset(p, "offsetTop") / 2;		
	//hshift = p.offsetLeft;
	//vshift = p.offsetTop;
	width = p.offsetWidth;
	xoffset = hshift * 2;
	yoffset = vshift * 2;
	//</ssser>
	
	div[5].x = hshift + width/2 - radius;
	div[5].y = vshift;

	shiftTo(div[5],div[5].x,div[5].y)
	
	clipBy(div[2],	radius + div[5].y * 2 - yoffset, radius + diameter + div[5].x * 2 - xoffset,
					radius + diameter + div[5].y * 2 - yoffset, radius + div[5].x * 2 - xoffset);
	shiftTo(div[2],(xoffset-(radius+div[5].x)),(yoffset-(radius+div[5].y)));

	shiftTo(div[6],div[5].x,div[5].y);
	return false
}
////////////////////////////////////

function onRemoveComment(commid){
	if(!confirm("Are you sure you want to remove this comment?")){
		return;
	}
	var form = obj("removeCommForm");
	form.commid.value = commid;
	form.submit();
}


