// JavaScript Document - Copyright © 2009-2010 artefficient.com
var D = document;
var O_MAIN_UI;
var O_MAP_NAV;
var AO_NAV_BUT = new Array(); // array of top navigation buttons;
var O_GO_LEFT, O_GO_RIGHT;	// buttons used for left and tight scrolling;

var O_CONTENT;	//DIV that contains all Pods. It has horisontal scrolliing
var O_POD_HEAD_TR; // TR that contains all pod HEADERS
var O_POD_BODY_TR; // TR that contains all pod BODIES

var A_POD_HEAD = new Array(); // array of PODs Heads
var A_POD_HEAD_TITLES = new Array();
var A_POD_BODY = new Array(); // array of DIV objects that contain the actual POD content. Most likely IFRAME
var A_POD_LOCATION_SCROLL = new Array(); // array of Numbers - PODs left scroll position in order to have pod in the center

var n_I_PDL = -1; // stores value of the the pod partially displayed from the left. -1 means that content is in the most left position
var n_I_PDR; // stores value of the the pod partially displayed from the right

var B_SOFTSCROLL = true;
var SCROLL_STEP = 100;
var SCROLL_SPEED = 10 // scrolls every 100 milliseconds

var A_POD_LOCATION_LEFT = new Array(); // array of Numbers - PODs left position
var A_POD_WIDTH = new Array(); // array of Numbers - PODs widths


function initialize() {
// 1. initialize UI objects
	O_MAIN_UI = D.getElementById("MAIN_UI");
	O_MAP_NAV = D.getElementById("mapNavigation");
	O_CONTENT 	= D.getElementById("content");
	O_POD_HEAD_TR = D.getElementById("podHeadContainer");
	O_POD_BODY_TR = D.getElementById("podBodyContainer");
		
		
// 2. Assigning function related styles
	O_MAIN_UI.style.overflow="hidden";
	O_CONTENT.style.overflow="auto";
	O_CONTENT.style.height="500px";
	
// 3. Detect all Pod headers. They contain information about the Pod widths
	detectPodHeaders();
	
// 4. Detecting all Pod bodies (DIV). Note: there cold be more than one IFRAME's with in the same pod
	detectPodBodies();

// 5. Creating navigation map links
	createNavigationComponents();
	
// 6. Assign functionally important styles 
	assignStyles();
	
// 7. Changeing Height of CONTENT and PODS. Recalculate Pods widths. Then Validate position and display it one the MAP
	makeUIadjustments();
	
// 8. Adding listeners to catch shortcuts, and handle window interactions;
	D.onkeyup = keyUp;
	D.onkeydown = keyDown;  // NOTE: document.keypress does NOT work in IE
	onresize = makeUIadjustments;
	O_CONTENT.setAttribute("onscroll","validatePosition()");

}


/*
Detecting Pod Headers in the first TR. The Header will be used for scrolling calculations
*/
function detectPodHeaders() {
	A_POD_HEAD = O_POD_HEAD_TR.getElementsByTagName("td");
	A_POD_HEAD_TITLES = O_POD_HEAD_TR.getElementsByTagName("h1");
}


/*
Detecting Pod TD and DIV's. The DIV's will accessed for Height change on window's load or resize
*/
function detectPodBodies() {
//1 Finding all DIVs classname = "pod"
	for (i=0; i<O_POD_BODY_TR.childNodes.length; i++) {
		if(O_POD_BODY_TR.childNodes[i].className) {
			// Looking of pods that are TD with className containg "pod"
			if(O_POD_BODY_TR.childNodes[i].className.indexOf("pod")>=0) {
				// Find all PODS
				A_POD_BODY[A_POD_BODY.length] = O_POD_BODY_TR.childNodes[i].getElementsByTagName("div")[0];	
			}
			// Making sure that subpods (dynamicaly displayed pods) never have any padding. They have to STICK to the parent node 
			if(O_POD_BODY_TR.childNodes[i].className.indexOf("sub_pod")>=0) {
				O_POD_BODY_TR.childNodes[i].setAttribute("style","padding: 0px !important");				
			}
		}
	}
}


/*
Change Height of CONTENT and PODS. Recalculate Pods widths. Then Validate position and display it one the MAP
*/
function makeUIadjustments(){
	calculatePodWidths();
	adjustContentDimentions();
	validatePosition();
}

/*
Calculate pod widths and scroll positions
*/
function calculatePodWidths() {	
	var n_place_in_center = 0;
	var n_spacing_delta = 0;
	var n_right_offset;
	
	for (i=0; i<A_POD_HEAD.length; i++) {
		/*
		A_POD_HEAD[i].scrollWidth - pod width
		A_POD_HEAD[i].offsetLeft - pod location from the left
		O_CONTENT.offsetWidth - browser window width
		O_CONTENT.scrollWidth - Whole Content width (wider that browser window width)
		*/
		A_POD_WIDTH[i] = A_POD_HEAD[i].scrollWidth;
		A_POD_LOCATION_LEFT[i] = A_POD_HEAD[i].offsetLeft;
		
		// Calculating the space that should be from left and right of the pod - placing it in the middle
		// (Window width - Pod width) / 2
		n_spacing_delta = (O_CONTENT.offsetWidth-A_POD_HEAD[i].scrollWidth)/2; 
		n_place_in_center = Math.floor(A_POD_HEAD[i].offsetLeft - n_spacing_delta);
		
		// Case for first pod from the left. 
		if(n_place_in_center<0) {
			n_place_in_center=0;
		}
		// cases for the last pods from the right.
		else if((O_CONTENT.scrollWidth - A_POD_HEAD[i].offsetLeft)<(O_CONTENT.offsetWidth)) {
			n_place_in_center=O_CONTENT.scrollWidth-(O_CONTENT.offsetWidth);
		}
		
		A_POD_LOCATION_SCROLL[i] = n_place_in_center;
	}	
}

/* 
used for adjusting heignt of the content section and all DIV PODS;
*/
function adjustContentDimentions() {
	//getWindowWH()[1] retutns Height of the window
	O_CONTENT.style.height = (getWindowWH()[1] - O_CONTENT.offsetTop)+"px"; // getting the height of the content left after substructing the height of the header
	
	// changing the height of the DIV.pod's
	// O_CONTENT.clientHeight = O_CONTENT.offsetHeight - 17px. I assume that 17px is the height of the horizontal scroll bar
	for (i=0; i<A_POD_BODY.length; i++) {
		// making PODs 50 px shorter for bottom navigation
		A_POD_BODY[i].style.height = ((O_CONTENT.clientHeight-O_POD_HEAD_TR.clientHeight)-50)+"px"; 
	}
}

/*
Validate position and display it one the MAP
*/
function validatePosition() {
	var n_left = O_CONTENT.scrollLeft;
	var n_right = O_CONTENT.scrollLeft+O_CONTENT.offsetWidth;
	var n_podLeft;
	var n_podRight;
	var b_selected = false;
	
	for(i=0; i<A_POD_HEAD.length; i++) {
		AO_NAV_BUT[i].className = "";
		n_podLeft = A_POD_HEAD[i].offsetLeft;
		n_podRight = A_POD_HEAD[i].offsetLeft+A_POD_HEAD[i].scrollWidth; //A_POD_HEAD[i].scrollWidth is the width of the POD
		//check if the pod is completely out of window display	
		if(n_podLeft>=n_right || n_podRight<=n_left) {
			// The pod is fully out of display!;
		}
		else {
			// the pod is somehow displayed			
			//alert(i +" : " + getDisplayPercentFromLeft(i) + ' ' + getDisplayPercentFromRight(i))
			if(n_podLeft<n_left && n_podRight>n_left) {
				n_I_PDL = i;
				AO_NAV_BUT[i].className = "selected" + getDisplayPercentFromLeft(i) +" left";
			}
			else if(n_podLeft<n_right && n_podRight>n_right)  {
				n_I_PDR = i;
				AO_NAV_BUT[i].className = "selected" + getDisplayPercentFromRight(i) +" right";
			}
			else {
				AO_NAV_BUT[i].className = "selected";
				b_selected = true;
			}
		}	
	}
	// there are not pods fuuly displayed
	if(!b_selected) {
		//alert(n_I_PDL +" "+n_I_PDR)
		/*there are two scenarious: 
			1. there are a PAIR of  partionally displayed pod. From left and right
			2. there a SINGLE partionally displayed pod (always treated as "from left"). The pod is wider that browser window There are no pod marked from right
			
		*/
		n_I_PDR = n_I_PDL+1;
		n_I_PDL = n_I_PDL-1;
	}
}

/*
A - A_POD_HEAD[i].offsetLeft - pod location from the left
B - A_POD_HEAD[i].scrollWidth - pod width
C - O_CONTENT.scrollLeft - content scroll from left;
D - O_CONTENT.offsetWidth - browser window width
*/

function getDisplayPercentFromLeft(n_podInd) {
	// n_t = ((A + B) - C)/B gives 0.234
	var n_t = ((A_POD_HEAD[n_podInd].offsetLeft + A_POD_HEAD[n_podInd].scrollWidth) - O_CONTENT.scrollLeft)/A_POD_HEAD[n_podInd].scrollWidth;
	// Following conversion in order to get 10%, 20%...: 0.234 -> 2.34 -> 3 -> 30
	return(Math.ceil(n_t*10)*10)
}
function getDisplayPercentFromRight(n_podInd) {
	// n_t = ((C+D)-A)/B gives 0.234
	var n_t = ((O_CONTENT.scrollLeft+O_CONTENT.offsetWidth)-A_POD_HEAD[n_podInd].offsetLeft)/A_POD_HEAD[n_podInd].scrollWidth;
	// Following conversion in order to get 10%, 20%...: 0.234 -> 2.34 -> 3 -> 30
	return(Math.ceil(n_t*10)*10)
}

/*
function reads number of Pod heads and create equivalent number of Navigation lin ks
*/
function createNavigationComponents() {
	
//Final HTML: <a href="javascript://" onclick="scrollToPosition(this)" podindex="0" title="Shortcut: 'Ctrl' + 'Shift' + '1'"><span>1</span></a>
//1.a. create A tag		
	var aTag = D.createElement("a");
		aTag.href = "javascript://";
		aTag.setAttribute("onclick","scrollToPosition(this)");
		var atr_podindex = D.createAttribute("podindex");
		aTag.setAttributeNode(atr_podindex);
	
//1.b create SPAN tag
	var spanTag = D.createElement("span");
	
//2 Create navigation links by cloning the template objects
	for(i=0; i<A_POD_HEAD.length; i++) {
			AO_NAV_BUT[i] = aTag.cloneNode(true);
			AO_NAV_BUT[i].setAttribute("podindex",i);
			var o_ts = spanTag.cloneNode(true);
			o_ts.innerHTML = "" +A_POD_HEAD_TITLES[i*3].innerHTML+ "";
			O_MAP_NAV.appendChild(AO_NAV_BUT[i]);	
			AO_NAV_BUT[i].appendChild(o_ts);	
	}
	
//3 create "Left" navigation button
	var navDivTagL = D.createElement("div");
		navDivTagL.id = "leftNavigation";
		O_GO_LEFT = D.createElement("a");
		O_GO_LEFT.href = "javascript://";
		O_GO_LEFT.setAttribute("onclick","scrollToLeft()");
	var navSpanTagL = D.createElement("span");
		navSpanTagL.innerHTML = "&laquo;";
		
		O_GO_LEFT.appendChild(navSpanTagL);
		navDivTagL.appendChild(O_GO_LEFT);
		O_MAIN_UI.appendChild(navDivTagL);
		

//4 create "Right" navigation button	
	var navDivTagR = D.createElement("div");
		navDivTagR.id = "rightNavigation";
		O_GO_RIGHT = D.createElement("a");
		O_GO_RIGHT.href = "javascript://";
		O_GO_RIGHT.setAttribute("onclick","scrollToRight()");
	
	var navSpanTagR = D.createElement("span");
		navSpanTagR.innerHTML = "&raquo;";	
		O_GO_RIGHT.appendChild(navSpanTagR);
		navDivTagR.appendChild(O_GO_RIGHT);
		O_MAIN_UI.appendChild(navDivTagR);
		
}


//Assigning functionally important styles. UI shold be functional even there are no CSS files attached
function assignStyles() {
//1 Finding all IFRAME's widhtin a pod and assigning functionally important styles
	var s_styleIframe = "width: 100%;height: 100%;";
	
	for (i=0; i<A_POD_BODY.length; i++) {
		var o_t = A_POD_BODY[i].getElementsByTagName("iframe")[0];
		if(o_t) {
			o_t.setAttribute("style", s_styleIframe);
		}
	}

//2 assigning functionally important styles to last Header and Pod: last padding from right should be equal the first Pod offet from left
var s_lastPod = "padding-right:"+A_POD_BODY[0].offsetLeft+"px !important"
	A_POD_BODY[A_POD_BODY.length-1].parentNode.setAttribute("style",s_lastPod);
	A_POD_HEAD[A_POD_HEAD.length-1].setAttribute("style",s_lastPod);	


//3 assigning functionally important styles to left and right buttons
	var s_style = "position: absolute; z-index: 100; bottom: 0.4em; padding: 5px 10px; font-size: 4em; "
	var s_styleLeft = "right: 50%;";
	var s_styleRight = "left: 50%;";
		O_GO_LEFT.parentNode.setAttribute("style",s_style+s_styleLeft);
		O_GO_RIGHT.parentNode.setAttribute("style",s_style+s_styleRight);
		O_GO_LEFT.setAttribute("style","text-decoration: none !important;");
		O_GO_RIGHT.setAttribute("style","text-decoration: none !important;");
}


/*
function checks if soft scrolling on ON (true), and initiate scrolling to Target pod. 
*/
var n_TARGET = 0;
function scrollToPosition(o_caller) {
	n_TARGET = A_POD_LOCATION_SCROLL[o_caller.getAttribute("podindex")];	
	if(B_SOFTSCROLL) {
		pageScroll() 
	}
	else {
		O_CONTENT.scrollLeft = n_TARGET;
	}
}


var n_goRight = 1;
var n_softStep; // getting calculated dynamicaly to slow down before the target
var n_distance;
function pageScroll() {
	//DIRECTION: left of right
	if(n_TARGET==O_CONTENT.scrollLeft) {
		stopScroll();
	}
	else {
		//validate direction
		n_goRight = 1;
		if(n_TARGET < O_CONTENT.scrollLeft) n_goRight=-1;
		
		//validate distance to target
		n_distance = n_TARGET-O_CONTENT.scrollLeft
		
		if((n_distance*n_goRight)>=SCROLL_STEP) {
			n_softStep = SCROLL_STEP;
		}
		else {
			n_softStep = getHalfStep(n_distance*n_goRight);
		}
		
		O_CONTENT.scrollLeft = O_CONTENT.scrollLeft+(n_softStep*n_goRight); // horizontal , vertical scroll increments
		scrolldelay = setTimeout('pageScroll()',SCROLL_SPEED);			
	}
}


function stopScroll() {
    	clearTimeout(scrolldelay);
}

function getHalfStep(n_sp) {
	if(n_sp!=1) {
		var d_num = n_sp/2;
		var r_num = Math.round(d_num);
		if(d_num==r_num) {
			return d_num; // number was even
		}
		else {
			return(n_sp-1)/2; // number was odd
		}
	}
	else {
		return 1;
	}
}

function scrollToLeft() {
	//alert("left:" + n_I_PDL +" right:" + n_I_PDR)
	scrollToPosition(AO_NAV_BUT[n_I_PDL]);
}

function scrollToRight() {
	//alert("left:" + n_I_PDL +" right:" + n_I_PDR)
	scrollToPosition(AO_NAV_BUT[n_I_PDR]);
}


// UTILs functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 

/*
returns Width and Height of the Window
*/
function getWindowWH() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( D.documentElement && ( D.documentElement.clientWidth || D.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = D.documentElement.clientWidth;
    myHeight = D.documentElement.clientHeight;
  } else if( D.body && ( D.body.clientWidth || D.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = D.body.clientWidth;
    myHeight = D.body.clientHeight;
  }
  return [myWidth , myHeight];
}


var n_pressedNumber;
function keyUp(evt) {
    evt = (evt) ? evt : window.event
	if(evt.ctrlKey && evt.shiftKey) {
		
		if(evt.keyCode==37) {
			O_GO_LEFT.onclick();	// navigate left
		}
		else if (evt.keyCode==39) {
			O_GO_RIGHT.onclick();	// navigate right
		}
		else { 
			// CNTR + SHIFT + someKey - validate if it is in the range of map targets			
			n_pressedNumber = (evt.keyCode*1)-48;
			if(evt.keyCode>=48 && evt.keyCode<=57 ) {
				AO_NAV_BUT[n_pressedNumber-1].onclick();
			}
		}
	}
	O_MAP_NAV.className = "";
    return false;
}

 //setting focus to Map navigation object to avoid text-select functionality
function keyDown(evt) {
	evt = (evt) ? evt : window.event
	if(evt.ctrlKey && evt.shiftKey) {
		O_MAP_NAV.focus();
	}
}




var O_OBJ;
var N_Width;
var widthStep = 40;
var widthStepDynamic = widthStep;
var dir;

function changeWidth() {
	var O_T = D.getElementById(O_OBJ)

	
	if(N_Width==O_T.scrollWidth){
		stopchangeWidth();
		widthStepDynamic = 40;
		makeUIadjustments();
	}
	else {
				
		if(N_Width>O_T.scrollWidth) {
			dir = 1; // 1 to increase
		}
		else {
			dir = -1; // -1 to reduce
		}
		
		if(((N_Width-O_T.scrollWidth)*dir)<=widthStep) {
			widthStepDynamic = getHalfStep(widthStepDynamic)
		}
		else {
			widthStepDynamic = widthStep;
		}
		O_T.style.width = (O_T.scrollWidth+(widthStepDynamic*dir))+"px";
		changeWidthTimer = setTimeout('changeWidth()',10);			
	}
}


function stopchangeWidth() {
    	clearTimeout(changeWidthTimer);
}

