/*
 * Javascript/JQuery - Main functions
 * @author: valerie.hanesse @ readingroom.com
 * @contributors: david.pickstone @ readingroom.com
 * @created: 14.03.2010
 * @updated: 26.05.2010
 *
 * ************************************************************/

Cufon.replace('h1', { fontFamily: 'Rotis SansSerif Std Light' });
var ieX = (parseInt(jQuery.browser.version));


jQuery(document).ready(function() {
	DoEverything();
});


	function DoEverything(){

	    offsetPersonas();
	    inputsText();

		/***** ADD THIS BAR *****/
		var secondaryElt = jQuery("#secondaryContent");
		var tools = jQuery(".tools");
		/*only appearing if there is a left navigation a right sidebar or in article tools*/
		/*
		in HIV - Membership section this button should not appear
		=> there is either no left navigation or no right sidebar
		*/
		if ((secondaryElt.size() == 1) && (jQuery("#tertiaryContent").size() == 1) && (jQuery("#inpageTools").size() == 0)) {
			jQuery("<div id=\"inpageTools\" class=\"block\"><div class=\"addthis_toolbox\"><div class=\"hover_effect block\"><div id=\"toolbox\" class=\"wrap\"></div></div></div></div>").prependTo("#tertiaryContent");
			var tbx = document.getElementById("toolbox"), svcs = {
				print: '&nbsp;Print',
				email: '&nbsp;',
				twitter: '&nbsp;',
				facebook: '&nbsp;',
				digg: '&nbsp;',
				compact: '&nbsp;More'
			};
			for (var s in svcs) {
				tbx.innerHTML += '<div><a href="#" class="addthis_button_' + s + '">' + svcs[s] + '</a></div>';
			}
			addthis.toolbox(tbx, {
				username: 'xa-4bbca94660af7e8f',
				services_compact: 'print,email,favorites,digg,facebook,twitter',
				services_expanded: 'print,email,favorites,digg,facebook,twitter'
			});
		}
		tools.each(function(index) {
			var elt = jQuery(this);
			var addThis = jQuery('<div class="share block"><h3>Share:</h3><div class="inner"><div class="addthis_toolbox"><div class="hover_effect"><div id="toolbox' + index + '" class="wrap"></div></div></div></div></div>');
			elt.append(addThis);
			var articletbx = document.getElementById("toolbox" + index), svcs = {
				print: '&nbsp;Print',
				email: '&nbsp;',
				twitter: '&nbsp;',
				facebook: '&nbsp;',
				digg: '&nbsp;'
			};
			for (var s in svcs) {
			    articletbx.innerHTML += '<div><a href="#" class="addthis_button_' + s + '">' + svcs[s] + '</a></div>';
			}
			addthis.toolbox(articletbx, {
				username: 'xa-4bbca94660af7e8f',
				services_compact: 'print,email,favorites,digg,facebook,twitter',
				services_expanded: 'print,email,favorites,digg,facebook,twitter'
			});
		});
		//.append('<div class="share block"><h3>Share:</h3><div class="inner"></div></div>');


		/***** PORTAL NAVIGATION ROLL OVER: selection page *****/
		jQuery("#portalNavigation .section").bind({
		    'mouseenter': function() {
		        jQuery("#portalNavigation .section h2 a").blur();
		        var bgcolor = "#68013d";
		        var liClass = (jQuery(this).parents("li:first")).attr("class");
		        switch (liClass) {
		            case "hiv": bgcolor = "#0c5578"; break;
		            case "charity": bgcolor = "#092269"; break;
		        }
		        jQuery(this).stop().css({ backgroundColor: "" }).animate({ backgroundColor: bgcolor }, 500);
		    },
		    'mouseleave': function() { jQuery(this).stop().css({ backgroundColor: "" }); },
		    'click': function() { jQuery(location).attr("href",(jQuery("h2 a", jQuery(this)).attr("href"))); }
		});
		jQuery("#portalNavigation .section a").bind({
		    'focus': function() {
		        var bgcolor = "#68013d";
		        var liClass = (jQuery(this).parents("li:first")).attr("class");
		        switch (liClass) {
		            case "hiv": bgcolor = "#0c5578"; break;
		            case "charity": bgcolor = "#092269"; break;
		        }
		        (jQuery(this).parents(".section:first")).stop().css({ backgroundColor: "" }).animate({ backgroundColor: bgcolor }, 500);
		    },
		    'blur': function() { (jQuery(this).parents(".section:first")).stop().css({ backgroundColor: "" }); }
		});
		/***** PORTAL NAVIGATION ROLL OVER *****/
		jQuery("#portalNav a").bind({
		    'focus mouseenter': function() {
		        var bgcolor = "#777";
		        var textcolor = "#fff;";
		        var liClass = jQuery(this).parent().attr("class");
		        switch (liClass) {
		            case "services": bgcolor = "#68013d"; break;
		            case "hiv": bgcolor = "#0c5578"; break;
		            case "charity": bgcolor = "#092269"; break;
		        }
		        jQuery(this).stop().animate({ backgroundColor: bgcolor }, 500);
		    }
		 });
		 jQuery("#portalNav a").bind("blur mouseleave", function() { jQuery(this).stop().css({ backgroundColor: "" }); });
		/***** PRIMARY NAVIGATION ROLL OVER *****/
		jQuery("#primaryNavigation ul.main-menus li a").bind({
		    'focus mouseenter':
		    function() {
		        var bgcolor = "#ebe3e7";
		        var bodyClass = jQuery("body").attr("class");
		        switch (bodyClass) {
		            case "hiv": bgcolor = "#97cde7"; break;
		            case "charity": bgcolor = "#e9e9e9"; break;
		        }
		        jQuery(this).stop().css({ backgroundColor: "" }).animate({ backgroundColor: bgcolor }, 500);
		    }
		 });
		jQuery("#primaryNavigation ul.main-menus li a").bind("blur mouseleave", function() { jQuery(this).stop().css({backgroundColor:""}); });
		/***** QUICK ROLL OVER *****/
		jQuery(".quick-links .corner-box .default a").bind({
		    'focus mouseenter': function() {
		        var bgcolor = "#68013d";
		        var bodyClass = jQuery('body').attr("class");
		        switch (bodyClass) {
		            case "hiv": bgcolor = "#0c5578"; break;
		            case "charity": bgcolor = "#092269"; break;
		        }
		        jQuery(this).stop().css({ backgroundColor: "" }).animate({ backgroundColor: bgcolor }, 1000);
		    }
		});
		jQuery(".quick-links .corner-box .important a").bind({
		    'focus mouseenter': function() {
    		    var bgcolor = "#960f51";
		        jQuery(this).stop().css({ backgroundColor: "" }).animate({ backgroundColor: bgcolor }, 1000);
		    }
		});
		jQuery(".quick-links .corner-box a").bind('blur mouseleave', function() { jQuery(this).stop().css({ backgroundColor: "" }); });
		/***** CONTROL PANEL BOXES *****/

		var boxes = jQuery("#tertiaryContent .boxes-container .box");
		var parentBoxes = jQuery("#tertiaryContent").closest("div.profile");
		var profile = (parentBoxes.size() == 1) ? true : false;
		if (boxes.size() > 0) {
		    boxes.each(function(i) {
		        var elt = jQuery(this);
		        var schemeBox = elt.children("div:first");
		        if (schemeBox.size() == 1) {
		            var boxClass = schemeBox.attr("class");
		            var boxId = schemeBox.attr("id");
		            var modele = /search/i;
		            var personaliseBox = /hand/i;

		            //the following will not apply on the search box
		            if (boxId.search(personaliseBox) == -1) {//all boxes except personalise one
		                //-1 if "hand" is not found or >0 index of "hand"
		                var clickElt = jQuery('<a class="click" href="#" title="open it">&nbsp;</a>');
		                var clickableTitle = elt.find("h2:first");
		                if (boxId == "related") {
		                    clickableTitle = elt.find("h3.more");
		                }
		                var contentSection = schemeBox.children("div.content:first");
		                jQuery(clickElt).bind({
		                    'click': function() {
		                        if (jQuery.browser.msie && (ieX == 7 || ieX == 6) && schemeBox.attr("id") == "drop") { jQuery(".white-box", contentSection).css({ visibility: "hidden" }); }
		                        if (schemeBox.hasClass("opened")) {
		                            contentSection.slideUp("slow");
		                            schemeBox.removeClass("opened");
		                            schemeBox.addClass("closed");
		                            jQuery(this).attr("title", "open it");
		                            forgetOpened(schemeBox.attr("id"));
		                        }
		                        else {
		                            contentSection.slideDown("slow", function() { if (jQuery.browser.msie && (ieX == 7 || ieX == 6) && schemeBox.attr("id") == "drop") { jQuery(".white-box", contentSection).css({ visibility: "visible" }); } });
		                            schemeBox.removeClass("closed");
		                            schemeBox.addClass("opened");
		                            jQuery(this).attr("title", "close it");
		                            rememberOpened(schemeBox.attr("id"));
		                        }
		                        return false;
		                    },
		                    'keypress': function(e) {
		                        if (e.which == '13') {
		                            if (jQuery.browser.msie && (ieX == 7 || ieX == 6) && schemeBox.attr("id") == "drop") { jQuery(".white-box", contentSection).css({ visibility: "hidden" }); }
		                            if (schemeBox.hasClass("opened")) {
		                                contentSection.slideUp("slow");
		                                schemeBox.removeClass("opened");
		                                schemeBox.addClass("closed");
		                                jQuery(this).attr("title", "open it");
		                                forgetOpened(schemeBox.attr("id"));
		                            }
		                            else {
		                                contentSection.slideDown("slow", function() { if (jQuery.browser.msie && (ieX == 7 || ieX == 6) && schemeBox.attr("id") == "drop") { jQuery(".white-box", contentSection).css({ visibility: "visible" }); } });
		                                schemeBox.removeClass("closed");
		                                schemeBox.addClass("opened");
		                                jQuery(this).attr("title", "close it");
		                                rememberOpened(schemeBox.attr("id"));
		                            }
		                            return false;
		                        }
		                    }
		                });
		                var clickBt;
		                jQuery(clickableTitle).bind({
		                    'click': function() {
		                        if (jQuery.browser.msie && (ieX == 7 || ieX == 6) && schemeBox.attr("id") == "drop") { jQuery(".white-box", contentSection).css({ visibility: "hidden" }); }
		                        if (schemeBox.hasClass("opened")) {
		                            contentSection.slideUp("slow");
		                            schemeBox.removeClass("opened");
		                            schemeBox.addClass("closed");
		                            clickBt = jQuery(this).prev("a.click");
		                            clickBt.attr("title", "open it");
		                            forgetOpened(schemeBox.attr("id"));
		                        }
		                        else {
		                            contentSection.slideDown("slow", function() { if (jQuery.browser.msie && (ieX == 7 || ieX == 6) && schemeBox.attr("id") == "drop") { jQuery(".white-box", contentSection).css({ visibility: "visible" }); } });
		                            schemeBox.removeClass("closed");
		                            schemeBox.addClass("opened");
		                            clickBt = jQuery(this).prev("a.click");
		                            clickBt.attr("title", "close it");
		                            rememberOpened(schemeBox.attr("id"));
		                        }
		                    },
		                    'mouseenter': function() {
		                        (jQuery(this).prev()).addClass("focus");
		                    },
		                    'mouseleave': function() {
		                        (jQuery(this).prev()).removeClass("focus");
		                    }
		                });


		                jQuery(clickElt).prependTo(schemeBox);
		                contentSection.hide();
		                if (!schemeBox.hasClass("closed")) {
		                    schemeBox.addClass("closed");
		                }
		                //now take off Related content and add in correct place
		                if ((jQuery('#related .content').children()).length) {
		                    jQuery('#related').find('a.click').insertBefore("#related .more");
		                } else {
		                    jQuery('#related a.click,#related .content,#related h3.more').remove();
		                }
		            }
		        }
		    });
		}
		checkRHScookies();
		
		if (jQuery(".sitemap").size() > 0) {
		    jQuery(".sitemap .allowSubLevel").each(function() {
		        var ulElt = jQuery(this).find("ul:first");
		        if (ulElt.length) {
		            jQuery(this).wrapInner('<div class="closing-box"></div>');
		            ulElt.wrap('<div class="content"></div>');
		            jQuery(this).addClass("dotted");
		        }
		    }); 
		    
		}

		/* closed / opened boxes*/
		var closingBoxes = jQuery(".closing-box");
		if (closingBoxes.size() > 0) {
		    closingBoxes.each(function(i) {
		        var elt = jQuery(this);
		        //the defaultOpen class denotes if box should be opened automatically
		        if (elt.hasClass("defaultOpen")) {
		            var clickElt = jQuery('<a class="click" href="#" title="close it">&nbsp;</a>');
		        } else {
		            var clickElt = jQuery('<a class="click" href="#" title="open it">&nbsp;</a>');
		        }
		        var contentSection = elt.find("div.content:first");
		        //button clickable
		        jQuery(clickElt).bind({
		            'click': function() {
		                if (elt.hasClass("opened")) {
		                    contentSection.slideUp("slow");
		                    elt.removeClass("opened");
		                    elt.addClass("closed");
		                    jQuery(this).attr("title", "open it");
		                }
		                else {
		                    contentSection.slideDown("slow");
		                    elt.removeClass("closed");
		                    elt.addClass("opened");
		                    jQuery(this).attr("title", "close it");
		                }
		                return false;
		            },
		            'keypress': function(e) {
		                if (e.which == '13') {
		                    if (elt.hasClass("opened")) {
		                        contentSection.slideUp("slow");
		                        elt.removeClass("opened");
		                        elt.addClass("closed");
		                        jQuery(this).attr("title", "open it");
		                    }
		                    else {
		                        contentSection.slideDown("slow");
		                        elt.removeClass("closed");
		                        elt.addClass("opened");
		                        jQuery(this).attr("title", "close it");
		                    }
		                    return false;
		                }
		            }
		        });
		        //title clickable
		        //default h2
		        var isBox = false;
		        var title = elt.children("h2:first"); //h2
		        if (elt.children("div.is").length) {
		            //or The Information Standard box and in this case the clickable title is a section
		            title = elt.find("div.title:first");
		            isBox = true;
		        }
		        if (title.size() == 0) {
		            //or h3
		            title = elt.children("h3:first");
		        }
		        jQuery(title).bind({
		            'click': function() {
		                if (elt.hasClass("opened")) {
		                    contentSection.slideUp("slow");
		                    elt.removeClass("opened");
		                    elt.addClass("closed");
		                    clickElt.attr("title", "open it");
		                }
		                else {
		                    contentSection.slideDown("slow");
		                    elt.removeClass("closed");
		                    elt.addClass("opened");
		                    clickElt.attr("title", "close it");
		                }
		                return false;
		            },
		            'keypress': function(e) {
		                if (e.which == '13') {
		                    if (elt.hasClass("opened")) {
		                        contentSection.slideUp("slow");
		                        elt.removeClass("opened");
		                        elt.addClass("closed");
		                        clickElt.attr("title", "open it");
		                    }
		                    else {
		                        contentSection.slideDown("slow");
		                        elt.removeClass("closed");
		                        elt.addClass("opened");
		                        clickElt.attr("title", "close it");
		                    }
		                    return false;
		                }
		            },
		            'mouseenter': function() {
		                (jQuery(this).prevAll("a.click:first")).addClass("focus");
		            },
		            'mouseleave': function() {
		                (jQuery(this).prevAll("a.click:first")).removeClass("focus");
		            }
		        });
		        if (isBox) {
		            jQuery(clickElt).prependTo(elt.children("div.is"));
		        }
		        else {
		            jQuery(clickElt).prependTo(elt);
		        }

		        //the defaultOpen class denotes if box should be opened automatically
		        if (elt.hasClass("defaultOpen")) {
		            elt.addClass("opened");
		        } else {
		            contentSection.hide();
		            if (!elt.hasClass("closed")) {
		                elt.addClass("closed");
		            }
		        }

		        //the showHide class denotes if h2 or h3 (anything with class="toggle") can be used as well as the arrow box
		        if (jQuery('.showHide').size() > 0) {

		            var clickh2Elt = jQuery(this).find(".toggle");
		            jQuery(clickh2Elt).bind({
		                'click': function() {
		                    if (elt.hasClass("opened")) {
		                        contentSection.slideUp("slow");
		                        elt.removeClass("opened");
		                        elt.addClass("closed");
		                    }
		                    else {
		                        contentSection.slideDown("slow");
		                        elt.removeClass("closed");
		                        elt.addClass("opened");
		                    }
		                    return false;
		                },
		                'keypress': function(e) {
		                    if (e.which == '13') {
		                        if (elt.hasClass("opened")) {
		                            contentSection.slideUp("slow");
		                            elt.removeClass("opened");
		                            elt.addClass("closed");
		                        }
		                        else {
		                            contentSection.slideDown("slow");
		                            elt.removeClass("closed");
		                            elt.addClass("opened");
		                        }
		                        return false;
		                    }
		                }
		            });
		        }
		    });
		}

// temp to avoid errors - CD
var commentOverride = false;
var commentListOverride = false;

		if (jQuery(".comments").size()) {
			if (commentOverride) {
				jQuery('#comment-entry a').click();
			}
			if (commentListOverride) {
				jQuery('#comment-list a').click();
			}
		}

		/* details boxes open/close */
		var detailsBoxes = jQuery(".details");
		if (detailsBoxes.size() > 0) {
		    detailsBoxes.each(function(i) {
		        var elt = jQuery(this);
		        var clickElt = jQuery('<a class="click" href="#" title="open it">&nbsp;</a>');
		        var contentSection = elt.children("div.content:first");
		        jQuery(clickElt).bind({
		            'click': function() {
		                if (elt.hasClass("opened")) {
		                    contentSection.slideUp("slow");
		                    elt.removeClass("opened");
		                    elt.addClass("closed");
		                    jQuery(this).attr("title", "open details");
		                }
		                else {
		                    contentSection.slideDown("slow");
		                    elt.removeClass("closed");
		                    elt.addClass("opened");
		                    jQuery(this).attr("title", "close detail");
		                }
		                return false;
		            },
		            'keypress': function(e) {
		                if(e.which=='13'){
		                    if (elt.hasClass("opened")) {
		                        contentSection.slideUp("slow");
		                        elt.removeClass("opened");
		                        elt.addClass("closed");
		                        jQuery(this).attr("title", "open details");
		                    }
		                    else {
		                        contentSection.slideDown("slow");
		                        elt.removeClass("closed");
		                        elt.addClass("opened");
		                        jQuery(this).attr("title", "close detail");
		                    }
		                    return false;
		                }
		            }
		        });
		        jQuery(clickElt).prependTo(elt);

		        if (elt.hasClass("defaultOpen")) {
		            elt.addClass("opened");
		        } else {
		            contentSection.hide();
		            if (!elt.hasClass("closed")) {
		                elt.addClass("closed");
		            }
		            contentSection.hide();
		        }
		    });
		}

		if (jQuery("#tertiaryContent").size()) {
			if (!(typeof (locationOverride) == "undefined")) {
				if (locationOverride) { jQuery('.location a.click').click(); }
			}
		}

		/***** HELP BUBBLES / TOOLTIPS *****/

		jQuery("span.help").each(function() {
		    var help = jQuery(this);
		    var helpClass = help.attr("class");
		    var title = help.children('.helpTitle').text();
		    var text = help.children('.helpText').html();
		    var newText = '<div class="' + helpClass + '"><a class="question-mark" href="#">More about this field</a><div class="bubble"><div class="content"><div class="title"><span>' + title + '</span><span class="closebubble"><a href="#" class="close">Close</a></span></div><div class="text">' + text + '</div></div></div></div>';
		    help.replaceWith(newText);
		    jQuery('.bubble .close').bind({
		        'mouseenter focus': function() {
		            (jQuery(this).parents('.closebubble:first')).addClass('focus');
		        },
		        'mouseleave blur': function() {
		            (jQuery(this).parents('.closebubble:first')).removeClass('focus');
		        },
		        'click': function() {
    		        (jQuery(this).parents('div.bubble:first')).fadeOut(200);
		            return false;
		        },
		        'keypress': function(e) {
		            if (e.which == '13') {
		                (jQuery(this).parents('div.bubble:first')).fadeOut(200);
		                return false;
		            }
		        }
		    });
		});

        jQuery(".question-mark").bind({
            'click': function() {
                jQuery('div.bubble').fadeOut(200);
                jQuery(this).addClass('focus');
                var help = jQuery(this).parents('.help:first');
                //jQuery('div.bubble', help).fadeOut(200);
                //var box = help.parent();
                jQuery("div.bubble", help).fadeIn(200, function() { jQuery(this).focus(); });
                return false;
            },
            'mouseleave blur': function() {
                jQuery(this).removeClass('focus');
            },
            'mouseenter focus': function() { jQuery(this).addClass('focus'); return false; },
            'keypress': function(e) {
                if (e.which == '13') {
                jQuery('div.bubble').fadeOut(200);
                jQuery(this).addClass('focus');
                var help = jQuery(this).parents('.help:first');
                //jQuery('div.bubble', help).fadeOut(200);
                //var box = help.parent();
                jQuery("div.bubble", help).fadeIn(200, function() { jQuery(this).focus(); });
                return false;
                }
            }
        });

		/* calendar bubbles */
		jQuery(".calendar a.booked").each(function(index) {
			var aElt = jQuery(this);
			//get appointment id targetted by the link
			//var id = aElt.attr("href", "return false;");
			var bubble = aElt.nextAll("div.appointment:first");
			var position = aElt.position();
			bubble.css({ "top": (position.top - bubble.height()), "left": (position.left - 68) });
			//aElt.click(function() { return false; });
			//aElt.keypress(function() { return false; });
			aElt.mouseenter(function() { bubble.css({ "visibility": "visible" }); });
			aElt.mouseleave(function() { bubble.css({ "visibility": "hidden" }); });
		});

        // restoring the graph jquery functionality needs to be done after an update as well as on Ready, so moved outside of DoEverything
		enhanceGraph();


		// External links:
		// class new shows logo and opens in new window
		// class newinline opens in new window
		var newLinks = jQuery("a.new");
		if (newLinks.size() > 0) {
			newLinks.append(" <span>(open in new window)</span>");
			newLinks.each(function() {
			    if (!jQuery(this).hasClass("userinput")) {
			        jQuery(this).attr("title", "open in a new window");
			    } else {
			        if (jQuery(this).attr('title') == "") { jQuery(this).attr("title", "open in a new window"); }
			    }
			});
			newLinks.bind({
			    'click': function() {
			        window.open(jQuery(this).attr("href"));
			        return false;
			    },
			    'keypress': function(e) {
			        if (e.which == '13') {
			            window.open(jQuery(this).attr("href"));
			            return false;
			        }
			    }
			});
        }
        var newLinks = jQuery("a.newinline");
        if (newLinks.size() > 0) {
            newLinks.each(function() {
                if (!jQuery(this).hasClass("userinput")) {
                    jQuery(this).attr("title", "open in a new window");
                } else {
                    if (jQuery(this).attr('title') == "") { jQuery(this).attr("title", "open in a new window"); }
                }
            });
            newLinks.bind({
                'click': function() {
                    window.open(jQuery(this).attr("href"));
                    return false;
                },
                'keypress': function(e) {
                    if (e.which == '13') {
                        window.open(jQuery(this).attr("href"));
                        return false;
                    }
                }
            });
        }

		//print link opening in a new window
		var prints = jQuery("a.print");
		prints.bind({
		    'click':function() {
			    window.open(jQuery(this).attr("href"));
			    return false;
		    },
		    'keypress':function(e) {
			    if(e.which=='13'){
			    window.open(jQuery(this).attr("href"));
			    return false;
			    }
		    }
		});

		var personaButtons = jQuery('.personalise a');
		personaButtons.bind({
		    'mouseenter': function() {
		        jQuery(this).toggleClass("focus");
		    },
		    'mouseleave': function() {
		        jQuery(this).toggleClass("focus");
		    },
		    'click': function() {
		        var mydate = new Date();
		        mydate.setTime(mydate.getTime() + (1 * 24 * 60 * 60 * 1000)); //for 30 days
		        var scrOfY = 0;
		        if (typeof (window.pageYOffset) == 'number') {
		            //page offset provided as a number
		            scrOfY = window.pageYOffset;
		        } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
		            //DOM compliant
		            scrOfY = document.body.scrollTop;
		        } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
		            //IE6 standards compliant mode
		            scrOfY = document.documentElement.scrollTop;
		        }

		        document.cookie = "yOffset=" + scrOfY + "; expires=" + mydate.toGMTString() + ";path=/";
		    }
		});
		
/*
personaButtons.click(function() {
var contentURL = jQuery(this).attr('href') + '&mode=ajax';
var fixedHeight = jQuery('#content').outerHeight();
 jQuery.get(contentURL, function(data) {
var d = jQuery(data);
jQuery('#ajaxtitle').replaceWith(
d.find('#ajaxtitle')
);
jQuery('#ajaxcontent').replaceWith(
d.find('#ajaxcontent')
);
jQuery('#ajaxaccreditation').replaceWith(
d.find('#ajaxaccreditation')
);
jQuery('#ajaxrightcolboxes').replaceWith(
d.find('#ajaxrightcolboxes')
);
jQuery('#ajaxmyexternallinks').replaceWith(
d.find('#ajaxmyexternallinks')
);
jQuery('#ajaxotherarticles').replaceWith(
d.find('#ajaxotherarticles')
);
// header background image
jQuery('#BgImgDiv').attr('style', d.find('.BgImgDiv').attr('style'));
DoEverything();
});
return false;
});
*/
		/***** RATE THIS *****/

		if (jQuery(".rate-this").size()) {
			if (allowVote) {
				jQuery(".rate-this img").mouseover(function() {
					var imgId = jQuery(this).attr("id");
					var thisId = parseFloat(imgId.substr(5));

					for (i = 1; i <= thisId; i++) {
						jQuery(".rate-this img:eq(" + i + ")").attr("src", "/images/templates/rate/star-full-value.gif");
					}
					for (i = 5; i >= thisId; i--) {
						jQuery(".rate-this img:eq(" + i + ")").attr("src", "/images/templates/rate/star-empty.gif");
					}
				});
				jQuery(".rate-this").mouseout(function() {
					for (i = 1; i <= 5; i++) {
						var thisImg = jQuery(".rate-this img:eq(" + i + ")");
						if (thisImg.hasClass("full")) {
							thisImg.attr("src", "/images/templates/rate/star-full-value.gif");
						} else if (thisImg.hasClass("half")) {
							thisImg.attr("src", "/images/templates/rate/star-half-value.gif");
						} else {
							thisImg.attr("src", "/images/templates/rate/star-empty.gif");
						}
					}
				});
			}
		}

		/***** FEATURES *****/
		function features() {
		    var features = jQuery(".features");
		    if (features.length) {
		        features.each(function() {
		            feature = jQuery(this);
		            //maximum 4 items
		            jQuery('.slides li:gt(3)', feature).remove();
		            feature.append('<div class="selectors block"><ol></ol></div>');
		            var bodyClass = jQuery('body').attr('class');
		            var section = '';
		            var ext = 'png';
		            if (jQuery.browser.msie && ieX == 6) { ext = 'gif'; }
		            if (bodyClass.indexOf('hiv') >= 0) { section = 'hiv-'; }
		            if (bodyClass.indexOf('charity') >= 0) { section = 'charity-'; }
		            jQuery('.slides h2', feature).each(function(i) {
		                jQuery('.selectors ol', feature).append('<li><img class="topSelector" src="/images/templates/backgrounds/' + section + 'features-top-selector.'+ext+'" alt="" /><a href="#' + (jQuery(this).parents('li:first')).attr('id') + '">' + jQuery(this).text() + '</a></li>');
		            });
		            jQuery('.selectors li:last', feature).addClass('last');
		            feature.wrapInner('<div class="fade" />');
		            //default side displayed
		            jQuery('.selectors li:first', feature).addClass('active');
		            jQuery('.slides li:first', feature).addClass('active');
		        });
		        var selectors = jQuery('.features .selectors li a');
		        if(selectors.length){
		            selectors.bind({
		                'click': function() { return false; },
		                'keypress': function(e) { if (e.which == '13') { return false; } },
		                'mouseenter focus': function() {
		                    var selector = jQuery(this);
		                    var currentFeature = selector.parents('.features:first');
		                    //jQuery('.slides li,.selectors li', currentFeature).stop();
		                    //var fade = selector.parents('.fade:first');
		                    currentFeature.addClass('current');
		                    var indexActive = jQuery('.selectors li', currentFeature).index(selector.parents('li:first'));
		                    var activeSlide = jQuery('.slides li:eq(' + indexActive + ')', currentFeature);
		                    var currentActiveSlide = jQuery('.slides li.active', currentFeature);

		                    //selector animation
		                    var bgcolorActive = '#580034'; var bgColor = '#8c0052';
		                    var bgImage = 'url(../images/templates/backgrounds/features-top-selector.png)';
		                    var bodyClass = jQuery('body').attr('class');
		                    if (bodyClass.indexOf('hiv') >= 0) { bgcolorActive = '#003b5a'; bgColor = '#0f7bae'; bgImage = 'url(../images/templates/backgrounds/hiv-features-top-selector.png)'; }
		                    if (bodyClass.indexOf('charity') >= 0) { bgcolorActive = '#001148'; bgColor = '#21409a'; bgImage = 'url(../images/templates/backgrounds/charity-features-top-selector.png)'; }
		                    jQuery('.selectors li a', currentFeature).stop().css({ 'background-color': bgColor });
		                    jQuery('.selectors li img', currentFeature).stop().css({ 'opacity': 0 });
		                    jQuery('.selectors li.active', currentFeature).removeClass('active');
		                    selector.prev('img.topSelector').animate({'opacity':1},500);
		                    selector.animate({ 'background-color': bgcolorActive }, 500, function() { (jQuery(this).parents('li:first')).addClass('active'); });

		                    //slide animation
		                    jQuery('.slides li', currentFeature).stop().css({ opacity: '', display: '' });
		                    currentActiveSlide.fadeOut(500, function() { jQuery(this).removeClass('active'); });
		                    activeSlide.fadeIn(500, function() { jQuery(this).addClass('active'); });
		                    currentFeature.removeClass('current');

		                    //jQuery(this).stop().css({ backgroundColor: "" }).animate({ backgroundColor: bgcolor }, 500);
		                }
		            });
		        }
		    }
		}
		features();
		
		/***** CONTACTUS *****/

		jQuery('.contactUs').prepend('<ol></ol>');
		jQuery('.contactUs').each(function(i) {
		    var contactElt = jQuery(this);
		    jQuery('li h2', jQuery(this)).each(function(i) {
		    jQuery('ol', contactElt).append('<li></li>');
		        jQuery(this).parent('li').attr('id', 'cont' + i);
		        jQuery(this).clone().wrapInner('<a href="cont' + i + '"></a>').appendTo('ol li:last', contactElt);
		        jQuery('ol li:last', contactElt).addClass('cont' + i);
		    });
		});
		jQuery('.contactUs,.contactUs').each(function(){
		    jQuery('ol li:first,ul li:first',jQuery(this)).addClass('active');
		});
		    
		jQuery('.contactUs ol a').click(function() {
		    var parent = jQuery(this).parents(".contactUs:first");
		    jQuery('li',parent).removeClass('active');
		    var cont = jQuery(this).parents('li').attr('class');
		    jQuery(this).parents('li').addClass('active');
		    jQuery('ul li#' + cont,parent).addClass('active');
		    return false;
		});

		/***** TABS *****/

		function tabs(){
				jQuery('.tabs .jump li:first, .tabs .tab:first').addClass('active');
			jQuery('.tabs .jump li').each(function(i) {
				jQuery(this).attr('id', 'tab' + i);
			});
			jQuery('.tabs .tab').each(function(i) {
				jQuery(this).addClass('tab' + i);
			});
			jQuery('.tabs .jump a').click(function() {
				jQuery('.tabs .tab, .tabs .jump li').removeClass('active');
				var tab = jQuery(this).parents('li').attr('id');
				jQuery(this).parents('li').addClass('active');
				jQuery('.tabs .' + tab).addClass('active');
				return false;
			});
		}
		tabs();

		/***** TABS2 *****/
		//because Tabs above doesn't suit purpose (service finder)

		jQuery('.tabs2').each(function() {
		    //create labels
		    var panes = jQuery(this).find(".pane");
		    panes.removeClass("block");
		    if (panes.size() > 0) {
		        var labels = jQuery('<ul class="labels" />');
		        var liClass = "";
		        var li;
		        panes.each(function() {
		            liClass = jQuery(this).attr("class");
		            liClass = liClass.replace("pane ", "");
		            li = jQuery('<li class="' + liClass + '">'+jQuery("h3.hide", jQuery(this)).text()+'</li>');
		            li.wrapInner('<a class="tag" />')
		            li.append(jQuery("h3 + div.help", jQuery(this)).detach());
		            li.wrapInner('<div class="tabTitle" />')
		            labels.append(li);
		        });
		    }
		    jQuery(this).prepend(labels);
		    var activeTab = jQuery(this).find('ul.labels li .active');
		    if (activeTab.size() == 0) {
		        jQuery(this).children('.pane').addClass("off");
		        jQuery(this).children('.pane:first').removeClass("off");
		        jQuery(this).find('ul li .tabTitle:first').addClass('active');
		    }
		    else {
		        var whichTabs = activeTab.parents('.tabs2');
		        var whichpane = (activeTab.parents('li:first')).attr('class');
		        whichTabs.find('.pane').removeClass("off");
		        whichTabs.find('.pane').addClass("off");
		        jQuery('.tabs2 .' + whichpane).removeClass("off");
		    }
		});
		jQuery('.tabs2 ul.labels li a.tag').bind({
		    'click': function() {
		        var whichTabs = jQuery(this).parents('.tabs2');
		        var whichpane = (jQuery(this).parents('li:first')).attr('class');
		        whichTabs.find('.pane').removeClass("off");
		        whichTabs.find('.pane').addClass("off");
		        whichTabs.find('ul.labels li .tabTitle').removeClass('active');
		        jQuery('.tabs2 .' + whichpane).removeClass("off");
		        (jQuery(this).parents('.tabTitle')).addClass('active');
		    }
		});
		jQuery('.tabs2 ul.labels li .tabTitle').bind({
		    'mouseenter': function() { jQuery(this).addClass('focus'); },
		    'mouseleave': function() { jQuery(this).removeClass('focus'); }
		});

		/***** DATE PICKER *****/

		//hook a picker on each .datepicker class elt
		jQuery(".datepicker").each(function() {
			//hook and set up the date format: dd/mm/yyyy
			jQuery(this).datepicker({
				dateFormat: 'dd/mm/y',
				firstDay: 1
			});
			var initialDate = jQuery(this).val();
			if ((initialDate != "") && (/^\d{2}\/\d{2}\/\d{4}$/.test(initialDate))) {//if there is a date defined
				var tabValues = initialDate.split("/");
				var d = parseInt(tabValues[0]);
				var m = parseInt(tabValues[1]);
				var y = parseInt(tabValues[2]);
				jQuery(this).datepicker('setDate', new Date(y, m - 1, d));
			}
		});

		/***** VIDEO PLAYER *****/
		/*
		only appearing if there is an call to an overlay on the page
		=> to be confirmed it does work please - val
		*/
		var overlay = jQuery("div#overlay:first");
		if (overlay.size() == 1) {
			var overlayClone = jQuery("div#overlay:first").clone();
			overlay.remove();
			jQuery("body").prepend(overlayClone);

			/*OVERLAY PLAYER*/
			// install flowplayer into flowplayer container
			var player = flowplayer("player", "/player/flowplayer-3.2.5.swf", {
				clip: {
					autoPlay: true,
					autoBuffering: true,
					width: "468px",
					height: "240px",
					scaling: "fit",
					onStart: function() {
					    SitecoreLogEvent("vidgo",rcolVidData,rcolVidContext);
    				},
                    onFinish: function() {
					    SitecoreLogEvent("vidend",rcolVidData,rcolVidContext);
    				}
				},
				canvas: {
					backgroundColor: "#333333"
				},
				plugins: {
					'controls': {
						height: "25px",
						all: false,
						play: true,
						scrubber: true,
						mute: true,
						volume: true,
						fullscreen: true,
						autoHide: { enabled: false },
						bufferColor: '#21409a',
						volumeSliderColor: '#21409a'
					}
				}
			});
			// setup button action. it will fire our overlay
			jQuery("a.overlay-link").append('<img class="noborder play" src="/images/templates/buttons/play.png" alt="play button" width="44" height="44"/>');
			jQuery("a.overlay-link").overlay({
				expose: {
					color: "#001148",
					opacity: "0.5"
				},
				target: "div#overlay",
				// when overlay is opened, load our player
				onLoad: function() {
					player.load();
				},
				// when overlay is closed, unload our player
				onClose: function() {
                    player.stop();
					player.unload();
				}
			});
		}

		/***** DRUGS EDITOR *****/
		if (jQuery('.drug-stack').length > 0) {
			jQuery('.drug-details').hide();
			jQuery('.drug-stack input:checked').each(function() {
				jQuery(this).parents('.drug-selection').siblings('.drug-details').show();
			});
			jQuery('.drug-stack input:checkbox').change(function() {
				if (jQuery(this).is(':checked')) {
					jQuery(this).parents('.drug-selection').siblings('.drug-details').slideDown();
					jQuery('.noTreatment').attr('checked', false);
				}
				else {
					jQuery(this).parents('.drug-selection').siblings('.drug-details').slideUp();
				}
			});
		}

		/***** VIDEOS GALLERY *****/
		jQuery(".gallery a.overlay-preview").mouseenter(function() {
			var aElt = jQuery(this);
			aElt.children("span.title:first").slideDown('fast');
		});
		jQuery(".gallery a.overlay-preview").mouseleave(function() {
			var aElt = jQuery(this);
			aElt.children("span.title:first").slideUp('fast');
		});

		/***** Even up Section Homepage Poll & Quiz *****/
		if ( (jQuery('.homepage .quiz').length > 0) || (jQuery('.homepage .poll').length > 0) ) {
		    var maxHeight = 0;
		    jQuery('.homepage .poll .middle').each(function(index) {
		        if (jQuery(this).height() > maxHeight) { maxHeight = jQuery(this).height(); } 
		    });
		    jQuery('.homepage .quiz .middle').each(function(index) {
		         if (jQuery(this).height() > maxHeight) { maxHeight = jQuery(this).height(); } 
		    });
		    jQuery('.homepage .w330 .middle').css({'min-height':maxHeight});
		}

		/***** Align two line headings on sub landing pages *****/
		if (jQuery('.landing-listing').length > 0) {
			var container = jQuery('.landing-listing .columns-container');
			container.each(function() {
				var maxHeight = 0;
				jQuery('.column h2', jQuery(this)).each(function(index) {
					if (jQuery(this).height() > maxHeight) { maxHeight = jQuery(this).height(); }
				});
				jQuery('.column h2', jQuery(this)).css({ 'min-height': maxHeight });
			});
		}
		
		/**** FAQS ****/
		if (jQuery(".faqs").length > 0) {
			jQuery(".faqs .faqs-listing").remove();
			jQuery(".faqs .backtop").remove();
        }
		/**** SUBMIT MY STORY ****/
        jQuery('.scfForm h1').replaceWith('<h2>Submit my story</h2>');

		/**** PUBLICATION SHOP ****/
		jQuery(".form .shop-registration .same-address-as input[type=checkbox]").change(function() {
			var checkbox = jQuery(this);
			var firstname = jQuery(".form .shop-registration .firstname input[type=text]");
			var lastname = jQuery(".form .shop-registration .lastname input[type=text]");
			var address1 = jQuery(".form .shop-registration .address1 input[type=text]");
			var address2 = jQuery(".form .shop-registration .address2 input[type=text]");
			var address3 = jQuery(".form .shop-registration .address3 input[type=text]");
			var postcode = jQuery(".form .shop-registration .postcode input[type=text]");
			var country = jQuery(".form .shop-registration .country select");
			var deliveryname = jQuery(".form .shop-registration .deliveryname input[type=text]");
			var deliveryaddress1 = jQuery(".form .shop-registration .deliveryaddress1 input[type=text]");
			var deliveryaddress2 = jQuery(".form .shop-registration .deliveryaddress2 input[type=text]");
			var deliveryaddress3 = jQuery(".form .shop-registration .deliveryaddress3 input[type=text]");
			var deliverypostcode = jQuery(".form .shop-registration .deliverypostcode input[type=text]");
			var deliverycountry = jQuery(".form .shop-registration .deliverycountry select");

			if (checkbox.attr("checked")) {
				deliveryname.val(firstname.val() + " " + lastname.val());
				deliveryaddress1.val(address1.val());
				deliveryaddress2.val(address2.val());
				deliveryaddress3.val(address3.val());
				deliverypostcode.val(postcode.val());
				deliverycountry.val(country.val());
			}
			else {
				deliveryname.val("");
				deliveryaddress1.val("");
				deliveryaddress2.val("");
				deliveryaddress3.val("");
				deliverypostcode.val("");
				deliverycountry.val("Select a country");
			}
        });
        jQuery('.googleMap').ready(function() { jQuery('.googlemapLink').hide(); });

	}
	
/***** FUNCTIONS *****/

//These functions set or delete cookies to track if rhs boxes are open or not
function rememberOpened(which) {
    var mydate = new Date();
    mydate.setTime(mydate.getTime() + (30 * 24 * 60 * 60 * 1000)); //for 30 days
    document.cookie = which + "=open; expires=" + mydate.toGMTString() +";path=/";
}
function forgetOpened(which) {
    var mydate = new Date();
    mydate.setTime(mydate.getTime() + (30 * 24 * 60 * 60 * 1000));//for 30 days
    document.cookie = which + "=closed; expires=" + mydate.toGMTString() +";path=/";
}
function checkRHScookies() {
    donateC = getCookie('donate');
    if (donateC == "open") { jQuery('#donate a.click').click(); }
    dropC = getCookie('drop');
    if (dropC == "open") { jQuery('#drop a.click').click(); }
    relatedC = getCookie('related');
    if (relatedC == "open") { jQuery('#related a.click').click(); }
    searchC = getCookie('search');
    if (searchC == "open") { jQuery('#search a.click').click(); }
}
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

/***** scroll to yOffset if we did request a persona *****/
function offsetPersonas() {
    if (window.document.URL.indexOf("?Persona") > 0) {
        window.scrollTo(0, parseInt(getCookie("yOffset")));
    }
}

/***** SHOW/HIDE LABELS IN TEXT INPUTS *****/
function inputsText() {
    jQuery(".servicePostcode")
        .focus(function() {
            if (jQuery(this).val() == "Enter your postcode") {
                jQuery(this).val("");
            }
        })
        .blur(function() {
            if (jQuery(this).val() == "") {
                jQuery(this).val("Enter your postcode");
            } else {
                jQuery('option', jQuery(this).siblings('.serviceOffice:first')).removeAttr("selected");
                jQuery('option:eq(0)', jQuery(this).siblings('.serviceOffice:first')).attr("selected","selected");
            }
        });
    jQuery(".serviceOffice")
        .change(function() {
            if (jQuery('option:eq(0)',jQuery(this)).attr("selected")!="selected") {
                jQuery(this).siblings('.servicePostcode:first').val("Enter your postcode");
            }
        });
    
    jQuery(".postcode").focus(function() { if (jQuery(this).val() == "Enter postcode") { jQuery(this).val(""); } }).blur(function() { if (jQuery(this).val() == "") { jQuery(this).val("Enter postcode"); } });

    jQuery("#topSearch input").focus(function() { if (jQuery(this).val() == "Keyword search") { jQuery(this).val(""); } }).blur(function() { if (jQuery(this).val() == "") { jQuery(this).val("Keyword search"); } });
    jQuery(".location input[type='text']").focus(function() { if (jQuery(this).val() == "Enter postcode") { jQuery(this).val(""); } }).blur(function() { if (jQuery(this).val() == "") { jQuery(this).val("Enter postcode"); } });

    jQuery(".jsUsername,.jsPassword").each(function() { if (jQuery(this).val() != "") { jQuery(this).addClass("noBg"); } });
    jQuery(".jsUsername,.jsPassword").focus(function() { jQuery(this).addClass("noBg"); }).blur(function() { if (jQuery(this).val() == "") { jQuery(this).removeClass("noBg"); } });
}

// restoring the graph jquery functionality needs to be done after an update as well as on Ready, so moved outside of DoEverything
function enhanceGraph() {
    jQuery('.graph area').each(function(index) {
        var areaElt = jQuery(this);
        areaElt.bind("keypress click", function() { return false; });
        areaElt.mouseenter(function() {
            var activeArea = jQuery(this);
            if (!activeArea.hasClass("active")) {
                jQuery('#levelInfo').stop(true).remove();
                //active the current area
                activeArea.addClass("active");

                var alt = activeArea.attr("alt");
                var hivid = activeArea.attr("id");
                var href = "/webservices/cd4andviralload.asmx";
                var type = 'v';
                var date = "";
                var val = 0;

                var arAlt = alt.split('\t');
                if (arAlt.length > 1) date = arAlt[1].replace(/^\s*/, "").replace(/\s*$/, "");
                if (arAlt.length > 2) type = ((arAlt[3].replace(/^\s*/, "").replace(/\s*$/, "").indexOf("CD4") >= 0) ? "c" : "v");
                if (arAlt.length > 4) val = arAlt[5].replace(/^\s*/, "").replace(/\s*$/, "");

                var graph = activeArea.parents('.graph:first');
                var bubble = jQuery('<div id="levelInfo" class="level"><div class="bubble"><div class="content"><p class="legend">Detail on the following input</p><p>Date: ' + date + '</p><p>' + ((type == "c") ? "CD4" : "Viral Load") + ' = ' + val + '</p></div></div></div>');

                //Delete button and method
                var deleteLink = jQuery('<a href="#" class="submit cancel">Delete</a>');
                deleteLink.bind('click', function() {
                    // call the web service to delete the value
                    jQuery.ajax({
                        url: href + "/ajaxDeleteResult",
                        data: { id: hivid, type: type },
                        type: "POST",
                        async: false,
                        error: function(XMLHttpRequest, textStatus, errorThrown)
                        {
                            alert("Your changes were not saved because the following error occurred:<br />" + XMLHttpRequest.responseText);
                        }, 
                        success: function(xml) {
                            resultText = jQuery(xml).text().replace('\n', "");
                            if (resultText == "OK")
                                resultText = "Your changes have been saved.";
                            else
                                resultText = "Your changes were not saved because the following error occurred:<br />" + resultText.substring(0, 100) + "...";
                        }
                    });

                    var overlay = jQuery('<div class="overlay"><div class="editResults"><p class="savedChanges">' + resultText + '</p></div></div>');
                    var close = jQuery('<a href="#" class="submit cancel">Close</a>');
                    close.bind('click keypress', function() {
                        (jQuery(this).closest('div.overlay')).slideUp(500, function() { jQuery(this).remove(); });
                        // refresh the graph and repeaters
                        refreshGraph("", "");
                        return false;
                    });
                    jQuery('.editResults', overlay).append(close);
                    overlay.css({ "display": "none" });
                    bubble.fadeOut(100, function() { bubble.remove(); graph.prepend(overlay); overlay.slideDown(500); });
                    return false;
                }); //end delete

                //Edit button and method
                var editLink = jQuery('<a href="#" class="submit">Edit</a>');
                editLink.bind('click', function() {
                    var overlay = jQuery('<div class="overlay"></div>');
                    //prepare the date picker field    
                    var dateField = jQuery('<input type="text" class="datepicker" id="dateOverlay" name="dateOverlay" value="' + date + '" />');
                    dateField.datepicker({
                        dateFormat: 'dd/mm/y',
                        firstDay: 1
                    });
                    var initialDate = dateField.val();
                    if ((initialDate != "") && (/^\d{2}\/\d{2}\/\d{4}$/.test(initialDate))) {//if there is a date defined
                        var tabValues = initialDate.split("/");
                        var d = parseInt(tabValues[0]);
                        var m = parseInt(tabValues[1]);
                        var y = parseInt(tabValues[2]);
                        dateField(this).datepicker('setDate', new Date(y, m - 1, d));
                    }
                    //date validation syntax
                    var patternDate = /^[0-9]{2}\/[0-9]{2}\/[0-9]{2}$/;
                    dateField.change(function() {
                        var dateInput = jQuery(this);
                        if (!patternDate.test(dateInput.val()) || dateInput.val() == "") {
                            alert("Syntax error: date format is required, e.g. 01/01/10.");
                            dateInput.val("dd/mm/yy");
                        }
                    });
                    dateField.focus(function() { jQuery(this).select(); });
                    //edit results section
                    //first fieldset
                    var editResults = jQuery('<div class="editResults" />');
                    editResults.append('<label for="dateOverlay">Date <span class="mandatory">*</span></label>');
                    editResults.append(dateField);
                    editResults.wrapInner('<fieldset class="row" />');
                    editResults.prepend('<p class="legend">Update the following input</p>');

                    var patternNb = /^[1-9][0-9]*$/;

                    //second fieldset
                    var secondFieldset = jQuery('<fieldset class="row" />');
                    if (type == "c")
                        secondFieldset.append('<label for="valueOverlay">CD4 count</label>');
                    else
                        secondFieldset.append('<label for="valueOverlay">Viral load</label>');

                    var valueField = "";
                    if (type == "c")
                        valueField = jQuery('<input class="cd4" type="text" id="valueOverlay" name="valueOverlay" value="' + val + '" />');
                    else
                        valueField = jQuery('<input class="viral" type="text" id="valueOverlay" name="valueOverlay" value="' + val + '" />');

                    //validation syntax
                    valueField.change(function() {
                        var valueInput = jQuery(this);
                        if (!patternNb.test(valueInput.val()) && valueInput.val() != "") {
                            alert("Syntax error: number format is required, e.g. 300.");
                            valueInput.val("");
                        }
                    });
                    //on focus select the input value
                    valueField.focus(function() { jQuery(this).select(); });
                    secondFieldset.append(valueField);
                    //secondFieldset.append('<span class="unit">CD4 count</span>');
                    editResults.append(secondFieldset);

                    //Cancel button
                    var cancelLink = jQuery('<a href="#" class="submit cancel">Cancel</a>');
                    cancelLink.bind('click', function() {
                        (jQuery(this).closest('div.overlay')).slideUp(500, function() { jQuery(this).remove(); });
                        return false;
                    }); //end cancel button

                    //Save button
                    var saveLink = jQuery('<a href="#" class="submit">Save</a>');
                    saveLink.bind('click', function() {
                        //validation mandatory
                        var validDateValue = patternDate.test(dateField.val()) && dateField.val() != "";
                        var validValue = patternNb.test(valueField.val());
                        var validForm = validDateValue && validValue;
                        var divOverlay = (jQuery(this).closest('div.overlay'));
                        var resultText = "";
                        if (validForm) {
                            //form is valid
                            (jQuery('.editResults', divOverlay).children()).remove();

                            jQuery.ajax({
                                url: href + "/ajaxUpdateResult",
                                data: { id: hivid, type: type, dateAdded: dateField.val(), value: valueField.val() },                                
				                type: "POST",
                                async: false,
                                error: function(XMLHttpRequest, textStatus, errorThrown)
                                {
                                    alert("Your changes were not saved because the following error occurred:<br />" + XMLHttpRequest.responseText);
                                },                                
                                success: function(xml) {
					                //alert(xml);
                                    resultText = jQuery(xml).text().replace('\n', "");
                                    if (resultText == "OK")
                                        resultText = "Your changes have been saved.";
                                    else
                                        resultText = "Your changes were not saved because the following error occurred:<br />" + resultText.substring(9, 100) + "...";
                               }
                            });

                            jQuery('.editResults', divOverlay).append(jQuery('<p class="savedChanges">' + resultText + '</p>'));
                            var close = jQuery('<a href="#" class="submit cancel">Close</a>');
                            close.bind('click', function() {
                                (jQuery(this).closest('div.overlay')).slideUp(500, function() { jQuery(this).remove(); });
                                // refresh the graph and repeaters
                                refreshGraph("", "");
                                return false;
                            }); //end close
                            jQuery('.editResults', divOverlay).append(close);
                        } else {
                            //form is not valid
                            jQuery('.formError', divOverlay).remove();

                            if (!validValue) {
                                jQuery('.editResults #valueOverlay', divOverlay).after(jQuery('<p class="formError">A value must be provided.</p>'));
                            }
                            if (!validDateValue) {
                                jQuery('.editResults #dateOverlay', divOverlay).after(jQuery('<p class="formError">Date is a mandatory field.</p>'));
                            }
                        }
                        return false;
                    }); //end save button

                    editResults.append(cancelLink);
                    editResults.append(saveLink);
                    overlay.append(editResults);
                    overlay.css({ "display": "none" });
                    bubble.fadeOut(100, function() { bubble.remove(); graph.prepend(overlay); overlay.slideDown(500); });
                    return false;
                });
                var content = bubble.find('.content:first');
                content.append(editLink);
                content.append(deleteLink);
                //prepend the bubble
                graph.prepend(bubble);
                var coords = activeArea.attr("coords");
                var coordsArray = coords.split(",");
                var x = coordsArray[0] - 139;
                var y = coordsArray[1] - 152;
                bubble.css({ "display": "none" });
                bubble.css({ "top": y + "px", "left": x + "px" });
                bubble.fadeIn(500);
                //alert(bubble.position().left); alert(bubble.position().top);
                //stop animation if over the bubble to access delete or edit button
                bubble.mouseenter(function() { jQuery(this).stop(true).fadeIn(); });
                bubble.mouseleave(function() { jQuery(this).fadeOut(500, function() { jQuery(this).remove(); activeArea.removeClass("active") }) });
            }
        });
        areaElt.mouseleave(function() {
            jQuery('#levelInfo').fadeOut(500, function() { jQuery(this).remove(); });
            jQuery(this).removeClass("active");
        });
    });
}

function SitecoreLogEvent(event,data,context) {
    var LogUrl = "/Utils/LogEvent.aspx?e=" + event + "&data=" + data + "&context=" + context;
    jQuery.get(LogUrl);
    //alert("Called: " + LogUrl);
}
