

	   document.write("<script type='text/javascript' src='http://translate.wapo.com/translation/js/jquery/jquery.loading.js'></script>");
	   document.write("<script type='text/javascript' src='http://translate.wapo.com/translation/js/jquery/jquery-ui.js'></script>");
	   document.write("<script type='text/javascript' src='http://translate.wapo.com/translation/js/jquery/dialog-patch.js'></script>");
	   document.write("<script type='text/javascript' src='http://translate.wapo.com/translation/js/jquery.getUrlParam.js'></script>");
	   document.write("<script type='text/javascript' src='http://translate.wapo.com/translation/plugins/ckeditor-0.3/js/ckeditor/ckeditor.js'></script>");
	   document.write("<link href='http://translate.wapo.com/translation/translateCss?requestedHost="+encodeURIComponent(window.location.hostname)+"' rel='stylesheet' type='text/css' />");
	   document.write("<link href='http://translate.wapo.com/translation/css/redmond/jquery-ui-custom.css' rel='stylesheet' type='text/css' />");
        if (window.addEventListener)
        {
          window.addEventListener('load', isTranslationSupported, false);
        }
        else if (window.attachEvent)
        {
          window.attachEvent('onload', isTranslationSupported);
        }

    function isTranslationSupported(){
	    var contentsDivId = $("#translateJS").getUrlParam("contentsDivId");
	    var titleDivId = $("#translateJS").getUrlParam("titleDivId");
		initTranslation(titleDivId, contentsDivId);
	}

    function openwindow(){
        if(document.domain == '' || document.domain == ''){
            window.open('http://www.foreignpolicy.com/translation');
        }else{
            var $dialog = $('<div></div>').html('<p>This toolbar allows translation of the article below using a combination of machine translation and community translators. To improve any translation, click the "improve translation" link below any translated paragraph.</p><p>If you have any questions or feedback about this service, please email us <a href="mailto:support+lt@wapolabs.com"><strong>here</strong></a>.</p>').dialog({	autoOpen: true,title: 'What\'s this?',width: 400,modal: true,resize:'auto'});
        }
    }

	function initTranslation(titleDivId, contentsDivId){
		$("div#wapolabs_translateDiv").html('<div id="translateDivGrey"><p class="translateDivGrey-title"></p><p class="translateDivGrey-image"><big style="font-size:10px;cursor:pointer;" onclick="openwindow()">What\'s This?</big><button type="button" id="translationButton" class="rounded"><span>Translate</span></button></p></div>');
		$("div#wapolabs_translateDiv").append('<div id="translateDivBlue"><p class="translateDivBlue-title"></p><p class="translateDivBlue-image"><big style="font-size:10px;cursor:pointer;" onclick="openwindow()">What\'s This?</big><button type="button" id="returnButton" class="rounded"><span>Return</span></button></p></div>')
		postInitTranslation(titleDivId, contentsDivId)
	}

	function postInitTranslation(titleDivId, contentsDivId){
		var url = "http://translate.wapo.com/translation/translation/translationSupported";
		var targetLanguage = "en"
		var params = "url="+encodeURIComponent(window.location)+"&format=json&jsoncallback=?"
		$.getJSON(url, params, function(data){
		targetLanguage = data.targetLanguage
			if(data.isSupported && $("."+contentsDivId).length > 0){
					$("#wapolabs_translateDiv").css("display","block")
					$("#translateDivGrey").css("display","block")
					$("#translateDivBlue").css("display","none")
					$('p.translateDivGrey-title').html('<img src="http://translate.wapo.com/translation/images/icon_gray.gif" class="icntry" width="17" height="12" border="0"/> &nbsp;' + data.translateHeader+'<sup style="font-size:9px;"> &nbsp; BETA </sup>')
					$('#translationButton').unbind("click").click(function() {
						$(this).attr("src", "http://translate.wapo.com/translation/images/btn_translate_click.gif");
						translateRequest(titleDivId, contentsDivId, targetLanguage, data.originalHeader, data.displayLanguage);
					})

					//store non translated contents
					$("div#wapolabs_translateDiv").append("<div id='nonTranslatedContents'></div>")
					$("div#nonTranslatedContents").hide()

                    $('.'+ titleDivId+',.'+contentsDivId).find('p,h1,h2,h3,blockquote,li,div').filter(function(index) {return $.trim($(this).html()) != '' && $.trim($(this).html()) != '&nbsp;'&& $(this).find('p,h1,h2,h3,blockquote,li,div').length == 0 && $(this).parents('.TWIIGSPOLL').length == 0 && $(this).attr('class') != 'post_more'}).each(function(index, value) {
                            $('div#nonTranslatedContents').append("<"+this.nodeName.toLowerCase()+" id ='nonTranslatedPara"+index+"'>"+$(this).html() + "<\/"+this.nodeName.toLowerCase()+">")
                    });
			}
		});
	}

	function editTranslation(titleDivId, contentsDivId, dataDivId, contentId, targetLanguage, displayLanguage, textToContribute, articlePageId){
	var updateURL = "http://translate.wapo.com/translation/translation/updateTranslation";
	var logEventURL = "http://translate.wapo.com/translation/translation/logEditEvent";
	var params ="url="+encodeURIComponent(window.location)+"&targetLanguage="+encodeURIComponent(targetLanguage)+
				"&pageId="+encodeURIComponent(articlePageId)+"&format=json";
	    var $dialog = $("<div id='textToTranslate'></div>")
			.html("<table width='100%' cellpadding='0' cellspacing='0' border='0' class='transltrhdr'><tr><td class='translatedLang' width='26%' align='left'>Translated "+displayLanguage+"</td><td class='lastUpdatedBy' width='23%' align='right'>Last edited by Guest</td><td width='3%'></td><td class='translatedLang' width='24%' align='left'>Original English</td><td class='lastUpdatedBy' width='24%' align='right'>(for your reference)</td></tr></table><div class='nonTranslated-div'><p class='nonTranslated-para'>"+$('#nonTranslatedPara'+contentId).html()+"</p></div>")
			.dialog({
				autoOpen: true,
				title: 'Improve translated text <sup style="font-size:9px;"> &nbsp; BETA </sup>',
				width: 840,
				modal: true,
				resize:'auto',
				resizable: false,
				position: 'top',
				buttons: { "Cancel": function() { $(this).dialog("close"); $dialog.remove();},
						   "Save": function() {
												jQuery.ajax({
									               type: "GET",
									               url: updateURL,
									               dataType:"jsonp",
									               jsonp:"jsoncallback",
									               scriptCharset:"UTF-8",
									               data:"textContributed="+encodeURIComponent(CKEDITOR.instances['contributedText'].getData())+
														"&targetLanguage="+encodeURIComponent(targetLanguage)+"&url="+encodeURIComponent(window.location)+ "&pageId="+encodeURIComponent(articlePageId)+"&format=json",
									               success:function(data){
									                   //reflect the contributed text immediately
									                    var invoker = $('.'+ titleDivId+',.'+contentsDivId).find('p,h1,h2,h3,blockquote,li,div').filter(function(index) {return $.trim($(this).html()) != '' && $.trim($(this).html()) != '&nbsp;'&& $(this).find('p,h1,h2,h3,blockquote,li,div').length == 0 && $(this).parents('.TWIIGSPOLL').length == 0 && $(this).attr('class') != 'post_more'}).eq(contentId);
									                    invoker.html(data.contents.result.translatedContents);
									                    var textToContribute =  invoker.html();
                                                         invoker.html(jQuery(":first", invoker).html());
                                                         invoker.append("<br><span class='datacntnts'><img src='http://translate.wapo.com/translation/images/icon_gray.gif' width='17' height='12' class='icntry' border='0'/>&nbsp; <a  target=_blank id='"+contentId+"ContributeLink' class='contibutelnk-popup'><b>Improve translation</b></a></span>")
                                                         $('a#'+contentId+'ContributeLink').unbind("click").click(function() { editTranslation(titleDivId, contentsDivId, dataDivId, contentId, targetLanguage, displayLanguage, textToContribute, data.contents.result.pageId); })
                                                            //show hand pointer on mouse over
                                                            $('a#'+contentId+'ContributeLink').hover(function() {
                                                             $('a#'+contentId+'ContributeLink').css("cursor","pointer");
                                                         });
														$dialog.dialog("close");
														$dialog.remove();
									               },
									               error:function (xhr, ajaxOptions, thrownError){
									               		alert("Translation services are down. Please contact admin");

									               }
									            });
									           }
						  },

				open: function(event, ui){
											$('.ui-dialog-buttonpane').find('button:contains("Cancel")').addClass('ui-dialog-cancel');
											jQuery.ajax({
                                                  type: "GET",
                                                  url: logEventURL,
                                                  dataType:"jsonp",
                                                  jsonp:"jsoncallback",
                                                  data: params,
                                                  success:function(data){
                                                  },
                                                  error:function (xhr, ajaxOptions, thrownError){
                                                      alert("Translation services are down. Please contact admin");
                                                  }
									        });
											var editor=CKEDITOR.instances['contributedText'];
											if (editor){
												CKEDITOR.remove(editor);
											}
                                            $("div#textToTranslate").append("<div id='textToContribute'></div>")
					                        $("div#textToContribute").html(textToContribute).hide();
											var fragment = "<textarea name='contributedText'/><script type='text/javascript'>CKEDITOR.replace( 'contributedText',{customConfig : 'http://translate.wapo.com/translation/js/ckeditorConfig.js',height:'227', data:'loading'});CKEDITOR.instances['contributedText'].setData($('div#textToContribute').html(), function(){CKEDITOR.instances['contributedText'].focus();});CKEDITOR.instances['contributedText'].on('key', function (e) {if(CKEDITOR.instances['contributedText'].getData().length > 5000){alert('You have exceeded the maximum number of characters allowed');}});</script>";
											$(this).append("<div id='conht'>"+fragment+"</div>");											

										 }
			})
			$dialog.bind( "dialogclose", function(event, ui) {
			  	$dialog.remove();
			});

	}

	function translateRequest(titleDivId, contentsDivId, targetLanguage, returnArticleHeader, displayLanguage){
	   $("div#wapolabs_translateDiv").loading({img:'http://translate.wapo.com/translation/images/loading.gif',text:'Loading',align: 'center'});
		var url = "http://translate.wapo.com/translation/translation/translateUrl";
		var idsToTranslate = $.makeArray(titleDivId+","+contentsDivId)
		var params ="url="+encodeURIComponent(window.location)+"&targetLanguage="+encodeURIComponent(targetLanguage)+
					"&idsToTranslate="+encodeURIComponent(idsToTranslate)+"&format=json";
        jQuery.ajax({
              type: "GET",
              url: url,
              dataType:"jsonp",
			  jsonp:"jsoncallback",
              data: params,              
              success:function(data){
                //append contribute link to each content
                $('.'+ titleDivId+',.'+contentsDivId).find('p,h1,h2,h3,blockquote,li,div').filter(function(index) {return $.trim($(this).html()) != '' && $.trim($(this).html()) != '&nbsp;'&& $(this).find('p,h1,h2,h3,blockquote,li,div').length == 0 && $(this).parents('.TWIIGSPOLL').length == 0 && $(this).attr('class') != 'post_more'}).each(function(index, value) {
                    if(data[index]){
                        var dataDivId = contentsDivId;
                        if($(this).parents('.'+titleDivId).length > 0){
                            dataDivId = titleDivId
                        }
                        updateContentData(titleDivId, contentsDivId, dataDivId, $(this), index, data, targetLanguage, displayLanguage)
                    }
                });
                $("#translateDivGrey").css("display","none")
                $("#translateDivBlue").css("display","block")
                $('p.translateDivBlue-title').html('<img src="http://translate.wapo.com/translation/images/icon_blue.gif" class="icntry" width="17" height="12" border="0"/> &nbsp; ' + returnArticleHeader +'<sup style="font-size:9px;"> &nbsp; BETA </sup>')
                $('#returnButton').unbind("click").click(function() {
                    $(this).attr("src", "http://translate.wapo.com/translation/images/btn_return_click.gif");
                    viewOriginal(titleDivId, contentsDivId);
                })
                $("div#wapolabs_translateDiv").loading( null);
              },
              error:function (xhr, ajaxOptions, thrownError){
                  alert("Translation services are down. Please contact admin");
              }
        });
	}

	function updateContentData(titleDivId, contentsDivId, dataDivId, invoker, index, data, targetLanguage, displayLanguage){
		 invoker.html(data[index].translatedContents);
		 var textToContribute =  invoker.html();
         invoker.html(jQuery(":first", invoker).html());
         invoker.append("<br><span class='datacntnts'><img src='http://translate.wapo.com/translation/images/icon_gray.gif' width='17' height='12' class='icntry' border='0'/>&nbsp; <a  target=_blank id='"+index+"ContributeLink' class='contibutelnk-popup'><b>Improve translation</b></a></span>")
         $('a#'+index+'ContributeLink').unbind("click").click(function() { editTranslation(titleDivId, contentsDivId, dataDivId, index, targetLanguage, displayLanguage, textToContribute, data[index].pageId); })
            //show hand pointer on mouse over
            $('a#'+index+'ContributeLink').hover(function() {
             $('a#'+index+'ContributeLink').css("cursor","pointer");
         });
	}

	function viewOriginal(titleDivId, contentsDivId){
		$('.'+ titleDivId+',.'+contentsDivId).find('p,h1,h2,h3,blockquote,li,div').filter(function(index) {return $.trim($(this).html()) != '' && $.trim($(this).html()) != '&nbsp;'&& $(this).find('p,h1,h2,h3,blockquote,li,div').length == 0 && $(this).parents('.TWIIGSPOLL').length == 0 && $(this).attr('class') != 'post_more'}).each(function(index, value) {
		        $(this).html($('div#nonTranslatedContents').children().eq(index).html())

        });
		postInitTranslation(titleDivId, contentsDivId)
	}
