/*	
  fbIR (FotoBuzz Image Replacement) Version 1.0
  Copyright 2004 2Entwine, LLC
  
  Portions adopted from:
  
  sIFR (Scalable Inman Flash Replacement) Version 2.0 RC1
  Copyright 2004 Mike Davidson, Shaun Inman, Tomas Jogin and Mark Wubben
  
  This software is licensed under the CC-GNU LGPL <http://creativecommons.org/licenses/LGPL/2.1/>
*/

//Flash Player Detection
function detectFlash(version) {
  if(navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.indexOf("Windows") > -1) {
    document.write('<script language="VBScript"\> \n');
    document.write('on error resume next \n');
    document.write('hasFlash = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & ' + version + '))) \n');  
    document.write('<'+'/script\> \n');
    /*	If executed, the VBScript above checks for Flash and sets the hasFlash variable. 
      If VBScript is not supported it's value will still be undefined, so we'll run it though another test
      This will make sure even Opera identified as IE will be tested */
    if(window.hasFlash != null)
      return window.hasFlash;
  }
  
  if(navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"] && navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin) {
    var flashDescription = (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description;
    var flashVersion = parseInt(flashDescription.charAt(flashDescription.indexOf(".") - 1));
    return flashVersion >= version;
  }
  
  return false;
}

var reqVersion = 7;
var hasFlash = detectFlash(reqVersion);

//String prototype
String.prototype.normalize = function() {
  return this.replace(/\s+/g, " ");
}

//Mac IE5 does not support pop() *or push()
if(Array.prototype.pop == null) {
  Array.prototype.pop = function() {
    if(this.length == 0) {
      return;
    } else {
      var last = this[this.length-1];
      this.length--;
      return last;
    }
  }
}

//User Agent detection (Opera and Mozilla require a namespace when creating elements in an XML page)
var sNameSpaceURI = "http://www.w3.org/1999/xhtml";
var sUA = navigator.userAgent.toLowerCase();

var UA = new Object();
UA.bIsKHTML = sUA.indexOf('safari') > -1 || sUA.indexOf('konqueror') > -1 || sUA.indexOf('omniweb') > -1; 
UA.bIsOpera = sUA.indexOf('opera') > -1;
UA.bIsGecko = navigator.product != null && navigator.product.toLowerCase() == 'gecko';
UA.bIsXML = document.contentType != null && document.contentType.indexOf('xml') > -1;
UA.bIsIE = sUA.indexOf('msie') > -1 && !(UA.bIsOpera || UA.bIsKHTML || UA.bIsGecko);

//Declare Viewlet Properties
var fbViewletPath;
var fbScriptPath;
var fbShowNotes = true; //default
var fbShowShadow = true; //default
var fbXData;

//Detects whether image replacement is possible
if(hasFlash && Boolean(document.getElementsByTagName) && Boolean(document.createElement)) {

  var rcount = 1; //replace count
  
  //hide images while page loads
  if(document.documentElement) {
    var clsName = document.documentElement.className;
    document.documentElement.className = clsName.normalize() + (clsName == "" ? "" : " ") + "fbIR-hasFlash";
  }
  
  //setup onLoad Event to replace images
  if(window.attachEvent) {
    window.attachEvent("onload", fbIR);
  
  } else if(document.addEventListener || window.addEventListener) {
    if(document.addEventListener)
      document.addEventListener("load", fbIR, false);	
  
    if(window.addEventListener)
      window.addEventListener("load", fbIR, false);	
  
  } else {
    //onLoad already defined, so redfine, inserting what we need
    if(typeof window.onload == "function") {
      var cLoad = window.onload;
      window.onload = function() { cLoad(); fbIR(); };
    } else {
    window.onload = fbIR;
    }
  }
}

//Finds all images to replace
function fbIR() {
  var cont = true;
  var images, len;
  
  while(cont) {
    cont = false;
    images = document.getElementsByTagName("img");
    len = images.length;
    
    for(var i=0; i<len; i++) {
      //if(images[i].className == "fotobuzz") {
	  if(images[i].className == "fotobuzz") {
        replaceImage(images[i]);
        cont = true;
        break;
      }
    }
  }
  
  forceRedraw();
}

//Corrects a margin-bottom sum bug in Mozilla
function forceRedraw() {
  var d = document;
  if (d.body && d.body.style) {
    d.body.style.height = "1px";
    d.body.style.height = "auto";
  }
}

//Splits a URL into a head and tail
function splitPath(path) {
  var spath = path.split("/");
  var tail = spath.pop();
  
  if(spath.length)
    return [spath.join("/")+"/",tail];
  else
    return ["",tail];
}

//Returns a relative path from sPath to ePath
function resolvePaths(sPath,ePath) {
  var bspath = sPath.split("/");
  var bepath = ePath.split("/");
  var repath = ""; //resolved path
  
  //if paths end with "/" strip
  if(bspath[bspath.length-1] == "")
    bspath.pop();
  if(bepath[bepath.length-1] == "")
    bepath.pop();
  
  //find common path
  var i = 0;
  var j;
  var len = (bspath.length >= bepath.length) ? bspath.length : bepath.length;
  while(bspath[i] == bepath[i] && i++ < len); // <- note no loop body needed
  //if spath is longer than common path, build reverse path
  j = i;
  while(j++ < bspath.length)
    repath += "../";
  //if epath is longer that common path, build forward path
  if(i < bepath.length)
    repath += bepath.slice(i).join("/")+"/";
	
  return repath;
}

//Gets a CSS style property for the given node * Does NOT work in Safari
function getStyle(node,style) {
  var value = node.style[style];
  
  if(!value && document.defaultView) {
    value = document.defaultView.getComputedStyle(node,"").getPropertyValue(style);
  } else if(!value && node.currentStyle) {
    value = node.currentStyle[hyphenToCamelCase(style)];
  }
  
  return value;
}

//converts a hyphenated string to a camelCase string
function hyphenToCamelCase(str) {
  var cb = str.split("-");
  
  if(cb.length == 1) //no "-" in str
    return str;
  else
    return cb[0]+cb[1].charAt(0).toUpperCase()+cb[1].substr(1);
}

function createElement(sTagName) {
  if(document.createElementNS)
    return document.createElementNS(sNameSpaceURI, sTagName);	
  else
    return document.createElement(sTagName);
}

function createObjectParameter(objNode,name,value){
  var node = createElement("param");
  node.setAttribute("name",name);	
  node.setAttribute("value",value);
  objNode.appendChild(node);
}

//Replaces an image with the viewlet
function replaceImage(node) {
  var width = parseInt(node.width)+((fbShowShadow) ? 14 : 0);
  var height = parseInt(node.height)+((fbShowShadow) ? 32 : 25);
  
  //Variables to pass to the viewlet
  var flashvars = "ImageURL="+escape(node.src)+"&FBDataURL="+escape(fbScriptPath)+"&FBPath="+escape(node.src.slice(node.src.indexOf("/",7)));
  flashvars += "&ShowNotes="+((fbShowNotes) ? "true" : "false");
  flashvars += "&ShowShadow="+((fbShowShadow) ? "true" : "false");
  flashvars += "&ID=fotobuzz"+rcount; //this matches the embed/object id
  
  //This allows passing arbitrary data to the viewlet which is then sent back as "xdata" in POST requests to the script
  if(fbXData != null)
    flashvars += "&XData="+fbXData;
  
  
  //Calculate the background color for the viewlet (ignore Safari)
  var color = (UA.bIsKHTML) ? "#FFFFFF" : getStyle(node.parentNode,"background-color");
  
  if(color.indexOf("rgb") > -1) { //mozilla style: rgb(r,g,b)
    color = color.substring(4,color.length-1);
    color = "#"+RGBToHex.apply(null,color.split(","));
  } else if(color.length == 4) { //color shorthand: #nnn *Does NOT work in Mac IE5
    color = ["#",color.charAt(1),color.charAt(1),
                 color.charAt(2),color.charAt(2),
                 color.charAt(3),color.charAt(3)].join("");
  } else if(color == "transparent") {
    color = "#FFFFFF";
  }
  
  //Only Opera requires an Object element
  if(UA.bIsOpera) {
    viewlet = createElement("object");
    viewlet.setAttribute("type", "application/x-shockwave-flash");
    viewlet.setAttribute("data", fbViewletPath);
    createObjectParameter(viewlet, "quality", "high");
    createObjectParameter(viewlet, "bgcolor", color);
    createObjectParameter(viewlet, "menu", "false");
    createObjectParameter(viewlet, "scale", "noscale");
    createObjectParameter(viewlet, "salign", "LT");
    createObjectParameter(viewlet, "flashvars", flashvars);
  } else {
    viewlet = createElement("embed");
    viewlet.setAttribute("src", fbViewletPath);
    viewlet.setAttribute("flashvars", flashvars);
    viewlet.setAttribute("type", "application/x-shockwave-flash");
    viewlet.setAttribute("pluginspage", "http://www.macromedia.com/go/getflashplayer");
    viewlet.setAttribute("bgcolor", color);
  }
  
  viewlet.className = "fbIR-flash";
  viewlet.setAttribute("id", "fotobuzz"+(rcount++)); //element.id not supported by Safari
  viewlet.setAttribute("width", width);
  viewlet.setAttribute("height", height);
  viewlet.style.width = width + "px";
  viewlet.style.height = height + "px";
  
  //Replace the Image with the Flash Object
  var parent = node.parentNode;
  parent.replaceChild(viewlet,node);
  
  /*Workaround to force KHTML-browsers to repaint the document. 
  Additionally, IE for both Mac and PC need this.
  See: http://neo.dzygn.com/archive/2004/09/forcing-safari-to-repaint */
  if(UA.bIsKHTML || UA.bIsIE)
    parent.innerHTML += "";
}

//Each viewlet resize in opera must be unique so we use a flip bit
var flipBit = 1;

//Resizes a Flash object
function resizeViewlet(w,h,id) {
  var viewlet = document.getElementById(id);
    
  viewlet.style.width = (UA.bIsOpera) ? (w + (flipBit = -flipBit)) : w + "px";
  viewlet.style.height = h + "px";
}

//converts a decimal to hex
function decToHex(num) {
 if (num==null) 
   return "00";
 
 num=parseInt(num); 
 
 if (num==0 || isNaN(num)) 
   return "00";
 
 num=Math.max(0,num); 
 num=Math.min(num,255); 
 num=Math.round(num);
 
 return "0123456789ABCDEF".charAt((num-num%16)/16) + "0123456789ABCDEF".charAt(num%16);
}

//converts an rgb value to hex
function RGBToHex(R,G,B) {
  return decToHex(R)+decToHex(G)+decToHex(B);
}