﻿/** 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');
                HideEmptySpotlights();
	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(parseInt(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) {
FixHorizontalLayout();
	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');
		pageready = 1;
		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')
	{	
	    if(typeof(thisMovie("main_movie")) != 'undefined') {
	        if (typeof(thisMovie("main_movie").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'))
	{
		iWidth += ""; iHeight += "";
		if (iWidth == '-1'){
			iWidth = '640';
		} else if (iWidth.indexOf('full') != -1){
			iWidth = '100%';
		}
		if (iHeight == '-1'){
			iHeight = '480';
		} else if (iHeight.indexOf('full') != -1){
			iHeight = '100%';
		}
		if(!(iWidth.charAt(iWidth.length - 1) == '%' || iWidth.charAt(iWidth.length - 1) == 'x')){
			iWidth += "px";
		}
		if(!(iHeight.charAt(iHeight.length - 1) == '%' || iHeight.charAt(iHeight.length - 1) == 'x')){
			iHeight += "px";
		}
		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;
		ifrm.style.height = iHeight;
		ifrm.style.backgroundColor = "#ffffff";

		if (iWidth == '100%' && iHeight == '100%'){
			$('body').css({'padding':'0','margin':'0'});
			$('body > div').each(function(){
				$(this).css('display', 'none');
			});
			$('body').append(ifrm);
		} else {
			$('#' + sFrameID).append(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");
}

function FormatMiniSpec()

{

            var contentDiv = ""

            var activeDiv = "div-link1"

            var activeLink = "a-link1"

           

            //Hide all and show first               

            $(".mini-specs-info-container").hide();

            $("#mini-specs-info-container1").show();

             

            //Update div based on click

            $(".image-container").click(function(){

                             

                contentDiv= "mini-specs-info-container" + this.id.replace("div-link" ,"" )

 

                //Hide all then show the main div relative to the click

                $(".mini-specs-info-container").hide();

                $("#" + contentDiv).show();

                //toggle the divs active state and update var(ready for next click)

                $("#" + this.id).toggleClass("div-active");

                $("#" + activeDiv).toggleClass("div-active");

                activeDiv = this.id                                                       

                $("#" + this.id + " a:first").toggleClass("link-active");

                $("#" + activeLink).toggleClass("link-active");        

                activeLink = $("#" + this.id + " a:first").get(0).id
            });
}


function RenderSearchDialog() {
            $("div.search-entry-header input.search-input").hide();
        $("div.search-entry-header input.magnify").hide()
        $("div.search-entry-initial").hover(function() {
            $("div.search-entry-initial").hide();
            $("div.search-entry-header input.search-input").show();
            $("div.search-entry-header input.magnify").show();
            }, function() {
                        
            });
            $("div.search-entry-header").hover(function() {
            
            }, function() {
              $("div.search-entry-initial").show();
            $("div.search-entry-header input.search-input").hide();
            $("div.search-entry-header input.magnify").hide();
            });
}


// Remove text decoration from key model names
var whenJQueryReady = setInterval(function() {
 if (typeof jQuery != 'undefined')
 {
     clearInterval(whenJQueryReady );
     $(document).ready(function() {
        $("h2:contains('RX 450h')").css("text-transform", "none");
        $("a:contains('RX 450h')").css("text-transform", "none");
        $("a:contains('LF-Xh')").css("text-transform", "none");
        $("a:contains('RX 400h HYBRID')").css("text-transform", "none");
        $("a:contains('IS 220d')").css("text-transform", "none");
        $("a:contains('LF-Ch')").css("text-transform", "none");
        $("a:contains('CT200h')").css("text-transform", "none");
        $("a:contains('CT 200h')").css("text-transform", "none");
        $(function() { $('#txt-scroll-pane').jScrollPane({showArrows:true}); });
     })
 }
}, 100);


function ScrollMultiBlocks() {

    //Global
    $(".minispecs-video-thumb-block", $(".container")).hide();          //Hide all containers
    $(".minispecs-video-thumb-block:first", $(".container")).show();    //Show the first one 
    
    //Process the Next button click    
    $("a.minispecs-video-thumb-arrow-right").click(function() {
  
        var nextDiv = $(this);
        var x=1     //Counter, initialised as 1
        var sId=""  //Temp var, initialised blank
        var n = $("div.minispecs-video-thumb-block", $(this).parent()).length     //The number of container divs
        var oneToTurnOn;
        
        //Loop through the blocks and find which one is active
        $("div.minispecs-video-thumb-block", $(this).parent()).each(function(i){
            
            if($(this).css("display") == "block"){

                oneToTurnOn = i + 1;

                if (oneToTurnOn!=n){
                
                    //first turn the prev div back on
                    $("a.minispecs-video-thumb-arrow-left", $(this).parent()).removeClass("minispecs-arrow-inactive");
                    
                    //Hide all then show the next one
                    $("div.minispecs-video-thumb-block", $(this).parent()).hide();
                    $("div.minispecs-video-thumb-block:eq(" + oneToTurnOn + ")", $(this).parent()).show();
                    
                    //If we're the last one then updated the 'next' link, else break out the loop
                    if ((oneToTurnOn+1)==n){
                        $(nextDiv.addClass("minispecs-arrow-inactive"));
                    }
                    else{
                        return false;
                    }
                }
            }
        });       
    });
    
    //Process the Previous button click
    $("a.minispecs-video-thumb-arrow-left").click(function() {
  
        var prevDiv = $(this);           
        var x=1     //Counter, initialised as 1
        var sId=""  //Temp var, initialised blank
        var n = $("div.minispecs-video-thumb-block", $(this).parent()).length     //The number of container divs    
        var oneToTurnOn;
        
        //Loop through the blocks and find which one is active
        $("div.minispecs-video-thumb-block", $(this).parent()).each(function(i){
            
            if($(this).css("display") == "block"){

                oneToTurnOn = i - 1;

                if (oneToTurnOn+1!=0){

                    //first turn the next div back on
                    $("a.minispecs-video-thumb-arrow-right", $(this).parent()).removeClass("minispecs-arrow-inactive");
                     
                    //Hide all then show the previous one 
                    $("div.minispecs-video-thumb-block", $(this).parent()).hide();
                    $("div.minispecs-video-thumb-block:eq(" + oneToTurnOn + ")", $(this).parent()).show();
                    
                    //If we're the last one then updated the 'previous' link, else break out the loop
                    if ((oneToTurnOn)==0){
                        $(prevDiv.addClass("minispecs-arrow-inactive"));
                    }
                    else{
                        return false;
                    }
                }
            }
        });       
    });
    

}



function matchHeight(sId,sTag){

    var targOuterContainer,targElements,contDivs,maxHeight,divHeight,d;

     try {

    // get all <div> elements in the document with id hours-section
    targOuterContainer = document.getElementById(sId);
    targElements = targOuterContainer.getElementsByTagName(sTag);

    contDivs=[];

    // initialize maximum height value
    maxHeight=0;

    // iterate over all tag elements in the id divs 
    for(var i=0;i<targElements.length;i++){
       
       
        d=targElements[i];

        contDivs[contDivs.length]=d;

        // determine height for <h5> element
        if(d.offsetHeight){
            divHeight=d.offsetHeight;
        }
        else if(d.style.pixelHeight){
            divHeight=d.style.pixelHeight;
        }

        // calculate maximum height
        maxHeight=Math.max(maxHeight,divHeight);
    }

    // assign maximum height value to all of the tag elements
    for(var i=0;i<contDivs.length;i++){
        contDivs[i].style.height=maxHeight + "px";
    }

  }

  catch(err) {

 }
}

// New functionality to test if Spotlights are empty and hide the HTML (to fix an IE bug)
// mpaton added 8/06/2009

function HideEmptySpotlights() {
$("div.spotlight").each(function(t) {
if ($(this).html() != "") {} else {
$(this).css("display", "none");
}
});}
/*UPDATE TO STANDARD FUNCTIONALITY: Addition of disableScrollTop parameter see blog notes */

/* Copyright (c) 2006 Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * See http://kelvinluck.com/assets/jquery/jScrollPane/
 * $Id: jScrollPane.js 33 2008-12-10 22:55:28Z kelvin.luck $
 */

/**
 * Replace the vertical scroll bars on any matched elements with a fancy
 * styleable (via CSS) version. With JS disabled the elements will
 * gracefully degrade to the browsers own implementation of overflow:auto.
 * If the mousewheel plugin has been included on the page then the scrollable areas will also
 * respond to the mouse wheel.
 *
 * @example jQuery(".scroll-pane").jScrollPane();
 *
 * @name jScrollPane
 * @type jQuery
 * @param Object	settings	hash with options, described below.
 *								scrollbarWidth	-	The width of the generated scrollbar in pixels
 *								scrollbarMargin	-	The amount of space to leave on the side of the scrollbar in pixels
 *								wheelSpeed		-	The speed the pane will scroll in response to the mouse wheel in pixels
 *								showArrows		-	Whether to display arrows for the user to scroll with
 *								arrowSize		-	The height of the arrow buttons if showArrows=true
 *								animateTo		-	Whether to animate when calling scrollTo and scrollBy
 *								dragMinHeight	-	The minimum height to allow the drag bar to be
 *								dragMaxHeight	-	The maximum height to allow the drag bar to be
 *								animateInterval	-	The interval in milliseconds to update an animating scrollPane (default 100)
 *								animateStep		-	The amount to divide the remaining scroll distance by when animating (default 3)
 *								maintainPosition-	Whether you want the contents of the scroll pane to maintain it's position when you re-initialise it - so it doesn't scroll as you add more content (default true)
 *								scrollbarOnLeft	-	Display the scrollbar on the left side?  (needs stylesheet changes, see examples.html)
 *								reinitialiseOnImageLoad - Whether the jScrollPane should automatically re-initialise itself when any contained images are loaded
 *								disableScrollTop 	-   Whether to disable scroll to top when inner pane item is clicked (see http://code.google.com/p/jscrollpane/issues/detail?id=77)
 * @return jQuery
 * @cat Plugins/jScrollPane
 * @author Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 */

(function($) {

$.jScrollPane = {
	active : []
};
$.fn.jScrollPane = function jScrollPane(settings)
{
	settings = $.extend({}, $.fn.jScrollPane.defaults, settings);

	var rf = function rf() { return false; };
	
	return this.each(
		function()
		{
			var $this = $(this);
			// Switch the element's overflow to hidden to ensure we get the size of the element without the scrollbars [http://plugins.jquery.com/node/1208]
			$this.css('overflow', 'hidden');
			var paneEle = this;
			
			if ($(this).parent().is('.jScrollPaneContainer')) {
				var currentScrollPosition = settings.maintainPosition ? $this.position().top : 0;
				var $c = $(this).parent();
				var paneWidth = $c.innerWidth();
				var paneHeight = $c.outerHeight();
				var trackHeight = paneHeight;
				$('>.jScrollPaneTrack, >.jScrollArrowUp, >.jScrollArrowDown', $c).remove();
				$this.css({'top':0});
			} else {
				var currentScrollPosition = 0;
				this.originalPadding = $this.css('paddingTop') + ' ' + $this.css('paddingRight') + ' ' + $this.css('paddingBottom') + ' ' + $this.css('paddingLeft');
				this.originalSidePaddingTotal = (parseInt($this.css('paddingLeft')) || 0) + (parseInt($this.css('paddingRight')) || 0);
				var paneWidth = $this.innerWidth();
				var paneHeight = $this.innerHeight();
				var trackHeight = paneHeight;
				$this.wrap(
					$('<div></div>').attr(
						{'className':'jScrollPaneContainer'}
					).css(
						{
							'height':paneHeight+'px', 
							'width':paneWidth+'px'
						}
					)
				);
				// deal with text size changes (if the jquery.em plugin is included)
				// and re-initialise the scrollPane so the track maintains the
				// correct size
				$(document).bind(
					'emchange', 
					function(e, cur, prev)
					{
						$this.jScrollPane(settings);
					}
				);
				
			}
			
			if (settings.reinitialiseOnImageLoad) {
				// code inspired by jquery.onImagesLoad: http://plugins.jquery.com/project/onImagesLoad
				// except we re-initialise the scroll pane when each image loads so that the scroll pane is always up to size...
				// TODO: Do I even need to store it in $.data? Is a local variable here the same since I don't pass the reinitialiseOnImageLoad when I re-initialise?
				var $imagesToLoad = $.data(paneEle, 'jScrollPaneImagesToLoad') || $('img', $this);
				var loadedImages = [];
				
				if ($imagesToLoad.length) {
					$imagesToLoad.each(function(i, val)	{
						$(this).bind('load', function() {
							if($.inArray(i, loadedImages) == -1){ //don't double count images
								loadedImages.push(val); //keep a record of images we've seen
								$imagesToLoad = $.grep($imagesToLoad, function(n, i) {
									return n != val;
								});
								$.data(paneEle, 'jScrollPaneImagesToLoad', $imagesToLoad);
								settings.reinitialiseOnImageLoad = false;
								$this.jScrollPane(settings); // re-initialise
							}
						}).each(function(i, val) {
							if(this.complete || this.complete===undefined) { 
								//needed for potential cached images
								this.src = this.src; 
							} 
						});
					});
				};
			}

			var p = this.originalSidePaddingTotal;
			
			var cssToApply = {
				'height':'auto',
				'width':paneWidth - settings.scrollbarWidth - settings.scrollbarMargin - p + 'px'
			}

			if(settings.scrollbarOnLeft) {
				cssToApply.paddingLeft = settings.scrollbarMargin + settings.scrollbarWidth + 'px';
			} else {
				cssToApply.paddingRight = settings.scrollbarMargin + 'px';
			}

			$this.css(cssToApply);

			var contentHeight = $this.outerHeight();
			var percentInView = paneHeight / contentHeight;

			if (percentInView < .99) {
				var $container = $this.parent();
				$container.append(
					$('<div></div>').attr({'className':'jScrollPaneTrack'}).css({'width':settings.scrollbarWidth+'px'}).append(
						$('<div></div>').attr({'className':'jScrollPaneDrag'}).css({'width':settings.scrollbarWidth+'px'}).append(
							$('<div></div>').attr({'className':'jScrollPaneDragTop'}).css({'width':settings.scrollbarWidth+'px'}),
							$('<div></div>').attr({'className':'jScrollPaneDragBottom'}).css({'width':settings.scrollbarWidth+'px'})
						)
					)
				);
				
				var $track = $('>.jScrollPaneTrack', $container);
				var $drag = $('>.jScrollPaneTrack .jScrollPaneDrag', $container);
				
				if (settings.showArrows) {
					
					var currentArrowButton;
					var currentArrowDirection;
					var currentArrowInterval;
					var currentArrowInc;
					var whileArrowButtonDown = function()
					{
						if (currentArrowInc > 4 || currentArrowInc%4==0) {
							positionDrag(dragPosition + currentArrowDirection * mouseWheelMultiplier);
						}
						currentArrowInc ++;
					};
					var onArrowMouseUp = function(event)
					{
						$('html').unbind('mouseup', onArrowMouseUp);
						currentArrowButton.removeClass('jScrollActiveArrowButton');
						clearInterval(currentArrowInterval);
					};
					var onArrowMouseDown = function() {
						$('html').bind('mouseup', onArrowMouseUp);
						currentArrowButton.addClass('jScrollActiveArrowButton');
						currentArrowInc = 0;
						whileArrowButtonDown();
						currentArrowInterval = setInterval(whileArrowButtonDown, 100);
					};
					$container
						.append(
							$('<a></a>')
								.attr({'href':'javascript:;', 'className':'jScrollArrowUp'})
								.css({'width':settings.scrollbarWidth+'px'})
								.html('Scroll up')
								.bind('mousedown', function()
								{
									currentArrowButton = $(this);
									currentArrowDirection = -1;
									onArrowMouseDown();
									this.blur();
									return false;
								})
								.bind('click', rf),
							$('<a></a>')
								.attr({'href':'javascript:;', 'className':'jScrollArrowDown'})
								.css({'width':settings.scrollbarWidth+'px'})
								.html('Scroll down')
								.bind('mousedown', function()
								{
									currentArrowButton = $(this);
									currentArrowDirection = 1;
									onArrowMouseDown();
									this.blur();
									return false;
								})
								.bind('click', rf)
						);
					var $upArrow = $('>.jScrollArrowUp', $container);
					var $downArrow = $('>.jScrollArrowDown', $container);
					if (settings.arrowSize) {
						trackHeight = paneHeight - settings.arrowSize - settings.arrowSize;
						$track
							.css({'height': trackHeight+'px', top:settings.arrowSize+'px'})
					} else {
						var topArrowHeight = $upArrow.height();
						settings.arrowSize = topArrowHeight;
						trackHeight = paneHeight - topArrowHeight - $downArrow.height();
						$track
							.css({'height': trackHeight+'px', top:topArrowHeight+'px'})
					}
				}
				
				var $pane = $(this).css({'position':'absolute', 'overflow':'visible'});
				
				var currentOffset;
				var maxY;
				var mouseWheelMultiplier;
				// store this in a seperate variable so we can keep track more accurately than just updating the css property..
				var dragPosition = 0;
				var dragMiddle = percentInView*paneHeight/2;
				
				// pos function borrowed from tooltip plugin and adapted...
				var getPos = function (event, c) {
					var p = c == 'X' ? 'Left' : 'Top';
					return event['page' + c] || (event['client' + c] + (document.documentElement['scroll' + p] || document.body['scroll' + p])) || 0;
				};
				
				var ignoreNativeDrag = function() {	return false; };
				
				var initDrag = function()
				{
					ceaseAnimation();
					currentOffset = $drag.offset(false);
					currentOffset.top -= dragPosition;
					maxY = trackHeight - $drag[0].offsetHeight;
					mouseWheelMultiplier = 2 * settings.wheelSpeed * maxY / contentHeight;
				};
				
				var onStartDrag = function(event)
				{
					initDrag();
					dragMiddle = getPos(event, 'Y') - dragPosition - currentOffset.top;
					$('html').bind('mouseup', onStopDrag).bind('mousemove', updateScroll);
					if ($.browser.msie) {
						$('html').bind('dragstart', ignoreNativeDrag).bind('selectstart', ignoreNativeDrag);
					}
					return false;
				};
				var onStopDrag = function()
				{
					$('html').unbind('mouseup', onStopDrag).unbind('mousemove', updateScroll);
					dragMiddle = percentInView*paneHeight/2;
					if ($.browser.msie) {
						$('html').unbind('dragstart', ignoreNativeDrag).unbind('selectstart', ignoreNativeDrag);
					}
				};
				var positionDrag = function(destY)
				{
					destY = destY < 0 ? 0 : (destY > maxY ? maxY : destY);
					dragPosition = destY;
					$drag.css({'top':destY+'px'});
					var p = destY / maxY;
					$pane.css({'top':((paneHeight-contentHeight)*p) + 'px'});
					$this.trigger('scroll');
					if (settings.showArrows) {
						$upArrow[destY == 0 ? 'addClass' : 'removeClass']('disabled');
						$downArrow[destY == maxY ? 'addClass' : 'removeClass']('disabled');
					}
				};
				var updateScroll = function(e)
				{
					positionDrag(getPos(e, 'Y') - currentOffset.top - dragMiddle);
				};
				
				var dragH = Math.max(Math.min(percentInView*(paneHeight-settings.arrowSize*2), settings.dragMaxHeight), settings.dragMinHeight);
				
				$drag.css(
					{'height':dragH+'px'}
				).bind('mousedown', onStartDrag);
				
				var trackScrollInterval;
				var trackScrollInc;
				var trackScrollMousePos;
				var doTrackScroll = function()
				{
					if (trackScrollInc > 8 || trackScrollInc%4==0) {
						positionDrag((dragPosition - ((dragPosition - trackScrollMousePos) / 2)));
					}
					trackScrollInc ++;
				};
				var onStopTrackClick = function()
				{
					clearInterval(trackScrollInterval);
					$('html').unbind('mouseup', onStopTrackClick).unbind('mousemove', onTrackMouseMove);
				};
				var onTrackMouseMove = function(event)
				{
					trackScrollMousePos = getPos(event, 'Y') - currentOffset.top - dragMiddle;
				};
				var onTrackClick = function(event)
				{
					initDrag();
					onTrackMouseMove(event);
					trackScrollInc = 0;
					$('html').bind('mouseup', onStopTrackClick).bind('mousemove', onTrackMouseMove);
					trackScrollInterval = setInterval(doTrackScroll, 100);
					doTrackScroll();
				};
				
				$track.bind('mousedown', onTrackClick);
				
				$container.bind(
					'mousewheel',
					function (event, delta) {
						initDrag();
						ceaseAnimation();
						var d = dragPosition;
						positionDrag(dragPosition - delta * mouseWheelMultiplier);
						var dragOccured = d != dragPosition;
						return !dragOccured;
					}
				);

				var _animateToPosition;
				var _animateToInterval;
				function animateToPosition()
				{
					var diff = (_animateToPosition - dragPosition) / settings.animateStep;
					if (diff > 1 || diff < -1) {
						positionDrag(dragPosition + diff);
					} else {
						positionDrag(_animateToPosition);
						ceaseAnimation();
					}
				}
				var ceaseAnimation = function()
				{
					if (_animateToInterval) {
						clearInterval(_animateToInterval);
						delete _animateToPosition;
					}
				};

				var scrollTo = function(pos, preventAni)
				{	if (settings.disableScrollTop)
					{	return;
						//this is due to a bug in the JScroller that forces the container pane
						// to scroll to the top when a click is recognised. See related items 
						// http://code.google.com/p/jscrollpane/issues/detail?id=77
					}   
					if (typeof pos == "string") {
						$e = $(pos, $this);
						if (!$e.length) return;
						pos = $e.offset().top - $this.offset().top;
					}
					$container.scrollTop(0);
					ceaseAnimation();
					var destDragPosition = -pos/(paneHeight-contentHeight) * maxY;
					if (preventAni || !settings.animateTo) {
						positionDrag(destDragPosition);
					} else {
						_animateToPosition = destDragPosition;
						_animateToInterval = setInterval(animateToPosition, settings.animateInterval);
					}
				};
				$this[0].scrollTo = scrollTo;
				
				$this[0].scrollBy = function(delta)
				{
					var currentPos = -parseInt($pane.css('top')) || 0;
					scrollTo(currentPos + delta);
				};
				
				initDrag();
				
				scrollTo(-currentScrollPosition, true);
			
				// Deal with it when the user tabs to a link or form element within this scrollpane
				$('*', this).bind(
					'focus',
					function(event)
					{
						var $e = $(this);
						
						// loop through parents adding the offset top of any elements that are relatively positioned between
						// the focused element and the jScrollPaneContainer so we can get the true distance from the top
						// of the focused element to the top of the scrollpane...
						var eleTop = 0;
						
						while ($e[0] != $this[0]) {
							eleTop += $e.position().top;
							$e = $e.offsetParent();
						}
						
						var viewportTop = -parseInt($pane.css('top')) || 0;
						var maxVisibleEleTop = viewportTop + paneHeight;
						var eleInView = eleTop > viewportTop && eleTop < maxVisibleEleTop;
						if (!eleInView) {
							var destPos = eleTop - settings.scrollbarMargin;
							if (eleTop > viewportTop) { // element is below viewport - scroll so it is at bottom.
								destPos += $(this).height() + 15 + settings.scrollbarMargin - paneHeight;
							}
							scrollTo(destPos);
						}
					}
				)
				
				// NOTE: custom. eliminate the code bellow. it causes 'Syntax error, unrecognized expression: #' in jQuery 1.3.2 on IE
                // if (location.hash) {
                //  scrollTo(location.hash);
                // }
				
				// use event delegation to listen for all clicks on links and hijack them if they are links to
				// anchors within our content...
				$(document).bind(
					'click',
					function(e)
					{
						$target = $(e.target);
						if ($target.is('a')) {
							var h = $target.attr('href');
							if (h.substr(0, 1) == '#' && h.length > 1) { // NOTE: custom code - <<&& h.length > 1>> !!! 
								scrollTo(h);
							}
						}
					}
				);
				
				$.jScrollPane.active.push($this[0]);
				
			} else {
				$this.css(
					{
						'height':paneHeight+'px',
						'width':paneWidth-this.originalSidePaddingTotal+'px',
						'padding':this.originalPadding
					}
				);
				// remove from active list?
				$this.parent().unbind('mousewheel');
			}
			
		}
	)
};

$.fn.jScrollPane.defaults = {
	scrollbarWidth : 10,
	scrollbarMargin : 5,
	wheelSpeed : 18,
	showArrows : false,
	arrowSize : 0,
	animateTo : false,
	dragMinHeight : 1,
	dragMaxHeight : 99999,
	animateInterval : 100,
	animateStep: 3,
	maintainPosition: true,
	scrollbarOnLeft: false,
	reinitialiseOnImageLoad: false,
	disableScrollTop : false
};

// clean up the scrollTo expandos
$(window)
	.bind('unload', function() {
		var els = $.jScrollPane.active; 
		for (var i=0; i<els.length; i++) {
			els[i].scrollTo = els[i].scrollBy = null;
		}
	}
);

})(jQuery);

/* Copyright (c) 2009 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * Version: 3.0.2
 * 
 * Requires: 1.2.2+
 */
(function(c){var a=["DOMMouseScroll","mousewheel"];c.event.special.mousewheel={setup:function(){if(this.addEventListener){for(var d=a.length;d;){this.addEventListener(a[--d],b,false)}}else{this.onmousewheel=b}},teardown:function(){if(this.removeEventListener){for(var d=a.length;d;){this.removeEventListener(a[--d],b,false)}}else{this.onmousewheel=null}}};c.fn.extend({mousewheel:function(d){return d?this.bind("mousewheel",d):this.trigger("mousewheel")},unmousewheel:function(d){return this.unbind("mousewheel",d)}});function b(f){var d=[].slice.call(arguments,1),g=0,e=true;f=c.event.fix(f||window.event);f.type="mousewheel";if(f.wheelDelta){g=f.wheelDelta/120}if(f.detail){g=-f.detail/3}d.unshift(f,g);return c.event.handle.apply(this,d)}})(jQuery);
/*!
 * Share Control Javascript
 * 
 * Date: 		$LastChangedDate: 2009-11-16 Mark Saunders call dcsTrk on Share form $
 * Date: 		$LastChangedDate: 2009-10-20 Mark Saunders fix to checkemail regex $
 * Revision:	$Revision: 752 $
 */

Sc = (function($) {

var maxMsgLen = 250
var params 		= parseQueryStr(document.location.href)
var title 		= params.title
var linkurl		= params.url
var campaign	= params.campaign
var socialGroup = params.social
var emailTitle	= ""
var emailHeader = ""
var emailFooter	= ""
var emailUrl	= "/site-tools/aspxFormPost.asp?TMMEACTION=SAVE&amp;EMAILFORM=YES&amp;EMAILFORMONLY=YES&amp;EMAILFROM={from}&amp;EMAILTO={to}&amp;EMAILSUBJECT={subject}&amp;EMAILBODY={body}"
var shareSites	= []
var socialSites	= []

function checkEmail(str) {
	//return /^[\n &lt;&quot;']*([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+)/.test(str)
    /*
    source: http://regexlib.com/DisplayPatterns.aspx
    regex to validate email address noteworthy: 
    (1) It allows usernames with 1 or 2 alphanum characters, or 3+ chars can have -._ in the middle. username may NOT start/end with -._ or any other non alphanumeric character. 
    (2) It allows heirarchical domain names (e.g. me@really.big.com). Similar -._ placement rules there. 
    (3) It allows 2-9 character alphabetic-only TLDs (that oughta cover museum and adnauseum :&gt;). 
    (4) No IP email addresses though -- I wouldn't Want to accept that kind of address
    */

	return /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})((,|;)\s?[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})*$/.test(str)
}                   
                       var br_sharelables = {
				fromError:		"Please enter your email address in a valid format",
				toError:		"Please enter your friend’s email address in a valid format",
				messageError:	"Please enter a message",
				sendConfirm:	"Your message is sent successfully",
				sendError:		"There was an error sending your message"
			}
var formElements = {   from:{valueSelector:"#fromEmail",errorSelector:"#fromEmailError",validator:checkEmail,errorMsg:br_sharelables.fromError},
					     to:{valueSelector:"#toEmail",errorSelector:"#toEmailError",validator:checkEmail,errorMsg:br_sharelables.toError},
					message:{valueSelector:"#message",errorSelector:"#messageError",validator:function(str){return (str&&str.length>0&&str.length<=maxMsgLen)},errorMsg:br_sharelables.messageError}}



$(document).ready(function() {

	if ((campaign==null)||(campaign.length==0)||(campaign=='null')) campaign = "*"

	$.ajax({
		type: "GET",
		url: "/sys/dotnet/xml/share-config.xml",
		dataType: "xml",
		success: function(xml) {
			
			var $xml 	= $(xml)
			$xml.find("content > item[id='sharesite']").each(function() {
				var $this 			= $(this)
				var result  		= {}
				result.display		= $this.find('title').text()
				result.id			= result.title 
				result.icon			= $this.find('icon').text()
				result.urlPattern	= $this.find('url_link').text()
				shareSites.push(result);
			});
			
			if (socialGroup) {socialGroup = '-' + socialGroup}
            $xml.find("content > item[id='socialgroup" + socialGroup + "']").each(function() {
                var $this 			= $(this)               
                var result  		= {}
                result.display		= $this.find('title').text()
                result.id			= result.title 
                result.icon			= $this.find('icon').text()
                result.urlPattern	= $this.find('url_link').text()
                socialSites.push(result);
            });
			
			title    = validateParam(title,"")
			linkurl  = validateParam(linkurl,"")
			campaign = validateParam(campaign,"*")

			emailUrl = validateParam($xml.find("content > item[id='emailurl'] > url_link").text(),emailUrl)	
			
			var defaultTitle
			var defaultHeader
			var defaultFooter
			
			$xml.find("content > item[id='email']").each(function() {
				var $this 			= $(this)
				var configText 		= $this.find('text').text()
				var instCampaign	= $this.find('instruction[id="1"]').text()
				var instType		= $this.find('instruction[id="2"]').text()
				
				if (instCampaign=="*") {
					if (instType=="title") defaultTitle = configText
					else if (instType=="header") defaultHeader = configText
					else if (instType=="footer") defaultFooter = configText
				}
				
				if (instCampaign==campaign) {
					if (instType=="title") emailTitle = configText
					else if (instType=="header") emailHeader = configText
					else if (instType=="footer") emailFooter = configText
				}
			})
			
			emailTitle  = validateParam(emailTitle,defaultTitle)
			emailHeader = validateParam(emailHeader,defaultHeader)
			emailFooter = validateParam(emailFooter,defaultFooter)
			
			title = emailTitle + " " + title
			
			//buildSitesMarkup($("#shareSiteList"))
			if ($.isFunction(window.shareCustom)) window.shareCustom()
	
			$('#emailForm').submit(function(event) {
			//$('#tellFriendSend').click(function(event) {
				event.preventDefault()
				submitEmail()
			})

			
			$('#shareClose').click(function(event) {
				event.preventDefault()
				self.parent.tb_remove()
			})
		},
		complete: function() {
		    if (shareSites.length < 1) {
                $("#shareSection").css("display", "none");
            } else {
                buildSitesMarkup($("#shareSiteList"))
            }
            
            if (socialSites.length < 1) {
                $("#socialSection").css("display", "none");
            } else {
                buildSocialMarkup($("#socialSiteList"))
            }
        }
	});
//				self.parent.tb_remove()
//			})
//		}
//	});
})

function validateParam(param,defaultValue) {
	return ((param==null)||(param.length==0)||(param=='null')) ? defaultValue : param 
}


function submitEmail() {
	var errors = false
	for (var formElm in formElements) {
		var elm = formElements[formElm]
		var $elm = $(elm.valueSelector)
		elm.value = $elm.val()
		if (!elm.validator(elm.value)) {
			$(elm.errorSelector).html(elm.errorMsg)
			$elm.addClass("inputError")
			errors = true
		} else {
			$(elm.errorSelector).html("&nbsp;")
			$elm.removeClass("inputError")
		}
}

	if (errors) return;

var content = $("#message").val();
var from = $("#fromEmail").val();
var to = $("#toEmail").val().replace(/,/g, ";").replace(/ /g, "");

	content = content.replace(/<\/?[^>]+(>|$)/g, "");
	var emailMessage = encodeURIComponent(emailHeader)
                                      + encodeURIComponent("###LF###")
		      + encodeURIComponent(content.replace(/\n/ig,  "###LF###"))
                                      + encodeURIComponent("###LF###")
		      + linkurl 
                                      + encodeURIComponent("###LF###")
		      + emailFooter

	//var thisEmailUrl = encodeURI(emailUrl.replace(/\{from\}/, from ).replace(/\{to\}/, to ).replace(/\{body\}/, message ).replace(/\{subject\}/, title ) )
	var emailMessageUrl = emailUrl.replace(/\{from\}/, from ).replace(/\{to\}/, to ).replace(/\{body\}/, emailMessage).replace(/\{subject\}/, title );

            try {
		if (/fakeEmail.html/.test(emailMessageUrl)){
			window.open(emailMessageUrl);
			$('#emailMsg').html(br_sharelables.sendConfirm)
		}
		else {
			$.post(emailMessageUrl, function(data){
				$('#emailMsg').html(br_sharelables.sendConfirm)
//MS:091116:UPDATE
				try {   dcsTrk('WT.pc=submit&WT.si_x=2&WT.si_cs="1"'); }
				catch(err) { }
//MS:091116:UPDATE END
			});
		}
	} catch (e) {
		$('#emailMsg').html(br_sharelables.sendError)
	}
	//self.parent.jQuery.fn.shareButton.close()
}

function buildSitesMarkup ($shareSiteList) {
    var ICON_SIZE = 16
    var createCallBack = function(name) { return function(){
		//alert(name)
	} }
        
    $shareSiteList.html('');
        
    for (var i=0; i < shareSites.length; i++) {
            
        var site = shareSites[i]

        var href = site.urlPattern.replace(/\{u\}/, linkurl).replace(/\{t\}/, title)

//MS:091116:UPDATE
		$('<li class="shareSite">' +
			'<a target="_blank" href="' + href + '" class="shareSiteLink" id="'+site.id+'" title="' + site.display + '" onclick="try{dcsTrk(\'WT.pn=Share&WT.ti=' + site.display + '\')} catch(err){ }">'+
				'<span class="siteIcon" style="background: url('+site.icon+') no-repeat;"></span>'+
				site.display +
			'</a>'+
		  '</li>'
		//).click( createCallBack(site.display) ).appendTo($shareSiteList)
		).appendTo($shareSiteList)
    };
}
//MS:091116:UPDATE END

function buildSocialMarkup ($socialSiteList) {
    var ICON_SIZE = 16
    var createCallBack = function(name) { return function(){
        //alert(name)
    } }
        
    $socialSiteList.html('');
        
    for (var i=0; i < socialSites.length; i++) {
        var site = socialSites[i]
        var href = site.urlPattern.replace(/\{u\}/, linkurl).replace(/\{t\}/, title)

        $('<li class="shareSite">' +
            '<a target="_blank" href="' + href + '" class="shareSiteLink" id="'+site.id+'" title="' + site.display + '" onclick="try{dcsTrk(\'WT.pn=Share&WT.ti=' + site.display + '\')} catch(err){ }">'+
                '<span class="siteIcon" style="background: url('+site.icon+') no-repeat;"></span>'+
                site.display +
            '</a>'+
          '</li>'
        ).appendTo($socialSiteList)
    };
}

function parseQueryStr(url) {
    function readVal(kv) { return decodeURI(kv.length === 2 ? kv[1] : '') }
    var i = url.indexOf('?')
    if (i === -1) { return {} }
    var q = url.substring(i + 1),
        params = {}
    $.each(q.split('&'), function(i, p) {
        var kv = p.split('=')
        var k = kv[0]
        if (params.hasOwnProperty(k)) {
            var v = params[k]
            if (!$.isArray(v)) {
                v = [v] // turn it into array
                params[k] = v
            }
            v.push(readVal(kv))
        }
        else {
            params[k] = readVal(kv)
        }
    })
    return params
}

})(jQuery)
function twitterCallback2(twitters) {

if (twitters != null && twitters != 'undefined') {
 $("#twitter_update_list").css("visibility", "hidden");
  var statusHTML = [];
  for (var i=0; i<twitters.length; i++){
    var username = twitters[i].user.screen_name;
    var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      return '<a href="'+url+'">'+url+'</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
      return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
    });
    statusHTML.push('<li><span>'+status+'</span> <a target="_blank" style="font-size:85%" href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'">'+relative_time(twitters[i].created_at)+'</a></li>');

var replaceLFCHScreenName = twitters[i].user.screen_name;
replaceLFCHScreenName = replaceLFCHScreenName.replace('LFCh', 'CT200h');

  $("a#blog-feed-link").attr("href", "http://twitter.com/" + replaceLFCHScreenName );
$("a#blog-feed-link").attr("target", "_blank");
  }
  $("#twitter_update_list").html(statusHTML.join(''));
  $("#twitter_update_list").css("visibility", "visible");

   var t;
   clearTimeout(t) 

   // FADE IN CONTENT
   t = setTimeout(function() 
   {
      $("#twitter_update_list").css("display", "block");
   }, 500);  

}
else {
$("#twitter_update_list").html("Error");
}
  
}

function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return 'less than a minute ago';
  } else if(delta < 120) {
    return 'about a minute ago';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (120*60)) {
    return 'about an hour ago';
  } else if(delta < (24*60*60)) {
    return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
    return '1 day ago';
  } else {
    return (parseInt(delta / 86400)).toString() + ' days ago';
  }
}





function initBlogStream() {

var page = parseInt(1);
$("a#blog-feed-prev").css("visibility", "hidden");
var numberOfEntries = $("#blogfeed ul#twitter_update_list li");
for (var i=0; i<numberOfEntries.length; i++) {
$(numberOfEntries).eq(i).hide()
}
$(numberOfEntries).eq(page-1).show();

$("#blogfeed").fadeIn("slow");

$("a#blog-feed-next").click(function() {
$("a#blog-feed-prev").css("visibility", "visible");
page++;
if (page > numberOfEntries.length) {
page = numberOfEntries.length;
}

else {
displayPage(page-1);
if (page == numberOfEntries.length) { $(this).css("visibility", "hidden");  }
}
return false;
});

$("a#blog-feed-prev").click(function() {
$("a#blog-feed-next").css("visibility", "visible");
page--;
if (page <= 1) {
page = 1;
$(this).css("visibility", "hidden");;
}
displayPage(page-1);
return false;
});

}

function displayPage(number) {
$("#blogfeed ul li").hide();
$("#blogfeed ul li").eq(number).fadeIn();
}


function initMediaStream() {

  // Global variables

  var to = 0;
  var from = 0;
  var modulusIndex = 0;
  var pages = 0;
  var page = 1;
   
  $("a#image-gallery-slideshow-prev").css("visibility", "hidden");                   
  var location = window.location.href;
  if (location.indexOf("?") > -1) {
  location = location  + "&method=requestflickrjson";
  }
else {
  location = location  + "?method=requestflickrjson";
}



  jQuery.ajax({
    type: "GET",
    url: location,
    dataType: "json",
    cache : "false",    
    success: function(data){   
                
     // alert("Data Length: " + data.items.length);

        $("div.image-gallery-slideshow").css("display", "none");                
                
        var numberOfItems = 0;                               

        if (data.items != null) {
            numberOfItems = data.items.length;
        }
        
        // Calculate how many we can fit on a page. This is dependent on the width of any free space in the container. 
        // Get the container that the div is sitting in.
        
        var containerWidth = $("div.image-gallery-slideshow").parent().width();

        var actualWidth = 0;
        
        // See if there's any other elements taking up space.
        
        var combinedWidth = $("div.image-gallery-slideshow").parent().children();     
                   
        $.each(combinedWidth, function(item) {
            if (this.className != "image-gallery-slideshow")    {
            actualWidth += isNaN(parseInt($(this).css("width"))) ? 0 : parseInt($(this).css("width"));
            actualWidth += isNaN(parseInt($(this).css("margin-right"))) ? 0 : parseInt($(this).css("margin-right"));
            actualWidth += isNaN(parseInt($(this).css("margin-left"))) ? 0 : parseInt($(this).css("margin-left"));         
            }
        });

        var itemWidth = 117;   
  
        if (actualWidth != 0) {
        
        // Calculate the number of DD's we can show per "block"        

        $("div.image-gallery-slideshow").css("width", 944 - 22 - actualWidth + "px" );
        
        }
        
        else {
            $("div.image-gallery-slideshow").css("width", "922px");
        }
        to = modulusIndex = parseInt(Math.ceil(parseInt($("div.image-gallery-slideshow").css("width")) - 22)  / itemWidth);           
       
            if (numberOfItems <= modulusIndex) {
        $("a#image-gallery-slideshow-next").css("visibility", "hidden");   
        }
       

        pages = parseInt(Math.ceil(numberOfItems / modulusIndex));
 
        var widthOfCurrentDisplayingItems = (modulusIndex * itemWidth);
        $("#image-gallery-slideshow").css("width", (parseInt($("div.image-gallery-slideshow").css("width")) - 22) + "px"); // deal with 11px
        
        // Work out the margin required for each one without wrapping               
        
        var marginToFill = Math.floor(parseInt($("#image-gallery-slideshow").css("width"))-parseInt(117 * modulusIndex));
   
        applyMargin = Math.floor(parseInt(marginToFill / (modulusIndex - 1)))        
        
            // Initialisation
       
            $.each(data.items, function(i,item) {        
                      
            if (i < modulusIndex)
                $("#image-gallery-slideshow").append("<a target='_blank'  href='" + item.link + "'><img class='photostream' src='" + item.media.m + "'/></a>");                                                                                                            
            else 
                $("#image-gallery-slideshow").append("<a target='_blank'  href='" + item.link + "'><img class='photostream' style='display:none' src='" + item.media.m + "'/></a>");                                 
            });
          
             for (var o=from; o<to; o++) {
             $("#image-gallery-slideshow img.photostream").eq(o).css("margin-right", applyMargin);
             }
          
            $("#image-gallery-slideshow img.photostream").eq(modulusIndex-1).css("margin-right", "0px");        
                       
        $("div.image-gallery-slideshow").fadeIn();                                        
        
        reBindClicks(); 

           $("a#image-gallery-slideshow-next").click(function() {     
                $("a#image-gallery-slideshow-prev").css("visibility", "visible");
                page++;                                 
                
                if (page > pages) {
                    page = pages;                                                                               
                }        
                
                else {                            
                    from = from + modulusIndex;
                    to = to + modulusIndex;                                  
                    showImageRange($("#image-gallery-slideshow img.photostream"), from, to);                 
                    
                    if (page == pages) {
                        $(this).css("visibility", "hidden"); 
                    }
                }            
return false;                                                                    
           });
           
           $("a#image-gallery-slideshow-prev").click(function() {   
                $("a#image-gallery-slideshow-next").css("visibility", "visible");
                
                page--;
                
                 if (page == 0) {
                    page = 1;
                  
                }
                   else { 
                        
                        from = from - modulusIndex;
                        to = to - modulusIndex;      
       
                    showImageRange($("#image-gallery-slideshow img.photostream"), from, to);                                         
                      
                      if (page == 1) {
                         $(this).css("visibility", "hidden"); 
                      }
                }
return false;
           });                            
                                               
           $("#image-gallery-slideshow img.photostream").hover(
                function () {                               
                   $(this).fadeTo(100, 0.5);
                }, 
                function()
                {
                  $(this).fadeTo(100, 1);
                });
           
    },
    error: function(XMLHttpRequest, textStatus, errorThrown){
//        alert("Error :   " + errorThrown + " " + textStatus);
    }
  });



  function reBindClicks() {

  $("#image-gallery-slideshow a").click(function() {       
       dcsTrk("WT.ac=LF-Ch_flickr_image_clicked");
     }); 

}    

}

function showImageRange(imgref, from, to) {
    imgref.hide();
    for (var t=from; t<to; t++) {
       imgref.eq(t).fadeIn().css("margin-right", applyMargin);    
       if (t==(to-1)) {       
        imgref.eq(t).css("margin-right", "0px");
       }
    }
}
/*
 * jQuery UI 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
jQuery.ui||(function(c){var i=c.fn.remove,d=c.browser.mozilla&&(parseFloat(c.browser.version)<1.9);c.ui={version:"1.7.2",plugin:{add:function(k,l,n){var m=c.ui[k].prototype;for(var j in n){m.plugins[j]=m.plugins[j]||[];m.plugins[j].push([l,n[j]])}},call:function(j,l,k){var n=j.plugins[l];if(!n||!j.element[0].parentNode){return}for(var m=0;m<n.length;m++){if(j.options[n[m][0]]){n[m][1].apply(j.element,k)}}}},contains:function(k,j){return document.compareDocumentPosition?k.compareDocumentPosition(j)&16:k!==j&&k.contains(j)},hasScroll:function(m,k){if(c(m).css("overflow")=="hidden"){return false}var j=(k&&k=="left")?"scrollLeft":"scrollTop",l=false;if(m[j]>0){return true}m[j]=1;l=(m[j]>0);m[j]=0;return l},isOverAxis:function(k,j,l){return(k>j)&&(k<(j+l))},isOver:function(o,k,n,m,j,l){return c.ui.isOverAxis(o,n,j)&&c.ui.isOverAxis(k,m,l)},keyCode:{BACKSPACE:8,CAPS_LOCK:20,COMMA:188,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38}};if(d){var f=c.attr,e=c.fn.removeAttr,h="http://www.w3.org/2005/07/aaa",a=/^aria-/,b=/^wairole:/;c.attr=function(k,j,l){var m=l!==undefined;return(j=="role"?(m?f.call(this,k,j,"wairole:"+l):(f.apply(this,arguments)||"").replace(b,"")):(a.test(j)?(m?k.setAttributeNS(h,j.replace(a,"aaa:"),l):f.call(this,k,j.replace(a,"aaa:"))):f.apply(this,arguments)))};c.fn.removeAttr=function(j){return(a.test(j)?this.each(function(){this.removeAttributeNS(h,j.replace(a,""))}):e.call(this,j))}}c.fn.extend({remove:function(){c("*",this).add(this).each(function(){c(this).triggerHandler("remove")});return i.apply(this,arguments)},enableSelection:function(){return this.attr("unselectable","off").css("MozUserSelect","").unbind("selectstart.ui")},disableSelection:function(){return this.attr("unselectable","on").css("MozUserSelect","none").bind("selectstart.ui",function(){return false})},scrollParent:function(){var j;if((c.browser.msie&&(/(static|relative)/).test(this.css("position")))||(/absolute/).test(this.css("position"))){j=this.parents().filter(function(){return(/(relative|absolute|fixed)/).test(c.curCSS(this,"position",1))&&(/(auto|scroll)/).test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0)}else{j=this.parents().filter(function(){return(/(auto|scroll)/).test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0)}return(/fixed/).test(this.css("position"))||!j.length?c(document):j}});c.extend(c.expr[":"],{data:function(l,k,j){return !!c.data(l,j[3])},focusable:function(k){var l=k.nodeName.toLowerCase(),j=c.attr(k,"tabindex");return(/input|select|textarea|button|object/.test(l)?!k.disabled:"a"==l||"area"==l?k.href||!isNaN(j):!isNaN(j))&&!c(k)["area"==l?"parents":"closest"](":hidden").length},tabbable:function(k){var j=c.attr(k,"tabindex");return(isNaN(j)||j>=0)&&c(k).is(":focusable")}});function g(m,n,o,l){function k(q){var p=c[m][n][q]||[];return(typeof p=="string"?p.split(/,?\s+/):p)}var j=k("getter");if(l.length==1&&typeof l[0]=="string"){j=j.concat(k("getterSetter"))}return(c.inArray(o,j)!=-1)}c.widget=function(k,j){var l=k.split(".")[0];k=k.split(".")[1];c.fn[k]=function(p){var n=(typeof p=="string"),o=Array.prototype.slice.call(arguments,1);if(n&&p.substring(0,1)=="_"){return this}if(n&&g(l,k,p,o)){var m=c.data(this[0],k);return(m?m[p].apply(m,o):undefined)}return this.each(function(){var q=c.data(this,k);(!q&&!n&&c.data(this,k,new c[l][k](this,p))._init());(q&&n&&c.isFunction(q[p])&&q[p].apply(q,o))})};c[l]=c[l]||{};c[l][k]=function(o,n){var m=this;this.namespace=l;this.widgetName=k;this.widgetEventPrefix=c[l][k].eventPrefix||k;this.widgetBaseClass=l+"-"+k;this.options=c.extend({},c.widget.defaults,c[l][k].defaults,c.metadata&&c.metadata.get(o)[k],n);this.element=c(o).bind("setData."+k,function(q,p,r){if(q.target==o){return m._setData(p,r)}}).bind("getData."+k,function(q,p){if(q.target==o){return m._getData(p)}}).bind("remove",function(){return m.destroy()})};c[l][k].prototype=c.extend({},c.widget.prototype,j);c[l][k].getterSetter="option"};c.widget.prototype={_init:function(){},destroy:function(){this.element.removeData(this.widgetName).removeClass(this.widgetBaseClass+"-disabled "+this.namespace+"-state-disabled").removeAttr("aria-disabled")},option:function(l,m){var k=l,j=this;if(typeof l=="string"){if(m===undefined){return this._getData(l)}k={};k[l]=m}c.each(k,function(n,o){j._setData(n,o)})},_getData:function(j){return this.options[j]},_setData:function(j,k){this.options[j]=k;if(j=="disabled"){this.element[k?"addClass":"removeClass"](this.widgetBaseClass+"-disabled "+this.namespace+"-state-disabled").attr("aria-disabled",k)}},enable:function(){this._setData("disabled",false)},disable:function(){this._setData("disabled",true)},_trigger:function(l,m,n){var p=this.options[l],j=(l==this.widgetEventPrefix?l:this.widgetEventPrefix+l);m=c.Event(m);m.type=j;if(m.originalEvent){for(var k=c.event.props.length,o;k;){o=c.event.props[--k];m[o]=m.originalEvent[o]}}this.element.trigger(m,n);return !(c.isFunction(p)&&p.call(this.element[0],m,n)===false||m.isDefaultPrevented())}};c.widget.defaults={disabled:false};c.ui.mouse={_mouseInit:function(){var j=this;this.element.bind("mousedown."+this.widgetName,function(k){return j._mouseDown(k)}).bind("click."+this.widgetName,function(k){if(j._preventClickEvent){j._preventClickEvent=false;k.stopImmediatePropagation();return false}});if(c.browser.msie){this._mouseUnselectable=this.element.attr("unselectable");this.element.attr("unselectable","on")}this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName);(c.browser.msie&&this.element.attr("unselectable",this._mouseUnselectable))},_mouseDown:function(l){l.originalEvent=l.originalEvent||{};if(l.originalEvent.mouseHandled){return}(this._mouseStarted&&this._mouseUp(l));this._mouseDownEvent=l;var k=this,m=(l.which==1),j=(typeof this.options.cancel=="string"?c(l.target).parents().add(l.target).filter(this.options.cancel).length:false);if(!m||j||!this._mouseCapture(l)){return true}this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet){this._mouseDelayTimer=setTimeout(function(){k.mouseDelayMet=true},this.options.delay)}if(this._mouseDistanceMet(l)&&this._mouseDelayMet(l)){this._mouseStarted=(this._mouseStart(l)!==false);if(!this._mouseStarted){l.preventDefault();return true}}this._mouseMoveDelegate=function(n){return k._mouseMove(n)};this._mouseUpDelegate=function(n){return k._mouseUp(n)};c(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);(c.browser.safari||l.preventDefault());l.originalEvent.mouseHandled=true;return true},_mouseMove:function(j){if(c.browser.msie&&!j.button){return this._mouseUp(j)}if(this._mouseStarted){this._mouseDrag(j);return j.preventDefault()}if(this._mouseDistanceMet(j)&&this._mouseDelayMet(j)){this._mouseStarted=(this._mouseStart(this._mouseDownEvent,j)!==false);(this._mouseStarted?this._mouseDrag(j):this._mouseUp(j))}return !this._mouseStarted},_mouseUp:function(j){c(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;this._preventClickEvent=(j.target==this._mouseDownEvent.target);this._mouseStop(j)}return false},_mouseDistanceMet:function(j){return(Math.max(Math.abs(this._mouseDownEvent.pageX-j.pageX),Math.abs(this._mouseDownEvent.pageY-j.pageY))>=this.options.distance)},_mouseDelayMet:function(j){return this.mouseDelayMet},_mouseStart:function(j){},_mouseDrag:function(j){},_mouseStop:function(j){},_mouseCapture:function(j){return true}};c.ui.mouse.defaults={cancel:null,distance:1,delay:0}})(jQuery);;/*
 * jQuery UI Slider 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Slider
 *
 * Depends:
 *	ui.core.js
 */
(function(a){a.widget("ui.slider",a.extend({},a.ui.mouse,{_init:function(){var b=this,c=this.options;this._keySliding=false;this._handleIndex=null;this._detectOrientation();this._mouseInit();this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget ui-widget-content ui-corner-all");this.range=a([]);if(c.range){if(c.range===true){this.range=a("<div></div>");if(!c.values){c.values=[this._valueMin(),this._valueMin()]}if(c.values.length&&c.values.length!=2){c.values=[c.values[0],c.values[0]]}}else{this.range=a("<div></div>")}this.range.appendTo(this.element).addClass("ui-slider-range");if(c.range=="min"||c.range=="max"){this.range.addClass("ui-slider-range-"+c.range)}this.range.addClass("ui-widget-header")}if(a(".ui-slider-handle",this.element).length==0){a('<a href="#"></a>').appendTo(this.element).addClass("ui-slider-handle")}if(c.values&&c.values.length){while(a(".ui-slider-handle",this.element).length<c.values.length){a('<a href="#"></a>').appendTo(this.element).addClass("ui-slider-handle")}}this.handles=a(".ui-slider-handle",this.element).addClass("ui-state-default ui-corner-all");this.handle=this.handles.eq(0);this.handles.add(this.range).filter("a").click(function(d){d.preventDefault()}).hover(function(){if(!c.disabled){a(this).addClass("ui-state-hover")}},function(){a(this).removeClass("ui-state-hover")}).focus(function(){if(!c.disabled){a(".ui-slider .ui-state-focus").removeClass("ui-state-focus");a(this).addClass("ui-state-focus")}else{a(this).blur()}}).blur(function(){a(this).removeClass("ui-state-focus")});this.handles.each(function(d){a(this).data("index.ui-slider-handle",d)});this.handles.keydown(function(i){var f=true;var e=a(this).data("index.ui-slider-handle");if(b.options.disabled){return}switch(i.keyCode){case a.ui.keyCode.HOME:case a.ui.keyCode.END:case a.ui.keyCode.UP:case a.ui.keyCode.RIGHT:case a.ui.keyCode.DOWN:case a.ui.keyCode.LEFT:f=false;if(!b._keySliding){b._keySliding=true;a(this).addClass("ui-state-active");b._start(i,e)}break}var g,d,h=b._step();if(b.options.values&&b.options.values.length){g=d=b.values(e)}else{g=d=b.value()}switch(i.keyCode){case a.ui.keyCode.HOME:d=b._valueMin();break;case a.ui.keyCode.END:d=b._valueMax();break;case a.ui.keyCode.UP:case a.ui.keyCode.RIGHT:if(g==b._valueMax()){return}d=g+h;break;case a.ui.keyCode.DOWN:case a.ui.keyCode.LEFT:if(g==b._valueMin()){return}d=g-h;break}b._slide(i,e,d);return f}).keyup(function(e){var d=a(this).data("index.ui-slider-handle");if(b._keySliding){b._stop(e,d);b._change(e,d);b._keySliding=false;a(this).removeClass("ui-state-active")}});this._refreshValue()},destroy:function(){this.handles.remove();this.range.remove();this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all").removeData("slider").unbind(".slider");this._mouseDestroy()},_mouseCapture:function(d){var e=this.options;if(e.disabled){return false}this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()};this.elementOffset=this.element.offset();var h={x:d.pageX,y:d.pageY};var j=this._normValueFromMouse(h);var c=this._valueMax()-this._valueMin()+1,f;var k=this,i;this.handles.each(function(l){var m=Math.abs(j-k.values(l));if(c>m){c=m;f=a(this);i=l}});if(e.range==true&&this.values(1)==e.min){f=a(this.handles[++i])}this._start(d,i);k._handleIndex=i;f.addClass("ui-state-active").focus();var g=f.offset();var b=!a(d.target).parents().andSelf().is(".ui-slider-handle");this._clickOffset=b?{left:0,top:0}:{left:d.pageX-g.left-(f.width()/2),top:d.pageY-g.top-(f.height()/2)-(parseInt(f.css("borderTopWidth"),10)||0)-(parseInt(f.css("borderBottomWidth"),10)||0)+(parseInt(f.css("marginTop"),10)||0)};j=this._normValueFromMouse(h);this._slide(d,i,j);return true},_mouseStart:function(b){return true},_mouseDrag:function(d){var b={x:d.pageX,y:d.pageY};var c=this._normValueFromMouse(b);this._slide(d,this._handleIndex,c);return false},_mouseStop:function(b){this.handles.removeClass("ui-state-active");this._stop(b,this._handleIndex);this._change(b,this._handleIndex);this._handleIndex=null;this._clickOffset=null;return false},_detectOrientation:function(){this.orientation=this.options.orientation=="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(d){var c,h;if("horizontal"==this.orientation){c=this.elementSize.width;h=d.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)}else{c=this.elementSize.height;h=d.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)}var f=(h/c);if(f>1){f=1}if(f<0){f=0}if("vertical"==this.orientation){f=1-f}var e=this._valueMax()-this._valueMin(),i=f*e,b=i%this.options.step,g=this._valueMin()+i-b;if(b>(this.options.step/2)){g+=this.options.step}return parseFloat(g.toFixed(5))},_start:function(d,c){var b={handle:this.handles[c],value:this.value()};if(this.options.values&&this.options.values.length){b.value=this.values(c);b.values=this.values()}this._trigger("start",d,b)},_slide:function(f,e,d){var g=this.handles[e];if(this.options.values&&this.options.values.length){var b=this.values(e?0:1);if((this.options.values.length==2&&this.options.range===true)&&((e==0&&d>b)||(e==1&&d<b))){d=b}if(d!=this.values(e)){var c=this.values();c[e]=d;var h=this._trigger("slide",f,{handle:this.handles[e],value:d,values:c});var b=this.values(e?0:1);if(h!==false){this.values(e,d,(f.type=="mousedown"&&this.options.animate),true)}}}else{if(d!=this.value()){var h=this._trigger("slide",f,{handle:this.handles[e],value:d});if(h!==false){this._setData("value",d,(f.type=="mousedown"&&this.options.animate))}}}},_stop:function(d,c){var b={handle:this.handles[c],value:this.value()};if(this.options.values&&this.options.values.length){b.value=this.values(c);b.values=this.values()}this._trigger("stop",d,b)},_change:function(d,c){var b={handle:this.handles[c],value:this.value()};if(this.options.values&&this.options.values.length){b.value=this.values(c);b.values=this.values()}this._trigger("change",d,b)},value:function(b){if(arguments.length){this._setData("value",b);this._change(null,0)}return this._value()},values:function(b,e,c,d){if(arguments.length>1){this.options.values[b]=e;this._refreshValue(c);if(!d){this._change(null,b)}}if(arguments.length){if(this.options.values&&this.options.values.length){return this._values(b)}else{return this.value()}}else{return this._values()}},_setData:function(b,d,c){a.widget.prototype._setData.apply(this,arguments);switch(b){case"disabled":if(d){this.handles.filter(".ui-state-focus").blur();this.handles.removeClass("ui-state-hover");this.handles.attr("disabled","disabled")}else{this.handles.removeAttr("disabled")}case"orientation":this._detectOrientation();this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation);this._refreshValue(c);break;case"value":this._refreshValue(c);break}},_step:function(){var b=this.options.step;return b},_value:function(){var b=this.options.value;if(b<this._valueMin()){b=this._valueMin()}if(b>this._valueMax()){b=this._valueMax()}return b},_values:function(b){if(arguments.length){var c=this.options.values[b];if(c<this._valueMin()){c=this._valueMin()}if(c>this._valueMax()){c=this._valueMax()}return c}else{return this.options.values}},_valueMin:function(){var b=this.options.min;return b},_valueMax:function(){var b=this.options.max;return b},_refreshValue:function(c){var f=this.options.range,d=this.options,l=this;if(this.options.values&&this.options.values.length){var i,h;this.handles.each(function(p,n){var o=(l.values(p)-l._valueMin())/(l._valueMax()-l._valueMin())*100;var m={};m[l.orientation=="horizontal"?"left":"bottom"]=o+"%";a(this).stop(1,1)[c?"animate":"css"](m,d.animate);if(l.options.range===true){if(l.orientation=="horizontal"){(p==0)&&l.range.stop(1,1)[c?"animate":"css"]({left:o+"%"},d.animate);(p==1)&&l.range[c?"animate":"css"]({width:(o-lastValPercent)+"%"},{queue:false,duration:d.animate})}else{(p==0)&&l.range.stop(1,1)[c?"animate":"css"]({bottom:(o)+"%"},d.animate);(p==1)&&l.range[c?"animate":"css"]({height:(o-lastValPercent)+"%"},{queue:false,duration:d.animate})}}lastValPercent=o})}else{var j=this.value(),g=this._valueMin(),k=this._valueMax(),e=k!=g?(j-g)/(k-g)*100:0;var b={};b[l.orientation=="horizontal"?"left":"bottom"]=e+"%";this.handle.stop(1,1)[c?"animate":"css"](b,d.animate);(f=="min")&&(this.orientation=="horizontal")&&this.range.stop(1,1)[c?"animate":"css"]({width:e+"%"},d.animate);(f=="max")&&(this.orientation=="horizontal")&&this.range[c?"animate":"css"]({width:(100-e)+"%"},{queue:false,duration:d.animate});(f=="min")&&(this.orientation=="vertical")&&this.range.stop(1,1)[c?"animate":"css"]({height:e+"%"},d.animate);(f=="max")&&(this.orientation=="vertical")&&this.range[c?"animate":"css"]({height:(100-e)+"%"},{queue:false,duration:d.animate})}}}));a.extend(a.ui.slider,{getter:"value values",version:"1.7.2",eventPrefix:"slide",defaults:{animate:false,delay:0,distance:0,max:100,min:0,orientation:"horizontal",range:false,step:1,value:0,values:null}})})(jQuery);;/*
 * jQuery UI Tabs 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Tabs
 *
 * Depends:
 *	ui.core.js
 */
(function(a){a.widget("ui.tabs",{_init:function(){if(this.options.deselectable!==undefined){this.options.collapsible=this.options.deselectable}this._tabify(true)},_setData:function(b,c){if(b=="selected"){if(this.options.collapsible&&c==this.options.selected){return}this.select(c)}else{this.options[b]=c;if(b=="deselectable"){this.options.collapsible=c}this._tabify()}},_tabId:function(b){return b.title&&b.title.replace(/\s/g,"_").replace(/[^A-Za-z0-9\-_:\.]/g,"")||this.options.idPrefix+a.data(b)},_sanitizeSelector:function(b){return b.replace(/:/g,"\\:")},_cookie:function(){var b=this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+a.data(this.list[0]));return a.cookie.apply(null,[b].concat(a.makeArray(arguments)))},_ui:function(c,b){return{tab:c,panel:b,index:this.anchors.index(c)}},_cleanup:function(){this.lis.filter(".ui-state-processing").removeClass("ui-state-processing").find("span:data(label.tabs)").each(function(){var b=a(this);b.html(b.data("label.tabs")).removeData("label.tabs")})},_tabify:function(n){this.list=this.element.children("ul:first");this.lis=a("li:has(a[href])",this.list);this.anchors=this.lis.map(function(){return a("a",this)[0]});this.panels=a([]);var p=this,d=this.options;var c=/^#.+/;this.anchors.each(function(r,o){var q=a(o).attr("href");var s=q.split("#")[0],u;if(s&&(s===location.toString().split("#")[0]||(u=a("base")[0])&&s===u.href)){q=o.hash;o.href=q}if(c.test(q)){p.panels=p.panels.add(p._sanitizeSelector(q))}else{if(q!="#"){a.data(o,"href.tabs",q);a.data(o,"load.tabs",q.replace(/#.*$/,""));var w=p._tabId(o);o.href="#"+w;var v=a("#"+w);if(!v.length){v=a(d.panelTemplate).attr("id",w).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").insertAfter(p.panels[r-1]||p.list);v.data("destroy.tabs",true)}p.panels=p.panels.add(v)}else{d.disabled.push(r)}}});if(n){this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all");this.list.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.lis.addClass("ui-state-default ui-corner-top");this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom");if(d.selected===undefined){if(location.hash){this.anchors.each(function(q,o){if(o.hash==location.hash){d.selected=q;return false}})}if(typeof d.selected!="number"&&d.cookie){d.selected=parseInt(p._cookie(),10)}if(typeof d.selected!="number"&&this.lis.filter(".ui-tabs-selected").length){d.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"))}d.selected=d.selected||0}else{if(d.selected===null){d.selected=-1}}d.selected=((d.selected>=0&&this.anchors[d.selected])||d.selected<0)?d.selected:0;d.disabled=a.unique(d.disabled.concat(a.map(this.lis.filter(".ui-state-disabled"),function(q,o){return p.lis.index(q)}))).sort();if(a.inArray(d.selected,d.disabled)!=-1){d.disabled.splice(a.inArray(d.selected,d.disabled),1)}this.panels.addClass("ui-tabs-hide");this.lis.removeClass("ui-tabs-selected ui-state-active");if(d.selected>=0&&this.anchors.length){this.panels.eq(d.selected).removeClass("ui-tabs-hide");this.lis.eq(d.selected).addClass("ui-tabs-selected ui-state-active");p.element.queue("tabs",function(){p._trigger("show",null,p._ui(p.anchors[d.selected],p.panels[d.selected]))});this.load(d.selected)}a(window).bind("unload",function(){p.lis.add(p.anchors).unbind(".tabs");p.lis=p.anchors=p.panels=null})}else{d.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"))}this.element[d.collapsible?"addClass":"removeClass"]("ui-tabs-collapsible");if(d.cookie){this._cookie(d.selected,d.cookie)}for(var g=0,m;(m=this.lis[g]);g++){a(m)[a.inArray(g,d.disabled)!=-1&&!a(m).hasClass("ui-tabs-selected")?"addClass":"removeClass"]("ui-state-disabled")}if(d.cache===false){this.anchors.removeData("cache.tabs")}this.lis.add(this.anchors).unbind(".tabs");if(d.event!="mouseover"){var f=function(o,i){if(i.is(":not(.ui-state-disabled)")){i.addClass("ui-state-"+o)}};var j=function(o,i){i.removeClass("ui-state-"+o)};this.lis.bind("mouseover.tabs",function(){f("hover",a(this))});this.lis.bind("mouseout.tabs",function(){j("hover",a(this))});this.anchors.bind("focus.tabs",function(){f("focus",a(this).closest("li"))});this.anchors.bind("blur.tabs",function(){j("focus",a(this).closest("li"))})}var b,h;if(d.fx){if(a.isArray(d.fx)){b=d.fx[0];h=d.fx[1]}else{b=h=d.fx}}function e(i,o){i.css({display:""});if(a.browser.msie&&o.opacity){i[0].style.removeAttribute("filter")}}var k=h?function(i,o){a(i).closest("li").removeClass("ui-state-default").addClass("ui-tabs-selected ui-state-active");o.hide().removeClass("ui-tabs-hide").animate(h,h.duration||"normal",function(){e(o,h);p._trigger("show",null,p._ui(i,o[0]))})}:function(i,o){a(i).closest("li").removeClass("ui-state-default").addClass("ui-tabs-selected ui-state-active");o.removeClass("ui-tabs-hide");p._trigger("show",null,p._ui(i,o[0]))};var l=b?function(o,i){i.animate(b,b.duration||"normal",function(){p.lis.removeClass("ui-tabs-selected ui-state-active").addClass("ui-state-default");i.addClass("ui-tabs-hide");e(i,b);p.element.dequeue("tabs")})}:function(o,i,q){p.lis.removeClass("ui-tabs-selected ui-state-active").addClass("ui-state-default");i.addClass("ui-tabs-hide");p.element.dequeue("tabs")};this.anchors.bind(d.event+".tabs",function(){var o=this,r=a(this).closest("li"),i=p.panels.filter(":not(.ui-tabs-hide)"),q=a(p._sanitizeSelector(this.hash));if((r.hasClass("ui-tabs-selected")&&!d.collapsible)||r.hasClass("ui-state-disabled")||r.hasClass("ui-state-processing")||p._trigger("select",null,p._ui(this,q[0]))===false){this.blur();return false}d.selected=p.anchors.index(this);p.abort();if(d.collapsible){if(r.hasClass("ui-tabs-selected")){d.selected=-1;if(d.cookie){p._cookie(d.selected,d.cookie)}p.element.queue("tabs",function(){l(o,i)}).dequeue("tabs");this.blur();return false}else{if(!i.length){if(d.cookie){p._cookie(d.selected,d.cookie)}p.element.queue("tabs",function(){k(o,q)});p.load(p.anchors.index(this));this.blur();return false}}}if(d.cookie){p._cookie(d.selected,d.cookie)}if(q.length){if(i.length){p.element.queue("tabs",function(){l(o,i)})}p.element.queue("tabs",function(){k(o,q)});p.load(p.anchors.index(this))}else{throw"jQuery UI Tabs: Mismatching fragment identifier."}if(a.browser.msie){this.blur()}});this.anchors.bind("click.tabs",function(){return false})},destroy:function(){var b=this.options;this.abort();this.element.unbind(".tabs").removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible").removeData("tabs");this.list.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.anchors.each(function(){var c=a.data(this,"href.tabs");if(c){this.href=c}var d=a(this).unbind(".tabs");a.each(["href","load","cache"],function(e,f){d.removeData(f+".tabs")})});this.lis.unbind(".tabs").add(this.panels).each(function(){if(a.data(this,"destroy.tabs")){a(this).remove()}else{a(this).removeClass(["ui-state-default","ui-corner-top","ui-tabs-selected","ui-state-active","ui-state-hover","ui-state-focus","ui-state-disabled","ui-tabs-panel","ui-widget-content","ui-corner-bottom","ui-tabs-hide"].join(" "))}});if(b.cookie){this._cookie(null,b.cookie)}},add:function(e,d,c){if(c===undefined){c=this.anchors.length}var b=this,g=this.options,i=a(g.tabTemplate.replace(/#\{href\}/g,e).replace(/#\{label\}/g,d)),h=!e.indexOf("#")?e.replace("#",""):this._tabId(a("a",i)[0]);i.addClass("ui-state-default ui-corner-top").data("destroy.tabs",true);var f=a("#"+h);if(!f.length){f=a(g.panelTemplate).attr("id",h).data("destroy.tabs",true)}f.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide");if(c>=this.lis.length){i.appendTo(this.list);f.appendTo(this.list[0].parentNode)}else{i.insertBefore(this.lis[c]);f.insertBefore(this.panels[c])}g.disabled=a.map(g.disabled,function(k,j){return k>=c?++k:k});this._tabify();if(this.anchors.length==1){i.addClass("ui-tabs-selected ui-state-active");f.removeClass("ui-tabs-hide");this.element.queue("tabs",function(){b._trigger("show",null,b._ui(b.anchors[0],b.panels[0]))});this.load(0)}this._trigger("add",null,this._ui(this.anchors[c],this.panels[c]))},remove:function(b){var d=this.options,e=this.lis.eq(b).remove(),c=this.panels.eq(b).remove();if(e.hasClass("ui-tabs-selected")&&this.anchors.length>1){this.select(b+(b+1<this.anchors.length?1:-1))}d.disabled=a.map(a.grep(d.disabled,function(g,f){return g!=b}),function(g,f){return g>=b?--g:g});this._tabify();this._trigger("remove",null,this._ui(e.find("a")[0],c[0]))},enable:function(b){var c=this.options;if(a.inArray(b,c.disabled)==-1){return}this.lis.eq(b).removeClass("ui-state-disabled");c.disabled=a.grep(c.disabled,function(e,d){return e!=b});this._trigger("enable",null,this._ui(this.anchors[b],this.panels[b]))},disable:function(c){var b=this,d=this.options;if(c!=d.selected){this.lis.eq(c).addClass("ui-state-disabled");d.disabled.push(c);d.disabled.sort();this._trigger("disable",null,this._ui(this.anchors[c],this.panels[c]))}},select:function(b){if(typeof b=="string"){b=this.anchors.index(this.anchors.filter("[href$="+b+"]"))}else{if(b===null){b=-1}}if(b==-1&&this.options.collapsible){b=this.options.selected}this.anchors.eq(b).trigger(this.options.event+".tabs")},load:function(e){var c=this,g=this.options,b=this.anchors.eq(e)[0],d=a.data(b,"load.tabs");this.abort();if(!d||this.element.queue("tabs").length!==0&&a.data(b,"cache.tabs")){this.element.dequeue("tabs");return}this.lis.eq(e).addClass("ui-state-processing");if(g.spinner){var f=a("span",b);f.data("label.tabs",f.html()).html(g.spinner)}this.xhr=a.ajax(a.extend({},g.ajaxOptions,{url:d,success:function(i,h){a(c._sanitizeSelector(b.hash)).html(i);c._cleanup();if(g.cache){a.data(b,"cache.tabs",true)}c._trigger("load",null,c._ui(c.anchors[e],c.panels[e]));try{g.ajaxOptions.success(i,h)}catch(j){}c.element.dequeue("tabs")}}))},abort:function(){this.element.queue([]);this.panels.stop(false,true);if(this.xhr){this.xhr.abort();delete this.xhr}this._cleanup()},url:function(c,b){this.anchors.eq(c).removeData("cache.tabs").data("load.tabs",b)},length:function(){return this.anchors.length}});a.extend(a.ui.tabs,{version:"1.7.2",getter:"length",defaults:{ajaxOptions:null,cache:false,cookie:null,collapsible:false,disabled:[],event:"click",fx:null,idPrefix:"ui-tabs-",panelTemplate:"<div></div>",spinner:"<em>Loading&#8230;</em>",tabTemplate:'<li><a href="#{href}"><span>#{label}</span></a></li>'}});a.extend(a.ui.tabs.prototype,{rotation:null,rotate:function(d,f){var b=this,g=this.options;var c=b._rotate||(b._rotate=function(h){clearTimeout(b.rotation);b.rotation=setTimeout(function(){var i=g.selected;b.select(++i<b.anchors.length?i:0)},d);if(h){h.stopPropagation()}});var e=b._unrotate||(b._unrotate=!f?function(h){if(h.clientX){b.rotate(null)}}:function(h){t=g.selected;c()});if(d){this.element.bind("tabsshow",c);this.anchors.bind(g.event+".tabs",e);c()}else{clearTimeout(b.rotation);this.element.unbind("tabsshow",c);this.anchors.unbind(g.event+".tabs",e);delete this._rotate;delete this._unrotate}}})})(jQuery);;
$(document).ready(function(){
    var index = 1;
    $("div.frmPage").each(function()
    { 
        $(this).append("<meta name='WT.si_x' content='"+index+"' />");
        index++;
        if(this.id.indexOf("1") > 0)
            $(this).show();
        else
            $(this).hide();       
    });
});

function frmNxtButtonClick(pagenumber)
{
    var tID = '#frmPage'+pagenumber;
    var tNxtID = '#frmPage' + (parseInt(pagenumber)+1);

    if(Validate(tID))
    {
        $(tID).hide();
        $(tNxtID).show();
    }
}

function frmPrvButtonClick(pagenumber)
{
    if(pagenumber != '1')
    {
        var tID = '#frmPage'+pagenumber;
        var tNxtID = '#frmPage' + (parseInt(pagenumber)-1);

        $(tID).hide();
        $(tNxtID).show();
    }
}

function ValidateForm()
{
    var formValid = true;
    $("div.frmPage").each(function()
    { 
      formValid = Validate("#"+this.id);
      if(!formValid)
        return formValid;   
    });
    return formValid;
}

function Validate(pageID)
{
    //LOCAL VARIABLE
    var pagevalid = true;
    
    //LOOP OVER FIELDS ON CURRENT PAGE
    $(pageID).find("div.frmFieldContainer").each(function()
    {  
        //LOCAL VARIABLES
        var fieldPopulated = true;
        var fieldValid = true;
      
        //IF FIELD IS TEXTBOX AND VALIDATE 
        if($(this).find("input[type=text]").length > 0)
        {
            //TEST FIELD MANDATORY
            if($(this).find(".frmFieldMandatoryText").length > 0)
            {
                fieldPopulated = ValidateTextBoxInputPopulated($(this).find("input[type=text]")[0]);
            }
            
            fieldValid = ValidateTextBoxInputValue($(this).find("input[type=text]")[0], $(this).find(".frmFieldRegEx").text());   
        }
        
        //IF FIELD IS RADIO COLLECTION AND VALIDATE
        else if($(this).find("input[type=radio]").length > 0)
        {
             //TEST FIELD MANDATORY
            if($(this).find(".frmFieldMandatoryText").length > 0)
            {
                fieldPopulated = ValidateRadioInputPopulated($(this).find("input[type=radio]"));  
            }
        }
        
        //IF FIELD IS DROPDOWNLIST AND VALIDATE
        else if($(this).find("select").length > 0)
        {       
            //TEST FIELD MANDATORY
            if($(this).find(".frmFieldMandatoryText").length > 0)
            {
                fieldPopulated = ValidateTextBoxInputPopulated($(this).find("select"));  
            }
        } 
        
        //IF FIELD IS CHECKBOX COLLECTION AND VALIDATE
        else if($(this).find("input[type=checkbox]").length > 0)
        {
            //TEST FIELD MANDATORY
            if($(this).find(".frmFieldMandatoryText").length > 0)
            {
                fieldPopulated = ValidateCheckBoxInputPopulated($(this).find("input[type=checkbox]"));  
            }
        }
                
        //CALL TO DISPLAY FORM VALIDATION
        DisplayFieldValidationMessages(this, fieldPopulated, fieldValid);
        
        //SET PAGE VALID FLAG
        if(fieldPopulated && fieldValid)
        {
         
        }
        else
        {
            pagevalid = false;
        }
    }); 

    return pagevalid;
}

function DisplayFieldValidationMessages(inputObj, pFieldPopulated, pFieldValid)
{
    var input = $(inputObj).find("input")[0];
   // alert('id: ' + $(input).attr('id') + ' Populated: ' + pFieldPopulated + ' Valid: ' + pFieldValid + ' Value: ' + $(input).val());
    if(pFieldPopulated)
    {
        $(inputObj).find(".frmFieldMandatoryText").hide();
        if(!pFieldValid)
        {
            //alert('in if');
            $(inputObj).find(".frmFieldValidationText").show();     
            $(inputObj).find(".frmFieldMandatoryText").hide();
        }
        else
        {
            $(inputObj).find(".frmFieldValidationText").hide();     
            $(inputObj).find(".frmFieldMandatoryText").hide();
        }
    }
    else
    {
        $(inputObj).find(".frmFieldMandatoryText").show();
        $(inputObj).find(".frmFieldValidationText").hide(); 
    }
}

function ValidateTextBoxInputPopulated(inputObj)
{
   return $(inputObj).val() != "";
}

function ValidateTextBoxInputValue(inputObj, regex)
{
    if($(inputObj).val() != "")
    {
        var re = new RegExp(regex);
        return re.test($(inputObj).val());
    }
    else
    {
        return true;
    }
}

function ValidateRadioInputPopulated(inputObj)
{
    return $(inputObj).is(":checked");
}

function ValidateCheckBoxInputPopulated(inputObj)
{
    return $(inputObj).is(":checked");    
}
//
// create closure
//
(function($) {
  //
  // plugin definition
  //
  $.fn.greyscale = function() {
	generate(this);
	//if (window.console) { console.log(rolloverColours); console.log(unselectedColours);}
	
	// iterate and reformat each matched element
	return this.each(function(i) {
	  $this = $(this);
	  $this.css("background-color", unselectedColours[i]);
	  $this.hover(function() {
		$(this).css("background-color", rolloverColours[i]);
	  }, function() {
		$(this).css("background-color", unselectedColours[i]);
	  });
	});
  };

  var unselectedColours = [];
  var rolloverColours = [];
  function generate($obj) 
  {
	var items = $obj.size(), increment = 16, color = 105; rollover = color + (increment * 2);
	for (var i = 0; i < items; ++i)
	{	   
		unselectedColours.push(RGB2Color(color,color,color));		
		rolloverColours.push(RGB2Color(rollover,rollover,rollover));
				
		rollover -= increment;
		color -= increment;
	}	
  };
  function RGB2Color(r,g,b) { return '#' + byte2Hex(r) + byte2Hex(g) + byte2Hex(b);}			  
  function byte2Hex(n) { var nybHexString = "0123456789ABCDEF"; return String(nybHexString.substr((n >> 4) & 0x0F,1)) + nybHexString.substr(n & 0x0F,1);}

//
// end of closure
//
})(jQuery);
var badBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
var ie = (/MSIE ((5\.5)|6|7)/.test(navigator.userAgent) && navigator.platform == "Win32");
var opera = $.browser.opera;
var windowTitle = document.title;

function hideWindowedElements() {
    try {
        Lfl.onCentralFrameClose();
        Lfl.pauseSim(); //the above function will resume it even if QL didn't pause it
    }
    catch(err) { //alert('Unable to access the Lfl context, the onCentralFrameClose() function or the pauseSim() function');
    }
    finally {
        if (badBrowser) {
            $("#map2", top.document).css({margin:"0 0 0 -3000px"});    
        }
        else
        {   $("#map2", top.document).css({margin:"0 0 0 3000px"});    
        }
    }

    if (badBrowser) {
        $("select").css({visibility:"hidden"});
    }
}

function showWindowedElements() {
    $("#map2", top.document).css({margin:"0 0 0 0"});

    if (badBrowser) {
        $("select").css({visibility:"visible"});
    }
}

/*QuickLinks*/
function quicklinks_init()
{
        function showPage(pagenumber) {
        $('div#quicklinks div.links').each(
    
            function(index) {
                $(this).hide();                    
            });
                
            $('div#quicklinks div.links').eq(pagenumber-1).fadeIn();  
    
            if (currentPage == 1) {
                $("a#pagerNext").css("visibility", "visible");
                $("a#pagerPrevious").css("visibility", "hidden");
            }       
            else if (currentPage == maximumPages) {
                $("a#pagerNext").css("visibility", "hidden");
                $("a#pagerPrevious").css("visibility", "visible");
            }
            else {
                 $("a#pagerNext").css("visibility", "visible");
                 $("a#pagerPrevious").css("visibility", "visible");
            }
        }

    if ($('a.quicklinks').length)
    {
        //move the quick links div to below the button
        var iPos = $('a.quicklinks').position().top + $('a.quicklinks').height() + 10;
        $('div#quicklinks').css("top", iPos);
    
        var currentPage = 1;
        var maximumPages = $('div#quicklinks div.links').length;

        if (maximumPages > 1) {
            showPage(1); // init     
        }
        else {
            $("a#pagerPrevious").hide();
            $("a#pagerNext").hide();
        }
        
        $("a#pagerPrevious").click(function() {    
            currentPage--;
            if (currentPage >= 1)  { 
                showPage(currentPage);
            }
            else {
                currentPage = 1;
            }      
        });
    
        $("a#pagerNext").click(function() {    
            currentPage++;
            if (currentPage <= maximumPages)  { 
                showPage(currentPage);
            }
            else {
                currentPage = maximumPages;
            } 
        });
    
    
        $("li#quicklinkscontainer a.quicklinks").hover(
        function ()
        {			
	    hideWindowedElements();
			
		var height = $("div#header").height();

		$("div#quicklinks").css("border-bottom","11px solid #fff");
		$("li#quicklinkscontainer a.quicklinks").css("padding-bottom","14px");
		$("div#header").height(height);
		$("div#quicklinks").show();
		$("div#quicklinks").animate({opacity: 1}, 0, 'swing');
		$("li#quicklinkscontainer").css("background-color","#5C5F62");
			
		$("div#quicklinks div.top").show();
		$("div#quicklinks div.bottom").show();
			
	                //first get height from css
 	                var iBottomHeight = $("div#quicklinks div.bottom").height();

                                //get the tallest bottom div
		var iTallest = $("div#quicklinks div.bottom div.left").height()
		if ($("div#quicklinks div.bottom div.right").height() > iTallest){
		    iTallest = $("div#quicklinks div.bottom div.right").height() 
		}

                            //get the headers height and add all margins
                            var iHeader = $("div#quicklinks div.bottom div.quicklinks-header").height() + 55;

                            //is bottom div taller than css declaration		
		var iBottomHeightCalc = iHeader + iTallest;
		if (iBottomHeightCalc > iBottomHeight){
		    iBottomHeight = iBottomHeightCalc 
		}

		//set height
		var qlheight = $("div#quicklinks div.top").height() + iBottomHeight;  	
		$("div#quicklinks").animate({height: qlheight}, 500, 'swing');
	
	            if(typeof(SWFReplace) == 'function') {   
			SWFReplace();        		
	            }

        },function(){}); 
           
        
        $("li#quicklinkscontainer").hoverIntent(
        function(){},		
        function ()
        {          
            // Make sure that you updated thickbox.js if you edit this code. 
            // They both contain coding to hide the quick links 
            //Comment these lins to make quicklinks stay on (for testing)
		$("div#quicklinks div.top").hide();
		$("div#quicklinks div.bottom").hide();
		$("div#quicklinks").animate({height: 0}, 500, 'swing', function(){ showWindowedElements() });
		$("div#quicklinks").animate({opacity: 0}, 0, 'swing');
		$("div#quicklinks").css("border-bottom","none");
		$("li#quicklinkscontainer a.quicklinks").css("padding-bottom","0px");
		    
	    var height = $("div#header").height();
		$("div#header").height(height);

        });  
    }
}  /* end quicklinks_init()*/
 



/* MODEL LINKS JS */

//on page load (as soon as its ready) call JT_init
$(document).ready(JT_init);

function JT_init(){
            $("ul#modelmenu li.series")
            .mouseover(function(){$(this).css({"background-color":"#5C5F62"});})
            .mouseout(function(){$(this).css({"background-color":"transparent"}); })
            .hoverIntent(
                function()
                { 
                    hideWindowedElements();
  	    $(this).css({"background-color":"#5C5F62"});
                    JT_show(this, $(this).find(".model").attr("alt"),$(this).find(".model").get(0).id,$(this).find(".model").attr("alt"))
                }
                ,
                function()
                {
                    showWindowedElements();
                    $(this).css({"background-color":"transparent"});
                    $('#JT').remove()

                    if (ie && document.title.indexOf("#") > -1 && location.href.indexOf("range") > -1) {
                        document.title = windowTitle;
                    }
                }
            )
            if (ie) { $("ul#modelmenu li.series").css({"padding":"7px 0 0"}); }
            if (opera && $('body').css("direction") == "rtl") { $('body').css({"direction": "ltr"}); $('div#container').css({"direction": "rtl"}); }
                $("ul#modelmenu li.series .model").click(function () {return false;})         	
 }

function JT_show(component, url,linkId,title)
{
	if(title == false)title="&nbsp;";
	var de = document.documentElement;
	var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var hasArea = w - getAbsoluteLeft(linkId);
	var clickElementy = getAbsoluteTop(linkId) -127; //set y position
	
	var queryString = url.replace(/^[^\?]+\??/,'');
	var params = parseQuery( queryString );

	//JPrimmer: No width is ever passed to the modellinks.ashx
	if(params['width'] === undefined){params['width'] = 250};
	if(params['link'] !== undefined){
	$('#' + linkId).bind('click',function(){window.location = params['link']});
	$('#' + linkId).css('cursor','pointer');
	}
	
	//JPrimmer: Removed the setting of the Left' and 'Width' style, we need to set this in the css instead (for RTL sites e.g. Israel)	
	if(hasArea>((params['width']*1)+75)){

	    //$(component).append("<div id='JT' style='width:"+params['width']*1+"px'><div id='JT_copy'><div class='JT_loader'><div></div></div>");//right side
		$(component).append("<div id='JT'><div id='JT_copy'><div class='JT_loader'><div></div></div>");//right side
		//var arrowOffset = getElementWidth(linkId);
		//var clickElementx = -150;//getAbsoluteLeft(linkId) -500;// + arrowOffset; //set x position
		$('#JT').css({top: clickElementy+"px"});
	}
	else{
	    //$(component).append("<div id='JT' style='width:"+params['width']*1+"px'><div id='JT_arrow_right' style='left:"+((params['width']*1)+1)+"px'></div><div id='JT_close_right'>"+title+"</div><div id='JT_copy'><div class='JT_loader'><div></div></div>");//left side
		$(component).append("<div id='JT'><div id='JT_arrow_right'></div><div id='JT_close_right'>"+title+"</div><div id='JT_copy'><div class='JT_loader'><div></div></div>");//left side
		var clickElementx = getAbsoluteLeft(linkId) -0;// - ((params['width']*1) + 15); //set x position
	    $('#JT').css({left: clickElementx+"px", top: clickElementy+"px"});
	}
	
   if (badBrowser) {
    $('#JT_copy').load(url, null, 
				function() 
				{       
     //$(component).css("background","#5C5F62 url()");
				});
			}
			else if (opera)
			{
			    var leftval = $('#JT').css("left");
			  
			    $('#JT').css({left:-5000});
			    $('#JT_copy').load(url, null, 
				function() 
				{ 
					var t;
					clearTimeout(t) 
				    t = setTimeout(function() 
					{
						$('#JT').css({left:leftval});
					}, 250);  
				
				   
				});
			}
			else
			{
	
	

	
			$('#JT_copy').load(url, null, 
				function() 
				{       
					var t;
					clearTimeout(t) 
					
					var height = $('ul.model').height()+ 22;
						
						//HIDE AND FADE TO ENABLE ANIMATION
						$('#modelmenuwrapper').hide(); 
						$('#modelmenuwrapper').fadeTo(1,0);
						
						$('div.models').hide();
						$('div.models').fadeTo(1,0);
						
						//ANIMATE SLIDE
						$('#modelmenuwrapper').animate({ opacity: 1, height: height}, 300, 'swing');
								
								//FADE IN CONTENT
								t = setTimeout(function() 
								{
									$('div.models').show();
									$('div.models').fadeTo(300,1);
								}, 500);           
						});
			}
}


function getElementWidth(objectId) {
	x = document.getElementById(objectId);
	return x.offsetWidth;
}

function getAbsoluteLeft(objectId) {
	// Get an object left position from the upper left viewport corner
	o = document.getElementById(objectId)
	oLeft = o.offsetLeft            // Get left position from the parent object
	while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oLeft += oParent.offsetLeft // Add parent left position
		o = oParent
	}
	return oLeft
}

function getAbsoluteTop(objectId) {
	// Get an object top position from the upper left viewport corner
	o = document.getElementById(objectId)
	oTop = o.offsetTop            // Get top position from the parent object
	while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent  // Get parent object reference
		oTop += oParent.offsetTop // Add parent top position
		o = oParent
	}
	return oTop
}

function parseQuery ( query ) {
   var Params = new Object ();
   if ( ! query ) return Params; // return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) continue;
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function blockEvents(evt) {
              if(evt.target){
              evt.preventDefault();
              }else{
              evt.returnValue = false;
              }
}

(function($) {
	$.fn.hoverIntent = function(f,g) {
		// default configuration options
		var cfg = {
			sensitivity: 225,
			interval: 100,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
			var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
			while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
			if ( p == this ) { return false; }

			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// else e.type == "onmouseover"
			if (e.type == "mouseover") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "onmouseout"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
return this.mouseover(handleHover).mouseout(handleHover);
	};
})(jQuery);
// math3d.js
/*
Copyright 2008 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Some Javascript math utilities.
//
// Exports V3 (3-vector utilities), M33 (3x3 matrix utilities)

// NOTE: This will be refactored in a more Object
// Oriented style, so don't get attached to this syntax!

// 3D vector functions.
V3 = {
  EARTH_RADIUS: 6378100,

  dup: function(a) {
    return [a[0], a[1], a[2]];
  },

  toString: function(a) {
    return "[" + a[0] + ", " + a[1] + ", " + a[2] + "]";
  },

  nearlyEqual: function(a, b, tolerance) {
    if (!tolerance) {
      tolerance = 1e-6;
    }
    return Math.abs(a[0] - b[0]) <= tolerance
      && Math.abs(a[1] - b[1]) <= tolerance
      && Math.abs(a[2] - b[2]) <= tolerance;
  },
  
  cross: function(a, b) {
    return [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0] ];
  },

  dot: function(a, b) {
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  },

  add: function(a, b) {
    return [
        a[0] + b[0],
        a[1] + b[1],
        a[2] + b[2]];
  },

  sub: function(a, b) {
    return [
        a[0] - b[0],
        a[1] - b[1],
        a[2] - b[2]];
  },

  scale: function(a, scale) {
    return [a[0] * scale, a[1] * scale, a[2] * scale];
  },

  length: function(a) {
    return Math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]);
  },

  normalize: function(a) {
    var len = V3.length(a);
    if (len <= 0) {
      return [NaN, NaN, NaN];
    }
    return V3.scale(a, 1.0 / len);
  },

  bisect: function(a, b) {
    return [(a[0] + b[0]) / 2,
            (a[1] + b[1]) / 2,
            (a[2] + b[2]) / 2];
  },

  // Returns v rotated counterclockwise about axis by radians.
  // axis should be a unit vector; otherwise you'll get weird results.
  rotate: function(v, axis, radians) {
    var vDotAxis = V3.dot(v, axis);
    var vPerpAxis = V3.sub(v, V3.scale(axis, vDotAxis));
    var vPerpPerpAxis = V3.cross(axis, vPerpAxis);
    var result = V3.add(V3.scale(axis, vDotAxis),
                        V3.add(V3.scale(vPerpAxis, Math.cos(radians)),
                               V3.scale(vPerpPerpAxis, Math.sin(radians))));
    return result;
  },

  // Takes a set of Euler angles and converts from degrees to radians.
  toRadians: function(v) {
    return [v[0] * Math.PI / 180,
            v[1] * Math.PI / 180,
            v[2] * Math.PI / 180];
  },

  // Takes a set of Euler angles and converts from radians to degrees.
  toDegrees: function(v) {
    return [v[0] * 180 / Math.PI,
            v[1] * 180 / Math.PI,
            v[2] * 180 / Math.PI];
  },

  // Input is [lat, lon, alt].  Lat & lon are in degrees, positive up
  // and east.  Alt in meters, relative to Earth's radius.
  //
  // Output is meters x,y,z.  x points out of (0,0) (just off West
  // Africa), y points out the North Pole, and z points out of (0,-90)
  // (near Ecuador).
  latLonAltToCartesian: function(vert) {
    var sinTheta = Math.sin(vert[1] * Math.PI / 180);
    var cosTheta = Math.cos(vert[1] * Math.PI / 180);
    var sinPhi = Math.sin(vert[0] * Math.PI / 180);
    var cosPhi = Math.cos(vert[0] * Math.PI / 180);

    var r = V3.EARTH_RADIUS + vert[2];
    var result = [
        r * cosTheta * cosPhi,
        r * sinPhi,
        r * -sinTheta * cosPhi ];
    return result;
  },

  // Input is meters [x, y, z].  Output is [lat, lon, alt].  Lat & lon
  // in degrees, alt in meters.
  // 
  // V3.cartesianToLatLonAlt([R, 0, 0]) ~= [0, 0, 0]
  // V3.cartesianToLatLonAlt([R/sqrt(2), R/sqrt(2), 0]) ~= [45, 0, 0]
  // V3.cartesianToLatLonAlt([R/sqrt(2), 0, R/sqrt(2)]) ~= [0, -45, 0]
  cartesianToLatLonAlt: function(a) {
    var r = V3.length(a);
    if (r <= 0) {
      return [NaN, NaN, NaN];
    }
    var alt = r - V3.EARTH_RADIUS;
    // Compute projection onto unit sphere.
    var n = V3.scale(a, 1 / r);
    var lat = Math.asin(n[1]) * 180 / Math.PI;
    if (lat > 90) {
      lat -= 180;
    }
    var lon = 0;
    if (Math.abs(lat) < 90) {
      lon = Math.atan2(n[2], n[0]) * -180 / Math.PI;
    }
    return [lat, lon, alt];
  },

  // Return the signed perpendicular distance from the point c to the line
  // defined by [a, b].
  //
  // We get the sign by determining if point is to the left of the line,
  // from the point of view of looking towards the origin through vert0.
  // I.e. is it to the left, looking at the surface of the Earth from
  // above.
  leftDistance: function(a, b, c) {
    var ab = V3.sub(b, a);
    var ac = V3.sub(c, a);
    var cross = V3.cross(ab, ac);

    var dot = V3.dot(a, cross);
    var lineLength = V3.length(ab);
    if (lineLength < 1e-6) {
      return NaN;
    }
    var perpendicularDistance = V3.length(cross) / lineLength;

    if (dot > 0) {
      return perpendicularDistance;
    } else {
      return -perpendicularDistance;
    }
  },

  // Return the distance between two cartesian 3d points, along the
  // surface of the Earth, assuming they are on the surface of the
  // Earth.  (If the inputs are not on the surface of the earth, they
  // are projected to the surface first.)
  earthDistance: function(a, b) {
    var dot = V3.dot(V3.normalize(a), V3.normalize(b));
    var angle = Math.acos(dot);
    var dist = V3.EARTH_RADIUS * angle;
    return dist;
  }
};

M33 = {
  // Conventions:
  //
  // * V3 is a 3-element array representing a column vector
  //
  // * M33 is an array of 3 column vectors, representing a 3x3 matrix
  //
  //   [ [00] [10] [20] ]
  //   [ [01] [11] [21] ]
  //   [ [02] [12] [22] ]
  
  toString: function(a) {
    return "[" + V3.toString(a[0]) + ", " + 
      V3.toString(a[1]) + ", " + V3.toString(a[2]) + "]";
  },

  nearlyEqual: function(a, b) {
    return V3.nearlyEqual(a[0], b[0])
      && V3.nearlyEqual(a[1], b[1])
      && V3.nearlyEqual(a[2], b[2]);
  },

  transpose: function(a) {
    return [
        [a[0][0], a[1][0], a[2][0]],
        [a[0][1], a[1][1], a[2][1]],
        [a[0][2], a[1][2], a[2][2]]];
  },

  multiply: function(a, b) {
    var result = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
    for (var i = 0; i < 3; i++) {
      for (var j = 0; j < 3; j++) {
        result[i][j] = a[0][j] * b[i][0]
                       + a[1][j] * b[i][1]
                       + a[2][j] * b[i][2];
      }
    }
    return result;
  },

  // Applies matrix a to column vector b.  (I.e. returns a * b)
  transform: function(a, b) {
    return [
        a[0][0] * b[0] + a[1][0] * b[1] + a[2][0] * b[2],
        a[0][1] * b[0] + a[1][1] * b[1] + a[2][1] * b[2],
        a[0][2] * b[0] + a[1][2] * b[1] + a[2][2] * b[2]];
  },

  // Applies the transpose of matrix a to column vector b.
  // (I.e. returns a.transpose() * b)
  transformByTranspose: function(a, b) {
    return [
        a[0][0] * b[0] + a[0][1] * b[1] + a[0][2] * b[2],
        a[1][0] * b[0] + a[1][1] * b[1] + a[1][2] * b[2],
        a[2][0] * b[0] + a[2][1] * b[1] + a[2][2] * b[2]];
  },

  identity: function() {
    return [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
  },

  makeOrthonormalFrame: function(dir, up) {
    var newright = V3.normalize(V3.cross(dir, up));
    var newdir = V3.normalize(V3.cross(up, newright));
    var newup = V3.cross(newright, newdir);
    return [newright, newdir, newup];
  },

  // [heading, tilt, roll] (degrees) to [[right],[dir],[up]] (local
  // coords).  The return value transforms global direction vectors
  // into local direction vectors.  The transpose of the return value
  // transforms local direction vectors into global direction vectors.
  //
  // heading, tilt, roll are in degrees, clockwise about z,x,y axes (!?).
  // heading of 0 means pointing North
  // heading of 90 means pointing West
  //
  // [1, 0, 0] in local coords points right (East, for 0, 0, 0 htr)
  // [0, 1, 0] in local coords points ahead (North, for 0, 0, 0 htr)
  // [0, 0, 1] in local coords points up (away from center of earth)
  headingTiltRollToLocalOrientationMatrix: function(htr) {
    return M33.eulToMat(V3.toRadians(htr));
  },

  // [[right], [dir], [up]] (in local cartesian coords) to [heading, tilt, roll]
  // (in degrees)
  localOrientationMatrixToHeadingTiltRoll: function(mat) {
    var htr = M33.matToEul(mat);
    return V3.toDegrees(htr);
  },

  // Builds a local orientation matrix, to transform from local coords
  // into global coords.  "Local" means that the local x basis vector
  // points East, the y basis vector points North and the z basis
  // vector points Up (towards the sky).
  makeLocalToGlobalFrame: function(latLonAlt) {
    var vertical = V3.normalize(V3.latLonAltToCartesian(latLonAlt));
    var east = V3.normalize(V3.cross([0, 1, 0], vertical));
    var north = V3.normalize(V3.cross(vertical, east));

    return [east, north, vertical];
  },

  // See Graphics Gems IV, Chapter III.5, "Euler Angle Conversion" by
  // Ken Shoemake.
  //
  // http://vered.rose.utoronto.ca/people/spike/GEMS/GEMS.html
  eulerConfig: {
    i: 2, j: 0, k: 1,     // NOTE: KML convention is Z, X, Y!
    counterClockwise: true,
    sameAxis: false,      // third axis same as first (i == k)
    frameRelative: false  // frame-relative (vs. static)
  },

  // Construct matrix from Euler angles (in radians).
  //
  // Thanks to Ken Shoemake / Graphics Gems
  eulToMat: function(eulerAnglesIn) {
    var ti, tj, th, ci, cj, ch, si, sj, sh, cc, cs, sc, ss;
    var config = M33.eulerConfig;
    var i = config.i;
    var j = config.j;
    var k = config.k;

    var ea = V3.dup(eulerAnglesIn);
    var m = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
    if (config.frameRelative) { var t = ea[0]; ea[0] = ea[2]; ea[2] = t; }
    if (!config.counterClockwise) {
      ea[0] = -ea[0]; ea[1] = -ea[1]; ea[2] = -ea[2];
    }
    ti = ea[0];	  tj = ea[1];	th = ea[2];
    ci = Math.cos(ti); cj = Math.cos(tj); ch = Math.cos(th);
    si = Math.sin(ti); sj = Math.sin(tj); sh = Math.sin(th);
    cc = ci*ch; cs = ci*sh; sc = si*ch; ss = si*sh;
    if (config.sameAxis) {
      m[i][i] = cj;     m[i][j] =  sj*si;    m[i][k] =  sj*ci;
      m[j][i] = sj*sh;  m[j][j] = -cj*ss+cc; m[j][k] = -cj*cs-sc;
      m[k][i] = -sj*ch; m[k][j] =  cj*sc+cs; m[k][k] =  cj*cc-ss;
    } else {
      m[i][i] = cj*ch; m[i][j] = sj*sc-cs; m[i][k] = sj*cc+ss;
      m[j][i] = cj*sh; m[j][j] = sj*ss+cc; m[j][k] = sj*cs-sc;
      m[k][i] = -sj;   m[k][j] = cj*si;    m[k][k] = cj*ci;
    }
    return m;
  },

  // Convert matrix to Euler angles (in radians).
  //
  // Thanks to Ken Shoemake / Graphics Gems
  matToEul: function(m, config) {
    var config = M33.eulerConfig;
    var i = config.i;
    var j = config.j;
    var k = config.k;

    var FLT_EPSILON = 1e-6;
    var ea = [0, 0, 0];
    if (config.sameAxis) {
      var sy = Math.sqrt(m[i][j] * m[i][j] + m[i][k] * m[i][k]);
      if (sy > 16 * FLT_EPSILON) {
        ea[0]= Math.atan2(m[i][j], m[i][k]);
        ea[1]= Math.atan2(sy, m[i][i]);
        ea[2]= Math.atan2(m[j][i], -m[k][i]);
      } else {
        ea[0]= Math.atan2(-m[j][k], m[j][j]);
        ea[1]= Math.atan2(sy, m[i][i]);
        ea[2]= 0;
      }
    } else {
      var cy = Math.sqrt(m[i][i] * m[i][i] + m[j][i] * m[j][i]);
      if (cy > 16 * FLT_EPSILON) {
        ea[0]= Math.atan2(m[k][j], m[k][k]);
        ea[1]= Math.atan2(-m[k][i], cy);
        ea[2]= Math.atan2(m[j][i], m[i][i]);
      } else {
        ea[0]= Math.atan2(-m[j][k], m[j][j]);
        ea[1]= Math.atan2(-m[k][i], cy);
        ea[2]= 0;
      }
    }
    if (!config.counterClockwise) {
      ea[0] = -ea[0]; ea[1] = -ea[1]; ea[2] = -ea[2];
    }
    if (config.frameRelative) { var t = ea[0]; ea[0] = ea[2]; ea[2] = t; }
    return ea;
  }
};
// geplugin-helpers.js
// requires math3d.js

/*
Copyright 2008 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
 * @fileoverview This file provides a very basic Google Earth plugin helpers
 * library called GEHelpers
 * @author Roman Nurik
 * @supported Tested in IE6+ and FF2+
 */

/**
 * Preliminary/very basic Google Earth plugin helpers library
 * @param {GEPlugin} ge Google Earth instance
 * @constructor
 */
function GEHelpers(ge) {
  this.ge = ge;
}

/**
 * Creates a point placemark at the given location
 * @param {google.maps.LatLng} loc Location of the point placemark
 * @param {Object?} opt_opts Options object, with the following fields:
 *   {string} id The placemark ID in the Earth object model
 *   {string} name The placemark name
 *   {string} description The placemark description
 *   {string} standardIcon The name of a standard KML icon (i.e. 'red-circle')
 *   {string} icon The URL of the placemark's icon
 * @return {KmlPlacemark} The created placemark
 */
GEHelpers.prototype.createPointPlacemark = function(loc, opt_opts) {
  var placemark = this.ge.createPlacemark(opt_opts.id ? opt_opts.id : '');
  
  if (opt_opts.name)
    placemark.setName(opt_opts.name);
  
  //if (opt_opts.description)
    //placemark.setDescription(opt_opts.description);
    
  if (opt_opts.icon) {
   	var icon = this.ge.createIcon('');
    icon.setHref(opt_opts.icon);
	
	 
    var iconStyle = this.ge.createStyle('');
    iconStyle.getIconStyle().setIcon(icon);
    
    var styleMap = this.ge.createStyleMap('');
    styleMap.setNormalStyle(iconStyle);
    styleMap.setHighlightStyle(iconStyle);
    placemark.setStyleSelector(styleMap);
  }
  
  var point = this.ge.createPoint('');
  point.setLatitude(loc.lat());
  point.setLongitude(loc.lng());
  placemark.setGeometry(point);
  
  this.ge.getFeatures().appendChild(placemark);
  return placemark;
}

/**
 * Clears all features in the plugin object model
 */
GEHelpers.prototype.clearFeatures = function() {
  var features = this.ge.getFeatures();
  var c;
  while (c = features.getLastChild())
    features.removeChild(c);
}

/**
 * Removes the feature with the given ID from the plugin object model
 * @param {string} id The ID of the feature to remove
 */
GEHelpers.prototype.removeFeature = function(id) {
  var features = this.ge.getFeatures();
  var c = features.getFirstChild();
  while (c) {
    if (c.getId() == id) {
      features.removeChild(c);
      break;
    }
    
    c = c.getNextSibling();
  }
}

/**
 * Creates a KmlStyle containing a line style with the given options
 * @param {Object?} opt_opts LineStyle parameters described by the fields:
 *   {number} width The line width
 *   {color} color The line color in KML's 'aabbggrr' format
 * @return {KmlStyle} The created KmlStyle with the given line style parameters
 */
GEHelpers.prototype.createLineStyle = function(opt_opts) {
  var style = this.ge.createStyle('');
  var lineStyle = style.getLineStyle();
  if (opt_opts.width)
    lineStyle.setWidth(opt_opts.width);
  if (opt_opts.color)
    lineStyle.getColor().set(opt_opts.color);
  return style;
}

/**
 * Calculates the heading/bearing between two locations. Taken from the formula
 * provided at http://mathforum.org/library/drmath/view/55417.html
 * @param {google.maps.LatLng} loc1 The start location
 * @param {google.maps.LatLng} loc2 The destination location
 * @return {number} The heading from loc1 to loc2, in degrees
 */
GEHelpers.prototype.getHeading = function(loc1, loc2) {
  lat1 = this.deg2rad(loc1.lat());
  lon1 = this.deg2rad(loc1.lng());
  
  lat2 = this.deg2rad(loc2.lat());
  lon2 = this.deg2rad(loc2.lng());
  
  var heading = this.fixAngle(this.rad2deg(Math.atan2(
    Math.sin(lon2 - lon1) * Math.cos(lat2),
    Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) *
      Math.cos(lon2 - lon1))));
  
  return heading;
}

/**
 * Converts radians to degrees
 * @param {number} r Radians
 * @return {number} Degrees
 */
GEHelpers.prototype.rad2deg = function(r) {
  return r * 180.0 / Math.PI;
}

/**
 * Converts degrees to radians
 * @param {number} d Degrees
 * @return {number} Radians
 */
GEHelpers.prototype.deg2rad = function(d) {
  return d * Math.PI / 180.0;
}

// Keep an angle in [-180,180]
/**
 * Keep an angle in the [-180, 180] range
 * @param {number} a Angle in degrees
 * @return {number} The angle in the [-180, 180] degree range
 */
GEHelpers.prototype.fixAngle = function(a) {
  while (a < -180)
    a += 360;
  
  while (a > 180)
    a -= 360;
  
  return a;
}

/**
 * Calculates an intermediate lat/lon, (100 * f)% between loc1 and loc2
 * @param {google.maps.LatLng} loc1 The start location
 * @param {google.maps.LatLng} loc2 The end location
 * @return {google.maps.LatLng} An intermediate location between loc1 and loc2
 */
GEHelpers.prototype.interpolateLoc = function(loc1, loc2, f) {
  return new GLatLng(
    loc1.lat() + f * (loc2.lat() - loc1.lat()),
    loc1.lng() + f * (loc2.lng() - loc1.lng()));
}

/**
 * Gets the earth distance between two locations, factoring in ground altitudes
 * provided by the associated Google Earth plugin instance
 * @param {google.maps.LatLng} loc1 The first location
 * @param {google.maps.LatLng} loc2 The second location
 * @return {number} The distance from loc1 to loc2, in meters
 */
GEHelpers.prototype.distance = function(loc1, loc2) {
  p1 = V3.latLonAltToCartesian([loc1.lat(), loc1.lng(),
    this.ge.getGlobe().getGroundAltitude(loc1.lat(), loc1.lng())]);
  p2 = V3.latLonAltToCartesian([loc2.lat(), loc2.lng(),
    this.ge.getGlobe().getGroundAltitude(loc2.lat(), loc2.lng())]);
  return V3.earthDistance(p1, p2);
}
// simulator.js
// requires geplugin-helpers.js

/*
Copyright 2008 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
 * The amount of real time to simulate per simulator tick
 * @type {number}
 */
DDSimulator.TICK_SIM_MS = 66;

/**
 * Total real time elapsed in the simulation, in seconds
 * @type {number}
 */
DDSimulator.prototype.totalTime = 0;

/**
 * Total distance traveled in the simulation, in meters
 * @type {number}
 */
DDSimulator.prototype.totalDistance = 0;

/**
 * Current traveling speed in the simulation, in meters per second
 * @type {number}
 */
DDSimulator.prototype.currentSpeed = 0;

DDSimulator.prototype.currentLoc = null;

DDSimulator.prototype.currentHeading = 0;

DDSimulator.prototype.running = false;
DDSimulator.prototype.paused  = false;


/**
 * Constructs a simulator object
 * @param {Object} ge The Google Earth instance
 * @param {Array.<Object>} path The path to simulate, as an array of vertex
 *     objects of the form:
 *   {google.maps.LatLng} loc The vertex location of vertex,
 *   {number} step The index of the associated directions step
 *   {number} duration The time duration before the next vertex, in seconds
 *   {number} distance The distance to the next vertex, in meters
 * @param {Object?} opt_opts An object with the following optional fields:
 *   {Function?} on_tick A callback function, called after one tick of the
 *       simulation completes
 *   {Function?} on_changeStep A callback function for when the current step
 *       changes (as per the step property of path items)
 *   {number} speed A multiplier on the simulation speed
 * @constructor
 */
function DDSimulator(path, opt_opts) {
	this.path = path;
	this.options = opt_opts || {};
	if (!this.options.speed)
		this.options.speed = 1.0;
 
 	var me = this;
	me.reset();
 	this.tickListener = function() {
      	if (me.running&&!me.paused) me.tick();
  	};
}

DDSimulator.prototype.reset = function(){
	this.currentLoc = this.path[0].loc;
    this.totalTime = 0;
	this.totalDistance = 0;
	this.currentSpeed = 0;
	this.oldFlyToSpeed = 0;
	this.currentHeading = getHeading(this.path[0].loc, this.path[1].loc);
 	this.running = false;
	this.paused = false;
 	this.pathIndex_ = 0;
 	this.currentStep_ = -1;
 	this.segmentTime_ = 0;
	this.segmentDistance_ = 0;
}

DDSimulator.prototype.start = function(){
	this.running = true;
	this.paused = false;
	this.tick();
}

DDSimulator.prototype.stop = function(){
	this.running = false;
	this.paused = false;
}

DDSimulator.prototype.pause = function(){
	this.paused = true;
}

DDSimulator.prototype.tick = function(){
	if (this.pathIndex_ >= this.path.length - 1) {
		this.running = false;
		if (this.options.on_finish) 
			this.options.on_finish();
		return;
	}
	// update current route step and run callback
	if (this.path[this.pathIndex_].step != this.currentStep_) {
		this.currentStep_ = this.path[this.pathIndex_].step;
		if (this.options.on_changeStep) 
			this.options.on_changeStep(this.currentStep_);
	}
	
	// move up TICK_SIM_MS milliseconds
	this.totalTime += DDSimulator.TICK_SIM_MS * this.options.speed / 1000.0;
	this.segmentTime_ += DDSimulator.TICK_SIM_MS * this.options.speed / 1000.0;
	
	var segmentDuration = this.path[this.pathIndex_].duration;
	
	if (!this.beforeSegmentDistance_) 
		this.beforeSegmentDistance_ = 0.0;
	
	// move to next segment if we pass it in this tick
	while (this.pathIndex_ < this.path.length - 1 && this.segmentTime_ >= segmentDuration) {
		this.segmentTime_ -= segmentDuration;
		
		// adjust distances
		this.beforeSegmentDistance_ += this.path[this.pathIndex_].distance;
		this.segmentDistance_ = 0;
		
		// update new position in path array
		this.pathIndex_++;
		
		// bugfix thanks to naeeem, markw65:
		segmentDuration = this.path[this.pathIndex_].duration;
	}
	
	// bugfix thanks to markw65
	if (segmentDuration) {
		this.segmentDistance_ = this.path[this.pathIndex_].distance *
		Math.min(1.0, this.segmentTime_ / segmentDuration);
		this.currentSpeed = this.path[this.pathIndex_].distance / segmentDuration;
	}
	else {
		this.segmentDistance_ = 0.0;
		this.currentSpeed = 0.0;
	}
	
	this.totalDistance = this.beforeSegmentDistance_ + this.segmentDistance_;
	
	if (this.pathIndex_ >= this.path.length - 1) {
		this.running = false;
		if (this.options.on_finish) 
			this.options.on_finish();
		return;
	}
	//Skip water etc
	var didSkip = false;
	if (this.path[this.pathIndex_].skip && this.options.on_skip) {
		this.options.on_skip();
		didSkip = true;
	}
	while (this.path[this.pathIndex_].skip) {
		this.pathIndex_++;
		this.totalDistance += this.path[this.pathIndex_].distance;
		this.totalTime += this.path[this.pathIndex_].duration;
	}
	//if (didSkip&&!onSkipResult) return
	if (didSkip&&this.options.after_skip) {
		if (!this.options.after_skip()) return
	}
			
	//if (didSkip&&!onSkipResult) return
  // update the current location
  this.currentLoc = interpolateLoc(
      this.path[this.pathIndex_].loc,
      this.path[this.pathIndex_ + 1].loc,
      this.segmentTime_ / this.path[this.pathIndex_].duration);
	  
  this.currentHeading = getHeading(this.path[this.pathIndex_].loc, this.path[this.pathIndex_ + 1].loc)
  
  // fire the callback if one is provided
  if (this.options.on_tick)
    this.options.on_tick();
}

function interpolateLoc(loc1, loc2, f) {
  return new GLatLng(
    loc1.lat() + f * (loc2.lat() - loc1.lat()),
    loc1.lng() + f * (loc2.lng() - loc1.lng()));
}

function getHeading(loc1, loc2) {
  lat1 = deg2rad(loc1.lat());
  lon1 = deg2rad(loc1.lng());
  
  lat2 = deg2rad(loc2.lat());
  lon2 = deg2rad(loc2.lng());
  
  var heading = fixAngle(rad2deg(Math.atan2(
    Math.sin(lon2 - lon1) * Math.cos(lat2),
    Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) *
      Math.cos(lon2 - lon1))));
  
  return heading;
}

function rad2deg(r) {
  return r * 180.0 / Math.PI;
}

function deg2rad(d) {
  return d * Math.PI / 180.0;
}

function fixAngle(a) {
  while (a < -180)
    a += 360;
  
  while (a > 180)
    a -= 360;
  
  return a;
}
/*!
 * Blast Radius General UI Library
 * 
 * Date: 		$LastChangedDate: 2009-06-19 10:27:30 +0100 (Fri, 19 Jun 2009) $
 * Revision:	$Revision: 789 $
 */
brUI = (function($) {

	var ZoomControl = null // ZoomControl 'class'
	var LinkControl = null // LinkControl 'class'
	
	/** 
	Creates dropdown component.
	
	Markup:
	<div id="myDropDown" class="br-dropdown">
		<div class="br-dropdown-prompt"><span>Prompt...</span></div>
		<div class="br-dropdown-options">
			<div>Option 1</div>
			<div>Option 2</div>
		</div>
	</div> 
	
	params:
	$holder - jQuery element 
	prompt  - text to show when no option is selected. if null the 1st option gets selected by default.
	options - array of options. Each object must have 'display' property
	onchange - function(selectedOption). 
	settings - {menuMode: Boolean; dropUp: Boolean}
	*/
	var makeDropDown = function($holder, prompt, options, onchange, settings) {
		var settings = settings || {}
		var options = options || {}
		// state
		var _selected = null
		var init = function(attribute) {
    		//generate markup
    		$holder.addClass("br-dropdown")
    		var html = '<div class="br-dropdown-prompt"><span>' + prompt + '</span></div>\n' +
    					'<div class="br-dropdown-options">\n'
    		for (var i=0; i < options.length; i++) {
    			var opt = options[i]
    			html += '<div>' + opt.display + '</div>\n'
    		};
    		html += '</div>\n'				
    		$holder.html(html)
    				
    		var $options = $holder.find(".br-dropdown-options"),
    		    $prompt  = $holder.find(".br-dropdown-prompt")
    		
    		$holder.click(function(event) {
				event.preventDefault();
				$options.toggle()
				//$('.br-dropdown-options',$(this)).toggle()
    			if (settings.dropUp) {
        		    $options.css('top', -($options.height() + 2) + 'px') // has to be called when $options is visible. otherwise $options.height() is 0. //ms: updated as ie6 works different with relative and absolute etc.
        		} else if (settings.top) {
					$options.css('top', settings.top);
				}    		    
    		})

    		$options.find("div").each(function(i) {
    			$(this).click(function(event) {
					event.preventDefault();
					$('div:parent',$(this)).hide()
    				//$options.hide()
        			var option = options[i]    				
				    if (option !== _selected) { // selection changed
    				    if (onchange) {
        					onchange(option)
        				}
        				if (! settings.menuMode) { // in menu mode don't keep selection.
        				    select(option)
        				}
			        }
    			})
    		})
    		
    		//default selection
    		if (!prompt) {
    		    select(options[0])
    		}
		}
	
		var select = function(option) {
		    _selected = option
	        $holder.find(".br-dropdown-prompt span").text(option ? option.display : prompt) //TODO check that option is in the options array?  
		}

		var selected = function() {
		    return _selected
		}
		
		init() // call constructor
		
		// return dropdown object with public members
		return {
		    select:   select,
		    selected: selected
		}
	}

    /** 
    google - requires google maps api
    id     - id for generated div
    */
    var makeZoomControl = function(google, id) {
        if (!ZoomControl) {
            _initZoomControl(google)
        }
        return new ZoomControl(id)
    }

    var _initZoomControl = function(google) {
        ZoomControl = function(id) {
            this._id = id
        }
        ZoomControl.prototype = new google.maps.Control() // inherit GControl
        
        $.extend( ZoomControl.prototype, {

            initialize: function(map) {

                var $control = $(document.createElement('div'))
                                    .attr('id', this._id)
                                    .addClass('fl-zoomcontrol')
                                    .html('<table><tr>' +
                                        '<td><a href="#" class="fl-zoomcontrol-minus">MINUS</a></td>' + 
                                        '<td><div class="fl-zoomcontrol-slider "></div></td>' + 
                                        '<td><a href="#" class="fl-zoomcontrol-plus">PLUS</a></td>' +
                                        '</tr></table>')
                var $slider = $control.find(".fl-zoomcontrol-slider")
                $slider.slider({
                    orientation: 'horizontal',
                    min: 0,
                    max: 17, //maximum zoom level for google maps
                    value: map.getZoom(),
                    change: function(event, ui) {
                        map.setZoom(ui.value)
                    }                
                })
                // cannot use ".fl-zoomcontrol-minus, .fl-zoomcontrol-plus" here - breaks on Safari.
                $control.find(".fl-zoomcontrol-minus").click(function(event) {
                    event.preventDefault()
                    map.zoomOut()
                })
                $control.find(".fl-zoomcontrol-plus").click(function(event) {
                    event.preventDefault()
                    map.zoomIn()
                })                
                google.maps.Event.addListener(map, "zoomend", function(oldLevel, newLevel) {
                    $slider.slider('option', 'value', newLevel)
                });

                var control = $control.get(0)
                map.getContainer().appendChild( control );
                return control;
            },

            getDefaultPosition: function() {
                return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(3, 0));
            }
        });
    }

    /** 
    google - requires google maps api
    id - id for generated dom element
    links : [{id: 'link1', label: 'Click me', callback?: fn}] - array of links
    */
    var makeLinkControl = function(google, id, links, mediaBase) {
        if (!LinkControl) {
            _initLinkControl(google)
        }
        return new LinkControl(id, links, mediaBase)
    }

    var _initLinkControl = function(google) {
        LinkControl = function(id, links, mediaBase) {
            this._id    = id
            this._links = links
			this._mediaBase = mediaBase
        }
        LinkControl.prototype = new google.maps.Control() // inherit GControl
        $.extend( LinkControl.prototype, {

            initialize: function(map) {
                var $control = $(document.createElement('div'))
                                    .attr('id', this._id)
                                    .addClass('fl-linkcontrol')
                var linksMarkup = '<table><tr>'
                for (var i=0; i < this._links.length; i++) {
                    var link = this._links[i]
                    linksMarkup += 
                        '<td>' +
                            '<table class="fl-linkcontrol-item" id="' + link.id + '"><tr>' +
                                '<td><div class="fl-linkcontrol-icon"><img src="'+this._mediaBase + link.image + '"/></div></td>' + 
                                '<td><a href="#" class="fl-linkcontrol-link">' + link.label + '</a></td>' + 
                            '</tr></table>' +
                        '</td>';
                };
                linksMarkup += '</tr></table>'
                $control.html(linksMarkup)
                
                var me = this
                $control.click(function(event) {
                    var $target = $(event.target)
                    if ($target.hasClass('fl-linkcontrol-link')) { // anchor was clicked
                        event.preventDefault()
                        var linkId = $target.parents('.fl-linkcontrol-item').attr('id')
                        for (var i=0; i < me._links.length; i++) { // find link by id
                            var link = me._links[i]
                            if (link.id.toString() === linkId) { // found
                                if (link.callback) {
                                    link.callback(link)
                                }
                                break;
                            }
                        };
                    }
                })
                
                var control = $control.get(0)
                map.getContainer().appendChild( control );
                return control;
            },

            getDefaultPosition: function() {
                return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(3, 0));
            }
        });
    }
    
    function initDefaultText ($input) {
        var $selection = $input || $('.default-text')
        $selection
            .focus(function(event) {
                $this = $(this)
                if ($this.is('.default-text-active')) {
                    $this.removeClass('default-text-active')
                    $this.addClass('default-text-entry')
                    $this.val('')
                }
            })
            .blur(function(event) {
                $this = $(this)
                if ($this.val() === '') {
					$this.removeClass('default-text-entry')
                    $this.addClass('default-text-active')
                    $this.val( this.title )
                }
            })
            .blur() // initially set default-text-active
    }

    function clearDefaultText () {
        $('.default-text-active').val('').removeClass('default-text-active')
    }
    
    $(document).ready(function() {
        // initialize dropdown
        $(document).mousedown(function(event) {
            var $target = $(event.target)
            if (($target.parents('.br-dropdown')).find('.br-dropdown-options').is(':visible')) {
                // clicked on the prompt of already opened dropdown - do nothing
                return
            }
            if ($target.parents(".br-dropdown-options").length === 0) { //click outside dropdown
                $(".br-dropdown-options").hide()
            }
        })        
    })
	
	// export public members
	return {
		makeDropDown    : makeDropDown,
		makeZoomControl : makeZoomControl,
		makeLinkControl : makeLinkControl,
		initDefaultText : initDefaultText,
		clearDefaultText: clearDefaultText
	}
})(jQuery)
function fiJavascriptReady()
{	pageready = 1;
	return true;
}

function fiFlashReady()
{ // tells js flash is ready
}


// Standard interface for Flash calls on JavaScript    
function fiPageComm(jObj) {
	switch(jObj.type)
	{	case "redirect":
			fi.redirect(jObj);break;

		case "share":
			fi.share(jObj);break;

		case "analytics":
			fi.analytics(jObj);break;

		default:
			console.debug('uncaught fiPageComm: javascriptLocalInterface(jObj);');
		break;
	}    
}

fi = { // this is the interface for flash triggered functionality  
    analytics: function(jObj){

	var a = jObj;
	var str = '';
	
	//if jObj is a wrapper .analytics then iterate through each child and call this again
	if(a.analytics != null && a.analytics != '')
	{	//alert('jObj is analytics - set jObj as jObj.analytics!');
		try{a = jObj.analytics}
		catch (e){//console.debug('fi.analytics error in testing for jObj.analytics');
		}
	}
	else {	//alert('jObj NOT analytics - deal with directly'); 
	}

	var t = '';
	if (typeof(a) == 'object')
		{	if (a.webtrends)
			{	if (a.webtrends.tags)
				{	$.each(a.webtrends.tags, function(i,item) {   t+=('WT.' + i + '=' + item + '&'); })
					if(t != '') 
					{	t=t.replace(/&$/,"").replace(/#$/,"");
						str+='webtrends.tags: ' + t; 
						try {	dcsTrk(t);	}
						catch(e){	console.debug('problem calling dcsTrk('+t+')');
						}
					}
					else {	str+='webtrends: tag object contains no tags';  }
				}
				else
				{	str+='webtrends: no tag object located'; 
				}
				//alert(str);
				str='';
			}
			t = '';
		}
		//else {	console.debug('analytics not triggered'); }
	},

	share: function(jObj){
		//manipulate obj.url to complete URL for overlay/open etc.
		//console.debug('IN:share');

		var shareFormURL = typeof(jObj.url) != 'undefined' ? jObj.url : '';
		var currentURL = window.location.href;
		var sectionURL = typeof(jObj.sectionURL) != 'undefined' ? jObj.sectionURL : '';
		
		//console.debug('shareFormURL'+shareFormURL+'\ncurrentURL'+currentURL+'\nsectionURL'+sectionURL+'\n');

		//added the url param onto the shareform url
		//  does the share form url have a ?
		shareFormURL.indexOf('?') > -1 ? shareFormURL+='&' : shareFormURL+='?';

		currentURL = currentURL.replace(/#$/,"").replace(/&$/,"")
		currentURL = escape(currentURL);

		shareFormURL += 'url=' + currentURL

		//assumption that section url doesn't contain ampersand or questionmark - uses #
		if (sectionURL != null && sectionURL != '')
		{	shareFormURL += escape(sectionURL)
		}

		//console.debug('shareFormURL:'+shareFormURL)

		jObj.url = shareFormURL 
		//console.debug('move fi.share to fi.redirect at:\n ' + jObj.url);
		//embedded analytics object is tested for in the redirect
		fi.redirect(jObj); //note dependancy
		//console.debug('back');
		jObj = null;
		//console.debug('OUT:share');
	}, 

	redirect: function(jObj){
//		//console.debug('IN:redirect');
//		var jObjAnalytics = null //clear incase created in previous interaction
//
//		//note check .share object too (this object passes redirect element to redirect object after manipulation of url
//
//		//check if we have an analytics object
//		if(jObj.analytics)
//		jObjAnalytics = jObj; //analytics object 
//
//		if((jObjAnalytics != null) && (jObjAnalytics != '')) 
//		{   fi.analytics(jObjAnalytics);
//		}

var jObjAnalytics = jObj.analytics; //the redirect from flash will always contain the webtrends etc. within an analytics object (although this may be null)

if(jObjAnalytics != null && jObjAnalytics != '')
{
	fi.analytics(jObjAnalytics);
	/*
	alert('call the function here');

	if(jObjAnalytics.webtrends != '' && jObjAnalytics.webtrends != null)
	{alert('got webtrends');
	}
	else
	{alert('not got webtrends');
	}
	*/
}
//else
//{alert('jObjAnalytics was null or empty');
//}


		var url = jObj.url;
		var wt = jObj.window;

		if (url != '' && url != undefined)
		{	if (wt == 'full') {  openWin.full(url); }
			else if (wt == 'new') {  var n=window.open(url); }
			else if (wt == 'overlay') { openOverlay(jObj); }
			else
			{	document.location.href=url; }
		}
		//else {  console.debug('there was no valid url'); }    
		jObjAnalytics = null;
		jObj = null;
		//console.debug('OUT:redirect');
	}
}

// opens an overlay window - default is thickbox script directly - used for Flash overlays
function openOverlay(jObj)
{   //this allows us to send either object in and use shared named vars
	if(jObj.redirect) 
	{	jObj = jObj.redirect}
	else if(jObj.share)
	{	jObj = jObj.share}

	var url = jObj.url;
	var title = null ;
	var overlayType = "thickbox";
	var width = 0;
	var height = 0;

	if(jObj.params)
	{	title = typeof(jObj.params.title) != 'undefined' ? jObj.params.title : null;
		overlayType = typeof(jObj.params.overlayType) != 'undefined' ? jObj.params.overlayType : "thickbox";
		width = typeof(jObj.params.width) != 'undefined' ? jObj.params.width : 0;
		height = typeof(jObj.params.height) != 'undefined' ? jObj.params.height : 0;
	}

	if(overlayType == "thickbox");
	{   //  does the redirect indicate to use TB_iframe? need to add id overlay mode
		url.toLowerCase().indexOf('tb_iframe=true') > -1 ? url = url.replace('tb_iframe', 'TB_iframe') : url+='&TB_iframe&';
		
		if (height > 0)
		{	url.indexOf('?') > -1 ? url = url.replace('?', '?height=' + height + '&') : url+='?height=' + height + '&';
		}
		if (width > 0)
		{	url.indexOf('?') > -1 ? url = url.replace('?', '?width=' + width + '&') : url+='?width=' + width + '&';
		}

		

		try {	var p=tb_getQueryStringParams(url);
				tb_show(title,url,false,p);
				return false;
			}
		catch(e){}
	}
	//extend for other overlay types here
}
