/*
 * MAP.CSSSwitch Class
 * This anonymous function acts as a namespace wrapper for the Class. 
 */
 (function(){

if(!window['MAP'])
  {
    alert("Include the MAP namespace and library first of all!");
  }


function myCssSwitch(id) {
  id = id || 'cssSwitch';

  var cssSwitch = MAP.$(id);
  var introText = "Switch your display to:";
  var cookieName = "activeCSS";
  var idName = "cssSwitch";
  var destination = "#skipNavigation";
  
  var stylesheetList = new Array();
  
  var findStylesheets = function() {
    
    var i, a, j, k, tmpList = new String(), titles;
    
    j = 0;
    for (i=0; (a=document.getElementsByTagName("link")[i]); i++) {
      var aTitle = a.getAttribute("title");
      if (a.getAttribute("rel").indexOf("stylesheet") != -1
          && aTitle) {
        titles = aTitle.split(',');
        for (k=0; k < titles.length; k++) {
          var trimmedTitle = titles[k].trim();
          if (tmpList.indexOf("{" + trimmedTitle + "}") == -1) {
            tmpList = tmpList.concat("{", trimmedTitle, "}");
            stylesheetList[j++] = a;
          }
        }
      }    
    }
  };
  
  this.createUI = function () {
  
    var i;
    var newP = document.createElement('P');
    newP.appendChild(document.createTextNode(introText));
    cssSwitch.appendChild(newP);
    
    var newUL = document.createElement('UL');
    for (i=0; i < stylesheetList.length; i++) {
      newUL.appendChild(createUIElement(stylesheetList[i]));
    }
    cssSwitch.appendChild(newUL); 
  };

  var createUIElement = function (aList) {
    
    var newLI = document.createElement('LI');
    var newA = document.createElement('A');
    newA.setAttribute('id',idName + aList.title.replace(" ", ""));
    newA.setAttribute('href',destination);
    newA.appendChild(document.createTextNode(aList.title));

    MAP.addEvent(newA,'click', function(W3CEvent) {
        var str = this.firstChild.nodeValue;
        MAP.setActiveStyleSheet(str);
        MAP.setCookie(cookieName,str,365);
      });

    newLI.appendChild(newA);
    
    return newLI;
  };
  
  findStylesheets();
  this.createUI();
  var cssCookie = MAP.getCookie(cookieName);
  if (cssCookie != null && cssCookie != '') {
    MAP.setActiveStyleSheet(cssCookie);
  }

}
window['MAP']['CSSSwitch'] = myCssSwitch;  
})();


MAP.addEvent(window,'load',function(W3CEvent) {
  var cssSwitcher = new MAP.CSSSwitch('cssSwitch');
});

