/*
Title:      Main JS Page
Author:     Ben Babics, bbabics@organic.com
Notes:      Site functions that are page specific
*/



//onload functions
onload_register('setup_menus()');
onload_register('lastBorder()');


//set vars
var arr = new Array();
var children = new Array();
var sec = new Array();
var selected;
var scroll_menu;



function curr_Page(obj, id, child_id) {	
	//if sub-nav exists make sub-nav id the id
	if (child_id != null) id = child_id;
	
	//call border function
	lastBorder(id);

	//call functions accordingly
	switch(id) {
		case "overview_of_systems":
			//set object array
			sec.push('custom_stack_1');
			sec.push('custom_stack_2');
			sec.push('custom_stack_3');

			//send to functions
			childHeight('div');			
			arr.sort(sortHei);
			oddChild();
			setAllHei();

			//set tracking
			var elms = $$('.thirds');

			//loop through divs
			for (i=0; i < elms.length; i++) {
				var id = removeStr(elms[i].id, 'custom_');
				createLink(elms[i], id, 'how_systems_work');
			}
			break


		case "rock_trac":
		case "command_trac":
		case "command_trac_2":
		case "selec_trac_2":
		case "quadra_drive_2":
		case "quadra_trac":
		case "quadra_trac_2":
		case "freedom_drive":
		case "freedom_drive_2":
			//add style(s)
			var desc = document.getElementById('custom_description');
			var movie = document.getElementById('custom_movie');
			addClass(desc, 'desc_bg');

			//apply left border to movie
			movie.style.background = "#D1CAA5 url(/en/4x4/img/borders.gif) repeat-y scroll left top";

			//set object array
			sec.push('custom_container');

			//send to function
			childHeight('div');
		break


		case "systems_by_vehicle":
			//define flash proxy call
			flashProxy = new FlashProxy(flash_func_id, "/en/4x4/swfs/JavaScriptFlashGateway.swf");

			//make var of the menu on the page
			var menu = document.getElementById('custom_menu');
			menu = menu.getElementsByTagName('ul')[0];

			//loop through the menu 
			//attach event handler to anchor tags
			add_onclick(menu, 'a', 'flash_proxy');

			//set first child in menu as selected
			selected = menu.firstChild.firstChild;

			//send selected to function
			//func used whenever newly selected
			displayContent(selected, 'flash_proxy');

			//get array of children			
			getChildren('custom_container', 'div');

			//array of children to exclude from height adjustment
			sec.push('custom_menu', 'custom_movie');

			//remove those children from 'getChildren' array
			spliceChild();

			//get difference in height and apply it to divs
			var container = getHei('custom_movie');
			var menu = getHei('custom_menu');
			var diff = container - menu;

			var set_hei = $('custom_movie').getSize().size.y;
			$('custom_container').setStyles({
				height: set_hei,
				overflow: 'hidden'
			});

			setHei(diff);
			break

		case "off_road_overview":
			//define flash proxy
			flashProxy = new FlashProxy(flash_func_id, "/en/4x4/swfs/JavaScriptFlashGateway.swf");

			//make var of the menu on the page
			var menu = document.getElementById('off_road_guide');
			menu = menu.getElementsByTagName('ul')[0];

			//loop through the menu
			//attach event handler to anchor tags
			add_onclick(menu, 'a', 'scrolling_menu');

			//set first child in menu as selected
			selected = menu.firstChild.firstChild;

			//setup SCROLLING menus
			setupMenu();

			//send selected to function
			//func used whenever newly selected
			displayContent(selected, 'scrolling_menu');

			//get array of children			
			getChildren('custom_container', 'div');

			//array of children to exclude from height adjustment
			sec.push('custom_menu', 'custom_movie');

			//remove those children from 'getChildren' array
			spliceChild();

			//get difference in height and apply it to divs
			var container = getHei('custom_movie');
			var menu = getHei('custom_menu');
			var diff = container - menu;

			var set_hei = $('custom_movie').getSize().size.y;
			$('custom_container').setStyles({
				height: set_hei,
				overflow: 'hidden'
			});

			setHei(diff);
			break


		case "trail_rated":
			//make var of the menu on the page
			var menu = document.getElementById('custom_menu');
			menu = menu.getElementsByTagName('ul')[0];

			//loop through the menu
			//attach event handler to anchor tags
			add_onclick(menu, 'a', 'trail_rated');

			//set first child in menu as selected
			selected = menu.firstChild.firstChild;

			//send selected to function
			//func used whenever newly selected
			displayContent(selected, 'trail_rated');

			//get array of children			
			getChildren('custom_container', 'div');

			//array of children to exclude from height adjustment
			sec.push('custom_menu', 'custom_movie');

			//remove those children from 'getChildren' array
			spliceChild();

			//get difference in height and apply it to divs
			var container = getHei('custom_movie');
			var menu = getHei('custom_menu'); 
			var diff = container - menu;

			var set_hei = $('custom_movie').getSize().size.y;
			$('custom_container').setStyles({
				height: set_hei,
				overflow: 'hidden'
			});

			setHei(diff);
			break


		case "faqs":
			//make var of the menu on the page
			var menu = document.getElementById('custom_questions');
			menu = menu.getElementsByTagName('ul')[0];

			//loop through the menu
			//attach event handler to anchor tags
			add_onclick(menu, 'a', false);

			//set first child in menu as selected
			selected = menu.firstChild.firstChild;

			//send selected to function
			//func used whenever newly selected
			displayContent(selected, false);

			//set tracking
			var questions = $$('#custom_questions li');

			//loop through divs
			for (i=0; i < questions.length; i++) {
				var child = questions[i].firstChild;
				var id = child.title;

				//set tracking
				child.setAttribute('name', '&lpos=engineering_faqs&lid=' + id);
			}

			//grab first-child's height to apply to all siblings
			var answers = $$('.answers');
			var fc_hei = answers[0].getStyle('height');

			//loop through answer divs
			for (i=0; i < answers.length; i++) {
				var child = answers[i];
				child.style.height = fc_hei;
			}

			//set appropriate height  //NOT USING *******************
			//headlineDiff('pageElements');
			break


		case "glossary":
			var page = document.getElementById('pageElements');
			addClass(page, 'glossary');

			add_onclick(page, 'a', false);

			var son = document.getElementById('custom_stack_1');
			selected = son.firstChild.firstChild.firstChild;

			displayContent(selected, 'false');

			//set tracking
			var elms = $$('.thirds');

			//loop through divs
			for (i=0; i < elms.length; i++) {
				var child = elms[i].firstChild.firstChild;
				var id = child.title;

				//set tracking
				child.setAttribute('name' , '&lpos=4x4_glossary_of-terms&lid=' + id);
			}

			//set height on divs
			var terms = $$('.custom_terms p');
			var fc_hei = terms[0].getStyle('height');

			//loop through terms divs
			for (i=0; i < terms.length; i++) {
				var child = terms[i];
				child.setStyle('height', fc_hei);
			}
			break


		default:
			//set tracking
			var elms = $$('.halfs');

		//loop through divs
		for (i=0; i < elms.length; i++) {
			var id = removeStr(elms[i].id, 'custom_');
			createLink(elms[i], id, '4x4_basic_overview');
		}

		//fix towing guide to point to the right page  
		$('custom_towing_guide').firstChild.href = "javascript:wrap('towing','','');";
	}

	//match height of nav to #contentCont
	navHei();

	//wrap nav & contentCont in a master div for bg transparency
	masterCont();
}



// Wraps content of a div inside an anchor so as to link entire div.
// Link automatically takes on full size of div.
function createLink(divID, link, lpos) {
	var div = $(divID);

	//var linkWidth = div.getStyle('width') + ' !important';
	var newLink = new Element('a', {
		'styles': {
			'display': 'block',
			'height': div.getStyle('height'),
			'width': div.getStyle('width'),
			'text-decoration': 'none'
		},
		'class': 'divWrapper',
		'href': link,
		'name': '&lpos=' + lpos + '&lid=' + link
	});

	newLink.adopt(div.getChildren());
	div.adopt(newLink);
}



function masterCont() {
	//grab nav & contentCont divs
	var cont = $('content');
	var nav = $('left_menu');
	var contentCont = $('contentCont');


	//establish content current height
	var before_hei = cont.getStyle('height');

	//content is assigned before height
	//cont.style.height = before_hei;  //UNCOMMENT THIS TO TURN ON OPENING ANIMATIONS


	//create div's
	var blank_div = new Element('div', { 'id': 'blank_div' } );
	var wrapper = new Element('div', { 'id': 'masterCont', 'class': 'autoclear'	} );
	var foot = new Element('div', { 'id': 'masterFoot' } );

	//set adoptions
	cont.adopt(blank_div);
	blank_div.adopt(wrapper);
	wrapper.adopt(nav);
	wrapper.adopt(contentCont);
	blank_div.adopt(foot);


	//establish blank_div current height
	var after_hei = blank_div.getSize().size.y;

	//var transitions
	/* UNCOMMENT THIS TO TURN ON OPENING ANIMATIONS */ /*
		var contentFx = new Fx.Styles(cont, {duration: 1000, transition: Fx.Transitions.linear});  //TO TURN OFF OPENING ANIMATIONS
		var wrapperFx = new Fx.Style(wrapper, 'opacity', {duration: 1000, transition: Fx.Transitions.linear});  //TO TURN OFF OPENING ANIMATIONS
		var footerFx = new Fx.Style(foot, 'opacity', {duration: 1000, transition: Fx.Transitions.linear});  //TO TURN OFF OPENING ANIMATIONS
		var navFx = new Fx.Style(nav, 'opacity', {duration: 1000, transition: Fx.Transitions.linear});  //TO TURN OFF OPENING ANIMATIONS

		//cue tranisitions
		contentFx.start({ 'height': [before_hei, adispfter_hei] }).chain(function() { wrapperFx.start(0,1); footerFx.start(0,1); navFx.start(0,1) });  //TO TURN OFF OPENING ANIMATIONS
	*/

	//reset adoptions
	cont.adopt(wrapper);
	cont.adopt(foot);

	//set styles
	contentCont.setStyle('visibility', 'visible');	
	nav.setStyle('visibility', 'visible'); //visiblity remains hidden because IE show's it because of absolute positioning
}



function setEmbedLoaded(){
	window.document["custom_movie_flash"].SetVariable('title','');
	window.document["custom_movie_flash"].SetVariable('poster','/en/4x4/images/trail_rated/lb_image.jpg');
	window.document["custom_movie_flash"].SetVariable('flv','/en/4x4/swfs/trail_rated/trail_rated_disclaim.flv');
	window.document["custom_movie_flash"].SetVariable('disclaimer','1:2007 and 2008 models shown.|');
	window.document["custom_movie_flash"].change();
}



function navHei() {
	var nav = $('left_menu');
	var cont = $('contentCont');
	var hei = cont.getStyle('height');

	nav.style.height = hei;
}



function headlineDiff(obj) {
	//set appropriate height
	var pageCopy = $('pageCopy');
	var headline = pageCopy.getStyle('height');
	headline = removeStr(headline, 'px');
	var height = (403 - headline) - 14;

	//push obj into array
	arr.push(obj);

	setHei(height);
}


function getChildren(obj, el) {
	var parent = document.getElementById(obj);
	var child = parent.getElementsByTagName(el);

	//loop through and push children into array
	for (i=0; i < child.length; i++) {
		arr.push( child[i].id );
	}
}



function spliceChild() {
	//loop through remove array
	for (i=0; i < sec.length; i++) {
		//if you find it remove it		
		for (x=0; x < arr.length; x++) {
			if (arr[x] == sec[i]) {
				arr.splice([x], 1);
			}
		}
	}
}



function replaceStr(val, rep, newVal) {
	//if val doesn't exist stop
	if (val == null) return false;

	//return val with replaced portion of string
	while (val.indexOf(rep) != -1) {
		val = val.replace(rep, newVal);
	}

	return val;
}



function removeStr(val, rem) {
	//if val doesn't exist stop
	if (val == null) {
		return false;
	}

	//return val with removed portion of string
	if (val.indexOf(rem) != -1) {
		return val.replace(rem, '');
	}
}



function add_onclick(obj, el, mode) {
	//create var of child elements and length
	var child = obj.getElementsByTagName(el);
	var len = child.length;

	//loop through length
	for (i=0; i < len; i++) {
		child[i].href = "#";

		//place tracking info from nav
		//into array for menu
		children.push(child[i].name);

		//attach onclick event handler and function
		child[i].onclick = function() {
			//if we don't need to call a flash function
			displayContent(this, mode);
			return false;
		}

	}
}



function displayContent(obj, mode) {
	var curr = obj;

	switch(mode) {
		case "flash_proxy":
			var curr_id = "custom_" + curr.title;
			var selected_id = "custom_" + selected.firstChild.title;
			var flash = true;
			var typeOfCall = "fselectSystem";
			var curr_path = removeStr(curr_id, 'custom_');
			var lbPath = "/en/4x4/images/systems_by_vehicle/" + curr_path + '.jpg';
			break

		case "scrolling_menu":
			var curr_id = "custom_" + curr.parentNode.id;
			var selected_id = "custom_" + selected.id;
			var flash = true;
			var typeOfCall = "getMovie";
			var swfPath = "/en/4x4/swfs/off_road_guide/" + curr.parentNode.id + '.swf';
			var lbPath = "/en/4x4/images/off_road_guide/" + curr.parentNode.id + '.jpg';

			//if scrolling menu set add value
			updateMenu(obj);
			break

		case "trail_rated":
			var curr_id = "custom_" + curr.title;
			var selected_id = "custom_" + selected.firstChild.title;
			var lbPath = "/en/4x4/images/trail_rated/lb_image.jpg";
			break


		default:
			var curr_id = "custom_" + curr.title;
			var selected_id = "custom_" + selected.firstChild.title;
			var flash = false;
	}

	var parent = curr.parentNode;
	var desc;

	//check if selected has className 'selected'
	if( checkClass(selected, 'selected') == true ) {
		//if so remove className 'selected'
		removeClass(selected, 'selected');

		//find description div
		desc = document.getElementById(selected_id);

		//display none to div
		addClass(desc, 'none');
	}

	//assign selected var
	selected = parent;

	//add 'selected' className
	addClass(parent, 'selected');

	//strip 'custom_' out of id
	var flash_id = removeStr(curr_id, 'custom_');

	if (swfPath) flash_id = swfPath;

	//send id to flash movie or write lo-band image
	if (userData.bandwidth != "low"
		&& flash
		&& typeof(flashProxy) != "undefined") {
		flashProxy.call(typeOfCall, flash_id);
		if(window.document["custom_movie_flash"])
		{
			console.log(flash_id);
			window.document["custom_movie_flash"].fselectSystem(flash_id);
		}
	}
	else if ($('custom_movie')) {
		$('custom_movie').setStyle('background', 'url(' + lbPath + ') right top no-repeat');
	}
	
	//find description div
	desc = document.getElementById(curr_id);

	//display div
	removeClass(desc, 'none');
	//desc.style.visibility = "hidden";
}



function setupMenu() {
	var scroll_menu = document.getElementById('custom_menu');
	scroll_menu = scroll_menu.getElementsByTagName('li')[0];

	scroll_menu.className = "autoclear";

	var el = scroll_menu.firstChild;
	scroll_menu.removeChild(el);

	var prev_button = document.createElement('a');
	var menu_title = document.createElement('span');
	var next_button = document.createElement('a');

	prev_button.setAttribute('id', 'prev_butt');
	menu_title.setAttribute('id', 'menu_title');
	next_button.setAttribute('id', 'next_butt');

	prev_button.setAttribute('href', '#');
	next_button.setAttribute('href', '#');

	scroll_menu.appendChild(prev_button);
	scroll_menu.appendChild(menu_title);
	scroll_menu.appendChild(next_button);
}




function updateMenu(obj) {
	//escape if SCROLLING menu doesn't exist
	if (!document.getElementById('menu_title')) {
		return false;
	}

	//find menu title element
	var menu_title = document.getElementById('menu_title');

	//add title
	menu_title.innerHTML = obj.innerHTML;

	//check for Previous & Next
	var parent = obj.parentNode;

	( parent.previousSibling == null )? switchButton('prev_butt', 'none') : switchButton('prev_butt', 'block', parent.previousSibling.firstChild);
	( parent.nextSibling == null )? switchButton('next_butt', 'none') : switchButton('next_butt', 'block', parent.nextSibling.firstChild);
}



function switchButton(dir, style, obj) {
	//var button obj
	var button = document.getElementById(dir);

	//toggle display style on button
	button.className = style;

	//assign tracking
	if (obj) button.setAttribute('name', '&lpos=off_road_guide&lid=' + obj.parentNode.id);

	if (obj != null) button.onclick = function() {
		displayContent(obj, 'scrolling_menu');
		return false;
	};
}



function emptyArray(arr) {
	//while length is larger than 0
	while ( sec.length > 0 ) {
		//remove children
		sec.pop();
	}
}



function childHeight(el) {
	var len = sec.length;

	for (i=0; i < len; i++) {	
		var parent = document.getElementById(sec[i]);
		var hei = parent.clientHeight + 10;
		var child = parent.getElementsByTagName(el);

		//matches height of current row
		for (j=0; j < child.length; j++) {
			//set height to current row
			child[j].style.height = hei + "px";

			//put row in array
			children.push(child[j]);
		}

		//put height in array
		arr.push(hei);
	}
}



function getHei(obj) {
	//get height from obj and return it
	var el = document.getElementById(obj);
	var hei = el.clientHeight;
	return hei;
}



function setHei(hei) {
	//loop through array
	for (i=0; i < arr.length; i++) {
		//set height to current child in array
		var curr = document.getElementById(arr[i]);
		curr.style.height = (hei - 6) + "px";
		curr.style.overflow = "auto";
		curr.style.marginbottom = "6px";
	}
}



function sortHei(a, b) {
	//sort highest first
	return b - a;
}



function oddChild() {
	//loop through "children" array
	for (i=0; i < children.length; i++) {
		var child = children[i];
		var odd = [i] % 2;

		//find if current child is odd number
		//add 'odd' className
		if (odd === 1) addClass(child, 'odd');
	}
}



function setAllHei() {
	var hei = arr[0] + "px";

/*	
	var heightSum = 0;
	arr.each(function(item) { heightSum += item; });

	var contentHeight = $('contentCont').effect('height', {duration: 300, transition: Fx.Transitions.linear});
	contentHeight.start($('contentCont').getSize().size.y + (3 * hei) - heightSum);
*/

	for (i=0; i < sec.length; i++) {
		var obj = document.getElementById(sec[i]);
		var len = obj.childNodes.length;

		for (j=0; j < len; j++) {
			var child = obj.childNodes[j];
			child.style.height = hei;
		}
	}
}



function lastBorder() {
	var parent = document.getElementById('pageElements');
	var child = parent.getElementsByTagName('div');

	//loop through elements in parent
	for (i=0; i < child.length; i++) {
		//find last element
		var gChild = child[i].lastChild;

		//assign 'last' className
		addClass(gChild, 'last');
	}
}