/*
*	Omobono / Accenture MOSS Microsites javascript functions library, December 2008
*	Author: james.ford@accenture.com
*	Contributers: paul.walker@accenture.com
*
*	Version 1.3
*
*	Dependencies: swfobject 2.1 (http://code.google.com/p/swfobject/)
*
*	Contents:
*		
*		omo_loadSWF(targetElementId, swfPath, width, height, [flashVersion, default:"8.0.0"], [windowMode, default:"opaque"]);
*		
*		createCookie(name, value, [lifetime(days), default:1]);
*		
*		readCookie(name);
*		
*		deleteCookie(name);
*
*		omo_loadContent(srcFilePath, targetElementId);
*
*		attachShareIt();
*
*		createDropDownNavigation(targetElement, optionsArray, [width]);
*
*		createDropDownNavigationFromSection(targetElement, [width]);
*
*		omo_applyImageRollOver(_linkId, _rolloverImagePath, [_hrefReplacement]);
*
*		omo_LoadFlashVideoPlayerToDiv(divID, width, height, flv_path, {videoTitle:string, jpegURL:path, totalTime:"00:00", bgColor:0x000000, textColor1:0x000000, textColor2:0x000000})
*
*		omo_applyPopUp(_linkId, _width, _height)
*
*/
if(typeof(flashElementsIndex) == "undefined"){
	var flashElementsIndex = 0;
}

if(typeof(swfobjectloaded) == "undefined"){
	var swfobjectloaded = false;
}

function omo_loadSWF(targetElement, swfPath, _width, _height, _fpVersion, _wmode, _flashVarsObj, _scaleMode, _altContent, _attributes)
{
	checkForSWFObject();
	
	if(_scaleMode == null){
		_scaleMode = "noscale";
	}
	if(_fpVersion == null){
		_fpVersion = "8.0.0";
	}
	if(_wmode == null){
		_wmode = "window";
	} else {
		if(_wmode != "transparent") {
			_wmode = "opaque";
		} else {
			_wmode = "transparent";
		}
	}
	if(typeof(swfobject) != "undefined") {
		if (swfobject.hasFlashPlayerVersion(_fpVersion)) {
			/*
			*	swfobject 2.1 replaces the target element with a flash embed element.  MOSS strips out non-supported elements
			*	when it saves the page, so would strip out the flash element (and not replace its holder).  This code creates
			*	a nested element to add the flash content into.
			*/
			var holder = document.createElement("div");
				holder.id = "flash_element"+flashElementsIndex;
			document.getElementById(targetElement).appendChild(holder);
			if (_flashVarsObj){
				flashVarsObj = _flashVarsObj;
				}
			else{
				flashVarsObj = {};
				}	
			flashVarsObj.urlPageName=window.location.href.toString();
			swfobject.embedSWF(swfPath, "flash_element"+flashElementsIndex, _width, _height, _fpVersion, "", flashVarsObj, {menu:"false", quality:"high", wmode:_wmode, scale:_scaleMode, salign:"lt", loop:"false", allowScriptAccess:"always", allowFullScreen:"true"}, {});
			flashElementsIndex++;
		} else {
			/*
			*	If the correct version of the Flash Plugin is not installed on the users' computer, then we add a (CIO specified)
			*	no flash message.
			*/
			Logger.log("Min Version of Flash not found so show something else");
			
			if(_attributes != undefined && _attributes.noFlashRedirectUrl != null && _attributes.noFlashRedirectUrl != "" && _attributes.noFlashRedirectUrl != undefined){
				
				Logger.log("No Flash Redirect");
				window.location = _attributes.noFlashRedirectUrl;
				}
				else{
			
			if(_altContent == null || _altContent == "" ){
			Logger.log("No Flash - Default Get Flash link");
			document.getElementById(targetElement).innerHTML = "<div class='no-flash-content'>This content requires the Adobe Flash Player. <a href=\"https://www.adobe.com/go/getflash/\">Get Flash</a></div>";
			}
			else
			{
			Logger.log("No Flash - Load bespoke alternative content");
			Logger.log(_altContent);
			document.getElementById(targetElement).style.height='auto'; 
			
			document.getElementById(targetElement).innerHTML = "<div class='no-flash-content'>"+_altContent+"</div>"
				
				}
			}
		}
	}
}

function checkForSWFObject() {
	/*
	*	This function detects whether swfobject is embedded in the page.  If it is not (which it should be) then we switch
	*	to a backup source file stored publically on the Google AJAX libraries site.
	*/
	if(typeof(swfobject) != "undefined"){
		isLoaded();
	} else {
		var script = document.createElement('script'); 
			script.type = 'text/javascript'; 
			script.src = 'https://ajax.googleapis.com/ajax/libs/swfobject/2.1/swfobject.js'; 
			script.onload = isLoaded;
			script.onreadystatechange = function() {
				if (this.readyState == 'complete' || this.readyState == 'loaded') {
					isLoaded();
					script.onreadystatechange = null;
				}
			}
		document.getElementsByTagName('head')[0].appendChild(script);  		
	}
	
	function isLoaded() {
		swfobjectloaded = true;
	}
}

function newsize (y, x)
{
	try
	{
		document.getElementById("div_flashtopnav").style.height = y + "px";
		if(typeof(x) != "undefined"){
			document.getElementById("div_flashtopnav").style.width = x + "px";	
		}
	}
	catch(err){}
}

/*
*	A selection of cookie management scripts...
*/
function createCookie(name,value,days,folder) {
	var expires = "";
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	else 
	{
		expires = "";
	}
	if(folder) {
		var path = "/"+window.location.href.toString().split("/")[3]+"/";
	} else {
		var path = "/";
	}
	document.cookie = name+"="+value+expires+"; path="+path;
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	var rtn = null;
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ')
		{
			c = c.substring(1,c.length);
		}
		if (c.indexOf(nameEQ) === 0){
			rtn =  c.substring(nameEQ.length,c.length);
		}
	}
	return rtn;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

/*
*	AJAX html loader scripts (loads valid XHTML body contents into a specified div)
*/

function omo_loadContent(srcFilePath, targetElementId) {
	loadExternalContent(srcFilePath, targetElementId);
	return false;
}

function loadExternalContentDone(req, url, target) {
  if (req.readyState == 4) { // only if req is "loaded"
    if (req.status == 200) { // only if "OK"
      document.getElementById(target).innerHTML = req.responseText;
    } else {
      document.getElementById(target).innerHTML=" loadExternalContent Error:\n"+ req.status + "\n" +req.statusText;
    }
  }
}

function loadExternalContent(url, target) {
  var req;
  document.getElementById(target).innerHTML = ' Fetching data...';
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (req !== undefined) {
    req.onreadystatechange = function() {loadExternalContentDone(req, url, target);};
    req.open("GET", url, true);
    req.send("");
  }
}  

/*
*	Functions for adding del.ico.us, facebook, newsvine, digg and reddit links to the page
*/

function attachShareIt()
{
    var shareItDeliciousLink = document.getElementById("shareItDelicious");
    if(shareItDeliciousLink)
    {
        shareItDeliciousLink.style.cursor = "pointer"
        if(shareItDeliciousLink.addEventListener)
            shareItDeliciousLink.addEventListener('click', ShareItDelicious, false);
        else
            shareItDeliciousLink.attachEvent('onclick', ShareItDelicious)
    }

    var shareItDiggLink = document.getElementById("shareItDigg");
    if(shareItDiggLink)
    {
        shareItDiggLink.style.cursor = "pointer"
        if(shareItDiggLink.addEventListener)
            shareItDiggLink.addEventListener('click', ShareItDigg, false);
        else
            shareItDiggLink.attachEvent('onclick', ShareItDigg)
    }
	
	var shareItFacebookLink = document.getElementById("shareItFacebook");
    if(shareItFacebookLink)
    {
        shareItFacebookLink.style.cursor = "pointer"
        if(shareItFacebookLink.addEventListener)
            shareItFacebookLink.addEventListener('click', ShareItFacebook, false);
        else
            shareItFacebookLink.attachEvent('onclick', ShareItFacebook)
    }
	
	var shareItNewsvineLink = document.getElementById("shareItNewsvine");
    if(shareItNewsvineLink)
    {
        shareItNewsvineLink.style.cursor = "pointer"
        if(shareItNewsvineLink.addEventListener)
            shareItNewsvineLink.addEventListener('click', ShareItNewsvine, false);
        else
            shareItNewsvineLink.attachEvent('onclick', ShareItNewsvine)
    }
	
	var shareItRedittLink = document.getElementById("shareItReditt");
    if(shareItRedittLink)
    {
        shareItRedittLink.style.cursor = "pointer"
        if(shareItRedittLink.addEventListener)
            shareItRedittLink.addEventListener('click', ShareItReditt, false);
        else
            shareItRedittLink.attachEvent('onclick', ShareItReditt)
    }
}

function ShareItDelicious()
{		
    var width = 800;
    var height = 600;
    var left = parseInt((screen.availWidth/2) - (width/2));
    var top = parseInt((screen.availHeight/2) - (height/2));
   
    var doc = encodeURIComponent(location.href);
	var title = document.title; 
    var win = window.open("http://del.icio.us/post?url=" + doc + "&title=" + title, "ShareItDelicious", "height=" + height + ", width=" + width + ", top=" + top + ", left=" + left + ",scrollbars=yes");
}

function ShareItDigg()
{	
    var width = 800;
    var height = 600;
    var left = parseInt((screen.availWidth/2) - (width/2));
    var top = parseInt((screen.availHeight/2) - (height/2));
    
    var doc = encodeURIComponent(location.href);
    var win = window.open("http://digg.com/submit?phase=2&url=" + doc, "ShareItDigg", "height=" + height + ", width=" + width + ", top=" + top + ", left=" + left + ",scrollbars=yes");
}

function ShareItFacebook()
{
	u=location.href;
	t=document.title;
	window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' +encodeURIComponent(t), 'sharer','toolbar=0,status=0,width=626,height=436');
}

function ShareItNewsvine()
{
    var width = 800;
    var height = 600;
    var left = parseInt((screen.availWidth/2) - (width/2));
    var top = parseInt((screen.availHeight/2) - (height/2));
    
    var doc = encodeURIComponent(location.href);
    var win = window.open("http://www.newsvine.com/_tools/seed?popoff=0&u=" + doc, "ShareItNewsvine", "height=" + height + ", width=" + width + ", top=" + top + ", left=" + left + ",scrollbars=yes");
}

function ShareItReditt()
{
    var width = 800;
    var height = 600;
    var left = parseInt((screen.availWidth/2) - (width/2));
    var top = parseInt((screen.availHeight/2) - (height/2));
   
    var doc = encodeURIComponent(location.href);
	var title = document.title; 
    var win = window.open("http://reddit.com/submit?url=" + doc + "&title=" + title, "ShareItReditt", "height=" + height + ", width=" + width + ", top=" + top + ", left=" + left + ",scrollbars=yes");
}

var dropDownsIndex = 0;
function createDropDownNavigation(targetElement, optionsArray, width){
	var innerHTMLCode = "<select id='dropdown_"+dropDownsIndex+"' name='dropdown_"+dropDownsIndex+"' onchange='window.location.href=document.getElementById(\"dropdown_"+dropDownsIndex+"\").options[document.getElementById(\"dropdown_"+dropDownsIndex+"\").selectedIndex].value;'";
	dropDownsIndex++;
	
	if(width){
		innerHTMLCode += " style='width:"+width+"px;'";
	}
	innerHTMLCode += ">";
	var optionsLength = optionsArray.length;
	for(var i = 0;i<optionsLength;i++){
		if(targetLinks[i].href != "") {
			innerHTMLCode += "<option value='"+targetLinks[i].url+"' class='haslink'>"+targetLinks[i].label+"</option>";
		} else {
			innerHTMLCode += "<option value='"+targetLinks[i].url+"'>"+targetLinks[i].label+"</option>";
		}
	}
	innerHTMLCode += "</select>";
	
	document.getElementById(targetElement).innerHTML = innerHTMLCode;
}

function createDropDownNavigationFromSection(targetElement, width) {
	var targetDiv = document.getElementById(targetElement);
	var targetLinks = targetDiv.getElementsByTagName("a");
	var optionsLength = targetLinks.length;
	var innerHTMLCode = "<select id='dropdown_" + dropDownsIndex + "' name='dropdown_" + dropDownsIndex + "' onchange='window.location.href=document.getElementById(\"dropdown_" + dropDownsIndex + "\").options[document.getElementById(\"dropdown_" + dropDownsIndex + "\").selectedIndex].value;'";
	dropDownsIndex++;
	
	if(width){
		innerHTMLCode += " style='width:"+width+"px;'";
	}
	innerHTMLCode += ">";
	
	for(var i = 0;i<optionsLength;i++){
		if(targetLinks[i].href != "") {
			innerHTMLCode += "<option value='"+targetLinks[i].href+"' class='haslink'>"+targetLinks[i].innerHTML+"</option>";
		} else {
			innerHTMLCode += "<option value='"+targetLinks[i].href+"'>"+targetLinks[i].innerHTML+"</option>";
		}
	}
	
	innerHTMLCode += "</select>";
	
	document.getElementById(targetElement).innerHTML = innerHTMLCode;
}


function omo_applyImageRollOver(_linkId, _rolloverImagePath, _hrefReplacement) {

preload_image_object = new Image();
preload_image_object.src=_rolloverImagePath;

    //alert("APPLYING");
    var linkId = _linkId;
    var rolloverImagePath = _rolloverImagePath;
	var hrefReplacement = _hrefReplacement;
    var linkElement = document.getElementById(linkId);
    var linkElementImageString = 'image-'+linkId;
    var linkElementImage = document.getElementById(linkElementImageString);
	//alert(linkElementImage);
	//alert(linkElementImage.src);

    if (linkElement && linkElementImage) {
	if(hrefReplacement==undefined || hrefReplacement==''){
	}
	else{
	linkElement.href=hrefReplacement;
	linkElement.target='';
	}
        var image_url_normal = linkElementImage.src;
        var image_url_over = rolloverImagePath;

        linkElement.imageObj = linkElementImage;
        linkElement.onmouseover = function() {
		this.imageObj.src=image_url_over;
        }
        linkElement.onmouseout = function(linkElementImage) {
		this.imageObj.src=image_url_normal;   
        }

    }

    else {
        window.setTimeout(omo_applyImageRollOver(linkId, rolloverImagePath), 100);
    }
}

function omo_LoadFlashVideoPlayerToDiv(varContainer, varWidth, varHeight, vfileName, optionsObj)
{

	checkForSWFObject();
	
	var varSWFPath = '/NonSecureSiteCollectionDocuments/omo_video_player_r4.swf';
	
	var flashvars = {};
	
	/**
	 *	Properties for optionsObj are:
	 *		videoTitle : text of the video title
	 *		jpegURL : relative / absolute url of the image to display
	 *		totalTime : the total time (00:00 format) of the video (because the video cannot know it without preloading)
	 *		bgColor : the colour of the background block, in 0x000000 format
	 *		textColor1 : the colour of the video title text, in 0x000000 format
 	 *		textColor2 : the colour of the 'Watch our video' text, in 0x000000 format
	 *		trackingValue : omniture tracking Value that gets tracked when video is initially played
	 */
	for(var i in optionsObj) {
		flashvars[i] = optionsObj[i];
	}
	
	flashvars.urlPageName = window.location.href.toString();
	flashvars.fileName = vfileName;
	
	if (swfobject.hasFlashPlayerVersion("6.0.65")) {
		/*
		*	swfobject 2.1 replaces the target element with a flash embed element.  MOSS strips out non-supported elements
		*	when it saves the page, so would strip out the flash element (and not replace its holder).  This code creates
		*	a nested element to add the flash content into.
		*/
		var holder = document.createElement("div");
			holder.id = "flash_element"+flashElementsIndex;
		document.getElementById(varContainer).appendChild(holder);
		
		swfobject.embedSWF(varSWFPath, "flash_element"+flashElementsIndex, varWidth, varHeight, "8.0.0", "/NonSecureSiteCollectionDocuments/expressInstall.swf", flashvars, {menu:"false", quality:"high", wmode:"transparent", scale:"noscale", salign:"lt", loop:"false", allowScriptAccess:"always"}, {id:"flash_element"+flashElementsIndex});
		
		try { 
			window["flash_element"+flashElementsIndex] = document.getElementById("flash_element"+flashElementsIndex);
			var newhref = "javascript:try{void(document.getElementById(\"flash_element"+flashElementsIndex+"\").playVideo());}catch(Err){}";
			//var newhref = "javascript:try{void(window.flash_element"+flashElementsIndex+".playVideo());}catch(Err){}";
			document.getElementById(varContainer+'Start').href = newhref;
			//document.getElementById(varContainer+'Start').onclick = newhref;
			document.getElementById(varContainer+'Start').target = "";
		}
		catch(err){}
		
		flashElementsIndex++;
	} else {
		/*
		*	If the correct version of the Flash Plugin is not installed on the users' computer, then we add a (CIO specified)
		*	no flash message.
		*/
		document.getElementById(varContainer).innerHTML = "This content requires the Adobe Flash Player. <a href=\"https://www.adobe.com/go/getflash/\">Get Flash</a>";
	}
}



function omo_applyPopUp(_linkId, _width, _height) {
var linkId = _linkId;
var width = _width;
var height = _height;

var existinghref = document.getElementById(linkId).href;
var existinghref2 = document.getElementById(linkId);
var newhref = "javascript:try{(w=window.open('" + existinghref  + "','popupWindow','toolbar=0,scrollbars=1,location=1,statusbar=0,menubar=0,resizable=1,width="+width+",height="+height+"'));w.focus()}catch(Err){};";
document.getElementById(linkId).href = newhref;
document.getElementById(linkId).target = "";
}



var Logger = new function() {
  this.log = function(str) {
    try {
      console.log(str);
    } catch(e) {
      // do nothing
    }
  };
};

