﻿/** global javascript stylesheet **/
//var debugMode = 'DEBUGv16:';
var debugMode = '';

AddEvent(window,'load',InitialisePage,false);

function InitialisePage()
{	/* a hook function for anything that you want to happen on page load */
	debugFunctionTitle='InitialisePage()';debug('entered function');
	FixHorizontalLayout();
	AddEvent(window,'resize',FixHorizontalLayout,false);
}

function FixHorizontalLayout()
{
	debugFunctionTitle='FixHorizontalLayout:';debug('entered function');
	if(!compatible) return false;

	var bodytag = document.getElementById("LEXUS");
	if (bodytag != null && bodytag.className.indexOf('horizontal') > -1 )
	{	var contentDiv = document.getElementById("content");
		var primaryContentDiv = document.getElementById("primary-content");
		var secondaryContentDiv = document.getElementById("secondary-content");
        // IE 6 needs to have 170 SUBTRACTED, whereas every other browser needs 30 ADDING.
        var additionalSpacer = (ieVersion() == 6) ? -170 : 30;
        
        if(contentDiv != null && primaryContentDiv != null && secondaryContentDiv != null)
		{	var contentHeight = primaryContentDiv.offsetHeight + secondaryContentDiv.offsetHeight + additionalSpacer + 'px';
			var msg = "primaryContentDiv.offsetHeight = [" + primaryContentDiv.offsetHeight + "] : ";
			msg += "secondaryContentDiv.offsetHeight = [" + secondaryContentDiv.offsetHeight + "] : ";
			msg += "additionalSpacer = [" + additionalSpacer + "] : ";
			msg += "Total height = [" + contentHeight + "]";
			debug(msg);
            if(contentHeight < 500)
                contentHeight = 500;

			contentDiv.style.height = contentHeight;
		}
		else 
		{	//there's a problem with accessing the divs?
			debug('cannot access one or more of the DIVs (primaryContentDiv, secondaryContentDiv)');
		}
	} else { } 
}

/* Generic Members and Methods that could be used elsewhere */
var compatible = (document.getElementById && document.getElementsByTagName && document.createElement&&!(navigator.userAgent.indexOf('MSIE 5') != -1 && navigator.userAgent.indexOf('Mac') != -1));

/* Toggle the display css attribute of the element with the given id */
function toggle(obj) 
{	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) {	el.style.display = 'none';}
	else {	el.style.display = '';}
}

function getElementsByClass(searchClass,node,tag) 
{
	debugFunctionTitle='getElementsByClass('+searchClass+','+node+','+tag+')';debug('entered function')
    var classElements = new Array();
	if (node == null) node = document;
	if (tag == null) tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) 
	{	if (pattern.test(els[i].className) ) 
		{	classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function getRefToDiv(divID,oDoc) 
{
	debugFunctionTitle='getRefToDiv('+divID+',oDoc)';debug('entered function');
    if( document.getElementById ) {	return document.getElementById(divID); }
	if( document.all ) {	return document.all[divID]; }
	if( !oDoc ) { oDoc = document; }
	if( document.layers ) 
	{	if( oDoc.layers[divID] ) { return oDoc.layers[divID]; } 
		else {	//repeatedly run through all child layers
			for( var x = 0, y; !y && x < oDoc.layers.length; x++ ) 
			{	//on success, return that layer, else return nothing
				y = getRefToDiv(divID,oDoc.layers[x].document); }
				return y; }
			}
		return false;
}    

function AddEvent(element,eventType,fn,useCapture)
{
    debugFunctionTitle='AddEvent()';debug('entered function eventType='+eventType);
    if(element.addEventListener){element.addEventListener(eventType,fn,useCapture);return true;}
	else if (element.attachEvent){var r = element.attachEvent('on' + eventType, fn);return r;}
	else{element['on' + eventType] = fn;}
    debug('function complete');
}

//PCD-Deleted-070905
//moved to .cs so we can use a literal for the font value (from the web.config settings)
//function SWFReplace()
//{
//	debugFunctionTitle='SWFReplace()';debug('entered function');
//    var nobelbook = { src: '/Images/nobel-book.swf'};  
//	var nobellight = { src: '/Images/nobel-light.swf'};   
//	sIFR.delayCSS  = true;  
//	sIFR.activate(nobelbook, nobellight);  
//	sIFR.replace(nobellight, { selector: 'h1' ,css: [ '.sIFR-root { text-transform: uppercase; color: #272f27 }' ,'a { text-decoration: none; }' ,'a:link { color: #000000; }' ,'a:hover { color: #CCCCCC; }' ] ,wmode: 'transparent' }); 
//	sIFR.replace(nobelbook, { selector: 'h2' ,css: [ '.sIFR-root { text-transform: uppercase; color: #272f27 }' ,'a { text-decoration: none; }' ,'a:link { color: #000000; }' ,'a:hover { color: #CCCCCC; }' ] ,wmode: 'transparent' });
//}
//\\PCD-Deleted-070905

// following functions are used within Aspnet Form tags specifically with ajax and flash 
var pageready = 0;

function pageAvailable()
{
	debugFunctionTitle='pageAvailable()';debug('entered function');
    if(pageready > 0) {	return true; }
	else {	return false; }
}

function triggerOnClick(ctrl)
{
	debugFunctionTitle='triggerOnClick()';debug('entered function')
	debug("Looking for control [" + ctrl + "]");    
	var ctrlToClick = findAspnetControl(ctrl);
	if(ctrlToClick != null)
	{	debug("Found control [" + ctrl + "]<br>About to trigger click event");
		ctrlToClick.click();
	}
}

function findAspnetControl(ctrl)
{
	debugFunctionTitle='findAspnetControl('+ctrl+')';debug('entered function');
    // Get the length of the control name we are looking for
	var ctrlLen = ctrl.length;
	// Loop through each element on the current form
	for(i=0; i<document.aspnetForm.elements.length; i++)
	{	var curCtrl = document.aspnetForm.elements[i];    // Get the current control
		var curCtrlName = curCtrl.name;                   // Get the control name       
		var curCtrlLen = curCtrlName.length;              // Get the length of the current control  

		// control name that we are looking for.
		if(ctrlLen > curCtrlLen){continue;} // We can eliminate those controls whos names are shorter than the 

		var curCtrlHTMLName = curCtrlName.substring(curCtrlLen - ctrlLen, curCtrlLen);
		var msg = "Current ctrl [" + curCtrlName + "] : Looking for [" + ctrl + "] : Found [" + curCtrlHTMLName + "] : ";
		debug(msg);

		// Finally - compare!
		if(ctrl == curCtrlHTMLName)
		{	debug("Match!");
			return curCtrl;
		}
 	}
	return null; 
}

// Resolves movie using supplied id
function thisMovie(movieName) 
{
    debugFunctionTitle='thisMovie('+movieName+')';debug('entered function');
	if (navigator.appName.indexOf("Microsoft") != -1) {return window[movieName]}
	else {	return document[movieName] }
}

// Standard interface for JavaScript calls on Flash
function flashInterface(jObj, movieName)
{
	debugFunctionTitle='flashInterface';debug('entered function');
	debug('typeof(jObj): ' + typeof(jObj) + ' : movieName: ' + movieName);
	var movie = thisMovie(movieName);
	//var msg = "thisMovie(movieName) " + (movie != null ? "!=" : "==") + " null";debug(msg);
//	try	
//	{
	if (movie != null) {thisMovie(movieName).flashInterface(jObj); }
//	}
//	catch(err)
//	{	// if we trigger a catch here then the swf doesn't poll for the movie etc.
		//txt="There was an error on this page.\n\nError description: " + err.description + "\n\n";if (movie == null) {txt+="Probable cause: the SWF element (" + movieName + ") could not be located.\n\n";}debug(txt);
//	}
}

// Standard interface for Flash calls on JavaScript
function javascriptInterface(jObj)
{
	debugFunctionTitle='javascriptInterface:';debug('entered function');
	debug("command: " + jObj.command + " : parameters: " + jObj.params + " : analytics: " + jObj.analytics);

	var analytics = jObj.analytics;
	if (typeof(analytics) == 'object')
	{	if (jObj.analytics.length>0) 
		{	if (jObj.analytics[0] != 'undefined' && jObj.analytics[0] != 'null' )
			{	debug("calling analytics dcsTrk("+jObj.analytics[0]+", "+jObj.analytics[1]+", "+jObj.analytics[2]+");");
				dcsTrk(jObj.analytics[0], jObj.analytics[1], jObj.analytics[2]);
			}
			else
			{	debug("analytics not called jObj.analytics[0]="+jObj.analytics[0]);
			}
		}
		else
		{	debug('analytics is an object but has no values');
		}
	}

	switch(jObj.command)
	{	case "page_available":
		debug('page_available: returning true');
		return true;
		break;

		case "redirect":
		debug('redirect has been fired');
		var url = jObj.params[0];
		if (url != '' && url != undefined)
		{
		  var winType = jObj.params[1];
		  var mode = jObj.params[2];
		  if (mode != '' && mode != undefined && mode != 'null')
		  {
		    if (url.indexOf('?')>0)
		    { url+='&flashvars=movieMode:' + mode;
		    }
		    else
		    {
		      url+='?flashvars=movieMode:' + mode;
		    }
		  }
		  debug('redirect to: ' + url + ' in Window Type: ' + winType);
		  if (winType == 'full')
		  {  openWin.full(url);
		  }
		  else if (winType == 'new')
		  {  var n=window.open(url);
		  }
		  else
		  {  document.location.href=url;
		  }
		}
		else
		{  debug('there was no valid url');
		}
		break;

		case "transition_complete_range":
		debug('transition_complete_range has been fired');
		carSelection(jObj);
		break;
		
		case "launch_flash":
		debug('launch_flash has been fired **DEPRECATED: use redirect with params:url,windowType,mode**');
		var params = jObj.params;	
		if (typeof(params) == 'object')
		{	if (jObj.params.length>0) 
			{	openWin.full(jObj.params[0]+"?flashvars=movieMode:"+jObj.params[1]);
			}
			else
			{	debug('the params (url, movieMode) required for launch_flash have not been provided');
			}
		}
		else
		{	debug('the params (url, movieMode) required for launch_flash have not been provided');
		}
		break;

		case "close_window":
		window.close();
		break;

		case "invoke_analytics":
		debug('invoke_analytics: this is simply a generic command where there is no other action required (analytics should have been called above)');
		//if (jObj.analytics.length>0) {alert('jObj.analytics.length detected');}
		//{ dcsTrk(jObj.analytics[0], jObj.analytics[1], jObj.analytics[2]);}
		break;

		case "transition_started_range":
		debug('transition_started_range: no action set at the moment');
		break;

		case "stop_video":
		debug('stop_video: no action set at the moment');
		break;
        
		case "pause_video":
		debug ('pause_video: no action set at the moment');
		break;

		case "unpause_video":
		debug ('unpause_video: no action set at the moment');
		break;
        
		case "update_history_range":
		debug('update_history_range: no action set at the moment');
		break;
		
		default :
		debug('case '+jObj.command+' not caught: calling javascriptLocalInterface(jObj);');
		javascriptLocalInterface(jObj);
		break;
	}
}

// invokes flashInterface to initiate video playback
function playVideo(movieName)
{
	debugFunctionTitle='playVideo('+movieName+')';debug('entered function');
	var jObj = {"command": "play_video", "return":false, "params":[]};
	if (typeof(flashInterface) == 'function')
	{	flashInterface(jObj, movieName);
	}
	else {	debug('flashInterface not available');
	}
}

// invokes flashInterface to stop video playback
function stopVideo(movieName)
{
	debugFunctionTitle='stopVideo('+movieName+')';debug('entered function');
	var jObj = {"command": "stop_video", "return":false, "params":[]};
	if (typeof(flashInterface) == 'function')
	{	flashInterface(jObj, movieName);
	}
	else {	debug('flashInterface is not available');
	}
}

// invokes flashInterface to update with the media passed in 
function updateMedia(movieName, sMediaUrl, sMediaType)
{ 
	var jObj = {"command": "update_media", "return":false, "params":[sMediaUrl,sMediaType]}; 
	if (typeof(flashInterface) == 'function')
	{	flashInterface(jObj, movieName); 
	} 
	else {	debug('flashInterface is not available'); 
	} 
} 

/** SWFFormFix v1.0.0: SWF ExternalInterface() Form Fix - http://http://www.teratechnologies.net/stevekamerman/  SWFFormFix is (c) 2007 Steve Kamerman and is released under the MIT License: http://www.opensource.org/licenses/mit-license.php Project sponsored by Tera Technologies - http://www.teratechnologies.net/ **/
SWFFormFixAuto = function()
{
	debugFunctionTitle='SWFFormFixAuto()';debug('entered function');
	if(navigator.appName.toLowerCase() != "microsoft internet explorer")return true;
	var objects = document.getElementsByTagName("object");
	if(objects.length == 0) return true;
	for(i=0;i<objects.length;i++){
		// here's all the objects on the page, now lets find the flash objects
		if(objects[i].classid == "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"){
			// this is a flash movie, apply the fix
			window[objects[i].id] = objects[i];
			debug('fix applied');
		}
	}
	var out = '';
	debug('returning true');
	return true;
}
SWFFormFix = function(swfname)
{
	debugFunctionTitle='SWFFormFix()';debug('entered function');
	if(navigator.appName.toLowerCase() != "microsoft internet explorer")return false;
	var testnodename = "SWFFormFixTESTER";
	document.write('<div id="'+testnodename+'" onclick="SWFFormFixCallback(this,\''+swfname+'\');return false;" style="display:none">&nbsp;</div>');
	document.getElementById(testnodename).onclick();
}
SWFFormFixCallback = function (obj,swfname)
{
	debugFunctionTitle='SWFFormFixCallback()';debug('entered function');
	var path = document;
	var error = false;
	var testnode = obj;
	while(obj = obj.parentNode){
		if(obj.nodeName.toLowerCase() == "form"){
			if(obj.name != undefined && obj.name != null && obj.name.length > 0){
				path = path.forms[obj.name];
			}else{
				debug("Error: one of your forms does not have a name!");
				error = true;
			}
		}
	}
	testnode.parentNode.removeChild(testnode);
	if(error) return false;
	window[swfname]=path[swfname];
	debug('returning true [fixed '+swfname+']')
	return true;
}

// add Accordion initialiser for pages that contain the Accordion-load script and Accordion DIVs
// requires onload...
//  $(document).ready(function() {
//    Accordion.init();
Accordion = {	init: function()
{
	debugFunctionTitle='Accordion()';debug('entered function ** SHOULD THIS OR swfformfix.js be USED? **')
	active = '#Accordion-1';
	running = 0;
	$('#Accordion-section/div/div').not(active).hide();
	$('#Accordion-section/div/h3').click(function(e){
		e.preventDefault();
		var p = $('div', this.parentNode);
		if (running || !p.is(":hidden")) return false;
		running = 2;
		$(active).slideUp('fast', function(){--running;});
		active = '#' + p.slideDown('slow', function(){--running;}).get(0).id;
		return false;
	});
	}
}

openWin = { 
	full: function(s){
	debugFunctionTitle='openWin.full()';debug('entered function s='+s);
	s=s.replace(/\s/g, ''); var n=window.open(s,'LexusPopUp', 'width='+screen.availWidth+',height='+screen.availHeight+',left=1,top=1,location=no,resizable=yes,scrollbars=yes,toolbar=no,status=no,menubar=no');n.focus();},
	half: function(s){
	debugFunctionTitle='openWin.half()';debug('entered function s='+s);
	s=s.replace(/\s/g, ''); var n=window.open(s,'LexusPopUp', 'width='+screen.availWidth/2+',height='+screen.availHeight/2+',left='+screen.availWidth/4+',top='+screen.availHeight/4+',location=no,resizable=yes,scrollbars=yes,toolbar=no,status=no,menubar=no');n.focus();},
	specific: function(s,w,h,sLoc,sResize,sScroll,sTool,sStat,sMenu){
	debugFunctionTitle='openWin.specific()';debug('entered function s='+s+',w'+w+',h'+h+',sLoc'+sLoc+',sResize'+sResize+',sScroll'+sScroll+',sTool'+sTool+',sStat'+sStat+',sMenu'+sMenu);
	if(sLoc!="yes"){sLoc='no';}
	if(sResize!="no"){sResize='yes';}
	if(sScroll!="no"){sScroll='yes';}
	if(sTool!="yes"){sTool='no';}
	if(sStat!="yes"){sStat='no';}
	if(sMenu!="yes"){sMenu='no';}
	s=s.replace(/\s/g, ''); 
	try {iLeft=(screen.availWidth-w)/2; }catch(err){iLeft=1;}
	try {iTop=(screen.availHeight-h)/2; }catch(err){iTop=1;}
	var n=window.open(s,'LexusPopUp', 'width='+w+',height='+h+',left='+screen.availWidth/4+',top='+screen.availHeight/4+',location='+sLoc+',resizable='+sResize+',scrollbars='+sScroll+',toolbar='+sTool+',status='+sStat+',menubar='+sMenu+'');
	n.focus();
	}
}

//Open window - deprecated - now use openWin.full('url');
function openwindowfull(s) 
{
    debugFunctionTitle='openwindowfull()';debug('entered function s='+s+' ** DEPRECATED - see openWin.full() ** ');
    openWin.full(s); 
}

function makeFrame(sSrc, iWidth, iHeight, sAlign, iFrameborder, sScrolling, sFrameID) 
{
    debugFunctionTitle='makeFrame()';debug('entered function sSrc='+sSrc+', iWidth='+iWidth+', iHeight='+iHeight+', sAlign='+sAlign+', iFrameborder='+iFrameborder+', sScrolling='+sScrolling+', sFrameID='+sFrameID);
	if (!document.getElementById(sFrameID + 'ID'))
	{	if (iWidth == -1){iWidth=640};
		if (iHeight == -1){iHeight=480};
		if (sSrc == ''){sSrc='about:no-url-passed'};
		if (sAlign == ''){sAlign='left'};
		if (sScrolling == ''){sScrolling='auto'};
		ifrm = document.createElement("IFRAME");
		ifrm.setAttribute("id", sFrameID + 'ID');
		ifrm.setAttribute("Name", window.location.host);
		ifrm.setAttribute("src", sSrc);
		ifrm.setAttribute("align", sAlign);
		ifrm.setAttribute("frameborder", iFrameborder);
		ifrm.setAttribute("scrolling", sScrolling);
		ifrm.style.width = iWidth +"px";
		ifrm.style.height = iHeight +"px";
		ifrm.style.backgroundColor = "#ffffff";

		document.getElementById(sFrameID).appendChild(ifrm);
	}
}


function makeFrameBg(sSrc, iWidth, iHeight, sAlign, iFrameborder, sScrolling, sFrameID, bgColor) 
{
    debugFunctionTitle='makeFrame()';debug('entered function sSrc='+sSrc+', iWidth='+iWidth+', iHeight='+iHeight+', sAlign='+sAlign+', iFrameborder='+iFrameborder+', sScrolling='+sScrolling+', sFrameID='+sFrameID);
	if (!document.getElementById(sFrameID + 'ID'))
	{	

                                var setTransparent = 'false'
                                if (iWidth == -1){iWidth=640};
		if (iHeight == -1){iHeight=480};
		if (sSrc == ''){sSrc='about:no-url-passed'};
		if (sAlign == ''){sAlign='left'};
		if (sScrolling == ''){sScrolling='auto'};
                                if (bgColor.toLowerCase == 'transparent'){setTransparent ='true'};
		ifrm = document.createElement("IFRAME");
		ifrm.setAttribute("id", sFrameID + 'ID');
		ifrm.setAttribute("Name", window.location.host);
		ifrm.setAttribute("src", sSrc);
		ifrm.setAttribute("align", sAlign);
		ifrm.setAttribute("frameborder", iFrameborder);
		ifrm.setAttribute("scrolling", sScrolling);
                                ifrm.setAttribute("allowTransparency", setTransparent);
                                
		ifrm.style.width = iWidth +"px";
		ifrm.style.height = iHeight +"px";
		ifrm.style.backgroundColor = bgColor;

		document.getElementById(sFrameID).appendChild(ifrm);
	}
}

function makeFrameBg2(sSrc, iWidth, iHeight, sAlign, iFrameborder, sScrolling, sFrameID) 
{
    debugFunctionTitle='makeFrame()';debug('entered function sSrc='+sSrc+', iWidth='+iWidth+', iHeight='+iHeight+', sAlign='+sAlign+', iFrameborder='+iFrameborder+', sScrolling='+sScrolling+', sFrameID='+sFrameID);
	if (!document.getElementById(sFrameID + 'ID'))
	{	if (iWidth == -1){iWidth=640};
		if (iHeight == -1){iHeight=480};
		if (sSrc == ''){sSrc='about:no-url-passed'};
		if (sAlign == ''){sAlign='left'};
		if (sScrolling == ''){sScrolling='auto'};
		ifrm = document.createElement("IFRAME");
		ifrm.setAttribute("id", sFrameID + 'ID');
		ifrm.setAttribute("Name", window.location.host);
		ifrm.setAttribute("src", sSrc);
		ifrm.setAttribute("align", sAlign);
		ifrm.frameBorder = iFrameborder;
		ifrm.setAttribute("scrolling", sScrolling);
		ifrm.style.width = iWidth +"px";
		ifrm.style.height = iHeight +"px";
		ifrm.style.backgroundColor = "#ffffff";

		document.getElementById(sFrameID).appendChild(ifrm);
	}
}

function debug(message) 
{   if (debugMode!='' || message=='')
	{   if (!debug.window_ || debug.window_.closed) 
	    {   var win = window.open("", "window_", "width=400,height=200,scrollbars=yes,resizable=yes,status=no,location=no,menubar=no,toolbar=no");
            if (!win) return;
            var doc = win.document;
            doc.write("<html><head><title>Debug Log</title></head>" + "<body><a href='javascript:window.close();'>[Close]</a></body></html>");
            doc.close();
            debug.window_ = win;
        }
        dayTwo = new Date();hrNow = dayTwo.getHours();mnNow = dayTwo.getMinutes();scNow = dayTwo.getSeconds();theTime = hrNow + ":" + mnNow + ":" + scNow ;
        var theDiv = debug.window_.document.createElement('div');
        var theP = debug.window_.document.createElement('p');
        var theBR = debug.window_.document.createElement('br');
        var theText = debug.window_.document.createTextNode(theTime + " " + debugMode + " " + debugFunctionTitle);
        var theText2 = debug.window_.document.createTextNode(message);
        theP.appendChild(theText);theP.appendChild(theBR);theP.appendChild(theText2);
        debug.window_.document.body.appendChild(theP);
    }
}


// The following 3 functions are added here for use on all specs pages that use CT_Mini_Spec. They handle the styling and send the update command to the flash where appropriate

function specLinkClick(oItem, movieName, sMediaUrl, sMediaType){
    $(".minispec-active-link").toggleClass("minispec-active-link");
    $("#" + oItem.id).toggleClass("minispec-active-link");
    updateMedia(movieName, sMediaUrl, sMediaType)
}

function specLinkHover(oItem){
    $(".minispec-hover-link").toggleClass("minispec-hover-link");
    $("#" + oItem.id + " img:first").toggleClass("minispec-hover-link");
}

function specLinkOut(oItem){
    $("#" + oItem.id + " img:first").toggleClass("minispec-hover-link");
}
