/*
	Ajax functions
*/

// Holds the ajax object
var http_requestPool = new Array();

/*
	Makes an ajax post request to the server.
		url: Url to post to
		parameters: params to post (form fields and so on)
		callbackFunction: what function to call once the request is done
		errorFunction: what function to call if the request failed.

	Note:
		If the response is "<!-- LogOut -->", then the session expired, go back to error screen.

*/
function makePOSTRequest(url, parameters, callbackFunction, errorFunction) {
	// NOTE: this might use to much ram if called to much.
	var http_request = false;

	url = ajaxAddJSessionId(url);

	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/html');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!http_request) {
		alert('Cannot create XMLHTTP instance, please update your browser.');
		return false;
	}
	http_request.onreadystatechange =
		function () {
			try{
				if (http_request.readyState == 4) {
					if (http_request.status == 200) {
						var response = http_request.responseText;
						// Remove from pool
						http_requestPool.remove(http_request);
						
						if (callbackFunction) { 
							eval ( callbackFunction); 
						}
						// Run the JavaScript
						ajaxJavaScript(response);
					} else {
						// Remove from pool
						http_requestPool.remove(http_request);
						// This is a minor error: page not found, restricted, etc.
						if (errorFunction) {
							eval (errorFunction);
						} else {
							ajaxRetry('Received Error Code: ' + http_request.status, url, parameters, callbackFunction, errorFunction, 3);
						}
					}
				}
			}
			catch(e){
				// Remove from pool
				http_requestPool.remove(http_request);
				// This is a more serious error
				if (errorFunction) {
					eval (errorFunction);
				} else {
					ajaxRetry('Fatal Error: 1' + e, url, parameters, callbackFunction, errorFunction, 3);
				}
			}
		};

	http_request.open('POST', url, true);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.setRequestHeader("Content-length", parameters.length);
	http_request.setRequestHeader("Connection", "close");
	http_request.send(parameters);
	http_requestPool.push(http_request);
}

function ajaxAddJSessionId(url) {

	var quesIdx = url.indexOf("?");
	var jsessIdx = url.indexOf(";jsessionid=");

	if (jsessIdx != -1)
	{
		return url;
	}

	if (quesIdx == -1)
	{
		return url + SID;
	}

	var preQues = url.slice(0, quesIdx);
	var postQues = url.slice(quesIdx, url.length);

	return preQues + SID + postQues;
}

/*
	This is the default ajax error function.
	It basically spits out on screen what was wrong.
	Can be overwritten to do anything.
	Note:
		Should not be used in production
*/
function ajaxError(txt) {
	alert (txt);
}

/*
	Function will retry your request a few times.
*/
function ajaxRetry(msg, url, parameters, callbackFunction, errorFunction, retries) {
	retries--;
	if (retries > 0) {
		// Clean the vars for js use
		msg = msg.replace(/'/,'\'');
		msg = msg.replace(/"/,'\"');
		url = url.replace(/'/,'\'');
		parameters = parameters.replace(/'/,'\'');
		callbackFunction = callbackFunction.replace(/'/,'\'');
		// Retry the request in 3 seconds.
		window.setTimeout('makePOSTRequest(\''+url+'\', \''+parameters+'\', \''+callbackFunction+'\',\'ajaxRetry(\"'+msg+'\", url, parameters, callbackFunction, errorFunction, '+retries+')\')',3000);
	}else{
		if (msg == 'Received Error Code: 403') {
			ajaxError("You do not have the necessary privileges to access this action.");
		} else if (msg == 'Received Error Code: 404') {
			ajaxError("The page you are looking for might have been removed, had its name changed, or is temporarily unavailable.");
		} else if (msg == 'Received Error Code: 500') {
			ajaxError("Mate1.com is experiencing technical difficulties...\nPlease wait a few minutes and try this action again. We apologize for the inconvienence.");
		} else {
			ajaxError("Mate1.com is experiencing technical difficulties... \n" + msg + "\nYour internet connection might have been lost, please wait a few minutes and refresh the page to try again.");
		}
	}
}

/*
 * ** Session Keep-Alive Function: Hit the ping function at regular intervals to
 * ** keep the user from logging out while reading/writing e-mails,profiles,etc
 * **
 * */
function ajDoPing () {
	makePOSTRequest('/profiles/ping', 'sid=sid&junk=rand', '');
	window.setTimeout("ajDoPing();",2640000); //2640000 ms == 44 mins
}


/*
	Function will parse all the form fields and create a string to be used in the ajax post.
	Note:
		This is the perfect place to add in some fancy javascript form validation.
*/
function getFormValues(frmObj) {
	var str = "";
	for(var i = 0; i < frmObj.elements.length; i++) {
		switch(frmObj.elements[i].type) {
			case "textarea":
				str += "&" + frmObj.elements[i].name + "=" + escape(frmObj.elements[i].value);
				break;
			case "text":
				str += "&" + frmObj.elements[i].name + "=" + escape(frmObj.elements[i].value);
				break;
			case "select-one":
				if(frmObj.elements[i].selectedIndex != null && frmObj.elements[i].selectedIndex != -1)
				{
					str += "&" + frmObj.elements[i].name + "=" + frmObj.elements[i].options[frmObj.elements[i].selectedIndex].value;
				}
				break;
			case "checkbox":
				if (frmObj.elements[i].checked) {
					str += "&" + frmObj.elements[i].name + "=" + frmObj.elements[i].value;
				}
				break;
			case "radio":
				if (frmObj.elements[i].checked) {
					str += "&" + frmObj.elements[i].name + "=" + frmObj.elements[i].value;
				}
				break;
			case "hidden":
				str += "&" + frmObj.elements[i].name + "=" + frmObj.elements[i].value;
				break;
		}
	}

	return str;
}

/*
	This function will parse the output and run whatever javascript it finds.
*/
function ajaxJavaScript(response) {
	var tmp_array = response.match(/<script type="text\/javascript">([^<]+)<\/script>/gi);
	if ((tmp_array) && (tmp_array.length > 0)) {
		if (tmp_array.length > 0) {
			for (i = 0; i < tmp_array.length; i++) {
				tmp_array[i] = tmp_array[i].substring(32,(tmp_array[i].length - 9));
				eval (tmp_array[i]);
			}
		}
	}
}

/*
**	Functions used in profile editing
**/

// Holds how many sections are opened in edit mode.
var openedSections = 0;

/*
	Function will show the save all button.
*/
function showSaveAll() {
	if (openedSections == 0) {
		// Get objects
		objContainer = document.getElementById('container_save_all');
		
		// Show the edit/hide the view
		objContainer.style.display = 'block';
	}
	openedSections++;
}

/*
	Function will hide the save all button.
*/
function hideSaveAll() {
	openedSections--;
	if (openedSections == 0) {
		// Get objects
		objContainer = document.getElementById('container_save_all');
		
		// Show the edit/hide the view
		objContainer.style.display = 'none';
	}
}

/*
	Function will display the edit section.
*/
function showEdit(sectionName) {
	// Get objects
	objController = document.getElementById('controller_'+sectionName);
	objView = document.getElementById('view_'+sectionName);
	objEdit = document.getElementById('edit_'+sectionName);
	// Change the controller text
//	objController.innerHTML = '<a href="#" onclick="cancelEdit(\'' + sectionName + '\'); return false;" onfocus="this.blur();" class="profile_edit">cancel</a>';
	objController.innerHTML = '';
	// Show the edit/hide the view
	objView.style.display = 'none';
	objEdit.style.display = 'block';
	// Show the save all button.
	showSaveAll();
	
	if ((sectionName == 'about_myself') || (sectionName == 'who_im_looking_for')) { 
		initCharCounters();
	}
}


/*
	Function will hide the edit section.
*/
function cancelEdit(sectionName) {
	// Get objects
	objController = document.getElementById('controller_'+sectionName);
	objView = document.getElementById('view_'+sectionName);
	objEdit = document.getElementById('edit_'+sectionName);
	// Change the controller text
	objController.innerHTML = '<a href="#" onclick="showEdit(\'' + sectionName + '\'); return false;" onfocus="this.blur();" class="profile_edit">edit</a>';
	// Show the edit/hide the view
	objEdit.style.display = 'none';
	objView.style.display = 'block';
	dfts_clear(sectionName);

	// Hide the save all button.
	hideSaveAll();
}

/*
	Function will hide the edit section.
*/
function saveSection(sectionName, componentName) {
	// Get objects
	objController = document.getElementById('controller_'+sectionName);

	// TODO: Make sure you check for this and return <!-- LogOut --> if the profile has no session
	postData = "ajax=1"	
	postData += getFormValues(document["form_"+sectionName]);

	// Change the controller text
	objController.innerHTML = '<em>loading...</em>';
		
	// Request the refresh data
	makePOSTRequest(componentName, postData, 'savedSection("'+sectionName+'",response)');

	// Hide the save all button.
	hideSaveAll();
}

/*
	Function will show the server response
*/
function savedSection(sectionName, response) {
	objContainer = document.getElementById('container_'+sectionName);
	objContainer.innerHTML = response;
	dfts_clear(sectionName);
	
}

/*
	Function will save all the changed sections.
	The section controller holds the state of that section.
 */
function saveAllSections(componentName) {
	// Lists all section names.
	var s = ['profile_information', 'about_myself', 'who_im_looking_for', 'lifestyle_and_interests', 'favorite_things', 'least_favorite_things'];

	// Holds the data to be posted
	var postData = "ajax=1";
	
	// See witch sections need saving
	for (var i=0;i<s.length;i++)
	{
		// Get Objects
		objController = document.getElementById('controller_'+s[i]);
		
		// If the controller has the "edit" or "loading" buttons, we don't save them.
		if ((objController.innerHTML.indexOf('showEdit') == -1) && (objController.innerHTML.indexOf('loading') == -1)) {
			// Get the form data
			postData += getFormValues(document["form_"+s[i]]);
			
			// Change the controller text
			objController.innerHTML = '<em>loading...</em>';

			// Deal with this section
			dfts_clear(s[i]);
		}
	}
	
	// Strip out the section names
	var regex = new RegExp("\\&section_name=[^&]+\\b", "g");
	postData = postData.replace(regex, '');

	// Add our save all section name
	postData = postData + '&section_name=save_all';
	
	// Request the refresh data
	makePOSTRequest(componentName, postData, 'redirectTo("'+componentName+'")');
}

/*
	Function saves new photo captions
*/
function editCaption(img_id)
{
	textarea = document.getElementById("caption_" + img_id);

	if(confirm("Are you sure you want to update your caption?")) {
		makePOSTRequest('/profiles/images/edit_caption?image_id='+img_id+'&image_caption='+textarea.value, 'aj=1', 'savedCaption('+img_id+', response)');
	}
}
/*
	Function will show the server response
*/
function savedCaption(img_id,response) {
	pending_box = document.getElementById("pending_" + img_id);
	pending_box.innerHTML = '<b> Pending</b>';
}

/*
**	Functions used in country/province/city selection
**/
var inAdvancedSearch = false;

/*
	Function will load up all provinces for a country
*/
function changeCountry(country_id) {
	// Select 'country' search type... if need be
	checkRadio('COUNTRY_SEARCH_TYPE');

	// Get objects
	obj_container_region_id = document.getElementById('container_region_id');
	obj_content_region_id = document.getElementById('content_region_id');
	obj_container_city = document.getElementById('container_city');
	obj_content_city = document.getElementById('content_city');
	obj_region_id = document.getElementById('region_id');
	obj_city = document.getElementById('city');
	obj_default_region_id = document.getElementById('default_region_id');

	// Hide the objects
	obj_container_region_id.style.visibility = '';
	obj_container_region_id.style.display = '';
	obj_container_city.style.visibility = 'hidden';
	
	// Reset their data
	obj_content_region_id.innerHTML = '<select name="'+obj_region_id.name+'" id="region_id" class="select" onchange="checkRadio(\'COUNTRY_SEARCH_TYPE\');"><option value="0" selected="selected">Loading...</option></select>';
	obj_content_city.innerHTML = '<input type="text" name="'+obj_city.name+'" id="city" class="input" value="" onchange="checkRadio(\'COUNTRY_SEARCH_TYPE\');">';

	// Make a server request for new provinces
	var tmpParam = '';
	if (inAdvancedSearch) {
		tmpParam += '&advSearch=1';
	}
	tmpParam += '&countryId=' + country_id;
	tmpParam += '&regionId=' + obj_default_region_id.value;
	tmpParam += '&regionName=' + obj_region_id.name;
	
	var url = 'http://www.mate1.com/nw/blocks/registration/location/regions';
	if ($('#inRegistration').length == 0) {
		url = 'http://www.mate1.com/nw/blocks/location/regions';
	}
	makePOSTRequest(url, 'aj=1&aj-block=1'+tmpParam, 'changedCountry(response)');
}

/*
	Function will show the server response for country changes
*/
function changedCountry(response) {
	// Get objects
	obj_container_region_id = document.getElementById('container_region_id');
	obj_content_region_id = document.getElementById('content_region_id');
	obj_container_city = document.getElementById('container_city');
	obj_content_city = document.getElementById('content_city');
	obj_country_id = document.getElementById('country_id');
	obj_region_id = document.getElementById('region_id');
	obj_city = document.getElementById('city');
	
	// Hide the objects
	obj_container_region_id.style.visibility = '';
	obj_container_region_id.style.display = '';
	obj_container_city.style.visibility = 'hidden';
	
	// Take off the errors on the country (if any)
	obj_country_id.className = obj_country_id.className.replace('formerror','');

	// Reset their data
	if (response.toLowerCase().indexOf('<option') > -1) {
		obj_content_region_id.innerHTML = response;
		focusField('region_id');
		// Show the city if we have something selected
		if (response.toLowerCase().indexOf('selected') > -1) {
			obj_region_id = document.getElementById('region_id');
			changeProvince(obj_region_id[obj_region_id.selectedIndex].value);
			obj_container_city.style.visibility = 'visible';
		}
	} else {
		obj_container_region_id.style.visibility = 'hidden';
		obj_container_region_id.style.display = 'none';
		obj_content_region_id.innerHTML = '<select name="'+obj_region_id.name+'" id="region_id" class="select" onchange="checkRadio(\'COUNTRY_SEARCH_TYPE\');"><option value="1" selected="selected">Loading...</option></select>';
		changedProvince('');
	}
	obj_content_city.innerHTML = '<input type="text" name="'+obj_city.name+'" id="city" value="" class="input" onchange="checkRadio(\'COUNTRY_SEARCH_TYPE\');">';
}

/*
	Function will load up all cities for a province
*/
function changeProvince(region_id) {
	// Select 'country' search type... if need be
	checkRadio('COUNTRY_SEARCH_TYPE');
		
	// Get objects
	obj_container_city = document.getElementById('container_city');
	obj_default_city = document.getElementById('default_city');
	obj_city = document.getElementById('city');

	// Hide objects
	obj_container_city.style.visibility = 'hidden';
	
	// Make a server request for new provinces (if region_id != 0)
	if ((region_id != 0) && (region_id != '')) {
		var tmpParam = '';
		if (inAdvancedSearch) {
			tmpParam += '&advSearch=1';
		}
		tmpParam += '&regionId=' + region_id;
		tmpParam += '&city=' + obj_default_city.value;
		tmpParam += '&cityName=' + obj_city.name;

		var url = 'http://www.mate1.com/nw/blocks/registration/location/cities';
		if ($('#inRegistration').length == 0) {
			url = 'http://www.mate1.com/nw/blocks/location/cities';
		}
		makePOSTRequest(url, 'aj=1&aj-block=1' + tmpParam, 'changedProvince(response)');
	} else {
		changedProvince('junk');
	}
}

/*
	Function will show the server response for country changes
*/
function changedProvince(response) {
	// Get objects
	obj_country_id = document.getElementById('country_id');
	obj_container_city = document.getElementById('container_city');
	obj_content_city = document.getElementById('content_city');
	obj_city = document.getElementById('city');
	
	// Show objects
	obj_container_city.style.visibility = 'visible';
	
	// Reset their data
	if (response.toLowerCase().indexOf('<option') > -1) {
		obj_content_city.innerHTML = response;
	} else {
		obj_content_city.innerHTML = '<input type="text" name="'+obj_city.name+'" id="city" value="" class="input" onchange="checkRadio(\'COUNTRY_SEARCH_TYPE\');">';
	}
	focusField('city');
}

/*
	Function will eventually set the focus on a field.
*/
function focusField(objName) {
	setTimeout("setFocusField('"+objName+"'),100");
}

/*
	Function will set the focus on a field.
*/
function setFocusField(objName) {
	obj = document.getElementById(objName);
	if (obj) {
		obj.focus();
	}else{
		setTimeout("setFocusField('"+objName+"'),1000");
	}
}

/*
	You can't search by zip code and country in the same time, so this will hide one or another.
	Note:
	- Only to be used in search poges.
*/
function toggleLocationSearch() {
	// Get objects
	var cur_c = window.document.search.country_id.selectedIndex;

	// Show the edit/hide the view
	if (cur_c == '0') {
		window.document.search.country_id[0].text = 'Please Select';
		inAdvancedSearch = false;
	} else {
		// Show the edit/hide the view
		window.document.search.country_id[0].text = 'Search by Zip/Postal Code Only';
		inAdvancedSearch = true;
	}
}

/**************************************
** Don't forget to save, functions.
**/

// NOTE: this might be in other places.
var dfts_form = new Array()
Array.prototype.remove=function(s){
  for(i=0;i<this .length;i++){
    if(s==this[i]) this.splice(i, 1);
  }
}

/*
  Function is called, every time a form field has been changed
*/
function dfts_change (frmName) {
  if (!dtf_in_array(dfts_form, frmName) ) {
    dfts_form.push(frmName);
  }
}
/*
  Function is called, every time a form change has been cancelled
*/
function dfts_clear (frmName) {
  dfts_form.remove(frmName);
}
/*
  Function is called, every time a form change has been cancelled
*/
function dfts_clear () {
  dfts_form = new Array();
}
/*
  Function is called every time the header is unloaded.
*/
function dfts_onunload() {
  if (dfts_form.length > 0) {
        return "You have unsaved changes. Continue?";
  }
}
/*
  Function will check to see if we have a value in an array
*/
function dtf_in_array(arr, value) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] == value) {
      return 1;
    }
  }
  return 0;
}

/**
 * Function will hotlist a profile, and change the text/class of the link to hotlisted.
 * 
 * @param obj The link object (this)
 * @param id user ID to hotlist
 * @param url url for the hotlist script
 * @param txt Hotlisted text
 */
//TODO: the harcoded strings need to be localized!
// listProfile(this, profileId, url, labelName)
function listProfile(obj, data, url, txt) {
	
	if(obj.className.indexOf('hotlisted') > -1)
	{
		return false;
	}

	profileId = data.split('=');

	if(obj.id == 'block_'+profileId[1])
	{
      objToggle = document.getElementById('hot_'+profileId[1]);
		  
			if (objToggle != null)
			{
				objToggle.innerHTML = 'Hotlist';
				objToggle.className = obj.className;
				obj.className = obj.className + " hotlisted";
			}
			else
			{
				obj.className = obj.className + " buttonDisabled";
			}
			// TODO: language this...
			alert("This user has been blocked!");
	}    
	else if(obj.id == 'hot_'+profileId[1])
	{
      objToggle = document.getElementById('block_'+profileId[1]);
  		
			if (objToggle != null)
			{
				objToggle.innerHTML = 'Blocklist';
				objToggle.className = obj.className;
				obj.className = obj.className + " hotlisted";
			}
			else
			{
				obj.className = obj.className + " buttonDisabled";
			}
			
		// Activate the hotlist button
	 	$('h2 span.right a').html('Block User');
	 	$('h2 span.right a').removeClass('hotlisted');

		
	}
      
	makePOSTRequest(url,data);
	obj.innerHTML = txt;
	return false;
}

/**
 * Function to hotlist users in simple mailclient
 */
function smailHotlist(data, url, myClass, txt){

	if ($("." + myClass).is('.buttonDisabled')){
		return false;
	}
	$("." + myClass).addClass('buttonDisabled');
	$("." + myClass).html(txt);
	makePOSTRequest(url,data);

 alert('The user has been hotlisted'); return false;
}

/**
 * Function will block a user, and change the clicked link text to whatever we specify 
 * 
 * @param obj The link we clicked / want to change.
 * @param id The profile ID to block.
 * @param url The URL to the blocking script.
 * @param txt The text to set the link to after the click.
 * @return false
 */
function blockProfile(obj, id, url, txt) {
	// Do not block if already blocked.
	if(obj.className.indexOf('hotlisted') > -1)
	{
		return false;
	}
	// Change the button
	obj.innerHTML = txt;
	obj.className = obj.className + " hotlisted";
	
	// Make the post
	makePOSTRequest(url,'profile_id='+id);

	// TODO: language this... 
	alert("This user has been blocked!");
	
	// Don't follow the link
	return false;
}

 /**
  * Function will block a user, and change the clicked link text to whatever we specify 
  * 
  * @param obj The link we clicked / want to change.
  * @param id The profile ID to block.
  * @param url The URL to the blocking script.
  * @param txt The text to set the link to after the click.
  * @return false
  */
 function blockProfileActiveateHotlist(id, blockId, blockUrl, hotlistId) {
 	// Do not block if already blocked.
 	if ($(blockId).hasClass('hotlisted')) {
 		return false;
 	}

 	// Change the blocked button
 	$(blockId).html('Blocked');
 	$(blockId).addClass('hotlisted');
 	
 	// Make the post
 	makePOSTRequest(blockUrl,'profile_id='+id);

 	// Activate the hotlist button
 	$(hotlistId).html('Hotlist');
 	$(hotlistId).removeClass('hotlisted');
 	$(hotlistId).removeClass('buttonDisabled');
 	
 	// TODO: language this... 
 	alert("This user has been blocked!");
 	
 	// Don't follow the link
 	return false;
}
  
  /**
   * Function will block a user, and change the clicked link text to whatever we specify 
   * 
   * @param obj The link we clicked / want to change.
   * @param id The profile ID to block.
   * @param url The URL to the blocking script.
   * @param txt The text to set the link to after the click.
   * @return false
   */
  function hotlistProfileActiveateBlocklist(id, hotlistId, hotlistUrl, blocklistId) {
  	// Do not block if already blocked.
  	if ($(hotlistId).hasClass('hotlisted')) {
  		return false;
  	}

  	// Change the hotlisted button
  	$(hotlistId).html('Hotlisted');
  	$(hotlistId).addClass('hotlisted');
  	$(hotlistId).addClass('buttonDisabled');
  	
  	// Make the post
  	makePOSTRequest(hotlistUrl,'profile_id='+id);

  	// Activate the blocklist button
  	$(blocklistId).html('Block User');
 	$(blocklistId).removeClass('hotlisted');
  	$(blocklistId).removeClass('buttonDisabled');
  	
  	// TODO: language this... 
  	alert("This user has been hotlisted!");
  	
  	// Don't follow the link
  	return false;
 }
   
/**
 * Function will send a flirt free message to a profile (ask for more photo, flirt free, let's correspond) 
 * and change the text/class of the "Flirt Free" button to 'Flirt Sent'.
 * 
 * @param objId the id of the "Flirt Free" button
 * @param url url for the hotlist script
 * @param txt 'Flirt Sent' text
 */
function flirtFreeActionMenu(objId, url, txtpre, txtpost) 
{
	pageTracker._trackPageview('/click/say_hi/' + getGALocation());

    makePOSTRequest(url,'ajax=1', 'flirtFreeActionMenuSent(response,"'+objId+'","'+ txtpost+'")');
    obj = document.getElementById(objId);
    if (obj != null)
    {       
            obj.innerHTML = txtpre;
    }
}

/**
 * Function callback function for flirtFreeActionMenu 
 * Change the text of an element while the Ajax request works.
 * 
 * @param objId the id of the "Flirt Free" button
 * @param txtpre the text for the button
 */
function flirtFreeActionMenuSent(response, objId, txtpost) {
        obj = document.getElementById(objId);
	if(response.indexOf('<script type="text/javascript">') == -1)
	{
        	if (obj != null)
	        {       
                	obj.innerHTML = txtpost;
	        }
	}
}

/**
 * Function will send a flirt free message to a profile (ask for more photo, flirt free, let's correspond) 
 * and change the text/class of the "Flirt Free" option in the drop down to 'Flirt Sent'.
 * 
 * @param obj The link object (this)
 * @param url url for the hotlist script
 * @param txt 'Flirt Sent' text
 */
function flirtFreeActionDropDown(obj, url, txt) {
  makePOSTRequest(url,'ajax=1');
  obj.innerHTML = txt;
	obj.className = obj.className + " hotlisted";
	obj.onclick = function() { return false; };
	return false;
}


/*
 * Send a say hi request from the photo
 */
function photoRequestAction(imgObjId, objLink, url, followupImg)
{
	makePOSTRequest(url, 'ajax=1');
	var objImg = document.getElementById(imgObjId);
	if (objImg != null)
	{
		objImg.src = followupImg;
	}
	objLink.onclick = function() { return false; };
	return false;
}

/*
 * Send a hi request for photo in the simple mailclient.
 * This will update the image for the same user in the view.
 */
function smailPhotoRequestAction(myClass, objLink, url, followupImg)
{
	$("." + myClass).attr("src", followupImg);
	makePOSTRequest(url, 'ajax=1');
	objLink.onclick = function() { return false; };
	return false;
}


/**
 * Function will remove the selected hotlist/blocklist items.
 * 
 * @param obj The object we clicked, that will be disabled.
 * @param question The question to add the user when they remove something.
 * @param url The url for the remove script.
 */
function removeSelectedHBItems(obj, question, url)
{
	var checkboxes = document.getElementsByName('hot_block_profiles');
	var profIds = new Array();

	for(var i = 0; i < checkboxes.length; i++)
	{
		if(checkboxes[i].checked)
		{
			profIds.push(checkboxes[i].value);
		}
	}

	if(profIds.length > 0)
	{
		var answer = confirm(question);
		
		if(answer) {
			obj.onclick = function () { return false; }
			makePOSTRequest(url, 'profileIds='+profIds.join(','), 'refreshPage()');
		}
	}
}

/**
 * Function to fetch number of new messages
 */
function getNumNewMessages()
{
	$.ajax({
		url: "/nw/mail/jsNumNewMessages",
		success:function(data){
			$("#mailboxIn").html(data);
		}
	});
}


/**
 * Function to refresh the inbox when clicking on the 'Mailbox' in the main
 * menu
 */
function refreshInbox()
{
  div = document.getElementById("mail_client");

  if (div)
  {
    reloadInbox();
    return false;
  }
  else
  {
    return true;
  }
}

/**
 * Callback to refresh the number of new messages in the main menu
 */
function refreshNumNewMessages(response)
{
	obj = document.getElementById('mainMenuMailbox');
  obj.innerHTML = response;
}

/**
 * Function will refresh the page.
 */
function refreshPage() {
	location.reload(true);
}

/**
 * Function will redirect the browser to the passed in url
 */
function redirectTo(url) {
	window.location.href = url;
}
 
/**
 * Function will redirect the browser to the passed in url, replacing the history
 */
function replaceTo(url) {
	window.location.replace = url;
}
 
/**
 * Function will set a value to a form field with the passed in ID
 */
function setField(id,value) {
	document.getElementById(id).value = value;
}

/**
 * This function associates an onchange event to the country select so that whenever the UK is selected the 
 * Postal Code input disappears (since it is redundant with the postCode select list).  Once a different country is 
 * selected the Postal Code input appears again.  
 * @param arrElementIdsToHide.  Array with Ids of html elements to hide when UK is selected as country.  Once
 * the country changes to something different than UK these elements are shown.
 * @param arrElementIdsToShow.  Array with Ids of html elements to show when UK is selected as country.  Once
 * the country changes to something different than UK these elements are hidden.
 * @param idUK.  CountryId for the UK.  
 * @return
 */
function registerAndExecutePostalCodeCallback(arrElementIdsToHide, arrElementIdsToShow, idUK) 
{
	//Defensive, in case a null param was passed instead of any array
	if (arrElementIdsToHide == null) 
	{
		arrElementIdsToHide = new Array();
	}
	if (arrElementIdsToShow == null)
	{
		arrElementIdsToShow = new Array();
	}
	$(document).ready(function() 
	{
		showHidePostalCodeBlock(arrElementIdsToHide, arrElementIdsToShow, idUK);
		$("#country_id").change(function () 
			{
			showHidePostalCodeBlock(arrElementIdsToHide, arrElementIdsToShow, idUK);
			});
	});	
}

/**
 * This function collaborates with registerAndExecutePostalCodeCallback to show/hide different html elements when
 * the UK is selected and when it changes again to another country.
 * @param arrElementIdsToHide
 * @param arrElementIdsToShow
 * @param idUK
 * @return
 */
function showHidePostalCodeBlock(arrElementIdsToHide, arrElementIdsToShow, idUK)
{
	//Verify if United Kingdom was selected
	if ($("#country_id").val() == idUK) 
	{
		for(var i=0; i < arrElementIdsToHide.length; i++)
		{
			$(arrElementIdsToHide[i]).hide();	
		}
		for(var i=0; i < arrElementIdsToShow.length; i++)
		{
			$(arrElementIdsToShow[i]).show();	
		}
	} 
	else 
	{
		for(var i=0; i < arrElementIdsToHide.length; i++)
		{
			$(arrElementIdsToHide[i]).show();	
		}		
		for(var i=0; i < arrElementIdsToShow.length; i++)
		{
			$(arrElementIdsToShow[i]).hide();	
		}
	}		
}


/**
 * This function exists to overwrite the saveSection function with show/hide support after the ajax response is
 * obtained.  NOTE:  It's not very elegant!! but had to be used to attach some additional functionality to the thread 
 * of execution of the callback function passed to the makePostRequest.  This function collaborates with:
 * savedSectionWithShowHideSupport. 
 * @param sectionName
 * @param componentName
 * @param postalCodeBlockId
 * @param idUK
 * @return
 */
function saveSectionWithShowHideSupport(sectionName, componentName, postalCodeBlockId, idUK) {
	// Get objects
	objController = document.getElementById('controller_'+sectionName);
	
	// TODO: Make sure you check for this and return <!-- LogOut --> if the profile has no session
	postData = "ajax=1"	
	postData += getFormValues(document["form_"+sectionName]);
	
	// Change the controller text
	objController.innerHTML = '<em>loading...</em>';
		
	// REPLACED THE OLD AJAX CALL WITH WITH JQUERY(SEE BELOW) THIS CALL HAD ISSUES WITH RUNNING JAVASCRIPT
	// ALSO WE WILL NOT USE savedSectionWithShowHideSupport CALLBACK SINCE WE ARE ONLY ALLOWING USERS TO 
	// CHANGE THEIR COUNTRY AND ZIP/POST/POSTAL CODE (or CITY FOR NON-NORMALIZED COUNTRIES).
	// makePOSTRequest(componentName, postData, 'savedSectionWithShowHideSupport("'+sectionName+'","' + postalCodeBlockId + '",' + idUK + ',response)');
	
	
	// Request the refresh data
	$.post(componentName, postData, function(response) {
		$("#container_" + sectionName).html(response);
		dfts_clear(sectionName);		
	});
	
	// Hide the save all button.
	hideSaveAll();
}

/**
 * This function is the callback registered with the postRequest by the function:  saveSectionWithShowHideSupport.  It
 * exists to make sure that the show/hide events associated when the UK is selected are registered and executed after
 * the response is obtained from the ajax call.
 * @param sectionName
 * @param postalCodeBlockId
 * @param idUK
 * @param response
 * @return
 */
function savedSectionWithShowHideSupport(sectionName, postalCodeBlockId, idUK, response) {
	objContainer = document.getElementById('container_'+sectionName);
	objContainer.innerHTML = response;
	dfts_clear(sectionName);
	var arrElementIdsToHideTemp = new Array(postalCodeBlockId);
	var arrElementIdsToShowTemp = new Array();
	registerAndExecutePostalCodeCallback(arrElementIdsToHideTemp, arrElementIdsToShowTemp, idUK);
	registerAndExecuteRegionLabelCallback();	
}

