// Initial variable setup
var whichdropdown = '';
var quickfinderCategoryNames = new Array();
var openEngineIdentificationTimeout;
var closeEngineIdentificationTimeout;
var seriesSelectElementOnManualsPage;
var hpSelectElementOnManualsPage;
var shaftSelectElementOnManualsPage;

function enableAlphaImages(){
    if ($.browser.msie && (parseInt(jQuery.browser.version) < 7)) {
        var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
        var itsAllGood = (rslt != null && Number(rslt[1]) < 7);
        if (itsAllGood) {
            for (var i=0; i<document.all.length; i++){
                var obj = document.all[i];
                var bg = obj.currentStyle.backgroundImage;
                var img = document.images[i];
                if (bg && bg.match(/\.png/i) != null) {
                    var img = bg.substring(5,bg.length-2);
                    var offset = obj.style["background-position"];
                    obj.style.filter =
                    "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+img+"', sizingMethod='crop')";
                    obj.rel = img;
                    obj.style.backgroundImage = "url('/common/images/spacer.gif')";
                    obj.style["background-position"] = offset; // reapply
                } else if (img && (img.src.match(/\.png$/i) != null || img.src.match(/fmt=png-alpha/i) != null)) {
                    var src = img.src;
                    img.style.width = img.width + "px";
                    img.style.height = img.height + "px";
                    img.style.filter =
                    "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+src+"', sizingMethod='crop')"
                    img.src = "/common/images/spacer.gif";
                }
            }
        }
    }
}

// Loop through all available category filters and create their dropdowns
function populateCategoryFilterSelects(r) {
    for (var i = 0; i < r.selects.length; i++) {
        populateOneCategoryFilterSelect($("#" + r.selects[i].id), r.selects[i].options);
    }
    $('#eng-quickfinder-count').text(r.count);
}

// Create a category filter dropdown
function populateOneCategoryFilterSelect(obj, options) {
    var selectedIdx = 0;
    var selectedValue = obj.find("option:selected")[0].value;
    var optionIndex = obj.attr('id').substring(9);
    var label = obj.find("option")[0].text;
    var displayedOptions = $('#displayed_filterOpt' + optionIndex + ' .eng-quickfinder-options');

    obj.children().remove(); // throw out the old options in the hidden form
    displayedOptions.children().remove(); // throw out the old divs representing the options

    obj.append('<option value="" class="quickfinder-all">' + label + '</option>');
    var displayedAllOption = $('<a href="#" class="displayed_quickfinder-all">' + label + '</a>');
    $(displayedAllOption).click(function() { updateQuickfinder(this); return false; });
    displayedOptions.append(displayedAllOption);
    
    for (var i = 0; i < options.length; i++) {
        if (selectedIdx == 0 && selectedValue.length > 0 && selectedValue == options[i].value) {
            selectedIdx = obj.find("option").length;  // getting the count *before* adding the new option
        }
        obj.append('<option value="' + options[i].value + '" id="opt' + optionIndex + '-' + i.toString() + '">' + options[i].value + '</option>');
        var displayedOption = $('<a href="#" id="displayed_opt' + optionIndex + '-' + i.toString() + '">' + options[i] .value+ '</a>');
        $(displayedOption).click(function() { updateQuickfinder(this); return false; });
        displayedOptions.append(displayedOption);
    }
    obj[0].selectedIndex = selectedIdx;
}

function categoryFilterUpdate(formData) {
    $.getJSON("/ajax/getFilteredCategoryFilters.htm?" + formData, function(r) {
        populateCategoryFilterSelects(r);
    });
}

function manualsCriteriaUpdate(formData) {
    // hack to get around jquery selector bug
    if (seriesSelectElementOnManualsPage == undefined && hpSelectElementOnManualsPage == undefined && shaftSelectElementOnManualsPage == undefined) {
        $('form#filters select').each(function() {
            if ($(this).attr('id') == 'filter\'ENGINE_SERIES\'') {
                seriesSelectElementOnManualsPage = $(this);
            } else if ($(this).attr('id') == 'filter\'HORSEPOWER_RANGE\'') {
                hpSelectElementOnManualsPage = $(this);
            } else if ($(this).attr('id') == 'filter\'SHAFT\'') {
                shaftSelectElementOnManualsPage = $(this);
            }
        });
    }
    
    $.getJSON("/ajax/getManualsFilteredCategoryFilters.htm?manuals=true" + formData, function(r) {
        for (var i = 0; i < r.selects.length; i++) {
            if (r.selects[i].label == 'Series') {
                updateOneManualsCriteria(seriesSelectElementOnManualsPage, 'unused', r.selects[i].options);
            } else if (r.selects[i].label == 'Horsepower (hp)') {
                updateOneManualsCriteria(hpSelectElementOnManualsPage, 'unused', r.selects[i].options);
            } else if (r.selects[i].label == 'Shaft') {
                updateOneManualsCriteria(shaftSelectElementOnManualsPage, 'unused', r.selects[i].options);
            }
        }
    });
}

function updateOneManualsCriteria(obj, defaultMessage, options) {
    var selectedIdx = 0;
    var selectedValue = $(obj).find("option:selected")[0].value;
    //$(obj).html('<option value="">' + defaultMessage + '</option>');
    $(obj).find("option:not(:first)").remove();
    for (var i = 0; i < options.length; i++) {
        if (selectedIdx == 0 && selectedValue.length > 0 && selectedValue == options[i].value) {
            selectedIdx = obj.find("option").length;  // getting the count *before* adding the new option
        }
        obj.append('<option value="' + options[i].value + '">' + options[i].value + '</option>');
    }
    obj[0].selectedIndex = selectedIdx;
}

function updateQuickfinder(element) {
    var quickfinderSelection = $(element).html();
    $(element).parent('.eng-quickfinder-options').prev('.eng-quickfinder-header').html(quickfinderSelection);
    $(element).parent('.eng-quickfinder-options').prev('.eng-quickfinder-header').css({ backgroundColor:"#283f59", color:"#FFFFFF" });
    $(element).parent('.eng-quickfinder-options').css('display','none');
    if ($(element).hasClass('displayed_quickfinder-all')) { // if 'All', unselect all options, select the 'All' option
        $(element).parents('.eng-quickfinder-select').find('option').each(function() { $(this).attr('selected', ''); });
        $(element).parents('.eng-quickfinder-select').find('option.quickfinder-all').attr('selected', 'selected');
    } else { // else select an option
        var optionId = $(element).attr('id').split('_');
        $('option#' + optionId[1]).attr('selected', 'selected');
    }
    return categoryFilterUpdate($("#categoryFilterForm").fastSerializeUrlStringIgnoreEmptyNotHidden());
}

function resetQuickfinder() {
    $('#categoryFilterForm option').each(function() { $(this).attr('selected', ''); });
    $('#categoryFilterForm option.quickfinder-all').attr('selected', 'selected');

    var i = 0;
    $('.eng-quickfinder-header').each(function() {
        $(this).text(quickfinderCategoryNames[i]).css({ backgroundColor:"#8597AA", color:"#08151D" });
        i++;
    });

    return categoryFilterUpdate($("#categoryFilterForm").fastSerializeUrlStringIgnoreEmptyNotHidden());
}

function categoryFilterSubmit(formData) {
    window.location = "/onlinecatalog/results.htm?" + formData;
	return false;
}

function showEquipmentPoweredBySection(element, section) {
    $('#equipmentPoweredBy-nav div').each(function() {
        var src = $(this).css('background-image');
        $(this).css('background-image', src.replace('-on', '-off'));
    })

    $('.eng-equipPoweredBy-links').hide().removeClass('clearfix');
    $('#eng-equipPoweredBy-links-' + section).addClass('clearfix').show();

    var src = $(element).parent('div').css('background-image');
    $(element).parent('div').css('background-image', src.replace('-off', '-on'));
}

function openEngineIdentificationInfo(element) {
    clearTimeout(closeEngineIdentificationTimeout);
	$(element).find('img.roundedCorners').css('display','block');	
    $(element).find('li').css('color','#FFFFFF');
	$(element).find('li').css('padding-top',0);
	$(element).find('li').css('background-position','9px 5px');
	$(element).find('li').css('background-image','url(/common/images/bullet-quickfinderArrow-on.gif)');
	var cssObj = {
		'height' : 'auto',
		'margin-bottom' : '20px',
		'background-image' : 'url(/common/images/bg-engineIdentificationSelection-on-middle.gif)',
		'background-repeat' : 'repeat-y'
    }
	$(element).css(cssObj);
	$(element).find('div').stop(true, true).slideDown(200);

    var numberType = $(element).find('li').text();
    var isVertical = $(element).parent('div').find('#modelNumber').size();
    var src;
    if (numberType == 'Model Number' && isVertical) {
        src = $('img#engineIdentification-label-vertical').attr('src');
        $('img#engineIdentification-label-vertical').attr('src', src.replace('.jpg', '-model.jpg'));
    } else if (numberType == 'Spec Number' && !isVertical) {
        src = $('img#engineIdentification-label-horizontal').attr('src');
        $('img#engineIdentification-label-horizontal').attr('src', src.replace('.jpg', '-spec.jpg'));
    }

    //$(element).css('background-color', '#a1aaaf').find('div').stop(true, true).slideDown(300);
}

function closeEngineIdentificationInfo(element) {
    var src = $('img#engineIdentification-label-vertical').attr('src');
    $('img#engineIdentification-label-vertical').attr('src', src.replace('-model.jpg', '.jpg'));
    src = $('img#engineIdentification-label-horizontal').attr('src');
    $('img#engineIdentification-label-horizontal').attr('src', src.replace('-spec.jpg', '.jpg'));
    
    $(element).find('div').stop(true, true).slideUp(200, function(){
		$(element).find('img.roundedCorners').css('display','none');
		var cssObj = {
			'height' : '42px',
			'margin-bottom' : '0',
			'background-image' : 'url(/common/images/bg-engineIdentificationSelection-off.gif)',
			'background-repeat' : 'no-repeat'
		}
	    $(element).css(cssObj);
		$(element).find('li').css('color','#A8B1B6');
		$(element).find('li').css('padding-top','8px');
		$(element).find('li').css('background-position','9px 15px');
		$(element).find('li').css('background-image','url(/common/images/spacer.gif)');
	});
}

function toggleWhereToBuyFields() {
    if ($('#eng-dealerLocator-form select#region').val() == 'USA' || $('#eng-dealerLocator-form select#region').val() == 'Canada') {
        $('#eng-dealerLocator-form select:not(#region), #eng-dealerLocator-form input:not(.submitbutton)').each(function() {
            $(this).removeAttr('disabled');
            if (!$(this).hasClass('textfield-error')) {
                $(this).css('background-color', '#fafafa');
            }
        });
    } else {
        $('#eng-dealerLocator-form select:not(#region), #eng-dealerLocator-form input:not(.submitbutton)').attr('disabled', 'disabled').val('').css('background-color', '#eee');
    }
}


function trimTextarea(elem, maxlength) {
    if ($(elem).val().length > maxlength) {
        $(elem).val($(elem).val().substring(0, maxlength - 1));
    }
}

function fixGradientDescriptionHeights() {
    var tempHeight = 0;
    $('.gradientcontainer .gradient-description').each(function(){
        if($(this).height() > tempHeight) tempHeight = $(this).height();
    });
    $('.gradientcontainer .gradient-description').css("height", tempHeight+'px');
}

function fixTabContentHeights() {
    var tempHeight = 0;
    $('#eng-landing-tabbedcontent div.tabcontent').each(function(){
        if($(this).height() > tempHeight) tempHeight = $(this).height();
    });
    $('#eng-landing-tabbedcontent div.tabcontent').css("height", tempHeight+'px');
}

$(function(){
    enableAlphaImages();
    
    var defaultSearchVal = $("#sitesearch").attr("value");
	$("#sitesearch").focus(function(){
		if($(this).val()==defaultSearchVal){
			$(this).val("");
		}
	});
	
    var modelNumberFieldDefaultText = $("form#modelNumber .textfield").val();
	$("form#modelNumber .textfield").focus(function(){
		if($(this).val() == modelNumberFieldDefaultText){
			$(this).val("");
		}
	});


	// NEW  - Main Navigation Rollovers
	$("div.navnode").mouseenter(
		function(){
			whichdropdown = $(this).find('a.navnode-link').attr('id');
			var speed = ($('#eng-dropdown-' + whichdropdown).height()/4)*3;
			$(this).find('a.navnode-link').toggleClass("on");
			$('#eng-dropdown-' + whichdropdown).css('display','block');

            closePopouts();
			}
	).mouseleave(
		function(){
			$(this).find('a.navnode-link').not($(".active")).toggleClass("on");
			whichdropdown = $(this).find('a.navnode-link').attr('id');
			$('#eng-dropdown-' + whichdropdown).css('display','none');

            closePopouts();
			}
	);
	
// NEW  - Engines Drop downs Rollovers - this will also perform the AJAX load of the pop out content.
    var flyoutTimer = null;
	$("a.engines-nav").click(function() {
        var	that = this;
        var	id = $(that).attr('id');
        if (!$(that).hasClass("lit")) {
            if (flyoutTimer != null) {
                clearTimeout(flyoutTimer);
            }
            closePopouts();
            openPopout(id);
        }

        return false;

    }).mouseenter(
		function(){
            if (flyoutTimer != null) {
                clearTimeout(flyoutTimer);
            }
            var	that = this;
            var	id = $(that).attr('id');
            flyoutTimer = setTimeout(function() {
                if (!$(that).hasClass("lit")) {
                    closePopouts();
                    openPopout(id);
                }
            }, 400);
        }
    );
	
	// Kills a poput from the Engines Nav
	$(".pop-out-killer").mouseenter(
		function(){
            if (flyoutTimer != null) {
                clearTimeout(flyoutTimer);
            }
            flyoutTimer = setTimeout(function() {
                closePopouts();
            }, 500);
		}
	); 	

    $(".eng-popout").mouseenter(function() {
        if (flyoutTimer != null) {
            clearTimeout(flyoutTimer);
        }
    });

    // using jsonp here so 3rd party hosted pages and get ajaxed content
    var flyoutContentUrl = '/ajax/getEnginesFlyout.htm';
    if ($("base").size() > 0) {
        flyoutContentUrl = $("base:first").attr("href") + flyoutContentUrl;
    }
    var getFlyoutContent = $.ajax({
        dataType: 'jsonp',
        url: flyoutContentUrl,
        jsonpCallback: 'enginesFlyoutCallback',
        data: { type: "jsonp" }
    });

    getFlyoutContent.success(function(data) {
        var content = data;
        content = Base64.decode(content);
        $('#flyout-content').append($(content));
    });

    function openPopout(id) {
        closePopouts();
        $("#" + id).addClass("lit");
        var currentpopout = $('#eng-popout-' + id);
        if(!$('#eng-popout-' + id + ' .popout-content').hasClass("loaded")){
            getFlyoutContent.success(function() {
                var content = $('#flyout-content #' + id + '-content');
                $('#eng-popout-' + id + ' .popout-content').empty().append(content);

                // mark as loaded
                $('#eng-popout-' + id + ' .popout-content').addClass("loaded");
                if(!$.browser.msie){
                    //$('#' + id + '-content').hide().fadeIn(500);
                }else if($.browser.msie && $.browser.version.substr(0,1)>=8){
                    //$('#' + id + '-content').hide().fadeIn(500);
                }else{	
                    enableAlphaImages();
                }	
            });
        }
        currentpopout.animate( {'width':'toggle'}, 300,
            function(){

            }
        );
    }

    function closePopouts() {
        if (flyoutTimer != null) {
            clearTimeout(flyoutTimer);
        }
        $("a.engines-nav").removeClass('lit');
        $(".eng-popout").stop(true,true).hide();
    }
	
	$("li.ho-engine").live("mouseenter", function() {
		$("div.ho-poput-sidebar-content").empty();
		if($(this).find(".flyout-list-hold").length) {
            var content = $(this).find(".flyout-list-hold").contents().clone();
            $(this).closest(".popout-content").find(".ho-poput-sidebar .ho-poput-sidebar-content").append(content);
		}
	});
	$("li.ho-engine").live("mouseleave", function() {
		$(this).closest(".popout-content").find(".ho-poput-sidebar .ho-poput-sidebar-content").empty();
	});
	

    // Set up filter criteria update on manuals page
    $('#engn-manualsLanding-nomodelnum select').change(function() {
        return manualsCriteriaUpdate($("#engn-manualsLanding-nomodelnum form").fastSerializeUrlStringIgnoreEmptyNotHidden()); 
    });

    $("#categoryFormSubmit").click(function() {
        return categoryFilterSubmit($("#categoryFilterForm").fastSerializeUrlStringIgnoreEmpty());
    });

    // Activate rollover images
    $('img.rollover').each(function() {
        var offSrc = $(this).attr('src');
        $(this).hover(function() {
            $(this).attr('src', offSrc.replace('-off', '-on'));
        }, function() {
            $(this).attr('src', offSrc);
        });
    });
	
	// Functions to set uniform height for certain objects. Use 1 ms delay to deal with Safari bug.
    setTimeout('fixGradientDescriptionHeights()', 1);
    setTimeout('fixTabContentHeights()', 1);
	
	//Funtion for Gradient container rollovers
	$('.gradientcontainer').hover(function() {
		$(this).css("width","166px");
		$(this).find('div.gradient-description').css("margin-right","2px");
		$(this).find('div.gradient-description').css("margin-bottom","2px");
		$(this).find('div.gradient-description').css("margin-left","2px");
		$(this).find('p.header').css("color","#7A9059");
		$(this).css("border-width","2px");
		$(this).css("border-color","#c2c2c2");
		$(this).css("background-image","url('/common/images/bg-gradient-on.gif')");
        $(this).find('.gradient-photo').css('margin-top', '-1px');
    }, function() {
		$(this).css("border-width","1px");
		$(this).find('div.gradient-description').css("margin-right","3px");
		$(this).find('div.gradient-description').css("margin-bottom","3px");
		$(this).find('div.gradient-description').css("margin-left","3px");
		$(this).find('p.header').css("color","#6B8896");
		$(this).css("border-color","#E3E2E2");
		$(this).css("width","168px");
		$(this).css("background-image","url('/common/images/bg-gradient-off.gif')");
        $(this).find('.gradient-photo').css('margin-top', '0');
    });

	// FAQs expansion script
	$('.eng-faq ul li a').click(
		function() {
			var whichQuestion = $(this).parents('div.eng-faq').attr('id');
			if($('#' + whichQuestion + '-answer').css("display")=="block") {
				$('#' + whichQuestion + '-answer').slideUp(500);
				$(this).css({'font-weight' : 'normal', 'font-style' : 'normal', 'color' : '#7A9059'});
				$(this).parent('li').css("background-image","url('/common/images/bullet-rightarrow.gif')");
			} else {
				$('.eng-faq-answer').slideUp(500);
				$('.eng-faq ul li').css("background-image","url('/common/images/bullet-rightarrow.gif')");
				$('.eng-faq ul li a').css({'font-weight' : 'normal', 'font-style' : 'normal', 'color' : '#7A9059'});
				$(this).css({'font-weight' : 'bold', 'font-style' : 'italic', 'color' : '#555555'});
				$('#' + whichQuestion + '-answer').slideDown(500);
				$(this).parent('li').css("background-image","url('/common/images/bullet-downArrowRotated.gif')");
			}
            return false;
        }
	);

    // Engine identification page effects
    $('.engineIdent-rolloverDef').hover(function() {
        var myDiv = this;
        openEngineIdentificationTimeout = setTimeout(function(){openEngineIdentificationInfo(myDiv)}, 100);
    }, function() {
        var myDiv = this;
        clearTimeout(openEngineIdentificationTimeout);
        closeEngineIdentificationTimeout = setTimeout(function(){closeEngineIdentificationInfo(myDiv)}, 100);
    });

    toggleWhereToBuyFields();
    $('#eng-dealerLocator-form select#region').change(toggleWhereToBuyFields);

    // Fix select element overlap bug in IE6
    if ($.browser.msie && (parseInt(jQuery.browser.version) < 7)) {
        $('.eng-dropdown').bgiframe();
    }
    
    // prepare document overlay so that we can close popups by clicking outside them
    $("#document-overlay").css('height', $(document).height());
    $("#document-overlay").css('width', $(document).width());

    // Trim length of message input
    $('textarea#message').keyup(function() { trimTextarea(this, 500); });

    // Hook up survey link
    $('div#eng-foreseelink a').click(function() {
        window.open('http://www.kohler.com/feedback/enginescommentcard.jsp', 'Feedback', 'height=560,width=560,resizable,location=no');
        return false;
    });
});

// from tabs.js
// Initial variable setup
var whichDetailTab = '';

// Tab Swapping Function
function detailTabs() {
    $('#tabs div').each(function() {
        $(this).css("backgroundImage",$(this).css("backgroundImage").replace("-on","-off"));
    });
    if ($('#tabs div.active').size() > 0) {
        $('#tabs div.active').css("backgroundImage",$('#tabs div.active').css("backgroundImage").replace("-off","-on"));
    }
}

// Bind Functions to Dom on document ready
$(function(){
	
    // Tab-related functions
    detailTabs();
    $('#tabs div').click(
            function() {
                $('#tabs div').removeClass('active');
                $(this).addClass('active');
                detailTabs();
                $('.tabcontent').css('display','none');
                whichDetailTab = $(this).attr('id');
                $('#tabcontent-' + whichDetailTab).css('display','block');

                // Size uses panel on product detail page
                if ($(this).attr('id') == 'uses' && $('#engineuses-tabs').size() > 0) {
                    var usesHeight = $('#engineuses-tabs').height();
                    if ($.browser.msie && (parseInt(jQuery.browser.version) < 7)) {
                        $('#engineuses-list .engUsesList').css('height', usesHeight + 'px');
                    } else {
                        $('#engineuses-list .engUsesList').css('min-height', usesHeight + 'px');
                    }
                }
            }
    );
});

$(document).ready(function(){
	$("#gas_check,#diesel_check").click(function(){
	if($("#gas_check").is(':checked') && $("#diesel_check").is(':checked') ){
		$("#searchParams").val("enginetype_110=on&enginetype_100=on");
	}else if($("#gas_check").is(':checked')){
		$("#searchParams").val("enginetype_110=on");
	}else if($("#diesel_check").is(':checked')){
		$("#searchParams").val("enginetype_100=on");
	}else{
		$("#searchParams").val("");
	}
	
	});
});




// private
var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
 
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
 
		return output;
 
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}

