/* Adapted from VoteItUp */
/* A general script for updating the contents of the vote widget on the fly */
/*
USAGE:
vote (object to update with vote count, object to update with after vote text, post id, user id, base url)
*/

var xmlHttp;
var currentobj;
var voteobj;
var aftervotetext;
var gpostid;
var aftervoteundo;
var votetext;
var currentVote;
var votestartvalue = -1;
var doPublish = false;

//Useful for compatibility
function function_exists( function_name ) { 
    if (typeof function_name == 'string'){
        return (typeof window[function_name] == 'function');
    } else{
        return (function_name instanceof Function);
    }
}

//Javascript Function for JavaScript to communicate with Server-side scripts
function lg_AJAXrequest(scriptURL) {
	xmlHttp=zGetXmlHttpObject()
if (xmlHttp==null)
  {
  alert ("Your browser does not support AJAX!");
  return;
  } 
	xmlHttp.onreadystatechange=zvoteChanged;
	xmlHttp.open("GET",scriptURL,true);
	xmlHttp.send(null);
}

function zGetXmlHttpObject()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}

function zvoteChanged() 
{ 
	if (xmlHttp.readyState==4)
	{ 
		if (currentobj){
			var votecount = currentobj;
			var voteno = xmlHttp.responseText;
			// hier muss noch für die alten was gemacht werden
			if(typeof(JSON) == 'undefined'){
				eval('voteno=' + voteno + ';');
			}else{
				voteno = JSON.parse(voteno);
			}
			for(var t in voteno){
				try{
					document.getElementById(currentobj + '_' + t).innerHTML = voteno[t];
				}catch(ee){
				}
				
			}
			currentobj = false;
		}else{
			var result = '';
			var votedisp   = document.getElementById('voteid'     + gpostid);
			var votelnk    = document.getElementById('voter'      + gpostid);
			var votecount  = document.getElementById('votecount'  + gpostid);
			var votewidget = document.getElementById('votewidget' + gpostid);
			var oldvote = votecount.innerHTML;
			var oldvote = parseInt(oldvote,10);
			var autopublish = false;
			if (fbDoPublish.indexOf('publish_stream') > 0){
				autopublish = true;
			}
			var xmlResult = xmlHttp.responseText
			var voteno = xmlHttp.responseText;
			votestartvalue = (votestartvalue == 1)? 0 : 1;
			votecount.innerHTML = voteno + ' Votes';
			result = 'voted';
			if (aftervotetext == '') {
				votedisp.style.display = 'none';
				votewidget.className = 'post_votewidget_closed';
			}else{
				if (aftervoteundo == 1){
					if (votestartvalue == 1){
						votelnk.innerHTML = aftervotetext;
					} else {
						votelnk.innerHTML = votetext;
					}
				}else{
					votedisp.innerHTML == aftervotetext;
				}
			}
			//if(result == 'voted' && votefbmessage && oldvote < voteno && fbDoPublish.indexOf('publish_stream') < 0){
			//	publishStream(voteno);
			//}
		}
	}


}
function publishStream(voteno){
	try{
		FB.ui({
			method: 'stream.publish',
			message: unescape(votefbmessage),
			display:'popup',
			attachment: {
				name: unescape(votename),
				caption: unescape(votecaption),
				description: unescape(votedescription) + ' ' + voteno + ' Votes',
				href: unescape(votefburl),
				media: [{ 'type': 'image', 'src': unescape(voteimage), 'href': unescape(votefburl)}]
			},
			action_links: [
							{ text: 'Code', href: unescape(votefburl) }
						],
			user_message_prompt: unescape(votemessagepromt)
			},
			function(response) {
					if (response && response.post_id) {
						//alert('Post was published.');
					} else {
						//alert('Post was not published.');
					}
			}
		);
	} catch(ee){
		alert(ee.toString());
	}
}

function vote(postID, aftervote, userID, baseURL,undo, voted, fba) {
	gpostid = postID;
	aftervoteundo = undo;
	if (fbDoPublish){
		if(fbDoPublish.indexOf('publish_stream') < 0){
			return fbAccess(postID, aftervote, userID, baseURL,undo, voted);
		}
	}
	if (votestartvalue < 0){
		aftervotetext = aftervote;
		votestartvalue = voted;
		if (undo){
			votetext = document.getElementById('voter'+ gpostid).innerHTML;
			if (votestartvalue == 1){
				aftervotetext = votetext;
				votetext      = aftervote;
			}
		}
	}
	var scripturl = baseURL+"/voteinterface.php?type=vote&tid=total&uid="+userID+"&pid="+postID;
	if (fba){
		scripturl += "&fba=1";
	}
	scripturl += "&auth="+Math.random();
	lg_AJAXrequest(scripturl);
}

function sink(postID, aftervote, userID, baseURL,undo, voted, fba) {
	gpostid = postID;
	aftervoteundo = undo;
	if (votestartvalue < 0){
		aftervotetext = aftervote;
		votestartvalue = voted;
		if (undo){
			votetext = document.getElementById('voter'+ gpostid).innerHTML;
			if (votestartvalue == 1){
				aftervotetext = votetext;
				votetext      = aftervote;
			}
		}
	}
	var scripturl = baseURL+"/voteinterface.php?type=sink&tid=total&uid="+userID+"&pid="+postID;
	if (fba){
		scripturl += "&fba=1";
	}
	scripturl += "&auth="+Math.random();
	lg_AJAXrequest(scripturl);
}

function observeVotes(obj,postID,baseURL) {
	currentobj = obj;
	var scripturl = baseURL+"/voteinterface.php?tid=total&observe="+postID+"&auth="+Math.random();
	lg_AJAXrequest(scripturl);
}

function fbAccess(postID, aftervote, userID, baseURL,undo, voted) {
	gpostid = postID;
	aftervoteundo = undo;
	if (votestartvalue < 0){
		FB.login(function testme(response) {
			if (response.session) {
				if (response.perms) {
					// user is logged in and granted some permissions.
					// perms is a comma separated list of granted permissions
					vote(postID, aftervote, userID, baseURL,undo, voted, true);
				} else {
					// user is logged in, but did not grant any permissions
					vote(postID, aftervote, userID, baseURL,undo, voted, true);
				}
			} else {
				// user is not logged in
				alert('Um zu Voten musst du angemeldet sein');
			}
		}, {perms:'publish_stream'});
	}
	
	
	function defaultLogin(response){
		// ask for perms
		if (response.status == 'connected'){
		}else{
			alert('Um zu Voten musst du angemeldet sein');
		}
	}
}
	function getPerms(response) {
		document.getElementById('fb-help').innerHTML = '';
		if (response.session) {
			if (response.perms) {
				// user is logged in and granted some permissions.
				// perms is a comma separated list of granted permissions
				if (response.perms) {
					if (response.perms.indexOf('publish_stream') > 0){
						doPublish = true;
					}
				}
			} else {
				// user is logged in, but did not grant any permissions
			}
			//vote(postID, aftervote, userID, baseURL,undo, voted, true);
		} else {
			// user is not logged in
			alert('Um zu Voten musst du angemeldet sein');
		}			
	}


