/*

Clock

*/        
Proto.UI.Clock = Class.create({
       	
       	topClock:false,
       	dragClockH:false,
       	dragClockM:false,
       	roth:0,
       	rotm:0,
       	dotch:true,
       	typing:false,
        initialize: function() 
        {
                      
        	this.options = Object.extend({
        	
                renderTo:document.body,
                ClockRadius:70,
                backgroundColor:"#ffffff",
                borderColor:"#000000",
                hourHandColor:"#000000",
                tagColor:"#000000",
                minuteHandColor:"#000000",
                secondHandColor:"#000000",
                showDiditClock:true,
                digitClockColor:"#00ff00",
                digitClockFont:"Arial",
                digitClockBg:"90-#101010-#505050:50-#101010",
                logoText:"",
                logoColor:"#000",
                logoFont:"Arial",
                digits:["I","II","III","IV","V","VI","VII","IIX","IX","X","XI","XII"],
                digitsColor:"#000000",
                digitsFont:"Arial",
                hourInput:false,
                minuteInput:false,
                comboInput:false,
                adjustable:true,
                initTime:false,
                minuteRound:1,
                timeOffset:0-new Date().getTimezoneOffset() / 60,
                calendar:false
                
                }, arguments[0] || { });
                
                this.r = this.options.ClockRadius;
                
                this.render();
                
                if(!this.options.initTime&&!this.options.calendar)
                {
                	this.setTime();this.startClock();
                }
                else
                {
                	this.dotch=true;
                	if(!this.options.calendar)
                	{
                		this.setTime(this.options.initTime);
                	}
                	else
                	{
                		if(this.options.calendar.options.field.value!="")
                		{
                		this.options.initTime=this.options.calendar.parseString(this.options.calendar.options.field.value);
                	//	alert(this.options.initTime+"\n"+this.options.calendar.options.field.value)
                		this.setTime(this.options.initTime);
                		}
                	}
                	this.c.hide();
                }
                
                if(this.options.comboInput&&false)
                {
                
                	this.options.comboInput.observe("keyup",function(){
                    if(this.typingtime)
                    {
                        window.clearTimeout(this.typingtime);
                    }
                    this.typingtime = this.stopTyping.bind(this).delay(1);
                }.bind(this));
               
                }
                
          },
         weelhandler:function(e)
        {
        
            window.clearTimeout(this.tmr);
           
           Event.stop(e);
            if(this.process){return;}
            var raw = e.detail ? e.detail : e.wheelDelta;
            
            if(Prototype.Browser.Gecko)
            {
            axis=((e.axis!=1)?"v":"h");
            }
            else
            {
            axis=((e.wheelDeltaY!=0)?"v":"h");
            }
            var sotn=((axis=="h")?this.hsotn:this.vsotn);
            var d = parseDateString(this.options.comboInput.value);
            this.fillInputs(d.getHours(), d.getMinutes()+1);
           if(axis == "v")
           {
            if(Prototype.Browser.WebKit)
            {
            if(raw <0){
            d.setMinutes(Number(d.getMinutes())+1);
            }else{
            d.setMinutes(Number(d.getMinutes())-1);
            }
            
            }else{
            if(raw <0){
            d.setMinutes(Number(d.getMinutes())-1);
            }else{
            d.setMinutes(Number(d.getMinutes())+1);
            }
               
            }
            this.tmr = this.weeltime(d);
            }
 
        },
        weeltime:function(d){
        this.noanimate=true;
        this.setTime(d);
        this.noanimate=false;
        },
         stopTyping:function(){
         if(this.dragClockH || this.dragClockM || this.options.comboInput.value==""){ return; }
         if(this.dly)
                    {
                        window.clearTimeout(this.dly);
                    }
                    
	                			var rg1 = /:.*$/;
                			var rg2 = /.*:/;
                			var rg3 = /^.* /;
                			var tm = this.options.comboInput.value.replace(rg3,"");
                			
                			var h = Number(tm.replace(rg1,""));
                			var m = Number(tm.replace(rg2,""));
                			
                			if(isNaN(h)){h=0;}if(isNaN(m)){m=0;}
                			var d = new Date();
                			d.setHours(h);
                			d.setMinutes(m);
                			if(this.options.calendar)
							{
								this.options.calendar.date.setHours(d.getHours());
								this.options.calendar.date.setMinutes(d.getMinutes());
								
							}
                			this.dly = this.setTime.bind(this).delay(0.5,d);
         },
          clickAngle:function (pnt, coord)
          {

				var c_x = coord.width/2;
				var c_y = coord.height/2;
				var pagescroll={top:((document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop),left:((document.documentElement.scrollLeft) ? document.documentElement.scrollLeft : document.body.scrollLeft)};
		        var x = pnt.x - pagescroll.left  - coord.left;
				var y = pnt.y - pagescroll.top  - coord.top;
				var t_x = c_x;
				var t_y = y;
				var CA = t_x - x;
				var CO = t_y - c_y;
				var AO = Math.sqrt(Math.pow(CA, 2) + Math.pow(CO, 2));
				var ang = Math.round((Math.acos((Math.pow(Math.abs(CA), 2) - Math.pow(Math.abs(AO), 2) - Math.pow(CO, 2))/(2 * CO * AO))) * 180/Math.PI);
				if (x < c_x) ang = 360 - ang;
				return ang;

		},
		setTime:function(date)
		{
				if(date!="" && date){
					var t = new Date(date.getFullYear(),date.getMonth(),date.getDate(),date.getHours(),date.getMinutes(),date.getSeconds());
        		}else{var t = new Date();}
				t.setHours(t.getHours() + this.options.timeOffset + (new Date().getTimezoneOffset() / 60));
				this.ticTack(t.getHours(),t.getMinutes(),t.getSeconds());
				this.fillInputs(t.getHours(),t.getMinutes());
				if(this.options.calendar)
				{
					this.options.calendar.date.setHours(t.getHours());
					this.options.calendar.date.setMinutes(t.getMinutes());
					
				}
				
		},
		fillInputs:function(h,m)
		{
					
					hv=h.toPaddedString(2);
    				hm=m.toPaddedString(2);
					        if(this.options.hourInput)
					        {
					        	this.options.hourInput.value = hv;
					        }
					        if(this.options.minuteInput)
					        {
					        	this.options.minuteInput.value = hm;
					        }
					        if(this.options.comboInput)
					        {
					        	
                				
                								if(this.options.calendar)
												{
													this.options.calendar.options.field.value=this.options.calendar.date.myformat(this.options.calendar.options.format);
													
												}
												else
												{
													var rg = / .*/;
                									tm = this.options.comboInput.value.replace(rg,"");
                									this.options.comboInput.value = tm+" "+hv+":"+hm;
												}
					        }		
		},
		startClock:function()
		{
			new PeriodicalExecuter(function(pe) { 
				if(this.stopClock){pe.stop();}
				
				var date = new Date();
				date.setHours(date.getHours())
				this.setTime(date);
			 }.bind(this), 1);		
		},
		ticTack:function(h,m,s){
				this.fillInputs(h,m);
				if(s==0 || this.noanimate){
				this.c.rotate(s*6,this.r,this.r);
				}else{
				this.c.animate({rotation:s*6+", "+this.r+", "+this.r}, 200, "elastic");
				}
				this.roth = (h+(m/60))*30;
				if(this.noanimate){
				this.h.rotate(this.roth,this.r,this.r);
				}else{
				this.h.animate({rotation:this.roth+", "+this.r+", "+this.r}, 200, "elastic");
				}
				
				hv=h.toPaddedString(2);
    			hm=m.toPaddedString(2);
    			if(this.options.showDiditClock)
    			{
    			if(this.dig1){this.dig1.remove();}
    			this.dig1 = this.paper.text(this.r, _proc(this.r,141.33), hv+(( this.dotch)?":":" ")+hm).attr({
    					'font': _proc(this.r,16)+'px '+this.options.digitClockFont, 
    					'fill': this.options.digitClockColor
    				});
				this.dig1.insertBefore(this.c);
 				}
 				this.dotch=!this.dotch;
 				this.rotm =m*6;
				if(this.noanimate){
				this.m.rotate(this.rotm,this.r,this.r);
				}else{
				this.m.animate({rotation:this.rotm+", "+this.r+", "+this.r}, 200, "elastic");
				}		
		},
		render:function()
		{
			this.container = new Element("div",{"style":"float:left;width:"+this.r*2+"px;height:"+this.r*2});
			this.options.renderTo.insert(this.container);
			if(this.options.adjustable)
				{
				    this.container.observe(((!Prototype.Browser.Gecko)?"mousewheel":"DOMMouseScroll"),this.weelhandler.bind(this));
				}
			this.paper = Raphael(this.container, this.r*2, this.r*2);
			this.a = this.paper.circle(this.r, this.r, _proc(this.r,93.33)).attr({
					stroke: this.options.borderColor,
					'stroke-width':_proc(this.r,5),
					'fill':this.options.backgroundColor
				});
				this.a.mousedown(function (e) { Event.stop(e);});
				this.paper.text(this.r, _proc(this.r,60), this.options.logoText).attr({
					font: _proc(this.r,15)+'px '+this.options.logoFont, 
					stroke: "#000",
					fill: this.options.logoColor, 
					'stroke-width':0.3
					});
					

				var cnt = [1,2,3,4,5,6,7,8,9,10,11,12];
					cnt.each(function(n)
					{
						var d = this.paper.path("M"+this.r+" "+_proc(this.r,10)+"L"+this.r+" "+_proc(this.r,16.66)).attr({
									stroke: this.options.tagColor, 
									'stroke-linecap':'round', 
									'stroke-width':1
									});
						d.rotate(n*30,this.r,this.r);
					}.bind(this));
		
		
					for(var n=1; n<60; n++)
					{
						if(cnt.indexOf(n/5)==-1)
						{
							u=this.paper.path("M"+this.r+" "+_proc(this.r,10)+"L"+this.r+" "+_proc(this.r,11.33)).attr({
										stroke: this.options.tagColor, 
										'stroke-linecap':'round', 
										'stroke-width':0.5
									});
							u.rotate(n*6,this.r,this.r);
						}
					}
					if(this.options.showDiditClock)
    			{
				this.paper.rect(_proc(this.r,78.5), _proc(this.r,131), _proc(this.r,42.66), _proc(this.r,20), _proc(this.r,2.66)).attr({
							'fill':this.options.digitClockBg, 
							'stroke-width':0
						});
				}
				for(var n=0; n<this.options.digits.length; n++)
				{
				
				angle=(n+1)*30+270;
				jsangle = Math.PI / 180 * (angle);
				var ofs =  _proc(this.r,28);
				var rad = this.r-ofs;
				var y = Math.sin(jsangle)*rad + this.r +(this.options.digitsOffset || _proc(this.r,5) );
				var x = Math.cos(jsangle)*rad  + this.r ;
				var di=this.paper.text(x,y, this.options.digits[n]).attr({
						'font': _proc(this.r,15)+'px '+this.options.digitsFont, 
						'stroke': "#000",
						'fill': this.options.digitsColor, 
						'stroke-width':0.3
					});
				
				}	
				
				this.c = this.paper.path("M"+this.r+" "+_proc(this.r,13.33)+"L"+this.r+" "+_proc(this.r,116.66)).attr({
						stroke: this.options.secondHandColor, 
						'stroke-width':_proc(this.r,1.1)
					});
		
				this.h = this.paper.rect(_proc(this.r,98.33), _proc(this.r,28), _proc(this.r,4), _proc(this.r,80), _proc(this.r,5)).attr({
						stroke: "#000000",
						'fill':this.options.hourHandColor, 
						'stroke-linecap':'round',
						'stroke-opacity':0,
						'fill-opacity':0.8, 
						'stroke-width':_proc(this.r,70)
					});
		
				this.m = this.paper.rect(_proc(this.r,98.33), _proc(this.r,28), _proc(this.r,2.66), _proc(this.r,80), _proc(this.r,5)).attr({
						stroke: "#000000",
						'fill':this.options.minuteHandColor,
						'stroke-linecap':'round',
						'stroke-opacity':0,
						'fill-opacity':0.8,
						'stroke-width':_proc(this.r,70)
					});
		
				this.b = this.paper.circle(this.r, this.r, _proc(this.r,2)).attr({
						stroke: this.options.borderColor, 
						'fill':this.options.backgroundColor
					});
					
				if(this.options.adjustable)
				{
					this.h.mousedown(function (e) {
		    				this.stopClock=true;
		    				this.dragClockH=true;
		    				Event.stop(e);
						}.bind(this));
					this.m.mousedown(function (e) {
		    				this.stopClock=true;
		    				this.dragClockM=true;
		    				Event.stop(e);
						}.bind(this));
					document.body.observe('mouseup',function (e) {
						if(this.dragClockH||this.dragClockM)
						{
		    
		    				var h = Math.floor(this.roth/30);
							var m = ((Math.floor(this.rotm/(6*this.options.minuteRound)))*(6*this.options.minuteRound))/6;
							this.dotch=true;
							var d = new Date();
                			d.setHours(h);
                			d.setMinutes(m);
                			this.setTime(d);
		        			this.c.hide();
		        			this.dragClockH=false;
		        			this.dragClockM=false;
		        			this.container.style.cursor="default";
						}
		    
					}.bind(this));
					
					
					document.body.observe('mousemove',function (e) {
		    			if(!this.stopClock||(!this.dragClockH && !this.dragClockM)){return;}
		    			
		    			
		   				this.container.style.cursor="move";
		   				var vp = this.container.viewportOffset();
		    			if(this.dragClockH)
		    			{
			    			bkp = this.roth;
			    			this.roth = this.clickAngle({x:Number(Event.pointerX(e)),y:Number(Event.pointerY(e))}, {width:this.r*2,height:this.r*2,left:Number(vp.left), top:Number(vp.top)});
			    			
			    			
			    			if( bkp > 360 )
						    {
						    	tmp =  bkp - Math.floor(bkp/360)*360;
						    }
						    else
						    {
						    	tmp = bkp;
						    }
							if(tmp >= 300 && this.roth <= 50)
						    {
						    	this.roth+=360;
						    }
						    if(tmp <= 50 && this.roth >= 300)
						    {
						    	this.roth-=360;
						    }
						    if( bkp > 360 )
						    {
						    	this.roth += Math.floor(bkp/360)*360;
						  	
						    }   
						    if(this.roth < 0){ this.roth += 720; }
						    if(this.roth >720){ this.roth -= 720; }
			    			if(isNaN(this.roth))
			    			{
			    				this.roth=bkp;
			    			}
		       			}
		     			if(this.dragClockM)
		     			{
		     				bkp=this.rotm;
		     				this.rotm = this.clickAngle({x:Number(Event.pointerX(e)),y:Number(Event.pointerY(e))}, {width:this.r*2,height:this.r*2,left:Number(vp.left), top:Number(vp.top)});
		    				if(bkp >=300 && this.rotm<=50)
						    {
						    	this.roth+=30;
						    }
						    if(bkp <=50 && this.rotm>=300)
						    {
						    	this.roth-=30;
						    }
						    if(isNaN(this.rotm))
			    			{
			    				this.rotm=bkp;
			    			}
						      
		       			}
		       			
		       				var h = Math.floor(this.roth/30);
							var m = Math.floor(this.rotm/6);
							
							
							this.dotch=true;
							var d = new Date();
                			d.setHours(h);
                			d.setMinutes(m);
                			this.setTime(d);
		       
		    		}.bind(this));
		    	}//end if
		}


          })