// JavaScript Document
var breakers=[]
var questionData = [];
var intVideo;
var paths = []

// get language from query string
function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	//alert('Query Variable ' + variable + ' not found');
}

document.selectedLang = getQueryVariable("lang");
if(document.selectedLang == undefined){
	document.selectedLang = 'en' // comment out when using multi-sco wrapper
}

$( document ).ready(function() {
	$.getJSON("content.json").done(build, getRest).fail(function( jqXHR, textStatus, error) {
		var err = textStatus + ", " + error;
    console.log("Request Failed: "+ err);
	var char = JSON.stringify(jqXHR);

  })
  .always(function() {

  });;

});

//Ensure rest of files are loaded after build is complete
function getRest(){
$.getScript( "js/file_loader.js", function( data, textStatus, jqxhr ) {
/*  console.log( data ); // Data returned
  console.log( textStatus ); // Success
  console.log( jqxhr.status ); // 200
  console.log( "Load was performed." );*/
});
	}

function build(data){
var Item;
var section;
var select_sec;
var select_sec_breaker;
var sec=[];
var page = [];
var topics = [];
var pageData = [];
var topicData = [];
var bullet_index = [];
var bull_counter = 0;
var images = [];
var breakerImg = [];
document.topic_intro = data.topic_intro;
document.course_title = data.course_title;
document.titles = data.topic_titles;
document.index = data.index;
document.intro_back = data.intro_backgound.topics;
document.intro_vid_mp4 = data.intro_video.mp4;
document.intro_vid_poster = data.intro_video.poster;
document.test_vid_mp4 = data.test_video.mp4;
document.test_vid_poster = data.test_video.poster;
var appendTo;
var appendItem;
var slides_length;
var content_text;
var itemSelect;
var textItem;
var imageItem;
var imgItem;
var inner_content;
var grid_inner;
var div;
var image_bullet;
var image_bool = true;
document.title = data.browser_title;
var vid_count = 0
function findBreaker(){
jQuery.each(data.topics, function() {
  var t = (this).title
  var p = (this).pages
  var breakerImage = (this).background.path
  sec.push(t)
	page.push(p)
	breakerImg.push(breakerImage)
	topics.push(this)
});
sectionBreaker();
}

function sectionBreaker(){
for(var i=0; i<sec.length; i++)	{
	var newBreaker = document.createElement('div');
	$( ".sec_rest_wrapper").append('<div class="section breaker"></div>');
	$('.section breaker').css('background-image', breakerImg[i]);
		}
}

function sectionPages(){
	var eachArray = function(arr) {
    if ( typeof(arr) == "object") {
        for (var i = 0; i < arr.length; i++) {
            eachArray(arr[i]);
        	}

   	 	}
    	else document.write(arr);
	}
eachArray(page);
}

//get JSON data and create and attach the data to each section
function associateData(){
	for(var i = 0; i < page.length; i++) {
	var p = page[i];
		for(var j = 0; j < p.length; j++) {
			if(j===p.length-1){
			$( ".section.breaker").eq(i).after('<div class="section intro"></div>');

			}else{
				$( ".section.breaker").eq(i).after('<div class="section meat"></div>');
			}
			pageData.push(p[j]);

		}
	}
}

function associateBreakerData(){
	for(var i = 0; i < topics.length; i++) {
	var t = topics[i];

		for(var j = 0; j < t.length; j++) {
			topicData.push(t[j]);
		}
	}
}

function attchData(){
	for(var i = 0; i < pageData.length; i++){
			select_sec = $( ".sec_rest_wrapper").children('.section').not($('.breaker'));
			select_sec.eq(i).data("div_content", pageData[i]);
		}
		for(var j = 0; j < topics.length; j++){
		select_sec_breaker =$( ".sec_rest_wrapper").children( ".section.breaker");
		select_sec_breaker.eq(j).data("div_content", topics[j]);
		}
	}

function setID(){
	for(var i = 0; i < $('.section').length; i++){
		var id = i+1
		$('.section').eq(i).attr('id', 'sec_'+id+'')

	}
}

function setCSS(){
	$('.breaker .grid_inner, .talk .grid_inner' ).css('opacity', '1');
	$('.question:first').css('display', 'block');
	}

function backGround(back_select){
	$(back_select).each(function() {
		if($(this).data("div_content")) {
			if($(this).data("div_content").hasOwnProperty('background')){
				$(this).append('<div class="background_stretch"></div>');
				var stretch = $(this).children('.background_stretch');
				if($(this).data("div_content").background.hasOwnProperty('color'))
				{
					var bgColor = $(this).data("div_content").background.color.toLowerCase();							
					bgColor = bgColor.split(" ").join("") + "BgColor";
					stretch.addClass(bgColor);					
				}
				else
				{					
					stretch.css("background-image", 'url('+ $(this).data("div_content").background.path +')');
				}
			}
		}
	});
}

function textColor(back_select){
	$(back_select).each(function() {
		if($(this).data("div_content")) {
			if($(this).data("div_content").hasOwnProperty('text_color')){
				var textColor = $(this).data("div_content").text_color.toLowerCase();							
				textColor = textColor.split(" ").join("") + "TextColor";
				$(this).addClass(textColor);	
			}
		}	
	});
}

//If no color assign background
function randomColor(current, color_select, colors){
	var random_color;
	if(current.context.className === "section breaker"){
		random_color = '#666666';
		}else{
	if(color_select.data("div_content")){
		if(color_select.data("div_content").hasOwnProperty('background')){
			var other_section = color_select.data("div_content").background;

			if(other_section.hasOwnProperty('color')){
				var otherColor = other_section.color;
				for(var i = 0; i < colors.length; i++){
					if(otherColor === colors[i]){
					var j = ($.inArray(colors[i], colors)) /*colors.indexOf(colors[i]); Not in IE8*/
					colors.splice(j, 1);
					}
				}
			}
		}
	}
	random_color = colors[Math.floor(Math.random() * colors.length)];
	current.data("div_content").background['color'] = random_color;
	}
	return random_color;
}

//Add Basic Structure if Section contains Content
function addContent(content_selector){
	$(content_selector).each(function() {
		image_bool=true
	if($(this).data("div_content")){
	if(content_selector === select_sec_breaker){
		if($(this).data("div_content").hasOwnProperty('title')|| $(this).data("div_content").hasOwnProperty('type')){
			$(this).append('<div class="grid"></div>');
			var grid_break = $(this).children('.grid');
			grid_break.append('<div class="grid_inner"></div>');
			var grid_break_inner = $(this).find('.grid_inner');
			grid_break_inner.append('<h1>'+$(this).data("div_content").title+'</h1>');
			}
		}else{
	if($(this).data("div_content").hasOwnProperty('content') || ($(this).data("div_content").hasOwnProperty('type') && $(this).data("div_content").type == "video")){
		$(this).append('<div class="grid"></div>');
		var grid = $(this).children('.grid');
		if($(this).data("div_content").hasOwnProperty('title')){
			grid.append('<div class="h2_inner"><h2>'+$(this).data("div_content").title+'</h2></div>');
		}else{
			grid.append('<div class="h2_inner"><h2></h2></div>');
		}
		grid.append('<div class="grid_inner"></div>');
		grid_inner = $(this).find('.grid_inner');
		div = $(this);
		if($(this).data("div_content").hasOwnProperty('type') && $(this).data("div_content").type == "video"){
			inner_content = [$(this).data("div_content")];
		} else {
			inner_content = $(this).data("div_content").content;
		}
				bull_counter=0
				bullet_index = []
			}

			decideAppend(select_sec);
			}
			}
		});
	}

//Decide whether one or two colmns
function decideAppend(content_selector){

	jQuery.each(inner_content, function(index) {
		var two_col_dom = '<div class="two_col"></div><div class="clear"></div>';
		var inner_content = content_selector.data("div_content").content;
		var itemSelect = this.type;
		var two_bool = false;
		var col_dom = '<div class="col"></div>';
		if(itemSelect === 'two_col_split'){
		if(grid_inner.find('.content_text').length === 0 || grid_inner.children().last()[0].className !== "content_text" ){
			grid_inner.append('<div class="content_text"></div>');
			}
			content_text =  div.find('.content_text').last();
			appendTo = content_text;
			appendItem = two_col_dom;
			addDomContent(appendTo, appendItem);
			var two_col = div.find('.two_col').last();
			for (var i = 0; i< this.columns.length; i++) {
					two_col.append(col_dom);
					}
			two_col.children(":first").addClass('first');
			two_col.children(":last").addClass('last');

			$.each(this.columns, function (index, item) {
			itemSelect = item.type;
			textItem = item.text;
			two_bool = true;
			soManyColumns(index);
			runItems(this, index, two_bool);
			});
			}else{
				runItems(this, index, two_bool);
		}
	});
}

//APPEND TO TWO COLUMNS
function soManyColumns(index, two_bool){
	if(two_bool === true){
	var two_col =  div.find('.two_col').last();
		if (index === 0){
			appendTo = two_col.children(':first-child');
				}else{
				appendTo = two_col.children(':first-child').next();
				}
			}
			two_bool = false;
	}

//CONSTRUCT AND APPEND ITEMS ONE COLUMN
function runItems(section, index, two_bool){
		Item = section;
		itemSelect = section.type;
		textItem = section.text;
		imageItem = section.image;
		if(itemSelect === 'slider'){
			slides_length = section.slides.length
			}

		var text_dom = 	'<div class="content_text"></div>';
		var image_bullet_dom = '<div class="image_list_item"><div class="image_item"><img src="'+imageItem+'" alt=""></div><div class="text_item">'+textItem+'</div></div>';
		var plain_text_img_right_dom = '<div class="intro_text_img_right"><img src="'+imageItem+'" alt=""></div><div class="clear"></div>';

		var slider = '<div class="slider"><div class="slide_left" id="sl_'+($('.slider').length +1 )+'"></div><div class="slide_right" id="sr_'+($('.slider').length +1 )+'"></div><div class="slider_wrap"><div class="slider_container num_'+slides_length+'"></div></div><div class="temp_slide_nums"></div></div>';
		var one_col = '<div class="one_col">'+textItem+'</div>';
		var example_dom = '<div class="example_header"><p>Example</p></div><div class="example_txt example">'+textItem+'</div><div class="clear"></div>';


			if((itemSelect === 'plain_text' || itemSelect === 'image_right' || itemSelect === 'two_col_split' || itemSelect === 'slider' || itemSelect == 'video')){
				if(grid_inner.find('.content_text').length === 0 || grid_inner.children().last()[0].className !== "content_text" ){
				appendTo = grid_inner;
				appendItem = text_dom;
				addDomContent(appendTo, appendItem);
				content_text =  div.find('.content_text');
				}
			}

			 if(itemSelect === 'plain_text'){
				appendTo = div.find('.content_text').last();
				soManyColumns(index, two_bool);
				appendItem = one_col;
				addDomContent(appendTo, appendItem);
				}

			 if(itemSelect === 'video'){
				appendTo = div.find('.content_text').last();
				soManyColumns(index);
				appendItem = '<div class="one_col"></div>';
				addDomContent(appendTo, appendItem);
				var addVid = content_text.find('.one_col').last();
				addVid.append('<div class="inline_video_element"><img alt="" src="images/video_play.png"></div><div class="transcript">'+section.transcript+'</div>');
				if(vid_count===0){
				$('body').prepend('<div class="the_in_vid"> <div class="video_wrap_g"><div class="floating_close"></div><video id="inline_v'+vid_count+'" class="inline_v inline_hide" controls=""><source src="'+Item.path.mp4+'" type="video/mp4"/></video><div class="swf_wrapper"><div id="swf_player'+vid_count+'"></div> </div></div></div>');
				}else{
					$('#inline_v'+(vid_count-1)+'').after('<video id="inline_v'+vid_count+'" class="inline_v inline_hide" controls=""><source src="'+Item.path.mp4+'" type="video/mp4"/></video>');
					$('#swf_player'+(vid_count-1)+'').after('<div id="swf_player'+vid_count+'"></div>');
					}

			paths.push(Item.path.flv);
			vid_count = vid_count+1;
				}



			if(itemSelect === 'image_bullet'){
				bullet_index.push(index);
				if(Math.abs(bullet_index[bullet_index.length - 1] - bullet_index[bullet_index.length - 2]) > 1){
					bull_counter = bull_counter+1; }
				if(grid_inner.find('.image_list').length === bull_counter){
				grid_inner.append('<div class="image_list"></div>');
				}
				var image_list = div.find('.image_list').last();
				image_list.append(image_bullet_dom );

				}

			if(itemSelect === 'image_right'){
				appendTo = content_text.last();
				soManyColumns(index);
				appendItem = plain_text_img_right_dom;
				addDomContent(appendTo, appendItem);
				var intro_text_img_right = div.find('.intro_text_img_right').last();
				appendTo = intro_text_img_right;
				appendItem = section.text;
				addDomContent(appendTo, appendItem);
				}

				if(itemSelect === 'slider'){
				appendTo = content_text.last();
				soManyColumns(index);
				appendItem = slider;
				addDomContent(appendTo, appendItem);
					}

				if(itemSelect === 'table_list'){
				appendTo = grid_inner;
				soManyColumns(index);
				appendItem = section.table;
				addDomContent(appendTo, appendItem);
							}
				if(itemSelect === 'example_box'){
					appendTo = content_text.last();
					soManyColumns(index);
					soManyColumns(index, two_bool);
					appendItem = example_dom;
					addDomContent(appendTo, appendItem);
					}

	  			if(section.hasOwnProperty('slides')){
	  				var slider_content = section.slides;
	  				var slider_container = div.find('.slider_container').last();
	  				var temp_slide_nums = div.find('.temp_slide_nums').last()	;
	 				for (var i = 0; i< slider_content.length; i++) {
		  				if(slider_content[i].hasOwnProperty('text')){
		 				 slider_container.append('<div class="slider_txt" id="slider_1_'+(i+1)+'"><h3>'+slider_content[i].title+		'</h3>'+slider_content[i].text+'</div>');
		 					 }
		  				temp_slide_nums.append('<div class="slide_focus" id="foc_'+$('.slider').length+'_'+(i+1)+'">'+(i+1)+'</div>');
		 			 }
	 				 temp_slide_nums.children(":first").addClass('focus');
	 				 slider_container.append('<div class="clear" id=""></div>');

	 				 }

				}

//Append Content
function addDomContent(appendTo, appendItem){
	appendTo.append(appendItem);
	}

//ADD INTRO VIDEO
function addInto(){
	if(data.intro_video !== ""){
	$("body").prepend('<div class="sec_1_wrapper" id=""></div>');
	var sec_1 = $('.sec_1_wrapper');
	sec_1.append('<div class="bg_video"><video id="bgvid" autoplay="" loop="" poster="'+data.intro_video.poster+'"><source id="mp4" src="'+data.intro_video.mp4+'" type="video/mp4"/></video></div>');
	sec_1.append('<div class="section" id="sec_1"></div>');
	$('.section').eq(0).data("div_content", data);

	}
}


function ie8Vid(){
	if (navigator.appName === 'Microsoft Internet Explorer'){
			if(navigator.userAgent.match(/MSIE 8/i)){
			$('#topic_intro .background_stretch').css('background-image', 'url('+data.intro_video.poster+')');
			}
		}
	}


//ADD MENU
function addMenu(){
$('#topic_intro').append('<div class="menu_bar v_menu"><div class="v_menu_header"><div class="burger_close"></div> <div class="burger_logo"></div></div><div class="menu_items"><ul></ul></div><div class="v_menu_footer"><div class="burger_logo2"></div></div></div><div class="menu_bar"><div class="branding"><div class="logo"></div><div class="logo2"></div></div></div><div class="background_stretch"></div><div class="grid"><div class="grid_inner"><h1>'+data.title+'</h1></div></div><div class="menu_bar bar_bot"><div class="app_close small"></div><div class="menu_items double_bg"><div class="chapters_burger"><div class="txt"></div></div><div class="left_brand" style="display: none;"></div><div class="right_brand" style="display: none;"></div><ul></ul></div><div class="vetical_menu"><div class="v_menu_item" id="temp_1"><div class="v_txt active">Introduction<div class="bord"></div></div></div></div></div>')
for(var i=0; i<sec.length; i++)	{
	$('.menu_items ul').append('<li>'+sec[i]+'<div class="bord"></div></li>')

}
var findMenu = $('.section')
var li_select = 0
for (var i = 0; i< findMenu.length; i++) {
	if($(findMenu[i]).is('.section.breaker')){
		var goTo = i+1;

				$('.bar_bot .menu_items li').eq(li_select).attr('id', 'goto_'+goTo +'');

				$('.v_menu .menu_items li').eq(li_select).attr('id', 'vto_'+goTo +'');
				li_select = li_select +1;
		}

		if($(findMenu[i]).is('.section.breaker')){
			var breaker = (i+1).toString()
			breakers.push(breaker)
		}
	}
	$('.bar_bot .menu_items li:first-child').addClass('first');
	$('.bar_bot .menu_items li:last').addClass('last');
	$('.v_menu .menu_items li:first-child').addClass('first');
	$('.v_menu .menu_items li:last').addClass('last');
}


//ADD TEST SECTION
function addTestBreaker(){
	if(data.hasOwnProperty("test_bank_questions")){
		$('.section:last').addClass('testlast');
		$('.section:last').after('<div class="section breaker"><div class="background_stretch"></div><div class="grid"><div class="grid_inner"><h1>Test Yourself</h1></div></div></div>');
		$('.section:last').addClass('teststart');
		var testContent = data.test_bank_questions;

		for (var i = 0; i< testContent.length; i++) {
			questionData.push(testContent[i]);

			}
		}

}

function addQuestions(){
if(data.hasOwnProperty("test_bank_questions")){
var testContent = data.test_bank_questions;
var question_sec = '<div class="section question"></div>';
	jQuery.each(testContent, function(index, value) {
	if(value.type === 'radio'){
		$('.sec_rest_wrapper').append(question_sec);
		$('.section:last').addClass('mcsa');
		$('.section:last').data("div_content", value);
		}
	if(value.type === 'numeric'){
		$('.sec_rest_wrapper').append(question_sec);
		$('.section:last').addClass('input');
		$('.section:last').data("div_content", value);
		}
	});
/*	console.log($('.section').eq(10).data())*/
	}

}

function addQuestionContent(){
if(data.hasOwnProperty("test_bank_questions")){
var select_question = $('.section.breaker.teststart').nextAll('.section.question');
backGround(select_question);
$(select_question).each(function(index) {
	var question_data = $(this).data("div_content");
	if (question_data.hasOwnProperty('stem')){
		$(this).append('<div class="grid"></div>');
		var grid_ques = $(this).find('.grid');
		grid_ques.append('<div class="h2_inner"><h2>Question '+(index+1)+'</h2><span class="return"></span></div>', '<div class="grid_inner"></div>');
		var grid_in_ques = $(this).find('.grid_inner');
		grid_in_ques.append('<div class="content_text"></div>');
		var context_ques = $(this).find('.content_text');
		context_ques.append('<div class="stem">'+question_data.stem+'</div>');

		var answers = $(this).data("div_content").answers;
		if (question_data.hasOwnProperty('answers')){
			context_ques.append('<div class="options one_col" id="sec_'+($(this).index('.section') + 1)+'_options"></div>');
		var ques_options = $(this).find('.options');
		for (var i = 0; i< answers.length; i++) {
			ques_options.append('<div class="option_row"><div class="option row_left" id="sec_'+($(this).index('.section') + 1)+'_'+(i+1)+'"><div class="input_box"></div><div class="op_txt">'+answers[i]+'</div><div class="ans_mark"></div><div class="clear"></div></div></div>');
			}
		}
		if ($(this).data('div_content').type === 'numeric'){
			context_ques.append('<div class="input_option" id="sec_'+($(this).index('.section') + 1)+'_1"></div>');
			var input_option = $(this).find('.input_option');
			var prefix = $(this).data('div_content').prefix ? $(this).data('div_content').prefix: "";
			var suffix= $(this).data('div_content').suffix ? $(this).data('div_content').suffix: "";
			var pre = '<div class="pre">' + prefix + '</div>';
			var aft = '<div class="aft">' + suffix +'</div>';
			input_option.append(pre + '<div class="ans"><input class="input_fill" id="inline_fillin_L5183" type="text"></input></div>' + aft + '<div class="ans_mark"></div><div class="clear"></div></div>');
			}
		context_ques.append('<div class="submit_btn_wrap"><div class="submit_btn">Submit</div></div><div class="feedback" id="feed_' + ($(this).index('.section') + 1) + '"></div>');


	}

	switch (index % 2) {
			case 0:
					$(this).addClass("quesBgColor1");
					break;
			case 1:
					$(this).addClass("quesBgColor2");
					break;
			default:
					$(this).addClass("quesBgColor1");
	}

	});
	}
}

function credit(back_select){
	$(back_select).each(function() {
		if($(this).data("div_content")) {
	if($(this).data("div_content").hasOwnProperty('background')){
	if($(this).data("div_content").background.hasOwnProperty('path')){
	var grid = $(this).children('.grid');
					grid.append('<div class="credit">'+$(this).data("div_content").background.credit+'</div>');

	}}}
	});
	}

function addResults(){
	if(data.hasOwnProperty("test_bank_questions") && (data.hasOwnProperty("test_results"))){	
		var testResultsText = data.test_results.text;
		$('.section:last').after(testResultsText);
	}
}

function addTalk(){
	if(data.hasOwnProperty("talk_to_us")){	
		var talkToUsText = data.talk_to_us.text;
		$('.section:last').after(talkToUsText);
	}
}	

function addBookMark(){
	if(data.hasOwnProperty("bookmark")){
		var bookmarkText1 = data.bookmark.text1;
		var bookmarkText2 = data.bookmark.text2;
		$('body').prepend(bookmarkText1);
		$('.sec_rest_wrapper').after(bookmarkText2);
	}
}	
	
function inlineImg(){
	for (var i = 0; i< $('.content_text p img').length; i++){
	var src = $('.content_text p img').eq(i).attr('src');
	$('.content_text p img').eq(i).attr('src', '../../../'+src);	
		}
	}

/*findBreaker();
sectionPages();
associateData();
addInto();
associateBreakerData();
attchData();
backGround(select_sec);
backGround(select_sec_breaker);
addContent(select_sec);
addContent(select_sec_breaker);
textColor(select_sec);
textColor(select_sec_breaker);
addTestBreaker();
addQuestions();
addQuestionContent();
addResults();
addTalk();
addMenu()
setID()
addBookMark()
setCSS()
credit(select_sec)
credit(select_sec_breaker)
ie8Vid()
inlineImg()*/
}
