/*
	Dynamic Heading Generator
    By Stewart Rosenberger
    http://www.stewartspeak.com/headings/

	This script searches through a web page for specific or general elements
	and replaces them with dynamically generated images, in conjunction with
	a server-side script.

  Updated for Prototype / DrawText / Multiple calls (for AJAX) by Dave Duchene http://adaptas.net
*/
 function setStyleSheetState(id,enabled) 
 {
     var sheet = document.getElementById(id);
     if(sheet)
         sheet.disabled = (!enabled);
 }

var Replacer = Class.create({
  initialize: function(hideFlicker, doNotPrintImages) {
    this.items = [];
    this.hideFlicker = hideFlicker;
    this.doNotPrintImages = doNotPrintImages;

    // Straight from Wikipedia Base64 article, updated for their "URL style" encoding
    this.base64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'.split("");

    var hideFlickerCSS = "http://www.condovue.com/blog/wp-content/themes/default/replacement-screen.css";
    var hideFlickerTimeout = 1000;
    var printerCSS = "http://www.condovue.com/blog/wp-content/themes/default/replacement-print.css";

    var imageLoadTestURL = "http://www.condovue.com/blog/wp-content/themes/default/images/rails.png";
 
    if (this.hideFlicker) {		
      // Use our document.write as a way to ensure first branch only runs once
      if (!$('hide_flicker')) {
        document.write('<link id="hide_flicker" rel="stylesheet" media="screen" href="' + hideFlickerCSS + '" />');		

        var imageLoadTest = window.imageLoadTest = new Image();
        var thisReplacer = this;
        var loadHandler = function() { window.imageLoaded = true; };

        Event.observe(window, 'load', loadHandler);
        imageLoadTest.onload = loadHandler;

        imageLoadTest.src = imageLoadTestURL + '?date=' + (new Date()).getTime();
        window.flickerCheck = function() { if (!window.imageLoaded) setStyleSheetState('hide_flicker', false); };

        setTimeout('window.flickerCheck();', hideFlickerTimeout);
      } else {
        setStyleSheetState('hide_flicker', true);
      }
    }  

    if (doNotPrintImages) document.write('<link id="print_text" rel="stylesheet" media="print" href="' + printerCSS + '" />');
  },

  replaceSelector: function(selector,url) {
    this.items[this.items.length] = {selector: selector, url: url};
  },

  excludeSelector: function(selector) {
    this.items[this.items.length] = {selector: selector, exclude: true};
  },

  replace: function() {
    if (this.replacedAlready) return;

    var items = this.items;
    var exclusions = {};

    for (var i = 0; i < items.length; i++) {
      var elements = $$(items[i].selector);
      if (items[i].exclude) for (var j = 0; j < elements.length; j++) {
        exclusions[elements[j].identify()] = true;
      } else if (elements.length > 0) for (var j = 0; j < elements.length; j++) {
        if (!elements[j]) continue;

        if (exclusions[elements[j].identify()]) continue;
      
        var text = this.extractText(elements[j]);
        while (elements[j].hasChildNodes()) elements[j].removeChild(elements[j].firstChild);
        var url = items[i].url + this.base64Encode(text.replace(/ /g,'+').replace(/[ \t\r]*\n[ \t\r]*/, "\n")) + ".png";
        var image = new Element('img', {'class': 'replacement', alt: text, src: url});
        elements[j].appendChild(image);

        if (this.doNotPrintImages) {
          var span = document.createElement("span");
          span.style.display = 'none';
          span.className = "print-text";
          span.appendChild(document.createTextNode(text));
          elements[j].appendChild(span);
        }
      }
    }

    if (this.hideFlicker) setStyleSheetState('hide_flicker', false);
    this.replacedAlready = true;
  },

  extractText: function(element) {
    var text = "";
    var kids = element.childNodes;
    for (var i = 0; i < kids.length; i++) {
      var kid = kids[i];

      if (kid.nodeType == 1) {
        // Element
        if (kid.tagName.toLowerCase() == 'br') text += "\n";
        else text += this.extractText(kid);
      }
      else if (kid.nodeType == 3) {
        // Text
        text += kid.nodeValue;
      }
    }

    return text;
  },

  base64Encode: function(s) {
    // Straight from Wikipedia Base64 article, updated for their "URL style" encoding

    // the result/encoded string, the padding string, and the pad count
	var tye=s;
    var r = ""; 
    var pad = 3 - s.length % 3;
    var c = s.length % 3;
   
    // add a right zero pad to make this string a multiple of 3 characters
    if (c > 0) { 
      for (; c < 3; c++) { 
        s += "\0"; 
      } 
    }
   
    // increment over the length of the string, three characters at a time
    for (c = 0; c < s.length; c += 3) {
   
      // we add newlines after every 76 output characters, according to the MIME specs
      if (c > 0 && (c / 3 * 4) % 76 == 0) { 
        r += "\r\n"; 
      }
   
      // these three 8-bit (ASCII) characters become one 24-bit number
      var n = (s.charCodeAt(c) << 16) + (s.charCodeAt(c+1) << 8) + s.charCodeAt(c+2);
   
      // this 24-bit number gets separated into four 6-bit numbers
      n = [(n >>> 18) & 63, (n >>> 12) & 63, (n >>> 6) & 63, n & 63];
   
      // those four 6-bit numbers are used as indices into the base64 character list
      r += this.base64chars[n[0]] + this.base64chars[n[1]] + this.base64chars[n[2]] + this.base64chars[n[3]];
    }
     // no need to pad
    return tye;
  }
});

var standardReplacer = new Replacer(true, true);

standardReplacer.excludeSelector('#flash_errors h2');
standardReplacer.excludeSelector('#flash_notice h2');

standardReplacer.replaceSelector("#header h1",  "http://www.condovue.com/blog/heading.php?style=h1&text=");
standardReplacer.replaceSelector("#content h2", "http://www.condovue.com/blog/heading.php?style=h2&text=");
standardReplacer.replaceSelector("#content h3", "http://www.condovue.com/blog/heading.php?style=h3&text=");
standardReplacer.replaceSelector("#content .with-microsite h3", "/images/text/");

standardReplacer.replaceSelector("#full_screen_content h1", 
    "/images/text/Omnes-Light/48_48_12_625_regular_normal_ffffff_ff9900/");

standardReplacer.replaceSelector("#landing #developments_teaser_wrap h2",
    "/images/text/Omnes-Medium/18_18_6_625_regular_normal_ffffff_666666/");
// standardReplacer.replaceSelector("#landing #developments_teaser_wrap .teaser strong",
    // "/images/text/Omnes-Medium/20_20_6_145_regular_normal_none_666666/");

standardReplacer.replaceSelector("#comparison_slots h2", "/images/text/Omnes-Medium/20_20_6_132_regular_normal_ffffff_6f6151/");

standardReplacer.replaceSelector("#sidebar h2", "http://www.condovue.com/blog/heading.php?side=sidebar&style=h2&text=");
standardReplacer.replaceSelector("#sidebar h3", "/images/text/Omnes-Medium/20_25_6_260_regular_normal_ffffff_ff9900/");
standardReplacer.replaceSelector("#sidebar h3.control-panel", 
    "/images/text/Omnes-SemiBold/14_25_6_260_regular_normal_c7e0e1_6f6151/");
standardReplacer.excludeSelector("legend.for-radio-button");
standardReplacer.replaceSelector("legend", "/images/text/Omnes-Medium/18_25_6_625_regular_normal_ffffff_ff9900/");

Event.observe(window, 'load', function() { standardReplacer.replace(); });

