﻿// jQuery Fog Functions javascript
// Phil Higgs - JPMH - Oct 2009

var updateSpeed = 50;       // ms / screen update
var matchSpeed = 50;        // allow updates to grow/shrink
var intervalID = 0;
var MINWIDTH = 849;         // width of main container (to allow scrolling of content)
var MAXWIDTH = 1400;        // max width of BGContainer - fog container
var FOGTOP = 500;           // start of where we draw the fog...
var MAXHEIGHT = 1000;       // max height after which we turn off/limit fog
var MinSpeed = 0.5;
var MaxSpeed = 1.99;
var LastTicks = 0;
var LastTicks2 = 0;

jQuery(document).ready(
    function()
    {
        // Init container details
        //contWidth = jQuery('#MainContainer').width();
        //contHeight = jQuery('#MainContainer').height();
        MINWIDTH = jQuery('#MainContainer').width();
        jQuery(window).wresize(content_resize);
        InitFog();
        // Can't just use setInterval as eats too much processor time - we try and
        // adjust the fog timing based on how the browser is responding
        //intervalID = setInterval("MoveFog()", updateSpeed);
        intervalID = setTimeout("FogLoop()", updateSpeed);
        LastTicks = 0;
        LastTicks2 = new Date().getTime();
        content_resize();   
    }
);

function FogLoop() {
    LastTicks = new Date().getTime()-LastTicks2;
    MoveFog();
    // Are we near our required timing?
    if (LastTicks > (updateSpeed*2))
        matchSpeed = LastTicks;
    else
        matchSpeed = matchSpeed - (LastTicks/4);
    if (matchSpeed < updateSpeed) matchSpeed = updateSpeed;
    else if (matchSpeed > (updateSpeed*3)) matchSpeed = (updateSpeed*3);
    intervalID = setTimeout('FogLoop()', matchSpeed);
    LastTicks2 = new Date().getTime();
}

function content_resize()      
{         
    contWidth = jQuery(window).width();
    if (contWidth > MAXWIDTH) contWidth = MAXWIDTH;
    wH = jQuery(window).height();
    dH = jQuery('#FogContainer').height();
    // get largest height
    contHeight = (wH > dH) ? wH : dH;
//    if (contHeight > MAXHEIGHT && intervalID!=0) {
        // page height max'd - turn off fog
        //clearInterval(intervalID);
//        clearTimeout(intervalID);
//        jQuery('#AllFog').hide();
//    } else {
        if (contWidth < MINWIDTH) {
            jQuery('#FogContainer').width(MINWIDTH);
        } else {
            if (bIsSafari && contWidth < MAXWIDTH)
                jQuery('#FogContainer').width(contWidth-20);
            else
                jQuery('#FogContainer').width(contWidth);
            if (wH > dH)
                jQuery('#FogContainer').height(contHeight);
        }
//    }
}      


// Arrays to store our fog details
var fogWidth = new Array();
var fogHeight = new Array();
//var fogLeftOffscreen = new Array();
var fogSpeed = new Array();
var fogX = new Array();
var fogY = new Array();
var fogAngle = new Array();
var fogDir = new Array();
// Container details
var contWidth = 0;
var contHeight = 0;

var radiusX = 120;
var radiusY = 240;

// sin/cos tables
var tbSin = new Array();
var tbCos = new Array();
var tbTan = new Array();

function InitFog() {
    // Init cos/sin/tan tables
    for (var x=0;x<360;x++) {
    	tbSin[x] = Math.sin(x * Math.PI / 180);
    	tbCos[x] = Math.cos(x * Math.PI / 180);
    	tbTan[x] = Math.tan(x * Math.PI / 180);
    }

    try {
        jQuery('.fog,.fog2,.fog3').each(function() {
            // Position bottom / left
            var src = jQuery("img", this).attr("src");
            var classname = jQuery(this).attr("class");
            if (src) {
                var hi = new Image();
                hi.src = src;
                var orig = jQuery(this);        // retain for use in recheck event
                var element = jQuery(hi);
                
                setTimeout(function(){element.trigger('recheck')}, 0);
                element.bind("recheck", function(e) {
                    var helpImage = new Image();
                    helpImage.src = src;
                    if (helpImage.complete) {
                        // FOG
                        // Position image offscreen left, aligned to bottom of container div
                        var lf = 0;
                        var ix = Math.floor(Math.random()*(contWidth/4));
                        if (classname == "fog" || classname == "fog3") {
                            lf = 0-helpImage.width;
                            // Randomly start offscreen...
                            if (Math.floor(Math.random()*(100)) >= 50) ix = lf;
                        } else {
                            lf = Math.floor(Math.random()*helpImage.width) - (helpImage.width/2);
                        }
                        
                        //var tp = (contHeight-helpImage.height)+Math.floor(Math.random()*(helpImage.height/((classname=="fog2")?3:4)))+1;
                        var tp = FOGTOP + (Math.random()*(contHeight-FOGTOP));
                        if (tp > MAXHEIGHT) tp = MAXHEIGHT;
                        
                        // If lang="aa" then position at top/center
                        if (orig.attr("lang").toLowerCase() == "aa") {
                            tp = FOGTOP;
                            ix = (contWidth/2)-(helpImage.width/2);
                        }
                        
                        orig.css('top', tp+'px').css('left', ix+'px');
                        // Store elements for this fog item
                        var id = orig.attr("id");

                        //orig.prepend(id);
                        
                        fogWidth[id] = helpImage.width;
                        fogHeight[id] = helpImage.height;
//                        fogLeftOffscreen[id] = lf;
                        fogX[id] = lf;
                        fogY[id] = tp;
                        fogDir[id] = orig.attr("dir").toLowerCase();
                        if (fogDir[id] == "") {
                            // random direction
                            fogDir[id] = ((Math.random()*10) >= 5) ? "ltr" : "rtl";
                        }
		                // Class variants here
                        if (classname == "fog" || classname == "fog3") {
	                        fogAngle[id] = Math.floor(Math.random()*360);
    	                    fogSpeed[id] = Math.floor(parseFloat(Math.random()*MaxSpeed)+MinSpeed)+1;
		                } else {
	                        //fogAngle[id] = 90+Math.floor(Math.random()*35);
	                        fogAngle[id] = Math.floor(Math.random()*360);
    	                    fogSpeed[id] = Math.min(parseFloat(Math.random()*MaxSpeed), MinSpeed);
        		        }
                        // Now we're done, display the fog
                        orig.css('display', 'inline');
                    } else {
                        // Not loaded yet - wait and recheck
                        setTimeout(function(){element.trigger('recheck')}, 100);
                    }
                });
            }
        });
    }
    catch (err) {}
}

var globalAng = 0;
var globalAngSpeed = 1.0;

function MoveFog() {
    try {
        jQuery('.fog').each(function() {
            var p = jQuery(this).position();
            var id = jQuery(this).attr("id");
            var spd = fogSpeed[id];
            var x = p.left;
            if (fogDir[id] == "ltr") x = x + spd;
            else x = x - spd;
            if (x > contWidth) {
                // Wrap around again and set new speed
                fogSpeed[id] = Math.min(parseFloat(Math.random()*MaxSpeed), MinSpeed)+1;
//                x = fogLeftOffscreen[id];
                x = 0-fogWidth[id];
            } else if (x < 0-fogWidth[id]) {
                // Wrap around again and set new speed
                fogSpeed[id] = Math.min(parseFloat(Math.random()*MaxSpeed), MinSpeed)+1;
                x = contWidth;
            }
            jQuery(this).css('left', x+'px')//;.animate({opacity: 'toggle'}, "slow");
        });

        jQuery('.fog2').each(function() {
            var id = jQuery(this).attr("id");
            var spd = fogSpeed[id];
            var y = fogY[id] + radiusY * ((((tbSin[fogAngle[id]]) / tbTan[fogAngle[id]])/2)/2);
            var x;
            if (fogDir[id] == "ltr")
                x = fogX[id] - (radiusX/1.5) * ((tbCos[fogAngle[id]]*2) * (tbTan[fogAngle[id]]/3));
            else
                x = fogX[id] + (radiusX/1.5) * ((tbCos[fogAngle[id]]*2) * (tbTan[fogAngle[id]]/3));
            fogAngle[id] = fogAngle[id] + 1;
            if (fogAngle[id] > 359) {
		        fogAngle[id] = 0;
	        }
            jQuery(this).css('top', y+'px').css('left', x+'px')//;.animate({opacity: 'toggle'}, "slow");;
        });

        jQuery('.fog3').each(function() {
            var p = jQuery(this).position();
            var id = jQuery(this).attr("id");
            var spd = fogSpeed[id];
            var x = p.left;
            if (fogDir[id] == "ltr") x = x + spd;
            else x = x - spd;
            if (x > contWidth) {
                // Wrap around again and set new speed
                fogSpeed[id] = Math.min(parseFloat(Math.random()*MaxSpeed), MinSpeed)+1;
//                x = fogLeftOffscreen[id];
                x = 0-fogWidth[id];
            } else if (x < 0-fogWidth[id]) {
                // Wrap around again and set new speed
                fogSpeed[id] = Math.min(parseFloat(Math.random()*MaxSpeed), MinSpeed)+1;
                x = contWidth;
            }
            var y = fogY[id] + radiusY * (tbSin[fogAngle[id]]/(spd*4));
            fogAngle[id] = fogAngle[id] + 1;
            if (fogAngle[id] > 359) {
		        fogAngle[id] = 0;
	        }
            jQuery(this).css('top', y+'px').css('left', x+'px')//;.animate({opacity: 'toggle'}, "slow");
        });

	    globalAng = globalAng + globalAngSpeed;
	    if (globalAng > 359) globalAng = 0;
    }
    catch (err) {/*alert("ERROR2="+err.description);*/}
    lastTick = (new Date()).getTime();
}

