// $Revision: 2829 $
// Copyright (c) 2011 ZubeHost LLC, All rights reserved.

//these functions handle the display of the 'feature hilight' boxes on account and site dashboards
//to force display of a feature on load, pass its number to the init function (first index = 1)
function initFeatureHilight(showFirst){
	var showing = 0;
	var showRandom = true;
	window.featureArray = new Array();
	var allFeatures = document.getElementById('features').getElementsByTagName('SPAN');
	for(i=0; i<allFeatures.length; i++){
		if(allFeatures[i].className=='feature'){
			if(allFeatures[i].id==showFirst){
				showRandom = false;
				var showing = featureArray.length;	
			}else{
			}
			featureArray.push(allFeatures[i].innerHTML);
		}
	}
	if(showRandom){
		var showing = Math.floor(Math.random()*window.featureArray.length);
	}
	displayFeature(showing);
}
function displayFeature(num){
	window.showingFeature = num;
	var featureWrapperEl = document.getElementById('featureWrapper');
	var featureNumWrapper = document.getElementById('featureNumber');
	var prevFeatureBut = document.getElementById('prevFeatureBut');
	var nextFeatureBut = document.getElementById('nextFeatureBut');
	featureWrapperEl.innerHTML = window.featureArray[num];
	featureNumWrapper.innerHTML=(num+1)+' of '+window.featureArray.length;
	if(num>0){
		prevFeatureBut.className=prevFeatureBut.className.replace('disabled','enabled');
	}else{
		prevFeatureBut.className=prevFeatureBut.className.replace('enabled','disabled');
	}
	if((num+1)<window.featureArray.length){
		nextFeatureBut.className=nextFeatureBut.className.replace('disabled','enabled');
	}else{
		nextFeatureBut.className=nextFeatureBut.className.replace('enabled','disabled');
	}
}
function nextFeature(){
	displayFeature(window.showingFeature+1);
}
function prevFeature(){
	displayFeature(window.showingFeature-1);
}

//this function handles the display of highlighted custom snippet areas
function hilightSnippetAreas(){
	var allDivs = document.getElementsByTagName('DIV');
	var hilighted = [];
	for(i=0; i<allDivs.length; i++){
		if(allDivs[i].className.search('hilighted')>-1 || allDivs[i].className.search('visible')>-1){
			hilighted.push(allDivs[i]);
		}
	}
	for(i=0; i<hilighted.length; i++){
		var overlay = document.createElement("DIV");
		overlay.className='hilightElement overlay';
		hilighted[i].appendChild(overlay);
		var borders = ["top","right","bottom","left"];
		for(b=0; b<borders.length; b++){
			var newBorderEl = document.createElement("DIV");
			newBorderEl.className='hilightElement border '+borders[b]+'Border';
			hilighted[i].appendChild(newBorderEl); 
		}
	}
}
//these functions handle the display of lists with multiple vertical sliding sections
function initSlideLists(){
	var lists = document.getElementsByTagName('UL');
	var slideLists = [];
	for(i=0; i<lists.length; i++){
		if(lists[i].className.search('slideList')>-1){
			slideLists.push(lists[i]);
		}
	}
	for(i=0; i<slideLists.length; i++){
		var listItems = slideLists[i].getElementsByTagName('LI');
		slideLists[i].sections = [];
		for(c=0; c<listItems.length; c++){
			if(listItems[c].parentNode == slideLists[i]){
				slideLists[i].sections.push(listItems[c]);
			}
		}
		for(s=0; s<slideLists[i].sections.length; s++){
			var header = slideLists[i].sections[s].getElementsByTagName('H2')[0];
			header.onclick=function(){expand(this);}
		}
	}
	expand();
}
function expand(clicked){
	var lists = document.getElementsByTagName('UL');
	for(c=0; c<lists.length; c++){
		if(lists[c].className.search('slideList')>-1){
			for(i=0; i<lists[c].sections.length; i++){
				var cDiv = lists[c].sections[i].getElementsByTagName('DIV')[0];
				var cssClass;
				if((clicked && clicked.parentNode == lists[c].sections[i] && clicked.parentNode.className.search('active')<0) || lists[c].sections[i].className == 'expanded'){
					if(i==0){
						cssClass = 'first active';
					}else if(i==lists[c].sections.length-1){
						cssClass = 'last active';
					}else{
						cssClass = 'active';
					}
					$(cDiv).slideDown(500, function(){;});
				}else{
					if(i==0){
						cssClass = 'first';
					}else if(i==lists[c].sections.length-1){
						cssClass = 'last';
					}else{
						cssClass = '';
					}
					if(clicked && clicked.parentNode.parentNode == lists[c]){	
						$(cDiv).slideUp(500, function(){;});
					}
				}
				lists[c].sections[i].className=cssClass;
			}
		}
	}
}
//content provider selection
function showFields(el){
	if(el){
		//get the parent wrapper for the element that was passed
		//first find the parent form tag, then look under that to find the wrapper div (1st child div)
		var node = el;
		while(node.tagName!=='FORM' && node.tagName!=='BODY'){
			node = node.parentNode;
		}
		var activeWrap = node.getElementsByTagName('DIV')[0];
	}
	var allDivs = document.getElementsByTagName('DIV');
	var pWrappers = [];
	for(i=0; i<allDivs.length; i++){
		if(allDivs[i].className.search('providerWrapper')>-1){
			pWrappers.push(allDivs[i]);	
		}
	}
	
	for(i=0; i<pWrappers.length; i++){
		
		//if we know which section should be active, set classes
		if(activeWrap){
			if(pWrappers[i]==activeWrap){
				pWrappers[i].className = 'providerWrapper active';
			}else{
				pWrappers[i].className = 'providerWrapper';
			}
		}
		
		//get the radio input for the current section
		var els = pWrappers[i].getElementsByTagName('INPUT');
		for(c=0; c<els.length; c++){
			if(els[c].type=='radio'){
				var radioEl = els[c];
				break;
			}
		}
		
		//get the form field wrapper for current section
		els = pWrappers[i].getElementsByTagName('DIV');
		for(c=0; c<els.length; c++){
			if(els[c].className=='mid'){
				var expandable = els[c];
				break;	
			}
		}
		
		//set radio state, expand/contract form field wrapper, focus first text input
		if(pWrappers[i].className.search('active')>-1){
			//identify the first text input to focus
			els = expandable.getElementsByTagName('INPUT');
			for(c=0; c<els.length; c++){
				if(els[c].type=='text'){
					var focusField = els[c];
					break;
				}
			}
			radioEl.checked=true;
			$(expandable).slideDown(300, function(){focusIt(focusField)});
		}else{
			radioEl.checked=false;
			$(expandable).slideUp(300, function(){});
		}
	}
}
function focusIt(el){
	el.focus();
}
function applyChanges(el){
	while(el.tagName!=='FORM' && el.tagName!=='BODY'){
		el = el.parentNode;
	}
	if(el.tagName=='FORM'){
		el.submit();
	}
}
	
//this function switches between template preview images (site > design > template)
function switchPic(triggerEl, targetEl, newSrc){
	var target = document.getElementById(targetEl);
	target.src = newSrc;
	var imgList = triggerEl.parentNode.parentNode;
	var allLinks = imgList.getElementsByTagName('A');
	for(i=0; i<allLinks.length; i++){
		allLinks[i].className='';
	}
	triggerEl.className='active';
}
//functions for fake video preview on partner link config page
function isNumeric(sText){
var ValidChars = "0123456789.";
var IsNumber=true;
var Char;
for (i = 0; i < sText.length && IsNumber == true; i++){ 
	Char = sText.charAt(i); 
	if (ValidChars.indexOf(Char) == -1){
		IsNumber = false;
	}
}
return IsNumber;
}
function renderFakePreview()
{
	//name
	document.getElementById('preview_fake_video_name').innerHTML = document.getElementById('fake_video_name').value.replace(/(<([^>]+)>)/ig,"");
	//description
	//document.getElementById('preview_fake_video_desc').innerHTML = document.getElementById('fake_video_description').value.replace(/(<([^>]+)>)/ig,"");
	//document.getElementById('preview_fake_video_description').innerHTML = document.getElementById('fake_video_description').value;
	//duration
	//document.getElementById('preview_fake_video_duration').innerHTML = document.getElementById('fake_video_duration').value.replace(/(<([^>]+)>)/ig,"");
	var nDuration = document.getElementById('fake_video_duration').value.replace(/(<([^>]+)>)/ig,'');
	// format duration from secons to h:m:s
	if (isNumeric(nDuration))
	{
	  var h = 0;
	  var m = 0;
	  var s = 0;
	  if (nDuration >= 3600)
	  {
		h = parseInt(nDuration / 3600);
		nDuration = nDuration % 3600;
	  }
	  if (nDuration >= 60)
	  {
		m = parseInt(nDuration / 60);
		nDuration = nDuration % 60;
	  }
	  s = nDuration;
	  var sDuration = (h>0) ? h+'h '+m+'m '+s+'s' : 
					  (m>0) ? m+'m '+s+'s' : s+'s';
	  document.getElementById('preview_fake_video_duration').innerHTML = sDuration;
	}
	//views
	document.getElementById('preview_fake_video_numviews').innerHTML = document.getElementById('fake_video_numviews').value.replace(/(<([^>]+)>)/ig,"");
	//rating
	//format rating class
	var input = parseInt(document.getElementById('fake_video_rating').value.replace(/(<([^>]+)>)/ig,""));//grab user input, convert to numeric
	if(isNumeric(input))
	{
		if(input>5)
		  input=5;
		var rating = 'rating50wWrap r'+input*20;
		//alert(rating);
		document.getElementById('preview_fake_video_rating').className = rating;
	}
	else alert('please enter a valid number (0-5)');
}

//zube popup functions
function sizeMask(){
	var winW = document.documentElement.clientWidth;
	var winH = document.documentElement.clientHeight;
	var pageMask = document.getElementById('pMask');
	pageMask.style.width = winW+'px';
	pageMask.style.height = winH+'px';
}
function centerPop(){
	var winW = document.documentElement.clientWidth;
	var winH = document.documentElement.clientHeight;
	var popEl = document.getElementById('popup');
	var popW = popEl.offsetWidth;
	var popH = popEl.offsetHeight;
	var leftPos = (winW-popW)/2;
	var topPos = (winH-popH)/2;
	if(topPos<0){
		topPos = 0;	
	}
	if(leftPos<0){leftPos=0;};
	if(topPos<0){topPos=0;};
	popEl.style.left = leftPos+'px';
	popEl.style.top = topPos+'px';
}
function posPopup(){
	sizeMask();
	centerPop();
}
function closePopups(){
	var pageMask = document.getElementById('pMask');
	var popup = document.getElementById('popup');
	pageMask.parentNode.removeChild(pageMask);
	popup.parentNode.removeChild(popup);
	window.onresize = null;
}
function popup(sourceId,width){
	
	var sObj = document.getElementById(sourceId);
	
	//if window.popups array doesn't exist, create it
	if(!window.popUps){
		window.popUps = [];	
	}
	var winW = document.documentElement.clientWidth;
	var winH = document.documentElement.clientHeight;
	var bodyEl = document.getElementsByTagName('BODY')[0];
	bodyEl.style.position='relative';
	var overlayEl = document.createElement('DIV');
	overlayEl.id = 'pMask';
	overlayEl.className = 'pageMask';
	bodyEl.appendChild(overlayEl);
	sizeMask();
	var popEl = document.createElement('div');
	popEl.id = 'popup';
	popEl.className = 'zubePop';
	
	//alert(width);
	if(width){
		//deduct 40px to allow for padding
		popEl.style.width = (width-40)+'px';
	}
	
	//if popup content not already stored in window.popups array, add it
	if(!window.popUps[sourceId]){
		window.popUps[sourceId]=sObj.innerHTML;
		sObj.parentNode.removeChild(sObj);//destroy original div to avoid conflicts
	}
	
	//grab the popup content from window.popUps array
	popEl.innerHTML = window.popUps[sourceId];
	
	//var oContent = document.getElementById(sourceEl).innerHTML;
	//popEl.innerHTML = oContent;
	
	var popCloseEl = document.createElement('A');
	popCloseEl.className = 'popClose';
	var closeText = document.createTextNode('x');
	popCloseEl.appendChild(closeText);
	popCloseEl.onclick = function(){closePopups();};
	popCloseEl.title='close';
	popEl.appendChild(popCloseEl);
	bodyEl.appendChild(popEl);
	centerPop();
	window.onresize = function(){posPopup();};
}

//this function is used to emulate a confirm dialogue 
// linkId = id of the <a> element (the popup won't work without an id)
// text = the confirmation box text
function linkConfirmationPopup(linkId, text){
	//grab the info info from the link
	var ddLink = document.getElementById(linkId);
	var ddPath = ddLink.getAttribute('href');
	var ddTitle = ddLink.getAttribute('title');
	//create an element that we'll use to hold popup content
	var popContent = document.createElement('DIV');
	//set the ID, class, and content
	popContent.id='popContent'+linkId;
	popContent.className='hidden';
	var buffer = '<p>'+text+'</p><br />';
	buffer += '<a href="'+ddPath+'" title="confirm" class="pill"><span><b>confirm</b></span></a> ';
	buffer += '<a href="javascript:closePopups()" title="cancel" class="pill"><span><b>cancel</b></span></a>';
	popContent.innerHTML = buffer;
	//add the popup content placeholder to the page
	document.getElementsByTagName('BODY')[0].appendChild(popContent);
	popup('popContent'+linkId,400);
}

//add extra markup for rounded cornered boxes (divs)
function addCorners(){
	//alert('adding corners');
	var allDivs = document.getElementsByTagName("DIV");
	for(i=0; i<allDivs.length; i++){
		if(allDivs[i].className.search('round')>-1){
			var sPos = allDivs[i].className.search('round')+5;
			var toRound = allDivs[i].className.substr(sPos,4);
			var cc = new Array('tl','tr','bl','br');
			for(c=0; c<cc.length; c++){
				if(toRound[c]==1){
					var newCnr = document.createElement('S');
					newCnr.className = cc[c];
					allDivs[i].appendChild(newCnr);
				}
			}
		}
	}
}
//swfupload functions
//set up fake hover effect for fake browse buttons
function initSwfuButs(){
	var spans = document.getElementsByTagName("SPAN");
	var flashButs = new Array();
	for(i=0; i<spans.length; i++){
		if(spans[i].className == "flashButtonWrapper"){
			flashButs.push(spans[i]);
		}
	}
	for(i=0; i<flashButs.length; i++){
		flashButs[i].onmouseover = function(){setHoverState(this)};
		flashButs[i].onmouseout = function(){clearHoverState(this)};
	}
}
function setHoverState(obj){
	var target = obj.getElementsByTagName("A")[0];
	target.className = 'pill hovered';
}
function clearHoverState(obj){
	var target = obj.getElementsByTagName("A")[0];
	target.className = 'pill';
}
//function to select all checkboxes in specified parent element
function selectAll(t, parent, checktext, cleartext){
  var pEl = document.getElementById(parent);
  if(!pEl.sa || pEl.sa == false){
    pEl.sa = true;
    t.innerHTML = cleartext;
  }else if(pEl.sa == true){
    pEl.sa = false;
    t.innerHTML = checktext;
  }
  var items = pEl.getElementsByTagName("INPUT");
  for(i=0; i<items.length; i++){
    items[i].checked = pEl.sa;
  }
  //hilightSelected();
}
//function to update classnames on labels for selected checkboxes
function hilightSelected(){
	alert('x');
  var listEls = document.getElementsByTagName('INPUT');
  for(i=0; i<listEls.length; i++){
    if(listEls[i].className == 'zcb'){
      if (listEls[i].checked){
        var cn = 'active';
      }else{
        var cn = '';
      }
      listEls[i].parentNode.getElementsByTagName('LABEL')[0].className = cn;
    }
  }
}
//this function automatically expands textareas to contain inputted text without scrolling
function checkRows(textarea){
  if(document.getElementById(textarea)){
    var textarea = document.getElementById(textarea);
  }
  if(document.all){
    //for IE
    while (textarea.rows > 1 && textarea.scrollHeight < textarea.offsetHeight){
      textarea.rows--;
    }
    while (textarea.scrollHeight > textarea.offsetHeight){
      textarea.rows++;
    }
    return;
  }else{
    //for others
    textarea.style.height = 0;
    textarea.style.height = (textarea.scrollHeight) + "px";
  }
}
//script to cycle through expanding textareas to initialize if they have preset text
function initETA(){
  var textAreas = document.getElementsByTagName("TEXTAREA");
  var expTextAreas = new Array();
  for(i=0; i<textAreas.length; i++){
    if(textAreas[i].className.search('tAMulti')>-1){
      expTextAreas.push(textAreas[i]);
    }
  }
  for(i=0; i<textAreas.length; i++){
    checkRows(textAreas[i]);
  }
}
//expanding list functions
function initCollapsableList(id, exclusive, active){
  var listObj = document.getElementById(id);
  listObj.exclusive = exclusive;
  listObj.cList = listObj.getElementsByTagName('LI');
  var cIndex = 1;
  var openItems;
  if(active){
    var openItems = active.split(',');
  }else{
    var openItems = '';
  }
  //alert(openItems.length);
  for(i=0; i<listObj.cList.length; i++){
    //alert(i);
    var tI = listObj.cList[i];
    if(tI.className.search(/expandable/)>-1){
      //alert(cIndex);
      tI.index = cIndex;
      var links = tI.getElementsByTagName('A');
      for(c=0; c<links.length; c++){
        if(links[c].className=='tLink'){
          tI.mHeight = links[c].offsetHeight;//TODO: add 2px for borders for IE only
          links[c].index = cIndex;
          links[c].onclick=function(){toggleItem(id, this.index); return false};
        }
      }
      tI.fHeight = tI.offsetHeight;//li at full height
      var activated=false;
      for(c=0; c<openItems.length; c++){
        if(openItems[c]==tI.index){
          activated=true;
          //alert('open');
        }
      }
      if(tI.className.search(/open/)>-1){
        //alert('open');
        activated=true;
      }
      if(activated){
        //alert('activated');
        tI.cHeight = tI.fHeight;
        tI.tHeight = tI.fHeight;
        tI.active = true;
      }else{
        //alert('inactive');
        tI.cHeight = tI.mHeight;
        tI.tHeight = tI.mHeight;
        tI.style.height = tI.mHeight;
        tI.active = false;
      }
      cIndex++;
    }
  }
  setClasses(id);
  animate(id);
}
function setClasses(id){
  var listObj = document.getElementById(id);
  for(i=0; i<listObj.cList.length; i++){
    var tI = listObj.cList[i];
    if(tI.className.search(/expandable/)>-1){
      //alert('setting classes');
      var links = tI.getElementsByTagName('A');
      for(n=0; n<links.length; n++){
        if(links[n].className.search(/tLink/)>-1){
          linkEl = links[n];
          if(tI.active){
            linkEl.className='tLink open';
          }else{
            linkEl.className='tLink closed';
          }
        }
      }
    }
  }
}
function animate(id){
  var runAgain = false;
  var listObj = document.getElementById(id);
  for(i=0; i<listObj.cList.length; i++){
    var tI = listObj.cList[i];
    if(tI.className.search(/expandable/)>-1){
      var cH = tI.cHeight;
      var tH = tI.tHeight;
      var dtt = Math.abs(cH-tH);
      var move = Math.ceil(dtt/4);
      if(cH>tH){
        var nH = parseInt(cH-move,10);
        tI.style.height = nH+"px";
      }else{
        var nH = parseInt(cH+move,10);
        tI.style.height = nH+"px";
      }
      tI.cHeight = nH;
      if(dtt>0){
        runAgain = true;
      }
    }
  }
  if(runAgain){
    if(listObj.tO){
      clearTimeout(listObj.tO);
    }
    listObj.tO = setTimeout(function(){animate(id);},30);
  }
  setClasses(id);
}
function toggleItem(id, index){
  var listObj = document.getElementById(id);
  var ccId = index;
  for(i=0; i<listObj.cList.length; i++){
    var tI = listObj.cList[i];
    if(tI.className.search(/expandable/)>-1){
      if(tI.index==ccId){
        if(tI.active){//if already active, deactivate
          tI.tHeight = tI.mHeight;
          tI.active = false;
        }else{
          tI.tHeight = tI.fHeight;
          tI.active = true;
        }
      }else{
        if(listObj.exclusive){
          tI.tHeight = tI.mHeight;
          tI.active = false;
        }
      }
    }
  }
  animate(id);
}
/*manage video functions*/
function initFilePicker(){
  var divs = document.getElementsByTagName('DIV')//get all divs on page
  var fileThumbs = new Array();
  for(i=0; i<divs.length; i++){
    if(divs[i].className=='fileThumbWrap'){
      fileThumbs.push(divs[i].getElementsByTagName("IMG")[0]);
    }
  }
  for(i=0; i<fileThumbs.length; i++){
    fileThumbs[i].onclick=function(){
      if(this.parentNode.parentNode.className.search('updated')<0){//check it's not a disabled thumb
        var cb = this.parentNode.getElementsByTagName('INPUT')[0];
        if(cb.checked){
          cb.checked = false;
        }else{
          cb.checked = true;
        }
      }
    }
  }
  //check that there are no selected vids before jumping between pages
  var pLinks = document.getElementById('pagingLibrary').getElementsByTagName('A');//get list of paging links
  for(i=0; i<pLinks.length; i++){
    pLinks[i].onclick = function(){
      if(checkNoneSelected('library','You have not yet added your selected videos. Are you sure that you want to proceed and lose your selections?')){
        return true;
      }else{
        return false;
      }
    }
  }
  var pLinks = document.getElementById('pagingSelected').getElementsByTagName('A');//get list of paging links
  for(i=0; i<pLinks.length; i++){
    pLinks[i].onclick = function(){
      if(checkNoneSelected('selected','You have not yet removed your selected videos. Are you sure that you want to proceed and lose your selections?')){
        return true;
      }else{
        return false;
      }
    }
  }
}
function checkNoneSelected(pId, confMsg){
  if(isSelected(pId)){
    if(confirm(confMsg)){
      return true;
    }else{
      return false;
    } 
  }else{
    return true;
  }
}
function isSelected(pId){
  var vids = document.getElementById(pId).getElementsByTagName('INPUT');//get list of cb's
  for(i=0; i<vids.length; i++){
    if(vids[i].checked){
      return true;
    }
  }
  return false;
}
/* function to compare contents of 2 text input fields (eg. password verification) */
function checkMatch(in1Id, in2Id, ErrorPlaceholderId, ErrMsg){
  var t1 = document.getElementById(in1Id).value;
  var t2 = document.getElementById(in2Id).value;
  var errEl = document.getElementById(ErrorPlaceholderId);
  if(t2.length >= t1.length && t1!=t2){
    errEl.innerHTML = ErrMsg;
  }else{
    errEl.innerHTML = '';
  }
}
/*vid upload page functions*/
function initQuickTags(){
  var tagList = document.getElementById('quickTags').getElementsByTagName('LI');
  for(i=0; i<tagList.length; i++){
    tagList[i].onclick=function(){
      addToTagList(this);
    }
  }
  markOffTags();
}
function addToTagList(tag){
  var tagText = tag.innerHTML;
  if(tagText.substr(tagText.length-1,1)==' '){
    tagText = tagText.slice(0, -1);
  }
  var tList = document.getElementById('v_tags').value;
  var exists = false;
  if(tList!==null && tList !==''){
    var existing = tList.split(', ');
  }else{
    existing = new Array();
  }
  for(i=0; i<existing.length; i++){
    if(tagText.toUpperCase() == existing[i].toUpperCase()){
      existing.splice(i,1);
      exists = true;
    }
  }
  if(exists == false){
    existing.push(tagText); 
  }
  document.getElementById('v_tags').value = existing.join(", ");
  checkRows('v_tags');
  markOffTags();
}
function markOffTags(){/*changes class of tags to show which are already added*/
  var quickList = document.getElementById('quickTags').getElementsByTagName('LI');
  var tagList = document.getElementById('v_tags').value;
  window.existing = tagList.split(', ');
  for(i=0; i<quickList.length; i++){
    var needle = quickList[i].innerHTML;
    if(is_in_array(needle, window.existing)){
      quickList[i].className = 'active';
    }else{
      quickList[i].className = '';
    }
  }
}
//show/hide toggle function
function toggleVis(el, updateEl, showText, hideText){
  var t = document.getElementById(el);
  if(t.className.search('peekabooHide')>-1){
    t.className = t.className.replace('peekabooHide','peekabooShow');
    if (updateEl)
      updateEl.innerHTML=hideText;
  }else{
    t.className = t.className.replace('peekabooShow','peekabooHide');
    if (updateEl)
      updateEl.innerHTML=showText;
  }
}
function checkPublisher(){
  var pubId = document.getElementById('v_source_id').value;
  //alert(pubId);
  var t = document.getElementById('addPubFields');
  if(pubId=='-1'){
    t.className="peekabooShow";
    document.getElementById('v_source_name').focus();
  }else{
    t.className="peekabooHide";
  }
}
function checkCollection(){
  var collId = document.getElementById('v_collection_id').value;
  var t = document.getElementById('addColFields');
  if(collId=='-1'){
    t.className="peekabooShow";
    document.getElementById('v_collection_name').focus();
  }else{
    t.className="peekabooHide";
  }
}
/*function to see if a value if in an array (case insensitive)*/
function is_in_array(needle,haystack){
  for(c=0; c<haystack.length; c++){
    if(haystack[c].toUpperCase() == needle.toUpperCase()){
      return true;
    }
  }
  return false;
}
/*function to get mouse coordinates*/
function getMouseXY(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 + document.documentElement.scrollLeft;
    posy = e.clientY + document.body.scrollTop  + document.documentElement.scrollTop;
  }
  window.mouseX = posx;
  window.mouseY = posy;
}
/*function to get x and y co-ordinates of an element*/
function getXYpos(elem) {
   if (!elem) {
      return {"x":0,"y":0};
   }
   var xy={"x":elem.offsetLeft,"y":elem.offsetTop}
   var par=getXYpos(elem.offsetParent);
   for (var key in par) {
      xy[key]+=par[key];
   }
   return xy;
}
//set class of video thumbs (edit page) - TODO: ensure selected thumb is visible in viewport after lading (calc scroll offset)
function selectedThumb(){
  var thumbRadios = document.getElementById('vidThumbList').getElementsByTagName('INPUT');
  for(i=0; i<thumbRadios.length; i++){
    thumbRadios[i].onclick=function(){selectedThumb();}
    var t = thumbRadios[i].parentNode.getElementsByTagName('LABEL')[0]
    if(thumbRadios[i].checked){
      t.className='active';
    }else{
      t.className='';
    }
  }
}
//initialise auto-scrolling in video thumb pane 
function initThumbScroller() {
  //determine and set width of thumbnail list
  var vidThumbs = document.getElementById('vidThumbList').getElementsByTagName('SPAN');
  var n=vidThumbs.length;
  var w=(n*5)+(166*n);//assuming thumbs are 160px wide, with a 3px border and 5px right margin and the list has 5px padding all round
  document.getElementById('vidThumbList').style.width=w+'px';
  if (window.Event) {
  document.captureEvents(Event.MOUSEMOVE);
  }
  document.onmousemove = getMouseXY;
  scrollStart();
}
//start interval timer for updating scroll position 
function scrollStart(){
  if(!T_scroller){
    var T_scroller = setInterval(function(){aScroll();},30);
  }
}
function aScroll() {
  var scroller = document.getElementById('vidThumbScroller');
  var scrollerX = getXYpos(scroller)['x'];
  var scrollerW = scroller.offsetWidth;
  var content = document.getElementById('vidThumbList');
  var contentX = getXYpos(content)['x'];
  var contentY = getXYpos(content)['y'];
  var contentW = content.offsetWidth;
  var contentH = content.offsetHeight;
  var hidden = contentW-scrollerW;
  var posx = window.mouseX;
  var posy = window.mouseY;
  var s = contentW/100;
  var m = (100/scrollerW)*(posx-scrollerX);
  if(posx > contentX && posx < contentX+scrollerW && posy > contentY && posy < contentY+contentH){
    if(m<50){//going left
      var step = (50-m);
      scroller.scrollLeft -= step;
    }else{//going right
      var step = (m-50);
      scroller.scrollLeft += step;
    }
  }
}
//function to limit character count of a span
/*
USAGE: wrap text in a span, and assign class of eg. 'truncate_100_1' to it
100 = character count, 1(or 0) specifies whether to show a link to view the full text
*/
function init_truncate(moreText,lessText){
  //get all spans on page
  var spanArr = document.getElementsByTagName("SPAN");
  //loop through, find those with truncate class
  var truncateArr = new Array;
  for(i=0; i<spanArr.length; i++){
    if(spanArr[i].className.search('truncate')>-1){
      truncateArr.push(spanArr[i]);
    }
  }
  //process spans
  for(i=0; i<truncateArr.length; i++){
    var obj = truncateArr[i];
    var classes = obj.className.split(" ");
    for(c=0; c<classes.length; c++){
      if(classes[c].search('truncate_')>-1){
        var trim = classes[c].split('_')[1];
        var showLink = classes[c].split('_')[2];
      }
    }
    //store full and truncated text on span object
    var originalText = obj.innerHTML;
    if(originalText.length > trim){var truncated = true;}else{var truncated=false;}
    if(showLink == 1){
      var moreLink = " <a href='#' onclick='showMore(this.parentNode); return false;'>"+moreText+"</a>";
      var lessLink = " <a href='#' onclick='showMore(this.parentNode); return false;'>"+lessText+"</a>";
    }else{
      var moreLink = "";
      var lessLink = "";
    }
    obj.fullText = originalText + lessLink ;
    obj.smallText = originalText.substring(0,trim) + ".." + moreLink;
    obj.trimmed = truncated;
    if(truncated){
      obj.innerHTML = obj.smallText;
    }
    //obj.style.visibility='visible';
  }
}
function showMore(obj){
  if(obj.trimmed){
    obj.innerHTML = obj.fullText;
    obj.trimmed = false;
  }else{
    obj.innerHTML = obj.smallText;
    obj.trimmed = true;
  }
}
//select/change class of selected template in theme edit page
function selTemplate(id){
	//alert('changing template');
	if(id){
		document.getElementById(id).checked = true;
	}
	var inputs = document.getElementsByTagName("INPUT");
	for(i=0; i<inputs.length; i++){
		if(inputs[i].className == 'template-radio'){
			//alert('radio found');
			if(inputs[i].checked){
				inputs[i].parentNode.className = 'selected';
			}else{
				inputs[i].parentNode.className = '';
			}
		}
	}
	//if the 'template saved' message is showing, hide it
	if(document.getElementById('templateChangedMsg')){
		document.getElementById('templateChangedMsg').style.display='none';
	}
	//show an advisory message that the user should apply their changes
	var clickApplyEl = document.getElementById('clickApplyMsg');
	clickApplyEl.style.display='block';
}
//unused
function show(rating){
		var uScore = document.getElementById("vUserScore");
		var uScoreDesc = document.getElementById("scoreDesc");
		var descriptions = new Array ("","horrible","not very good","worth watching","very good","awesome!");
		//alert(rating);
		if(rating){
				uScore.className="r"+rating;
				uScoreDesc.innerHTML = descriptions[rating];
		}else{
				uScore.className="";
				uScoreDesc.innerHTML = "";
		}
}
function score(rating){
		//do ajax stuff?
		alert(rating);
		return false;
}

// Execute the [doThis] function when the Enter key s pressed
// this should be attached to the onKeyPress event of a text input
function doOnEnter(e,doThis){
  var kp;
  if(window.event){
    kp = window.event.keyCode;
  }else{
    kp = e.which;
  }
  if(kp==13){
    //enter was pressed, run the script that was passed
    doThis();
  }
}

//this function evaluates which button was pressed in the 'category name' field. (site > edit > categories > add new category)
//if it's the enter key (code 13), we need to stop the default action (submission of the main form) and trigger the CreateCategory function.
function addCatOnEnter(e){
	var key;
	if(window.event){
		key = window.event.keyCode;
	}else{
		key = e.which;
	}
	if(key==13){
		YAHOO.ZubeHost.WebmasterCategoryCreator.CreateCategory();
		return false;
	}else{
		return true;
	}
}

