/* 
========================================================================================================= 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 isUserLoggedIn = "unknown";

// 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:deserve"; }
	// 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();

function getLoggedInStatus(pBool) {
	if (pBool == "True") {
		isUserLoggedIn = "loggedIn";
	}
	else {
		isUserLoggedIn = "unknown";	
	}
}

function trackCouponDownload() {
	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,eVar39,eVar40,prop28";      //Defining the list of variables that will be sent in the server call	
	s.events="event20";
    s.linkTrackEvents = "event20";	
	s.eVar40 ="Sharethebliss:couponclick"
	s.prop28 = isUserLoggedIn;
	s.eVar39 = isUserLoggedIn;	
    
	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
    }	
}

// 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("loadViewStory");

/* ====================================================================================================== DROPDOWN JUMP MENU */
function jumpMenu(targ,selObj,restore){
    eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
    if (restore) selObj.selectedIndex=0;
}

var divDebug;
function debug(inVal) {
	if (!divDebug) {
		divDebug = document.createElement('div');
		document.body.appendChild(divDebug);
		
		divDebug.style.border = '1px dashed red';
		divDebug.style.backgroundColor = '#ffc';
		divDebug.style.margin = '5px;'
		divDebug.style.padding = '25px;'
		divDebug.style.position = 'absolute';
		divDebug.style.right = '5px';
		divDebug.style.top = '5px';
	}
	
	var newMsg = document.createElement('div');
	newMsg.innerHTML = inVal;
	divDebug.appendChild(newMsg);
}

function loadViewStory() {
	var arrLinks = document.getElementsByTagName('a');
	var lnkViewStory;
	var storyID;
	for (var i = 0; i < arrLinks.length; i++) {
		if (arrLinks[i].id) {
			lnkViewStory = arrLinks[i];
			if (lnkViewStory.id.substr(lnkViewStory.id.length-13) == '_lnkViewStory') {				
				lnkViewStory.onclick = function() {
					var visible;
					var pShort;
					var pLong;
					storyID = this.id.substr(0,this.id.length-13);
					pShort = document.getElementById(storyID + '_pTextShort');
					pLong = document.getElementById(storyID + '_pTextLong');
					
					visible = pShort.style.display;
					pShort.style.display = (visible == '') ? 'none' : '';
					pLong.style.display = visible;
					
					var imgName = (visible == '') ? 'close-story.gif' : 'view-story.gif';
					this.style.background = 'url(/bliss/share/lib/img/buttons/' + imgName + ')';
					
					var txtLink = (visible == '') ? 'Close story' : 'View story';
					this.innerHTML = txtLink;
					
					var intWidth = (visible == '') ? '40px' : '70px';
					this.style.width = intWidth;
										
					return false;
				};
					
				//ctl00_mpContent_entriesDL_ctl02_pTextLong
				//ctl00_mpContent_entriesDL_ctl02_lnkViewStory
			}
		}
	}
}

/* ====================================================================================================== LOAD FLASH FILES */
function loadFlash() {
	// HERSHEY BLISS DESERVE HOME PAGE
	if (document.getElementById('flash-home') != null) {
        var flashvars = {userLoggedInStatus: isUserLoggedIn, curr_pgName: curr_pgName};
        var params = { wmode: "transparent", base: "." };
        var attributes = {};

		swfobject.embedSWF("/bliss/share/lib/swf/sharethebliss.swf", "flash-home", "952", "484", "9.0.0", "/bliss/share/lib/swf/expressInstall.swf", flashvars, params, attributes);
		if (document.getElementById('flash-home-alt') != null) {
			document.getElementById('flash-home-alt').style.visibility = "visible";
		}
	}
	// HERSHEY BLISS DESERVE QUIZ
	if (document.getElementById('flash-logo') != null) {
        var flashvars = {};
        var params = { wmode: "transparent" };
        var attributes = {};

		swfobject.embedSWF("/bliss/share/lib/swf/logo.swf", "flash-logo", "322", "127", "9.0.0", "/bliss/share/lib/swf/expressInstall.swf", flashvars, params, attributes);
		if (document.getElementById('flash-logo-alt') != null) {
			document.getElementById('flash-logo-alt').style.visibility = "visible";
		}
	}
	// HERSHEY BRAND FOOTER
	if (document.getElementById('brand-footer') != null) {
        var flashvars = { bgColor: "0xffffff", xmlPath: "/general/xml/brandbar.xml", logoPath: "/general/swf/logos/", curr_pgName: curr_pgName, inputDevAccount: "hersheyintshareblissdev,hersheyglobaldev", inputLiveAccount: "hersheyintsharethebliss,hersheyglobal" };
        var params = { wmode: "transparent" };
        var attributes = {};

		swfobject.embedSWF("/general/swf/brandbar.swf", "brand-footer", "920", "75", "9.0.0", "/bliss/devotion/lib/swf/expressInstall.swf", flashvars, params, attributes);
		if (document.getElementById('brand-footer-alt') != null) {
			document.getElementById('brand-footer-alt').style.visibility = "visible";
		}
	}
}

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 b y 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
    }
	
}

function querySt(pQuery) {
	queryParams = window.location.search.substring(1);
	individQueryParams = queryParams.split("&");
	for (i=0;i<individQueryParams.length;i++) {
		finalParam = individQueryParams[i].split("=");
		if (finalParam[0] == pQuery) {
			return finalParam[1];
		}
	}
}

$(document).ready(function(){

	// word count 
	if ( $('textarea.story').html() != null ) {
		$('textarea.story').wordCount();
		$('textarea.story').wordCount({ counterElement:"count" });
		$('div#error a').click( function() {
			$('textarea.story').removeAttr('disabled');
			$('div#error').css('display','none');
		});
		$('textarea.story').change( function() {
			if ( $('#count').text() >= 150 ) {
				$('#count').parent().addClass('error');
				$('textarea.story').attr('disabled', 'disabled');
				$('div#error').css('display','block');
			}
			else {
				$('#count').parent().removeClass('error');
				$('div#error').css('display','none');
			}
		});
	}
		
	// 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';
	
	// send to correct url
	function assignURLstrings(service) {
		
		P_TITLE = $('title').text();
		P_TITLE = escape(P_TITLE);
		P_URL = escape(P_URL);
			
		if (service == '#delicious') { window.location = 'http://del.icio.us/post?url=' + P_URL + '&amp;title=' + P_TITLE; }
		else if (service == '#digg') { window.location = 'http://digg.com/submit?phase=2&amp;url=' + P_URL + '&amp;title=' + P_TITLE; }
		else if (service == '#facebook') { window.location = 'http://www.facebook.com/share.php?u=http://www.hersheys.com/bliss/facebook/share_the_bliss.html&amp;t=' + P_TITLE; }
		else if (service == '#mixx') { window.location = 'http://www.mixx.com/submit?page_url=' + P_URL + '&amp;title=' + P_TITLE; }
		else if (service == '#myspace') { window.location = 'http://www.myspace.com/Modules/PostTo/Pages/?u=' + P_URL + '&amp;t=' + P_TITLE; }
		else if (service == '#reddit') { window.location = 'http://reddit.com/submit?url=' + P_URL + '&amp;title=' + P_TITLE; }
		else if (service == '#stumbleupon') { window.location = 'http://www.stumbleupon.com/submit?url=' + P_URL + '&amp;title=' + P_TITLE; }
		else if (service == '#twitter') { window.location = 'http://www.twitter.com/home?status=' + P_URL; }		
	}
	
	$('#ss').cycle({
		fx:     'turnUp', 
		speed:  'slow',
		delay:	-500,
		timeout: 0, 
		next:  '.ss-next',
		prev:  '.ss-prev' 
	});
	
	$("li.read-more").toggle(
      function () {
        $(this).parent().parent().parent().addClass('more');
      },
      function () {
        $(this).parent().parent().parent().removeClass('more');
      }
    );
	$("li.ss-next, li.ss-prev").click( function () {
        $(this).parent().parent().parent().removeClass('more');
      }
    );
	
});