/*	
  fbIR (FotoBuzz Image Replacement) Version 1.1
  Copyright 2004-2005 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 fbLockAuthor;

//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.indexOf("fotobuzz") > -1) {
        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) {
  //FotoBuzz uses the CSS class to pass params to the viewlet
  var width, height, index, endIndex;
  var options = node.className;
    
  //Setup Viewlet Preferences
  var flashvars = "ID=fotobuzz"+rcount; //this matches the embed/object id
  flashvars += "&ImageURL="+encodeURI(node.src);
  flashvars += "&ScriptURL="+encodeURI(fbScriptPath);
  flashvars += "&RelImageURL="+encodeURI(node.src.slice(node.src.indexOf("/",7)));
  flashvars += "&ShowShadow="+!inString("fbShadowOff",options);
  flashvars += "&ShowNotes="+!inString("fbNotesOff",options);
  flashvars += "&ShowDownload="+!inString("fbDownloadOff",options);
  flashvars += "&NumMode="+!inString("fbNumModeOff",options);
  flashvars += "&ShowCaptions="+!inString("fbCaptionsOff",options);

  //Lock the author field for new comments
  flashvars += "&AuthorName="+((fbLockAuthor) ? fbLockAuthor : "");

  //Localization preferences
  flashvars += "&Lang="+[fbLangOk,fbLangCncl,fbLangEdit,fbLangDel,fbLangRfsh,
			 fbLangAdCt,fbLangAnCt,fbLangSvIm,fbLangAbt,fbLangName,
			 fbLangTitl,fbLangCmnt,fbLangReme,fbLangErr1,fbLangErr2,
			 fbLangRss].join("|");

  //Refresh preferences
  flashvars += "&Refresh="+findEnding("fbRefresh",options);

  //Border preferences
  var showBorder = !inString("fbBorderOff",options);
  flashvars += "&ShowBorder="+showBorder;
  flashvars += "&BorderColor="+findEnding("fbBorderColor#",options);

  //Matting preferences
  var showMatte = !inString("fbMatteOff",options);
  var matteSize = parseInt(findEnding("fbMatteSize",options));

  if(isNaN(matteSize)) //default matte size
    matteSize = 10;

  flashvars += "&ShowMatte="+showMatte;
  flashvars += "&MatteSize="+matteSize;
  flashvars += "&MatteColor="+findEnding("fbMatteColor#",options);
  
  //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";
  }

  //Calculate Viewlet Size
  width = (node.width > 230) ? node.width : 230;
  height = (node.height > 200) ? node.height : 200;

  //compensate for shadow preference
  if(!inString("fbShadowOff",options)) {
    width += 14;
    height += 7;
  }

  //compensate for border
  if(showBorder) {
    width += 2;
    height += 2;
  }

  //compensate for matting
  if(showMatte && matteSize) {
    width += matteSize*2;
    height += matteSize*2;
  }
  
  //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 += "";
}

function inString(needle,haystack) {
  return (haystack.indexOf(needle) != -1);
}

//looks for needle in haystack and returns user specified ending
function findEnding(needle,haystack) {
  var start = haystack.indexOf(needle);
  var end;

  if(start > -1) {
    start += needle.length;
    end = haystack.indexOf(" ",start);
    if(end == -1)
      end = haystack.length;
    
    return haystack.substring(start,end);
  } else {
    return "";
  }
}

//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);
}
