// A global collection of all tabbed master page elements.
tabbedPageElements={};


/**
 * Constructor for instances of a tabbed element
 * @param instanceId
 * @returns
 */
function TabbedPageElement(instanceId, siteId, tabbingType, slideShowDelay, hasAjaxableElement, uiContainerInfo, onLoadActionType){
	this.instanceId = instanceId;
	this.siteId = siteId;
	this.tabbingType = tabbingType;
	this.tabs= new Array();
	this.subPageElements = new Array()
	this.disableSlideShow = false;
	this.slideShowDelay = slideShowDelay;
	this.hasAjaxableElement = hasAjaxableElement;
	this.uiContainerInfo = uiContainerInfo;
	this.onLoadActionType = onLoadActionType;
}

/**
Format
	aj   pet  pei  cah  ret
	 0  | 1  | 2  | 3  | 4
	true|226 |3363|true|true
**/
function makeAjaxKey(ajaxable, pageElementTypeId, pageElementInstanceId, cachePlugin, retrieved) {
	return ajaxable +'|'+ pageElementTypeId + '|' + pageElementInstanceId + '|' + cachePlugin + '|' + retrieved;
}

/**
// Get query string parameter of the specified name.
**/
function getIntQueryStringParam(name) {
	var valueToReturn = -1;
	if (name != null && name.length > 0) {
		var strWindowLocation = "" + window.location;
		var indexOfQuestionMark = strWindowLocation.indexOf("?");
		var queryStringValues = null;
		if (indexOfQuestionMark != -1) {
			strWindowLocation = strWindowLocation
					.substring(indexOfQuestionMark + 1);
			queryStringValues = strWindowLocation.split("&");

			// look for value
			for ( var a = 0; a < queryStringValues.length; a++) {
				if (queryStringValues[a].indexOf(name + "=") != -1) {
					valueToReturn = queryStringValues[a]
							.substring(queryStringValues[a].indexOf("=") + 1);
					break;
				}
			}
		}
	}
	return valueToReturn;
}

/**
//
// This function will look for a querystring parameter matching the tabbed element instance id, open the tab 
// that is passed on this parameter and return whether the tab was successfully switched.
//
**/
function switchToTabByQueryStringParam(instanceId){
	//
	//Look for tab<instanceId> in the querystring.
	//
	var tabOption = getIntQueryStringParam("tab"+instanceId);

				
	//Tab index start from 1 (hence the tabOption-1).
	if ((!isNaN(tabOption)) && tabOption > 0){
    	//Call switch function.
		// Why the setTimeout?
    	setTimeout('switchTab('+ instanceId + ',' (tabOption-1) + ')', 0);
	}
}

/**
//****************************************************************************
//
// Function:   switchTab
//
// Purpose:    Toggles between the different tabs.
//
// Parameters: tab - index of the selected tab.
//             disableSlideShow - Flag to tell whether to enable slide show.
//                                This will only be applicable when the tab
//                                element has been set up in slide show mode.
//             isTimeoutCall - flag that tells whether this is an automatic 
//                             call made using javascript timeout function.
//
// Returns:    Nothing
//
//****************************************************************************
**/          
function switchTab(instanceId, tab, disableSlideShow, isTimeoutCall) {
	  if(tabbedPageElements[instanceId].hasAjaxableElement){
	   	var pageElementDataSrc = tabbedPageElements[instanceId].subPageElements[tab];
				 	var pageElementData = pageElementDataSrc.split("|");
					
					var retrieved = pageElementData[4];
					var ajaxable = pageElementData[0];
					
					if (ajaxable == 'true' && retrieved == 'false') {
				
						var pageElementTypeId = pageElementData[1];
						var pageElementInstanceId = pageElementData[2];
						var cachePlugin = pageElementData[3]; 
						var masterTabContentId = tabbedPageElements[instanceId].uiContainerInfo.masterTabContentId;
						tabbedPageElements[instanceId].subPageElements[tab] = makeAjaxKey(instanceId, ajaxable, pageElementTypeId, pageElementInstanceId, cachePlugin, true);
						populateContent(instanceId, tabbedPageElements[instanceId].siteId, pageElementTypeId, pageElementInstanceId, 'ajaxPlaceholder'+ masterTabContentId + instanceId + '_' + tab, cachePlugin, tab);
					}
	  }
				
	if (disableSlideShow) {
		tabbedPageElements[instanceId].disableSlideShow = true;
	}

	// If disable slide show is disabled and this is one of the old automatic timeout calls, stop here...
	if (tabbedPageElements[instanceId].disableSlideShow && isTimeoutCall) {
		return;
	}	

	// Hide all the tab contents, set the style class of all the tabs to 
	// "not selected" and set tab images (if they exist) to off.

	for (var x = 0; x < tabbedPageElements[instanceId].tabs.length; x++) {
		var selector = '#' + tabbedPageElements[instanceId].uiContainerInfo.masterTabContentId + instanceId + '_' + x +'.inDisplayTab';
    if ($(selector).length > 0) {
    	if(!(tabbedPageElements[instanceId].uiContainerInfo.accordionEffect)){
    		document.getElementById(tabbedPageElements[instanceId].uiContainerInfo.masterTabContentId + instanceId + '_' + x).style.display = "none";
    	} else {
            $('#' + tabbedPageElements[instanceId].uiContainerInfo.masterTabContentId + instanceId + '_' + x + ':visible').each(function(){
            	if(tabbedPageElements[instanceId].uiContainerInfo.looseDocType){
            		$(this).slideUp(tabbedPageElements[instanceId].uiContainerInfo.slidingSpeed);
            	} else {
	            	$(this).hide();
            	}
            });
    	}
      
          /**
          //
          // Set the style class of all the tabs to "not selected" 
          // and set tab images to off only if the configuration
          // of the element is set to display the tabs.
          //
          **/
	      if(tabbedPageElements[instanceId].tabbingType != 2 && tabbedPageElements[instanceId].tabbingType != 4){			
            /**
            //
            // Setting tabs style class to not selected.
            //  
            **/
            document.getElementById(tabbedPageElements[instanceId].uiContainerInfo.masterTabListId + instanceId + '_' + x).className = tabbedPageElements[instanceId].uiContainerInfo.masterTabClass + x;
          
            /** 
            //
            // Setting tab images to off.
            //  
            **/
            if (document.images["masterTabImage" + instanceId + "_" + x]) {
            	document.images["masterTabImage" + instanceId + "_" + x].src = tabbedPageElements[instanceId].tabs[x][0];
            }
            document.getElementById(tabbedPageElements[instanceId].uiContainerInfo.masterTabListId + instanceId + '_' + tab).className = tabbedPageElements[instanceId].uiContainerInfo.masterTabSelectedClass + tab;
            
            // Set the selected tab's image (if it exists) to on (only if tabs showing).
            if (document.images["masterTabImage"+instanceId+"_" + tab]) {
              document.images["masterTabImage" + instanceId + "_" + tab].src = tabbedPageElements[instanceId].tabs[tab][1];
            }
    	  }

         /**
		 //
		 // Set the select list.
		 //
		 **/
	     if(tabbedPageElements[instanceId].tabbingType == 4){
			var selectList = document.getElementById('select'+tabbedPageElements[instanceId].uiContainerInfo.masterTabContainerId + instanceId);
			selectList.selectedIndex = tab;
	     } 
	}
  }
  
  /**
  // 
  // Display selected panel,
  // set the selected tab style class to "selected"
  // and set selected tab image (if it exists) to on.
  //
  // If the tab we are supposed to select does not exist (this can
  // happen when we remove some tabs depending on whether the user
  // is logged in or not), select the next one in a round robin
  // fashion.
  //
  **/
  if (!$('#' + tabbedPageElements[instanceId].uiContainerInfo.masterTabContentId + instanceId + '_' + tab +'.inDisplayTab').length > 0) {
    for (var x = 0; x < tabbedPageElements[instanceId].tabs.length; x++) {                
      tab = ((tab + 1) % tabbedPageElements[instanceId].tabs.length);
      if ($('#' + tabbedPageElements[instanceId].uiContainerInfo.masterTabContentId + instanceId + '_' + tab +'.inDisplayTab').length > 0) {
        break;                
      } 
    }
  }          
  if ($('#' + tabbedPageElements[instanceId].uiContainerInfo.masterTabContentId + instanceId + '_' + tab +'.inDisplayTab').length > 0) {

    /**
    //
    // Display the selected tab's content panel.
    //
    **/
	  
	if(!tabbedPageElements[instanceId].uiContainerInfo.accordionEffect){
		document.getElementById(tabbedPageElements[instanceId].uiContainerInfo.masterTabContentId + instanceId + '_' + tab).style.display = "block";
	} else {
        $('#' + tabbedPageElements[instanceId].uiContainerInfo.masterTabContentId + instanceId + '_' + tab).slideDown(tabbedPageElements[instanceId].uiContainerInfo.slidingSpeed);
  		 $('#' + tabbedPageElements[instanceId].uiContainerInfo.masterTabContentId + instanceId + '_' + tab).show();	// Not if the line above works	
	}
  }
  
  /**
  //
  // Save the selected tab to this element's cookie.
  //
  **/
  if(tabbedPageElements[instanceId].onLoadActionType == 0){
	  SetCookie("tabPreferences"+instanceId, tab, never);
  }
  
  /**
  // 
  // If slide show active, set timeout for recall of the function.
  // 
  **/
  
  if(tabbedPageElements[instanceId].onLoadActionType == 2 && !tabbedPageElements[instanceId].disableSlideShow){
      setTimeout("switchTab("+instanceId+"," + ((tab + 1) % tabbedPageElements[instanceId].tabs.length) + ",false,true)",               
    		  tabbedPageElements[instanceId].slideShowDelay * 1000);              
  }
  
            
  /**
  //
  // If a specific onDisplay method exists for this tab then call it
  //
  **/
  if(window['onTabSwitched' + instanceId + '_' + tab]) {
    window['onTabSwitched' + instanceId + '_' + tab].call();
  }
}

function selectPreviousTabByCookie(instanceId){
    if (window.GetCookie) {
        var cookieTab = GetCookie("tabPreferences" + instanceId);
        if (cookieTab != null) {
          switchTab(instanceId, cookieTab);    
        } else {
          switchTab(instanceId,0);
        }
      }
}


function getRandomTab(weightsArray) {
    var randomNumber = Math.floor(Math.random() * 1000);
    // Set the last tab as the selected one by default;
    var selectedRandomTab = (weightsArray.length -1);
    for(var x = 0; x < weightsArray.length; x++){
    	var weight = weightsArray[x];
    	if(randomNumber < weight){
    		selectedRandomTab = x;
    		break;
    	}
    }
    return selectedRandomTab;
}


/**
//
// Depending on whether the user is logged in or logged out, hide all
// the components that have been configured to show only when the user
// is either logged in or logged out.
//
**/
function toggleSessionBasedTabs(instanceId) {
  var isUserLoggedIn = IsLoggedIn();
  var tabs = tabbedPageElements[instanceId].tabs;
  var containerInfo = tabbedPageElements[instanceId].uiContainerInfo;
  for (var x = 0; x < tabs.length; x++) {
    if ((isUserLoggedIn && tabs[x][2] == 6) || (!isUserLoggedIn && tabs[x][2] == 5)) {
      $('#' + containerInfo.masterTabListId + instanceId + '_' + x).remove();
      $('#' + containerInfo.masterTabContentId + instanceId + '_' + x).addClass('removedTab').remove();               
    } else {
      $('#' + containerInfo.masterTabContentId + instanceId + '_' + x).addClass('inDisplayTab');
    }
  }
}

function populateContent(instanceId, siteId, pageElementTypeId, pageElementInstanceId, divIdToUpdate, cached, tab) {
	var pageElement_detailId =(window.GLOBAL_DETAIL_ID && window.GLOBAL_DETAIL_ID > 0?GLOBAL_DETAIL_ID:0);
	var pageElement_detailTypeId =(window.GLOBAL_DETAIL_TYPE_ID && window.GLOBAL_DETAIL_TYPE_ID > 0?GLOBAL_DETAIL_TYPE_ID:0);  
	var pageNumber = 1;
	var cachemarker = "";
	if(cached != 'true') {
		cachemarker="/uncached_y";  
	}

	var url = '/page/pageelementservlet' + cachemarker; 
		url += '/pageelementtypeid_' + pageElementTypeId;
		url += '/instanceid_'+pageElementInstanceId;
		// Need to move site id
		url += '/0,,'+ siteId + '~' + pageElement_detailId + '~' + pageElement_detailTypeId + '~' + (window.GLOBAL_PAGE_ID?GLOBAL_PAGE_ID:0) + '~' + pageNumber + ',00.html';        
		if(window['onTabSwitched' + instanceId + '_' + tab]) {
			getContent(url, divIdToUpdate, 30000, 'onTabSwitched' + instanceId + '_' + tab);
		} else {
			getContent(url, divIdToUpdate, 30000); 
		}
}


