/* 
========================================================================================================= CREDITS
Copyright 	: Copyright (c) 2009 JPL & The Hershey Company, Inc. All Rights Reserved.
Author(s) 	: Larry Daughenbaugh - ldaugh@jplcreative.com
Date      	: 4/20/2009
Notes     	: JavaScript file for handling various events ... onLoad, onClick, etc
========================================================================================================= CHANGE LOG
Date		Name			Desc
---			---				---
========================================================================================================= BEGIN JAVASCRIPT
*/
/* ====================================================================================================== MULTIPLE ONLOAD HANDLER */
var onLoadFunctions = new Array();
var iloadFunction = 0;
var memoStatus = true;

// Build page name for Omniture reporting.
// Page name built by buildPgName() function.
var curr_pgName = null; 

function buildPgName() {
	var curr_url = window.location.href.split("//");
	var path_array = curr_url[1].split("/");
	// create page name object
	build_pgName = new Object;
	build_pgName.domain = path_array[0];
	build_pgName.dir = '';
	// assign domain
	if ( build_pgName.domain.match(/hersheys/) ) { build_pgName.domain = "Hersheys"; }
	// build directory structure, append file name
	for ( i = 1; i <= path_array.length-1; i++ ) {
		if( path_array[i].indexOf("?") == -1) {
			build_pgName.dir = build_pgName.dir + ":" + path_array[i];
		}
		else {
			var tempSplit = path_array[i].split("?");
			build_pgName.dir = build_pgName.dir + ":" + tempSplit[0];
		}
	}
	// cut file extensions
	build_pgName.dir = build_pgName.dir.split(".");
	build_pgName.dir = build_pgName.dir[0]
	// if there is reference to "index" or "default", replace with "home"
	if ( build_pgName.dir.match(/index/) ) { build_pgName.dir = build_pgName.dir.replace(/index/, "home") }
	if ( build_pgName.dir.match(/default/) ) { build_pgName.dir = build_pgName.dir.replace(/default/, "home") }
	// if the last character is ":", replace with "home"
	if ( build_pgName.dir.charAt(build_pgName.dir.length-1) == ":" ) { build_pgName.dir = build_pgName.dir + "home" }
	// build page name structure
	curr_pgName = build_pgName.domain + build_pgName.dir;
}

buildPgName();

// 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 EACH FUNCTION TO LOAD */
addOnLoad("loadFlash");
addOnLoad("checkSubnavs");
addOnLoad("setupFlashListeners");
addOnLoad("init_modal");

/* ====================================================================================================== LOAD FLASH FILES */
function loadFlash() {
	// HERSHEY HEROES HOME PAGE
	if (document.getElementById('flash-home') != null) {

        var flashvars = { curr_pgName: curr_pgName, pickupID: swfobject.getQueryParamValue("pickupID"), bgColor: "0x970404" };
        var params = { wmode: "transparent", base: "." };
        var attributes = {};

		swfobject.embedSWF("lib/swf/Preloader.swf", "flash-home", "100%", "600", "9.0.0", "lib/swf/expressInstall.swf", flashvars, params, attributes);
		if (document.getElementById('flash-home-alt') != null) {
			document.getElementById('flash-home-alt').style.visibility = "visible";
		}
	}
	// HERSHEY BRAND FOOTER
	if (document.getElementById('brand-footer') != null) {
        var flashvars = { bgColor: "0x7b0202", xmlPath: "/general/xml/brandbar.xml", logoPath: "/general/swf/logos/", curr_pgName: curr_pgName, inputDevAccount: "hersheyintironmancanadadev,hersheyglobaldev", inputLiveAccount: "hersheyintironmancanada,hersheyglobal" };
        var params = { wmode: "transparent" };
        var attributes = {};

		swfobject.embedSWF("/general/swf/brandbar.swf", "brand-footer", "920", "75", "9.0.0", "/kisses/heroesathome/lib/swf/expressInstall.swf", flashvars, params, attributes);
		if (document.getElementById('brand-footer-alt') != null) {
			document.getElementById('brand-footer-alt').style.visibility = "visible";
		}
	}
}

/* ==================================================================================== CHECK THE ELEMENTS TO HIDE IF ON THE COMING SOON PAGE */
function checkSubnavs() {
	// HERSHEY HEROES SUBNAVS
	if (document.getElementById('comingsoon') != null) {
		document.getElementById('nav').innerHTML = "&nbsp;";
		document.getElementById('footernav').innerHTML = "&nbsp;";
	}
}

/* ==================================================================================== SETUP LISTENERS FOR THE HTML NAVIGATION TO SPEAK TO FLASH */
function setupFlashListeners() {
	var arrLinks = document.getElementsByTagName("a");
	for (var i = 0; i < arrLinks.length; i++) { 
		if (arrLinks[i].getAttribute("rel") == "flashcall") {
			arrLinks[i].onclick = passToFlash;
		}
		else {
			if (arrLinks[i].getAttribute("rel") == "newwin") {
				arrLinks[i].onclick = openinnewwindow;
			}
		}
	}		
}

/* ============================================================================================================================= OPEN NEW WINDOW FROM HREF */
function openinnewwindow() {
	var test = window.open(this.href, "blank");
	return false;
}

/* ============================================================================================================================= DETERMINE THE FLASH MOVIE */

function thisMovie(movieName) {
	if (window.document[movieName]) return window.document[movieName];
	if (navigator.appName.indexOf("Microsoft Internet") == -1) {
		if (document.embeds && document.embeds[movieName]) return document.embeds[movieName]; 
	} else {
		return document.getElementById(movieName);
	} 
}

/* ====================================================================================================== PASS DATA TO FLASH */
function passToFlash() {
	pFunc = this.href.split("#")[1];
	if (document.getElementById('flash-home-alt') == null) {
		switch(pFunc) {
			case "post":
				if (document.getElementById('flash-home') != null) thisMovie("flash-home").callFromJS("postMessage");
				trackOmniClick("HAH1002");
				break;
			case "view":
				if (document.getElementById('flash-home') != null) thisMovie("flash-home").callFromJS("viewMessage");
				trackOmniClick("HAH1003");				
				break;
			default:
				break;
		}
	}
	// return false here to prevent the page from changing
	return false;
}

/* ====================================================================================================== GET DATA FROM FLASH */
function receiveFromFlash(pFunc) {
	// Do something
	switch(pFunc) {
		case "about":
			// open the about modal from Flash
			open_modal('#modal0', '');
			break;
		case "terms":
			// open the terms modal from Flash
			open_modal('#modal1', '');
			break;			
		case "kmart":
			theURL = "redirect.aspx?code=KMT";
			features = "status=0,scrollbars=0,resizable=0,width=1000,height=750,top=0,left=0";
			window.open(theURL,"redirector",features);
			break;
		case "kmartEmail":
			theURL = "redirect.aspx?code=KMTEM";
			features = "status=0,scrollbars=0,resizable=0,width=1000,height=750,top=0,left=0";
			window.open(theURL,"redirector",features);
			break;
		case "kisses":
			theURL = "http://www.hersheys.com/kisses/baking/";
			features = "status=0,scrollbars=0,resizable=0,width=1000,height=750,top=0,left=0";
			window.open(theURL,"redirector",features);	
			break;			
		case "hersheys":
			theURL = "http://www.hersheys.com";
			features = "status=0,scrollbars=0,resizable=0,width=1000,height=750,top=0,left=0";
			window.open(theURL,"redirector",features)	
			break;
		case "postinflash":
			trackOmniClick("HAH1004");
			break;
		case "viewinflash":
			trackOmniClick("HAH1005");
			break;
		default:
			break;
	}	
}

/* ======================================================================================================= SETUP THE SHARE LINK HANDLERS */
$(document).ready(function(){

	// share it functionality
	$('a#btn').click( function () {
		if ($.browser.msie && $.browser.version=="6.0") { $('ul#list').css('display','block'); }
		else { $('ul#list').fadeIn('slow'); }		
	});
	$("ul#list").hover(
		function () { },
		function () {
			if ($.browser.msie && $.browser.version=="6.0") { $(this).css('display','none'); }
			else { $('ul#list').fadeOut('slow'); }	
		}
    );
	$('li.mix a, li.dig a, li.fac a, li.del a, li.red a, li.stu a, li.mys a, li.twi a').click( function () {
		var service = $(this).attr('href');
		assignURLstrings(service)
	});
	
	// url string variables
	var P_URL = jQuery(document.location).attr('href');
	var P_TITLE = 'default';
	var p_OPENURL;
	
	// send to correct url
	function assignURLstrings(service) {
		
		P_TITLE = $('title').text();
		P_TITLE = encodeURIComponent(P_TITLE);
		P_URL = encodeURIComponent(P_URL);
			
		if (service == '#delicious') { P_OPENURL = 'http://del.icio.us/post?url=' + P_URL + '&amp;title=' + P_TITLE; }
		else if (service == '#digg') { P_OPENURL = 'http://digg.com/submit?phase=2&amp;url=' + P_URL + '&amp;title=' + P_TITLE; }
		else if (service == '#facebook') { P_OPENURL = 'http://www.facebook.com/sharer.php?u=' + P_URL + '&amp;t=' + P_TITLE; }
		else if (service == '#mixx') { P_OPENURL = 'http://www.mixx.com/submit?page_url=' + P_URL + '&amp;title=' + P_TITLE; }
		else if (service == '#myspace') { P_OPENURL = 'http://www.myspace.com/Modules/PostTo/Pages/?u=' + P_URL + '&amp;t=' + P_TITLE; }
		else if (service == '#reddit') { P_OPENURL = 'http://reddit.com/submit?url=' + P_URL + '&amp;title=' + P_TITLE; }
		else if (service == '#stumbleupon') { P_OPENURL = 'http://www.stumbleupon.com/submit?url=' + P_URL + '&amp;title=' + P_TITLE; }
		else if (service == '#twitter') { P_OPENURL = 'http://www.twitter.com/home?status=' + P_URL; }	

		features = "status=0,scrollbars=0,resizable=0,width=800,height=550,top=0,left=0";
		window.open(P_OPENURL,"shareitlink",features)
	}
	
});


function openShareLink(pSocialApp, pId) {
	var result = null;
	var urlToAdd = "http://www.hersheys.com/kisses/heroesathome/default.aspx?pickupID=" + pId;
	var urlPageTitle = "HERSHEY'S Heroes at Home";
	switch(pSocialApp) {
		case "mixx": result = 'http://www.mixx.com/submit?page_url=' + urlToAdd; break;
		case "digg": result = 'http://digg.com/submit/?url=' + urlToAdd; break;
		case "facebook": result = 'http://www.facebook.com/sharer.php?u=' + encodeURIComponent(urlToAdd) + '&t=' + encodeURIComponent(urlPageTitle); break;
		case "delicious": result = 'http://del.icio.us/post?url=' + encodeURIComponent(urlToAdd) + '&amp;title=' + encodeURIComponent(urlPageTitle); break;
		case "reddit": result = 'http://reddit.com/submit?url=' + encodeURIComponent(urlToAdd) + '&amp;title=' + encodeURIComponent(urlPageTitle); break;
		case "stumbleupon": result = 'http://www.stumbleupon.com/submit?url=' + encodeURIComponent(urlToAdd); break;
		case "myspace": result = 'http://www.myspace.com/Modules/PostTo/Pages/?u=' + encodeURIComponent(urlToAdd) + 't=' + encodeURIComponent(urlPageTitle); break;
		case "twitter": result = 'http://twitter.com/home?status=' + encodeURIComponent(urlPageTitle) + ' ' +  encodeURIComponent(urlToAdd); break;
		default: result = null;
	}
	if (result) {
		window.open (result,"socialWindow","location=0,status=0,scrollbars=0,width=650,height=550"); 	
	}
}

// Track internal campaign clicks
function trackOmniClick(pTrackCode) {
	clearAllOmnitureVars();
	var s = s_gi(s_account);
	if(s.pageName.indexOf("#modal1") != -1) {
		s.pageName = s.pageName.replace("#modal1", "home");
	}
    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.tl(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
    }
	clearAllOmnitureVars();
}

function clearAllOmnitureVars() {
	var tempVar;
	for (var i = 1; i < 51; i++) {
		tempVar = "eVar";
		tempVar = tempVar + i.toString();
		s[tempVar] = "";
	}
	for (i = 1; i < 51; i++) {
		tempVar = "prop";
		tempVar = tempVar + i.toString();
		s[tempVar] = "";
	}
	s.events = "";
	s.products = "";
	s.linkDownloadFileTypes = "";
	s.linkTrackVars = "";
	s.linkTrackEvents = "";
}
/*
function openRedirectWindow(pWin) {
	if(pWin == "sega") {
		theURL = "redirect.aspx?code=FP";
	}
	features = "status=0,scrollbars=0,resizable=0,width=920,height=650,top=0,left=0";
	window.open(theURL,"redirector",features);	
}*/
