/*

		Author: Thomas Melvin
		http://www.reusserdesign.com/
		
		Copyright (c) 2009, Reusser Design, LLC 
		All rights reserved.
		
		Redistribution and use in source and binary forms, with or without modification, are 
		permitted provided that the following conditions are met:
		
		    * Redistributions of source code must retain the above copyright notice, this list 
		      of conditions and the following disclaimer.
		    * Redistributions in binary form must reproduce the above copyright notice, this 
		      list of conditions and the following disclaimer in the documentation and/or other
		      materials provided with the distribution.
		    * Neither the name of the organization nor the names of its contributors may be 
		      used to endorse or promote products derived from this software without specific 
		      prior written permission.
		
		THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
		EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
		MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
		COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
		EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
		SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
		HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR 
		TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
		EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

	//Load google js api
	google.load("language", "1");
	
	//Save existing onload function (if exists)
	var o = window.onload;
	
	//Declare Application Variables
	var Text_Elements = [], currently_translating = 0, current_language = 'en', translate_to_language = 'es', error_timeout = false, element_filter = 'script,language';
	
	//Set window onload function
	window.onload = function() {
		
		//Check for language
		if( location.hash != '' ) {
		
			var hash = location.hash, language = '';
			
			if( hash.indexOf('-translate') != -1 ) {
			
				translate_to_language = hash.substring(1, hash.indexOf('-translate'));
				get_header_translation();
				update_page_links();
						
			}
			
		}
	
		//Run the existing onload function (if existed)
		if( typeof o == 'function' ) {
			o();
		}

	};

	//Get All TEXT based Elements
	function get_text_elements( Element, pElement ) {
	
		if( Element.id == 'language' || Element.nodeName == 'SCRIPT' ) {
			return false;
		}
	
		if( Element.childNodes.length > 0 ) {
			
			for( var x = 0; x < Element.childNodes.length; x++ ) {
				get_text_elements(Element.childNodes[x], Element.childNodes[x].parentNode);
			}
			
		}
		
		//Do not add text elements that are empty
		else if( Element.nodeName == '#text' && Element.nodeValue.replace(/^\s+|\s+$/g,"") != '' ) {
			
			//We can not pass a string over 1000 characters, so divide string up at an end of sentence

			if( Element.nodeValue.length > 900 ) {
			
				var Tmp = encapsulate_string(Element);
				var span = document.createElement('span');
				
				for( var x = 0; x < Tmp.length; x++ ) {
					span.appendChild(Tmp[x]);
					Text_Elements.push(Tmp[x]);
				}
				
				pElement.insertBefore(span, Element);
				pElement.removeChild(Element);

			}
			else {

				Text_Elements.push(Element);			
			}

		}

		return false;
		
	}
	
	function encapsulate_string( Element ) {
	
		//Divide string up with a maximum of 450 characters a piece
		var split_string = Element.nodeValue, Strings = [], tmp = '';
		
		while( split_string.length > 0 ) {
		
			if( split_string.length > 450 ) {

				tmp = split_string.substring(0, 450);
				tmp = tmp.substring(0, tmp.lastIndexOf('. '));
				split_string = split_string.substring(tmp.length, split_string.length);
				Strings.push(document.createTextNode(tmp));
				
			}
			else {
				Strings.push(document.createTextNode(split_string));
				split_string = '';
			}

		}
		
		return Strings;
	
	}
	
	//Translate text elements into different language
	function translate_text(Element) {
		
		//Clear error_message
		if( error_timeout != false ) {
			clearTimeout(error_timeout);
		}
		
		var text = Element.nodeValue;

		//Send text off to google to be translated		
		google.language.translate(text, current_language, translate_to_language, function(result) {

			//Store translated text
			if( !result.error ) {
			
				var span = document.createElement('span');
				span.innerHTML = result.translation;
				//!
				if( Text_Elements[currently_translating].parentNode ) {
					Text_Elements[currently_translating].parentNode.replaceChild(span, Text_Elements[currently_translating]);
				}
			
			}
			else {
				
				translate_text(Text_Elements[currently_translating]);
				return false;
				
			}
			//Translate next element
			if( currently_translating < (Text_Elements.length - 1) ) {
			
				currently_translating++;
				translate_text(Text_Elements[currently_translating]);
				update_status(currently_translating);
				return false;
				
			}
			else {
			
				//Set local links to translate onload
				update_page_links();
				
				//Remove translating screen
				remove_translating_screen();
				
			}
			
		});
		
	}
	
	//This function has one purpose of translating "Translatingi Page" and updating status window
	function get_header_translation() {
	
		google.language.translate('Translating Page', current_language, translate_to_language, function(result) {
		
			if( !result.error ) {
		
				//Load translating screen
				load_translating_screen(result.translation);
							
			}
			
		});		
	
	}
	
	//Replace the old text with the translated TextNode
	function update_page_text() {
		
		for( var x = 0; x < Text_Elements.length; x++ ) {
		
			var span = document.createElement('span');
			span.innerHTML = Text_Elements[x]['translated_text'];
			//!
			if( Text_Elements[x].parentNode ) {
				Text_Elements[x].parentNode.replaceChild(span, Text_Elements[x]);
			}

		}

		//Remove translating screen
		remove_translating_screen();
	
	}
	
	function update_page_links() {
	
		var links = document.getElementsByTagName('a');
		
		for( var x = 0; x < links.length; x++ ) {
			
			var link = links[x].href;
			
			//Dont add translations to mailto links, links to other servers, or .pdf files
			if( link.indexOf(location.hostname) != -1 && link.indexOf('mailto:') == -1 && link.indexOf('.pdf') == -1 ) {
				
				if( link.indexOf('?') != -1 && link.indexOf('-translate') == -1 ) {
				
					var part1 = part2 = '';
					part1 = link.substring(0, link.indexOf('?') );
					part2 = links[x].href.substring(links[x].href.indexOf('?'), links[x].href.length);
					links[x].href = part1+'#'+translate_to_language+'-translate'+part2;
					
				}
				else if( links[x].href.indexOf('-translate') == -1 ) {
					links[x].href += '#'+translate_to_language+'-translate';
				}

			}

		}
		
		if( document.getElementById('language') ) {
			document.getElementById('language').innerHTML = '<a href="'+location.toString().replace(location.hash, '')+'">Back to English</a>';
		}
		
	}
	
	//This function builds and styles the translation screen
	function load_translating_screen( header_text ) {

		get_text_elements(document.getElementsByTagName('html')[0], false);

		var body = document.getElementsByTagName('body')[0], width = document.body.clientWidth, scroll_dimensions = get_scroll();
			
		//Build expose` background
		body.style.overflow = 'hidden';
		
		var screen = document.createElement('div');
		screen.id="translating_screen", screen.style.position = 'absolute', screen.style.left = 0, screen.style.top = 0;
		screen.style.background = '#000000', screen.style.height = '2500px', screen.style.width = '100%';
		screen.style.zIndex = '10000', screen.style.opacity = '.5', screen.style.filter = 'alpha(opacity=50)';
		body.appendChild(screen);
		
		//Build status window
		var status = document.createElement('div');
		status.id = 'status_window', status.style.position = 'absolute', status.style.left = (width-400)/2+'px', status.style.top = (scroll_dimensions.top+100)+'px';
		status.style.background = '#ffffff', status.style.zIndex = '10001', status.style.width = '400px', status.style.height='175px';
		body.appendChild(status);
		
		//Build header
		var header = document.createElement('h2');
		header.style.color = '#444444', header.style.padding = '10px 20px', header.style.margin = '0px 10px';
		header.innerHTML = header_text+'...';
		status.appendChild(header);
		
		//Build Progress Bar
		var progress_bar = document.createElement('div');
		progress_bar.id = 'translation_progress_bar';
		progress_bar.style.background = '#939393', progress_bar.style.border = '1px solid #222', progress_bar.style.width = '300px';
		progress_bar.style.height = '25px', progress_bar.style.margin = '20px auto';
		
		var progress = document.createElement('div');
		progress.id = 'translation_progress';
		progress.style.background = '#655ef4', progress.style.width = '0px', progress.style.height = '25px';
		progress_bar.appendChild(progress);
		status.appendChild(progress_bar);
		
		//Build Progress Percentage
		var progress_percent = document.createElement('h1');
		progress_percent.style.border = 'none', progress_percent.style.color = '#655ef4', progress_percent.style.margin = '0 60px';
		progress_percent.style.fontSize = '30px';
		var percent = document.createElement('span');
		percent.id = 'translate_percentage', percent.appendChild(document.createTextNode('0'));
		progress_percent.appendChild(percent);
		progress_percent.appendChild(document.createTextNode('%'));
		
		status.appendChild(progress_percent);
		
		//Bottom right corner "Translating Page" text
		var text = document.createElement('span');
		text.style.position = 'absolute', text.style.bottom = '0px', text.style.right = '0px', text.style.padding = '5px';
		text.appendChild(document.createTextNode('Translating Page'));
		
		status.appendChild(text);
		
		//Finally, start doing the translations
		translate_text( Text_Elements[0] );
		
	}
	
	//Status = currently_translating element
	function update_status( status ) {
		
		var total_elements = Text_Elements.length;
		var percentage = Math.round((status/total_elements)*100);
		document.getElementById('translate_percentage').innerHTML = percentage;
		document.getElementById('translation_progress').style.width = Math.round((percentage/100)*300)+'px';
		
	}
	
	function remove_translating_screen() {
	
		document.getElementById('translating_screen').style.display = 'none';
		document.getElementById('status_window').style.display = 'none';
		document.getElementsByTagName('body')[0].style.overflow='scroll';

	}

	function get_scroll() {
	
		var left = 0, top = 0;
		
		if( typeof( window.pageYOffset ) == 'number' ) {
			top = window.pageYOffset;
			left = window.pageXOffset;
		} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
			top = document.body.scrollTop;
			left = document.body.scrollLeft;
		} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
			top = document.documentElement.scrollTop;
			left = document.documentElement.scrollLeft;
		}
		
		return { left:left, top:top };
		
	}	