//INITIALIZATION
///////////////////////////
var html = document.getElementsByTagName('html')[0];
jscss('add',html,'hasScript');
if ( detectFlash(6) ) jscss('add',html,'hasFlash');

var hasReqdDOM = (document.getElementsByTagName && document.getElementById);

function PageInit() {
	if ( !(hasReqdDOM) ) return;
	InitNavMenu();
	PopUpSafe( document.getElementsByTagName('a') );
}
addEvent(window,'load',PageInit);

function initFlash() {
	if ( !document.getElementById || typeof(FlashObject) == 'undefined')  return;
	myFlash = new FlashObject("/images/mp/sc_flash_final.swf", "flashy", "766", "209", 6.0, "#ffffff");
	myFlash.addParam("wmode","opaque"); //fix bug with IE 5.x
	myFlash.write("fl_replace");
}

function PopUpSafe(els) {
	if (!els) return;
	for (var i = 0; i < els.length; i++) {
		var r = els[i].rel;
		if (r.indexOf(':') >= 0) {
			els[i].onclick = function() { args = this.rel.split(':'); return PopWin(this.href,args[0],args[1],args[2]); }
		}
		else if (r.indexOf("external") >= 0 || r.indexOf("photogallery") >= 0 || r.indexOf("tripplanner") >= 0) {
			els[i].onclick = function() { return PopWin(this.href,r); }
		}
	}
}


// DROPDOWN HANDLER
////////////////////////
function InitNavMenu() {
	var mn = document.getElementById('navsub');
	var oldIE = (document.all && getIEVersion() < 7)
	if (!mn) return;
	
	var uls = mn.getElementsByTagName('ul');
	
	var fn_a = function() { this.navMenu.onactivate(); }
	var fn_d = function() { this.navMenu.ondeactivate(); }
	if (oldIE)	{
		fn_a = IEactive;
		fn_d = IEinactive;
	}
	for (var i = 0; i < uls.length; i++ ){
		//setOpacity(uls[i],0);
		if ( uls[i].id=='' || !uls[i].id ) uls[i].id = 'menu'+i;
		uls[i].parentNode.navMenu = uls[i];
		uls[i]["onactivate"] = setLyr;
		uls[i]["ondeactivate"] = unsetLyr;
		uls[i].activator = getActivator(uls[i]);
		uls[i].parentNode.onmouseover = fn_a;
		uls[i].parentNode.onmouseout = fn_d;
		if ( oldIE ) {
			if (uls[i].parentNode.nodeName != 'DD') {
			uls[i].onmouseover = function() { if(this.activator) jscss('add',this.activator,"chsel"); };
			uls[i].onmouseout = function() { if(this.activator) jscss('remove',this.activator,"chsel");  };
			}
		}
	}
}

//action to occur when the menu is activated
function setLyr() {
	if (!this.active){ Fade(this.id,60,100,200,(new Date).getTime()); }
	this.active = true;
	if (CloseTimers[this.id]) clearTimeout(CloseTimers[this.id]);
	if (this.parentNode.nodeName != "DD") {
		var cw = document.body.clientWidth || window.innerWidth;
		var diff = (findObjPos(this).dx + this.offsetWidth) - cw;
		if ( diff > 0 ) 
			this.style.left =  -(this.offsetWidth - 15) + "px";
	}
}
//action to occur when menu is deactivated
function unsetLyr() {
	jscss('add',this,'closeing'); //this class lets menus remain visible after closing
	CloseTimers[this.id] = window.setTimeout("close('"+this.id+"')",300);
}
// set delay before closing menu
var CloseTimers = new Object();
function close(id) {
	if (!hasReqdDOM) return;
	el = document.getElementById(id);
	if (!el) return;
	el.active = null;
	jscss('remove',el,'closeing');
	CloseTimers[id] = null;
	
}
// Find the object that "activates" the menu
function getActivator(n) {
	while(n.previousSibling ) {
		n = n.previousSibling;
		if( n.nodeName == "A" ) { return n; }
	}
	return null;
}

// additional properties for IE compatibility
function IEactive() { jscss('add',this,"IEhover"); jscss('add',this.navMenu,"ddesc"); this.navMenu.onactivate(); }
function IEinactive() { jscss('remove',this,"IEhover"); jscss('remove',this.navMenu,"ddesc"); this.navMenu.ondeactivate(); }

//IMAGE ROLLOVERS
///////////////////////////
var over = new Object();
var out = new Object();
function Rollovers(idArr,func) {
	var imgs, a;
	if (!func) func = getRollSrc;
	if (!document.images) return;

	for (i = 0; i < idArr.length; i++) {
		imgs = getObj(idArr[i]);
		if (!imgs) continue;
		out[ idArr[i] ] = new Image();
		over[ idArr[i] ] = new Image();
		out[ idArr[i] ].src = imgs.src;
		over[ idArr[i] ].src = func(imgs.src,1);
		a = imgs.parentNode;
		if ((a && a.tagName.toLowerCase() == 'a') ){
			a.onmouseover = function() { this.childNodes[0].src = over[this.childNodes[0].id].src; }
			a.onmouseout = function() { this.childNodes[0].src = out[this.childNodes[0].id].src;  }
			a.onfocus = function() { this.childNodes[0].src = over[this.childNodes[0].id].src; }
			a.onblur = function() { this.childNodes[0].src = out[this.childNodes[0].id].src; }
		}
		else if (imgs.tagName.toLowerCase() == 'input') {
			imgs.onmouseover = function() { this.src = over[this.id].src; }
			imgs.onmouseout = function() { this.src = out[this.id].src; }
		}
	}
}
function getRollSrc(src, hover) { return (hover) ? src.replace(/a.(gif|jpg)/,"b.$1") : src.replace(/b.(gif|jpg)/,"a.$1"); }


//UTILITY FUNCTIONS
///////////////////////////
var wini; //Reference to a window
function PopWin(url, name, width, height) {
	var s;
	if (width || height) {
		h = (height) ? height : 600;
		w = (width) ? width : 800;
		lp = (screen.width) ? (screen.width-w)/2 : 0;
		tp = (screen.height) ? (screen.height-h)/2 : 0;
		sc = (name == 'gallery') ? 'no' : 'yes';
		s = 'height='+ h +',width='+ w +',top='+tp+',left='+lp+',scrollbars='+sc+',resizable,menubar=1';
	}
	else s = '';
	wini = window.open(url,name,s);
	if (wini) wini.focus();
	return ( !wini )
}// PopWin()

function getObj(objId) {
	if (document.getElementById)
		obj = document.getElementById(objId);
	else if (document.all)
		obj = document.all[objId];
	else
		obj = null;
	return obj;
}

function addEvent(obj,evType,fn){
	if(obj.addEventListener){
		obj.addEventListener(evType,fn,false);
	}
	else if(obj.attachEvent){
		var r=obj.attachEvent("on"+evType,fn);
	}
	else{
		if ( typeof( obj['on'+evType] ) == 'function' ) {
			var last = obj['on'+evType] ;
			obj['on'+evType] = null;
			obj['on'+evType] = function() { last(); fn(); };
		}
		else obj['on'+evType] = fn;
	}
}

function setOpacity(obj, opacity) {
  opacity = (opacity == 100)?99.999:opacity;
  // IE/Win -jps disabled
  obj.style.filter = "alpha(opacity:"+opacity+")";
  // Safari<1.2, Konqueror
  obj.style.KHTMLOpacity = opacity/100;
  // Older Mozilla and Firefox
  obj.style.MozOpacity = opacity/100;
  // Safari 1.2, newer Firefox and Mozilla, CSS3
  obj.style.opacity = opacity/100;
}

var Faders = new Object();
function Fade(objId,from, to, dur, st) {
	obj = document.getElementById(objId);
	var time = (new Date).getTime();
	var Tpos = (time-st) / dur;
	if(time >= dur+st) {
		setOpacity(obj,to);
		clearInterval(Faders[objId]);
		Faders[objId] = null;
	}
	else {
		next = ((-Math.cos(Tpos*Math.PI)/2) + 0.5) * (to-from) + from;
		setOpacity(obj,next);
		if ( !Faders[objId] ) Faders[objId] = setInterval("Fade('"+objId+"',"+from+","+to+","+dur+","+st+")",13);
	}
}

function findObjPos(obj){
	var curtop = 0;
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y && obj.x) {
		curtop += obj.y;
		curleft += obj.x;
	}
	var t = new Object();
	t.dx = curleft;
	t.dy = curtop;
	return t;
}

function includeCSS(file,media){
	var head = document.getElementsByTagName('head').item(0);
	var scriptTag = document.getElementById('loadCSS');
	if(scriptTag) head.removeChild(scriptTag);
	css = document.createElement('link');
	css.rel = "stylesheet";
	css.href = file;
	css.type = 'text/css';
	css.id = 'loadCSS';
	css.media = media;
	head.appendChild(css)
}

// found at http://www.onlinetools.org/articles/unobtrusivejavascript/cssjsseparation.html
function jscss(a,o,c1,c2) {
  switch (a){
    case 'swap':
      o.className=!jscss('check',o,c1)?o.className.replace(c2,c1): o.className.replace(c1,c2);
    break;
    case 'add':
      if(!jscss('check',o,c1)){o.className+=o.className?' '+c1:c1;}
    break;
    case 'remove':
      var rep=o.className.match(' '+c1)?' '+c1:c1;
      o.className=o.className.replace(rep,'');
    break;
    case 'check':
      return new RegExp('\\b'+c1+'\\b').test(o.className)
    break;
  }
}

// FUNCTIONS NEEDED FOR VARIOUS DETECTIONS
///////////////////////////////////////////
function getIEVersion() {
  var rv = -1;
  if (navigator.appName == 'Microsoft Internet Explorer') {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

function getFlashVersion() {
	var flashversion = 0;
	if (navigator.plugins && navigator.mimeTypes.length) {
		var x = navigator.plugins["Shockwave Flash"];
		if(x && x.description) {
			var y = x.description;
   			flashversion = y.charAt(y.indexOf('.')-1);
		}
	} else {
		result = false;
	    for(var i = 15; i >= 3 && result != true; i--){
   			execScript('on error resume next: result = IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.'+i+'"))','VBScript');
   			flashversion = i;
   		}
	}
	return flashversion;
}
function detectFlash(ver) { return (getFlashVersion() >= ver) ? true:false; }

/****************************
//** FROM: somewhere. Seen these functions elsewhere too many times to properly credit
//***************************/
function setOpacity(obj, opacity) {
  opacity = (opacity == 100)?99.999:opacity;
  // IE/Win
  obj.style.filter = "alpha(opacity:"+opacity+")";
  // Safari<1.2, Konqueror
  obj.style.KHTMLOpacity = opacity/100;
  // Older Mozilla and Firefox
  obj.style.MozOpacity = opacity/100;
  // Safari 1.2, newer Firefox and Mozilla, CSS3
  obj.style.opacity = opacity/100;
}

function fadeIn(objId,opacity) {
  if (document.getElementById) {
    obj = document.getElementById(objId);
    if (opacity <= 100) {
      setOpacity(obj, opacity);
      opacity += 10;
      window.setTimeout("fadeIn('"+objId+"',"+opacity+")", 100);
    }
  }
}


function ImgRotator (objId,chainId,speed)
{
	this.objId = objId; // VARIABLE SHOULD BE NAMED THIS AS WELL
	this.objChainId = chainId;
	this.obj = getObj(objId);
	this.linkedObj = getObj(chainId)
	this.speed = speed;
	this.ImgSrc = new Object();
	this.ImgAlt = new Object();
	this.curIndex =  0;
	this.count = 0;
	this.started = false;
	this.preloaded = false;
	this.chain;
	this.paused = false;
	if (this.obj) {
		var a = this.obj.parentNode;
		if (a.tagName == 'A') { a.style.display = 'block'; }
	}

}

var IR = ImgRotator.prototype;

IR.addImage = function(source,alt) { this.ImgSrc[this.count] = source; this.ImgAlt[this.count++] = alt; }
IR.preloadImages = function() { for(i=0;i < this.count;i++) { var img= new Image(); img.src = this.ImgSrc[i]; } this.preloaded = true; }
IR.beginSlideShow = function() { if (!this.obj) return; this.started = true; setInterval("eval("+this.objId+").showImage()",this.speed);}
IR.beginLinkedSlideShow = function() { if (!this.linkedObj) return; this.started = true; this.showImage(); this.chain = setTimeout("eval("+this.objChainId+").showImageChain()",this.speed);}
IR.showImage = function () { 
	if (this.obj.parentNode) {
		this.obj.parentNode.style.backgroundImage = 'url('+this.obj.src+')';
	}
	this.obj.title = this.ImgAlt[this.curIndex];
	this.obj.alt = this.ImgAlt[this.curIndex];
	this.obj.src = this.ImgSrc[this.curIndex];
	this.curIndex++; this.curIndex %= this.count;
	
	fadeIn(this.objId,0);
}
IR.showImageChain = function () { 
	clearTimeout(this.chain);
	this.beginLinkedSlideShow();
}