/* 
	$Rev: 15 $ 
    
    Modified:
    03/04/2009      Thone       Fix color tab cookie process
	12/07/2009		Thone		Added Full Screen Media Popup
	12/15/2009		Thone		Add script that search for a tags
								and add GA code for static file tracking
    03/11/2010      Thone       Code comments
    04/28/2010      Thone       Update flash video popup function
*/

var floatingObjs = new Array();
var floatingObjsLi = new Array();
var floatingObjsDis = new Array();

var headerPanelHeight = 16;
var isLoaded = false;
var checkTimeout = 250;

//Text size
var defaultFontSize = 12;
var maxFontSize = 20;
var minFontSize = 8;

window.onresize = smcDoResizing;
window.onload = smcOnLoad;

/**
 *  setCookie sets browser cookie
 *    
 *  @param c_name (string) cookie name 
 *  @param value (string) cookie value
 *  @author Thone
 */
function setCookie(c_name,value)
{
	var exdate=new Date();
	document.cookie=c_name+ "=" +escape(value) + "; path=/;";
}

/**
 * getCookie returns cookie value for specify cookie name
 *
 * @param c_name (string) cookie name
 * @return value of the cookie name specified or blank "" if not exists
 * @author Thone
 */
function getCookie(c_name)
{
	if (document.cookie.length>0)
	{
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1)
		{ 
			c_start=c_start + c_name.length+1; 
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return "";
}

/**
 * hideSelect hides all "select" elements in the page. The function is created 
 * to solve IE bug when absolute elements was layered on top of select 
 * elements, select elements always are on top of the absolute elements and the
 * only solution is to hide them.
 *
 * @author Thone
 */
function hideSelect(){
	var s = document.getElementsByTagName('select');
	if( s == null ) return;

	for(var i = 0 ; i < s.length ; i++ )
	{
		s[i].style.visibility = 'hidden';
	}
	
}

/**
 * showSelect shows all select elements. This function is used in conjunction
 * with hideSelect. It puts all select elements back into visible state. 
 *
 * @author Thone
 */
function showSelect(){
	var s = document.getElementsByTagName('select');
	if( s == null ) return;
	
	for(var i = 0 ; i < s.length ; i++ )
	{
		s[i].style.visibility = 'visible';
	}
	
}

/**
 * findPos returns array of top left position of the object
 * 
 * @param obj (object) DOM element to get top left position
 * @return (array) coordinate [x,y] in two dimention array
 */
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}

/* ------------------- Pop up navigation menu -------------------- */

/**
 * addFloatingObj adds new floating object (popup menu) into the list
 * 
 * @params obj (string)  object id
 * @author Thone
 */
function addFloatingObj(obj)
{
	floatingObjsLi[floatingObjs.length] = 0;    //This is state of parent object, 0 means mouse is not over
	floatingObjsDis[floatingObjs.length] = 0;   //This is state of popup object, 0 means mouse is not over
	floatingObjs[floatingObjs.length] = obj;
}

/**
 * TestAndHide tests and hide if popup menu should be changed to hidden state.
 * This should happen when
 *
 *    1) mouse is not currently over the parent element
 *    2) mouse is not currently over popup menu
 *
 * @params i (integer) index the floatingObjs in the list
 * @author Thone
 */
function TestAndHide(i)
{
	if( floatingObjsDis[i] + floatingObjsLi[i] == 0 ) 
	{
		var obj = document.getElementById(floatingObjs[i]+'_dis');
		if( obj != null ) obj.style.display = 'none'; 
	}
}

/**
 * TestAndHide tests and show if popup menu should be changed to hidden state.
 * This should happen when
 *
 *    1) mouse is currently over the parent element
 *      OR
 *    2) mouse is currently over popup menu
 *
 * @params i (integer) index the floatingObjs in the list
 * @author Thone
 */
function TestAndShow(i)
{
	if( floatingObjsDis[i] + floatingObjsLi[i] > 0 ) 
	{
		var obj = document.getElementById(floatingObjs[i]+'_dis');
		if( obj != null ) obj.style.display = ''; 
	}
}

/**
 * mOutObj is called when mouse was moved out from the element area
 * it triggers test and hide 
 *
 * @params id (string) id of the floating obj
 * @params type (integer) integer indicate whether this is parent or popup menu
 * @author Thone
 */
function mOutObj(id,type)
{
	var i;
	for(i = 0 ; i < floatingObjs.length ; i++ )
	{
		if( floatingObjs[i] == id )
		{
			if( floatingObjsLi[i] != null && floatingObjsDis[i] != null )
			{
				if( type == 0 ) floatingObjsLi[i] = 0;
				else floatingObjsDis[i] = 0;

				setTimeout("TestAndHide("+i+")",checkTimeout);
			}
		}
	}
	showSelect();
}

/**
 * mOvrObj is called when mouse was moved over the element area
 * it triggers test and show 
 *
 * @params id (string) id of the floating obj
 * @params type (integer) integer indicate whether this is parent or popup menu
 * @author Thone
 */
function mOvrObj(id,type)
{
	var i;
	for(i = 0 ; i < floatingObjs.length ; i++ )
	{
		if( floatingObjs[i] == id )
		{
			if( floatingObjsLi[i] != null && floatingObjsDis[i] != null )
			{
				if( type == 0 ) floatingObjsLi[i] = 1;
				else floatingObjsDis[i] = 1;
				
				setTimeout("TestAndShow("+i+")",checkTimeout);
			}
		}
	}
	hideSelect();
}

/**
 * makeFloatingObj create all floating objects. It should only be called once 
 * just before </body>
 *
 * @author Thone
 */
function makeFloatingObj()
{
	var i;
	var loc = new Array();
	for(i=0;i<floatingObjs.length;i++)
	{
		var obj = document.getElementById(floatingObjs[i]+'_div');
		var obj_li = document.getElementById(floatingObjs[i]+'_li');
		var div_str = '';
		loc = findPos(obj_li);
		loc[1]=loc[1]+headerPanelHeight;
		
		div_str += '<div onmouseover="mOvrObj(\''+floatingObjs[i]+'\',1);" onmouseout="mOutObj(\''+floatingObjs[i]+'\',1);" class="smcFloatingDiv" id="'+floatingObjs[i]+'_dis" ';
		div_str += 'style="display:none;position:absolute;left:'+loc[0]+'px;top:'+loc[1]+'px;">'
		
		document.write(div_str);
		document.write(obj.innerHTML);
		document.write('</div>');
	}
}

/**
 * This was called automatically when browser window is resized. It 
 * recalculates new popup element position
 *
 * @author Thone
 */
function smcDoResizing() {
  //reconstruct floating objection location
  var i;
  for(i=0;i<floatingObjs.length;i++)
  {
	var obj = document.getElementById(floatingObjs[i]+'_dis');
	var obj_li = document.getElementById(floatingObjs[i]+'_li');
	var loc = new Array();
	loc = findPos(obj_li);
	loc[1]=loc[1]+headerPanelHeight;
	obj.style.left = loc[0]+'px';
	obj.style.top = loc[1]+'px';
  }
}

function smcOnLoad()
{
	isLoaded = true;
}

/* ----------------------------- Color Tab  ----------------------------- */

//this is variable to store all color tab portlet prefix
var smcPlColorTab = new Array();
//this is variable to store color of tabs for each portlet
var smcPlColorTabColor = new Array();

/**
 * getSetId searches color tab group index for specifying id name
 *
 * @params idname (string) Id name of the color tab group
 * @return index of the color tab group in the array
 */
function getSetId(idname)
{
    var i;
    for(i=0;i<smcPlColorTab.length;i++)
    {
        if( smcPlColorTab[i] == idname ) return i;
    }
    return -1;
}

/**
 * smcAddColorTabPrefix adds new prefix to the tab list. tab prefix identifies
 * tab in case there are several tab group in the same page. It must be called
 * before smcAddColorTabColor and it should be the first function in color tab
 * to be called.
 *
 * @params prefix (string) tab group prefix (aka idname)
 */
function smcAddColorTabPrefix(prefix)
{
    smcPlColorTab[smcPlColorTab.length] = prefix;
}

/**
 * smcAddColorTabColor sets color for tabs within specified tab group. 
 *
 * @params prefix (string) tab group prefix (aka idname)
 * @params colorstr (string) color string. must include "#"
 */
function smcAddColorTabColor(prefix,colorstr)
{
    var i;
    for(i=0;i<smcPlColorTab.length;i++)
    {
        if( smcPlColorTab[i] == prefix )
        {
            var size;
            if( smcPlColorTabColor[i] == null ) 
            { 
                smcPlColorTabColor[i] = new Array();
                size = 0;
            }
            else size = smcPlColorTabColor[i].length;
            smcPlColorTabColor[i][size] = colorstr;
        }
    }
}

/**
 * smcSwitchTab hides current displaying tab and show the specifying tab 
 * instead. This usually be called when a tab is clicked.
 *
 * @params idname (string) tab group prefix
 * @params tabid (string) tab index to change to
 */
function smcSwitchTab (idname,tabid)
{
    var setid;
    setid = getSetId(idname);
    if( setid < 0 ) return;

    //get bar to change color
    var evbar = document.getElementById(smcPlColorTab[setid] + "_bar");
    var evcontent;
    var i;
    if( evbar == null ) return;

    if(smcPlColorTabColor[setid][tabid]==null){
        if(smcPlColorTabColor[setid].length>0){
            tabid=0;
        }
        else {
            return;
        }
    }

    evbar.style.background = smcPlColorTabColor[setid][tabid];
    //switching contents
    for(i=0;i<smcPlColorTabColor[setid].length;i++)
    {
        evcontent = document.getElementById(smcPlColorTab[setid] + "_content_" + i);
        
        if( evcontent == null ) continue;

        if( i == tabid ) evcontent.style.display = '';
        else evcontent.style.display = 'none';
    }
    setCookie('ct_'+idname,tabid);
}

/**
 * smcInitColorTab initializes color tab. This function must be called to work. 
 * It is also get cookie to default tab selection to the latest user selected.
 * This should be called after elements for tabs are loaded.
 *
 * @params idname (string) tab group prefix
 */
function smcInitColorTab(idname) {
    var t = getCookie('ct_'+idname);
    if ( t != '' ){
        smcSwitchTab (idname,t);
    }
    else
    {
        smcSwitchTab (idname,0);
    }
}



/**
 * (depreciated)
 * smcSwitchTab is ADA Compliant version of smcSwitchTab. Currently not being 
 * used due to alternative was found.
 *
 * @params idname (string) tab group prefix
 * @params tabid (string) tab index to change to
 */
function smcSwitchTab_a (idname,tabid)
{
    smcSwitchTab (idname,tabid);
    window.location.hash=idname + "_a_" + tabid;
}


/**
 * (depreciated)
 * smcInitColorTab_a is ADA Complaint version of smcInitColorTab. The 
 * additional function allows to set tab link hyper-link and replace it with 
 * javascript tag later. This is fallback setup for browsers which do not 
 * support or have javscript disabled. Currently not being used due to 
 * alternative was found.
 *
 * @params idname (string) tab group prefix
 */
function smcInitColorTab_a(idname) {
    
    //Change A tag to call javascript instead of anchor
    //This is ADA complaint additional to the older version
    var setid;
    var i;
    setid = getSetId(idname);
    if( setid >= 0 ) 
    {
        for(i=0;i<smcPlColorTabColor[setid].length;i++)
        {
            //replace anchor with javascript
            var obj = document.getElementById(smcPlColorTab[setid] + "_a2_" + i);
            obj.href = "javascript: smcSwitchTab ('" + smcPlColorTab[setid] + "'," +  i + ");";
        }
    }

    var t = getCookie('ct_'+idname);
    if ( t != '' ){
        smcSwitchTab (idname,t)
    }
    else
    {
        smcSwitchTab (idname,0)
    }
}

/* ------------------------------ Tab  ----------------------------- */
	
var smcTabSize = new Array();

/**
 * smcAddTabPl adds tab prefex for identifying tab group.
 *
 * @params prefix (string) tab group prefix (aka idname)
 * @params size (integer) 
 */
function smcAddTabPl(prefix,size)
{
	smcTabSize[prefix] = size;
}

/**
 * smcTabChange switches tab .
 *
 * @params prefix (string) tab group prefix (aka idname)
 * @params size (integer) 
 */
function smcTabChange(prefix,id)
{
	if( smcTabSize[prefix] == null ) return;
	var i;

	for( i = 0 ; i < smcTabSize[prefix] ; i++ )
	{
		var obj = document.getElementById(prefix + "_" + i );
		var objr = document.getElementById(prefix + "_r_" + i );
		var objl = document.getElementById(prefix + "_l_" + i );
		var objd = document.getElementById(prefix + "_d_" + i );
		var objh = document.getElementById(prefix + "_h_" + i );
		
		if( obj == null || objr == null || objl == null || objd == null || objh == null ) continue;
		
		if( i == id )
		{
			obj.setAttribute("class", "smcPlTabHeaderBgSelect");
			obj.setAttribute("className", "smcPlTabHeaderBgSelect");
			
			objr.setAttribute("class", "smcPlTabHeaderRightSelect");
			objr.setAttribute("className", "smcPlTabHeaderRightSelect");
			
			objl.setAttribute("class", "smcPlTabHeaderLeftSelect");
			objl.setAttribute("className", "smcPlTabHeaderLeftSelect");
			
			objh.setAttribute("class", "smcPlTabHeaderTextSelected");
			objh.setAttribute("className", "smcPlTabHeaderTextSelected");
			
			objd.style.display = "";
		}
		else
		{
			obj.setAttribute("class", "smcPlTabHeaderBgNoSelect");
			obj.setAttribute("className", "smcPlTabHeaderBgNoSelect");
			
			objr.setAttribute("class", "smcPlTabHeaderRightNoSelect");
			objr.setAttribute("className", "smcPlTabHeaderRightNoSelect");
			
			objl.setAttribute("class", "smcPlTabHeaderLeftNoSelect");
			objl.setAttribute("className", "smcPlTabHeaderLeftNoSelect");
			
			objh.setAttribute("class", "smcPlTabHeaderText");
			objh.setAttribute("className", "smcPlTabHeaderText");
			
			objd.style.display = "none";
		}
	}
	
	setCookie('t_'+prefix,id);
}


function smcTabChange_a(prefix,id)
{
    smcTabChange(prefix,id);
    window.location.hash=prefix + "_a_" + id;
}

function smcInitTabChange(prefix) {
	var t = getCookie('t_'+prefix);
	if ( t != '' ){
		smcTabChange(prefix,t);
	}
	else
	{
		smcTabChange(prefix,0);
	}
}

//ADA Complaint version of smcInitTabChange
function smcInitTabChange_a(prefix) {
    if( smcTabSize[prefix] != null )
    {
        var i;
        for( i = 0 ; i < smcTabSize[prefix] ; i++ )
        {
            var obj = document.getElementById(prefix+"_a2_"+i);
            obj.href="javascript:smcTabChange('"+prefix+"',"+i+");";
        }
    }

	var t = getCookie('t_'+prefix);
	if ( t != '' ){
		smcTabChange(prefix,t);
	}
	else
	{
		smcTabChange(prefix,0);
	}
}

function changeFontSize(updown)
{
	var el=new Array('p','a','div','span','li','td','body','h1','h2','h3','h4');
	for(var i=0;i<el.length;i++)
	{
		var e = document.getElementsByTagName(el[i]);
		for(var j=0;j<e.length;j++)
		{
			var s = defaultFontSize;
			if( e[j].style.fontSize )
			{
				s = parseInt(e[j].style.fontSize.replace(/px|pt|em/i,""));
			}
			//going up
			if( updown == 0 )
			{
				if(s<maxFontSize)
				{
					s += 1;
				}
				try{
				e[j].style.fontSize	= s+'px';
				}catch(err){}
			}
			else
			{
				if(s>minFontSize)
				{
					s-=1;
				}
				try{
				e[j].style.fontSize	= s+'px';
				}catch(err){}
			}
		}
	}
}

/*
    - Thone -
   In order to use this function, ID of each element must corresponding to
   <id_prefix>_<number>. The element must has number range from 
   0 - (Max - 1)
*/
function swapElement(id_prefix,num,max)
{
    for(var i=0;i<max;i++){
        var element = document.getElementById(id_prefix+"_"+i);
        if( element != null ){
            if(i==num){
                element.style.display = '';
            }
            else {
                element.style.display = 'none';
            }
        }
    }
}

/*
function changeFontSize(updown)
{
	var el=new Array('p','a','div','span','li');
	for(var i=0;i<el.length;i++)
	{
		var e = document.getElementsByTagName(el[i]);
		for(var j=0;j<e.length;j++)
		{
			var s = defaultFontSize;
			if( e[j].style.fontSize )
			{
				s = parseInt(e[j].style.fontSize.replace("px",""));
			}
			//going up
			if( updown == 0 )
			{
				if(s<maxFontSize)
				{
					s += 1;
				}
				e[j].style.fontSize	= s+'px';
			}
			else
			{
				if(s>minFontSize)
				{
					s-=1;
				}
				e[j].style.fontSize	= s+'px';
			}
		}
	}
}
*/

function popUpPrintFriendly(URL) {
var printW = window.open(URL, 'printW', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=1,resizable=1,width=720,height=500,left = 152,top = 134');
}

function popUpMedia(clip,caption,live) {
   if(live==1){
      var mediaW = window.open('/vgn-ext-templating/mp/mpl.jsp?v='+clip, 'mediaW', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=440,height=320,left = 152,top = 134');
   }
   else {
       var mediaW = window.open('/vgn-ext-templating/mp/mp.jsp?v='+clip+'&cc='+caption, 'mediaW', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=440,height=320,left = 152,top = 134');
   }
}

function popUpMediaWH(clip,caption,live,cWidth,cHeight,wWidth,wHeight,top,left){
	var sWidth = screen.width-1;
	var sHeight = screen.height-1;
	var url = '';
	var config='';
	
	//set base URL
	if(live==1){
		url='/vgn-ext-templating/mp/mpl.jsp?v='+clip;
	}
	else {
		url='/vgn-ext-templating/mp/mp.jsp?v='+clip+'&cc='+caption;
	}
	//Add Clip width and height if specified
	if(cWidth!=null&&cWidth!=0&&cHeight!=null&&cHeight!=0){
		url=url+'&w='+cWidth+'&h='+cHeight;
	}
	
	if(wWidth==null||wWidth==0||wHeight==null||wHeight==0){
		wWidth=sWidth;
		wHeight=sHeight;
	}
	if(top==null||top==0){
		top=(sHeight-wHeight)/2;
		if(top < 0) top=1;
	}
	if(left==null||left==0){
		left=(sWidth-wWidth)/2;
		if(left<0) left=1;
	}
	//Base configuration
	config='toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1';//,width=440,height=320,left=152,top=134
	config=config+',width='+wWidth+',height='+wHeight+',left='+left+',top='+top;;
	var mediaW = window.open(url, 'mediaW', config);
}

//04/28/2010 Thone
function popUpVodMediaWH(clip,caption,live,cWidth,cHeight,wWidth,wHeight,top,left,vTitle,vAutoPlay,vSplashImage){
	var sWidth = screen.width-1;
	var sHeight = screen.height-1;
	var url = '';
	var config='';
	
	//set base URL
	url='/vgn-ext-templating/mp/mp.jsp?v='+clip;
    if(cWidth!=null&&cWidth!=""&&cWidth!=0)url+='&w='+cWidth;
    if(cHeight!=null&&cHeight!=""&&cHeight!=0)url+='&h='+cHeight;
    if(vTitle!=null&&vTitle!="")url+='&t='+vTitle;
    if(vAutoPlay!=null&&vAutoPlay!="")url+='&a='+vAutoPlay;
    if(vSplashImage!=null&&vSplashImage!="")url+='&s='+vSplashImage;
	
	if(wWidth==null||wWidth==0||wHeight==null||wHeight==0){
		wWidth=sWidth;
		wHeight=sHeight;
	}
	if(top==null||top==0){
		top=(sHeight-wHeight)/2;
		if(top < 0) top=1;
	}
	if(left==null||left==0){
		left=(sWidth-wWidth)/2;
		if(left<0) left=1;
	}
	//Base configuration
	config='toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1';//,width=440,height=320,left=152,top=134
	config=config+',width='+wWidth+',height='+wHeight+',left='+left+',top='+top;;
	var mediaW = window.open(url, 'mediaW', config);
}


function popUpMediaFullScreen(clip,caption,live) {
	var sWidth = screen.width-1;
	var sHeight = screen.height-1;

   if(live==1){
      var mediaW = window.open('/vgn-ext-templating/mp/mpl.jsp?v='+clip, 'mediaW', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width='+sWidth+',height='+sHeight+',left = 0,top = 0');
   }
   else {
       var mediaW = window.open('/vgn-ext-templating/mp/mp.jsp?v='+clip+'&cc='+caption, 'mediaW', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width='+sWidth+',height='+sHeight+',left = 0,top = 0');
   }
}

//link status variable
//var linkTrackerMsg = "";

//Check if this link should be tracked
function verifyLinkTracker(obj){
	var arHosts = new Array('http://www.co.sanmateo.ca.us',
		'http://10.35.55.21',
		'http://10.35.55.22',
		'http://10.35.55.25',
		'http://10.35.55.29',
		'/','./');
	var arExts = new Array('.pdf','.doc');

	var hr = obj.href;
	if (hr != null && hr.length > 0){
		//check if the begining match
		for(var j=0;j<arHosts.length;j++){
			var beginning = hr.substring(0,arHosts[j].length);
			if(beginning == arHosts[j]){
				//begining match
				for(var k=0;k<arExts.length;k++){
					if (hr.length >= arExts[k].length){
						var end = hr.substring(hr.length - arExts[k].length, hr.length);
						if( end == arExts[k] ){
							//match, execute google analytic
							var fileUrl = hr.substring(arHosts[j].length);
							return fileUrl;
							//alert('trigger: '+fileUrl);
							//pageTracker._trackPageview(fileUrl);
						}
					}
				}
			}
		}
	}
	return null;
}

//Search for all a tags and modify them if they meet conditions.
function modifyLinks(){
    var inlineLinkStartPattern = /[^{]+{\s*window.open\s*/
    var inlineLinkEndPattern = /return\s+false\s*;\s*}\s*$/
    var replacePattern = /\s*return\s+false\s*;\s*}\s*$/

	//get all anchor tag
	var arTags = document.getElementsByTagName('a');
	for(var i=0;i<arTags.length;i++){
        //linkTrackerMsg += "["+i+"] "+arTags[i].href+"\n";
        var fileUrl = verifyLinkTracker(arTags[i]);
		if (arTags[i].onclick == null && fileUrl != null ) {
            
            arTags[i].onclick = new Function("e","pageTracker._trackPageview('"+fileUrl+"');return true;");
            
            //linkTrackerMsg += ">>> "+arTags[i].onclick+"\n";
		}
        else if(arTags[i].onclick != null && fileUrl != null){
            var funcBody = arTags[i].onclick.toString();
            
            //possibly inline-link
            //linkTrackerMsg += "+++ "+funcBody+"\n";
            
            if( inlineLinkStartPattern.test(funcBody)
                && inlineLinkEndPattern.test(funcBody)
                && replacePattern.test(funcBody) ) {
                
                //remove functin heading
                funcBody = funcBody.replace(/^[^{]+{/,"");
                //replace at the end of the function
                funcBody = funcBody.replace(replacePattern,"pageTracker._trackPageview('"+fileUrl+"');return false;");
                arTags[i].onclick = new Function("e",funcBody);
                
            }
            //linkTrackerMsg += ">>> "+arTags[i].onclick+"\n";
        }
	}	
}
