/* 
================================================================================================================================ CREDITS
Copyright 	: Copyright (c) 2009 JPL & The Hershey Company. All Rights Reserved.
Author(s) 	: Larry Daughenbaugh - ldaugh@jplcreative.com
Date      	: 6/5/2009
Notes     	: JavaScript file for handling various events ... onLoad, onClick, etc
================================================================================================================================ CHANGE LOG
Date		Name			Desc
---			---				---
================================================================================================================================ BEGIN JAVASCRIPT
*/

/* ============================================================================================================================= GET X/Y COORDINATE FUNCTIONS */

function find_pos_x(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while(1) {
			curleft += obj.offsetLeft;
			if (!obj.offsetParent) break;
			obj = obj.offsetParent;
		}
	} else if (obj.x) {
		curleft += obj.x;
	}
	return curleft;
}
function find_pos_y(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while(1) {
			curtop += obj.offsetTop;
			if(!obj.offsetParent) break;
			obj = obj.offsetParent;
		}
	} else if (obj.y) {
		curtop += obj.y;
	}
	return curtop;
}

/* ============================================================================================================================= GET WIDTH/HEIGHT OF BROWSER WINDOW */

function getWinX() {
    var myWidth = -1;
    if (typeof(window.innerWidth) == 'number') {
	    myWidth = window.innerWidth; // non-ie
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
	    myWidth = document.documentElement.clientWidth; // ie 6+ standards mode
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
	    myWidth = document.body.clientWidth; // ie4 compatible
    }
    return myWidth;
}

function getWinY() {
    var myHeight = -1;
    if (typeof(window.innerHeight) == 'number') {
	    myHeight = window.innerHeight; // non-ie
    } else if (document.documentElement && (document.documentElement.clientHeight || document.documentElement.clientWidth)) {
	    myHeight = document.documentElement.clientHeight; // ie 6+ standards mode
    } else if (document.body && (document.body.clientHeight || document.body.clientWidth)) {
	    myHeight = document.body.clientHeight; // ie4 compatible
    }
    return myHeight;
}

/* ============================================================================================================================= BASIC AJAX FUNCTIONS */

var on_home_page = true;

function ajax_request(content_url, container_id, subnav_id) {
	var page_request = false;
	
	// SET page_request BASED UPON WHICH BROWSER WE ARE IN (FIREFOX/MOZILLA/ETC OR MICROSOFT 
	if (window.XMLHttpRequest) {
		page_request = new XMLHttpRequest()
	} else if (window.ActiveXObject) { // if IE
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) {
			try {
				page_request = new ActiveXObject("Microsoft.XMLHTTP");
			}
		catch (e) {}
		}
	} else {
		return false;
	}

	// ---------------------------------------------------------------------------------------------------------------
	// RESET ALL SUB-NAV ACTIVE STYLES, THEN SET ACTIVE STYLE IF ONE IS CLICKED
	if (document.getElementById("sub_link" + i) != "") {
		if (subnav_id.indexOf("nutrition") == 0 || subnav_id == "no_reset") {
			// IF 'nutrition' IS THE ID THEN DON'T RESET THE ACTIVE SUB_LINK
		} else {
			var i = 0;
			while(document.getElementById("sub_link" + i)) {
				document.getElementById("sub_link" + i).className = "";
				i++;
			}
		}
	}
	// ---------------------------------------------------------------------------------------------------------------

	if (subnav_id.indexOf("product_landing") > -1) {
		var landingLink = subnav_id.replace("product_landing","").toString();
		
		// Relate landing links (image and text links) to array of "sub_link" variables so that we can update sub-nav
		var arr_sub_links = new Array("sub_link0","sub_link0","sub_link1","sub_link1","sub_link2","sub_link2",
									  "sub_link3","sub_link3","sub_link4","sub_link4","sub_link5","sub_link5");
		
		document.getElementById(arr_sub_links[landingLink]).className = "active";
	} else if (subnav_id.indexOf("home_callout") > -1) {
		document.getElementById("sub-nav").style.display = "block";
		setup_products_subnav("sub_link");
		// SET ACTIVE CLASS FOR APPROPRIATE LINK BASED UPON THE GRAPHIC CALLOUT ON THE HOME PAGE
		document.getElementById("sub_link3").className = "active";
	}

	if (subnav_id.indexOf("sub_link") > -1) document.getElementById(subnav_id).className = "active";
	// ---------------------------------------------------------------------------------------------------------------
	
	// SET UP LISTENER FOR READY STATE CHANGE 
	page_request.onreadystatechange = function() { load_content(page_request, container_id, content_url); }
	
	if (content_url.indexOf("?") > -1) {
		content_url = content_url + "&request=ajax";
	} else {
		content_url = content_url + "?request=ajax";
	}
	page_request.open('GET', content_url, true)
	page_request.send(null)
}

// ATTACH PRODUCT SUB-NAV EVENT LISTENERS (ONCE THEY ARE AVAILABLE ON THE PAGE)
function setup_products_subnav(obj_name) {
	var i = 0;

	if (document.getElementById(obj_name + i) != null) {
		while(document.getElementById(obj_name + i)) {
			var temp = document.getElementById(obj_name + i);
			temp.onclick = function() {
				if (obj_name == "nutrition_back") {
					function nextObject(n) {
						do n = n.nextSibling;
						while (n && n.nodeType != 1);
						return n;
					}

                    var back_link = document.getElementById("back_button");
			        var div_content = nextObject(back_link);
				    ajax_request(div_content.innerHTML, 'main-content', this.id);
				} else if (obj_name.indexOf("bar_bag") > -1) {
					ajax_request(this.href, 'main-content', "no_reset");
				} else {
				    ajax_request(this.href, 'main-content', this.id);
				}
				return false;
			}
			i++;
		}
	}
}

// SET UP FOOD/DRINK EVENT LISTENERS (ONCE THEY ARE AVAILABLE ON THE PAGE)
function setup_food_drink_pairings() {
	var food = document.getElementById("food");
	var drink = document.getElementById("drink");

	if (food != null) {
		food.onclick = function() {
			ajax_request(this.href, 'main-content', 'no_reset');
			return false;
		}
	}
	if (drink != null) {
		drink.onclick = function() {
			ajax_request(this.href, 'main-content', 'no_reset');
			return false;
		}
	}
}

function load_content(page_request, container_id, content_url) {
	if (page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf("http") == -1)) {
				
		if (document.getElementById("logo") != null) {
			if (document.getElementById("logo").style.display == "none") document.getElementById("logo").style.display = "block";
		}

		// DISPLAY CONTENT NOW THAT IT IS LOADED
		//document.getElementById(container_id).innerHTML = page_request.responseText;
		$('#' + container_id).html(page_request.responseText);
		
        	window.scroll(0,0); // reset scroll position to the top of the page

		setup_products_subnav("product_landing");
		setup_products_subnav("nutrition");
		setup_products_subnav("nutrition_back");
		setup_products_subnav("bar_bag");
		setup_food_drink_pairings();
		move_above_fold();
		
		// HIDE LOGO IF ON A NUTRITION PAGE
		if (content_url.indexOf("/nutrition-information.aspx") > -1) {
			if (document.getElementById("logo") != null) document.getElementById("logo").style.display = "none";
			
			//Track
			trackOmniNutrition(content_url);
			
			// SET BAR OR BAG CLASS FOR APPROPRIATE NUTRITION PAGES 
			if (content_url.indexOf("type=bar") > -1) {
				document.getElementById("bar_bag0").className = "active";
				document.getElementById("bar_bag1").className = "";
				
			} else if (content_url.indexOf("type=bag") > -1) {
				document.getElementById("bar_bag0").className = "";
				document.getElementById("bar_bag1").className = "active";
			}
		}
		// SET UP RETURN LINKS FROM FOOD/DRINK PAIRING PAGES
		if (content_url.indexOf("-pairing.aspx") > -1) {
			var flavor_return = document.getElementById("flavor_return");
			if (flavor_return != null) {
				flavor_return.onclick = function() {
					ajax_request(this.href, 'main-content', 'no_reset');
					return false;
				}
			}
		}

		// SET UP HOME CALLOUT ACTION
		var home_callout = document.getElementById("home_callout");
		if (home_callout != null) home_callout.onclick = function() {
		    trackOmniClick('BLS1007');
			ajax_request(this.href, 'main-content', 'home_callout');
			return false;
		}

	 } else {
		// DISPLAY LOADING CONTENT WHILE CONTENT LOADS (WANTED IT TO BE NOTHING)
		document.getElementById(container_id).innerHTML = '<p class="loading">Loading content, please wait. <br /><img src="/bliss/lib/img/loading.gif" alt="Loading" /></p>';
	}
}

/* ============================================================================================================================= MULTIPLE ONLOAD HANDLER */

var onLoadFunctions = new Array();
var iloadFunction = 0;

// Pass each function that needs to load
function addOnLoad(func) {
    onLoadFunctions[iloadFunction] = func;
    iloadFunction++;
}
// Loops through all of the functions that were added
function loadAllFunctions() {
    for(i=0; i < onLoadFunctions.length; i++) {
        eval(onLoadFunctions[i]+"()");
    }
}
// Load all of the functions that you've set
window.onload = loadAllFunctions;

/* ============================================================================================================================= CALL FUNCTIONS TO BE LOADED */

addOnLoad("position_content");
addOnLoad("load_flash");
addOnLoad("setup_ajax_calls");
addOnLoad("share_it_link");
addOnLoad("move_above_fold");

/* ============================================================================================================================= LOAD FLASH FILES */

function load_flash() {
	if (document.getElementById('flash-video') != null) {
        var flashvars = {};
        var params = { wmode: "transparent", base: "." };
        var attributes = {};

		swfobject.embedSWF(
			"/bliss/lib/swf/preloader.swf", "flash-video", "836", "768", "9.0.0", "/bliss/lib/swf/expressInstall.swf", 
			flashvars, params, attributes
		);
	}
}

/* ============================================================================================================================= SET UP LISTENERS FOR AJAX CALLS */

function setup_ajax_calls() {
	// LINKS THAT ARE TO BE USED FOR AJAX CALLS
	var nav_home = document.getElementById("home");
	var nav_home_footer = document.getElementById("home_footer");
	var nav_story = document.getElementById("story");
	var nav_story_footer = document.getElementById("story_footer");
	var nav_products = document.getElementById("products");
	var nav_products_footer = document.getElementById("products_footer");
	var nav_home_logo = document.getElementById("home_logo");
	var home_callout = document.getElementById("home_callout");

	// ARRAY OF AJAX CALLS
	var arr_nav_links = new Array(nav_home,nav_story,nav_products,nav_home_footer,nav_story_footer,nav_products_footer,nav_home_logo,home_callout);

	// ATTACH EVENT LISTENERS TO AJAX CALL ITEMS
	var i = 0;
	while(i < arr_nav_links.length) {
		var temp = arr_nav_links[i];

		if (temp != null) {
		    temp.onclick = function() {
			    // SHOW PRODUCTS SUB-NAV IF THAT ITEM IS CLICKED
			    if (this.id == "products" || this.id == "products_footer" || this.id == "home_callout" || this.id.indexOf("sub_link") > -1 || this.id.indexOf("product_landing") > -1 || this.id.indexOf("nutrition") > -1) { 
					document.getElementById("sub-nav").style.display = "block";
				    setup_products_subnav("sub_link");
			    } else {
				    document.getElementById("sub-nav").style.display = "none";
			    }
    			
				if (this.id == "home_callout") {
					trackOmniClick('BLS1007');
					ajax_request(this.href, 'main-content', 'home_callout');
				} else {
					switch (this.id){
						case "home":
							trackOmniClick('BLS1000');
						break;
						case "story":
							trackOmniClick('BLS1001');
						break;
						case "products":
							trackOmniClick('BLS1002');
						break;
						case "home_footer":
							trackOmniClick('BLS1008');
						break;
						case "story_footer":
							trackOmniClick('BLS1009');
						break;
						case "products_footer":
							trackOmniClick('BLS1010');
						break;
					}
					
					ajax_request(this.href, 'main-content', '');
				}
			    return false;
		    }
		}
		i++;
	}

	setup_products_subnav("product_landing");
	setup_products_subnav("nutrition");
	setup_products_subnav("nutrition_back");
	setup_products_subnav("bar_bag");
	setup_products_subnav("sub_link");
	setup_food_drink_pairings();
	
	var content_url = window.location.toString();
	if (content_url.indexOf("/nutrition-information.aspx") > -1) {
		if (document.getElementById("logo") != null) document.getElementById("logo").style.display = "none";
	}
}

/* ============================================================================================================================= SHARE IT LINK */

function share_it_link() {
	var share_it = document.getElementById("share_it");
	var share_it_container = document.getElementById("share-it-container");

	function open_share_it_div(share_it_container, share_it_button) {
		var share_it_x = find_pos_x(share_it_button);
		var share_it_y = find_pos_y(share_it_button);

		if (share_it_container.style.visibility == "hidden") {
			share_it_container.style.visibility = "visible";
			share_it_container.style.top = (share_it_y - 180) + "px";
			share_it_container.style.left = (share_it_x + 3) + "px";
			share_it.className = "active";
		} else {
			share_it_container.style.visibility = "hidden";
			share_it.className = "";
		}
		// Record Omni click
		trackShareClick();
	}
	
	function hide_share_it_div(e) {
		if (!e) var e = window.event;
		
		var tg = (window.event) ? e.srcElement : e.target;
		if (tg.nodeName != 'UL') return;
		var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
		while (reltg != tg && reltg.nodeName != 'BODY') {
			reltg = reltg.parentNode;
		}
		if (reltg == tg) return; 
	
		// Mouseout took place when mouse actually left layer, Handle event
		document.getElementById("share-it-container").style.visibility = "hidden";
		document.getElementById("share_it").className = "";
	}

	if (share_it != null) {
		share_it.onclick = function() {
			open_share_it_div(share_it_container, this);
			return false;
		}
	}
	if (share_it_container != null) share_it_container.onmouseout = function(e) { hide_share_it_div(e); }
}

/* ============================================================================================================================= SHARE IT LINK */

function move_above_fold() {
	var page_height = getWinY();
	var callout_image_y = 0;
	var callout_image = document.getElementById("callout_image");
	var callout_image_padding = 155; // DEFAULT PADDING BEFORE ANY "ABOVE FOLD" MOVEMENT
	var nav_height = 535; // DEFAULT HEIGHT BEFORE ANY "ABOVE FOLD" MOVEMENT

	if (callout_image != null) {
		callout_image_y = find_pos_y(callout_image);
		if (callout_image_y > 0) {
			var callout_image_height = 185; // HEIGHT OF CALLOUT IMAGE
			callout_image_y = callout_image_y + callout_image_height;
					
			if (callout_image_y > page_height) {
				var adjustment = callout_image_y - page_height;
				
				// KEEP MAXIMUM ADJUST TO 135, OTHERWISE THINGS WOULD START OVERLAPPING
				if (adjustment > 135) adjustment = 135;
					
				callout_image_padding = callout_image_padding - adjustment;
				nav_height = nav_height - adjustment;
	
				document.getElementById("home-callout").style.paddingTop = callout_image_padding + "px";
				document.getElementById("nav").style.height = nav_height + "px";
			}
		}
	}
}


/* ============================================================================================================================= Interal Omniture calls */
function trackOmniClick(pTrackCode) {
	var s = s_gi(s_account);
    s.templtv = s.linkTrackVars;          //Saving the original state of the variables
    s.templte = s.linkTrackEvents;         //Saving the original state of the variables
    s.linkTrackVars = "events,eVar2";      //Defining the list of variables that will be sent in the server call
	s.eVar2 = pTrackCode + ":" + s.pageName // Tracking code will be provided by Kendra
    s.linkTrackEvents = "event9";
    s.events = "event9";              //Passing in the value into s.events
    s.prop5=s.eVar7=document.location.hostname;
	s.tl(true,'o','internal campaign clicks');   //Server call
    
	if(s.templtv) {
		s.linkTrackVars=s.templtv;    //reassigning the variables to the original state
	}
	
	if(s.templte) {
		s.linkTrackEvents=s.templte;   //reassigning the variables to the original state
    }
}

function trackHeroClick(pTrackCode) {
	var s = s_gi(s_account);
	s.templtv = s.linkTrackVars;          	//Saving the original state of the variables
	s.templte = s.linkTrackEvents;         	//Saving the original state of the variables
	s.linkTrackVars = "events,eVar2";      	//Defining the list of variables that will be sent in the server call
	s.eVar2 = "BLS1007:hersheys:bliss:home"	// Tracking code will be provided by Kendra
	s.linkTrackEvents = "event9";
	s.events = "event9";              		//Passing in the value into s.events
	s.prop5=s.eVar7=document.location.hostname;
	s.tl(true,'o','internal campaign clicks');   //Server call
    
	if(s.templtv) {
		s.linkTrackVars=s.templtv;    	//reassigning the variables to the original state
	}
	
	if(s.templte) {
		s.linkTrackEvents=s.templte;   	//reassigning the variables to the original state
    }
}

function trackShareClick(pTrackCode) {
	// We only have to fire this event on the homepage
	if ($('#home-callout').length){
		var s = s_gi(s_account);
		s.templtv = s.linkTrackVars;          	//Saving the original state of the variables
		s.templte = s.linkTrackEvents;         	//Saving the original state of the variables
		s.linkTrackVars = "events,eVar2";      	//Defining the list of variables that will be sent in the server call
		s.eVar2 = "BLS1006:hersheys:bliss:home"	// Tracking code will be provided by Kendra
		s.linkTrackEvents = "event9";
		s.events = "event9";              		//Passing in the value into s.events
		s.prop5=s.eVar7=document.location.hostname;
		
		s.tl(true,'o','internal campaign clicks');   //Server call
	    
		if(s.templtv) {
			s.linkTrackVars=s.templtv;    	//reassigning the variables to the original state
		}
		
		if(s.templte) {
			s.linkTrackEvents=s.templte;   	//reassigning the variables to the original state
	    }
	    console.log('woot!');
	}
}

function trackOmniNutrition(phref) {
	
	var s = s_gi(s_account);
	
	s.events = "event8,event11";              //Passing in the value into s.events
	
	var productname
	
	if (phref.indexOf("cid=mc") > -1) {
		productname = "HERSHEYS BLISS Milk Chocolate"
	}else if(phref.indexOf("cid=dc") > -1) {
		productname = "HERSHEYS BLISS Dark Chocolate"
	}else if(phref.indexOf("cid=rm") > -1){
		productname = "HERSHEYS BLISS Raspberry Meltaway"
	}else if(phref.indexOf("cid=wcm") > -1){
		productname = "HERSHEYS BLISS White Chocolate Meltaway"
	}else if(phref.indexOf("cid=mcm") > -1){
		productname = "HERSHEYS BLISS Milk Chocolate Meltaway"
	}else if(phref.indexOf("cid=mm") > -1){
		productname = "HERSHEYS BLISS Creme de Menthe Meltaway"
	}
	
	
	s.products=";"+ productname
	
	s.pageName = "hersheys:bliss:nutrition view";
	s.channel="hersheys:bliss:products"
	s.prop1=s.prop2=s.prop3=s.prop4=s.channel
	
	s.prop5=s.eVar7=document.location.hostname;
	s.prop6=s.eVar8="Bliss"
	
	
	s.t();
	
	/*var s = s_gi(s_account);
    s.templtv = s.linkTrackVars;          //Saving the original state of the variables
    s.templte = s.linkTrackEvents;         //Saving the original state of the variables
    s.linkTrackVars = "events,eVar2";      //Defining the list of variables that will be sent in the server call
	s.eVar2 = pTrackCode + ":" + s.pageName // Tracking code will be provided by Kendra
    s.linkTrackEvents = "event9";
    s.events = "event9";              //Passing in the value into s.events
    
	s.t(true,'o','internal campaign clicks');   //Sever call
    
	if(s.templtv) {
		s.linkTrackVars=s.templtv;    //reassigning the variables to the original state
	}
	
	if(s.templte) {
		s.linkTrackEvents=s.templte;   //reassigning the variables to the original state
    }*/
}



/* ============================================================================================================================= POSITION CONTENT */

function position_content() {	
    var container = document.getElementById("container");    
    var flash = document.getElementById("video-container");    
    if (container != null) {
		var winX = getWinX();
	    container.style.left = Math.round((winX-960)/2) + "px";
	    flash.style.left = Math.round(((winX-960)/2+122)) + "px";
	}

	// HIDE SHARE IT DIV IF IT EXISTS
	var share_it_container = document.getElementById("share-it-container");

	if (share_it_container != null) share_it_container.style.visibility = "hidden";
}
window.onresize = position_content;