// prevents conflicts
var $j = jQuery.noConflict();

/* ---------- start - jQuery ---------- */

$j(document).ready(function() {
	$j("a.linkTrack").click(function() {
		var jQthis = $j(this);
		var jQhref = $j(this).attr("href");
		var ok = ""; 
		$j.post(site_url + "ajax/link_track/", {
				target : escape(jQhref),
				referrer : escape(window.location)
			}, function(data) {
				var data = eval("(" + data + ")");
				if(data.result == 1) {
					//window.location = jQhref;
					ok = "ok";
				}
		});
		while(ok === "ok") {
			break;
		}
		return true;
	});
	
	// Rotating header on signed in Doctor
	$j("#lineRotateActive").newsTicker();
	
	// display userId id from email for registration
	$j("#userId").val($j("#email").val());
	$j("#email").blur(function() {
		var email = $j(this).val();		
		$j("#userId").val(email);
	});
	
	//disable input field on doctor search demo	
	$j(".disableDemoInput").find("#searchTerms").attr("readOnly","true");
	
	//Reset selects on doctor search demo	
	$j(".disableDemoSelect").find("#filterCity").attr("disabled","true");			
	
	$j(".disableDemoSelect").find("#filterLanguage").attr("disabled","true");	
	
	$j(".disableDemoSelect").find("#filterGender").attr("disabled","true");
	
	// patient evaluating a doctor
	/*$j("#check-box-1 div").click(function() {
		
		var check = $j(this).attr("id").split("-");

		// L‰‰ketieteellinen osaaminen oli tasokasta	
		if ($j(this).hasClass("doc")) {
			if ($j(this).hasClass("checked")) {
				$j(this).removeClass("checked");
				$j("#evalDoctorSkilled-" + check[1]).removeAttr("checked","checked");
			}
			else {			
				$j("#check-box-1 div.doc").removeClass("checked");
				$j(this).addClass("checked");
				$j("#evalDoctorSkilled-" + check[1]).attr("checked","checked");
			}
		}
		
		// Koin saaneeni erinomaista palvelua l‰‰k‰rilt‰ni
		if ($j(this).hasClass("pro")) {
			if ($j(this).hasClass("checked")) {
				$j(this).removeClass("checked");
				$j("#evalDoctorService-" + check[1]).removeAttr("checked","checked");
			}
			else {
				$j("#check-box-1 div.pro").removeClass("checked");
				$j(this).addClass("checked");
				$j("#evalDoctorService-" + check[1]).attr("checked","checked");
			}
		}
		
		// Sain l‰‰k‰rilt‰ni riitt‰v‰sti tietoa
		if ($j(this).hasClass("info")) {
			if ($j(this).hasClass("checked")) {
				$j(this).removeClass("checked");
				$j("#evalDoctorInformation-" + check[1]).removeAttr("checked","checked");
			}
			else {
				$j("#check-box-1 div.info").removeClass("checked");
				$j(this).addClass("checked");
				$j("#evalDoctorInformation-" + check[1]).attr("checked","checked");
			}
		}
		
		return false;
	});

	$j("#check-box-2 div").click(function() {

		var check = $j(this).attr("id").split("-");

		// Sain ajan l‰‰k‰rille helposti
		if ($j(this).hasClass("time")) {
			if ($j(this).hasClass("checked")) {
				$j(this).removeClass("checked");
				$j("#evalServiceProviderAppointment-" + check[1]).removeAttr("checked","checked");
			}
			else {
				$j("#check-box-2 div.time").removeClass("checked");
				$j(this).addClass("checked");
				$j("#evalServiceProviderAppointment-" + check[1]).attr("checked","checked");
			}
		}
		
		// Maksuasiat hoituivat sujuvasti
		if ($j(this).hasClass("reg")) {
			if ($j(this).hasClass("checked")) {
				$j(this).removeClass("checked");
				$j("#evalServiceProviderRegistration-" + check[1]).removeAttr("checked","checked");
			}
			else {
				$j("#check-box-2 div.reg").removeClass("checked");
				$j(this).addClass("checked");
				$j("#evalServiceProviderRegistration-" + check[1]).attr("checked","checked");
			}
		}
		
		// Olin eritt‰in tyytyv‰inen palveluun
		if ($j(this).hasClass("pay")) {
			if ($j(this).hasClass("checked")) {
				$j(this).removeClass("checked");
				$j("#evalServiceProviderPayment-" + check[1]).removeAttr("checked","checked");
			}
			else {
				$j("#check-box-2 div.pay").removeClass("checked");
				$j(this).addClass("checked");
				$j("#evalServiceProviderPayment-" + check[1]).attr("checked","checked");
			}
		}
		
		// Vaihtuva kysymys
		if ($j(this).hasClass("extra")) {
			if ($j(this).hasClass("checked")) {
				$j(this).removeClass("checked");
				$j("#evalServiceProviderExtraQuestionAnswer-" + check[1]).removeAttr("checked","checked");
			}
			else {
				$j("#check-box-2 div.extra").removeClass("checked");
				$j(this).addClass("checked");
				$j("#evalServiceProviderExtraQuestionAnswer-" + check[1]).attr("checked","checked");
			}
		}	

		return false;
	});*/

	// clears the input field when focused (include clicking)
	$j(".inputClear").focus(function() {
		$j(this).val("");
	});

	// clears all the textareas when focused for the first time
	$j("textarea").focus(function() {
		var word = $j(this).val();
		var text = word.substring(0,"Kirjoita".length);
		
		if(text == "Kirjoita") {
			$j(this).val("");
		}
	});
	
	// illnessList click-handler

	$j("#symptomAreaList a").click(function() {
		if ($j(this).hasClass("selected")) {
			$j('#symptomAreaList .symptomArea').removeClass('selected');
			$j('#symptomAreaId').val('');
		}
		else {
			$j('#symptomAreaList .symptomArea').removeClass('selected');
			$j(this).addClass("selected");
			var number = $j(this).attr("id").substr('symptomArea'.length);
			$j('#symptomAreaId').val(number);
		}
		return false;
	});
	
	$j("#symptomList a").click(function() {
		if ($j(this).hasClass("selected")) {
			$j('#symptomList .symptom').removeClass('selected');
			$j('#symptomId').val('');
		}
		else {
			$j('#symptomList .symptom').removeClass('selected');
			$j(this).addClass("selected");
			var number = $j(this).attr("id").substr('symptom'.length);
			$j('#symptomId').val(number);
		}
		return false;
	}); 


	// checkInfo click-handler
	$j("img.checkInfo").click(function() {
		if ($j(this).next("img").hasClass("hidden")) {
			$j(this).addClass("hidden");
			$j(this).next("img").removeClass("hidden");

		}
		else {
			$j(this).addClass("hidden");
			$j(this).prev("img").removeClass("hidden");

		}
		return false;
	}); 
	

	// clears the field when focused
	$j("#former-visitDate span input").focus(function() {
		if($j(this).val() == 'vvvv' || $j(this).val() == 'kk') {
			$j(this).val("");
		}
	});


	// evaluate doctor
	// clear firstName and lastName fields
	/*$j("#patientEvaluateDoctorContent #firstName, #patientEvaluateDoctorContent #lastName, #doctorEvaluateColleagueContent #firstName, #doctorEvaluateColleagueContent #lastName").focus(function() {

		var firstWord = $j("#firstName").val();
		var first = firstWord.substring(0,"Etunimi".length);
		
		var lastWord = $j("#lastName").val();
		var last = lastWord.substring(0,"Sukunimi".length);
		
		if(first == "Etunimi" && last == "Sukunimi") {
			$j("#firstName, #lastName").val("");
		}

	});*/

	// focuses the username input field
	if(!$j.browser.safari) {
		$j("div#login input#userName").focus();
	}

	// first ".field dl" in search results page 
	$j("div#editServiceProvider .field").find("dl:first").css("margin","0px");

	// doctor edit info
	// & search results
	
	$j("div.headerInfo").click(function() {
		var getParentId = $j(this).parent().find(".field:first").attr("id");
		var nextField = "#" + getParentId;

		var allIcons = $j(this).parent().parent().find("span.icon");
		var thisIcon = $j(this).parent().find("span.icon");

		if ($j(nextField).hasClass("hidden")) {
			// changes all to "+"			
			$j(allIcons).removeClass("opened").addClass("closed");
			// changes this to "-"
			$j(thisIcon).removeClass("closed").addClass("opened");

			// if multible field needed to see, comment below row out			
			$j("div.field").addClass("hidden");
			$j(nextField).removeClass("hidden");
			// removes the bottom border
			$j("div.headerInfo").css("border-bottom","none");
			// prevents jiggling
			$j(this).css("border-bottom","1px solid #249920");
		}
		else {
			// changes all to "+"
			$j(allIcons).removeClass("opened").addClass("closed");

			$j(nextField).addClass("hidden");
			$j(this).css("border-bottom","none");
		}
		return false;
	});


	/**
	 * Event handler for ajaxComplete event. Will be called when an AJAX call has been completed.
	 * Writing error handling in this function makes it easier to write functions making ajax calls as you need to only handle the succesful cases and leave everything else to this function
	 * 
	 * Parameters for the callback function:
	 * event - The event object (not that useful in this case)
	 * response - XMLHttpRequest object containing the server HTTP response data (use response.responseText to get the body)
	 * settings - Global jQuery ajax settings object (probably not needed, either)
	 */
	 
	$j("body").ajaxComplete(function(event, response, settings) {
		var data = eval("(" + response.responseText + ")");
		if (data.result == 0) {
			//Generic error handling takes place here (showing error messages etc)
			addMessage('error', data['errorMessage'], 0, 'body');
			//TODO it probably should be possible to override this error handling
			//console.log(data.errorMessage);
		}

	});	

	// adminPanel background hovering
	$j("div.adminPanel.useHover table.mainTable tr").hover(
		function() {
			mainTableOverOn($j(this));
		},
		function() {
			mainTableOverOff($j(this));
		}
	);


	// check the suckerfish.js & ie6.js
	// for helptext (toolclick) click-handler

	// so the link around the img won't do anyting
	$j("a.helpText").parent().click(function() {
		return false;
	});

	// Prevent free text from being submitted if it wasn't changed
	window.evalFreeTextDefault = $j('#evalDoctorFreeText').val();

	// limits the textarea#extra_text to 800 chars
	function textareaMaxLength(jqObj) {
		var text = $j(jqObj).val(); 
		var textLength = text.length;
		
		if(textLength >= 800) {
			var textVal = $j(jqObj).val(); 
			var dropRest = textVal.substr(0,800);
			
			$j(jqObj).val(dropRest);
			$j("div#editServiceProvider").find("span.maxMarkup").addClass("orange");	
			return false;
		}
		
		else {
			$j("div#editServiceProvider").find("span.maxMarkup").removeClass("orange");	
			return false;			
		}
		
	}

	// change function (for copying text)
	$j("textarea#extra_text").keyup(function() {
		textareaMaxLength($j(this));
	});

	// keydown function (for typing text)
	$j("textarea#extra_text").keydown(function() {
		textareaMaxLength($j(this));		
	});

	// for holding down the keys
	$j("textarea#extra_text").change(function() {
		textareaMaxLength($j(this));		
	});


	// counts all the elements (h5 & span) inside div#firstCol
	var elemCount = $j("div#firstCol").children().length;
	
	//alert(elemCount);

});

/* ----------- end - jQuery ----------- */

function toolclicks(e, obj, infoAttr, offset) {
	if($j('div.toolPopup').length > 0 ) {
		$j("div.toolPopup").remove();
	}
	else {
		var content = $j(obj).attr(infoAttr);
		var validated_content = new String(content);
		validated_content = validated_content.replace(/&lt;/g, "<");
		validated_content = validated_content.replace(/&gt;/g, ">");
			
		// remove any old helptexts
		$j("div.toolPopup").remove();

		// Keep the help text box on the page even when it's on the far right
		if(offset.left > 640) {
			var distance = (offset.left)-330;
		}
		else {
			var distance = (offset.left)+30;
		}
				
		// generate new helptext
		$j("body").append($j("<div class='toolPopup'><a href='#' class='close'>SULJE</a><p>"+validated_content+"</p></div>").css("top",offset.top + "px").css("left",distance + "px"));
		
		// if the helptext close-link is clicked, it will close
		$j("div.toolPopup a.close").click(function() {
			$j('div.toolPopup').remove();
			return false;
		});	
	}
} 

// mainTable tr mouse on
function mainTableOverOn(jQthis) {
	$j(jQthis).addClass("over");	
}

// mainTable tr mouse out
function mainTableOverOff(jQthis) {
	$j(jQthis).removeClass("over");	
}


/**
 * Adds a system message on the current page
 */
function addMessage(type, text, delay, where) {
	var temp = new Date;
	var messageId = temp.getMilliseconds();

	var message = '<li id="message'+messageId+'" class="'+type+'" style="display:none;">'+text+'</li>';

	if($j(where+' .systemMessages').length>0) {
		$j(where+'.systemMessages').append(message);
	}
	else {
		var message = '<ul id="systemMessages" class="systemMessages">'+message+'</ul>';
		$j(where).append(message);
	}

	var cmd = "$j('#message"+messageId+"').fadeIn(1000)";
	window.setTimeout(cmd, delay);
	
	return messageId;
}


function clearFoundDoctors() {
	$j('#foundDoctors').html('');
	$j("#foundDoctorsContainer").addClass('hidden');
	$j("#writeInInstructions").addClass('hidden');
}


/**
 * @param Boolean colleagues Boolean determining if the search is being done by a patient(not set or false) 
 * or a doctor(true).
 *
 */

function getDoctorsByName(colleagues) {
	$j('#foundDoctorCountContainer').removeClass('hidden');

	if(colleagues) {
		var functionName = 'get_colleagues_by_name';
		if($j('#former-otherServiceProvider').hasClass('hidden')) {
			var serviceProviderId = $j('#serviceProvider').val();
		}
		else {
			// If otherServiceProvider is visible, we're trying to search
			// with a write-in service provider name. That can't work.
			if($j('#otherServiceProvider').val()!='') {
				var serviceProviderId = -2;			
			}
			else {
				var serviceProviderId = -1;
			}
		}
	}
	else {
		var functionName = 'get_doctors_by_name';
		var serviceProviderId = $j('#serviceProvider').val();
		var specialityId = $j('#speciality').val();
	}

	var lastName = $j('#lastName').val();
	var firstName = $j('#firstName').val();
	var specialityId = $j('#speciality').val();		

	if(firstName == undefined || firstName=='') {
		firstName = '0';
	}
	if(lastName == undefined || lastName=='') {
		lastName = '0';
	}


	$j.post(site_url+"ajax/"+functionName+"/", {firstName: firstName, lastName: lastName, specialityId: specialityId, serviceProviderId: serviceProviderId},function(data) {
		data = eval("("+data+")");
		
		var doctorCount = data['additional']['count'];
		
		if (data['result']) {
			// On successful AJAX call, update #foundDoctors with the returned list and
			// update the count
			$j('#foundDoctorCount').html(""+doctorCount);
			
			if(doctorCount == 0) {
				$j('#refineDoctorSearch').addClass('hidden');
				$j("#foundDoctorsContainer").addClass('hidden');
				// only show newDoctor if both first and last name have been defined
				if(parseInt($j('#firstName').val().length) > 1 && parseInt($j('#lastName').val().length) > 1) {
					$j('#newDoctor').removeClass('hidden');
				}
				else {
					$j('#newDoctor').addClass('hidden');
				}
			}
			else if(doctorCount > 20){
				$j('#refineDoctorSearch').removeClass('hidden')
				$j("#foundDoctorsContainer").addClass('hidden');
				$j('#newDoctor').addClass('hidden');
			}
			else {
				//doctorCount >0 && <=20
				$j('#foundDoctors').html(data['output']);
				$j("#foundDoctorsContainer").removeClass('hidden');
				$j('#refineDoctorSearch').addClass('hidden');
				$j('#newDoctor').addClass('hidden');
			}
		}
	});
}


function toggleServiceProviderFilter(colleague) {
	if($j('#serviceProviderFilter').hasClass('hidden')) {
		$j('#serviceProviderFilter').removeClass('hidden');
	}
	else {
		$j('#serviceProviderFilter').addClass('hidden');
		$j('#serviceProviderCity').val(-1);
		populateServiceProviders(colleague);
	}
}


function selectDoctor(doctorId) {
	// Move the details of the selected doctor to the appropriate fields
	var doctorName = $j('#doctorName'+doctorId).html();
	$j('.selectedDoctorNameVisible').html(doctorName);
	$j('#selectedDoctorName').val(doctorName);
	$j('#selectedDoctorId').val(doctorId);

	// If the service provider filter was used, pre-select the corresponding city and sp:
	if($j('#serviceProvider').val() != -1) {
		$j('#visitServiceProviderCity').val($j('#serviceProviderCity').val());
		populateVisitServiceProviders(true);
	}
	else {
		populateVisitServiceProviders();	
	}

	// Show the form fields for the doctor visit details
	$j('#selectedDoctor').removeClass('hidden');
	$j('#evaluationDetails').removeClass('hidden');
	
	// Hide the elements used to find the doctor
	$j('#findDoctor').addClass('hidden');
	$j('#foundDoctorsContainer').addClass('hidden');
}


/**
 * Used to evaluate a doctor that can't be found in the system yet.
 *
 */
 
/*function selectNewDoctor() {
	if($j('#serviceProvider').val() == -1 || $j('#serviceProviderFilter').hasClass('hidden')) {
		$j('#writeInInstructions').removeClass('hidden');
		$j('#serviceProviderFilter').removeClass('hidden');
		return false;
	}
	
	var doctorName = $j('#firstName').val() + ' ' + $j('#lastName').val();
	$j('.selectedDoctorNameVisible').html(doctorName);
	$j('#selectedDoctorName').val(doctorName);
	$j('#selectedDoctorId').val(-1);
	
	// Since it's a new doctor, we populate the visitServiceProviderCity with all the cities
	$j.get(site_url+"ajax/get_municipalities_with_service_providers/0", function(data) {
		data = eval("("+data+")");
		
		if(data['result']) {
			$j('#visitServiceProviderCity').html(data['output']);

			// Set the value to the value of the filter select
			$j('#visitServiceProviderCity').val($j('#serviceProviderCity').val());

			// ..and get the content for the secondary based on that.
			populateVisitServiceProviders(true);
		}
	});


	// Show the form fields for the doctor visit details
	$j('#selectedDoctor').removeClass("hidden");
	$j('#evaluationDetails').removeClass("hidden");
	
	// Hide the elements used to find the doctor
	$j('#findDoctor').addClass("hidden");
	$j('#foundDoctorsContainer').addClass("hidden");
}*/


function selectColleague(doctorId) {
	// Move the details of the selected doctor to the appropriate fields
	var doctorName = $j('#doctorName'+doctorId).html();
	$j('#selectedDoctorNameVisible').html(doctorName);
	$j('#selectedDoctorName').val(doctorName);
	$j('#selectedDoctorId').val(doctorId);
	
	$j('#selectedDoctor').removeClass("hidden");
	$j('.evaluationInfo').removeClass("hidden");
	
	// Hide the elements used to find the doctor
	$j('#findDoctor').addClass("hidden");
	$j('#foundDoctorsContainer').addClass("hidden");
	
	// Gets previous / old colleague evaluation if this is a re-evaluation
	// and populates the #evaluation tr.
	$j.get(site_url+"ajax/get_colleague_evaluation/"+doctorId, function(data) {
		data = eval("("+data+")");
		
		if(data['result']) {
			$j('#evaluation').html(data['output']);
		}
	});
	
}


function selectNewColleague() {
	// First make sure that the mandatory Service Provider information is set:
	if($j('#serviceProvider').val() == -1 || $j('#serviceProviderFilter').hasClass('hidden')) {
		$j('#writeInInstructions').removeClass('hidden');
		$j('#serviceProviderFilter').removeClass('hidden');
		return false;
	}

	var doctorName = $j('#firstName').val() + ' ' + $j('#lastName').val();
	$j('#selectedDoctorNameVisible').html(doctorName);
	$j('#selectedDoctorName').val(doctorName);
	$j('#selectedDoctorId').val(-1);
	
	$j('#selectedDoctor').removeClass("hidden");
	$j('.evaluationInfo').removeClass("hidden");
	
	// Hide the elements used to find the doctor
	$j('#findDoctor').addClass("hidden");
	$j('#foundDoctorsContainer').addClass("hidden");
	
}


function unSelectDoctor() {
	getDoctorsByName();

	$j('.selectedDoctorName').html('');
	$j('#selectedDoctorName').val('');
	$j('#selectedDoctorId').val('');
	
	$j('#visitServiceProviderCity').val(-1);
	$j('#visitServiceProvider').val(-1);
	$j('#visitDate-month').val('kk');
	$j('#visitDate-year').val('vvvv');
	
	$j('.initiallyHidden').addClass("hidden");
	
	$j('#findDoctor').removeClass("hidden");
	$j('#foundDoctorsContainer').removeClass("hidden");
	
	// Clear any started evaluation
	$j('.pseudoCB').removeClass('checked');
	$j('.former-radio input').attr('checked', '');
}


function unSelectColleague() {
	$j('#selectedDoctorName').html('');
	$j('#selectedDoctorName').val('');
	$j('#selectedDoctorId').val('');
	
	$j('.evaluationInfo').addClass("hidden");
	$j('#selectedDoctor').addClass("hidden");
	
	$j('#findDoctor').removeClass("hidden");
	$j('#foundDoctorsContainer').addClass("hidden");
	
	// Clear any started evaluation
	$j('.pseudoCB').removeClass('checked');
	$j('.former-radio input').attr('checked', '');
}


function showOtherServiceProvider() {
	$j('#former-visitServiceProviderCity').addClass('hidden');
	$j('#former-visitServiceProvider').addClass('hidden');
	$j('#linkOtherServiceProvider').addClass('hidden');
	$j('#former-visitOtherServiceProviderCity').removeClass('hidden');
	$j('#former-visitOtherServiceProvider').removeClass('hidden');
	$j('#linkServiceProvider').removeClass('hidden');
	$j('#visitServiceProvider').val(-1);
	$j('#visitOtherServiceProviderCity').val($j('#visitServiceProviderCity').val());
	checkVisitDetails();
}


function hideOtherServiceProvider() {
	$j('#former-visitServiceProviderCity').removeClass('hidden');
	$j('#former-visitServiceProvider').removeClass('hidden');
	$j('#linkServiceProvider').addClass('hidden');
	$j('#former-visitOtherServiceProviderCity').addClass('hidden');
	$j('#former-visitOtherServiceProvider').addClass('hidden');
	$j('#linkOtherServiceProvider').removeClass('hidden');
	$j('#visitOtherServiceProvider').val('');
	$j('#visitServiceProviderCity').val($j('#visitOtherServiceProviderCity').val());
	checkVisitDetails();
}


function colleagueShowOtherServiceProvider() {
	$j('#former-serviceProviderCity').addClass('hidden');
	$j('#former-serviceProvider').addClass('hidden');
	$j('#linkOtherServiceProvider').addClass('hidden');
	$j('#former-otherServiceProviderCity').removeClass('hidden');
	$j('#former-otherServiceProvider').removeClass('hidden');
	$j('#linkServiceProvider').removeClass('hidden');
	$j('#visitServiceProvider').val(-1);
	checkVisitDetails();
}


function colleagueHideOtherServiceProvider() {
	$j('#former-serviceProviderCity').removeClass('hidden');
	$j('#former-serviceProvider').removeClass('hidden');
	$j('#linkServiceProvider').addClass('hidden');
	$j('#former-otherServiceProviderCity').addClass('hidden');
	$j('#former-otherServiceProvider').addClass('hidden');
	$j('#linkOtherServiceProvider').removeClass('hidden');
	$j('#visitOtherServiceProvider').val('');
	checkVisitDetails();
}


function doctorShowOtherServiceProvider(el) {
	var callerId = el.attr('id');
	var row = callerId.substr(1+callerId.lastIndexOf('-'));
	
	el.parent().parent().find('select').val('-1');
	el.parent().find('#former-workPlace-rowItem-'+row).html('');
	  
	$j('#switchPlace').removeClass('hidden');
	$j('#former-workPlaceFilter1-rowItem-'+row).addClass('hidden');
	$j('#former-workPlace-rowItem-'+row).addClass('hidden');
	$j('#linkOtherServiceProvider-rowItem-'+row).addClass('hidden');
	$j('#former-otherServiceProviderCity-rowItem-'+row).removeClass('hidden');
	$j('#former-otherServiceProvider-rowItem-'+row).removeClass('hidden');
	$j('#linkServiceProvider-rowItem-'+row).removeClass('hidden');
}


function doctorHideOtherServiceProvider(el) {
	var callerId = el.attr('id');
	var row = callerId.substr(1+callerId.lastIndexOf('-'));

	//$j('#otherServiceProviderCity-rowItem-'+row).val('-1');
	//$j('#otherServiceProvider-rowItem-'+row).val('');
	
	$j('#switchPlace').addClass('hidden');
	$j('#former-workPlaceFilter1-rowItem-'+row).removeClass('hidden');
	$j('#former-workPlace-rowItem-'+row).removeClass('hidden');
	$j('#linkServiceProvider-rowItem-'+row).addClass('hidden');
	$j('#former-otherServiceProviderCity-rowItem-'+row).addClass('hidden');
	$j('#former-otherServiceProvider-rowItem-'+row).addClass('hidden');
	$j('#linkOtherServiceProvider-rowItem-'+row).removeClass('hidden');
}


/**
 * Checks that the patient has filled up all the necessary fields in the visit details,
 * and shows the actual evaluation if so.
 *
 */
 
/*function checkVisitDetails() {
	var dateYear = parseInt($j('#visitDate-year').val());
	var dateMonth = parseInt(($j('#visitDate-month').val()), 10);
	var dateDay = parseInt($j('#visitDate-day').val());
	var visitSP = parseInt($j('#visitServiceProvider').val());
	var visitOtherSP = $j('#visitOtherServiceProvider').val();
	var visitOtherSPCity = parseInt($j('#visitOtherServiceProviderCity').val());
	
	// The time must be filled, and either the serviceProvider must be selected from the list, or entered in to the Other fields.
	if(dateYear && dateMonth && dateDay != -1 && ((visitSP != -1 && !isNaN(visitSP) && !$j('#former-visitServiceProvider').hasClass('hidden')) || (visitOtherSP != '' && visitOtherSPCity != -1))) {
	
		$j(".evaluationInfo").removeClass("hidden");
		
		// Move the service provider name to its place
		if($j('#former-visitOtherServiceProvider').hasClass('hidden')) {
			// Chosen from the list
			var number = $j('#visitServiceProvider').val();
			var name = $j('#visitServiceProvider option[value='+number+']').html();
			
			$j('#visitServiceProviderName').html(name);
		}
		else {
			// Write-in sp
			$j('#visitServiceProviderName').html($j('#visitOtherServiceProvider').val());
		}
		
	}
	else {
		$j(".evaluationInfo").addClass("hidden");
	}
	
	if ($j('#visitServiceProviderCity').val()==-1 && $j('#visitOtherServiceProviderCity').val()==-1){
		$j(".evaluationInfo").addClass("hidden");
	}
	
}*/


/**
 * Populates the symptom <select> with symptoms based on the selected symptom_area.
 *
 */
 
function populateSymptoms(el) {
	var number = el.attr('id').substring('symptom-rowArea-'.length);
	var symptomAreaId = $j('#'+el.attr('id')).val();
	
	$j.get(site_url+"ajax/get_symptoms_by_symptom_area/"+symptomAreaId, function(data) {
		data = eval("("+data+")");
		
		if(data['result']) {
			$j('#symptom-rowItem-'+number).html(data['output']);
		}
	});	
}


/**
 * Populates the symptom <select> with symptoms based on the selected symptom_area.
 *
 */
 
function populateSpecialSkills(el) {
	var number = el.attr('id').substring('symptom-rowArea-'.length);
	var symptomAreaId = $j('#'+el.attr('id')).val();
	
	$j.get(site_url+"ajax/get_special_skills_by_symptom_area/"+symptomAreaId, function(data) {
		data = eval("("+data+")");
		
		if(data['result']) {
			$j('#symptom-rowItem-'+number).html(data['output']);
		}
	});	
}


/**
 * @param showDoctor Boolean Are we calling this from showDoctor? If we are,
 * we need to pre-select an sp according to the filter, if the filter was 
 * used.
 *
 */
 
function populateVisitServiceProviders(showDoctor) {
	var municipalityId = $j('#visitServiceProviderCity').val();
	var selectedDoctorId = $j('#selectedDoctorId').val();
	// In case something was already selected, and the user just happens to click on the city select
	var preSelected = $j('#visitServiceProvider').val();
	
	if(selectedDoctorId == -1 || selectedDoctorId == '') {
		// No doctor selected.
		if(municipalityId == -1 || municipalityId == '') {
			// There's nothing to select yet, we need more data
			$j('#visitServiceProvider').html('<option value="-1"></option>');
		}
		else {
			// Otherwise just get all sp's in this selected city, drop Yksityisvastaanotto, since
			// SP is mandatory data with write-in doctors
			$j.get(site_url+"ajax/get_service_providers_by_municipality_id/"+municipalityId+"/1/1", function(data) {
				data = eval("("+data+")");
				
				if(data['result']) {
					$j('#visitServiceProvider').html(data['output']);
					if(showDoctor) {
						$j('#visitServiceProvider').val($j('#serviceProvider').val());
					}
					else {
						$j('#visitServiceProvider').val(preSelected);
					}				
					
					checkVisitDetails();
				}
			});				
		}		
	}
	else {
		// doctor has been selected
		if(municipalityId == -1 || municipalityId == '') {
			$j('#visitServiceProvider').html('<option value="-1"></option>');
		}
		else {
			// Otherwise just get all sp's in this selected city
			$j.get(site_url+"ajax/get_service_providers_by_municipality_id/"+municipalityId+"/0/1", function(data) {
				data = eval("("+data+")");
				
				if(data['result']) {
					$j('#visitServiceProvider').html(data['output']);
					if(showDoctor) {
						$j('#visitServiceProvider').val($j('#serviceProvider').val());
					}
					else {
						$j('#visitServiceProvider').val(preSelected);					
					}
					
					checkVisitDetails();
				}
			});
		}		
	}	
}


function populateServiceProviders(colleague) {
	var municipalityId = $j('#serviceProviderCity').val();

	$j.get(site_url+"ajax/get_service_providers_by_municipality_id/"+municipalityId+"/1/1", function(data) {
		data = eval("("+data+")");
		
		if(data['result']) {
			$j('#serviceProvider').html(data['output']);
			$j('#serviceProvider').val(-1);
			getDoctorsByName(colleague);
			if(!colleague) {
				checkVisitDetails();
			}
		}
	});				
		
}


/**
 * Populate workplaces by selected municipality
 * 
 */

function populateWorkPlaces(el) {
	var number = el.attr('id').substring('workPlaceFilter1-rowItem-'.length);
	var workPlaceCityId = $j('#'+el.attr('id')).val();

	var municipalityId = workPlaceCityId;
	
	if(workPlaceCityId != -1 || workPlaceCityId != '') {
		// Select service providers by city
		// The second parameter drops "yksityisvastaanotto"
		$j.get(site_url+"ajax/get_service_providers_by_municipality_id/"+workPlaceCityId+"/1/0", function(data) {
			data = eval("("+data+")");
			
			if(data['result']) {
				$j('#workPlace-rowItem-'+number).html(data['output']);
			}
			
		});	
	}
}


/* Functions for general use */

/**
 * Clones elements. Used with form elements where you can optionally have several 
 * copies of the same elements(doctor specialities or languages, for example).
 *
 * Expects to be called from a link that's inside a <p> that's inside a <div>
 * that's inside the element to be cloned. The calling <div> will be removed
 * from the clone, and replaced with an element for removing the clone.
 *
 * The containing div should have id "rowContainer-n"
 * 
 * Set second parameter 'noreset' to 1 if dropdown selection should be 
 * reseted in the clone.
 *
 */

function addRow(je, reset) {
	// get a handle for the "add" link
	var callerId = je.parent().parent().attr('id');

	// get the name of the group
	var groupName = callerId.substr(1+callerId.indexOf('-'));
	groupName = groupName.substr(0,groupName.indexOf('-'));

	// Find the right element to copy and get the html
	var html = je.parent().parent().parent().html();

	// get the largest number of a rowContainer
	var rowContainer = je.parent().parent().parent();
	var number = 0;
	rowContainer.parent().find('.rowContainer').each(function(){
		var id = $j(this).attr('id');
		var rowNumber = parseInt(id.substring((groupName+'-rowContainer-').length));
		if(rowNumber > number) {
			number = rowNumber;
		}
	});

	// Increment the number in the id's of the cloned elements
	number++;
	
	// TODO: This is legacy code, the elements should be named to work with the replaces below
	html = html.replace(/rowArea-([0-9]+)/g,"rowArea-"+number);
	html = html.replace(/rowArea\[([0-9]+)\]/g,"rowArea["+number+"]");
	html = html.replace(/rowItem-([0-9]+)/g,"rowItem-"+number);
	html = html.replace(/rowItem\[([0-9]+)\]/g,"rowItem["+number+"]");
	
	// TODO: Should rename all fields to work like this:
	// For example 'specialities-year-row[1]'
	html = html.replace(/-([a-zA-z]+)-row(-?)(\[?)([0-9]+)(\]?)/g,"-$1-row$2$3"+number+"$5");

	// fixes doubleSelect js
	html = html.replace(/rowItem_([0-9]+)/g,"rowItem_"+number);

	// Create the id and copy the class attributes for the new rowContainer
	var eId = groupName+'-rowContainer-'+number;
	var eClass = rowContainer.attr('class');

	// rename the "Lis√§√§" element
	html = html.replace(/\-addRowLink\-([0-9]+)/,"-removeRowLink-"+number);

	html = '<div id="'+eId+'" class="'+eClass+'">' + html + '</div>';
	je.parent().parent().parent().parent().append(html);

	
	// hack to fix ff2 textarea under selects after added selects
	var textVal = $j('#otherSpecialSkills').val();
	$j('#otherSpecialSkills').val(textVal+' ');
	$j('#otherSpecialSkills').val(textVal);

	// Change the "poista" link html
	$j('#'+'former-'+groupName+'-removeRowLink-'+number+' p').html('<a href="#" onclick="removeRow($j(this));return false;">Poista</a>');
	
	// Delete "main" flag(doctorEditInfo)
	$j('#'+'former-'+groupName+'-main-row-'+number+' p').html('');
	
	// reset selections in new row?
	if(reset) {
		// No selections in the new row
		$j('#'+groupName+'-rowItem-'+number+'-area').val(-1);
		$j('#'+groupName+'-rowItem-'+number).html('');
	
		// And with the new syntax, in specialities
		$j('#'+groupName+'-rowContainer-'+number+' select').val(-1);
		$j('#'+groupName+'-rowContainer-'+number+' input').val('');
		$j('#'+groupName+'-rowContainer-'+number+' .main p').html('');		
	
		// Special treatment for the doctorInfo form:
		$j('#otherServiceProviderCity-rowItem-'+number).val(-1);
		$j('#otherServiceProvider-rowItem-'+number).val('');
	}
	
}


function removeRow(je) {
	je.parent().parent().parent().remove();
}


/**
 * Using this keeps the user from posting the form by pressing enter in a text field
 *
 */
 
function mySubmit(formId) {
	window.maySubmit = true;
	
	// Prevents posting of free text feedback if nothing was entered
	if($j('#evalDoctorFreeText').val() == window.evalFreeTextDefault) {
		$j('#evalDoctorFreeText').val('');
	}
	
	$j('#'+formId).submit();
}


/*
 * Function for printing debug data from javascript code.
 * @param str (String) text to be printed
 * @param clear (boolean) Clear textarea?
 *
 * Recommended usage is to have a textarea with an id of 'debug'
 * on the page being debugged. If there is no textarea, alertboxes
 * are used to print the debug data.
 *
 */
 
function debug(str, clear) {
  if (document.getElementById('debug')) {
	if (clear) {
	  document.getElementById('debug').value = str +"\n";
	} else {
	  document.getElementById('debug').value += str + "\n";
	}
  }
}


var dt;
var dtt=0;
function debugTime(str, start) {
	var dt = window.dt;
	var temp = new Date();
	var ms = temp.valueOf();
	window.dt = ms;
	if(!start) {
		window.dtt = window.dtt+(0+ms-dt);
		debug(str+':'+window.dtt+' ('+(0+ms-dt)+')');
	}
	else {
		debug('',true);
		window.dtt=0;
	}

}

function clearAdminShowDoctors(){
	$j('#doctor').addClass('hidden');
	$j('#countDoctor').addClass('hidden');
	$j('#goBackLink').addClass('hidden');
}

function getAdminDoctors(attach, doctorId){
	var searchString = $j.trim($j('#searchString').val());
	$j('#goBackLink').removeClass('hidden');
	if (searchString.length >= 3){
		if (typeof attach != 'undefined') {
			$j.post(site_url+"ajax/search_doctors_admin/", {searchString: searchString, attach: attach, doctorId: doctorId}, function(data) {
			data = eval("("+data+")");
			$j('#countDoctor').removeClass('hidden');
			$j('#doctor').removeClass('hidden');
			$j('#countDoctor').html('');
			$j('#doctor').html('');
			$j('#countDoctor').html(data['additional']['msg']);
			if (data['additional']['count'] <= 80){
				$j('#doctor').html(data['output']);
			}
		});
		}
		else {
			$j.post(site_url+"ajax/search_doctors_admin/", {searchString: searchString}, function(data) {
			data = eval("("+data+")");
			$j('#countDoctor').removeClass('hidden');
			$j('#doctor').removeClass('hidden');
			$j('#countDoctor').html('');
			$j('#doctor').html('');
			$j('#countDoctor').html(data['additional']['msg']);
			if (data['additional']['count'] <= 80){
				$j('#doctor').html(data['output']);
			}
		});
		}
	}
}

function clearAdminShowUsers(){
	$j('#user').addClass('hidden');
	$j('#countUser').addClass('hidden');
	$j('#goBackLink').addClass('hidden');
}

function getAdminUsers(){
	var searchString = $j.trim($j('#searchString').val());
	$j('#goBackLink').removeClass('hidden');
	if (searchString.length >= 3){
		$j.post(site_url+"ajax/search_users_admin/", {searchString: searchString}, function(data) {
			data = eval("("+data+")");
			$j('#countUser').removeClass('hidden');
			$j('#user').removeClass('hidden');
			$j('#countUser').html('');
			$j('#user').html('');
			$j('#countUser').html(data['additional']['msg']);
			if (data['additional']['count'] <= 80){
				$j('#user').html(data['output']);
			}
		});
	}
//     else if (searchString.length < 3 && searchString.length >=1){
//         $j.post(site_url+"ajax/search_users_admin/", {searchString: searchString}, function(data) {
//             data = eval("("+data+")");
//             $j('#countUser').removeClass('hidden');
//             $j('#user').removeClass('hidden');
//             $j('#countUser').html('');
//             $j('#user').html('');
//             $j('#countUser').html(data['additional']['msg']);
//         });
//     }
}


//sp user functions
function clearAdminShowUsersServProv(){
	$j('#user').addClass('hidden');
	$j('#countUser').addClass('hidden');
	$j('#goBackLink').addClass('hidden');
}

function getAdminUsersServProv(){
	var searchString = $j.trim($j('#searchString').val());
	$j('#goBackLink').removeClass('hidden');
	if (searchString.length >= 3){
		$j.post(site_url+"ajax/search_users_admin/SP_USER", {searchString: searchString}, function(data) {
			data = eval("("+data+")");
			$j('#countUser').removeClass('hidden');
			$j('#user').removeClass('hidden');
			$j('#countUser').html('');
			$j('#user').html('');
			$j('#countUser').html(data['additional']['msg']);
			if (data['additional']['count'] <= 80){
				$j('#user').html(data['output']);
			}
		});
	}
}

function selectUserServProv(userId) {

	var userName = $j('#userName'+userId).html();
	$j('#selectedUserNameVisible').html(userName);

	$j('#selectedUserServProvId').val(userId);
	
	$j('#selectedUserNameVisible').removeClass("hidden");
	$j('#serviceProviderDIV').removeClass("hidden");
	$j('#submitButton').removeClass("hidden");
	
	// Hide the elements
	$j('#searchUserServProv').addClass("hidden");
	$j('#searchUserSerProvResult').addClass("hidden");
	$j('#countUser').html('');
	$j('#countUser').addClass("hidden");
	
}

function clearFoundUsersServProv(){
	$j('#countUser').addClass('hidden');
	$j('#searchUserSerProvResult').addClass("hidden");
}

function getUserServProvByName(){
	var searchString = $j.trim($j('#name').val());
	if (searchString.length >= 2){
		$j.post(site_url+"ajax/search_users_get_name_by_admin/SP", {searchString: searchString}, function(data) {
			data = eval("("+data+")");
			$j('#countUser').removeClass('hidden');
			$j('#searchUserSerProvResult').removeClass('hidden');
			$j('#countUser').html('');
			$j('#searchUserSerProvResult').html('');
			
			$j('#countUser').html(data['additional']['msg']);
			if (data['additional']['count'] <= 80){
				$j('#searchUserSerProvResult').html(data['output']);
			}
		});
	}
}
//end sp user functions

//IC user functions
function clearAdminShowUsersIC(){
	$j('#user').addClass('hidden');
	$j('#countUser').addClass('hidden');
	$j('#goBackLink').addClass('hidden');
}

function getAdminUsersIC(){
	var searchString = $j.trim($j('#searchString').val());
	$j('#goBackLink').removeClass('hidden');
	if (searchString.length >= 3){
		$j.post(site_url+"ajax/search_users_admin/IC_USER", {searchString: searchString}, function(data) {
			data = eval("("+data+")");
			$j('#countUser').removeClass('hidden');
			$j('#user').removeClass('hidden');
			$j('#countUser').html('');
			$j('#user').html('');
			$j('#countUser').html(data['additional']['msg']);
			if (data['additional']['count'] <= 80){
				$j('#user').html(data['output']);
			}
		});
	}
}

function clearPowerUserShowUsersIC(){
	$j('#user').addClass('hidden');
	$j('#countUser').addClass('hidden');
	$j('#goBackLink').addClass('hidden');
}

function getUsersICByPowerUser(){
	var searchString = $j.trim($j('#searchString').val());
	$j('#goBackLink').removeClass('hidden');
	if (searchString.length >= 3){
		$j.post(site_url+"ajax/search_users_insurance_company_by_power_user/", {searchString: searchString}, function(data) {
			data = eval("("+data+")");
			$j('#countUser').removeClass('hidden');
			$j('#user').removeClass('hidden');
			$j('#countUser').html('');
			$j('#user').html('');
			$j('#countUser').html(data['additional']['msg']);
			if (data['additional']['count'] <= 80){
				$j('#user').html(data['output']);
			}
		});
	}
}

function selectUserIC(userId) {

	var userName = $j('#userName'+userId).html();
	$j('#selectedUserNameVisible').html(userName);

	$j('#selectedUserICId').val(userId);
	
	$j('#selectedUserNameVisible').removeClass("hidden");
	$j('#insuranceCompany').removeClass("hidden");
	$j('#submitButton').removeClass("hidden");
	
	// Hide the elements
	$j('#searchUserIC').addClass("hidden");
	$j('#searchUserICResult').addClass("hidden");
	$j('#countUser').html('');
	$j('#countUser').addClass("hidden");
	
}

function clearFoundUsersIC(){
	$j('#countUser').addClass('hidden');
	$j('#searchUserICResult').addClass("hidden");
}

function getUserICByName(){
	var searchString = $j.trim($j('#name').val());
	if (searchString.length >= 2){
		$j.post(site_url+"ajax/search_users_get_name_by_admin/IC", {searchString: searchString}, function(data) {
			data = eval("("+data+")");
			$j('#countUser').removeClass('hidden');
			$j('#searchUserICResult').removeClass('hidden');
			$j('#countUser').html('');
			$j('#searchUserICResult').html('');
			
			$j('#countUser').html(data['additional']['msg']);
			if (data['additional']['count'] <= 80){
				$j('#searchUserICResult').html(data['output']);
			}
		});
	}
}
//end IC user functions

//check if extra question adding by SP is text or option type
function checkIfAnswerTextExtraQuestion() {
	if ($j("input#isAnswerText").attr("checked") == true) {
		$j("div#optionTextDiv").addClass("hidden");
	}
	else {
		$j("div#optionTextDiv").removeClass("hidden");
	}
}

//check SP reserve the question right when he/she add an extra question
function checkReservationExtraQuestion() {
	if ($j("#reserved").attr("checked") == false) {
		$j("#beginEndDateDiv").addClass("hidden");
	}
	else {
		$j("#beginEndDateDiv").removeClass("hidden");
	}
}

//search terms related functions
function clearFoundSearchTerms(){
	$j('#searchTermResults').addClass("hidden");
}

function getSearchTerms(){
	var searchString = $j.trim($j('#searchTerms').val());
	if (searchString.length >= 3){
		$j.post(site_url+"ajax/get_symptom_and_search_term", {searchString: searchString}, function(data) {
			data = eval("("+data+")");
			$j('#searchTermResults').removeClass('hidden');
			$j('#searchTermResults').html('');
			
			$j('#searchTermResults').html(data['output']);
		});
	}
}

function selectSearchTerm(term){
	$j('#searchTermResults').addClass("hidden");
	$j('#searchTerms').val(term);
}
//End search terms related functions