var DOMloaded=false;
jQuery(document).ready(
	/*
	This function gets loaded when all the HTML, not including the portlets, is
	loaded.
	*/
	function() {
		
		if(isIE6()) {
			if(jQuery("#scroll_container").length > 0) {
				jQuery("#scroll_container .first_article_no_border .two_columns").css(
				{
					"display" : "inline",
					"margin-right" : "2px"
				});
				
				jQuery("#scroll_container .last_article_no_border .two_columns").css(
				{
					"display" : "inline",
					"margin-right" : "0px"
				});
				
				jQuery("#scroll_container .one_column").each(function() {
					jQuery(this).css("margin-right", "2px");
				})
			}			
			
			if ((jQuery("#home_menu").length > 0) && (jQuery("#home_menu").attr("rel") === "vb_home_layouttpl")) {
				jQuery(".right_floated_container").css({
					"position": "relative",
					"float": "right",
					"display": "block",
					"margin-right": "-6px",
					"width": "186px"
				});				
			}
			
			if(jQuery("#menu").attr("rel") === "vb-sme-inner-layouttpl") {
				jQuery(".right_floated_container").css({
					"position": "relative",
					"float": "right",
					"display": "block",
					"margin-right": "1px",
					"width": "186px"
				});
				
				jQuery(".three_columns_full_width").css(
				{
					"margin-left" : "1px",
					"width" : "558px"
				});
				
				jQuery("#third_row").css(
				{
					"margin-top" : "0",
					"margin-left" : "0"
				});
				
				jQuery("#row_container .left_floated_container").css(
				{
					"width" : "550px"
				});
				
				jQuery("#body_content .pagebuilder .three_columns_full_width").css("width", "570px");
			}
			
			if (jQuery("#menu").attr("rel") === "vb-sme-content-layouttpl") {
				jQuery(".left_floated_container .four_columns_content_container").css(
				{
					"margin-right" : "4px",
					"width" : "705px"
				});
			}
		}
		
        DOMloaded=true;
		try {    
	        loadModules();
	    } catch(e) {
	        //don't have modules on the page
	    }
		
		if((jQuery("#menu").length !== 0) && (jQuery("#terms").length !== 0)) { 
		    jQuery("#menu").css("margin-bottom", "6px");
		}
		
		compatibilityNotifier();
		
		/* Removes dotted lines that appear when a link is clicked in for example Firefox. This is a usability enhancement
		 * added by browsers but needs to be removed for this site.
		 */
		jQuery("a").focus(function() {
			if(jQuery(this).blur()) {
				jQuery(this).blur();
			}
		});
		jQuery(":radio").focus(function() {
			if(jQuery(this).blur()) {
				jQuery(this).blur();	
			}
		});
		
		/* Fix for inner templates spacing between first row and third row when second row is empty */
		if(!isBrowser("MSIE 7.")) {
			fixInnerTemplate();
		}	
		
		if(jQuery(".sub_footer").length > 0) {
			highlightQuicklink();
		}
		
		jQuery(".VBAccordionHeadLink .portlet-topper").hover(
			function() {
				jQuery(this).removeClass("portlet-topper").addClass("portlet-topper-hover");
			},
			function() {
				jQuery(this).removeClass("portlet-topper-hover").addClass("portlet-topper");
			}
		);
		
		if(jQuery(".VBAccordionBodyExpandedState").length > 0 ) {
		    setAccordionExpandedHeight();
		}
		
		jQuery("#scrollable tbody tr:odd td").removeClass("odd").addClass("odd");
		fixPopUp();		
	}
);

Liferay.Portlet.ready(

	/*
	This function gets loaded after each and every portlet on the page.

	portletId: the current portlet's id
	jQueryObj: the jQuery wrapped object of the current portlet
	*/

	function(portletId, jQueryObj) {

	}
);

jQuery(document).last(

	/*
	This function gets loaded when everything, including the portlets, is on
	the page.
	*/

	function() {
		
	}
);

var ie6 = function() {
	
	var isVBCLoginPage;
	if(jQuery("#home_menu").attr("rel") === "vbc-login-layouttpl") {
		isVBCLoginPage = true;	
	};
	
	if(isVBCLoginPage) {
		jQuery("#my_account").css(
		{
			"margin-right" : "30px",
			"width" : "180px"
		});
	}
}
var compatibilityNotifier = function() {

	if(readCookie('compatibility') !== "accepted") {
		if(isUserAgent("Firefox")) {
			if(isBrowserVersion("3.5.") == false && isBrowserVersion("3.6.") == false) {
				jQuery("body").append("<div id='notifier'></div><div id='compat_notify'><p>This website is best viewed in Firefox 3.5 and up or Internet Explorer 6 and above.</p><p><a href='#' title='Accept' class='blue_button' onclick='closeNotifier();'>Accept</a></p></div>");
				jQuery("#notifier").fadeTo("fast", 0.4);
			}
		}
		
		if(isWebKit()) {
			jQuery("body").append("<div id='notifier'></div><div id='compat_notify'><p>This website is best viewed in Firefox 3.5 and up or Internet Explorer 6 and above</p><p><a href='#' title='Accept' class='blue_button' onclick='closeNotifier();'>Accept</a></p></div>");
			jQuery("#notifier").fadeTo("fast", 0.4);
		}
	}	
}
var closeNotifier = function() {
	jQuery("#notifier").remove();
	jQuery("#compat_notify").remove();
	createCookie('compatibility', 'accepted', 1);
}
var isBrowserVersion = function(key) {
	if(navigator.userAgent.indexOf(key) > -1) {
		return true;
	}
	return false;
}

var isUserAgent = function(browser) {
	if(navigator.userAgent.indexOf(browser) > -1) {
		return true;
	}
	return false;
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
/* 
 * Receives a URL, closes the active window 
 * and redirects the parent window to the new URL
 * 
 * url : the new URL
 */
var closeRedirect = function(url) {
	if(window.opener !== null) {
		window.opener.location = url;
		window.close();
	} else {
		window.close();
		window.open(url);
	}	
}
/*
 * Function sets the width of the wrapper element to prevent IE and Chrome
 * from incorrectly centering the content inside the pop-up's. Also adjusts the width 
 * of the container DIV to avoid scroll bars in Webkit based browsers.
 */
var fixPopUp = function() {
	var wrapperSelector = jQuery("#wrapper");
	
	if(jQuery(".popup_content_container_no_logo").length != 0) {
		/*
	 	* Should create the "options" object once and re-use
	 	*/
		jQuery(wrapperSelector).css({
			"margin-left" : "0",
			"width" : "570px"
		});
		jQuery("form[name='hrefFm']").css("display", "none");
	}
	
	if(jQuery(".popup_content_container").length != 0) {
		jQuery(wrapperSelector).css({
			"margin-left" : "0",
			"width" : "570px"
		});
		jQuery("form[name='hrefFm']").css("display", "none");
	}
	
	if(jQuery("#tools_container").length != 0) {
		jQuery(wrapperSelector).css({
			"margin-left" : "0",
			"width" : "570px"
		});
		jQuery("form[name='hrefFm']").css("display", "none");
	}
}

/*
 * Finds a link with a matching friendly URL in the sub footer and adds the CSS class 
 * selected to it, which will bold the link item.
 */
var highlightQuicklink = function() {
	var currentURL = window.location.href;
  
	if (currentURL != null && currentURL != "") {
		var startIndex = currentURL.lastIndexOf("/");
		var friendlyUrl = currentURL.substring(startIndex+1,currentURL.length);
		
		jQuery('.sub_footer  a[href$=\'' + friendlyUrl + '\']').addClass('submenu_selected');
	
	}
}

var fixInnerTemplate = function() {
	if(jQuery("#general_column div").length <= 5) {
		    jQuery("#general_column").hide();
	}
	
	if(isIE6() && (jQuery("#general_column div").length <= 6)) {
		 jQuery("#general_column").hide();
	}
	
	if((jQuery("#body_content").length !== 0) && (jQuery("#second_row .empty").length !== 0)) {
		jQuery("#second_row").css("margin-top", "0px");	   
	}
}

function isBrowser(key){
    
    var UserInfo=navigator.userAgent.toUpperCase();
    if (UserInfo.indexOf(key)>-1){
        return true;
    }else{
        return false;
    }

}

function isMicrosoft(){
    return isBrowser("MSIE");
}

function isFirefox(){
    return isBrowser("FIREFOX");
}


function isSafari(){

    return isBrowser("SAFARI") && !isBrowser("CHROME"); 
}

function isIE6(){
    
    return isBrowser("MSIE 6.");
}

function isWebKit(){
    return isBrowser("WEBKIT");
}

(function($){$.fn.bgIframe=$.fn.bgiframe=function(s){if($.browser.msie&&/6.0/.test(navigator.userAgent)){s=$.extend({top:'auto',left:'auto',width:'auto',height:'auto',opacity:true,src:'javascript:false;'},s||{});var prop=function(n){return n&&n.constructor==Number?n+'px':n;},html='<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+'style="display:block;position:absolute;z-index:-1;'+(s.opacity!==false?'filter:Alpha(Opacity=\'0\');':'')+'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+'"/>';return this.each(function(){if($('> iframe.bgiframe',this).length==0)this.insertBefore(document.createElement(html),this.firstChild);});}return this;};})(jQuery);

/**
 * @author neethlsc
 */
jQuery(document).ready(function() {	
	
	jQuery(".selected > ul").show("slow");
	jQuery(".selected > ul").addClass("expanded");
	
	jQuery(".expand").click(function() {	
			
		var menuVisible = false;
		
		if(menuVisible == false) {
			jQuery(this).next().addClass("expanded");
			jQuery(this).next().slideToggle("slow");
			menuVisible = true;
		} else if(menuVisible == true) {
			jQuery(this).next().slideToggle("slow");
			jQuery(this).next().removeClass("expanded");
			menuVisible = false;
		}
		
		return false;
	});
	
	jQuery(".subnav > li > a").click(function() {
		handleSecondLevelEvents(jQuery(this));
	});
	
	/*
	 * The functionality for the first and second level menu items are as follows:
	 * TODO
	 */
	var menuItemVisible = false;
	
	jQuery("#nav_level1 > li > a").click(function() {
		
		if (jQuery(this).hasClass("show_second_level")) {			
			
			clickedMenuItemClass = jQuery(this).attr("rel");
		
			jQuery("#nav_level1 > li > a").each(function() {
				if(jQuery(this).parent().hasClass("level1_selected")) {
					jQuery(this).parent().removeClass("level1_selected");
					currentSecondLevelClassName = jQuery(this).attr("rel");
					jQuery("." + currentSecondLevelClassName).hide();
				}
			});	
					
			if((clickedMenuItemClass != "") && (jQuery(this).parent().hasClass("level1_selected") == false)) {
				jQuery(this).parent().addClass("level1_selected");
				jQuery("." + clickedMenuItemClass).show("slow");
				menuItemVisible = true;
			} else if((clickedMenuItemClass != "") && (jQuery(this).parent().hasClass("level1_selected") == true)) {
				jQuery(this).parent().removeClass("level1_selected");
				jQuery("." + clickedMenuItemClass).hide("slow");
				menuItemVisible = false;
			}			
		}
	});
});

var handleSecondLevelEvents = function(currentItem) {
	
}

// Replaces all instances of the given substring.
String.prototype.replaceAll = function(strTarget, strSubString) {
	var strText = this;
	var intIndexOfMatch = strText.indexOf( strTarget );
	 
	// Keep looping while an instance of the target string
	// still exists in the string.
	while (intIndexOfMatch != -1) {
	// Relace out the current instance.
	strText = strText.replace( strTarget, strSubString )
	 
	// Get the index of any next matching substring.
	intIndexOfMatch = strText.indexOf( strTarget );
	}
	 
	// Return the updated string with ALL the target strings
	// replaced out with the new substring.
	return(strText);
}

var setCookie = function(cookie_name,value,expiredays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = cookie_name + "=" + value + ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

var getCookie = function(cookie_name) {
	if (document.cookie.length > 0) {
		c_start = document.cookie.indexOf(cookie_name + "=");
		if (c_start != -1) {
		    c_start = c_start + cookie_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 "";
}


/* Copyright (c) 2006 Mathias Bank (http://www.mathias-bank.de)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * Thanks to Hinnerk Ruemenapf - http://hinnerk.ruemenapf.de/ for bug reporting and fixing.
 */
jQuery.extend({
/**
* Returns get parameters.
*
* If the desired param does not exist, null will be returned
*
* @example value = $.getURLParam("paramName");
*/ 
 getURLParam: function(strParamName){
	  var strReturn = "";
	  var strHref = window.location.href;
	  var bFound=false;
	  
	  var cmpstring = strParamName + "=";
	  var cmplen = cmpstring.length;

	  if ( strHref.indexOf("?") > -1 ){
	    var strQueryString = strHref.substr(strHref.indexOf("?")+1);
	    var aQueryString = strQueryString.split("&");
	    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
	      if (aQueryString[iParam].substr(0,cmplen)==cmpstring){
	        var aParam = aQueryString[iParam].split("=");
	        strReturn = aParam[1];
	        bFound=true;
	        break;
	      }
	      
	    }
	  }
	  if (bFound==false) return null;
	  return strReturn;
	}
});

/* VODACOM BUSINESS */

function getThemeImagePath(){
    if(themeDisplay){
        return themeDisplay.getPathThemeImages();       
    }else{
        return "";
    }
}


function unrollMainMenu()
{
	var vTable=document.createElement("TABLE");
	vTable.setAttribute('cellSpacing',0);
    vTable.setAttribute('cellPadding',0);
    vTable.setAttribute('className','mainMenuTable');
    vTable.setAttribute('class','mainMenuTable');
    
    var vTableBody=document.createElement("TBODY");
	var vTR=document.createElement("TR");
	
	if (mainMenu==null)
		return;
	
	for (var x=0;x<mainMenu.length;x++)
	{
		var vTD=document.createElement("TD");
		
		var vItemParts=mainMenu[x].split(",");
		

		var vInnerTable=document.createElement("TABLE");
        vInnerTable.setAttribute('cellSpacing',0);
        vInnerTable.setAttribute('cellPadding',0);

		var vInnerTableBody=document.createElement("TBODY");
		var vInnerTR=document.createElement("TR");
		
		//var vInnerTD=document.createElement("<TD class=mnuMain id=mnuXCHILD"+vItemParts[0]+" onmouseover=xxOverWrapper("+vItemParts[0]+",true); onclick=xxClick('"+vItemParts[1]+"'); onmouseout=xxOut("+vItemParts[0]+",true); name='mnuXCHILD'>");
        var vInnerTD=document.createElement("TD");
        vInnerTD.setAttribute('id',"mnuXCHILD"+vItemParts[0]);
        vInnerTD.setAttribute('name',"mnuXCHILD");
        vInnerTD.setAttribute('className','mnuMain');
        vInnerTD.setAttribute('class','mnuMain');
        vInnerTD.setAttribute('seq',vItemParts[0]);
        vInnerTD.setAttribute('seqClick',vItemParts[1]);
        vInnerTD.onmouseover = function() { xxOverWrapper(this.getAttribute("seq"),true); };
        vInnerTD.onmouseout = function() { xxOut(this.getAttribute("seq"),true); };
        vInnerTD.onclick= function() { xxClick(this.getAttribute("seqClick"),this.getAttribute("seq")); };

	    /*var vSpaceDiv=document.createElement("div");
        vSpaceDiv.setAttribute('className','menuSpacer');
        vSpaceDiv.setAttribute('class','menuSpacer');
        vInnerTD.appendChild(vSpaceDiv);*/
        
        if (vItemParts.length>3 && vItemParts[4]!=null && vItemParts[4]!="") {

            var vMenuIcon=document.createElement("img"); 

            if(themeDisplay){
            
                vMenuIcon.setAttribute('src',themeDisplay.getPathThemeImages()+"/"+vItemParts[4]);
            }else{
                vMenuIcon.setAttribute('src',getContextPath()+vItemParts[4]);
            }
            vInnerTD.appendChild(vMenuIcon);

        }else{
        
        
            var vWordAlignDiv=document.createElement("div");
            vWordAlignDiv.setAttribute('className','menuTextDiv');
            vWordAlignDiv.setAttribute('class','menuTextDiv');
            var vWords=document.createTextNode(vItemParts[2]);
            
            vWordAlignDiv.appendChild(vWords);
            
    
            //var vBR=document.createElement("br");
            //vWordAlignDiv.appendChild(vBR);
    
            
            if (vItemParts.length>2 && vItemParts[3]!=null && vItemParts[3]!="") {
    
                var vCommentSpan=document.createElement("div");
                vCommentSpan.setAttribute('className','menuComment');
                vCommentSpan.setAttribute('class','menuComment');
    
                var vWordsComment=document.createTextNode(vItemParts[3]);
        		vCommentSpan.appendChild(vWordsComment);
                vWordAlignDiv.appendChild(vCommentSpan);
            }
    
    		vInnerTD.appendChild(vWordAlignDiv);

        }

		vInnerTR.appendChild(vInnerTD);
		vInnerTableBody.appendChild(vInnerTR);
		vInnerTable.appendChild(vInnerTableBody);
		
		vTD.appendChild(vInnerTable);
		vTR.appendChild(vTD);
	}
	
	vTableBody.appendChild(vTR);
	vTable.appendChild(vTableBody);
	
	var menuStart=document.getElementById("menuOrigin");
	if (menuStart!=null)
		menuStart.appendChild(vTable);
}


function unrollMenuSubMenu(pIndex)
{
	var vSubMenuString=subMenus[pIndex];
	if (vSubMenuString.charAt(vSubMenuString.length-1)=='|')
	{
		vSubMenuString=vSubMenuString.substring(0,vSubMenuString.length-1);
	}
	
	var vSubMenuItems=vSubMenuString.split("|");
	if (vSubMenuItems.length>0)
	{
		var vOuterTable=document.createElement("TABLE");
        vOuterTable.setAttribute('cellSpacing',0);
        vOuterTable.setAttribute('cellPadding',0);
		var vOuterTableBody=document.createElement("TBODY");
		
		var vDivId="mnuCONT"+pIndex;;
		//var vDiv=document.createElement("<DIV class=mnuCONT id='"+vDivId+"' name='mnuCONT' style='z-index:99;'>");
        var vDiv=document.createElement("DIV");
        vDiv.setAttribute('id',vDivId);
        vDiv.setAttribute('name',"mnuCONT");
        vDiv.setAttribute('className','mnuCONT');
        vDiv.setAttribute('class','mnuCONT');
        vDiv.setAttribute('style','z-index:99;');

		var vTable=document.createElement("TABLE");
        vTable.setAttribute('cellSpacing',0);
        vTable.setAttribute('cellPadding',0);


		var vTableBody=document.createElement("TBODY");	
	
		for (var y=0;y<vSubMenuItems.length;y++)	
		{
			var vTR=document.createElement("TR");
			var vItemParts=vSubMenuItems[y].split(",");

            //if url mapping is - then pass through the seq id
            var link=vItemParts[1];
            if (link=="U:-") {
                link=vItemParts[0];
            }

			//var vTD=document.createElement("<TD style='z-index:99' class=mnuC1 id=mnuXCHILD"+vItemParts[0]+" onmouseover=xxOverWrapper("+vItemParts[0]+",false); url='"+link+"' onclick='xxClick(this.url);' onmouseout='xxOut("+vItemParts[0]+");' noWrap name='mnuXCHILD'>");
            vTD=document.createElement("TD");
            vTD.setAttribute('id',"mnuXCHILD"+vItemParts[0]);
            vTD.setAttribute('name',"mnuXCHILD");
            vTD.setAttribute('className','mnuC1');
            vTD.setAttribute('class','mnuC1');
            //vTD.setAttribute('align','right');
            vTD.setAttribute('seq',vItemParts[0]);
            vTD.setAttribute('style','z-index:99;');
            vTD.setAttribute('noWrap','true');            
            vTD.setAttribute('url',link);
            
            vTD.onmouseover = function() { xxOverWrapper(this.getAttribute("seq"),false); };
            vTD.onmouseout = function() { xxOut(this.getAttribute("seq"),false); };
            vTD.onclick= function() { xxClick(this.getAttribute("url"),this.getAttribute("seq")); };
			
			var vWords=document.createTextNode(vItemParts[2]);				
			vTD.appendChild(vWords);
			vTR.appendChild(vTD);
			
			var vTDArrow;
            var ArrowText="";
			if (vItemParts.length>3 && vItemParts[3]=="1")
			{
                ArrowText=">";
            
            }
				
            //vTDArrow=document.createElement("<TD class=mnuC2 id=mnuXARR"+vItemParts[0]+" onmouseover=xxOverWrapper("+vItemParts[0]+",false); onmouseout=xxOut("+vItemParts[0]+",false); align=right name='mnuXARR'>");
            vTDArrow=document.createElement("TD");
            vTDArrow.setAttribute('id',"mnuXARR"+vItemParts[0]);
            vTDArrow.setAttribute('name',"mnuXARR");
            vTDArrow.setAttribute('className','mnuC2');
            vTDArrow.setAttribute('class','mnuC2');
            vTDArrow.setAttribute('align','right');
            vTDArrow.setAttribute('seq',vItemParts[0]);
            vTDArrow.onmouseover = function() { xxOverWrapper(this.getAttribute("seq"),false); };
            vTDArrow.onmouseout = function() { xxOut(this.getAttribute("seq"),false); };

            var vArrowWords=document.createTextNode(ArrowText);
            vTDArrow.appendChild(vArrowWords);							
				
			vTR.appendChild(vTDArrow);
			vTableBody.appendChild(vTR);
		}
		
		vTable.appendChild(vTableBody);
		vDiv.appendChild(vTable);
		
		var menuStart=document.getElementById("menuOrigin");
		if (menuStart!=null)
			menuStart.appendChild(vDiv);
	
	}                                                           
}

var lastMainMenuSeq;
function xxOverWrapper(pSeq,isMainMenu)
{    

	var vIndex=xxGetChildContainer(pSeq);
	if (vIndex!=-1)
	{
				
		var vSubMenu=document.getElementById("mnuCONT"+vIndex);
		//only generate submenu if it hasn't been generated previously
		if (vSubMenu==null || vSubMenu==undefined)
		{
			unrollMenuSubMenu(vIndex);

		}
		else
		{
			//window.status="created before - "+pSeq;
		}
	}
    
	xxOver(pSeq,vIndex);

    if (isMainMenu){
    
        var newMenuItem=document.getElementById("mnuXCHILD"+pSeq);
        if (newMenuItem!=null){
            newMenuItem.className="mnuMainOver";
            lastMainMenuSeq=pSeq;
            var comments=newMenuItem.getElementsByTagName("div");
            if (comments!=null && comments.length>1) {
                comments[1].className="menuCommentOver";
            }
        } 
    }

    
}

/*WCM functions*/

function quickLink(selectControl){
  if(selectControl.value!=""){
      window.location.href=selectControl.value;
  }
}

function showProductDescription(aControl, id){
    var productDesc=jQuery(aControl).parents(".productDescTable").find(".productDesc");
    var nextDesc=jQuery(productDesc).find("#"+id);

    jQuery(productDesc).find(".productDescContainer").css("display","none");
    jQuery(nextDesc).show();

    jQuery(aControl).parent().find(".productDescMenuActive").removeClass();
    jQuery(aControl).removeClass().addClass("productDescMenuActive");

}


function highlightImageRotateKeys(container,index,currentIndex){
    
    var keyContainer=jQuery(container).find(".imageRotateKeys");
    if(currentIndex>-1){
        jQuery(keyContainer).find("#key"+(currentIndex+1)).removeClass().addClass("imageRotateKey");                   
    }
    jQuery(keyContainer).find("#key"+(index+1)).removeClass().addClass("imageRotateKey_o");

}

function setImageRotate(containerId,divId,index,pause,oldIndex){
    var container=jQuery("#"+containerId);
            
    if(pause){
        jQuery(container).attr("pause","true");
    }

    var nextDiv=jQuery(container).find("#"+divId);

    jQuery(container).find(".imageRotateDiv").css("display","none");
    jQuery(nextDiv).show();

    if(pause){
        var currentIndex=jQuery(container).attr("currentIndex");
        var currentIndexInt=parseInt(currentIndex);
        oldIndex=currentIndexInt;
        index=index-1;
        jQuery(container).attr("currentIndex",index+"");
    }

    highlightImageRotateKeys(container,index,oldIndex);
}


function rotateImageBanner(containerId,seconds,bannerSize){
    
    var container=jQuery("#"+containerId);
    var pause=jQuery(container).attr("pause");

    if(pause=="true"){
        return;
    }

    
    var currentIndex=jQuery(container).attr("currentIndex");
    var currentIndexInt;

    if(currentIndex==undefined || currentIndex==null || currentIndex==""){
      jQuery(container).attr("currentIndex","0");
      currentIndex="-1";
    }

    var reset=false;
    var tempIndex;
    currentIndexInt=parseInt(currentIndex);
    tempIndex=currentIndexInt;
    if(bannerSize-1<=currentIndexInt){
        currentIndexInt=-1;
        reset=true;
    }
    
    currentIndexInt=currentIndexInt+1;
    jQuery(container).attr("currentIndex",currentIndexInt+"");


    if(currentIndexInt>0 || reset==true){

        setImageRotate(containerId,"imageRotateDiv"+currentIndexInt,currentIndexInt,false,tempIndex);        

    }else{
        highlightImageRotateKeys(container,currentIndexInt,tempIndex);
    }

    setTimeout("rotateImageBanner('"+containerId+"',"+seconds+","+bannerSize+")", seconds*1000);

}


/*End of WCM functions*/
function takeMeToVodaBizConnect(place){ 	
    window.location.href=window.location.protocol+"//"+window.location.host+"/group/vodabizconnect/"+place;
}
function takeMeToVodaBizConnectPublic(place) {            
    window.location.href=window.location.protocol+"//"+window.location.host+"/web/vodabizconnect/"+place;
}
function takeMeToVodacomBusiness(place){	
    window.location.href=window.location.protocol+"//"+window.location.host+"/web/vodacombusiness/"+place;
}
function takeMeToPortal(place)
{
	if(themeDisplay) {
		var layoutUrl=themeDisplay.getLayoutURL();
		var lastSlash=layoutUrl.lastIndexOf("/");
		layoutUrl=layoutUrl.substring(0,lastSlash+1);
		//window.navigate doesn't work in firefox!                      
		window.location.href=window.location.protocol+"//"+window.location.host+layoutUrl+place;
	} else {
		window.location.href=window.location.protocol+"//"+window.location.host+"/group/vodabizconnectnew/"+place;
	}
}
function takeMeToRelative(place){
    window.location.href=window.location.protocol+"//"+window.location.host+place;
}
function redirect(_url) {
	window.location.href = window.location.protocol + "//" + window.location.host + _url;
}

function getContextPath(){
    return window.location.protocol+"//"+window.location.host;
}

//input is either a string URL or the id of the calling element
function xxClick(pAction,pSeq)
{    


    //SetCookieWithPath(pMaxiCookieName,null,"/");
    if ( pAction == "NONE" ) return;

    //if we get an id parameter and not a url then we want to call the parent URL!!!
        
    if (!isNaN(pAction))
    {   
        var currentItem=document.getElementById("mnuXCHILD"+pAction);
        if (currentItem!=null) {      
            while (currentItem.parentNode.tagName!="DIV")
            {
                currentItem=currentItem.parentNode;
            }
            
            var currentItemId=currentItem.parentNode.id;
            var parentLink=document.getElementById("mnuXCHILD"+arContainerHolder[currentItemId.substring(7,currentItemId.length)]);
            if (parentLink!=null) {

                pAction=parentLink.url;
            }
         }
    }

    //var oForm = document.getElementById("MIIMenuForm2");
    var ar = pAction.split(":");
    var ar1 = pAction.substr(0,1);
    var s2 = pAction.substr(2,pAction.length);
       while( s2.indexOf("`") > -1 )
          s2 = s2.replace("`","'");

    if ( ar1 == "U" )
    {
        //oForm.action="http://"+window.location.host+"/wps/myportal/"+ar[1];
        //storeLastPageVisited(window.location.href,"http://"+window.location.host+"/wps/myportal/"+ar[1]);
        //oForm.submit(); 

        //remove crumbs
        //SetCookieWithPath("lastSeqClicked",pSeq,"/");
        if(ar[1]!=-1){
        
            takeMeToPortal(ar[1]);
        }
    }
    else if ( ar1 == "J" )
	{
	  eval(s2);
	}
}




function SetCookieWithPath(sName, sValue, sPathName)
{
    document.cookie = sName + "=" + escape(sValue) + "; path=" + sPathName;
}


function GetCookie(sName)
{
	var aCookie = document.cookie.split("; ");

	for (var i=0; i < aCookie.length; i++)
	{
		var aCrumb = aCookie[i].split("=");
		if (sName == aCrumb[0])
			{
			//alert("Getting cookie ::: " + unescape(aCrumb[1]))
			return unescape(aCrumb[1]);
			}
	}
}

var xxTmr = null;
function xxOver(pSeq,pIndex)
{
    var ixLeft = 0;
    var ixTop = 0;
    var boxX = 0;
    var boxY = 0;
    var oxP = null;
    var omnu = null;
    var oarr = null;
    
    window.clearTimeout(xxTmr);

    omnu = document.getElementById("mnuXCHILD"+pSeq);

    //if we have the index already don't do search again.
    var vIdx;
    if (pIndex==-1 || pIndex==undefined)
    	vIdx = xxGetChildContainerBinary(pSeq);
    else
    	vIdx=pIndex;
    
     
    
    if ( vIdx != -1 )
    {
        var occ = document.getElementById("mnuCONT"+vIdx);
        
        if ( sRootIds.indexOf( "["+pSeq+"];" ) >= 0 )
        {
            // Hide everything else first.
            xxHideAll(); 
            
            //use parentNode instead of parentElement!!!
            oxP = omnu.parentNode;

            //when using parentNode might get an undefined tag at the end!!!
            while ( oxP != null && oxP.tagName!=undefined)
            {
                //VBContent has position relative so we don't need it's offsetLeft!
                if (oxP.className=="VBContent") {
                    break;
                }

                ixLeft += oxP.offsetLeft;
                ixTop += oxP.offsetTop;
                oxP = oxP.parentNode;
            }

            var customBuffer=0;

            var isIExplorer=isMicrosoft();
            if (isIExplorer){
                customBuffer=0;
            }else if(isWebKit()){
                customBuffer=35;
            }else{
                customBuffer=5;
            }

            //cater for cornered edges on menu
            customBuffer=customBuffer+10;            
            
            boxX = ixLeft-customBuffer;
            //boxY = ixTop-24;
            boxY = omnu.style.top;
            
        }
        else
        {            
            
            oarr = document.getElementById("mnuXARR"+pSeq);
            omnu.className = "mnuCO1";
            oarr.className = "mnuCO2";
            // First hide all the containers dependant on this one.
            xxHideAllFor(pSeq);
            
            var vW = omnu.clientWidth+oarr.clientWidth;
            oxP = omnu.parentNode;
            while ( oxP != null && oxP.tagName!=undefined)
            {
                ixLeft += oxP.offsetLeft;
                ixTop += oxP.offsetTop;
                oxP = oxP.parentNode;
            }

            var pageWidth=document.getElementById("VBContent").clientWidth;
            var sideBarBuffer=0;

            if (document.body.scrollWidth>pageWidth) {                
                sideBarBuffer=(document.body.clientWidth-pageWidth)/2;
                //cater for precison lost
                if (document.body.clientWidth%2==0){
                    sideBarBuffer=sideBarBuffer+1;
                }else{
                    var isIExplorer=isMicrosoft();
                    if (!isIExplorer){
                        sideBarBuffer=sideBarBuffer+2;
                    }
                }

                
            }else{
                sideBarBuffer=1;                
            }            

            //window.status=window.screen.availWidth+" vs "+document.body.scrollWidth;
            boxX = ixLeft+vW-sideBarBuffer-3;
            //boxY = ixTop-227;
            //boxY = ixTop-376;

            var parentOfSource = omnu.parentNode;
            //offset of parent Menu div to top of body + offset of menu item to top of parent menu div
            boxY=parentOfSource.parentNode.parentNode.parentNode.offsetTop+parentOfSource.offsetTop;
            
        }

        // Check Pos
		var winWidth = document.body.clientWidth;
		var winHeight = document.body.clientHeight;

        // Move off sreen to display and get width.
        occ.style.left = boxX;
        occ.style.display='block';
        
        // If too far right, move it left.
		if ( (winWidth - boxX) < occ.clientWidth )
		{
            var vMyIdx = -1;
    		var ii = 0;
    		for ( ii=0; ii<arContainers.length; ii++ )
    		{
                if ( arContainers[ii].indexOf("["+pSeq+"];") >= 0 )
                    vMyIdx = ii;
            }

            if ( vMyIdx != -1 )
            {
                var oMyCon = document.getElementById("mnuCONT"+vMyIdx);
                if ( oMyCon != null )
                {
                    if ( oMyCon.style.left == "" ) oMyCon.style.left = winWidth;
                    boxX = winWidth - (winWidth-parseInt(oMyCon.style.left)) - occ.clientWidth-1;
                }
            }
        }

        //with strict doctype and firefox - you need to add "px" to the end of postions!               
        if (boxY!=null && boxY!=undefined && boxY!="") {
            boxY=boxY+"px";
        }

        if (boxX!=null && boxX!=undefined && boxX!="") {
            boxX=boxX+"px";
        }

        occ.style.top = boxY;
        occ.style.left = boxX;
        occ.style.display='block';
        

        var oxF = document.getElementById("popFrame"+vIdx);
        if ( oxF != null )
        {
            oxF.style.top = occ.style.top;
            oxF.style.left = occ.style.left;
            oxF.style.width = occ.clientWidth;
            oxF.style.height = occ.clientHeight;
            oxF.style.zIndex = 1;
            occ.style.zIndex = 2;
            oxF.style.display = "block";
        }
    }
    else
    {
        if ( sRootIds.indexOf( "["+pSeq+"];" ) == -1 )
        {
            oarr = document.getElementById("mnuXARR"+pSeq);
            omnu.className = "mnuCO1";
            oarr.className = "mnuCO2";
            // Hide all the containers dependant on this one.
            xxHideAllFor(pSeq);
        }
        else
        {
            // Hide everything.
            xxHideAll();
        }
    }
    

    toggleDropDownsH();
}
function xxOut(pSeq,pIsMain)
{
    var omnu = document.getElementById("mnuXCHILD"+pSeq);
    
    if (pIsMain==undefined || !pIsMain)
    	omnu.className = "mnuC1";	
    //rather hide when hiding all submenus
    //else
    //	omnu.className = "mnuMain";

    
    
    var oarr = document.getElementById("mnuXARR"+pSeq);
    if (oarr!=null)
    	oarr.className = "mnuC2";
    	
    xxTmr = window.setTimeout("xxHideAll()",350);
}
function xxOutR(pSeq)
{
    var omnu = document.getElementById("mnuXCHILD"+pSeq);
    omnu.className = "mnuC1";
    xxTmr = window.setTimeout("xxHideAll()",350);
}
function xxGetChildContainer(pSeq)
{
    var iC;
    var iMax = arContainerHolder.length;
    for ( iC=0; iC<iMax; iC++ )
    {    	
        if ( arContainerHolder[iC] == pSeq )
            return iC;
    }
    return -1;
}

function xxGetChildContainerBinary(pSeq)
{
    var iMax = arContainerHolder.length;
    //binarySearch on arContainerHolder which seems to be ordered already:)
    return binarySearch(0,iMax-1,pSeq,arContainerHolder);
}


function xxHideAll()
{
    //alert("timing!");
    var newMenuItem=document.getElementById("mnuXCHILD"+lastMainMenuSeq);
    if (newMenuItem!=null){
        newMenuItem.className="mnuMain";
        var comments=newMenuItem.getElementsByTagName("div");
        if (comments!=null && comments.length>1) {
            comments[1].className="menuComment";
        }
    }


    
    var oc;
    var iC;
    var iMax = arContainerHolder.length;
    for ( iC=0; iC<iMax; iC++ )
    {
        if ( arContainerHolder[iC] != -1 )
        {
            oc = document.getElementById("mnuCONT"+iC);
            
            if (oc!=null)
            	oc.style.display = "none";
            //oc = document.getElementById("popFrame"+iC);
            //oc.style.display = "none";
        }
    }
    toggleDropDownsV();
}
function xxHideAllFor(pSeq)
{
    var ar;
    var iC;
    var iMax = arContainers.length;
    
    // First find the list this Seq belongs to, then put it in an array.
    for ( iC=0; iC<iMax; iC++ )
    {
        if ( arContainers[iC].indexOf("["+pSeq+"];") >= 0 )
        {
            ar = arContainers[iC].split(";");
            break;
        }
    }

    iMax = ar.length-1;
    for ( iC=0; iC<iMax; iC++ )
    {
        xxHideAllForEx( ar[iC].substr(1,ar[iC].length-2) );
    }
}


function xxHideAllForEx(pSeq)
{

    var ar;
    var oc;
    var iC;
    var iMax = arContainerHolder.length;

    for ( iC=0; iC<iMax; iC++ )
    {
        if ( arContainerHolder[iC] == pSeq )
        {
            oc = document.getElementById("mnuCONT"+iC);       
            if (oc!=null)
            	oc.style.display = "none";
            //oc = document.getElementById("popFrame"+iC);
            //oc.style.display = "none";
            
            ar = arContainers[iC].split(";");
            xxHideAllFor( ar[0].substr(1,ar[0].length-2) ); // Only need to call for the first one.
        }
    }
}

function binarySearch(min,max,code,array)
{
    var index=Math.round((max+min)/2); 
    
    if (min>max)
        return -1;
    
    if (code<array[index])
    {
        return binarySearch(min,index-1,code,array);
    }
    else if (code>array[index])
    { 
        return binarySearch(index+1,max,code,array);
    }
    else
    { 
        return index;
    }
}

function toggleDropDownsH()
{
	if (navigator.appName == "Microsoft Internet Explorer")
	{
		toggleElementVisM(document.all.tags("SELECT"), "hidden");
		//Get all the selects inside each iFrame
		for (var i=0;i<window.frames.length;i++)
		{
           try{
               
               toggleElementVisM(window.frames[i].document.all.tags("SELECT"), "hidden");
           }catch(e){
               //we might not have access to the DOM inside the iframe as it may be on a different domain
           }
		}
		//toggleElementVisM(document.all.tags("IFRAME"), "hidden");
	}
}
function toggleDropDownsV()
{
	if (navigator.appName == "Microsoft Internet Explorer")
	{
		toggleElementVisM(document.all.tags("SELECT"), "visible");
		//Get all the selects inside each iFrame
		for (var i=0;i<window.frames.length;i++)
		{
		    try{
            
                toggleElementVisM(window.frames[i].document.all.tags("SELECT"), "visible"); 
            }catch(e){
               //we might not have access to the DOM inside the iframe as it may be on a different domain
           }
		}
		//toggleElementVisM(document.all.tags("IFRAME"), "visible");
	}
}

function toggleElementVisM(objElem, obj_status)
{
	if (navigator.appName == "Microsoft Internet Explorer")
	{
		if (objElem!=null)
		{
			for (i=0; i<objElem.length; i++)
				objElem[i].style.visibility = obj_status;
		}
	}
}

function trim(str)
{
    return str.replace(/^\s*|\s*$/g,"");
}

function getCrumbs(pSeq){
    
    try{
        var crumbString="";
        crumbString=recursiveCrumb(pSeq,crumbString);
        crumbString=crumbString.substring(0,crumbString.length-2);
        
        if (trim(crumbString)=="Home") {
            return null;
        }else{
            return "Home > "+crumbString;
        }
        
        //alert(crumbString);
    }catch(e){
       alert("error:"+e.message);
    }


}

function recursiveCrumb(pSeq,crumbString){
    if (pSeq==-1) {
        return crumbString;
    }
    
    for (x=arContainers.length-1;x>-1;x--) {
        if (arContainers[x].indexOf("["+pSeq+"];")>-1){
            
            if (arContainerHolder[x]==-1) {
                return getCrumbDetails(pSeq,mainMenu[x])+" > "+crumbString;
            }else{
                crumbString=getCrumbDetails(pSeq,subMenus[x])+" > "+crumbString;
                return recursiveCrumb(arContainerHolder[x],crumbString);
            }

            break;
        }
    }

}

function getCrumbDetails(pSeq,menuStr){
    var items=menuStr.split("|");
    var x;
    var itemParts;
    for(x=0;x<items.length;x++){
         itemParts=items[x].split(",");
         if (pSeq==itemParts[0]) {
             return itemParts[2];
         }

    }
    return "";

}


function openfooterWindow(url){
    window.open(url,'','width=900,height=500,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes');
}

function doPortletValidation(items,namespace){
    var x;
    var currentItem;
    var currentNode;
    var currentMessageDiv;

    for(x=0;x<items.length;x++){
        
        currentItem=items[x].split("|");        
        currentNode=document.getElementById(namespace+currentItem[0]);                      

        currentMessageDiv=document.createElement("SPAN");
        currentMessageDiv.setAttribute('className','validationError');
        currentMessageDiv.setAttribute('class','validationError');
        currentMessageDiv.innerHTML="&nbsp;*&nbsp;"+currentItem[1];       

        if(currentNode.nextSibling){  
            
            currentNode.parentNode.insertBefore(currentMessageDiv,currentNode.nextSibling);
        }else{
            currentNode.parentNode.appendChild(currentMessageDiv);
        }

        /*if(currentNode.nodeName=="INPUT"){

            currentNode.style.border="1px red solid";
        }*/

        //currentNode.parentNode.style.whiteSpace='nowrap';
        //currentNode.parentNode.noWrap=true;
    }
}

function doParameterStateManagement(items,namespace){
    
    //alert(items);
    var x;
    var currentItem;
    var currentControl;
    var currentKey;
    var currentValue;
    for(x=0;x<items.length;x++){
        currentItem=items[x].split("|");
        currentControl=document.getElementById(namespace+currentItem[0]);
        if (currentControl) {  
            if (currentControl.nodeName=="INPUT") {
                if (currentControl.type=="text" || currentControl.type=="hidden") {
                    currentControl.value=currentItem[1];
                }else if (currentControl.type=="checkbox"){
                    
                    if (currentItem[1]!=null && currentItem[1]!=""){
                        currentControl.checked=true;
                    }
                    //currentControl.value=currentItem[1];

                }else if (currentControl.type=="radio"){
                    //currentControl.value=currentItem[1];
                    var radioButtons=document.getElementsByName(currentItem[0]);
                    var z;
                    for(z=0;z<radioButtons.length;z++){
                        if (radioButtons[z].value==currentItem[1]) {
                            radioButtons[z].checked=true;
                            break;
                        }
                    }
                   
                }

            }else if (currentControl.nodeName=="SELECT") {
              
                  if (!currentControl.multiple){
                  
                      var options=currentControl.options;
                      var y;
                      for(y=0;y<options.length;y++){
                          if (options[y].text==currentItem[1]) {                          
                              currentControl.selectedIndex=y;
                              break;
                          }
                      }
                  
                  }else{
                      var valueAr=currentItem[1].split(",");
                      var options=currentControl.options;
                      var y;
                      var p;
                      for(y=0;y<options.length;y++){
                          for(p=0;p<valueAr.length;p++){
                          
                              if (options[y].text==valueAr[p]) {                          
                                  options[y].selected=true;
                                  
                              }
                          }
                      }
                  }

            }else{
            
                currentControl.value=currentItem[1];
            }
        }else{                                                       
              var selector="input[name='"+currentItem[0]+"']";
              var currentControl=jQuery(selector).each(function(){
                    if(jQuery(this).attr("type")=="checkbox"){
                        if(jQuery(this).attr("value")==currentItem[1]){
                            jQuery(this).attr("checked",true);
                         }
                    }
              });
		}


    }

}

function doWizardNav(state,namespace){
    document.getElementById(namespace+"WizardNav").value=state;
    document.getElementById(namespace+"WizardNavForm").submit();
}

function previousWizardPage(prefix){
      var currentLink=document.getElementById(prefix+"currentWizardHeading");
      if(currentLink!=null){
      
          while (currentLink.previousSibling){
              currentLink=currentLink.previousSibling;
              if (currentLink.nodeName=="TD" && currentLink.className=="wizardHeadingClickable") {
                  currentLink.onclick();
                  break;
              }
          }
      }            
}

function nextWizardPage(prefix){
    try{
        var validationPassed=true;
        eval("if (!"+prefix+"wizardValidation()) validationPassed=false;");
        if (!validationPassed){
            return;
        }
    }catch(e){
        //No client side validation found
    }

    try{    
        eval(prefix+"getWizardForm();");
    }catch(e){
        alert("You must provide an implementation of [namespace]getWizardForm().");
        return;
    }

    try{    
        eval(prefix+"onBeforeSubmitWizardForm();");
    }catch(e){
    }

    try{    
        eval(prefix+"nextWizardPage();");
    }catch(e){
        //Next funtionality wasn't overrriden
        eval("WizardSubmitForm("+prefix+"getWizardForm());");
    }
}

function submitWizardPage(prefix){
    nextWizardPage(prefix);
}


function WizardSubmitForm(formId){
    var form=document.getElementById(formId);
    if(form){
        var inputBoxes=form.getElementsByTagName("input");
        var x;
        var hiddenInput;
        for (x=0;x<inputBoxes.length;x++) {
            if (inputBoxes[x].type=="checkbox") {
                if (!inputBoxes[x].checked){
                    
                    hiddenInput=document.createElement("input");
                    //hiddenInput.setAttribute('id',inputBoxes[x].id);
                    hiddenInput.setAttribute('type','hidden');
                    hiddenInput.setAttribute('name',inputBoxes[x].name);
                    hiddenInput.setAttribute('value',"");
                    form.appendChild(hiddenInput);
                    inputBoxes[x].disabled=true;                    
                }
            }
        }

        form.submit();
    }
}

function cancelWizardPage(prefix,url){
    VBPopUpDialog("Are you sure you want to leave without saving?","wizardPopUpConfirmed('"+prefix+"','"+url+"')",true);
}


function saveAndExitWizardPage(prefix,url){
       
    VBPopUpDialog("Your details will be saved for later use, and will not be submitted yet. Are you sure you want to Save and Exit?","wizardPopUpConfirmed('"+prefix+"','"+url+"')",true);
}



function wizardPopUpConfirmed(prefix,url){
    //alert("Saving and Exiting!"+prefix);
    var formId;
    try{    
        eval("formId="+prefix+"getWizardForm();");
    }catch(e){
        alert("You must provide an implementation of [namespace]getWizardForm().");
        return;
    }

    var wizForm=document.getElementById(formId);
    if (wizForm) {
        wizForm.action=url;
        wizForm.submit();
    }
}



/*FireFox and IE treat nodes differently - FF treats whitespace/new lines as text nodes*/ 
function getLastChild(parent)
{
    var currentLast=parent.lastChild;
    while (currentLast.nodeType !=1 ){
        currentLast=currentLast.previousSibling;
    }

    return currentLast;
}

/*FireFox and IE treat nodes differently - FF treats whitespace/new lines as text nodes*/
function getFirstChild(parent)
{
    var currentFirst=parent.firstChild;
    while (currentFirst.nodeType !=1 ){
        currentFirst=currentFirst.nextSibling;
    }

    return currentFirst;
}

function getRightSibling(element){
    
    var currentSibling=element.nextSibling;
    while (currentSibling.nodeType !=1 ){
        currentSibling=currentSibling.nextSibling;
    }

    return currentSibling; 
}


function addModuleToPage(title,portletId,url,excerpt,addBeforeCurrent,showServiceContext){
	 
	 var portletDiv=document.createElement("div");
     portletDiv.setAttribute("id","portlet-wrapper-"+portletId+"");
     portletDiv.setAttribute("ajax",url);
     portletDiv.setAttribute("onclick","makeCurrentModule(this,'"+portletId+"');");
     portletDiv.setAttribute("class","portlet");          

     var inActiveDiv=document.createElement("div");             
     inActiveDiv.setAttribute("class","vbcSkinInActive add_border");   

     portletDiv.appendChild(inActiveDiv);     

     var portletTable=document.createElement("table");
     portletTable.setAttribute("cellspacing","0");
     portletTable.setAttribute("cellpadding","0");             
     portletTable.setAttribute("width","100%");

     inActiveDiv.appendChild(portletTable);

     var portletTableTR=document.createElement("tr");

     portletTable.appendChild(portletTableTR);

     var portletTableTD=document.createElement("td");
     portletTableTD.setAttribute("class","vbcTitle");

     portletTableTR.appendChild(portletTableTD);


     var portletTitleSpan=document.createElement("span");             
     portletTitleSpan.setAttribute("class","portlet-title");
     portletTitleSpan.innerHTML=title;

     portletTableTD.appendChild(portletTitleSpan);

     var portletTableContentTR=document.createElement("tr");

     portletTable.appendChild(portletTableContentTR);

     var portletTableContentTD=document.createElement("td");
     var TDClass="vbcContent";
     if(showServiceContext==true){
         TDClass=TDClass+" serviceContext";
     }

     portletTableContentTD.setAttribute("class",TDClass);

     portletTableContentTR.appendChild(portletTableContentTD);

     var portletContentDiv=document.createElement("div");                 
     portletContentDiv.setAttribute("class","divContent");

     portletTableContentTD.appendChild(portletContentDiv);

     var excerptDiv=document.createElement("div");                 
     excerptDiv.setAttribute("class","excerpt");
     excerptDiv.innerHTML=excerpt;

     portletContentDiv.appendChild(excerptDiv); 
      

     var dummyDiv=document.createElement("div");
     dummyDiv.appendChild(portletDiv);


     jQuery("#layout-grid .sideColumn").append(jQuery(dummyDiv).html());
     
 }

function addTabToSkin(title,tabHookId,url,addBeforeCurrent,index){
    
    var tabRow=document.getElementById(tabHookId);
    if(tabRow){
         var tdsInTabRow=tabRow.childNodes;
          
         if (tdsInTabRow.length>0) {

             var z;
             var titleTDIndex=-1;
             
             for(z=0;z<tdsInTabRow.length;z++){                 
                 if (tdsInTabRow[z].nodeType == 1 && tdsInTabRow[z].getAttribute("name")=="VBSkinTitleTD") {
                     titleTDIndex=z;
                     break;
                 }                  
             }


             if (titleTDIndex==-1) {
                 return;
             }            

             var newTitleTD=document.createElement("td");            
             var newTitleDiv=document.createElement("div");
             newTitleDiv.setAttribute("id","VBSkinTitleNotSelected");             
             newTitleDiv.setAttribute("height","100%");
             newTitleDiv.setAttribute("vAlign","middle");
             newTitleDiv.innerHTML=title;
             newTitleDiv.className="VBSkinTitleNotSelected";             
             newTitleDiv.onclick=function(){takeMeToRelative(url)};
             newTitleDiv.onmouseover=function(){customHover(this,true);};
             newTitleDiv.onmouseout=function(){customHover(this,false);};
             newTitleTD.appendChild(newTitleDiv);

             var newGapTD=document.createElement("td");
             newGapTD.className="VBSkinTitleGap";
             newGapTD.innerHTML="&nbsp;";                          

             if (!addBeforeCurrent){
                 tabRow.appendChild(newGapTD);
                 tabRow.appendChild(newTitleTD);
                 
             }else{
                 tabRow.insertBefore(newGapTD,tdsInTabRow[titleTDIndex]);
                 tabRow.insertBefore(newTitleTD,tdsInTabRow[titleTDIndex]);
                 
             }     
            
         }

     }
 }


function callPreviousTabs(hook,currentIndex){

    var index=currentIndex;
    if(index>0){
        var x;
        for(x=0;x<index;x++){
            eval("addTabToSkin_"+hook+x+"();");
        }
    }

    
}

function customHoverButton(control,over){
    
    var path="/VodaBizConnect-theme/images";

    if(themeDisplay){
        path=themeDisplay.getPathThemeImages();
    }    
    
    if (over) {
        jQuery(control).prev().attr("src",path+"/btnGreenCorner_o.png");
    }else{
        jQuery(control).prev().attr("src",path+"/btnGreenCorner.png");
    }

    customHover(control,over);
}




function customHover(control,over){
            
    var oldClass=control.className;

    //FOR IE6, liferay appends " button" to the end of the class name
    if (isIE6()) {
        var weirdSuffixIndex=oldClass.indexOf(" button");
        if (weirdSuffixIndex>-1) {
            oldClass=oldClass.substring(0,weirdSuffixIndex);
        }else{
            //alert(oldClass);
            var weirdSubmitSuffixIndex=oldClass.indexOf(" submit");
            if (weirdSubmitSuffixIndex>-1) {
                oldClass=oldClass.substring(0,weirdSubmitSuffixIndex);
            }

        }
    }

    //Cater for elements rounded by plugin
    var suffixRoundIn=oldClass.indexOf("jrcRounded");
    if (suffixRoundIn>-1){
        oldClass=oldClass.substring(0,suffixRoundIn-1);
    }


    /*if (over) {
        
        if (oldClass.indexOf("_o")!=oldClass.length-2) {                
            control.className=oldClass+"_o";
        }
    }else{

        var suffixIndex=oldClass.indexOf("_o");
        if (oldClass.length>2 && suffixIndex==oldClass.length-2) {
            control.className=oldClass.substring(0,suffixIndex);
        }
        
    }*/

    var overSuffix="_o";
    if (!oldClass.match(overSuffix+"$")){

        control.className=oldClass+overSuffix;

    }else{
        control.className=oldClass.substring(0,oldClass.length-overSuffix.length);
    }

}

/*
 * Sets alternate row colors on a table
 * node The table on which alternate rows should be applied.
 */
function setAlternateRows(tableNode){

	var tbody = tableNode.getElementsByTagName("tbody")
	if ((tbody) && tbody.length > 0) {
		var trs = tbody[0].rows;
		var evenIndicator = 0;
		for (var x = 0; x < trs.length; x++) {
		
			if (trs[x].style.display != "none") {
				evenIndicator++;
			}
			
			evenIndicator = evenIndicator % 2;
			
			if (evenIndicator != 0) 
				trs[x].className = "VBRow1";
			else 
				trs[x].className = "VBRow2";
			
		}
	}
}
function setTLAlternateRows(tableNode, odd, even){

	var tbody = tableNode.getElementsByTagName("tbody")
	if ((tbody) && tbody.length > 0) {
		var trs = tbody[0].rows;
		var evenIndicator = 0;
		for (var x = 0; x < trs.length; x++) {
		
			if (trs[x].style.display != "none") {
				evenIndicator++;
			}
			
			evenIndicator = evenIndicator % 2;
			
			if (evenIndicator != 0) 
				trs[x].className = even;
			else 
				trs[x].className = odd;
			
		}
	}
}
function setAllTableAlts(){

    var altTable=document.getElementsByName("VBAltGrid");
    jQuery(altTable).find(".scrollContainerVB").each(function(){
         setAlternateRows(this);
    });
	
	jQuery(altTable).find(".scrollContainerTL").each(function(){
         setTLAlternateRows(this, "VBRowOddTL", "VBRow1");
    });

}
function setModuleSkinHeights(){
        
    //we need javascript because overflow doesn't seem to play nicely percentage heights
    
    var flowDivs=jQuery(".mainSkinContent .portlet");

    //set back to default so when minimizing the parent td goes back to %
    jQuery(flowDivs).css("height","190px");

    jQuery(flowDivs).each(function(intIndex){
                       
        //set to height of parent container
        jQuery(this).css("height",jQuery(this).parent().attr("clientHeight"));

    });
}

function makeCurrentModule(control,portletId){
	
    //show all side portlets
    jQuery("#layout-grid .sideColumn .portlet").css("display","");
    //var selector="#"+control.id;
	
    var nextPortlet=jQuery(control);	
    setCurrentModuleParts(nextPortlet,true);
	
    //setJourneyBarToPortlet(portletId);

}

function startsWith(fullStr,str){
    if (fullStr.indexOf(str)==0) {
        return true;
    }else{
        return false;
    }
}

function endsWith(fullStr,str){
    if (fullStr.lastIndexOf(str)==(fullStr.length-str.length)) {
        return true;
    }else{
        return false;
    }
}


function scrollableTableTbodyFix(){
    if (!isMicrosoft()) {            
        var scollableTables=jQuery(".scrollContainerVB table");
        var scrollableTbodies=jQuery(scollableTables).find("tbody");
        var q;
        var rowHeight="25";
        var actualHeight;
        for (q=0;q<scrollableTbodies.length;q++) {
            actualHeight=rowHeight*jQuery(scrollableTbodies[q]).find("tr").size();
            if (actualHeight<scrollableTbodies[q].clientHeight) {
               scrollableTbodies[q].style.height="auto";
           }
        }
    }
}


function setupScrollableTable(){

    scrollableTableTbodyFix();

    jQuery(".scrollContainerVB").scroll(function(event){
        /*if the focus is on the search input fields, it cause the floating TR is jump in IE*/
            
            jQuery(this).find(".VBGridSearch th input").each(function(){
                
                if(jQuery(this).attr("hasFocus")=="true"){
                    
                    jQuery(this).blur();
                }
            });
        
     });
	 
	 /*
	  * Added to enable the scrolling container on the Tariff Locator tool for Vodacom Business
	  */
	 jQuery(".scrollContainerTL").scroll(function(event){
        	/*if the focus is on the search input fields, it cause the floating TR is jump in IE*/            
            jQuery(this).find(".VBGridSearch th input").each(function(){
                
                if(jQuery(this).attr("hasFocus")=="true") {                    
                    jQuery(this).blur();
                }
            });        
     });


    /*jQuery(".VBGridSearch th input").each(function(){
        this.onfocus=function(){jQuery(this).parents(".scrollContainerVB").scrollTop(0);};
        
    }); */

    //when filtering set the scrollbar to the top
    var searchRow=jQuery(".VBGridSearch th input").focus(function(){
        jQuery(this).attr("hasFocus","true");
    
    }).blur(function(event) {
        jQuery(this).attr("hasFocus","");
    });
}

var moduleStateInconsistent=false;
function setCurrentModuleInner(mainPortlet, nextPortlet) {
	
	jQuery(mainPortlet).find(".portlet-title").html("").append(jQuery(nextPortlet).find(".portlet-title").html());
	jQuery(mainPortlet).find(".portlet-title img").removeClass(); 


	var nextClass=jQuery(nextPortlet).find(".vbcContent").attr("class");
	
	var ajaxURL=jQuery(nextPortlet).attr("ajax");
	if(moduleStateInconsistent && !ajaxURL){
		ajaxURL=jQuery(nextPortlet).attr("ajaxURL");
		//jQuery(nextPortlet).find(".portlet-content").empty();
	}
	
	if (ajaxURL) {
		
		
		jQuery(mainPortlet).find(".portlet-content").html("").load(ajaxURL,function (responseText, textStatus, XMLHttpRequest) {
			
			if(textStatus=="success"){
				fixAjaxActions(jQuery(mainPortlet).find(".portlet-content"),true);
				/*
				* set custom drop down on new content
				* jQuery(mainPortlet).find(".portlet-content select").sexyCombo();
				*/
				jQuery("#scrollable tbody tr:odd td").removeClass("odd").addClass("odd");
				setAllTableAlts();				
				clearAjaxLoader();
			} else {
				jQuery(mainPortlet).find(".portlet-content").html("There was an error loading the content");
				clearAjaxLoader();
			}
		});
	} else {
		var newContent=jQuery(nextPortlet).find(".portlet-content").html().trim();            
	
		/*The side modules were commented out so that any javascript calls wouldn't be called on load and then again
		when the content is dynamically added to the DOM*/
	
		var scriptStart="<!--";
		var scriptEnd="-->";
		if(startsWith(newContent,scriptStart) && endsWith(newContent,scriptEnd)) {					
			newContent=newContent.substr(scriptStart.length);
			newContent=newContent.substr(0,newContent.length-scriptEnd.length);                
		}

		jQuery(document).ready(function(){
	
		jQuery(mainPortlet).find(".portlet-content").html("").append(newContent);
			/*
			 * set custom drop down on new content
			 * jQuery(mainPortlet).find(".portlet-content select").sexyCombo();
			 */   
			fixAjaxActions(jQuery(mainPortlet).find(".portlet-content"),true);
			jQuery("#scrollable tbody tr:odd td").removeClass("odd").addClass("odd");
			setAllTableAlts();			
			clearAjaxLoader();
		});
	}
}
/* 
 * Adds the Ajax loader image to the page by either injecting the div with the
 * image or, if the element already exists on the page, it simply shows it.
 */
var loadAjaxLoader = function() {
	
	if(jQuery("#ajax_loader").length < 1) {
		var ie6iFrameFix = "<iframe src='javascript:'&lt;html&gt;&lt;/html&gt;';' scrolling='no' frameborder='0' style='position:absolute;width:0px;height:0px;top:35%;left:45%;border:none;display:block;z-index:0'></iframe>";
		var loader = getThemeImagePath() + "/icons/ajax-loader.gif";
		
		jQuery("body").append("<div id='ajax_loader'><img src='" + loader + "' /></div>");
		jQuery("#ajax_loader").show();
	} else {
		jQuery("#ajax_loader").show();
	}
}
/*
 * Removes the Ajax loader animation from the page if it exists
 */
var clearAjaxLoader = function() {
	var loader = jQuery("#ajax_loader");
	if(loader.length != 0) {
		loader.hide("slow");
	} 
}

function setCurrentModuleParts(nextPortlet, animate){
	  
	jQuery(nextPortlet).css("display","none");
	var mainPortlet=jQuery("#layout-grid #maxColumn .portlet");
	
	loadAjaxLoader();
	
	/*the button corner image and scrollable headings don't animate nicely*/
	if(isMicrosoft()){
	  animate=false;
	}
	
	if(animate){
	  jQuery(mainPortlet).fadeOut("fast", function(){
	      setCurrentModuleInner(mainPortlet,nextPortlet);
	  });
	
	  jQuery(mainPortlet).fadeIn("slow");
	}else{
	  setCurrentModuleInner(mainPortlet,nextPortlet);          
	}
}


function setModuleAdmin() {
    var mainPortlet=jQuery("#layout-grid #maxColumn .portlet");
    jQuery(mainPortlet).find(".portlet-title").html("Module Administration");
    jQuery(mainPortlet).find(".portlet-content").html("All Modules should have a portlet-skin of module and a excerpt preference that is displayed when the portlet is not active.");
}

        
function setCurrentModule(){
    
	var currentPortletPPID = jQuery.getURLParam("p_p_id");
	
	if(currentPortletPPID!=null){
	
		var portletSelector="#layout-grid .sideColumn .portlet#portlet-wrapper-"+currentPortletPPID;
		var nextPortlet=jQuery(portletSelector);
	
	} else {
		var nextPortlet=jQuery("#layout-grid .sideColumn .portlet:first");	
	}
		
	fixLoadContentImageTop(nextPortlet);
	setCurrentModuleParts(nextPortlet,false);
}

function loadAjaxContentIntoDiv(divId,url,ajaxAction,namespace){

      initAjaxDone=false;
      var divId="#"+divId;
      var theDiv=jQuery(divId);
          
      jQuery(theDiv).html("").load(url,function (responseText, textStatus, XMLHttpRequest) {
    
          if(textStatus=="success"){              
              fixAjaxActions(theDiv,ajaxAction);
			  /*
			   * set custom drop down on new content
			   * jQuery(theDiv).find("select").sexyCombo();
			   */
              initAjaxDone=true;

              if(namespace!=null && namespace!=undefined && namespace!=""){
                  try{
                      eval(namespace+"AjaxContentLoaded();");
                  }catch(e){
                      //couldn't find the function
                      alert("Ajax load error: Exception in function "+namespace+"AjaxContentLoaded()");
                  }
              }
              
          }else{
              jQuery(theDiv).html("There was an error loading the content");
          }
      });  

}



function fixLoadContentImageTop(control){
    /*In firefox, either due to malformed html or browswer bug, the corner image doesn't display with the correct
    top value. A hack fix is to put a space before the button div*/
    if(isFirefox()){
        jQuery(control).find(".VBFormButtons:first").before("&nbsp;");
    }
}


function fixAjaxActions(control,ajaxAction) {
    
    jQuery(control).find("form").submit(function() {

        var vAction=this.action;

        if(ajaxAction==true){  
		
			if(vAction.indexOf("p_p_state=normal")>-1){
                vAction=vAction.replace("p_p_state=normal","p_p_state=exclusive");
            }          

            jQuery.post(vAction, jQuery(this).serializeArray(),
              function(data){                         
                jQuery(control).html(""+data);
                VBPopUpDialogReAdjustSize();
                fixAjaxActions(control,ajaxAction);
				/*
				 * jQuery(control).find("select").sexyCombo();
				 */
				
				moduleStateInconsistent=true;  
				clearAjaxLoader();              
             });

            
            return false;

        }else{                            
            
            if(vAction.indexOf("p_p_state=exclusive")>-1){
                vAction=vAction.replace("p_p_state=exclusive","p_p_state=normal");
            }
            
            this.action=vAction;
        }
    
    });
}

  
function VBWebContentPreviewPopup(articleId, group){
	var contentUrl = "/c/journal/view_article_content?groupId=" + group + "&articleId=" + articleId + "&version=1.0";
	VBAjaxPopUpDialog(contentUrl,"vbPopup",null,false);
}

function notificationBoardLightBoxRedirect(noticeUrl) {
  VBAjaxPopUpDialog(noticeUrl,'Pop Up',null,false);
}

function expandVBTable(control){

    var hiddenClass="expandHide";
    var endOfExpandSelection=false;

    customHover(control);

    var nextTR=jQuery(control).parent().next();

    
    while(!endOfExpandSelection){
       
        if(nextTR!=undefined && nextTR!=null && jQuery(nextTR).attr("tagName")=="TR"){

            var controlClass=jQuery(nextTR).attr("class");
            if (!controlClass) {
                controlClass=jQuery(nextTR).attr("className");
            }

            if(controlClass.indexOf(hiddenClass)>-1){
                
                jQuery(nextTR).removeClass(hiddenClass);

            }else if(jQuery(nextTR).find("td:first").attr("class").match("^vbContentTableTitleExpand")){
                
                endOfExpandSelection=true;

            }else{
                jQuery(nextTR).addClass(hiddenClass);
            }

            if(!endOfExpandSelection){
                nextTR=jQuery(nextTR).next("tr");            
            } 
        }else{
            endOfExpandSelection=true;
        }
    }

}

function showMessageOnForm(formId,message,iconFlag) {
	var selector="#"+formId;
	var divClass="userMessagesTag-error";
	if(iconFlag!=null && iconFlag!=undefined){            
		switch(iconFlag){
				case 0:
				  divClass="userMessagesTag-error";
				  break;
				case 1:
				  divClass="userMessagesTag-information";
				  break;
				default:
				  divClass="userMessagesTag-error";
				  break;
			}
	}
	var newMessageHTML = "<tr><td><p class='"+divClass+"'>"+message+"</p></td></tr>";
	var portletContainer = jQuery(selector).parents(".portlet-content-container:first");
	
	/* Added for VBC-Module pages where the .portlet-content-container does not exist */
	if(portletContainer.length == 0) {
		portletContainer = jQuery("#maxColumn .vbcContent");
	}	
	
	var existingTable = jQuery(portletContainer).find(".userMessagesTag-table");
	if(existingTable.size()==0){
		jQuery(portletContainer).prepend("<table cellpadding='2' cellspacing='0' class='userMessagesTag-table'>"+newMessageHTML+"</table>");
	} else {
		jQuery(existingTable).html(newMessageHTML);
	}
}

/*creating global variables as an optimization for the window.resize function*/ 
if(isIE6()){
    var mainContainerMinWidth=958;
    var mainContainerMaxWidth=1280;
    
    var mainContainerMinWidthPx=mainContainerMinWidth+"px";
    var mainContainerMaxWidthPx=mainContainerMaxWidth+"px";

    
}

function applyMinMaxWidth(container){

/*This should only be called on IE6 - be careful on what you put in this function because it is called on every resize event!!!*/    
    
    var minWidth=958;
    var maxWidth=1280;

    var currentContainerWidth=container.clientWidth;
    var browserWidth=document.documentElement.clientWidth;
    var browserWidth90=browserWidth*0.9;

    var percent=currentContainerWidth/browserWidth;
    var is90=(percent<0.92 && percent>0.88);

    var isMin=currentContainerWidth-mainContainerMinWidth<=2 && currentContainerWidth-mainContainerMinWidth>=-2;
    
    /* Updating the DOM is SLOW so we can't do it everytime this function is called otherwise in certain usecases it kills the browswer.
       So instead there is complex logic that determines when it should update and only does it once.
       
       DON'T TOUCH THIS UNLESS YOU KNOW WHAT YOU'RE DOING!!! 
    */

    if(is90 && currentContainerWidth<=mainContainerMinWidth){

        container.style.width=mainContainerMinWidthPx;        
        //window.status="too small"+new Date();

    }else if(is90 && currentContainerWidth>=mainContainerMaxWidth){

        container.style.width=mainContainerMaxWidthPx;
        //window.status="too big"+new Date();

    }else if(!is90 && (browserWidth90>mainContainerMinWidth && browserWidth90<mainContainerMaxWidth)){
        container.style.width="90%";
        //window.status="just right!"+new Date();

    }else if(!is90 && (isMin && browserWidth90>mainContainerMaxWidth)){
        container.style.width="90%";
        //window.status="maxi!"+new Date();
    }
    
}


function forceMinMaxWidth(){
/*This should only be called on IE6 - be careful on what you put in this function because it is called on every resize event!!!*/ 

    var container=document.getElementById("mainContainer");

    jQuery(window).resize(function(){

          applyMinMaxWidth(container);
                    
    });

    applyMinMaxWidth(container);
       
}

function getCSSPXValueAsInt(control,css){

         var cssValue=jQuery(control).css(css);
         if(cssValue==undefined || cssValue=="0px"){
             cssValue=0;
         }else{
             cssValue=parseInt(cssValue.substring(0,cssValue.length-2));
         }

         return cssValue;
}


function makeWCMCellAdjustment(control){

    var cellHeight=jQuery(control).height()-8;

    var portlet=jQuery(control).find(".portlet .VBNoSkinBody").parent();
    jQuery(portlet).find(".portlet-content-container").children("div").children("table,div").each(function(){
    
        /*don't adjust journey bar or sitemap*/
        if(this.id=="journeyBar" || this.className=="siteNav"){
            return;
        }
                            
        var paddingTop=0;
        var paddingBottom=0;

        if(this.tagName=="DIV"){
         
                /*TODO:this should only be done when the height is 100%*/
                paddingTop=getCSSPXValueAsInt(this,"padding-top");
                paddingBottom=getCSSPXValueAsInt(this,"padding-bottom");            
            
         }

       //alert(cellHeight+" vs "+this.clientHeight);
       if(cellHeight!=this.clientHeight && cellHeight!=0){

           jQuery(this).height(cellHeight-(paddingTop+paddingBottom));
           /*for some weird reason IE makes the element have a greater height than specified. Padding? Margin?*/
           if (isMicrosoft()){
               var diff=this.clientHeight-(cellHeight-(paddingTop+paddingBottom));
               if(diff>0){

                   jQuery(this).height(cellHeight-diff);
               }
           }
       }

    });
}

function adjustWCMCellHeights(){


    var contentWrapperClass=jQuery("#content-wrapper").attr("class");
    if (!contentWrapperClass) {
        contentWrapperClass=jQuery("#content-wrapper").attr("className");
    }

    if(contentWrapperClass.indexOf("vbContentArea")>-1){

        jQuery("#layout-grid").children("tbody").children("tr").children("td").each(function(){

            if(this.className.indexOf("subContainer")>-1){

                jQuery(this).find(".subContainerTable").children("tbody").children("tr").children("td").each(function(){
                    makeWCMCellAdjustment(this);
                });   
                
            }else{            
                      
                makeWCMCellAdjustment(this);    
            
            }
         });
    } 



}

function VBAccordion(control) {

    var controlClass;
	
	if(jQuery(control).parent().find(".VBAccordionBody") > 0) {
		controlClass = jQuery(control).parent().find(".VBAccordionBody").attr("class");
	} else {
		controlClass = jQuery(control).parent().find(".VBAccordionBodyExpandedState").attr("class");
	}	
	
    if (!controlClass) {
        controlClass=jQuery(control).parent().find(".VBAccordionBody").attr("className");
    }

    /*don't slideup if the item clicked is already expanded*/
    var closeCurrent=false;	
    if(controlClass != undefined && (controlClass.indexOf("VBAccordionBodyExpanded") >- 1 || controlClass.indexOf("VBAccordionBodyExpandedState") >- 1)){
        closeCurrent=true;
    }
	
	jQuery(".expandedState").removeClass("expandedState");
	
	if(jQuery(control).parents(".portlet-boundary").parent().find(".VBAccordionBodyExpanded").length > 0) {
		jQuery(control).parents(".portlet-boundary").parent().find(".VBAccordionBodyExpanded").removeClass("VBAccordionBodyExpanded").slideUp("fast");
		jQuery(control).removeClass("expandedState").addClass("collapsedState");
	} else {
		jQuery(control).parents(".portlet-boundary").parent().find(".VBAccordionBodyExpandedState").removeClass("VBAccordionBodyExpandedState").addClass("VBAccordionBody").slideUp("fast");
		jQuery(control).removeClass("expandedState").addClass("collapsedState");
	}
	
    if(!closeCurrent) {
        jQuery(control).parent().find(".VBAccordionBody").addClass("VBAccordionBodyExpanded").slideToggle("fast");
		jQuery(control).removeClass("collapsedState").addClass("expandedState");
		setAccordionExpandedHeight();
    }
}

var setAccordionExpandedHeight = function() {
	var container_height = 280;
	
	var headers_height = 0;
	
	var expanding_content = jQuery("#accordion_container .VBAccordionHead");
	var link_content = jQuery("#accordion_container .VBAccordionHeadLink");
	
	jQuery(expanding_content).each(function() {
	    headers_height += jQuery(this).height();
	});
	
	jQuery(link_content).each(function() {
	    headers_height += jQuery(this).height();
	});
	
	if(jQuery(".VBAccordionBodyExpandedState").length > 0) {
		jQuery(".VBAccordionBodyExpandedState .wcm_finder").css("height", container_height - headers_height);
	} else {
		jQuery(".VBAccordionBodyExpanded .wcm_finder").css("height", container_height - headers_height);
	}	
}

var VBAccordionLink = function(url) {
	window.location.href=url;
}

function findReplaceToggle(control){
    if(control.className=="findReplaceItem"){
        control.className="findReplaceItemReject";        
    }else{
        control.className="findReplaceItem";
    }

    var oldValue=jQuery(control).attr("old");
    var value=jQuery(control).text();
    jQuery(control).text(oldValue);
    jQuery(control).attr("old",value);
}


var initDone=false;
function prometheusInit(){
    
    /*setModuleSkinHeights();

    jQuery(window).resize(function(){
          setModuleSkinHeights();
    });*/

    
    if(jQuery("#mainContainer").attr("class").indexOf("admin")<0){
        adjustWCMCellHeights();
    }

    try{
    
        loadModules();
    }catch(e){
        //don't have modules on the page
    }
	
	jQuery("#scrollable tbody tr:odd td").removeClass("odd").addClass("odd");
	setAllTableAlts();

	/*
	 * jQuery("#quickLink,#mainSkinTitle select").sexyCombo();
	 * jQuery("#quickLink").sexyCombo();
	 */
    

    if (isMicrosoft()){
        
        var ie6CornerParameter="";
        if(isIE6()){
    
            /*Only apply if in VodaBizConnect*/
            if(jQuery("#mainContainer").attr("class").indexOf("Connect")>-1){
                /*apply min and max widths for IE6*/
                forceMinMaxWidth();
            }
    
            ie6CornerParameter=" ie6fixexpr"
    
            var userMessageP=jQuery(".userMessagesTag-table").find("p");
            if (userMessageP){
                
                var userMessagePClass=userMessageP.attr("className");
                if (!userMessagePClass) {
                    userMessagePClass=userMessageP.attr("class");
                }
    
                if (userMessagePClass=="userMessagesTag-success") {
                    userMessageP.append("<img src='"+themeDisplay.getPathThemeImages()+"/ICONS/Medium_Icons/Tick_Icon_Medium.png' class='userIcon'>");
                }else if (userMessagePClass=="userMessagesTag-information" || userMessagePClass=="userMessagesTag-instruction") {
                    userMessageP.append("<img src='"+themeDisplay.getPathThemeImages()+"/ICONS/Medium_Icons/Exclamation_Icon_Medium.png' class='userIcon'>");
                }else if (userMessagePClass=="userMessagesTag-error" || userMessagePClass=="userMessagesTag-criticalError") {
                    userMessageP.append("<img src='"+themeDisplay.getPathThemeImages()+"/ICONS/Medium_Icons/Error_Icon_Medium.png' class='userIcon'>");
                }        
            }

            /*fix pngs*/
            //jQuery(".iconGo,.iconNOTIFICATIONS,.iconBROWSEPRODUCTS,.iconLIVECHAT,.iconNEWFEATURES,.iconCONTACTUS,.iconWIDGETDOWNLOADS,.iconNoticeMinimised,.iconNoticeExpanded,.VBGridContainer .VBGridSearch input").supersleight({shim: "/VodaBizConnect-theme/images/transparent.gif"});            
            jQuery("#searchSpan .icon,#searchSpan .iconGo,.VBGridContainer .VBGridSearch input,.imageRotateKeys .whiteCorner,.imageRotateKeys .imageRotateKey,.imageRotateKeys .imageRotateKey_o").supersleight({shim: "/VodaBizConnect-theme/images/transparent.gif"});

        }


        jQuery("#mainSkinTitle").corner("top 20px"+ie6CornerParameter);
        jQuery("#noticeBar").corner("bottom 20px"+ie6CornerParameter);

        jQuery(".greenBtn").corner("tl 20px"+ie6CornerParameter);

    }
        



    jQuery("#VBExpander .VBExpanderOuter tbody tr:even").attr("className","VBExpandDivAlt");
    jQuery("#VBExpander .VBExpanderOuter tbody tr:odd").attr("className","VBExpandDiv");

    jQuery("#VBExpander .VBExpanderInner tbody tr:odd").attr("className","VBExpandInnerDiv");
    jQuery("#VBExpander .VBExpanderInner tbody tr:even").attr("className","VBExpandInnerDivAlt");




    
    initDone=true;

}

var initAjaxDone=true;
function VBAjaxPopUpDialog(pUrl,pTitle,hookId,ajaxAction) {	
	
	if(pUrl.indexOf("/get_file?") > -1) {
	  window.open(pUrl,'previewWindow','scrollbars=yes,menubar=no,height=600,width=960,resizable=yes,toolbar=no,location=no,status=no');                                                                                                
	  return;
	}

	initAjaxDone=false;
	var theDiv=jQuery("#vbcPopUpContent");
	
	jQuery.get(pUrl, function(data) {
	
	  if(hookId!=undefined && hookId!=null && hookId!=""){
	      data="<script language='javascript'>function getAjaxDialogHook(){return jQuery('#"+hookId+"');}</script>"+data;
	  }
	              
	  VBPopUpDialog(data,null,false,pTitle);
	  setAllTableAlts();
	  fixAjaxActions(theDiv,ajaxAction);
	  /*
	   * jQuery(theDiv).find("select").sexyCombo();
	   */
	  initAjaxDone=true;
	
	
	});            
}



function VBLoadDivInPopUp(divId, title){
    
    VBPopUpDialog(jQuery(divId).html(),null,null,title);

}

function closeVBPopUpDialog(){
    jQuery("#vbcPopUp").dialog("close");
    
}

function setContentTableWidthsInPopUp(popUpControl){
    var maxWidth=750;
    var currentWidth;
    var currentControl;
    var spanWidth;
    var adjustWidth=true;
    var contentSpan=jQuery(popUpControl).children("#vbcPopUpContent");
    jQuery(contentSpan).children("table.vbContentTable,p").each(function(){
            
            adjustWidth=true;
            currentControl=this;
            currentWidth=jQuery(currentControl).width();


            if(currentControl.tagName=="P"){
                
                if(isMicrosoft()) {
                
                    var oldDisplay=jQuery(currentControl).css("display");
                    jQuery(currentControl).css("display","inline");
                    currentWidth=jQuery(currentControl).width();
                    jQuery(currentControl).css("display",oldDisplay);
                    
                    if(currentWidth<=maxWidth){
                        adjustWidth=false;
                    }
                    
                }
                
            }
            
            if(adjustWidth==true){
            
                if(currentWidth>maxWidth){
                    currentWidth=maxWidth;
                }
    
                jQuery(currentControl).width(currentWidth);
            }
            
    });



}


function VBPopUpDialog(text,successFunction,confirmationFlag,popUpTitle,subText,iconFlag){


    var contentSpan=jQuery("#vbcPopUp").find("#vbcPopUpContent");


    var buttonsDiv=jQuery("#vbcPopUp").find("#vbcPopUpButtons");

    var popConfirmSpan=jQuery(buttonsDiv).find("#popConfirmSpan");
    var popOkSpan=jQuery(buttonsDiv).find("#popOkSpan");

    var showButtons=true;

    if(confirmationFlag==null || confirmationFlag==undefined || (popUpTitle!=null && popUpTitle!=undefined && popUpTitle!="")){
		
        jQuery(popOkSpan).hide();        
        jQuery(popConfirmSpan).hide();
        showButtons=false;
        
    }else if(confirmationFlag){

        //use question icon
        iconFlag=3;

        jQuery(popOkSpan).hide();        
        jQuery(popConfirmSpan).show();

        /*remove any existing events on the confirm button*/
        jQuery(popConfirmSpan).find("#popConfirmBtn").unbind();
        if(successFunction==null || successFunction==undefined){
            jQuery(popConfirmSpan).find("#popConfirmBtn").bind("click", function(){
                alert("No success function has been specified!");
            });
        }else{
            jQuery(popConfirmSpan).find("#popConfirmBtn").bind("click", function(){
                
                closeVBPopUpDialog();

                try{
                    eval(successFunction);
                }catch(e){
                    alert("Either "+successFunction+" could not be found or there was an exception!");
                }

                
            });
        }
        

    }else{
        jQuery(popConfirmSpan).hide();
        jQuery(popOkSpan).show();        

    }

    if(showButtons){
        if(themeDisplay){

            var iconImg="/alert_low.png";
            if(iconFlag!=null && iconFlag!=undefined){            
                switch(iconFlag){
                    case 0:
                      break;
                    case 1:
                      iconImg="/alert_medium.png";
                      break;
                    case 2:
                      iconImg="/alert_high.png";
                      break;
                    case 3:
                      iconImg="/are_you_sure.png";
                      break;
                    default:
                      iconImg="/alert_medium.png";
                      break;
                }
            }

            text="<img class='popupIcon' src='"+themeDisplay.getPathThemeImages()+iconImg+"'/>"+text;
        }
        jQuery(contentSpan).addClass("popupMessage");

        /*
        //This would affect the content width since <p> is a block element!!! 
        if(subText!=null && subText!=undefined && subText!=""){
        
           text=text+"<p class='popupSubText'>"+subText+"</p>";
        }*/ 
    }else{
        jQuery(contentSpan).removeClass("popupMessage");
    }
            


    jQuery(contentSpan).html(text);

     var dimensions=getPopUpContentDimensions(showButtons);
     var contentWidth=dimensions.width;
     var contentHeight=dimensions.height;
    
    /*We add this after the width is determined since since <p> is a block element and would affect the width*/
    if(showButtons){
        if(subText!=null && subText!=undefined && subText!=""){           
            jQuery(contentSpan).append("<p class='popupSubText'>"+subText+"</p>");
        }
    }
  

    /*certain events on in the popup change the height and getPopUpContentDimensions is bit heavy for a small height adjustment*/
    jQuery(contentSpan).bind("click",function(e){

        //doing a height adjustment breaks the functionality of input and select elements
        if(e.target.tagName=="INPUT" || e.target.tagName=="SELECT" ){
            return;
        }
        
        var uiDialogDivInner=jQuery("#vbcPopUp").parents(".ui-dialog");
        jQuery(contentSpan).css("visibility","hidden");
        var paddingInner=40;
        if(showButtons){
            paddingInner+=70;
        }
        jQuery(uiDialogDivInner).height(jQuery(contentSpan).height()+paddingInner);
        
        jQuery(contentSpan).css("visibility","visible");

        fixDialogOverlay(uiDialogDivInner);
    });


    if(popUpTitle=="vbPopup"){
        popUpTitle=" ";
    }

    jQuery("#vbcPopUp").dialog({
        title: popUpTitle,
        bgiframe: false,
        width:contentWidth,
        height:contentHeight,
        modal: true,
        resizable:false,
        open: function(event, ui) {

                

                  var uiDialog=jQuery(this).parent().parent();


                  var titlebar=jQuery(uiDialog).find(".ui-dialog-titlebar");
                  var titlebarClose=jQuery(titlebar).find(".ui-dialog-titlebar-close");

                  //jQuery(titlebar).addClass("vbPopupTitle");
                  if(popUpTitle==null || popUpTitle==undefined || popUpTitle==""){                                              
                       jQuery(titlebarClose).hide();

                  }else{                      

                      jQuery(titlebarClose).show();
                  }


                  if(isIE6() && jQuery(uiDialog).height()-jQuery(this).height()<30){
                       jQuery(this).height(jQuery(this).height()-35);
                  } 

                  
                  jQuery(contentSpan).click();                  

                  //fixDialogOverlay(uiDialog);
        }

    });

}

function getPopUpContentDimensions(showButtons){

    var dimensions=new Object();
    dimensions.width=0;
    dimensions.height=0;

    /*if elements display:none then width returns 0. We have to show and set the width of .ui-dialog because if the dialog is called again,
    it will have the previous width and the content in #vbcPopUp will wrap*/
    var uiDialogDiv=jQuery("#vbcPopUp").parents(".ui-dialog");
    var contentSpan=jQuery("#vbcPopUp").find("#vbcPopUpContent");
    var buttonsDiv=jQuery("#vbcPopUp").find("#vbcPopUpButtons");

    jQuery("#vbcPopUp").addClass("inactivePopup");
    jQuery("#vbcPopUp").show();

    if(uiDialogDiv.length>0){    
        jQuery(uiDialogDiv).show();
        /*it's not visible but it's still there*/
        jQuery(uiDialogDiv).css("visibility","hidden");
        jQuery(uiDialogDiv).width("100%");
        jQuery("#vbcPopUp").width("100%");
        jQuery(uiDialogDiv).height("100%");
        jQuery("#vbcPopUp").height("100%");
    }
        
    jQuery(contentSpan).css("visibility","hidden");


    setContentTableWidthsInPopUp(jQuery("#vbcPopUp"));

    var widthPadding=10;
    if(showButtons){
        widthPadding=widthPadding+40;
    }
    /*Get the dynamic content of the width - doesn't take the subtext into account which is what we want*/
    var contentWidth=jQuery(contentSpan).width()+widthPadding;
    //alert("contentWidth2:"+contentWidth+" | "+document.getElementById("vbcPopUpContent").clientWidth+" | "+jQuery(contentSpan).css("visibility"));
    /*if(contentWidth==20){
        contentWidth=jQuery("#vbcPopUp").width();
    }*/


    /*Don't allow popups to be more than a certain amount*/
    var minWidth=300;
    var maxWidth=900;
    if(contentWidth<minWidth){                   
        contentWidth=minWidth;
    }else if(contentWidth>maxWidth){
        contentWidth=maxWidth;
    }



    /*we need to set the container width as it affects the height as the content might wrap due to max width thus changing the height*/
    jQuery("#vbcPopUp").width(contentWidth);
    if(uiDialogDiv.length>0){ 
        jQuery(uiDialogDiv).width(contentWidth);
    }
    
    /*make "active" when doing height*/
    jQuery("#vbcPopUp").removeClass("inactivePopup");


    var contentHeight=jQuery(contentSpan).height();
    /*if(contentHeight==0){
        contentHeight=jQuery("#vbcPopUp").height();
    }*/
    


    jQuery(contentSpan).css("visibility","visible");
    jQuery(uiDialogDiv).hide();

    
    var buttonTopMargin=0;
    if(showButtons){
        buttonTopMargin=70;
        contentHeight=contentHeight+buttonTopMargin;
        contentHeight=contentHeight+jQuery(buttonsDiv).height();
    } 

    var paddingAndTitleHeight=40;
    contentHeight=contentHeight+paddingAndTitleHeight;

    /*Don't allow popups to be more than a certain amount*/
    var minHeight=200;
    if(contentHeight<minHeight){                   
        contentHeight=minHeight;
    }
        
    
    dimensions.width=contentWidth;
    dimensions.height=contentHeight;

    return dimensions;
}


function VBPopUpDialogReAdjustSize(){
    //this function is usually called after an ajax action
	
	//don't bother if the popup is hidden
    if(jQuery("#vbcPopUp").is(":hidden")){
		return;
	}
	
    var oldWidth=jQuery("#vbcPopUp").width();

    var dimensions=getPopUpContentDimensions(false);
    var contentWidth=dimensions.width;
    var contentHeight=dimensions.height;

    var uiDialogDivInner=jQuery("#vbcPopUp").parents(".ui-dialog");
    
    var leftAdjustment=(contentWidth-oldWidth)/2;
    var dialogLeft=getCSSPXValueAsInt(uiDialogDivInner,"left");

    jQuery(uiDialogDivInner).width(contentWidth);
    jQuery(uiDialogDivInner).height(contentHeight);

    jQuery(uiDialogDivInner).css("left",(dialogLeft-leftAdjustment)+"px");
    jQuery(uiDialogDivInner).css("visibility","visible");

    jQuery("#vbcPopUp").find("#vbcPopUpContent").click();

    fixDialogOverlay(uiDialogDivInner);
}


function fixDialogOverlay(uiDialog){
    /*if the dialog goes lower than the overlay then increase the overlay height*/
      var dialogTop=getCSSPXValueAsInt(uiDialog,"top");
      var overlayPadding=30;
            
      var dialogOverlay=jQuery(uiDialog).parent().children(".ui-dialog-overlay");
      var newHeight=dialogTop+jQuery(uiDialog).height()+overlayPadding;
      if (newHeight>jQuery(dialogOverlay).height()){
          jQuery(dialogOverlay).height(newHeight);
      }

}




function fixCorneredClasses(control,excludeClassName,controlObtainedViaJQuery){    
    
    if(controlObtainedViaJQuery){

        var controlClass=control.attr("class");
        if (!controlClass) {
            controlClass=control.attr("className");
        }

        var suffixIn=controlClass.indexOf("jrcRounded");
        if (suffixIn>-1){
            var oldClassName=controlClass.substring(0,suffixIn-1);
            if(excludeClassName!=null){
                if (oldClassName==excludeClassName) {
                    return;
                }
    
            }
    
            control.attr("className",oldClassName);        
        }

    }else{

        var controlClass=control.getAttribute("class");
        if (!controlClass) {
            controlClass=control.getAttribute("className");
        }

        var suffixIn=controlClass.indexOf("jrcRounded");
        if (suffixIn>-1){
            var oldClassName=controlClass.substring(0,suffixIn-1);
            if(excludeClassName!=null){
                if (oldClassName==excludeClassName) {
                    return;
                }
    
            }
    
            control.setAttribute("className",oldClassName);        
        }

    }
}
/* returns the first character of the passed in string */
String.prototype.startsWith = function(str){
    return (this.indexOf(str) === 0);
}

/*
Author: Joe Potgieter
Date  : 2007/03/05

This function filters the body fields of a specified table based on a range of input text
boxes.  These input text boxes may be in the first row of the body of the table or may be
contained in another table outside of the table which will be filtered.

The table to be filtered must have a <tbody> tag that wraps the information to be filtered.

oTable - Table containing body values to filter
oStartRow - Row to start from in Body.  If the filter fields is the 
            first row, then pass 1 as the parameter to filter from the 
            row after the one containing the filter fields.
oFilterFieldElementId - the id of the elment that contains the table data rows
                        that holds the text boxes for the filter.  If a row should 
                        not have a filter, the <td> tag should contain a &nbsp; value.
oCaseSensitive - a boolean value of true or false to indicate if the filter should be 
                 case sensitive.  It can be applied per field.
                        
*/
function filterColumn(oTable, oStartRow, oFilterFieldElementId, oCaseSensitive) {
    
    //TODO: rewrite function, too slow with large number of rows!!!
    
	jQuery(".scrollContainerVB tbody").scrollTop(0);

    var vFilterFieldContainer = document.getElementById(oFilterFieldElementId);
    //var vFiltersFields = vFilterFieldContainer.children.length;
    var vFiltersFields = vFilterFieldContainer.getElementsByTagName("th").length;

    var vTable = document.getElementById(oTable);
    //var vRows = vTable.tBodies[0].rows;

    vTable.parentNode.scrollTop="0px";

    var vtBody=vTable.getElementsByTagName("tbody")[0];
    
    if (!vtBody.getAttribute("originalScrollHeight")) {                
        vtBody.setAttribute("originalScrollHeight",vtBody.scrollHeight);
        vtBody.setAttribute("originalHeight",vtBody.clientHeight);
    }

    //alert(vtBody.clientHeight);
    var vRowsVisible=0;
    var vRows=vtBody.getElementsByTagName("tr");    

    var vStr1 = "";
    var vStr2 = "";
    for ( i = oStartRow ; i < vRows.length ; i++ ) {

       // var vDisplay = 'inline';

         var vDisplay = '';

        // Check each of the filters and apply all
        for( j = 0 ; j < vFiltersFields ; j++ ) {
            //var vTxt = vRows[i].cells[j].innerText;            
            var vTxt = innerText(vRows[i].cells[j]);            

            //var vFilterBox = vFilterFieldContainer.childNodes[j];
            var vFilterBox = vFilterFieldContainer.getElementsByTagName("th")[j];

            
            // Check for a text box at this location and if none, ignore this column.
            if( vFilterBox.childNodes[0] == null || vFilterBox.childNodes[0]==undefined) {
                continue;
            }
            
            //check if child node is valid
            for(k=0; k < vFilterBox.childNodes.length; k++){
                
                if (vFilterBox.childNodes[k].tagName==undefined){
                    continue;
                }


                if(vFilterBox.childNodes[k].tagName.toLowerCase() == "input"){

                                // Check case sensitivity.
                                if( !oCaseSensitive ) {
                                    vStr1 = vTxt.toLowerCase();
                                    vStr2 = vFilterBox.childNodes[k].value.toLowerCase();
                                }
                                else {
                                    vStr1 = vTxt;
                                    vStr2 = vFilterBox.childNodes[k].value;
                                }

                               // Apply the check.
							   /* Changed from indexOf to startsWith based on feedback from Vodacom Business */

                                if(!vStr1.startsWith(vStr2)) {
                                    vDisplay = 'none';
                                    break;
                                }								                        
                         }
                  }              					                  
        }

        if (vDisplay==""){
            vRowsVisible++;
        }

        vRows[i].style.display = vDisplay; 
                
    }

   
    //TODO:change to isFireFox()
    if (!isMicrosoft()){
        var newTbodyHeight=vtBody.getAttribute("originalScrollHeight")*(vRowsVisible/vRows.length);
        if (newTbodyHeight<vtBody.getAttribute("originalHeight")) {
            vtBody.style.height=newTbodyHeight+"px";
        }else{
             vtBody.style.height=vtBody.getAttribute("originalHeight")+"px";
        }  
    }       

    setAllTableAlts();
    
    if (isIE6()) {      
        greyDivToggle=greyDivToggle+1;
        greyDivToggle=greyDivToggle%2;
        /* customHover(document.getElementById("greyOutDiv"),greyDivToggle); */
    }
   

    
}


var greyDivToggle=0;

function innerText(str){
        var re = /<\/?[^>]+>/gi;
        str = str.innerHTML.replace(re,"");
        return trim(str);
}


 function addVBCalendar(uid){
      var control=document.getElementById(uid);
      if (control) {
          jQuery(function() {
          jQuery(control).datepicker({dateFormat:"yy-mm-dd", changeMonth: true,changeYear: true, showOn: 'both', buttonImage: themeDisplay.getPathThemeImages()+'/icons/date_picker.png', buttonImageOnly: true});
      });

      }
      
 }



 function makePortletActive(control){

          makePortletInActive();
          jQuery(control).removeClass().addClass("vbcSkinActive");

        
    }

    function makePortletInActive(){
          jQuery(".vbcSkinActive").removeClass().addClass("vbcSkinInActive");   
        
    }



//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2007 Adobe Systems Incorporated.  All rights reserved.

var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful. 
			
			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	
	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function AC_AddExtension(src, ext)
{
  return src;
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?');     
  else
    return src + ext;
    
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '';
  if (isIE && isWin && !isOpera)
  {
    str += '<object ';
    for (var i in objAttrs)
    {
      str += i + '="' + objAttrs[i] + '" ';
    }
    str += '>';
    for (var i in params)
    {
      str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    }
    str += '</object>';
  }
  else
  {
    str += '<embed ';
    for (var i in embedAttrs)
    {
      str += i + '="' + embedAttrs[i] + '" ';
    }
    str += '> </embed>';
  }

  /*Only write to document if the page is still loading otherwise breaks firefox*/
  if(!DOMloaded){
      document.write(str);
  }else{
      /*attached generate html dynamically to parent*/
      if(document.getElementById(flashAttachToParentId)){
           document.getElementById(flashAttachToParentId).innerHTML=str;
      }else{
          alert("Embed flash error: The variable flashAttachToParentId (id:"+flashAttachToParentId+") was not set to a valid DOM Object");
      }
  }
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
    
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblclick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}


function getFlashMovieObject(movieName){
    

    if (window.document[movieName]){
        return window.document[movieName];
    }
    if (navigator.appName.indexOf("Microsoft Internet")==-1){
        if (document.embeds && document.embeds[movieName]){
            return document.embeds[movieName]; 
        }
    }else{  
        return document.getElementById(movieName);
    }
}

function xGetElementById(e) { 
    if(typeof(e)!='string'){
        return e;
    }    
    if(document.getElementById) {    
        e=document.getElementById(e);
    }else if(document.all){
        e=document.all[e];
    }else{
        e=null;
    }
    return e;             
}
function EmbedFlash(swfFile,name,width,height){
    var htmlUseSwfCacheBuster = "false";
    
    if(name==undefined){
        name = "FlashObject";
    }
    if(width==undefined){
        width = document.body.clientWidth;
    }
    if(height==undefined){
        height = document.body.clientHeight;
    }
    
    
    /*
    //take this out for now as some content doesn't have a swf since it's coming from a servlet
    var pathAr = swfFile.split(".");
    if(pathAr[pathAr.length-1].toLowerCase() == "swf"){
        pathAr.pop();
        swfFile = pathAr.join(".")
    }*/
    
    var mCacheLevel = 0;
    var mCacheID ="";
    var qParam = "?cachebuster=";
    
    if(typeof(flashCacheLevel) == "undefined"){
        alert("please declare var flashCacheLevel = 0,1 or 2 before calling EmbedFlash\n0: no cache busting\n1: daily cash busting\n2: hourly cache busting\n3: full cache busting");
        return;
    }
    if(typeof(flashCacheID) == "undefined"){
        alert("please declare var flashCacheID use blank '' string or a unique flashCacheID string.");
        return;
    }
    
    mCacheLevel = flashCacheLevel;
    
    if(mCacheLevel==0 && flashCacheID.length > 0){
        mCacheID = flashCacheID
    }else{
    
        var today = new Date();
        mCacheID = today.getFullYear() +""+ today.getMonth()+""+ today.getDate();    
             
        switch(mCacheLevel){        
            case 1 :
                mCacheID = mCacheID;
                break;
                
            case 2 :        
                mCacheID += ""+ today.getHours();
                break;        
                
            case 3 :        
                mCacheID += ""+ today.getHours()+""+ today.getMinutes()+""+ today.getSeconds()+""+ today.getSeconds()+""+today.getMilliseconds()+"_"+(parseInt(Math.random(5)*100));
                break;        
                
            default :
                mCacheID = "";
                break;
            
        }
    }
        
    
    if(swfFile.indexOf("?")>-1){
        qParam="&cachebuster=";
    }
    
    swfFile = swfFile + qParam + mCacheID;
    
    //param name="allowNetworking" value="none"
    var args = new Object();

    args['codebase'] = 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0';
    args['width'] = width;
    args['height'] = height;
    args['src'] = swfFile;
    args['quality'] = getDefaultValue(args['quality'],'best');
    args['pluginspage'] = 'http://www.macromedia.com/go/getflashplayer';
    args['align'] = getDefaultValue(args['align'],'middle');
    args['play'] = getDefaultValue(args['play'],'true');
    args['loop'] = getDefaultValue(args['loop'],'false');
    args['scale'] = getDefaultValue(args['scale'],'noScale');
    /*args['wmode'] = getDefaultValue(args['wmode'],'window');*/
    args['wmode'] = getDefaultValue(args['wmode'],'transparent');
    args['devicefont'] = getDefaultValue(args['devicefont'],'false');
    args['allowNetworking'] = getDefaultValue(args['allowNetworking'],'all');    
    args['id'] = name;
    args['bgcolor'] = getDefaultValue(args['bgcolor'],'#FFFFFF');
    args['name'] = name;
    args['menu'] = getDefaultValue(args['menu'],'false');
    args['allowFullScreen'] = getDefaultValue(args['allowFullScreen'],'false');
    args['allowScriptAccess'] = getDefaultValue(args['allowScriptAccess'],'always');
    args['movie'] = swfFile;
    args['salign'] = getDefaultValue(args['salign'],'');
    
    for(var i = 4;i<arguments.length;i+=2){        
        args[arguments[i]] = arguments[i+1];
    }
    

    if(args["FlashVars"] == undefined){
        args["FlashVars"] = "?flashCacheLevel=" + mCacheLevel +"&flashCacheID="+mCacheID;
        
    }else if(typeof(args["FlashVars"])=="string"){
        args["FlashVars"] += "&flashCacheLevel=" + mCacheLevel+"&flashCacheID="+mCacheID;
    }else{
        var tmpObj = args["FlashVars"]
        var buff = new Array();
        for(var i in tmpObj){
            buff.push(i + "=" + escape(tmpObj[i]));
            
        }
        buff.push("flashCacheLevel=" + escape(mCacheLevel));
        buff.push("flashCacheID=" + escape(mCacheID));                
        args["FlashVars"] = "" + buff.join("&");
    }
    //alert(args["FlashVars"]);
    
    var fArgs = new Array();
    for(i in args){
        fArgs.push(i);
        fArgs.push(args[i]);        
        //alert(i +"\n"+args[i]);
    }
    
    AC_FL_RunContent.apply(null,fArgs)
    return xGetElementById(name);
}
function getDefaultValue(prop,def){    
    if(prop==undefined || prop==null){
        return def;
    }
    return prop;
    
}
function getInnerHTML(node){
        var buffer = new Array();
        do_getInnerHTML(node,buffer);
        return buffer.join("");
    }
function do_getInnerHTML (obj,buff) {
    if (!obj){ 
        return;
    }
    for (var ix = 0; ix < obj.childNodes.length; ix++) {
        
        var cObj = obj.childNodes[ix];
        
        if (!cObj.tagName){
            buff.push(cObj.nodeValue);
        }else{
            buff.push("<"+cObj.tagName);
            for( var x = 0; x < cObj.attributes.length; x++ ) {
                if(cObj.attributes[x].nodeValue !=null){
                    buff.push(" " + cObj.attributes[x].nodeName + "='"+cObj.attributes[x].nodeValue+"'");
                }
            }
            buff.push(">")
            if (cObj.childNodes) { 
                do_getInnerHTML(cObj,buff); 
            }
            buff.push("</"+cObj.tagName+">");
        }
    }
}


var traceWin = null;
function htmlTrace(str){

    if(traceWin!=null){
        if(traceWin.closed){
            traceWin = null;
        }
    }
    if(traceWin==null){
       traceWin = window.open ("aboutblank","mywindow","status=1,toolbar=1,location=0,width=960px,height=540");
       
        
    }
    traceWin.document.write(str);
}

function googleTrackPageView(url){
    try{
        pageTracker._trackPageview(url);
    }catch(err){}
}
/* New monthly widget pop-up */
var launchDatePicker = function(title, content) {
	jQuery(document).ready(function() {
		
		jQuery("#month_selector_widget_header").empty();
		jQuery("#month_selector_widget_body").empty();
		
		/*Adds the title and the HTML content for the body of the pop-up */
		var close = "<span><a href=\"#close\" id=\"close_month_widget\" title=\"Close Month Widget\">X</a></span>";
		jQuery("#month_selector_widget_header").append(title + close);
		jQuery("#month_selector_widget_body").append(content);
		
		openDatePicker();
		
		jQuery("#close_month_widget").click(closeDatePicker);
	});
}

var openDatePicker = function() {
	if (isMicrosoft()){
		jQuery("#month_selector_widget").corner("10px");
	}
	
	var pos = jQuery("#launch_date_picker").offset();
	if(isIE6()) {
		jQuery("#month_selector_widget").css({
			"left": (pos.left - 540) + "px",
			"top": pos.top + "px"
		});
	} else {
		jQuery("#month_selector_widget").css({
			"left": (pos.left - 420) + "px",
			"top": pos.top + "px"
		});
	}	
	jQuery("#month_selector_widget").fadeIn("slow");	
	return false;
}

var closeDatePicker = function() {
	jQuery("#month_selector_widget").hide();
	return false;
}

/*
 * Function sets the width of the wrapper element to auto to prevent IE and Chrome
 * from incorrectly centering the content inside the pop-up's. Also adjusts the width 
 * of the container DIV to avoid scroll bars in Webkit based browsers.
 */
var fixPopUp = function() {
	var wrapperSelector = jQuery("#wrapper");
	
	if(jQuery(".popup_content_container_no_logo").length != 0) {
		/*
	 	* Should create the "options" object once and re-use
	 	*/
		jQuery(wrapperSelector).css({
			"margin-left" : "0",
			"width" : "570px"
		});
		jQuery("form[name='hrefFm']").css("display", "none");
	}
	
	if(jQuery(".popup_content_container").length != 0) {
		jQuery(wrapperSelector).css({
			"margin-left" : "0",
			"width" : "570px"
		});
		jQuery("form[name='hrefFm']").css("display", "none");
	}
	
	if(jQuery("#tools_container").length != 0) {
		jQuery(wrapperSelector).css({
			"margin-left" : "0",
			"width" : "570px"
		});
		jQuery("form[name='hrefFm']").css("display", "none");
	}
}

/*
 * Uses the jQuery outerHeight function and passes in true which means that for the 
 * specified element, jQuery will return the element height including padding, borders 
 * as well as margins. Some height is added to overcome cross browser compatibility
 * 
 * @tools_container = If testing for the id #tools_container returns true, we know that the current 
 * pop-up is one which uses the vb-tools-layout and that has a heading, body and footer.
 */
var dynamicPopup = function(_width) {

	fixPopUp();
	
	if (isIE6()) {
		if ((jQuery("#tools_container").length > 0) && (jQuery(".tools_heading").length > 0)) {
			window.resizeTo(_width, (jQuery("#tools_container").outerHeight() + jQuery(".tools_heading").outerHeight()) + 10);
		} else if((jQuery("#tools_container").length > 0) && (jQuery(".tools_heading").length == 0)) {
			window.resizeTo(_width, (jQuery("#tools_container").outerHeight(true) + jQuery(".tools_heading").outerHeight(true)) + 40);
		} else if(jQuery("#tools_footer").length > 0) {
			window.resizeTo(_width, jQuery(".tools_heading").outerHeight() + jQuery("#tools_container").outerHeight() + jQuery("#tools_footer").outerHeight() + 20);
		} else {
			window.resizeTo(_width, jQuery("#wrapper").outerHeight(true) + 40);
		}		
		
	} else if(isMicrosoft()) {
		if ((jQuery("#tools_container").length > 0) && (jQuery(".tools_heading").length > 0)) {
			window.resizeTo(_width, (jQuery("#tools_container").outerHeight() + jQuery(".tools_heading").outerHeight()) + 75);
		} else if((jQuery("#tools_container").length > 0) && (jQuery(".tools_heading").length == 0)) {
			window.resizeTo(_width, (jQuery("#tools_container").outerHeight(true) + jQuery(".tools_heading").outerHeight(true)) + 100);
		} else if(jQuery("#tools_footer").length > 0) {
			window.resizeTo(_width, jQuery(".tools_heading").outerHeight() + jQuery("#tools_container").outerHeight() + jQuery("#tools_footer").outerHeight() + 20);
		} else {
			window.resizeTo(_width, jQuery("#wrapper").outerHeight(true) + 40);
		}
	} else {
		
		if (jQuery("#body_content").length != 0) {
			var _height = jQuery("#body_content").outerHeight(true);
			window.resizeTo(parseInt(_width) + 5, jQuery("body").outerHeight(true) + _height + 93);
		} else if((jQuery("#tools_container").length > 0) && (jQuery(".tools_heading").length > 0)) {
			window.resizeTo(_width, jQuery("#tools_container").outerHeight(true) + jQuery(".tools_heading").outerHeight(true) + 65);
		} else if((jQuery("#tools_container").length > 0) && (jQuery(".tools_heading").length == 0)) {
			window.resizeTo(_width, jQuery("#tools_container").outerHeight(true) + jQuery(".tools_heading").outerHeight(true) + 95);
		} else if(jQuery(".popup_content_container_no_logo").length != 0) {
		    window.resizeTo(_width, jQuery("body").outerHeight(true) + 93);   
		} else if(jQuery("#tools_footer").length > 0) {
			window.resizeTo(_width, jQuery(".tools_heading").outerHeight() + jQuery("#tools_container").outerHeight() + jQuery("#tools_footer").outerHeight() + 65);
		} 
	}
}

var resizeTariffLocator = function(_width) {
	window.resizeTo(_width, (jQuery("#tools_container").outerHeight(true) + jQuery(".tools_heading").outerHeight(true)) + 75);
}

var VBOpenPopUp = function(_url, _height, _width) {
	var defaultWidth = 960;
	var defaultHeight = 400;
	
	var _width = _width;
	var _height = _height;
	
	var newwindow;
	
	if((_width === '') || (_width === '$popupWidth')) {
		_width = defaultWidth;
	}
	
	if((_height === '') || (_height === '$popupHeight')) {
		_height = defaultHeight;
	}
	
	if(isMicrosoft()) {
		newwindow = window.open(_url, 'VodacomBusiness', 'height=' + _height + ', width=' + _width + ' resizable=false');
	} else {
		newwindow = window.open(_url, 'VodacomBusiness', 'height=' + _height + ', width=' + _width + ' resizable=false');
	}
	
	if(window.focus) {
		newwindow.focus();
	}
	return false;
}

/* Rob JavaScript */
function VBNewWindowPopup(url) {
	return window.open(url);
}

function VBWindowRedirect(url) {
	return window.location(url);
}

function imageRotatePopup(url) {
	popupWindow = window.open(url);
}

var myRotatingTimer;
function rotateImageTimer(reservedArticleId,seconds,numOfPages,activateTimer,showNext) {
	
	var containerId = "imageRotatorContainer" + reservedArticleId;
	var container=jQuery("#"+containerId);
	
	var nextIndex=jQuery(container).attr("nextIndex");
	var nextIndexInt;
	
	if(nextIndex==undefined || nextIndex==null || nextIndex=="" || nextIndex=="NaN") {
		jQuery(container).attr("nextindex","0");
		nextIndex = "0";
	}
	
	nextIndexInt=parseInt(nextIndex);
	
	var currentIndex = nextIndexInt;
	
	if((numOfPages == nextIndexInt || nextIndexInt < 0) && showNext) {
		nextIndexInt=0;
	}
	
	
	if (showNext) {
	    updateIndexInt=nextIndexInt+1;
	} else {
		    updateIndexInt = nextIndexInt-1;
			nextIndexInt = nextIndexInt-2;
	}
	
	jQuery(container).attr("nextIndex",updateIndexInt+"");
	imageRotateChangeBanner(currentIndex, nextIndexInt,numOfPages,reservedArticleId,seconds,activateTimer);
	if (activateTimer) {
	    clearTimeout(myRotatingTimer);
		myRotatingTimer = setTimeout("rotateImageTimer('" + reservedArticleId + "'," + seconds + "," + numOfPages + "," + activateTimer + "," + true + ")", seconds * 1000);
	}
}

function imageRotateChangeBanner(_currentIndex, pageIndex, numberOfPages,reservedArticleId,seconds,activateTimer) {
	
	var divContainerId = "imageRotatorContainer" + reservedArticleId;
	var currentDivAdvertId = "currentAdvertId" + _currentIndex;
	var divAdvertId = "currentAdvertId" + pageIndex;
	
	if (pageIndex >= 0 && pageIndex<numberOfPages) {
		jQuery('#' + divContainerId + ' .imageRotateDiv').hide();
		jQuery('#' + divContainerId + ' #'+ divAdvertId).show();
	}
	
}

function setPreviousMainContainerRotate(pageIndex, numberOfPages,reservedArticleId) {
	if (pageIndex >= 0 && pageIndex<numberOfPages) {
		var showDivId = "content_page_Id" + reservedArticleId + "" + pageIndex;		
		var hideDivId = "main_content_identifier" + reservedArticleId;
		jQuery('.' + hideDivId).hide();
		jQuery('#'+ showDivId).show();
	}
}


// Paging
var pagingTables=new Array();
	
function registerPagingTable(tableId,servletPath,parameterIds){
	var vTableSelector="#"+tableId;
	var vTable=jQuery(vTableSelector);
	var vTbody=jQuery(vTable).find("tbody");
	var vRows=jQuery(vTbody).attr("rows");
	var itemsPerPage=jQuery(vTable).attr("itemsPerPage");
	if(!itemsPerPage){
		itemsPerPage=jQuery(vTable).attr("itemsPerPage","10");
	}
	itemsPerPage=parseInt(itemsPerPage);
	
	var currentPagingTableOffsets=new Array();
	var numPages=vRows.length/itemsPerPage;
	for(x=0;x<numPages;x++){
			
		currentPagingTableOffsets.push(x);
	}
			
	pagingTables.push(currentPagingTableOffsets);
	
	jQuery(vTable).attr("pagingTablesIndex",pagingTables.length-1);
	jQuery(vTable).attr("servletPath",servletPath);
	jQuery(vTable).attr("parameterIds",parameterIds);
	
	jQuery(vTable).attr("currentPage","0");
	
	gotoPageOnTable(tableId,0);
}	

function arrayContains(arr,element){
	var x=0;
	for(x=0;x<arr.length;x++){
		if(arr[x]==element){
			return true;
		}
	}
	
	return false;
}



function registerPageForTable(tableId,pageIndex,html,extraPages){
		var vTableSelector="#"+tableId;
		var vTable=jQuery(vTableSelector);
		var pagingTablesIndex=jQuery(vTable).attr("pagingTablesIndex");
		if(!pagingTablesIndex || pagingTables.length==0){
			alert("The table "+tableId+" has not been registered for paging.");
			return;
		}
		
		var itemsPerPage=jQuery(vTable).attr("itemsPerPage");	
		itemsPerPage=parseInt(itemsPerPage);
		var maxItems=jQuery(vTable).attr("maxItems");
		maxItems=parseInt(maxItems);
		var numPages=Math.ceil(maxItems/itemsPerPage);
		
		pagingTablesIndex=parseInt(pagingTablesIndex);						
		var currentOffsets=pagingTables[pagingTablesIndex];
		
		if(!arrayContains(currentOffsets,pageIndex)){				
			if(pageIndex>=numPages){
				return;
			}
			currentOffsets.push(pageIndex);
			//add extra pages
			var x;
			for(x=1;x<=extraPages;x++){
					if((pageIndex+x)>=numPages){
						break;
					}
					currentOffsets.push(pageIndex+x);
			}
			
			extraPages=x-1;
			
			var newRowSearch=html.match(/<\/tr>/g);
			var newRows=0;
			if(newRowSearch){
				newRows=newRowSearch.length;
			}
			
			var expectedRows=itemsPerPage*(extraPages+1); 
			if(expectedRows>newRows){
				var differenceRows=expectedRows-newRows;
				var z=0;
				var y=0;
				var differenceHTML="";
				var cols=0;
				var trMatch=html.match(/<tr>[\s\S]*?<\/tr>/m);

				if(trMatch && trMatch.length>0){
					var tdMatches=trMatch[0].match(/<\/td>/g);
					if(tdMatches){
						cols=tdMatches.length;
					}
				}
				
				for(z=0;z<differenceRows;z++){
					differenceHTML=differenceHTML+"<TR>";
						for(y=0;y<cols;y++){
									differenceHTML=differenceHTML+"<TD>&nbsp;</TD>";
						}
					differenceHTML=differenceHTML+"</TR>";
				}
				
				html=html+differenceHTML;
			}
			
			addRowsToPagingTable(vTable,html);
		}
}

function addRowsToPagingTable(tableElement,html){
	var vTbody=jQuery(tableElement).find("tbody");
	vTbody.append(html);
	/* I hate doing this but here we go - Schalk */
	var waitForDom = setTimeout("window.resizeTo(580, (jQuery('#tools_container').outerHeight(true) + jQuery('.tools_heading').outerHeight(true)) + 10)", 1000);
}

function fetchPageForTable(vTable,pageIndex,batchCall,gotoPageAfter){
	var vTableId=jQuery(vTable).attr("id");
	
	var itemsPerPage=jQuery(vTable).attr("itemsPerPage");	
	itemsPerPage=parseInt(itemsPerPage);
	
	var newIndex=pageIndex;
	var extraPages=0;
	
	
	if(batchCall){
		var pagingTablesIndex=jQuery(vTable).attr("pagingTablesIndex");
		if(!pagingTablesIndex || pagingTables.length==0){
			alert("The table "+tableId+" has not been registered for paging.");
			return;
		}
		
		pagingTablesIndex=parseInt(pagingTablesIndex);						
		var currentOffsets=pagingTables[pagingTablesIndex];
	
		var numPagesAhead=3;
		var z;
		var newItemsPerPage=0;
		for(z=pageIndex;z<=(pageIndex+numPagesAhead);z++){
			if(!arrayContains(currentOffsets,z)){				
				//newItemsPerPage=newItemsPerPage+itemsPerPage;
				extraPages=extraPages+1;
			}else{
				break;
			}
		}
		
		
		for(z=pageIndex-1;z>=(pageIndex-numPagesAhead);z--){
			if(!arrayContains(currentOffsets,z)){				
				//newItemsPerPage=newItemsPerPage+itemsPerPage;
				extraPages=extraPages+1;
				newIndex=newIndex-1;
			}else{
				break;
			}
		}
				
		//itemsPerPage=newItemsPerPage;
	}
	
	var servletPath=jQuery(vTable).attr("servletPath");
	var parameterIds=jQuery(vTable).attr("parameterIds");
	var parameterIdParts=parameterIds.split("|");
	var parameterUrlStr="";
	if(parameterIdParts!=null && parameterIdParts.length>0){
		var x;
		var parameterName;
		var parameterValue;
		var tempElement;
		for(x=0;x<parameterIdParts.length;x++){
			parameterName=parameterIdParts[x];
			parameterValue="";
			tempElement=document.getElementById(parameterName);
			if(tempElement){
				parameterValue=tempElement.value;
			}
			
			if(parameterValue && parameterValue!=null && parameterValue!=""){
				parameterUrlStr=parameterUrlStr+parameterIdParts[x]+"="+parameterValue+"&";
			}
		}
		
		if(endsWith(parameterUrlStr,"&")){
			parameterUrlStr=parameterUrlStr.substring(0,parameterUrlStr.length-1);
		}
	}

	servletPath=servletPath+"?PageIndex="+newIndex+"&ItemsPerPage="+itemsPerPage+"&NumPages="+extraPages;
	//alert("servletPath:"+servletPath);
	if(parameterUrlStr!=""){
		servletPath=servletPath+"&"+parameterUrlStr;
	}

	jQuery.get(servletPath, function(data){			
			//don't include current page
			registerPageForTable(vTableId,newIndex,data,extraPages-1);
			if(gotoPageAfter){
				/*we still go to the original index*/
				gotoPageOnTable(vTableId,pageIndex);
			}else{
				doingPreEmptiveCall=false;
			}
    }); 
}

function getPagingOffset(offsetArray,pageIndex){
	
	var offsetIndex=0;
	for(offsetIndex=0;offsetIndex<offsetArray.length;offsetIndex++){
			if(offsetArray[offsetIndex]==pageIndex){
				break;
			}
	}
	
	return offsetIndex;
}

var doingPreEmptiveCall=false;
function gotoPageOnTable(tableId,pageIndex){		
	
	var vTableSelector="#"+tableId;
	var vTable=jQuery(vTableSelector);	
	var itemsPerPage=jQuery(vTable).attr("itemsPerPage");
	if(!itemsPerPage){
		itemsPerPage=jQuery(vTable).attr("itemsPerPage","10");
	}
	
	var currentPage=jQuery(vTable).attr("currentPage");	
	if(!currentPage){
		currentPage=0;
		jQuery(vTable).attr("currentPage","0");
	}
	
	currentPage=parseInt(currentPage);
	itemsPerPage=parseInt(itemsPerPage);
	
	var pagingTablesIndex=jQuery(vTable).attr("pagingTablesIndex");
	if(!pagingTablesIndex || pagingTables.length==0){
		alert("The table "+tableId+" has not been registered for paging.");
		return;
	}
	
	pagingTablesIndex=parseInt(pagingTablesIndex);
	
	
						
	var currentOffsets=pagingTables[pagingTablesIndex];
	
	if(!arrayContains(currentOffsets,pageIndex)){		
		fetchPageForTable(vTable,pageIndex,true,true);
		return;
	}
	
	var maxItems=jQuery(vTable).attr("maxItems");
	maxItems=parseInt(maxItems);
	var numPages=Math.ceil(maxItems/itemsPerPage);	
	
	/*don't look ahead if we are at the end*/
	if(pageIndex<(numPages-1)){
		/*do pre-emptive check going forward*/
		var futureIndex=pageIndex+1;
		if(!arrayContains(currentOffsets,futureIndex)){
			/*load the pages but don't goto the page*/
			if(!doingPreEmptiveCall){
				fetchPageForTable(vTable,futureIndex,true,false);
			}
		}else if(!arrayContains(currentOffsets,futureIndex+1)){
			/*load the pages but don't goto the page*/
			doingPreEmptiveCall=true;
			try{
				fetchPageForTable(vTable,futureIndex+1,true,false);
			}catch(e){
				alert("Error doing pre-emptive call.");
				doingPreEmptiveCall=false;				
			}
		}
	}
	

	
	var newOffsetIndex=getPagingOffset(currentOffsets,pageIndex);
	var oldOffsetIndex=getPagingOffset(currentOffsets,currentPage);
	
	var vTbody=jQuery(vTable).find("tbody");	
	var vRows=jQuery(vTbody).attr("rows");
	
	/*hide old page*/
	var vStartingIndex=oldOffsetIndex*itemsPerPage;
	var vEndIndex=(oldOffsetIndex*itemsPerPage)+itemsPerPage;
	var i;
	for(i=vStartingIndex;i<vEndIndex;i++){
			//jQuery(vRows[i]).css("display", "none");
			if(vRows[i]){
				vRows[i].style.display="none";
			}
	}
	
	/*show new page*/
	vStartingIndex=newOffsetIndex*itemsPerPage;
	vEndIndex=(newOffsetIndex*itemsPerPage)+itemsPerPage;
	var oddRow=0;
	for(i=vStartingIndex;i<vEndIndex;i++){
			//jQuery(vRows[i]).css("display", "table-row");
			if(vRows[i]){
				if(isMicrosoft()){
					vRows[i].style.display="inline-block";
				}else{
					vRows[i].style.display="table-row";
				}
				
				if(oddRow==0){
					jQuery(vRows[i]).attr("class", "VBRow1");
				}else{
					jQuery(vRows[i]).attr("class", "VBRowOddTL");
				}
				
				if (vRows[i].style.display != "none") {
					oddRow=oddRow+1;
				}
				oddRow=oddRow%2;
			}
	}

	jQuery(vTable).attr("currentPage",pageIndex);
	drawPagingControls(vTable);
}

function gotoNextPageOnTable(tableId){
	
	var vTableSelector="#"+tableId;
	var vTable=jQuery(vTableSelector);
	
	var currentPage=jQuery(vTable).attr("currentPage");				
	
	if(!currentPage){
		currentPage=0;
		jQuery(vTable).attr("currentPage","0");
	}
			
	var itemsPerPage=jQuery(vTable).attr("itemsPerPage");					
	var maxItems=jQuery(vTable).attr("maxItems");			
	itemsPerPage=parseInt(itemsPerPage);
	maxItems=parseInt(maxItems);
	var numPages=Math.ceil(maxItems/itemsPerPage)-1;
	if(currentPage<numPages){
		currentPage=parseInt(currentPage)+1;
		gotoPageOnTable(tableId,currentPage);
	}
}

function gotoPreviousPageOnTable(tableId){
	
	var vTableSelector="#"+tableId;
	var vTable=jQuery(vTableSelector);
	
	var currentPage=jQuery(vTable).attr("currentPage");				
	
	if(!currentPage){
		currentPage=0;
		jQuery(vTable).attr("currentPage","0");
	}

	if(currentPage>0){
		currentPage=parseInt(currentPage)-1;
		gotoPageOnTable(tableId,currentPage);
	}
}

function gotoLastPageOnTable(tableId){
	var vTableSelector="#"+tableId;
	var vTable=jQuery(vTableSelector);
	var itemsPerPage=jQuery(vTable).attr("itemsPerPage");					
	var maxItems=jQuery(vTable).attr("maxItems");			
	itemsPerPage=parseInt(itemsPerPage);
	maxItems=parseInt(maxItems);
	var numPages=Math.ceil(maxItems/itemsPerPage);
	gotoPageOnTable(tableId,numPages-1);	
}

function drawPagingControls(vTable){

	jQuery(document).ready(function(){
		var vTableId = jQuery(vTable).attr("id");
		var vPagingFooter = jQuery(vTable).parents(".portlet-boundary").find(".pagingFooter");
		var controlNumbers = "";
		
		var itemsPerPage = jQuery(vTable).attr("itemsPerPage");
		var currentPage = jQuery(vTable).attr("currentPage");
		var maxItems = jQuery(vTable).attr("maxItems");
		currentPage = parseInt(currentPage);
		itemsPerPage = parseInt(itemsPerPage);
		maxItems = parseInt(maxItems);
		
		var maxDisplay = 7;
		var numPages = Math.ceil(maxItems / itemsPerPage);
		var startIndex = 0;
		var endIndex = numPages - 1;
		var dotsAtStart = false;
		var dotsAtEnd = false;
		if (numPages > maxDisplay) {
			var halfOfMaxDisplay = Math.ceil(maxDisplay / 2);
			if (currentPage < halfOfMaxDisplay) {
				startIndex = 0;
				endIndex = startIndex + maxDisplay - 1;
			}
			else 
				if ((numPages - currentPage) < halfOfMaxDisplay) {
					endIndex = numPages - 1;
					startIndex = endIndex - maxDisplay;
					dotsAtStart = true;
				}
				else {
					startIndex = currentPage - halfOfMaxDisplay + 1;
					endIndex = currentPage + halfOfMaxDisplay - 1;
					dotsAtStart = true;
					dotsAtEnd = true;
				}
			
			
			
		}
		
		if (dotsAtStart) {
			controlNumbers += "<a href='#'>...</a>";
		}
		
		for (i = startIndex; i <= endIndex; i++) {
			controlNumbers += "<a href='#' onclick='gotoPageOnTable(\"" + vTableId + "\"," + i + ");'";
			if (i == currentPage) {
				controlNumbers += " class='pageSelected'";
			}
			controlNumbers += ">" + (i + 1) + "</a>";
		}
		
		if (dotsAtEnd) {
			controlNumbers += "<a href='#'>...</a>";
		}
		
		var pagingControlsSpan = jQuery(vPagingFooter).find("span.pagingControls");
		var vPagingSpanPre = "<span class='pagingControls'>";
		var vPagingFooterPre = "<a href='#' onclick='gotoPageOnTable(\"" + vTableId + "\",0);'>First</a> <a href='#' onclick='gotoPreviousPageOnTable(\"" + vTableId + "\");'>Previous</a>";
		var vPagingFooterPost = "<a href='#' onclick='gotoNextPageOnTable(\"" + vTableId + "\");'>Next</a><a href='#' onclick='gotoLastPageOnTable(\"" + vTableId + "\");'>Last</a>";
		var vPagingSpanEnd = "</span>";
		
		if (currentPage == 0) {
			vPagingFooterPre = "";
		}
		else 
			if (currentPage == (numPages - 1)) {
				vPagingFooterPost = "";
			}
		
		if (numPages == 1) {
			vPagingFooterPre = "";
			vPagingFooterPost = "";
			controlNumbers = "";
		}
		
		if (pagingControlsSpan.size() == 0) {
			jQuery(vPagingFooter).append(vPagingSpanPre + vPagingFooterPre + controlNumbers + vPagingFooterPost + vPagingSpanEnd);
		}
		else {
			jQuery(pagingControlsSpan).html(vPagingFooterPre + controlNumbers + vPagingFooterPost);
		}
	});
}

/* SEXY COMBO */
;(function($) {
    $.fn.sexyCombo = function(config) {
        return this.each(function() {
		if ("SELECT" != this.tagName.toUpperCase()) {
		    return;	
		}
	    new $sc(this, config);
	    });  
    };
    
    //default config options
    var defaults = {
        //skin name
        skin: "sexy",
	
	    //this suffix will be appended to the selectbox's name and will be text input's name
	    suffix: "__sexyCombo",
	
	    //the same as the previous, but for hidden input
	    hiddenSuffix: "__sexyComboHidden",
	
	   //initial / default hidden field value.
	   //Also applied when user types something that is not in the options list
	    initialHiddenValue: "",
	
	    //if provided, will be the value of the text input when it has no value and focus
	    emptyText: "",
	
	    //if true, autofilling will be enabled
	    autoFill: false,
	
	    //if true, selected option of the selectbox will be the initial value of the combo
	    triggerSelected: true,
	
	    //function for options filtering
	    filterFn: null,
	
	    //if true, the options list will be placed above text input
	    dropUp: false,
	
	    //separator for values of multiple combos
	    separator: ",",
	
	    //all callback functions are called in the scope of the current sexyCombo instance
	
	    //called after dropdown list appears
	    showListCallback: null,
	
	    //called after dropdown list disappears
	    hideListCallback: null,
	
	    //called at the end of constructor
	    initCallback: null,
	
	    //called at the end of initEvents function
	    initEventsCallback: null,
	
	    //called when both text and hidden inputs values are changed
	    changeCallback: null,
	
	    //called when text input's value is changed
	    textChangeCallback: null
    };
    
    //constructor
    //creates initial markup and does some initialization
    $.sexyCombo = function(selectbox, config) {
		
        if (selectbox.tagName.toUpperCase() != "SELECT")
	        return;
	    
	    this.config = $.extend({}, defaults, config || {}); 		   
	    
        var spacerWidth=$(selectbox).parent().width();

	    this.selectbox = $(selectbox);
	    this.options = this.selectbox.children().filter("option");
	
	    this.wrapper = this.selectbox.wrap("<div>").
	    hide().
	    parent().
	    addClass("combo").
	    addClass(this.config.skin);

        		
	    this.input = $("<input type='text' />").
	    appendTo(this.wrapper).
	    attr("autocomplete", "off").
	    attr("value", "").
	    attr("name", this.selectbox.attr("name") + this.config.suffix);
	
	    this.hidden = $("<input type='hidden' />").
	    appendTo(this.wrapper).
	    attr("autocomplete", "off").
	    attr("value", this.config.initialHiddenValue).
	    attr("name", this.selectbox.attr("name") + this.config.hiddenSuffix);
	
        this.icon = $("<div />").
	    appendTo(this.wrapper).
	    addClass("icon"); 
	
	    this.listWrapper = $("<div />").
	    appendTo(this.wrapper).
	    //addClass("invisible").
	    addClass("list-wrapper"); 
		if ("function" == typeof this.listWrapper.bgiframe) {
		    this.listWrapper.bgiframe({height: 1000});
		}
	    this.updateDrop();
	
	    this.list = $("<ul />").appendTo(this.listWrapper); 
	    var self = this;
	    this.options.each(function() {
	        var optionText = $.trim($(this).text());
	        $("<li />").
	        appendTo(self.list).
	        html("<span>"+optionText+"</span>").
	        addClass("visible");
	    
	    });  
		
	
	    this.listItems = this.list.children();
		
		//alert(this.listItems.find("span").outerWidth());
		
		var optWidths = [];
		
		this.listItems.find("span").each(function() {
		    optWidths.push($(this).outerWidth());										  
		});
		
		optWidths = optWidths.sort(function(a, b) {
		    return a - b;									
		});
		var maxOptionWidth = optWidths[optWidths.length - 1];

        this.singleItemHeight = this.listItems.outerHeight();
		this.listWrapper.addClass("invisible");
		
       
	    if ($.browser.opera) {
	        this.wrapper.css({position: "relative", left: "0", top: "0"});
	    } 
	
	
	
	    this.filterFn = ("function" == typeof(this.config.filterFn)) ? this.config.filterFn : this.filterFn;
	
	    this.lastKey = null;
	    //this.overflowCSS = "overflow";
	
	    this.multiple = this.selectbox.attr("multiple");
	
	    var self = this;
	
	    this.wrapper.data("sc:lastEvent", "click");
	
	    this.overflowCSS = "overflowY";

        //alert(maxOptionWidth+"-"+this.input.innerWidth());
	
	    //if (this.listWrapper.innerWidth() < maxOptionWidth) {
        if (this.input.innerWidth() < maxOptionWidth) {

            //alert("in");

            this.overflowCSS = "overflow";


            this.wrapper.width(maxOptionWidth+20);
            this.input.width(maxOptionWidth+14);
            
            this.listWrapper.width(maxOptionWidth+20);

            this.icon.css("left",maxOptionWidth-4+"px");
		}
        
        
                /*var spacerDiv="<div style='background:red;width:"+spacerWidth+"px;'/>";
        this.input = $(spacerDiv).appendTo(this.wrapper); */



	    this.notify("init");
	    this.initEvents();
    };
    
    //shortcuts
    var $sc = $.sexyCombo;
    $sc.fn = $sc.prototype = {};
    $sc.fn.extend = $sc.extend = $.extend;
    
    $sc.fn.extend({
        //TOC of our plugin
	    //initializes all event listeners
        initEvents: function() {
	        var self = this;
	    
	        this.icon.bind("click", function() {
		        if (self.input.attr("disabled")) {
			         self.input.attr("disabled", false);   
		        }
		        self.wrapper.data("sc:lastEvent", "click");
		        self.filter();
	            self.iconClick();
	        }); 
	    
	        this.listItems.bind("mouseover", function(e) {
	            self.highlight(e.target);
	        });

            

	    
	        this.listItems.bind("click", function(e) {
	            self.listItemClick($(e.target));
	        });
		
			this.input.bind("keyup", function(e) {
				self.wrapper.data("sc:lastEvent", "key");							                //alert(self.wrapper.data("sc:lastEvent"));
			});		
	    
	        this.input.bind("keyup", function(e) {
	            self.keyUp(e);
	        });
			

            /*set the default value if the current value is not valid*/
            this.input.bind("blur", function(e) {

                /*if(self.getHiddenValue()==undefined || self.getHiddenValue()==""){
                    //set default value
                    //self.getActive().text()
                    if(self.listItems.length>0){                    
                        self.setComboValue($(self.listItems.get(0)).text(), false, false);
                    }
                    
                } */

	        });

	    
	        this.input.bind("keypress", function(e) {
	            if ($sc.KEY.RETURN == e.keyCode) {
	                e.preventDefault();
			    }
		        if ($sc.KEY.TAB == e.keyCode)
			        e.preventDefault();
	        });
	    
	        $(document).bind("click", function(e) {
	            if ((self.icon.get(0) == e.target) || (self.input.get(0) == e.target))
		            return;
		    
		        self.hideList();    
	        });
	    
	        this.triggerSelected();
	        this.applyEmptyText();
	    
	        
		
		    this.input.bind("click", function(e) {
			    self.wrapper.data("sc:lastEvent", "click");	
			    self.icon.trigger("click");
		    });
			
			
			//here
	        this.wrapper.bind("click", function() {
	            self.wrapper.data("sc:lastEvent", "click");								
	        });
	
	        this.input.bind("keydown", function(e) {
	            if (9 == e.keyCode) {
		            e.preventDefault();
		        }
	        });
	
	        this.wrapper.bind("keyup", function(e) {
		        var k = e.keyCode;
		        for (key in $sc.KEY) {
		            if ($sc.KEY[key] == k) {
			            return;	
			        }
		        }
	            self.wrapper.data("sc:lastEvent", "key");	
				//$sc.log("Last evt is key");
	        });	
	
	        this.input.bind("click", function() {
	            self.wrapper.data("sc:lastEvent", "click");		
            });
	
	        this.icon.bind("click", function(e) {
	            if (!self.wrapper.data("sc:positionY"))	{
		            self.wrapper.data("sc:positionY", e.pageY);	    	
		        }
	        });
	
	        this.input.bind("click", function(e) {
	            if (!self.wrapper.data("sc:positionY"))	{
		            self.wrapper.data("sc:positionY", e.pageY);	    	
		        }								 
	        });
	

	        this.wrapper.bind("click", function(e) {
	            if (!self.wrapper.data("sc:positionY"))	{
		            self.wrapper.data("sc:positionY", e.pageY);	 
		        }									   
	        });				
			
			this.notify("initEvents");
	    },
	
	
	    getTextValue: function() {
            return this.__getValue("input");
	    },
	
	    getCurrentTextValue: function() {
            return this.__getCurrentValue("input");
	    },
	
	    getHiddenValue: function() {
            return this.__getValue("hidden");
	    },
	
	    getCurrentHiddenValue: function() {	    
	        return this.__getCurrentValue("hidden");
	    },
	
	    __getValue: function(prop) {
	        prop = this[prop];
	        if (!this.multiple)
	            return $.trim(prop.val());
		
	        var tmpVals = prop.val().split(this.config.separator);
	        var vals = [];
	    
	        for (var i = 0, len = tmpVals.length; i < len; ++i) {
	            vals.push($.trim(tmpVals[i]));
	        }	
	    
	        vals = $sc.normalizeArray(vals);
	    
	        return vals;
	    },
	
	    __getCurrentValue: function(prop) {
	        prop = this[prop];
	        if (!this.multiple)
	            return $.trim(prop.val());
		 
            return $.trim(prop.val().split(this.config.separator).pop());		 
	    },
	
	    //icon click event listener
	    iconClick: function() {
	        if (this.listVisible()) { 
	            this.hideList();
			    this.input.blur();
		    }
	        else {			
	            this.showList();
			    this.input.focus();
	            if (this.input.val().length) {
		            this.selection(this.input.get(0), 0, this.input.val().length);    	
		        }			
		    }          
	    },
	
	    //returns true when dropdown list is visible
	    listVisible: function() {
	        return this.listWrapper.hasClass("visible");
	    },
	
	    //shows dropdown list
	    showList: function() {
	        if (!this.listItems.filter(".visible").length)
	            return;

	        this.listWrapper.removeClass("invisible").
	        addClass("visible");
	        this.wrapper.css("zIndex", "99999");
	        this.listWrapper.css("zIndex", "99999");
	        this.setListHeight();
		
		    var listHeight = this.listWrapper.height();
		    var inputHeight = this.wrapper.height();
		
		    var bottomPos = parseInt(this.wrapper.data("sc:positionY")) + inputHeight + listHeight;
		    var maxShown = $(window).height() + $(document).scrollTop();
		    if (bottomPos > maxShown) {
		        this.setDropUp(true); 
		    }
		    else {
		        this.setDropUp(false);	
		    }
		
	        this.highlightFirst();
	        this.listWrapper.scrollTop(0);
	        this.notify("showList");
	    },
	
	    //hides dropdown list
	    hideList: function() {
	        if (this.listWrapper.hasClass("invisible"))
	            return;
	        this.listWrapper.removeClass("visible").
	        addClass("invisible");
	        this.wrapper.css("zIndex", "0");
	        this.listWrapper.css("zIndex", "99999");	
	    
	        this.notify("hideList");
	    },
	
	    //returns sum of all visible items height
	    getListItemsHeight: function() {
	        /*var itemHeight = 20;
	        if ($.browser.msie) {
		        itemHeight = 18;   
	        }*/
			var itemHeight = this.singleItemHeight;
	        return itemHeight * this.liLen();
	    },
	
	    //changes list wrapper's overflow from hidden to scroll and vice versa (depending on list items height))
	    setOverflow: function() {
		    var maxHeight = this.getListMaxHeight();
		    
	        if (this.getListItemsHeight() > maxHeight)
	            this.listWrapper.css(this.overflowCSS, "scroll");
	        else
	            this.listWrapper.css(this.overflowCSS, "hidden");	
	    },
	
	    //highlights active item of the dropdown list
	    highlight: function(activeItem) {
	        if (($sc.KEY.DOWN == this.lastKey) || ($sc.KEY.UP == this.lastKey))
	            return;
		
            //TODO:integrate this fix!!!
            this.listItems.removeClass("active");

            if ($(activeItem).attr("tagName")=="SPAN"){
                $(activeItem).parent().addClass("active");

            }else{
                $(activeItem).addClass("active");
            }

	        

	    },
	

	
	    //sets text and hidden inputs value
	    setComboValue: function(val, pop, hideList) {
	        var oldVal = this.input.val();
	    
	        var v = "";
	        if (this.multiple) {
	            v = this.getTextValue();
		        if (pop) 
		            v.pop();
		        v.push($.trim(val));
		        v = $sc.normalizeArray(v);
		        v = v.join(this.config.separator) + this.config.separator;   
		 
	        } else {
	            v = $.trim(val);
	        }
	        this.input.val(v);
	        this.setHiddenValue(val);
	        this.filter();
	        if (hideList)
	            this.hideList();
	        this.input.removeClass("empty");

	    
	        if (this.multiple)
	            this.input.focus();
		
	        if (this.input.val() != oldVal)
	            this.notify("textChange");	
				
	    },
	
	
	
	    //sets hidden inputs value
	    //takes text input's value as a param
	    setHiddenValue: function(val) {
	        var set = false;
	        val = $.trim(val);
	        var oldVal = this.hidden.val();
	    	    
	        if (!this.multiple) {
	            for (var i = 0, len = this.options.length; i < len; ++i){
		            if (val == this.options.eq(i).text()) {
		                this.hidden.val(this.options.eq(i).val());
			            set = true;
			            break;
		            }
		        }
	         }
	        else {
	            var comboVals = this.getTextValue();
		        var hiddenVals = [];
		        for (var i = 0, len = comboVals.length; i < len; ++i) {
		            for (var j = 0, len1 = this.options.length; j < len1; ++j) {
		                if (comboVals[i] == this.options.eq(j).text()) {
			                hiddenVals.push(this.options.eq(j).val());
			            }      
		            }
		        }
		
		        if (hiddenVals.length) {
		            set = true;
		        this.hidden.val(hiddenVals.join(this.config.separator));
		    }
	     }
	    
	    if (!set) {
	        this.hidden.val(this.config.initialHiddenValue);
	    }
	    
	    if (oldVal != this.hidden.val())
	        this.notify("change");
		
	    this.selectbox.val(this.hidden.val());


        var initDoneDoesntExist=false;
        try{
            if(initDone && initAjaxDone){        
                initDoneDoesntExist=false;
            }
        }catch(e){
            initDoneDoesntExist=true;
        }
        
        if(initDoneDoesntExist || (initDone && initAjaxDone)){
            this.selectbox.trigger("change");            
        }

	},
	
	
	    listItemClick: function(item) {
	        this.setComboValue(item.text(), true, true);
	        this.inputFocus();
	    },
	
	    //adds / removes items to / from the dropdown list depending on combo's current value
	    filter: function() {
		    if ("yes" == this.wrapper.data("sc:optionsChanged")) {
		        var self = this;
		        this.listItems.remove();
                this.options = this.selectbox.children().filter("option");
	            this.options.each(function() {
	                var optionText = $.trim($(this).text());
	                $("<li />").
	                appendTo(self.list).
	                text(optionText).
	                addClass("visible");
	    
	            }); 
	
	            this.listItems = this.list.children();
	
	            this.listItems.bind("mouseover", function(e) {
	                self.highlight(e.target);
	            });
	    
	            this.listItems.bind("click", function(e) {
	                self.listItemClick($(e.target));
	            });
			
			    self.wrapper.data("sc:optionsChanged", "");
		    }
			
	        var comboValue = this.input.val();
	        var self = this;

	        this.listItems.each(function() {
	            var $this = $(this);
	            var itemValue = $this.text();
		        if (self.filterFn.call(self, self.getCurrentTextValue(), itemValue, self.getTextValue())) {
		           $this.removeClass("invisible").
		           addClass("visible");
		        } else {
		            $this.removeClass("visible").
		            addClass("invisible");
		        }
	        });
	     
	        this.setOverflow();
	        this.setListHeight();
	    },
	
	//default dropdown list filtering function
	filterFn: function(currentComboValue, itemValue, allComboValues) {
		if ("click" == this.wrapper.data("sc:lastEvent")) {
		    return true;	
		}
		//alert(currentComboValue.toSource());
	    if (!this.multiple) {
	        return itemValue.toLowerCase().indexOf(currentComboValue.toLowerCase()) == 0;
	    }
	    else {
	        //exclude values that are already selected

		for (var i = 0, len = allComboValues.length; i < len; ++i) {
		    if (itemValue == allComboValues[i]) {
		        return false;
		    }
		}
		
		return itemValue.toLowerCase().search(currentComboValue.toLowerCase()) == 0;
	    }
	},
	
	//just returns integer value of list wrapper's max-height property
	getListMaxHeight: function() {
			
		var result = parseInt(this.listWrapper.css("maxHeight"), 10);
		if (isNaN(result)) {
		    result = 200;	
		}
		
		return result;
	},
	
	//corrects list wrapper's height depending on list items height
	setListHeight: function() {
	
	    var liHeight = this.getListItemsHeight();
		
	    var maxHeight = this.getListMaxHeight();
        
        /*Check if bug exists on safari 4*/
        var safariFix=isSafari()?0:0;
	    
        var listHeight = this.listWrapper.height();
	    if (liHeight < listHeight) {
	        this.listWrapper.height(liHeight+safariFix); 
			
			return liHeight+safariFix;
	    }
	    else if (liHeight > listHeight) {
			
	        this.listWrapper.height(Math.min(maxHeight, liHeight)+safariFix);
			
			return Math.min(maxHeight, liHeight)+safariFix;
	    }
				
	},
	
	//returns active (hovered) element of the dropdown list
	getActive: function() {
	    return this.listItems.filter(".active");
	},
	
	keyUp: function(e) {
	    this.lastKey = e.keyCode;
	    var k = $sc.KEY;
	    switch (e.keyCode) {
	        case k.RETURN:
			case k.TAB:
			//this.input.focus();
		    this.setComboValue(this.getActive().text(), true, true);
		    if (!this.multiple)
		        this.input.blur();
		    	
		break;
		case k.DOWN:
		    this.highlightNext();
		break;
		case k.UP:
		    this.highlightPrev();
		break;
		case k.ESC:
		    this.hideList();
		break;
		default:
		    this.inputChanged();
		break;
	    }
	    
	    
	},
	
	//returns number of currently visible list items
	liLen: function() {
	    return this.listItems.filter(".visible").length;
	},
	
	//triggered when the user changes combo value by typing
	inputChanged: function() {
	    this.filter();

	    if (this.liLen()) {
	        this.showList();
		this.setOverflow();
		this.setListHeight();
	    } else {
	        this.hideList();
	    }
	    
	    this.setHiddenValue(this.input.val());
	    this.notify("textChange");
	    
	},
	
	//highlights first item of the dropdown list
	highlightFirst: function() {
	    this.listItems.removeClass("active").filter(".visible:eq(0)").addClass("active");
	    this.autoFill();
	},
	
	//highlights item of the dropdown list next to the currently active item
	highlightNext: function() {
	    var $next = this.getActive().next();
	    
	    while ($next.hasClass("invisible") && $next.length) {
	        $next = $next.next();
	    }
	    
	    if ($next.length) {
	        this.listItems.removeClass("active");
		$next.addClass("active");
		this.scrollDown();
	    }
	},
	
	//scrolls list wrapper down when needed
	scrollDown: function() {
	    if ("scroll" != this.listWrapper.css(this.overflowCSS))
	        return;
		
            var beforeActive = this.getActiveIndex() + 1;
			/*if ($.browser.opera)
			    ++beforeActive;*/
	    
	    var minScroll = this.listItems.outerHeight() * beforeActive - this.listWrapper.height();
        
		if ($.browser.msie)
            minScroll += beforeActive;
	    
	    if (this.listWrapper.scrollTop() < minScroll)
	        this.listWrapper.scrollTop(minScroll);
	},
	
	
	//highlights list item before currently active item
	highlightPrev: function() {
	    var $prev = this.getActive().prev();
	    
	    while ($prev.length && $prev.hasClass("invisible"))
	        $prev = $prev.prev();
		
            if ($prev.length) {
	        this.getActive().removeClass("active");
		$prev.addClass("active");
		this.scrollUp();
	    }
	},
	
	//returns index of currently active list item
	getActiveIndex: function() {
	    return $.inArray(this.getActive().get(0), this.listItems.filter(".visible").get());
	},
	
	
	//scrolls list wrapper up when needed
	scrollUp: function() {
	    
	    if ("scroll" != this.listWrapper.css(this.overflowCSS))
	        return;
		
	    var maxScroll = this.getActiveIndex() * this.listItems.outerHeight();
	    
	    if (this.listWrapper.scrollTop() > maxScroll) {
	        this.listWrapper.scrollTop(maxScroll);
	    }     
	},
	
	//emptyText stuff
	applyEmptyText: function() {
	    if (!this.config.emptyText.length)
	        return;
		
	    var self = this;	
	    this.input.bind("focus", function() {
                self.inputFocus();
	    }).
	    bind("blur", function() {
                self.inputBlur();
	    });	
	    
	    if ("" == this.input.val()) {
	        this.input.addClass("empty").val(this.config.emptyText);
	    }
	},
	
	inputFocus: function() {
	    if (this.input.hasClass("empty")) {
		this.input.removeClass("empty").
		val("");
            }
	},
	
	inputBlur: function() {
	    if ("" == this.input.val()) {
		this.input.addClass("empty").
		val(this.config.emptyText);
	    }
	    
	},
	
	//triggerSelected stuff
	triggerSelected: function() {
	    if (!this.config.triggerSelected)
	        return;
		
	    var self = this;	
		var set = false;
	    this.options.each(function() {
	        if ($(this).attr("selected")) {
		    set = true;
		    self.setComboValue($(this).text(), false, true);    
		}
	    });	
		//alert(set.toSource());
		
	},
	
	//autofill stuff
	autoFill: function() {
	    if (!this.config.autoFill || ($sc.KEY.BACKSPACE == this.lastKey) || this.multiple)
	        return;
		    	
	    var curVal = this.input.val();
	    var newVal = this.getActive().text();
	    this.input.val(newVal);
	    this.selection(this.input.get(0), curVal.length, newVal.length);
	   
	    	
	},
	
	//provides selection for autofilling
	//borrowed from jCarousel
	selection: function(field, start, end) {
	    if( field.createTextRange ){
		var selRange = field.createTextRange();
		selRange.collapse(true);
		selRange.moveStart("character", start);
		selRange.moveEnd("character", end);
		selRange.select();
	    } else if( field.setSelectionRange ){
		field.setSelectionRange(start, end);
	    } else {
		if( field.selectionStart ){
			field.selectionStart = start;
			field.selectionEnd = end;
		}
	    }
	   // field.focus();	
	},
	
	
	//for internal use
	updateDrop: function() {
	    if (this.config.dropUp)
	        this.listWrapper.addClass("list-wrapper-up");
	    else 
	        this.listWrapper.removeClass("list-wrapper-up");		
	},
	
	//updates dropUp config option
	setDropUp: function(drop) {
        this.config.dropUp = drop;   
	    this.updateDrop(); 
	},
	
	notify: function(evt) {
	    if (!$.isFunction(this.config[evt + "Callback"]))
	        return;
		
	    this.config[evt + "Callback"].call(this);	
	}
    });
    
    $sc.extend({
        //key codes
	//from jCarousel
        KEY: {
	    UP: 38,
	    DOWN: 40,
	    DEL: 46,
	    TAB: 9,
	    RETURN: 13,
	    ESC: 27,
	    COMMA: 188,
	    PAGEUP: 33,
	    PAGEDOWN: 34,
	    BACKSPACE: 8	
	},
	
	//for debugging
	log: function(msg) {
	    var $log = $("#log");
	    $log.html($log.html() + msg + "<br />");
	},
	
    createSelectbox: function(config) {
	    var $selectbox = $("<select />").
	    appendTo(config.container).
	    attr({name: config.name, id: config.id, size: "1"});
	    
	    if (config.multiple)
	        $selectbox.attr("multiple", true);
	    
	    var data = config.data;
	    var selected = false;
	    
	    for (var i = 0, len = data.length; i < len; ++i) {
	        selected = data[i].selected || false;
	        $("<option />").appendTo($selectbox).
		attr("value", data[i].value).
		text(data[i].text).
		attr("selected", selected);
	    }
	    
	    return $selectbox.get(0);
	},
	
	create: function(config) {
            var defaults = {
	        //the name of the selectbox
	        name: "",
		//the ID of the selectbox
		id: "",
		//data for the options
		/*
		This is an array of objects. The objects should contain the following properties:
		(string)value - the value of the <option>
		(string) text - text of the <option>
		(bool) selected - if set to true, "selected" attribute of this <option> will be set to true
		*/
		data: [],
		
		//if true, combo with multiple choice will be created
		multiple: false,
		
		//an element that will contain the widget
		container: $(document),
		//url that contains JSON object for options data
		//format is the same as in data config option
		//if passed, "data" config option will be ignored
		url: "",
		//params for AJAX request
		ajaxData: {}
	    };
	    config = $.extend({}, defaults, config || {});
	    
            if (config.url) {
	        return $.getJSON(config.url, config.ajaxData, function(data) {
		    delete config.url;
		    delete config.ajaxData;
		    config.data = data;
		    return $sc.create(config);
		});
	    }
	    
	    config.container = $(config.container);
	    
            var selectbox = $sc.createSelectbox(config);
	    return new $sc(selectbox, config);
	    
	},
	
	deactivate: function($select) {
	    $select = $($select);
		$select.each(function() {
		    if ("SELECT" != this.tagName.toUpperCase()) {
			    return;	
			}
			var $this = $(this);
			if (!$this.parent().is(".combo")) {
			    return;	
			}
			//$this.parent().find("input[type='text']").attr("disabled", true);
			
		});
	},
	
	activate: function($select) {
	    $select = $($select);
		$select.each(function() {
		    if ("SELECT" != this.tagName.toUpperCase()) {
			    return;	
			}
			var $this = $(this);
			if (!$this.parent().is(".combo")) {
			    return;	
			}
			$this.parent().find("input[type='text']").attr("disabled", false);
		});		
	},
	
	changeOptions: function($select) {
		$select = $($select);
        $select.each(function() {
		    if ("SELECT" != this.tagName.toUpperCase()) {
			    return;	
			}
			
			var $this = $(this);
			var $wrapper  = $this.parent();
			var $input = $wrapper.find("input[type='text']");
			var $listWrapper = $wrapper.find("ul").parent();
			
	        $listWrapper.removeClass("visible").
	        addClass("invisible");
	        $wrapper.css("zIndex", "0");
	        $listWrapper.css("zIndex", "99999");			
			
			$input.val("");
			$wrapper.data("sc:optionsChanged", "yes");
			var $selectbox = $this;
		    $selectbox.parent().find("input[type='text']").val($selectbox.find("option:eq(0)").text());
		    $selectbox.parent().data("sc:lastEvent", "click");
		    $selectbox.find("option:eq(0)").attr('selected','selected');
		});
	},
	
	normalizeArray: function(arr) {
	    var result = [];
	    for (var i = 0, len =arr.length; i < len; ++i) {
	        if ("" == arr[i])
		    continue;
		    
		result.push(arr[i]);    
	    }
	    
	    return result;
	}
    });
})(jQuery);

var zebraRows = function(selector, className) {
	jQuery(selector).removeClass(className).addClass(className);
}