/*!
 * jQuery.lineClock
 *
 * Line Digital
 * http://www.line.uk.com/
 *
 * @author	Brian Coit <http://brian.co.it/>
 * @version	1.0
 */
;(function($)
{
    $.fn.lineClock = function(options)
    {
    	/** check if modernizr dependency exists before continuing */
    	if(!window.Modernizr || !window.Raphael)
    	{
	       console.log('jQuery.lineClock depends on Modernizr for browser capability detection and Raphael for SVG support.');
	       return false;
    	}

        var defaults = {
            handOffset: 0, // number of degrees that the clock hands are offset by
            serverTime: false, // time generated by server (for line time), to calc offset
            preserveOffsetSeconds: true, // probably want to allow the use of the seconds from local time, on localised clock (to allow them all to tick together)
            updateInterval: 500,
            imagePath: 'assets/images/clock/'
        };

        var options = $.extend(defaults, options);

        return this.each(function()
        {
    		var face = this;
	        var hands = new Array();
	        var time;
	        
        	!Modernizr.csstransforms
        			? createSvg(face)
            		: createHtml(face);
            
            setInterval(function()
            {
            	var date = getServerTime() || new Date();
            	
            	update(date);
            },
            options.updateInterval);
            
            var diff = false;
            
            function getServerTime()
            {
            	if(options.serverTime)
	        	{
	        		var time = new Date();
					var date = new Date();
					var tp = options.serverTime.split(':');

					if(tp.length < 3)
					{
						console.log('Invalid serverTime format. Expected format: "23:10:57"');
						return false;
					}
					
					if(!diff)
					{
						date.setHours(tp[0]);
						date.setMinutes(tp[1]);
						date.setSeconds(tp[2]);
						
						diff = date.getTime() - time.getTime();
					}
					
					time = new Date().getTime() + diff;
					time = new Date(time);
					return time;
				}
				return false;
            }

            /** calculate the angle for a given hand from 12 */
	        function calcDegrees(hand, time)
	        {
        		var d;
        		
	            switch(hand)
	            {
	                case 'hours':
	                   d = 0.5 * (60 * time.getHours() + time.getMinutes());
	                   break;

	                case 'mins':
	                    d = time.getMinutes() * 6;
	                    break;

	                case 'secs':
						d = 360 / 60 * time.getSeconds();
	                    break;
	            }
	            return d - options.handOffset;
	        }

	        /** generic clock update method - handles delegation to canvas or css3 implementations */
	        function update(time)
	        {
	        	if(options.preserveOffsetSeconds)
	        	{
	        		var tmp = new Date();
					time.setSeconds(tmp.getSeconds());
	        	}

	            /** set title attributes to updated formatted date string */
	            $(face).attr('title', time.toLocaleTimeString());

	            Modernizr.csstransforms
            		? updateCss3Rotate(time)
            		: updateSvg(time);
	        }

	        /** CSS implementation */
	        function updateCss3Rotate(dateObj)
	        {
	            var units = new Array('hours', 'mins', 'secs');
	            
	            for(var i in units)
	            {
            		var deg = calcDegrees(units[i], dateObj);
            		
					hands[units[i]].css({
						'-webkit-transform': 'rotate(' + deg + 'deg)',
		                '-moz-transform': 'rotate(' + deg + 'deg)',
		                'transform': 'rotate(' + deg + 'deg)'
					});
	            }
	        }

	        /** creates the html markup for the css3 version */
	        function createHtml(container)
	        {
	            var handNames = new Array('hours', 'mins', 'secs');
	            
	            for(var i in handNames)
	            {
					hands[handNames[i]] = $('<div />').addClass(handNames[i]).appendTo(container);
	            }
	        }

        	/** SVG implementation */
            function createSvg(container)
            {
            	var stage = Raphael($(container).get(0), $(container).width(), $(container).height());
			
				var handNames = new Array('hours', 'mins', 'secs');
	            
	            for(var i in handNames)
	            {
					hands[handNames[i]] = stage.image(options.imagePath + handNames[i] + ".png", 0, 0, 34, 34);
	            }
            	
            }
            
            function updateSvg(dateObj)
            {
				var units = new Array('hours', 'mins', 'secs');
	            
	            for(var i in units)
	            {
            		var deg = calcDegrees(units[i], dateObj);

					hands[units[i]].animate({rotation: deg}, 0, function() {});
	            }
            }
        });
    }
})
(jQuery);
