var amountOfSelectedImages = 0;

$(document).ready(function () {
    clearfield();

    $(".PartyVinderStage.OverView .PartyTicketArea").prepend("<div class='emptyParty' style='height:78px;'></div><div class='emptyParty' style='height:78px;'></div>");
    $(".PartyVinderStage.OverView .PartyTicketArea").append("<div class='emptyParty' style='height:92px;width:100%;'></div><div class='emptyParty' style='height:92px;width:100%;'></div>");

    $("#backgroundIMG").fullBg();




    (function($, window, undefined){
        var tvbanner = $('a.tv_banner');
        if(tvbanner.length > 1){
            var _mouseover = false;
            var speed = 800; // angabe in millisekunden wie lange die ueberblendung dauern soll
            var showtime = 5000; // angabe in millisekunden wie lange das element sichtbar sein soll,
                                 // bis es wieder ausgeblendet wird.
            var tvbannerdiv = $('<div class="tv_banner_rot" />');
            tvbanner.first().before(tvbannerdiv);
            tvbannerdiv.append(tvbanner);
            var loaderBox = $('<div class="loaderBox" />');
            var loaderBar = $('<div class="loaderBar" />');
            loaderBox.append(loaderBar);
            tvbannerdiv.append(loaderBox);
            var active_banner = 0;
            var next_banner = active_banner+1;
            tvbanner.hide().css('zIndex', 1);
            tvbanner.first().show();
            var timer;
            var isFading = false;
            tvbannerdiv.height(tvbanner.eq(next_banner).height());
            tvbannerdiv.width(tvbanner.eq(next_banner).width());
            var banner_rot = function(){
                if(isFading || _mouseover){return;}
                window.clearTimeout(timer);
                if(active_banner >= tvbanner.length){ active_banner = 0; }
                if(next_banner >= tvbanner.length){ next_banner = 0; }
                
                tvbannerdiv.height(tvbanner.eq(next_banner).height());
                tvbannerdiv.width(tvbanner.eq(next_banner).width());
                
                tvbanner.eq(active_banner).css('zIndex', 10);
                tvbanner.eq(next_banner).css('zIndex', 20).fadeIn(speed, showComplete);
                loaderBar.stop(true).css('width', '100%').animate({width: '0'}, speed, 'linear');
                
                isFading = true;
            }
            var showComplete = function(){
                tvbanner.eq(active_banner).css('zIndex', 1).hide();
                    
                active_banner++;
                next_banner++;
                
                isFading = false;
                showtimed();
            }
            var showtimed = function(time){
                time = time || showtime;
                loaderBar.stop(true).css('width', 0).animate({width: '100%'}, time, 'linear');
                timer = window.setTimeout(function(){
                    banner_rot();
                }, time);
            }
            tvbannerdiv.mouseover(function(){
                if(!hasBlured){
                    loaderBar.stop(true, true).css('width', 0);
                    tvbanner.eq(next_banner).stop(true, true);
                    isFading = false;
                    _mouseover = true;
                    window.clearTimeout(timer);
                }
            });
            tvbannerdiv.mouseleave(function(){
                if(!hasBlured){
                    _mouseover = false;
                    showtimed(500);
                }
            });
            
            var hasBlured = false;
            function onBlur() {
                hasBlured = true;
                loaderBar.stop(true, true).css('width', 0);
                tvbanner.eq(next_banner).stop(true, true);
                isFading = false;
                _mouseover = true;
                window.clearTimeout(timer);
            };
            function onFocus(){
                if(hasBlured){
                    _mouseover = false;
                    showtimed(showtime);
                }
                hasBlured = false;
            };

            if (/*@cc_on!@*/false) { // check for Internet Explorer
                document.onfocusin = onFocus;
                document.onfocusout = onBlur;
            } else {
                window.onfocus = onFocus;
                window.onblur = onBlur;
            }
            
            showtimed();
        }
    })(jQuery, window);




    //Scrollpane
    $('.scroll-pane').jScrollPane({
        showArrows: true,
        verticalDragMaxHeight: 54,
        verticalDragMinHeight: 54
    });

    $('.CodeFormular input.CodeField').autotab_magic();

    //Add Lightbox for Text
    $("a[rel^='lightboxText']").click(function () {
        var messageID = $(this).attr('href');
        showMessage(messageID, "");
        return false;
    });
    if(location.href.toLowerCase().indexOf('teilnahmebedingungen') > 0){
        showMessage('TEILNAHMEBEDINGUNGEN', "");
    }

    //Add lightbox for Photos 
    initImgLightwindow();

    //$("a[bild^='1008_002']").click();
    //$(".imgSelect a:first").dispatchEvent("click");
    //$("a[bild^='1008_002']").click();
    //init IMG Slider
    initSlider();

    //Add Custom Styles
    $('select').customStyle();
    $("input:radio:checked, input:checkbox:checked").each(function (i) {
        $(this).parent(".Checkbox").addClass("True");
    });

    $("input:radio, input:checkbox").click(function () {
        /*
        if ($(this).hasClass("radiobutton_gender")) {
            $(".radiobutton_gender").parent(".Checkbox").children("input").attr("checked", "");
            $(".radiobutton_gender").parent(".Checkbox").removeClass("True");
            $(this).attr('checked', false);
        }
        if ($(this).hasClass("radio_gender")) {
            $(".radio_gender").parent(".Checkbox").children("input").attr("checked", "");
            $(".radio_gender").parent(".Checkbox").removeClass("True");
            $(this).attr('checked', false);
        }
        */
        if ($(this).hasClass("radio_flyer")) {
            $(".radio_flyer").parent(".Checkbox").children("input").attr("checked", "");
            $(".radio_flyer").parent(".Checkbox").removeClass("True");
            $(this).attr('checked', false);
        }
        if ($(this).hasClass("radio_plakat")) {
            $(".radio_plakat").parent(".Checkbox").children("input").attr("checked", "");
            $(".radio_plakat").parent(".Checkbox").removeClass("True");
            $(this).attr('checked', false);
        }
        if ($(this).hasClass("radio_werbung")) {
            $(".radio_werbung").parent(".Checkbox").children("input").attr("checked", "");
            $(".radio_werbung").parent(".Checkbox").removeClass("True");
            $(this).attr('checked', false);
        }
        if($(this).parent(".Checkbox").length > 0){
            if ($(this).parent(".Checkbox").hasClass("True")) {
                $(this).parent(".Checkbox").removeClass("True");
                $(this).attr('checked', false);
            } else {
                $(this).parent(".Checkbox").addClass("True");
                $(this).parent(".Checkbox").children().attr('checked', 'checked');
                $(this).attr('checked', true);
            }
        }
    });
   
    $('#ende_gewinnvestival_teilnahme').click(function() {
            $('.ende_gewinnvestival_start').css("display", "none"); 
            $('.ende_gewinnvestival_teilnahmebedingung').css("display", "block");
    });   
    $('#ende_gewinnvestival_close').click(function() {
            $('.ende_gewinnvestival_start').css("display", "block"); 
            $('.ende_gewinnvestival_teilnahmebedingung').css("display", "none");
    });
    
    $('.registrierformular input').focus(function() {
        $('.registrierformular input').removeClass("orange");
        $(this).addClass("orange");
    });
    $('#form_pwrecover input').focus(function() {
        $('#form_pwrecover input').removeClass("orange");
        $(this).addClass("orange");
    });

    
    /*
    if('.dsds2012 .content_container.xlarge .Item')
        $('.dsds2012 .content_container.xlarge .Item').removeAttr("style");
    */

    /*
    $('#ende_gewinnvestival_close').click(function() {
            $('.ende_gewinnvestival_start').css("display", "block"); 
            $('.ende_gewinnvestival_teilnahmebedingung').css("display", "none");
    });  
    */
});

function initSlider() {
    var i = 0;
    var imgSelectWidth = 152;
    var pageingwidth = 5;
    var finished = true;
    var currentpage = 1;

    if (amountOfSelectedImages == 1) $(".FotoDownloadArea .DownloadText p").text(amountOfSelectedImages + " Foto");
    else $(".FotoDownloadArea .DownloadText p").text(amountOfSelectedImages + " Fotos");

    $(".FotoSlide .imgSelect").each(function () {
        i++;
    });

    $(".FotoSlide").css("width", i * imgSelectWidth + "px");

    var amountOfPages = Math.ceil(i / pageingwidth);

    for (var y = 1; y <= amountOfPages; y++) {
        $(".ToolFotoSlide .BGFotoSlide span").append("<a class='pages' href='#'>" + y + "</a>");
    }

    if (amountOfPages > 7) {
        $(".ToolFotoSlide span").prepend("<a class='pagePrev' href='#'>...</a>");
        $(".ToolFotoSlide span").append("<a class='pageNext' href='#'>...</a>");
        $(".ToolFotoSlide span a.pageNext").click(function () {
            $(".ToolFotoSlide .FotoNext").click();
            return false;
        });
        $(".ToolFotoSlide span a.pagePrev").click(function () {
            $(".ToolFotoSlide .FotoPrevious").click();
            return false;
        });
    }

    $(".ToolFotoSlide span a.pages:first").addClass("active");
    $(".ToolFotoSlide span a.pages:first").addClass("not");
    $(".ToolFotoSlide .FotoPrevious").addClass("not");

    refreshpages();

    function refreshpages() {
        //alert(currentpage);
        if (amountOfPages > 7) {
            $(".ToolFotoSlide .BGFotoSlide span a.pages").each(function (i) {
                if (currentpage == 1) $(".ToolFotoSlide span a.pagePrev").hide();
                else $(".ToolFotoSlide span a.pagePrev").show();
                if (currentpage == amountOfPages) $(".ToolFotoSlide span a.pageNext").hide();
                else $(".ToolFotoSlide span a.pageNext").show();
                $(this).hide();
                $(this).removeClass("active");
                var betweenMin = currentpage - 2;
                var betweenMax = currentpage + 2;
                if (parseInt($(this).text()) >= betweenMin && parseInt($(this).text()) <= betweenMax) {
                    $(this).show();
                }
                if (parseInt($(this).text()) == currentpage) {
                    $(this).addClass("active");
                }
            });
        }
    }

    $(".ToolFotoSlide span a.pages").click(function () {
        $(".ToolFotoSlide span a.pages").removeClass("not");
        $(this).addClass("not");
        var clickedPage = parseInt($(this).text()) - 1;
        $(".ToolFotoSlide span a.pages").removeClass("active");
        $(this).addClass("active");
        finished = false;
        $(".FotoSlide").animate({
            left: ((pageingwidth * clickedPage) * imgSelectWidth) * -1
        }, 500, function () {
            finished = true
        });
        positionLeft = $(".FotoSlide").position().left;
        currentpage = clickedPage + 1;
        refreshpages();
        if ($(".ToolFotoSlide span a.pages.active").text() == amountOfPages) {
            $(".ToolFotoSlide .FotoNext").addClass("not");
            $(".ToolFotoSlide .FotoPrevious").removeClass("not");
        }
        if ($(".ToolFotoSlide span a.pages.active").text() == 1) {
            $(".ToolFotoSlide .FotoPrevious").addClass("not");
            $(".ToolFotoSlide .FotoNext").removeClass("not");
        }
        return false;
    });

    $(".ToolFotoSlide .FotoPrevious, .ToolFotoSlide span a.pagePrev").click(function () {
        if (finished == true && $(".FotoSlide").position().left < 0) {
            $(this).removeClass("not");
            $(".ToolFotoSlide span a.pages.active").prev().addClass("TMPactive");
            $(".ToolFotoSlide span a.pages.active").removeClass("active");
            $(".ToolFotoSlide span a.pages.TMPactive").removeClass("TMPactive").addClass("active");
            $(".ToolFotoSlide span a.pages").removeClass("not");
            $(".ToolFotoSlide span a.pages.active").addClass("not");
            $(".ToolFotoSlide .FotoNext, .ToolFotoSlide span a.pageNext").removeClass("not");
            if ($(".ToolFotoSlide span a.pages.active").text() == amountOfPages) $(".ToolFotoSlide .FotoPrevious").addClass("not");
            if ($(".ToolFotoSlide span a.pages.active").text() == 1) $(".ToolFotoSlide .FotoPrevious").addClass("not");
            finished = false;
            $(".FotoSlide").animate({
                left: "+=" + pageingwidth * imgSelectWidth
            }, 500, function () {
                finished = true
            });
            currentpage--;
        } else $(this).addClass("not");
        refreshpages();
        return false;
    });

    $(".ToolFotoSlide .FotoNext, .ToolFotoSlide span a.pageNext").click(function () {
        if (finished == true && ($(".FotoSlide").position().left * -1) < (imgSelectWidth * (i - 9))) {
            $(".ToolFotoSlide span a.pages.active").next().addClass("TMPactive");
            $(".ToolFotoSlide span a.pages.active").removeClass("active");
            $(".ToolFotoSlide span a.pages.TMPactive").removeClass("TMPactive").addClass("active");
            $(".ToolFotoSlide span a.pages").removeClass("not");
            $(".ToolFotoSlide span a.pages.active").addClass("not");
            $(".ToolFotoSlide .FotoPrevious, .ToolFotoSlide span a.pagePrev").removeClass("not");
            if ($(".ToolFotoSlide span a.pages.active").text() == amountOfPages) $(".ToolFotoSlide .FotoNext").addClass("not");
            if ($(".ToolFotoSlide span a.pages.active").text() == 1) $(".ToolFotoSlide .FotoPrevious").addClass("not");
            finished = false;
            $(".FotoSlide").animate({
                left: "-=" + pageingwidth * imgSelectWidth
            }, 500, function () {
                finished = true
            });
            currentpage++;
        }
        refreshpages();
        return false;
    });

    $(".DownloadText a").click(function () {
        //var download = new Array(); 
        var download = "";
        $(".FotoSlide .pseudoCheckbox.active").each(function () {
            //download.push($(this).parent(".imgSelect").children("a").attr("id"));
            download += $(this).parent(".imgSelect").children("a").attr("id") + "+";
        });
        //alert(download);
        //alert($(".FotoDownloadArea .BtnDownloadStart").attr("href"));
/*$.post($(".FotoDownloadArea .BtnDownloadStart").attr("href"), {
          download: download
      });*/
        $(".ImageDownload").append('<input id="download" style="display:none" name="download[]" type="text" />');
        $(".ImageDownload #download").val(download);
        $(".ImageDownload").submit();

/*$(".ImageDownload").append('<input id="download" name="download[]" type="hidden" />');
    $(".ImageDownload #download").val(download);
    $(".ImageDownload").submit();*/
        //$.post($(".BtnDownloadStart").attr("href"), { download: download } );
        return false;
    });

    $(".FotoSlide .pseudoCheckbox").click(function () {
        if ($(this).hasClass("active")) {
            $(this).removeClass("active");
            amountOfSelectedImages--;
            if (amountOfSelectedImages == 1) $(".FotoDownloadArea .DownloadText p").text(amountOfSelectedImages + " Foto");
            else $(".FotoDownloadArea .DownloadText p").text(amountOfSelectedImages + " Fotos");
        } else {
            $(this).addClass("active");
            amountOfSelectedImages++;
            if (amountOfSelectedImages == 1) $(".FotoDownloadArea .DownloadText p").text(amountOfSelectedImages + " Foto");
            else $(".FotoDownloadArea .DownloadText p").text(amountOfSelectedImages + " Fotos");
        }
    });
}

//create message lightbox
var isShowMessage = false;
function showMessage(messageID, html) {
    isShowMessage = true;
    var html = html;
    $.ajax({
        type: "GET",
        url: "fileadmin/xml/messages.xml",
        dataType: "xml",
        success: function (xml) {
            $(xml).find('message').each(function () {
                var id = $(this).attr('id');
                if (messageID == id) {
                    var extraClass = $(this).find('extraClass').text();
                    var additionalClass = $(this).find('additionalClass').text();
                    var headline = $(this).find('headline').text();
                    if (html == undefined || html == "") html = $(this).find('html').text();
                    createLightbox(extraClass, additionalClass, headline, html);
                }
            });
        }
    });
}

function createLightbox(extraClass, additionalClass, headline, html) {
    $("#myFlashContent").hide();
    var htmlMessage = '<div id="Layer" style="display:none"></div>\
                  <div id="LightBox" display:none;" class="' + extraClass + '">\
                  <div class="LightBoxArea">\
                  <div class="LightBoxTop ' + additionalClass + '">\
                      <a href="#" class="ClosedLink"></a>\
                      <div class="LightBoxMain">\
                      <h3>' + headline + '</h3>\
                      ' + html + '\
                      </div>\
                    </div>\
                    </div>\
                    <div class="LightBoxBottom"> </div>\
                  </div>';
    $("body #Container").prepend(htmlMessage);
    $("#Layer").height($(window).height());
    $("#Layer").fadeTo("500", 0.8)
    $("#LightBox").fadeIn(500);
    $('#LightBox .scroll-pane').jScrollPane({
        showArrows: true
    });
    var api = $("#LightBox .scroll-pane").data('jsp');
    if (api != undefined) api.reinitialise();
    $("#LightBox .ClosedLink, #Layer, #LightBox .close").click(function () {
        closeLightbox();
        isShowMessage = false;
        $("#myFlashContent").show();
        $("#Layer, #LightBox").fadeOut(500, function () {
            $("#Layer, #LightBox").remove()
        });
        return false;
    });
}

function closeLightbox(){
    isShowMessage = false;
    $("#myFlashContent").show();
    $("#Layer, #LightBox").fadeOut(500, function () {
        $("#Layer, #LightBox").remove()
    });
}

function updateFBUrl(likeURL) {
    var fbURL = '<a target="_blank" href="http://de.facebook.com/sharer.php?u=' + likeURL + '" class="facebookShare">Bild teilen</a>';
    //var fbURL = '<iframe src="http://www.facebook.com/plugins/like.php?href=' + likeURL + '&amp;layout=button_count&amp;show_faces=false&amp;width=120&amp;action=like&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:120px; height:21px;" allowTransparency="true"></iframe>';
    return fbURL;
}

// init IMG Lightwindow


function initImgLightwindow() {
    var current = null;
    $("a[rel^='lightboxImg']").click(function () {
        //$(this).children("checkbox").val(1);
        current = $(this);
        var imgURL = $(this).attr("href"); //.children(".selected"
        var likeURL = escape(document.URL + "&imgid=" + current.attr("bild"));
        var currentID = $(this).attr("id");
        var headline = "";
        var htmlMessage = '<span class="numbersLightwindow"></span>\
					<div class="LightBoxImgContent LightBoxImgBg">\
                    <a class="prev scroll" href="#">prev</a>\
                    <div class="imgContainer">\
                      <div class="imgOverlay">\
                          <span class="pseudoCheckbox">Bild in den Download Ordner legen</span>\
                            <span class="downloadImg">Bild Downloaden</span>\
                        </div>\
                        <div style="text-align:center">\
                            <img class="contentImg" src="' + imgURL + '">\
                        </div>\
                    </div>\
                    <a class="next scroll" href="#">next</a>\
                    <div class="imgFooter">\
                          <span class="nr"></span>\
                            <span class="backtotheparty close">zurück</span>\
                            <span class="facebookShare">' + updateFBUrl(likeURL) + '</span>\
                            <br />\
                            <span class="text"></span>\
                            <a class="announceImg" href="/home/footer/kontakt/?reportImage=">Bild Melden</a>\
                    </div>\
                 </div>';
        //Erstelle Ligthbox
        createLightbox("LightBoxImg", headline, htmlMessage);
        if (current.parent(".imgSelect").children(".pseudoCheckbox").hasClass("active")) $("#LightBox .imgOverlay .pseudoCheckbox").addClass("active");

        var imagesAmount = 0;
        $(".FotoSlide .imgSelect").each(function () {
            imagesAmount++;
            $(this).children("a").attr("number", imagesAmount);
        });			
        $("#LightBox .numbersLightwindow").text(current.attr("number") + "/" + imagesAmount);
		if (imagesAmount == 0)
			$("#LightBox .numbersLightwindow").text("");	
        $("#LightBox .contentImg").attr("src", current.attr("href")).attr("alt", current.children("img")).attr("alt", current.children("img").attr("title"));
        //$("#LightBox .imgFooter .nr").text(current.attr("id"));
        $("#LightBox .imgFooter .nr").hide();
        $("#LightBox .imgFooter .announceImg").attr("href", "/home/footer/kontakt/?reportImage=" + current.attr("id"));
        $("#LightBox .imgFooter .text").text(current.children(".revieImageCaption").text());
        //Add Events für Blättern
        //vorwärts
		
		if (current.hasClass("location"))
		{
			$("#LightBox .next").css("background-image", "none");
			$("#LightBox .prev").css("background-image", "none");
			$("#LightBox .imgOverlay").remove();
			$("#LightBox .announceImg").remove();
		}
		
        $("#LightBox .next").click(function () {
            $("#LightBox .imgOverlay .pseudoCheckbox").removeClass("active");
            if (current.parent(".imgSelect").next(".imgSelect").children("a").html() != null) {
                current = current.parent(".imgSelect").next(".imgSelect").children("a");
            } else {
                current = $("a[rel^='lightboxImg']:first");
            }
            currentID = current.attr("id");
            if (current.parent(".imgSelect").children(".pseudoCheckbox").hasClass("active")) $("#LightBox .imgOverlay .pseudoCheckbox").addClass("active");
            $("#LightBox .contentImg").attr("src", current.attr("href")).attr("alt", current.children("img")).attr("alt", current.children("img").attr("title"));
            //$("#LightBox .imgFooter .nr").text(current.attr("title"));
            $("#LightBox .imgFooter .text").text(current.children(".revieImageCaption").text());
            $("#LightBox .imgFooter .facebookShare").html(updateFBUrl(escape(document.URL + "&imgid=" + current.attr("bild"))));
            $("#LightBox .imgFooter .announceImg").attr("href", "/home/footer/kontakt/?reportImage=" + current.attr("id"));
            $("#LightBox .numbersLightwindow").text(current.attr("number") + "/" + imagesAmount);
            return false;
        });
        //rückwärts
        $("#LightBox .prev").click(function () {
            $("#LightBox .imgOverlay .pseudoCheckbox").removeClass("active");
            if (current.parent(".imgSelect").prev(".imgSelect").children("a").html() != null) {
                current = current.parent(".imgSelect").prev(".imgSelect").children("a");
            } else {
                current = $("a[rel^='lightboxImg']:last");
            }
            currentID = current.attr("id");
            if (current.parent(".imgSelect").children(".pseudoCheckbox").hasClass("active")) $("#LightBox .imgOverlay .pseudoCheckbox").addClass("active");
            $("#LightBox .contentImg").attr("src", current.attr("href")).attr("alt", current.children("img")).attr("alt", current.children("img").attr("title"));
            //$("#LightBox .imgFooter .nr").text(current.attr("title"));
            $("#LightBox .imgFooter .text").text(current.children(".revieImageCaption").text());
            $("#LightBox .imgFooter .facebookShare").html(updateFBUrl(escape(document.URL + "&imgid=" + current.attr("bild"))));
            $("#LightBox .imgFooter .announceImg").attr("href", "/home/footer/kontakt/?reportImage=" + current.attr("id"));
            $("#LightBox .numbersLightwindow").text(current.attr("number") + "/" + imagesAmount);
            return false;
        });
        //Bild auswählen
        $("#LightBox .pseudoCheckbox").click(function () {
            if ($(this).hasClass("active")) {
                $(this).removeClass("active");
                current.parent(".imgSelect").children(".pseudoCheckbox").removeClass("active");
                amountOfSelectedImages--;
                if (amountOfSelectedImages == 1) $(".FotoDownloadArea .DownloadText p").text(amountOfSelectedImages + " Foto");
                else $(".FotoDownloadArea .DownloadText p").text(amountOfSelectedImages + " Fotos");
            } else {
                $(this).addClass("active");
                current.parent(".imgSelect").children(".pseudoCheckbox").addClass("active");
                amountOfSelectedImages++;
                if (amountOfSelectedImages == 1) $(".FotoDownloadArea .DownloadText p").text(amountOfSelectedImages + " Foto");
                else $(".FotoDownloadArea .DownloadText p").text(amountOfSelectedImages + " Fotos");
            }
        });
        $("#LightBox .downloadImg").click(function () {
            $(".ImageDownload").append('<input id="download" style="display:none" name="download[]" type="text" />');
            $(".ImageDownload #download").val(current.attr("id"));
            $(".ImageDownload").submit();
            return false;
        });
        $("#LightBox .downloadImg").hover(

        function () {
            $(this).toggleClass("active");
        }, function () {
            $(this).toggleClass("active");
        });
        $("#LightBox .imgFooter .backtotheparty").hover(

        function () {
            $(this).toggleClass("active");
        }, function () {
            $(this).toggleClass("active");
        });
        return false;
    });
}

function MM_preloadImages() { //v3.0
    var d = document;
    if (d.images) {
        if (!d.MM_p) d.MM_p = new Array();
        var i, j = d.MM_p.length,
            a = MM_preloadImages.arguments;
        for (i = 0; i < a.length; i++)
        if (a[i].indexOf("#") != 0) {
            d.MM_p[j] = new Image;
            d.MM_p[j++].src = a[i];
        }
    }
}

function MM_findObj(n, d) { //v4.01
    var p, i, x;
    if (!d) d = document;
    if ((p = n.indexOf("?")) > 0 && parent.frames.length) {

        d = parent.frames[n.substring(p + 1)].document;
        n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) x = d.all[n];
    for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n);
    return x;
}

function MM_nbGroup(event, grpName) { //v3.0
    var i, img, nbArr, args = MM_nbGroup.arguments;
    if (event == "init" && args.length > 2) {
        if ((img = MM_findObj(args[2])) != null && !img.MM_init) {
            img.MM_init = true;
            img.MM_up = args[3];
            img.MM_dn = img.src;
            if ((nbArr = document[grpName]) == null) nbArr = document[grpName] = new Array();
            nbArr[nbArr.length] = img;
            for (i = 4; i < args.length - 1; i += 2) if ((img = MM_findObj(args[i])) != null) {
                if (!img.MM_up) img.MM_up = img.src;
                img.src = img.MM_dn = args[i + 1];
                nbArr[nbArr.length] = img;
            }
        }
    } else if (event == "over") {
        document.MM_nbOver = nbArr = new Array();
        for (i = 1; i < args.length - 1; i += 3) if ((img = MM_findObj(args[i])) != null) {
            if (!img.MM_up) img.MM_up = img.src;
            img.src = (img.MM_dn && args[i + 2]) ? args[i + 2] : args[i + 1];
            nbArr[nbArr.length] = img;
        }
    } else if (event == "out") {
        for (i = 0; i < document.MM_nbOver.length; i++) {
            img = document.MM_nbOver[i];
            img.src = (img.MM_dn) ? img.MM_dn : img.MM_up;
        }
    } else if (event == "down") {
        if ((nbArr = document[grpName]) != null) for (i = 0; i < nbArr.length; i++) {
            img = nbArr[i];
            img.src = img.MM_up;
            img.MM_dn = 0;
        }
        document[grpName] = nbArr = new Array();
        for (i = 2; i < args.length - 1; i += 2) if ((img = MM_findObj(args[i])) != null) {
            if (!img.MM_up) img.MM_up = img.src;
            img.src = img.MM_dn = args[i + 1];
            nbArr[nbArr.length] = img;
        }
    }
}



function MM_reloadPage(init) {
    if (init == true) with(navigator) {
        if ((appName == "Netscape") && (parseInt(appVersion) == 4)) {
            document.MM_pgW = innerWidth;
            document.MM_pgH = innerHeight;
            onresize = MM_reloadPage;
        }
    } else if (innerWidth != document.MM_pgW || innerHeight != document.MM_pgH) location.reload();
}
MM_reloadPage(true);


function menuover(roimage, newSrc) {

    $(roimage).find('img').attr('src', newSrc);
}

function menuout(link) {

    var curSrc = $(link).find('img').attr('src');
    var newSrc = curSrc.replace('_ro', '_static');
    $(link).find('img').attr('src', newSrc);

}

function clearfield() {
    var settings = jQuery.extend({
        blurClass: 'clearFieldBlurred',
        activeClass: 'clearFieldActive',
        attribute: 'rel',
        value: ''
    }, settings);

    $('input,text,textarea').each(function () {
        var el = $(this);
        settings.value = el.val();

        if (el.attr(settings.attribute) == undefined) {
            el.attr(settings.attribute, el.val()).addClass(settings.blurClass);
        } else {
            settings.value = el.attr(settings.attribute);
        }

        el.focus(function () {
            if (el.parent(".Textfield").hasClass("PX96")) {
                el.parent(".Textfield").removeClass("PX96");
                el.parent(".Textfield").addClass("PX96_Orange");
            }
            if (el.parent(".Textfield").hasClass("PX198")) {
                el.parent(".Textfield").removeClass("PX198");
                el.parent(".Textfield").addClass("PX198_Orange");
            }
            if (el.parent(".Textfield").hasClass("PX299")) {
                el.parent(".Textfield").removeClass("PX299");
                el.parent(".Textfield").addClass("PX299_Orange");
            }
            if (el.parent(".Textfield").hasClass("PX596")) {
                el.parent(".Textfield").removeClass("PX596");
                el.parent(".Textfield").addClass("PX596_Orange");
            }
            if (el.parent(".Textfield").hasClass("TextareaPX596")) {
                el.parent(".Textfield").removeClass("TextareaPX596");
                el.parent(".Textfield").addClass("TextareaPX596_Orange");
            }
            if (el.parent(".Textfield").hasClass("TextareaPX299")) {
                el.parent(".Textfield").removeClass("TextareaPX299");
                el.parent(".Textfield").addClass("TextareaPX299_Orange");
            }
            if (el.parent(".Textfield").hasClass("TextareaPX299Short")) {
                el.parent(".Textfield").removeClass("TextareaPX299Short");
                el.parent(".Textfield").addClass("TextareaPX299Short_Orange");
            }
            if (el.attr("alt") == el.attr(settings.attribute) && el.val() == el.attr(settings.attribute)) {
                el.val('').removeClass(settings.blurClass).addClass(settings.activeClass);
            }

        });

        el.blur(function () {
            if (el.parent(".Textfield").hasClass("PX96_Orange")) {
                el.parent(".Textfield").removeClass("PX96_Orange");
                el.parent(".Textfield").addClass("PX96");
            }
            if (el.parent(".Textfield").hasClass("PX198_Orange")) {
                el.parent(".Textfield").removeClass("PX198_Orange");
                el.parent(".Textfield").addClass("PX198");
            }
            if (el.parent(".Textfield").hasClass("PX299_Orange")) {
                el.parent(".Textfield").removeClass("PX299_Orange");
                el.parent(".Textfield").addClass("PX299");
            }
            if (el.parent(".Textfield").hasClass("PX596_Orange")) {
                el.parent(".Textfield").removeClass("PX596_Orange");
                el.parent(".Textfield").addClass("PX596");
            }
            if (el.parent(".Textfield").hasClass("TextareaPX596_Orange")) {
                el.parent(".Textfield").removeClass("TextareaPX596_Orange");
                el.parent(".Textfield").addClass("TextareaPX596");
            }
            if (el.parent(".Textfield").hasClass("TextareaPX299_Orange")) {
                el.parent(".Textfield").removeClass("TextareaPX299_Orange");
                el.parent(".Textfield").addClass("TextareaPX299");
            }
            if (el.parent(".Textfield").hasClass("TextareaPX299Short_Orange")) {
                el.parent(".Textfield").removeClass("TextareaPX299Short_Orange");
                el.parent(".Textfield").addClass("TextareaPX299Short");
            }
            if (el.attr("alt") == el.attr(settings.attribute) && el.val() == '') {
                el.val(el.attr("alt")).removeClass(settings.activeClass).addClass(settings.blurClass);
                //el.val(el.attr(settings.attribute)).removeClass(settings.activeClass).addClass(settings.blurClass);
            }

        });
    });
}

// Tab Automatic
(function ($) {
    // Look for an element based on ID or name
    var check_element = function (name) {
        var obj = null;
        var check_id = $('#' + name);
        var check_name = $('input[name=' + name + ']');

        if (check_id.length) obj = check_id;
        else if (check_name != undefined) obj = check_name;

        return obj;
    };

    /**
     * autotab_magic automatically establishes autotabbing with the
     * next and previous elements as provided by :input.
     * 
     * autotab_magic should called after applying filters, if used.
     * If any filters are applied after calling autotab_magic, then
     * Autotab may not protect against brute force typing.
     * 
     * @name	autotab_magic
     * @param	focus	Applies focus on the specified element
     * @example	$(':input').autotab_magic();
     */
    $.fn.autotab_magic = function (focus) {
        for (var i = 0; i < this.length; i++) {
            var n = i + 1;
            var p = i - 1;

            if (i > 0 && n < this.length) $(this[i]).autotab({
                target: $(this[n]),
                previous: $(this[p])
            });
            else if (i > 0) $(this[i]).autotab({
                previous: $(this[p])
            });
            else $(this[i]).autotab({
                target: $(this[n])
            });

            // Set the focus on the specified element
            if (focus != null && (isNaN(focus) && focus == $(this[i]).attr('id')) || (!isNaN(focus) && focus == i)) $(this[i]).focus();
        }
        return this;
    };

    /**
     * This will take any of the text that is typed and
     * format it according to the options specified.
     * 
     * Option values:
     *	format		text|number|alphanumeric|all|custom
     *	- Text			Allows all characters except numbers
     *	- Number		Allows only numbers
     *	- Alphanumeric	Allows only letters and numbers
     *	- All			Allows any and all characters
     *	- Custom		Allows developer to provide their own filter
     *
     *	uppercase	true|false
     *	- Converts a string to UPPERCASE
     * 
     *	lowercase	true|false
     *	- Converts a string to lowecase
     * 
     *	nospace		true|false
     *	- Remove spaces in the user input
     * 
     *	pattern		null|(regular expression)
     *	- Custom regular expression for the filter
     * 
     * @name	autotab_filter
     * @param	options		Can be a string, function or a list of options. If a string or
     *						function is passed, it will be assumed to be a format option.
     * @example	$('#number1, #number2, #number3').autotab_filter('number');
     * @example	$('#product_key').autotab_filter({ format: 'alphanumeric', nospace: true });
     * @example	$('#unique_id').autotab_filter({ format: 'custom', pattern: '[^0-9\.]' });
     */
    $.fn.autotab_filter = function (options) {
        var defaults = {
            format: 'all',
            uppercase: false,
            lowercase: false,
            nospace: false,
            pattern: null
        };

        if (typeof options == 'string' || typeof options == 'function') defaults.format = options;
        else $.extend(defaults, options);

        for (var i = 0; i < this.length; i++) {
            $(this[i]).bind('keyup', function (e) {
                var val = this.value;

                switch (defaults.format) {
                case 'text':
                    var pattern = new RegExp('[0-9]+', 'g');
                    val = val.replace(pattern, '');
                    break;

                case 'alpha':
                    var pattern = new RegExp('[^a-zA-Z]+', 'g');
                    val = val.replace(pattern, '');
                    break;

                case 'number':
                case 'numeric':
                    var pattern = new RegExp('[^0-9]+', 'g');
                    val = val.replace(pattern, '');
                    break;

                case 'alphanumeric':
                    var pattern = new RegExp('[^0-9a-zA-Z]+', 'g');
                    val = val.replace(pattern, '');
                    break;

                case 'custom':
                    var pattern = new RegExp(defaults.pattern, 'g');
                    val = val.replace(pattern, '');
                    break;

                case 'all':
                default:
                    if (typeof defaults.format == 'function') var val = defaults.format(val);

                    break;
                }

                if (defaults.nospace) {
                    var pattern = new RegExp('[ ]+', 'g');
                    val = val.replace(pattern, '');
                }

                if (defaults.uppercase) val = val.toUpperCase();

                if (defaults.lowercase) val = val.toLowerCase();

                if (val != this.value) this.value = val;
            });
        }
    };

    /**
     * Provides the autotabbing mechanism for the supplied element and passes
     * any formatting options to autotab_filter.
     * 
     * Refer to autotab_filter's description for a detailed explanation of
     * the options available.
     * 
     * @name	autotab
     * @param	options
     * @example	$('#phone').autotab({ format: 'number' });
     * @example	$('#username').autotab({ format: 'alphanumeric', target: 'password' });
     * @example	$('#password').autotab({ previous: 'username', target: 'confirm' });
     */
    $.fn.autotab = function (options) {
        var defaults = {
            format: 'all',
            maxlength: 2147483647,
            uppercase: false,
            lowercase: false,
            nospace: false,
            target: null,
            previous: null,
            pattern: null
        };

        $.extend(defaults, options);

        // Sets targets to element based on the name or ID
        // passed if they are not currently objects
        if (typeof defaults.target == 'string') defaults.target = check_element(defaults.target);

        if (typeof defaults.previous == 'string') defaults.previous = check_element(defaults.previous);

        var maxlength = $(this).attr('maxlength');

        // defaults.maxlength has not changed and maxlength was specified
        if (defaults.maxlength == 2147483647 && maxlength != 2147483647) defaults.maxlength = maxlength;
        // defaults.maxlength overrides maxlength
        else if (defaults.maxlength > 0) $(this).attr('maxlength', defaults.maxlength)
        // defaults.maxlength and maxlength have not been specified
        // A target cannot be used since there is no defined maxlength
        else defaults.target = null;

        if (defaults.format != 'all') $(this).autotab_filter(defaults);

        // Go to the previous element when backspace
        // is pressed in an empty input field
        return $(this).bind('keydown', function (e) {
            if (e.which == 8 && this.value.length == 0 && defaults.previous) defaults.previous.focus().val(defaults.previous.val());
        }).bind('keyup', function (e) {
            /**
             * Do not auto tab when the following keys are pressed
             * 8:	Backspace
             * 9:	Tab
             * 16:	Shift
             * 17:	Ctrl
             * 18:	Alt
             * 19:	Pause Break
             * 20:	Caps Lock
             * 27:	Esc
             * 33:	Page Up
             * 34:	Page Down
             * 35:	End
             * 36:	Home
             * 37:	Left Arrow
             * 38:	Up Arrow
             * 39:	Right Arrow
             * 40:	Down Arrow
             * 45:	Insert
             * 46:	Delete
             * 144:	Num Lock
             * 145:	Scroll Lock
             */
            var keys = [8, 9, 16, 17, 18, 19, 20, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 144, 145];

            if (e.which != 8) {
                var val = $(this).val();

                if ($.inArray(e.which, keys) == -1 && val.length == defaults.maxlength && defaults.target) defaults.target.focus();
            }
        });
    };

})(jQuery);

// Fullsize BG
(function ($) {
    $.fn.fullBg = function () {
        var bgImg = $(this);

        function resizeImg() {
            var imgwidth = bgImg.width();
            var imgheight = bgImg.height();

            var winwidth = $(window).width();
            var winheight = $(window).height();

            var widthratio = winwidth / imgwidth;
            var heightratio = winheight / imgheight;

            var widthdiff = heightratio * imgwidth;
            var heightdiff = widthratio * imgheight;

            if (heightdiff > winheight) {
                bgImg.css({
                    width: winwidth + 'px',
                    height: heightdiff + 'px'
                });
            } else {
                bgImg.css({
                    width: widthdiff + 'px',
                    height: winheight + 'px'
                });
            }
        }
        resizeImg();
        $(window).resize(function () {
            resizeImg();
        });
    };
})(jQuery)
