/* imagewrap.js
 Copyright 2006 Chris Renner
 All and ALL RIGHTS RESERVED (for now)

*/

window.onload = setup;
window.onresize = rewrap;

var element;
var spans = new Array();
var widths = new Array();
var thespan;

function setup() {


	thespan = document.getElementById('thespan');
		
	var width = xGetComputedStyle(thespan.parentNode, 'width', true);
	if(width == 0) width = thespan.parentNode.offsetWidth;
	
	var height = xGetComputedStyle(thespan.parentNode, 'height', true);
	if(height == 0) height = thespan.parentNode.offsetHeight;
		
	thespan.style['width'] = width + 'px';
	thespan.style['height'] = height + 'px';
	thespan.style['display'] = 'block';
	thespan.parentNode.style['display'] = 'block';

	var totalwidth = new Array(0);
	var currentline = 0;
	for(var i=0;i<breaks.length;i++) {
		if(i==0) {
			widths[i] = breaks[i];
		} else {
			widths[i] = breaks[i] - breaks[i-1];
		}
		spans[i] = document.createElement('span') ;
		spans[i].style['height'] = imageheight + 'px' ;
		spans[i].style['width'] = widths[i] + 'px' ;
		spans[i].style['left'] = (breaks[i-1]?breaks[i-1]:0) + "px";
		spans[i].style.backgroundPosition = '-' + (breaks[i-1]?breaks[i-1]:0) + 'px 0px';
 		
 		thespan.appendChild(spans[i]);
	}
	
	rewrap();
	
}

function rewrap() {
	var width = xGetComputedStyle(thespan.parentNode, 'width', true);
	if(width == 0) width = thespan.parentNode.offsetWidth;

	thespan.style['width'] = width + 'px';
	var linewidth = new Array(0,0,0,0);
	var linecount = 0;
	
	for(var i=0;i<spans.length;i++) {
		 
		 if(linewidth[linecount] + widths[i] > width) {
		 	linecount++;
		 }
		 spans[i].style['top'] = (linecount * lineheight) + 'px';
		 spans[i].style['left'] = (linewidth[linecount]) + 'px';
		 
		linewidth[linecount] += widths[i];
	}
	
	thespan.style['height'] = (lineheight * (linecount + 1) + 8) + 'px';
	thespan.parentNode.style['height'] = thespan.style['height'];
}

function xGetComputedStyle(oEle, sProp, bInt)
{
  var s, p = 'undefined';
  var dv = document.defaultView;
  if(dv && dv.getComputedStyle){
    s = dv.getComputedStyle(oEle,'');
    if (s) p = s.getPropertyValue(sProp);
  }
  else if(oEle.currentStyle) {
    // convert css property name to object property name for IE
    var a = sProp.split('-');
    sProp = a[0];
    for (var i=1; i<a.length; ++i) {
      c = a[i].charAt(0);
      sProp += a[i].replace(c, c.toUpperCase());
    }   
    p = oEle.currentStyle[sProp];
  }
  else return null;
  return bInt ? (parseInt(p) || 0) : p;
}

