function initiate() {
	ctxGlobal = null;
	imgGlobal = null;
	initialGlobal = false;
	rotationGlobal = 0;
	scaleGlobal = 1;
	startScale = 1;
	wOr = 0;
	hOr = 0;
	
	first = true;
	array = new Array();
    count = 0;
	interval1 = 1;

	zoomRotateControls();

	if(displayBC){
		brightContrastControls();
	}
	
	var newImg = new Image();
	newImg.src = document.getElementById(imgID).src;
	
	while(interval1 > 0){
		if(document.getElementById(imgID).complete || newImg.complete){
			interval1 = -1;
			initialGlobal = true;
			displayImg(newImg);
		}
	}
}	

function displayImg(newImg){

	if(document.getElementById(imgID).complete.complete){
		wOr = document.getElementById(imgID).width;
		hOr = document.getElementById(imgID).height;
		img_path = document.getElementById(imgID).src;
	}		

	if(newImg.complete){
		wOr = newImg.width;
		hOr = newImg.height;
		img_path = document.getElementById(imgID).src;
	}

	if(wOr > hOr){
		startScale = img_act_width/wOr; 
	}
	else{
		startScale = img_act_height/hOr;
	}
	
	scaleGlobal = startScale;

	min_width = startScale;

	canvasWidth = Math.round(wOr*max_width) + canvasLeft;
	canvasHeight = Math.round(hOr*max_width) + canvasTop;
	
	this.canvas = document.getElementsByTagName("canvas")[0];

	if(hOr >= wOr){
		this.canvas.style.left = -canvasLeft + img_act_width/2 - wOr*scaleGlobal/2 + "px";
		this.canvas.style.top = -canvasTop + "px";
	}
	else{
		this.canvas.style.left = -canvasLeft + "px";
		this.canvas.style.top = -canvasTop + img_act_height/2 - hOr*scaleGlobal/2 + "px";
	}
	
	if(document.getElementById("zoomout") != null){   
		document.getElementById("zoomout").className = "zoomout_disable";
	}

	document.getElementById("demo-frame").style.width = img_act_width + "px";
	document.getElementById("main-frame").style.width = img_act_width + 50 + "px";

	new ImageRotator(document.getElementById("image-rotator"), img_path, wOr, hOr);
	
	setTimeout("set_original(false)",1200);
	
}

function zoom_out()
{
	if(scaleGlobal <= min_width){
		return;
	}
	  
	this.imageWidth = imgGlobal.width;
	this.imageHeight = imgGlobal.height;
	  	
	var prevScale = scaleGlobal;

	if(scaleGlobal > min_width){
	  	scaleGlobal = scaleGlobal - step;

	  	$("#move").draggable("enable");
		
		document.getElementById("zoomout").className="zoomout_enable";

		this.canvas.style.left = parseInt(document.getElementById('draggable').style.left) + (wOr*prevScale - wOr*scaleGlobal)/2 + "px";
		this.canvas.style.top = parseInt(document.getElementById('draggable').style.top) + (hOr*prevScale - hOr*scaleGlobal)/2 + "px";

		this.move.style.left = 0 + "px";
		this.move.style.top = 5 + "px";
	}
	
	if(scaleGlobal <= min_width){
		set_original(false); 
	}
	
	initialGlobal = true; 
	
	new ImageRotator(document.getElementById("image-rotator"),
	                   img_path, wOr, hOr);
	
} 

function zoom_in()
{
	this.imageWidth = imgGlobal.width;
	this.imageHeight = imgGlobal.height;

	var prevScale = scaleGlobal;

	if(scaleGlobal < max_width){
 		 scaleGlobal = scaleGlobal + step;

 		 $("#move").draggable("enable"); 
		 document.getElementById("zoomout").className="zoomout_enable";

		 this.canvas.style.left = parseInt(document.getElementById('draggable').style.left) + parseInt(document.getElementById('move').style.left) - (wOr*scaleGlobal - wOr*prevScale)/2 + "px";
		 this.canvas.style.top = parseInt(document.getElementById('draggable').style.top) + parseInt(document.getElementById('move').style.top) - (hOr*scaleGlobal - hOr*prevScale)/2 + "px";

		this.move.style.left = 0 + "px";
		this.move.style.top = 5 + "px";

 	}

	initialGlobal = true; 

 	new ImageRotator(document.getElementById("image-rotator"),
                   img_path, wOr, hOr);

} 

function resume_zoom()
{
	this.canvas = document.getElementsByTagName("canvas")[0];
}

function pause_zoom()
{
	this.canvas = document.getElementsByTagName("canvas")[0];
}

function set_original(zoomed)
{
	scaleGlobal = startScale;

	this.canvas = document.getElementsByTagName("canvas")[0];
	if(hOr >= wOr){
		this.canvas.style.left = -canvasLeft + img_act_width/2 - wOr*scaleGlobal/2 + "px";
		this.canvas.style.top = -canvasTop + "px";
	}
	else{
		this.canvas.style.left = -canvasLeft + "px";
		this.canvas.style.top = -canvasTop + img_act_height/2 - hOr*scaleGlobal/2 + "px";
	}
	
	this.move = document.getElementById("move");
	this.move.style.left = 0 + "px";
	this.move.style.top = 5 + "px";

    
    document.getElementById("zoomout").className="zoomout_disable";
	
	first = true;
	array = new Array();
	
    count = 0;

	rotationGlobal = 0;
	$("#move").draggable("disable"); 
	if(zoomed){
		initialGlobal = true; 
		new ImageRotator(document.getElementById("image-rotator"), img_path, wOr, hOr);	
	}

}


// ROTATOR

function sawFunc(a) {
  var PI = Math.PI;
  var PI2 = PI / 2;
  // make sure a is within 0 to PI
  a = a % PI;
  if (a < 0) {
    a += PI;
  }
  if (a < PI2) {
    return a / PI2;
  } else {
    return (PI - a) / PI2;
  }
}

function easeInEaseOut(t) {
  var t2 = t * t;
  return 3 * t2 - 2 * t * t2;
}

function ImageRotator(el, src, w, h) {

  this.element = el;
  this.toolBar = el.getElementsByTagName("div")[0];
  this.canvas = el.getElementsByTagName("canvas")[0];
    
  //var images = el.getElementsByTagName("img");
  //imgGlobal = images[images.length - 1];

  imgGlobal = document.getElementById("zimg");

  var btns = el.getElementsByTagName("button");

  this.btnCw = btns[1];
  this.btnCcw = btns[0];
  
  this.w = w;
  this.h = h;

  var self = this;
  this.btnCcw.onclick = function () {
    self.rotateCcw();
  };
  this.btnCw.onclick = function () {
    self.rotateCw();
  };
  imgGlobal.onload = function (e) {
    self.onImageLoad(e);
  };
  

  imgGlobal.onerror = function (e) {
    self.onImageError(e);
  };
  imgGlobal.onabort = function (e) {
    self.onImageAbort(e);
  };
  this.setImage(src, w, h);
  this.layout();

  var onResize = function () {
    self.layout();
  };
  var onLoad = function () {
    self.onWindowLoad();
  };
  if (window.addEventListener) {
    window.addEventListener("resize", onResize, false);
    window.addEventListener("load", onLoad, false);
  } else if (window.attachEvent) {
    window.attachEvent("onresize", onResize);
    window.attachEvent("onload", onLoad);
  }

}

ImageRotator.prototype = {
  getLoaded: function () {
    return this.imageLoaded && this.windowLoaded;
  },
  setImage: function (src, w, h) {
    this.imageLoaded = false;
    imgGlobal.src = src;
    this.imageWidth = w;
    this.imageHeight = h;

  },

  layout: function () {
    var PI2 = Math.PI / 2;
    var h = this.imageHeight;
    var w = this.imageWidth;
    
    var th = this.toolBar.offsetHeight;
    if (!ctxGlobal || ctxGlobal == null) {
      this.btnCw.disabled = true;
      this.btnCcw.disabled = true;
      this.canvas.style.display = "none";
      imgGlobal.style.display = "none";
      var ratio = Math.min(w / this.imageWidth, h / this.imageHeight, 1);
      var imgW = this.imageWidth * ratio;
      var imgH = this.imageHeight * ratio;
      var y = th + (h - imgH) / 2;
      var x = (w - imgW) / 2;
      imgGlobal.style.left = Math.round(x) + "px";
      imgGlobal.style.top = Math.round(y) + "px";
      imgGlobal.style.width = Math.round(imgW) + "px";
      imgGlobal.style.height = Math.round(imgH) + "px";
      

   } else {
	   if(initialGlobal){
		this.btnCw.disabled = this.isAnimating_;
		this.btnCcw.disabled = this.isAnimating_;
		   
		this.canvas.style.display = "block";
		imgGlobal.style.display = "none";
		
		
		this.canvas.style.width = canvasWidth + "px";
		this.canvas.width = canvasWidth;
		this.canvas.style.height = canvasHeight + "px";
		this.canvas.height = canvasHeight; 
		
		
		ctxGlobal.save();
		ctxGlobal.clearRect(0, 0, w, h);      
		
		var curLeft = Math.abs(parseInt(document.getElementById('draggable').style.left));
		var curTop = Math.abs(parseInt(document.getElementById('draggable').style.top));
		
		ctxGlobal.scale(scaleGlobal, scaleGlobal);
		
      	rw = Math.round( (wOr) /2) + canvasLeft/scaleGlobal;
      	rh = Math.round( (hOr) /2) + canvasTop/scaleGlobal;
      	
		ctxGlobal.translate(rw, rh);
		ctxGlobal.rotate(rotationGlobal);
		ctxGlobal.translate(-rw, -rh);
		
		ctxGlobal.drawImage(imgGlobal, canvasLeft/scaleGlobal, canvasTop/scaleGlobal, wOr, hOr);
		
		if(!first){
			var i;
			for(i = 0; i < count; i++) {
               	adjust(array[i][0],array[i][1]);
            }
		}

		ctxGlobal.restore();    
		initialGlobal = false;
      }
   }
  },

  rotation: 0,
  animationDuration: 500,

  rotateCcw: function () {
    if (!this.isAnimating_) {
      this.startTime_ = (new Date).valueOf();
      this.currentAngle_ = rotationGlobal;
      this.deltaAngle_ = Math.PI / 2;
      this.isAnimating_ = true;
      this.animCounter_ = 0;
      this.rotate_();
    }
  },

  rotateCw: function () {
    if (!this.isAnimating_) {
      this.startTime_ = (new Date).valueOf();
      this.currentAngle_ = rotationGlobal;
      this.deltaAngle_ = -Math.PI / 2;
      this.isAnimating_ = true;
      this.animCounter_ = 0;
      this.rotate_();
    }
  },

  rotate_: function () {
  	$("#move").draggable("enable"); 
    if (this.isAnimating_) {
      var t = easeInEaseOut(Math.min(1, (new Date - this.startTime_) /
                            this.animationDuration));
      rotationGlobal = t * this.deltaAngle_ + this.currentAngle_;
      if (t < 1) {
        var self = this;
        window.setTimeout(function () {
          self.rotate_();
        }, 10);
      } else {
        this.isAnimating_ = false;
      }
	  initialGlobal = true; 
      this.layout();
    }
  },

  onImageLoad: function (e) {
    this.imageLoaded = true;
    this.initCanvas();
  },
  

  onImageError: function (e) {
    this.imageLoaded = false;
  },
  onImageAbort: function (e) {
    this.imageLoaded = false;
  },
  onWindowLoad: function (e) {
    this.windowLoaded = true;
    this.initCanvas();
  },

  initCanvas: function () {

    if ((!ctxGlobal || ctxGlobal == null) && this.imageLoaded) {
      // IE recreates the element?
      
	  this.canvas = this.element.getElementsByTagName("canvas")[0];
	  
      ctxGlobal  = this.canvas.getContext("2d");
      

      if (!ctxGlobal || ctxGlobal == null) {
        return;
      }
      this.layout();
    }
  }
  

};

function zoomRotateControls(){
	//ROTATE BUTTONS
	document.getElementById("funcButton").appendChild(addDiv("tool-bar","tool-bar","","DIV"));
	document.getElementById("tool-bar").style.float="left";

	if(document.getElementById("bRight") == null && document.getElementById("bLeft") == null){
		document.getElementById("tool-bar").appendChild(addDiv("bRight","bRight","Rotate Right","BUTTON"));
		document.getElementById("tool-bar").appendChild(addDiv("bLeft","bLeft","Rotate Left","BUTTON"));
	}
	
	//ZOOM CONTROLS
	document.getElementById("funcButton").appendChild(addDiv("zoom","zoom","","DIV"));
	
	document.getElementById("zoom").appendChild(addDiv("zoomin","zoomin","","DIV"));
	document.getElementById("zoomin").innerHTML = '<a onclick="javascript:resume_zoom();zoom_in();" title="Zoom In" alt="Zoom In"></a>';

	document.getElementById("zoom").appendChild(addDiv("reset","reset","","DIV"));
	document.getElementById("reset").innerHTML = '<a onclick="javascript:resume_zoom();set_original(true);" title="Reset" alt="Reset"> </a>';
	
	document.getElementById("zoom").appendChild(addDiv("zoomoutDiv","zoomoutDiv","","DIV"));
	document.getElementById("zoomoutDiv").innerHTML = '<a onclick="javascript:resume_zoom();zoom_out();" title="Zoom Out" alt="Zoom Out" id="zoomout"> </a>';
	
	if(!displayRZ){
		document.getElementById("funcButton").style.display = "none";
	}
}

function brightContrastControls(){
	var controls = '';
	
	//----------- CHECKING IF THE BROWSER SUPPORTS THE 'hasCanvasImageData' FUNCTION AND ADD A CANVAS ELEMENT FOR BRIGHTNESS/CONTRAST FUNCTIONALITY ----------->
	if (Pixastic.Client.hasCanvasImageData()){
		//CONTROLS FOR SETTING UP BRIGHTNESS/CONTRAST
		document.getElementById("image_container").appendChild(addDiv("demo","demo","","DIV"));
		
		controls = '';
		controls += '<p>';
		controls += '<label for="brightness-value">Brightness:</label>';
		controls += '<input type="text" id="brightness-value" style="border:0; color:#f6931f; font-weight:bold;"/>';
		controls += '</p>';			
		controls += '<div id="brightness-slider"></div>';
		
		controls += '<p>';
		controls += '<label for="contrast-value">Contrast:</label>';
		controls += '<input type="text" id="contrast-value" style="border:0; color:#f6931f; font-weight:bold;" />';
		controls += '</p>';
		controls += '<div id="contrast-slider"></div>';
		
		document.getElementById("demo").innerHTML = controls;
		
		//BUTTON ADJUST & RESET
		document.getElementById("image_container").appendChild(addDiv("bc","bc","","DIV"));
		
		controls = '';
	
		controls += '<input type="button" onclick="push($(\'#brightness-value\').val(),$(\'#contrast-value\').val());adjust($(\'#brightness-value\').val(),$(\'#contrast-value\').val());" value="Adjust B&amp;C"/>';
		controls += '<input type="button" onclick="reset();" value="Reset"/><br/>';
	
		document.getElementById("bc").innerHTML = controls;
	}
}


function addDiv(cName,id,title,el){
	var eDiv=document.createElement(el);
	eDiv.className = cName;
	
	if(id != ""){
		eDiv.id = id;
	}
	
	if(title != ""){
		eDiv.title = title;
		eDiv.alt = title;
	}


	return eDiv;
}



