var showEffectDuration = 0.4;
var hideEffectDuration = 0.4;

var userNameMinLength = 2;
var userNameMaxLength = 13;

/**
* ==================================
* General functions
* ==================================
*/

function ToggleById(id) {
    if ($(id).style.display == "none")
        $(id).show();
    else
        $(id).hide();
}

function ToggleAction(container, action, text1, text2) {
    ToggleById(container);
    if ($(action).innerHTML == text1)
        $(action).innerHTML = text2;
    else
        $(action).innerHTML = text1;    
        
}

function SelectAll(id) {
    document.getElementById(id).focus();
    document.getElementById(id).select();
}

// id - the element id
// effectName - the effect name, defualt is 'slide'
// duration - the effect duration, defualt is 0.5
function toggleContent(options)
{
    var duration = options.duration != null ? options.duration : 0.5;
    var effectName = options.effectName != null ? options.effectName : "slide";
    new Effect.toggle(options.id, effectName, {duration: duration});
}

function getParent(elm)
{
    if (typeof elm.parentElement != 'undefined')
        return elm.parentElement;
    if (typeof elm.parentNode != 'undefined')
        return elm.parentNode;
    return null;
}

function findParentWithClass(elm, className) {
    var parent = getParent(elm);
    if (parent != null && !Element.hasClassName(parent, className))
        parent = findParentWithClass(parent, className);
    return parent;
}


function showEffect(elem, duration)
{
    if(duration != null)
    {
        new Effect.Appear(elem, {duration: duration}); 
    }
    else
    {
        new Effect.Appear(elem); 
    }
}

/**
* ==================================
* Mailbox
* ==================================
*/    
function showMessage(elemId, isNew)
{
    var message = document.getElementById('Message' + elemId);
    var messageOpen = document.getElementById('MessageOpen' + elemId);
    
    if(messageOpen.style.display == "none")
    {
        new Effect.BlindDown(messageOpen, {duration: 0.9});
    
        if(isNew)
        {
            var pars = 'id=' + elemId + "&isAjax=true"; 
            new Ajax.Request(siteRoot + '/Community/Mailbox/MarkAsRead.aspx',
                {
                    parameters: pars,          
                    onFailure: function(t){
                        showServiceMessage("An error");
                    },
                    onSuccess: function(t){
                        var messageContainer = $('Message' + elemId);
                        var newMessagesCount = $('newMessagesCount');
                        var newMessagesCountTopMenu = $('newMessagesCountTopMenu');
                        var newMessagesTopMenuImg = $('newMessagesTopMenuImg');
                        var count = parseInt(newMessagesCount.innerHTML);
                        var showMessageAnchor = $('showMessageAnchor' + elemId );
                        count -= 1;
                        if(count == 0)
                        {
                            newMessagesTopMenuImg.style.display = "none";
                            $('InboxFlashAnchor').hide();
                        }
                        newMessagesCount.innerHTML = count;
                        newMessagesCountTopMenu.innerHTML = count;
                        messageContainer.removeClassName('MessageBold');
                        showMessageAnchor.href = "javascript:showMessage(" + elemId + ", false)"; 
                    }
                });
        }
    }
    else
    {
        new Effect.BlindUp(messageOpen, {duration: 0.9});
    }
}

function checkAll()
{
    var chkAll = $('chkAll');
    var checkboxes = $$('#Messages .Message .Check input');
    var divs = $$('#Messages .Message');
    var checked = chkAll.checked;
    for(var i = 0; i < checkboxes.length; i++ )
    {
        if(checkboxes[i].checked != checked)
        {
            if(checkboxes[i].checked == true)
            {
                checkboxes[i].checked = false;
                divs[i].removeClassName ("MessageHighlight");
            }
            else
            {
                checkboxes[i].checked = true;
                divs[i].addClassName ("MessageHighlight");
            }
        }
    }
}



/******************
Herb List
*******************/
function getSpecificConditionsByInitials(search, page)
{
    new Ajax.Updater(
        {success: 'SpecificConditionsOuter'},
        siteRoot + "/Conditions/SpecificConditionsList.aspx", 
        {
            method: 'get', 
            parameters: { search: search, page: page },
            onFailure: reportError
        });
}

function getHerbTableByInitials(search, page, view)
{
    new Ajax.Updater(
        {success: 'HerbsOuter'},
        siteRoot + "/Ingredients/HerbTable.aspx", 
        {
            method: 'get', 
            parameters: { search: search, page: page, view: view },
            onFailure: reportError,
            onComplete: function()
            {
                if(view == 'HerbTableChoosing')
                {
                    //alert("F");
                    selectCheckboxes();
                }
            }
        });
}
    
function getHerbByInitials(search)
{
    new Ajax.Updater(
        {success: 'HerbsOuter'},
        siteRoot + "/Ingredients/Herbs.aspx", 
        {
            method: 'get', 
            parameters: { search: search },
            onFailure: reportError
        });
}

function reportError()
{    
    //TODO: Ofir - replace with audition method
    alert('Error');
}

function addToFavorites(id, url, reload) {  
    var img = $('AddRemoveImg');
    var anchor = $('AddRemoveAnchor');
    var pars = 'id=' + id + "&isAjax=true"; 
    new Ajax.Request(siteRoot + '/' + url + '/AddToFavorites.aspx',
        {
            parameters: pars,          
            onFailure: function(t){
				showLoginPopup({ registeredOnly : true });
            },
            onSuccess: function(t){
                img.title = "Remove from favorites";
                img.alt = "Remove from favorites";
                img.src =  fullSiteRoot + "/Static/Images/Icons/btRemove.gif";     
                img.onclick = "removeFromFavorites('" + id + "', '" + url + "', false)";
                
                anchor.href = "javascript:removeFromFavorites('" + id + "', '" + url + "', false)";
                anchor.innerHTML = "Remove from Favorite " + url;
            }
        });
}

function removeFromFavorites(id, url, reload) 
{  
     var urlName = url;
     if(urlName == "Remedies")
        urlName = "ingredients";
     Dialog.confirm("Are you sure you want to remove from your favorite " + urlName + "?", 
      {
       width:400, 
       buttonClass: "myButtonClass",
       id: "EmptyTrashConfirmDialog",
       className: "alphacube",
       showEffectOptions: {duration: showEffectDuration}, 
       hideEffectOptions: {duration: hideEffectDuration},
       okLabel: "Yes", cancelLabel: "No",
       onCancel: function(win) {return false;},
       onOk: function(win) 
            {
                removeFromFavoritesWithoutConfirm(id, url, reload);
                return true;
            }     
      });
}

function removeFromFavoritesWithoutConfirm(id, url, reload) 
{
    var pars = 'id=' + id + "&isAjax=true"; 
    new Ajax.Request(siteRoot + '/' + url + '/RemoveFromFavorites.aspx',
        {
            parameters: pars,          
            onFailure: function(t){
                showServiceMessage(t.responseText);
            },
            onSuccess: function(t){
                if(reload)
                {
                    location.reload();
                }
                else
                {
//                    var favorite = $('Favorite' + url + id);
//                    if(favorite)
//                        new Effect.BlindUp(favorite, {duration: 1.0});
//                    showServiceMessage(t.responseText);
                    var img = $('AddRemoveImg');
                    var anchor = $('AddRemoveAnchor');
                    img.title = "Add to favorites";
                    img.alt = "Add to favorites";
                    img.src =  fullSiteRoot + "/Static/Images/Icons/btStar.gif";     
                    img.onclick = "addToFavorites('" + id + "', '" + url + "', " +  reload + ")";                    
                    anchor.href = "javascript:addToFavorites('" + id + "', '" + url + "', " + reload + ")";
                    anchor.innerHTML = "Add to Favorite " + url;
                }
            }
        });
}

var winServiceMessage = null;
function showServiceMessage(message, width, height)
{
    var winWidth = 270;
    var winHeight = 140;
    if (width) { winWidth = width; }
    if (height) { winHeight = height; }   
    if(winServiceMessage == null)
    { 
        winServiceMessage = new Window
            ({className: "alphacube", 
            width:winWidth , height:winHeight, 
            title: 'Message from site service',
            showEffectOptions: {duration: showEffectDuration}, 
            hideEffectOptions: {duration: hideEffectDuration},
            destroyOnClose: false,
            recenterAuto:false, 
            resizable: false,
			minimizable: false,
      		maximizable: false }
            );
        
    }
    winServiceMessage.setHTMLContent("<div style='text-align: center; padding-top: 40px'>" + message + 
        "</div><div style='text-align: center; margin-top: 30px;'><a class='ButtonGreenSearch' href='#' style='width: 25px; margin: 0 auto;' onclick='closeServiceMessage()'>OK</a></div>");
    winServiceMessage.showCenter(); 
}

function showServiceMessageAndReload(message, width, height)
{
    Dialog.alert("You've been signed out.", {
                                className:"alphacube",
                                showEffectOptions: {duration: showEffectDuration},
                                hideEffectOptions: {duration: hideEffectDuration},	
                                width:250, 
                                height:80, 
                                //okLabel: "OK", ok:function(win) {return true;}});
                                okLabel: "OK", ok:function(win) {reloadAfterSignOut("index"); return true;}});
}

function reloadAfterSignOut(action)
{
    window.location.replace(fullSiteRoot + "/Users/SignoutAndRedirect.aspx?action=" + action + "&showSuccessfullSignout=false");
}

function closeServiceMessage()
{
    if(winServiceMessage != null)
    {    
        winServiceMessage.destroy();
        winServiceMessage = null;
    }
}
function closeInviteFriendDialog()
{
    if(winInviteFriend != null)
    {    
        $('InviteFriend').style.display = "none";
        winInviteFriend.destroy();
        winInviteFriend = null;
    }
}

function printPage()
{
    window.print();
}

function highlight(elm, messageId)
{
    var elm = $(elm);
    var chkAll = $('chkAll');
    var divMessage = $(messageId);
    if(elm.checked == true)
    {
        divMessage.addClassName ("MessageHighlight");
        if(isAllChecked())
            chkAll.checked = true;
    }
    else
    {
        divMessage.removeClassName ("MessageHighlight");
        if(chkAll.checked == true)
            chkAll.checked = false;
    }
}

function isAllChecked()
{
    var checkboxes = $$('#Messages .Message .Check input');
    var allChecked = true;
    for(var i = 0; i < checkboxes.length; i++ )
        if(checkboxes[i].checked == false)
        {    
            allChecked = false;
            break;
        }
    return allChecked;
}

/////////////////////////////////////////////
// clears the form when the page is refreshed
/////////////////////////////////////////////
function clearForm()
{
    var messagesForm = $('messagesForm');
    messagesForm.reset();
}

function deleteList()
{
    var messagesForm = $('messagesForm');
    var checkboxes = $$('#Messages .Message .Check input');
    for(var i = 0; i < checkboxes.length; i++ )
    {
        if(checkboxes[i].checked)
            checkboxes[i].name = "messages[" + i + "]";
    }
    messagesForm.submit();
}

function confirmRemoveFromFriends(id, name, afterAction)
{
    Dialog.confirm("Are you sure you want to remove " + name + " from your friends list?", 
      {
       width:380, 
       buttonClass: "myButtonClass",
       id: "RemoveFromFriendsbackConfirmDialog",
       className: "alphacube",
       okLabel: "Yes", cancelLabel: "No",
       showEffectOptions: {duration: showEffectDuration}, 
       hideEffectOptions: {duration: hideEffectDuration},
       onCancel: function(win) {return false;},
       onOk: function(win) 
            {
                removeFromFriends(id, afterAction);
                return true;
            }
      });
}

function removeFromFriends(id, afterAction)
{    
    var pars = 'id=' + id + "&isAjax=true"; 
    new Ajax.Request(siteRoot + "/Community/People/RemoveFromFriends.aspx",
        {
            parameters: pars,          
            onFailure: function(t){
                if(t.responseText == "signin")
                    showLoginPopup({ registeredOnly : true });
                else    
                    showServiceMessage(t.responseText);
            },
            onSuccess: function(t)
            {
                if(afterAction == "reload")
                {
                    //var removeFriend = $('RemoveFriend' + id);
                    //removeFriend.innerHTML = "Refresh to clear";
                    location.reload();
                }
                else if(afterAction == "change")
                {
                    var img = $('AddRemoveFriendImg');
                    var icon = $('AddRemoveFriendIcon');
                    var link = $('AddRemoveFriendLink');
                    img.src = fullSiteRoot + "/Static/Images/Icons/user_add.gif";
                    link.innerHTML = "Add to friends";
                    link.href = "javascript:addToFriends(" + id + ",'" + name + "', 'change')";
                    icon.href = "javascript:addToFriends(" + id + ",'" + name + "', 'change')";
                }
                else
                {
                    var friend = $('Profile' + id);
                    new Effect.BlindUp(friend, {duration: 1.0});
                }
                showServiceMessage(t.responseText);
            }
        });
}

function addToFriends(id, name, afterAction)
{
     var pars = 'id=' + id + "&isAjax=true"; 
     new Ajax.Request(siteRoot + "/Community/People/AddToFriends.aspx",
        {
            parameters: pars,          
            onFailure: function(t){
                if(t.responseText == "signin")
                    showLoginPopup({ registeredOnly : true });
                else    
                    showServiceMessage(t.responseText);
            },
            onSuccess: function(t)
            {
                if(afterAction == "change")
                {
                    var img = $('AddRemoveFriendImg');
                    var icon = $('AddRemoveFriendIcon');
                    var link = $('AddRemoveFriendLink');
                    img.src = fullSiteRoot + "/Static/Images/Icons/btRemove.gif";
                    link.innerHTML = "Remove from friends";
                    link.href = "javascript:confirmRemoveFromFriends(" + id + ",'" + name + "', 'change')";
                    icon.href = "javascript:confirmRemoveFromFriends(" + id + ",'" + name + "', 'change')";
                }
                showServiceMessage(t.responseText);
            }
        });
}

function forgotPassword(formId) 
{
	$(formId).request
	( 
        {
            onFailure: function(t){
                showServiceMessage(t.responseText);
            },
            onSuccess: function(t){
                var div = $(formId).up();
                toggleContent({id: div});
				showServiceMessage(t.responseText);
            }
        });
}

function submitContactUsForm(signedIn)
{
	var form = $('ContactUsForm');	
	var Error = {};
    Error.elementToFocus = null;
    Error.found = false;
    
    if(signedIn != "SignedIn")
    {    
        var name = form.getElementsBySelector('input[id=ContactUsName]')[0];
        validateNotEmpty(name, 'ContactUsNameErrorContainer', "Please fill in your name", Error);
        var email = form.getElementsBySelector('input[id=ContactUsEmail]')[0];
        validateEmail(email, 'ContactUsEmailErrorContainer', "Incorrect or incomplete email address", Error);
    }
    
    var subject = form.getElementsBySelector('input[id=ContactUsSubject]')[0];
    validateNotEmpty(subject, 'ContactUsSubjectErrorContainer', "You must fill in the subject", Error);
    var content = form.getElementsBySelector('textarea[id=ContactUsContent]')[0];
    validateNotEmpty(content, 'ContactUsContentErrorContainer', "You must fill in the content", Error);
    
    if(Error.found == false)
	{
	    form.request(
        {
            onFailure: function(t){
                showServiceMessage("There was a problem with your message, check your email adress again");
            },
            onSuccess: function(t){
				//form.submit();
				form.reset();
                showServiceMessage("Your contact request has been submitted successfully and will be answered shortly.");
            }
        });   
	}
	else
	{
        if(Error.elementToFocus != null)
            Error.elementToFocus.focus();
    }
}

function bookmarkPage(url, title)
{
	url = window.location; 
	title = document.title; 

	if (window.sidebar) 
    {
		window.sidebar.addPanel(title, url, "");
	}
	else if(window.opera && window.print)
	{ 
		var elem = document.createElement('a');
	    elem.setAttribute('href',url);
	    elem.setAttribute('title',title);
	    elem.setAttribute('rel','sidebar');
	    elem.click();
	} 
	else if(document.all)
	{
	    window.external.AddFavorite(url, title);
	}
	else
	{ 
		alert("Sorry! Your browser doesn't support this function.")
	}; 
}

function enlargePic(imageId, imageWidth, imageHeight)
{
		var imgOuter = $('ImgOuter');
		if(imgOuter.style.display == "none")
		{	
			new Ajax.Updater(
	        {success: 'ImgOuter'},
	        siteRoot + "/Images/LargeImage.aspx", 
	        {
	            parameters: { imageId: imageId, width: imageWidth,  height: imageHeight},
				onSuccess : function(r) 
	            {
	                //var centerPos = getCenterPosition(imgOuter.getWidth(), imgOuter.getHeight());
	                //var centerPos = getCenter();
	                var ViewContentsWrapper = $('ViewContentsWrapper');
	                
					var a = (ViewContentsWrapper.getWidth() - imgOuter.getWidth()) / 2;
					imgOuter.style.left = (ViewContentsWrapper.getWidth() - imgOuter.getWidth()) / 2 + 20 + "px";
					imgOuter.style.top = "50px";
					//new Effect.BlindDown(imgOuter, {duration: 1.0});
					imgOuter.show();
		        } 
	        });
		}
		else
		{
			imgOuter.hide();		
		}
}

function getCenterInfo(width, height) 
{    
    var windowScroll = WindowUtilities.getWindowScroll();
    var pageSize = WindowUtilities.getPageSize();
    var centerPos = [];
    centerPos[0] = (windowScroll.width - width) / 2;
    centerPos[1] = (windowScroll.height- height) / 2;
    return centerPos;
}


function hideEnlargePic(divId)
{
	var imgOuter = $('ImgOuter');
	//new Effect.BlindUp(imgOuter, {duration: 1.0});
	imgOuter.hide();	
}

function getCenter()
{
    var centerPos = [];
    centerPos[0] = 5;
    centerPos[1] = 5;
    return centerPos;
}

function getCenterPosition(elWidth, elHeight)
{
    var position = [0, 0];
    var screenWidth;
    if (window.innerWidth) //if browser supports window.innerWidth
         screenWidth = window.innerWidth;
    else if (document.all) //else if browser supports document.all (IE 4+)
        screenWidth = document.body.clientWidth;
    var iebody = (document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body;
    var dsoctop = document.all? iebody.scrollTop : pageYOffset;
    
    position[0] = parseInt((screenWidth - elWidth) / 2);
    position[1] = parseInt((dsoctop + ((screen.availHeight - elHeight + 50) / 2)));
   
    return position;
}

/**
====================
Mailbox 
====================
*/
function submitMessageForm(form)
{
    var Error = {};
    Error.elementToFocus = null;
    Error.found = false;   
    
    var form = $(form);
    
    var ToErrorContainer = $('ToErrorContainer');
    var to = form.getElementsBySelector('select[id=To]')[0];
    if(to != undefined)
    {
        if(to.options.length == 0)
        {
            ToErrorContainer.innerHTML = "You can send messages only to your friends";
            ToErrorContainer.show();
        }
        else
            ToErrorContainer.hide();
    }
    
    var subject = form.getElementsBySelector('input[id=Subject]')[0];
 	validateNotEmpty(subject, 'SubjectErrorContainer', 
		"Subject must not be empty", Error); 
	 
	   
    if(Error.found == false)
	{
	    form.submit();
	//    return true;
	}
	else
	{    
	    if(Error.elementToFocus != null)
	        Error.elementToFocus.focus();
	    return false;
    }
}

function confirmEmptyTrash()
{
    Dialog.confirm("Are you sure you want to empty your trash?", 
      {
       width:350, 
       buttonClass: "myButtonClass",
       id: "EmptyTrashConfirmDialog",
       className: "alphacube",
       showEffectOptions: {duration: showEffectDuration}, 
       hideEffectOptions: {duration: hideEffectDuration},
       okLabel: "Yes", cancelLabel: "No",
       onCancel: function(win) {return false;},
       onOk: function(win) 
            {
                location.replace(fullSiteRoot + "/Community/Mailbox/DeleteTrash.aspx");
            }     
      });
}

function confirmDeleteList()
{
    Dialog.confirm("Are you sure you want to delete the selected items?", 
      {
       width:350, 
       buttonClass: "myButtonClass",
       id: "EmptyTrashConfirmDialog",
       className: "alphacube",
       showEffectOptions: {duration: showEffectDuration}, 
       hideEffectOptions: {duration: hideEffectDuration},
       okLabel: "Yes", cancelLabel: "No",
       onCancel: function(win) {return false;},
       onOk: function(win) 
            {
                deleteList();
                return true;
            }     
      });
}

function confirmDeleteMessage(id)
{
    Dialog.confirm("Are you sure you want to delete this message?", 
      {
       width:350, 
       buttonClass: "myButtonClass",
       id: "EmptyTrashConfirmDialog",
       className: "alphacube",
       okLabel: "Yes", cancelLabel: "No",
       showEffectOptions: {duration: showEffectDuration}, 
       hideEffectOptions: {duration: hideEffectDuration},
       onCancel: function(win) {return false;},
       onOk: function(win) 
            {
                 location.replace(fullSiteRoot + "/Community/Mailbox/Delete.aspx?id=" + id);
                return true;
            }     
      });
}

function communityFilterByCondition(conditionId)
{
    if(conditionId > 0)
        location.replace(fullSiteRoot + "/Community/People/List.aspx?conditionId=" + conditionId);
    else
        location.replace(fullSiteRoot + "/Community/People/List.aspx");
}

function filterByConditionByName(ingedientName, conditionId)
{
    if(conditionId > 0)
        location.replace(fullSiteRoot + "/Ingredients/View.aspx?name=" + ingedientName + "&scfId=" + conditionId + "#RelatedTreatments");
    else
        location.replace(fullSiteRoot + "/Ingredients/View.aspx?name=" + ingedientName + "#RelatedTreatments");
}

//TODO: remove after URL-Rewrite
function filterByCondition(ingedientId, conditionId)
{
    if(conditionId > 0)
        location.replace(fullSiteRoot + "/Ingredients/View.aspx?id=" + ingedientId + "&scfId=" + conditionId + "#RelatedTreatments");
    else
        location.replace(fullSiteRoot + "/Ingredients/View.aspx?id=" + ingedientId + "#RelatedTreatments");
}

function selectOptionAlert()
{
    Dialog.alert("You must select an option in order to vote.", {
                                className:"alphacube",
                                showEffectOptions: {duration: 0.7},	
                                width:280, 
                                height:80, 
                                okLabel: "OK", ok:function(win) {return true;}});
}

function confirmPollVoting()
{
    radio = $$(".OptionRadio");
    voted = false;
    for (i=0; i<radio.length; i++)
        if(radio[i].checked == true) voted=true;
        
    if (!voted)
    {
        selectOptionAlert();
        //alert("Sorry! select an option in order to vote.");
        return ;
    }
    
    $("VoteForm").submit();
}

function confirmPollAnonymousVoting()
{
    radio = $$(".OptionRadio");
    voted = false;
    for (i=0; i<radio.length; i++)
        if(radio[i].checked == true) voted=true;
        
    if (!voted)
    {
        selectOptionAlert();
        //alert("Sorry! select an option in order to vote.");
        return ;
    }
    
    Dialog.confirm("You are not signed in. Voting as a user offers better statistics on your personal page.<br>Are you sure you want to vote anonymously?", 
      {
       width:400, 
       buttonClass: "myButtonClass",
       id: "EmptyTrashConfirmDialog",
       className: "alphacube",
       okLabel: "Vote anyway", cancelLabel: "Sign-In first",
       showEffectOptions: {duration: showEffectDuration}, 
       hideEffectOptions: {duration: hideEffectDuration},
       onCancel: function(win) {showLoginPopup({ registeredOnly : true }); return false; },
       onOk: function(win) 
            {
                $("VoteForm").submit();
                return true;
            }     
      });
}

function openInviteFriendsWindow()
{
    var winWidth = 455 ;
    var winHeight = 475;    
    var winIM = window.open(fullSiteRoot + '/Users/InviteFriendsWindow.aspx?', "", "fullscreen=no,menubar=no,toolbar=no,location=no,titlebar=no,scrollbars=no,resizable=no,left=0,top=0,width="+winWidth+",height="+winHeight);
}

function AjaxCommunityPager(page, conditionId, pageType)
{
    if(pageType == undefined)
    { 
        pageType = "listUsers"; // default - list users
    }
    new Ajax.Updater(
        {success: 'PageListOuter'},
        siteRoot + "/Community/People/ListAll.aspx", 
        {
            method: 'post', 
            parameters: { 
                'page': page,
                'conditionId': conditionId,
                'pageType': pageType
            },
            onFailure: reportError
        });
}



function getFriendList(name, page)
{
    new Ajax.Updater(
        'FriendsContainer',
        siteRoot + "/Community/MyPages/FriendList.aspx", 
        {
            parameters: { name: name, page: page}
        });
}

/**
====================
Cookies 
====================
*/
function createCookie(name,value,days) 
{
	if (days) 
	{
		var date = new Date();
		date.setTime(date.getTime()+(days * 24 * 60 * 60 * 1000));
		var expires = "; expires="+date.toGMTString();
	}
	else 
	    var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) 
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i = 0; i < ca.length; i++) 
	{
		var c = ca[i];
		while (c.charAt(0) == ' ') 
		    c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) 
		    return c.substring(nameEQ.length, c.length);
	}
	return null;
}

function eraseCookie(name) 
{
	createCookie(name, "", -1);
}

function showProgressBarDialog()
{
    Dialog.info("", { className:"alphacube",
                          showEffectOptions: {duration: showEffectDuration},
                          hideEffectOptions: {duration: hideEffectDuration},	
                          width:250, 
                          height:150,
                          showProgress: true});
}

var progressBarImages = [];
function showProgressBar(elem)
{
    var elem = $(elem);
    var parent = elem.up();
    var img = '<img style="top: 3px; position:absolute; margin-left: 3px" id="imgProgress" src="/static/images/content/progress.gif"  />'
    new Insertion.Bottom(parent, img);
    progressBarImages.push(parent.getElementsByTagName("img")[0]);
}

function closeProgressBar()
{
    $(progressBarImages.shift()).remove();
}

function liveUpdateSetTimeout()
{
    var seconds = 60;            
    setTimeout(liveUpdate, seconds * 1000);
}

function liveUpdate()
{
    var pars = "isAjax=true"; 
    new Ajax.Request(fullSiteRoot + '/Home/GetStatistics.aspx',
                {
                    parameters: pars,          
                    onSuccess: function(t){
                        var count = t.responseText.split(":");
                        var treatmentCount = $('treatmentCount');
                        var ingredientCount = $('ingredientCount');
                        var conditionCount = $('conditionCount');
                        var oldTreatmentCount = parseInt(treatmentCount.innerHTML);
                        var oldIngredientCount = parseInt(ingredientCount.innerHTML);
                        var oldConditionCount = parseInt(conditionCount.innerHTML);
                        var newTreatmentCount = parseInt(count[0]);
                        var newIngredientCount = parseInt(count[1]);
                        var newConditionCount = parseInt(count[2]);
                        
                        if(oldConditionCount != newConditionCount)
                            conditionCount.innerHTML = count[2];
                        if(oldIngredientCount != newIngredientCount)
                            ingredientCount.innerHTML = count[1];
                        if(oldTreatmentCount != newTreatmentCount)
                            treatmentCount.innerHTML = count[0];
                    }
                });
    var seconds = 60;            
    setTimeout(liveUpdate, seconds * 1000);
}

function getSpecificConditionsByInitials3(search, page)
{
        new Ajax.Updater(
            {success: 'SpecificConditionsList'},
            siteRoot + "/Conditions/SpecificConditionsList.aspx", 
            {
                method: 'get', 
                parameters: { search: search, page: page, view: 'SpecificConditionsList3', pageSize: 30 }
            });
}

var specificConditionsType = null;
var specificConditionsOpen = false;
var firstTimeABC = true;
var firstTimeGroups = true;
function openSpecificConditionsList(options)
{
    var Groups = $("ByGroups");
    var ABC = $("ByABC");
    
    if(options.type == "ABC" && !ABC.visible())
    {
        if(firstTimeABC)
        {
            firstTimeABC = false;
            getSpecificConditionsByInitials2('A', 1, 'HomeSpecificConditionsList', 'SpecificConditionsListContianer', 30);
        }
        ABC.show();
        Groups.hide();
    }
    else if (options.type == "Groups" && !Groups.visible())
    {
        if(firstTimeGroups)
        {
            firstTimeGroups = false;
            getSpecificConditionsByGroups('SpecificConditionsByGroupsContianer');
        }
        ABC.hide();
        Groups.show();
    }
    if(specificConditionsType != null && specificConditionsType != options.type && specificConditionsOpen)
    {
        specificConditionsType = options.type;
        
        return;
    }
    specificConditionsOpen = !specificConditionsOpen;
    specificConditionsType = options.type;
    new Effect.toggle('SpecificConditionsList', "blind", {duration: 0.5});
}

function closeSpenSpecificConditionsList()
{
    specificConditionsOpen = false;
    new Effect.toggle('SpecificConditionsList', "blind", {duration: 0.5});
}

function getSpecificConditionsByInitials2(search, page, view, containerId, pageSize)
{
    new Ajax.Updater(
            {success: containerId},
            siteRoot + "/Conditions/SpecificConditionsList.aspx", 
            {
                method: 'get', 
                parameters: { search: search, page: page, view: view, pageSize: pageSize },
                onFailure: reportError
            });
}

function getSpecificConditionsByGroups(containerId)
{
    new Ajax.Updater(
            {success: containerId},
            siteRoot + "/Conditions/SpecificConditionsByGroups.aspx", 
            {
                method: 'get', 
                onFailure: reportError
            });
}

function ToggleSpecificConditionsSubList()
{    
    new Effect.toggle('SelectedRelatadSpesificConditions', "blind", {duration: 0.5});
}

function ToggleSpecificConditions(event)
{
    var element = Event.element(event);
    if(element.tagName == "SPAN")
    {
        var parent = this.up();
        if(parent.tagName == "DIV")
        {
            var specificConditions = parent.getElementsByTagName("DIV")[0];
            specificConditions = $(specificConditions);
            new Effect.toggle(specificConditions, "blind", {duration: 0.5});
        }
    }
}

function getRelatedSpesificConditions(conditionId, elm)
{
    var elm = $(elm);
    var parent = elm.up();
    var div = "<div style='display: none' class='SpecificConditionsSubListOuter' id='SpecificConditionsSubList" + conditionId + "'></div>";
    new Insertion.Bottom(parent, div);
    elm.onclick = function() {};
    setTimeout(function(){ Event.observe(elm, 'click', ToggleSpecificConditions)}, 50);
    
    new Ajax.Updater(
            {success: 'SpecificConditionsSubList' + conditionId},
            siteRoot + "/Conditions/RelatadSpesificConditions.aspx", 
            {
                method: 'get', 
                parameters: { conditionId: conditionId },
                onFailure: reportError,
                onComplete: function()
                {
                    var SpecificConditionsSubList = $('SpecificConditionsSubList' + conditionId);
                    new Effect.BlindDown(SpecificConditionsSubList, {duration: 0.5});
                    //var specificConditions = $$('#SpecificConditionsSubList' + conditionId + ' .SpecificConditionsSubList')[0];
                    //specificConditions.show();
                }
            }
        );
}            
    
function browseConditionsBy(type, button)
{
    var buttons = $$('#ContentWrapper .BrowseConditionsBy ul li a');
    for(var i = 0; i < buttons.length; i++)
    {
        buttons[i].removeClassName("selected");
    }
    var button = $(button);
    button.addClassName("selected");
    
    new Ajax.Updater(
            {success: 'ConditionsListContainer'},
            siteRoot + "/Conditions/ConditionsSubList.aspx", 
            {
                method: 'get', 
                parameters: { view: "List" + type },
                onFailure: reportError
            }
        );
}


/******************
Registration 
*******************/
function showPrivacyPolicy()
{
    window.open(fullSiteRoot + "/Users/PrivacyPolicyPopup.aspx");
}
function showCopyrighPolicy()
{
    window.open(fullSiteRoot + "/Users/CopyrightPolicyPopup.aspx");
}
function showTermsOfService()
{
    window.open(fullSiteRoot + "/Users/TermsOfServicePopup.aspx");
}

function signUpFromPopup()
{
    var doSubmit = submitRegistrationFormPopup('PopupSignUpForm');
	if(doSubmit != false)
	{
        Dialog.closeInfo();
    }
}

function submitRegistrationFormPopup(form)
{
    var form = $(form);
    var Error = {};
    Error.elementToFocus = null;
    Error.found = false;    
	
    // check for valid email
    var email = $('Email');
    validateEmail(email, 'SignUpEmailErrorContainer', "Incorrect or incomplete email address", Error);
	
	var retypedEmail = $('RetypedEmail');
	validateStringsMatch(email, retypedEmail, 
		'SignUpRetypedEmailErrorContainer', "Original and re-typed email do not match", Error);
	
	// check for not empty Name
	var name = form.getElementsBySelector('input[id=Name]')[0];
	//alert($('SignUpUsernameErrorContainer').style.display == "none");
	
 	    //validateLength(name, 'SignUpUsernameErrorContainer', userNameMinLength, userNameMaxLength, 
		//    "Screen name cannot exceed 13 characters", Error); 
	var pattern = /^[a-zA-Z0-9\s\._-]{2,13}$/;	    
	validateRegEx(name, 'SignUpUsernameErrorContainer', "Screen name can contain only letters, digits, space, '_', '.' and '-'", pattern, Error);
	
	
	// check for valid password and matching password and retyped password
	var password = $('Password');
	var retypedPassword = $('RetypedPassword');    
	
	validatePassword(password, 'SignUpPasswordErrorContainer', Error);
	
	validateStringsMatch(password, retypedPassword, 
		'SignUpRetypePasswordErrorContainer', "Original and re-typed password do not match", Error);
		
	// check for not empty Captcha
	var captcha = form.getElementsBySelector('input[id=Captcha]')[0];
    validateLength(captcha, 'SignUpCaptchaErrorContainer', 4, 4, "Please enter the code shown in the image below", Error);    
		
		
	// check for UserAgreed checked
	var userAgreed = $('UserAgreed');
	validateUserAgreement(userAgreed, 'SignUpUserAgreedErrorContainer', 
		"You must review and accept the terms of service and privacy policy", Error );	
	
	if(!Error.found && !UsernameError.found)
	{
	    form.submit();
	    return true;
	}
	else
	{    
	    if(Error.elementToFocus != null)
	        Error.elementToFocus.focus();
	    else if(UsernameError.elementToFocus != null)
	        UsernameError.elementToFocus.focus();
	    return false;
    }
}

function inviteFriends(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, 'InviteFriendFromEmailErrorContainer', "Incorrect or incomplete email address", Error);
    }
    
    var fromName = form.getElementsBySelector('input[id=fromName]')[0];
    validateNotEmpty(fromName, 'InviteFriendFromNameErrorContainer', "Please fill in your name", Error);
    var toName = form.getElementsBySelector('input[id=toName]')[0];
    validateNotEmpty(toName, 'InviteFriendToNameErrorContainer', "Please fill in a friend's name", Error);
    var toEmail = form.getElementsBySelector('textarea[id=toEmail]')[0];
    validateEmails(toEmail, 'InviteFriendToEmailErrorContainer', "Incorrect or incomplete email address", Error);
    
    //winInviteFriend.updateHeight();
    
    if(Error.found == false)
	{	   
	    showProgressBarDialog(); 
        form.request( 
        {
            onFailure: function(t){
                showServiceMessage(t.responseText); 
            },
            onSuccess: function(t){
                form.reset();
                if(winInviteFriend != null)
                    winInviteFriend.hide();
                Dialog.closeInfo();    
                showServiceMessage("The invitation was successfully sent to your friend");                
            }
        });
    }
    else
    {
        if(Error.elementToFocus != null)
            Error.elementToFocus.focus();
    }    
}

function submitChangePasswordForm()
{
	var form = $('ChangedPasswordForm');
   	var Error = {};
    Error.elementToFocus = null;
    Error.found = false;   
    
	var password = $('Password');
   	var newPassword = $('NewPassword');
   	var retypedNewPassword = $('RetypedNewPassword');

	if( password.value.length > 0 || 
	    newPassword.value.length > 0 || 
	    retypedNewPassword.value.length > 0 )
	{
	    validatePassword(password, 'EditUserOldPasswordErrorContainer', Error);
	    validatePassword(newPassword, 'EditUserNewPasswordErrorContainer', Error);
	    
	    validateStringsMatch(newPassword, retypedNewPassword, 
		'EditUserNewRetypedPasswordErrorContainer', "New and retyped password do not match", Error);
	}
	
	if(Error.found == false)
	{
	    var btSubmitEditUser = $('btSubmitEditUser');
        btSubmitEditUser.onclick = function (){return false;};
        showProgressBarDialog();
	    form.submit();
	    return true;
	}
	else
	{    
	    if(Error.elementToFocus != null)
	        Error.elementToFocus.focus();
	    return false;
    }
}

function updateContent(options)
{
    var successContainerId = options.containerId;
    var asynchronous =  options.evalScripts != null ? options.evalScripts : false; 
    var parameters = options.parameters != null ? options.parameters : null;        
    var onFailure = options.onFailure != null ? options.onFailure : null;        
    var onSuccess = options.onSuccess != null ? options.onFailure : null;
    var path = options.path != null ? options.path : null;
            
    new Ajax.Updater
    (
        { success: successContainerId},
        fullSiteRoot + path, 
        {
            parameters: options.parameters,
            onFailure : options.onFailure,
            onSuccess : options.onSuccess
        }
    ); 
}

//

function refreshCaptcha(captchaType)
{
    $('divCaptchaProgress').innerHTML = "<img id='CaptchaProgress' src='" + siteRoot + "/Static/Images/Content/progress.gif' />";
    $('Captcha').value = "";
    $('divCaptchaProgress').style.display = "block";
    //$('CaptchaContainer').innerHTML = "<img id='CaptchaProgress' src='" + siteRoot + "/Static/Images/Content/progress.gif' />";
    new Ajax.Updater(
                {success: 'CaptchaContainer'},
                
                siteRoot + "/Images/CaptchaImage.aspx", 
                {
                    evalScripts: true,
                    method: 'get', 
                    parameters: { captchaType: captchaType },
                    onFailure: reportError,
                    onSuccess: function(t)
                    {
                        setTimeout(function(){$('divCaptchaProgress').style.display = "none";}, 1000);
                    } 
                });
           
}

