// picnikbox
// Based on lightbox implementation by Chris Campbell (http://particaltree.com)
// Chris' version inspired by the lightbox implementation found at http://www.huddletogether.com/projects/lightbox/

/*-----------------------------------------------------------------------------------------------*/

//Browser detect script origionally created by Peter Paul Koch at http://www.quirksmode.org/

instructions = '&nbsp; Instructions : <table width=100% border=0><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td><td>Upload and edit your photo using Picnik (the feature below). When finished, save the photo to your computer, then upload it to Print on Demand Shop into either your "File Manager" or when requested to "Design Your Own Products".</td></tr></table>';

statcounter = '<img class="statcounter" src="http://c39.statcounter.com/3471094/0/f8234115/1/" alt="website page counter" >';

var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;

function getBrowserInfo() {
	if (checkIt('konqueror')) {
		browser = "Konqueror";
		OS = "Linux";
	}
	else if (checkIt('safari')) browser 		= "Safari"
	else if (checkIt('omniweb')) browser 	= "OmniWeb"
	else if (checkIt('opera')) browser 		= "Opera"
	else if (checkIt('webtv')) browser 		= "WebTV";
	else if (checkIt('icab')) browser 		= "iCab"
	else if (checkIt('msie')) browser 		= "Internet Explorer"
	else if (checkIt('firefox')) browser 		= "Firefox"
	else if (!checkIt('compatible')) {
		browser = "Netscape Navigator"
		version = detect.charAt(8);
	}
	else browser = "An unknown browser";

	if (!version) version = detect.charAt(place + thestring.length);

	if (!OS) {
		if (checkIt('linux')) OS 		= "Linux";
		else if (checkIt('x11')) OS 	= "Unix";
		else if (checkIt('mac')) OS 	= "Mac"
		else if (checkIt('win')) OS 	= "Windows"
		else OS 								= "an unknown operating system";
	}
}

function checkIt(string) {
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

/* Helpers swiped from prototype.js (http://www.prototypejs.org) and elsewhere ------------------*/

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}

function $() {
  var elements = new Array();

  for (var i = 0; i < arguments.length; i++) {
    var element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);

    if (arguments.length == 1)
      return element;

    elements.push(element);
  }

  return elements;
}

Function.prototype.bindAsEventListener = function(object) {
  var __method = this;
  return function(event) {
    return __method.call(object, event || window.event);
  }
}

function hasClassName(element, className) {
    if (element.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
        return true;
    return false;
}

document.getElementsByClassName = function(className, parentElement) {
  var elements = new Array();
  var children = ($(parentElement) || document.body).getElementsByTagName('*');
  for (var i = 0; i < children.length; i++) {
    var child = children[i];
    if (child.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
      elements.push(child);
  }
  return elements;
}

function observeEvent(element, name, observer, useCapture) {
	var element = $(element);
	useCapture = useCapture || false;
	
	if (element.addEventListener) {
		element.addEventListener(name, observer, useCapture);
	} else if (element.attachEvent) {
		element.attachEvent('on' + name, observer);
	}
}

function getViewportSize() {
	var size = [0, 0];
	if (typeof window.innerWidth != 'undefined') {
		// Don't trust Firefox
		var ovl = $('overlay');
		if (ovl && ovl.scrollWidth) {
			size = [ ovl.scrollWidth, ovl.scrollHeight ];
		} else {
			size = [ window.innerWidth, window.innerHeight ];
		}
	} else if (typeof document.documentElement != 'undefined' &&
			typeof document.documentElement.clientWidth != 'undefined' &&
			document.documentElement.clientWidth != 0) {
		size = [ document.documentElement.clientWidth, document.documentElement.clientHeight ];
	} else {
		size = [ document.getElementsByTagName('body')[0].clientWidth,
				document.getElementsByTagName('body')[0].clientHeight ];
	}
	
	return size;
}

// Thanks quirksmode.org
function getStyle(el, styleProp) {
	var x = el;	// document.getElementById(el);
	if (x.currentStyle) {
		var y = x.currentStyle[styleProp];
	} else if (document.defaultView.getComputedStyle) {
		var css = document.defaultView.getComputedStyle(x,null);
		if (css)
//			var y = css.getPropertyValue(styleProp);
			var y = css[styleProp];
	} else if (window.getComputedStyle) {
		var css = window.getComputedStyle(x,null);
		if (css)
			var y = css.getPropertyValue(styleProp);
	}
	return y;
}

function parsePx(strPx) {
	return parseInt(strPx.substr(0, strPx.length - 2));
}

function getPicnikboxStyleValue(strStyle) {
	var strT = getStyle($('picnikbox'), strStyle);
	if (strT)
		return parsePx(strT);
	return 0;
}

/*-----------------------------------------------------------------------------------------------*/

pbActive = null;

observeEvent(window, 'load', onLoad, false);
observeEvent(window, 'resize', onResize, false);

var picnikbox = Class.create();

picnikbox.prototype = {
	yPos : 0,

	initialize: function(ctrl) {
		this.content = ctrl.href;
		observeEvent(ctrl, 'click', this.activate.bindAsEventListener(this), false);
		ctrl.onclick = function() { return false; };
	},
	
	// Turn everything on - mainly the IE fixes
	activate: function() {
		if (browser == 'Internet Explorer') {
			this.getScroll();
			this.prepareIE('100%', 'hidden');
			this.setScroll(0, 0);
			this.hideSelects('hidden');
		}
		this.displayPicnikbox("block");
		pbActive = this;
	},
	
	// IE requires height to 100% and overflow hidden or else you can scroll down past the picnikbox
	prepareIE: function(height, overflow) {
		bod = document.getElementsByTagName('body')[0];
		bod.style.height = height;
		bod.style.overflow = overflow;
  
		htm = document.getElementsByTagName('html')[0];
		htm.style.height = height;
		htm.style.overflow = overflow; 
	},
	
	// In IE, select elements hover on top of the picnikbox
	hideSelects: function(visibility) {
		selects = document.getElementsByTagName('select');
		for(i = 0; i < selects.length; i++) {
			selects[i].style.visibility = visibility;
		}
	},
	
	// Taken from lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
	getScroll: function() {
		if (self.pageYOffset) {
			this.yPos = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {
			this.yPos = document.documentElement.scrollTop; 
		} else if (document.body) {
			this.yPos = document.body.scrollTop;
		}
	},
	
	setScroll: function(x, y) {
		window.scrollTo(x, y); 
	},
	
	displayPicnikbox: function(display) {
		$('overlay').style.display = display;
		$('picnikbox').style.display = display;
		
		// Write an iframe to house Picnik
		if (display != 'none') {            
			$('picnikbox').innerHTML = "" + instructions + "<iframe id='picnikiframe' frameborder='0' scrolling='no' src='" + this.content + "'></iframe>" + statcounter + "";
			onResize();
		} else {
			$('picnikbox').innerHTML = '';
		}
	},
	
	// Remove the picnikbox
	deactivate: function() {
        alert ("finished closing");
		if (browser == "Internet Explorer") {
			this.getScroll();
			this.prepareIE("auto", "auto");
			this.hideSelects("visible");
			this.setScroll(0, this.yPos);
		}
		
		this.displayPicnikbox("none");
	}
}

/*-----------------------------------------------------------------------------------------------*/

// onload, make all links that need to trigger a picnikbox active
function onLoad() {
	getBrowserInfo();
	addPicnikboxMarkup();
	var links = document.getElementsByClassName('pbox');
	for (i = 0; i < links.length; i++)
		var valid = new picnikbox(links[i]);
}

function onResize() {
	var cxBorder = getPicnikboxStyleValue('borderLeftWidth');
	cxBorder += getPicnikboxStyleValue('borderRightWidth');
	var cyBorder = getPicnikboxStyleValue('borderTopWidth');;
	cyBorder += getPicnikboxStyleValue('borderBottomWidth');
	
	var size = getViewportSize();
	var pbox = $('picnikbox');
	
	var cxMargin = getPicnikboxStyleValue('marginLeft');
	cxMargin += getPicnikboxStyleValue('marginRight');
	var yTop = getPicnikboxStyleValue('top');
	var cyMarginTop = getPicnikboxStyleValue('marginTop');
	var cyMarginBottom = getPicnikboxStyleValue('marginBottom');
	cyBox = size[1] - yTop - cyMarginTop - cyMarginBottom;
	cxBox = size[0] - cxMargin;

	pbox.style.width = (cxBox - cxBorder) + 'px';
	pbox.style.height = (cyBox - cyBorder) + 'px';

	$('overlay').style.zIndex = "9997";
	if (browser == "Firefox") {
		// firefox can't handle flash and opacity styles at the same time
		if (!hasClassName( $('overlay'), "UsePNGForBackground" )) 
			$('overlay').className += " UsePNGForBackground";
	} else {
		if (!hasClassName( $('overlay'), "UseOpacityForBackground" )) 
			$('overlay').className += " UseOpacityForBackground";
	}
	
	$('picnikbox').style.zIndex = "9998";
	var ifrm = $('picnikiframe');
	if (ifrm) {
        if (ifrm.style.height != 0){
           alert("height exists");
        } else {
		   ifrm.style.height = pbox.style.height - 10;
        }
		ifrm.style.zIndex = "9999";
	}
}

function onPicnikClose() {
  	var bod = document.getElementsByTagName('body')[0];
    var old_overlay = document.getElementById('overlay');
    bod.removeChild(old_overlay);
    var old_picnikbox = document.getElementById('picnikbox');
    bod.removeChild(old_picnikbox);
		bod.style.height = "auto";
		bod.style.overflow = "auto";
  
		htm = document.getElementsByTagName('html')[0];
		htm.style.height = "auto";
		htm.style.overflow = "auto"; 
}


function close_de_layer() {
}


var fExpanded = false;
var strMarginLeftSav, strMarginRightSav, strMarginTopSav, strMarginBottomSav, strLeftSav, strTopSav;

function onPicnikExpand(fExpand) {
	if (fExpanded != fExpand) {
		var pbox = $('picnikbox');
		if (fExpand) {
			strMarginLeftSav = getStyle(pbox, 'marginLeft');
			strMarginTopSav = getStyle(pbox, 'marginTop');
			strMarginRightSav = getStyle(pbox, 'marginRight');
			strMarginBottomSav = getStyle(pbox, 'marginBottom');
			strLeftSav = getStyle(pbox, 'left');
			strTopSav = getStyle(pbox, 'top');
			
			pbox.style.marginLeft = '0px';
			pbox.style.marginTop = '0px';
			pbox.style.marginRight = '0px';
			pbox.style.marginBottom = '0px';
			pbox.style.left = '0px';
			pbox.style.top = '0px';
		} else {
			pbox.style.marginLeft = strMarginLeftSav;
			pbox.style.marginTop = strMarginTopSav;
			pbox.style.marginRight = strMarginRightSav;
			pbox.style.marginBottom = strMarginBottomSav;
			pbox.style.left = strLeftSav;
			pbox.style.top = strTopSav;
		}
		fExpanded = fExpand;
		onResize();
	}
}

// Add in markup necessary to make this work. Basically two divs:
// Overlay holds the shadow
// Picnikbox is the centered square that the Picnik iframe is put into.
function addPicnikboxMarkup() {
	var bod = document.getElementsByTagName('body')[0];
	var overlay = document.createElement('div');
	overlay.id = 'overlay';
	var pbox = document.createElement('div');
	pbox.id = 'picnikbox';
	bod.appendChild(overlay);
	bod.appendChild(pbox);
}
