// Pixl8 drop-down module

// Settings
// Element which the event is attached to.  If you change it, make sure the sDDBaseIdTrigger[x] ID is attached to the new element.
var sDDElementTrigger		= "a";
var sDDElementDropDownSecondary	= "a";
var sDDElementDropDownThird	= "a";

var sDDCookieState			= "DDState";
// Id of a layer where the module is attached.  We currently support only one layer.
var sDDIdLayer					= "aima-dd";
// Base part of the Id of the element showing/hiding the drop down
var sDDBaseIdTrigger			= "aima-switch-";
// Base part of the Id of the element that is being shown or hidden
var sDDBaseIdDropDown	= "aima-body-";
// Class name - collapsed
var sDDClassCollapse			= "aima-collapse";
var sDDClassCollapseA		= "aima-ico-triangle-collapsed";
var sDDClassCollapsePlus	= "aima-ico-plus";
// Class name - expanded
var sDDClassExpand			= "aima-expand";
var sDDClassExpandA		= "aima-ico-triangle-expanded";
var sDDClassExpandPlus	= "aima-ico-minus";
var sDDClassHidden			= "aima-hidden";

var bCPDUpdated	= false;


window.onbeforeunload = function() {
	if (bCPDUpdated) {
		return "You have attempted to leave this page.  If you have made any changes to the fields without clicking any of the Save buttons, your changes will be lost.  Are you sure you want to exit this page?";
	}
}

window.onload	= function() {
	// Routine DOM support check
	if (! document.getElementById) {
		return false;
	}
	


	var i	= 0;
	var k	= 0;
	var g = 0;
	var bDDIsFirstRequest	= false;
	// Ideally a "A" element that can be accessed both with a mouse or keyboard.  DD stands for "drop-down".
	var oDDTrigger		= "";
	var oDDTriggerSecondary	= "";
	var oDDDropDown	= "";
	// Layer containing the drop down script
	var oDDLayer			= document.getElementById(sDDIdLayer);
	if(!oDDLayer){
		return false;
	}
	// Trigger elements, ideally "A" attributes
	var aDDTrigger		= oDDLayer.getElementsByTagName(sDDElementTrigger);
	// Secondary drop-down elements
	var aDDTBody		= "";
	var oCPDHTMLCollectionSelect	= "";
	var oCPDHTMLCollectionSubmit	= "";
	// Check if this is IE or other browser
	IsIE		= getIsIE();
	// Rel=external replaced with target=blank
	setExternalLinks();

	// This is a structure where the information about expanded/collapsed nodes is to be stored
	if (! cpdIsCookieDDDefined() ) {
		cpdResetCookieDDState();
		bDDIsFirstRequest	= true;
	}

	//IIACPD-21 Attach an onchange event to all select boxes so we can prevent from leaving the page without saving details
	oCPDHTMLCollectionSelect	= document.getElementsByTagName("select");
	for (i = 0; i < oCPDHTMLCollectionSelect.length; i++) {
		if (! IsIE) {
			oCPDHTMLCollectionSelect[i].addEventListener("change", cpdRegisterChange, false);
		} else {
			// Internet Explorer
			if (! oCPDHTMLCollectionSelect[i].attachEvent("onchange", cpdRegisterChange) ) {
				alert('An error occured during the interactive table initialisation.  Please try accessing this page with a different, standards-compliant browser.');
			}
		}
	}
	i	= 0;

	//IIACPD-21 Remove the leave-the-page lock when the save button is clicked
	oCPDHTMLCollectionSubmit	= document.getElementsByTagName("input");
	for (i = 0; i < oCPDHTMLCollectionSubmit.length; i++) {
		if (oCPDHTMLCollectionSubmit[i].type == "submit") {
			if (! IsIE) {
				oCPDHTMLCollectionSubmit[i].addEventListener("click", cpdUnRegisterChange, false);
			} else {
				// Internet Explorer
				if (! oCPDHTMLCollectionSubmit[i].attachEvent("onclick", cpdUnRegisterChange) ) {
					alert('An error occured during the interactive table initialisation.  Please try accessing this page with a different, standards-compliant browser.');
				}
			}
		}
	}
	i	= 0;

	// Main layers
	for (i = 1; i <= aDDTrigger.length; i++) {
		oDDTrigger		= document.getElementById(sDDBaseIdTrigger + i);
		oDDDropDown	= document.getElementById(sDDBaseIdDropDown + i);
		// Add expand/collapse event
		if (oDDTrigger) {
			if (! IsIE) {
				oDDTrigger.addEventListener("click", cpdToggleCompetencyGroup, false);
			} else {
				// Internet Explorer
				if (! oDDTrigger.attachEvent("onclick", cpdToggleCompetencyGroup) ) {
					alert('An error occured during the interactive table initialisation.  Please try accessing this page with a different, standards-compliant browser.');
				}
			}
		}
		// We might store the IDs in a cookie variable so only certain modules expand on page refresh
		if (oDDDropDown) {
			// Collapse all main modules on startup (except the first one)
			if ( (bDDIsFirstRequest && i > 1)  ||  (! bDDIsFirstRequest && ! cpdCookieIsDDExpanded(sDDBaseIdTrigger + i) ) ) {
				oDDDropDown.className	= sDDClassCollapse;
				oDDTrigger.className		= sDDClassCollapseA;
			}
			else{
				oDDDropDown.className	= sDDClassExpand;
				oDDTrigger.className		= sDDClassExpandA;
			}
			
			// Sub layers
			aDDTBody		= oDDDropDown.getElementsByTagName(sDDElementDropDownSecondary);
			// Collapse all competencies except for the first one
			for (k = 0; k < aDDTBody.length; k++) {
				g	= k + 1;
				oDDTriggerSecondary	= document.getElementById(sDDBaseIdTrigger + i + "-" + g);
				if(oDDTriggerSecondary){
					if ( (bDDIsFirstRequest && i > 0)  ||  (! bDDIsFirstRequest && ! cpdCookieIsDDExpanded(sDDBaseIdTrigger + i + "-" + g) ) ) {
						//if (k < aDDTBody.length) {
							//aDDTBody[k].className		= sDDClassHidden;
						//}
						// Work out the state of plus-minus icons
						//if (k > 0) {
							oDDTriggerSecondary.className	= sDDClassCollapsePlus;
						//}
					}
					
						//ADDON: toggle the 2nd level as well
							oDDSecondaryBody = document.getElementById(sDDBaseIdDropDown+i+'-'+g);
					
							if(oDDSecondaryBody && !cpdCookieIsDDExpanded(oDDTriggerSecondary.id)){
								
								oDDSecondaryBody.className		= sDDClassHidden;
							}
							else if (cpdCookieIsDDExpanded(oDDTriggerSecondary.id)){
								oDDTriggerSecondary.className = sDDClassExpandPlus;
							}
							
							//ADDON: 3rd level
							if(oDDSecondaryBody){
									aDDThird		= oDDSecondaryBody.getElementsByTagName('a');
									
									// Collapse all competencies except for the first one
									for (l = 0; l < aDDThird.length; l++) {
										h	= l + 1;
										oDDTriggerThird	= document.getElementById(sDDBaseIdTrigger + i + "-" + g+"-"+h);
										if(oDDTriggerThird){
											if ( (bDDIsFirstRequest && i > 0)  ||  (! bDDIsFirstRequest && ! cpdCookieIsDDExpanded(sDDBaseIdTrigger + i + "-" + g+"-"+h) ) ) {
												//if (k < aDDTBody.length) {
													//aDDThird[l].className		= sDDClassHidden;
												//}
												// Work out the state of plus-minus icons
												//if (k > 0) {
													oDDTriggerThird.className	= sDDClassCollapsePlus;
												//}
											}
											else{
												oDDTriggerThird.className	= sDDClassExpandPlus;
											}
											//3rd level collapse too											
											oDDThirdBody = document.getElementById(sDDBaseIdDropDown+i+'-'+g+'-'+h);
											
											if(oDDThirdBody && !cpdCookieIsDDExpanded(oDDTriggerThird.id)){
													
												oDDThirdBody.className		= sDDClassHidden;
												
											}
											else if (cpdCookieIsDDExpanded(oDDTriggerSecondary.id)){
												oDDThirdBody.className = sDDClassExpandPlus;
											}
											
												//4th level - just add trigger
												aDDFourth		= oDDThirdBody.getElementsByTagName('a');
												for (m = 0; m < aDDThird.length; m++) {
													f	= m + 1;
													
													oDDTriggerFourth	= document.getElementById(sDDBaseIdTrigger + i + "-" + g+"-"+h+"-"+f);
													if(oDDTriggerFourth){
													
													
														if (! IsIE) {
															oDDTriggerFourth.addEventListener("click", cpdToggleCompetency, false);
														} else {
															// Internet Explorer
															if (! oDDTriggerFourth.attachEvent("onclick", cpdToggleCompetency) ) {
																alert('An error occured during the interactive table initialisation.  Please try accessing this page with a different, standards-compliant browser.');
															}
														}
														
														//4th level collapse too											
														oDDFourthBody = document.getElementById(sDDBaseIdDropDown+i+'-'+g+'-'+h+'-'+f);
														
														if(oDDFourthBody && !cpdCookieIsDDExpanded(oDDTriggerFourth.id)){
																
															oDDFourthBody.className		= sDDClassHidden;
															oDDTriggerFourth.className = sDDClassCollapsePlus;
														}
														else if (cpdCookieIsDDExpanded(oDDTriggerFourth.id)){
															oDDTriggerFourth.className = sDDClassExpandPlus;
														}
														
													}
													

													
												}
											
											// third level drop-down event
											if (! IsIE) {
												oDDTriggerThird.addEventListener("click", cpdToggleCompetency, false);
											} else {
												// Internet Explorer
												if (! oDDTriggerThird.attachEvent("onclick", cpdToggleCompetency) ) {
													alert('An error occured during the interactive table initialisation.  Please try accessing this page with a different, standards-compliant browser.');
												}
												else{
													//alert('trigger added to : '+oDDTriggerThird.id)
												}
												
	
											}	
										
										}
									}
								}
					
					
					// Secondary drop-down event
					if (! IsIE) {
						oDDTriggerSecondary.addEventListener("click", cpdToggleCompetency, false);
					} else {
						// Internet Explorer
						if (! oDDTriggerSecondary.attachEvent("onclick", cpdToggleCompetency) ) {
							alert('An error occured during the interactive table initialisation.  Please try accessing this page with a different, standards-compliant browser.');
						}

						
					}
				
				}
			}
		}
	}
	setTimeout("if($('overlay-loading'))$('overlay-loading').style.display = 'none';",1200);
}


// Primary drop-down functionality
function cpdToggleCompetencyGroup() {
	// Element acting as a switch, A by default
	var oDDATrigger			= "";
	if (! IsIE) {
		oDDATrigger				= this;
		
	} else {
		oDDATrigger				= event.srcElement;
	}
	var aDDIdTrigger			= oDDATrigger.id.split("-");
	var iDDElementLast		= aDDIdTrigger.length - 1;
	var oDDDropDown			= document.getElementById(sDDBaseIdDropDown + aDDIdTrigger[iDDElementLast] );

	// Expand-collapse functionality based on CSS classes
	if (oDDDropDown) {
		if (oDDDropDown.className == sDDClassCollapse) {
			// Display the main table
			oDDDropDown.className	= sDDClassExpand;
			// Switch triangle
			oDDATrigger.className		= sDDClassExpandA;
			// Remember the currently expanded element
			cpdSetCookieDDState(1, oDDATrigger.id);
		} else {
			oDDDropDown.className	= sDDClassCollapse;
			oDDATrigger.className		= sDDClassCollapseA;
			cpdSetCookieDDState(0, oDDATrigger.id);
		}
		

	}
	
	return false;
}


// Secondary drop-down functionality
function cpdToggleCompetency() {
	var oDDDropDownSecondary	= "";
	// Element acting as a switch, A by default
	var oDDATrigger			= "";
	if (! IsIE) {
		oDDATrigger				= this;
	} else {
		oDDATrigger				= event.srcElement;
		//alert('triggered id: '+oDDATrigger.id + ' class name: '+ oDDATrigger.className);
	}

	// tbody tag
	oDDDropDownSecondary	= document.getElementById(oDDATrigger.id.replace(sDDBaseIdTrigger, sDDBaseIdDropDown) );
	
	//oDDDropDownSecondary	= oDDATrigger.parentNode.parentNode.parentNode.nextSibling.nextSibling;
	//if (oDDDropDownSecondary.nodeName == "TBODY") {
	if(oDDDropDownSecondary){
		
		if (oDDDropDownSecondary.className == sDDClassHidden) {
			// Display the main table
			oDDDropDownSecondary.className	= "";
			
			// Switch triangle
			oDDATrigger.className		= sDDClassExpandPlus;
			
			// Remember the currently expanded element
			cpdSetCookieDDState(1, oDDATrigger.id);
		} else {
			oDDDropDownSecondary.className	= sDDClassHidden;
			oDDATrigger.className		= sDDClassCollapsePlus;
			
			cpdSetCookieDDState(0, oDDATrigger.id);
		}	
	}	
	/*} else {
		alert(oDDDropDownSecondary.nodeName);
	}*/
	//console.log(oDDDropDownSecondary);
	
	return false;
}


// Save before exit functionality
function cpdRegisterChange() {
	bCPDUpdated	= true;
}


function cpdUnRegisterChange() {
	bCPDUpdated	= false;
}


/**
 * Adds an entry to a cookie variable indicating an element was expanded (iDDState = 1) or deletes it if collapsed (iDDState = 0)
 */
function cpdSetCookieDDState(iDDState, sDDIdSwitch) {
	if (document.cookie.length < 0) {
		//return -1;
	}

	var iStart	= document.cookie.indexOf(sDDCookieState + "=");
	var iEnd		= 0;
	var sValueCookie	= "";
	var sValueCookieNew	= "";
	var dExpiryCookie	= new Date();
	
	dExpiryCookie.setDate(dExpiryCookie.getDate() + 7);

	if (iStart == -1) {
		// Scenario 1: Expand node when the cookie doesn't yet exist
		if (iDDState == 1) {			
			document.cookie	= sDDCookieState + "=|" + escape(sDDIdSwitch) + "|;expires=" + dExpiryCookie.toGMTString();
		}
		return;
	}

	iStart	= iStart + sDDCookieState.length + 1;
	iEnd	= document.cookie.indexOf(";", iStart);
	if (iEnd == -1) {
		iEnd	= document.cookie.length;
	}
	sValueCookie	= document.cookie.substring(iStart, iEnd);

	// Scenario 2: Collapse node
	if (iDDState == 0) {
		// Delete the expanded-node entry only if the cookie variable exists (if it doesn't there is no point doing anything)
		sValueCookieNew	= sValueCookie.replace("|" + sDDIdSwitch + "|", "|");
	} else {
		if (iDDState == 1) {
			sValueCookieNew	= sValueCookie + sDDIdSwitch + "|";
		}
	}
	document.cookie	= sDDCookieState + "=" + sValueCookieNew + ";expires=" + dExpiryCookie.toGMTString();
}


function cpdCookieIsDDExpanded(sDDIdSwitch) {
	if (document.cookie.length < 0) {
		return -1;
	}

	var iStart		= document.cookie.indexOf(sDDCookieState + "=");
	var iEnd			= 0;
	var sValueCookie	= "";
	var iPosition	= 0;

	if (iStart == -1) {
		return -1;
	}

	iStart	= iStart + sDDCookieState.length + 1;
	iEnd	= document.cookie.indexOf(";", iStart);
	if (iEnd == -1) {
		iEnd	= document.cookie.length;
	}
	sValueCookie	= document.cookie.substring(iStart, iEnd);
	
	iPosition			= sValueCookie.indexOf(sDDIdSwitch + "|");

	// Check if sDDIdSwitch exists and return true or false on this basis
	if (iPosition != -1) {
		// The element is expanded
		return true;
	} else {
		// The element is collapsed
		return false;
	}
}


function cpdResetCookieDDState() {
	var dExpiryCookie	= new Date();
	
	dExpiryCookie.setDate(dExpiryCookie.getDate() + 7);

	document.cookie	= sDDCookieState + "=|;expires=" + dExpiryCookie.toGMTString();
}


function cpdIsCookieDDDefined() {
	var iStart	= document.cookie.indexOf(sDDCookieState + "=");
	var dExpiryCookie	= new Date();
	
	dExpiryCookie.setDate(dExpiryCookie.getDate() + 7);

	if (iStart != -1) {
		return true;
	} else {
		return false;
	}
}


function cpdConfirmPDPRemove(oLink, sIdCompetency) {
	if (! confirm("Do you want to archive this task before removal?") ) {
		if (! confirm("Are you sure you want to remove this task from your PDP?") ) {
			// Resign
			return false;
		} else {
			// Remove
			window.open(oLink.href, "pdp_remove_competency");
			return false;
		}
	} else {
		// Archive competency in PDP
		oLink.href += "&cpd_pdp_archive=1";
		window.open(oLink.href, "pdp_archive_competency");
		return false;
	}
}


function getIsIE() {
	if (document.addEventListener) {
		// Gecko
		return false;
	} else {
		// IE
		return true;
	}
}


function setExternalLinks() {
	if (! document.getElementsByTagName) {
		return;
	}

	var anchors = document.getElementsByTagName("a");

	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];

	 	if (anchor.getAttribute("href") && 	anchor.getAttribute("rel") == "external") {
			anchor.target = "_blank";
		}
	}
}