/// <reference path="Globals.js">
/// <reference path="validationFunctions.js">

var treatmentFieldMaxLength = 20000;

/******************
New Treatment 
*******************/
function submitTreatmentForm(saveAndNew)
{
    var form = $('EditTreatmentForm');
    var Error = {};
    Error.elementToFocus = null;
    Error.found = false;
    
    if(saveAndNew)
    {
        $('saveAndNew').value = "true";
    }
    
//    var title = form.getElementsBySelector('input[name=treatment.Title]')[0];
//    validateNotEmpty(title, 'TitleErrorContainer', "Please enter a title", Error);
    var description = form.getElementsBySelector('textarea[name=treatment.Description]')[0];
    validateLength(description, 'DescriptionErrorContainer', 0, treatmentFieldMaxLength, 
		"Description cannot exceed 20,000 characters long", Error); 
    
    if ($('pollQuestion')!=null)
    {
        if (surveyNeedValidation()) //$('PollContainer').style.display != 'none')
            validateSurvey("PollErrorContainer","One or more fields are empty",Error);
        else
            $("PollErrorContainer").hide();
    }
     
    gatherTreatmentData(form, Error);    
    
    validateLinks("LinksErrorContainer","Pleae enter a description ,a url and source, or clear both of them",Error);
   
	if(Error.found == false)
	{
	    var btSaveTreatment = $('btSaveTreatment');
        btSaveTreatment.onclick = function (){return false;};
        var btSaveAndNewTreatment = $('btSaveAndNewTreatment');
        btSaveAndNewTreatment.onclick = function (){return false;};
        showProgressBarDialog();
        form.submit();    
	}
	else
	{
        //Element.scrollTo('pageTop');
        if(Error.elementToFocus != null)
            Error.elementToFocus.focus();
    }
}

function surveyNeedValidation()
{
    var result = false;
    var question = $('pollQuestion');
    if (question.value!="") result = true;
    var options = $$('#PollDiv .caPollOption');
    options.each(function (option)
        {
            if (option.value!="") {
                result = true;
            } 
        }
    );    
    return result;
}

var freeText = "- Free Text -";
function gatherTreatmentData(form, Error) 
{
	var i = 0;
	
	var existingFreeTexts = $$('#FreeTextContainer .existingFreeText input[type=hidden]');
	if(existingFreeTexts.length > 0)
	{
	    i = 0;
        existingFreeTexts.each(function (existingFreeText) {
		    existingFreeText.name = 'existingFreeTextsIds['+ i +']';
		    ++i;
	    });
	}
	
    var newFreeTexts = $$('#FreeTextContainer .FreeText input[type=text]');
    i = 0;
    newFreeTexts.each(function (newFreeText) 
    {
		if(newFreeText.value != freeText && newFreeText.value.length > 0)
		{
		    newFreeText.name = 'freeTexts['+ i +']';
		    ++i;
		}
	});
	
	var newIngredients = $$('#IngredientsContainer input[type=hidden]');
    i = 0;
    newIngredients.each(function (newIngredient) {
		newIngredient.name = 'ingredientIds['+ i +']';
		++i;
	});
	
	
	var existingIngredients = $$('#IngredientsContainer .ExistingIngredientsContainer input[type=hidden]');
	if(existingIngredients.length > 0)
	{
	    i = 0;
        existingIngredients.each(function (existingIngredient) {
		    existingIngredient.name = 'existingIngredientIds['+ i +']';
		    ++i;
	    });
	}
	else
	{
	    validateIngredientSelected(Error, i, newIngredients);
	}	
	
	var newConditions = $$('#ConditionsContainer select');
	i = 0;
    newConditions.each(function (newCondition) {
		newCondition.name = 'conditionIds['+ i +']';
		++i;
	});
	
	var existingConditions = $$('#ConditionsContainer .ExistingConditionContainer input[type=hidden]');
	if(existingConditions.length > 0)
	{
	    i = 0;
        existingConditions.each(function (existingCondition) {
		    existingCondition.name = 'existingConditionIds['+ i +']';
		    ++i;
	    });
	}
	else
	{
	    validateItemSelected(Error, i, newConditions, 'ConditionErrorContainer', true);
	}

	var existingImageIds = $$('#AddPicturesContainer input[type=hidden]');
	i = 0;
	existingImageIds.each(function (existingImageId) {
		existingImageId.name = 'existingImageIds['+ i +']';
		++i;
	});
    var newImages = $$('#AddPicturesContainer input[type=file]');
	i = 0;
	newImages.each(function (newImage) {
        newImage.name = 'images['+ i +']';
		++i;
	});
	
	var existingLinksIds = $$('#RelatedLinksContainer .ExistingLinks input[type=hidden]');
	i = 0;
	existingLinksIds.each(function (existingLinksId) {
		existingLinksId.name += '['+ i +']';
		++i;
	});

	var newLinks = $$('#RelatedLinksContainer .RelatedLinks');
	i = 0;
	newLinks.each(function (newLink) {
	    var LinkTitle = newLink.down('.LinkTitle');
	    var LinkHref = newLink.down('.LinkHref');
	    var LinkSource = newLink.down('.LinkSource');
	    
	    if (LinkTitle.value == '' && LinkHref.value == '' && LinkSource.value == '') {
	        LinkTitle.name = '';
	        LinkHref.name = '';
	        LinkSource.name = '';
	    } 
	    else 
	    {
	        LinkTitle.name = 'linkTitles[' + i + ']';
		    LinkHref.name = 'linkHrefs[' + i + ']';
		    LinkSource.name = 'linkSources[' + i + ']';
		}
		++i;
	});
	
	
	var existingSpecificConditions = $$('#ConditionsContainer .ExistingSpecificConditionContainer input[type=hidden]');
	if(existingSpecificConditions.length > 0)
	{
	    i = 0;
        existingSpecificConditions.each(function (existingSpecificCondition) {
		    existingSpecificCondition.name = 'existingSpecificConditionIds['+ i +']';
		    ++i;
	    });
	}
	
	
	var newSpecificConditions = $$('#ConditionsContainer .SpecificConditionsSelect');
    i = 0;
	newSpecificConditions.each(function (newSpecificCondition) {
		//if(parseInt(newSpecificConditions.value) > 0)
			newSpecificCondition.name = 'specificConditionIds['+ i +']';
		++i;
	});
}

/******************
New Remedy 
*******************/
function submitRemedyForm(saveAndNew)
{
    var form = $('EditRemedyForm');
    var Error = {};
    Error.elementToFocus = null;
    Error.found = false;
    Error.id = 2;
	
	if(saveAndNew)
    {
        $('saveAndNew').value = "true";
    }
    
    var name = form.getElementsBySelector('input[name=remedyVersion.Name]')[0];
    var validName = validateNotEmpty(name, 'NameErrorContainer', "You must enter a name", Error);
    //check that name does not include:    ;/?:@&=+$,-
    //validName = validateDoesntContain(name,';/?:@&=+$,-', 'NameErrorContainer', ";/?:@&=+$,- are forbbiden", Error);
    gatherRemedyData(form);
    
    var fileExtensionPattern = /^(.+\.(jpg|gif|jpeg|png))?$/i;	
    var newImages = $$('#AddPicturesContainer input[type=file]');
	for(var i = 0; i < newImages.length; i++)
	{
		if(newImages[i].value.length > 0)
		{    
		    if(!validateRegEx(newImages[i], 'ImageErrorContainer', "Please provide a valid image extension (jpeg, jpg, gif, png)", fileExtensionPattern, Error))
		        break;
	    }
	}
    
    validateLinks("LinksErrorContainer","Pleae enter a title and a url, or clear both of them",Error);
    
    if(Error.found == false)
    {
        var btSaveRemedy = $('btSaveRemedy');
        btSaveRemedy.onclick = function (){return false;};
        var btSaveNewRemedy = $('btSaveNewRemedy');
        btSaveNewRemedy.onclick = function (){return false;};
        showProgressBarDialog();
	    form.submit();
	}
	else
	{
        if(Error.elementToFocus != null)
            Error.elementToFocus.focus();
   }
}



function gatherRemedyData(form) {
	var i = 0;

    // Images
	var existingImageIds = $$('#AddPicturesContainer input[type=hidden]');
	i = 0;
	existingImageIds.each(function (existingImageId) {
	    existingImageId.name = 'existingImageIds['+ i +']';
		++i;
	});

	var newImages = $$('#AddPicturesContainer input[type=file]');
	i = 0;
	newImages.each(function (newImage) {
		newImage.name = 'images['+ i +']';
		++i;
	});
	
	// Other Names
	var existingOtherNames = $$('#OtherNamesContainer input[type=hidden]');
	i = 0;
	existingOtherNames.each(function (existingOtherName) {
	    existingOtherName.name = 'existingOtherNames['+ i +']';
		++i;
	});
	
	var newOtherNames = $$('#OtherNamesContainer input[type=text]');
	i = 0;
	newOtherNames.each(function (newOtherName) {
		if(newOtherName.value.length > 0)
		{   
		    newOtherName.name = 'newOtherNames['+ i +']';
		    ++i;
		}
	});   
	
	// Links
	var existingLinksIds = $$('#RelatedLinksContainer .ExistingLinks input[type=hidden]');
	i = 0;
	existingLinksIds.each(function (existingLinksId) {
		existingLinksId.name += '['+ i +']';
		++i;
	});

	var newLinks = $$('#RelatedLinksContainer .RelatedLinks');
	i = 0;
	newLinks.each(function (newLink) {
	    var LinkTitle = newLink.down('.LinkTitle');
	    var LinkHref = newLink.down('.LinkHref');
	    
	    if (LinkTitle.value == '' && LinkHref.value == '') {
	        LinkTitle.name == '';
	        LinkHref.name == '';
	    } else {
	        LinkTitle.name = 'linkTitles[' + i + ']';
		    LinkHref.name = 'linkHrefs[' + i + ']';
		}
		++i;
	});
}

/******************
Image Gallery
*******************/
function showImage(imageId)
{
    var imageWidth = 125;
    var imageHeight = 80;
    var image = $('image');
    var anchor = $('imageExpand');
    anchor.href= siteRoot + "/Images/GetImage.aspx?imageId=" + imageId + "&imageSizeType=8";
    image.src= siteRoot + "/Images/GetImage.aspx?imageId=" + imageId + "&imageSizeType=6";
    $('ImgOuter').hide();	
}

var currImageIndex = 0;
function fnNextImage(imageCount)
{
    if(currImageIndex < (imageCount - 3))
        ++currImageIndex;
    else
    {
        return;
    }
    
    var ThumbsInner = $('ThumbsInner');
    var left = parseInt(ThumbsInner.getStyle('left'));
    
    if(currImageIndex >= imageCount - 3)
    {
        $('nextImage').addClassName('Disabled');       
    }
    $('prevImage').removeClassName('Disabled');    
    ThumbsInner.setStyle({ left: left - 40 + 'px' });
}

function fnPrevImage(imageCount)
{
    if(currImageIndex > 0)
        --currImageIndex;
    else
        return;
    
    var ThumbsInner = $('ThumbsInner');
    var left = parseInt(ThumbsInner.getStyle('left'));
    
    if(currImageIndex == 0)
    {
        $('prevImage').addClassName('Disabled');
    }
    $('nextImage').removeClassName('Disabled');       
    ThumbsInner.setStyle({ left: left + 40 + 'px' });
}


/******************
Picutres
*******************/
function addPictureDiv() {
    addPictureDivWithDuration(.5);
}

function addPictureDivWithDuration(duration) {
	var picDiv =	'<div style="display:none" class="AddPictureDiv">' +
						'<input class="AddPicture TextField" type="file" name="images" size="50" /> ' +
						'<span class="AddRemove">' +
						'<a href="javascript:addPictureDiv()">Add another picture</a> | ' +
						'<a href="javascript:void(0)" onclick="removeDiv(this);return false;">Remove</a>' +
					    '</span>' +
					'</div>';
    var picturesContainer = $('AddPicturesContainer');
    new Insertion.Bottom(picturesContainer, picDiv);
    var newPicture = picturesContainer.lastChild;
    showEffect(newPicture, duration);
    setTimeout(function() {
        newPicture.getElementsByTagName('input')[0].focus();
    }, duration * 1000);    

}

// new
function removeDiv(elm, cssRule) {
	if(cssRule)
		var div = $(elm).up(cssRule);
    else
		var div = $(elm).up().up();
	Effect.BlindUp(div, {
		duration: .5, 
		afterFinish: function(obj) {
			Element.remove(obj.element);
		}
	});
}

/******************
Links
*******************/
function addLinkDiv(options) {
    options.duration = 0.5;
    //callback, removeCallback
    addLinkDivWithDuration(options);
}

function  addLinkDivWithDuration(options) {
    
    var optionsStr = "";
    var first = true;
    for(var key in options)
    {
        optionsStr += (first == true ? "" : ",")  + key + ":" + options[key];
        first = false;
    }
    
    var addLinkMarkup = "javascript:addLinkDiv({" + optionsStr + "})";
     
    var removeLinkMarkup = options.removeCallback ? "removeLinkDiv(this, " + options.removeCallback + ")" : "removeLinkDiv(this)";
   
    var linkDivMarkup = "";
    if(!options.treatementRefernece)
    {
        linkDivMarkup = '<div style="display:none" class="RelatedLinksDiv">' +
							'<table class="RelatedLinks">' +
								'<tr>' +
									'<td>Description:</td>' +
									'<td><input type="text" name="linkTitles" class="LinkTitle CreateRemedyTextField RelatedLinksTextField TextField"  /></td>' +
									'<td></td>' +
								'</tr>' +
								'<tr>' +
									'<td>URL:</td>' +
									'<td><input type="text"  name="linkHrefs" class="LinkHref CreateRemedyTextField RelatedLinksTextField TextField" /></td>' +
									'<td><a href="' + addLinkMarkup + '">Add</a> | <a href="javascript:void(0)" onclick="' + removeLinkMarkup + ';return false;">Remove</a></td>' +
								'</tr>' +
							'</table>' +
						'</div>';
	}
	else
	{
	    linkDivMarkup = '<div class="RelatedLinksDiv">' +
							'<table class="RelatedLinks">' +
								'<tr>' +
									'<td>Link Description:</td>' +
									'<td><input type="text" class="LinkTitle CreateRemedyTextField RelatedLinksTextField TextField"  /></td>' +
									'<td></td>' +
								'</tr>' +
								'<tr>' +
									'<td>Link:</td>' +
									'<td><input type="text"  class="LinkHref CreateRemedyTextField RelatedLinksTextField TextField" /></td>' +
									'<td></td>' +
								'</tr>' +
								
								'<tr>' +
									'<td>Source\'s Name:<br /><span class="Small">(e.g. CNN.com)</span></td>' +
									'<td><input type="text" class="LinkSource CreateRemedyTextField RelatedLinksTextField TextField"  /></td>' +
									'<td><a href="' + addLinkMarkup + '">Add</a> | <a href="javascript:void(0)" onclick="' + removeLinkMarkup + ';return false;">Remove</a></td>' +
								'</tr>' +
								
							'</table>' +
							'</div>'; 
	}				
    
    var relatedLinksContainer = $('RelatedLinksContainer');
    new Insertion.Bottom(relatedLinksContainer, linkDivMarkup);
    var newLink = relatedLinksContainer.lastChild;
    showEffect(newLink, options.duration);
    
    setTimeout(function(){
        newLink.getElementsByTagName('input')[0].focus();
    }, options.duration * 1000); 
    if(options.callback)
    {
        options.callback();
    }       
}

function removeLinkDiv(elem, callback)
{
    //linksDivCount--;
    var link = elem;
    while (link!= null && link.className.indexOf("RelatedLinksDiv") == -1)
        link = getParent(link);
    Effect.BlindUp(link, {duration: .5, afterFinish:function(obj){Element.remove(obj.element);}});
    if(typeof callback == 'function')
    {
        callback();
    }   
}

/******************
Conditions Treated
*******************/
var conditionsCount = 1;

function addDiv(containerId, newDivClass, originalElemClass)
{
    if(originalElemClass == '.Condition' || originalElemClass == '.ConditionTreatedSelectOuter' )
        conditionsCount++;  

    var duration = 0.5;
    var cssRule = '#' + containerId + ' ' + originalElemClass;
    var originalElemArr = $$(cssRule);
    var originalElemInnerHtml = "";
    if(originalElemArr)
        originalElemInnerHtml = originalElemArr[0].innerHTML;
    
    var div = '<div class="' + newDivClass + '" style="display: none">' + originalElemInnerHtml + 
    '| <a href="javascript:void(0)" onclick="removeDiv(this, \''+ originalElemClass + '\');return false;">Remove</a>' +
    '</div>';
    var container = $(containerId);
    new Insertion.Bottom(container, div);
    var newDiv = container.lastChild;
    showEffect(newDiv, duration);
    setTimeout(function(){
        newDiv.getElementsByTagName('select')[0].focus();
    }, duration * 1000);    
}

function addCondition(originalElemClass, containerId)
{
    if(originalElemClass == '.Condition' || originalElemClass == '.ConditionTreatedSelectOuter' )
        conditionsCount++;    
    addConditionWithDuration(originalElemClass, .5, containerId);
}

var secificConditionComboCount = 0;
function  addConditionWithDuration(originalElemClass, duration, containerId)
{
    secificConditionComboCount++;
    var cssRule = '#' + containerId + ' ' + originalElemClass;
    var originalElemArr = $$(cssRule);
    var originalElemInnerHtml = "";
    if(originalElemArr)
        originalElemInnerHtml = originalElemArr[0].innerHTML;
    
    originalElemInnerHtml = originalElemInnerHtml.replace(/'0'/, "'" + secificConditionComboCount + "'");
    var div = 
        '<div class="Condition" style="display: none">' + originalElemInnerHtml + 
            '<div id="SecificConditionComboContainer' + secificConditionComboCount + '" style="display: inline">' +
                '<select class="SpecificConditionsSelect"><option value="0">- Specific Conditions -</option></select>&nbsp;' +
            '</div>' +
            '<a href="javascript:addCondition(\'.ConditionTreatedSelectOuter\', \'' + containerId + '\')">Add</a> | ' +
            '<a href="javascript:void(0)" onclick="removeDiv(this, \'.Condition\');return false;">Remove</a>' + 
        '</div>';
	   
    var ConditionsContainer = $(containerId);
    new Insertion.Bottom(ConditionsContainer, div);
    var newDiv = ConditionsContainer.lastChild;
    showEffect(newDiv, duration);
    setTimeout(function(){
        newDiv.getElementsByTagName('select')[0].focus();
    }, duration * 1000);    
}

/******************
Other Names
*******************/
function validateRemedyNameExist(name, definitionId)
{
    if(name.value.length == 0)
        return;
    showProgressBar(name);
	var params = 'name=' + name.value + "&isAjax=true";
	if(definitionId)
	    params += "&definitionId=" + definitionId;
 	new Ajax.Request(fullSiteRoot + "/Ingredients/validateNameExist.aspx",
        {
            parameters: params,
            onFailure: function(t){
                showServiceMessage("Error. Please try again");
            },
            onSuccess: function(t){
            setTimeout( closeProgressBar, 200);   
				if(t.responseText != "NotExist")
				{
				        var div = "";
                        var ingredients = t.responseText.evalJSON();
                        for(var i = 0; i < ingredients.ingredientsExist.length; i++)
                        {
                            
                            div +=  
                                "<div class='AlignLeft'><a href='" + ingredients.ingredientsExist[i].path + "'>Click here to go to " + ingredients.ingredientsExist[i].name + "</a></div>";
                        }
                        showIngredientExist(div);
				}
            }
        });
}

var winIngredientExist = null;
function showIngredientExist(message, width, height)
{
    var winWidth = 500;
    var winHeight = 200;
    if(width)
        winWidth = width;
    if(height)
        winHeight= height;

    if(winIngredientExist == null)
    { 
        winIngredientExist = new Window
            ({className: "alphacube", 
            width:winWidth , height:winHeight, 
            title: 'Existing ingredients with the same name',
            showEffectOptions: {duration: showEffectDuration}, 
            hideEffectOptions: {duration: hideEffectDuration},
            destroyOnClose: false,
            recenterAuto:false, 
            resizable: false,
			minimizable: false,
      		maximizable: false }
            );
        
    }
    winIngredientExist.setHTMLContent(
        "<div style='padding: 10px 5px 0px 10px;'>" +
            "Please note the site already contains an ingredient with the name you chose (maybe it appears as a synonym to an existing ingredient)." + 
            "<br />Before you continue, " + 
            "please choose another name or edit the existing one so you won't be creating a duplicate. Thanks." +
        "</div>" +
        "<div style='text-align: center; padding: 10px 5px 5px 10px; height: 60px; overflow: auto;'>" 
            + message + 
        "</div>" + 
        "<div style='text-align: center; margin-top: 2px;'>" +
            "<a class='ButtonGreenSearch' href='#' style='width: 35px; margin: 0 auto;' onclick='closeIngredientsExist()'>Close</a>" + 
        "</div>");
   
    winIngredientExist.showCenter(); 
}


function closeIngredientsExist()
{
    if(winIngredientExist != null)
    {    
        winIngredientExist.destroy();
        winIngredientExist = null;
    }
}

function addOtherNameDiv(definitionId)
{
    addOtherNameWithDuration(.5, definitionId);
}

function addOtherNameWithDuration(duration, definitionId)
{
    var defId = definitionId || "";
    var defIdStr = definitionId ? "," +  definitionId : "";
    var div = "<div class='AddOtherNameDiv' style='display: none'>" + 
		"<input type='text' class='CreateRemedyTextField TextField' maxlength='80' onblur='validateRemedyNameExist(this" + defIdStr + ")' />" +
		"&nbsp;<a href='javascript:addOtherNameDiv(" + defId + ")'>Add</a> | " + 
        "<a href='javascript:void(0)' onclick='removeDiv(this, \".AddOtherNameDiv\");return false;'>Remove</a></div>";
    
    var OtherNamesContainer = $('OtherNamesContainer');
    new Insertion.Bottom(OtherNamesContainer, div);
    var newOtherName = OtherNamesContainer.lastChild;
    showEffect(newOtherName, duration);
    setTimeout(function(){
        newOtherName.getElementsByTagName('input')[0].focus();
    }, duration * 1000);    
}


/******************
Free Text
*******************/
function addFreeText()
{
    addFreeTextWithDuration(.5);
}

function  addFreeTextWithDuration(duration)
{
    var div = "<div class='FreeText' style='display: none'>" + 
		"<input type='text' class='FreeTextField TextField' value='" + freeText + "' onfocus='clearTextValue(this, \"" + freeText + "\")' onblur='addTextValue(this, \"" + freeText + "\")' />" +
		"&nbsp;<a href='javascript:addFreeText()'>Add</a> | " + 
        "<a href='javascript:void(0)' onclick='removeDiv(this, \".FreeText\");return false;'>Remove</a></div>";
    var FreeTextContainer = $('FreeTextContainer');
    new Insertion.Bottom(FreeTextContainer, div);
    var newFreeText = FreeTextContainer.lastChild;
    showEffect(newFreeText, duration);
    setTimeout(function(){
        newFreeText.getElementsByTagName('input')[0].focus();
    }, duration * 1000);    
}

function clearInputField(elemId)
{
    $(elemId).value = "";
}

function clearInputFields(elemIdsArr)
{
    elemIdsArr.each(function(elemId) 
    {
        $(elemId).value = "";
    });
    
}

/******************
SpecificConditions
*******************/
var specificConditionCount = 0;
function addSpecificCondition(specificConditionId, specificConditionName) 
{
    addSpecificConditionWithDuration(.8, specificConditionId, specificConditionName);
}

function  addSpecificConditionWithDuration(duration, specificConditionId, specificConditionName) 
{
    var divMarkup;
	
	if(specificConditionName)
	{
		divMarkup = 
                '<div class="Ingredient" style="display:none" >' +
                    '<input type="text" id="SpecificCondition' + specificConditionCount  + '" readOnly="readOnly" value="' + specificConditionName + '" class="IngredientTextField TextField" />&nbsp;' +
                    '<input type="hidden" id="SpecificConditionHidden' + specificConditionCount + '" value="' + specificConditionNameId + '" />' +
                    '<img src="' + siteRoot + '/Static/Images/Content/Treatment/EyeGlass.gif" onclick="openSpecificConditionNamePopup(' + specificConditionCount + ');" class="ImageButton" />&nbsp;' +
                    '<a href="javascript:addIngredient()">Add</a> | ' +
					'<a href="javascript:void(0)" onclick="removeIngredient(this);return false;">Remove</a>' +
                '</div>';
	}
	else
	{	
		divMarkup = 
                '<div class="Ingredient" style="display:none" >' +
                    '<input type="text" id="SpecificCondition' + specificConditionCount  + '" readOnly="readOnly" value="Click on the Eyeglass" class="IngredientTextField TextField" style="color: #969696;" />&nbsp;' +
                    '<input type="hidden" id="SpecificConditionHidden' + specificConditionCount + '" value="0" />' +
                    '<img src="' + siteRoot + '/Static/Images/Content/Treatment/EyeGlass.gif" onclick="openSpecificConditionNamePopup(' + specificConditionCount + ');" class="ImageButton" />&nbsp;' +
                    '<a href="javascript:addIngredient()">Add</a> | ' +
					'<a href="javascript:void(0)" onclick="removeIngredient(this);return false;">Remove</a>' +
                '</div>';
    }   
	
	var IngredientsContainer = $('IngredientsContainer');
    new Insertion.Bottom(IngredientsContainer, divMarkup);
    var newIngredient = IngredientsContainer.lastChild;
    showEffect(newIngredient, duration);
    setTimeout(function(){
        newIngredient.getElementsByTagName('input')[0].focus();
    }, duration * 1000 + 500);    
}

var winSpecificConditions = null;
function openSpecificConditionsPopup(textFieldId)
{
    var path = siteRoot + "/Conditions/SpecificConditionsForPopup.aspx?textFieldId=" + textFieldId;
    winSpecificConditions = new Window(
            {   className: "alphacube", 
                title: "Specific Conditions", 
                width:300, 
                height:400, 
                destroyOnClose: true, 
                recenterAuto:false,
                resizable: false,
		        minimizable: false,
      	        maximizable: false
            }
        ); 
    winSpecificConditions.setAjaxContent(path, {method: 'get'});
    winSpecificConditions.showCenter(); 
}

function fillSpecificCondition(specificConditionName, textFieldId, specificConditionId)
{
    var textField = $('SpecificCondition' + textFieldId);
    var hidden = $('SpecificConditionHidden' + textFieldId);
    hidden.value = specificConditionId;
    textField.value = specificConditionName;
    textField.setStyle({color: "#5F5F5F"});
    if(winSpecificConditions)
    {
        winSpecificConditions.destroy();
        winSpecificConditions = null;
    } 
}

/******************
Ingredients
*******************/
var ingredientsCount = 1;
var maxIngredients = 4;

function addIngredient(remedyId, remedyName) {
    
    ingredientsCount++;    
    addIngredientWithDuration(.8, remedyId, remedyName);
}

function  addIngredientWithDuration(duration, remedyId, remedyName) {
    var divMarkup;
	
	if(remedyName)
	{
		divMarkup = 
                '<div class="Ingredient" style="display:none" >' +
                    '<input type="text" id="Ingredient' + ingredientsCount + '" readOnly="readOnly" value="' + remedyName + '" class="IngredientTextField TextField" />&nbsp;' +
                    '<input type="hidden" id="RemedyHidden' + ingredientsCount + '" name="ingredientIds" value="' + remedyId + '" />' +
                    '<img src="' + siteRoot + '/Static/Images/Content/Treatment/EyeGlass.gif" onclick="openIngredientPopup(' + ingredientsCount + ');" class="ImageButton" />&nbsp;' +
                    '<a href="javascript:addIngredient()">Add</a> | ' +
					'<a href="javascript:void(0)" onclick="removeIngredient(this);return false;">Remove</a>' +
                '</div>';
	}
	else
	{	
		divMarkup = 
                '<div class="Ingredient" style="display:none" >' +
                    '<input type="text" id="Ingredient' + ingredientsCount + '" readOnly="readOnly" value="Click on the Eyeglass" class="IngredientTextField TextField" style="color: #969696;" />&nbsp;' +
                    '<input type="hidden" id="RemedyHidden' + ingredientsCount + '" name="ingredientIds" value="0" />' +
                    '<img src="' + siteRoot + '/Static/Images/Content/Treatment/EyeGlass.gif" onclick="openIngredientPopup(' + ingredientsCount + ');" class="ImageButton" />&nbsp;' +
                    '<a href="javascript:addIngredient()">Add</a> | ' +
					'<a href="javascript:void(0)" onclick="removeIngredient(this);return false;">Remove</a>' +
                '</div>';
    }           
            
    var IngredientsContainer = $('IngredientsContainer');
    new Insertion.Bottom(IngredientsContainer, divMarkup);
    var newIngredient = IngredientsContainer.lastChild;
    showEffect(newIngredient, duration);
    setTimeout(function(){
        newIngredient.getElementsByTagName('input')[0].focus();
    }, duration * 1000 + 500);    
}

function removeIngredient(elem) {
    ingredientsCount--;
    removeDiv(elem, '.Ingredient');
}

function getHerbByInitialsForPopup(textFieldId, search)
{
    new Ajax.Updater(
        {success: 'HerbsOuter'},
        siteRoot + "/Ingredients/HerbListForPopup.aspx", 
        {
            method: 'get', 
            parameters: { 
                'search': search,
                'textFieldId': textFieldId 
            },
            onFailure: reportError,
            onSuccess: function(t)
            {
            }
        });
}

var win = null;
function openIngredientPopup(textFieldId)
{
    var path = siteRoot + "/Ingredients/HerbsForPopup.aspx?textFieldId=" + textFieldId + "&search=a";
    win = new Window(
            {   className: "alphacube", 
                title: "Ingredients", 
                width:300, 
                height:400, 
                destroyOnClose: true, 
                recenterAuto:false,
                resizable: false,
		        minimizable: false,
      	        maximizable: false,
      	        zIndex: 1000
            }
        ); 
    win.setAjaxContent(path, {method: 'get'});
    win.showCenter(); 
    
    
}

/////////
function closeTreatmentsExist()
{
    if(winTreatmentsExist != null)
    {    
        winTreatmentsExist.destroy();
        winTreatmentsExist = null;
    }
}

var winTreatmentsExist = null;
function showTreatmentsExist(message, width, height)
{
    var winWidth = 500;
    var winHeight = 260;
    if(width)
        winWidth = width;
    if(height)
        winHeight= height;

    if(winTreatmentsExist == null)
    { 
        winTreatmentsExist = new Window
            ({className: "alphacube", 
            width:winWidth , height:winHeight, 
            title: 'Existing treatments with the same ingredient and specific condition',
            showEffectOptions: {duration: showEffectDuration}, 
            hideEffectOptions: {duration: hideEffectDuration},
            destroyOnClose: false,
            recenterAuto:false, 
            resizable: false,
			minimizable: false,
      		maximizable: false }
            );
        
    }
    winTreatmentsExist.setHTMLContent(
        "<div style='padding: 10px 5px 0px 10px;'>" +
            "Please note the site already contains a treatment for the same specific condition, " + 
            "using the same ingredients. Maybe it's the one you're planning to add? <br />Before you continue, " + 
            "please verify using the links below, you won't be creating a duplicate. If it's not, just click 'Close' and continue. Thanks." +
        "</div>" +
        "<div style='text-align: center; padding: 10px 5px 5px 10px; height: 100px; overflow: auto;'>" 
            + message + 
        "</div>" + 
        "<div style='text-align: center; margin-top: 20px;'>" +
            "<a class='ButtonGreenSearch' href='#' style='width: 35px; margin: 0 auto;' onclick='closeTreatmentsExist()'>Close</a>" + 
        "</div>");
   
    winTreatmentsExist.showCenter(); 
}

////////
function FillIngredientField(ingredientName, textFieldId, ingredientId)
{
    var ingredientName =  unescape(ingredientName);
    var textField = $('Ingredient' + textFieldId);
    var ingredientHidden = $('RemedyHidden' + textFieldId);
    ingredientHidden.value = ingredientId;
    textField.value = ingredientName;
    textField.setStyle({color: "#5F5F5F"});
    if(win)
    {
        win.destroy();
        win = null;
    } 
    checkSimilarTreatments();
}

function checkSimilarTreatments()
{
    var ingredientIds = "";
    var newIngredients = $$('#IngredientsContainer input[type=hidden]');
    var first = true;
    newIngredients.each(function (newIngredient) 
    {
		if(!first)
		{
		    ingredientIds += "," + newIngredient.value;
		}
		else
		{
		    first = false;
		    ingredientIds += newIngredient.value;
		}
	});
    
    var newSpecificConditions = $$('#ConditionsContainer .SpecificConditionsSelect');
    var specificConditionsIds = "";
    first = true;
    newSpecificConditions.each(function (newSpecificCondition) 
    {
   	    if(!first)
		{
		    specificConditionsIds += "," + newSpecificCondition.value;
		}
		else
		{
		    first = false;
		    specificConditionsIds += newSpecificCondition.value;
		}
	});
	
    var params= 'ingredientIds=' + ingredientIds + "&specificConditionsIds=" + specificConditionsIds + "&isAjax=true"; 			
 	new Ajax.Request(siteRoot + "/Treatments/IsExistWithSameIngredient.aspx",
        {
            parameters: params,          
            onFailure: function(t){
                showServiceMessage("Error. Please try again");
            },
            onSuccess: function(t)
            {
                if(t.responseText.length > 0)
                {
                   
                    var treatmentsDiv = "";
                    var treatments = t.responseText.evalJSON();
                    for(var i = 0; i < treatments.treatmentList.length; i++)
                    {
                        treatmentsDiv +=  
                            "<div style='text-align: left; margin-bottom: 5px'>" +
                                "<a target='_blank' href='" + fullSiteRoot  + "/Treatments/View.aspx?id=" + 
                                treatments.treatmentList[i].Id + "'>" + treatments.treatmentList[i].Title + 
                                "</a></div>";
                    }
                    showTreatmentsExist(treatmentsDiv);
                }				
            }
        });
}

/******************
Ratings
*******************/

function onFailure(r, mustAllowCookieText, alreadyText)
{
    if(r.responseText == alreadyText)
        showServiceMessage("Your vote is already counted.");
    else if(r.responseText == "MustAllowCookie")
        showServiceMessage("You must allow cookies " + mustAllowCookieText);
    else if(r.responseText == "signin") 
		showLoginPopup({ registeredOnly : true });
	else
        alert('Due to some network problems, the operation could not be completed. Please retry in a few minutes');
            
}

function rate(star, i) {
    var stars = findParentWithClass(star, "Stars");
    var id = stars.getAttribute('id');
    new Ajax.Updater(
        { success: stars },
        fullSiteRoot + '/Treatments/Rate.aspx', 
        {
            evalScripts: true, 
            parameters: "id=" + id + "&rating=" + i + "&isAjax=true",
            onFailure : function(r) 
            {
                onFailure(r, "to rate a treatment", "AlreadyRated");
            } 
        }); 
}

function rateYourRating(star, i, treatmentId) {
    var stars = $("" + treatmentId);
    var id = stars.getAttribute('id');
    var starsYourRating = $("YourRating" + treatmentId);
    var idYourRating = starsYourRating.getAttribute('id');
    new Ajax.Updater(
        { success: 'StarsOuter' },
        fullSiteRoot + '/Treatments/Rate.aspx', 
        {
            evalScripts: true, 
            parameters: "id=" + id + "&rating=" + i + "&isAjax=true" + "&renderYourRating=true",
            onFailure : function(r) 
            {
                onFailure(r, "to rate a treatment", "AlreadyRated");
            } 
        }); 
}

////
//function helpedMe(id) 
//{
//    updateContent({containerId: 'HelpedMeCount' + id, path: '/Treatments/HelpedMe.aspx', evalScripts: true, parameters: "id=" + id + "&isAjax=true" , 
//    onFailure: function(r) 
//            {
//              onFailure(r, "for adding your vote", "AlreadyHelpedMe");                } 
//    });
//}
////

function helpedMe(id) {
    new Ajax.Updater(
        { success: 'HelpedMeCount' + id },
        fullSiteRoot + '/Treatments/HelpedMe.aspx', 
        {
            evalScripts: true, 
            parameters: "id=" + id + "&isAjax=true",
            onFailure : function(r) 
            {
                onFailure(r, "for adding your vote", "AlreadyHelpedMe");    
            } 
        }); 
}

var winInappropriate = null;
function openInappropriatePopup(title, signed)
{
    var height = 270;
    var width = 300;
    if(!signed)
    {
        height = 430;
        width = 350;
    }

    if(winInappropriate == null)
    { 
        winInappropriate = new Window
        ({className: "alphacube", 
        title: "Inappropriate " + title, 
        width:width, height:height, 
        destroyOnClose: false,
        recenterAuto:false,
		resizable: false,
		minimizable: false,
      	maximizable: false});
        winInappropriate.setContent('MarkInappropriate');  
    }
    
    var remark = $('remark');
    remark.value = "";
    winInappropriate.showCenter(); 
}

function closeInappropriatePopup()
{
    if(winInappropriate != null)
    {    
        var markInappropriate = $('MarkInappropriate');
        markInappropriate.style.display = "none";
        winInappropriate.destroy();
        winInappropriate = null;
    }
}

function submitMarkInappropriate(signedIn)
{
    var form = $('MarkInappropriateForm');
    var Error = {};
    Error.elementToFocus = null;
    Error.found = false;
    
    if(signedIn != "SignedIn")
    {    
        var name = form.getElementsBySelector('input[id=MarkInappropriateName]')[0];
        validateNotEmpty(name, 'MarkInappropriateNameErrorContainer', "You must fill in your name", Error);
        var email = form.getElementsBySelector('input[id=MarkInappropriateEmail]')[0];
        validateEmail(email, 'MarkInappropriateEmailErrorContainer', "Incorrect or incomplete email address", Error);
        validateLength($('feedbackCaptcha'), 'feedbackCaptchErrorContainer', 4, 4, "Please enter the code shown in the image", Error );
    
    }
    
    var remark = form.getElementsBySelector('textarea[id=remark]')[0];
    validateNotEmpty(remark, 'MarkInappropriateRemarkErrorContainer', "You must fill in the reason", Error);
    
    if(Error.found == false)
    {
        form.request(
            {
                onFailure: function(t){
                    alert(t.responseText);
                },
                onSuccess: function(t){
                    if(t.responseText != "ERROR")
                    {
                        if(winInappropriate)
                        {
                            winInappropriate.hide();
                            showServiceMessage("Your message has been sent successfully.");
                        }
                    }
                    else
                    {
                        if(winInappropriate)
                        {
                            winInappropriate.hide();
                        }
                        showServiceMessage("There was an error. Please try again");
                    } 
                }
            });
    }
    else
	{
        if(Error.elementToFocus != null)
            Error.elementToFocus.focus();
    }
}

var winSendToFriend = null;
function openSendToFriendPopup(title)
{
    if(winSendToFriend == null)
    { 
        winSendToFriend = new Window
            ({className: "alphacube", 
            title: "Send " + title, 
            width:300, height:370, 
            destroyOnClose: false,
            recenterAuto:false,
			resizable: false,
			minimizable: false,
      		maximizable: false}
            );
        
        winSendToFriend.setContent('SendToFriend');   
    }
    winSendToFriend.showCenter(); 
}

var winInviteFriend = null;
function openInviteFriendPopup()
{
    //openInviteFriendsWindow();
    if(winInviteFriend == null)
    { 
        winInviteFriend = new Window
            ({className: "alphacube", 
            title: "Invite a Friend", 
            width:345, height:380, 
            destroyOnClose: false,
            recenterAuto:false,
			resizable: false,
			minimizable: false,
      		maximizable: false,
      		zIndex: 1100}
            );
        
        winInviteFriend.setContent('InviteFriend');   
    }
    winInviteFriend.showCenter(); 
}

var winInvitationPreview = null;
function openInvitationPreviewPopup()
{
    if(winInvitationPreview == null)
    { 
        winInvitationPreview = new Window
            ({className: "alphacube", 
            title: "Invitation", 
            width:450, height:360, 
            destroyOnClose: false,
            recenterAuto:false,
			resizable: false,
			minimizable: false,
      		maximizable: false}
            );
        
        winInvitationPreview.setContent('Invitation');   
    }
    winInvitationPreview.showCenter(); 
}

var winSendTreatmentPreview = null;
function openSendTreatmentPreviewPopup()
{
    if(winSendTreatmentPreview == null)
    { 
        winSendTreatmentPreview = new Window
            ({className: "alphacube", 
            title: "Send Treatment Preview", 
            width:450, height:160, 
            destroyOnClose: false,
            recenterAuto:false,
			resizable: false,
			minimizable: false,
      		maximizable: false}
            );
        
        winSendTreatmentPreview.setContent('SendTreatmentToFriend');   
    }
    winSendTreatmentPreview.showCenter(); 
}

var winSendRemedyPreview = null;
function openSendRemedyPreviewPopup()
{
    if(winSendRemedyPreview == null)
    { 
        winSendRemedyPreview = new Window
            ({className: "alphacube", 
            title: "Send Ingredient Preview", 
            width:450, height:160, 
            destroyOnClose: false,
            recenterAuto:false,
			resizable: false,
			minimizable: false,
      		maximizable: false}
            );
        
        winSendRemedyPreview.setContent('SendRemedyToFriend');   
    }
    winSendRemedyPreview.showCenter(); 
}

function showSendToFriendDiv(divId)
{
    new Effect.toggle(divId, "blind", {duration: 0.9});
}

function successSendToFriends(form, signedIn)
{
    var form = $(form);
    var Error = {};
    Error.elementToFocus = null;
    Error.found = false;
    var atLeastOneEamil = false;
        
    if(signedIn != "SignedIn")
    {  
        var fromEmail = form.getElementsBySelector('input[id=fromEmail]')[0];
        validateEmail(fromEmail, 'SendToFriendFromEmailErrorContainer', "Incorrect or incomplete email address", Error);
    }
    
    var fromName = form.getElementsBySelector('input[id=fromName]')[0];
    validateNotEmpty(fromName, 'SendToFriendFromNameErrorContainer', "Please fill in your name", Error);
    
    var toName = null;
    var toEmail = null;
    for(var i = 1;i <= 4; i++)
    {
        toName = form.getElementsBySelector('input[id=toName' + i + ']')[0];
        toEmail = form.getElementsBySelector('input[id=toEmail' + i + ']')[0];
        if(toName.value.length > 0)
        {
            atLeastOneEamil = true;
            validateNotEmpty(toName, 'SendToFriendToNameErrorContainer' + i, "Please fill in a friend's name", Error);
            validateEmails(toEmail, 'SendToFriendToEmailErrorContainer'  + i, "Incorrect or incomplete email address", Error);
        }
        else if(toEmail.value.length > 0)
        {
            atLeastOneEamil = true;
            validateEmails(toEmail, 'SendToFriendToEmailErrorContainer'  + i, "Incorrect or incomplete email address", Error);
        }
        else
        {
            var sendToFriendToNameErrorContaine = $('SendToFriendToNameErrorContainer' + i);
            var sendToFriendToEmailErrorContainer = $('SendToFriendToEmailErrorContainer' + i);
            sendToFriendToNameErrorContaine.hide();
            sendToFriendToEmailErrorContainer.hide();
        }
    }
    
    var multipleEmails = form.getElementsBySelector('input[id=MultipleEmails]')[0];
    if(multipleEmails.value.length > 0)
        validateEmails(multipleEmails, 'MultipleEmailsErrorContainer', "Incorrect or incomplete email address", Error);
    
    if(Error.found == false)
	{
	    if(atLeastOneEamil || multipleEmails.value.length > 0) 
            form.submit();
        else
        {    
            var errorContainer = $('MultipleEmailsErrorContainer');
            errorContainer.innerHTML = "Please enter at least one email adress";
            errorContainer.show();
        }
    }
    else
    {
        if(Error.elementToFocus != null)
            Error.elementToFocus.focus();
    }
}

// send a treatment's or a remedy's link to a friend asynchronously
function sendToFriends(form, signedIn)
{
    var form = $(form);
    var Error = {};
    Error.elementToFocus = null;
    Error.found = false;
        
    if(signedIn != "SignedIn")
    {  
        var fromEmail = form.getElementsBySelector('input[id=fromEmail]')[0];
        validateEmail(fromEmail, 'SendToFriendFromEmailErrorContainer', "Incorrect or incomplete email address", Error);
    }
    
    var fromName = form.getElementsBySelector('input[id=fromName]')[0];
    validateNotEmpty(fromName, 'SendToFriendFromNameErrorContainer', "Please fill in your name", Error);
    var toName = form.getElementsBySelector('input[id=toName]')[0];
    validateNotEmpty(toName, 'SendToFriendToNameErrorContainer', "Please fill in a friend's name", Error);
    var toEmail = form.getElementsBySelector('input[id=SendToFriendToEmail]')[0];
    validateEmails(toEmail, 'SendToFriendToEmailErrorContainer', "Incorrect or incomplete email address", Error);
    
    if(Error.found == false)
	{
        form.request( 
        {
            onFailure: function(t){
                alert(t.responseText);
            },
            onSuccess: function(t){
                form.reset();
                var sendToFriendOuter = $('SendToFriendOuter');
                sendToFriendOuter.hide();
                showServiceMessage(t.responseText + " was successfully sent to your friend");                
            }
        });
    }
    else
    {
        if(Error.elementToFocus != null)
            Error.elementToFocus.focus();
    }
}

function rateComment(rating, id, commentIndex)
{
    var ContainerId = 'Comment' + id; 
    new Ajax.Updater(
        { success: ContainerId},
        fullSiteRoot + '/Treatments/RateComment.aspx', 
        {
            evalScripts: true, 
            parameters: "id=" + id + "&rating=" + rating + "&commentIndex=" + commentIndex +"&isAjax=true",
            onFailure : function(r) 
            {
				if(r.responseText == "MustAllowCookie")
                    showServiceMessage("You Must Allow Cookies to Rate a Comment");
				else
				    showServiceMessage(r.responseText);
				//alert('Due to some network problems, the operation could not be completed. Please retry in a few minutes');
            } 
        }); 
}

var stopComment = false;
// add a comment asynchronously and render it at the bottom of the div
function addComment(formId, aButton) 
{   
    if(stopComment)
        return;

	var Error = {};
    Error.elementToFocus = null;
    Error.found = false;
	
	var form = $(formId);
	var author = form.getElementsBySelector('input[name=author]')[0];
    if(author)
		validateNotEmpty(author, 'AuthorErrorContainer', "You must enter your name", Error);
    var content = form.getElementsBySelector('textarea[name=comment.Content]')[0];
    validateLength(content, 'ContentErrorContainer', 1, 2000, 
		"Content cannot be empty or exceed 2,000 characters long", Error); 
    
//    var email = form.getElementsBySelector('input[name=email]')[0];
//    if(email)
//        validateEmail(email, 'EmailErrorContainer', "Incorrect or incomplete email address", Error);
//		//validateNotEmpty(email, 'EmailErrorContainer', "You must enter your email", Error);
//	var captcha = form.getElementsBySelector('input[id=Captcha]')[0];
//	if(captcha)
//		validateNotEmpty(captcha, 'CaptchaErrorContainer', "You must enter the code above", Error);  
//	
	var errorMessage = $('ErrorMessage');
    errorMessage.innerHTML = "";
                
    var commentsCount = $('commentsCount');
    var originalCommentsCount = $('originalCommentsCount');
    commentsCount.value = "" + (parseInt(originalCommentsCount.value) + 1);
    originalCommentsCount.value = commentsCount.value;
    	
	if(Error.found == false)
	{
		stopComment = true;
		$(form).request( 
	    {
	        onComplete: function(t) 
	        {
	            stopComment = false;
	            if(t.responseText.indexOf('fail') == 0)
	            { 
					var errorMessageContainers = [$('AuthorErrorContainer'), 
						$('ContentErrorContainer')];
					for(var i = 0; i < errorMessageContainers.length; i++)
						if(errorMessageContainers[i])
							errorMessageContainers[i].hide();
				
					var separator = ":";
					var errorMessages = t.responseText.split(separator);
					originalCommentsCount.value = originalCommentsCount.value - 1;
					errorMessage.innerHTML = "Please fill in all the fields (one or more field are empty or contains a banned URL)";
	            	errorMessage.show();
					
					for(var i = 1; i < errorMessages.length; i++)
					{
						var errorContainer = $(errorMessages[i]);
						errorContainer.show();
					}					
				}
	            else
	            {
	                $(form).reset();
					var errorMessageContainers = [$('AuthorErrorContainer'), 
						$('ContentErrorContainer')];
					for(var i = 0; i < errorMessageContainers.length; i++)
					{
						if(errorMessageContainers[i])
							errorMessageContainers[i].hide();
	                }
	                
					new Insertion.Bottom($('CommentsInner'), t.responseText);
					
					
					var addCommentContainer = $('AddComment');
                    if(addCommentContainer.style.display != "none")
                        new Effect.BlindUp(addCommentContainer, {duration: 0.9});
	                
	                
					var noCommnetsYet = $('NoCommnetsYet');
					if(noCommnetsYet.style.display != "none")
						noCommnetsYet.hide(); 
					
					var addYourComment = $('AddYourComment');
					if(addYourComment == null)
					{	
					    var div = '<div id="AddYourComment" class="Right"><a href="javascript:toggleContent({id: \'AddComment\', effectName: \'blind\'})">Add your comment</a></div>';
					    new Insertion.Top($('Comments'), div);	
	                }
	            }    	            
	        }
	    });
	}
	else
	{
		originalCommentsCount.value = originalCommentsCount.value - 1;
        if(Error.elementToFocus != null)
            Error.elementToFocus.focus();
		return false;
    }
}
function addHelpedComment(formId, id) {
    if (stopComment)
        return;

    var Error = {};
    Error.elementToFocus = null;
    Error.found = false;

    var form = $(formId);
    var author = form.getElementsBySelector('input[name=author]')[0];
    if (author)
        validateNotEmpty(author, 'AuthorErrorContainer', "You must enter your name", Error);
    var content = form.getElementsBySelector('textarea[name=comment.Content]')[0];
    validateLength(content, 'ContentErrorContainer', 1, 2000,
		"Content cannot be empty or exceed 2,000 characters long", Error);

    var commentsCount = $('commentsCount');
    var originalCommentsCount = $('originalCommentsCount');

    if (Error.found == false) {
        stopComment = true;
        $(form).request(
	    {
	        onComplete: function(t) {
	            stopComment = false;
	            if (t.responseText.indexOf('fail') == 0) {
	                var errorMessageContainers = [$('AuthorErrorContainer'),
						$('ContentErrorContainer')];
	                for (var i = 0; i < errorMessageContainers.length; i++)
	                    if (errorMessageContainers[i])
	                    errorMessageContainers[i].hide();

	                var separator = ":";
	                var errorMessages = t.responseText.split(separator);
	                originalCommentsCount.value = originalCommentsCount.value - 1;
	                //errorMessage.innerHTML = "Please fill in all the fields";
	                //errorMessage.show();

	                for (var i = 1; i < errorMessages.length; i++) {
	                    var errorContainer = $(errorMessages[i]);
	                    errorContainer.show();
	                }
	            }
	            else {
	                //$(form).reset();
	                CancelHelpedMeComment(id);
	                var errorMessageContainers = [$('AuthorErrorContainer'),
						$('ContentErrorContainer')];
	                for (var i = 0; i < errorMessageContainers.length; i++) {
	                    if (errorMessageContainers[i])
	                        errorMessageContainers[i].hide();
	                }

	                new Insertion.Bottom($('CommentsInner'), t.responseText);

	                var addCommentContainer = $('HelpedComment' + id);
	                if (addCommentContainer.style.display != "none")
	                    new Effect.BlindUp(addCommentContainer, { duration: 0.9 });


	                var noCommnetsYet = $('NoCommnetsYet');
	                if (noCommnetsYet.style.display != "none")
	                    noCommnetsYet.hide();

	                var addYourComment = $('AddYourComment');
	                if (addYourComment == null) {
	                    var div = '<div id="AddYourComment" class="Right"><a href="javascript:toggleContent({id: \'AddComment\', effectName: \'blind\'})">Add your comment</a></div>';
	                    new Insertion.Top($('Comments'), div);
	                }
	            }
	        }
	    });
    }
    else {
        //originalCommentsCount.value = originalCommentsCount.value - 1;
        if (Error.elementToFocus != null)
            Error.elementToFocus.focus();
        return false;
    }
}

function areYouSureYouWantToGoBack(remedyDefId, remedyVerId)
{
    Dialog.confirm("Are You Sure You Want To Go Back?", 
      {
       width:300, 
       buttonClass: "myButtonClass",
       id: "GobackConfirmDialog",
       okLabel: "Yes", cancelLabel: "No",
       className: "alphacube",
       showEffectOptions: {duration: showEffectDuration}, 
       hideEffectOptions: {duration: hideEffectDuration},
       onCancel: function(win) {return false;},
       onOk: function(win) 
            {
                location.replace(fullSiteRoot + "/Ingredients/GoBackTo.aspx?remedyDefId=" + remedyDefId + "&remedyVerId=" + remedyVerId);
            }
      });
}

function youCantGoBack()
{
    Dialog.alert("We're sorry, but you can't go back because that ingredient version name or its other names already exist in another ingredient", 
      {
       width:400, 
       buttonClass: "myButtonClass",
       id: "GobackConfirmDialog",
       okLabel: "close",
       className: "alphacube",
       showEffectOptions: {duration: showEffectDuration}, 
       hideEffectOptions: {duration: hideEffectDuration},
       onOk: function(win) 
            {
                return true;
            }
      });
}

function resetFormDataWithConfirm(formId, elemetToFocusId, msg)
{
    if(!msg)
		msg = "";
	var html = "<div>" + msg + "</div>";
	Dialog.confirm(html, 
		{className:"alphacube", width:300, height:100,
		okLabel: "Yes", cancelLabel: "No",
		ok:function(win)
		{
			resetFormData(formId, elemetToFocusId);
			return true;
		}
		
  	});
}

function resetFormData(formId, elemetToFocusId)
{
    var form = $(formId);
    var elements = $$("#" + formId + " input[type=text]");
    for(var i = 0; i < elements.length; i++)
    {
        if (elements[i].id!="Name") elements[i].value = "";
    }
    elements = $$("#" + formId + " textarea");
    for(var i = 0; i < elements.length; i++)
    {
        elements[i].value = "";
    }
    elements = $$("#" + formId + " select");
    for(var i = 0; i < elements.length; i++)
    {
        elements[i].selectedIndex = 0;
    }
    elements = $$("#" + formId + " input[type=checkbox]");
    for(var i = 0; i < elements.length; i++)
    {
        elements[i].checked = false;
    }
    elements = $$("#" + formId + " input[type=file]");
    for(var i = 0; i < elements.length; i++)
    {
        elements[i].value = "";
    }
    Element.scrollTo('pageTop');
    var elemetToFocus = $(elemetToFocusId);
    elemetToFocus.focus();
}

function clearTextValue(inputField, str)
{
	if(inputField.value == str )
	{
		inputField.value = "";
		inputField.style.color = '#5F5F5F';
	}
}

function addTextValue(inputField, str)
{
	if(inputField.value == "" )
	{
		inputField.value = str;
		inputField.style.color = '#969696'; 
	}
}

function addNewRemedy()
{
    window.open(fullSiteRoot + "/Ingredients/Edit.aspx");
}

function populateSpecificConditions(conditionId, containerIdSuffix, doOnchange)
{
    var ContainerId = 'SecificConditionComboContainer' + containerIdSuffix; 
    new Ajax.Updater(
        { success: ContainerId},
        fullSiteRoot + '/Treatments/PopulateSpecificConditions.aspx', 
        {
            evalScripts: true, 
            parameters: "conditionId=" + conditionId + "&doOnchange=" + doOnchange + "&isAjax=true",
            onFailure : function(r) 
            {
				//if(r.responseText == "MustAllowCookie")
                //    showServiceMessage("You Must Allow Cookies to Rate a Comment");
				//else
				showServiceMessage(r.responseText);
				//alert('Due to some network problems, the operation could not be completed. Please retry in a few minutes');
            } 
        }); 
}

Event.observe(window, "load", showRate_load);
function showRate_load()
{
    var imgs = $$('#StarsOuter .YourRating img');
    if(imgs)
    {
        for(var i = 0; i < imgs.length; i++)
        {
            imgs[i].onmouseover = function()
            {
                var number = this.id.substring(13, 14);
                var treatmentId = this.id.substring(14);
                showRate(number, treatmentId, true);
            };
            imgs[i].onmouseout = function()
            {
                var number = this.id.substring(13, 14);
                var treatmentId = this.id.substring(14);
                showCurrentRate(number, treatmentId, true);
            };
        }
    }
    imgs = $$('#StarsOuter .Stars img');
    if(imgs)
    {
        for(var i = 0; i < imgs.length; i++)
        {
            imgs[i].onmouseover = function()
            {
                var number = this.id.substring(3, 4);
                var treatmentId = this.id.substring(4);
                showRate(number, treatmentId, true);
            };
            imgs[i].onmouseout = function()
            {
                var number = this.id.substring(3, 4);
                var treatmentId = this.id.substring(4);
                showCurrentRate(number, treatmentId, true);
            };
        }
    }
    imgs = $$('.Top .Stars img');
    if(imgs)
    {
        for(var i = 0; i < imgs.length; i++)
        {
            imgs[i].onmouseover = function()
            {
                var number = this.id.substring(3, 4);
                var treatmentId = this.id.substring(4);
                showRate(number, treatmentId, false);
            };
            imgs[i].onmouseout = function()
            {
                var number = this.id.substring(3, 4);
                var treatmentId = this.id.substring(4);
                showCurrentRate(number, treatmentId, false);
            };
        }
    }
}

function showRate(i, treatmentId, isYourRating)
{
    var ratingHeaders = new Array("bad", "so-so", "ok", "good", "excellent");
    
    for(var j=1; j <= i; j++)
    {
        if(isYourRating)
        {
            var imgYourRating = $('imgYourRating' + j + treatmentId);
            imgYourRating.src = fullSiteRoot + "/static/images/Content/Rating/StarOnGreen.gif";  
            var ratingHeader = $('RatingHeader');
            ratingHeader.innerHTML = ratingHeaders[j-1];
        }
        else
        {
            var img = $('img' + j + treatmentId);
            img.src = fullSiteRoot + "/static/images/Content/Rating/StarOnGreen.gif";      
        }
    }
}

function showCurrentRate(i, treatmentId, isYourRating)
{
     for(var j=1; j <= i; j++)
    {
        if(isYourRating)
        {   
            var imgYourRating = $('imgYourRating' + j + treatmentId);
            var starTypeYourRating = imgYourRating.className;
            imgYourRating.src = fullSiteRoot + "/static/images/Content/Rating/Star" + starTypeYourRating + ".gif";
            var ratingHeader = $('RatingHeader');
            ratingHeader.innerHTML = ""; 
        }
        else
        {
            var img = $('img' + j + treatmentId);       
            var starType = img.className;
            img.src = fullSiteRoot + "/static/images/Content/Rating/Star" + starType + ".gif";  
        }
    }
}

function enableExpectedResults(box)
{
    var hours = $('hours');
    var days = $('days');
    var weeks = $('weeks');
    var months = $('months');
    
    if(!box.checked)
    {
        hours.disabled= false;
        days.disabled= false;
        weeks.disabled= false;
        months.disabled= false;
    }
    else
    {    
        hours.selectedIndex = 0;
        days.selectedIndex = 0;
        weeks.selectedIndex = 0;
        months.selectedIndex = 0;
        hours.disabled= true;
        days.disabled= true;
        weeks.disabled= true;
        months.disabled= true;
    }
}

/*********************
Edit/Delete Comments
**********************/

function deleteComment(commentId, parentId, actionName)
{
    Dialog.confirm("Are You Sure You Want To Delete Your Comment?", 
      {
       width:300, 
       buttonClass: "myButtonClass",
       okLabel: "Yes", cancelLabel: "No",
       className: "alphacube",
       showEffectOptions: {duration: showEffectDuration}, 
       hideEffectOptions: {duration: hideEffectDuration},
       onCancel: function(win) {return false;},
       onOk: function(win) 
            {
                new Ajax.Updater(
                {success: 'CommentsContainer'},
                fullSiteRoot + "/" + actionName + "/DeleteComment.aspx", 
                {
                    method: 'get', 
                    parameters: { 
                        'commentId': commentId,
                        'parentId': parentId
                    },
                    onFailure: reportError
                });
                return true;
            }
      });
}

function editComment(commentId, treatmentId, actionName)
{
    var ancorCancel = $("CancelComment" + commentId);
    var ancorEdit = $("EditComment" + commentId);
    var id = "CommentBody" + commentId;
    var commentBodyDom = $(id);
    var parent = commentBodyDom.up();
    var commentBody = commentBodyDom.innerHTML;
//    if(commentBody[0] == " ")
//        commentBody = commentBody.substring(1);
    commentBody = commentBody.replace(/<br>/g, "\r\n");
    commentBodyDom.hide();
    
 	new Ajax.Request(siteRoot + "/" + actionName + "/EditCommentContent.aspx",
        {
            parameters: { commentId: commentId},
            onFailure: function(t){
                MHAlert("Error. Please try again");
            },
            onSuccess: function(t){
                new Insertion.Bottom(parent, 
                    "<div id='divEdit" + commentId + "' class='EditTreatmentCommnet'>" + 
                        "<textarea id='textarea" + commentId + "'>" + t.responseText + "</textarea>" + 
                        "<div style='display: none;' class='Required' id='EditTreatmentCommentError" + commentId + "'>Comment content must not be empty</div>" +
                        "<p class='AlignRight' >" + 
                            "<a class='ButtonGreen Right Edit' style='margin-right: -3px; margin-top: 3px' href='javascript:void(0)' onclick='sendEditComment(" + commentId + ", " + treatmentId + ", \"" + actionName + "\")'>Publish</a>" +
                        "</p>" + 
                        "<p class='Break'></p>" + 
                        
                    "</div>"
                    );
            }
        });    
    
    
    ancorEdit.hide();
    ancorCancel.show();        
}

function cancelEditComment(commentId)
{
    var ancorCancel = $("CancelComment" + commentId);
    var ancorEdit = $("EditComment" + commentId);
    
    var id = "CommentBody" + commentId;
    var commentBodyDom = $(id);
    $('divEdit' + commentId).remove();
    
    commentBodyDom.show();
    
    ancorEdit.show();
    ancorCancel.hide();        
}

function sendEditComment(commentId, parentId, actionName)
{
    var body = $('textarea' + commentId).value;
    var errorDiv = $('EditTreatmentCommentError' + commentId);
    if(body.length == 0)
    {
        errorDiv.show(); 
        return;
    }
    
    new Ajax.Updater(
        {success: 'CommentsContainer'},
        fullSiteRoot + "/" + actionName + "/EditComment.aspx", 
        {
            method: 'post', 
            parameters: { 
                'commentId': commentId,
                'parentId': parentId,
                'body': body
            },
            onFailure: reportError
        });
}

function submitAddRefernce(_isUser)
{
    var addRefernceSubmit = $('addRefernceSubmit');
    var isUser = (_isUser == "t") ? true : false;
    //showProgressBarDialog();
    var form = $('addRefernceForm');	
    var Error = {};
    Error.elementToFocus = null;
    Error.found = false;
    
    
    var newLinks = $$('#addRefernceForm #RelatedLinksContainer .RelatedLinks');
	i = 0;
	newLinks.each(function (newLink) {
	    var LinkTitle = newLink.down('.LinkTitle');
	    var LinkHref = newLink.down('.LinkHref');
	    var LinkSource = newLink.down('.LinkSource');
	    
	    if (LinkTitle.value == '' && LinkHref.value == '' && LinkSource.value == '') {
	        LinkTitle.name = '';
	        LinkHref.name = '';
	        LinkSource.name = '';
	    } 
	    else 
	    {
	        LinkTitle.name = 'linkTitles[' + i + ']';
		    LinkHref.name = 'linkHrefs[' + i + ']';
		    LinkSource.name = 'linkSources[' + i + ']';
		}
		++i;
	});
	
	var errorMsg = "";
	if(isUser)
	{
	    errorMsg = "Pleae enter a description ,a url and a source, or clear all of them";
	}
	else
	{
	    errorMsg = "Pleae enter a description ,a url, a source and the code shown in the image";
	}
	validateReferences({errorContainerId: "LinksErrorContainer", errorMessage: errorMsg ,Error: Error});
	
	if(!isUser)
	{
	    var captcha = $('referenceCaptcha');
        validateLength(captcha, 'LinksErrorContainer', 4, 4, errorMsg, Error);    
    }
     
    if(Error.found == false)
    {
        if(addRefernceSubmit.disabled == true)
        {
            return;
        }
        new Ajax.Updater(
        {success: 'ReferencesContainer'},
        fullSiteRoot + "/Treatments/AddReference.aspx", 
        {
            parameters: form.serialize(true),
            evalScripts: true,
            onFailure: function(t){
                closeAddReference();
                showServiceMessage("There was a problem with your message");
            },
            onSuccess: function(t){
			    closeAddReference();
            }
        });
    }
    else
    {
        if(Error.elementToFocus != null)
        {
            Error.elementToFocus.focus();
        }
    }
    if(Error.found == false)
    {
        addRefernceSubmit.value = "Submitting";
        addRefernceSubmit.disabled = true;
    }
}

var winAddReference = null;
function addReference(treatmentId, isUser)
{
    var winWidth = 675;
    var winHeight = 170;   
    if(isUser == "f")
        winHeight = 250;
    
    var captcha = "";
    if(isUser == "f")
    {
        var captcha = '<div style="margin-left: 13px"><span class="Required">*</span>Enter The Code Shown Below:</div>' +
				    '<div style="padding-left: 13px"><input style="width: 167px" type="text" name="referenceCaptcha" id="referenceCaptcha" class="TextField" onblur="validateCaptchaCode(this, \'LinksErrorContainer\', \'ref\')" /></div>' +
                    '<div style="margin-left: 13px; margin-top: 5px; Border: 1px solid #CBCFD2; width: 170px; height: 45px"><img src="' + fullSiteRoot + '/Images/CaptchaForReferences.aspx?width=170&height=45" alt="captcha" /></div>';
    }

    if(winAddReference == null)
    { 
        winAddReference = new Window
            ({className: "alphacube", 
            width:winWidth , height:winHeight, 
            showEffectOptions: {duration: showEffectDuration}, 
            hideEffectOptions: {duration: hideEffectDuration},
            destroyOnClose: false,
            recenterAuto:false, 
            resizable: false,
			minimizable: false,
      		maximizable: false,
      		onClose: function() { closeAddReference()},
      		zIndex: 5000 }
            );        
    }
    
    var linkDivMarkup = '<form id="addRefernceForm" method="post" action="' + fullSiteRoot + '/Treatments/AddReference.aspx" onsubmit="submitAddRefernce(\'' + isUser + '\'); return false;">' +
                            '<input type="hidden" name="treatmentId" value="' + treatmentId + '">' +
                            '<div id="RelatedLinksContainer" class="RelatedLinksContainerPopup">' +
                                '<h4 style="margin-bottom: 5px; font-weight: normal">Add References:</h4>' + 
                                '<div class="RelatedLinksDiv">' +
							        '<table class="RelatedLinks">' +
								        '<tr>' +
									        '<td><span class="Required">*</span>Link Description:</td>' +
									        '<td><input type="text" class="LinkTitle CreateRemedyTextField RelatedLinksTextField TextField"  /></td>' +
									        '<td></td>' +
								        '</tr>' +
								        '<tr>' +
									        '<td><span class="Required">*</span>Link:</td>' +
									        '<td><input type="text" class="LinkHref CreateRemedyTextField RelatedLinksTextField TextField" /></td>' +
									        '<td></td>' +
								        '</tr>' +
        								
								        '<tr>' +
									        '<td>Source\'s Name:<br /><span class="Small">(e.g. CNN.com)</span></td>' +
									        '<td><input type="text" class="LinkSource CreateRemedyTextField RelatedLinksTextField TextField"  /></td>' +
									        '<td><a href="javascript:addLinkDiv({\'callback\': increaseWinHeight, \'removeCallback\': decreaseWinHeight, \'treatementRefernece\': true})">Add</a></td>' +
								        '</tr>' +								
							        '</table>' +
						        '</div>'+ 
						    '</div>' + 
						    
						    captcha +        
						
						    '<div style="text-align: right; width: 650px; padding-left: 13px"><div id="LinksErrorContainer" class="Error Required" style="display: none; float: left"></div><input id="addRefernceSubmit" type="submit" value="Submit" onmouseout="MH.changeClass(this, \'Login\')" onmouseover="MH.changeClass(this, \'LoginFleep\')" class="Login" style="margin-right: 2px;"/>' + 
						    '<a href="javascript:closeAddReference()" style="float: right; margin-right : 15px; top: 3px; position: relative">Cancel</a><div class="Break"></div></div>' +
						'</form>';
    winAddReference.setHTMLContent(linkDivMarkup);
    winAddReference.showCenter(); 
}
3
function increaseWinHeight()
{
    var size = winAddReference.getSize();
    winAddReference.setSize(size.width, size.height + 110);
}

increaseWinHeight.toString = function(){return "increaseWinHeight"}
decreaseWinHeight.toString = function(){return "decreaseWinHeight"}

function decreaseWinHeight()
{
    var size = winAddReference.getSize();
    setTimeout(function(){  winAddReference.setSize(size.width, size.height - 110)}, 425);
}

function closeAddReference()
{
    if(winAddReference != null)
    {    
        winAddReference.destroy();
        winAddReference = null;
    }
}

function openConditionInfo(elm, specificConditionName)
{
    var elm = $(elm);
    var ConditionInfoOuter = $('ConditionInfoOuter');
    if(!ConditionInfoOuter.visible())
    {
        elm.innerHTML = "Close";
    }
    else
    {
        elm.innerHTML = "Read more about " + specificConditionName;
    }
    new Effect.toggle(ConditionInfoOuter, "blind", {duration: 0.5});
}  

function setFontSize(a, size, content)
{
    var anchors = $$(".Font_Sizes a");
    var divs = $$(".Font_Sizes div");
    divs.each(function(s){s.removeClassName('selected');});
    anchors.each(function(s){s.removeClassName('selected');});
    a.blur();
    a = $(a);
    var parent = a.up();
    parent.addClassName("selected");
    a.addClassName("selected");
    var sizePercent = 100;
    if(size == 2)
    {
        sizePercent = 115;
    }
    else if(size == 3)
    {
        sizePercent = 135;
    }
    
    if(content == "treatment")
    {
        var paragraphs = $$("#TreatmentContent #ContentRight p");
        for(var i = 0; i < paragraphs.length; i++)
        {
            paragraphs[i].style.fontSize = sizePercent + "%";
        }
        var h4 = $$("#TreatmentContent .ReferencesContainerOuter h4")[0];
        h4.style.fontSize = (sizePercent + 20) + "%";
        
        var h5 = $$("#CommentsContainer h5")[0];
        h5.style.fontSize = (sizePercent + 20) + "%";
        
        h5 = $$("#SurveyContainerOuter h5")[0];
        if(h5)
        {
            h5.style.fontSize = (sizePercent + 20) + "%";
        }
        
        var references = $$("#TreatmentContent .ReferencesContainerOuter div");
        for(var i = 0; i < references.length; i++)
        {
            references[i].style.fontSize = sizePercent + "%";
        }
        var span = $$("#TreatmentContent .ReferencesContainerOuter span")[0];
        span.style.fontSize = (sizePercent - 20) + "%";
    }
    else if(content == "ingredient")
    {
        var paragraphs = $$("#RemedyOuter #Content p");
        for(var i = 0; i < paragraphs.length; i++)
        {
            paragraphs[i].style.fontSize = sizePercent + "%";
        }
        
         var paragraphs = $$("#RemedyOuter #Content p.TreatmentDescription");
        for(var i = 0; i < paragraphs.length; i++)
        {
            paragraphs[i].style.fontSize = (sizePercent + 10) + "%";
        }
    }
}