/*
    Rvolve Zoom Pics
    
    Copyright (C) 2011 Rvolve  Ver 0.53

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.  The only exception to this
    license is the Rvolve 'zoompic' logo must remain visible, and clickable.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see http://www.gnu.org/licenses/.



Usage:
	
	Header:
	<script src="http://rvolve.com/js/zoom-pic.js" type="text/javascript"></script>
	<!--[if IE]><script src="http://rvolve.com/js/excanvas.compiled.js"></script><![endif]-->
	
	<script type="text/javascript">
		startImage('http://mysite/myimage.jpg', 200, 200);
	</script>
	<div id="zoom-pic">
		<div id="mycanvas_0"></div>
	</div>
	
	Where:
	One zoom-pic gets displayed at 200x200 pixels.


Using Multiple Images:	
	<script type="text/javascript">
		startImages(4, 'photos/img', 0, 200, 200);
	</script>
	
	Body:
	<div id="zoom-pic">
		<div id="mycanvas_0"></div>
		<div id="mycanvas_1"></div>
		<div id="mycanvas_2"></div>
		<div id="mycanvas_3"></div>
	</div>

	Where:
	Which would display the 4 images photos/img0.jpg, photos/img1.jpg, photos/img2.jpg, photos/img3.jpg
	within the divs above, at 200 pixels wide by 200 pixels high.

	startImages(number of images, 
			path to images (without number and extension),
			number to start from to append to path, 
			width pixels, 
			height pixels)
Options:
	rvolveFileType		- '.png', '.jpg', '.gif' default: .jpg
	rvolveVerticalPoint 	- 0.0-1.0.  Where 0.0 is zooming into top point
	rvolveHorizontalPoint 	- 0.0-1.0.  Where 0.0 is zooming into left point, 1.0 is zooming into right
	
	Surround the <div id="mycanvas_0"></div> with a href tag to provide a link
		e.g. <a href="http://google.com"><div id="mycanvas_0"></div></a>

	
For assistance:
	webmaster AT rvolve.com
*/


function scaleImage(canvasWidth, canvasHeight, imageWidth, imageHeight, zoom)
{
	var outputX = 0;
	var outputY = 0;
	var outputWidth = 1;
	var outputHeight = 1;
	
	//Scale up
	var ratioImage = imageWidth / imageHeight;
	var ratioCanvas = canvasWidth / canvasHeight;

	if(ratioImage >= 1) {
		if(ratioCanvas >= ratioImage) {
			var scale = canvasWidth / imageWidth;
		} else {
			var scale = canvasHeight / imageHeight;
		}
	} else {
		if(ratioCanvas >= ratioImage) {
			var scale = canvasWidth / imageWidth;
		} else {
			var scale = canvasHeight / imageHeight;
		}
	}
	
	scale = scale * zoom;
	outputWidth = imageWidth * scale;
	outputHeight = imageHeight * scale;

	if(outputHeight > canvasHeight) {
		outputY = - ((imageHeight * scale) * rvolveVerticalPoint) + (canvasHeight * rvolveVerticalPoint);
	}

	if(outputWidth > canvasWidth) {
		outputX = - ((imageWidth * scale) * rvolveHorizontalPoint) + (canvasWidth * rvolveHorizontalPoint);
	}
	
	return [outputX, outputY, outputWidth, outputHeight, scale];


}

var rvolveHasFocus = true;
var stopAllAnimations = false;
var zp = new Image();
var rvolveLogoWidth = 70;
var rvolveLogoHeight = 28;
var rvolvePath = '';
var rvolveStart = 0;
var rvolveCanvasHeight = 200;
var rvolveCanvasWidth = 200;
var rvolveVerticalPoint = 0.5;
var rvolveHorizontalPoint = 0.5;
var rvolveFileType = ".jpg";	
var rvolveCm = false;


function animate(context, cat, canvasWidth, canvasHeight, catWidth, catHeight, zoom, zoomVector)
{
	
	
	//A warning to stop everything
	if(stopAllAnimations != false) {
		stopAllAnimationsFunc();
		return;
	}
	
	
	var newZoom = zoom;
	if(rvolveHasFocus == true) {		//Just ensure we are actually on the window before animating
		var outputImage = scaleImage(canvasWidth, canvasHeight, catWidth, catHeight, zoom);
		context.drawImage(cat, outputImage[0], outputImage[1], outputImage[2], outputImage[3]);
	
		//Show the copyright
		if(rvolveCm == false) {
			context.drawImage(zp, canvasWidth - rvolveLogoWidth - 2, canvasHeight - rvolveLogoHeight - 2);
		}
	
		var newZoom = zoom + zoomVector;
		if(newZoom >= 3) {
		
			zoomVector = - 0.0075;
		
		}
		if(newZoom <= 1) {
			zoomVector = 0.0075;
			//Zoomed out to max - wait for a second
			setTimeout(function(){animate(context, cat, canvasWidth, canvasHeight, catWidth, catHeight, newZoom, zoomVector)}, 3000);
			return;
		}
	}
	
	//A normal next frame
	setTimeout(function(){animate(context, cat, canvasWidth, canvasHeight, catWidth, catHeight, newZoom, zoomVector)}, 30);
		//alert('new frame ' + rvolveHasFocus);
	

}



//Check to see if our window has focus at the moment
function onBlur() {
    rvolveHasFocus = false;
}
function onFocus(){
    rvolveHasFocus = true;
}

if (/*@cc_on!@*/false) { // check for Internet Explorer
    document.onfocusin = onFocus;
    document.onfocusout = onBlur;
} else {
    window.onfocus = onFocus;
    window.onblur = onBlur;
}




function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

//http://mghtb.com/2011/05/27/detecting-ie9s-document-mode-using-javascript/
function isIE9Std() {
  var a;
  try{var b=arguments.caller.length;a=0;}catch(e){a=1;}
  return((document.all&&a)==1);
}


var iePre9 = false;

var ver = getInternetExplorerVersion();

if( ver > -1) {
	//var stndMode = isIE9Std(); 
	//alert(document.documentMode);
	if((typeof(document.documentMode) === 'undefined')||(document.documentMode < 9)) {
		iePre9 = true;
	}
	
}


		//Wait for us to be defined
function setImages(cnt, myImage, linkUrl) {
	
	
	
	
	if (!document.getElementById('rvimg_' + cnt)) {
		var timeout = 'setImages(' + cnt + ',  "' + myImage + '",  "' + linkUrl + '")'; 
		setTimeout(timeout, 150);
		//alert('in here');
	} else {
	
		
		
			 
		var canvas = document.getElementById('rvimg_' + cnt);
		if(iePre9 == true) {
			//Because the element is created dynamically we need to init if using js library
			if(typeof(G_vmlCanvasManager.initElement)  === 'undefined') { 
				//Bit of a hack - wait until the object becomes available
				var timeout = 'setImages(' + cnt + ', "' + myImage + '", "' + linkUrl + '")'; 
				setTimeout(timeout, 100);
				
			} else {
				
				
				G_vmlCanvasManager.initElement(canvas);
					
			}
		}
		
		//alert('Creating pic ' + myImage);
		
		
		var context = canvas.getContext('2d');
		var cat = new Image();
		
		
				
		cat.onload = function(){
			var outputImage = scaleImage(canvas.width, canvas.height, cat.width, cat.height, 1);
			if(outputImage[4] >  2.2) {
				//A blurred image will be replaced with the Rvolve logo
				myImage = "http://rvolve.com/images/rvolve_large_with_border.png";
				cat.src = myImage;	//Will rerun this onload
			} else {
				if(rvolveCm == false) {
					context.drawImage(cat, outputImage[0], outputImage[1], outputImage[2], outputImage[3]);
					zp.src = 'http://rvolve.com/images/rvolve_zoompic.png';
					zp.onload = function() {
						context.drawImage(zp, canvas.width - rvolveLogoWidth - 2, canvas.height - rvolveLogoHeight - 2);
					}
				}

				
				if((iePre9 == false)&&(outputImage[4] < 1.7)) {		//Cut off for blurred images from animating
					animate(context, cat, canvas.width, canvas.height, cat.width, cat.height, 1, 0.0075);
				}
				
			}
		}
		cat.src = myImage;
		
		
		
	}
	
}

function listImages(imgCnt)
{

 	for(cnt = 0; cnt< imgCnt; cnt++) {
		setImages(cnt, rvolvePath + (rvolveStart+cnt) + rvolveFileType, '#');
	}
			

}


function getElementPosition(theElement){

  var posX = 0;
  var posY = 0;
	      
  while(theElement != null){
    posX += theElement.offsetLeft;
    posY += theElement.offsetTop;
    theElement = theElement.offsetParent;
  }
		        		      
   return {x:posX,y: posY};

}


function processClick(event, mycanvas, url) {
    event = event || window.event;
	    	
    var canvas =document.getElementById(mycanvas);
	pos = getElementPosition(canvas);
	x = event.pageX - pos.x,
	y = event.pageY - pos.y;
	
	if((x> (canvas.width - rvolveLogoWidth)) &&
		(y > (canvas.height - rvolveLogoHeight))) {
		
		//Go to our page, and override any a href above it
		if(rvolveCm == false) {
			if(typeof(canvas.parentNode.parentNode.attributes['href']) !== 'undefined') {
				canvas.parentNode.parentNode.attributes['href'].value = 'http://rvolve.com/developer.php#zoompic';
			}
			window.location = 'http://rvolve.com/developer.php#zoompic';
		}
		 
		return false;
	} else {
		if(typeof(canvas.parentNode.parentNode.attributes['href']) === 'undefined') {
			//Fallback is going to the image itself - if there is no a href from user surrounding div
			window.location = url;
		}
	}
}

function createCanvas(id, width, height, url)
{
	
	
	if ((!document.getElementById('mycanvas_' + id))) {
		
		setTimeout('createCanvas(' + id + ',' + width +',' +height+ ',"' + url + '")', 50);
		
	} else {
		if(iePre9 == true) {
			if(typeof(G_vmlCanvasManager)  === 'undefined') {
				setTimeout('createCanvas(' + id + ',' + width +',' +height+ ',"' + url + '")', 50);
				
			} 	
		}
		var mycanvas = document.getElementById('mycanvas_' + id);
		var canvas = document.createElement('canvas');
		canvas.setAttribute("id", 'rvimg_' + id);
		
		canvas.setAttribute("width", width);
		canvas.setAttribute("height", height);
		canvas.setAttribute("style", 'border: solid 1px #DDDDDD'); 
		canvas.setAttribute("onclick", 'processClick(event,\'rvimg_' + id + '\', \'' + url  + '\');');
		mycanvas.appendChild(canvas);
		
	}
		

}

function stopImages() {
	stopAllAnimations = true;
	//setTimeout
}

function startImages(imgNum, path, start, width, height) { 
	rvolvePath = path;
	rvolveStart = start;
	rvolveCanvasWidth = width;
	rvolveCanvasHeight = height;
	
	
	if (!document.getElementById('zoom-pic')) {
		
		setTimeout('startImages(' + imgNum + ',\'' + path + '\',' + start + ',' + width + ',' + height + ')', 150);
		
	} else {
		
		for(cnt = 0; cnt< imgNum; cnt++) {
			createCanvas(cnt, rvolveCanvasWidth, rvolveCanvasHeight, path + (cnt + start) + rvolveFileType);
		}			
				
		listImages(imgNum);
	}
}


function startImage(src, width, height) {
	rvolveCanvasWidth = width;
	rvolveCanvasHeight = height;
	
	if (!document.getElementById('zoom-pic')) {
		
		setTimeout('startImage(\'' + src + '\',' + width + ',' + height + ')', 150);
		
	} else {

		createCanvas(0, rvolveCanvasWidth, rvolveCanvasHeight, src);	
		setImages(0, src, '#');
	}
	

}




				

