$(document).ready(function(){
    $('a[href^="http://"]').attr({target: "_blank", title: "Opens in a new window"});

    $('ul.links li a').ahover();
    $('.ibox','#servicesbox').each(function() {
        $(this).css('opacity','0.6');
        $(this).mouseover(function() {
            $(this).stop().animate({ "opacity": 1}, "fast");
        });
        $(this).mouseout(function() {
            $(this).stop().animate({ "opacity": 0.6}, "fast");
        });
    });

    var thatchSlideShow = function(what) {
        var me = this;
        var timer = 4000;
        var fade = timer / 4;
        var text = $(what+' div.text');
        var stuff = {
            doSwitch: function() {
                var active = $(what+' img.active');
                if ( active.length == 0 ) active = $(what+' img:last');
                var next =  active.next().length ? active.next() : $(what+' img:first');

                var split = $(next).attr('alt').split(' :: ');
                //var textString = $('<h4>'+split[0]+'</h4><h5>'+split[1]+'</h5>');
                if (split[2]) { var textString = $('<h4>'+split[0]+'</h4><h5>'+split[1]+'</h5><a href="'+split[2]+'" class="external">View More</a>'); }
                else { var textString = $('<h4>'+split[0]+'</h4><h5>'+split[1]+'</h5>'); }

                active.addClass('last-active');

                setTimeout(function(){$(text).html(textString);},fade/2.75);
                next.css({opacity: 0.0})
                .addClass('active')
                .animate({opacity: 1.0}, fade, function() {
                    active.removeClass('active last-active');
                });


            },
            init:function() {
                //force preload the slideshow
                $('#slideshow img').each(function() {
                    Preload.load($(this).attr('src'));
                });
                // start the slideshow
                setInterval(function() {
                    stuff.doSwitch.apply()},timer);
            }
        }
        stuff.init.apply(stuff);
        return stuff;
    };


    if ($('#slideshow').length) {
        new thatchSlideShow('#slideshow');
    }

    var fade = 1000;
    var gallery = $('#gallery');
    var text = $('#text',gallery);
    var image = $('#image',gallery);
    var copy = $('#copy');
    //$(text).slideUp('fast');

    // fadein/out stuff
    $('#pics > a > img','#footer').each(function(i) {
        $(this).css('opacity', 0.6);
        $('#footer').css('margin-top','0');
        $(this).mouseover(function() {
            $(this).stop().animate({ "opacity": 1}, "fast");
        });
        $(this).mouseout(function() {
            $(this).stop().animate({ "opacity": 0.6}, "fast");
        });
        // hrefNormalized: Is equal to true if the browser leaves intact the results from getAttribute("href")(is currently false in IE, the URLs are normalized).
        if (i>38 && jQuery.support.hrefNormalized) {$('#footer').css({height:'47px'});$('#pics').css({height:'47px',marginLeft:'2px'}); }
    });

    $('#pics a', '#footer').each(function(i,link) {
        Preload.load($(this).attr('href'));

        $(this).click(function(i,thelink) {
            if ($('#backlink')) { $('#backlink').css('display','block'); }
            var link = this;
            window.location.hash = $(this).attr('id');
            //if ($(text).not(':hidden')) { $(text).hide('slow'); }
            //if ($(text).not(':hidden')) { var nh = true; }
            $(text).slideUp('slow',function() {
                var src = $(link).attr('href');
                var w = $(link).attr('_w');
                var h = $(link).attr('_h');
                var textString = '<h4>'+$(link).attr('title')+'</h4>';

                $(image).empty();

                //var next = $('<img src="'+src+'" style="width:'+w+'px;height:'+h+'px;" />');
                var next = $('<div style="background:url('+src+') no-repeat top center;width:'+900+'px;height:'+h+'px;clear:both"></div>');
                $(image).append(next);
                //$(image).css('height',h);
                $(copy).html(textString);

                if (w > 900) { var wi = Math.round((900 - w) / 2)+"px";
                    next.css({opacity: 0.0})
                        .addClass('active')
                        .animate({opacity: 1.0, width:w+"px", marginLeft: wi}, fade, function() {
                        });
                }
                else {
                    next.css({opacity: 0.0})
                        .addClass('active')
                        .animate({opacity: 1.0}, fade, function() {
                        });
                }
                //nh = false;
            });
            addActive($(link).children().get(0));
            return false;
        });
    });

    addActive = function(id) {
        $('#pics > a > img','#footer').each(function() {
            $(this).removeClass('active');
        });
        if (id) { $(id).addClass('active'); }
    }


    if ($('#metachanger')) {
        var metadata = '';
        var id = $('#metalink').attr('rel');
        $('#metadiv').hide();
        $('#metalink').click(function(){
            $('#metadiv').slideToggle(500);
            //$("#metadiv").animate({ height: "300px" }).animate({height: "250px" }, "fast");

            $.get("/update.php", { getcontent: "1", id: $(this).attr('rel'), target: 'title' },function(data) {
                $("form.metaform input[name='title']").val(data);
            });
            $.get("/update.php", { getcontent: "1", id: $(this).attr('rel'), target: 'headline' },function(data) {
                $("form.metaform input[name='desc']").val(data);
            });

            $.get("/update.php", { getcontent: "1", id: $(this).attr('rel'), target: 'keywords' },function(data) {
                $("form.metaform input[name='keywords']").val(data);
            });

            $.get("/update.php", { getcontent: "1", id: $(this).attr('rel'), target: 'weight' },function(data) {
                $("form.metaform input[name='weight']").val(data);
            });

            return false;
        });

        $('form.metaform').submit(function() {
            var inputs = [];
            $(':input', this).each(function() {
                inputs.push(this.name + '=' + escape(this.value));
            });
            $('#metadiv').slideUp('fast');
             $.ajax({
                type: "POST",
                url: this.action,
                data: inputs.join('&'),
                beforeSend: function(){$("#loading").slideDown("fast");}, //show loading just when link is clicked
                complete: function(){ $("#loading").slideUp("fast");}, //stop showing loading when the process is complete
                success: function(html){ //so, if data is retrieved, store it in html
                    $("#metadiv").show("slow"); //animation
                    $('#metalog').slideDown('fast');
                    $("#metalog").html("<h2>Meta Log</h2><div style='clear:both'></div>"+html); //show the h
                    setTimeout(function(){
                        $('#metalog').slideUp('slow');
                    }, 5000);
                }
            });
            return false;
        });
    }
});


/*******************************************************************************
 *  Preloading
 ******************************************************************************/
var Preload = {
    load: function(trigger, handlers) {
        if( (typeof trigger).toLowerCase() == 'string' ){
            src = trigger;
        }else{
            src = $(trigger).attr('href');
            try{
                opts = eval( '({' + $(trigger).attr('rel') + '})' );
            }catch(e){}
        }
        //test if it is an image, otherwise, use ajax
        if( src.match(/.jpg$|.jpeg$|.png$|.gif$|.bmp$|.tif$|.tiff$|.gi$/i) ){
            var img = new Image();
            if( handlers ){
                if( handlers.loaded && typeof handlers.loaded == 'function' ){
                    img.onload = function(){
                        response = {
                            width: img.width,
                            height: img.height,
                            obj: $('<img>').attr('src',img.src)
                        };
                        handlers.loaded( response );
                    };
                }
                if( handlers.loaded && typeof handlers.error == 'function' ){
                    img.onerror = function( err ){
                        handlers.error( err );
                    }
                }
            }
            img.src = src;
        }else if( src.match(/.swf$|.flv$|.SWF$|.FLV$/i) ){
            if( $.fn.flash ){
                if( handlers ){
                    if( handlers.loaded && typeof handlers.loaded == 'function' ){
                    // todo: code flash handling
                    }
                }
            }
        }else{
            $.get(
                src,
                function( html ){
                    if( handlers ){
                        if( handlers.loaded && typeof handlers.loaded == 'function' ){
                            var content = $('<div>').html( html );
                            response = {
                                width: parseInt(content.children(0).css('width')),
                                height: parseInt(content.children(0).css('height')),
                                obj: content,
                                data: html
                            };
                            handlers.loaded( response );
                        }
                    }
                }
            );
        }
    }
};