$(document).ready(function () {

init();

    function init() {
    	clock();
    	
    	$('[name=q]').focus();
        
        var elems = {
            clockContainer: $('#klocka'),
            clockSelector:	$('#klockaType'),
            digitalClock:   $('#digitalClock'),
            analogClock:    $('#analogClock'),
            links:			$('#links'),
            secondHand:     $('#sec'),
            minuteHand:     $('#min'),
            hourHand:       $('#hour')
        };
        
        var theme = {
            clockType: function (type) {
                if (type == 'digital') {
                    elems.digitalClock.show();
                    elems.analogClock.hide();
                } else {
                    elems.analogClock.show();
                    elems.digitalClock.hide();
                }
            },
            digitalFntSize: function (size) {
                elems.digitalClock.css({
                    fontSize: size
                });
            },
            bgColor: function (color) {
                $('#bgColor').css({
                    backgroundColor: color
                });
            },
            fntColor: function (fnt_color) {
                $('#contents').css({
                    color: fnt_color
                });
            },
            links: function (visibility) {
            	(visibility == 'true') ? elems.links.show() : elems.links.hide();
            }
        };
        
        function visibleClock() {
            if ($(elems.analogClock).is(":visible")) {
                return 'analog';
            } else {
                return 'digital';
            }
        }
        
        function visibleLinks() {
        	if ($(elems.links).is(':visible') == true) {
        		return 'true';
        	} else {
        		return 'false';
        	}
        }
        
        function getInternetExplorerVersion()
        // Internet Explorer version 8, 7 or 6. 
        // return -1 if the browser is not Internet Explorer.
        {
           var rv = -1; // Return value assumes failure.
           if (navigator.appName == 'Microsoft Internet Explorer')
           {
              var ua = navigator.userAgent;
              var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
              if (re.exec(ua) != null)
                 rv = parseFloat( RegExp.$1 );
           }
           return rv;
        }
        
        function checkIEVersion()
        {
           var version = getInternetExplorerVersion();
           var isFail = false;
           
           if (version > -1) {
               if (version == 8.0 || version == 7.0 || version == 6.0)
               isFail = true;
           } else {
               isFail = false;
           }
            
           return isFail;
        }
        
        var rgbColorToHex = function (colorStr) {
	        var hex = '#';
	        
	        $.each(colorStr.substring(4).split(','), function (i, str) {
	            var h = ($.trim(str.replace(')', '')) * 1).toString(16);
	            hex += (h.length == 1) ? "0" + h : h;
	        });
	        
	        return hex;
	    };
        
        function getTime() {
            var today = new Date();
            var time = {
                full: today.toLocaleTimeString(),
                hours: today.getHours(),
                minutes: today.getMinutes(),
                seconds: today.getSeconds()
            };
            return time
        }

        function clock() {
            function setCssTransforms(value) {
                var transform = {
                    "transform": value,
                    "-moz-transform": value,
                    "-webkit-transform": value,
                    "-o-transform": value,
                    "-ms-transform": value
                };
                return transform;
            }

            setInterval(function () {
                var sdegree = getTime().seconds * 6;
                var srotate = "rotate(" + sdegree + "deg)";
                elems.secondHand.css(setCssTransforms(srotate));
            }, 1000);
            
            setInterval(function () {
                var hdegree = getTime().hours * 30 + (getTime().minutes / 2);
                var hrotate = "rotate(" + hdegree + "deg)";
                elems.hourHand.css(setCssTransforms(hrotate));
            }, 1000);
            
            setInterval(function () {
                var mdegree = getTime().minutes * 6;
                var mrotate = "rotate(" + mdegree + "deg)";
                elems.minuteHand.css(setCssTransforms(mrotate));
            }, 1000);
        }
        
        function storeTheme(backgroundColor, fontColor, fontSize, clockType, visibleLinks) {
            (backgroundColor) ? theme.bgColor(backgroundColor) : null;
            (fontColor) ? theme.fntColor(fontColor) : null;
            (fontSize) ? theme.digitalFntSize(fontSize) : null;
            (clockType) ? theme.clockType(clockType) : null;
            theme.links(visibleLinks);
            
            var settings = [];
            settings.push(backgroundColor, fontColor, fontSize, clockType, visibleLinks);
            
            setCookie('klocka.nu', settings.toString(), 365);
        }
        
        function setTheme(theme) {
            switch (theme) {
            case 'standard':
                storeTheme(rgbColorToHex('rgb(48, 48, 48)'), rgbColorToHex('rgb(255, 255, 255)'), elems.digitalClock.css('font-size'), visibleClock(), visibleLinks());
                break;
            case 'vit':
                storeTheme(rgbColorToHex('rgb(238, 238, 238)'), rgbColorToHex('rgb(0, 0, 0)'), elems.digitalClock.css('font-size'), visibleClock(), visibleLinks());
                break;
            case 'sverige':
                storeTheme(rgbColorToHex('rgb(10, 89, 166)'), rgbColorToHex('rgb(255, 229, 0)'), elems.digitalClock.css('font-size'), visibleClock(), visibleLinks());
                break;
            case 'analog':
                storeTheme(rgbColorToHex($('#bgColor').css('background-color')), rgbColorToHex($('#contents').css('color')), '100px', 'analog', visibleLinks());
                break;
            case 'digital':
                storeTheme(rgbColorToHex($('#bgColor').css('background-color')), rgbColorToHex($('#contents').css('color')), '100px', 'digital', visibleLinks());
                break;
            case 'storDigital':
                storeTheme(rgbColorToHex($('#bgColor').css('background-color')), rgbColorToHex($('#contents').css('color')), '200px', 'digital', visibleLinks());
                break;
            }
        }
        
        function setCookieTheme(userSettings) {
            var cookieValue = userSettings.split(',');
            storeTheme(cookieValue[0], cookieValue[1], cookieValue[2], cookieValue[3], cookieValue[4]);
        }
        
        function getCookie(name) {
        	var start = document.cookie.indexOf( name + "=" );
        	var len = start + name.length + 1;
        	if ((!start) && (name != document.cookie.substring(0, name.length))) {
        		return null;
        	}
        	if (start == -1) return null;
        	var end = document.cookie.indexOf(';', len);
        	if (end == -1) end = document.cookie.length;
        	return unescape( document.cookie.substring(len, end));
        }
        
        function setCookie(name, value, expires, path, domain, secure) {
        	var today = new Date();
        	today.setTime(today.getTime());
        	
        	if (expires) {
        		expires = expires * 1000 * 60 * 60 * 24;
        	}
        	
        	var expires_date = new Date(today.getTime() + (expires));
        	document.cookie = name+'='+escape(value) +
        	((expires) ? ';expires='+expires_date.toGMTString() : '') + //expires.toGMTString()
        	((path) ? ';path=' + path : '' ) + 
        	(( domain ) ? ';domain=' + domain : '') +
        	(( secure ) ? ';secure' : '');
        }
        
        function deleteCookie(name, path, domain) {
            if (getCookie(name)) document.cookie = name + '=' + ((path) ? ';path=' + path : '') + ((domain) ? ';domain=' + domain : '') + ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
        }
        
        elems.clockSelector.chosen();
        
        elems.clockSelector.change(function () {
            deleteCookie('klocka.nu');
            var option = $(this).val();
            if (option == 'analog') {            	
            	if (checkIEVersion() == true) {
            		alert('Uppgradera din webbläsare till den senaste versionen');
            		return false;
            	}
            }
            setTheme(option);
        });
        
        $('#hideLinks').click(function () {
        	theme.links('false');
        	storeTheme(
        		rgbColorToHex($('#bgColor').css('background-color')),
        		rgbColorToHex($('#contents').css('color')),
        		elems.digitalClock.css('font-size'),
        		visibleClock(),
        		'false');
        });
        
        var userSettings = getCookie('klocka.nu');
        if (userSettings) {
            setCookieTheme(userSettings);
        }      
    }
});
