/**
 * Ajax upload
 * Project page - http://valums.com/ajax-upload/
 * Copyright (c) 2008 Andris Valums, http://valums.com
 * Licensed under the MIT license (http://valums.com/mit-license/)
 * Version 3.6 (26.06.2009)
 */

/**
 * Changes from the previous version:
 * 1. Fixed minor bug where click outside the button
 * would open the file browse window
 * 
 * For the full changelog please visit: 
 * http://valums.com/ajax-upload-changelog/
 */

(function(){
	
var d = document, w = window;

/**
 * Get element by id
 */	
function get(element){
	if (typeof element == "string")
		element = d.getElementById(element);
	return element;
}

/**
 * Attaches event to a dom element
 */
function addEvent(el, type, fn){
	if (w.addEventListener){
		el.addEventListener(type, fn, false);
	} else if (w.attachEvent){
		var f = function(){
		  fn.call(el, w.event);
		};			
		el.attachEvent('on' + type, f)
	}
}


/**
 * Creates and returns element from html chunk
 */
var toElement = function(){
	var div = d.createElement('div');
	return function(html){
		div.innerHTML = html;
		var el = div.childNodes[0];
		div.removeChild(el);
		return el;
	}
}();

function hasClass(ele,cls){
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
	if (!hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
	var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
	ele.className=ele.className.replace(reg,' ');
}



/**
 * Crossbrowser mouse coordinates
 */

/**
 * Function generates unique id
 */		
var getUID = function(){
	var id = 0;
	return function(){
		return 'ValumsAjaxUpload' + id++;
	}
}();

function fileFromPath(file){
	return file.replace(/.*(\/|\\)/, "");			
}

function getExt(file){
	return (/[.]/.exec(file)) ? /[^.]+$/.exec(file.toLowerCase()) : '';
}			

// Please use AjaxUpload , Ajax_upload will be removed in the next version
Ajax_upload = AjaxUpload = function(button, options){
	if (button.jquery){
		// jquery object was passed
		button = button[0];
	} else if (typeof button == "string" && /^#.*/.test(button)){					
		button = button.slice(1);				
	}
	button = get(button);	
	
	this._input = null;
	this._button = button;
	this._disabled = false;
	this._submitting = false;
	// Variable changes to true if the button was clicked
	// 3 seconds ago (requred to fix Safari on Mac error)
	this._justClicked = false;
	this._parentDialog = d.body;
	
	this._settings = {
		// Location of the server-side upload script
		action: '../ext/classes/fileupload/fileUploadCallBack.php?&width=270&height=270',			
		// File upload name
		name: 'userfile',
		
		theDevilsBrowser: false,
		giftBoxPage: false,
		
		left: '17px',
		
		top: '-86px',

        width: '100px',

        uploadChocolateImage_top: '-348',
	    uploadChocolateImage_left: '65',
		
		// Additional data to send
		data: {},
		// Submit file as soon as it's selected
		autoSubmit: true,
		// The type of data that you're expecting back from the server.
		// Html and xml are detected automatically.
		// Only useful when you are using json data as a response.
		// Set to "json" in that case. 
		responseType: false,
		// When user selects a file, useful with autoSubmit disabled			
		onChange: function(file, extension){},					
		// Callback to fire before file is uploaded
		// You can return false to cancel upload
		onSubmit: function(file, ext){
			
				//if (ext && new RegExp('^(' + allowed.join('|') + ')$').test(ext)){
				if (ext && /^(jpg|png|jpeg|gif|bmp)$/.test(ext)){

					if (false == this._settings.theDevilsBrowser) {				
					  $.blockUI({ 
					    message: 'Uploading photo, Please wait',
					    css: { 
	            		border: 'none', 
	            		padding: '15px', 
	            		backgroundColor: '#000', 
	            		'-webkit-border-radius': '10px', 
	            		'-moz-border-radius': '10px', 
	            		opacity: .5, 
	            		color: '#fff' 
	        		  } });
	        		}

				} else {

					$.blockUI({ 
						overlayCSS: { backgroundColor: '#43071b' },
					    message: 'We cannot accept image types of - '  + ext + '. The image type must be one of jpg,png,jpeg,gif or bmp... Click the screen to continue',
					    css: { 
		        		border: 'none', 
		        		padding: '15px', 
		        		backgroundColor: '#000', 
		        		'-webkit-border-radius': '10px', 
		        		'-moz-border-radius': '10px', 
		        		opacity: .5, 
		        		color: '#fff' 
		    		  } });
					  //setTimeout($.unblockUI, 2000);
					  $('.blockOverlay').attr('title','Click to continue').click($.unblockUI);
					
					return false;				
				}
		},
		// Fired when file upload is completed
		// WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
		onComplete: function(file, response) {
			
			// Just pause the blocking to allow time for processing the image 
			// prior to display
			//setTimeout($.unblockUI, 2000);
			$.unblockUI();
			
			if (response == '/images/gif/transparent.gif') {				
			  $.blockUI({ 
				overlayCSS: { backgroundColor: '#43071b' },
			    message: 'We could not upload your image please contact us on 0845 230 1845... Click the screen to continue',
			    css: { 
        		border: 'none', 
        		padding: '15px', 
        		backgroundColor: '#000', 
        		'-webkit-border-radius': '10px', 
        		'-moz-border-radius': '10px', 
        		opacity: .5, 
        		color: '#fff' 
    		  } });
			  //setTimeout($.unblockUI, 2000);
			  $('.blockOverlay').attr('title','Click to continue').click($.unblockUI);
    		} else {
				var productIdElement = document.getElementById('productId');
				productIdElement.value = "IM00001";
            }
				
			$('img#uploadChocolateImage').attr('src', response); 
			$('img#uploadChocolateImage').css('display', 'inline');
			
			if (this._settings.theDevilsBrowser) {
                $('img#uploadChocolateImage').css('top', this._settings.uploadChocolateImage_top); 
			    $('img#uploadChocolateImage').css('left', this._settings.uploadChocolateImage_left); 
		    }
		
		    addUploadPhotoToSlideShow(response);
			
		}
	};

	// Merge the users options with our defaults
	for (var i in options) {
		this._settings[i] = options[i];
	}
	
	// IE 6 truly is the devils browser of choice 
	// notice the obvious check for ie6 returning version 4
	var appName =navigator.appName;
	if (appName == 'Microsoft Internet Explorer') {
  		var b_version=navigator.appVersion;
		var version=parseFloat(b_version);
		if (4 == version ) {
        this._settings.theDevilsBrowser = true;
		}
	}
	//
	// Reposition input field for Safari && IE
	//
	if (this._settings.giftBoxPage) {
	    this._settings.left = '-1px';
		if ($.browser.msie) {
	       this._settings.top = '-140px';	
       	   this._settings.left = '-1px';
	   }
	   if ($.browser.safari) {
	       this._settings.top = '-162px';	
    	   this._settings.left = '-1px';
	  }
	}
	
	
	this._createInput();
	//this._rerouteClicks();
}
			
// assigning methods to our class
AjaxUpload.prototype = {
	setData : function(data){
		this._settings.data = data;
	},
	disable : function(){
		this._disabled = true;
	},
	enable : function(){
		this._disabled = false;
	},
	// removes ajaxupload
	destroy : function(){
		if(this._input){
			if(this._input.parentNode){
				this._input.parentNode.removeChild(this._input);
			}
			this._input = null;
		}
	},				
	/**
	 * Creates invisible file input above the button 
	 */
	_createInput : function(){
		var self = this;
		//var input = get(this._settings.name);
		
		var input = d.createElement("input");
		
		input.setAttribute('type', 'file');
		input.setAttribute('name', this._settings.name);
		input.setAttribute('id', this._settings.name);
		var styles = {
			'position' : 'relative'
			,'left': this._settings.left
			,'top': this._settings.top
			,'padding': 0
			,'width': this._settings.width
			,'height': '30px'
			,'fontSize': '16px'								
			,'opacity': 0
			,'cursor': 'pointer'
			//,'display' : 'none'
			,'zIndex' :  2147483582 //Max zIndex supported by Opera 9.0-9.2x 
			// Strange, I expected 2147483647
		};
		for (var i in styles){
			input.style[i] = styles[i];
		}
	
		// Make sure that element opacity exists
		// (IE uses filter instead)
		if ( ! (input.style.opacity === "0")){
			input.style.filter = "alpha(opacity=0)";
			
			//re position as this browser is truly the devils child
			// notice the obvious check for ie6 returning version 4
			var b_version=navigator.appVersion;
            var version=parseFloat(b_version);
			if (version == 4 ) {
			  input.style.width  = '135px';
			}
		}
				
		col3Element = get('uploadButtonDiv');
		col3Element.appendChild(input);					
//		this._parentDialog.appendChild(input);

		addEvent(input, 'change', function(){
			// get filename from input
			var file = fileFromPath(this.value);	
			if(self._settings.onChange.call(self, file, getExt(file)) == false ){
				return;				
			}														
			// Submit form when value is changed
			if (self._settings.autoSubmit){
				self.submit();						
			}						
		});
		
		// Fixing problem with Safari
		// The problem is that if you leave input before the file select dialog opens
		// it does not upload the file.
		// As dialog opens slowly (it is a sheet dialog which takes some time to open)
		// there is some time while you can leave the button.
		// So we should not change display to none immediately
		addEvent(input, 'click', function(){
			self.justClicked = true;
			setTimeout(function(){
				// we will wait 3 seconds for dialog to open
				self.justClicked = false;
			}, 2500);			
		});		
		
		this._input = input;
	},
	
	/**
	 * Creates iframe with unique name
	 */
	_createIframe : function(){
		// unique name
		// We cannot use getTime, because it sometimes return
		// same value in safari :(
		var id = getUID();
		
		// Remove ie6 "This page contains both secure and nonsecure items" prompt 
		// http://tinyurl.com/77w9wh
		var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
		iframe.id = id;
		iframe.style.display = 'none';
		d.body.appendChild(iframe);			
		return iframe;						
	},
	/**
	 * Upload file without refreshing the page
	 */
	submit : function(){
		var self = this, settings = this._settings;	
					
		if (this._input.value === ''){
			// there is no file
			return;
		}
										
		// get filename from input
		var file = fileFromPath(this._input.value);			

		// execute user event
		if (! (settings.onSubmit.call(this, file, getExt(file)) == false)) {
			// Create new iframe for this submission
			var iframe = this._createIframe();
			
			// Do not submit if user function returns false										
			var form = this._createForm(iframe);
			form.appendChild(this._input);
			
			form.submit();
			
			d.body.removeChild(form);				
			form = null;
			this._input = null;
			
			// create new input
			this._createInput();
			
			var toDeleteFlag = false;
			
			addEvent(iframe, 'load', function(e){
					
				if (// For Safari
					iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" ||
					// For FF, IE
					iframe.src == "javascript:'<html></html>';"){						
					
					// First time around, do not delete.
					if( toDeleteFlag ){
						// Fix busy state in FF3
						setTimeout( function() {
							d.body.removeChild(iframe);
						}, 0);
					}
					return;
				}				
				
				var doc = iframe.contentDocument ? iframe.contentDocument : frames[iframe.id].document;

				// fixing Opera 9.26
				if (doc.readyState && doc.readyState != 'complete'){
					// Opera fires load event multiple times
					// Even when the DOM is not ready yet
					// this fix should not affect other browsers
					return;
				}
				
				// fixing Opera 9.64
				if (doc.body && doc.body.innerHTML == "false"){
					// In Opera 9.64 event was fired second time
					// when body.innerHTML changed from false 
					// to server response approx. after 1 sec
					return;				
				}
				
				var response;
									
				if (doc.XMLDocument){
					// response is a xml document IE property
					response = doc.XMLDocument;
				} else if (doc.body){
					// response is html document or plain text
					response = doc.body.innerHTML;
					if (settings.responseType && settings.responseType.toLowerCase() == 'json'){
						// If the document was sent as 'application/javascript' or
						// 'text/javascript', then the browser wraps the text in a <pre>
						// tag and performs html encoding on the contents.  In this case,
						// we need to pull the original text content from the text node's
						// nodeValue property to retrieve the unmangled content.
						// Note that IE6 only understands text/html
						if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE'){
							response = doc.body.firstChild.firstChild.nodeValue;
						}
						if (response) {
							response = window["eval"]("(" + response + ")");
						} else {
							response = {};
						}
					}
				} else {
					// response is a xml document
					var response = doc;
				}
																			
				settings.onComplete.call(self, file, response);
						
				// Reload blank page, so that reloading main page
				// does not re-submit the post. Also, remember to
				// delete the frame
				toDeleteFlag = true;
				
				// Fix IE mixed content issue
				iframe.src = "javascript:'<html></html>';";		 								
			});
	
		} else {
			// clear input to allow user to select same file
			// Doesn't work in IE6
			// this._input.value = '';
			d.body.removeChild(this._input);				
			this._input = null;
			
			// create new input
			this._createInput();						
		}
	},		
	/**
	 * Creates form, that will be submitted to iframe
	 */
	_createForm : function(iframe){
		var settings = this._settings;
		
		// method, enctype must be specified here
		// because changing this attr on the fly is not allowed in IE 6/7		
		var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
		form.style.display = 'none';
		form.action = settings.action;
		form.target = iframe.name;
		d.body.appendChild(form);
		
		// Create hidden input element for each data key
		for (var prop in settings.data){
			var el = d.createElement("input");
			el.type = 'hidden';
			el.name = prop;
			el.value = settings.data[prop];
			form.appendChild(el);
		}			
		return form;
	}	
};
})();


	/***********************************************************************************************
	
	Copyright (c) 2005 - Alf Magne Kalleland post@dhtmlgoodies.com
	
	UPDATE LOG:
	
	March, 10th, 2006 : Added support for a message while large image is loading
	
	Get this and other scripts at www.dhtmlgoodies.com
	
	You can use this script freely as long as this copyright message is kept intact.
	
	***********************************************************************************************/ 
	
	var displayWaitMessage=true;	// Display a please wait message while images are loading?
	
    var SLIDE_RIGHT='SLIDE_RIGHT';
    var SLIDE_LEFT='SLIDE_LEFT';
	var NO_BUFFER='NONE';
    var BUFFER_LEFT='BUFFER_LEFT';
    var BUFFER_RIGHT='BUFFER_RIGHT';
    var ONE_IMAGE='ONE_IMAGE';
    var OPAQUE=0.5;
    var NORMAL=1;
	var IMAGE_SIZE=404;
 
    var sliding = false;	
	var activeImage = false;
	var imageGalleryLeftPos = false;
	var imageGalleryWidth = false;
	var imageGalleryObj = false;
	var smallImageGalleryObj = false;
	var maxGalleryXPos = false;
	var slideSpeed = 0;
	var imageGalleryCaptions = new Array();
	var numberPixelsToSlide = 0;
	var offsetLeftAtStartOfSlide = 0;
	var slideshowImages;
	var smallImages;
	var activeImageIdx = 0;
	var previewImage;
	
	function startSlideLeft(e)
	{
		if (goingToAllow(SLIDE_LEFT)) {
	
			sliding = true;
			
			if(document.all)e = event; 

			obj = document.getElementById('arrow_left');
		
			slideSpeedMultiply = 10 - Math.floor((e.clientX - obj.offsetLeft) / 5);
			slideSpeed = 1*slideSpeedMultiply;
			slideSpeed = Math.min(10,slideSpeed);
			if(slideSpeed<0)slideSpeed=10;
	
	    	getOffsetLeft();
	    	numberPixelsToSlide = IMAGE_SIZE*-1;
     
	    	gallerySlideLeft();
     }
	}
	

	
	// Check we need to slide, then slide, 
	
	function gallerySlideLeft() {
		
		leftPos = getNewLeftPos();
		buffer  = checkForBuffer(SLIDE_LEFT, leftPos);
		leftPos = limitSlideToBuffer(buffer, leftPos);
		
		imageGalleryObj.style.left = leftPos + 'px';
		
		if (buffer==NO_BUFFER) {
			setTimeout('gallerySlideLeft()',20);
		} else {
			tidyUpTheSlide(SLIDE_LEFT);
		}
	}
		
		
	function startSlideRight(e) {

     if (goingToAllow(SLIDE_RIGHT)) {
			
			sliding = true;
			
			if(document.all)e = event; 
		
			obj = document.getElementById('arrow_right');
		
			slideSpeedMultiply = Math.floor((e.clientX - obj.offsetLeft) / 5);
			slideSpeed = -1*slideSpeedMultiply;
			slideSpeed = Math.max(-10,slideSpeed);
		
	    	getOffsetLeft();
	    	numberPixelsToSlide = IMAGE_SIZE;

	    	if (offsetLeftAtStartOfSlide == 0) {
		  		numberPixelsToSlide = numberPixelsToSlide - 40;
	    	}

	    	gallerySlideRight();
	    }
	}
	

	function gallerySlideRight() {
		
		leftPos = getNewLeftPos();
		buffer  = checkForBuffer(SLIDE_RIGHT, leftPos);
		leftPos = limitSlideToBuffer(buffer, leftPos);
		
		imageGalleryObj.style.left = leftPos + 'px';
		
		if (buffer==NO_BUFFER) {
			setTimeout('gallerySlideRight()',20);
		} else {
			tidyUpTheSlide(SLIDE_RIGHT);
		}
		
	}
	
	function getNewLeftPos() {
		var leftPos = imageGalleryObj.offsetLeft;
	
		leftPos = leftPos/1 + slideSpeed;
		
		return leftPos;
	}
	
	function limitSlideToBuffer(buffer, leftPos) {
		
		if (buffer == BUFFER_LEFT) {
		  leftPos = maxGalleryXPos;
		}
		if (buffer == BUFFER_RIGHT) {
		  leftPos = minGalleryXPos;
		} 
		if(buffer == ONE_IMAGE) {
		  leftPos = (offsetLeftAtStartOfSlide + numberPixelsToSlide) *-1;
		}
		
		return leftPos;	
	}
	
	function checkForBuffer(slideDirection, leftPos) {
		
		var buffer = NO_BUFFER;
		
		if (leftPos<minGalleryXPos) {
		  buffer = BUFFER_RIGHT;  	
		} 
		
		if(leftPos>maxGalleryXPos) {
		  buffer = BUFFER_LEFT;
		} 
		
		if(slideDirection == SLIDE_RIGHT && ((leftPos*-1) > offsetLeftAtStartOfSlide + numberPixelsToSlide)) {
		  buffer = ONE_IMAGE;	
		}	
		
		if(slideDirection == SLIDE_LEFT && ((leftPos*-1) < offsetLeftAtStartOfSlide + numberPixelsToSlide)) {
	      buffer = ONE_IMAGE;	
		}
		
		return buffer;
	}
	
	function getOffsetLeft() {
		if (isNaN(imageGalleryObj.style.left))
			  offsetLeftAtStartOfSlide = parseInt(imageGalleryObj.style.left)*-1;
	}
	
	
	
	function mouseOverImage() {
		displayMouseOverImage(this);
	}
	
	function displayMouseOverImage(image) {
		image.getElementsByTagName('IMG')[0].src = '../images/gif/' + image.id + '_over.gif';	
	}
	
	function mouseOutImage() {
		displayMouseOutImage(this);
	}
	
	function displayMouseOutImage(image) {
		image.getElementsByTagName('IMG')[0].src = '../images/gif/' + image.id + '.gif';	
	}

	function setOpacity(activeImageIdx, opacity) {
		slideshowImages[activeImageIdx].style.filter = 'alpha(opacity=' + (opacity*100) +')';
		slideshowImages[activeImageIdx].style.opacity = opacity;	
	}

    function setSmallImageBorder(activeImageIdx, borderColour) {
		//smallImages[activeImageIdx].style.borderColor = borderColour;	
    }	
	
	function tidyUpTheSlide(jumpToTheLeft) {
		setOpacity(activeImageIdx, OPAQUE);
		setSmallImageBorder(activeImageIdx, "#FFFFFF");
		activeImageIdx=(jumpToTheLeft==SLIDE_LEFT)?activeImageIdx-1:activeImageIdx+1;  
		setOpacity(activeImageIdx, NORMAL);
		setSmallImageBorder(activeImageIdx, "#CA0F5E");
		setTextAndProductId();
		
		sliding = false;
	}
	
	function goingToAllow(slideDirection) {
		allowSlide = true;
		
		if (!sliding && 
			((slideDirection==SLIDE_LEFT && (activeImageIdx-1 < 0)) || 
			(slideDirection==SLIDE_RIGHT && activeImageIdx+1 == slideshowImages.length))) allowSlide = false;
		return allowSlide;
	}
	
	function initSlideShow()
	{
		document.getElementById('arrow_left').onmousemove = mouseOverImage;
		document.getElementById('arrow_left').onmouseout = mouseOutImage;
		document.getElementById('arrow_right').onmousemove = mouseOverImage;
		document.getElementById('arrow_right').onmouseout = mouseOutImage;
		
		imageGalleryObj = document.getElementById('theImages');
		smallImageGalleryObj = document.getElementById('theSmallImages');
		imageGalleryWidth = document.getElementById('galleryContainer').offsetWidth - 80;

		imageGalleryLeftPos = imageGalleryObj.offsetLeft;
		maxGalleryXPos      = imageGalleryObj.offsetLeft; 
		minGalleryXPos      = imageGalleryWidth - document.getElementById('slideEnd').offsetLeft + 40; 
     
		slideshowImages = imageGalleryObj.getElementsByTagName('IMG');
		//smallImages     = smallImageGalleryObj.getElementsByTagName('IMG');
		setOpacity(activeImageIdx, NORMAL);
		setSmallImageBorder(activeImageIdx, "#CA0F5E");
		
		var divs = imageGalleryObj.getElementsByTagName('DIV');
		for(var no=0;no<divs.length;no++){
			if(divs[no].className=='imageCaption')imageGalleryCaptions[imageGalleryCaptions.length] = divs[no].innerHTML;
		}
   
       	setTextAndProductId();
	
	}

	function addUploadPhotoToSlideShow(response) {
		
		insertUploadedImageIntoGallery(response);
		resetSlideShow();
		initSlideShow();
		
		return false;				
 	}


    function insertUploadedImageIntoGallery(response) {
	
		if (response != '/images/gif/transparent.gif') {
		
		  var anchor = document.createElement("a");
	   	  anchor.setAttribute('href', '#');

		  var img = document.createElement("img");
	      img.setAttribute('src', response);
	      img.setAttribute('numTextLines', '2');
	      img.setAttribute('productId', 'IM00001');

		  anchor.appendChild(img);

		  imageGalleryObj = document.getElementById('theImages');
		  var firstIMG = imageGalleryObj.getElementsByTagName('a')[0];
		  firstIMG.parentNode.insertBefore(anchor,firstIMG);		
	    }
    }
		
    function resetSlideShow() {
		setOpacity(activeImageIdx, OPAQUE);
		activeImageIdx = 0;
		imageGalleryObj.style.left = '0px';
    }


    function setTextAndProductId() {
	  
	  numOptions = slideshowImages[activeImageIdx].getAttribute("numTextLines");
	
	  hideUnWantedTextLines(numOptions);
      drawTextLines(numOptions);
	
      var productIdElement = document.getElementById('productId');
      productIdElement.value = slideshowImages[activeImageIdx].getAttribute("productId");
    
    }

	function hideUnWantedTextLines(numOptions) {
		for(var no= numOptions;no<4;no++){
  
		   var textLineId      = document.getElementById("line" + no);
		   textLineId.value = "";
		   
		   setDisplayToNone(textLineId);
		}
	}

	function drawTextLines(numOptions) {
		for(var no=0;no<numOptions;no++){

		   var textLineId      = document.getElementById("line" + no);

		   setDisplayToInline(textLineId) ;
		}
	}

	function setDisplayToNone(elementId) {
		   elementId.style.display = "none";
	}

	function setDisplayToInline(elementId) {
		   elementId.style.display = "inline";
	}


 	function initOrderPage() {
     	initSlideShow();	
	}

