/**Hyper Studio html5 player 
 * file rev. 64660
 */




/**Drawing shape on canvas, according to 
 * given points array or image;
 * Soon drawing image on canvas will be added.
 */
drawShape = Class.create({
	initialize: function(options) {
		try{
		    this.options = {
		      elementId:       	'canvas',
		      object:			{}
		    };
		    Object.extend(this.options, options || { });
		    this.elementId = this.options.elementId;
		    this.object = this.options.object;
		    this.draw();
		}
		catch(err){
			alert('drawShape: initialize error:' + console.log(err));
		}
	},
	
	elementId: 	'', 
	
	draw: function(){
		try{
			if(!Object.isUndefined(this.object.shape)&&this.object.shape.draw == true){
						var pointsString = false;
						var canVas  = $(this.elementId);
						canVas.setStyle(	"-webkit-transform:rotate(" + (this.object.rotationAngle ) + "deg);" +
											"-moz-transform:rotate(" + (this.object.rotationAngle)  + "deg);" +
											"-ms-transform:rotate(" + (this.object.rotationAngle)  + "deg);" +
											"-o-transform:rotate(" + (this.object.rotationAngle ) + "deg);");
			
						var ctx = canVas.getContext('2d');
						ctx.beginPath();  
						ctx.moveTo(0,0);  
					 
						 for(var i=1;i<this.object.shape.points.length;++i){
							 var points = this.object.shape.points[i];
						 		ctx.lineTo(points.xCoord,points.yCoord);
						 		//ctx.bezierCurveTo(points.ctrl1xCoord,points.ctrl1yCoord,points.ctrl2xCoord,points.ctrl2yCoord,points.xCoord,points.yCoord);
						 }
						 ctx.closePath();
						 ctx.fill();
						 var obj = this.object;
						 canVas.observe('mousemove',function(event){
							 
							 if(play.help.checkIfShapeClicked(canVas,event)){
								 canVas.style.cursor = play.template.cursorStyle(obj.cursor);
							 }
							 else{
								 canVas.style.cursor = cardsCollection.currentElement().cursor;
							 }
						 });
						
						 /***setOpacity(0.5)**/
						
			}
			else{
				var canVas  = $(this.elementId);
				//console.log(this.object);
				/**FIXME: "ratation"->"rotation"
				 *13.05
				 *19.05 - fixed 
				 */
				canVas.setStyle(	"-webkit-transform:rotate(" + (this.object.rotationAngle ) + "deg);" +
									"-moz-transform:rotate(" + (this.object.rotationAngle)  + "deg);" +
									"-ms-transform:rotate(" + (this.object.rotationAngle)  + "deg);" +
									"-o-transform:rotate(" + (this.object.rotationAngle ) + "deg);");
				
				var ctx = canVas.getContext('2d');
				var img = new Image();
				if(!Object.isUndefined(this.object.src))img.src = prefix + this.object.src /*+ "?" + new Date().getTime()*/;
				if(!Object.isUndefined(this.object.shapeFile))img.src = prefix + this.object.shapeFile /*+ "?" + new Date().getTime()*/;
				img.observe("load",function(){
					setTimeout(function(){
					ctx.drawImage(img,0,0);
					canVas.setOpacity(0);
					canVas.style.zIndex = 999;
					if(this.object.isVisible==0)canVas.hide();
					}.bind(this),500);
				}.bind(this));
				
				 canVas.observe('mousemove',function(event){
					 
					 if(play.help.checkIfShapeClicked(canVas,event)){
						 canVas.style.cursor = play.template.cursorStyle(this.object.cursor);
						// console.log(play.help.checkIfShapeClicked(canVas,event));
					 }
					 else{
						 canVas.style.cursor = cardsCollection.currentElement().cursor;
					 }
				 }.bind(this));
				
			}
		}
	
	catch(err){
		alert('drawShape: draw error:' + console.log(err));
	}
	}
});



/**Custom ScrollBar
 * Allows to add styled scroll bars
 * to block elevent.
 * Mousewheel support and compatibility
 * with all text actions. 
 */

var scrollBar = Class.create({
	 initialize: function(options) {
		try{
		    this.options = {
		      block:       	$('ScrollDiv'),
		      content:		$('ContentDiv'),
		      suffixId:			'qwerty'/*,
		      contentHeight: 0*/
		    };
		    
		    Object.extend(this.options, options || { });
		    //fix for hidden objects dimentions rendering
		    var tempDisp = $(this.options.block).style.display;
		    $(this.options.block).style.visibility = 'hidden';
		    $(this.options.block).style.display = 'block';
		    
			    var block = $(this.options.block);
			    var cont = $(this.options.content);
			    /**Detecting Content height*/
			    if(cont.childNodes.length>0&&!Object.isUndefined(cont.firstDescendant())&&cont.firstDescendant().tagName.toLowerCase()=="img")this.options.fullContentHeight =cont.firstDescendant().getHeight();
			    else {
			    	var tmpEl = new Element("div",{style:"visibility:hidden;"});
			    	
			    	$A(cont.childNodes).each(function(el){
			    		tmpEl.insert(el);
			    	}.bind(this));
			    	
			    	
			    	$('contPane').insert(tmpEl);
			    		this.options.fullContentHeight = tmpEl.getHeight();
			    	
			    		$A(tmpEl.childNodes).each(function(el){
				    		cont.insert(el);
				    	}.bind(this));
			    		
			    	$('contPane').removeChild(tmpEl);
			    	
			    	
			    	
			    	cont.style.height=this.options.fullContentHeight+"px";
			    	//console.log(this.options.fullContentHeight);
			    }
			    /**EOF*/
				this.options.fullBlockHeight = block.getHeight();
				contHeight = this.options.fullContentHeight - this.options.fullBlockHeight;
				this.options.contentHeight = contHeight;
				this.options.content = cont;
				cont.relativize();
				cont.style.zIndex = "auto";
				//console.log(block);
			$(this.options.block).style.display = tempDisp;
			$(this.options.block).style.visibility = 'visible';
			
			
			if(contHeight<10){
				$('handle'+this.options.suffixId).style.display = 'none';
				$('scrollHolder'+this.options.suffixId).hide();
				$('track'+this.options.suffixId).style.height = parseInt($('track'+this.options.suffixId).style.height.replace(/px$/,""))+ 30 + 'px';
				return;
				//$('track'+this.options.suffixId).parentNode.hide();	
				/*$('scrollHolder'+this.options.suffixId).hide();
				$('handle'+this.options.suffixId).style.display = 'none';
				$('track'+this.options.suffixId).hide();*/
				//cont.style.width = parseInt(cont.style.width.replace(/px$/,"")) + 15 + 'px';
				
			}
			
			this.wrap(cont,this.options.contentHeight,this);
		}
		catch(err){
			alert('scrollBar: initialize error:' + console.log(err));
		}
	},    
	
	wrap: function(el,contentHeight,scroller){
		try{	
			var makeScroll = new Control.Slider($('handle'+this.options.suffixId),$('track'+this.options.suffixId),{
								
								axis:'vertical',
								range:$R(0,contentHeight),
								//values:$R(0,contentHeight),
								onSlide: function(val,event){
									//event.stop();
									var cont = scroller.options.content;
									var newTop = parseInt(val);
									cont.setStyle({top: -newTop + 'px'});
									
									
								},
								onChange: function(val,event){
									//event.stop();
									var cont = scroller.options.content;
									var newTop = parseInt(val);
									cont.setStyle({top: -newTop + 'px'});
								}
							});
			this.makeScroll = makeScroll;
			$(this.options.block).observe('DOMMouseScroll', this.mouseWheel.bindAsEventListener(this,makeScroll));
			$(this.options.block).observe('mousewheel', this.mouseWheel.bindAsEventListener(this,makeScroll));
			/**Up Arrow*/
			$('scrollHolder'+this.options.suffixId).firstDescendant().observe('mousedown',function(event){
				Event.stop(event);
				this.clearIntervals();
				this.scrollUpInterval = setInterval(function(){
					makeScroll.setValueBy(-4);
				}.bind(this),33);
			
			}.bind(this));
			$('scrollHolder'+this.options.suffixId).firstDescendant().observe('mouseup',function(event){
				//alert('hi');
				Event.stop(event);
				this.clearIntervals();
			}.bind(this));
			/**Down Arrow*/
			$('scrollHolder'+this.options.suffixId).firstDescendant().next().observe('mousedown',function(event){
				Event.stop(event);
				this.clearIntervals();
				this.scrollDownInterval = setInterval(function(){
					makeScroll.setValueBy(4);
				}.bind(this),33);
			}.bind(this));
			$('scrollHolder'+this.options.suffixId).firstDescendant().next().observe('mouseup',function(event){
				Event.stop(event);
				this.clearIntervals();
			}.bind(this));
			
			
			$(this.options.block).observe('click', function(event){Event.stop(event);});
			
			 
		}
	catch(err){
		alert('error in scrollBar wrap:' + console.log(err));
		
	}
	},
	
	clearIntervals: function(){
		clearInterval(this.scrollUpInterval);
		clearInterval(this.scrollDownInterval);
	},
	
	mouseWheel: function(event,scroll){
		var move = 0;
		if(!event) event = window.event;
		if(event.wheelDelta) move = event.wheelDelta / 120;
		else if(event.detail) move = -event.detail / 3;
		move = Math.round(move);
		if(move) scroll.setValueBy(-move);
		Event.stop(event);
	},
	
	scroll: function(direction, delta){
		this.makeScroll.setValue(delta);
	},
	
	scrollBy: function(direction, delta){
		if(delta == 1) delta = 1.5;
		this.makeScroll.setValueBy(delta);
	},
	
	scroller: function(direction,delta){
		var d = parseFloat(delta);
		var currentTop = + $(this.options.content).style.top.substr(0,$(this.options.content).style.top.length - 2);
		if(this.options.fullContentHeight > ((- currentTop) + this.options.fullBlockHeight))
			$(this.options.content).style.top = (currentTop - d) + 'px';
	}
	
	
	
});

/**TODO:
 * x-global objects preloader, disabling events for preload delay
 * x-move prototype and script.aculo.us to lib folder
 * x-templates-based common strings
 * x-We need to add DOM id for each element in collection
 * x-stack for card object effects,
 * -internal action priority
 * x-load,
 * x-unload card actions,
 * x-fix goto from panel,
 * x-add sound support,
 * -add effects:
 * 		x-no transition
 * 		x-fade
 * 		x-push up
 * 		x-push Left
 * 		x-push right
 * 		x-push down
 * 		x-slide down
 * 		x-slide left
 * 		x-slide remove down
 * 		x-slide remove left
 * 		x-slide remove right
 * 		x-slide remove up
 * 		x-slide up
 * 		x-slide right
 * 		x-zoom
 * 		x-swirl
 * 		x-iris rectangle;
 * 		x-iris circle
 * 		x-barnDoor
 * 		x-barnClose
 * 		x-wipe up
 * 		x-wipe down
 * 		x-wipe left
 * 		x-wipe right
 * *x-add	video support,
 * x-add text support with custom scroller,
 * *x-add buttons support
 * x-ghost writer
 * x-show/hide object
 * x-open a web page
 * x-print card
 * x-automatic timer
 * x-scrollCard
 * -refactor code	
 * */
var appState = Class.create({
	itemAnimationCycles: 0
});

/**Helper object
 * Contains some helpful 
 * functions.
 */
var helper = Class.create({
	getCountTypeActions: function(actions,type){
		var i = 0;
		actions.each(function(action){
			if(action.priority == type) i++;
		});
		
		return i;
	},
	
	getCountObjectActions: function(actions){
		return actions.length;
	},
	
	checkForGroupObjectData: function(newCard,play,j){
		return (!Object.isUndefined(newCard.objects[j].isGroupObject)&&!Object.isUndefined(play.groupObjectsData)&&!Object.isUndefined(play.groupObjectsData[newCard.objects[j].id]));
	},
			
	checkIfShapeClicked: function(element,e){
	/*	function inspect( obj ) {
		    if (typeof obj === "undefined") {
		        return "undefined";
		    }
		    var _props = [];

		      for ( var i in obj ) {
		          _props.push( i + " : " + obj[i] ); 
		      }
		      console.log( " {" + _props.join( "," ) + "} ");
		  
		}*/
				var canVas = element;
				var ctx = canVas.getContext('2d');
			 	var x;
			    var y;
			    x = e.pointerX();
				y = e.pointerY();
				
				
				
				if((!x||!y)&&!Object.isUndefined(e.touches[0])){
					x = e.touches[0].clientX;
					y = e.touches[0].clientY;
					if(!x) return false;
				}
				var diffX = 0;
			    if($('scrollThumbs')){
			    	if($('scrollThumbs').style.display == 'block') diffX =  $('scrollThumbs').getWidth();
			    }
			    
			    var offset = canVas.cumulativeOffset();
			    x -= parseInt(offset.left);
			    y -= parseInt(offset.top);
			    
			    try { 
			    	 var imgData = ctx.getImageData(x,y,1,1).data;  
			      } catch (err) { 
			    	  // if(!Object.isUndefined(this.ask)) return;
			    	  try{
				    	  netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
				    	 
				    	  this.ask = 1;
				    	 // return;
				    	  var imgData = ctx.getImageData(x,y,1,1).data;
			    	  }
			    	  catch(e){
			    		  
			    	  }
			      } 		
			    
			    if(typeof(imgData)!='undefined'&&imgData[0]==0&&imgData[1]==0&&imgData[2]==0&&imgData[3]==0){
			    	
			    	return false;
			    }
			    else{
			    	return true;
			    }
			 
			},
			getKeyCode: function(key){
				switch(key){
					
					case "0": 	
						return 48;
					break;
					
					case "1": 	
						return 49;
					break;
					
					case "2": 	
						return 50;
					break;
					
					case "3": 	
						return 51;
					break;
					
					case "4": 	
						return 52;
					break;
					
					case "5": 	
						return 53;
					break;
					
					case "6": 	
						return 54;
					break;
					
					case "7": 	
						return 55;
					break;
					
					case "8": 	
						return 56;
					break;
					
					case "9": 	
						return 57;
					break;
					
					case "a": 	
						return 65;
					break;
					
					case "b": 	
						return 66;
					break;
					
					case "c": 	
						return 67;
					break;
					
					case "d": 	
						return 68;
					break;
					
					case "e": 	
						return 69;
					break;
					
					case "f": 	
						return 70;
					break;
					
					case "g": 	
						return 71;
					break;
					
					case "h": 	
						return 72;
					break;
					
					case "i": 	
						return 73;
					break;
					
					case "j": 	
						return 74;
					break;
					
					case "k": 	
						return 75;
					break;
					
					case "l": 	
						return 76;
					break;
					
					case "m": 	
						return 77;
					break;
					
					case "n": 	
						return 78;
					break;
					
					case "o": 	
						return 79;
					break;
					
					case "p": 	
						return 80;
					break;
					
					case "q": 	
						return 81;
					break;
					
					case "r": 	
						return 82;
					break;
					
					case "s": 	
						return 83;
					break;
					
					case "t": 	
						return 84;
					break;
					
					case "u": 	
						return 85;
					break;
					
					case "v": 	
						return 86;
					break;
					
					case "w": 	
						return 87;
					break;
					
					case "x": 	
						return 88;
					break;
					
					case "y": 	
						return 89;
					break;
					
					case "z": 	
						return 90;
					break;
					
					/*f-keys*/
					case "f1": 	
						return  112;
					break;
					
					case "f2": 	
						return  113;
					break;
					
					case "f3": 	
						return  114;
					break;
						
					case "f4": 	
						return  115;
					break;
						
					case "f5": 	
						return  116;
					break;
						
					case "f6": 	
						return  117;
					break;
						
					case "f7": 	
						return  118;
					break;
						
					case "f8 ": 	
						return 	119;
					break;
						
					case "f9": 	
						return  120;
					break;
						
					case "f10": 	
						return  121;
					break;
						 
					case "f11": 	
						return  122;
					break;
					
					case "f12": 	
						return  123;
					break;
					
					/**others*
					 */
					case "enter":
						return 13;
					break;
					
					case "escape":
						return 27;
					break;
					
					case "space":
						return 32;
					break;
					
					case "del":
						return 8;
					break;
				}
			},
			
			fixEditableText: function(el){
				//console.log(el.id);
				el.observe("keyup",function(e){
					try{
						
					if (Prototype.Browser.WebKit&&(!el.lastChild || el.lastChild.nodeName.toLowerCase() != "br")) {
						
						el.appendChild(document.createElement("br"));
					}
					/*var sanitazed = el.innerHTML.replace(/<div[^<]*?>/g, '').replace(/<\/div[^<]*?>/g, '<br>');
					el.update(sanitazed);*/
					}catch(err){
						console.log(err);
					}
				}.bind(this));
			    
			    
				el.observe("keypress", function(e){
					var charCode = (e.which) ? e.which : e.keyCode;
					
					if (charCode == 13) {
			    	 if (window.getSelection&&!Prototype.Browser.Gecko) {
			        	e.preventDefault();
			        	var selection = window.getSelection();
			        	var range = selection.getRangeAt(0);
			        	var br = document.createElement("br");
			        	range.deleteContents();
			        	range.insertNode(br);
			        	range.setStartAfter(br);
			        	range.setEndAfter(br);
			        	range.collapse(false);
			        	selection.removeAllRanges();
			        	selection.addRange(range);
			        	return false;
			        }
			      }
			    });

			},
			
			stopAllMovies: function(){
				$$("video").each(function(el){
					//alert(el);
					el.pause();});
			},
			stopAllSounds: function(){
				$$("audio").each(function(el){el.pause();});
			}
	});




/**Main player object
 * Contains logic, oservers and 
 * card injection realization
 */
var playerObj = Class.create({
	 
	initialize: function(options) {
		try{
			this.help = new helper;
		    this.options = {
		      onInitGo:       	'firstCard',
		      onInitCardNumber:	'0',
		      onInitTransition:	'HSFadeTransition',
		      globalData:{},
		      test:false
		    };
		    Object.extend(this.options, options || { });
		    
		   
		    this.globalData = this.options.globalData;
		    	var wrapperWidth = (parseInt(this.globalData.stacks[0].xSize)>180)?parseInt(this.globalData.stacks[0].xSize)+10:180;
		    	var contPaneOffset = (parseInt(this.globalData.stacks[0].xSize)>180)? "": ("left:50%;margin-left:-" + (this.globalData.stacks[0].xSize/2 ) + "px;");
		    	
		    	$('mainbar').morph("top:"+(parseInt(this.globalData.stacks[0].ySize)+35)+"px;");
		    	if(contPaneOffset!="")$('contPane').setStyle("left:50%;margin-left:-400px;");
		    	$('contPane').morph("width:" + this.globalData.stacks[0].xSize + "px;height:" + this.globalData.stacks[0].ySize + "px;"+contPaneOffset);
		    	$('wrapperTable').morph("width:" + wrapperWidth + "px;height:" + (parseInt(this.globalData.stacks[0].ySize) + 80) + "px;");
		    	
		    		
		    //console.log(typeof(this.supportsVideo()));
		    this.flashVideo = !this.supportsVideo();
		    this.draggableObjects = [];
		    this.clearChangeFlag = false;
		    this.timerTimeouts = [];
		    this.preloadElements = Array();
		    
		    ["click","mousedown","mouseup"].each(function(el){
		    	this.appendMouseMethods(el);
		    }.bind(this));
		    
		    this.appendEventsSimulation();
		    	
		    setTimeout(function(){$('contPane').style.background ="#fff";},300);
		    this.animateGoto(this.options.onInitGo, this.options.onInitCardNumber, this.options.onInitTransition);
		   
		}
		catch(err){
			alert('playerObj: initialize error:' + console.log(err));
		}
	},

	unloadAlerted: 0,
	
	where: '',
	
	no: '',
	
	effect: '',
	
	animateFrom: '',
	
	textObjects:{},
	
	flashVideo: false,
	
	saveGroupObjectsState: function(){
		var thisCard = cardsCollection.currentElement();
		this.groupObjectsData = {};
		thisCard.objects.each(function(el){
			if(!Object.isUndefined(el.isGroupObject)&&el.isGroupObject==1&&Object.isElement($(this.template.newCardElementId(cardsCollection.currentElement().id,el.id)))){
				//console.log(this.template.newCardElementId(cardsCollection.currentElement().id,el.id));
				var element = $(this.template.newCardElementId(cardsCollection.currentElement().id,el.id));
				var tempData = {
						width:		element.getStyle('width'),
						height:		element.getStyle('height'),
						top:		element.getStyle('top'),
						left:		element.getStyle('left'),
						position:	element.getStyle('position'),
						zIndex:		element.getStyle('z-index')
						
						
					};
				this.groupObjectsData[el.id] = tempData;
			}
		}.bind(this));
		
		
		
	},
	
	appendMouseMethods:function(evtName){
		try{
		HTMLElement.prototype[evtName] = function() {
	    	var evt = this.ownerDocument.createEvent('MouseEvents');
	    	evt.initMouseEvent(evtName, false, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
	    	this.dispatchEvent(evt);
	    };
		}
		catch(err){
			console.log(err);
		}
	},
	
	appendEventsSimulation: function(){
		Element.prototype.triggerEvent = function(eventName)
		{
		    if (document.createEvent)
		    {
		    	var evt = document.createEvent('HTMLEvents');
		    	evt.initEvent(eventName, true, true);

		    	return this.dispatchEvent(evt);
		    }

		    if (this.fireEvent)
		    	return this.fireEvent('on' + eventName);
		};

	},
	
	supportsVideo: function() {
		try{
		  if(!!document.createElement('video').canPlayType == false||(document.createElement('video').canPlayType('video/quicktime') ==''&&document.createElement('video').canPlayType('video/mp4') =='')) return false;
		  else return true;
		}
		catch(err){
			alert(err);
			return false;
		}
	},
	
	supportsAudio: function() {
		try{
			
		  if(!!document.createElement('audio').canPlayType == false||(document.createElement('audio').canPlayType('audio/aac') ==''&&document.createElement('audio').canPlayType('audio/mp4') =='')){
			 // alert('hi');	
			  return false;
		  }
		  else return true;
		}
		catch(err){
			return false;
		}
	},
	
	changeStack: function(link,effect,homeStackAction){
		tempPrefix = prefix;
		prefix = "data/stackData/";
		if(this.options.test){
			console.log('hi');
			console.log(prefix +link);
		}
		var req = new Ajax.Request(prefix + link,
			{ onSuccess:function(responce){
				try{
						var data = responce.responseText.evalJSON(false);
					
			if(this.options.test)	console.log(data);
			var jsonData = new stackJsonParser();
			var stackCount = jsonData.getStackCount(data);
			var stack = jsonData.getStack(data, 0); 
			var cards = stack.cards;
			
			document.title = stack.name;
			var lastVisitedCard = cardsCollection.currentElement().id;
			cardsCollection = new stackObj();
			if(this.options.test)console.log(cardsCollection);
			
			for(var i=0;i<cards.length;i++){
				cardsCollection.push(cards[i]);
			}
			//cardsCollection.els.empty();
			this.unloadAlerted = 0;
			
			
			}
			catch(err){
				console.log(err);
			}
			
			try{
			prefix = "data/stackData/" + link.replace(/stack.json$/,"");
			
			/**if we have visited home stack and the action is to go back to home stack,
			 * we should set the card pointer to those card, that was last seen in the home stack
			 */
			if(homeStackAction){
				(Object.isUndefined(this.globalData.HSCardNumber))?this.globalData.HSCardNumber = prevLastVisitedStackCard = lastVisitedCard : prevLastVisitedStackCard =  this.globalData.HSCardNumber;
				this.globalData = data;
				this.globalData.HSCardNumber = lastVisitedCard;
				cardsCollection.setPointer(prevLastVisitedStackCard);
				/**FIXING CARD DIMENSIONS*/
				$('contPane').morph("width:" + this.globalData.stacks[0].xSize + "px;height:" + this.globalData.stacks[0].ySize + "px;");
		    	$('wrapperTable').morph("width:" + (parseInt(this.globalData.stacks[0].xSize) + 10) + "px;height:" + (parseInt(this.globalData.stacks[0].ySize) + 80) + "px;");
		    	$('mainbar').morph("top:"+(parseInt(this.globalData.stacks[0].ySize)+35)+"px;");
		    	/**EOF*/
			}
			else {
				(Object.isUndefined(this.globalData.HSCardNumber))?this.globalData.HSCardNumber = prevLastVisitedStackCard = lastVisitedCard : prevLastVisitedStackCard =  this.globalData.HSCardNumber;
				this.globalData = data;
				this.globalData.HSCardNumber = lastVisitedCard;
				cardsCollection.setPointer(0);
				/**FIXING CARD DIMENSIONS*/
				$('contPane').morph("width:" + this.globalData.stacks[0].xSize + "px;height:" + this.globalData.stacks[0].ySize + "px;");
		    	$('wrapperTable').morph("width:" + (parseInt(this.globalData.stacks[0].xSize) + 10) + "px;height:" + (parseInt(this.globalData.stacks[0].ySize) + 80) + "px;");
		    	$('mainbar').morph("top:"+(parseInt(this.globalData.stacks[0].ySize)+35)+"px;");
		    	/**EOF*/
			}
			
			var animateFrom = $($('contPane').down());
			
			var newCard = cardsCollection.currentElement();
			var animateTo = this.injectCard(newCard,effect);
			
		 	setTimeout(function(){this.playEffect(animateFrom,animateTo,"HSFadeTransition");}.bind(this),500);
			}
			catch(err){
					console.log(err);
				}
			
			
		}.bind(this),
		
		onException: function(){
			//alert('hi');
			prefix = tempPrefix;
			new messageCreate({image:"./data/engine/templates/img/info.png",text:"Stack not found!",caption:"OK"});
		},
		
		onFailure: function(){
			prefix = tempPrefix;
			new messageCreate({image:"./data/engine/templates/img/info.png",text:"Stack not found!",caption:"OK"});
			
		}.bind(this)
		});
		
	},
	
	extendObject: function(){
		if(!document.createElement('object').play){
			Element.addMethods("OBJECT",{
				play: function(element){
				   var element = $(element);
				   Try.these(function(){element.playMedia();}.bind(this))||false;
				   
				},
				
				pause: function(element){
					var element = $(element);
				    element.pauseMedia();
				},
				
				rotate: function(element,degree){
					var element = $(element);
					var elPosition = $(element).getDimensions();
					var height = elPosition.height;
					var width = elPosition.width;
					var radius = Math.sqrt((height*height + width*width));
					var top = parseInt($(element).style.top.replace(/px$/,""));
					var left = parseInt($(element).style.left.replace(/px$/,""));
					var flVideoTopPos = Math.abs( (width * Math.sin((degree +90) * Math.PI/180)) - (width -height));
					var flVideoLeftPos = Math.abs(height * Math.cos((degree) * Math.PI/180) - height);
					var newTop = top - width * Math.sin((degree + 90) * Math.PI/180) + height;
					var newLeft = left - (flVideoLeftPos + Math.sqrt(flVideoLeftPos) +5);
					
					/*console.log(radius + ":radius");
						console.log(top + ":top");
						console.log(newTop + ":newTop");
						console.log("flVideoLeftPos:" + (flVideoLeftPos ));
						console.log(100 * width/radius);
						console.log("delta:" + flVideoTopPos);
						console.log("deg:" + degree);
					*/
					
					$(element).setStyle("top:" + (newTop) + "px;left:"+newLeft+"px;height:" + radius + "px; width:" + radius + "px;");
					//$(element).height = radius;
					//Math.pow();
					//$(element).setStyle("left:100px;top:200px;height:" + radius + "px; width:" + radius + "px;");
					//element.TSetProperty('/',0,0);
					element.TSetProperty('/',2, 100 * width/radius);
					element.TSetProperty('/',3, 100 * width/radius);
					//setTimeout(function(){
						element.TSetProperty('/',0, 0);
						element.TSetProperty('/',1, flVideoTopPos - 50);
					//}.bind(this),100);
					
					element.TSetProperty('/', 10, degree);
					
					
					
					
				}//,
				
			//	getDuration: function(element){
			//		var element = $(element);
			//		return element.duration();
			//	},
				
			//	duration: this.getDuration()
				
				
				});
		}
	},
	
	rotateVideo: function(id, degree){
		document.observe('Card'+cardsCollection.currentElement().id +':loaded' ,function(e){
			setTimeout(function(){
				$(id).rotate(degree);
			}.bind(this),50);
		}.bind(this));
	
	},
	
	makeVideoDraggable:function(id){
		document.observe('Card'+cardsCollection.currentElement().id +':loaded' ,function(e){
			setTimeout(function(){
				this.draggableObjects.push(new Draggable(id,{
					ghosting: false,
					starteffect:false,
					endeffect:false,
					onEnd:function(eventName,draggable,event){
						draggable.element().click();
					}
				}));
				$(id).setAttribute("passmeevt","true");
			}.bind(this),250);
		}.bind(this));
	},
	
	setVideoAutoplay: function(id){
		document.observe('Card'+cardsCollection.currentElement().id +':loaded' ,function(e){
		setTimeout(function(){
				$(id).setAttribute("playonstart","true");
				$(id).play();
			}.bind(this),250);
		}.bind(this));
	},
	
	setVideoDontAutoplay: function(id){
		document.observe('Card'+cardsCollection.currentElement().id +':loaded' ,function(e){
		setTimeout(function(){
				$(id).pause();
			}.bind(this),250);
		}.bind(this));
	},
	
	createVideoElement: function(newCard,j){
		
		
		var videoId = this.template.newCardElementId(newCard.id,newCard.objects[j].id);
		
		/**PNG MAP VIDEO SIMULATIONS*/
		if(newCard.objects[j].isPNGMap==1) return new createElements.pngMapVideo({id:videoId,object:newCard.objects[j]}).element;
		/**EOF*/
		if(this.supportsVideo()){ 
			var videoElement = new Element(newCard.objects[j].type ,
											{src:prefix + newCard.objects[j].src ,
											id: videoId,
											/*controls: true,*/
											autoplay:false,
											data:prefix+newCard.objects[j].src,
											style:	'position:absolute;background:none;z-index:'+newCard.objects[j].order+';display:none;top:' + 
													newCard.objects[j].yCoord + 'px;left:'+newCard.objects[j].xCoord+'px;height:'+
													newCard.objects[j].ySize+'px;width:' + newCard.objects[j].xSize + 'px;'});
											videoElement.insert("<source src='"+prefix+newCard.objects[j].src+"' type='video/quicktime'>");
											videoElement.insert('your browser doesn\'t support this video encoding');
		//	this.setVideoAutoplay(videoId);
		}
		else{
			
			this.extendObject();
			var videoElement = '<object type="application/x-shockwave-flash" data="data/engine/templates/flash/mediaplayer.swf" id="'+videoId+'"'+ 
								'style="position:absolute;background:none;z-index:'+newCard.objects[j].order+';';
			videoElement +=(newCard.objects[j].isVisible==1)?"display:block;":"display:none;";
							
			videoElement +=		'top:' + newCard.objects[j].yCoord + 'px;left:'+newCard.objects[j].xCoord+'px;height:'+
								newCard.objects[j].ySize+'px;width:' + newCard.objects[j].xSize + 'px;">'+
								'<param name="allowNetworking" value="all">'+
								'<param name="allowFullScreen" value="true">'+
								'<param name="allowScriptAccess" value="always">'+
								'<param name="wmode" value="transparent">'+
								'<param name="movie" value="data/engine/templates/flash/mediaplayer.swf">'+
								'<param name="flashvars" value="src=../../../../'+prefix + newCard.objects[j].src+'&id='+videoId+'&controls=flase&autoplay=false">'+
								'</object>';
			//this.setVideoDontAutoplay(videoId);
					
		}
		
		return videoElement;
				
	},
	
	
	
	enableTracking: function(el){
		mouseMoveTrack = this.mouseMoveTracking.bindAsEventListener(this);
		
		el.observe("mousedown",function(event){
			if(event.stopped) return;
			this.trackingButton = el;		
			if(this.help.checkIfShapeClicked(el,event)){ 
				el.setOpacity(0.3);
				document.observe("mousemove",mouseMoveTrack);
			}
		}.bind(this));
		document.observe("mouseup",function(event){
			if(el.getOpacity()!=0)el.setOpacity(0);
			document.stopObserving("mousemove",mouseMoveTrack);
		}.bind(this));
		
		/**IOS**/
		el.observe("touchstart",function(event){
			this.trackingButton = el;	
			
			if(this.help.checkIfShapeClicked(el,event)){ 
				el.setOpacity(0.3);
				document.observe("touchmove",mouseMoveTrack);
			}
		}.bind(this));
		document.observe("touchend",function(event){
			if(el.getOpacity()!=0)el.setOpacity(0);
			document.stopObserving("touchmove",mouseMoveTrack);
		}.bind(this));
		/**EOF IOS*/
		
		
		
	},
	
	mouseMoveTracking: function(e){
	//	e.preventDefault();
		//setTimeout(function(){
			var el = this.trackingButton;
			if(e.element() != el){
				if(el.getOpacity()!=0)el.setOpacity(0);
				return;
			}
			else if(this.help.checkIfShapeClicked(el,e)){
				el.setOpacity(0.3);
			}
			else{
				if(el.getOpacity()!=0)el.setOpacity(0);
			}
		//}.bind(this),33);
	},
	
	forwardMouseEvent: function(el){
		if(Object.isFunction(el.observe)){
			el.observe("mousedown",function(event){
				var el =event.element();
				var position = [event.pointerX(),event.pointerY()];
				this.makeFMECalculations(el,position,event);
			}.bind(this));
		}
	},
	
	makeFMECalculations:function(el,position,event){
		//console.log(el.tagName);
		
		el.hide();
		var underlayingElement = document.elementFromPoint(position[0],position[1]);
		//alert('hi');
		el.show();
		
		if(underlayingElement==null)return;
		if(underlayingElement.id == $('contPane').firstDescendant().childElements()[1].id || underlayingElement.id =='contPane') return;
		else if($(underlayingElement).readAttribute("passmeevt")=="true"){
				event.stop();
				event.preventDefault();
				event.stopPropagation();
				underlayingElement.fire("e:mousedown",{position:position});
				return;
		}
		else {
			el.hide();
			this.makeFMECalculations(underlayingElement, position, event);
			el.show();
		}
	},
	
	template:{
		cardId: function(cId){
			return new Template('Card#{cardId}').evaluate({cardId:cId});
		},
		
		newCardElementId:  function(cId,eId){
			return new Template('Card#{cardId}cardObjects#{objectId}').evaluate({cardId:cId,objectId:eId});
		},
		
		cardActionEventDone:  function(eId,priority){
			return new Template('card#{elementId}action#{actionPriority}:done').evaluate({elementId:eId,actionPriority:priority});
		},
		
		cardLoadActionEventDone:  function(eId,priority){
			return new Template('card#{elementId}loadAction#{actionPriority}:done').evaluate({elementId:eId,actionPriority:priority});
		},
		
		cardUnloadActionEventDone:  function(eId,priority){
			return new Template('card#{elementId}unloadAction#{actionPriority}:done').evaluate({elementId:eId,actionPriority:priority});
		},
		
		cardElementEventDone:  function(cId,eId,priority){
			return new Template('Card#{cardId}cardObjects#{elementId}action#{actionPriority}:done').evaluate({cardId:cId,elementId:eId,actionPriority:priority});
		},
		
		eventDone:  function(eId,priority){
			return new Template('#{cardId}#{actionPriority}:done').evaluate({elementId:eId,actionPriority:priority});
		},
		
		cursorStyle: function(val){
			return val.replace("url(","url(" + prefix);
		}
	},
	
	playEffect: function(animateFrom,animateTo,effect){
		try{
			/**if isset animateTo, we'll play 
			 * goto effect
			 * -only for supported effects
			 */
			if(animateTo){
				//setTimeout(function(){
				var durr = 1.5;
				new transitions({
					currentElement:animateFrom,
					nextElement:animateTo,
					effect:effect,
					durr:durr
					});
				//}.bind(this),500);
				return true;
				
			}
			
			else{
				
			}
		}	
		catch(err){
			alert('player.js (playEffect) error: ' + err);
		}
	},
	
	finalUnload: function(event){
		try{
			if(!event.stopped){
				event.stop();
				document.stopObserving();
				this.draggableObjects.each(function(el){
					el.destroy();
				});
				/**Group objects handling*/
				if(!this.clearChangeFlag){
					this.saveGroupObjectsState();
					this.clearChangeFlag = false;
				}
				else {
					this.groupObjectsData = {};
					this.clearChangeFlag = false;
				}
				/**EOF group objects handling*/
				/**AutomaticTimer clearing*/
				this.timerTimeouts.each(function(el){
					clearTimeout(el);
				});
				
				var animateFrom = $('Card' + cardsCollection.getPointer());
				var animateTo = this.prepareGoto(this.where,this.no,this.effect);
				if(!animateTo) return;
			 	this.playEffect(animateFrom,animateTo,this.effect);
			 	this.unloadAlerted = 0;
			}
		}
		catch(err){
			console.log(err);
		}
	},
	
	animateGoto: function(where,no,effect){
		try{
			
			this.where = where;
			this.no = no;
			this.effect = effect;
			if($('showedImg')){ 
					document.stopObserving();
					var animateFrom = $('showedImg');
					var animateTo = this.prepareGoto(where,no,effect);
				 	this.playEffect(animateFrom,animateTo,effect);
				}
			else {
					var animateFrom = $('Card' + cardsCollection.getPointer());
					if(this.where=='HSGoToHomeStackAction') return;
					else if(this.where=='HSGoToSpecificCardAction'){
						var animateTo = this.prepareGoto(this.where,this.no,this.effect,true);
						if(!animateTo) return;
						//var animateTo = this.prepareGoto(this.where,this.no,this.effect);
					}
					if(this.unloadAlerted == 0){
						this.unloadAlerted = 1;
						/**!!! We need to give some time for scripts to handle this right*/
						setTimeout(function(){document.fire('Card' + cardsCollection.getPointer() +':unloaded');},200);
					}
			
			}
			
			document.observe('Card' + cardsCollection.getPointer() +':canUnload',this.finalUnload.bindAsEventListener(this));
			
		}
		catch(err){
			alert('aimateGoto error'+ console.log(err));
		}
	},
	
	prepareGoto: function(where,no,effect,test){
		try{
			//alert(test);
			if(Object.isUndefined(test)) test = false;
			//if(no == 'HSNextCardAction') where = "HSNextCardAction";
			//else if(no == "HSPrevCardAction") where = "HSPrevCardAction";
			if(effect == 'LString') effect = "HSFadeTransition";
			if(this.options.test)console.log("where" + where + ",no"+no+", effect" + effect);
			switch(where){
				case 'firstCard':
					cardsCollection.setPointer(0);
					var newCard = cardsCollection.currentElement();
					return this.injectCard(newCard,effect);
					break;
				//anotherCard
				case 'HSGoToSpecificCardAction':
					if(!Object.isUndefined(cardsCollection.elements()[no])){
						if(!test){
						//	console.log('testThis');
						//	console.log(cardsCollection.elements()[no]);
							cardsCollection.setPointer(no);
							var newCard = cardsCollection.currentElement();
							return this.injectCard(newCard,effect);
						}
						else {
							//alert("testing:true");
							return true;
						}
					}
					else{
						new messageCreate({image:"./data/engine/templates/img/info.png",text:"<b>Cannot go to specified card</b><br/>This card has been deleted.",caption:"OK"});
						return false;
					}
					break;
				//nextCard
				case 'HSNextCardAction':
					
					var newCard = cardsCollection.nextElement();
					return this.injectCard(newCard,effect);
					break;
				
				case 'HSPreviousCardAction':
					var newCard = cardsCollection.prevElement();
					return this.injectCard(newCard,effect);
				break;
					
				case 'HSBackAction':
					cardsCollection.setPointer(cardsCollection.lastSeenElement().id);
					var newCard = cardsCollection.currentElement();
					return this.injectCard(newCard,effect);
				break;
					
				case 'HSOpenStackAction':
					this.changeStack(no,effect,false);
					
				break;
				
				case 'HSGoToHomeStackAction':
					this.changeStack('stack.json',effect,true);
				break;
				
				default:
					
					throw new exception('hello');
				break;
			}
		}
		catch(err){
			alert('prepareGoto error:' + console.log(err));
		}
	},
	
	injectCard: function(newCard,effect){
		try{
		/**construct new object**/
			if(this.options.test)console.log(this.globalData);
			//alert(this.globalData.stacks[0].xSize);
				//$('contPane').style.cursor = newCard.cursor;
				
				var cardObject = new Element('div',{id:	'Card'+newCard.id,
													style: 'display:block;width:'+this.globalData.stacks[0].xSize+'px;height:'+this.globalData.stacks[0].ySize+'px;float:left;overflow:hidden !important;cursor:'+newCard.cursor.replace(/Resources/,prefix + "Resources")});
				
				var cardPreview = new Element('img',{src: prefix +"Previews/"+ newCard.images.preview,
													id: 'Preview'+newCard.id,
													style: 'display:none;height:'+this.globalData.stacks[0].ySize+'px;cursor:'+cardObject.style.cursor});
				
				var cardObjectImage = new Element('img',{src: prefix +"Previews/"+ newCard.images.background,
														id: 'Img'+newCard.id,
														style: 'height:'+this.globalData.stacks[0].ySize+'px;cursor:'+cardObject.style.cursor});	
				cardObjectImage.observe("mousedown",function(e){
					e.preventDefault();
				});
				cardObject.insert(cardPreview).insert(cardObjectImage);
				this.textObjects = {};
				var textId = [];
				var suffixId =[];
				for(var j=0;j<newCard.objects.length;j++){
					var cardElements = [];
					
					//fix for numeric id's
					//newCard.objects[j].id = j;
					/**for different objects we'll use different constructors*/
					
					switch (newCard.objects[j].type){
						case "video":
							cardElements[j] = this.createVideoElement(newCard,j);
							if(Object.isFunction(cardElements[j].setStyle)){
								cardElements[j].setStyle(	"-webkit-transform:rotate(" + (newCard.objects[j].rotationAngle ) + "deg);" +
															"-moz-transform:rotate(" + (newCard.objects[j].rotationAngle ) + "deg);" +
															"-ms-transform:rotate(" + (newCard.objects[j].rotationAngle ) + "deg);" +
															"-o-transform:rotate(" + (newCard.objects[j].rotationAngle ) + "deg);");
							}
							else if(newCard.objects[j].rotationAngle > 0){
								//alert("hi");
								this.rotateVideo(this.template.newCardElementId(newCard.id,newCard.objects[j].id), (newCard.objects[j].rotationAngle));
							}
							
							if(this.help.checkForGroupObjectData(newCard,this,j)){
								var style = "top:"  + this.groupObjectsData[newCard.objects[j].id].top + ";" +
											"left:" + this.groupObjectsData[newCard.objects[j].id].left + ";" +
											"height:"+ this.groupObjectsData[newCard.objects[j].id].height + ";" +
											"width:" + this.groupObjectsData[newCard.objects[j].id].width + ";" + 
											"z-index:" + this.groupObjectsData[newCard.objects[j].id].zIndex + ";";
								cardElements[j].setStyle(style);
							}
							
							cardObject.insert(cardElements[j]);
							
							if(newCard.objects[j].isDropOffOnly == 1){
								Droppables.add(cardElements[j], { 
									  onDrop: function(draggable,droppable,event) { 
									    setTimeout(function(){$(droppable).fire("element:dropOff");}.bind(this),33);
									  }.bind(this) 
									}); 
							}
							
							if(newCard.objects[j].isDraggable == 1){
								this.makeVideoDraggable(this.template.newCardElementId(newCard.id,newCard.objects[j].id));
							}
							/*else{
								this.forwardMouseEvent(cardElements[j]);
							}*/
						
							if(newCard.objects[j].isVisible != 0 && !Object.isUndefined(cardElements[j].style) ||(!Object.isUndefined(newCard.objects[j].isShowFirstFrame)&&newCard.objects[j].isShowFirstFrame==1)) {
								//alert('hi');
								cardElements[j].style.display ="block";
							}
							if(newCard.objects[j].isVisible==0 && !Object.isUndefined(cardElements[j].style) ||(!Object.isUndefined(newCard.objects[j].isShowFirstFrame)&&newCard.objects[j].isShowFirstFrame==0)) {
								//alert('hi2');
								cardElements[j].style.display ="none";
							}
							cardElements[j].isVisible = newCard.objects[j].isVisible;
							/**TODO: handle this*/
							cardElements[j].paused = true;
							if(!Object.isUndefined(newCard.objects[j].stopOtherMovies)){
								cardElements[j].stopOtherMovies = newCard.objects[j].stopOtherMovies;
								cardElements[j].stopOtherSounds =  newCard.objects[j].stopOtherSounds;
							}
							if(newCard.objects[j].movieClicking==1){
								if(newCard.objects[j].isPNGMap==0&&Object.isFunction(cardElements[j].observe)){
									["touchstart","mousedown"].each(function(el){
										cardElements[j].observe(el,function(e){
											
											if(e.element().paused){
												
											/*e.element().load();*/	
												if(!Object.isUndefined(e.element().stopOtherMovies)){
													
													if(e.element().stopOtherMovies==1) this.help.stopAllMovies();
													if(e.element().stopOtherSounds==1) this.help.stopAllSounds();
												}
												e.element().play();
											}
											else{
												e.element().pause();
											}
											
										}.bind(this));
									}.bind(this));
								}
							}
							//cardElements[j].onclick="event.stop();return false;";//TODO:change this with something acceptable
						break;
						
						case "imageSequence":
						//	console.log(newCard.objects[j]);
							//return;
							cardElements[j] = new Element("img" ,
									{src:prefix+newCard.objects[j].frames[0].src ,
								id: this.template.newCardElementId(newCard.id,newCard.objects[j].id),
								style:'position:absolute;z-index:5;display:none;top:' + newCard.objects[j].yCoord + 'px;left:'+newCard.objects[j].xCoord+'px;height:'+newCard.objects[j].ySize+'px;width:' + newCard.objects[j].xSize + 'px;'});
								cardObject.insert(cardElements[j]);
								if(newCard.objects[j].isVisible != 0)cardElements[j].show();
								var itemObjectActions = new Action.playSequenceAnimation({
									imgElement: cardElements[j], 
									imagesTemplate: newCard.objects[j].frames,
									info: newCard.objects[j],
									fps: newCard.objects[j].fps/*,
									imagesCount: newCard.objects[j].imagesCount*/
									});
								cardObject.insert(cardElements[j]);
								
								Object.extend(cardElements[j], itemObjectActions);
								if(newCard.objects[j].isVisible == 0) cardElements[j].hide();
							//	console.log(cardElements[j]);
								
						break;
						
						case "sound":
							cardElements[j] = createElements.sound(newCard,j,this);
							cardObject.insert(cardElements[j]);
						break;
						
						
						case "img":
							cardElements[j] = new Element(newCard.objects[j].type ,
									{src:prefix+newCard.objects[j].src ,
									id: this.template.newCardElementId(newCard.id,j),
									style:'position:absolute;z-index:' + newCard.objects[j].order + ';display:none;top:' + newCard.objects[j].yCoord + 'px;left:'+newCard.objects[j].xCoord+'px;height:'+newCard.objects[j].ySize+'px;width:' + newCard.objects[j].xSize + 'px;'});

							if(newCard.objects[j].rotationAngle != 0){
								cardElements[j].setStyle(	"-webkit-transform:rotate(" + (newCard.objects[j].rotationAngle ) + "deg);" +
														"-moz-transform:rotate(" + (newCard.objects[j].rotationAngle ) + "deg);" +
														"-ms-transform:rotate(" + (newCard.objects[j].rotationAngle ) + "deg);" +
														"-o-transform:rotate(" + (newCard.objects[j].rotationAngle ) + "deg);");
							}
							
							cardObject.insert(cardElements[j]);	
							if(newCard.objects[j].isVisible != 0) cardElements[j].appear();
							
						break;
						
						case "image":
							
							cardElements[j] = createElements.image(newCard,j,this);
							cardObject.insert(cardElements[j]);
							if(newCard.objects[j].isVisible != 0) cardElements[j].show();
							
							
							if(newCard.objects[j].isDropOffOnly == 1){
								Droppables.add(cardElements[j], { 
									  onDrop: function(draggable,droppable,event) { 
									    setTimeout(function(){$(droppable).fire("element:dropOff");}.bind(this),33);
									  }.bind(this) 
									}); 
							}
							
							if(newCard.objects[j].isDraggable == 1){
								cardElements[j].observe("click", function(e){
									e.stop();
									e.stopPropagation();
									e.preventDefault();
									
								});
								
								this.draggableObjects.push(new Draggable(cardElements[j],{
									ghosting: false,
									starteffect:false,
									endeffect:false,
									zindex:cardElements[j].style.zIndex,
									quiet:true,
									
									onEnd:function(draggable,event){
										event.stop();
										event.preventDefault();
										event.stopPropagation();
										event.element().setAttribute("isfromaction", 1);
										event.element().click();
										event.element().setAttribute("isfromaction", 0);
									}
								}));
								cardElements[j].setAttribute("passmeevt","true");
								
							}
							else{
								this.forwardMouseEvent(cardElements[j]);
								//cardElements[j].setAttribute("passmeevt","true");
							}
							
							//this.createShapeOnload(elementId,object);
							
							
							/*if(!Object.isUndefined(newCard.objects[j].shapeFile)){
								this.enableTracking(cardElements[j]);
							}*/
							
						break;
						
						
						case "button":
							cardElements[j] = createElements.button(newCard,j,this);
									cardObject.insert(cardElements[j]);
								/*	if(newCard.objects[j].isVisible==1)*/cardElements[j].show();
									var object = newCard.objects[j];
									var elementId  = cardElements[j].id;
									
									if(newCard.objects[j].isDropOffOnly == 1){
										Droppables.add(cardElements[j], { 
											  onDrop: function(draggable,droppable,event) { 
											    setTimeout(function(){$(droppable).fire("element:dropOff");}.bind(this),33);
											  }.bind(this) 
											}); 
									}
									
									if(newCard.objects[j].isDraggable == 1){
										cardElements[j].observe("click", function(e){
											e.stop();
											e.stopPropagation();
											e.preventDefault();
											
										});
										this.draggableObjects.push(new Draggable(cardElements[j],{
											ghosting: false,
											starteffect:false,
											endeffect:false,
											zindex:cardElements[j].style.zIndex,
											onEnd:function(eventName,draggable,event){
											draggable.element().setAttribute("isfromaction", 1);
											draggable.element().click();
											draggable.element().setAttribute("isfromaction", 0);
												
											}
										}));
									}
									else{
										this.forwardMouseEvent(cardElements[j]);
									}
									
									this.createShapeOnload(elementId,object);
									
									//alert(newCard.objects[j].shapeFile);
									if(!Object.isUndefined(newCard.objects[j].shapeFile)&&newCard.objects[j].isHighlight==1&&newCard.objects[j].isDropOffOnly!=1&&newCard.objects[j].isNoClick!=1){
										//alert('hi');
										console.log(cardElements[j]);
										this.enableTracking(cardElements[j]);
									}
									
									if(newCard.objects[j].src != ''){
										var butImage = createElements.src(newCard,j,this);
										cardObject.insert(butImage);
									}
									
							if(newCard.objects[j].isVisible != 1) {
								cardElements[j].style.display = "none";
							}
							//cardElements[j].observe("touchstart",function(e){e.preventDefault();})
						break;
						
						
						case "text":
							cardElements[j] = createElements.text(newCard,j,this);
							
							//if(newCard.objects[j].drawScrollBar=='1'){		
										
										/**var track = new Element("div",{id:'track'+newCard.objects[j].id,'class':'track',style:'width:15px;height:'+ (newCard.objects[j].ySize - 32) +'px;'});
										if(!Object.isUndefined(newCard.objects[j].drawTrack)&&newCard.objects[j].drawTrack==0) track.setStyle("display:none;");
										var wrap = new Element("div",{style:'float:right;width:15px;height:'+ newCard.objects[j].ySize+'px;'});
										var handle = new Element('div',{id:'handle'+newCard.objects[j].id,'class':'handle',style:"height:37px;"});
										track.insert(handle);
										var holder = new Element('div',{id:'scrollHolder' + newCard.objects[j].id,style:'top:'+parseFloat(newCard.objects[j].ySize-74)+'px;'});
										holder.insert(new Element('img',{src:'./data/engine/templates/img/scrollUpArrow.png',style:"margin-top:-5px;"}));
										holder.insert(new Element('img',{src:'./data/engine/templates/img/scrollDownArrow.png'}));
										wrap.insert(track);
										wrap.insert(holder);
										if(newCard.objects[j].textType =='rotatable')wrap.style.display='none';
										cardElements[j].insert(wrap);*/
										var textPane = new Element("div",{id:cardElements[j].id + 'textPane',
																			style:"z-index:auto;text-align:left;"/*height:" + cardElements[j].style.height +";"/*(parseFloat(cardElements[j].style.width.gsub('px;','')) -5 - parseInt(track.style.width.gsub('px;','')))+"px;"*/});
										
										//
										
										if(!Object.isUndefined(newCard.objects[j].textImage)&&newCard.objects[j].textImage!=''){
											cardObject.insert(cardElements[j].insert(textPane.update(new Element("img",{src:prefix + newCard.objects[j].textImage}))));
											textPane.setStyle("overflow:visible;");
										}
										else cardObject.insert(cardElements[j].insert(textPane.update(newCard.objects[j].text)));
										
										if(!Object.isUndefined(newCard.objects[j].background))	cardElements[j].setStyle("background:url("+ prefix + newCard.objects[j].background+") repeat-y;");
										//if(newCard.objects[j].text=='')newCard.objects[j].text = '<div style="display:inline-block;height:inherit;"></div>';
										
										if(newCard.objects[j].isVisible != 0) cardElements[j].show();
										
										
										
										textId.push(cardElements[j].id);
										suffixId.push(newCard.objects[j].id); 
										
										if(newCard.objects[j].isReadOnly=='0'){
											/*cardElements[j].setStyle(	"-moz-user-select: text;" +
																		"-moz-user-modify: read-write;"+
																		"-webkit-user-select: text;"+
																		"-khtml-user-select: text;"+
																		"-o-user-select: text;");*/
											
											textPane.setAttribute("contenteditable","true");
											textPane.setAttribute("spellcheck","false");
											textPane.setStyle(	"-moz-user-select: text;-moz-user-modify: read-write;" +
																"-o-user-select: text;-khtml-user-select: text;" +
																"-webkit-user-select: text; cursor: text;" +
																"height:"+newCard.objects[j].ySize+"px;line-height:inherit;");
											
											
											this.help.fixEditableText(textPane);
										}
										
										
											var textAlignProperty = "";
											
											textPane.childElements().each(function(el){
												
												if(el.tagName.toLowerCase()=="br") return;

	                                               if(textAlignProperty!=el.style.textAlign&&!(el.childNodes.length==1&&(el.childElements()[0])&&el.childElements()[0].tagName.toLowerCase()=="br")){
	                                            	   
	                                                   if(!Object.isUndefined(el.previous())&&el.previous().tagName.toLowerCase()=="br"){
	                                                       el.parentNode.removeChild(el.previous());
	                                                       return;
	                                                   }

	                                                   el.style.width = "100%";
	                                                   textAlignProperty = el.style.textAlign;
	                                                   el.parentNode.insertBefore(new Element("div",{style:"height:0px;overflow:hidden;line-height:1px;width:100%;"}),el);
	                                                   el.parentNode.style.textAlign = el.style.textAlign;

	                                               }
	                                            else if(el.childNodes.length==1&&(el.childNodes[0].tagName)&&el.childNodes[0].tagName.toLowerCase()=="br"){
	                                            	textAlignProperty = "";
	                                            	el.style.width = "";
													var prev = $(el).previous();
													if(!Object.isUndefined(prev)&&!Object.isUndefined(prev.style))prev.style.width = "100%";
													if(!Object.isUndefined(prev)&&prev.childNodes.length>1)el.style.width = "100%";
													
	                                            }
												else{
													
													el.style.width = "";
													var prev = $(el).previous();
													if(!Object.isUndefined(prev)&&!Object.isUndefined(prev.style))prev.style.width = "";
												}
	                                               
												if(el.style.textAlign=="justify"){
													el.style.wordSpacing = "3px";
													el.style.whiteSpace = "pre-line";
												}
												
												if(newCard.objects[j].isReadOnly=='0'){
												el.setStyle(	
																"-moz-user-select: text; " +
																"-moz-user-modify: read-write;" +
																"-webkit-user-select: text;"+
																"-khtml-user-select: text;"+
																"-o-user-select: text;" +
																"cursor:text;");
												}
											}.bind(this));
											
										
										if(newCard.objects[j].drawScrollBar!='1'){
											//textPane.setStyle("overflow:hidden;");
											cardElements[j].setStyle("overflow-y:hidden;");
										}
										/**
										document.observe('Card'+cardsCollection.currentElement().id +':loaded',function(event){
											
											for(var q=0;q<textId.length;q++){
												var suff = suffixId[q];
												var text = textId[q];
												if(Object.isUndefined(this.textObjects[text])) this.textObjects[text] = new scrollBar({block: text,content:text + 'textPane',suffixId:suff});
											}
										}.bind(this));*/
										
							/**}
							else{
								if(newCard.objects[j].textType=='rotatable') cardObject.insert(cardElements[j].update(new Element("img",{src:prefix + newCard.objects[j].textImage })/*newCard.objects[j].text));
								else cardObject.insert(cardElements[j].update(newCard.objects[j].text));
								if(!Object.isUndefined(newCard.objects[j].background))	cardElements[j].style.background ="url("+ prefix + newCard.objects[j].background+") no-repeat";*/
								if(parseInt(newCard.objects[j].rotationAngle) != 0){
									cardElements[j].setStyle(		"-webkit-transform:rotate(" + (newCard.objects[j].rotationAngle ) + "deg);" +
																"-moz-transform:rotate(" + (newCard.objects[j].rotationAngle)  + "deg);" +
																"-ms-transform:rotate(" + (newCard.objects[j].rotationAngle)  + "deg);" +
																"-o-transform:rotate(" + (newCard.objects[j].rotationAngle ) + "deg);");
								}
								
								if(newCard.objects[j].isDropOffOnly == 1){
									Droppables.add(cardElements[j], { 
										  onDrop: function(draggable,droppable,event) { 
										    setTimeout(function(){$(droppable).fire("element:dropOff");}.bind(this),33);
										  }.bind(this) 
										}); 
								}
								
								if(newCard.objects[j].isDraggable == 1){
									this.draggableObjects.push(new Draggable(cardElements[j],{
										ghosting: false,
										starteffect:false,
										endeffect:false,
										zindex:cardElements[j].style.zIndex,
										onEnd:function(eventName,draggable,event){
											draggable.element().setAttribute("isfromaction", 1);
											draggable.element().click();
											draggable.element().setAttribute("isfromaction", 0);
											
										}
									}));
								}
								
								
								if(newCard.objects[j].isVisible != 0) cardElements[j].show();
								cardElements[j].observe("click",function(e){
									e.stopPropagation();
								});
								
								
								
							//}
						break;
						
						
						
						
						
						default:
							new Action.playShowMessage({text:"undefined object type '" + newCard.objects[j].type + "'"});
						break;
							
					}
					
					if(Object.isFunction(cardElements[j].observe)&&cardElements[j].tagName != "video"){
						/** Images preloading*/
						
						if(newCard.objects[j].type == "image") {
							this.preloadElements.push(cardElements[j].src);
						}
						/**eof*/
						if(newCard.objects[j].type != "text"&&newCard.objects[j].type != "video") {
							
						cardElements[j].observe("mousedown",function(e){
							e.preventDefault();
							e.stop();
							return false;
						});
						}
					}
				}
				
				new imgPreloader({images:this.preloadElements});
				
				$('contPane').insert(cardObject);
				
				
			/**EOF**/
				/**Adding event listeners*/
				//if(!Object.isUndefined(newCard.actions)){
				document.observe('Card'+cardsCollection.currentElement().id +':loaded' ,function(e){
					/**MOBILE SAFARI hack, activating sound and movie objects*/
					if(Prototype.Browser.MobileSafari&&($$('video').length>0||$$('audio').length>0)){
						
						new mobileMessageCreate({text:"Would you like to play movies and sounds in the stack?",
												captionOk:"OK",
												captionCancel:"Cancel",
												okCallback:function(){
													tempDisp = [];
													$$('video').each(function(el){
															el.load();
															el.style.visibility = 'hidden';
															tempDisp.push(el.style.display);
															el.show();
															el.play();
															
														});
													
													$$('video').each(function(el,index){
														el.load();
														el.style.display = tempDisp[index];
														el.style.visibility = 'visible';
													});
													
													$$('audio').each(function(el){
														el.show();
														el.play();
														el.pause();
														el.hide();
													});
													
													
													
													this.eventObserver(newCard,cardObject,'click');
													
														for(var i=0; i<newCard.objects.length; i++){
															if(newCard.objects[i].actions){
																if(newCard.objects[i].isDropOffOnly !=1)this.elementEventObserver(newCard.objects[i],$('Card'+newCard.id + 'cardObjects'+newCard.objects[i].id),'click');
																else this.elementEventObserver(newCard.objects[i],$('Card'+newCard.id + 'cardObjects'+newCard.objects[i].id),'element:dropOff');
																if (newCard.objects[i].isNoClick ==1) this.elementEventObserver(newCard.objects[i],$('Card'+newCard.id + 'cardObjects'+newCard.objects[i].id),'mouseover');
															}
														}
														
													setTimeout(function(){$$('video').each(function(el,index){
														
														if(!Object.isUndefined(el.playonstart)&&el.playonstart == "playonstart"){
															el.load();
															el.play();
															return;
														}
														
													});},500);
												}.bind(this),
												
												cancelCallback:function(){
													
													
													
													this.eventObserver(newCard,cardObject,'click');
													
														for(var i=0; i<newCard.objects.length; i++){
															if(newCard.objects[i].actions){
																if(newCard.objects[i].isDropOffOnly !=1)this.elementEventObserver(newCard.objects[i],$('Card'+newCard.id + 'cardObjects'+newCard.objects[i].id),'click');
																else this.elementEventObserver(newCard.objects[i],$('Card'+newCard.id + 'cardObjects'+newCard.objects[i].id),'element:dropOff');
																if (newCard.objects[i].isNoClick ==1) this.elementEventObserver(newCard.objects[i],$('Card'+newCard.id + 'cardObjects'+newCard.objects[i].id),'mouseover');
															}
														}
														
													setTimeout(function(){$$('video').each(function(el,index){
														
														if(!Object.isUndefined(el.playonstart)&&el.playonstart == "playonstart"){
															el.load();
															el.play();
															return;
														}
														
													});},500);
												}.bind(this)
						});
					}
					/**EOF MOBILE SAFARI hack*/
					
					else{
						this.eventObserver(newCard,cardObject,'click');
					//this.eventObserver(newCard,cardObject,'arrive');
					//this.eventObserver(newCard,cardObject,'leave');
				//}
						for(var i=0; i<newCard.objects.length; i++){
							if(newCard.objects[i].actions){
								if(newCard.objects[i].isDropOffOnly !=1)this.elementEventObserver(newCard.objects[i],$('Card'+newCard.id + 'cardObjects'+newCard.objects[i].id),'click');
								else this.elementEventObserver(newCard.objects[i],$('Card'+newCard.id + 'cardObjects'+newCard.objects[i].id),'element:dropOff');
								if (newCard.objects[i].isNoClick ==1) this.elementEventObserver(newCard.objects[i],$('Card'+newCard.id + 'cardObjects'+newCard.objects[i].id),'mouseover');
							}
						}
				}
				
				/**EOF*/
				}.bind(this));
				return cardObject;
		
		
		}
		catch(err){
			if(this.options.test) alert('injectCard error:' + err + console.log(err));
			else new messageCreate({image:"./data/engine/templates/img/info.png",text:"Resource not found, please ensure all resources were exported!",caption:"OK"});
			//new Action.playShowMessage({text:"Resource not found, please ensure all resources were exported."}); 
		}
	},
	
	
	createShapeOnload: function(elementId,object){
		document.observe('Card'+cardsCollection.currentElement().id +':loaded',function(){	
			new drawShape({elementId: elementId, object:object});
		}.bind(this));
	},
	
	eventObserver: function(newCard,cardObject,event){
		try{

			
			var cardClk = new Array();
			var cardLoad = new Array();
			var cardUnload = new Array();
			if(newCard.actions){
				if(newCard.actions.click!=''){
					$H(newCard.actions.click).toArray().each(function(actions){
						actions.each(function(act){
							if(Object.isString(act)){
								typE = act;
							}
							
							else if(!Object.isFunction(act)&&!Object.isString(act)){
									act.creator = "cardClick";
									cardClk.push(act);
							}
							/*else{
									if(Object.isArray(act)){
								act.each(function(a){
									//here we can put types
									a.type = typE;
									a.creator="cardClick";
									cardClk.push(a);
								});
									}
									else{
										cardClk.push(act);
									}
								
							}*/
						});
					});
				}
				
				
				if(newCard.actions.arrive!=''){
					$H(newCard.actions.arrive).toArray().each(function(actions){
						actions.each(function(act){
							if(Object.isString(act)){
								typE = act;
							}
							else if(!Object.isFunction(act)&&!Object.isString(act)){
									act.creator = "cardLoad";
									cardLoad.push(act);
							}
						});
					});
				}
			if(newCard.actions.leave!=''){
				$H(newCard.actions.leave).toArray().each(function(actions){
					actions.each(function(act){
						if(Object.isString(act)){
							typE = act;
							
						}
						else if(!Object.isFunction(act)&&!Object.isString(act)){
								act.creator = "cardUnload";
								cardUnload.push(act);
						}
						
					});
				});
			}
			}
			
/***********************************/
			if(this.options.test){
				console.log('click:');
				console.log(cardClk);
				console.log('load:');
				console.log(cardLoad);
				console.log('unload:');
				console.log(cardUnload);
			}
/***********************************/
			/**click events*/
				var isFired = 0;
				cardObject.observe('click',function(e){
					//alert('hi');
					/*if(isFired != 1)*/ this.setEffectsChain(cardsCollection.currentElement(),cardClk);
					isFired = 1;
				}.bind(this));
				var isFiredF = 0;
				cardObject.observe(cardObject.id+':clickFake',function(e){
					//alert('hello');
					/*if(isFiredF != 1)*/ this.setEffectsChain(cardsCollection.currentElement(),cardClk);
					isFiredF = 1;
				}.bind(this));
			/**eof*/
			/**Load events*/
				//console.log("observing");
				//console.log('Card'+cardsCollection.currentElement().id +':loaded');
				//document.observe('Card'+cardsCollection.currentElement().id +':loaded' ,function(e){
					setTimeout(function(){ this.setLoadEffectsChain(cardsCollection.currentElement(),cardLoad);}.bind(this),500);
				//}.bind(this));
			/**eof*/
			/**unLoad events*/
				
				document.observe('Card'+cardsCollection.currentElement().id +':unloaded' ,function(e){
						 this.setUnloadEffectsChain(cardsCollection.currentElement(),cardUnload);
					}.bind(this));
			/**EOF*/
		}
		
		catch(err){
			alert('player.js (eventObserver) error:' + console.log(err));
		}
	},
	
	
	elementEventObserver: function(newCard,elementObject,event){
		
		try{
			
			var elClk = new Array();

			$H(newCard.actions.click).toArray().each(function(actions){
				
				actions.each(function(act){
					
					if(Object.isString(act)){
						typE = act;
					}
					else if(!Object.isFunction(act)&&!Object.isString(act)){
							if(elementObject != null) act.creator = elementObject.id;
							else act.creator ="unknown";
							 elClk.push(act);
					}
				});
			});
			
			//console.log(elementObject);
			isFiredElement= ({});
			var elementKey = elementObject.id;
			isFiredElement[elementKey] = 0;
			
			if(!Object.isUndefined(newCard.timer)){
				
				this.setElementsEffectsChain(elementObject,elClk,newCard);
			}
			
			elementObject.observe(event,function(event){
			if(event.element().tagName.toLowerCase() !='video')event.stop();
				if(this.options.test)console.log('element clicked:'+ elementObject.id);
				/*if(isFiredElement.elementKey != 1)*/ 
				/**Checking if the opacity object was clicked on non-opacity area*/
				if(elementObject.tagName.toLowerCase()=='canvas'){
					if(newCard.isDropOffOnly == 1||elementObject.readAttribute("isfromaction") == 1||this.help.checkIfShapeClicked(elementObject,event)){
						if(this.options.test) console.log(newCard);	
						if(this.options.test) console.log(elClk);
						this.setElementsEffectsChain(elementObject,elClk);
					}
					else{
						//console.log(elementObject.up());
						elementObject.up().fire(elementObject.up().id+':clickFake');
						//console.log($('Card'+cardsCollection.currentElement().id));
					}
					
				}
				else{
					this.setElementsEffectsChain(elementObject,elClk);
				}
				isFiredElement.elementKey = 1;
				}.bind(this));
			
			
		
		}
		
		catch(err){
			alert('player.js (injectCard) error:' + err + console.log(err));
		}
	},
	
	/**
	 * This function detects which action should be played
	 * and delegates playing that action to proper object
	 */
	bfx: function(event,objA,actions,element,eventType){
		try{
			//console.log('hi');
			//console.log(objA);
			var gt = 'goto';
			
		/*	
			if(objA.stopAll){
				new Action.playSound({
					info:	objA
				});
				
			}
			*/
			if(!Object.isUndefined(objA.effect)){
				
				if(Object.isUndefined(objA.cardNum))objA.cardNum =0;
				if(objA.type=="HSOpenStackAction"){
					try{
						var req = new Ajax.Request(prefix + objA[gt],
								{ 
							
							
								onCreate:		function(transport){
									try{
										
										setTimeout(function(){
											//console.log(transport.transport.responseText);
											//console.log(req);
											if(transport.transport.responseText=='') {
												
												new messageCreate({image:"./data/engine/templates/img/info.png",text:"Stack not found!",caption:"OK"});
											}
											else {
												//alert(transport.transport.responseText);
												this.animateGoto(objA.type,objA[gt],objA.effect);
											}
											transport.transport.abort();
										}.bind(this),500);
													
									}
									catch(err){
										console.log(err);
									}
								}.bind(this),
								onError:function(transport){
									transport.transport.abort();
									new messageCreate({image:"./data/engine/templates/img/info.png",text:"Stack not found!",caption:"OK"});
								}.bind(this)
		
							/*	onFailure:function(transport){
									alert('hi');
									transport.transport.abort();
									new messageCreate({image:"./data/engine/templates/img/info.png",text:"Stack not found!",caption:"OK"});
								}.bind(this),*/
		
								/*onException:function(transport){
									//alert('hi');
									transport.transport.abort();
									new messageCreate({image:"./data/engine/templates/img/info.png",text:"Stack not found!",caption:"OK"});
								}.bind(this),
								
								onSuccess:function(responce){
									this.animateGoto(objA.type,objA[gt],objA.effect);
								}.bind(this)*/
								
						});
					}
					catch(err){
						console.log(err);
					}
				}
				else {	
						if(!objA[gt]) objA[gt] = objA.type;
						this.animateGoto(objA.type,objA[gt],objA.effect);
					}
				//delete objA[gt];
				
			}
			
			switch(objA.type){
			
				case 'HSAnimationAction':
					if(objA.points){
						if(eventType)
							var type = eventType;
						else
							var type='other';
						
						if (objA.template) var sequence = true;
						else var sequence = false; 
						//console.log(sequence);
						var len = play.help.getCountTypeActions(actions,objA.priority);
						new Action.playItemAnimation({
							item:   	objA,
					    	length:		len,
					    	cardId:		element.id,
					    	type:	type,
					    	sequence: sequence
					    });
					}
				break;
				
				case 'HSHideShowAction':
					
					objA.objects.each(function(obj){
						obj.creator = objA.creator;
						obj.priority = objA.priority;
						if(play.options.test) console.log(Object.isElement($('Card'+cardsCollection.currentElement().id + 'cardObjects' + obj.object)));
						if(Object.isElement($('Card'+cardsCollection.currentElement().id + 'cardObjects' + obj.object))){
							//if($('Card'+cardsCollection.currentElement().id + 'cardObjects' + obj.object).getOpacity() != "0") {
								switch (obj.mode){
								case "1":	
									if(play.options.test)console.log("showing"+obj.object);
									new Action.playShow({
										item:	obj
									});
								break;
								
								case "2":
									if(play.options.test)console.log("hiding"+obj.object);
									new Action.playHide({
										item:	obj
									});
								break;
								
								case "3":
									//toggle
									if(play.options.test){
											console.log("switching");
											console.log(obj); 
									}
										if($('Card'+cardsCollection.currentElement().id + 'cardObjects' + obj.object).style.display != "none"){
											
											new Action.playHide({
												item:	obj
											});
										}
										else{
											new Action.playShow({
												item:	obj
											});
										}
								break;
								}
						}
					});
					//console.log("firing: " + play.template.cardElementEventDone(cardsCollection.currentElement().id,objA.creator,(objA.priority+1)));
					//document.fire(play.template.cardElementEventDone(cardsCollection.currentElement().id,objA.creator,(objA.priority+1)));
				break;
				
				case 'HSMoveToFrontAction':
					new Action.playMoveToFront({
						item:	objA
					});
				break;
				
				case 'HSButtonListerAction':
					//console.log(objA);
					new Action.playButtonLister({
						item:	objA
					});
				break;
				
				case 'HSButtonScannerAction':
					new Action.playButtonScanner({
						item:	objA
					});
				break;
				
				case 'HSButtonStepperAction':
					new Action.playButtonStepper({
						item:	objA
					});
				break;
				
				case 'HSPlayMovieAction':
					new Action.playVideo({
						item:	objA
					});
				break;
				
				case 'HSPlaySoundAction':
					new Action.playSound({
						info:	objA
					});
					
				break;
				
				case 'HSOpenWebPageAction':
					/**opening window*/
					new Action.playWebPage({//TODO: need to fix in safari
						item:	objA
					});
				break;
				
				case 'HSSendMailAction':
					/**sending email*/
					new Action.playSendMail({//TODO: need to fix in safari
						item:	objA
					});
				break;
				
				case 'HSPrintCardAction':
					/**printing card*/
					new Action.playPrintCard();
				break;
				
				case 'HSGhostWriterAction':
					new Action.playGhostWriter({
						item:	'Card'+ cardsCollection.currentElement().id + 'cardObjects'+ objA.object,
						data:	objA.data,
						speed:	objA.speed//,
						//className:
					});
				break;
				
				case 'movieController':
					new Action.playMovieController({
						item:	objA
					});
				break;
				
				case 'textMover':
					new Action.playTextMover({
						source:	'Card'+ cardsCollection.currentElement().id + 'cardObjects'+ objA.subject,
						item:	'Card'+ cardsCollection.currentElement().id + 'cardObjects'+ objA.object,
						mode: 	'copy',
						insertPos: 'end'//{[replace,end]}
					});
				break;
				
				case 'HSAutoScrollAction':
					if(play.options.test)console.log(objA);
					new Action.playRollCredits({
						item:   	'Card'+ cardsCollection.currentElement().id + 'cardObjects'+ objA.object,
				    	mode:		objA.scrollingSetup,//pixels
				    	nOfPixels:	objA.pixelsAmount,
				    	nOfSteps:	objA.numberOfSteps,
				    	speed:		objA.stepsPerSecond,
				    	direction:	objA.scrollDirection
						
					});
				break;
				
			/*	case 'HSPlaySoundAction':
					if(play.options.test)console.log(objA);
					/*new Action.playRollCredits({
						item:   	'Card'+ cardsCollection.currentElement().id + 'cardObjects'+ objA.object,
				    	mode:		objA.mode,//pixels
				    	nOfPixels:	objA.nOfPixels,
				    	nOfSteps:	objA.nOfSteps,
				    	speed:		objA.speed,
				    	direction:	objA.direction
						
					});
				break;*/
				
				case 'HSShowMessageAction':
					if(play.options.test)console.log(objA);
					new Action.playShowMessage({
						source:	'Card'+ cardsCollection.currentElement().id + 'cardObjects'+ objA.subject,
				    	icon:	objA.src,
				    	text:	objA.messageString,
				    	buttonText:		objA.buttonTitle
						
					});
				break;
				//scrollCard
				case 'HSScrollCardAction':
					if(play.options.test)console.log(objA);
					new Action.playScrollCard({
				    	xCoord:	objA.xCoord,
				    	yCoord:	objA.yCoord,
				    	duration:	'1.0'
						
					});
				break;
				
				case 'HSClearChangeFlagAction':
					new Action.playClearChangeFlag();
				break;
				
				case "HSShowHideCursorAction":
					switch(objA.cursorVisibility){
						case "0":
							objA.mode = "show";
						break;
					
						case "1":
							objA.mode = "hide";
						break;
						
						case "2":
							objA.mode = "hideUntil";
						break;
					
					}
					
					new Action.playHideCursor({mode:objA.mode});
				break;
				
				case "cardShuffler":
					new Action.playCardShuffler();
				break;
				
				case "HSKeyMapperAction":
					new Action.playKeyMapper({items:objA.mappings});
				break;
				
				case 'sequence':
					$('Card'+ cardsCollection.currentElement().id + 'cardObjects'+ objA.object).playSequence();
				break;
				
				default:
					if(!objA[gt]){
						new messageCreate({image:"./data/engine/templates/img/info.png",text:"Unsupported action.",caption:"OK"});
						
					}
				break;
			
			}
		}
		catch(err){
			alert('error in player.js (bfx):' + console.log(err));
		}
	
	},
	
	
	setLoadEffectsChain: function(element,actions){
		/**TODO:
		 * generating internal priority
		 **/
		try{
			//objA.priority = 0;
			chain = this.makeChain(actions);
			chain.each(function(objA,cnt){
				objA.priority = cnt;
				/*if(cardsCollection.lastSeenElement().id != cardsCollection.currentElement().id && cardsCollection.currentElement().id != 0){
					document.stopObserving('card' + cardsCollection.lastSeenElement().id + 'action' + objA.priority + ':done');
				}*/
				/**if isset timer, playing action after timeout*/
				timer = 'automaticTimer';
				if(objA[timer]){
					try{
						document.observe(this.template.cardLoadActionEventDone(element.id,objA.priority),function(){
						setTimeout(
								
								function(){
									//alert('hi');
										this.bfx(this,objA,actions,element);
								}.bind(this), objA[timer]*1000);
						}.bind(this));
						}
					catch(err){
						console.log(err);
					}
				}
				/**else using common onload event*/
				else{
				document.observe(this.template.cardLoadActionEventDone(element.id,objA.priority),play.bfx.bindAsEventListener(play,objA,actions,element,'load'));
				
					firstCardEvent = this.template.cardLoadActionEventDone(element.id,objA.priority);
				}
			}.bind(this));
				
				document.fire(this.template.cardLoadActionEventDone(element.id,0)); 
				document.stopObserving(this.template.cardLoadActionEventDone(element.id,0));
				 
		}
		catch(err){
			alert('error in player.js (setEffectsChain):' + console.log(err));	
			}
	},
	
	setEffectsChain: function(element,actions){
		/**TODO:
		 * generating internal priority
		 **/
		try{
			
			
			chain = this.makeChain(actions);
			chain.each(function(objA){
				objA.priority = 0;
				/**if isset timer, plaing action after timeout*/
				timer = 'timer';
				
				/**FIX for events observers*/
				var registry = Element.retrieve(document, 'prototype_event_registry');
			    
				/**responders = registry.get(eventName); */
				var responders = registry.get(this.template.cardElementEventDone(cardsCollection.currentElement().id,element.id,objA.priority));
				
			    if (Object.isUndefined(registry)||Object.isUndefined(responders)||Object.isUndefined(responders[0])){
			    	  
					if(objA[timer]){
						try{
							setTimeout(function(){this.bfx(this,objA,actions,element);}.bind(this),objA[timer]*1000);
							}
						catch(err){
							console.log(err);
						}
					}
					/**else using common onload event*/
					else{
						
					document.observe(this.template.cardActionEventDone(element.id,objA.priority),play.bfx.bindAsEventListener(play,objA,actions,element));
					
						firstCardEvent = this.template.cardActionEventDone(element.id,objA.priority);
					}
			     }
			}.bind(this));
				
				document.fire(this.template.cardActionEventDone(element.id,0)); 
				document.stopObserving(this.template.cardActionEventDone(element.id,0));
				 
		}
		catch(err){
			alert('error in player.js (setEffectsChain):' + console.log(err));	
			}
	},
	
	
	setUnloadEffectsChain: function(element,actions){
		
		try{
			
			chain = this.makeChain(actions);
			chain.each(function(objA){
				
				if(objA.type == "HSGoToSpecificCardAction"&&play.help.getCountObjectActions(actions)>1) objA.priority=1;
				else objA.priority = 0;
				
				
				timer = 'timer';
				
				/**FIX for events observers*/
				var registry = Element.retrieve(document, 'prototype_event_registry');
			    
				/**responders = registry.get(eventName); */
				var responders = registry.get(this.template.cardUnloadActionEventDone(element.id,objA.priority));
				
			      if (Object.isUndefined(registry)||Object.isUndefined(responders)||Object.isUndefined(responders[0])){
			    	  /**if isset timer, playing action after timeout*/
			    	  if(typeof(elementObject)!='undefined'&&!Object.isUndefined(elementObject[timer])){
			    		  
			    		  document.observe(this.template.cardUnloadActionEventDone(element.id,objA.priority),function(){
								var tempTimeout =  setTimeout(
										function(){
												
												this.bfx(this,objA,actions,'unload');
													
										}.bind(this), elementObject[timer]*1000);
								this.timerTimeouts.push(tempTimeout);
							}.bind(this));
					  }
			    	 
			    	  else document.observe(this.template.cardUnloadActionEventDone(element.id,objA.priority),play.bfx.bindAsEventListener(play,objA,actions,element,'unload'));
			      
			      }
				if(objA.priority == '0') { 
					
					firstObjectEvent = this.template.cardUnloadActionEventDone(element.id,objA.priority);
					if(this.options.test)console.log(firstObjectEvent);
				}
				
				
				
				
			}.bind(this));
			
			document.fire(this.template.cardUnloadActionEventDone(element.id,0));	
			
				var lastIndex = chain.length-1;
				if(chain[lastIndex]){
					var lastPriority = chain[lastIndex].priority +1;
					document.observe(this.template.cardUnloadActionEventDone(element.id,lastPriority),function(){
						document.fire('Card' + cardsCollection.getPointer() +':canUnload');
					});
				}
				else{
					
					document.fire('Card' + cardsCollection.getPointer() +':canUnload');
				}
				 
		}
		catch(err){
			alert('error in player.js (seUnloadtEffectsChain):' + console.log(err));	
			}
	},
	
	setElementsEffectsChain: function(element,actions,elementObject){
		try{
			chain = this.makeChain(actions);
			if(this.options.test)console.log(chain);
			
			if(Object.isUndefined(this.timerTimeouts)) this.timerTimeouts = [];
			delete this.gtaction;
			chain.each(function(objA,counter){
				//objA.priority = 0;
				
				
				/**FIXME!!!*/
				if(objA.type == "HSGoToSpecificCardAction"&&play.help.getCountObjectActions(actions)>1) {
					objA.priority=1;
					this.gtaction = 1;
				}
				else if(!Object.isUndefined(this.gtaction)) {
					objA.priority = 0;
				}
				else objA.priority = counter;
				//console.log(objA.priority);
				/**EOF*/
				
				timer = 'timer';
				
				/**FIX for events observers*/
				var registry = Element.retrieve(document, 'prototype_event_registry');
			    
				/**responders = registry.get(eventName); */
				var responders = registry.get(this.template.cardElementEventDone(cardsCollection.currentElement().id,element.id,objA.priority));
				
			      if (Object.isUndefined(registry)||Object.isUndefined(responders)||Object.isUndefined(responders[0])){
			    	  /**if isset timer, playing action after timeout*/
			    	  if(!Object.isUndefined(elementObject)&&!Object.isUndefined(elementObject[timer])){
			    		  if(objA.priority == 1) console.log(this.template.cardElementEventDone(cardsCollection.currentElement().id,element.id,objA.priority));
							document.observe(this.template.cardElementEventDone(cardsCollection.currentElement().id,element.id,objA.priority),function(){
								var tempTimeout =  setTimeout(
										function(){
												this.bfx(this,objA,actions,element);
										}.bind(this), elementObject[timer]*1000);
								this.timerTimeouts.push(tempTimeout);
							}.bind(this));
					  }
			    	 
			    	  else document.observe(this.template.cardElementEventDone(cardsCollection.currentElement().id,element.id,objA.priority),play.bfx.bindAsEventListener(play,objA,actions,element));
			    	  
			      }
				if(objA.priority == '0') { 
					
					firstObjectEvent = this.template.cardElementEventDone(cardsCollection.currentElement().id,element.id,objA.priority);
					//if(this.options.test)console.log('waiting for' + firstObjectEvent);
				}
			
		}.bind(this));
		document.fire(this.template.cardElementEventDone(cardsCollection.currentElement().id,element.id,0)); 
		
		if(cardsCollection.lastSeenElement().id != cardsCollection.currentElement().id){
			setTimeout(function(){document.stopObserving(this.template.cardElementEventDone(cardsCollection.lastSeenElement().id,element.id,0));}.bind(this),500);
		}
		
	}
	catch(err){
			alert('error in player.js (setEffectsChain):' + console.log(err));	
		}
	},
	
	makeChain: function(actions){
		if(!Object.isFunction(Array.prototype.sortByPriority)){
	/**SORTING BY PRIORITY*/	
			function sortByPriority(){
				var sorted = new Array();
				var ident = 0;
				var min = this[ident];
				for(j =0; j < this.length; j++){
					
					for (i = 0; i < this.length; i++) {
						
						if(this[i] != undefined){
						   
							if (min.priority > this[i].priority){
							   
							   min = this[i];
							   ident = i;
							}
						}
					}
					
					sorted[j] = min;
					
					delete this[ident];
					min = this.compact().first();
					
					
				}
				return sorted;
			}
			
		/**EOF*/
			
			Array.prototype.sortByPriority = sortByPriority;
		}
		chain = $A(actions).toArray().compact().sortByPriority();
		
		return chain;
	}
	
	
});


var createElements = {
		
	sound: function(newCard,j,play){
		var cardElement = new Element("audio" ,
			{src:prefix+newCard.objects[j].src /*+'?' +  new Date().getTime()*/ ,
			id: play.template.newCardElementId(newCard.id,newCard.objects[j].id),
			style:	"position:absolute;" + 
					"z-index:-1;" +
					"display:block;" +
					"width:0px;" +
					"height:0px;"
					});
		return cardElement;
	
	},
	
	image:function(newCard,j,play){
	
		var cardElement = new Element("img" ,
				{src:prefix+newCard.objects[j].src /*+'?' +  new Date().getTime()*/ ,
				id: play.template.newCardElementId(newCard.id,newCard.objects[j].id),
				style:	"position:absolute;" + 
						"z-index:auto;" +
						"display:none;" +
						"cursor:" + play.template.cursorStyle(newCard.objects[j].cursor) + ";"
						});
		//console.log(newCard.objects[j].cursor);
		
		if(play.help.checkForGroupObjectData(newCard,play,j)){
			var style = "top:"  + play.groupObjectsData[newCard.objects[j].id].top + ";" +
						"left:" + play.groupObjectsData[newCard.objects[j].id].left + ";" +
						"height:"+ play.groupObjectsData[newCard.objects[j].id].height + ";" +
						"width:" + play.groupObjectsData[newCard.objects[j].id].width + ";" + 
						"z-index:" + play.groupObjectsData[newCard.objects[j].id].zIndex + ";";
			//console.log(style);
			cardElement.setStyle(style);
			
		}
		else{
			cardElement.setStyle(	"top:" + newCard.objects[j].yCoord + "px;" +
									"left:"+newCard.objects[j].xCoord+"px;" +
									"height:"+newCard.objects[j].ySize+"px;" +
									"width:" + newCard.objects[j].xSize + "px;" +
									"z-index:" + (parseInt(newCard.objects[j].order) + 1) + ";"
									);
			
			
		}
		
		
		
		if(newCard.objects[j].rotationAngle != 0){
		cardElement.setStyle(	"-webkit-transform:rotate(" + (newCard.objects[j].rotationAngle ) + "deg);" +
									"-moz-transform:rotate(" + (newCard.objects[j].rotationAngle ) + "deg);" +
									"-ms-transform:rotate(" + (newCard.objects[j].rotationAngle ) + "deg);" +
									"-o-transform:rotate(" + (newCard.objects[j].rotationAngle ) + "deg);");
		}
		
		if(newCard.objects[j].opacity != "1.0") cardElement.setOpacity(newCard.objects[j].opacity);
		
		return cardElement;
	},
	
	pngMapVideo: Class.create({
		
		initialize: function(options) {
			    this.options = {
			    	id:   	'id',
			    	object: {}
			    };
			    
			    Object.extend(this.options, options || { });
			    
			    /***/
			    this.counter = 0;
			    this.totalCounter = 0;
			    this.currentMap = 0;
			    this.setRate(this.options.object.mapFPS);
			    this.playbackRate = this.getRate();
			    this.refreshRate = parseInt(1000 / this.playbackRate);
			    this.playing = false;
			    this.imgInterval =[];
			    //FIXME:this.duration = this.options.object.;
			    
			   /***/
			   return this.run();
		},
		
		run: function(){
			this.currentFramePos ={};
			this.currentFramePos.y =0;
			this.currentRow = 0; 
			this.currentCol =0;
			this.totalFrames = 0;
			this.maps = Array();
			this.countMaps = this.options.object.mapData.length;		
			
			(this.countMaps>1)?this.multiMap=true:this.multiMap=false;
			
			this.nextMapOnFrame = this.options.object.mapData[0]['length'];
			
			this.options.object.mapData.each(function(el){
				this.maps.push(el);
				this.totalFrames += parseInt(el.length);
				
			}.bind(this));
			
			this.element = this.constructElement();
			this.extendElement();
			this.preload();
			setTimeout(function(){this.setObservers();}.bind(this),1000);
			return this.element;
		},
		
		extendElement:function(){
			Object.extend(this.element, this);
		},
		
		constructElement: function(){
			var el = new Element("div", {id:this.options.id,
				style:	"position:absolute;" +
						"top:"+this.options.object.yCoord+"px;" +
						"left:"+this.options.object.xCoord+"px;" +
						"width:"+this.options.object.xSize+"px;" +
						"height:"+this.options.object.ySize+"px;" +
						"background-repeat:no-repeat;" +
						"background-color:transparent;" +
						"background-image:url(" + prefix + this.getCurrentMap().src + ");" +
						"background-position:0px 0px;"});
			
			el.setStyle(	"-webkit-transform:rotate(" + (this.options.object.rotationAngle ) + "deg);" +
							"-moz-transform:rotate(" + (this.options.object.rotationAngle ) + "deg);" +
							"-ms-transform:rotate(" + (this.options.object.rotationAngle ) + "deg);" +
							"-o-transform:rotate(" + (this.options.object.rotationAngle ) + "deg);");
			/***/
				if(this.multiMap) this.createElementClone(el);
			/***/
			return el;
		},
		
		createElementClone: function(el){
			var el2 = el.clone();
			el2.id = el.id + "2";
			this.element2 = el2;
			el2.style.visibility = "hidden";
			el2.style.backgroundImage = "url(" + prefix + this.maps[1].src + ")";	
			setTimeout(function(){$("Card" + cardsCollection.currentElement().id).insert(el2);}.bind(this),500);
		},
		
		
		preload:function(){
			this.maps.each(function(map){
				//var loadme2 = new Element("div",{style:"display:block;height:1px;width:1px;overflow:hidden;background-image:url(" + prefix + map.src + ");"});
				var loadme= new Image();
				loadme.src = prefix + map.src;
			});
		},
		
		setObservers: function(){
			$(this.element).observe("click",function(){
				if(this.playing||this.element.playing||(!Object.isUndefined(this.element2)&&this.element2.playing)) {
					this.element.pause();
				}
				else this.element.play();
			}.bind(this));
			if(!Object.isUndefined(this.element2)){
				$(this.element2).observe("click",function(){
					if(this.playing||this.element.playing||(!Object.isUndefined(this.element2)&&this.element2.playing)) {
						this.element.pause();
					}
					else this.element.play();
				}.bind(this));
			}
		},
		
		play: function(){
			this.paused = false;
			this.playing = true;
			//console.log('hi');
			this.imgInterval.push(setInterval(function(){
				this.nextFrame();
				this.totalCounter++;
				//console.log(this.totalCounter);
				if(!this.loop&&this.totalCounter>=this.totalFrames){
					
					this.pause();
					this.totalCounter = 0;
				}
				
				//console.log(this.refreshRate);
			}.bind(this),(this.refreshRate)));
		},
		
		stop: function(){
			this.paused = true;
			this.playing = false;
			this.imgInterval.each(function(el){
				clearInterval(el);
			});
			this.counter = 0;
			this.currentCol =0;
			this.currentRow = 0;
			this.currentFramePos.y =0;
			this.resetFrame(this.element);
		},
		
		pause: function(){
			console.log('paused');
			this.playing = false;
			this.paused = true;
			this.imgInterval.each(function(el){
				clearInterval(el);
			});
		},
		
		getCurrentMap:function(){
			
			if(this.nextMapOnFrame==(this.counter)){ 
				++this.currentMap;
				if(!Object.isUndefined(this.maps[this.currentMap])){
					/***/
					if(this.multiMap){
						this.element2.style.visibility = "visible";
						this.element.style.visibility = "hidden";
						var tmp = this.element;
						this.element = this.element2;
						this.element2= tmp;
					}
					/***/
					this.counter = 0;
					this.currentCol =0;
					this.currentRow = 0;
					this.currentFramePos.y =0;
					this.nextMapOnFrame = this.maps[this.currentMap]['length'];
					if(!Object.isUndefined(this.maps[this.currentMap+1]))this.loadMap(this.element2,this.maps[(this.currentMap+1)].src); 
					//else this.load(this.element2,this.maps[0].src); 
					
				}
				else {
					this.currentMap = 0;
						
						if(this.multiMap){
							this.element2.style.visibility = "visible";
							this.element.style.visibility = "hidden";
							var tmp = this.element;
							this.element = this.element2;
							this.element2= tmp;
							this.loadMap(this.element,this.maps[this.currentMap].src);
							this.loadMap(this.element2,this.maps[(this.currentMap+1)].src); 
						}
						else{
							this.nextMapOnFrame = this.maps[this.currentMap]['length'];
							this.loadMap(this.element,this.maps[this.currentMap].src);
							this.resetFrame(this.element);
						}
						
						this.counter = 0;
						this.currentCol =0;
						this.currentRow = 0;
						this.currentFramePos.y =0;
						this.nextMapOnFrame = this.maps[this.currentMap]['length'];
					}
			}
			
			return this.maps[this.currentMap];
		},
		
		getCurrentFramePos:function(){
			var pos ={};
			var map = this.getCurrentMap();
			var apoint =this.counter;
			pos.x = (apoint%=(map.xSize/this.options.object.xSize))  * this.options.object.xSize;
			pos.y = this.currentFramePos.y;
			if(pos.x >= map.xSize - this.options.object.xSize) {
				this.currentRow++;
				this.currentFramePos.y += parseInt(this.options.object.ySize);
				if(this.currentFramePos.y>=map.ySize){
					this.currentFramePos.y =0;
					this.currentRow =0;
				}
			}
			
			return pos;
		},
		
		nextFrame: function(){
			var bgPos =  this.getCurrentFramePos();
			this.setFrame(this.element,-bgPos.x,  -bgPos.y);
			//console.log(this.counter);
			++this.counter;
		},
		
		prevFrame: function(){
			--this.counter;
			this.currentTime = t;
			$(this.imgElement.id).src = this.images[this.counter]; 
		},
		
		loadMap:function(element,src){
			element.style.backgroundImage = "url(" + prefix + src + ")"; 
		},
		
		load: function(){
			
		},
		
		resetFrame: function(element){
			element.style.backgroundPosition = "0px  0px";
		},
		
		setFrame: function(element,x,y){
			element.style.backgroundPosition = x + "px " + y + "px";
		},
		
		setRate: function(r){
			this.rate = r;
		},
		
		getRate: function(){
			return this.rate;
		}
		
	
		
	}),
	
	button:function(newCard,j,play){
		var cardElement = new Element("canvas" ,
				{id: 	play.template.newCardElementId(newCard.id,newCard.objects[j].id),
				style:	"position:absolute;" +
						"z-index:2;" +
						"display:none;" +
						"cursor:" + play.template.cursorStyle(newCard.objects[j].cursor) + ";" +
						"overflow:hidden;",
				height:	newCard.objects[j].ySize,
				width:	newCard.objects[j].xSize});
		
		
		if(play.help.checkForGroupObjectData(newCard,play,j)){
			var style = "top:"  + play.groupObjectsData[newCard.objects[j].id].top + ";" +
						"left:" + play.groupObjectsData[newCard.objects[j].id].left + ";" +
						"height:"+ play.groupObjectsData[newCard.objects[j].id].height + ";" +
						"width:" + play.groupObjectsData[newCard.objects[j].id].width + ";"/* + 
						"z-index:" + play.groupObjectsData[newCard.objects[j].id].zIndex + ";"*/;
			//console.log(style);
			cardElement.setStyle(style);
			
		}
		else{
			cardElement.setStyle(	/*"z-index:" + newCard.objects[j].order + ";" +*/
									"top:" + newCard.objects[j].yCoord + "px;" +
									"left:"+newCard.objects[j].xCoord+"px;" +
									"height:"+newCard.objects[j].ySize+"px;" +
									"width:" + newCard.objects[j].xSize + "px;"
									);
			
		}
		
		
		if(newCard.objects[j].rotationAngle != 0){
			cardElement.setStyle(	"-webkit-transform:rotate(" + (newCard.objects[j].rotationAngle ) + "deg);" +
										"-moz-transform:rotate(" + (newCard.objects[j].rotationAngle)  + "deg);" +
										"-ms-transform:rotate(" + (newCard.objects[j].rotationAngle ) + "deg);" +
										"-o-transform:rotate(" + (newCard.objects[j].rotationAngle ) + "deg);");
		}
		
		return cardElement;
	},
	
	src:function(newCard,j,play){
		var butImage = new Element("img",{	
									id: 	play.template.newCardElementId(newCard.id,newCard.objects[j].id)+"_image",
									src:	prefix + newCard.objects[j].src,
									style: "position:absolute;z-index:" + newCard.objects[j].order + ";" +
											"display:block;cursor:" + play.template.cursorStyle(newCard.objects[j].cursor) + ";" +
											"top:" + newCard.objects[j].yCoord + "px;" +
											"left:"+newCard.objects[j].xCoord+"px;" +
											"overflow:hidden;"});
		if(newCard.objects[j].isVisible != 1)		butImage.style.display = "none";
		
		if(newCard.objects[j].rotationAngle != 0){
			butImage.setStyle(	"-webkit-transform:rotate(" + (newCard.objects[j].rotationAngle ) + "deg);" +
										"-moz-transform:rotate(" + (newCard.objects[j].rotationAngle)  + "deg);" +
										"-ms-transform:rotate(" + (newCard.objects[j].rotationAngle ) + "deg);" +
										"-o-transform:rotate(" + (newCard.objects[j].rotationAngle ) + "deg);");
		}
		return butImage;
	},
	
	text: function(newCard,j,play){
		var textElement = new Element("div" ,
				{	id: 	play.template.newCardElementId(newCard.id,newCard.objects[j].id),
					style:	"position:absolute;" +
							"z-index:"+(parseInt(newCard.objects[j].order)+1)+";" +
							"display:none;" +
							"background:"+newCard.objects[j].src+";" +
							"top:" + newCard.objects[j].yCoord + "px;" +
							"left:"+newCard.objects[j].xCoord+"px;" +
							"height:"+newCard.objects[j].ySize+"px;" +
							"width:" + newCard.objects[j].xSize + "px;" +
							"overflow-y:scroll;" +
							"overflow-x:hidden;" +
							"white-space:pre-wrap;" +
							"word-wrap: break-word;"});
		if(newCard.objects[j].hasShadow == 1){
			textElement.setStyle(/*"-webkit-text-shadow:"+ newCard.objects[j].shadow.xOffset + "px " + newCard.objects[j].shadow.yOffset + "px " + newCard.objects[j].shadow.blur + "px #000" +*/
								"text-shadow:"+ newCard.objects[j].shadow.yOffset + "px " + newCard.objects[j].shadow.xOffset + "px " + newCard.objects[j].shadow.blur + "px #000");
		}
		
		if(!Object.isUndefined(newCard.objects[j].cssString)&&newCard.objects[j].cssString!=""){
			textElement.setStyle(newCard.objects[j].cssString);
		}
		
		if(newCard.objects[j].textType == "rotatable"){
			textElement.setStyle("overflow-y:hidden;");
		}
		
		if(newCard.objects[j].rotationAngle != 0){
			textElement.setStyle(		"-webkit-transform:rotate(" + (newCard.objects[j].rotationAngle ) + "deg);" +
										"-moz-transform:rotate(" + (newCard.objects[j].rotationAngle)  + "deg);" +
										"-ms-transform:rotate(" + (newCard.objects[j].rotationAngle ) + "deg);" +
										"-o-transform:rotate(" + (newCard.objects[j].rotationAngle ) + "deg);");
		}
		
		if(newCard.objects[j].drawScrollBar!='1')textElement.setStyle("overflow:hidden;");
		if(newCard.objects[j].drawFrame=='1')textElement.setStyle("border:1px #aaa solid;");
		
		return textElement;
	}
	
};



var createCardObject = {
		
		image: function(item,animationConstructor){
		try{
			var cardElement = new Element("img" ,
				{src:prefix+item.src ,
					id: new Date().getTime(),
					style:	"position:absolute;" +
							"display:none;"
				});
			
			if(!Object.isUndefined(animationConstructor)&&animationConstructor) cardElement.style.display = "block";
			cardElement.setStyle(	"z-index:" 	+ item.order + ";" 	+
									"top:" 		+ item.yCoord + "px;" 	+
									"left:"		+ item.xCoord + "px;" 	+
									"height:"	+ item.ySize + "px;" 	+
									"width:" 	+ item.xSize + "px;"
									);
			
			if(item.rotationAngle != 0){
				cardElement.setStyle(	"-webkit-transform:rotate(" + (item.rotationAngle) + "deg);" +
										"-moz-transform:rotate(" + (item.rotationAngle) + "deg);" +
										"-ms-transform:rotate(" + (item.rotationAngle) + "deg);" +
										"-o-transform:rotate(" + (item.rotationAngle) + "deg);");
			}
			
			return cardElement;
		}
		catch(err){
			console.log(err);
		}
		},
		
		
		button: function(item){
			
		},
		
		text: 	function(item){
			var textElement = new Element("div" ,
					{	id: 	new Date().getTime(),
						style:	"position:absolute;" +
								"z-index:25;" +
								"display:none;" +
								"background:" + item.src + ";" +
								"top:" 		+ item.yCoord + "px;" +
								"left:" 	+ item.xCoord + "px;" +
								"height:"	+ item.ySize + "px;" +
								"width:" 	+ item.xSize + "px;" +
								"overflow:hidden;"
			});
			
			if(item.hasShadow == 1){
				textElement.setStyle(/*"-webkit-text-shadow:"+ newCard.objects[j].shadow.xOffset + "px " + newCard.objects[j].shadow.yOffset + "px " + newCard.objects[j].shadow.blur + "px #000" +*/
									"text-shadow:"+ newCard.objects[j].shadow.yOffset + "px " + newCard.objects[j].shadow.xOffset + "px " + newCard.objects[j].shadow.blur + "px #000");
			}
			
					
					
		/************************************/
					
			if((item.textType == 'scrollable' && item.drawScrollBar=='1')||(item.textType == 'rotatable' && item.drawScrollBar=='1')){		
						
					var track = new Element("div",{id:'track' + textElement.id,'class':'track',style:'width:15px;height:'+ (item.ySize - 35) +'px;'});
					if(!Object.isUndefined(item.drawTrack)&&item.drawTrack==0) track.setStyle("display:none;");
					var wrap = new Element("div",{style:'float:right;width:15px;height:'+ item.ySize+'px;'});
					var handle = new Element('div',{id:'handle'+newCard.objects[j].id,'class':'handle',style:"height:37px;"});
					track.insert(handle);
						
					var holder = new Element('div',{id:'scrollHolder' + textElement.id,style:'top:'+parseFloat(item.ySize-74)+'px;'});
					holder.insert(new Element('img',{src:'./data/engine/templates/img/scrollUpArrow.png',style:"margin-top:-5px;"}));
					holder.insert(new Element('img',{src:'./data/engine/templates/img/scrollDownArrow.png'}));
					wrap.insert(track);
					wrap.insert(holder);
					if(newCard.objects[j].textType =='rotatable')wrap.style.display='none';
					textElement.insert(wrap);
					var textPane = new Element("div",{id:textElement.id + 'textPane',
															style:"z-index:1;overflow:hidden;width:"+(parseFloat(textElement.width.gsub('px;','')) -5 - parseInt(track.style.width.gsub('px;','')))+"px;"});
						
					if(!Object.isUndefined(newCard.objects[j].background))	textPane.style.background ="url("+ prefix + newCard.objects[j].background+") no-repeat";
					if(item.textType =='rotatable'||item.drawScrollBar!='1'){
							[holder,handle].each(function(el){el.style.display = 'none';});
							
							track = parseInt(track.style.height.replace(/px$/,""))+ 30 + 'px !important';
					}
						
					if(item.textType!='rotatable') cardObject.insert(textElement.insert(textPane.update(item.text)));
					else cardObject.insert(textElement.insert(textPane.update(new Element("img",{src:prefix + item.textImage}))));
						
						
					if(newCard.objects[j].isVisible != 0) cardElements[j].show();
						
					var text = textElement.id;
						
					play.textObjects[text] = new scrollBar({block: text,content:text + 'textPane',suffixId:text});
			}
			else{
				
					if(newCard.objects[j].textType=='rotatable') cardObject.insert(cardElements[j].update(new Element("img",{src:prefix + newCard.objects[j].textImage })/*newCard.objects[j].text*/));
					else cardObject.insert(cardElements[j].update(newCard.objects[j].text));
					if(!Object.isUndefined(newCard.objects[j].background))	cardElements[j].style.background ="url("+ prefix + newCard.objects[j].background+") no-repeat";
					
					if(newCard.objects[j].isVisible != 0) cardElements[j].show();
				
			}
		
		
		
			
			return textElement;
		},
		
		video: 	function(item){
			/*	videoElement = this.createVideoElement(newCard,j);
				if(Object.isFunction(cardElements[j].setStyle)){
					cardElements[j].setStyle(	"-webkit-transform:rotate(" + (newCard.objects[j].rotationAngle * 180) / Math.PI + "deg);" +
												"-moz-transform:rotate(" + (newCard.objects[j].rotationAngle * 180) / Math.PI + "deg);" +
												"-o-transform:rotate(" + (newCard.objects[j].rotationAngle * 180) / Math.PI + "deg);");
				}
				else if(newCard.objects[j].rotationAngle != 0) this.rotateVideo(this.template.newCardElementId(newCard.id,newCard.objects[j].id), (newCard.objects[j].rotationAngle * 180) / Math.PI);
				cardObject.insert(cardElements[j]);
			*/
		},
		
		sequence: function(item){
			
		}
};

var Action = {
	
		finishAction : function(creator,priority){
	
			switch(creator){
				case "cardUnload":
					return function(){
						//alert('hi');
						document.fire(play.template.cardUnloadActionEventDone(cardsCollection.currentElement().id,(priority+1)));
					}.bind(this).delay(0.1);
				break;
				
				case "cardLoad":
					return function(){
						document.fire(play.template.cardLoadActionEventDone(cardsCollection.currentElement().id,(priority+1)));
					}.bind(this).delay(0.1);
				break;
				
				case "cardClick":
					return function(){
						document.fire(play.template.cardActionEventDone(cardsCollection.currentElement().id,(priority+1)));
					}.bind(this).delay(0.1);
				break;
				
				default:
					return function(){
						document.fire(play.template.cardElementEventDone(cardsCollection.currentElement().id,creator,(priority+1)));
					}.bind(this).delay(0.1);
				break;
			}
		}
};
/**
 * Here comes actions objects.
 * To add new action we need:
 * 1. Create new object at the bottom;
 * 2. Add initialization for it in bfx function.
 */



Action.playSound = Class.create({
	
	initialize: function(options) {
		try{
		    this.options = {
		    	info:   	'info'
		    };
		    
		    Object.extend(this.options, options || { });
		    //console.log("sound play");
		   
		    
		    /*******/
		    /*var sound = new Element('input',
					{type:'hidden',
					value:prefix+info.sounds[0].src,
					id: "justDemo"});
			$(cardCollection.currentElement().id).insert(sound);*/
			/*****/
		    if(this.options.info.stopAllSounds==1){
		    	this.stopAll(this.options.info);
		    }
		    
		    else if(!play.supportsAudio())  this.playSound(this.options.info);  
		    else this.playHTMLSound(this.options.info);
		}
		catch(err){
			alert('actions.playSound: initialize error:' + console.log(err));
		}
	},
	
	playSound: function(info){
		try{
		Sound.enable();
		
			info.sounds.each(function(sound){
				Sound.play($(play.template.newCardElementId(cardsCollection.currentElement().id,sound.object)).src,{replace:true});
			});
			
		}catch(e){
			if(this.options.test)console.log(e);
		}
		
		if(info.creator=='cardUnload') setTimeout(function(){document.fire(play.template.cardUnloadActionEventDone(cardsCollection.currentElement().id,(info.priority+1)));}.bind(this),100);
		else if(info.creator=='cardLoad') setTimeout(function(){document.fire(play.template.cardLoadActionEventDone(cardsCollection.currentElement().id,(info.priority+1)));}.bind(this),100);
		else if (info.creator=='cardClick') setTimeout(function(){document.fire(play.template.cardActionEventDone(cardsCollection.currentElement().id,(info.priority+1)));}.bind(this),100);
		else setTimeout(function(){document.fire(play.template.cardElementEventDone(cardsCollection.currentElement().id,info.creator,(info.priority+1)));}.bind(this),100);
	},
	stopAll: function(info){
		try{
			Sound.enable();
			Sound.play('qwe.mp4',{replace:true}); 
		    Sound.disable(); 
		    Sound.enable();
		}catch(e){
			if(this.options.test)console.log(e);
		}
		
		$$('audio').each(function(el){
			el.load();
			el.pause();
		});
		
		if(info.creator=='cardUnload') setTimeout(function(){document.fire(play.template.cardUnloadActionEventDone(cardsCollection.currentElement().id,(info.priority+1)));}.bind(this),100);
		else if(info.creator=='cardLoad') setTimeout(function(){document.fire(play.template.cardLoadActionEventDone(cardsCollection.currentElement().id,(info.priority+1)));}.bind(this),100);
		else if (info.creator=='cardClick') setTimeout(function(){document.fire(play.template.cardActionEventDone(cardsCollection.currentElement().id,(info.priority+1)));}.bind(this),100);
		else setTimeout(function(){document.fire(play.template.cardElementEventDone(cardsCollection.currentElement().id,info.creator,(info.priority+1)));}.bind(this),100);
		//$('sound_global_'+el);
	},
	
	playHTMLSound: function(info){
		try{
		info.sounds.each(function(sound){
			var elId = play.template.newCardElementId(cardsCollection.currentElement().id,sound.object);
			if(sound.stopThisSound==1){
				$(elId).load();
				return;
			}
			$(elId).load();
			$(elId).play();
		});
			
		}catch(e){
			if(this.options.test)console.log(e);
		}
		
		if(info.creator=='cardUnload') setTimeout(function(){document.fire(play.template.cardUnloadActionEventDone(cardsCollection.currentElement().id,(info.priority+1)));}.bind(this),100);
		else if(info.creator=='cardLoad') setTimeout(function(){document.fire(play.template.cardLoadActionEventDone(cardsCollection.currentElement().id,(info.priority+1)));}.bind(this),100);
		else if (info.creator=='cardClick') setTimeout(function(){document.fire(play.template.cardActionEventDone(cardsCollection.currentElement().id,(info.priority+1)));}.bind(this),100);
		else setTimeout(function(){document.fire(play.template.cardElementEventDone(cardsCollection.currentElement().id,info.creator,(info.priority+1)));}.bind(this),100);
	}

});


Action.playVideo = Class.create({
	
	initialize: function(options) {
		try{
		    this.options = {
		    	item:   	'info'
		    };
		    
		    Object.extend(this.options, options || { });
		    this.options.item.movies.each(function(movie){
			    this.setOptions(movie);
			    this.playVideo(movie);
		    }.bind(this));
		    if(this.options.item.creator=='cardLoad'){
		    	this.options.item.movies.each(function(info){
		    		obj = $(play.template.newCardElementId(cardsCollection.currentElement().id,info.object));
		    		if(!Object.isElement(obj)) return;
		    		obj.setAttribute("playonstart","playonstart");
		    	});
		    }
		  
		}
		catch(err){
			alert('playerObj: initialize error:' + console.log(err));
		}
	},
	
	playVideo: function(info){
		var obj = $(play.template.newCardElementId(cardsCollection.currentElement().id,info.object));
		if(!Object.isElement(obj)) return;
		if(obj.isVisible !=1) return;
		
		obj.play();
		obj.observe("ended",function(e){
			Action.finishAction(this.options.item.creator,parseInt(this.options.item.priority));
		}.bind(this));
		
		obj.observe("pause",function(e){
			Action.finishAction(this.options.item.creator,parseInt(this.options.item.priority));
		}.bind(this));
		
		setTimeout(function(){
		if(!Object.isUndefined(obj.currentTime)&&!play.supportsVideo()){
			this.interval = setInterval(function(){
				if(!Object.isFunction(obj.currentTime))clearInterval(this.interval);
				if(obj.currentTime()>=obj.duration()){
					Action.finishAction(this.options.item.creator,parseInt(this.options.item.priority));
					clearInterval(this.interval);
				}
			}.bind(this),500);
			
		}}.bind(this),1500);
		/**
		 * 
		 * */

		/*if( _this.type == 'other'){
			document.fire(play.template.cardElementEventDone(cardsCollection.currentElement().id,this.options.item.creator,parseInt(item.priority + 1))); 
		}
		if(!item[timer] && _this.type == 'load')
			itemObject.fire('card' + cardId + 'loadAction' + parseInt(item.priority + 1) + ':done');
		timer = 'automaticTimer';
		if(!item[timer] && _this.type == 'unload')
			itemObject.fire('card' + cardId + 'unloadAction' + parseInt(item.priority + 1) + ':done');*/
	},
	
	setOptions: function(info){
		
		var obj = $(play.template.newCardElementId(cardsCollection.currentElement().id,info.object));
		if(!Object.isElement(obj)) return;
		if(obj.isVisible !=1) return;
		obj.show();
		if(info.isPlayOnTop == 1){
			obj.style.zIndex = 999;
		}
		//else obj.style.zIndex = 0;
		
		if(info.isEraseWhenDone == 1){
			
		}
		if(info.isLooped == 1){
			obj.loop = true;
		}
		
		if(info.useMovieController == 1){
			obj.controls = true;
		}
	}
});

Action.playVideoSequence = Class.create({
		initialize: function(options) {
		try{
			this.options = {
					imgElement: $('imgElement'),
					imagesTemplate:		Array(),
					imagesCount: 10
			};
			    Object.extend(this.options, options || { });
			    this.counter = 0;
			    this.imgElement = this.options.imgElement;
			    this.imagesCount = this.options.imagesCount;
			    
			    /***/
			    this.setRate(r);
			    this.playbackRate = this.getRate();
			    
			    this.playing = false;
			    this.duration = t;
			    /***/
			    
			    /**here we'll populate our apositions array*/
			    for(var i=0;i<=this.options.imagesCount;i++){
			    	(i<10)?i='0'+i:'';
			    	this.images.push(this.template.evaluate({num:i})); 
			    }
			  
			 
		}
		catch(err){
			console.log(err);
		}
	},
	
	play: function(){
		this.playing = true;
		var i =this.counter + 1;
		this.imgInterval = setInterval(function(){
			if(!$(this.imgElement.id)||$(this.imgElement.id)=='undefined'||$(this.imgElement.id)=='null') {
				
				this.stopSequence();
			}
			else{
				if(i>this.imagesCount) i = 0;
				$(this.imgElement.id).src = this.images[i]; 
				i++;
			}
			
		}.bind(this),33);
	},
	
	stop: function(){
		this.playing = false;
		clearInterval(this.imgInterval);
		this.counter = 0;
	},
	
	pause: function(){
		this.playing = false;
		this.paused = true;
		clearInterval(this.imgInterval);
	},
	
	nextFrame: function(){
		++this.counter;
		this.currentTime = t;
		$(this.imgElement.id).src = this.images[this.counter]; 
	},
	
	prevFrame: function(){
		--this.counter;
		this.currentTime = t;
		$(this.imgElement.id).src = this.images[this.counter]; 
	},
	
	load:function(src){
		this.frameSprite = src;
		this.currentFrame =[0,0];
	},
	
	setRate: function(r){
		this.rate = r;
	},
	
	getRate: function(){
		return this.rate;
	}
});

Action.playItemAnimation = Class.create({
	
	initialize: function(options) {
		try{
		    this.options = {
		    	item:   	'item',
		    	length:		'0',
		    	cardId:		'cardId',
		    	type: 		'other',
		    	sequence: false
		    }; 
		    
		    Object.extend(this.options, options || { });
		    this.type = this.options.type;
		    this.pointsLength =  this.options.item.points.length;
		    this.length = this.options.length;
		    this.sequence = this.options.sequence;
		    this.counter = 0;
		    this.repeats = 0;
		    this.animationDirection = 0;
		    if(this.length > 1) {
		    	this.sync = this.options.item.creator;
		    }
		    
		    var points = this.preparePoints(this.options.item.points,this.options.item.playbackDirection);
		    //  console.log(this.options.item.points);
		    // console.log(points);
		    
		    this.playItemAnimation(this.options.item, this.length, this.options.cardId,points,this.options.item.playbackDirection);
		 
		}
		catch(err){
			alert('playerObj: playItemAnimation error:' + console.log(err));
		}
	},
	
	state: 'inactive',
	
	key: '',
	
	type: '',
	
	sequence: false,
	
	playItemAnimation: function(item,length,cardId,points,playbackDirection){
		item.id = play.template.newCardElementId(cardsCollection.currentElement().id,item.object);
		var itemElement = $(item.id);
		if(!Object.isElement($(item.id))) return;
		$(item.id).show();
		
		/**cloning element at start*/
			if(this.options.playbackDirection!=1){
				//var itemElement = this.cloneElement(itemElement);
				this.setNoFlip(itemElement);
				/*itemElement.style.mozTransform
				//var itemElement = this.cloneElement(itemElement);
				itemElement.setStyle('-moz-transform: scale(-1, -1);');
				!Object.isUndefined(itemElement.style['-moz-transform'])? itemElement.style['-moz-transform']+=" scale(-1, -1)":itemElement.style['-moz-transform'] = " scale(-1, -1)";
				itemElement.style.msTransform +=" scale(1, 1)";
				itemElement.style.webkitTransform +=" scale(1, 1)";
				itemElement.style.oTransform +=" scale(1, 1)";
				itemElement.style.ransform +=" scale(1, 1)";*/
						
			}
		/**EOF*/
		
		/**Checking if the animated object is images  sequence*/ 
		if(this.sequence){
			var itemObject = itemElement;
			/*var itemObjectActions = new Action.playSequenceAnimation({
				imgElement: $('Card'+cardsCollection.currentElement().id + 'cardObjects' + item.object), 
				imagesTemplate: item.template,
				imagesCount: item.imagesCount
				});
			Object.extend(itemObject, itemObjectActions);
			*/
			var duration = 0.045;
		}
		else {
			var itemObject = itemElement;
			var duration = 0.5;
		}
		
		this.animateObject = itemObject; 
		
		var scopeName = cardId + 'goto' + item.id;
		counterJ = {};
		var _this = this;
		if(_this.sync)
			counterJ[_this.sync] = 0;
		else{
			_this.sync = item.id;//'noSync';
			counterJ[_this.sync] = 0;
		}
		
		/***/
		if(this.options.playbackDirection==1){
			if(this.options.item.horizontalFlipAtFinish==1&&this.options.item.verticalFlipAtFinish==0){
				this.setHorizontalFlip(itemObject);
			}
			else if(this.options.item.verticalFlipAtFinish==1&&this.options.item.horizontalFlipAtFinish==0){
				this.setVerticalFlip(itemObject);
			}
			else if(this.options.item.verticalFlipAtFinish==1&&this.options.item.horizontalFlipAtFinish==1){
				this.setFullFlip(itemObject);
			}
		}
		/***/
		Try.these(
				function(){
					
					//itemObject.loop = true;
					itemObject.play();
					if(Object.isUndefined(itemObject.playSequence)&&points.length >1){
						itemObject.play();
					}
					
					//$(itemObject.id).pause();
					/*setTimeout(function(){
							
						
						$(itemObject.id).play();
					}.bind(this),800);*/
					
				}) || '';
		
		//scale(-1, -1)
		points.each(function(point,itemNumber){
			try{	
					
					var nextPoint = ++itemNumber;
					if(!Object.isUndefined(item.points[nextPoint])){
						//alert
					var iterationDurr = Math.abs(item.points[nextPoint].t - point.t)/parseInt(this.options.item.speedMultiplier);
					new Effect.Move(this.animateObject,{x:item.points[nextPoint].x,y:item.points[nextPoint].y,
						mode:'absolute',transition:Effect.Transitions.linear,
						duration:iterationDurr, queue:{ scope:scopeName,position:'end'},
						beforeUpdate: function(effect){
							if(itemObject.paused||itemObject.ended){
								//alert('hi');
								itemObject.play();
							}
							
							/**Layers handling*/
							switch(this.options.item.layer){
								case "0":
									this.animateObject.style.zIndex = 0;
								break;
								
								case "2":
									this.animateObject.style.zIndex = 9999;
								break;
							}
							/**EOF*/
							if(this.animationDirection == 0){
								
								/**dont erase going*/
									if(this.options.item.goingAbsoluteLayer=="1") this.animateObject.style.zIndex = 9999;
									//else this.animateObject.style.zIndex = 9999;
									if(this.options.item.eraseGoing == 0){
										this.animateObject = this.cloneElement(this.animateObject,point);
										this.animateObject.show();
									}
								/**EOF*/
							}
							else if(this.animationDirection == 1){
								/**dont erase going*/
									if(this.options.item.returningAbsoluteLayer=="1") this.animateObject.style.zIndex = 9999;
									//else this.animateObject.style.zIndex = 9999;
									if(this.options.item.eraseReturning == 0){
										this.animateObject = this.cloneElement(this.animateObject,point);
										this.animateObject.show();
									}
								/**EOF*/
							}
							
							
							
						}.bind(this),
						afterFinish: function(effect) {
							
							//if(this.sequence && itemObject.playing == false)itemObject.nextFrame();
							/*Try.these(
									function(){
										itemObject.play();
										itemObject.play();
									}) || '';*/
							
							//console.log(_this.counter + ',' + counterJ[_this.sync] + ':'+length + ',' + _this.pointsLength);
							_this.counter ++;
							if(_this.counter >= parseInt(_this.pointsLength -1)){
									
									++counterJ[_this.sync];
									
								if(counterJ[_this.sync] >= length || Object.isUndefined(counterJ[_this.sync]) || !counterJ[_this.sync]){
									try{
										Try.these(function(){itemObject.pause();}.bind(this));
										if(this.repeats<this.options.item.loopPathRepeats && this.checkAutoReverse()){ 
											this.repeats++;
											return;
										}
										
										if(!item[timer] && _this.type == 'other'){
											document.fire(play.template.cardElementEventDone(cardsCollection.currentElement().id,this.options.item.creator,parseInt(item.priority + 1))); 
										}
										if(!item[timer] && _this.type == 'load')
											itemObject.fire('card' + cardId + 'loadAction' + parseInt(item.priority + 1) + ':done');
										timer = 'automaticTimer';
										if(!item[timer] && _this.type == 'unload')
											itemObject.fire('card' + cardId + 'unloadAction' + parseInt(item.priority + 1) + ':done');
									//	console.log('hi');
										Try.these(
												function(){
													itemObject.pause();
												}) || '';
										
										if(this.options.item.autoReverse==1) this.options.item.points.reverse();
										
								
									}
									catch(err){
											alert(err);
										}
									}
								}
						   }.bind(this)
					});
				}
				}
				catch(err){
					console.log(err);
					return;
				}
			}.bind(this));
	
	},
	
	preparePoints: function(points,direction){
		if(direction==1){
		//	alert('hi');
			points = points.reverse();
		}
		
		return points;
	},
	
	cloneElement: function(item,point){
		if(!Object.isUndefined(item)){
			switch(item.tagName.toLowerCase()){
				case "img":
					var object = item.clone();
					if(!Object.isUndefined(point)) object = this.setPosition(object,point);
					object.style.zIndex = "1";
					object.id = object.id + "clone" + new Date().getTime();
				break;
				
				case "button":
					var object = item;
				break;
				
				case "text":
					var object = item;
				break;
					
				case "video":
					var object = item;
				break;
				
				case "sequence":
					var object = item;
				break;
			}
			$(play.template.cardId(cardsCollection.currentElement().id)).insert(object);
			return object;
		}
	},
	
	setPosition: function(object,point){
		object.style.top = point.y + "px";
		object.style.left = point.x +"px";
		object.hide();
		return object;
	},
	
	checkAutoReverse: function(){
		if(this.options.item.autoReverse==1){
			this.counter = 0;
			this.options.playbackDirection = 1;
			
			if(this.animationDirection == 1)this.animationDirection = 0;
			else this.animationDirection = 1;
			
			var points = this.preparePoints(this.options.item.points,1);
			this.playItemAnimation(this.options.item, this.length, this.options.cardId,points,this.options.playbackDirection);
			return true;
		}
		else return false;
	},
	
	setNoFlip: function(itemElement){
		if(!Object.isUndefined(itemElement.style.mozTransform))mozillaTransform = itemElement.style.mozTransform + " scale(1, 1);";
		else mozillaTransform = " scale(1, 1);";
		if(!Object.isUndefined(itemElement.style.msTransform))microsoftTransform = itemElement.style.msTransform + " scale(1, 1);";
		else microsoftTransform = " scale(1, 1);";
		if(!Object.isUndefined(itemElement.style.webkitTransform))appleTransform = itemElement.style.webkitTransform + " scale(1, 1);";
		else appleTransform = " scale(1, 1);";
		if(!Object.isUndefined(itemElement.style.oTransform))operaTransform = itemElement.style.oTransform + " scale(1, 1);";
		else operaTransform =" scale(1, 1);";
		if(!Object.isUndefined(itemElement.style.transform))othersTransform = itemElement.style.transform + " scale(1, 1);";
		else othersTransform =" scale(1, 1);";
		itemElement.setStyle("-moz-transform:" + mozillaTransform +
				"-ms-transform:" + microsoftTransform +
				"-webkit-transform:" + appleTransform +
				"-o-transform:" + operaTransform +
				"transform:" + othersTransform);
		
	},
	
	setVerticalFlip: function(itemElement){
		if(!Object.isUndefined(itemElement.style.mozTransform))mozillaTransform = itemElement.style.mozTransform + " scale(1, -1);";
		else mozillaTransform = " scale(1, -1);";
		if(!Object.isUndefined(itemElement.style.msTransform))microsoftTransform = itemElement.style.msTransform + " scale(1, -1);";
		else microsoftTransform = " scale(1, -1);";
		if(!Object.isUndefined(itemElement.style.webkitTransform))appleTransform = itemElement.style.webkitTransform + " scale(1, -1);";
		else appleTransform = " scale(1, -1);";
		if(!Object.isUndefined(itemElement.style.oTransform))operaTransform = itemElement.style.oTransform + " scale(1, -1);";
		else operaTransform =" scale(1, -1);";
		if(!Object.isUndefined(itemElement.style.transform))othersTransform = itemElement.style.transform + " scale(1, -1);";
		else othersTransform =" scale(1, -1);";
		itemElement.setStyle("-moz-transform:" + mozillaTransform +
				"-ms-transform:" + microsoftTransform +
				"-webkit-transform:" + appleTransform +
				"-o-transform:" + operaTransform +
				"transform:" + othersTransform);
		
	},
	
	setHorizontalFlip: function(itemElement){
		if(!Object.isUndefined(itemElement.style.mozTransform))mozillaTransform = itemElement.style.mozTransform + " scale(-1, 1);";
		else mozillaTransform = " scale(-1, 1);";
		if(!Object.isUndefined(itemElement.style.msTransform))microsoftTransform = itemElement.style.msTransform + " scale(-1, 1);";
		else microsoftTransform = " scale(-1, 1);";
		if(!Object.isUndefined(itemElement.style.webkitTransform))appleTransform = itemElement.style.webkitTransform + " scale(-1, 1);";
		else appleTransform = " scale(-1, 1);";
		if(!Object.isUndefined(itemElement.style.oTransform))operaTransform = itemElement.style.oTransform + " scale(-1, 1);";
		else operaTransform =" scale(-1, 1);";
		if(!Object.isUndefined(itemElement.style.transform))othersTransform = itemElement.style.transform + " scale(-1, 1);";
		else othersTransform =" scale(-1, 1);";
		itemElement.setStyle("-moz-transform:" + mozillaTransform +
				"-ms-transform:" + microsoftTransform +
				"-webkit-transform:" + appleTransform +
				"-o-transform:" + operaTransform +
				"transform:" + othersTransform);
		
	},
	
	setFullFlip: function(itemElement){
		if(!Object.isUndefined(itemElement.style.mozTransform))mozillaTransform = itemElement.style.mozTransform + " scale(-1, -1);";
		else mozillaTransform = " scale(-1, -1);";
		if(!Object.isUndefined(itemElement.style.msTransform))microsoftTransform = itemElement.style.msTransform + " scale(-1, -1);";
		else microsoftTransform = " scale(-1, -1);";
		if(!Object.isUndefined(itemElement.style.webkitTransform))appleTransform = itemElement.style.webkitTransform + " scale(-1, -1);";
		else appleTransform = " scale(-1, -1);";
		if(!Object.isUndefined(itemElement.style.oTransform))operaTransform = itemElement.style.oTransform + " scale(-1, -1);";
		else operaTransform =" scale(-1, -1);";
		if(!Object.isUndefined(itemElement.style.transform))othersTransform = itemElement.style.transform + " scale(-1, -1);";
		else othersTransform =" scale(-1, -1);";
		itemElement.setStyle("-moz-transform:" + mozillaTransform +
				"-ms-transform:" + microsoftTransform +
				"-webkit-transform:" + appleTransform +
				"-o-transform:" + operaTransform +
				"transform:" + othersTransform);
		
	}
});

Action.playHide = Class.create({
	
	initialize: function(options) {
		try{
		    this.options = {
		    	item:   	'item'
		    };
		    
		    Object.extend(this.options, options || { });
		    this.hide(this.options.item);
		}
		catch(err){
			alert('playerObj: initialize error:' + console.log(err));
		}
	},
	
	hide: function(item){
		 $('Card'+cardsCollection.currentElement().id + 'cardObjects' + item.object).hide();
		 $('Card'+cardsCollection.currentElement().id + 'cardObjects' + item.object).isVisible = 0;
		 Try.these(function(){
			 var obj = $('Card'+cardsCollection.currentElement().id + 'cardObjects' + item.object);
			 /**FOR 20435*/
			 if(!obj.paused&&!obj.ended){
				 obj.pause();
				 obj.isPausedFromHideAction = true;
			 }
			 /**EOF*/
			}.bind(this));
		 if(typeof($('Card'+cardsCollection.currentElement().id + 'cardObjects' + item.object + '_image'))!='null'&&Object.isElement($('Card'+cardsCollection.currentElement().id + 'cardObjects' + item.object + '_image')))
			 $('Card'+cardsCollection.currentElement().id + 'cardObjects' + item.object + '_image').hide();
		
		 Action.finishAction(item.creator,item.priority);
	}
});

Action.playShow = Class.create({
	initialize: function(options) {
		try{
		    this.options = {
		    	item:   	'item'
		    };
		    
		    Object.extend(this.options, options || { });
		    this.show(this.options.item);
		}
		catch(err){
			alert('playerObj: initialize error:' + console.log(err));
		}
	},
	
	show: function(item){
	//	var el = $('Card'+cardsCollection.currentElement().id + 'cardObjects' + item.object);
		var obj = $('Card'+cardsCollection.currentElement().id + 'cardObjects' + item.object);
		obj.show();
		obj.isVisible = 1;
		/**FOR 20435*/
		Try.these(function(){
			if(obj.isPausedFromHideAction == true){
				obj.isPausedFromHideAction = false;
				obj.play();
			}
		}.bind(this));
		/**EOF*/
		if(typeof($('Card'+cardsCollection.currentElement().id + 'cardObjects' + item.object + '_image'))!='null'&&Object.isElement($('Card'+cardsCollection.currentElement().id + 'cardObjects' + item.object + '_image')))
			 $('Card'+cardsCollection.currentElement().id + 'cardObjects' + item.object + '_image').show();
		
		Action.finishAction(item.creator,item.priority);
	}
});

Action.playWebPage = Class.create({
	initialize: function(options) {
		try{
		    this.options = {
		    	item:   	'item'
		    };
		    
		    Object.extend(this.options, options || { });
		    this.openWebPage(this.options.item);
		}
		catch(err){
			alert('playerObj: initialize error:' + console.log(err));
		}
	},
	
	openWebPage: function(item){
		try{
			var w = window.open();
			if(typeof w == 'undefined') {
					alert('You have popup-blocker enabled in your browser. Please disable it to open ' + item.href);
					return;
			}
		    	w.opener = null;
		    	w.document.location = item.href;
			//window.open(item.href,"_blank");
		}
		catch(err){
			console.log(err);
		}
	}
});

Action.playSendMail = Class.create({
	initialize: function(options) {
		try{
		    this.options = { 
		    	item:   	'item'
		    };
		    
		    Object.extend(this.options, options || { });
		    this.addr = "";
		    this.subject = this.options.item.subject;
		    this.options.item.addresses.each(function(el){
		    	this.addr += el.email + ';';
		    }.bind(this));
		     
		    this.sendMail();
		}
		catch(err){
			alert('Action.playSendMail: initialize error:' + console.log(err));
		}
	},
	
	sendMail: function(item){
		try{
			var addr = this.addr;
			var subject = this.subject;
			var w = window.open();
			if(typeof w == 'undefined') {
					alert('You have popup-blocker enabled in your browser. Please disable it to send an email');
					return;
			}
		    	w.opener = null;
		    	w.document.location = "mailto:"+addr+"?subject="+subject+'&body=';
			//window.open(item.href,"_blank");
		    	setTimeout(function(){w.close();}.bind(this),1000);
		}
		catch(err){
			console.log(err);
		}
	}
});

Action.playPrintCard = Class.create({
	initialize: function(options) {
		try{
		    this.printCard();
		}
		catch(err){
			alert('playerObj: initialize error:' + console.log(err));
		}
	},
	
	printCard: function(){
		window.print();
	}
});

Action.playGhostWriter = Class.create({
	initialize: function(options) {
		try{
			this.options = {
			    	item:   	'item',
			    	data:		'data',
			    	speed: 		'speed',
			    	className: 	'gW'
			};
			   
			    Object.extend(this.options, options || { });
			    this.item = this.options.item;
			    this.contPane = $($(this.item).id + 'textPane');
			    /**without scrollbar fallback*/
			    /*   $(this.item).innerHTML = '';
			    	new Element('div',{
			    	id: $(this.options.item).id + 'textPane',
			    	style: 'position:relative;'
			    });
			    $(this.item).insert(this.contPane);*/
			    //  this.contPane.update(this.options.data);
			    //  console.log($(this.item).id);
			    //    play.textObjects[$(this.item).id]= new scrollBar({block:$(this.item),content:this.contPane});
			    //  this.contPane.update();
			    this.beforePointer = this.contPane.innerHTML;
			    this.data = this.transformGhostData(this.options.data);
			    /**FIXME:need to make this more beautifoul*/
			    if(this.data[0]=="|")this.data[0]="";
			    if(this.data[(this.data.length-1)]=="|")this.data[(this.data.length-1)]="";
			    /**EOF*/
			    this.ghostWrite(this.data,this.options.speed,this.options.className);
		}
		catch(err){
			alert('playerObj: initialize error:' + console.log(err));
		}
	},
	
	item: 	'',
	
	contPane: '', 
	
	pointer: 0,
	
	afterPointer: '',
	
	setPosition: function(pos){
		var tmpBeforePointer = (this.beforePointer+this.afterPointer).substr(0,this.beforePointer.length + pos);
		var tmpAfterPointer = (this.beforePointer+this.afterPointer).substr(tmpBeforePointer.length);
		this.beforePointer = tmpBeforePointer;
		this.afterPointer = tmpAfterPointer;
	},
	
	deleteSymbol: function(pos){
		var tmpBeforePointer = (this.beforePointer+this.afterPointer).substr(0,this.beforePointer.length + pos);
		var tmpAfterPointer = (this.beforePointer+this.afterPointer).substr(tmpBeforePointer.length - pos +1);
		this.beforePointer = tmpBeforePointer;
		this.afterPointer = tmpAfterPointer;
	},
	
	addSymbol: function(char){
		this.beforePointer = this.beforePointer + char;
	},
	
	erase: function(){
		//this.deleteSymbol(1); 
		this.contPane.update();
		this.beforePointer = '';
		this.afterPointer = '';
	},
	
	backspace: function(){
		this.deleteSymbol(-1);
	},
	
	moveLeft: function(){
		return this.setPosition(-1);
	}, 
	
	moveRight: function(){
		return this.setPosition(1);
	},
	
	changeSpeed:function(speed){
		speed = speed.gsub('|','');
		clearInterval(this.writeInterval);
		//console.log(speed);
		this.ghostWrite(this.data,speed);
	},
	
	updateContent: function(){
		$(this.contPane).style.cursor= 'url(data/engine/templates/img/bb.png), pointer';
		$(this.contPane).update(this.beforePointer + '<span style="text-decoration:blink;">|</span>' +  this.afterPointer);
		var newTop = $(this.item).getHeight() - $(this.contPane).getHeight();
		if(newTop>0)newTop=0;
		//play.textObjects[$(this.item).id].scroll('vertical',-newTop);
		$(this.contPane).setStyle({top: -newTop + 'px'});
	},
	
	transformGhostData: function(data){
		data = data.gsub('|{erase}|', ',|erase|,');
		data = data.gsub('|{backspace}|', ',|backspace|,');
		data = data.gsub('|{moveLeft}|', ',|moveLeft|,');
		data = data.gsub('|{moveRight}|', ',|moveRight|,');
		
		data = data.gsub('|{1}|', ',|10|,');
		data = data.gsub('|{2}|', ',|50|,');
		data = data.gsub('|{3}|', ',|100|,');
		data = data.gsub('|{4}|', ',|200|,');
		data = data.gsub('|{5}|', ',|500|,');
		data = data.gsub('|{6}|', ',|1000|,');
		data = data.gsub('|{7}|', ',|3000|,');
		//data = data.gsub('|{4}|', ',|moveRight|,');
		
		data = data.split(',');
		//console.log(data);
		var retData ='0';
		data.each(function(el){
			if(el !='|erase|' && el!='|backspace|'&&el!='|moveLeft|'&&el!='|moveRight|'&&el!='|10|'&&el!='|50|'&&el!='|100|'&&el!='|200|'&&el!='|500|'&&el!='|1000|'&&el!='|3000|') el = el.toArray();
			else el = new Array(el);
			if(retData!=0) /*retData = retData +el;*///
				retData.push(el);
			else retData = new Array(el);
		});
		//onsole.log(retData);
		
		return retData.flatten();
	},
	
	ghostWrite: function(data,speed,className){
		if(!speed) speed = 200;
		//console.log(speed);
		if(Object.isUndefined(this.i)) this.i = 0;
		//console.log(data);
		var countIterations = data.length;
		this.writeInterval = setInterval(function(el){
			//alert(this.i);
			if(data[this.i] == '|erase|') this.erase();
			else if (data[this.i] == '|backspace|') this.backspace();
			else if (data[this.i] == '|moveLeft|') this.moveLeft();
			else if (data[this.i] == '|moveRight|') this.moveRight();
			else if (data[this.i] == '|10|') this.changeSpeed(data[this.i]);
			else if (data[this.i] == '|50|') this.changeSpeed(data[this.i]);
			else if (data[this.i] == '|100|') this.changeSpeed(data[this.i]);
			else if (data[this.i] == '|200|') this.changeSpeed(data[this.i]);
			else if (data[this.i] == '|500|') this.changeSpeed(data[this.i]);
			else if (data[this.i] == '|1000|') this.changeSpeed(data[this.i]);
			else if (data[this.i] == '|3000|') this.changeSpeed(data[this.i]);
			else this.addSymbol(data[this.i]);
			
			this.i++;
			if(this.i>=countIterations) clearInterval(this.writeInterval);
			this.updateContent();
		}.bind(this),speed);
	}
});


Action.playTextMover = Class.create({
	initialize: function(options) {
		try{
			this.options = {
					source:		'source',
			    	item:   	'item',
			    	mode:		'copy',
			    	insertPos:	'bottom'
			};
			    Object.extend(this.options, options || { });
			    /**defining elements and text containers*/
			    this.item = this.options.item;
			    this.source = this.options.source;
			    $(this.item).innerHTML = '';
			    this.itemContPane = $($(this.options.item).id + 'textPane');
			    this.sourceContPane = $($(this.options.source).id + 'textPane');
			    /**eof*/
			    /**launching textMover*/
			    this.playTextMover();
			    /**eof*/
		}
		catch(err){
			alert('playerObj: initialize error:' + console.log(err));
		}
	},
	
	item: {},
	
	source: {},
	
	itemContPane: {},
	
	sourceContPane: {},
	
	data: '',
	
	getData:	function(dataEl){
		this.data = dataEl.innnerHTML;
		if (this.options.mode == 'move') this.clearData(dataEl);
	},
	
	clearData: function(dataEl){
		$(dataEl).update();
	},
	
	insertData: function(){
		switch(this.options.insertPos){
		
			case 'end':
				$(this.sourceContPane).insert(this.data);
			break;
			
			case 'replace':
				$(this.sourceContPane).update(this.data);
			break;
		}
	},
	
	playTextMover: function(){
		this.getData(this.sourceContPane);	
		this.insertData();
		return true;
	}
});

Action.playRollCredits = Class.create({
	initialize: function(options) {
		try{
			this.options = {
			    	item:   	'item',
			    	mode:		'pixels',
			    	nOfPixels:	'3',
			    	nOfSteps:	'0',
			    	speed:		'10',
			    	direction:	'0' //0 - vertical; 1-horyzontal
			};
			//console.log(this.options);
			    Object.extend(this.options, options || { });
			    if(Object.isUndefined(Action.rollCredits))Action.rollCredits=[];
			    /**defining elements and text containers*/
			    this.item = this.options.item;
			    this.itemContPane = $($(this.options.item).id + 'textPane');
			    /**eof*/
			    /**launching rollCredits*/
			    if(!Object.isUndefined(Action.rollCredits[this.options.item])){
			    	//alert('hi');
			    	/*this.observeInterval = setInterval(function(){
			    		if(Object.isUndefined(Action.rollCredits[this.options.item])){*/
			    			
			    			clearInterval(Action.rollCredits[this.options.item].inter);
			    			
			    			$(this.item).scrollTop = 0;
			    			$(this.item).scrollLeft = 0;
					    	this.playRollCredits();
					    	Action.rollCredits[this.options.item] = this;
					    	
			    	/*	}
			    	}.bind(this),500);*/
			    }
			    else this.playRollCredits();
			    /**eof*/
			    Action.rollCredits[this.options.item] = this;
		}
		catch(err){
			alert('playerObj: initialize error:' + console.log(err));
		}
	},
	
	item: {},
	
	itemContPane: {},
	
	transformOptions: function(){
		try{
			var ops = {};
			if(this.options.mode != 0){
				ops.nOfPixels = Math.round(parseInt($(this.item).getStyle('lineHeight') / 33.3 * parseInt(this.options.speed)));
			}
			else ops.nOfPixels = parseInt(this.options.nOfPixels) / 33.3 * this.options.speed;
			if(ops.nOfPixels<1) ops.nOfPixels = 1;
			else ops.nOfPixels = Math.round(ops.nOfPixels);
			
			if(this.options.nOfSteps == 0) {
				ops.nOfSteps = Math.round($(this.itemContPane).getHeight() / ops.nOfPixels);
			}
			else ops.nOfSteps = (this.options.nOfSteps * 33.3) / this.options.speed;
			ops.speed = this.options.speed;
			ops.direction = this.options.direction;
			return ops;
		}
		catch(err){
			alert('error in rollCredits.transformOptions'+ console.log(err));
		}
	},
	
	rollVertical: function(ops){
		if(!Object.isElement($(this.item))){
			clearInterval(this.inter);
			return;
		}
		//console.log(ops.nOfPixels);
		$(this.item).scrollTop +=ops.nOfPixels;
		//play.textObjects[$(this.item).id].scroller('vertical', ops.nOfPixels);
	},
	
	rollHorizontal: function(ops){
		$(this.item).scrollLeft +=ops.nOfPixels;
		//play.textObjects[$(this.item).id].scrollBy('horizontal',ops.nOfPixels);
	},
	
	playRollCredits: function(){
		try{
			var ops = this.transformOptions();
			var i = 0;
			if(ops.direction == 0) {
				
				this.inter = setInterval(function(){
					this.rollVertical(ops);
					++i;
					if(i>=ops.nOfSteps) {
						clearInterval(this.inter);
						delete Action.rollCredits[this.options.item];
					}
					}.bind(this),33);
				}
			else {
				
				this.inter = setInterval(function(){
					this.rollHorizontal(ops);
					i++;
					if(i>=ops.nOfSteps) {
						clearInterval(this.inter);
						delete Action.rollCredits[this.options.item];
					}
					}.bind(this),33);
				}
		}
		catch(err){
			alert('error in rollCredits.playRollCredits'+ console.log(err));
		}
	}
});

Action.playShowMessage = Class.create({
	initialize: function(options) {
		try{
			this.options = {
					source:		'source',
					icon:		'/templates/img/ui/trashBox.png',
			    	text:   	'item',
			    	buttonText:		'copy'
			};
			    Object.extend(this.options, options || { });
			    /**defining elements*/
			    this.icon = this.options.icon;
			    this.text = this.options.text;
			    this.buttonText = this.options.buttonText;
			    /**eof*/
			    /**launching showMessage*/
			    this.playShowMessage();
			    /**eof*/
		}
		catch(err){
			alert('playerObj: initialize error:' + console.log(err));
		}
	},
	
	
	playShowMessage: function(){	
		return new messageCreate({image:this.icon,text:this.text,caption:this.buttonText});
	}
});

Action.playScrollCard = Class.create({
	initialize: function(options) {
		try{
			this.options = {
					xCoord:		'100',
					yCoord:		'100',
					creator:	'creator',
					duration:	'1.0'
			    	
			};
			    Object.extend(this.options, options || { });
			    /**defining elements*/
			    this.xCoord = this.options.xCoord;
			    this.yCoord = this.options.yCoord;
			    /**eof*/
			    /**launching showMessage*/
			    this.playScrollCard();
			    /**eof*/
		}
		catch(err){
			alert('playerObj: initialize error:' + console.log(err));
		}
	},
	
	createElement: function(){
		var element = new Element('div',{
			style:	"width:1px;" +
					"height:1px;" +
					"position:absolute;" +
					"top:"+ this.yCoord + "px;" +
					"left:"+ this.xCoord + "px;" +
					"overflow:hidden;" +
					"z-index:99999;" +
					"background:transparent",
			id:"scrollDiv"+ this.options.creator + Math.random()
		});
		this.object = element;
		document.body.insert(element);
		return element;
	},
	
	playScrollCard: function(){
		var element = this.createElement();
		//console.log(this.xCoord+","+this.yCoord);
		new Effect.ScrollTo($(element),{duration:this.options.duration});
		setTimeout(function(){ 
			document.body.removeChild(this.object);
		}.bind(this),this.options.duration*1000);
		
		return true;
	}
});

Action.playSequenceAnimation = Class.create({
	
	initialize: function(options) {
		try{
			this.options = {
					imgElement: $('imgElement'),
					imagesTemplate:		Array(),
					imagesCount: 10,
					info: {},
					fps: 25
			};
			    Object.extend(this.options, options || { });
			    this.playing = false;
			    this.imgInterval = {};
			    this.counter = 0;
			    this.imgElement = this.options.imgElement;
			    this.imagesCount = this.options.imagesTemplate.length;
			    this.template = new Template(prefix + this.options.imagesTemplate);
			    this.images = Array();
			    
			    this.options.imagesTemplate.each(function(el){
			    	this.images.push(prefix + el.src); 
			    }.bind(this));
			  
			 this.startSequence();
		}
		catch(err){
			console.log(err);
		}
	},
	
	
	startSequence: function(){
		try{
			//	if(play.options.test)	console.log($(this.imgElement));
			//	return $(this.imgElement);
			
		}
		catch(err){
			console.log(err);
		}
		
	},
	
	playSequence: function(){
		this.playing = true;
		var i =this.counter + 1;
		this.imgInterval = setInterval(function(){
			if(!$(this.imgElement.id)||$(this.imgElement.id)=='undefined'||$(this.imgElement.id)=='null') {
				
				this.stopSequence();
			}
			else{
				if(i>(this.imagesCount-1)) i = 0;
				$(this.imgElement.id).src = this.images[i]; 
				i++;
			}
			
		}.bind(this),(1000/this.options.fps));
	},
	
	
	stopSequence: function(){
		this.playing = false;
		clearInterval(this.imgInterval);
		this.counter = 0;
	},
	
	pauseSequence: function(){
		this.playing = false;
		clearInterval(this.imgInterval);
	},
	
	play: function(){
		return this.playSequence();
	},
	
	stop: function(){
		return this.stopSequence();
	},
	
	pause: function(){
		return this.pauseSequence();
	},
	
	nextFrame: function(){
		++this.counter;
		$(this.imgElement.id).src = this.images[this.counter]; 
	}
});

Action.playMovieController = Class.create({
	initialize: function(options) {
		try{
		    this.options = {
		    	item:   	{}
		    };
		    
		    Object.extend(this.options, options || { });
		    this.playMovieController(this.options.item);
		}
		catch(err){
			console.log(err);
		}
	},
	playMovieController: function(item){
		try{
			var itemId = play.template.newCardElementId(cardsCollection.currentElement().id,item.object);
			$(itemId).controls=true;
			return true;
		}
		catch(err){
			console.log(err);
		}
	}
	
});

Action.playHideCursor = Class.create({
	initialize: function(options) {
		try{
		    this.options = {
		    	mode:   	'hide'
		    };
		    
		    Object.extend(this.options, options || { });
		    switch(this.options.mode){
		    	case "hide":
		    		this.hideCursor();
		    	break;
		    	
		    	case "show":
		    		this.showCursor();
		    	break;
		    	
		    	case "hideUntil":
		    		this.hideUntilMoved();
		    	break;
		    }
		   
		}
		catch(err){
			alert('playerObj: initialize error:' + console.log(err));
		}
	},
	
	hideCursor: function(){
		if(!Object.isElement($('cursorShield')))document.body.insert(this.createShield());
		$('cursorShield').setStyle({ 
			cursor: this.returnEmptyCursor()
		});
		document.body.setStyle({ 
			cursor: this.returnEmptyCursor()
		}); 
	},
	
	createShield: function(){
		return new Element("div",{id:"cursorShield",style:	"position:absolute;" +
															"z-index:99999;top:0px;" +
															"left:0px;height:100%;" +
															"width:100%;"});
	},
	
	showCursor: function(){
		try{
			if(Object.isElement($('cursorShield')))document.body.removeChild($('cursorShield'));
			document.body.setStyle({ 
				cursor: "default"
			}); 
		}
		catch(err){
			console.log(err);
		}
	},
	
	hideUntilMoved: function(){
		if(!Object.isElement($('cursorShield')))document.body.insert(this.createShield());
		document.body.setStyle({ 
			cursor: this.returnEmptyCursor()
		}); 
		$('cursorShield').setStyle({ 
			cursor: this.returnEmptyCursor()
		});
		this.bindObserverFunction = this.observerFunction.bindAsEventListener(this);
		document.observe("mousemove",this.bindObserverFunction);
	},
	
	returnEmptyCursor: function(){
		return "url("+/*prefix+*/"data/engine/templates/img/empty.cur), default !important";
	},
	
	observerFunction: function(){
		document.stopObserving("mousemove",this.bindObserverFunction);
		if(Object.isElement($('cursorShield')))document.body.removeChild($('cursorShield'));
		this.showCursor();
		delete this;
	}
});

Action.playCardShuffler = Class.create({
	initialize: function(options) {
		try{
		    this.shuffleCards();
		}
		catch(err){
			alert('playerObj: initialize error:' + console.log(err));
		}
	},
	
	shuffleCards: function(){
		cardsCollection.shuffleElements();
	}
});

Action.playMoveToFront = Class.create({
	initialize: function(options) {
		try{
		    this.options = {
		    	item:   	'item'
		    };
		    
		    Object.extend(this.options, options || { });
		    this.moveToFront(this.options.item);
		}
		catch(err){
			alert('playerObj: initialize error:' + console.log(err));
		}
	},
	
	moveToFront: function(item){
		$('Card'+cardsCollection.currentElement().id + 'cardObjects' + item.object).setStyle({
			zIndex: 999
		});
		if(Object.isElement($('Card'+cardsCollection.currentElement().id + 'cardObjects' + item.object + '_image'))){
			$('Card'+cardsCollection.currentElement().id + 'cardObjects' + item.object + '_image').setStyle({
				zIndex: 998
			});
		}
		
	}
});

Action.playClearChangeFlag = Class.create({
	initialize: function() {
		try{
		    play.clearChangeFlag = true;
		}
		catch(err){
			alert('playerObj: action clearChangeFlag error error:' + console.log(err));
		}
	}
});

Action.playKeyMapper = Class.create({
	initialize: function(options) {
		try{
		    this.options = {
		    	items:   	'item'
		    };
		    
		    Object.extend(this.options, options || { });
			this.options.items.each(function(item){
				this.mapKey(item);
			}.bind(this));
		    
		}
		catch(err){
			alert('playerObj: initialize error:' + console.log(err));
		}
	},
	
	getKeyCode: function(key){
		switch(key){
			
			case "0": 	
				return 48;
			break;
			
			case "1": 	
				return 49;
			break;
			
			case "2": 	
				return 50;
			break;
			
			case "3": 	
				return 51;
			break;
			
			case "4": 	
				return 52;
			break;
			
			case "5": 	
				return 53;
			break;
			
			case "6": 	
				return 54;
			break;
			
			case "7": 	
				return 55;
			break;
			
			case "8": 	
				return 56;
			break;
			
			case "9": 	
				return 57;
			break;
			
			case "a": 	
				return 65;
			break;
			
			case "b": 	
				return 66;
			break;
			
			case "c": 	
				return 67;
			break;
			
			case "d": 	
				return 68;
			break;
			
			case "e": 	
				return 69;
			break;
			
			case "f": 	
				return 70;
			break;
			
			case "g": 	
				return 71;
			break;
			
			case "h": 	
				return 72;
			break;
			
			case "i": 	
				return 73;
			break;
			
			case "j": 	
				return 74;
			break;
			
			case "k": 	
				return 75;
			break;
			
			case "l": 	
				return 76;
			break;
			
			case "m": 	
				return 77;
			break;
			
			case "n": 	
				return 78;
			break;
			
			case "o": 	
				return 79;
			break;
			
			case "p": 	
				return 80;
			break;
			
			case "q": 	
				return 81;
			break;
			
			case "r": 	
				return 82;
			break;
			
			case "s": 	
				return 83;
			break;
			
			case "t": 	
				return 84;
			break;
			
			case "u": 	
				return 85;
			break;
			
			case "v": 	
				return 86;
			break;
			
			case "w": 	
				return 87;
			break;
			
			case "x": 	
				return 88;
			break;
			
			case "y": 	
				return 89;
			break;
			
			case "z": 	
				return 90;
			break;
			
			/*f-keys*/
			case "f1": 	
				return  112;
			break;
			
			case "f2": 	
				return  113;
			break;
			
			case "f3": 	
				return  114;
			break;
				
			case "f4": 	
				return  115;
			break;
				
			case "f5": 	
				return  116;
			break;
				
			case "f6": 	
				return  117;
			break;
				
			case "f7": 	
				return  118;
			break;
				
			case "f8 ": 	
				return 	119;
			break;
				
			case "f9": 	
				return  120;
			break;
				
			case "f10": 	
				return  121;
			break;
				 
			case "f11": 	
				return  122;
			break;
			
			case "f12": 	
				return  123;
			break;
			
			/**others*
			 */
			case "enter":
				return 13;
			break;
			
			case "escape":
				return 27;
			break;
			
			case "space":
				return 27;
			break;
		}
	},
	
	mapKey: function(item){
		var mappedCode = this.getKeyCode(item.HSKeyMapperActionCharacterKey);
		document.observe("keydown",function(e){
		//	console.log(e);
			var charCode = (e.which) ? e.which : e.keyCode;
		//	console.log(item.HSKeyMapperActionObjectUIDKey);
			if(mappedCode == charCode){
				var actionButton = $(play.template.newCardElementId(cardsCollection.currentElement().id,item.HSKeyMapperActionObjectUIDKey));
					actionButton.setAttribute("isfromaction", 1);
					actionButton.click();
					actionButton.setAttribute("isfromaction", 0);
			}
			
		}.bind(this));

	}
});

Action.playButtonLister = Class.create({
	initialize: function(options) {
		try{
			this.options = {
			    	item:   	'item'
			    };
			Object.extend(this.options, options || { });
		    this.run();
		}
		catch(err){
			alert('Action.playButtonLister: initialize error:' + console.log(err));
		}
	},
	
	run: function(){
		this.hideCursor();
		this.switchButtons("forward");
		this.setObservers();
	},
	
	hideCursor: function(){
		new Action.playHideCursor({mode:"hide"});
	},
	
	highlightButton: function(button){
		setTimeout(function(){$(button).setOpacity(0.3);}.bind(this),50);
	},
	
	removeHighlightButton: function(button){
		$(button).setOpacity(0);
	},
	
	setPointer:function(dir){
		var cnt = this.options.item.objects.length;
		if(Object.isUndefined(this.pointer)){
			this.pointer =0;
		}
		else {
			(dir=="forward")?this.pointer++:this.pointer--;
		}
		if(this.pointer>=cnt) this.pointer=0;
		if(this.pointer<0) this.pointer = --cnt;
	},
	
	switchButtons:function(dir){
		
		if(!Object.isUndefined(this.activeButton)) this.removeHighlightButton(this.activeButton);
		this.setPointer(dir);
		this.activeButton = $(play.template.newCardElementId(cardsCollection.currentElement().id,this.options.item.objects[this.pointer].id));
		this.highlightButton(this.activeButton);
		this.timeout = setTimeout(function(){
			this.activeButton.setAttribute("isfromaction", 1);
			$(this.activeButton).click();
			this.activeButton.setAttribute("isfromaction", 0);
			delete this.timeout;
		}.bind(this),this.options.item.timer*1000);
	},
	
	setObservers:function(){
		document.observe("keypress",function(e){
			//console.log(e);
			e.preventDefault();
			e.stop();
			var charCode = (e.which) ? e.which : e.keyCode;
			if(charCode == play.help.getKeyCode("1")||charCode == play.help.getKeyCode("space")){
				if(!Object.isUndefined(this.timeout))clearTimeout(this.timeout);
				this.switchButtons("forward");
			}
			else if(charCode == play.help.getKeyCode("2")){
				if(!Object.isUndefined(this.timeout))clearTimeout(this.timeout);
				this.switchButtons("backward");
			}
			else if(charCode == play.help.getKeyCode("escape")||charCode == play.help.getKeyCode("del")){
				this.destruct();
			}
		}.bind(this));
		
	},
	
	destruct:function(){
		document.stopObserving("keypress");
		this.removeHighlightButton(this.activeButton);
		new Action.playHideCursor({mode:"show"});
		delete this;
	}
});

Action.playButtonScanner = Class.create({
	initialize: function(options) {
		try{
			this.options = {
			    	item:   	'item'
			    };
			    
			Object.extend(this.options, options || { });
			this.options.item.objects = [];
			cardsCollection.currentElement().objects.each(function(el){
				if(el.type=="button") this.options.item.objects.push(el);
			}.bind(this));
			
			this.run();
		}
		catch(err){
			alert('Action.playButtonScanner: initialize error:' + console.log(err));
		}
	},
	
	run: function(){
		if(this.options.hideCursor==1)this.hideCursor();
		this.interval = setInterval(function(){
			this.switchButtons();
		}.bind(this),this.options.item.scanDelay*1000);
		this.setObservers();
	},
	
	hideCursor: function(){
		new Action.playHideCursor({mode:"hideUntil"});
	},
	
	highlightButton: function(button){
		button.setOpacity(0.3);
	},
	removeHighlightButton: function(button){
		$(button).setOpacity(0);
	},
	
	setPointer:function(){
		var cnt = this.options.item.objects.length;
		if(Object.isUndefined(this.pointer)){
			this.pointer =0;
		}
		else {
			this.pointer--;
		}
		if(this.pointer>=cnt) this.pointer=0;
		if(this.pointer<0) this.pointer = --cnt;
	},
	
	switchButtons:function(){
		if(!Object.isUndefined(this.activeButton)) this.removeHighlightButton(this.activeButton);
		this.setPointer();
		this.activeButton = $(play.template.newCardElementId(cardsCollection.currentElement().id,this.options.item.objects[this.pointer].id));
		this.highlightButton(this.activeButton);
		
	},
	
	setObservers:function(){
		document.observe("keypress",function(e){
			e.preventDefault();
			e.stop();
			var charCode = (e.which) ? e.which : e.keyCode;
			if(charCode == play.help.getKeyCode("enter")||charCode == play.help.getKeyCode("space")){
				this.activeButton.setAttribute("isfromaction", 1);
				$(this.activeButton).click();
				this.activeButton.setAttribute("isfromaction", 0);
				this.destruct();
			}
			else if(charCode == play.help.getKeyCode("escape")){
				this.destruct();
			}
		}.bind(this));
		
	},
	
	destruct:function(){
		clearInterval(this.interval);
		document.stopObserving("keypress");
		this.removeHighlightButton(this.activeButton);
		new Action.playHideCursor({mode:"show"});
		delete this;
	}
});




Action.playButtonStepper = Class.create({
	initialize: function(options) {
		try{
			this.options = {
			    	item:   	'item'
			    };
			Object.extend(this.options, options || { });
		    this.run();
		}
		catch(err){
			alert('Action.playButtonLister: initialize error:' + console.log(err));
		}
	},
	
	run: function(){
		this.hideCursor();
		this.switchButtons("forward");
		this.setObservers();
	},
	
	hideCursor: function(){
		new Action.playHideCursor({mode:"hide"});
	},
	
	highlightButton: function(button){
		this.hightlightInt = setInterval(function(){
			if($(button).getOpacity!=0.3)$(button).setOpacity(0.3);
		}.bind(this),33);
		//setTimeout(function(){$(button).setOpacity(0.3);}.bind(this),70);
	},
	
	removeHighlightButton: function(button){
		$(button).setOpacity(0);
		clearInterval(this.hightlightInt);
	},
	
	setPointer:function(dir){
		var cnt = this.options.item.objects.length;
		if(Object.isUndefined(this.pointer)){
			this.pointer =0;
		}
		else {
			(dir=="forward")?this.pointer++:this.pointer--;
		}
		if(this.pointer>=cnt) this.pointer=0;
		if(this.pointer<0) this.pointer = --cnt;
	},
	
	switchButtons:function(dir){
		
		if(!Object.isUndefined(this.activeButton)) this.removeHighlightButton(this.activeButton);
		this.setPointer(dir);
		this.activeButton = $(play.template.newCardElementId(cardsCollection.currentElement().id,this.options.item.objects[this.pointer].id));
		this.highlightButton(this.activeButton);
		
	},
	
	setObservers:function(){
		this.mouseObserver = this.observeMouseEvent.bindAsEventListener(this);
		document.observe("mousedown",this.mouseObserver);
		
		document.observe("keypress",function(e){
			e.preventDefault();
			e.stop();
			var charCode = (e.which) ? e.which : e.keyCode;
			if(charCode == play.help.getKeyCode("1")||charCode == play.help.getKeyCode("space")){
				if(!Object.isUndefined(this.timeout))clearTimeout(this.timeout);
				this.switchButtons("forward");
			}
			else if(charCode == play.help.getKeyCode("2")){
				if(!Object.isUndefined(this.timeout))clearTimeout(this.timeout);
				this.switchButtons("backward");
			}
			else if(charCode == play.help.getKeyCode("enter")){
				this.activeButton.setAttribute("isfromaction", 1);
				$(this.activeButton).click();
				this.activeButton.setAttribute("isfromaction", 0);
			}
			else if(charCode == play.help.getKeyCode("escape")||charCode == play.help.getKeyCode("del")){
				this.destruct();
			}
		}.bind(this));
		
	},
	
	observeMouseEvent: function(){
		this.activeButton.setAttribute("isfromaction", 1);
		$(this.activeButton).click();
		this.activeButton.setAttribute("isfromaction", 0);
	},
	
	destruct:function(){
		document.stopObserving("keypress");
		document.stopObserving("mousedown",this.mouseObserver);
		this.removeHighlightButton(this.activeButton);
		new Action.playHideCursor({mode:"show"});
		delete this;
	}
});

Action.playSequencer = Class.create({
	initialize: function(options) {
		try{
			this.options = {
			    	items:   	'item'
			};
			Object.extend(this.options, options || { });
			this.timeouts = {};
		    this.run();
		}
		catch(err){
			alert('Action.playSequencer: initialize error:' + console.log(err));
		}
	},
	
	run: function(){
		this.options.items.each(function(el){
			this.addToSequence(el);
		}.bind(this));
	},
	
	addToSequence: function(el){
		this.timeouts[el.id]= setTimeout(function(){
			$(play.template.newElementId(cardsCollection.currentElement().id,el.id)).click();
			delete this.timeouts[el.id];
		}.bind(this),el.delay);
	}
});


Action.playTextCompare = Class.create({
	initialize: function(options) {
		try{
			this.options = {
			    	item:   	'item'
			};
			Object.extend(this.options, options || { });
			this.run();
		}
		catch(err){
			alert('Action.playTextCompare: initialize error:' + console.log(err));
		}
	},
	
	run: function(){
		this.firstText = this.getText(this.options.first);
		this.secondText = (this.options.mode=="custom")?this.options.customText:this.getText(this.options.last);
		if(this.firstText == this.secondText) this.activateElement(this.options.activateIf);
		else this.activateElement(this.options.activateElse);
	},
	
	getText:function(){
		return $(play.template.newElementId(cardsCollection.currentElement().id,el.id)).firstDescendant().innerHTML;
	},
	
	activateElement: function(el){
		$(play.template.newElementId(cardsCollection.currentElement().id,el.id)).click();
	}
});


Action.playTextMover = Class.create({
	initialize: function(options) {
		try{
			this.options = {
			    	item:   	'item'
			};
			Object.extend(this.options, options || { });
			this.run();
		}
		catch(err){
			alert('Action.playTextMover: initialize error:' + console.log(err));
		}
	},
	
	run: function(){
		this.firstText = this.getText(this.options.first.id);
		this.secondText = (this.options.mode=="custom")?this.options.customText:this.getText(this.options.last.id);
		
		if(this.options.first.mode == "move") this.eraseText(this.options.first.id);
		
		switch(this.options.second.mode){
		
			case "replace":
				this.replaceText(this.options.second.id,this.firstText);
			break;
				
			case "append":
				this.appendText(this.options.second.id,this.firstText);
			break;
			
			case "cursor":
				this.cursor(this.options.second.id,this.firstText);
			break;
			
		}
		
		if(this.firstText == this.secondText) this.activateElement(this.options.activateIf);
		else this.activateElement(this.options.activateElse);
	},
	
	getText:function(el){
		return $(play.template.newElementId(cardsCollection.currentElement().id,el)).firstDescendant().innerHTML;
	},
	
	eraseText: function(el){
		return $(play.template.newElementId(cardsCollection.currentElement().id,el)).firstDescendant().update("");
	},
	
	appendText: function(el,text){
		return $(play.template.newElementId(cardsCollection.currentElement().id,el)).firstDescendant().insert(text);
	},
	
	replaceText:function(el,text){
		this.eraseText(el);
		this.appendText(el,text);
		return true;
	},
	
	cursor: function(el,text){
		 
	}
});



Action.playPictureShow = Class.create({
	initialize: function(options) {
		try{
			this.options = {
			    	item:   	'item'
			};
			Object.extend(this.options, options || { });
			this.counter = 0;
			this.run();
		}
		catch(err){
			alert('Action.playPictureShow: initialize error:' + console.log(err));
		}
	},
	
	run: function(){
		this.showImage();
		
	},
	
	showImage: function(){
		var img = this.getImage(this.counter);
		img.observe("load",function(){
			if(!Object.isUndefined(this.img))document.body.removeChild(this.img);
			this.img = img;
			this.insertElement();
			this.addTimeout();
		}.bind(this));
	},
	
	getElement: function(id){
		var img= new Image();
		img.src = prefix + this.options.item.elements[id];
		this.preloadImage(id);
		return img;
	},
	
	preloadImage: function(id){
		var img= new Image();
		img.src = prefix + this.options.item.elements[++id];
	},
	
	insertElement: function(){
		document.body.insert(this.img);
	},
	
	addTimeout: function(){
		this.timeout = setTimeout(function(){
			this.counter++;
			this.showImage();
		}.bind(this),this.options.item.timeout*1000);
	}
});

