/*********************************************/
/*              PMG FUNCTIONS                */
/*********************************************/

function tourClick(p){
	if(typeof(p) != "object"){
		alert("Object not passed to tourClick()");
		return;
	}
	switch(p.id.toLowerCase()){
		case "tour_hcc":
			var lLoc = "/hcc/tour_hcc.aspx";
			if(gProps.flash.available){
				lLoc = "/hcc/tour2_hcc.aspx";
			}
			location.href = lLoc;
			break;
		case "tour_hcp":
			var lLoc = "/hcp/tour_hcp.aspx";
			if(gProps.flash.available){
				lLoc = "/hcp/tour2_hcp.aspx";
			}
			location.href = lLoc;
			break;
	}
}


// ******************************************** //
// WRITE A BODY CONTENT LINK   
// p = {};
// p.arrow = boolean will add the orange arrow
// p.id = passed to doBodyContentClick();
// p.write = boolean write or return string
// can redirect or call openNewWindow();
// ******************************************** //
function PMG_writeLink(p){

	if(typeof(p) != "object"){
		p = {text:"Text not passed to writeBodyLink()"}
	}
	
	if(!p.href){p.href = ""}
	if(!p.script){p.script = "PMG_clickLink"}

	var ws = (p.arrow)? '<p class="triangle_links">' : '';
	ws += '<a class="bodyContentLinks" ';
	ws += 'href="#" ';
	ws += 'onfocus="this.blur();" ';
	ws += 'onclick="' + p.script + '(\'' + p.href + '\');return false;" ';
	ws += '>' + p.text + '</a>';
	ws += (p.arrow)? '</p>' : '';
	
	if(p.inline){
		return ws;
	}else{
		document.write(ws);
	}
	
	return true;
}


// ******************************************** //
// EXEC A BODY CONTENT LINK   
// _location = string
// can redirect or call openNewWindow();
// ******************************************** //
function PMG_clickLink(_location){
	
	var pLoc = null;

	switch(_location){
		case "azprivacystatement":
			pLoc = "/privacy.aspx";
			break;
		case "az_me":
			var p = {};
			//p.loc = "http://www.astrazeneca-us.com/content/patientAssistance/astrazeneca-pparx.asp?PPA=CorpID";
			p.loc = "http://www.azandme.com";
			p.w = 1024;
			PMG_newWindow(p);
			break;
		default:
		 	//alert("set branching logic for the \"" + p_id + "\" link in mp_functions.js")
			if(_location != ""){
				pLoc = _location + ".aspx";
			}else{
				alert("href not passed to PMG_clickLink() in functions_pmg.js");
			}
			break;
	}

	
	if(pLoc != null){
		location.href = pLoc;
	}
}

// ***************************************************************************** //
// PMG_img() Writes or returns an <img>
// p = {}
// p.graphic = the graphic name
// p.extension = jpg, png, gif
// p.path = allows for a custom path
// p.w = integer width
// p.h = integer height
// p.id = unique id default is ""
// p.cname = unique class default is ""
// p.title = the title tag default is ""
// p.alt = the alt tag default is ""
// p.write = boolean will write or return value
// ***************************************************************************** //

function PMG_img(p){

	var ws = ''
	var lExt = p.ext || "jpg";
	var lPath = p.path || gPaths.images;
	var lGraphic = (typeof(p.graphic) == "object")? p.graphic[Math.round(Math.random()*(p.graphic.length-1))] : p.graphic;
	var lImage = lPath + lGraphic + '.' + lExt;
	
	// Check for special styles //
	var lID = (p.id)? 'id="' + p.id + '"' : '';
	var lClass = (p.cname)? 'class="' + p.cname + '"' : '';
	var lAlt = (p.alt)? 'alt="' + p.alt + '"' : '';
	var lTitle = (p.title)? 'alt="' + p.title + '"' : '';
	
	if(lExt == "png" && gBrowser.vendor == "IE"){
			ws = '<div ' + lID + lClass + ' style="width:' + p.w + 'px; height:' + p.h + 'px; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + lImage + '\', sizingMethod=\'image\');"></div>';
	}else{
		var lSize = (p.w)? 'width="' + p.w + '" height= "' + p.h + '"': '';		
		ws = '<img ' + lID + lClass + lTitle + ' src="' + lImage + '" ' + lSize + ' vspace="0" hspace="0" border="0" ' + lAlt + ' />';
	}
	
	
	if(p.inline){
		return ws;
	}else{
		document.write(ws);		
	}
	
	return false;
}


function PMG_background(p){
	
	var ws = ''
	var lType = p.ext || "jpg";
	var lPath = p.path || gPaths.images;
	var lImage = lPath + p.graphic + '.' + lType
	var lScale = p.scale || "image";
	
	if(lType == "png" && gBrowser.vendor == "IE"){
		ws += 'filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + lImage + '\', sizingMethod=\'' + lScale + '\')'
	} else {
		ws += 'background-image: url(\'' + lImage  + '\')';
	}

	return ws;
			
}

// add a function to the onload //
function add_onload(pFunction){
	if(window.attachEvent){
		window.attachEvent("onload", eval(pFunction));
	}else{
		window.addEventListener("load", eval(pFunction), false);
	}
}

// ********************************* //
//        WRITE BOX			         //
// ********************************* //
function writeTableBox(pTop,pWrite){

	var ws = "";
	if(pTop){
		ws += '<table width="100%" cellpadding="0" cellspacing="0" border="0">';
		ws += '<tr><td class="table_box_top_left"></td><td class="table_box_top"></td><td class="table_box_top_right"></td></tr>';
		ws += '<tr><td class="table_box_left"></td><td class="table_box_back">'
	}else{
		ws += '</td><td class="table_box_right"></td></tr>';
		ws += '<tr><td class="table_box_bottom_left"></td><td class="table_box_bottom"></td><td class="table_box_bottom_right"></td></tr>';
		ws += '</table>';
	}

	if(pWrite){
		document.write(ws);
	}else{
		return ws;
	}
	
	return true;
	
}

// ******************************************** //
// PRINT POPUP WINDOW   
// ******************************************** //
function PMG_print(){
	window.print();
}


function confirmLeaving(p){
	//alert(p.site);

	gLightBox.init({div:"confirm_leaving"});

	gPanel.confirm_leaving.p_url = p;
	gPanel.confirm_leaving.openSite = function(){
		PMG_newWindow(this.p_url)
		this.closePanel();
	}
	
}

// ***************************************************************************** //
// OPEN A POPUP WINDOW = Default is 800x600 with chrome = "status" only
// pWin = {}
// pWin.name = "window name"
// pWin.w = integer window width
// pWin.h = integer window height
// pWin.chrome = {} contains all chrome settings ({toolbar:'yes',status:'yes'})
// pWin.center = boolean set to false to respect left and top window properties :)
// ***************************************************************************** //
var gWindow_pmg = false;
function PMG_newWindow(pWin){
 
	// close the existing window if one is open //
	/*
	if(typeof(gWindow_pmg) == "object"){
		if(gWindow_pmg != false){
			//getVariable_debugTool(gWindow_pmg.window)
			gWindow_pmg.close();
			alert("close")
			gWindow_pmg = false;
		}
	}
	*/
	
	var pChrome = {};
	pChrome.fullscreen = "no";
	pChrome.titlebar = (pWin.nochrome)? "no" : "yes";
	pChrome.toolbar = (pWin.nochrome)? "no" : "yes";
	pChrome.location = (pWin.nochrome)? "no" : "yes";
	pChrome.directories = (pWin.nochrome)? "no" : "yes";
	pChrome.status = "yes";
	pChrome.menubar = (pWin.nochrome)? "no" : "yes";
	pChrome.scrollbars = (pWin.nochrome)? "no" : "yes";
	pChrome.resizable = (pWin.nochrome)? "no" : "yes";
	pChrome.width = (pWin.w)? pWin.w : 800; // Default width for all popups //
	pChrome.height = (pWin.h)? pWin.h : 600; // Default height for all popups //
	pChrome.innerHeight = pChrome.height; // used with firefox //
	pChrome.top = "0";
	pChrome.left = "0";
 
 	// if the name is not defined then use the default name for all windows //
 	if(typeof(pWin.name) == "undefined"){
		pWin.name = PMG_TimeStamp();
	}
	// Always center window 
	if(typeof(pWin.center) == "undefined"){
		pWin.center = true;
	}
	// loop and change properties //
	if(pWin.chrome){
		for(prop in pWin.chrome){
			pChrome[prop] = pWin.chrome[prop];
		}
	}

	// This will center the window on the screen //
	// center is enabled by default //
	if (pWin.center != false) {
		var lMinus = 40;
		var lPlus = 10;
		// fix for 800x600 center window //
		if(screen.height < 700){
			lMinus = 0;
			lPlus = 20;
		}

		var ah = screen.availHeight - lMinus;
		var aw = screen.availWidth - 10;
		var x = (aw - pChrome.width) / 2;
		var y = (ah - (pChrome.innerHeight + lPlus)) / 2;
		pChrome.left = x;
		pChrome.top = y;

	}
	// setup the window chrome //
	var lNewChrome = ""
	for(prop in pChrome){
		lNewChrome += prop + '=' + pChrome[prop] + ",";
	}

	// open window and set reference //
	gWindow_pmg = window.open(pWin.loc,pWin.name,lNewChrome);
	//gWindow_pmg.focus();
	
}

PMG_TimeStamp = function(){
	var p_date = new Date();
	var p_time = new String(p_date.getTime());
	var p_sub = p_time.substr((p_time.length-4),p_time.length-1);
	return p_sub;
}

// ******************************************** //
// CLOSE A POPUP WINDOW   
// p = {}
// p.id = opener new location?
// p.frame = the frame to redirect (parent,top)
// closes a popup and can redirect the opener
// ******************************************** //
function PMG_closeWindow(p){

	var pLocation = false;
	if(p){
		switch(p.id){
			case "register":
				pLocation = "registration.aspx";
				break;
			default:
				alert("p.id = " + p.id + "\nID not passed to closeThisWindow()");
				break;
		}
	}
	
	if(pLocation){
		if(p.frame){
			/* Break out of the frame? */
			window.opener[p.frame].location.href = pLocation;
		}else{
			window.opener.location.href = pLocation;
		}
	}
	
	window.close();

}

// ***************************************************************************** //
// OPEN A PDF In A POPUP WINDOW
// pLoc = page location
// Assumes form PDFLauncher exists in page (required to get dynamically
// generated PDFs to display.
// ***************************************************************************** //
function openPDFWindow(pLoc){

	PMG_newWindow({loc:pLoc,nochrome:true,w:800,h:600});

	//document.forms["PDFLauncher"].target = "printpdf";
	//document.forms["PDFLauncher"].action = pLoc;
	//document.forms["PDFLauncher"].submit();	
}

// HCC consent radio click //
function checkHCC_Consent(e){
	var lRadio = e.target || window.event.srcElement;
	if(lRadio.value){
		var lDisplay = false;
		if(lRadio.nextSibling.firstChild.data.toLowerCase() == "no"){
			lDisplay = true;
		}
		var lP = document.getElementById("ctl00_ContentPlaceHolder1_consent_error");
		if(lP){
			lP.style.display = (lDisplay)? "block" : "none";
		}
		
	}
	return false;
}

var gTourButton = 1;
function initTour(p){
	var lDiv = document.getElementById("navigation_tour");
	var lA = null;

	if(lDiv){
		lA = lDiv.getElementsByTagName("a");
	}

	
	
	if(lA){
		var lBack = document.getElementById('back_button');
		var lNext = document.getElementById('next_button');
		var lA2 = [];
		
		for(var x = 0; x<lA.length; x++){
			if(lA[x].id.indexOf("tour") != -1){
				lA2.push(lA[x]);
			}
		}
		
		
		for(var x = 0; x<lA2.length; x++){
			var obj = {obj:lA2[x],back_button:lBack,next_button:lNext,buttons:lA2,type:"text"}
			new tourLink(obj);
		}
		
		
		obj.obj = lBack;
		obj.type = lBack.id;
		new tourButton(obj);

		obj.obj = lNext;
		obj.type = lNext.id;
		new tourButton(obj);
		
		// Init the first button //
		lA2[0].onclick();
		
	}

}


function tourLink(p){
	//alert(p.obj.id)
	p.obj.p_back_button = p.back_button;
	p.obj.p_next_button = p.next_button;
	p.obj.p_buttons = p.buttons;
	p.obj.p_num = parseInt(p.obj.id.split("-")[1]);
	p.obj.p_graphic = document.getElementById("tour_img_" + p.obj.p_num);
	p.obj.p_text = document.getElementById("tour_" + p.obj.p_num);
	p.obj.p_selected = false;
	
	p.obj.hideShowMe = function(pNum){
		var lDisplay = "none";
		if(this.p_num == pNum){
			gTourButton = parseInt(pNum);
			lDisplay = "block"
			this.style.textDecoration = "underline";
			this.p_selected = true;
		}else{
			this.style.textDecoration = "none";
			this.p_selected = false;
		}
		this.p_text.style.display = lDisplay;
		this.p_graphic.style.display = lDisplay;
	}
	
	p.obj.onmouseover = function(){
		if(!this.p_selected){
			this.style.textDecoration = "underline";
		}
	}

	p.obj.onmouseout = function(){
		if(!this.p_selected){
			this.style.textDecoration = "none";
		}
	}

	
	p.obj.onclick = function(){
		for(var x = 0; x<this.p_buttons.length; x++){
			this.p_buttons[x].hideShowMe(this.p_num)
		}

		switch(this.p_num){
			case 1:
				this.p_back_button.disableMe();
				this.p_next_button.enableMe();
				break;
			case this.p_buttons.length:
				this.p_back_button.enableMe();
				this.p_next_button.disableMe();
				break;
			default:
				this.p_next_button.enableMe();
				this.p_back_button.enableMe();
				break;
		}
	}

}


function tourButton(p){
	//alert(p.obj.id)
	p.obj.p_back_button = p.back_button;
	p.obj.p_next_button = p.next_button;
	p.obj.p_buttons = p.buttons;
	p.obj.p_enabled = (p.obj.id == "back_button")? false : true;
	p.obj.p_direction = (p.obj.id == "back_button")? false : true;
	
	p.obj.onclick = function(){
		if(this.p_enabled){
			if(this.p_direction){
				var lNum = (gTourButton+1);
			}else{
				var lNum = (gTourButton-1);
			}
			
			switch(lNum){
				case 1:
					this.disableMe();
					break;
				case 2:
					this.p_back_button.enableMe();
					break;
				case (this.p_buttons.length-1):
					this.p_next_button.enableMe();
					break;
				case this.p_buttons.length:
					this.disableMe();
					break;
				default:
					break;
			}
			
			for(var x = 0; x<this.p_buttons.length; x++){
				this.p_buttons[x].hideShowMe(lNum)
			}
		}
	}
	
	p.obj.enableMe = function(){
		if(!this.p_enabled){
			this.p_enabled = true;
			if(this.id == "back_button"){
				this.className = "redButton";
			}else{
				this.className = "greenButton";
			}
		}
	}
	
	p.obj.disableMe = function(){
		this.className = "disableButton";
		this.p_enabled = false;
	}

}


/***** SIGN UP LIGHTBOX ****/
function check_Signup_LightBox(){
	var lP = document.getElementById("hcc_signup_error");
	if(lP.innerHTML != ""){
		init_Signup_LightBox({type:"hcc",error:true})
	}
}

function init_Signup_LightBox(p){
	
	if(!p || !p.type){
		alert("type is not defined in init_Signup_LightBox()");
		return;
	}
	
	if(gPanel.signup_hcc){
		gPanel.signup_hcc.openPanel();
		return;
	}else{
		gLightBox.init({div:"signup_hcc"});
	}
	
	var lDiv = document.getElementById("hcc_signup_buttons");
	var lButton = null;
	if(lDiv){
		lButton = lDiv.getElementsByTagName('a')[0];
	}
	
	if(lButton){
		lButton.validateLightBox = function(){
			//alert(this.storeClick)
			var lSubmit = true;
			if(!this.input_yes.checked){
				lSubmit = false;
				this.error_age.style.display = "block";
			}
			
			//if(this.input_number)
			/*
			if(this.input_number.value.length != 6){
				if(this.input_number.value.length != 8){
					this.error_number.innerHTML = "Please try again"
					this.error_number.style.display = "block";
					lSubmit = false;
				}
			}
			*/
			
			if(this.input_number.value.length == 0){
				this.error_number.innerHTML = "Please try again"
				this.error_number.style.display = "block";
				lSubmit = false;
			}
			
			return lSubmit;
		}

		var lRadio = document.getElementById("signup_hcc").getElementsByTagName('input');
		//lButton.storeClick = lButton.href.split("'");
		//lButton.href = "javascript:void(0)";
		lButton.error_age = document.getElementById("hcc_signup_age_error");
		lButton.error_number = document.getElementById("hcc_signup_error");
		gPanel.signup_hcc.error_age = lButton.error_age;
		gPanel.signup_hcc.error_number = lButton.error_number;
		
		if(p.error){
			lButton.error_number.style.display = "block";
		}
		lButton.input_yes = lRadio[0];
		lButton.input_no = lRadio[1];
		lButton.input_number = lRadio[2];
		lButton.onclick = lButton.validateLightBox;
		
		// Yes Button //
		lRadio[0].error_age = lButton.error_age;
		lRadio[0].onclick = function(){
			this.error_age.style.display = "none";
		}
		
		// this restricts the enrollment number to numeric only //
		lRadio[2].onkeypress = gForms.numbers_only;
		 
		//alert(gPanel.signup_hcc.storeClick)
	
	}
}

function validateAddAddress(){
	alert("STOP")

	return false;
}

/***********************************************/
/*********** HCP PROFILE ADDRESSES *************/
/***********************************************/
function confirmAddressDelete(){
	var lDiv = document.getElementById("practice_addr");
	if(lDiv){
		var lA = lDiv.getElementsByTagName("a");
		if(lA.length){
			for(var x = 0; x<lA.length; x++){
				if(lA[x].className == "address_delete_link"){
					lA[x].onclick = function(){
						var lSubmit = confirm("Do you wish to remove the selected address?")
						return lSubmit;
					}
				}
			}
		}
	}
}

function PMG_HCP_address(p) {
    gHCPAddress.id = p.id || null;


    this.header = document.getElementById('add_edit_address_h3');
    this.add_btn = document.getElementById('add_btn');
    this.edit_btn = document.getElementById('edit_btn');

    this.lContainer = document.getElementById('address_'+p.id); // PM - this container has a single address
    this.lMainContainer = document.getElementById('practice_addr'); // PM - this container contains all the addresses

    this.iContainer = document.getElementById('practice_address'); // PM - this container contains all the inputs and selects
	this.lInputs = this.iContainer.getElementsByTagName('input');
	this.lSelects = this.iContainer.getElementsByTagName('select');

	gHCPAddress.field_names = new Array();
	gHCPAddress.span_names = new Array();

	this.pKey = p.key;
	
    this.init = function() {
        this.loadFields();
        this.resetFields();
        if (gHCPAddress.id == null) {
            gHCPAddress.id = 1; 
            gHCPAddress.func = 'add'; // PM - identifies which function should be called on the submit click
            this.header.innerHTML = 'Add an Address';
            this.add_btn.style.display='';
            this.edit_btn.style.display='none';
        	var lDivs = this.lMainContainer.getElementsByTagName("div");
            if(lDivs.length){
                for(var x = 0; x<lDivs.length; x++){
                    if (lDivs[x].className == 'address_container') {
                       gHCPAddress.id++; // PM - assigns new id for the new address block
                    }                    
                }
            }
        } else {
            gHCPAddress.func = 'update';
            this.header.innerHTML = 'Edit Address';
            this.add_btn.style.display='none';
            this.edit_btn.style.display='';
            this.getHCPAddress(); // PM - loads the HCP address into the input fields
        }
    }
    
    this.getHCPAddress = function() {
        for(var x = 0; x<gHCPAddress.span_names.length; x++){
			// For edit address store the key in a hidden field //
			if(gHCPAddress.span_names[x] == "hdKey"){
				if(this.pKey){
					var lKey = document.getElementById(gHCPAddress.field_names[x]);
					if(lKey){
						lKey.value = this.pKey;
					}
				}
			}else{
            	document.getElementById(gHCPAddress.field_names[x]).value = document.getElementById(gHCPAddress.span_names[x]+'_'+gHCPAddress.id).innerHTML;
			}
       }
    }
    
    this.resetFields = function() {
		if(this.lInputs.length){
			for(var x = 0; x<this.lInputs.length; x++){
			    this.lInputs[x].value = '';
			}
		}
		if(this.lSelects.length){ // PM - resets all the dropdowns (selects)
			for(var x = 0; x<this.lSelects.length; x++){
			    this.lSelects.selectedIndex = 0;
			}
	    }
    }
    
    this.loadFields = function() {
		if(this.lInputs.length){
			for(var x = 0; x<this.lInputs.length; x++){
			    var lName = this.lInputs[x].id.split("_")[2];
                gHCPAddress.field_names.push(this.lInputs[x].id);
                gHCPAddress.span_names.push(lName);
                if (lName == 'City') {
                    var lName = this.lSelects[0].id.split("_")[2];
                    gHCPAddress.field_names.push(this.lSelects[0].id);
                    gHCPAddress.span_names.push(lName);
                }
			}
        }
    }
}

function updateHCPAddress() {
    if (gHCPAddress.func == 'add') {
        insertHCPAddressBlocks();
    }

    upddate_HCP_address_span_elements();

	// PM - reset the field and span arrays
	gHCPAddress.field_names = new Array();
    gHCPAddress.span_names = new Array();

    //gPanel.practice_address.closePanel();
	
}

function insertHCPAddressBlocks() {

	var lContainer = document.getElementById("address_"+gHCPAddress.id);
	if(!lContainer){
		lContainer = document.createElement('div');
		lContainer.id = "address_"+gHCPAddress.id;
	    lContainer.className = "address_container";
	} else {
        alert("address_"+gHCPAddress.id+" already exists and cannot be added");
        return false;
	}
	
	for(var x = 0; x<gHCPAddress.span_names.length; x++){

        switch (gHCPAddress.span_names[x]) {
            case 'State':
            case 'Zip':
                break;
            default:
        	    var lDiv = document.createElement('div');
                lDiv.id = gHCPAddress.span_names[x]+'_div_'+gHCPAddress.id;
                break;            
	    }

	    var lSpan = document.createElement('span');
	    lSpan.id = gHCPAddress.span_names[x]+'_'+gHCPAddress.id;
	    lSpan.className = "addr_span";
	    lDiv.appendChild(lSpan);

	    switch (gHCPAddress.span_names[x]){
	        case 'City':
        	    var lSpan = document.createElement('span');
        	    lSpan.innerHTML = ', ';
        	    lDiv.appendChild(lSpan);
	        case 'State':
	            break;
	        default:
	            lContainer.appendChild(lDiv);
	            break;
        }
    }

    var lDiv = document.createElement('div');
    lDiv.id = 'links_container';
    var html = '<a href="javascript:void(0);" onclick="show_address_lightbox({id:\''+gHCPAddress.id+'\'});">Edit Address</a>';
/*
    html += '<span id="DeleteAddress_'+gHCPAddress.id+'" runat="server" visible="false">';
    html += '<span class="link_pipes" runat="server"> | </span>';
    html += '<asp:LinkButton ID="del_address_'+gHCPAddress.id+'" runat="server" OnClick="DeleteAddress_Click">Remove Address</asp:LinkButton>';
    html += '</span>';
*/
    html += '<span id="add_address_'+gHCPAddress.id+'">';
    html += '<span class="link_pipes"> | </span>';
    html += '<a href="javascript:void(0);" onclick="show_address_lightbox({});">Add Address</a>';
    html += '</span>';
    lDiv.innerHTML = html;
    lContainer.appendChild(lDiv);

    var lMainContainer = document.getElementById('practice_addr');
    lMainContainer.appendChild(lContainer);

    var prev_id = gHCPAddress.id - 1;
    document.getElementById('add_address_'+prev_id).style.display = 'none';

    return true;

}

function upddate_HCP_address_span_elements() {
    for(var x = 0; x<gHCPAddress.span_names.length; x++){
        
        switch (gHCPAddress.span_names[x]) {
            case 'State':
                var new_value = document.getElementById(gHCPAddress.field_names[x]).value+' ';
                break;
            case 'ADcPhone':
            case 'ADcFax':
                if (document.getElementById(gHCPAddress.field_names[x]).value == '') {
                    document.getElementById(gHCPAddress.span_names[x]+'_div_'+gHCPAddress.id).style.display = 'none';
                } else {
                    document.getElementById(gHCPAddress.span_names[x]+'_div_'+gHCPAddress.id).style.display = 'block';
                }
            default:
                var new_value = document.getElementById(gHCPAddress.field_names[x]).value;
                break;
        }
        
        document.getElementById(gHCPAddress.span_names[x]+'_'+gHCPAddress.id).innerHTML = new_value;
    }
}

function show_address_lightbox(p) {
	if(typeof(p) != "object"){
		alert("Object not passed to show_address_lightbox()");
		return;
	}
	
	if(gPanel.practice_address){
		gPanel.practice_address.openPanel();
	}else{
		gLightBox.init({div:'practice_address'});
		var lDiv = document.getElementById("practice_address");
		var lA = lDiv.getElementsByTagName("a");
		
		gPanel.practice_address.validateMe = function(){
			var lValidate = {ctl00_ContentPlaceHolder1_PracticeName:true,ctl00_ContentPlaceHolder1_Address1:true,ctl00_ContentPlaceHolder1_City:true,ctl00_ContentPlaceHolder1_State:true,ctl00_ContentPlaceHolder1_Zip:true}
			var lSubmit = true;
			for(var x in lValidate){
				var item = document.getElementById(x);
				if(item){
					switch(item.type){
						case "text":
							if(item.value == ""){
								lSubmit = false;
							}
							break;
						default:
							if(item.selectedIndex == 0){
								lSubmit = false;
							}
							break;
					}
				}
			}
			
			if(!lSubmit){
				var lP = document.getElementById("add_adress_error");
				if(lP){
					lP.style.display = "block";
				}
			}
			
			return lSubmit;
		}
		
		
		lA[0].onclick = function(){
			return gPanel.practice_address.validateMe();
		}

		lA[1].onclick = function(){
			return gPanel.practice_address.validateMe();
		}
		
		
	}

	if(p.key){
		//alert(p.key)
	}

	
    p = new PMG_HCP_address(p);
    p.init();
	
	
}

function initRegistrationHCP(){
	var radio_checked = false;
   	var iContainer = document.getElementById('signup_hcp'); // PM - this container contains radio button selection for the HCP registration
	var lInputs = iContainer.getElementsByTagName('input');
	if(lInputs.length){
		for(var x = 0; x<lInputs.length; x++){
			if (lInputs[x].checked)  {
				radio_checked = true;
				switch (lInputs[x].value) {
					case 'yes':
						document.location.href = '/hcp/register_hcp.aspx';
						return;
					case 'no':
						//document.getElementById('reg_step1').style.display = 'none';
						document.getElementById('not_us').style.display = 'block';
						document.getElementById('errorText').style.display = 'none';
						return;
				} 
			}
		}
	}
	
	if (!radio_checked) {
		document.getElementById('errorText').style.display = 'block';
	}
		
}


// ********************************* //
// returns the x and y of an element //
// ********************************* //
function PMG_getCoords(pObj){
	//gDebug.getVar(pObj)
	//gDebug.getVar(pObj.getClientRects()[0])
	if(pObj){
		var lCoords = {x:0,y:0,width:pObj.offsetWidth,height:pObj.offsetHeight};
		while(pObj){
			lCoords.x += parseInt(pObj.offsetLeft);
			lCoords.y += parseInt(pObj.offsetTop);
			pObj = pObj.offsetParent;
			//alert("pObj.id = " + pObj.id);
		}
		lCoords.right = (lCoords.x + lCoords.width);
		lCoords.bottom = (lCoords.y + lCoords.height);
		return lCoords;
	}
	
	return false;
}


function logoClick(){
	// HCC Site //
	if(location.href.indexOf("hcc/") != -1){
		var lHeader = document.getElementById("header_sfw");
		if(lHeader){
			var lLink = lHeader.getElementsByTagName("a")[0];
			if(lLink){
				location.href = lLink.href;
			}
		}
	}else{
		// HCP Site //
		location.href = "/hcp/index_hcp.aspx";
	}
}


// ********************************* //
// *** View Recipe functionality *** //
// ********************************* //
var gRecipe = {};
function getRecipeData(p){
	
	if(!p.id){
		alert("Recipe ID not defined in getRecipeData()")
		return false;
	}
	
	gRecipe.data = {RecipeID:true,RecipeNb:true,Description:true,MealDescription1:true,MealDescription2:true,Instructions:true};
	gRecipe.nutrition = {Kcals:true,Protein:true,Carb:true,Fat:true,SatFat:true,Chol:true,Sodium:true,PercentFat:true};
	gRecipe.url = "getrecipe.aspx?ID=" + p.id;
	
	gRecipe.callBack = function(p){
		var lText = p.split("<NewDataSet>")[1];
		var lXML = '<?xml version="1.0"?>' + lText.split("</NewDataSet>")[0];
		var lXML = gXML.parseXML(lXML);
		// IE reports undefined with the firstChild.length ?? //
		var lNodes = lXML.childNodes[lXML.childNodes.length-1].childNodes;
		for(var x = 0; x<lNodes.length; x++){
			if(lNodes[x].nodeName != "#text"){
				var lNodeName = lNodes[x].nodeName;
				var lNodeValue = lNodes[x].firstChild.nodeValue;
				if(gRecipe.data[lNodeName]){
					gRecipe.data[lNodeName] = lNodeValue;
				}else{
					if(gRecipe.nutrition[lNodeName]){
						gRecipe.nutrition[lNodeName] = lNodeValue;
					}
				}
				//alert(lNodes[x].nodeName + " = " + lNodes[x].firstChild.nodeValue);
			}
		}
		
		
		//gDebug.getVar(gRecipe.data)
		var lDiv = document.getElementById("recipe_data_goes_here");

		if(lDiv){
			// add the recipe photo //
			var lPhoto = null;
			if(gRecipe.data.RecipeNb <= 56){
				var lPhoto = document.createElement("img");
				lPhoto.id = "view_recipe_photo";
				lPhoto.className = "recipe_photo";
				lPhoto.src = gPaths.images + "planner_meal/recipes/" + gRecipe.data.RecipeNb + ".jpg";
				lPhoto.alt = (gDebug.tools)? gRecipe.data.RecipeNb : "";
				//alert(gRecipe.data.RecipeNb)
			}
			
			// add the recipe title
			var lH3 = document.createElement("h3");
			lH3.id = "view_recipe_title";
			var lTitle = document.createTextNode(gRecipe.data.Description);
			lH3.appendChild(lTitle);
			
			// create the print link //
			var lA = document.createElement("a");
			lA.href = "javascript:void(0);";
			lA.id = "view_recipe_print_pdf"
			lA.onclick = function(){
				window.print();
			}
			var lText = document.createTextNode("print");
			lA.appendChild(lText)
			
			// H3 & print container //
			var lSpan = document.createElement("span");
			lSpan.id = "view_recipe_span";
			lSpan.appendChild(lH3);
			lSpan.appendChild(lA);
			
			//<a href="javascript:void(0);" id="print_pdf" onclick="">print</a>
			
			// append the UL ingredients //
			var lBullets = document.createElement("div");
			lBullets.id = "view_recipe_bullets";
			lBullets.className = "recipe_bullets";
			var B1 = gRecipe.data.MealDescription1.split("</ul>")[0];
			var B2 = gRecipe.data.MealDescription2.split("<ul>")[1];
			lBullets.innerHTML =  B1 + B2;
			
			// append the intructions //
			var lInstructions = document.createElement("div");
			lInstructions.id = "view_recipe_instructions";
			lInstructions.className = "recipe_instructions";
			var lP = document.createElement("p");
			lP.innerHTML = gRecipe.data.Instructions;
			lInstructions.appendChild(lP);
			
			// format the nutrients //
 			//gDebug.getVar(gRecipe.nutrition);
			var lNutrients = document.createElement("div");
			lNutrients.id = "view_recipe_nut";
			var lTable = '<table id="view_recipe_nut_table" cellpadding="0" cellspacing="0" border="0">';
			lTable += '<tr><td colspan="2" style="padding-left: 0;"><b>Nutrient content per serving:</b></td></tr>';
			lTable += '<tr><td>Total calories: ' + gRecipe.nutrition.Kcals + '</td><td>Calories from fat: ' + gRecipe.nutrition.PercentFat + '</td></tr>';
			lTable += '<tr><td>Protein: ' + gRecipe.nutrition.Protein + '</td><td>Saturated fat: ' + gRecipe.nutrition.SatFat + '</td></tr>';
			lTable += '<tr><td>Carbohydrates: ' + gRecipe.nutrition.Carb + '</td><td>Choleserol: ' + gRecipe.nutrition.Chol + '</td></tr>';
			lTable += '<tr><td>Fat: ' + gRecipe.nutrition.Fat + '</td><td>Sodium: ' + gRecipe.nutrition.Sodium + '</td></tr>';
			lTable += '</table>';
			lNutrients.innerHTML = lTable;
			
			var lNutrients2 = document.createElement("div");
			lNutrients2.id = "view_recipe_nut_print";
			var lPrintNut = '<ul id="view_recipe_nut_print">';
			lPrintNut += '<li><b>Nutrient content per serving:</b></li>';			
			lPrintNut += '<li>Total calories: ' + gRecipe.nutrition.Kcals  + '</li>';
			lPrintNut += '<li>Protein: ' + gRecipe.nutrition.Protein + '</li>';
			lPrintNut += '<li>Carbohydrates: ' + gRecipe.nutrition.Carb + '</li>';
			lPrintNut += '<li>Fat: ' + gRecipe.nutrition.Fat + '</li>';
			lPrintNut += '<li>Calories from fat: ' + gRecipe.nutrition.PercentFat + '</li>';
			lPrintNut += '<li>Saturated fat: ' + gRecipe.nutrition.SatFat + '</li>';
			lPrintNut += '<li>Choleserol: ' + gRecipe.nutrition.Chol + '</li>';
			lPrintNut += '<li>Sodium: ' + gRecipe.nutrition.Sodium + '</li>';
			lPrintNut += '</ul>';
			lNutrients2.innerHTML = lPrintNut;
			
			
			// hide the loading graphic //
			var lLoading = document.getElementById("recipe_loader");
			if(lLoading){
				lLoading.style.display = "none";
			}
			
			var lSpan2 = lSpan.cloneNode(true);
			if(lPhoto){
				var lPhoto2 = lPhoto.cloneNode(true);
			}
			var lBullets2 = lBullets.cloneNode(true);
			var lInstructions2 = lInstructions.cloneNode(true);
			
			// append all the elements //
			lDiv.appendChild(lSpan);
			if(lPhoto){
				lDiv.appendChild(lPhoto);
			}
			lDiv.appendChild(lBullets);
			lDiv.appendChild(lNutrients);
			lDiv.appendChild(lInstructions);
			gPanel.view_recipe_mp.centerPanel();
			
			var lAddButton = document.getElementById("view_recipe_add_button");
			if(lAddButton){
				if(gProps.page.indexOf("edit_mp") != -1){
					lAddButton.style.display = "inline";
				}
			}
			

			var lPrintDiv = document.createElement("div");
			lPrintDiv.id = "view_recipe_print";
			lPrintDiv.appendChild(lSpan2);
			if(lPhoto){
				lPrintDiv.appendChild(lPhoto2);
			}
			lPrintDiv.appendChild(lBullets2);
			lPrintDiv.appendChild(lNutrients2);
			lPrintDiv.appendChild(lInstructions2);
			document.body.insertBefore(lPrintDiv,document.body.firstChild)

		}
		
	}
	
	
	PMG_request(gRecipe);
}

/***************************************/
/*            HTTP REQUEST             */
/***************************************/
function PMG_request(p){
	var AJAX = {};

	if(window.XMLHttpRequest){
		AJAX.request = new XMLHttpRequest();
	}else{
		if(window.ActiveXObject){
			AJAX.request = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	if(typeof(AJAX.request) != "undefined"){
		AJAX.request.onreadystatechange = function(){
			p.request = AJAX.request;
			PMG_requestDone(p);
		}
		AJAX.request.open("GET", p.url, true);
		AJAX.request.send("");
	}
}  

function PMG_requestDone(p){
	var lText = null;
	if(p.request.readyState == 4){ // only if p_x is "loaded"
		if(p.request.status == 200){ // only if "OK"
			lText = p.request.responseText;
		}else{
			lText = "PMG_requestDone() Error:\n" + p.request.status + "\n" + p.request.statusText;
		}
	}
	
	if(lText){
		p.callBack(lText);
	}
	
	return false;
}

// ***************************************************************************** //
// gXML = XMLHttpRequest() - All XML Object functions
// ***************************************************************************** //
var gXML = {};
gXML.parseXML = function(text) {
    if(typeof DOMParser != "undefined"){
        // Mozilla, Firefox, and related browsers
        return (new DOMParser()).parseFromString(text, "application/xml");
    }else{
		if(typeof ActiveXObject != "undefined"){
	        // Internet Explorer. //
	        var doc = gXML.newDocument( );
	        doc.loadXML(text);
	        return doc;
    	}else{
	        // As a last resort, try loading the document from a data: URL, Safari //
	        var url = "data:text/xml;charset=utf-8," + encodeURIComponent(text);
	        var request = new XMLHttpRequest();
	        request.open("GET", url, false);
	        request.send(null);
	        return request.responseXML;
	    }
	}
}


gXML.loadAsync = function(url, callback) {
    var xmldoc = gXML.newDocument();

    // If we created the XML document using createDocument, use
    // onload to determine when it is loaded
    if (document.implementation && document.implementation.createDocument) {
        xmldoc.onload = function(){
			callback(xmldoc);
		}
    }else{
		// IE, use onreadystatechange as with XMLHttpRequest
		xmldoc.onreadystatechange = function() {
            if (xmldoc.readyState == 4){
				callback(xmldoc);
			}
        }
    }

    // Now go start the download and parsing
    xmldoc.load(url);
}

gXML.load = function(url) {
    var xmldoc = gXML.newDocument();
    xmldoc.async = false;
    xmldoc.load(url);
    return xmldoc;
}

gXML.newDocument = function(rootTagName, namespaceURL) {
    if (!rootTagName) rootTagName = "";
    if (!namespaceURL) namespaceURL = "";
	
    if (document.implementation && document.implementation.createDocument) {
        // This is the W3C standard way to do it
        return document.implementation.createDocument(namespaceURL,rootTagName, null);
    }else{
		// This is the IE way to do it //
        // Create an empty document as an ActiveX object //
        // If there is no root element, this is all we have to do //
        var doc = new ActiveXObject("MSXML2.DOMDocument");

        // If there is a root tag, initialize the document
        if(rootTagName){
            // Look for a namespace prefix
            var prefix = "";
            var tagname = rootTagName;
            var p = rootTagName.indexOf(':');
            if(p != -1){
                prefix = rootTagName.substring(0, p);
                tagname = rootTagName.substring(p+1);
            }

            // If we have a namespace, we must have a namespace prefix
            // If we don't have a namespace, we discard any prefix
            if (namespaceURL) {
                if(!prefix){
					prefix = "a0"; // What Firefox uses
				}
            }else{
				prefix = "";
			}

            // Create the root element (with optional namespace) as a
            // string of text
            var text = "<" + (prefix?(prefix+":"):"") + tagname + (namespaceURL?(" xmlns:" + prefix + '="' + namespaceURL +'"'):"") + "/>";
            // And parse that text into the empty document
            doc.loadXML(text);
        }
        return doc;
    }
}

// ********************************* //
//          Form functions           //
// ********************************* //
var gForms = {};
// this function will only allow numbers to be entered into a field //
gForms.numbers_only = function(e){
	var lKey = (e)? e.which : event.keyCode;
	// key 48 = 0, key 57 = 9, key 8 = backspace, key 0 = TAB //
	if(!this.pError){
		this.pError = document.getElementById(this.id + "_error");
	}else{
		if(this.pError.style.display != "none"){
			this.pError.style.display = "none";
		}
	}
	
	var lOK = ((lKey >= 48) && (lKey <= 57));

	if(lOK || (lKey == 8) || (lKey == 0)){
		return true;
	}else{
		//alert(lKey)
		return false;
	}
}

gForms.assignEnterKey = function(e){
	var lKey = (e)? e.which : event.keyCode;
	//var lOK = ((lKey >= 48) && (lKey <= 57));
	
	if((lKey == 13) && gForms.enterKey){
		gForms.enterKey.onclick();
		return false;
	}
}

// ******************************************** //
// validates e-mail address   
// p = {}
// p.address = string (email address)
// p.error = object error container
// ******************************************** //
gForms.validEmail = function(p){
	var lValid = false;
	
	if(typeof(p) != "object"){
		alert("object not passed to gForms.validEmail()");
	}else{
		
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		lValid = reg.test(p.address);
		// show the error message /
		if(p.error && !lValid){
			p.error.style.display = "block";
		}
	}
	
	return lValid;
}

// ********************************* //
//         Print functions           //
// ********************************* //
function initPrintButton(){
	if(gPrint.enabled){
		if(gPrint.divs.length){
			
			var lPrintDiv = document.createElement("div");
			lPrintDiv.id = (gPrint.id)? gPrint.id + "_generic_id" : "print_generic_id";
			lPrintDiv.className = "generic_print";
			
			for(var x =0; x<gPrint.divs.length; x++){
				var lDiv = document.getElementById(gPrint.divs[x]);
				if(lDiv){
					var lDivNew = lDiv.cloneNode(true);
					lPrintDiv.appendChild(lDivNew);
				}
			}
			
			document.body.appendChild(lPrintDiv);
			
			var lButton = document.getElementById("print_pdf");
			if(lButton){
				lButton.onclick = function(){
					window.print();
					return false;
				}
			}
		}
	}
}

// ********************************* //
//         REORDER MATERIALS         //
// ********************************* //
function initReorderMaterials(){
	
	var lRadios = document.getElementById("order_radios");
	if(lRadios){
		lRadios = lRadios.getElementsByTagName('input')
	}
	
	if(lRadios && lRadios.length){
		for(var x = 0; x<lRadios.length; x++){
			new orderRadioButton(lRadios[x]);
		}
	}

	var lButtons = document.getElementById("order_buttons");
	if(lButtons){
		lButtons = lButtons.getElementsByTagName('a');
	}
	
	if(lButtons && lButtons.length){
		for(var x = 0; x<lButtons.length; x++){
			lButtons[x].pNum = x;
			lButtons[x].pRadio = lRadios;
			new orderButton(lButtons[x]);
		}
	}
}

function orderButton(p){
	
	p.pReset = (p.id.indexOf("reset") != -1)? true : false;
	p.pPrint = false;
	
	// reset button //
	if(p.pReset){
		p.onclick = function(){
			resetOrderForm({checkboxes:true,selects:true});
			return false;
		}
	}else{
		// submit button validate form //
		p.onclick = function(){
			
			var lQuantity = true;
			var lAddress = true;
			for(var x = 0; x<this.pRadio.length; x++){
				if(this.pRadio[x].checked){
					this.pPrint = this.pRadio[x].pPrint;
					lQuantity = this.pRadio[x].validateMe();
					if(lQuantity){
						// get all the pdf print properties //
						if(this.pPrint){
							this.pPDF = this.pRadio[x].getProps();
						}
						
						break;
					}
				}
			}

			
			var lDiv = document.getElementById("order_address");
			if(lDiv){
				var lSelect = lDiv.getElementsByTagName("select")[0];
				if(lSelect.selectedIndex == 0){
					lAddress = false;
				}else{
					var lAddress_ID = lSelect.value;
				}
			}
			
			orderFormErrors({"quantity":!lQuantity, "address":!lAddress});

			// check if it is print PDF //
			if(this.pPrint){
				if((lQuantity == true) && (lAddress == true)){
					//gDebug.getVar(this.pPDF);
					var lString = "/hcp/reorder_pdf.aspx?ID=" + lAddress_ID + "&pqty=" + this.pPDF.PAD + "&sqty=" + this.pPDF.SURVEYS;
					openPDFWindow(lString);

					return false;
				}
			}else{
				// NOT PDF print = pass true for code behind to mail forms & pads //
				if((lQuantity == true) && (lAddress == true)){
					return true;
				}else{
					return false;
				}
			}
			
			return false;
		}	
	}
}

function orderFormErrors(p){
	if(!p){
		p = {"quantity":false, "address":false};
	}
	
	for(var prop in p){
		var lDisplay = "none";
		if(p[prop]){
			lDisplay = "block";
		}
		
		var lP = document.getElementById(prop + "_error");
		if(lP){
			lP.style.display = lDisplay;
		}
	}
}

function resetOrderForm(p){
	var lDiv = document.getElementById("reorder_container");
	if(lDiv){
		if(p.checkboxes){
			// reset the checkboxes //
			var lA = lDiv.getElementsByTagName("input");
			if(lA.length){
				for(var x = 0; x<lA.length; x++){
					var input = lA[x];
					if(input.type == "checkbox"){
						input.checked = false;
					}
				}
			}
		}
		
		if(p.selects){
			var lA = lDiv.getElementsByTagName("select");
			if(lA.length){
				for(var x = 0; x<lA.length; x++){
					var input = lA[x];
					input.selectedIndex = 0;
				}
			}
		}
	}
	
	orderFormErrors({"quantity":false, "address":false});
}

function orderRadioButton(p){

	p.pNum = p.id.split("_").pop();
	p.pType = (p.pNum == 0)? "printable_" : "ship_";
	p.pPrint = (p.pNum == 0)? true : false;
	p.pDivs = ["ship_materials_forms","printable_PDF_forms","ship_materials_pads","printable_PDF_pads"];
	p.pValidate = (p.pNum == 0)? ["printable_PDF_forms","printable_PDF_pads"] : ["ship_materials_forms","ship_materials_pads"]
	
	p.validateMe = function(){
		var lReturn = false;
		for(var x = 0; x<this.pValidate.length; x++){
			var lDiv = document.getElementById(this.pValidate[x]);
			var lA = lDiv.getElementsByTagName("select");
			if(lA.length){
				for(var i = 0; i<lA.length; i++){
					var input = lA[i];
					if(input.selectedIndex != 0){
						lReturn = true;
					}
				}
			}
		}
		return lReturn;
	}
	
	
	p.getProps = function(){
		var pProps = {};
		for(var x = 0; x<this.pValidate.length; x++){
			var lDiv = document.getElementById(this.pValidate[x]);
			var lA = lDiv.getElementsByTagName("select");
			if(lA.length){
				for(var i = 0; i<lA.length; i++){
					var input = lA[i];
					var pMe = input.id.split("_")[input.id.split("_").length-2];
					pProps[pMe] = input.value;
				}
			}
		}
		return pProps;
	}
	
	p.showMe = function(){
		for(var x in this.pDivs){
			var lDiv = document.getElementById(this.pDivs[x]);
			if(lDiv){
				if(lDiv.id.indexOf(this.pType)!=-1){
					lDiv.style.display = "block";
				}else{
					lDiv.style.display = "none";
				}
			}
		}
	}

	p.onclick = function(){
		this.showMe();
		resetOrderForm({checkboxes:false,selects:true});
	}

	if(p.pNum == 0){
		p.onclick();
		p.checked = true;
	}
	
}