/* 
    Fading Stylesheet Transitions
    
    Version 0.02
    Author: Ben Yanis, www.barnyardbbs.com
    License: Creative Commons Attribution, 3.0, No special restrictions.  Share and Enjoy.
    
    Creates a temporary invisible div (overtop everything), fades it in, switches sheets, and fades it out
    Includes javascript-based preloading of all images from alternate stylesheets
    
    Instructions:
    
        1.  Reference this .js from your page.  For example: <script src="/CSSTransitions.js" type="text/javascript" />
        2.  Make links that call the transition javascript.  Use the name of the stylesheet, not the path.  For example: <a onclick="TransitionStyle('Classic');return false;">Classic</a>   
        3.  Optional (for preloading): Add this line of javascript to your page: window.onload=preLoadAlternateStyleSheets;
        
*/


/* Transitioning */

function TransitionStyle(NewSheetName) {

    var HiderDivName = 'StyleSheetTransitionHider';

    //Set the cookie
    document.cookie = 'StyleSheet=' + NewSheetName + ';path=/';

    //Figure out our widths
    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        WindowHeight = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        WindowHeight = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        WindowHeight = document.body.clientHeight;
    }

    //Make a new element out of thin air
    var newdiv = document.createElement('div');
    var divIdName = HiderDivName;
    newdiv.setAttribute('id',divIdName);
    newdiv.style.position = 'absolute';

    newdiv.style.top = '0';
    newdiv.style.left = '0';
    newdiv.style.width = '100%';
    if (WindowHeight > document.body.offsetHeight) {
        newdiv.style.height = WindowHeight + 'px';
    } else {
        newdiv.style.height = document.body.offsetHeight + 'px';
    }
    newdiv.style.zIndex = 99;
    newdiv.style.backgroundColor = '#ffffff';
    document.body.appendChild(newdiv);
    
    //alter the opacity three ways
    newdiv.style.opacity = 0;
    newdiv.style.KhtmlOpacity = 0;
    newdiv.style.filter = 'alpha(opacity=0)';


    // Fade it in from 0 opacity to 100 opacity over one second
    opacity(HiderDivName, 0, 100, 1000);

    //Queue for later (until 
    // Switch the stylesheets in the DOM
    setTimeout("ChangeStyle('" + NewSheetName + "')", 1100);

    //Queue for later still
    //Fade the temporary div back out, over one second
    setTimeout('opacity("' + HiderDivName + '", 100, 0, 1000);', 1200);

    //Queue for even later still
    //Remove the temporary div from the DOM
    setTimeout('document.body.removeChild(document.getElementById("' + HiderDivName +'"));', 2500);            

    }

function ChangeStyle(NewSheetName) {

    window.scroll(0,0);

    var LinkElements = document.getElementsByTagName('link');
    var GoodSheet
    
    // It's important to disable ALL of them on the first pass, then re-enable.  It fixed compatibility with IE!

    for (i=0;i<LinkElements.length;i=i+1) {
        if (LinkElements[i].getAttribute('type') == 'text/css') {
            LinkElements[i].disabled = true;
            if (LinkElements[i].getAttribute('id') == ('StyleSheet' + NewSheetName)) {
                LinkElements[i].setAttribute('rel', 'stylesheet');
                GoodSheet = i;
            } else {
                LinkElements[i].setAttribute('rel', 'alternate stylesheet');
            }
        }
    }
    LinkElements[GoodSheet].disabled = false;
}

function opacity(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
}

/* Preloading */

var reqs = new Array();
var images = new Array();
var count = 0;
var imageCount = 0;

function preLoadCSSImages(url) {

    var baseURL = url.substring(0, url.lastIndexOf("/") + 1);

    if (window.XMLHttpRequest) {
        reqs[count] = new XMLHttpRequest();
        reqs[count].onreadystatechange = Function("","processImagesFromRequest('" + count + "', '" + baseURL + "')"); //processReqChange(count);
        reqs[count].open("GET", url, true);
        reqs[count].send(null);
    } 
    else if (window.ActiveXObject) {
        reqs[count] = new ActiveXObject("Microsoft.XMLHTTP");
        reqs[count].onreadystatechange = Function("","processImagesFromRequest('" + count + "', '" + baseURL + "')"); //processReqChange(count);
        reqs[count].open("GET", url, true);
        reqs[count].send();
    }
    count++;
}

function processImagesFromRequest(offset, baseURL) {

    if (reqs[offset].readyState == 4) {
        if (reqs[offset].status == 200) {
           
            var cssText = reqs[offset].responseText;
            var startIdent = "url(";
            var endIdent = ")";
            var startPos = 0;
            var endPos = 0;
            var imageName;
            
            //alert("begin images: " + baseURL);
            
            while (startPos >= 0) {
                
                startPos = cssText.indexOf(startIdent, startPos + 1);
                endPos = cssText.indexOf(endIdent, startPos + 1);
                
                if ((startPos > 0) && (endPos > 0)) {
                    imageName = cssText.substring(startPos, endPos);
                    
                    //Filter out the junk
                    imageName = imageName.replace(startIdent, '');
                    imageName = imageName.replace(endIdent, '');
                    imageName = imageName.replace(/"/g, "");
                    imageName = imageName.replace(/'/g, "");
                    images[imageCount] = new Image();
                    images[imageCount].src = baseURL + imageName;
                    imageCount += 1;     
                }
                   
            }
            
        }
    }
}		

function preLoadAlternateStyleSheets() {

    imageCount = 0;
    var linkElements = document.getElementsByTagName('link');

    for (i = 0; i < linkElements.length; i = i + 1) {
        if (linkElements[i].getAttribute('rel') == 'alternate stylesheet') {
            preLoadCSSImages(linkElements[i].getAttribute('href'));
        }
    }
}
