(function ($) {
    $.fn.listenForEnter = function () {
        return this.each(function () {
            $(this).focus(function () {
                $(this).data('safeEnter_InAutocomplete', false);
            });
            $(this).keypress(function (e) {
                var key = (e.keyCode ? e.keyCode : e.which);
                switch (key) {
                    case 13:
                        // Fire the event if:
                        //   - we're not currently in the browser's Autocomplete, or
                        //   - this isn't a textbox, or
                        //   - this is Opera (which provides its own protection)
                        if (!$(this).data('safeEnter_InAutocomplete') || !$(this).is('input[type=text]') || $.browser.opera) {
                            $(this).trigger('pressedEnter', e);
                        }
                        $(this).data('safeEnter_InAutocomplete', false);
                        break;

                    case 40:
                    case 38:
                    case 34:
                    case 33:
                        // down=40,up=38,pgdn=34,pgup=33
                        $(this).data('safeEnter_InAutocomplete', true);
                        break;

                    default:
                        $(this).data('safeEnter_InAutocomplete', false);
                        break;
                }
            });
        });
    };

    $.fn.clickOnEnter = function (target) {
        return this.each(function () {
            $(this)
				.listenForEnter()
				.bind('pressedEnter', function () {
				    $(target).click();
				});
        });
    };
})(jQuery);

var font = (function () {
    var test_string = 'mmmmmmmmmwwwwwww';
    var test_font = '"Comic Sans MS"';
    var notInstalledWidth = 0;
    var testbed = null;
    var guid = 0;

    return {
        // must be called when the dom is ready
        setup: function () {
            if ($('#fontInstalledTest').length) return;

            $('head').append('<' + 'style> #fontInstalledTest, #fontTestBed { position: absolute; left: -9999px; top: 0; visibility: hidden; } #fontInstalledTest { font-size: 50px!important; font-family: ' + test_font + ';}</' + 'style>');


            $('body').append('<div id="fontTestBed"></div>').append('<span id="fontInstalledTest" class="fonttest">' + test_string + '</span>');
            testbed = $('#fontTestBed');
            notInstalledWidth = $('#fontInstalledTest').width();
        },

        isInstalled: function (font) {
            guid++;

            var style = '<' + 'style id="fonttestStyle"> #fonttest' + guid + ' { font-size: 50px!important; font-family: ' + font + ', ' + test_font + '; } <' + '/style>';

            $('head').find('#fonttestStyle').remove().end().append(style);
            testbed.empty().append('<span id="fonttest' + guid + '" class="fonttest">' + test_string + '</span>');

            return (testbed.find('span').width() != notInstalledWidth);
        }
    };
})();

var minLeftNavHeight = 600;
var pageRequestManager = Sys.WebForms.PageRequestManager.getInstance();
pageRequestManager.add_endRequest(endRequest);

function endRequest(sender, eventArgs) {
    setTimeout("SetLeftHeight()", 100);
}
var currentLoadIndex = 0;
//get the same height for the right and left continers
$(document).ready(function () {
    var allImages = jQuery("img", "DIV.paragraphContent");
    var allImageslength = allImages.length;
    allImages.each(function () {
        jQuery(this)
        .load(function () { currentLoadIndex++; if (currentLoadIndex == allImageslength) { setTimeout("SetLeftHeight()", 100); } });
    });
    setTimeout("SetLeftHeight()", 100);
    //popup
    $("a.EmailLink").bind("click", function () {
        $("#Email_popup").bPopup();
        return false
    });
    //clear search input filed
    $('.inputVal').each(function () {
        var currentVal = this.value;
        $(this).focus(function () {
            if (this.value == currentVal) {
                this.value = '';
            }
        });
        $(this).blur(function () {
            if (this.value == '') {
                this.value = currentVal;
            }
        });
    });

    /// file input
    $("#inputFile").change(function () {
        $(".fakefile input").val($(this).val());
    });


    /// world map

    $(".worldwideMap A").click(function () {
        $(".worldwideMap A.mapArea_on").removeClass("mapArea_on").addClass("mapArea_off");
        $(this).removeClass("mapArea_off").addClass("mapArea_on");
        var currentVal = $(this).children("span").text();
        var currentKey = $(this).children("span").attr("CountryKey");
        $(".locationsFilter .jqTransformSelectWrapper DIV SPAN").text(currentVal);
        $(".locationsFilter .jqTransformSelectWrapper UL LI A").each(function () {
            if ($(this).text() == currentKey) {
                $(".locationsFilter .jqTransformSelectWrapper UL LI A").removeClass("selected");
                $(this).addClass("selected");
            }
        });
        //$("span[id$='LocationArea']").html = currentVal;
        $("a[id$='ClickMap']").click();
        eval($("a[id$='ClickMap']").attr('href'));
    });

    // in tabs
    $(".tapiTab UL:eq(0) LI A").not(".tollTipTop a").click(function () {
        var tabInd = $(".tapiTab UL:eq(0) LI A").index($(this));
        $(".tapiTab UL:eq(0) LI A").not(".tollTipTop a").removeClass("tabSelect").addClass("tabNormal");
        $(this).removeClass("tabNormal").addClass("tabSelect");
        $(".tapiTab UL:eq(0) LI:not(:first):not(:last)").attr("class", "mid");
        if (tabInd < 2) {
            $(".tapiTab UL:eq(0) LI:eq(0)").attr("class", "first");
        }
        else {
            $(".tapiTab UL:eq(0) LI:eq(0)").attr("class", "first2");
            $(".tapiTab UL:eq(0) LI:eq(" + (tabInd - 1) + ")").attr("class", "second");
        }

        // should make post to get data
        $(".resultsPadding").html("<div style='margin:0 auto;text-align:center;font-size:14px'>tabName - " + $(this).children("span").text() + " <br/>preview some loading image<br/>make post to render tab data</div>");
    });
});


$(document).ready(function () {
    $(".expandableParagraph .paragraphContent").toggle();
    $(".expandableParagraph .paragraphTitle h2").addClass("pPlus").click(function () {
        var divText = $(this).parent().parent().children(".paragraphContent");
        $(divText).toggle("slow", function () {
            $(this).parent().children(".paragraphTitle h2").toggleClass("pMinus").toggleClass("pPlus");
        });
    });

});

//world map
function worldMapAfterjqTransform() {
    $(".locationsFilter .jqTransformSelectWrapper UL LI A").click(function () {
        var currentVal = $(this).text();
        var currentKey = $(".locationsFilter .jqTransformSelectWrapper select option:selected").val();
        $(".worldwideMap A").each(function () {
            $(this).removeClass("mapArea_on").addClass("mapArea_off");
            if ($(this).find("SPAN").attr("CountryKey") == currentKey) {
                $(this).removeClass("mapArea_off").addClass("mapArea_on");
            }
        });
        $("input[id$='MapSelectedText']").val("");
        $("input[id$='MapSelectedVal']").val("");
    });
}
function GridToPrint(printUrl) {
    if (printUrl.length > 0) {
        var win = window.open(printUrl, "PrintPage");
        PrintGridDelay(win);
    }
}
function PrintGridDelay(win) {
    var oIframe = jQuery(win.document.body);
    var oBody = oIframe.find("DIV[id$='pnlContent']");
    if (oBody.length == 0) {
        setTimeout(function () { PrintGridDelay(win); }, 100);
        return;
    }
    win.print();
    if (!win.closed) {
        win.close();
    }
}
var globalRemoveAttachFile = null;
var globalRemoveAttachCtrl = null;
function RemoveAttachLine(ctrl, f, message) {
    globalRemoveAttachCtrl = ctrl;
    globalRemoveAttachFile = f;
    jConfirm(message, "Confirm", RemoveAttachLineCallBack);
}
function RemoveAttachLineCallBack(result) {
    if (result) {
        var f = globalRemoveAttachFile;
        var ctrl = globalRemoveAttachCtrl;
        var hidFiles = jQuery("input[id$='hidAttachments']");
        var files = hidFiles.val();
        files = files.replace("*" + f, "");
        hidFiles.val(files);
        var parentCtrl = jQuery(ctrl).parent();
        parentCtrl.remove();
    }
}
function SetLeftHeight() {
    var leftObject = jQuery("div[id$='NavigationControl']");
    var leftControl = jQuery("DIV.leftNavi", leftObject);
    if (leftControl.length == 0) {
        leftControl = jQuery("DIV.MyTapiLeft", leftObject);
    }
    var rightHeight = jQuery("#divRightArea").height() - 20;
    if (minLeftNavHeight < rightHeight) {
        leftControl.css("height", rightHeight + "px");
    }
}
function getClientId(arr, id) {
    if (arr != null && arr != undefined && arr.length > 0) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].id == id) {
                return arr[i].ClientID;
            }
        }
    }
    return "";
}
function GetMaxLengthString(text, maxchars) {
    if (text != null && text != undefined && text.length > 0) {
        var atext = text.split(' ');
        var chars = 0;
        var newtext = "";
        maxchars = maxchars - 4;//the length of ' ...'
        for (var index = 0; index < atext.length; index++) {
            chars += atext[index].length + 1/*the space char removed with split*/;
            if (chars <= maxchars) {
                newtext += atext[index] + " ";
            } else {
                newtext += " ...";
                break;
            }
        }
        return newtext;
    } else {
        return "";
    }
}
function RequestItemsForCombobox(sender, eventArgs) {
    sender.requestItems("", false);
}
