
//vars globales que representan los parámetros de la última búsqueda seteada:
var lastSearchOrder = "date";//document.getElementById("order").select.value;
var lastSearchSpecialty = "any";//document.getElementById("specialty").select.value;
var lastSearchKeyword = "";//document.getElementById("filter").value;
var lastSearchInEnglish = true;//(document.getElementById("english").checked)? true : false;
var lastSearchInSpanish = true;//(document.getElementById("spanish").checked)? true : false;
//var lastSearchSameCountry = false;//(document.getElementById("myCountry").checked)? true : false;
var lastSearchGaranteedPayment = false;//(document.getElementById("garanteed_payment").checked)? true : false;
var lastSearchFrom = 0; //in last search, what was the first request requested (valga la redundancia :p)
var lastSearchTo = 5; //in last search, what was the last request requested (valga la redundancia :p)
var lastSearchNumberOfExtrasRequested = 5; //in last search, how many extra requests were returned
var lastSearchLocation = 'anywhere';
var lastSearchDistance = 0;
var lastSearchUnit = 'km.';

/*
update requests with new paramenters, that means reset table. new search!
*/
function update(username)
	{
	
	emptyTable("requestsmaintable");
	
	lastSearchFrom = 0;
	lastSearchTo = (document.getElementById("entriesPerClick"))[document.getElementById("entriesPerClick").selectedIndex].value;
	lastSearchNumberOfExtrasRequested = lastSearchTo;
	addEntries((document.getElementById("entriesPerClick"))[document.getElementById("entriesPerClick").selectedIndex].value,username);
	
	}

	/*
	Borra las últimas celdas, en cantidad determinada por 'number'
	*/
	function removeEntries(number)
	{
	for(i=0;i < number;i++)
		{
		deleteRow("requestsmaintable");
		}
	}

	/*
	Se llama cuando se clickea en el botón 'more'. Actualiza variables y agrega celdas a la tabla. Number: cantidad de celdas solicitadas
	*/
	function addExtraEntries(number,username)
	{
	if((lastSearchTo - lastSearchFrom) < lastSearchNumberOfExtrasRequested) //means no more requests available
			return;
	lastSearchFrom = lastSearchTo;
	lastSearchNumberOfExtrasRequested = number;
	addEntries(number,username);
	}
	
	
	/*
	agrega celdas vacías y hace el request para agregar dinamicamente la cantidad 'number' de requests a la tabla
	*/
	function addEntries (number, username)
	{

	//desactivar el 'more' provisoriamente hasta que llegue el request
	var table = document.getElementById("requestsmaintable");
	
	var row = table.rows[table.rows.length -2 ];
	
	
    (document.getElementById("arrowContainer")).innerHTML = "";   
	(document.getElementById("entriesPerClick")).style.visibility="hidden";
	(document.getElementById("showMe")).style.visibility="hidden";
	(document.getElementById("more")).style.visibility="hidden";
	
		for(i=0; i < number; i++) 
			{
				
				addRow("requestsmaintable");
				
			}
	
	//actualizar variables con nuevos parámetros
	lastSearchOrder = (document.getElementById("order"))[document.getElementById("order").selectedIndex].value;
	lastSearchSpecialty = (document.getElementById("specialty"))[document.getElementById("specialty").selectedIndex].value;
	lastSearchKeyword = document.getElementById("filter").value;
	lastSearchInEnglish = (document.getElementById("english").checked)? true : false;
	lastSearchInSpanish = (document.getElementById("spanish").checked)? true : false;
	if (document.getElementById("location") != null)
		{
		
		lastSearchLocation = (document.getElementById('location'))[document.getElementById('location').selectedIndex].value;
		lastSearchDistance = document.getElementById('distance').value;
		lastSearchUnit = (document.getElementById('unit'))[document.getElementById('unit').selectedIndex].value;
		}
	else
		lastSearchLocation = 'anywhere';
	lastSearchGaranteedPayment = (document.getElementById("garanteed_payment").checked)? true : false;
	
	
	
	
	requestNewEntries(number,username)		;
	
	}
	
	/*send request to update requests table, number is the quantity, username is the id of the current user*/
	function requestNewEntries (number,username)
	{
		
			var url = 'http://www.game-joint.com/extrarequestshandler.php';
	rand = parseInt(Math.random()*999999999999999);
	//añade número aleatorio para evitar problemas de caché
	var modurl= url + "?rand=" + rand;
	var selectOrder = document.getElementById("order");

	
	modurl= modurl + "&order="+('""','',(selectOrder[selectOrder.selectedIndex].value).replace('"',''));
	
	modurl= modurl + "&from_request=" + lastSearchFrom;
	modurl= modurl + "&number_of_requests=" + number;
	modurl = modurl + "&specialty=" + lastSearchSpecialty;
	modurl = modurl + "&keyword=" + lastSearchKeyword;
	var language;
	if (lastSearchInEnglish && lastSearchInSpanish)
		language = "both";
	else if (lastSearchInEnglish)
		language = "english";
	else
		language = "spanish";
	
	modurl = modurl + "&language=" + language;
	modurl = modurl + "&location=" + lastSearchLocation;

	if (lastSearchLocation == 'specificDistance' )
		{
		modurl = modurl + "&distance="+lastSearchDistance ; 
		modurl = modurl + "&unit="+lastSearchUnit ; 
		}

	//
	
	if (username != "")
		modurl = modurl + "&username=" + username;
	modurl = modurl + "&payment=" +  (lastSearchGaranteedPayment ? "yes":"no");
	//alert("URL:"+modurl);
	request.open("GET",modurl,true);
	//configurar función de respuesta:
	request.onreadystatechange = receiveRequestResponse;
	request.send(null);	
	}
	

    
    
	/*returns a text-cell with all the data passed as parameters included, set for requests table. fullDisplay: will show full announcement and no 'view full' if true*/
		function showNewRequestCell(id, date, days_since, technologies, mot_money, mot_profit, mot_creativity, mot_learn, mot_art, mot_other, announcement, lang, specialty, estimated_time, pay_per_hour, user_posting, country, city, title, fullDisplay,payType) {
		var cell ="";

		
		
		if (specialty == 'programmer')
			specialty = '<span style="color:DarkBlue ">programmer</span>';
		else if (specialty == 'artist')
			specialty = '<span style="color:purple">artist</span>';	
		else if (specialty == 'game_designer')
			specialty = '<span style="color:FireBrick ">game designer</span>';		
		else if (specialty == 'hybrid')
			specialty = '<span style="color:DimGray>hybrid</span>';			
		else if (specialty == 'other')
			specialty = '<span style="color:black">other</span>';		
   		else if (specialty == 'any')
			specialty = '<span style="color:DarkSlateGrey ">any</span>';		    
		cell= cell +  '<table class="requestbody" width=100%>';	
			cell= cell +  '<tr>';
			cell= cell +  '<td class="requestbody" width=33% style="height:30px;">';
            if (fullDisplay)
				cell= cell +  '<span style="font-size:14px;"><b>looking for: </b>'+specialty+'</span>';
            else
	            cell= cell +  '<span style="font-size:13px;"><b>looking for: </b>'+specialty+'</span>';
            if (fullDisplay)
				cell= cell +  '<div style="margin-top: 4px;font-size:14px; line-height:17px;"overflow:hidden; align=left><b>technologies:</b> '+ technologies+'</div>';
            else    
				cell= cell +  '<div style="margin-top: 4px;font-size:13px; line-height:17px;"overflow:hidden; align=left><b>technologies:</b> '+ technologies+'</div>';
			cell= cell +  '</td>';
			cell= cell +  '<td class="requestbody" align=top width=33%>';	
            if (!fullDisplay)		
				cell = cell + '<div style="text-align:center;"><H3><a style="color:#000000" href="http://www.game-joint.com/singlerequest.php?id='+id+'&user='+user_posting+'#!">'+title+'</a></H3></div>';
            else    
            	cell = cell + '<div style="text-align:center;"><H2>'+title+'</H2></div>';
			cell= cell +  '</td>';		
			cell= cell +  '<td class="requestbody" align=right width=33%>';
			//y aca? otra tabla mas? y daale
			cell= cell +  '<table class="motivations" width=250 height=43 style="">';
	    	cell= cell +  '<col width=37 height=37>';
 				cell= cell +  '<col width=37 height=37>';
		  	cell= cell +  '<col width=37 height=37>';
				cell= cell +  '<col width=37 height=37>';
				cell= cell +  '<col width=37 height=37>';
 				

				cell= cell +  '<tr class="motivations">';
				//money:
				cell= cell +  '<td class="motivations" align=center>';
				var size = 31*0.01*mot_money;
				cell= cell +  '<a href="#"  onClick="popup(\'http://www.game-joint.com/motivationsdetail.php\',\'motivations\');"><IMG style="border-width: 0px;" title="'+mot_money+'% about money" SRC="http://www.gamejoint.com.ar/mot-money.gif" width='+size+' height='+size+'></a>';
				cell= cell +  '</td>';
				//profit
				cell= cell +  '<td class="motivations" align=center>';
				size = 31*0.01*mot_profit;
				cell= cell +  '';
				cell= cell +  '<a href="#" onclick="popup(\'http://www.game-joint.com/motivationsdetail.php\',\'motivations\');"><img style="border-width: 0px;" title="'+mot_profit+'% about profit" src="http://www.gamejoint.com.ar/mot-profit.gif" width='+size+' height='+size+' /></a></td>';
				//creative participation:
				cell= cell +  '<td class="motivations" align=center>';
				size = 31*0.01*mot_creativity;
				cell= cell +  '<a href="#" onClick="popup(\'http://www.game-joint.com/motivationsdetail.php\',\'motivations\');"><IMG style="border-width: 0px;" title="'+mot_creativity+'% about creative participation" SRC="http://www.gamejoint.com.ar/mot-creativity.gif" width='+size+' height='+size+'></a>';
				cell= cell +  '</td>';
				//learning
				cell= cell +  '<td class="motivations" align=center>';
				size = 31*0.01*+mot_learn;
				cell= cell + '<a href="#" onClick="popup(\'http://www.game-joint.com/motivationsdetail.php\',\'motivations\');"><IMG style="border-width: 0px;" title="'+mot_learn+'% about learning" SRC="http://www.gamejoint.com.ar/mot-learn.gif" width='+size+' height='+size+'></a>';
				cell= cell +  '</td>';
				//love of the art!
				cell= cell +  '<td class="motivations" align=center>';
				size = 31*0.01*mot_art;
				cell= cell +  '<a href="#" onClick="popup(\'http://www.game-joint.com/motivationsdetail.php\',\'motivations\');"><IMG style="border-width: 0px;" title="'+mot_art+'% about love of the art" SRC="http://www.gamejoint.com.ar/mot-loveoftheart.gif" width='+size+' height='+size+'></a>';
				cell= cell +  '</td>';  
				//other

				cell= cell +  '<td class="motivations" align=center>';
				size =  31*0.01*mot_other;
				cell= cell +  '<a href="#" onClick="popup(\'http://www.game-joint.com/motivationsdetail.php\',\'motivations\');"><IMG style="border-width: 0px;" title="'+mot_other+'% about other motivations" SRC="http://www.gamejoint.com.ar/mot-other.gif" width='+size+' height='+size+'></a>';
				cell= cell +  '</td>';
				cell= cell +  '</tr>';
			cell= cell +  '</table>	';
			cell= cell +  '</td>';
			cell= cell +  '</tr>';
			cell= cell +  '<tr>';
			cell= cell +  '<td colspan="3">';
			cell= cell +  '<table widt=100% class="requestbody" >';
			if (fullDisplay)
				cell= cell +  '<td colspan=3 style="padding-bottom:7px;"><div style="font-size: 15px;">';
			else					
				cell= cell +  '<td colspan=3 style="height:15px"><div style="text-align:justify;font-size: 13px;position:relative;float:left;max-height: 16px;overflow:hidden;max-width:96%; text-overflow:ellipsis;word-wrap:break-word;">';
			cell= cell +  announcement;
			if (fullDisplay)
				cell= cell +  '</div></td>';
			else					
				cell= cell +  '</div><div style=" position:relative;float:left">...</div></td>';				
			
			
					
			if (!fullDisplay)	
				{ 
				cell= cell + '<td style=" border-radius: 6px;background-color: #A4B9C1;text-align: center;font-size:10px;" rowspan="2">';
				cell= cell + '<div >&nbsp;<a href="http://www.game-joint.com/singlerequest.php?id='+id+'&user='+user_posting+'#!" >VIEW&nbsp;FULL</a>&nbsp; </div><a href="http://www.game-joint.com/singlerequest.php?id='+id+'&user='+user_posting+'#!" onMouseOver="ReplaceImage(\'ImgArrow'+id+'\',\'flechaderON.gif\')" onMouseDown="ReplaceImage(\'ImgArrow'+id+'\',\'flechaderPRESSED.gif\')" onMouseOut="ReplaceImage(\'ImgArrow'+id+'\',\'flechader.gif\')"> <img border=0 name="ImgArrow'+id+'" id="arrowDown"  src="http://www.gamejoint.com.ar/flechader.gif"  width="22" height="22" "border="0" ></a>';
				cell= cell + '</td>';
				}
			
			cell= cell + '<tr>';
			cell= cell + '<td width=28%>';
                       
			if (estimated_time != 'not sure')
				cell= cell +  '<b>estimated work time: </b>'+estimated_time+' hours' ;
			cell= cell +  '</td>';
			cell= cell +  '<td width=22% align="left">';
			if (pay_per_hour > 0)
            	if (payType == 'hourly')
					cell= cell +  '<b>estimated pay per hour (U$S): </b>'+ pay_per_hour ;
                else //total    
                	cell= cell +  '<b>total to be paid (U$S): </b>'+ pay_per_hour ;
			cell= cell +  '</td>';
			cell= cell + '<td width=50% align="left">';

			if (fullDisplay)
				cell= cell + '<span align=right><b>posted on: </b>'+date.substring(0,date.indexOf(' '))+' by <a href="http://www.game-joint.com/users/profile.php?user='+user_posting+'">'+user_posting+'</a> from '+country+' ('+city+')</span>';
			else	
				cell= cell + '<span align=right><b>posted: </b>'+days_since+' days ago by <a href="http://www.game-joint.com/users/profile.php?user='+user_posting+'">'+user_posting+'</a> from '+country+' ('+city+')</span>';
				cell= cell +'</td>';
				cell= cell +'</tr>';
			cell= cell + '</table>';

			cell= cell + '</td>';

			cell= cell + '</tr>';
		cell= cell +'</table>';
		




		return cell;
	}
	
	function receiveRequestResponse()
	{

	var table = document.getElementById("requestsmaintable");

	//(table.rows[1].cells[0]).innerHTML='        <td class="requests"  style="background-color: #C4EDB8; border-width: 0px;padding: 0px;margin: 0; height:100%"><IMG SRC="http://www.gamejoint.com.ar/canioblue-rightside.gif" WIDTH=7 HEIGHT=100%></td>';
	if (request.readyState == 4) {
		if (request.status == 200)
			{
				//parse XML:
			
			var number = request.responseXML.getElementsByTagName("amount")[0].childNodes[0].nodeValue;
			
			
			
			lastSearchTo = lastSearchFrom + number;
			if (number < lastSearchNumberOfExtrasRequested)
				{//manage that this is the last block of requests
				//erase cells that won't have requests
					removeEntries((lastSearchNumberOfExtrasRequested - number));
					
					if (table.rows.length == 5)//just headers, meaning the table is empty, no requests displayed. must show message
						{
							var newRow = addRow("requestsmaintable");
							newRow.innerHTML = '<div align="center"><br><b>No actual requests matching that criteria.</b><br><br></div>';
							
						}
					
					
					updateLastCell(false);
				}
			else
			{
								
				//che, acordate de mostrar de nuevo el selector y boton para pedir requests
				updateLastCell(true);
				}
					for(i=0;i < number;i++)
					{
						
						
						var row = table.rows[table.rows.length -3 /*last cell*/+ 2/*header*/ - (number*2) + 2*i -1];
                        
                        
                        

						(row.cells[1]).innerHTML = showNewRequestCell(request.responseXML.getElementsByTagName("id")[i].childNodes[0].nodeValue, request.responseXML.getElementsByTagName("date")[i].childNodes[0].nodeValue,request.responseXML.getElementsByTagName("days_since")[i].childNodes[0].nodeValue, (request.responseXML.getElementsByTagName("technologies")[i].childNodes[0].nodeValue == false ? '':request.responseXML.getElementsByTagName("technologies")[i].childNodes[0].nodeValue ),
						request.responseXML.getElementsByTagName("motivation_money")[i].childNodes[0].nodeValue,request.responseXML.getElementsByTagName("motivation_profit")[i].childNodes[0].nodeValue,
						request.responseXML.getElementsByTagName("motivation_creativity")[i].childNodes[0].nodeValue,
						request.responseXML.getElementsByTagName("motivation_learn")[i].childNodes[0].nodeValue,request.responseXML.getElementsByTagName("motivation_art")[i].childNodes[0].nodeValue,
						request.responseXML.getElementsByTagName("motivation_other")[i].childNodes[0].nodeValue,request.responseXML.getElementsByTagName("announcement")[i].childNodes[0].nodeValue,
						request.responseXML.getElementsByTagName("language")[i].childNodes[0].nodeValue,request.responseXML.getElementsByTagName("specialty")[i].childNodes[0].nodeValue,
						request.responseXML.getElementsByTagName("estimated_time")[i].childNodes[0].nodeValue,request.responseXML.getElementsByTagName("pay_per_hour")[i].childNodes[0].nodeValue,
						request.responseXML.getElementsByTagName("username")[i].childNodes[0].nodeValue, request.responseXML.getElementsByTagName("country")[i].childNodes[0].nodeValue,
						request.responseXML.getElementsByTagName("city")[i].childNodes[0].nodeValue,request.responseXML.getElementsByTagName("title")[i].childNodes[0].nodeValue	,false, request.responseXML.getElementsByTagName("price_type")[i].childNodes[0].nodeValue);
					}
                  

				
				
			}
		}	
	
	}
	
	
	
	//actualiza la última celda con botón para expandir tabla y cantidad de registros extra a pedir. showMore: debe mostrar o no el botó de more
	function updateLastCell(showMore){
			var table = document.getElementById("requestsmaintable");
		var row = table.rows[table.rows.length -2 ];
		
		if (showMore) //show 'more' if there are more requests to show
			{

	        (document.getElementById("arrowContainer")).innerHTML = '<a id="arrowLink" href="javascript:addExtraEntries(document.getElementById(\'entriesPerClick\').value,\'\')" onMouseOver="ReplaceImage(\'ImgArrow\',\'flechaabajoON.gif\')" onMouseDown="ReplaceImage(\'ImgArrow\',\'flechaabajoPRESSED.gif\')" onMouseOut="ReplaceImage(\'ImgArrow\',\'flechaabajo.gif\')"> <img border=0 name="ImgArrow" id="arrowDown" align="absmiddle"  src="http://www.gamejoint.com.ar/flechaabajo.gif"  width="22" height="22" "border="0" ></a> ';
			

			(document.getElementById("entriesPerClick")).style.visibility="visible";
			(document.getElementById("showMe")).style.visibility="visible";
			(document.getElementById("more")).style.visibility="visible";

			}
		else
			{
          
	      	(document.getElementById("arrowContainer")).innerHTML = "";   
			(document.getElementById("entriesPerClick")).style.visibility="hidden";
			(document.getElementById("showMe")).style.visibility="hidden";
			(document.getElementById("more")).style.visibility="hidden";

				
				
			}

	}
	
	

/*
Create an URL according to the search parameters and go there
*/
function composeRSSURL(username)
{
	var baseURL = '/rss/rss.php';
    baseURL = baseURL + '?lang=en';
	baseURL = baseURL + '&specialty=' + document.getElementById("specialty").value;
	if (document.getElementById("filter").value != '')
		baseURL = baseURL + '&keyword=' + document.getElementById("filter").value;
	var language;

	if (document.getElementById("english").checked && document.getElementById("spanish").checked )
		language = "both";
	else if (document.getElementById("english").checked)
		language = "english";
	else
		language = "spanish";
	baseURL = baseURL + '&language='+language;	
	if (document.getElementById("location") != null)
		{
		baseURL = baseURL + '&location=' + document.getElementById("location").value;
		if (document.getElementById("location").value == 'specificDistance')
			{
			baseURL = baseURL + '&unit=' + document.getElementById("unit").value;
			baseURL = baseURL + '&distance=' + document.getElementById("distance").value;
			if (username == null || username == ' ')
				{
				alert ("Error, you're supposed to be logged to request this Feed");
				return -1;
				}
			baseURL = baseURL + '&username='+username	;
				

			}
		}
	if	(document.getElementById("garanteed_payment").checked)
		baseURL = baseURL + '&payment=yes' ;
	 window.open(baseURL.replace(' ','$'));
	
}

/*
Checks if the other language checkbox is checked when unclicking the first. To avoid both languages being empty.
*/
function checkAtLeastOneLanguage(checkedName)
{
	if (checkedName == 'english' && !document.getElementById("english").checked)
		document.getElementById("spanish").checked = true;
	else if (checkedName == 'spanish' && !document.getElementById("spanish").checked)
		document.getElementById("english").checked = true;	
	
	}
