//pagination variables
var totalRows = 0;
var totalPages = 0;
var auto_radius = true;

window.onload = function(){
	init();
}

function init(){
	
	//check filters
	checkFilters();
	
	//run the search
	runSearch();
	
	//add event listeners
	Event.observe(document.getElementById('field_location_zipcode'), 'keypress', function(event){ if(event.keyCode == 13) runSearch();})
	Event.observe(document.getElementById('field_rate_from'), 'keypress', function(event){ if(event.keyCode == 13) runSearch();})
	Event.observe(document.getElementById('field_rate_to'), 'keypress', function(event){ if(event.keyCode == 13) runSearch();})
	
}

function runSearch(){

	document.getElementById('results_container').className = "opacity90";
	document.getElementById('progress').style.display = "";

	var postline = "";

	//pagination variables
	var start = (currentPage-1) * perPage;
	var perpage = perPage;
	
	postline = 'action=runsearch&searchstring='+searchstring+"&start="+start+"&perpage="+perpage+"&offset="+getTimeZoneOffset();
	
	//zip code?
	if(document.getElementById('field_location').checked && document.getElementById('field_location_zipcode').value!="" && document.getElementById('field_location_zipcode').value!="ZIP Code"){
		postline += "&zipcode=" + document.getElementById('field_location_zipcode').value + "&miles=" + document.getElementById('field_location_miles').value;
		
		//if zip code hide the status message about multiple cities
		document.getElementById('search_message').style.display = "none";
		
	}else{
	
		//if search message is full reshow it
		if(document.getElementById('search_message').innerHTML != ""){
			document.getElementById('search_message').style.display = "";
		}
	
	}
	
	//rate?
	if(document.getElementById('field_rate').checked){
		var rate_to = "";
		if(document.getElementById('field_rate_to').value!=""){
			rate_to = document.getElementById('field_rate_to').value;
		}else{
			rate_to = "999999999";
		}
		postline += "&ratefrom=" + document.getElementById('field_rate_from').value + "&rateto=" + rate_to;
	}
	
	//rating?
	if(document.getElementById('field_rating').checked && document.getElementById('field_rating_stars').value!=""){
		postline += "&rating=" + document.getElementById('field_rating_stars').value;
	}
	
	//available?
	if(document.getElementById('field_available').checked && document.getElementById('field_available_day').value!=""){
		postline += "&available_day=" + document.getElementById('field_available_day').value + "&available_hour=" + document.getElementById('field_available_hour').value;
	}
	
	//city?
	if(document.getElementById('field_countries').value!=""){
	  var countries = document.getElementById('field_countries').value.split(',');
	  var l = countries.length;
	  for(i = 0; i < l; i++) {
  		postline += "&country[]=" + countries[i];
	  }
	}
	//city?
	if(document.getElementById('field_city').value!=""){
		postline += "&city=" + document.getElementById('field_city').value;
	}
	
	//state?
	if(document.getElementById('field_state').value!=""){
		postline += "&state=" + document.getElementById('field_state').value;
	}
	
	//gender?
	if($('field_gender').checked && document.getElementById('field_gender_male').checked){
		postline += "&gender=1"
	}else if($('field_gender').checked && document.getElementById('field_gender_female').checked){
		postline += "&gender=2"
	}
	
	//auto_radius
	postline += "&auto_radius=" + auto_radius;
	
	//jobtitle
	postline += "&jobtitle=" + jobtitle;

	new Ajax.Request(document.base_url+'search/search_ajax', {method:'post', postBody:postline, onComplete:searchResultsGot});

}

function clearResults(){

	var el_container = document.getElementById('ajax_results');
	
	if(el_container){
		document.getElementById('results_container').removeChild(el_container);
	}
	
	var el_pagination = document.getElementById('pagination');
	
	if(el_pagination){
		document.getElementById('results_container').removeChild(el_pagination);
	}

}

function searchResultsGot(t){

	clearResults();
		
	//document.getElementById('debug').innerHTML = t.responseText;	
		
	xmlDoc = t.responseXML;
	
	totalRows = xmlDoc.getElementsByTagName("total")[0].childNodes[0].nodeValue;
	closestMiles = xmlDoc.getElementsByTagName("closest_miles")[0].childNodes[0].nodeValue;
	totalPages = Math.ceil(totalRows / perPage);
	
	//document.getElementById('debug').innerHTML = xmlDoc.getElementsByTagName("query")[0].childNodes[0].nodeValue;
	
	xmlResults = xmlDoc.getElementsByTagName("result");
	
	//if we have closest miles we need to update the dropdown
	if(closestMiles>0){
		
		var options = document.getElementById('field_location_miles').options;
		for(var m=(options.length-1);m>0;m--){
				
				if(Number(closestMiles) <= Number(options[m].value)){
					options[m].selected = true;
				}else{
					options[m].selected = false;
				}
				
		}
		
	}
	
	//handle rows
	if(totalRows>0){
	
		//handle results
		var container = document.createElement('div');
		container.id = "ajax_results";
		
		for (var i=0;i<xmlResults.length;i++){
			
			var user_id = null;
			var username = null;
			var tn_url = null;
			var jobtitle = null;
			var location = null;
			var rate = null;
			var rating_html = null;
			var available_icon = null;
			var available_html = null;
			var extra_icon = null;
			var plus = null;
			var tools = null;
		  var currency_symbol = null; 
			for (var j=0;j<xmlResults[i].childNodes.length;j++){
				
				if(xmlResults[i].childNodes[j].nodeType != 1) continue;
				if(xmlResults[i].childNodes[j].nodeName=="user_id"){ user_id = xmlResults[i].childNodes[j].firstChild.nodeValue; }
				if(xmlResults[i].childNodes[j].nodeName=="username"){ username = xmlResults[i].childNodes[j].firstChild.nodeValue; }
				if(xmlResults[i].childNodes[j].nodeName=="tn_url"){ tn_url = xmlResults[i].childNodes[j].firstChild.nodeValue; }
				if(xmlResults[i].childNodes[j].nodeName=="jobtitle"){ jobtitle = xmlResults[i].childNodes[j].firstChild.nodeValue; }
				if(xmlResults[i].childNodes[j].nodeName=="location"){ location = xmlResults[i].childNodes[j].firstChild.nodeValue; }
				if(xmlResults[i].childNodes[j].nodeName=="rate"){ rate = xmlResults[i].childNodes[j].firstChild.nodeValue; }
				//if(xmlResults[i].childNodes[j].nodeName=="rating_html"){ rating_html = xmlResults[i].childNodes[j].firstChild.nodeValue; }
				if(xmlResults[i].childNodes[j].nodeName=="available_icon"){ available_icon = xmlResults[i].childNodes[j].firstChild.nodeValue; }
				if(xmlResults[i].childNodes[j].nodeName=="available_html"){ available_html = xmlResults[i].childNodes[j].firstChild.nodeValue; }
				if(xmlResults[i].childNodes[j].nodeName=="extra_icon"){ extra_icon = xmlResults[i].childNodes[j].firstChild.nodeValue; }
				if(xmlResults[i].childNodes[j].nodeName=="plus"){ plus = xmlResults[i].childNodes[j].firstChild.nodeValue; }
				if(xmlResults[i].childNodes[j].nodeName=="tools"){ tools = xmlResults[i].childNodes[j].firstChild.nodeValue; }
        if(xmlResults[i].childNodes[j].nodeName=="currency_symbol"){ currency_symbol = xmlResults[i].childNodes[j].firstChild.nodeValue; }
        
			}
			
			var isAlt = null;
			if(i%2==0){ isAlt = true; }else{ isAlt = false; }
			
			addRow(container,user_id,username,tn_url,jobtitle,location,rate,isAlt,'',available_icon,available_html,extra_icon,plus,tools,currency_symbol);
			
		}
		
		document.getElementById('results_container').appendChild(container);
		
		
		
		//handle pagination
		
		if(totalPages>1){
		
			var pagination = document.createElement('div');
			pagination.id = "pagination";
			pagination.className = "no-top-border pagination";
			
			
			
			//fieldset
			var fieldset = document.createElement('fieldset');
			
				//box left
				/*
				var box_left = document.createElement('div');
				box_left.id = "box_left";
				box_left.innerHTML = "Jump to Page";
				
				var box_left_textfield = document.createElement('input');
				box_left_textfield.type = "text";
				box_left_textfield.value = String(currentPage);
				box_left_textfield.id = "field_jump";
				box_left_textfield.name = "field_jump";
				box_left_textfield.className = "form";
				
				Event.observe(box_left_textfield, 'keypress', handleJumpSubmit);
				box_left.appendChild(box_left_textfield);
				fieldset.appendChild(box_left);
				*/
				
				
				//box right
				var box_right = document.createElement('div');
				box_right.id = "box_right";
				
					//prev
					if(currentPage>1){
						var box_right_prev = document.createElement('a');
						box_right_prev.href="#";
						box_right_prev.onclick = prevPage;
						box_right_prev.className = "link_black nounderline";
						box_right_prev.innerHTML = "Prev";
						box_right.appendChild(box_right_prev);
					}
					
					//other pages
					for(var k=1;k<=totalPages;k++){
						var box_right_link = document.createElement('a');
						box_right_link.href="#";
						box_right_link.pagenum = k;
						box_right_link.onclick = function(){ jumpPage(this.pagenum); }
						if(k==currentPage){
							box_right_link.className = "link_red nounderline";
						}else{
							box_right_link.className = "link_black nounderline"
						}
						box_right_link.innerHTML = k;
						box_right.appendChild(box_right_link);
					}
					
					
					//next
					if(currentPage<totalPages){
						var box_right_next= document.createElement('a');
						box_right_next.href="#";
						box_right_next.onclick = nextPage;
						box_right_next.className = "link_black nounderline";
						box_right_next.innerHTML = "Next";
						box_right.appendChild(box_right_next);
					}
				
				fieldset.appendChild(box_right);
			
			//add fieldset to pagination
			pagination.appendChild(fieldset);
			
			document.getElementById('results_container').appendChild(pagination);
			
			
			
		}
		
		
	}else{
	
	}

	if(totalRows>0){
	
		//update the display number
		var totalToShow = null;
		if(totalPages==1){ totalToShow = totalRows; }else{ totalToShow = (currentPage*perPage); }
		
		document.getElementById('box_displaying').innerHTML = "Displaying "+(((currentPage-1)*perPage)+1)+"-"+totalToShow+" of <span class=\"text_red\">"+totalRows+"</span> results.";
		
		if(document.getElementById('search_message').innerHTML != ""){
			document.getElementById('search_message').style.display = "";
		}
		
		document.getElementById('results').style.display = "";
		document.getElementById('no_results').style.display = "none";
		
	}else{
	
		//no results
		
		document.getElementById('box_displaying').innerHTML = "<span class=\"text_red\">No Results.</span>";
		document.getElementById('search_message').style.display = "none";
		
		document.getElementById('results').style.display = "none";
		document.getElementById('no_results').style.display = "";
		
		//show zip box?
		if(document.getElementById('field_location').checked){
			document.getElementById('help_zip').style.display = "none";
		}else{
			document.getElementById('help_zip').style.display = "";
		}
		
		//ny nj?
		if(document.getElementById('field_location_text').innerHTML.indexOf("NY")==-1 && document.getElementById('field_location_text').innerHTML.indexOf("NJ")==-1){
			document.getElementById('help_nyc').style.display = "";
		}else{
			document.getElementById('help_nyc').style.display = "none";
		}
	
	}
	
	document.getElementById('results_container').className = "";
	document.getElementById('progress').style.display = "none";	
	

}

function handleJumpSubmit(e){
	
	if(e.keyCode=="13"){
		
		var el_value = Number(document.getElementById('field_jump').value);
		
		if(el_value){
			jumpPage(el_value);
		}
		
	}
	
}

function nextPage(){
	
	currentPage++;
	runSearch();
	
}

function prevPage(){
	
	currentPage--;
	runSearch();
	
}

function jumpPage(pageNum){

	if(pageNum>totalPages || pageNum<0){
		alert("Error: Page is out of range.");
	}else{
	
		currentPage=pageNum;
		runSearch();
		
	}
	
}

function addRow(container,user_id,username,tn_url,jobtitle,location,rate,isAlt,rating_html,available_icon,available_html,extra_icon,plus,tools,currency_symbol){
	//create the link
	var row_a = document.createElement('a');
	row_a.href = "/"+username+"/"+document.searchstring;

	//create the row
	var row = document.createElement('div');
	row.className = "box_litegrey no-top-border row" + (plus ? ' plus_row' : '');
	
	if(isAlt){
		row.className += " alt";
	}
	
	//create the fieldset
	var fieldset = document.createElement('fieldset');
	
	//create the columns
		
		//create column 1
		var col1 = document.createElement('div');
		col1.className = "col_1";
		
			//create col_1 fieldset
			var col1_fieldset = document.createElement('fieldset');
			
			var tn = document.createElement('img');
			tn.className = "tn";
			tn.src = tn_url;
			col1_fieldset.appendChild(tn);
			
			//create col_1 icon
			var col1_icon = document.createElement('div');
			col1_icon.className = "icon_status";
			col1_icon.innerHTML = available_icon;
			col1_fieldset.appendChild(col1_icon);
			
			//create col_1 username
			var col1_username = document.createElement('h4');
			col1_username.innerHTML = wordwrap(username,16,'<br />',true);
			col1_fieldset.appendChild(col1_username);

      //create col_1 line break
			var col1_br = document.createElement('br');
			col1_fieldset.appendChild(col1_br);
      
      //create col_1 plus
      /*
			var col1_plus = document.createElement('div');
			col1_plus.className = "plus_icon";
			col1_plus.innerHTML = plus;
			col1_fieldset.appendChild(col1_plus);
			*/
			
      //create col_1 extra_icon
			var col1_extraicon = document.createElement('div');
			col1_extraicon.className = "extra_icon";
			col1_extraicon.innerHTML = extra_icon;
			col1_fieldset.appendChild(col1_extraicon);
      
			//add the fieldset to col1
			col1.appendChild(col1_fieldset);
		
			//create the stars
			/*var col1_stars = document.createElement('div');
			col1_stars.innerHTML = rating_html;
			col1.appendChild(col1_stars);*/
			
		//add col1 to fieldset
		fieldset.appendChild(col1);
		
		//create cols fieldset
		var el_fieldset2 = document.createElement('fieldset');
		
		//create column 2
		var col2 = document.createElement('div');
		col2.className = "col_2";
		col2.innerHTML = jobtitle;
		el_fieldset2.appendChild(col2);
		
		//create column 3
		var col3 = document.createElement('div');
		col3.className = "col_3";
		col3.innerHTML = location;
		el_fieldset2.appendChild(col3)
		
		//create column 4
		var col4 = document.createElement('div');
		col4.className = "col_4";
		col4.innerHTML = currency_symbol + "" + rate + "/hr";
		el_fieldset2.appendChild(col4)
		
		//create column 5
		var col5 = document.createElement('div');
		col5.className = "col_5";
		col5.innerHTML = available_html;
		el_fieldset2.appendChild(col5)
		
		fieldset.appendChild(el_fieldset2);
		
		//create column 6
		var col6 = document.createElement('div');
		col6.className = "col_6";
		col6.innerHTML = tools;
		fieldset.appendChild(col6);
		
	//add fieldset to row
	row.appendChild(fieldset);
	
	//add row to a
	row_a.appendChild(row);

	//add it to the container
	container.appendChild(row_a);

}

function checkFilters(){
	
	checkFilter('field_available','box_availability');
	checkFilter('field_location','box_location');
	checkFilter('field_rate','box_rate');
	checkFilter('field_rating','box_rating');
	checkFilter('field_gender','box_gender');
	
}

function fillBox(box_id){
	document.getElementById(box_id).checked = true;
}

function checkFilter(checkbox_id,box_id){
	
	var el_checkbox = document.getElementById(checkbox_id);
	var el_box = document.getElementById(box_id);
	
	if(el_checkbox.checked){
		
		el_box.style["backgroundColor"]='#fcf0f0';
		
	}else{
	
		el_box.style["backgroundColor"]='#ffffff';
		
		if(checkbox_id=="field_gender"){
			$('field_gender_male').checked = false;
			$('field_gender_female').checked = false;
		}
	
	}

}