// function to change content
// when the OAS JSON file is called, this function is executed
// the response calls this function with a large JSON object as the parameter
// this object is parsed and the appropriate elements are changed
//
// Example calling the URR (x20 - x31) on sleep-disorder:
//
// url:  http://ls.webmd.com/2/webmd/sleep-disorder/1368494156@Position1,x20,x21,x22,x23,x24,x25,x26,x27,x28,x29,x30,x31,Position2?_RM_NO_COMMENT_
//
// Response:
/*
webmd.p.fe_content_update({'x20' : {'pos':'x20', 'text':'ARTICLE', 'href':'http://ls.webmd.com/RealMedia/ads/click_lx.ads/webmd/sleep-disorder/L20/892675990/x20/WebMD/Excessive_Sweating_TC_URR/Excessive_Sweating_TC_URR.html/5134496d416b377257444d4143775235', 'img':'http://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/thumbnails/unified_right_rail/menopause/69x75_thumbnail_sweating_evaluator.jpg', 'alt':'Night Sweats Keeping You Awake?'},'x21' : {'pos':'x21', 'text':'ARTICLE', 'href':'http://ls.webmd.com/RealMedia/ads/click_lx.ads/webmd/sleep-disorder/L20/408568797/x21/WebMD/ADHD_Inventory_Guide_Pages1_URR/ADHD_Inventory_Guide_Pages1_URR.html/5134496d416b377257444d4143775235', 'img':'http://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/thumbnails/unified_right_rail/sleep_disorder/69x75_thumbnail_fight_fatigue_sleepiness_on_the_road.jpg', 'alt':'Is Snoring Related to ADHD?'},'x22' : {'pos':'x22', 'text':'ARTICLE', 'href':'http://ls.webmd.com/RealMedia/ads/click_lx.ads/webmd/sleep-disorder/L20/967929234/x22/WebMD/Lilly_Cymbalta_Fibro_HZ1_URR/Lilly_Cymbalta_Fibro_HZ1_URR.html/5134496d416b377257444d4143775235', 'img':'http://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/thumbnails/unified_right_rail/fibromyalgia/69x75_pain_at_night.jpg', 'alt':'Beating Fibromyalgia Pain at Night'},'x23' : {'pos':'x23', 'text':'SLIDESHOW', 'href':'http://ls.webmd.com/RealMedia/ads/click_lx.ads/webmd/sleep-disorder/L20/2136428963/x23/WebMD/J_and_J_Tylenol_Cold_Flu_HZinM_URR/J_and_J_Tylenol_Cold_Flu_HZinM_URR.html/5134496d416b377257444d4143775235', 'img':'http://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/health_checks/allergy_sinus_symptoms_evaluator/69x75_allergy_sinus_symptoms_evaluator.jpg', 'alt':'10 Ways to Rest Better With a Cold'},'x24' : {'pos':'x24', 'text':'ARTICLE', 'href':'http://ls.webmd.com/RealMedia/ads/click_lx.ads/webmd/sleep-disorder/L20/1416730986/x24/WebMD/Target_Ask_the_Pharm_Answers2_URR/Target_Ask_the_Pharm_Answers2_URR.html/5134496d416b377257444d4143775235', 'img':'http://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/thumbnails/unified_right_rail/sleep_apnea/69x75_sa_clues_you_may_have_osa.jpg', 'alt':'Side Effects of Sleeping Pills'},'x25' : {'pos':'x25', 'text':'SLIDESHOW', 'href':'http://ls.webmd.com/RealMedia/ads/click_lx.ads/webmd/sleep-disorder/L20/104859776/x25/WebMD/Sleep_PV_Drivers2_URR/Sleep_PV_Drivers2_URR.html/5134496d416b377257444d4143775235', 'img':'http://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/thumbnails/unified_right_rail/sleep_disorder/69x75_thumbnail_foods_that_help_or_harm_your_sleep.jpg', 'alt':'Foods That Help or Harm Your Sleep'},'x26' : {'pos':'x26', 'text':'ARTICLE', 'href':'http://ls.webmd.com/RealMedia/ads/click_lx.ads/webmd/sleep-disorder/L20/1488582476/x26/WebMD/Target_Ask_the_Pharm_Answers3_URR/Target_Ask_the_Pharm_Answers3_URR.html/5134496d416b377257444d4143775235', 'img':'http://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/can_herbs_and_supplements_help_sleep/69x75_can_herbs_and_supplements_help_sleep.jpg', 'alt':'Which Herbs Can Improve Sleep?'},'x27' : {'pos':'x27', 'text':'SLIDESHOW', 'href':'http://ls.webmd.com/RealMedia/ads/click_lx.ads/webmd/sleep-disorder/L20/1888734796/x27/WebMD/Sleep_PV_Drivers7_URR/Sleep_PV_Drivers7_URR.html/5134496d416b377257444d4143775235', 'img':'http://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/thumbnails/unified_right_rail/sleep_disorder/69x75_thumbnail_insomnia_20_tips_for_better_sleep.jpg', 'alt':'Can\'t Sleep? 20 Tips for More ZZZs'},'x28' : 'null','x29' : 'null','x30' : 'null','x31' : 'null','End' : 'null'});
*/

// Example of single item (first URR element, x20):
// this item contains (in this order): the position, text below the thumbnail, link url, image source, and link text
/*
'x20' : {
	'pos':'x20',
	'text':'ARTICLE',
	'href':'http://ls.webmd.com/RealMedia/ads/click_lx.ads/webmd/sleep-disorder/L20/892675990/x20/WebMD/Excessive_Sweating_TC_URR/Excessive_Sweating_TC_URR.html/5134496d416b377257444d4143775235',
	'img':'http://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/thumbnails/unified_right_rail/menopause/69x75_thumbnail_sweating_evaluator.jpg',
	'alt':'Night Sweats Keeping You Awake?'
}
*/
webmd.p.fe_content_update = function(data){
	var self = this;

	// temporary fix
	// this is ONLY to allow the span to be placed in a link
	// this is because the link will be rewritten
	// and this ensures the span is added AFTER the link is written
	var $promo = {}, link_written, promo_text = '';

    // 'x' element map to template items
    // these are grouped by type
    // the value is where they map to in the template below
    // "lnk" is like a default; it is used in many places
    //
    // 1-3 - homepage RR links
    // 4 - promo image
    // 5-7 - promo links
    // 8-14 - top stories
    // 20-31 - URR
    // 56-61 - tools and resources
    // 62-67 - top picks
    // 68-77 - A-Z hot topics
    var oas_mapping = {
    	'x01': 'hrr', 'x02': 'hrr', 'x03': 'hrr',
    	'x04': 'ovr',
    	'x05': 'prm', 'x06': 'prm', 'x07': 'prm',
    	'x08': 'lnk', 'x09': 'lnk', 'x10': 'lnk', 'x11': 'lnk', 'x12': 'lnk', 'x13': 'lnk', 'x14': 'lnk', 
    	'x20': 'urr', 'x21': 'urr', 'x22': 'urr', 'x23': 'urr', 'x24': 'urr', 'x25': 'urr', 'x26': 'urr', 'x27': 'urr', 'x28': 'urr', 'x29': 'urr', 'x30': 'urr', 'x31': 'urr',
    	'x56': 'lnk', 'x57': 'lnk', 'x58': 'lnk', 'x59': 'lnk', 'x60': 'lnk', 'x61': 'lnk',
    	'x62': 'lnk', 'x63': 'lnk', 'x64': 'lnk', 'x65': 'lnk', 'x66': 'lnk', 'x67': 'lnk',
    	'x68': 'lnk', 'x69': 'lnk', 'x70': 'lnk', 'x71': 'lnk', 'x72': 'lnk', 'x73': 'lnk', 'x74': 'lnk', 'x75': 'lnk', 'x76': 'lnk', 'x77': 'lnk'
    };

    // this is a simple template used to determine what goes where
    // the key ia the template name, for example 'hrr' is used by x01-x03
    //
    // in the object, the keys are what OAS passes
    // each of these has values of objects
    //
    // these object keys are a string which represents where in the context of the "x" element to place the value
    // these object values are either 1) attributes 2)html or 3) span
    //
    // when html is set, the text INSIDE the selector elements are changed
    // when span is set, a span tag is APPENDED to the selector elements
    // every other value will change the ATTRIBUTE of the selector elements
    //
    // 'template': {'oas-key-passed': {'selector-in-relation-to-x-element': 'attribute-or-html'}}
	var oas_template = {
		'hrr': {'href': {'a': 'href', '.feature h3 a': 'href'}, 'alt': {'.feature h3 a': 'html'}, 'img': {'a img': 'src'}, 'text': {'.feature p': 'html'}},
		'ovr': {'href': {'a': 'href'}, 'alt': {'a img': 'alt'}, 'img': {'a img': 'src'}},
		'prm': {'href': {'a': 'href'}, 'alt': {'a': 'html'}, 'text': {'a': 'span'}},
		'urr': {'img': {'a img': 'src'}, 'text': {'.header_fmt': 'html'}, 'href': {'a': 'href', '.link_fmt a': 'href'}, 'alt': {'a img': 'alt', '.link_fmt a': 'html'}},
		'lnk': {'href': {'a': 'href'}, 'alt': {'a': 'html'}}
	};

	// on document ready...
	$(function(){
		// go through each 'x' value passed in the OAS response
		$.each(data, function(x_key, x_val){
			
			// temporary fix
			link_written = false;

			/* Add to keep images from blinking in webkit browsers
			wait = false;
			*/


			// make sure it is an 'x' value
			// some keys are not 'x' elements
			if(/^x\d{2,3}/i.test(x_key)){

				// now go through the object
				//
				// Example:
				// 'alt': 'Night Sweats Keeping You Awake?'
				//
				// 'alt' is object_key
				// 'Night Sweats Keeping You Awake?' is 
				$.each(x_val, function(object_key, object_val){

					// if the key exists in the map AND the template uses this field...
					// the first part checks if the "x" element is mapped
					//
					// Example:
					//
					// the first part is checked:  oas_mapping[x_key]
					// x_key = "x20"
					// oas_mapping["x20"] == "urr" == true
					//
					// if true it checks the second part:   oas_template[oas_mapping[x_key]][object_key]
					//
					// x_key = "x20"
					// 'alt': {'a': 'html'}
					// oas_template[oas_mapping[x_key]][object_key]
					// oas_template[oas_mapping["x20"]][object_key]
					// oas_template["urr"][object_key]
					// oas_template["urr"]["alt"] == {'a': 'html'} == true
					//
					// the object is coerced to true so it continues
					// 
					if(oas_mapping[x_key] && oas_template[oas_mapping[x_key]][object_key]){

						// go through the value of each key
						//
						// using the example above:
						// oas_template[oas_mapping[x_key]][object_key] == {'a': 'html'}
						//
						// template_key is 'a'
						// template_val is 'html'
						$.each(oas_template[oas_mapping[x_key]][object_key], function(template_key, template_val){

							// handle plain text changes
							// .text is used instead of .html because .html doesn't correctly handle some characters such as ampersands
							if(template_val == 'html'){

								// this selects the element
								// > is used to find the immediate descendant
								// this allows us to be very specific about which element to change and how
								//
								// Example:  $('#' + x_key + ' > ' + template_key)
								//
								// $('#' + x_key + ' > ' + template_key)
								// $('#' + 'x20' + ' > ' + 'a')
								// $('#x20 > a')
								$('#' + x_key + ' > ' + template_key).text(x_val[object_key]);


								/* start temporary fix */
								// this is to allow the span to be written inside elements and not be rewritten
								link_written = true;
								if($promo.length){
									$promo.append(promo_text);
									promo_text = '';
									$promo = {};
								}
								/* end temporary fix */

							// appends instead of replaces
							} else if(template_val == 'span'){
								/* start temporary fix */
								if(link_written){
									$('#' + x_key + ' > ' + template_key).append('<span>' + x_val[object_key] + '</span>');
								} else {
									$promo = $('#' + x_key + ' > ' + template_key);
									promo_text = '<span>' + x_val[object_key] + '</span>';
								}
								/* end temporary fix */

							// everything else is an attribute
							} else {

								// necessary to remove attribute first to prevent blinking - eg. images take a while to load
								$('#' + x_key + ' > ' + template_key).attr(template_val, '').attr(template_val, x_val[object_key]);
							}
							/* Add to keep images from blinking in webkit browsers
							if(object_key == 'img'){
								wait = true;
								$("<img>").bind("load", function(){ $('#' + x_key).css('visibility','visible'); }).attr(template_val, x_val[object_key]);
							}
							*/
						});
					}
				});
			}
			/* Add to keep images from blinking in webkit browsers
			if(!wait){
				$('#' + x_key).css('visibility','visible');
			}
			*/
			/* Remove this to keep images from blinking in webkit browsers */
			// after all is done, show it
			$('#' + x_key).css('visibility','visible');
		});
		
		// cancel the timeout since it is already visible
		clearTimeout(webmd.p.fe_content_update.oas_timeout);
	});
}

// the keys here are what are added to the query string
// the values are regex literals used to check the url
// if there is a regex match with the url, the key is used in the url of the query string
webmd.p.oas_get_center = {
	'men' : /http:\/\/men\./i,
	'sleep-disorder' : /\.webmd\.com\/sleep-disorders/i,
	'a-to-z-guides' : /\.webmd\.com\/a-to-z-guides/i
}

// on load, page is scanned for #x__ elements
$(function(){
	var oas_elements = [],		// 
		oas_query,				// stores the query string to call the OAS JSON response
		oas_section,			// stores the key used in get_center
		oas_element_id,			// stores the ids being inpected for "x" elements
		oas_timeout,  			// used to store the timeot
		url = location.href;	// the url

	// determine which center the page
	$.each(webmd.p.oas_get_center, function(index, value){
		if(value.test(url)){
			oas_section = index;
			return false;
		}
	});

	// homepage is the default
	if(!oas_section){
		// !!!  to add homepage, remove the comment below and delete the line after it:   oas_section = '';  !!!
		// Turning on OAS for homepage 1/25 -thoppe 

		oas_section = 'homepage'; // uncomment this
		//oas_section = ''; // remove this
	}

	// go through each id on the page that contains "x"
	$("[id*='x']").each(function(){
		oas_element_id = $(this).attr('id');

		// check to see if the ids have the format   x-number-number   or    x-number-number-number
		if(/^x\d{2,3}$/.test(oas_element_id)){

			// add the "x" element to an array
			oas_elements.push(oas_element_id);
		}
	});

	// query is created for all elements
	//
	// the random method adds a random number to prevent caching
	// the join method contructs a string from the array of "x" elements
	oas_query = "http://ls.webmd.com/2/webmd/" + oas_section + "/" + ((Math.floor(Math.random() * 1000000000)) + 1000000000) + "@Position1," + oas_elements.join(',') + ",Position2?_RM_NO_COMMENT_";

	// if preview or staging add "env=1"
	if(/preview\.webmd/i.test(url) || /staging\.webmd/i.test(url)){
		oas_query += "&env=1";
	}

	// in case it doesn't load, it will appear anyway after 2 seconds (2000 milliseconds)
	webmd.p.fe_content_update.oas_timeout = setTimeout(function(){
		// go through all ids and if they have "x", make them visible
		$("[id*='x']").css('visibility','visible');
		webmd.p.fe_content_update = function(data){
			return false;
		}
	}, 2000);

	// use the query string to call the OAS JSON response
	// the response calls the function:   webmd.p.fe_content_update
	// this is listed above
	webmd.load({ js: oas_query });
});
