

function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
}

var http = createRequestObject();

function undosetfavorite(id, option) {

    if (!http)
    {
      alert('We are sorry, your browser does not support this operation.');
      return;
    }

    var details = null;

    http.open('get', '/ajax.php?option=' + option + '&task=setfavorite&favorite=0&id=' + id + '&uniqueid=' + (new Date().getTime()));
   
    http.onreadystatechange = handleResponse;
    http.send(null);
  
    
}



function addcomment(form) {

    if (!http)
    {
      alert('We are sorry, your browser does not support this operation.');
      return;
    }

    // build the informatoin
    
    // check that text was entered in

    http.open('get', '/ajax.php?option=' + option + '&task=addcomment&id=' + id + '&uniqueid=' + (new Date().getTime()));
   
    http.onreadystatechange = handleResponse;
    http.send(null);
  
    
}

function setfavorite(id, option) {

    if (!http)
    {
      alert('We are sorry, your browser does not support this operation.');
      return;
    }
    var details = null;

    http.open('get', '/ajax.php?option=' + option + '&task=setfavorite&favorite=1&id=' + id + '&uniqueid=' + (new Date().getTime()));
    
    http.onreadystatechange = handleResponse;
    http.send(null);
  
    
}


function invitemate(id) 
{

    if (!http)
    {
      alert('We are sorry, your browser does not support this operation.');
      return;
    }
    var details = null;

    http.open('get', '/ajax.php?task=invitemate&id=' + id + '&uniqueid=' + (new Date().getTime()));
    
    http.onreadystatechange = handleResponse;
    http.send(null);
      
}


function acceptmate(id) {

    if (!http)
    {
      alert('We are sorry, your browser does not support this operation.');
      return;
    }
    var details = null;

    http.open('get', '/ajax.php?&task=acceptmate&id=' + id + '&uniqueid=' + (new Date().getTime()));
    
    http.onreadystatechange = handleResponse;
    http.send(null);
  
    
}

function ratecontent(id, option, rating, count, userid) {

    if (!http)
    {
      alert('We are sorry, your browser does not support this operation.');
      return;
    }
    if (userid == 0)
    {
     alert('Please sign in or signup to rate this content');
      return;
    }
    var details = null;

    http.open('get', '/ajax.php?option=' + option + '&task=ratecontent&count=' + count + '&rating=' + rating + '&id=' + id + '&uniqueid=' + (new Date().getTime()));
    
    http.onreadystatechange = handleResponse;
    http.send(null);
  
    
}

function postcomment(formname, commentElementId) 
{
   postForm(formname, true, function (req) { updatecomments(req, commentElementId); });
}

function urlEncodeDict(dict)
{ 
	var result = "";
	for (var i=0; i<dict.length; i++) {
		result += "&" + encodeURIComponent(dict[i].name) + "=" + encodeURIComponent(dict[i].value);
	}
	return result;
}

function execOnSuccess(stateChangeCallback)
{
	return function(xmlHttpReq)
		{
			if (xmlHttpReq.readyState == 4 &&
					xmlHttpReq.status == 200)
				stateChangeCallback(xmlHttpReq);
			//alert(xmlHttpReq + " " + xmlHttpReq.readyState + " " + xmlHttpReq.status);
		};
}

function getXmlHttpRequest()
{
	var httpRequest = null;
	try
	{
		httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch (e)
	{
		try
		{
			httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (e)
		{
			httpRequest = null;
		}
	}
	
	if (!httpRequest && typeof XMLHttpRequest != "undefined")
	{
		httpRequest = new XMLHttpRequest();
	}
	
	return httpRequest;
}


function handleResponse() {
    if(http.readyState == 4){
        var response = http.responseText;
        var update = new Array();
 
        if(response.indexOf('|' != -1)) {
        
            update = response.split('|');
             //alert('x' + 'abstract' + trim(update[0]) + 'y');
             //alert(response);

            if (update[1] == '0')
            {
         
            }
            else if (update[1] == '1')
            {
              var fav = document.getElementById('fav' + update[0]);
              var notfav = document.getElementById('unfav' + update[0]);

              if (update[2] == '1') // from non to fav
              {  
	      	 if (fav != null) fav.style.display= 'inline';
	         if (notfav != null) notfav.style.display= 'none';
              }
              else // from fav to non
              {   
                 if (fav != null) fav.style.display= 'none';
		 if (notfav != null) notfav.style.display= 'inline';
              }
              
            }
            else if (update[1] == '2') // rating set 0 - id: 1 - type: 2 new count: 3 - new rating
            {
         
              document.getElementById('ratingmessage_' + update[0]).innerHTML = 'You have rated';
              // update count message
              setratingcount(update[0], update[2]);
              showStars(update[3], update[0], false, 'd');

              // prevent user from voting again
              document.getElementById('enablestar' + update[0]).style.display = 'none';
              document.getElementById('disablestar' + update[0]).style.display = 'inline';
              
  
            }
            else if (update[1] == '3') // rating set 0 - id: 1 - type: 2 new count: 3 - new rating
	    {

	        var mate = document.getElementById('mate' + update[0]);
	        var matepending = document.getElementById('matepending' + update[0]);
	        var matependingtext = document.getElementById('matependingtext' + update[0]);
		var mateaccepted = document.getElementById('mateaccepted' + update[0]);
		var materejected = document.getElementById('matereject' + update[0]);

	
	        if (update[2] == '1') // from none to pending
	        {  
	      	   if (matepending != null) 
	      	   { 
	      	   matepending.style.display= 'inline';
	      	   matependingtext.style.display= 'inline';
	      	   }
		   if (mate != null) mate.style.display= 'none';
		   alert('Invitation has been sent!');
	        }
	        else if (update[2] == '2') // from pending to yes
	        {
	            alert('Invitation Accepted');
	        }
 
            }
        }
    }
}

function postUrl(url, data, async, stateChangeCallback)
{ 
	var xmlHttpReq = getXmlHttpRequest(); 

	if (!xmlHttpReq)
		return;

	xmlHttpReq.open("POST", url, async);
	xmlHttpReq.onreadystatechange = function()
		{
			stateChangeCallback(xmlHttpReq);
		};
	xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlHttpReq.send(data);
//	alert ('url: ' + url + '\ndata: ' + data);
}

function postForm(formName, async, successCallback)
{
	// postFormByName
	var form = document.forms[formName];
	return postFormByForm(form, async, successCallback);
}

function postFormByForm(form, async, successCallback) {
	var formVars = new Array();
	for (var i = 0; i < form.elements.length; i++)
	{
		var formElement = form.elements[i];
		
		// Special handling for checkboxes (we need an array of selected checkboxes..)!
		if(formElement.type=='checkbox' && !formElement.checked) {
			continue;
		} 
		var v=new Object;
		v.name=formElement.name;
		v.value=formElement.value;
		formVars.push(v);		
	} 
	// alert('post from by form');
	postUrl(form.action, urlEncodeDict(formVars), async, execOnSuccess(successCallback));
}

function updatecomments(xmlHttpRequest, dstDivId)
{
	var dstDiv = document.getElementById('message' + dstDivId);
	dstDiv.innerHTML = xmlHttpRequest.responseText;
	var dstDiv = document.getElementById('addcomment' + dstDivId);
	dstDiv.style.display = 'none';
	// hide comment form
}
