
/* 10News.com scripts */
// Begin national js scripts


 
/*
 * Copyright 2006, Internet Broadcasting Systems. All Rights Reserved.
 * CVS: $Id: video.js,v 1.14 2007/07/03 20:52:16 breisinger Exp $
 * CVS Path: $Source: /u01/cvsroot/javascript/video/mere_post/video.js,v $
 * Phaedra Content ID: 9372270
 * Example URL: http://www.kvvu.com/video/index.html
*/

/*****************************************************************************************
* VARS
******************************************************************************************/
if(typeof akamaispeed == "undefined") {
	akamaispeed = "low";
}
IBSYS.vp = {
	//objects
	content: new Array(),		//master store of content
	categories: new Array(),	//master list of categories
	searchContent: new Array(),	//where search results are stored. should be build identically to vp.content
	//HTML elements
	searchBox: document.getElementById("videoSearchBox"),
	searchTab: document.getElementById("tabSearch"),
	searchButton: document.getElementById("videoSearchSubmit"),
	searchTextInput: document.getElementById("videoSearchInput"),
	searchArrow: document.getElementById("searchArrow"),
	videoSearchClose: document.getElementById("videoSearchClose"),	
	
	categoriesEl: document.getElementById("videoCategories"),
	categoriesTray: document.getElementById("vidCatList"),
	categoriesTab: document.getElementById("tabCategories"),
	catArrow: document.getElementById("catArrow"),
	videoCategoriesClose: document.getElementById("videoCategoriesClose"),
	
	videoTray: document.getElementById("slides"),
	popularTray: document.getElementById("mostPopularSlides"),
	popularTab: document.getElementById("tabPopular"),
	blurbText: document.getElementById("blurbText"),
	headlineText: document.getElementById("headline"),
	imgCell: document.getElementById("imageCell"),
	playerBox: document.getElementById("player"),
	flashPlayerBox: document.getElementById("flvPlayerHolder"),
	categoryDisplay: document.getElementById("currentCategory"),
	playlistDiv: document.getElementById("playlist"),
	emailButton: document.getElementById("emailButton"),
	helpButton: document.getElementById("helpButton"),
	wmvControlStrip: document.getElementById("videoControls"),
	wmvFullScreenButton: document.getElementById("fullScreen"),
	
	firstLoad: true,
	//strings
	partner: siteinfo.owner.toLowerCase(),
	adTarget: "playerpage",	//for pre/post roll ad targetting
	flashAdTarget: "flashplayer",
	currentItemCoid: false, 	//content id of video currently playing
	currentCategory: "ALL VIDEO",  //name of currently displaying category (in slides tray)
	currentVideoType: false,	//type of video currently playing (string: "wmv" or "flv")
	dndTimer: false, 		//timer object for dragging/dropping playlist item
	mouseY: false,			//Y position of mouse relative to document, in px
	defaultSmallImage: "http://images.ibsys.com/" + siteinfo.sitekey.lc + "-structure/images/structures/misc/mediawindow_default_60x45.jpg",
	defaultLargeImage: "http://images.ibsys.com/" + siteinfo.sitekey.lc + "-structure/images/structures/misc/mediawindow_default_320x240.jpg"
}

/*********************
/ Driver to fire sequence of functions that builds page
/******************/
IBSYS.vp.managePageBuild = function() {
	//create content object to work with
	var isbuilt = IBSYS.vp.buildContentObject();

	//uses vp.content to build slides for each video
	for(var i=0; i<IBSYS.vp.content.length; i++)
		IBSYS.vp.buildVideoSlide(IBSYS.vp.content[i]);
	
	//shows each category so user can choose between them
	IBSYS.vp.buildCategories();
	//display "all video" by default
	IBSYS.vp.showCategory();
	
	//event handlers
	//addEvent(document.body,"mousemove",vp.getMouseXY);
	addEvent(IBSYS.vp.searchBox,"keydown", IBSYS.vp.checkKeyForSearchSubmit);
	addEvent(IBSYS.vp.searchButton,"click",IBSYS.vp.searchSubmit);
	IBSYS.vp.wmvFullScreenButton.onclick = IBSYS.vp.fullScreen;
	addEvent(IBSYS.vp.emailButton,"click",IBSYS.vp.emailVideo);
	addEvent(IBSYS.vp.helpButton,"click",function() {
		window.open('/surveypopup/4813639/detail.html', 'help', 'width=320,height=400,toolbar=no,location=no,status=no,menuBar=no,scrollBars=1,resizable=yes,top=50,left=50');
		return false;
	});
	//document.onmousemove = function() { return false }
	addEvent(IBSYS.vp.popularTab,"click", function() {
		IBSYS.vp.clickToggleVis(IBSYS.vp.popularTray,"block");
		IBSYS.vp.clickToggleVis(IBSYS.vp.videoTray,"none");
		IBSYS.vp.categoryDisplay.innerHTML = "MOST POPULAR";
	});
	addEvent(IBSYS.vp.searchTab,"click", function() {
		IBSYS.vp.clickToggleVis(IBSYS.vp.searchBox);
		IBSYS.vp.toggleImgSrc(IBSYS.vp.searchArrow,"http://images.ibsys.com/sh/images/videoplayer/" + IBSYS.vp.partner + "/arrow_down.png","http://images.ibsys.com/sh/images/videoplayer/" + IBSYS.vp.partner + "/arrow_up.png");
		IBSYS.vp.toggleImgSrc(IBSYS.vp.catArrow,"http://images.ibsys.com/sh/images/videoplayer/" + IBSYS.vp.partner + "/arrow_down.png");
	});
	addEvent(IBSYS.vp.categoriesTab,"click", function() {
		IBSYS.vp.toggleImgSrc(IBSYS.vp.searchArrow,"http://images.ibsys.com/sh/images/videoplayer/" + IBSYS.vp.partner + "/arrow_down.png");
		IBSYS.vp.clickToggleVis(IBSYS.vp.categoriesEl);
		IBSYS.vp.toggleImgSrc(IBSYS.vp.catArrow,"http://images.ibsys.com/sh/images/videoplayer/" + IBSYS.vp.partner + "/arrow_down.png","http://images.ibsys.com/sh/images/videoplayer/" + IBSYS.vp.partner + "/arrow_up.png");
	});
	addEvent(IBSYS.vp.videoCategoriesClose, "click", function() {
		IBSYS.vp.clickToggleVis(IBSYS.vp.categoriesEl);
		IBSYS.vp.toggleImgSrc(IBSYS.vp.catArrow,"http://images.ibsys.com/sh/images/videoplayer/" + IBSYS.vp.partner + "/arrow_down.png");
	});
	addEvent(IBSYS.vp.videoSearchClose, "click", function() {
		IBSYS.vp.clickToggleVis(IBSYS.vp.searchBox);
		IBSYS.vp.toggleImgSrc(IBSYS.vp.searchArrow,"http://images.ibsys.com/sh/images/videoplayer/" + IBSYS.vp.partner + "/arrow_down.png");
	});
	//close categories or search drop down menus if user clicks anywhere on document
	addEvent(document,"click",function(e) {
		var el;
		if(window.event) {
			el = window.event.srcElement;
		} else { 
			el = e.target; 
		}
		
		// ddj 17Jul2006
		while(el != null && 
			(/\w+/.exec(el.id) == null) && 
			(/body/i.exec(el.nodeName) == null))
		{
			el = el.parentNode;
		}
		
		if(el != null && 
			(el.id != "searchArrow" && 
			el.id != "tabSearch" && 
			el.id != "searchBox" && 
			el.id != "videoSearchInput"))
		{
			IBSYS.vp.clickToggleVis(IBSYS.vp.searchBox,"none");
		}
		
		if(el != null && 
			(el.id != "categoriesEl" && 
			el.id != "vidCatList" && 
			el.id != "tabCategories" && 
			el.id != "catArrow"))
		{
			IBSYS.vp.clickToggleVis(IBSYS.vp.categoriesEl,"none");
		}
		
		// while((typeof el.id == "undefined" || el.id == "") && el.nodeName.toUpperCase != "BODY") {
		// 	el = el.parentNode;
		// }
		// if(el.id != "searchArrow" && el.id != "tabSearch" && el.id != "searchBox" && el.id != "videoSearchInput") {
		// 	IBSYS.vp.clickToggleVis(IBSYS.vp.searchBox,"none");
		// }
		// if(el.id != "categoriesEl" && el.id != "vidCatList" && el.id != "tabCategories" && el.id != "catArrow") {
		// 	IBSYS.vp.clickToggleVis(IBSYS.vp.categoriesEl,"none");
		// }
	});
	//checks URL for a video coid
	if(!IBSYS.vp.checkUrlForVideo()) {
		//loads first content object into video player, initializes controls
		IBSYS.vp.loadObject(IBSYS.vp.content[0]);
	}
	//init windows media player
	IBSYS.vp.wmp.initializePlayer();
	IBSYS.vp.firstLoad = false;
}
addEvent(window, "load", IBSYS.vp.managePageBuild);

/*****************************************************************************************
* DATA
*****************************************************************************************/
/*************
/ builds content object for use in the rest of application
/ content[i] = {
	category: uppercase text
	headline: text
	teaser: text
	coid: integer
	imgSrc: relative path to 60X45img
	type: string (wmv/flv)
	pool: string (i.e det, cnn, natl)
}
/*******/
IBSYS.vp.buildContentObject = function() {
	var numIndeces = 0;
	var currIndex = 0;
	for(num in ibIndex) {
		numIndeces++;
	}
	if (typeof ibIndex != "undefined") {
		
		for(index in ibIndex) {
			currIndex++;
			for(var i=0; i<ibIndex[index].co.length; i++) {
				var currObj = ibIndex[index].co[i];
				var newObj = new Object();
				//coid 
				newObj.coid = currObj.coid;
				//headline
				newObj.headline = currObj.headline;
				//teaser 
				newObj.teaser = padTags(fixString(currObj.teaser));
				//strip html out of teaser
				newObj.teaser = newObj.teaser.replace(/<[\/]{0,1}[\w]+.+>/gi,"");
				//pool
				newObj.pool = currObj.owner;
				//category
				if(document.getElementById("gamma") != null && currIndex == numIndeces) {
					//if there is something in gamma, and it's the last one, then it's "most popular"
					newObj.category = "MOST POPULAR";
				} else {
					if(currObj.videosubcategory != "") {
						newObj.category = currObj.videosubcategory;
					} else {
						newObj.category = currObj.videocategory;
					}
					newObj.category = fixString(newObj.category.replace(/_/g, " ").replace(/...no.ads/g, ""));
					newObj.category = newObj.category.toUpperCase();
				}
				//add category to master list if it's not there already
				IBSYS.vp.addCategory(newObj.category);
				//image source
				if(currObj.img.imgSrc) {
					newObj.imgSrc = IBSYS.vp.getImageByTargetWidth(currObj.img,60);
					if(!newObj.imgSrc) {
						newObj.imgSrc = IBSYS.vp.defaultSmallImage;
					}
				} else {
					newObj.imgSrc = IBSYS.vp.defaultSmallImage;
				}
				//store video type and path
				for(var j = 0; j < currObj.videostream.length; j++) {
					if(currObj.videostream[j].type == "flv") {
						newObj.type = "flv";
						newObj.loc = currObj.videostream[j].location;
						//favor flv's
						break;
					}
					if(currObj.videostream[j].type == "wmv") {
						newObj.type = "wmv";
						newObj.loc = currObj.videostream[j].location;
					}
				}
				IBSYS.vp.content.push(newObj);
			}
		}
	}
	return true;
}
/*****
/ Check URL query string for a video coid
/****/
IBSYS.vp.checkUrlForVideo = function() {
	if(!pageProps.coid) {
		return false;
	}
	var coid = pageProps.coid;
	//go back to server and grab content for this
	IBSYS.vp.fetchXML(coid);
	return true;
}
/*****
/ make ajax req. for xml
/****/
IBSYS.vp.fetchXML = function(coid) {
	if (window.ActiveXObject) {
		 //WINDOWS
		IBSYS.vp.xmldata = new ActiveXObject("Microsoft.XMLHTTP");
	} else if (document.implementation && document.implementation.createDocument) {
		//MOZILLA
		IBSYS.vp.xmldata = new XMLHttpRequest();
	}
	IBSYS.vp.xmldata.onreadystatechange = IBSYS.vp.addVideoFromXml;
	IBSYS.vp.xmldata.open("GET", '/_objectxml/' + coid + '/detail.html', true);
	IBSYS.vp.xmldata.send(null);		
}
/*****
/ build content object from a single coid's xml 
/ for structure info, see buildContentObject
/****/
IBSYS.vp.addVideoFromXml = function() {
	if(IBSYS.vp.xmldata.readyState == 4) {
		if(typeof IBSYS.vp.xmldata.responseXML == 'undefined') {
			thedata = IBSYS.vp.xmldata;
		} else {
			thedata = IBSYS.vp.xmldata.responseXML;
		}
		//the XML node we want 
		var currentClip = thedata.getElementsByTagName("video")[0];		
		obj = new Object();
		
		//pool
		obj.pool = currentClip.getAttribute("owner");
		
		//store category
		if(!(obj.category = currentClip.getAttribute("categoryname"))) {
			obj.category = "NEWS";
		}
		obj.category = obj.category.replace(/_/g, " ").replace(/...no.ads/g, "");
		obj.category = obj.category.toUpperCase();
		
		//add category to master list if it's not there already
		IBSYS.vp.addCategory(obj.category);
		
		//store headline
		obj.headline = currentClip.getElementsByTagName("headline")[0].firstChild.nodeValue;
		if(currentClip.getElementsByTagName("teaser")[0].firstChild) {
			obj.teaser = padTags(fixString(currentClip.getElementsByTagName("teaser")[0].firstChild.nodeValue));
		} else {
			obj.teaser = obj.headline;
		}
		//store content id 
		obj.coid = currentClip.getAttribute("id");
		
		//store image href
		if(currentClip.getElementsByTagName("ibs_image").length > 0) {
			var ibsImage = currentClip.getElementsByTagName("ibs_image")[0];
			var imgSrcTag = ibsImage.getElementsByTagName("src")[0].firstChild.nodeValue;
			if(!imgSrcTag) {
				obj.imgSrc = IBSYS.vp.defaultSmallImage;
			} else {
				obj.imgSrc = imgSrcTag.split(".")[0] + "_60X45.jpg";
			}
		} else {
			obj.imgSrc = IBSYS.vp.defaultSmallImage;
		}
		
		var vidStreams = currentClip.getElementsByTagName("videostream");
		for(var t = 0; t < vidStreams.length; t++) {
			if(vidStreams[t].getAttribute("type") == "flv") {
				obj.type = "flv";
				obj.loc = vidStreams[t].getAttribute("location");
				break;
			}
			if(vidStreams[t].getAttribute("type") == "wmv") {
				obj.type = "wmv";
				obj.loc = vidStreams[t].getAttribute("location");
			}
		}
		IBSYS.vp.content.unshift(obj);
		IBSYS.vp.buildVideoSlide(obj);
		IBSYS.vp.currentCategory = obj.category;
		IBSYS.vp.showCategory();
		IBSYS.vp.playlist.add(obj,"pre")();
		IBSYS.vp.createVideo(obj)();
	}
};
/*******************
* Finds image source based on width. If not present, gets next smallest width available.
* For use in conjuction with jsObj display type.
/******************/
IBSYS.vp.getImageByTargetWidth = function(imgObj,targetW) {
	var k = imgObj.availableSizes.length;
	var temp = 0;
	var src = false;
	while(k > 0) {
		var currImg = parseInt(imgObj.availableSizes[k]);
		if(currImg == targetW) {
			src = imgObj.imgSrc.split("_")[0] + "_" + imgObj.availableSizes[k] + ".jpg";
			return src; //bingo
		}
		if(currImg < targetW && currImg > temp)	
			temp = currImg; //find the next closest size (smaller)
		k--;
	}
	src = imgObj.imgSrc.split("_")[0];
	src += "_" + temp + "x" + parseInt(temp*0.75) + ".jpg"; //weakness: 4:3 images
	return src;
}
/*****
/ add category to list of categories
/****/
IBSYS.vp.addCategory = function(category) {
	for(var k=0; k<IBSYS.vp.categories.length; k++) {
		if (IBSYS.vp.categories[k].indexOf(category) != -1) {
			return false;
		}
	}
	if(category == "SEARCH RESULTS" || category == "NEWS") {
		IBSYS.vp.categories.unshift(category);
	} else {
		IBSYS.vp.categories.push(category);
	}
	return true;
}

/*******
/ show selected category of videos
/*******/
IBSYS.vp.showCategory = function() {
	//this just goes through all videos and sets css display based on category name
	var clips = IBSYS.vp.getElementsByClassName(IBSYS.vp.videoTray,"slideItem");
	for(i = 0; i < clips.length; i++) {
		//show all video
		if(IBSYS.vp.currentCategory == "ALL VIDEO") {
			clips[i].style.display = "block";
			
		//show selected category
		} else {
			
			if(clips[i].getAttribute("category") == IBSYS.vp.currentCategory) {
				clips[i].style.display = "block";
			} else {
				clips[i].style.display = "none";
			}
		}
	}
	
	IBSYS.vp.categoryDisplay.innerHTML = IBSYS.vp.currentCategory;
	return false;
}
/*****************************************************************************************
* HTML
*****************************************************************************************/
/*******
/ builds and displays HTML for categories
/*******/
IBSYS.vp.buildCategories = function() {
	//first, clear out any existing categories
	IBSYS.vp.categoriesTray.innerHTML = "";
	var cat;
	//all video category 
	cat = document.createElement("a");
	cat.className = "videoCategory";
	cat.id = "ALL VIDEO";
	cat.innerHTML = "ALL VIDEO";
	cat.href = "#";
	
	cat.onclick = function() {
		IBSYS.vp.currentCategory = this.id;
		IBSYS.vp.showCategory();
		IBSYS.vp.clickToggleVis(IBSYS.vp.categoriesEl,"none");
		IBSYS.vp.clickToggleVis(IBSYS.vp.searchBox,"none");
		IBSYS.vp.clickToggleVis(IBSYS.vp.popularTray,"none");
		IBSYS.vp.clickToggleVis(IBSYS.vp.videoTray,"block");
		IBSYS.vp.toggleImgSrc(IBSYS.vp.catArrow,"http://images.ibsys.com/sh/images/videoplayer/" + IBSYS.vp.partner + "/arrow_down.png");
		return false;
	};
	IBSYS.vp.categoriesTray.appendChild(cat);
	
	//cycle through list of categories
	for(var i=0; i<IBSYS.vp.categories.length; i++) {
		if(IBSYS.vp.categories[i] != "MOST POPULAR") {
			cat = document.createElement("a");
			cat.className = "videoCategory";
			cat.id = IBSYS.vp.categories[i];
			cat.innerHTML = IBSYS.vp.categories[i];
			cat.href = "#";
			
			cat.onclick = function() {
				IBSYS.vp.currentCategory = this.id;
				IBSYS.vp.showCategory();
				IBSYS.vp.clickToggleVis(IBSYS.vp.categoriesEl,"none");
				IBSYS.vp.clickToggleVis(IBSYS.vp.searchBox,"none");
				IBSYS.vp.clickToggleVis(IBSYS.vp.popularTray,"none");
				IBSYS.vp.clickToggleVis(IBSYS.vp.videoTray,"block");
				IBSYS.vp.toggleImgSrc(IBSYS.vp.catArrow,"http://images.ibsys.com/sh/images/videoplayer/" + IBSYS.vp.partner + "/arrow_down.png");
				return false;
			};
			IBSYS.vp.categoriesTray.appendChild(cat);
		}
	}
}

/***********
/ builds and displays a single slide inside the video tray
/ obj = IBSYS.vp.content[i] or IBSYS.vp.searchContent[i]
/*******/
IBSYS.vp.buildVideoSlide = function(obj) {
	var div = document.createElement("div");
	div.className = "slideItem";
	div.setAttribute("category", obj.category);
	div.id = "slide" + obj.coid;
	
	var buttons = document.createElement("div");
	buttons.className = "slideButtons";
	
	var playText = document.createElement("span");
	playText.className = "slidePlayText";
	playText.innerHTML = "PLAY";
	playText.onclick = function() {
		if(!IBSYS.vp.playlist.add(obj,"pre")()) {
			IBSYS.vp.playlist.remove(obj.coid)();
			IBSYS.vp.playlist.add(obj,"pre")();
		}
		IBSYS.vp.createVideo(obj)();
	}
	
	var addText = document.createElement("span");
	addText.className = "slideAddText";
	addText.innerHTML = "ADD TO PLAYLIST";
	addText.onclick = IBSYS.vp.playlist.add(obj,"post")
	
	var img = document.createElement("img");
	img.className = "slideImage";
	img.src = obj.imgSrc;
	img.title = obj.headline.replace(/~/g,"'");
	img.onclick = function() {
		if(!IBSYS.vp.playlist.add(obj,"pre")()) {
			IBSYS.vp.playlist.remove(obj.coid)();
			IBSYS.vp.playlist.add(obj,"pre")();
		}
		IBSYS.vp.createVideo(obj)();
	}
	
	var headline = document.createElement("div");
	headline.className = "slideHeadline";
	headline.innerHTML = padTags(fixString(obj.headline));
	
	buttons.appendChild(playText);
	buttons.appendChild(addText);
	
	div.appendChild(buttons);
	div.appendChild(img);
	div.appendChild(headline);
	if(obj.category == "MOST POPULAR") {
		IBSYS.vp.popularTray.appendChild(div);
	} else {
		IBSYS.vp.videoTray.appendChild(div);
	}
}

/*******
/ loads first item's blurb image and text in video box
/*******/
IBSYS.vp.loadObject = function(obj) {
	//create image for new 
	var img = document.createElement("img");
	if(obj.imgSrc != IBSYS.vp.defaultSmallImage) {
		img.src = obj.imgSrc.split("_")[0] + "_320X240.jpg";
	} else {
		img.src = IBSYS.vp.defaultLargeImage;
	}
	img.title = obj.headline.replace(/~/g,"'");
	img.onclick = IBSYS.vp.createVideo(obj);
	
	while(IBSYS.vp.imgCell.firstChild) {
		IBSYS.vp.imgCell.removeChild(IBSYS.vp.imgCell.firstChild);
	}
	if(window.attachEvent && !IBSYS.vp.firstLoad) {
		mediaPlayer.controls["player"].getPlay().onclick = IBSYS.vp.createVideo(obj);
	}
	IBSYS.vp.imgCell.appendChild(img);
	IBSYS.vp.imgCell.style.display = "block";
	IBSYS.vp.playerBox.style.display = "none";
	
	IBSYS.vp.headlineText.innerHTML = padTags(fixString(obj.headline));
	IBSYS.vp.blurbText.innerHTML = obj.teaser;
}

/*******
/ loads default image and text in video box
/*******/
IBSYS.vp.loadDefault = function() {
	var img = document.createElement("img");
	img.src = IBSYS.vp.defaultLargeImage;
	img.title = "Video";
	
	while(IBSYS.vp.imgCell.firstChild) {
		IBSYS.vp.imgCell.removeChild(IBSYS.vp.imgCell.firstChild);
	}
	IBSYS.vp.imgCell.appendChild(img);
	IBSYS.vp.imgCell.style.display = "block";
	IBSYS.vp.playerBox.style.display = "none";
	
	IBSYS.vp.headlineText.innerHTML = siteinfo.sitename.uc + " Video";
	IBSYS.vp.blurbText.innerHTML = "Browse the videos to the right and click play to play a video."
	return false;
}

/*****************************************************************************************
* PLAYLIST
*****************************************************************************************/

IBSYS.vp.playlist = {
	items: new Array(),	//all items in playlist
	activeItem: false, 	//coid of active item (playing in video player)
	draggingObj: false,	//content object that is being dragged
	itemHeight: 22,		//pixel height of a playlist item
	/*******
	/ remove a clip from the playlist
	/*******/
	remove: function(coid,cueNext) {
		return function() {
			if(typeof cueNext == "undefined") cueNext = false;
			if(typeof coid == "undefined") {
				if(typeof this.id != "undefined") {
					coid = this.id.split("_")[1];
				} else { 
					coid = IBSYS.vp.currentItemCoid;
				}
			}
			
			//if this is the active item, unset active item and stop video
			if(IBSYS.vp.playlist.activeItem) {
				if(coid == IBSYS.vp.playlist.activeItem) {
					IBSYS.vp.playlist.activeItem = false;
					IBSYS.vp.stopVideo();
				}
			}
			var first = IBSYS.vp.playlist.items[0];	//store first item
			//remove item from playlist master list
			for(var i = 0; i<IBSYS.vp.playlist.items.length;i++) {
				if(IBSYS.vp.playlist.items[i] == coid) {
					IBSYS.vp.playlist.items.splice(i,1);
				}
			}
			var el = document.getElementById("playlistItem_" + coid);
			//remove html node from playlist container
			el.parentNode.removeChild(el);
			if(cueNext == true && first == coid) {
				IBSYS.vp.playlist.cueNext();
			}
			return false;
		}
	},
	/*******
	* add a clip to the playlist
	* where: "pre" | "post" | int (to insert)
	********/
	add: function(obj,where) {
		return function() {
			//prevent duplicate entries
			var clips = IBSYS.vp.getElementsByClassName(IBSYS.vp.playlistDiv,"playlistItem");
			for(var i=0; i<clips.length; i++) {
				if(clips[i].id.split("_")[1] == obj.coid) {
					return false;
				}
			}
			//dom node construction
			var el = document.createElement("div");
			el.className = "playlistItem";
			el.id = "playlistItem_" + obj.coid;
			
			var text = document.createElement("div");
			text.className = "playlistText";
			text.innerHTML = padTags(fixString(obj.headline));
			
			var play = document.createElement("div");
			play.innerHTML = "PLAY";
			play.className = "playlistPlayLink";
			play.id = "playlistPlayLink_" + obj.coid;
			play.onclick = function() {
				IBSYS.vp.playlist.remove(obj.coid,false)();
				IBSYS.vp.playlist.add(obj,"pre")();
				IBSYS.vp.createVideo(obj)();
			}
			
			var remove = document.createElement("div");
			remove.innerHTML = "REMOVE";
			remove.className = "playlistRemoveLink";
			remove.id = "playlistRemove_" + obj.coid;
			remove.onclick = IBSYS.vp.playlist.remove(obj.coid,true);
			
			el.appendChild(text);
			el.appendChild(remove);
			el.appendChild(play);
			//prepend
			if(where == "pre") {
				IBSYS.vp.playlist.items.unshift(obj.coid);
				IBSYS.vp.playlistDiv.insertBefore(el,IBSYS.vp.playlistDiv.childNodes[0]);
			//insert at "where"
			} else if (parseInt(where)) {
				IBSYS.vp.playlistDiv.insertBefore(el,IBSYS.vp.playlistDiv.childNodes[(where - 1)]);
				IBSYS.vp.playlist.items = IBSYS.vp.playlist.refreshItems();
			//append
			} else {
				IBSYS.vp.playlist.items.push(obj.coid);
				IBSYS.vp.playlistDiv.appendChild(el);
			}
		}
	},
	/*******
	/ set active item, change font weight to bold
	/*******/
	setActive: function(coid) {
		if(IBSYS.vp.playlist.activeItem) {
			document.getElementById("playlistItem_" + IBSYS.vp.playlist.activeItem).style.fontWeight = "normal";
		}
		IBSYS.vp.playlist.activeItem = coid;
		IBSYS.vp.currentItemCoid = coid;
		document.getElementById("playlistItem_" + IBSYS.vp.playlist.activeItem).style.fontWeight = "bold";
	},
	/*******
	/ remove current item from playlist, play next item
	/*******/
	advance: function() {
		if(IBSYS.vp.currentVideoType == "wmv") {
			document.getElementById("videoplugplayer").fullScreen = false;
		}
		if(IBSYS.vp.playlist.items.length > 1) {
			IBSYS.vp.playlist.remove(IBSYS.vp.currentItemCoid)();
			IBSYS.vp.createVideo(IBSYS.vp.getContentItemByCoid(IBSYS.vp.playlist.items[0]))();
		} else {
			IBSYS.vp.playlist.remove(IBSYS.vp.playlist.items[0])();
			IBSYS.vp.loadDefault();
		}
	},
	/*******
	/ drag and drop
	/*******/
	drag: function() {},
	drop: function() {},
	
	/*******
	/ refresh IBSYS.vp.playlist.items
	/*******/
	refreshItems: function() {
		var a = new Array();
		var items =IBSYS.vp.getElementsByClassName(IBSYS.vp.playlistDiv,"playlistItem");
		for(var i=0; i<items.length; i++) {
			a.push(items[i].id.split("_")[1]);
		}
		return a;
	},
	/**********
	/
	/********/
	cueNext: function() {
		if(IBSYS.vp.playlist.items.length > 0) {
			var co = IBSYS.vp.getContentItemByCoid(IBSYS.vp.playlist.items[0]);
			IBSYS.vp.loadObject(co);
		} else {
			IBSYS.vp.loadDefault();
		}
	}
		
}

/*****************************************************************************************
* SEARCH
*****************************************************************************************/
/*******
/ if user presses Enter or Return, fire submit search function
/*******/
IBSYS.vp.checkKeyForSearchSubmit = function(e) {
	var keycode = e.keyCode;	
	if(keycode == 13) {
		IBSYS.vp.searchSubmit();
	}
}


/*******
/ submit search
/*******/
IBSYS.vp.searchSubmit = function(e) {
	//hide all slides in tray, display "Searching...."
	IBSYS.vp.currentCategory = "Searching..."; //this most likely won't clobber any other category
	IBSYS.vp.showCategory();
	IBSYS.vp.clickToggleVis(IBSYS.vp.searchBox,"none");
	IBSYS.vp.toggleImgSrc(IBSYS.vp.searchArrow,"http://images.ibsys.com/sh/images/videoplayer/" + IBSYS.vp.partner + "/arrow_down.png");
	var searchText = IBSYS.vp.searchTextInput.value;
	//initiate search
	mySearch.getResults(searchText);
}


/*******
/ overwrite the default populate results function
/ 
/ TODO: flv/wmv detection? 
/
/ builds a content object (IBSYS.vp.searchContent) for use in the rest of application
/ the structure of this object must be the same as IBSYS.vp.content
/ IBSYS.vp.searchContent = [
/	category: uppercase text
/	headline: text
/	teaser: text
/	coid: integer
/	imgSrc: relative path to 60x45img
/	pool: det, natl, etc etc
/ ]
/*******/
mySearch.populateResults = function() {
	if (mySearch.query.readyState == 4) {
		if(typeof mySearch.query.responseXML == 'undefined') {
			theresults = mySearch.query;
		} else {
			theresults = mySearch.query.responseXML;
		}
		var category = "SEARCH RESULTS";
		mySearch.resultsXML = theresults.getElementsByTagName("result");
		if(mySearch.resultsXML.length > 0) {
			//remove any previous search results
			var slides = IBSYS.vp.getElementsByClassName(IBSYS.vp.videoTray, "slideItem");
			for(var i=0; i<slides.length; i++) {
				if(slides[i].getAttribute("category") == category) {
					IBSYS.vp.videoTray.removeChild(slides[i]);
				}
			}
			IBSYS.vp.searchContent = new Array();
			
			//loop through result set
			for(var i=0; i<mySearch.resultsXML.length; i++) {
				
				//figure out what site this result is for, skip if wrong site
				var site = mySearch.resultsXML[i].getAttribute("href").split("/")[2].split(".")[1];
				if(site != siteinfo.sitename.lc) {
					continue;
				}
				
				//parse XML into javascript object
				var th = new Object();
				th.category = category;
				
				//headline
				th.headline = "";
				var headline = mySearch.resultsXML[i].getElementsByTagName("title")[0].childNodes;
				//combine headline nodes together (also removes HTML/XML in headline)
				for(h=0; h<headline.length; h++){
					if(headline[h].nodeType == 1) th.headline += headline[h].childNodes[0].nodeValue;
					if(headline[h].nodeType == 3) th.headline += headline[h].nodeValue;
				}
				
				//teaser
				th.teaser = "";
				var teaser = mySearch.resultsXML[i].getElementsByTagName("summary")[0].childNodes;
				//combine teaser nodes together (also removes HTML/XML in teaser)
				for(h=0; h<teaser.length; h++){
					if(teaser[h].nodeType == 1) th.teaser += teaser[h].childNodes[0].nodeValue;
					if(teaser[h].nodeType == 3) th.teaser += teaser[h].nodeValue;
				}
				
				extras = mySearch.resultsXML[i].getElementsByTagName("extra");
				for(var k=0; k<extras.length; k++) {
					var name = extras[k].firstChild;
					//coid
					if(name.childNodes[0].nodeValue == "contentid") {
						th.coid = extras[k].firstChild.nextSibling.childNodes[0].nodeValue;
					}
					
					//image source
					if(name.childNodes[0].nodeValue == "urlThumb60X45") {
						th.imgSrc = extras[k].firstChild.nextSibling.childNodes[0].nodeValue;
					} 	
				}
				if(!th.imgSrc) {
					th.imgSrc = IBSYS.vp.defaultSmallImage;
				}
				//pool (saquery does not return pool info at this time)
				th.pool = siteinfo.sitekey.lc;
				IBSYS.vp.searchContent.push(th);
			}
			
			//display results
			if(IBSYS.vp.searchContent.length > 0) {
				//add new results to tray
				for(var i=0; i<IBSYS.vp.searchContent.length; i++) {
					IBSYS.vp.buildVideoSlide(IBSYS.vp.searchContent[i]);
				}
				
				//display search slides in video tray
				IBSYS.vp.currentCategory = th.category;
				IBSYS.vp.showCategory();
				
				//show a new category name containing search results
				IBSYS.vp.addCategory(th.category);
				IBSYS.vp.buildCategories();
			
			//report no results to user
			} else {
				IBSYS.vp.currentCategory = "No Results Found";
				IBSYS.vp.showCategory();
			}
			
		}
	}
}
/*****************************************************************************************
* VIDEO
*****************************************************************************************/

/*****************
* creates new video player on page, loads video player based on type (flv or wmp)
*****************/
IBSYS.vp.createVideo = function(co) {
	return function() {
		IBSYS.vp.stopVideo();
		IBSYS.vp.blurbText.innerHTML = co.teaser;
		IBSYS.vp.headlineText.innerHTML = padTags(fixString(co.headline));
		IBSYS.vp.imgCell.style.display = "none";
		
		if(IBSYS.vp.playlist.items.length == 0) {
			IBSYS.vp.playlist.add(co)();
		}
		IBSYS.vp.playlist.setActive(co.coid);
		IBSYS.vp.currentVideoType = IBSYS.vp.determineVideoType(co);
		
		//Play WMV video (mediaPlayer)
		if(IBSYS.vp.currentVideoType == "wmv") {
			IBSYS.vp.wmp.play(co.coid,false);
		
		//play Flash Video
		} else if (IBSYS.vp.currentVideoType == "flv") {
			var location = IBSYS.vp.flvp.params.swf + 
				"?xspf=" + IBSYS.vp.flvp.generatePlaylistLink(co.coid);
			if(mediaPlayer.getInstance('player').isActiveX) {
				location += "&activex=true";
			}
			location += "&skin=" + IBSYS.vp.flvp.params.skin; 
			location += "&backgroundImage=" + IBSYS.vp.flvp.params.backgroundImage;
			location +=	"&loading=http://" + window.location.host + 
					"/download/sh/images/videoplayer/" + IBSYS.vp.partner + "/buffering.swf";
			IBSYS.vp.flvp.load("document", location, IBSYS.vp.flvp.params.width, IBSYS.vp.flvp.params.height);
		}
		//web trends
		if (typeof dcsMultiTrack == "function") {
			dcsMultiTrack('WT.ti',co.headline,'DCSext.mtype','Video','DCSext.vtype','Clickplay','DCSext.ib_coid',co.coid,'DCSext.ib_pool',co.pool);
		}
		/* set content id of banner ad to currently playing video so that when ad refreshes it shows up in banner ad call */
		if(typeof AdObj.elements.banner1 != "undefined") {
			AdObj.elements.banner1.coId = "+" + IBSYS.vp.currentItemCoid;
		}
		return false;
	}
}
/*****
* play a wmv ad (called by flash in case it gets a wmv ad in playlist)
*****/
IBSYS.vp.playWmvAd = function(url) {
	IBSYS.vp.wmp.play(url,true);
}
IBSYS.vp.stopVideo = function() {
	if(IBSYS.vp.currentVideoType == "flv") {
		IBSYS.vp.flvp.stop();
	} else if (IBSYS.vp.currentVideoType == "wmv") {
		IBSYS.vp.wmp.destroyPlayers();
	}
}
IBSYS.vp.determineVideoType = function(co) {
	if(typeof co.type != "undefined") {
		return co.type;
	} else {
		return "wmv";
	}
	//return "wmv";
}
/*********************************************************
* FLASH VIDEO
*********************************************************/
IBSYS.vp.flvp = {
	// Load the player
	load: function(target,location,width,height) {
		IBSYS.vp.wmvFullScreenButton.style.display = "none";
		IBSYS.vp.wmvControlStrip.style.display = "none";
		IBSYS.vp.playerBox.style.visibility = "hidden";
		IBSYS.vp.flashPlayerBox.style.display = "block";
		var prefix = '<html><head><title>Video Player</title></head><body '+
			'marginheight=0 marginwidth=0 topmargin=0 leftmargin=0 bottommargin=0 rightmargin=0';
		var requiredMajorVersion = 8;
		var requiredMinorVersion = 0;
		var requiredRevision = 0;
		var hasReqestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
		if (hasReqestedVersion) {
			var code = 
				'<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '+
					'codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/'+
					'swflash.cab#version=8,0,0,0" '+
					'width="'+width+'" '+
					'height="'+height+'" id="flvPlayerObject" align="middle"> '+
				'<param name="allowScriptAccess" value="sameDomain" /> '+
				'<param id="flvPlayerMovieParam" name="movie" '+
					'value="'+location+'" /> '+
				'<param name="quality" value="high" /> '+
				'<param name="bgcolor" value="#000000" /> '+
				'<embed id="embedFLVplayer" '+
					'src="'+location+'" '+
					'quality="high" bgcolor="#000000" width="'+width+'" '+
					'height="'+height+'" name="flvPlayerEmbed" '+
					'align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" '+
					'pluginspage="http://www.macromedia.com/go/getflashplayer" />'+
				'</object>';
		}
		else {
			var code = '<font color=ffffff>This video requires Flash Player 8 or higher. ' + 
				'<a href=http://www.adobe.com/go/getflash/>Click here</a> to download.</font>';
		}
		var suffix = '</body></html>';
		if (target == "flvFullScreen") {
			top.flvFullScreen.document.write(prefix+code+suffix);
		}
		else {
			// Display Embed Code After Blurb
			if (document.location.href.indexOf('dev') != -1) {
				document.getElementById('blurbText').innerHTML += 
					"<div style='margin-top:5px;font-size:10px;'>"+
					"Copy & Paste this HTML to Embed this Video: "+
					"<input style='font-size:9px;' type='text' width='5' value='"+
					"<embed style=\"width:428px;height:270px;\""+
					" type=\"application/x-shockwave-flash\""+
					" src=\"http://"+window.location.host+
					replace(location,"player.skin","external.skin")+"&domain="+
					window.location.host+"\"></embed>"+
					"' onclick='this.focus();this.select();'>"+
					"</div>";
			}
			document.getElementById('flvPlayerHolder').innerHTML = code;
		}
	},
	// Actions once player is written
	action: function(action,startVideo,startTime) {
		// Enter Full Screen Mode
		var url = IBSYS.vp.flvp.params.swf + 
			"?xspf=" + IBSYS.vp.flvp.generatePlaylistLink();
		if(mediaPlayer.getInstance('player').isActiveX) {
			url += "&activex=true";
		}
			url += "&skin=" + IBSYS.vp.flvp.params.skin;
			url += "&loading=http://" + window.location.host + 
				"/download/sh/images/videoplayer/" + IBSYS.vp.partner + "/buffering.swf";
		if (action == "goFullScreen") {
			if(confirm("You are about to enter \"Full Screen\" mode.  \n Please click this button again to return to \"Normal\" mode.")) {
				IBSYS.vp.stopVideo();
				top.flvFullScreen = window.open('about:blank','fullscreen','fullscreen=yes');
				IBSYS.vp.flvp.load("flvFullScreen",url+"&startVideo="+
					startVideo+"&startTime="+
					startTime+"&fullScreen=1","100%","100%");
			}
		}
		// Exit Full Screen Mode
		else if (action == "goNormal") {
			var location = url+"&fullScreen=0&startVideo="+startVideo+
				"&startTime="+startTime;
			IBSYS.vp.flvp.load(top.flvFullScreen, location, IBSYS.vp.flvp.params.width, IBSYS.vp.flvp.params.height);
		}
	},
	//Define Parameters
	params: {
		width:428,
		height:270,
		// swf:"//0710/9494146.swf",
		// swf:"/2006/0707/9484988.swf",
		swf:"/download/sh/upp/player.swf",
		skin:"http://" + window.location.host + "/sh/images/videoplayer/" + IBSYS.vp.partner + "/player.skin",
		externalSkin:"http://" + window.location.host + 
			"/sh/images/videoplayer/" + IBSYS.vp.partner + "/external.skin",
		backgroundImage:"http://" + window.location.host + "/sh/images/videoplayer/" + siteinfo.sitekey.lc + "/bg.jpg"
	},
	generatePlaylistLink: function(coid) {
		if(typeof coid == "undefined") {
			coid = IBSYS.vp.currentItemCoid;
		}
		var url = "http://" + window.location.host + "/flashvideo/";
		url += coid + "/playlist.html?qs=;ng=y;adtarget=" + IBSYS.vp.flashAdTarget;
		url += ";speed=";
		url += (akamaispeed == "high" ? "high" : "low");
		return url;
	},
	finished: function(url) {
		//stub
	},
	play: function() {
		//stub
	},
	stop: function() {
		document.getElementById("flvPlayerHolder").innerHTML = "";
	}
}
/**********************************************************
* WINDOWS MEDIA VIDEO
**********************************************************/
IBSYS.vp.wmp = {
	timer: false,	//timer to monitor video progress
	nextVideoButton: false,
	/***************
	* Constructs controls and buffering container support
	***************/
	initializePlayer: function() {
		//instantiate custom controls 
		if(window.attachEvent) {
			var co = IBSYS.vp.content[0];
			mediaPlayer.controls["player"] = new Controls("videoControls","player",true);
			mediaPlayer.controls["player"].setEnabled(true);
			mediaPlayer.controls["player"].getPlay().onclick = IBSYS.vp.createVideo(co);
			var swfurl = "/sh/images/videoplayer/" + IBSYS.vp.partner + "/buffering.swf";
			mediaPlayer.buffering["player"] = new BufferingSwf("buffer",swfurl).loadSwf();
			mediaPlayer.adTarget["player"] = IBSYS.vp.adTarget;
			/**
			* overwrite default setEnabled fct
			**/
			mediaPlayer.controls["player"].setEnabled = function(b) {
				this.enabled = b;
				var str = b ? "" : "off";
				this.getBack().className = "control back" + str;
				this.getPlay().className = "control play" + str;
				this.getStop().className = "control stop" + str;
				this.getTrack().className = "track track" + (b ? "on" : "off");
				this.getFill().className = "fill fill" + (b ? "on" : "off");
				//heres the extra line i needed to add
				document.getElementById("nextVideoButton").className = "control next" + str;
				if(this.getSeekKnob()) {
					this.getSeekKnob().className = "seekKnob" + str;
				}
			}
			
			/***************
			Custom video controls
			/***************/
			//"next video" button
			IBSYS.vp.wmp.nextVideoButton = document.createElement("div");
			IBSYS.vp.wmp.nextVideoButton.className = "control next";
			IBSYS.vp.wmp.nextVideoButton.id = "nextVideoButton"; 
			IBSYS.vp.wmp.nextVideoButton.title = "Skip to Next Video";
			
			var controls = document.getElementById("videoControls").firstChild;
			controls.insertBefore(IBSYS.vp.wmp.nextVideoButton,controls.childNodes[1]);
			
			//function to fire when next button is clicked
			addEvent(IBSYS.vp.wmp.nextVideoButton,"click",function() {
				if(mediaPlayer.controls["player"].enabled) {
					IBSYS.vp.playlist.advance();
				}
			});
			
			//"back to start" button 
			var toStart = document.createElement("div");
			toStart.className = "control toStart";
			toStart.id = "toStartButton";
			toStart.title = "Back to Start of Video";
			
			controls.insertBefore(toStart,controls.childNodes[1]);
			
			addEvent(toStart,"click",function() {
				if(document.getElementById("videoplugplayer") != null) {
					document.getElementById("videoplugplayer").controls.currentPosition = 0;
				}
			});
		}
	},
	/*****************
	* reliable way to stop/destroy wmp video 
	*****************/
	destroyPlayers: function() {
		//delete embedded player
		if(document.getElementById("videoplugplayer")) {
			el = document.getElementById("videoplugplayer");
			//kills player in IE / Win
			if(mediaPlayer.getInstance('player').isActiveX) {
				if(IBSYS.vp.wmp.timer) {
					window.clearInterval(IBSYS.vp.wmp.timer);
				}
				el.controls.stop();
				el.close();
			//For other browsers
			} else {
				el.parentNode.removeChild(el);
			}
		}
	},
	/*****************
	* play a wmp video 
	*****************/
	play: function(coid,isAd) {
		if(typeof isAd != "boolean") {
			isAd = false;
		}
		IBSYS.vp.wmp.destroyPlayers();
		if(document.attachEvent) {
			IBSYS.vp.wmvFullScreenButton.style.display = "block";
			IBSYS.vp.wmvControlStrip.style.display = "block";
		}
		IBSYS.vp.flashPlayerBox.style.display = "none";
		IBSYS.vp.playerBox.style.display = "block";
		IBSYS.vp.playerBox.style.visibility = "visible";

		IBSYS.vp.wmp.nextVideoButton.className = "control next";
		if(isAd) {
			mediaPlayer.getInstance("player").createPlayer("url",coid,true,"none",true);
		} else {
			mediaPlayer.getInstance("player").createPlayer("video",coid,true,"none",true);
		}		
		if(mediaPlayer.getInstance("player").isActiveX) {
			IBSYS.vp.wmp.timer = window.setInterval("IBSYS.vp.wmp.monitorVideo()",20);
			
			if(document.getElementById("videoplugplayer") &&
				document.getElementById("videoplugplayer").attachEvent)
			{
				document.getElementById("videoplugplayer").attachEvent(
					"currentItemChange",
					AdObj.createAdRefreshHandler("videoplugplayer"));
			}
		}
	},
	/*****************
	* monitor for end of playlist, advance to next item if end
	*****************/
	monitorVideo: function(newstate) {
		//check for playlist end, advance if so
		var percentComplete = parseInt((videoplugplayer.controls.currentPosition / videoplugplayer.currentMedia.duration) * 100);
		var isEndOfAsxPlaylist = (videoplugplayer.currentMedia.getItemInfo("LastEntry") != "") ? true : false;
		//debug("end: " + isEndOfAsxPlaylist + " complete: " + percentComplete,true);
		if(isNaN(percentComplete) && isEndOfAsxPlaylist) {
			IBSYS.vp.playlist.advance();
		}
	}
}


/******************
/ full-screens the video
/*****************/
IBSYS.vp.fullScreen = function() {
	var failMessage = "Video must be playing in order to view it in full-screen mode";
	var confirmMessage = "You are about to go to Full Screen mode. Press ESC to return to normal mode. Do you wish to continue?";
	// first, check to see if video player is playing or paused
	if(document.getElementById("videoplugplayer")) {
		if (document.getElementById("videoplugplayer").playState == 3) {
			if(confirm(confirmMessage)) {
				try {
					document.getElementById("videoplugplayer").fullScreen = true;
				} catch(e) {}
			}
		} else {
			alert(failMessage);
		}
	} else {
		alert(failMessage);
	}
}
/*****************************************************************************************
* TOOLS
*****************************************************************************************/
/***********
* Send video link to friend
***********/
IBSYS.vp.emailVideo = function() {
	if(typeof pageProps != 'undefined') hostElems = pageProps.envhost.split('.');
	else hostElems = new Array('www','ibsys','com');
	emailPage = 'http://cf.' + hostElems[1] + '.' + hostElems[2] + '/' + siteinfo.sitekey.lc;
	emailPage += '/sh/toafriend/index.cfm?page=' + hostElems[0] + '.' + hostElems[1] + '.' + hostElems[2];
	emailPage += '/video/';
	if(IBSYS.vp.currentItemCoid)	emailPage += IBSYS.vp.currentItemCoid + "/";
	emailPage += 'index.html';
	window.open(emailPage,'emailafriend','width=450,height=225');
}

/******
/ getContentItemByCoid
/ returns a content item (co[i]) matching coid
* indexName = "index4938473" or similar
/*****/
IBSYS.vp.getContentItemByCoid = function(coid) {
	for(var i=0; i<IBSYS.vp.content.length; i++) {
		if(IBSYS.vp.content[i].coid == coid) {
			return IBSYS.vp.content[i];
		}
	}
}
/********
/ toggle visibility of a doc element
/*******/
IBSYS.vp.clickToggleVis = function(el,force) {
	force = force ? force : false;
	if(force) {
		el.style.display = force;			
	} else if(el.style.display == "none") {
		el.style.display = "block";
	} else {
		el.style.display = "none";
	}	
}

/********
* Toggle image source in a given img element
********/
IBSYS.vp.toggleImgSrc = function(el,src1,src2) {
	if(src2) {
		if(el.src == src1) {
			el.src = src2;
		} else {
			el.src = src1;
		}
	} else {
		el.src = src1;
	}
	//fix png transparency if image is a png
	if(el.src.indexOf(".png") != -1) {
		el.setAttribute("tested",false);
		fixPngImage(el);
	}
}

/******
/ Fix transparency for all pngs on the page (in IE only)
/*****/
if(window.attachEvent) {
	window.attachEvent("onload",function() {
		imgs = document.getElementsByTagName("img");
		for(var i=0; i<imgs.length; i++) {	
			if(imgs[i].src.match(/\.png$/) != -1) {
				fixPngImage(imgs[i]);
			}
		}
	});
}

/******
/ check url for a query string, return a particular value if found
/*****/
IBSYS.vp.getParamValue = function(str) {
	var q = window.location.search.substring(1);
	var p = q.split("&");
	for(var i=0; i<p.length; i++) {
		var tmp = p[i].split("=");
		//if this paramater is the same as str, return value of param
		if(tmp[0] == str) {
			return tmp[1];
		}
	}
	return false;
}
/*****
/ Track user mouse position
/****/
IBSYS.vp.getMouseXY = function(e) {
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) {
		posx = e.pageX;
		posy = e.pageY;
	} else if (e.clientX || e.clientY) {
		posx = e.clientX + document.body.scrollLeft;
		posy = e.clientY + document.body.scrollTop;
	}
	IBSYS.vp.mouseY = posy;
}
/*****
* get Y offset of an HTML element
*****/
IBSYS.vp.getYOffset = function(obj) {
	var yoff = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			yoff += obj.offsetTop
			obj = obj.offsetParent;
		}
	} else if (obj.y) {
		yoff += obj.y;
	}
	return yoff;
}
/*****
/ get elements by class name
/****/
IBSYS.vp.getElementsByClassName = function(node, classname) {
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
	if(re.test(els[i].className))a.push(els[i]);
    return a;
}

/*****
/ Just for deeebugging
/*****/
var debugnumber = 0;
var notCreated = true;
function debug(text,clear) {
	clear = (clear ? true : false);
	var parent;
	var div;
	if(notCreated) {
		div = document.createElement("div");
		div.id = "debug";
		parent = document.getElementsByTagName("div")[0];
		parent.appendChild(div);
		notCreated = false;
	}
	debugnumber++;
	if(clear) {
		document.getElementById("debug").innerHTML = "";
	}
	var prev = document.getElementById("debug").innerHTML;
	document.getElementById("debug").innerHTML = debugnumber + ". " + text + "<br />" + prev;
}

function replace(string,text,by) {
// Replaces text with by in string
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return string;

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return string;
    if (i == -1) return string;

    var newstr = string.substring(0,i) + by;

    if (i+txtLength < strLength)
        newstr += replace(string.substring(i+txtLength,strLength),text,by);

    return newstr;
}



// End national_js scripts


