﻿/*
    Theming.js
    
    cleanThemes
        is used by:-
    changeTheme(newTheme)
        changes the theme to the theme name in newTheme.
        Before loading the new theme css files it adds all the current 
        themed stylesheets (URL contains 'themes') to an array (toRemove).
        
        After a delay (to allow new styles to load first, and prevent page flicker)
        all the stylesheets in toRemove are removed.
*/

var clTimer;
var toRemove = $A([]);

function cleanThemes()
{
    $$(toRemove).each(
        function(item)
        {
            item.dispose();    
        }
    );
}


function changeTheme(newTheme)
{
    var myRequest = new Request.HTML(
        {
            url: 'Services/ThemeService.asmx/SetTheme',
            onSuccess: function(responseText,responseXML) 
            {
               oldTheme = "/" + responseXML[0].innerHTML + "/";
               newTheme2 = "/" + newTheme + "/";
               
               if (oldTheme != newTheme2)
               {
                    //alert('DIFFERENT!');
                    $$("link").each(
                        function(item)
                        {
                            if (item.href.contains(oldTheme))
                            {
                                if (!$A(toRemove).contains(item))
                                {
                                    var newRef = item.href.replace(oldTheme,newTheme2);
                                    var myCss = new Asset.css(newRef);
                                    toRemove = $A(toRemove).include(item);
                                }
                            }
                        }
                    )
                        
                                 
                    clearTimeout(clTimer);
                    clTimer = setTimeout('cleanThemes();',3000);
                    
                    $$("img").each(
                        function(item){
                            var newSrc = item.src.replace(oldTheme,newTheme2);
                            var newImg = new Asset.images(newSrc,{
                                onComplete:function()
                                    {
                                        item.set("src",newSrc);        
                                    }
                                });                                                
                        }
                    );
                    
                   
               }
            }                
        }).post(
            {
            'newTheme':newTheme        
            }
        );
    
}