//Variables
var playSlideShow = true;
var playNewsTicker = true;
var playTestimonials = true;


//Used to determine whether slideShow has started or not
var hasSlideShowStarted = false;

//Create the slideshow array
var a1 = ["Green Market Craftsman", "A craftsman at work in Green Market Square in central Cape Town, a short train ride from The Knowledge Workshop", "Craftsman-Green-Market-Sq.jpg"];
var a2 = ["Local hiking", "All over the Cape Peninsula there are some spectacular, easily accessible trails that take hikers into a world far removed from the hustle and bustle of the city", "local-hiking-.jpg"];
var a3 = ["Road to", "You don't have to travel far out of Cape Town to get to the Cederberg Wilderness, a dramatic area of outstanding natural beauty, popular with hikers, climbers and adventurers", "Road-to.jpg"];
var a4 = ["Swartberg View", "The Klein Karoo in the Western Cape is a fertile valley, renowned for its magnificent spring flowers and rural way of life - great for a short getaway from Cape Town", "swartberg-view.jpg"];
var a5 = ["Table Mountain at night", "Recently voted as one of the new 7 Wonders of Nature, Table Mountain is the only natural site on the planet to have a constellation of stars named after it - Mensa, meaning \"the table\"", "Table-Mountain-at-night.jpg"];
var a6 = ["Table Mtn Wonder of Nature", "Table Mountain forms part of the Cape Floral Kingdom, the smallest and richest of only 6 floral kingdoms globally", "Table-Mtn-wonder-of-nature.jpg"];
var a7 = ["Teacher training complete", "A group of our TEFL/TESOL trainees celebrate reaching the end of practical training, having gained experience through our Schools' Assist Programme", "Teacher-training-complete.jpg"];
var a8 = ["V&A Waterfront", "The V & A Waterfront is South Africa\'s most-visited destination, having the highest rate of foreign tourists of any attraction in the country", "V&A-Waterfront.jpg"];
var a9 = ["TEFL - Korea", "Many of our TEFL/TESOL graduates head for Asia to take up their first teaching post. Here are some young learners in South Korea", "TEFL-Korea.jpg"];
var a10 = ["Ikamvalethu", "For one of our community projects we organised a speech contest at Ikamvalethu Secondary School in Langa, Cape Town's oldest township", "Ikamvalethu.jpg"];
var a11 = ["Just another sunset", "Meeting for sundowners is a popular pastime in Cape Town, with many idyllic locations for a beach picnic, while the sun slips away", "Just-another-sunset.jpg"];
var a12 = ["TEFL complete", "At TKW we take your training seriously, but the process of learning should be fun and engaging, while providing learners with opportunities to make new friends", "TEFL-complete.jpg"];
var aImages = [a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12];
	
//When document is ready
$(document).ready(function(){
	
	//slideShow :: Start the ball rolling with the first image (index = 0)
	if (playSlideShow) processImage(0);

  	//Testimonial Options
  	var optTestimonials = {
  		pauseTime: 10000,
		transitionTime: 1000,
		ignore: "#introslide",
		delayStart: 4000,
		pauseOnMouseOver: true,
		createNavButtons: true
  	}
  	//Initialize :: Testimonials
	if (playTestimonials) $("#myTestimonialsC").fadeTransition(optTestimonials);

	
	//News Ticker Bryan Gullan options
	var options = {
		newsList: "#news",
		startDelay: 10,
		placeHolder1: "|",
		placeHolder2: "|",
		tickerRate: 40,
		stopOnHover: false
	}
	if (playNewsTicker) {
		$().newsTicker(options);
	}
	$('#ticker-title').addClass("notranslate");


   	/* Read the language Cookie (tkwLanguage) */
	var cookieLanguage = $.cookie("tkwLanguage");

	//console.log("tkwLanguage: " + cookieLanguage);
	if (cookieLanguage !== 'en' && cookieLanguage !== null){
		//showProgress(cookieLanguage);

	}
	
	//Initiate translator
	//initTranslator();
});


function processImage(index){
	//slideShow :: This loads each image and its caption into the slideshow	
	if (index < aImages.length) {
		//If index == 3 then we've loaded 3 which is enough to start the show. This could be lower or higher
		if (index == 3 && hasSlideShowStarted == false)
		{
			hasSlideShowStarted = true;
			beginTimer(); //Begin slide show
		}
		
		var row = aImages[index];
		
		var imgi = new Image();
		imgi.onload = function() {
			
			//add the slide element if the index is not 0 (the first one is already present)
			if (index !== 0) {
				$('#slideShow').append('<div id="slide' + index + '" class="slide"><img src="/images/homepage/' + row[2] + '" alt="' + row[1] + '" /></div>');
			}
				
			// always called
		    //console.log(row[0] + ' Loaded!');
			
			//load the caption background
			var imgc = new Image();
			imgc.onload = function() {
				
				//Add the caption element		    	
		    	$('#slide' + index).append('<div class="caption darker"><div><b>' + row[0] + '</b>&nbsp;' + row[1] + ' <a href="/content/gallery/">Photo Gallery  &#187;</a></div></div>');
		    	
		    	//Process the next image
		    	processImage(index+1);
	  
			}


			//Set caption source
			imgc.src = '/images/ui/sliderTextBgOpacity80.png';
		    
		};

		//Set image source
		imgi.src = '/images/homepage/' + row[2];
	}
}

function showProgress(lang){
	//Set text
	$('#languageProgress span').html('translating page ( ' + lang + ' ) | please be patient...');

	//Get current #languageProgress Value
	var oldValue = $('#languageProgress').html();

	//Add watch to check when the contents of #languagProgress changes
	var changeId = window.setInterval(
		function()
		{
		  
			//Check old VS current
			if (oldValue !== curValue){
				//It has changed (i.e. translated)
				console.log("It's been changed. Stopping...(changeId: " + changeId + ")");
				clearInterval(changeId);       

				//Hide #languageProgress
				$('#languageProgress').fadeOut('slow');                  
			}

		}
	, 1000);

	//Show #languageProgress
	$ ('#languageProgress').show();

	//console.log("Initialising Google translator...");
	initTranslator();
}

function addHandler() {
	//Add event
	$('.goog-te-combo').change(function() {
		alert('Value change to ' + $(this).attr('value'));
	});
}

function hideLang() {
	//Hide the language Box
	$('#lang').css("display","none");
}

function showLang(){
	//Show the change language box
	if ($("#google_translate_element").length == 0) {
		initTranslator();
	}

	$('#lang').css("display","block");
}

function initTranslator(){
	//Add progress
	$('#lang').prepend('<img src="/images/animations/ajax-loader.gif" width="14px" height="14px"/>');

	//Ajax call
	$.ajax({
		url: "/ajax/googleTranslator.html",
		success: function(data) {
      
			$('#langInner').html(data);		
			//watchDropdown();	
		}
	});
}

function watchDropDown (){
	///WATCH: for google dropdown 
	var intervalId = window.setInterval(function(){
	
		//call your function here
		//console.log("Checking...(intervalid: " + intervalId + ")");

		if ($('.goog-te-combo').length > 0){

		  //remove progress
		  $('#lang img').remove();

		  //show langInner
		  $('#langInner').css("display","block");

		  //console.log("Control found | adding handler.....");
		  $('.goog-te-combo').change(function() {
			
			//console.log("Changing event...");
			var langId = $(this).attr('value');

			//console.log('Value change to ' + langId);

			$.cookie("tkwLanguage", langId, {expires:1, path:'/'});

			window.location = "";
			showProgress(langId);

			$('#lang').hide();
			
			
		  });

		  //console.log("Stopping...(intervalid: " + intervalId + ")");
		  clearInterval(intervalId);       
		}

	}, 500);
}
