(function() {
if (!("console" in window) || !("firebug" in console)) {
	var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
				 "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
	window.console = {};
	for (var i = 0; i < names.length; ++i)
		window.console[names[i]] = function() {};
};

//todo: tak nie wolno robić
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
};

function getUniqueId() {
	return (new Date()).getTime();
}

function loadJS(url) {
	// TO AVOID DOUBLE REQUESTS AT IE
	var id = "script" + getUniqueId();
	url += "&scriptId=" + id;
	var script = document.createElement('script');
	script.setAttribute("type", "text/javascript");
	script.setAttribute("src", url);
	script.setAttribute("id", id);
	if (typeof script != "undefined")
		document.getElementsByTagName("head")[0].appendChild(script);
}

function loadCSS(url) {
	var style = document.createElement('link');
	style.setAttribute("type", "text/css");
	style.setAttribute("rel", "stylesheet");
	style.setAttribute("href", url);
	if (typeof style != "undefined")
		document.getElementsByTagName("head")[0].appendChild(style);
}

function hour2float(hour) {
    var splt = hour.split(":");
    var hour = parseFloat(splt[0]);
    var minute = parseFloat(splt[1]);
    return (hour + (minute/60.0));
}

function extract_end_hour(daterange) {
    var end_date = jQuery.trim(daterange.split("to")[1]);
    return jQuery.trim(end_date.split(" ")[1]);
}

function extract_day(daterange) {
    var end_date = jQuery.trim(daterange.split("to")[1]);
    return jQuery.trim(end_date.split(" ")[0]);
}

function detectServer() {
    var ctcServer = null;

	var html = document.getElementsByTagName("html").item(0);
	var head = html.getElementsByTagName("head").item(0);
	var body = html.getElementsByTagName("body").item(0);

	// detect ctcServer in head
	var scripts = head.getElementsByTagName("script");
	for(i=0; scripts.item(i); i++) {
		var script = scripts.item(i);
		if(script.getAttribute("type") == "text/javascript" &&
		   script.getAttribute("src") &&
		   script.getAttribute("src").indexOf("ctc.js") >= 0){
			ctcServer = script.getAttribute("src");
			ctcServer = ctcServer.substring(0, ctcServer.indexOf("ctc.js") - 1);
		}
	}

	// detect ctcServer in body
	scripts = body.getElementsByTagName("script");
	for(i=0; scripts.item(i); i++) {
		var script = scripts.item(i);
		if(script.getAttribute("type") == "text/javascript" &&
		   script.getAttribute("src") &&
		   script.getAttribute("src").indexOf("ctc.js") >= 0){
			ctcServer = script.getAttribute("src");
			ctcServer = ctcServer.substring(0, ctcServer.indexOf("ctc.js") - 1);
		}
	}

	return ctcServer;
}

function setUpCampaignTracker(trackerId, campaignId) {
	var tracker = null;
	if(window._gat == null) {
		console.debug("still no ga, building fake tracker");
		tracker = {};
		tracker._trackPageview = function(msg) {};
	} else {
		tracker = _gat._getTracker(trackerId);
		tracker._setDomainName("none");
	}
    tracker._trackCTCEvent = function(event) {
        if(event == "wrong_campaign_id") {
            tracker._trackPageview("/" + event);
            console.debug("ctc event sent:", event);
        } else {
            tracker._trackPageview("/" + campaignId + "/" + event);
            console.debug("ctc event sent:", campaignId, event);
        }
    };
	return tracker;
};

var ourjQuery = false;
function importJQuery() {
    if(window.jQuery == null) {
		console.debug("no jquery, importing!");
		var jQueryUrl = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js";
		document.write(unescape("%3Cscript src='" + jQueryUrl + "' type='text/javascript'%3E%3C/script%3E"));
		ourjQuery = true;
	}

}

var ourGA = false;
function importGA() {
	if(window._gat == null) {
		console.debug("no ga, importing!");
		var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
		document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
        ourGA = true;
	}
}

window._CTCheckScripts = function() {
	var jQueryReady = false;
	var GAReady = false;
	var period = 100;
	var iterations = 0;

	return function(checkJQuery, checkGA, meat) {
		if(window.jQuery != null || !checkJQuery) {
			jQueryReady = true;
		}
		if(window._gat != null || !checkGA) {
			GAReady = true;
		}
		if(jQueryReady && GAReady) {
			console.debug("Deps ready");
			meat(); 
		} else if(jQueryReady && iterations*period > 2000) {
			console.debug("Can't fetch ga. Proceeding without it.");
			meat();
		} else {
			iterations++;
			console.debug("Deps not ready, jQuery: " + jQueryReady + 
						  ", GA: " + GAReady);
			window.setTimeout('_CTCheckScripts()', period);
		}
	};
}();

window._initCTC = function(params) {
	var emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	var countryCodeReg = /^[\+][0-9]{1,4}$/;
	var phoneReg = /^[0-9 +]{1,20}$/;

	var tracker = null;
	var campaignId = params.campaign;
	var formLang = params.formLang ? params.formLang : null;
	var logo = params.logo ? params.logo : null;
	var ask4ClientLang = params.ask4ClientLang ? params.ask4ClientLang : false;
	var offererLang = params.offererLang ? params.offererLang : null;
	var offererEmail = params.offererEmail ? params.offererEmail : null;
	var offererTimezone = params.offererTimezone ? params.offererTimezone : "";
	var offererServiceName = params.offererServiceName ? params.offererServiceName : null;

	var clientTimezone = params.clientTimezone ? params.clientTimezone : "";
	var clientServiceName = params.clientServiceName ? params.clientServiceName : null;

	var ctcServer = detectServer();

	var mltb = params.mltb; 

	if(ctcServer == null) {
		console.warn("No ctcServer defined.");		
	} else if(ctcServer == "") {
		console.debug("Relative ctcServer location found.");		
	} else {
		console.debug("ctcServer: ", ctcServer);
	}

	var invalidStyle = {'background-color' : '#FFAFAF'};
	var validStyle = {'background-color' : '#FFF'};

    function addFormHandlers(elems, template) {

		var currentDay = template.find("input[name='currentDay']").val();
		var currentHour = parseInt(template.find("input[name='currentHour']").val());
		var officeHourStart = template.find("input[name='officeHourStart']").val();
		var officeHourEnd = template.find("input[name='officeHourEnd']").val();

		elems.each(function(e) {
			var widget = template.clone(true);

			jQuery(this).append(widget);

			var day = widget.find("select[name='day']");
			var tz = widget.find("[name='clientTimezone']");
			var seltz = widget.find("select[name='clientTimezone']");

			var email = widget.find("input[name='email']");
			var countryCode = widget.find("input[name='countryCode']");
			var phone = widget.find("input[name='phone']");

			day.change(function() {
			    if(day.val() == 'asap') {
                    seltz.attr("optional","")
					seltz.hide();
				} else {
                    seltz.attr("optional",undefined)
					seltz.show();
				}
			});

			day.change();

			widget.show();

			widget.find("input[name='countryCode']")
				.val(widget.find("select[name='countryCodeSelector']").val());

			widget.find("input[name='countryCode'], select[name='countryCodeSelector']")
				.bind('load focus keyup change blur', function() {
						widget.find("input[name='countryCode'], select[name='countryCodeSelector']")
							.val(jQuery(this).val());
			});

			widget.find(".ctcReset").click(function() {
				// RESETING VARS
				widget.find(".ctcField:not(.ctcDontReset)").each(function() {
					jQuery(this).val('');
				});

				day.change();

				widget.find(".ctcMessage").hide();
                widget.find("#submit-result-for-selenium").val('0');
				widget.find(".ctcBody").show();

				if(widget.find(".ctcClose").html() != null){
					widget.find(".ctcClose").show();
					jQuery("#wiCtc", top.document).hide('slow');
				}
			});

			widget.find(".ctcSubmit").click(function() {
				// VALIDATION
				var formValid = true;

    			var widgetHeight = widget.find(".ctcBody").height();
    			widget.find(".ctcMessage").css('height', widgetHeight);

				widget.find(".ctcField").css(validStyle);

				widget.find(".ctcField").each(function() {
					var field = jQuery(this);
					//console.debug(field.attr("name"), field.val(), field.val() == '', !field.attr('mandatory') == 'false');
				    if(field.val() == '' && field.attr('optional') == undefined) 					    
					{
						console.debug("invalid:", field.attr("name"), "=", field.val());
						field.css(invalidStyle);
						formValid = false; 
					}
				});

                if(!countryCodeReg.test(countryCode.val())) {
					console.debug("invalid: country code");
					countryCode.css(invalidStyle);
					formValid = false;
                }

                if(!phoneReg.test(phone.val())) {
					console.debug("invalid: phone number: " + phone.val());
					phone.css(invalidStyle);
					formValid = false;
                }

				if(email.size() && !emailReg.test(email.val())) {
					console.debug("invalid: email");
					email.css(invalidStyle);
					formValid = false;
				}

				if(day.val() != 'asap') {
                    if (!tz.val()) {
                        console.debug("invalid: timezone");
                        tz.css(invalidStyle); 
                        formValid = false; 
                    }
                    var formHour = hour2float(extract_end_hour(day.val()));
                    var formOffsetTz = tz;
                    if (formOffsetTz.length > 0 && formOffsetTz[0].value) {
                        formOffsetTz = parseFloat(
                            tz.find("[value='"+formOffsetTz[0].value+"']")
                            .attr("offsettz"));
                    } else {
                        formOffsetTz = 0;
                    }
                    formHour -= formOffsetTz;
                    formHour -= formHour > 24 ? 24 : 0;
                    if(extract_day(day.val()) == currentDay && 
                       (formHour <= currentHour || 
                        currentHour >= parseInt(officeHourEnd) || 
                        currentHour <= parseInt(officeHourStart))) 
                    { 
                        console.debug("invalid: dayrange");
                        day.css(invalidStyle); 
                        formValid = false; 
                    }
				}

				if(formValid) {
					widget.find(".ctcLoading").show();
					widget.find(".ctcBody").hide();
					widget.find(".ctcClose").hide();

					formId = "submitted" + getUniqueId();

					widget.attr("id", formId);

					submitUrl = "";

					widget.find(".ctcField").each(function() {
					    var field = jQuery(this);
						if(field.val() != '') {
							submitUrl += "&" + field.attr("name") + "=" + encodeURIComponent(field.val());
						}
				    });

					submitUrl += "&formId=" + formId;

					submitUrl = ctcServer + "/ctc/submit?" + submitUrl.substring(1);

					console.debug('Sending: ' + submitUrl);

					window._formSubmitted = function (formId, scriptId, result, reqId) {
						console.debug('Data sent and answer:', result, 'received for form: ', 
									  formId, ' via script:', scriptId);

						jQuery("#" + scriptId).remove();
						var widget = jQuery("#" + formId);
						
						if(result == 'payment_summary') {
							tracker._trackCTCEvent("submitted");
							jQuery("#_ctcFakeForm")
							.attr("action", ctcServer + "/ctc/summary")
							.empty()
							.append("<input name='id' value='" + reqId + "'>")
							.submit();
						} else {
							widget.find(".ctcLoading").hide();
							widget.removeAttr("id");
							if(result == 'saved') {
								tracker._trackCTCEvent("submitted");
								widget.find(".ctcOK").show();
                                widget.find("#submit-result-for-selenium").val('1');
							} else if(result == 'not_found') {
								widget.find(".ctcErrorNotFound").show();
							} else if(result == 'not_enabled') {
								widget.find(".ctcErrorNotEnabled").show();
							} else if(result == 'exception') {
								widget.find(".ctcErrorException").show();
							} else {
								widget.find(".ctcErrorException").show();
							}
						}
					};
                    loadJS(submitUrl);
				} else {
					console.debug(widget);
				}
			});//widget.find(".ctcSubmit")
		}); //elems.each(
	} //addFormHandlers

	window._initCTCForm = function (found, enabled, gaTrackerId, 
									formHtml, formStyle, formStyleGlobal,
								    mltbGlossary, mltbFix) {
		function meat() {

			if(ourjQuery){ jQuery.noConflict(); }

  		    tracker = setUpCampaignTracker(gaTrackerId, campaignId);

			if(mltb) {
				mltb.callback(tracker, mltbGlossary, mltbFix);
                if(mltb.httpsMonitorMode) {
                    return;
                }
            }
			function initForm(template) {
				console.debug("init form called:", campaignId);

				var formEventSent = false;

				var are_styles = jQuery('.ctcWidget').css('backgroundColor');

				if(are_styles == 'transparent' || are_styles == 'rgba(0, 0, 0, 0)'){
					jQuery("head").append('<style type="text/css">' + formStyle + '</style>');
				}
				jQuery("head").append('<style type="text/css">' + formStyleGlobal + '</style>');

				// FORMS OPENED BY CTC BUTTONS	
				jQuery("body").append('<div id="wiCtc" style="display: none; position: absolute;"></div>');
				addFormHandlers(jQuery("#wiCtc"), template);

				jQuery(".ctc", top.document).each(function() {
					jQuery(this).click(function() {
					    if(enabled && !formEventSent) {
						    tracker._trackCTCEvent("form");
						}

                        // POSITION OF FLOATING WIDGET
                        var scrollTop;
            			if(self.pageYOffset){
            				scrollTop = self.pageYOffset;
            			}else if(document.documentElement && document.documentElement.scrollTop){ // Explorer 6 Strict
            				scrollTop = document.documentElement.scrollTop;
            			}else if(document.body){ // all other Explorers
            				scrollTop = document.body.scrollTop;
            			}
						var elementPosition = jQuery(this).offset();
						var widgetHeight = jQuery("#wiCtc").height();
						var elementHeight = jQuery(this).height();
						var windowHeight = jQuery(window).height();
                        var spaceAbove = elementPosition.top - scrollTop;
                        var spaceBelow = windowHeight - spaceAbove - elementHeight;

						if(spaceBelow >= widgetHeight){
						    widgetY = elementPosition.top + elementHeight;
						}else if(spaceAbove >= widgetHeight){
						    widgetY = elementPosition.top - widgetHeight;
						}else{
						    if(widgetHeight <= windowHeight) widgetY = scrollTop + (windowHeight - widgetHeight) / 2;
                            else widgetY = scrollTop;
						}

                        // SHOWING WIDGET
						jQuery("#wiCtc").show();
					    jQuery("#wiCtc").css('top', widgetY + 'px'); 
						jQuery("#wiCtc").css('left', elementPosition.left + 'px');

						var close = jQuery("#wiCtc").find(".ctcClose");
						jQuery(close).click(function() {
								jQuery("#wiCtc").hide();
						});
				    });
			    });

				// INLINE FORMS
				if(mltbMode){
					var close = jQuery(".ctcClose");
					jQuery(close).click(function() {
						jQuery(".ctc-form").hide();
					});
				}else{
				    jQuery(".ctcClose", template).remove();
			    }

				addFormHandlers(jQuery(".ctc-form"), template);
				if(enabled && jQuery(".ctc-form", top.document).length) {
					tracker._trackCTCEvent("form");
					formEventSent = true;
				}
			}

			console.debug("_initCTCForm called: ", campaignId, found, enabled);
			var formTemplate = document.createElement("div");
			formTemplate.style.display = "none";
			document.body.appendChild(formTemplate);
			jQuery(formTemplate).html(formHtml);

			if(!found) {
			    tracker._trackCTCEvent("wrong_campaign_id");
		    } else {
			    tracker._trackCTCEvent("partnerpage");
			    if(!enabled) {		      
				    tracker._trackCTCEvent("disabled");
			    }
			}
			initForm(jQuery(formTemplate));
			jQuery(".ctcPartnership").click(function() {
			    tracker._trackCTCEvent("partnership");					
			});
			jQuery("body").append("<form id='_ctcFakeForm' method='get' style='display: none'> </form>");
		};//meat

		_CTCheckScripts(true, true, meat);
	}; //window._initCTCForm
	
	importJQuery();
	importGA();

	formUrl = ctcServer +
		      "/ctc/form?campaign=" + campaignId + 
		      "&ask4ClientLang=" + ask4ClientLang + 
		      "&formLang=" + formLang +
		      "&clientTimezone=" + clientTimezone +
		      "&offererTimezone=" + offererTimezone +
		      "&offererLang=" + offererLang + 
		      "&offererEmail=" + encodeURIComponent(offererEmail);

	if(clientServiceName) {
		formUrl += "&clientServiceName=" + clientServiceName;
	}

	if(offererServiceName) {
		formUrl += "&offererServiceName=" + offererServiceName;
	}		

	if(logo) {
		formUrl += "&logo=" + logo;
	}		

	if(mltb) {
		formUrl += "&mltb=" + mltb.languageFrom + "," + 
			mltb.languageTo;
	}		

	console.debug("including form: " + formUrl);

	document.write(unescape("%3Cscript defer src='") + formUrl + unescape("' type='text/javascript'%3E%3C/script%3E"));

}; //window._initCTC

window._initCTCRequest = function(params) {
	var tracker = null;
	var ctcServer = detectServer();

	var campaignId = params.campaign;

	window._sendCTCRequest = function(params) {
		var ctcString = detectServer() + '/ctc/submit';
        ctcString += '?countryCodeSelector=';
        ctcString += '&countryCode=';
        ctcString += '&phone=' + params.phone;
        ctcString += '&campaign=' + campaignId;
        ctcString += '&clientLang=' + params.language;
        ctcString += '&day=' + params.date;
        ctcString += '&hour=' + params.hour;
        ctcString += '&clientTimezone=Europe/Paris'; // GET

		if(params.callback) {
			window._formSubmitted = function (formId, scriptId, result) {
				console.debug('Data sent and answer:', result, 'received via script:', scriptId);

				if(tracker && result == 'saved') {
					tracker._trackCTCEvent("submitted");
				}
				params.callback();
			};
		} else {
			window._formSubmitted = function (formId, scriptId, result) {};
			if(tracker) {
				tracker._trackCTCEvent("submitted");
			}
		}
		loadJS(ctcString);
		return true;
	};

	window._initCTCTracker = function(found, enabled, gaTrackerId) {
		console.debug("tracker received: " + gaTrackerId);
		function meat() {
			tracker = setUpCampaignTracker(gaTrackerId, campaignId);
			tracker._trackCTCEvent("partnerpage");
		};
		_CTCheckScripts(false, true, meat);
	};

	importGA();

	trackerUrl = ctcServer + "/ctc/tracker?campaign=" + campaignId;

	console.debug("asking for tracker: " + trackerUrl);
	document.write(unescape("%3Cscript defer src='" + trackerUrl + "' type='text/javascript'%3E%3C/script%3E"));
}; //window._initCTCRequest

var mltbMode = false;
window._initMLTB = function(params){
    mltbMode = true;

    var mltbServer = detectServer() + '/';

    var httpMode = (document.location.protocol == "https:") ? false : true;
    //var httpMode = (document.location.href.indexOf('www.') == "-1") ? false : true;
    if(!httpMode) console.warn('Yes, we are in HTTPS mode now.');

    // params
	var campaignId = params.campaignId;
	var languageFrom = params.languageFrom;
	var languageTo = params.languageTo;
	var skin = params.skin ? params.skin : 'default';

    console.debug('MLTB mode: ' + campaignId + ', ' + languageFrom + ', ' + languageTo);

    function setInfo(info){
        if(info == 'translated') jQuery('#preloader').show().html('&nbsp;');
        else jQuery('#preloader').show().html(info);
    }

	function checkGoogleJSApiReady(callback) {	
		// check if scripts are loaded
		window._checkGoogleJSApiReady = function() {
    		// check for Google Translate
    		if(window.google != null && window.google.load != null) {
    			console.debug("Google JSApi ready");
    			callback(); 
    		} else {
    			console.debug("Google JSApi not ready");
    			window.setTimeout('checkScripts()', 100);
    		}
		};
		window._checkGoogleJSApiReady();
	}
	
    var translation = function(text){
		var translations = {
			en: {please_wait: 'Please wait...',
				 button: 'Questions? Click here! We will call you back for free!',
				 translated_by: 'Translated by',
				 frames_error: 'Error. Only frameless pages are supported.',
				 translating: 'Translating'},
			de: {please_wait: 'Einen Moment bitte..',
				 button: 'Fragen? Klicken Sie hier! Wir rufen Sie kostenlos zurück!',
				 translated_by: 'Übersetzt von',
				 frames_error: 'Error. Only frameless pages are supported.',
				 translating: 'Übersetzung läuft'},
			fr: {please_wait: 'Veuillez attendre..',
				 button: 'Des questions ? Cliquez ici! Nous vous rappelons gratuitement!',
				 translated_by: 'Traduit par',
				 frames_error: 'Error. Only frameless pages are supported.',
				 translating: 'Traduction en cours'},
			es: {please_wait: 'Espere, por favor...',
				 button: '¿Preguntas? Pulse aquí. Le llamamos de vuelta gratuítamente!',
				 translated_by: 'Traducido por',
				 frames_error: 'Error. Only frameless pages are supported.',
				 translating: 'Traduciendo'},
			pl: {please_wait: 'Prosz&#281; czeka&#263;...',
				 button: 'Masz pytania? Kliknij tu! Oddzwonimy do Ciebie za darmo!',
				 translated_by: 'Przet&#322;umaczone przez',
				 frames_error: 'Obs&#322;ugujemy tylko strony bez ramek.',
				 translating: 'T&#322;umaczenie'}
		};
		return function(text) {
			if(translations[languageTo] && translations[languageTo][text])
				return translations[languageTo][text];
			else
				return translations['en'][text];
		};
    }();

    var editMode = (self.location.href).split('edit=')[1] ? true : false;

    if(httpMode){
        // find partner's specified url
        var startString = (top.location.href).split('page=')[1];
        // or set root if not found
        if(!startString) startString = '/';
        startPage = 'http://' + top.location.host + startString;

    	console.debug("loading into iframe:", startPage);
    }

    // append alien construction to document
    var construnction = '<table id="mltbTable" border="0" cellpadding="0" cellspacing="0">';
    construnction +='<tr>';
    construnction +='<td style="height: 1%;">';
    construnction +='<div id="topBar">';
    if(httpMode) construnction +='<a href="http://www.webinterpret.com/" target="_blank"><img alt="" id="wi-logo" src="' + mltbServer  + 'mltb/logo.png" /></a>';
    if(httpMode) construnction +='<button class="showHideCtc" id="ctc">' + translation('button') + '</button>';
    construnction +='<div id="preloader" style="display: none;">' + translation('please_wait') + '</div>';
    construnction +='<div class="clear"></div>';
    construnction +='</div>';
    construnction +='</td>';
    construnction +='</tr>';
    construnction +='<tr>';
    construnction +='<td style="width: 99%;">';
    if(httpMode){
        construnction +='<iframe src="' + 
            startPage + '" scrolling="auto" name="main" id="main" width="100%" height="100%" frameborder="0"></iframe>';
        construnction +='<iframe src="about:blank" scrolling="auto" name="httpsFrame" id="httpsFrame" width="0" height="0" frameborder="0"></iframe>';
    }
    construnction +='</td>';
    construnction +='</tr>';
    construnction +='</table>';
    construnction +='<div class="ctc-form"></div>';
    document.write(construnction);

    // load alien CSS
    loadCSS(mltbServer + "mltb/style.css");
    loadCSS(mltbServer + "mltb/" + skin + ".css");

    // load Google
	document.write(unescape("%3Cscript src='http://www.google.com/jsapi' type='text/javascript'%3E%3C/script%3E"));
	//loadJS("http://www.google.com/jsapi");

    // resize window function too keep iframe height up-to-date
    function resizeWindow(){
        jQuery('#main').css('height', jQuery(window).height() - jQuery('#topBar').height());
    }
    function httpsFramePosition(){
        frame_x = jQuery('#wi-logo').width();
        frame_width = jQuery(window).width() - jQuery('#wi-logo').width() - jQuery('.button1').width() - jQuery('.button2').width() - jQuery('.button3').width();

        //console.debug(frame_x, frame_width);
        jQuery('#httpsFrame').css('left', frame_x).css('width', frame_width);
    }

	var tracker;

    function initTranslation(track, glossary, fix){
		tracker = track;

        //jQuery('head').find('meta').attr('content', 'text/html; charset=UTF-8')
        //alert(jQuery('head').find('meta[http-equiv=content-type]').attr('content'));
        //alert(jQuery('head').find('meta').attr('content'));

        jQuery('.showHideCtc').click(function(){
            jQuery('.ctc-form').toggle();
        });

        if(httpMode){
            // window resize
            jQuery(window).resize(resizeWindow);
            resizeWindow();

    		jQuery("#c2c").html(translation("button"));
    		jQuery("#c2c").show();
		}

		checkGoogleJSApiReady(function () {							  
		    google.load("language", "1", {"callback": function() {startUrlCheck(glossary, fix);}});
		});
    };

    // init CTC
    _initCTC({campaign: campaignId, 
			  formLang: languageTo, 
			  mltb: {languageFrom: languageFrom,
					 languageTo: languageTo,
					 httpsMonitorMode: (!httpMode),
					 callback: initTranslation}});

    var isMonitor = false;
	function loadHTTPSMonitor() {
	    if(!isMonitor){
    		isMonitor = true;
    		httpsFrame.location.href = top.location.href.replace('http://', 'https://');
    		//httpsFrame.location.href = top.location.href.replace('www.', 'fr.');
            httpsFramePosition();
    		//console.debug('HTTPS Monitor loaded.', top.location.href.replace('www.', 'fr.'));
        }
        jQuery('#httpsFrame').filter(":hidden").show();
	}

	var oldUrl = startString;
	var translatedByElement = true;

    // check page url
    function startUrlCheck(glossary, fix) {

    	var time = null;
    	window.check = function() {	
    	    //console.debug(httpMode ? 'HTTP check' : 'HTTPS check');
			try {
				var x = top.frames['main'] && top.frames['main'].location.href;
				//due to buggy behavior of webkit browsers x may 
				//be undefined instead of raising security exception
				if(!x) {
                    if(httpMode) loadHTTPSMonitor();
					setTimeout('check()', 2000);
					return;
				};
			} catch(e){
			    if(httpMode) loadHTTPSMonitor();
				setTimeout('check()', 1000);
				return;
			}

            if(httpMode) jQuery('#httpsFrame').filter(":visible").hide();

            var main = top.frames['main'];

    		if(main && !jQuery(main.document).find('#mltbTranslated').text()) {
    			console.debug("Page reloaded to:", main.location.href);

                // set preloader
                setInfo(translation('please_wait'));

    			time = setInterval(function () {
    			    if(typeof main !== "undefined"){
        			    var doc = main.document;
        			    if(doc && doc.getElementsByTagName && doc.getElementById && doc.body && doc.body.innerHTML.length){
        					clearInterval(time);
        					console.debug("iFrame ready");
        					if(jQuery(doc).find('body').length){
                                jQuery(doc).ready(function(){
                                    translate(doc, languageFrom, languageTo, glossary, fix);
                                    translatedByElement = true;
                                });
        					}else{
                                setInfo(translation('frames_error'));
        					    console.warn(translation('frames_error'));
        					}
        				}else{
        					console.debug("iFrame not ready");
        				}
				    }
    			}, 200);
    		} else {
    		    if(httpMode){
    		        var newUrl = (top.location.href).split('page=')[1];
    		        if(oldUrl != newUrl){
    		            if(!translatedByElement) main.location.href = newUrl;
    		            oldUrl = newUrl;
    		        }
		            translatedByElement = false;
    		        //console.log(newUrl, oldUrl, translatedByElement);
    		    }
				setTimeout('check()', 200);
			}
    	};
        setTimeout('check()', 200);
    }

	function updateBar(doc) {
        // timing
        //var end = new Date();
        //console.debug('Translated in: ' + (end.getTime() - start.getTime()) + ' ms');
        setInfo('translated');
        if(httpMode){
            //top.frames['main'].scrollTo(0, 0);
            top.scrollTo(0, 0);
            // set translated title at main titlebar
            top.document.title = doc.title;
            
            // keep page's location in main url to easy bookmark
            top.location.hash = '#page=' + doc.location.pathname + doc.location.search;

            if(editMode) editElements();
        }
	};

	var regexNBSP = new RegExp(String.fromCharCode(160), "g");
	var regexSP = new RegExp(String.fromCharCode(32), "g");

	function fixWhiteSpaces(orig, translated) {
	    // add &nbsp; if needed to keep right design of pages
	    var testText = orig.trim();
        if(regexNBSP.test(testText) && !regexSP.test(testText)) {
			translated = translated.replace(/ /g, '\u00A0');
		}
        // add empty space to as first or last character to keep text nodes right look
        if(jQuery.browser.msie && jQuery.browser.version.substr(0,1) < 8) {
			translated = " " + translated + " ";
        } else {
    		if(orig[0] == " " || orig[0] == "\n")
    			translated = " " + translated;
    		if(orig[orig.length - 1] == " " || orig[orig.length - 1] == "\n")
    			translated += " ";
        }
		//console.warn(orig, "===>", translated);
		return translated;
	}

    function saveToEdit(selector, original, translation){
        var arr = jQuery(selector).data('arr');
        if(!arr) arr = new Array();
        arr.push([original.trim(), translation.trim()]);

	    jQuery(selector).css('border', '1px dotted red')
	                    .data('arr', arr)
                        .addClass('editModeElement');
    }

    function editElements(){
        jQuery(main.document).find('a').attr('href', '#');
        jQuery(main.document).find('form').attr('action', '#');
        jQuery(main.document).find('*').attr('onclick', '');
        jQuery(main.document).find('.editModeElement').click(function(event){
            event.stopPropagation();
            var data = jQuery(this).data('arr');
            var dataLength = data.length - 1;
            var fieldHeight = parseInt((jQuery(window).height() - 180) / (dataLength + 1)) - (dataLength + 1);

	        var editor = '<div id="editor">';
                editor += '<div class="i">';
                    editor += '<b class="close" onclick="jQuery(\'#editor\').remove(); return false;">&#10006;</b>';
                    editor += '<div class="title">Editor</div>';
                    var pairs = 0;
                    for(i = 0; i <= dataLength; i++){
                        if(data[i][0] != ''){
                            editor += '<div class="field">';
                            if(!i) editor += '<span style="border-right: 0;">Original</span>';
                                editor += '<div class="i" style="border-right: 0;">';
                                    editor += '<textarea class="original" name="original_' + i + '" cols="1" rows="1" readonly="readonly">' + data[i][0] + '</textarea>';
                                editor += '</div>';
                            editor += '</div>';
                            editor += '<div class="field">';
                            if(!i) editor += '<span>Translation</span>';
                                editor += '<div class="i">';
                                    editor += '<textarea class="translation" name="translation_' + i + '" cols="1" rows="1">' + data[i][1] + '</textarea>';
                                editor += '</div>';
                            editor += '</div>';
                            editor += '<div class="clear"></div>';
                            pairs++;
                        }
                    }
                    editor += '<div class="buttons">';
                        editor += '<button id="saveButton" style="background: #2FA2FF;">Save</button>';
                        editor += '<button id="cancelButton" onclick="jQuery(\'#editor\').remove(); return false;" style="background: #FF3300;">Cancel</button>';
                        editor += '<span class="preloader"><img src="' + detectServer() + '/images/ajax_loading.gif" style="vertical-align: middle;" /> Saving...</span>';
                    editor += '</div>';
		        editor += '</div>';
	        editor += '</div>';

	        if(pairs){
	            jQuery('#editor').remove();
    	        jQuery('body').append(editor);
    	        jQuery('#editor textarea').css('height', fieldHeight + 'px');
    	        jQuery('#editor').show()
    	                         .css('top', parseInt((jQuery(window).height() - jQuery('#editor').height()) / 2) + 'px')
    	                         .css('left', parseInt((jQuery(window).width() - jQuery('#editor').width()) / 2) + 'px');

                jQuery('#editor #saveButton').click(function(){
                    jQuery('#editor #cancelButton').hide();
                    jQuery('#editor #saveButton').hide();
                    jQuery('#editor .preloader').show();

                    var secret = (((self.location.href).split('edit=')[1]).split('#')[0]).split('&')[0];
                    var query = mltbServer;

                    query += 'ctc/mltb_glossary_input';
                    query += '?secret=' + secret;
                    query += '&campaignId=' + campaignId;
                    query += '&languageFrom=' + languageFrom;
                    query += '&languageTo=' + languageTo;

                    jQuery('#editor .original').each(function(){
                        query += '&original=' + encodeURIComponent(jQuery(this).val());
                    });
                    jQuery('#editor .translation').each(function(){
                        query += '&translation=' + encodeURIComponent(jQuery(this).val());
                    });
			        jQuery.getScript(query);
                    console.debug(query);
                });
            }
	    });
    }

    window.editError = function(info){
        jQuery('#editor .preloader').html('<b style="color: red;">' + info + '</b>');
    }

    window.editOK = function(info){
        jQuery('#editor .preloader').html('<b style="color: green;">' + info + '</b>');
        setTimeout("jQuery('#editor').remove()", 500);
    }

	function groupTexts(elem, glossary, groupLength, f) {
		var texts = [];
		var totalLength = 0;

		function pushText(text, setter) {
            if(totalLength + text.length > groupLength) {
				f(texts);
				texts = [];
				totalLength = 0;
			} 
			texts.push({"text": text, "set": setter});								   
			totalLength += text.length;				
		}

		function flushTexts() {
        	if(texts) {
				f(texts);
			}
		}

		function groupOrBreak(text, setter) {
			var translation = glossary[text.trim()];
			if(translation) {
				console.debug("translated:", text, "from glossary to: ", translation);
				setter(fixWhiteSpaces(text, translation));
			} else {
				if(text.replace(/[ \n\r\t]/g, "")) { //not empty
					if(text.length < groupLength) { //not too long
						//console.debug("pushing text: ", text.length, " under: ", groupLength, text);
						pushText(text, function(translation) {
					        setter(fixWhiteSpaces(text, translation));
						});
					} else { //text too long, lets split it
						var acc = ""; //accumulator for translated fragments
						var tail = text;
						while(true) {
							var fragment = tail.substr(0, groupLength);
							if(fragment.length < tail.length) {
								for(var splitChar in {". ": 1, ", ": 1, "\n": 1, " ": 1}) {
									var splitIndex = fragment.lastIndexOf(splitChar);
									if(splitIndex >= 0) {
										//console.debug("long text broken at: '", splitChar, "'", fragment);
										fragment = fragment.substr(0, splitIndex + splitChar.length);
										break;
									}
								}
							}
							tail = tail.substr(fragment.length);
							if(tail) {
								//console.debug("pushing text fragment:", fragment.length, fragment, "tail: ", tail);
								pushText(fragment, function(translation) {
								    acc += fixWhiteSpaces(fragment, translation);
								});
							} else {
								//console.debug("pushing last text fragment:", fragment.length, fragment);
								pushText(fragment, function(translation) {
							        setter(acc + fixWhiteSpaces(fragment, translation));
									acc = null; //not sure if necessary
								});								
								break;
							}
						}
					}
				}
			}
		}

		function handleElement(key, value) {
			if(value.nodeType === 3) {
				if (jQuery(value).parent().get(0).nodeName.toLowerCase() != 'textarea') {
    				groupOrBreak(value.nodeValue, function(translation) {
    				    if(editMode) saveToEdit(jQuery(value).parent(), value.nodeValue, translation);
    				    value.nodeValue = translation;
    				});
				}
			} else if(value.nodeType === 1) {
				var nodeName = value.nodeName;
				value = jQuery(value);
				if(nodeName.toLowerCase() == "input" &&
				   value.attr("type") && (value.attr("type") == 'submit' ||
					                      value.attr("type") == 'button' ||
					                      value.attr("type") == 'reset')) {
					pushText(value.attr("value"), function(translation) {
                            if(editMode) saveToEdit(value, value.attr("value"), translation);
                			var glossary_translation = glossary[value.attr("value").trim()];
                			if(glossary_translation) value.attr("value", glossary_translation);
                			else value.attr("value", translation);
					});
				} else if(value.attr("title")) {
					pushText(value.attr("title"), function(translation) {
    				    if(editMode) saveToEdit(value, value.attr("title"), translation);
            			var glossary_translation = glossary[value.attr("title").trim()];
            			if(glossary_translation) value.attr("title", glossary_translation);
            			else value.attr("title", translation);
					});
				} else if(value.attr("alt")) {
					pushText(value.attr("alt"), function(translation) {
    				    if(editMode) saveToEdit(value, value.attr("alt"), translation);
            			var glossary_translation = glossary[value.attr("alt").trim()];
            			if(glossary_translation) value.attr("alt", glossary_translation);
            			else value.attr("alt", translation);
					});
				}
			}
		}

/*
        elem.find(":not(script)").contents().each(function(key, value) {
			if(value.nodeType === 3) {
				var parent = jQuery(value).parent();
				//console.debug(value, parent);
				if(parent.get(0).nodeName.toLowerCase() == 'strong') {
					parent = parent.parent();
				}
				if(parent.children().length > 1) {
					parent.addClass("flatten-ok");
				}
				parent.parents().addClass("flatten-not-ok");
			}
		});
		
		elem.find(":not(script)")
			.filter(".flatten-ok")
			.filter(":not(.flatten-not-ok)").each(function() 
		{
			console.warn(jQuery(this).html());
		});
*/

        elem.find(":not(script)").contents().each(handleElement);			  
		flushTexts();
    };


    // translate page
    function translate(doc, srcLang, dstLang, glossary, fix) {

        console.debug('Translating...');

        var context = 0;
		var texts = [];
		var totalLength = 0;
		var allTexts = {};
		
		var translated = 0;
		var all = 0;
		var isAlreadyDone = false;

        // timing
        var start = new Date();

		window._translatedCallback = function(context, result) {
			jQuery(result).each(function(index, value) {
 				var translatedText = value.responseData ? 
										value.responseData.translatedText : 
										value.translatedText;
				if(translatedText){
    				translatedText = translatedText.replace(/&#39;/g, "'");
    				translatedText = translatedText.replace(/&quot;/g, '"');
    				translatedText = translatedText.replace(/&lt;/g, "<");
    				translatedText = translatedText.replace(/&gt;/g, ">");
    				translatedText = translatedText.replace(/&amp;/g, "&");
    				allTexts[context][index].set(translatedText);
			    }
				delete allTexts[context][index];					
			});
			translated++;
            setInfo(translation('translating') + ' <b>' + Math.floor(100*translated/all) + '%</b>');
			if(all && translated == all && !isAlreadyDone) {
			    isAlreadyDone = true;
				updateBar(doc);
				fix(doc, dstLang);
				jQuery(doc).find('body').prepend('<div id="mltbTranslated" style="display: none;">1</div>');

				// Changing flash wmode and replacing it's dom
				/*
            	var p = document.createElement('param');
            	p.setAttribute("name", "wmode");
            	p.setAttribute("value", "transparent");
				jQuery(doc).find('object').each(function(){
				    console.debug(jQuery(this).find('param[name="movie"]'));
				    var movie = jQuery(this).find('param[name="movie"]');
				    jQuery(this).find('param[name="movie"]').after(p).remove();
				});
				*/

				jQuery(doc).find('embed').each(function(){

                	var p = document.createElement('embed');
                	if(jQuery(this).attr('bgcolor')) p.setAttribute("bgcolor", jQuery(this).attr('bgcolor'));
                	if(jQuery(this).attr('height')) p.setAttribute("height", jQuery(this).attr('height'));
                	if(jQuery(this).attr('id')) p.setAttribute("id", jQuery(this).attr('id'));
                	if(jQuery(this).attr('name')) p.setAttribute("name", jQuery(this).attr('name'));
                	if(jQuery(this).attr('quality')) p.setAttribute("quality", jQuery(this).attr('quality'));
                	if(jQuery(this).attr('src')) p.setAttribute("src", jQuery(this).attr('src'));
                	if(jQuery(this).attr('type')) p.setAttribute("type", jQuery(this).attr('type'));
                	if(jQuery(this).attr('width')) p.setAttribute("width", jQuery(this).attr('width'));
                	p.setAttribute("wmode", "transparent");

                    jQuery(this).after(p).remove();
				});

                /*
                if(jQuery.browser.msie){
    				jQuery(doc).find('object').each(function(){
    				    var n = jQuery(this).clone();
    				    //alert(n);
                        jQuery(this).after(n).remove();
    				});                    
                }
                */
				
				tracker._trackCTCEvent("translated");
                console.debug('Translated in: ' + (new Date().getTime() - start.getTime()) + ' ms');
				startUrlCheck(glossary, fix);
			}
		};

        groupTexts(jQuery(doc).find('html'), glossary, 400, function(texts) {
			var url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0";
		    url += "&langpair=" + srcLang + "|" + dstLang ;									
		    jQuery(texts).each(function() {
			    url+="&q=" + encodeURIComponent(this.text);
			});
			url+="&context=" + context; 
			url+="&callback=_translatedCallback";
		    //console.debug(context, url);
			allTexts[context] = texts;
			jQuery.getScript(url);
			context++;									
		});
		all = context;
    }
};
})();
