﻿/*
general.js for Essent trading
Based on Prototype 1.6.0 and script.aculo.us 1.8.0
Version: 2.0.0
Developer: SFJ, SCM, JH
*/

// defaults assume sustainability content
var SWFobject = {
	src: '/_internet/sustainability/flash/World.swf',
	xml_loc: '/_internet/sustainability/xml/EN/content_world.xml',
	width: 900, height: 538,
	flash: 9, flashID: 'essentFlashOverlay',
	timer: '', bgcolor: '#ffffff', 'SIFRheaders': []};

Event.observe(window,'load',initSus);

//wait for the document to be loaded
function initSus(){
    if ($('translator')) {
        $('tanslator_lang').select('a').each(function(i){
            Event.observe(i, 'click', function(e){
                var link = Event.findElement(e, 'a');
                var alias = '/translocal/' + gup('translocal', link.href);
                magicTracking(alias, link.href);
                Event.stop(e);
            }, false);
        });
    }
    resizeFlashOverlay();
    Event.observe(window, 'resize', function(){ 
        resizeFlashOverlay();
    }, false);
        
    $$('a.flash_overlay').each(function(i) {
        Event.observe(i,'click',function(e) {
            link = Event.findElement(e, 'a');
            launchFlashOverlay(link.href);
        	Event.stop(e);
        });
    });
    
    $$('a.flash_overlay_close').each(function(i) {
        Event.observe(i,'click',function(e) {
            closeFlashOverlay();
        	Event.stop(e);
        });
    });
    
    query = document.location.toString();
    query = query.replace(/&amp;/g,'&');
    
    if(query.indexOf("?") != -1){

	    queryVars = query.substring(query.indexOf("?")+1,query.length);
	    queryVars = queryVars.split("&");

	    queryVars.each(function(i) {
		    if(i.indexOf("overlay") != -1) {
			    if (i.split("=")[1] == "true") launchFlashOverlay(query);
		    }
				
			// catch deep_link requests
			param = i.split("=");
			if (param[0] == 'deep_link') {
				launchFlashOverlay(i);
			}
	    });
    }
    
     if ($('searchform')){
        Event.observe($('searchform'), 'submit', function(e) {
            var alias = '/searchpage/' + $('search').value.replace(/ /g, '%20');
            magicTracking(alias, $('searchform'), null, true);
            Event.stop(e);
        });
    }
}
    
function resizeFlashOverlay(){
    if ($('flash_overlay')){
        var dims = getPageSize();
        $('flash_overlay').setStyle({
                width: dims[0] + 'px',
                height: dims[1] + 'px'
            });
    }
}

/* Remove the Flash overlay if exists */
function closeFlashOverlay() {
    if ($('flash_overlay_holder')){
        if (Prototype.Browser.Opera){  //opera hack
	        var elem_to_rep = new Array('block_2', 'block_1');
	        elem_to_rep.each(function(i, cnt){
		        if ($(i) && $(i).down().hasClassName('sIFR-replaced')){
			        $(i).down().innerHTML = SWFobject.SIFRheaders[cnt];
		        }
	        });
            $('flash_overlay_holder').remove();
            $('flash_overlay').hide();
            $('hero').setStyle({visibility: 'visible'});
        } else {
            window.setTimeout(function(){
                $('flash_overlay_holder').remove();
                $('flash_overlay').hide();
                $('hero').setStyle({visibility: 'visible'});
            }, 200);
        }
    }
}

function createSwfObject(SWFobject_new){
    var so = new SWFObject(SWFobject.src, SWFobject.flashID, SWFobject.width, SWFobject.height, SWFobject.flash, SWFobject.bgcolor);
    so.addParam('wmode', 'transparent');
        
    for (param in SWFobject_new) {
        so.addVariable(param, SWFobject_new[param]);
    }
    so.write("flash_overlay_content");
}

function getBreadcrumb(frameid) {
    if (document.getElementById && document.createElement) {
        var frameContainer = document.getElementById(frameid);
        var breadcrumb = document.getElementById('breadcrumb');
        var breadcrumbEntry = 'titleFromFrame';

        if (frameContainer) {
            if (frameContainer.contentDocument && frameContainer.contentDocument.title) { //ff/op/saf
                var insertTitle = document.createTextNode(frameContainer.contentDocument.title);
            } else if (frameContainer.Document && frameContainer.Document.title) { //IE
                var insertTitle = document.createTextNode(frameContainer.Document.title);
            }
            if (document.getElementById(breadcrumbEntry)) {
                var replaceItem = document.getElementById(breadcrumbEntry);
                replaceItem.innerHTML = '';
                replaceItem.appendChild.insertTitle;
            } else {
                breadcrumb.lastChild.className = '';

                var insertItem = document.createElement('li');
                insertItem.setAttribute('class','last');
                insertItem.setAttribute('id',breadcrumbEntry);
                insertItem.appendChild(insertTitle);

                breadcrumb.appendChild(insertItem);

                if (frameContainer.Document) { //IE
                    document.getElementById(breadcrumbEntry).className = 'last';
                }
            }
        }
    }
}

/***********************************************
* IFrame SSI script II- � Dynamic Drive DHTML code library (http://www.dynamicdrive.com)
* Visit DynamicDrive.com for hundreds of original DHTML scripts
* This notice must stay intact for legal use
***********************************************/

/* modified for Essent Trading 22/11/2006 - syzygy */

var iframeid="careersFrame"

function resizeCaller() {
    alert(location.search.substring(1));
    if (document.getElementById) resizeIframe(iframeid);
}

function resizeIframe(frameid) {
    var frameContainer = document.getElementById(frameid)
    if (frameContainer) {
        if (frameContainer.contentDocument && frameContainer.contentDocument.documentElement.offsetHeight) { //moz/op/saf syntax
            frameContainer.height = frameContainer.contentDocument.documentElement.offsetHeight;
        } else if (frameContainer.Document && frameContainer.Document.body.scrollHeight) { //ie5+ syntax
            frameContainer.height = frameContainer.Document.body.scrollHeight;
        }
        getBreadcrumb(frameid);

        if (frameContainer.addEventListener) {
            frameContainer.addEventListener("load", readjustIframe, false);
        } else if (frameContainer.attachEvent) {
            frameContainer.detachEvent("onload", readjustIframe); // Bug fix line
            frameContainer.attachEvent("onload", readjustIframe);
        }
    }
}

function readjustIframe(loadevt) {
    var crossevt=(window.event)? event : loadevt
    var iframeroot=(crossevt.currentTarget)? crossevt.currentTarget : crossevt.srcElement
    if (iframeroot) resizeIframe(iframeroot.id);
}

function loadintoIframe(iframeid, url) {
    if (document.getElementById) document.getElementById(iframeid).src=url;
}

// http://www.howtocreate.co.uk/tutorials/javascript/browserwindow

function alertSize() {
    if (document.getElementById('careersFrame')) {
        var myHeight = 0;
        if (typeof(window.innerHeight) == 'number' ) { //Non-IE
            myHeight = window.innerHeight;
        } else if (document.documentElement && (document.documentElement.clientHeight)) { //IE 6+ in 'standards compliant mode'
            myHeight = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientHeight)) { //IE 4 compatible
            myHeight = document.body.clientHeight;
        }

        // have to set 40px margin-top on footer explicitly
       // var elementsHeight = document.getElementById('navContainer').clientHeight + document.getElementById('hero').clientHeight + document.getElementById('breadcrumb').clientHeight + document.getElementById('footer').clientHeight + 40;
        var elementsHeight = document.getElementById('navContainer').scrollHeight + document.getElementById('hero').scrollHeight + document.getElementById('breadcrumb').scrollHeight + document.getElementById('footer').scrollHeight + 40;



        var frameHeight = myHeight - elementsHeight;
        //  var frameHeight = 3000;

        // don't resize iFrame if it would be too small
        if (frameHeight > 250) {
            document.getElementById('careersFrame').height = frameHeight;
        }

        if (window.addEventListener) {
            window.addEventListener("resize", alertSize, false);
        } else if (window.attachEvent) {
            window.detachEvent("onresize", alertSize); // Bug fix line
            window.attachEvent("onresize", alertSize);
        }
    }
}

// generic popup window allowing size to be set
function openWindow (url, winName, w, h, properties) {
    properties = properties || "resizable"
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+','+ properties;
	newWindow = window.open(url,winName,settings);
	if(url.indexOf("://") == -1) newWindow.focus();
	//top.newWindow = true;
	return false;
}

function careersWindow(url) {
    openWindow(url, 'essentradingcareers', 788, 475, 'resize=no,scrollbars=yes');
}
function careersPopup(url) {
    openWindow(url, 'careerspopup', 495, 418, 'status=no,top=110,left=200,toolbar=no,menubar=no,scrollbars=yes');
}

function popUp(url){
   openWindow(url, "", 788, 475, 'resize=no,scrollbars=yes');
}

function popUpTag(url, text, tagValue, tagPosition)
{
  var analyticsTag;
  var extra;
  /* build an execute tag */
  if(tagPosition == null || tagPosition == "")
  {
    /* external link somewhere :: tagValue = entireTag */
     analyticsTag = tagValue
  }
  else
  {
    /* specified position tag  :: tagVaue = tagPrefix */
    if(tagPosition == "Body")
      extra = "Other";
    else
      extra = "Nav";

      analyticsTag = tagValue + "_" + tagPosition + "_" + extra + "_Text_" +  text;
      var intIndexOfMatch = analyticsTag.indexOf(" ");

      while (intIndexOfMatch != -1)
      {
         analyticsTag = analyticsTag.replace( " ", "%20" )
         intIndexOfMatch = analyticsTag.indexOf( " " );
      }
  }
   //urchinTracker(analyticsTag);
    if (analyticsTag.indexOf('/') !== 0) {
        analyticsTag = '/popuplogging/' + analyticsTag;
    }
   pageTracker._trackPageview(analyticsTag); /* new tracking code */
   popUp(url);
}

if (window.addEventListener) {
    window.addEventListener("load", alertSize, false)
} else if (window.attachEvent) {
    window.attachEvent("onload", alertSize)
} else {
    window.onload=alertSize
}

function locationSelector(doWhat, nElement)
{
   alert(nElement);
   var wElement = document.getElementById(nElement);
   switch(doWhat)
   {
        case "open":
            wElement.style.visibility = "visible";
             new Effect.SlideDown(nElement);
          break;

        case "close":
            break;
   }
}

function gup(name, tmpURL) {
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp(regexS);
    if (tmpURL) { //if is set - use it
       
    } else {
        var tmpURL = window.location.href;
    }
    var results = regex.exec(tmpURL);
    
    if (results == null) return false;
    else return results[1];
}


// Core code from - quirksmode.com
// Edit for Firefox by pHaez
// returns: [pageWidth,pageHeight,windowWidth,windowHeight]
function getPageSize() {
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
}

/* SCM: 28/01/2008 - tracking */
var config = {url: '', delay: 200, target: '_self', timeout: '', alias: ''};
/* alias - tracking string, url - URL redirect after tracking (optional), submit - flag form submission */
function magicTracking(alias, url, target, submit){
   // alert('Start of magic tracking');
    if (alias == undefined || alias == '') { return; }
    config.target = target || '_self';
    if (alias.indexOf('/') !== 0) {
        alias = '/flashlogging/' + alias;
    }
    config.alias = alias;
    if (typeof url == 'undefined' || url == 'undefined' || url == '') {
        //no URL specified do just the tracking
    } else {
        config.url = url;
    }
    if (typeof pageTracker == 'undefined' ) {
        //not here
        doRedirect();
        return;
    }
    pageTracker._trackPageview(config.alias);
    if (submit == true ) {
        config.timeout = self.setTimeout(function(){
                self.clearTimeout(config.timeout); //reset the timeout
                url.submit();
            },config.delay);
    } else if (config.url !== '') {
        config.timeout = self.setTimeout(function(){
            self.clearTimeout(config.timeout); //reset the timeout
            if (config.target == '_self') {
                window.location = config.url;
            } else if (config.target == '_blank') {
                window.open(config.url); //open a new window
            } else {
                //just the tracking
            }
        },config.delay);
    }
   // alert('End of magic tracking');
}

function trackSpotlight(typeVal,catVal,href) {
	var spotLightTag;
	var Img;
	var axel = Math.random() + "";
	var ord = axel * 1000000000000000000;
	var prx = "?";

	spotLightTag="http://ad.uk.doubleclick.net/activity;src=1666402;type="+typeVal+";cat="+catVal+";ord="+ord+prx;
	img = new Image();
	if (typeof href !== 'undefined') {
        config.timeout = self.setTimeout('doRedirect()',config.delay);
        if (img.addEventListener) {
            img.addEventListener('load', doRedirect, false);
        } else if (img.attachEvent) {
            img.attachEvent('onload', doRedirect);
        } else if (img.onload){
	        img.onload = function () {
		        doRedirect();
	        };
        }
        config.url = href;
    }
    img.src = spotLightTag;
}

function doRedirect(){

    self.clearTimeout(config.timeout); //reset the timeout
    var href = config.url;
	if(href.search(/mailto:/g) !== -1){
	    location.href = href;
	} else {
	    if (href.search(/http/g) == -1 ){
           
            location.href = "http://"+location.host+"/" + href;
    	} else {
    	    location.href = href;
    	}
    }
}



/* Create Flash overlay */
function launchFlashOverlay(link) {
    if (link == null) { return false; }  //do nothing - no parameters passed on
	// deep_link=0 means show the default movie copy
	if (link == 'deep_link=0') link = '';

	var SWFobject_new = link.toQueryParams();
	
	Object.extend(SWFobject_new, SWFobject);  //inherit variables from the URL string
	
	if (SWFobject_new.src !== '') {
        window.scrollTo(0,0);    
        if (!$('flash_overlay_holder')){
            var container = Builder.node('div', { id: 'flash_overlay_holder' }, [
    	        Builder.node('div', { id: 'flash_overlay_content' })
            ]);
            document.getElementsByTagName('body')[0].appendChild(container);
        }
        if (!$('flash_overlay')){
            var overlay = Builder.node('div', { id: 'flash_overlay', 'style': 'display: none;' }, '');
            document.getElementsByTagName('body')[0].appendChild(overlay);
        }
        new Effect.Opacity($('flash_overlay'), {duration: 0, to: 0, afterFinish: function() {
            $('flash_overlay').style.backgroundColor = '#fff';
            if (Prototype.Browser.Gecko) {
                //FF bug stops flash working on transparent background
                new Effect.Opacity($('flash_overlay'), {duration: 0, to: 1});
                $('flash_overlay').setStyle({
                    background: 'transparent url(images/elements/trans_ff.png)'
                });
                resizeFlashOverlay();
                $('flash_overlay').show();
                createSwfObject(SWFobject_new);
            } else {
                resizeFlashOverlay();
                $('flash_overlay').show();
                new Effect.Opacity($('flash_overlay'), {duration: 0.8, from: 0, to: 0.70, afterFinish: function() {
                       
                        if (Prototype.Browser.Opera){  //opera hack
	                        var elem_to_rep = new Array('block_2', 'block_1');
	                        elem_to_rep.each(function(i, cnt){
		                        if ($(i) && $(i).down().hasClassName('sIFR-replaced')){
			                        SWFobject.SIFRheaders[cnt] = $(i).down().innerHTML;
			                        $(i).down().innerHTML = '&nbsp;';
		                        }
	                        });
	                        $('hero').setStyle({visibility: 'hidden'});
                        }
                       createSwfObject(SWFobject_new);
                    }});
            }
            
        }});

		    
		//$('flash_overlay').show();

	}
}
