var mouseClicked;

// JQuery Scripts
$(document).ready(function() {

    //general
    $("a").focus(function() {
        $(this).blur();
    });

    $(document).click(function(e) {
        mouseClicked = e;
        //leftVal=e.pageX-(width/2)+"px";
        //topVal=e.pageY-(height/2)+"px"; 
        //show the popup message and hide with fading effect
        //$('#popuup_div').css({left:leftVal,top:topVal}).show().fadeOut(1500);
    });

    //help
    $("a.que").click(function() {
        $(this).addClass("on")
		.siblings("div.ans").show()
		.siblings("a.cls").show();
        return false;
    });

    $("a.cls").click(function() {
        $(this).siblings("div.ans").hide()
		.siblings("a.que").removeClass("on");
        $(this).hide();
        return false;
    });

    // my account/help sub nav
    $(".utilRightNav h3.withNav").click(function() {
        $(this).next("ul").slideToggle("fast")
		.siblings("ul").hide("fast");
        $(this).find("a").addClass("on");
        $(this).siblings("h3.withNav").find("a").removeClass("on");
        return false;
    });

    //dashboard for ie
    $(".dashboard li a").hover(
		function() { $(this).addClass("over"); },
		function() { $(this).removeClass("over"); }
	);


    if (typeof Shadowbox != 'undefined') {

        // initialize shadowbox
        // original
        //Shadowbox.skin.markup = '<div id="sb-container"><div id="sb-overlay"></div><div id="sb-wrapper"><div id="sb-title"><div id="sb-title-inner"></div></div><div id="sb-body"><div id="sb-body-inner"></div><div id="sb-loading"><a onclick="Shadowbox.close()">{cancel}</a></div></div><div id="sb-info"><div id="sb-info-inner"><div id="sb-counter"></div><div id="sb-nav"><a id="sb-nav-close" title="{close}" onclick="Shadowbox.close()"></a><a id="sb-nav-next" title="{next}" onclick="Shadowbox.next()"></a><a id="sb-nav-play" title="{play}" onclick="Shadowbox.play()"></a><a id="sb-nav-pause" title="{pause}" onclick="Shadowbox.pause()"></a><a id="sb-nav-previous" title="{previous}" onclick="Shadowbox.previous()"></a></div><div style="clear:both"></div></div></div></div></div>';

        Shadowbox.skin.markup = '<div id="sb-container"><div id="sb-overlay"></div><div id="sb-wrapper"><div id="sb-title"><div id="sb-title-inner"></div><a href="javascript:Shadowbox.close()"><img border="0" src="/includes/shadowbox/close_header.gif" alt="Close" title="Close"></a></div><div id="sb-wrapper-inner"><div id="sb-body"><div id="sb-body-inner"></div><div id="sb-loading"><div id="sb-loading-inner"><span>{loading}</span></div></div></div></div><div id="sb-info"><div id="sb-info-inner"><div id="sb-caption"><div id="sb-caption-inner"></div></div><div id="sb-counter"></div><div id="sb-nav"><a id="sb-nav-close" title="{close}" onclick="Shadowbox.close()"></a><a id="sb-nav-next" title="{next}" onclick="Shadowbox.next()"></a><a id="sb-nav-play" title="{play}" onclick="Shadowbox.play()"></a><a id="sb-nav-pause" title="{pause}" onclick="Shadowbox.pause()"></a><a id="sb-nav-previous" title="{previous}" onclick="Shadowbox.previous()"></a></div></div></div></div></div>';


        Shadowbox.init({
            initialWidth: 620,
            initialHeight: 200,
            players: ["qt", "swf", "img", "flv", "html", "iframe", "wmp"],
            overlayColor: "#000",
            overlayOpacity: 0.5,
            animate: true,
            autoplayMovies: true,
            resizeDuration: 0.1,
            slideshowDelay: 5
        });

    }

});

// -----------------------------------------------------------------------------------------------------------------------------------------
/// Flash UFO functions
// -----------------------------------------------------------------------------------------------------------------------------------------

function FixFlash(strContainerID, strFlashPath, width, height, flashvars){
	var FO = { movie:strFlashPath, width:width + "px", height:height + "px", flashvars:flashvars, wmode:"transparent", majorversion:"7", build:"40", swliveconnect:"true"};
	UFO.create(FO, strContainerID);	
}

// function to change the color of the row when mouseover 
function changeTrColor(currow) {
	currow.style.backgroundColor = "#fff4ca";
	currow.style.backgroundColor = "#fff4ca";
}

// function to restore back the color of the row when mouseout 
function restoreTrColor(currow) {
	currow.style.backgroundColor = "#ffffff";
	currow.style.backgroundColor = "#ffffff";
}

// function to show and hide the element 
//function showhideElement(elementToShow,elementToChange,showText,hideText) {
//	
//	var objElementToChange = document.getElementById(elementToChange);
//	
//	if(document.getElementById(elementToShow).style.visibility == "" || document.getElementById(elementToShow).style.visibility == "visible") {
//		document.getElementById(elementToShow).style.visibility = "hidden";
//		objElementToChange.innerHTML = showText;
//		objElementToChange.className = "showextra";
//	} else {
//		document.getElementById(elementToShow).style.visibility = "visible";
//		objElementToChange.innerHTML = hideText;
//		objElementToChange.className = "hideextra";
//	}
//}

//---------------------------------------------------------------------------------------
/// Home Hero Image
//---------------------------------------------------------------------------------------
$(document).ready(function () {
	
	if ($(".homeHero")){
		initHomeHero();
	};
	$(".homeHeroNumbers a").click(function(){  
		stopInterval();
		if (!$(this).hasClass("on")){
			ShowHero($(".homeHeroNumbers a").index(this));
		}
		return false;
	});

	
});

var heroInterval;
function initHomeHero()
{
	$(".homeHero li:not(:first)").hide();
	$(".homeHeroNumbers a:eq(0)").addClass("on");
	heroInterval = setInterval("nextHero()", 8000);	
}

function ShowHero(contentIndex)
{
	var newContent = $(".homeHero li:eq(" + contentIndex + ")");
	var newNumber = $(".homeHeroNumbers a:eq(" + contentIndex + ")");
	$(newContent).fadeIn("slow");
	$(newContent).siblings("li:visible").fadeOut("slow");
	$(".homeHeroNumbers a").removeClass("on");	
	$(newNumber).addClass("on");	
}

function prevHero()
{
	var currentHero = $(".homeHero li").index($(".homeHero li:visible"));
	var prevHero = currentHero - 1;
	
	if (prevHero<0){
		prevHero = 	$(".homeHero li").length - 1;
	}	
	ShowHero(prevHero);	
}

function nextHero()
{
	var currentHero = $(".homeHero li").index($(".homeHero li:visible"));
	var nextHero = currentHero + 1;
	
	if (nextHero>$(".homeHero li").length - 1){
		nextHero = 	0;
	}	
	ShowHero(nextHero);
}
function stopInterval()
{
	clearInterval(heroInterval);
}

//function ChangeBanner(){
//	//alert("change" + arr.length)
//	var bnrImg = $("#bannerimg")
//	var tmpImageSRC = bnrImg.attr("src");
//	while(tmpImageSRC==bnrImg.attr("src") || arr.length < 2){
//		tmpImageSRC = arr[Math.ceil(Math.random()*arr.length) - 1].innerHTML;
//	}
//	$("#banner").css("background-image","url(" + tmpImageSRC + ")")
//	bnrImg.fadeOut("medium",function(){
//  		bnrImg.attr("src",tmpImageSRC);
//		bnrImg.show()
//	})
//}



//---------------------------------------------------------------------------------------
/// Registration Functions 
//---------------------------------------------------------------------------------------


// function to show the element 
function showElementWithIframe(elementID) {
	document.getElementById(elementID).style.display = "block";
	document.getElementById(elementID + 'iframe').style.display = "block";
}

// function to hide the element 
function hideElementWithIframe(elementID) {
	document.getElementById(elementID).style.display = "none";
	document.getElementById(elementID + 'iframe').style.display = "none";
}

// function to show the element 
function showElement(elementID) {
	document.getElementById(elementID).style.display = "block";
}

// function to hide the element 
function hideElement(elementID) {
	document.getElementById(elementID).style.display = "none";
}

// function to change the color of the column when mouseover 
function changeTdColor(columnID) {
	var feetColumn = document.getElementById('feet'+columnID);
	var meterColumn = document.getElementById('meter'+columnID);
	
	feetColumn.style.backgroundColor = "#deecff";
	meterColumn.style.backgroundColor = "#deecff";
}

// function to restore back the color of the column when mouseout 
function restoreTdColor(columnID) {
	var feetColumn = document.getElementById('feet'+columnID);
	var meterColumn = document.getElementById('meter'+columnID);
	
	feetColumn.style.backgroundColor = "#ffffff";
	meterColumn.style.backgroundColor = "#ffffff";
}



// Tile Functions
//function openCloseTile(tileID){
//	var tileContent;
//	var tileOpenCloseWrapper;
//	var tileOpenCloseLink;
//	var tileOpenCloseBottom;
//	tileContent = $('tilecontent' + tileID);
//	tileOpenCloseWrapper = $('tilewrapper' + tileID);
//	tileOpenCloseLink = $('openclose' + tileID);
//	tileOpenCloseBottom = $('closedbottom' + tileID);
//	
//	if(tileContent != null) {
//		if(tileContent.className == "tilecontent tileopen"){
//			tileContent.className = 'tilecontent tileclosed';
//			tileOpenCloseWrapper.style.display = 'none';
//			tileOpenCloseLink.className = 'tileclosed';
//			if (tileOpenCloseBottom != null)
//				tileOpenCloseBottom.style.display = 'block';
//		} else{
//			tileContent.className = 'tilecontent tileopen';
//			tileOpenCloseWrapper.style.display = 'block';
//			tileOpenCloseLink.className = 'tileopen';
//			if (tileOpenCloseBottom != null)
//				tileOpenCloseBottom.style.display = 'none';
//		}
//	}
//}


//---------------------------------------------------------------------------------------
/// Menu Plan Functions 
//---------------------------------------------------------------------------------------

/* function to change the element's border depending on the state */
function changeBorder(elementID,straction){ 

	if(straction=="off"){
		document.getElementById(elementID).style.border = "1px solid #fff";
		document.getElementById(elementID).style.borderWidth = "1px";
		document.getElementById(elementID).style.borderTopStyle = "solid";
		document.getElementById(elementID).style.borderTopColor = "#cecece";
		//document.getElementById(elementID).style.background = "url(/css/images/menuplan/bg_mealday.gif) no-repeat 0 0";
	} else {
		document.getElementById(elementID).style.border = "1px solid #cfcfcf";
		//document.getElementById(elementID).style.background = "none";
	}
	
} 

/* function to change the element's background color depending on the state */
function showColor(elementID,action){ 
	if(action=="off"){
		document.getElementById(elementID).style.background = "#fff";
	} else {
		document.getElementById(elementID).style.background = "#fff4ca";
	}
}

//Glossary Items
var IE = document.all?true:false
//Add the event
document.onclick = SetXY

var MouseX = 0;
var MouseY = 0;


function SetXY(e){
		
	   if( e ) {
		  if( typeof( e.pageX ) == 'number' ) {
			 MouseX = e.pageX;
			 MouseY = e.pageY;
		  } else {
			 MouseX = e.clientX;
			 MouseY = e.clientY;
		  }
	   }  else {
		  e = window.event;
		  MouseX = e.clientX;
		  MouseY = e.clientY;
		  
		  if( document.documentElement && ( document.documentElement.scrollTop || document.documentElement.scrollLeft ) ) {
			 MouseX += document.documentElement.scrollLeft;
			 MouseY += document.documentElement.scrollTop;
		  } else if( document.body && ( document.body.scrollTop || document.body.scrollLeft ) ) {
			 MouseX += document.body.scrollLeft;
			 MouseY += document.body.scrollTop;
		  }
	   }		
		
		//alert("MouseX: "+MouseX+"   MouseY: "+MouseY); 
}


/* function to show and hide the element using visibility */
function hideElementbyClass(classname){ 
	var inc=0; 
	var alltags=document.all? document.all : document.getElementsByTagName("*"); 
	
	for (i=0; i<alltags.length; i++){ 
		if (alltags[i].className==classname) 
			if(alltags[i].style.visibility == "hidden") {
				alltags[i].style.visibility = "visible";
			} else {
				alltags[i].style.visibility = "hidden";
			}
			//customcollection[inc++]=alltags[i]; 
	} 
} 

/* function to show and hide the element using display property */
function hideElementbyClassDisplay(classname){ 
	var inc=0; 
	var alltags=document.all? document.all : document.getElementsByTagName("*"); 
	
	for (i=0; i<alltags.length; i++){ 
		if (alltags[i].className==classname) 
			if(alltags[i].style.display == "none") {
				alltags[i].style.display = "block";
			} else {
				alltags[i].style.display = "none";
			}
			//customcollection[inc++]=alltags[i]; 
	} 
} 


/* function to change the button text */
function showhideCalories(buttonID) {
	
	if(document.getElementById(buttonID).innerHTML == "show") {
		document.getElementById(buttonID).innerHTML = "hide";
	} else {
		document.getElementById(buttonID).innerHTML = "show";
	}
	
	hideElementbyClass('titlecalper');
	hideElementbyClass('mealplancalories');
	hideElementbyClassDisplay('mealplantotalcal');	
}

/* function to show and hide the element, also change the button text */
function showhideElement(elementID,buttonID) {
	
	if(document.getElementById(elementID).style.display == "none" || document.getElementById(elementID).style.display == "") {
		document.getElementById(elementID).style.display = "block";
		document.getElementById(buttonID).innerHTML = "Hide";
	} else {
		document.getElementById(elementID).style.display = "none";
		document.getElementById(buttonID).innerHTML = "Show";
	}
}

/* function to show the element */
//function showhideBubble(elementID,positionEmelmentID) {
//	objPopup = $(elementID);
//	objWrapper = $('wrapper');
//	leftOffset = objWrapper.offsetLeft;
//	
//	divHeight = objPopup.offsetHeight + 1;
//	
//	if(document.getElementById(elementID).style.visibility == "" || document.getElementById(elementID).style.visibility == "hidden") {
//		if((positionEmelmentID!=null) && (positionEmelmentID!='')){
//			// Get the position based on the position of another object
//			var ObjPosElementCoords = Position.page($(positionEmelmentID))
//			var arrPosition = ObjPosElementCoords.toString().split(",")
//			objPopup.style.top = (arrPosition[1]-divHeight+10) +"px";
//			objPopup.style.left = (arrPosition[0]-leftOffset) +"px";
//			objPopup.style.visibility = "visible";

//		}else{
//			objPopup.style.top = (MouseY-divHeight) +"px";
//			objPopup.style.left = (MouseX-35-leftOffset) +"px";
//			objPopup.style.visibility = "visible";

//		}
//	} else {
//		objPopup.style.visibility = "hidden";
//	}
//}

function showhideBubble(elementID,positionElementID) {
	var objPopup = $('#' + elementID);
	
	if($(objPopup).css("visibility") == "visible")
	{
		$(objPopup).css("visibility","hidden");
	}
	else
	{
		var divHeight = $(objPopup).height() + 1;
		
		if((positionElementID!=null) && (positionElementID!='')){
			// Get the position based on the position of another object
			var ObjPosElementCoords = $("#" + positionElementID).offset();
			$(objPopup).css({"left":ObjPosElementCoords.left-35 + "px", "top":ObjPosElementCoords.top-divHeight-35 + "px"});

		}else{
			var objWrapper = $('#wrapper');
			var wrapperOffset = objWrapper.offset();		
			$(objPopup).css({"left":mouseClicked.pageX-35-wrapperOffset.left + "px", "top":mouseClicked.pageY-divHeight-35 + "px"});
		}
		
		$(objPopup).css("visibility","visible");		
		
	}
	
}

// Shadowbox support functions

function OpenModalWindow(url, width, height, player) {
    if (!player || player == '') {
        player = 'iframe';
    }

    if (!width || width == '') {
        width = '620';
    }

    if (!height || height == '') {
        height = '200';
    }
    
    Shadowbox.open({ content: url
                    , caption: ''
                    , title: ''
                   , player: player
                   , width: width + 'px' //change your width
                   , height: height + 'px' //change your height
                   , options: { modal: true, enableKeys: false, animate: false, animateFade: false, handleOversize:'drag' }

    });
}


function CloseModalWindow() {
    if (Shadowbox.isOpen()) {
        Shadowbox.close();
    }
}

function FixShadowBoxLinks() {
    var a = document.getElementsByTagName("a");
    for (var i = 0; i < a.length; ++i) {
        if (a[i].rel && a[i].rel.indexOf('shadowbox') >= 0) {
            Shadowbox.setup(a[i]);
        }
    }

}


//  HELP FUNCTIONS //

function showHelp(helpID,height,width) {
    url = document.location.protocol + '//' + document.location.host + '/popup/popup.aspx?id=' + helpID;
    if (height == null || height < 200) {
        height = 200;
    }
    if (width == null || width < 400) {
        width = 620;
    }
    Shadowbox.open({ content: url
                    , caption: ''
                    , title: ''
                   , player: 'iframe'
                   , width: width + 'px' //change your width
                   , height: height + 'px' //change your height
                   }
                );
}

function showPopupText(title, text, topoffset, leftoffset, e) {
    var topMargin = 0;
    if (topoffset) {
        topMargin = topMargin + topoffset;
    };

    var leftMargin = 0;
    if (leftoffset) {
        leftMargin = leftMargin + leftoffset;
    };

    // hide existing help box
    $('#helppanel').hide();

    // get the URL for content
    var strURL = '';
    strURL = '/remote/getPopupText.aspx?title=' + escape(title) + '&text=' + escape(text)

    //populate help box
    $("#helppanel").load(strURL);

    //position box
    var objHelpPanel = $('#helppanel')

    var realOffset = objHelpPanel.offset();

    //alert(realOffset.top + " " + realOffset.left);
    objHelpPanel.css("left", 200 + leftMargin + "px");
    objHelpPanel.css("top", 200 + realOffset.top + topMargin + "px");
    //objHelpPanel.style.z-index = "99999";
    //hide select boxes in IE
    if (document.all) {
        var tags = document.getElementsByTagName("select");
        for (var i = 0; i < tags.length; i++) {
            tags[i].style.visibility = 'hidden';
        }
    }

    //show populated help box
    $('#helppanel').show();


	// Cancel the event bubbling.
    cancelEventBubbling(e);
}

function showSelects(){
	if(document.all){
		var tags = document.getElementsByTagName("select");
		for (var i = 0; i < tags.length; i++) {
			tags[i].style.visibility = 'visible';		
		}		
	}
}

function cancelEventBubbling(e) {
	if (!e) var e = window.event;
	e.cancelBubble = true;							// This is for IE browsers.
	if (e.stopPropagation) e.stopPropagation();		// This is for non IE browsers.
}


// Function to show / hide tabs in members home personalisation

//var memHomeShowingID = '';
//function showLeftContent(id){
//	if(document.all){
//		document.execCommand("BackgroundImageCache",false,true);	
//	}
//	if(memHomeShowingID != ''){
//		$('left' + memHomeShowingID).style.display = 'none';
//		memHomeShowingID = id;
//	}
//	$('left' + id).style.display = 'block';
//	$('leftTabs').className = 'tabs' + id;	
//}

function ToggleCaloriesOut(arrowID,tblCalories){
	var objArrow = $('#' + arrowID);
	if($(objArrow).attr("src") == ('/css/images/diary/arrow_calories_right.gif') ){
		$(objArrow).attr("src", "/css/images/diary/arrow_calories_down.gif");
		$('#' + tblCalories).show();
	}else{
		$(objArrow).attr("src", "/css/images/diary/arrow_calories_right.gif");
		$('#' + tblCalories).hide();
	}
}

function ToggleKey(arrowID,KeyImgDiv,siteFolder){
	var objArrow = $('#' + arrowID);
	if($(objArrow).attr("src").indexOf('cal_arrow_right.gif') > -1 ){
		$(objArrow).attr("src", siteFolder + "/images/cal_arrow_down.gif");
		$('#' + KeyImgDiv).show();
	}else{
		$(objArrow).attr("src", siteFolder + "/images/cal_arrow_right.gif");
		$('#' + KeyImgDiv).hide();
	}
}


function ToggleNutritionInfo(imageID, tblNutrition, hfdDiaryNutritionDisplayStateId){
	var objImage = document.getElementById(imageID)
	// This client side hidden field may not be defined on the page.
	var objDiaryNutritionDisplayState = document.getElementById(hfdDiaryNutritionDisplayStateId);
	var displayState = "false";

	if(objImage.src.indexOf('show_nutrition_info.gif') > 0 ){
		objImage.src = "/css/images/hide_nutrition_info.gif"
		document.getElementById(tblNutrition).style.display = "block";
		displayState = "true";
	}else{
		objImage.src = "/css/images/show_nutrition_info.gif"
		document.getElementById(tblNutrition).style.display = "none";
		displayState = "false";
	}
	
	if(objDiaryNutritionDisplayState != null)
	{
		objDiaryNutritionDisplayState.value = displayState;
	}
}


// [string].pad(length: Integer, [substring: String = " "], [type: Integer = 0]): String
// Returns the string with a substring padded on the left, right or both sides.
//   length: amount of characters that the string must have.
//   substring: string that will be concatenated.
//   type: specifies the side where the concatenation will happen, where: 0 = left, 1 = right and 2 = both sides.
String.prototype.pad = function(l, s, t){
return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
    + 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
    + this + s.substr(0, l - t) : this;
};


// This function checks if the queryString contains a "Date" parameter. If not then get the client date 
// and redirect with the client date (?date=yyyyMMdd).
function GetClientDate(redirctToPage) {
	var found = false;
	var queryString = location.search;
	if(queryString != "") queryString = queryString.substr(1);
	var aryQueryStringParams = queryString.split("&");		
	for(var i=0 ; i<aryQueryStringParams.length ; i++) {
		if(aryQueryStringParams[i].toLowerCase().indexOf("date=") == 0) {
			if(aryQueryStringParams[i].split("=")[1] != "") {
				found = true;
				break;
			}
		}
	}
	if (!found) {
		var now = new Date();
		var m = "" + (now.getMonth()+1);
		var d = "" + (now.getDate());
//		alert("Redirect to: " + redirctToPage + "?Date=" + now.getFullYear() + m.pad(2, "0", 0) + d.pad(2, "0", 0));
		location.href = redirctToPage + "?Date=" + now.getFullYear() + m.pad(2, "0", 0) + d.pad(2, "0", 0);
	}
//		else
//			alert("date ok");
}



// TEAMS SCRIPT.

function MyOtherTeam(strURL){
    if(strURL!=""){
        document.location.href=strURL;
    }
}


function toggleRenewalNotes() {
    var renewalNote1 = document.getElementById("renewalNote1");
    var allRenewalNotes = document.getElementById("allRenewalNotes");
    var renewalNotesLink = document.getElementById("renewalNotesLink");
    if (renewalNote1.style.display == "none") {
        renewalNote1.style.display = "block";
        allRenewalNotes.style.display = "none";
        renewalNotesLink.innerHTML = "View all renewal notes";
    } else {
        renewalNote1.style.display = "none";
        allRenewalNotes.style.display = "block";
        renewalNotesLink.innerHTML = "Hide renewal notes";
    }
}


function Popup(strURL, intWidth, intHeight, strWindowName) {
    if (strWindowName == null) { strWindowName = '_blank' }

    var intLeft
    var intTop

    if (intWidth == 0) {
        intWidth = screen.width - 10
        intLeft = 0
    }
    else {
        intLeft = (screen.width - intWidth) / 2;
    }

    if (intHeight == 0) {
        intHeight = screen.height - 70
        intTop = 0
    }
    else {
        intTop = (screen.height - intHeight - 35) / 2;
    }

    NewChild = window.open(strURL, strWindowName, 'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width=' + intWidth + ',height=' + intHeight + ',top=' + intTop + ',left=' + intLeft)
    return NewChild
}



// Execute a webservice recieving a synchronous response.
// The results is always returned in the "d" parameter. Use "parseJSON" to safely parse the JSON string.
// Eg. var result = JSON.parse(GetSynchronousJSONResponse('/WebServices/ValidatorService.asmx/IsNicknameValid2', '{"a":"2", "b":"asd"}'));
//     alert(result.d);
function GetSynchronousJSONResponse(url, postData) {
	var xmlhttp = null;
	if (window.XMLHttpRequest)
		xmlhttp = new XMLHttpRequest();
	else if (window.ActiveXObject) {
		if (new ActiveXObject("Microsoft.XMLHTTP"))
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		else
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	}
	// to be ensure non-cached version of response
	url = url + "?rnd=" + Math.random();

	xmlhttp.open("POST", url, false); //false means synchronous
	xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
	xmlhttp.send(postData);
	var responseText = xmlhttp.responseText;
	return responseText;
}


/*
Examples:
	AddClass(document.getElementById("test"), "test");
	RemoveClass(document.getElementById("test"), "test");
	if(HasClass(document.getElementById("test"), "test")){//do something};
*/
function HasClass(ele,cls) {
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function AddClass(ele, cls) {
	if (!this.HasClass(ele,cls)) ele.className += " "+cls;
}
function RemoveClass(ele, cls) {
	if (HasClass(ele,cls)) {
		var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		ele.className=ele.className.replace(reg,' ');
	}
}
function ToggleClass(ele, removeCls, addCls) {
	RemoveClass(ele, removeCls);
	AddClass(ele, addCls);
}
function AddClasses(ele, clss) {
	for (var i = 0; i < clss.length; i++) {
		AddClass(ele, clss[i]);
	}
}
function RemoveClasses(ele, clss) {
	for (var i = 0; i < clss.length; i++) {
		if (HasClass(ele, clss[i])) {
			RemoveClass(ele, clss[i]);
		}
	}
}
function ToggleClasses(ele, removeClss, addClss) {
	RemoveClasses(ele, removeClss);
	AddClasses(ele, addClss);
}


// Usage:
//	var element = document.getElementById('test');
//	var formFieldList = getElementsByTagNames('input,select,textarea', element);
function getElementsByTagNames(list, obj) {
	if (!obj) var obj = document;
	var tagNames = list.split(',');
	var resultArray = new Array();
	for (var i = 0; i < tagNames.length; i++) {
		var tags = obj.getElementsByTagName(tagNames[i]);
		for (var j = 0; j < tags.length; j++) {
			resultArray.push(tags[j]);
		}
	}
	var testNode = resultArray[0];
	if (!testNode) return [];
	if (testNode.sourceIndex) {
		resultArray.sort(function(a, b) {
			return a.sourceIndex - b.sourceIndex;
		});
	}
	else if (testNode.compareDocumentPosition) {
		resultArray.sort(function(a, b) {
			return 3 - (a.compareDocumentPosition(b) & 6);
		});
	}
	return resultArray;
}

// Format a number with no trailing zeros, to 2 decimal places, and prefix with optional string.
// Usage:
//   var n = 123.45; n.formatCurrency("$") // => $123.45
//   var n = 123.5; n.formatCurrency("$") // => $123.50
//   var n = 123; n.formatCurrency("$") // => $123
Number.prototype.formatCurrency = function(prefix) {
	var amount = this;
	var i = parseFloat(amount);
	if (isNaN(i)) { i = 0.00; }
	var minus = '';
	if (i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	//	if(s.indexOf('.') < 0) { s += '.00'; }
	if ( (s.indexOf('.') > -1) && (s.indexOf('.') == (s.length - 2)) )
		{ s += '0'; }
	s = prefix + minus + s;
	return s;
}

