jQuery.noConflict();

var puzzle = {
    /* config */
    rows: 4,
    columns: 3,

    /* time in milliseconds */
    waitToStart: 1000,
    hideSpeed: 1000,
    waitAfterHide: 10,
    waitForNextMove: 10,
    moveSpeed: 1000,
    waitForBeforeShow: 1000,
    showSpeed: 1000,
    waitForNextHide: 2000,

    hoverDelay: 100,
    hoverFadeIn: 300,
    hoverFadeOut: 300,

    /* functions */
    init: function() {
        // begin puzzle (after delay)
        puzzle.delay(puzzle.hide, puzzle.waitToStart)();

        puzzle.spaces = puzzle.rows * puzzle.columns;
        puzzle.visible = [];
        puzzle.hidden = [];
        puzzle.all = {};

        // build a list of visible projects
        jQuery("#container a.project").each(function() {
            puzzle.visible.push({ id: this.id });
            puzzle.all[this.id] = {};
        });
        puzzle.shuffle(puzzle.visible);

        // build a list of hidden projects
        jQuery("#bullpen a.project").each(function() {
            puzzle.hidden.push({ id: this.id });
            puzzle.all[this.id] = {};
        });
        puzzle.shuffle(puzzle.hidden);

        // switch from hiding descriptions via display to (cross-browser) opacity
        jQuery("a.project>div").css({ display: "block", opacity: 0 })
        // attach onhover behavior to projects
        jQuery("a.project").mouseover(function() {
            var m = this;
            var a = puzzle.all[m.id];
            a.hover = puzzle.debounce(function() {
                // fade in bg and content on mouseover
                jQuery("div.desc-bg", m).animate({ opacity: 0.4 }, puzzle.hoverFadeIn);
                jQuery("div.desc", m).animate({ opacity: 1 }, puzzle.hoverFadeIn);
            }, puzzle.hoverDelay, a.hover);
        }).mouseout(function() {
            var m = this;
            var a = puzzle.all[m.id];
            a.hover = puzzle.debounce(function() {
                // fade out bg and content on mouseout
                jQuery("div.desc-bg", m).animate({ opacity: 0 }, puzzle.hoverFadeOut);
                jQuery("div.desc", m).animate({ opacity: 0 }, puzzle.hoverFadeOut);
            }, puzzle.hoverDelay, a.hover);
        });
    },
    hide: function() {
        // remove from visible queue and add to hidden queue
        var item = puzzle.visible.shift();
        puzzle.hidden.push(item);
        var space = parseInt(jQuery("#" + item.id).parent().get(0).id.replace(/[^1-9]*/, ""));

        // hide (then move next after delay)
        jQuery("#" + item.id).animate({ opacity: 0 }, puzzle.hideSpeed, "swing", function() {
            // remove old space content
            jQuery("#" + item.id).appendTo("#bullpen");

            // move another project to this space
            delete puzzle.prevspace;
            puzzle.delay(puzzle.move, puzzle.waitAfterHide, space)();
        });
    },
    show: function(space) {
        // remove from hidden queue and add to visible queue
        var item = puzzle.hidden.shift();
        puzzle.visible.push(item);

        // hide new space content, add it to the space,
        // and show new space (then hide next after delay)
        jQuery("#" + item.id).css({ opacity: 0 }).appendTo(puzzle.space_id(space))
            .animate({ opacity: 1 }, puzzle.showSpeed, "swing", puzzle.delay(puzzle.hide, puzzle.waitForNextHide));
    },
    move: function(tospace) {
        var torow = parseInt((tospace-1) / puzzle.columns); // space 1-based
        var tocolumn = (tospace-1) % puzzle.columns; // space 1-based

        // choose whether to move horizontally or vertically (but not the way we just came from)
        var space = puzzle.prevspace, row, column;
        while (space == puzzle.prevspace) {
            row = torow; column = tocolumn;

            // move horizontally
            if (Math.random() < 0.5) {
                // at far left: move right
                if (tocolumn == 0)
                    column++;
                // at far right: move left
                else if (tocolumn == puzzle.columns - 1)
                    column--;
                // else randomly move right
                else if (Math.random() < 0.5)
                    column++;
                // else randomly move left
                else
                    column--;
                    
            // move vertically
            } else {
                // at far left: move right
                if (torow == 0)
                    row++;
                // at far right: move left
                else if (torow == puzzle.rows - 1)
                    row--;
                // else randomly move right
                else if (Math.random() < 0.5)
                    row++;
                // else randomly move left
                else
                    row--;
            }

            space = row * puzzle.columns + column + 1; // space 1-based
        }
        // remember not to move back to the space we're going to
        puzzle.prevspace = tospace;

        // position mover over from-space, and tranfer from-space's contents to mover
        jQuery(puzzle.space_id(space) + ">a.project").appendTo("#mover");

        // move mover to to-space
        jQuery("#mover").css(jQuery(puzzle.space_id(space)).offset()).animate(jQuery(puzzle.space_id(tospace)).offset(), puzzle.moveSpeed, "swing", function() {
            // transfer mover's content to to-space
            jQuery("#mover>a.project").appendTo(puzzle.space_id(tospace));
            // hide mover div
            jQuery("#mover").css({ top: "-9999px" });

            // choose whether to move again or to wait
            if (Math.random() < 0.5)
                puzzle.delay(puzzle.move, puzzle.waitForNextMove, space)();
            else
                puzzle.delay(puzzle.show, puzzle.waitBeforShow, space)();
        });
    },
    space_id: function(space) {
        var s = String(space);
        return "#space_" + (s.length > 1 ? "" : "0") + s;
    },
    shuffle: function(array) {
        array.sort(function() { return Math.random() - 0.5; });
    },
    delay: function(fn, ms) {
        // collect args after fn and ms
        var args = [];
        for (var i = 2; i < arguments.length; i++)
            args.push(arguments[i]);

        // pass args to fn after delay of ms
        return function() {
            setTimeout(function() { fn.apply(window, args); }, ms);
        };
    },
    debounce: function(fn, ms, handle) {
        clearTimeout(handle);
        return setTimeout(fn, ms);
    }
};

var plb = {
    init: function() {
        var $ = jQuery;
        // convert all <a class="plb"> links to be opened in a lightbox
        $("a.plb").click(function() {
            var m = this;
            setTimeout(function() { plb.open(m.href, m.title); }, 10);
            return false;
        });
    },
    open: function(url, title) {
        var $ = jQuery;

        // initial lightbox size (small so it can grow)
        var loadingWidth = 200;
        var loadingHeight = 200;
        var loadingRect = {
            left: ($(window).width() - loadingWidth) / 2,
            top: ($(window).height() - loadingHeight) / 2,
            width: loadingWidth,
            height: loadingHeight
        };

        // create the lightbox elements
        // plb-ajax is the offscreen container into which to load the async content
        // plb-dim is the dark semi-opaque div that hides the entire document content when the lightbox is shown
        // plb-box is the white lightbox
        // plb-content is the container inside the lightbox to display the content
        // plb-nav is the container inside the lightbox, below the content, for the close button
        // plb-loading is the loading-image container
        var box = $("#plb-box");
        if (!box.get(0)) {
            $(document.body).append("<div id='plb-ajax'></div><div id='plb-dim'></div><div id='plb-box'><div id='plb-content'></div><div id='plb-nav'><a href='javascript:plb.close()'><img src='/images/closelabel.gif' alt='Close'></a></div></div><div id='plb-loading'><img src='/images/loading.gif' alt='Loading...'></div>");
            box = $("#plb-box");

            // resize dim / reposition loading when window is resized
            $(window).resize(plb.resize);
        }
        
        // clear content
        $("#plb-content").css({ opacity: 0 }).html("");

        // show loading content
        $("#plb-dim").css({ display: "block", opacity: 0 }).animate({ opacity: 0.8 }, 1000, "swing");
        $("#plb-box").css(loadingRect).css({ display: "block", opacity: 0 }).animate({ opacity: 1 }, 500, "swing");
        $("#plb-loading").show();
        // position loading
        plb.resize();

        // load url asynchronously
        // use t param to break caching
        $("#plb-ajax").load(url, "t=" + new Date().getTime(), function() {
            // calculate content size
            var padding = parseInt($("#plb-content").css("padding-top")) || 0;
            var width = $("#plb-ajax").width();
            var height = $("#plb-ajax").height() + $("#plb-nav").height() + padding;
            var rect = {
                left: ($(window).width() - width) / 2 + padding,
                top: ($(window).height() - height) / 2 + padding,
                width: width + padding * 2,
                height: height + padding * 2
            };

            // resize box
            $("#plb-box").animate(rect, 1000, "swing", function() {
                $("#plb-loading").hide();

                // inject hidden content into the lightbox
                var html = $("#plb-ajax").html();
                $("#plb-ajax").html("");
                $("#plb-content").html(html);

                // fade in content
                $("#plb-content").animate({ opacity: 1 }, 500, "swing");
            });
						
						setTimeout(function() { plb.check($("form:first")); }, 2000);
        });
    },
		check: function(form) {
      var $ = jQuery;
			$('input:#elname').focus();
			form.submit(function() {
			 var name = $('input:#elname');
			 var email = $('input:#email');
				if(name.val() < 1) {
					alert("Please enter your name");
					name.focus();
					return false
				}
				if(email.val() < 1) {
					alert("Please enter your email");
					email.focus();
					return false
				}
				var subject =  $('input:#subject').val();
				var message = $('#message').val();
				var params = 'name='+ name.val() +'&email=' + email.val() + '&subject=' + subject + '&message=' + message;
				$('#contactArea').load('contact_check.php', params, function() {
					//$('#contactArea').html("Thank you");
					return false;
				});
				return false;
			});
		},
    close: function() {
        var $ = jQuery;
        $("#plb-dim").animate({ opacity: 0 }, 1000, "swing", function() {
            $("#plb-dim").hide();
        });
        $("#plb-box").animate({ opacity: 0 }, 500, "swing", function() {
            $("#plb-box").hide();
        });
    },
    resize: function() {
        var $ = jQuery;
        $("#plb-dim").css({ width: $(document).width(), height: $(document).height() });
        if ($("#plb-loading").width())
            $("#plb-loading").css({ left: ($(window).width() - $("#plb-loading").width()) / 2 , top: ($(window).height() - $("#plb-loading").height()) / 2 });
    }
};


/* init when page dom loaded */
jQuery(document).ready(puzzle.init);
jQuery(document).ready(plb.init);


