//on page load call tb_init
var tb_timer1 = '';
var tb_timer2 = '';
var tb_scrollpos = 0;
$(document).ready(function () {
    tb_init('a.thickbox, area.thickbox, input.thickbox');
});

//add thickbox to href & area elements that have a class of .thickbox


function tb_init(domChunk) {
    $(domChunk).click(function () {
        var t = this.title || this.name || $(this).data('title') || null;
        var a = this.href || this.alt;
        var g = this.rel || false;
        tb_show(t, a, g);
        this.blur();
        return false;
    });
}

function tb_show(caption, url, imageGroup, callback) {
    tb_scrollpos = $(document).scrollTop();
    try {
        window["ajaxTimeoutCallback"] = null;
        if (typeof (callback) === "function") window["ajaxTimeoutCallback"] = callback;
		if (document.getElementById("TB_overlay") === null) {
			$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
			$("#TB_overlay").click(tb_remove);
		}
        if (tb_detectMacXFF()) {
            $("#TB_overlay").addClass("TB_overlayMacFFBGHack");
        } else {
            $("#TB_overlay").addClass("TB_overlayBG");
        }
        if (caption === null) {
            caption = "";
        }
        //$("body").append("<div id='TB_load'></div>"); //add loader to the page
        var baseURL;
        if (url.indexOf("?") !== -1) {
            //ff there is a query string involved
            baseURL = url.substr(0, url.indexOf("?"));
        } else {
            baseURL = url;
        }
        var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
        var urlType = baseURL.toLowerCase().match(urlString);
        // Create template
        var template = '';
        template += "<div id='TB_container1'>";
        template += "<div id='TB_header'><span class='a'></span><span class='b'></span><span class='c'></span></div>";
        template += "<div id='TB_main'><span class='main-a'></span><span class='main-c'></span><div class='main-b'><div id='TB_body' class='clear'>";
        if (typeof (locales) != 'undefined' && locales.simpleloader) {
            template += '<div id="TB_loader2" class="loader03 center"><span>' + locales.simpleloader + '</span></div>';
        } else {
            template += '<div id="TB_loader2" class="loader03 center"><span>...</span></div>';
        }
        template += "</div></div></div>";
        template += "<div id='TB_footer'><span class='a'></span><span class='b'></span><span class='c'></span></div>";
        template += "</div>";
        $("#TB_container1").remove();
        $("#TB_window").append(template);
        tb_timer1 = window.setTimeout('tb_preloader()', 1000);
        if (urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp') {
            //code to show images
            TB_PrevCaption = "";
            TB_PrevURL = "";
            TB_PrevHTML = "";
            TB_NextCaption = "";
            TB_NextURL = "";
            TB_NextHTML = "";
            TB_imageCount = "";
            TB_FoundURL = false;
            if (imageGroup) {
                TB_PrevHTML = "<a href='#' id='TB_prev'></a>";
                TB_NextHTML = "<a href='#' id='TB_next'></a>";
                TB_TempArray = $("a[rel=" + imageGroup + "]").get();
                for (TB_Counter = 0;
                ((TB_Counter < TB_TempArray.length) && (TB_NextURL === "")); TB_Counter++) {
                    var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
                    if (!(TB_TempArray[TB_Counter].href == url)) {
                        if (!TB_FoundURL) {
                            TB_PrevCaption = TB_TempArray[TB_Counter].title;
                            TB_PrevURL = TB_TempArray[TB_Counter].href;
                        } else {
                            TB_NextCaption = TB_TempArray[TB_Counter].title;
                            TB_NextURL = TB_TempArray[TB_Counter].href;
                        }
                    } else {
                        TB_FoundURL = true;
                        TB_imageCount = "<span id='TB_imgcount'>" + (TB_Counter + 1) + " / " + (TB_TempArray.length) + "</span>";
                    }
                }
            }
            imgPreloader = new Image();
            imgPreloader.onload = function () {
                imgPreloader.onload = null;
                // Resizing large images - orginal by Christian Montoya edited by me.
                var pagesize = tb_getPageSize();
                var x = pagesize[0] - 150;
                var y = pagesize[1] - 150;
                var imageWidth = imgPreloader.width;
                var imageHeight = imgPreloader.height;
                if (imageWidth > x) {
                    imageHeight = imageHeight * (x / imageWidth);
                    imageWidth = x;
                    if (imageHeight > y) {
                        imageWidth = imageWidth * (y / imageHeight);
                        imageHeight = y;
                    }
                } else if (imageHeight > y) {
                    imageWidth = imageWidth * (y / imageHeight);
                    imageHeight = y;
                    if (imageWidth > x) {
                        imageHeight = imageHeight * (x / imageWidth);
                        imageWidth = x;
                    }
                }
                // End Resizing
                TB_WIDTH = imageWidth;
                TB_HEIGHT = imageHeight;
                // Fixing small images - original by me :)
                var placeholderInject = '';
                var x2 = 300;
                var y2 = 250;
                var z = '';
                if (imageWidth < x2) {
                    TB_WIDTH = x2;
                    z += ' padding-left: ' + (x2 - imageWidth) / 2 + 'px;';
                    z += ' padding-right: ' + (x2 - imageWidth) / 2 + 'px;';
                }
                if (imageHeight < y2) {
                    TB_HEIGHT = y2;
                    z += ' padding-top: ' + (y2 - imageHeight) / 2 + 'px;';
                    z += ' padding-bottom: ' + (y2 - imageHeight) / 2 + 'px;';
                }
                placeholderInject = ' style="' + z + '"';
                var createwindow = ''
                createwindow += "<div class='clear' id='TB_ajaxWindowTitle'>";
                createwindow += "<a href='#' id='TB_closeWindowButton'></a>";
                createwindow += TB_PrevHTML;
                createwindow += TB_imageCount;
                createwindow += TB_NextHTML;
                createwindow += "</div>";
                createwindow += "<div id='TB_container2'><div id='TB_content_placeholder'><a href='' id='TB_ImageOff'" + placeholderInject + "><img id='TB_Image' src='" + url + "' width='" + imageWidth + "' height='" + imageHeight + "' alt=''/></a></div></div>";
                if (caption !== "") {
                    createwindow += "<div id='TB_caption'><p>" + caption + "</p></div>";
                }
                $("#TB_body").append(createwindow);
                $("#TB_closeWindowButton").click(function () {
                    tb_remove();
                    return false;
                });
                if (!(TB_PrevURL === "")) {
                    function goPrev() {
                        if ($(document).unbind("click", goPrev)) {
                            $(document).unbind("click", goPrev);
                        }
                        $("#TB_window").remove();
                        $("body").append("<div id='TB_window'></div>");
                        tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
                        return false;
                    }
                    $("#TB_prev").click(function () {
                        goPrev();
                        return false;
                    });
                } else {
                    $("#TB_prev").addClass('TB_disabled').click(function () {
                        return false;
                    });
                }
                if (!(TB_NextURL === "")) {
                    function goNext() {
                        $("#TB_window").remove();
                        $("body").append("<div id='TB_window'></div>");
                        tb_show(TB_NextCaption, TB_NextURL, imageGroup);
                        return false;
                    }
                    $("#TB_next").click(function () {
                        goNext();
                        return false;
                    });
                } else {
                    $("#TB_next").addClass('TB_disabled').click(function () {
                        return false;
                    });
                }
                document.onkeydown = function (e) {
                    if (e == null) { // ie
                        keycode = event.keyCode;
                    } else { // mozilla
                        keycode = e.which;
                    }
                    if (keycode == 27) { // close
                        tb_remove();
                    } else if (keycode == 190) { // display previous image
                        if (!(TB_NextHTML == "")) {
                            document.onkeydown = "";
                            goNext();
                        }
                    } else if (keycode == 188) { // display next image
                        if (!(TB_PrevURL == "")) {
                            document.onkeydown = "";
                            goPrev();
                        }
                    }
                };
                $("#TB_load").remove();
                $("#TB_ImageOff").click(tb_remove);
                tb_display();
            };
            imgPreloader.src = url;
        } else {
            //code to show html
            var queryString = url.replace(/^[^\?]+\??/, '');
            var params = tb_parseQuery(queryString);
            TB_WIDTH = (params['width'] * 1) || 630;
            TB_HEIGHT = (params['height'] * 1) || 440;
            ajaxContentW = TB_WIDTH;
            ajaxContentH = TB_HEIGHT;
            if (url.indexOf('TB_iframe') != -1) {
                // iframe
                urlNoQuery = url.split('#TB_');
                $("#TB_iframeContent").empty().remove();
                if (params['modal'] == "true") {
                    $("#TB_overlay").unbind();
                }
                $('#TB_content_placeholder').remove();
                $('#TB_body').append("<div id='TB_content_placeholder' class='hidden'><iframe frameborder='0' hspace='0' src='" + urlNoQuery[0] + "' id='TB_iframeContent' name='TB_iframeContent" + Math.round(Math.random() * 1000) + "' style='width:" + (ajaxContentW) + "px;height:" + (ajaxContentH) + "px;' scrolling='auto'></iframe></div>");
            } else {
                // inline
                if ($("#TB_window").hasClass('TB_window_visible') != true) {
                    if (params['modal'] == "true") {
                        $("#TB_overlay").unbind();
                    }
                    $('#TB_content_placeholder').remove();
                    $('#TB_body').append("<div id='TB_content_placeholder' class='hidden'><div id='TB_ajaxContent' style='width:" + ajaxContentW + "px;height:" + ajaxContentH + "px'></div></div>");
                } else {
                    //this means the window is already up, we are just loading new content via ajax
                    $("#TB_ajaxContent")[0].style.width = ajaxContentW + "px";
                    $("#TB_ajaxContent")[0].style.height = ajaxContentH + "px";
                    $("#TB_ajaxContent")[0].scrollTop = 0;
                    $("#TB_ajaxWindowTitle").html(caption);
                }
            }
            if (url.indexOf('TB_inline') != -1) {
                $('#TB_content_container').contents().unwrap();
                $("#TB_ajaxContent").append($('#' + params['inlineId']).children());
                $("#TB_window").unload(function () {
                    $('#' + params['inlineId']).append($("#TB_ajaxContent").children()); // move elements back when you're finished
                });
                if (url.indexOf('autoscale') != -1) {
                    $('#TB_ajaxContent').data('autoscale', params['autoscale']);
                }
                tb_display();
            } else if (url.indexOf('TB_iframe') != -1) {
                if (url.indexOf('autoscale') != -1) {
                    $('#TB_iframeContent').data('autoscale', params['autoscale']);
                }
                $('#TB_iframeContent').load(tb_display);
            } else {
                $("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()), function () {
                    $("#TB_load").remove();
                    tb_init("#TB_ajaxContent A.thickbox");
                });
                tb_display();
            }
        }
        if (!params['modal']) {
            document.onkeyup = function (e) {
                if (e == null) { // ie
                    keycode = event.keyCode;
                } else { // mozilla
                    keycode = e.which;
                }
                if (keycode == 27) { // close
                    tb_remove();
                }
            };
        }
    } catch (e) {}
}

function tb_preloader() {
    $("#TB_window").removeClass('TB_window_hidden').addClass('TB_window_visible');
    $("#TB_window").css({
        width: '10000px'
    });
    var tb_tmp01w = $('#TB_window').outerWidth() - $('#TB_body').outerWidth() + 200;
    var tb_tmp01h = $('#TB_window').outerHeight() - $('#TB_body').outerHeight() + 100;
    $("#TB_window").css({
        marginLeft: '-' + parseInt((tb_tmp01w / 2), 10) + 'px',
        width: tb_tmp01w + 'px'
    });
    if (!(jQuery.browser.msie6)) {
        $("#TB_window").css({
            marginTop: '-' + parseInt(($("#TB_window").outerHeight() / 2), 10) + 'px'
        });
    }
}
// All the positioning and resizing functionality.

function tb_scale() {
    $("#TB_window").removeClass('TB_window_hidden').addClass('TB_window_visible');
    $("#TB_content_placeholder").removeClass('hidden');
    $("#TB_loader2").addClass('hidden');
    if ($('#TB_iframeContent').length > 0 && $('#TB_iframeContent').data('autoscale') == 1) {
        // autoscale 1 - content resize changes window height, iframe
        var $contents = $('#TB_iframeContent').contents();
        $contents.find('HTML').css({
            overflowX: 'hidden',
            overflowY: 'auto'
        });
        if ($contents.find('BODY').outerHeight() < tb_getPageSize()[1] - 150) {
            TB_HEIGHT2 = $contents.find('BODY').outerHeight() + 2;
            TB_WIDTH2 = TB_WIDTH;
            $('#TB_main DIV.main-b').css({
                marginRight: '35px'
            });
        } else {
            TB_HEIGHT2 = tb_getPageSize()[1] - 150;
            TB_WIDTH2 = TB_WIDTH + 30;
            $('#TB_main DIV.main-b').css({
                marginRight: '20px'
            });
            $contents.find('HTML').css({
                overflowY: 'auto'
            });
        }
        $('#TB_iframeContent').css('width', TB_WIDTH2 + 'px');
        $contents.find('#TB_content_container').css('width', TB_WIDTH);
        $('#TB_iframeContent').css('height', TB_HEIGHT2);
    } else if ($('#TB_iframeContent').length > 0 && $('#TB_iframeContent').data('autoscale') == 2) {
        // autoscale 2 - content does not resize window height, iframe
        var $contents = $('#TB_iframeContent').contents();
        $contents.find('HTML').css({
            overflowX: 'hidden',
            overflowY: 'auto'
        });
        TB_HEIGHT2 = TB_HEIGHT;
        if ($contents.find('BODY').outerHeight() < TB_HEIGHT) {
            TB_WIDTH2 = TB_WIDTH;
            $('#TB_main DIV.main-b').css({
                marginRight: '35px'
            });
        } else {
            TB_WIDTH2 = TB_WIDTH + 30;
            $('#TB_main DIV.main-b').css({
                marginRight: '20px'
            });
            $contents.find('HTML').css({
                overflowY: 'auto'
            });
        }
        $contents.find('#TB_content_container').css('width', TB_WIDTH)
        $('#TB_iframeContent').css({
            width: TB_WIDTH2 + 'px',
            height: TB_HEIGHT2 + 'px'
        });
    } else if ($('#TB_ajaxContent').length > 0 && $('#TB_ajaxContent').data('autoscale') == 1) {
        // autoscale 1 - content resize changes window height, div
        if ($('#TB_content_container').outerHeight() < tb_getPageSize()[1] - 150) {
            TB_HEIGHT2 = $('#TB_content_container').outerHeight();
            TB_WIDTH2 = TB_WIDTH;
            $('#TB_main DIV.main-b').css({
                marginRight: '35px'
            });
        } else {
            TB_HEIGHT2 = tb_getPageSize()[1] - 150;
            TB_WIDTH2 = TB_WIDTH + 30;
            $('#TB_main DIV.main-b').css({
                marginRight: '20px'
            });
        }
        $('#TB_ajaxContent').css('width', TB_WIDTH2 + 'px').find('#TB_content_container').css('width', TB_WIDTH);
        $('#TB_ajaxContent').css('height', TB_HEIGHT2);
    } else if ($('#TB_ajaxContent').length > 0 && $('#TB_ajaxContent').data('autoscale') == 2) {
        // autoscale 2 - content does not resize window height, div
        TB_HEIGHT2 = TB_HEIGHT;
        if ($('#TB_content_container').outerHeight() < TB_HEIGHT) {
            TB_WIDTH2 = TB_WIDTH;
            $('#TB_main DIV.main-b').css({
                marginRight: '35px'
            });
        } else {
            TB_WIDTH2 = TB_WIDTH + 30;
            $('#TB_main DIV.main-b').css({
                marginRight: '20px'
            });
        }
        $('#TB_ajaxContent').css('width', TB_WIDTH2 + 'px').find('#TB_content_container').css('width', TB_WIDTH);
        $('#TB_ajaxContent').css('height', TB_HEIGHT2);
    } else {
        // no autoscale - fixed everything
        if ($('#TB_iframeContent').length > 0) {
            $('#TB_iframeContent').contents().find('HTML').css({
                overflow: 'hidden'
            });
        }
        if ($('#TB_ajaxContent').length > 0) {
            $('#TB_ajaxContent').css({
                overflow: 'hidden'
            });
        }
        TB_WIDTH2 = TB_WIDTH;
        TB_HEIGHT2 = TB_HEIGHT;
    }
    $('#TB_content_placeholder').css({
        width: TB_WIDTH2 + 'px',
        height: TB_HEIGHT2 + 'px'
    });
    $("#TB_window").css({
        width: '10000px'
    });
    var tb_tmp01w = $('#TB_window').outerWidth() - $('#TB_body').outerWidth() + TB_WIDTH2;
    var tb_tmp01h = $('#TB_window').outerHeight() - $('#TB_body').outerHeight() + TB_HEIGHT2;
    $("#TB_window").css({
        marginLeft: '-' + parseInt((tb_tmp01w / 2), 10) + 'px',
        width: tb_tmp01w + 'px',
        left: '50%',
        top: '50%'
    });
    if (!(jQuery.browser.msie6)) {
        $("#TB_window").css({
            marginTop: '-' + parseInt(($("#TB_window").outerHeight() / 2), 10) + 'px'
        });
    }
    if (tb_tmp01w > $(window).width()) {
        $("#TB_window").css({
            marginLeft: 0,
            left: 0
        });
    }
    if (tb_tmp01h > $(window).height()) {
        $("#TB_window").css({
            top: $(document).scrollTop() + 'px',
            marginTop: 0
        });
    }
    if (tb_tmp01w > $(window).width() || tb_tmp01h > $(window).height()) {
        // thickbox is wider than can fit in the viewport
        $('BODY').addClass('TB_cantfit');
    } else {
        $('BODY').removeClass('TB_cantfit');
    }
    $("#TB_window").removeClass('TB_window_hidden').addClass('TB_window_visible');
}

function tb_display() {
    var $contents = $('#TB_iframeContent').contents();
    if ($('#TB_iframeContent').data('autoscale')) {
        $contents.find('BODY').bind('blur focus mousedown mouseup click', function () {
            tb_timer2 = window.setTimeout('tb_scale()', 1);
        });
        $contents.find('BODY').wrapInner('<div id="TB_content_container"></div>');
    }
    if ($('#TB_ajaxContent').data('autoscale')) {
        $('#TB_ajaxContent').bind('blur focus mousedown mouseup click', function () {
            tb_timer2 = window.setTimeout('tb_scale()', 1);
        });
        if ($('#TB_ajaxContent #TB_content_container').length == 0) {
            $('#TB_ajaxContent').wrapInner('<div id="TB_content_container"></div>');
        }
    }
    window.clearTimeout(tb_timer1);
    window.clearTimeout(tb_timer2);
    $("#TB_load").remove();
    $(window).bind('resize.thickbox', tb_scale);
    tb_scale();
}

function tb_remove() {
    window.clearTimeout(tb_timer1);
    window.clearTimeout(tb_timer2);
    $("#TB_ImageOff").unbind("click");
    $('#TB_window, #TB_overlay').trigger("unload").unbind().remove();
    $("#TB_load").remove();
    document.onkeydown = "";
    document.onkeyup = "";
    $(document).scrollTop(tb_scrollpos);
    $(window).unbind('thickbox');
    $('BODY').removeClass('TB_cantfit');
    return false;
}

function tb_parseQuery(query) {
    var Params = {};
    if (!query) {
        return Params;
    } // return empty object
    var Pairs = query.split(/[;&]/);
    for (var i = 0; i < Pairs.length; i++) {
        var KeyVal = Pairs[i].split('=');
        if (!KeyVal || KeyVal.length != 2) {
            continue;
        }
        var key = unescape(KeyVal[0]);
        var val = unescape(KeyVal[1]);
        val = val.replace(/\+/g, ' ');
        Params[key] = val;
    }
    return Params;
}

function tb_getPageSize() {
    var de = document.documentElement;
    var w = window.innerWidth || self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
    var h = window.innerHeight || self.innerHeight || (de && de.clientHeight) || document.body.clientHeight;
    arrayPageSize = [w, h];
    return arrayPageSize;
}

function tb_detectMacXFF() {
    var userAgent = navigator.userAgent.toLowerCase();
    if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1) {
        return true;
    }
}
