/*
 * DetectRight JavaScript Client
 *
 * @author Alain Lefebvre <alain.lefebvre@gmail.com>, Chris Abbott <chris@detectright.com>
 * @version 1.0
 */
 
var DetectRight = {
    
    isTablet: null,
    isMobile: null,
    isAndroid: null,
    isBlackBerry: null,
    isWindowsPhone: null,
    isSymbianOs: null,
    isWebOs: null,
    isWebkit: null,
    isWebkitMobile: null,
    orientation: null,
    dpi: null,
    userAgent: null,
    udid: null,
    coords: {latitude: '', longitude: ''},
    commonTablet: null,
    isWebSqlCompatible: null,
    isIndexedDbCompatible: null,
    isLocalStorageCompatible: null,
    isWebSocketCompatible: null,
    isGeoLocationCompatible: null,
    isWebAppCacheCompatible: null,
    isWebGlCompatible: null,
    isHtml5VideoCompatible: null,
    isFileSystemApiCompatible: null,
    isHtmlFileUploadCompatible: null,
    isDomPerformanceStatsCompatible: null,
    isNotificationsCompatible: null,  
    isHtml5HistoryEnabled: null,
    isOnline: null,
    isKnownPcBrowser: null,
    connectionType: null,
    commonVideoCodecSupport: null,
    domLoaded: null,
    drid: null,
    isGecko: null,
    
    debug: false,
    time: null,
    
    
    init: function(params){
        
        if(params.geotarget && params.geotarget == true)
            this.setCoords();
            
        if(params.drid != "" && params.drid.length > 1)
            this.drid = params.drid;
        
        /* for Mozilla/Opera9 */
        if (document.addEventListener) {
            document.addEventListener("DOMContentLoaded", DetectRight.isDomLoaded, false);
        }

        /* for Internet Explorer */
        /*@cc_on @*/
        /*@if (@_win32)
              document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
              var script = document.getElementById("__ie_onload");
              script.onreadystatechange = function() {
                if (this.readyState == "complete") {
                  DetectRight.isDomLoaded(); // call the onload handler
                }
              };
        /*@end @*/
        /* for Safari */
        else if (this.getIsWebkit()) { // sniff
            this.timer = setInterval(function() {
                if (/loaded|complete/.test(document.readyState)) {
                  DetectRight.isDomLoaded(); // call the onload handler
                }
            }, 10);
        }
        else
            window.onload = DetectRight.isDomLoaded();
    },
    
    android: {
	getOsVersionAsString: function(){
		var matches = DetectRight.getUserAgent().match(/\s*Android\s*([0-9]+)\.?([0-9]+)?\.?([0-9]+)?\s*/);
                return (matches && matches[1] ? matches[1] : '');

	},
	getOsVersion: function(){	
		var matches = DetectRight.getUserAgent().match(/\s*Android\s*([0-9]+)\.?([0-9]+)?\.?([0-9]+)?\s*/);
               	// TODO
	},
        installedApps: {},
        isAppInstalled: function(app_name){
            if("isApplicationInstalled" in navigator || typeof navigator.isApplicationInstalled === 'function'){
                // If this app has not been checked yet, then check for it
                //var propName = app.replace(/[^a-zA-Z0-9]+/g, ''); 
                if(app_name in DetectRight.android.installedApps === false){
		            var res = navigator.isApplicationInstalled(app_name, function(){});
                    DetectRight.android.installedApps[app_name] = res; 
                } 
                return DetectRight.android.installedApps[app_name];     
            }   
        },
    },
    
    apple: {
        isIphone: null,
        isIpad: null,  
        getIsIphone: function(){
            if(this.apple.isIphone == null)
                this.isApple = (this.getUserAgent().match(/iPhone|iPad|iPod/i)) ? true : false ;            
            return this.isApple;
        },
        getIsPad: function(){
            if(this.apple.isIphone == null)
                this.isApple = (this.getUserAgent().match(/iPhone|iPad|iPod/i)) ? true : false ;            
            return this.isApple;
        }, 
        iphone: {
            is1stGeneration: null, // iPhone
            is2ndGeneration: null, // iPhone 3G 
            is3rdGeneration: null, // iPhone 3Gs
            is4thGeneration: null, // iPhone 4/4S
            getIs1stGeneration: function(){
                if(DetectRight.apple.iphone.is1stGeneration == null){
                    DetectRight.apple.iphone.is1stGeneration = (DetectRight.apple.getIsIphone() && DetectRight.getPixelRatio() < 2 ? true : false)   
                }  
                return DetectRight.iphone.is1stGeneration;
            },
            getIs2ndGeneration: function(){
                if(DetectRight.apple.iphone.is2ndGeneration == null){
                    DetectRight.apple.iphone.is2ndGeneration = (DetectRight.apple.getIsIphone() && DetectRight.getPixelRatio() < 2 ? true : false)         
                }  
                return DetectRight.apple.iphone.is2ndGeneration;
            },
            getIs3rdGeneration: function(){
                if(DetectRight.apple.iphone.is3rdGeneration == null){
                    DetectRight.apple.iphone.is3rdGeneration = (DetectRight.apple.getIsIphone() && DetectRight.getPixelRatio() < 2 ? true : false)             
                }  
                return DetectRight.apple.iphone.is3rdGeneration;
            },
            getIs4thGeneration: function(){
                if(DetectRight.apple.iphone.is4thGeneration == null){
                    DetectRight.apple.iphone.is4thGeneration = (DetectRight.getIsIphone() && (DetectRight.getPixelRatio() >= 2 || DetectRight.getIs2xDPI()) ? true : false);   
                }  
                return DetectRight.apple.iphone.is4thGeneration;    
            }
        },
        ipad: {
            is1stGeneration: null,
            is2ndGeneration: null,
            getIs1stGeneration: function(){
                if(DetectRight.apple.ipad.is1stGeneration == null){
                    DetectRight.apple.ipad.is1stGeneration = (DetectRight.getIsIpad() && (DetectRight.getPixelRatio() < 2  || !DetectRight.getIs2xDPI()) ? true : false);        
                }  
                return DetectRight.apple.ipad.is1stGeneration;
            },
            getIs2ndGeneration: function(){
                if(DetectRight.apple.ipad.is2ndGeneration == null){
                    DetectRight.apple.ipad.is2ndGeneration = (DetectRight.getIsIpad() && (DetectRight.getPixelRatio() < 2  || !DetectRight.getIs2xDPI()) ? true : false);            
                }  
                return DetectRight.apple.ipad.is2ndGeneration;
            }, 
        }
        
    },
    
    blackberry: {
        
    },
    

    getOrientation: function(){

	    if("orientation" in window && this.orientation == null){
		    if(window.orientation == 0)
			    this.orientation = 'portrait';
		    else if(window.orientation == -90)
			    this.orientation = 'landscape_right';
		    else if(window.orientation == 90)
			    this.orientation = 'landscape_left';
	    } else {
            this.orientation = 'unknown';
        }
        
        return this.orientation;

    },
      
    getIsTablet: function() {
        
        var device_type = getIdentCookie();
        if(this.isTablet == true || device_type == 'tablet')
            return true;
        
        if(this.getIsCommonTable())
            return true;
        
        this.isTablet = (this.getUserAgent().match(/tablet/i)) ? true : false ;      
    },
    
    
    getIsCommonTablet: function(){
        if(this.commonTablet == null){
            this.commonTablet = (this.getUserAgent().match(/ipad|xoom|playbook|touchpad|flyer|transformer/i)) ? true : false ;            
        }
        return this.commonTablet;
    },
    
    
    display: {
        screenWidth: null,
        screenHeight: null,
        visibleScreenWidth: null,
        visibleScreenHeight: null,
        is2xDPI: null,
        pixelRatio: null,
        isTouch: null,
        getWidth: function(){
            if(this.screenWidth == null){ this.screenWidth = screen.width; }
            return this.screenWidth;   
        },
        getHeight: function(){
            if(this.screenHeight == null){ this.screenHeight = screen.height; }
            return this.screenHeight;   
        },
        getVisibleWidth: function(){
            if(this.visibleScreenWidth == null){ this.visibleScreenWidth = window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth||0; }
            return this.visibleScreenWidth;   
        },  
        getVisibleHeight: function(){
            if(this.visibleScreenHeight == null){ this.visibleScreenHeight = window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight||0; }
            return this.visibleScreenHeight;   
        },  
        getPixelRatio: function(){
            if(this.pixelRatio == null){   
                if("devicePixelRatio" in window)             
                    this.pixelRatio = window.devicePixelRatio;
                else
                    this.pixelRatio = 'unknown';  
            }
            return this.pixelRatio;
            
        },
        getIs2xDPI: function(){
            if(this.is2xDPI == null){  
                if("devicePixelRatio" in window)
                    this.is2xDPI = (window.devicePixelRatio == 2) ? true : false ;                     
                else if("matchMedia" in window){       
                    if(this.getUserAgent().match(/webkit/i))
                        this.is2xDPI = window.matchMedia("(-webkit-min-device-pixel-ratio: 2)").matches;
                    else if(this.getUserAgent().match(/firefox|fennec/i))
                        this.is2xDPI = window.matchMedia("(-moz-device-pixel-ratio: 2)").matches;
                    else
                        this.is2xDPI = window.matchMedia("(device-pixel-ratio: 2)").matches;   
                }
            }
            return this.is2xDPI;
              
        },
        hasTouchSupport: function(){        
            if(this.isTouch == null){
                this.isTouch = ("createTouch" in document ? true : false);
                if(this.isTouch == false){
                    this.isTouch = ("touchstart" in document ? true : false);
                }
            } 
            return this.isTouch;
        },
        
    },
    
    
    
    getIsMobile: function() {
        if(this.isMobile == null){
            var regex = /iphone|ipod|ipad|blackberry|playbook|htc|palm|Samsung|Nokia|SGH|SCH|LG|Android|MOT|Motorolla|SonyEricsson|Sony|PSP|Kyocera|ASUS|PANTECH|Audiovox|BenQ|Fly|i-mobile|LENOVO|Haier|i-mate|Hyundai|Nintendo DSi|O2 Xda|Sagem| SIE |Vario|winwap|DoCoMo|NetFront|Vodafone|UP.Browser|konka|tianyu|ktouch|series60|kddi|sagem|MIDP|CLDC|SoftBank|TelecaBrowser|Teleca|Symbian|Treo|WAP|pocket|kindle|mobile|Opera Mini|Obigo|Windows Mobile|Windows CE|Windows Phone OS|OPWV|T-Mobile|webOS|Archos/i;
            this.isMobile = (this.getUserAgent().match(regex)) ? true : false ;      
            this.setIdentCookie('mobile');    
        }
        return this.isMobile;
    },
    
    
    getUserAgent: function() {
        if(this.userAgent == null){
            this.userAgent = navigator.userAgent;
        }
        return this.userAgent;
    },
    
     /****************/ 
     
    getOS: function(){
        if(this.os == null){
            if(this.getUserAgent().match(/iPhone|iPad|iPod/i)) {
                this.os = 'iOS';
            } else if(this.getUserAgent().match(/Android/i)) {
                this.os = 'Android';  
            } else if(this.getUserAgent().match(/BlackBerry/i)) {
                this.os = 'BlackBerry';  
            } else if(this.getUserAgent().match(/Windows CE|IEMobile|Windows Phone OS/i)) {
                this.os = 'Windows Mobile';  
            } else if(this.getUserAgent().match(/WebOS/i)) {
                this.os = 'WebOS';  
            } else if(this.getUserAgent().match(/Symbian/i)) {
                this.os = 'Symbian OS';  
            } else {
                this.os = 'Unknown';       
            }
        }
        return this.os; 
    },
    
    
    getIsAndroid: function(){
        if(this.isAndroid == null) 
            this.isAndroid = (this.getUserAgent().match(/Android/i)) ? true : false ;            
        return this.isAndroid;
    },
    
    
    getIsBlackBerry: function(){
        if(this.isBlackBerry == null)   
            this.isBlackBerry = (this.getUserAgent().match(/BlackBerry|PlayBook/i) || "blackberry" in window) ? true : false ;            
        return this.isBlackBerry;
    },
    
    
    getIsWindowsPhone: function(){
        if(this.isWindowsPhone == null)  
            this.isWindowsPhone = (this.getUserAgent().match(/Windows CE|IEMobile|Windows Phone OS/i) || document.createElement("div").style.filter != null || XDomainRequest != null) ? true : false ;            
        return this.isWindowsPhone;
    },
    
    /****************/
    
    getIsWebkit: function(){
        if(this.isWebkit == null) 
            this.isWebkit = (this.getUserAgent().match(/Webkit/i) || document.body.style.webkitBoxShadow !== undefined) ? true : false ;            
        return this.isWebkit;
    },
    
    getIsGecko: function(){
        if(this.isGecko == null) 
            this.isGecko = (this.getUserAgent().match(/Gecko/i) || document.body.style.mozBoxShadow !== undefined) ? true : false ;            
        return this.isGecko;
    },
    
    
    getIsWebkitMobile: function(){
        if(this.isWebkitMobile == null)   
            this.isWebkitMobile = (this.getUserAgent().match(/Mobile/i) && this.getIsWebkit()) ? true : false ;            
        return this.isWebkitMobile;
    },
    
    
    getDPI: function(){
        if(this.dpi == null){ 
            var div = document.createElement("div");
            div.style.width="1in";
            div.style.visibility = "hidden";
            var body = ("querySelector" in document) ? document.querySelector("body") : document.getElementsByTagName("body")[0] ;
            body.appendChild(div);
            this.dpi = document.defaultView.getComputedStyle(div, null).getPropertyValue('width');
            this.dpi = parseFloat(this.dpi, 10);
            body.removeChild(div);   
        }
        return this.dpi;
    },
    
    
    
    isDomLoaded: function(){
        
        if(this.domLoaded == null){
            // quit if this function has already been called
            if (arguments.callee.done) 
                return;
            // flag this function so we don't do the same thing twice
            arguments.callee.done = true;
            // kill the timer
            if (this.timer) 
                clearInterval(this.timer);
            
            this.domLoaded = true;   
        }
        // do stuff  
        return this.domLoaded;
           
    },
    
    
    setCoords: function(){
    
        if(!this.supportsHtml5GeoLocation()){
            DetectRight.coords.latitude = 'unknown';
            DetectRight.coords.longitude = 'unknown';
        }
          
        if((DetectRight.coords.latitude - 0) == DetectRight.coords.latitude && DetectRight.coords.latitude.length > 0)      
            return true;
            
        console.log('asdfasdfads');
        
        navigator.geolocation.getCurrentPosition( 
     
            function (position) {  
                /* 
                    To see everything available in the position.coords array:
                    for (key in position.coords) {alert(key)}
                */ 
                console.log('position found!'); 
                DetectRight.coords.latitude = position.coords.latitude,
                DetectRight.coords.longitude = position.coords.longitude;  
            }, 

            function (error) {
                switch(error.code) {
                    case error.TIMEOUT:
                        break;
                    case error.POSITION_UNAVAILABLE:
                        break;
                    case error.PERMISSION_DENIED:
                        break;
                    case error.UNKNOWN_ERROR:
                        break;
                }
                DetectRight.coords.latitude = 'unknown';
                DetectRight.coords.longitude = 'unknown';
            }
            
        );    
    },
    
    
    getLongitude: function(){
        return this.coords.longitude;       
    },
    
    
    getLatitude: function(){
        return this.coords.latitude;                    
    },
    
    
    getVideoCodecsSupported: function(){             
      
         if ( this.supportsHtml5Video() && this.commonVideoCodecSupport == null) {
         
            this.commonVideoCodecSupport = {};
            var testEl = document.createElement("video");           
            var rating = 0;
            
            var typeStr = testEl.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');
            this.commonVideoCodecSupport.h264_cbp_l3 = {'support_confidence': (typeStr == "" ? 0 : (typeStr == 'probably' ? 2 : 1)), 'comment': 'H.264 Constrained baseline profile video (main and extended video compatible) level 3 and Low-Complexity AAC audio in MP4 container'};    
            rating+=this.commonVideoCodecSupport.h264_cbp_l3.support_confidence;
            
            typeStr = testEl.canPlayType('video/mp4; codecs="avc1.58A01E, mp4a.40.2"');
            this.commonVideoCodecSupport.h264_ep_L3 = {'support_confidence': (typeStr == "" ? 0 : (typeStr == 'probably' ? 2 : 1)), 'comment': 'H.264 Extended profile video (baseline-compatible) level 3 and Low-Complexity AAC audio in MP4 container'};    
            rating+=this.commonVideoCodecSupport.h264_ep_L3.support_confidence;  
            
            typeStr = testEl.canPlayType('video/mp4; codecs="avc1.4D401E, mp4a.40.2"');      
            this.commonVideoCodecSupport.h264_mp_L3 = {'support_confidence': (typeStr == "" ? 0 : (typeStr == 'probably' ? 2 : 1)), 'comment': 'H.264 Main profile video level 3 and Low-Complexity AAC audio in MP4 container'};    
            rating+=this.commonVideoCodecSupport.h264_mp_L3.support_confidence;  
            
            typeStr = testEl.canPlayType('video/mp4; codecs="avc1.64001E, mp4a.40.2"');      
            this.commonVideoCodecSupport.h264_hp_L3 = {'support_confidence': (typeStr == "" ? 0 : (typeStr == 'probably' ? 2 : 1)), 'comment': 'H.264 "High" profile video (incompatible with main, baseline, or extended profiles) level 3 and Low-Complexity AAC audio in MP4 container'};    
            rating+=this.commonVideoCodecSupport.h264_hp_L3.support_confidence;  
            
            typeStr = testEl.canPlayType('video/mp4; codecs="mp4v.20.8, mp4a.40.2"');      
            this.commonVideoCodecSupport.mpeg4_sp_L0 = {'support_confidence': (typeStr == "" ? 0 : (typeStr == 'probably' ? 2 : 1)), 'comment': 'MPEG-4 Visual Simple Profile Level 0 video and Low-Complexity AAC audio in MP4 container'};         
            rating+=this.commonVideoCodecSupport.mpeg4_sp_L0.support_confidence;  
            
            typeStr = testEl.canPlayType('video/mp4; codecs="mp4v.20.240, mp4a.40.2"');      
            this.commonVideoCodecSupport.mpeg4_asp_L0 = {'support_confidence': (typeStr == "" ? 0 : (typeStr == 'probably' ? 2 : 1)), 'comment': 'MPEG-4 Advanced Simple Profile Level 0 video and Low-Complexity AAC audio in MP4 container'};         
            rating+=this.commonVideoCodecSupport.mpeg4_asp_L0.support_confidence;  
            
            typeStr = testEl.canPlayType('video/3gpp; codecs="mp4v.20.8, samr"');      
            this.commonVideoCodecSupport.mpeg4_sp_L0_3gp = {'support_confidence': (typeStr == "" ? 0 : (typeStr == 'probably' ? 2 : 1)), 'comment': 'MPEG-4 Visual Simple Profile Level 0 video and AMR audio in 3GPP container'};         
            rating+=this.commonVideoCodecSupport.mpeg4_sp_L0_3gp.support_confidence;  
            
            typeStr = testEl.canPlayType('video/ogg; codecs="dirac, vorbis"');      
            this.commonVideoCodecSupport.ogg = {'support_confidence': (typeStr == "" ? 0 : (typeStr == 'probably' ? 2 : 1)), 'comment': 'Dirac video and Vorbis audio in Ogg container'};         
            rating+=this.commonVideoCodecSupport.ogg.support_confidence;  
            
            typeStr = testEl.canPlayType('video/x-matroska; codecs="theora, vorbis"');      
            this.commonVideoCodecSupport.theora = {'support_confidence': (typeStr == "" ? 0 : (typeStr == 'probably' ? 2 : 1)), 'comment': 'Theora video and Vorbis audio in Matroska container'};         
            rating+=this.commonVideoCodecSupport.theora.support_confidence;  
           
            this.commonVideoCodecSupport.overallRating = Math.round((rating*100)/18)
            testEl = typeStr = null;
              
        } 
        
        return this.commonVideoCodecSupport;
                
    },
    
    
    getIsOnline: function(){
        if(this.isOnline == null){   
            this.isOnline = (typeof window.navigator.onLine === "boolean" ? (window.navigator.onLine) : 'unknown' );                       
        }
        return this.isOnline;           
    },
    
    
    getConnectionType: function(){
        
	    if("blackberry" in window && this.connectionType == null){
	 	    var type = blackberry.network;
		    // Will have to do a preg-slipt to see if more than
		    // one network is available at that given time, if so,
 		    // take the fastest one that is available
		    this.connectionType = type;
	    } else if("connection" in navigator && this.connectionType == null){   
            var type = navigator.connection.type;
            switch(type){
                case navigator.connection.WIFI:
                    this.connectionType = "WiFi";
                    break;  
                case navigator.connection.ETHERNET:
                    this.connectionType = "Ethernet";
                    break;
                case navigator.connection.CELL_2G:
                    this.connectionType = "2G";
                    break;
                case navigator.connection.CELL_3G:
                    this.connectionType = "3G";
                    break;
                default:
                    this.connectionType = "unknown";
                    break;
            }                    
        } else if(this.connectionType == null) {
            this.connectionType = 'unknown';     
        }

	    return this.connectionType;            
    }, 
    
    
    getIsKnownPcBrowser: function() {
        if(this.isKnownPcBrowser == null){
            if("chrome" in window){ // property only on chrome PC browser
                this.isKnownPcBrowser = true;
            } else if(navigator.javaEnabled()) {    // property only on desktop browsers
                this.isKnownPcBrowser = true;      
            } else if(typeof window.fullScreen != "undefined"){  // property only on firefox browser
                this.isKnownPcBrowser = true;         
            } else {
                this.isKnownPcBrowser = false;         
            }
        }
        return this.isKnownPcBrowser;
    },
    
    
    supportsHtml5Video: function(){
        if(this.isHtml5VideoCompatible == null){   
            this.isHtml5VideoCompatible = (document.createElement("video").canPlayType != 'undefined' ? true : false );                       
        }
        return this.isHtml5VideoCompatible;        
    },
    
    
    supportsWebSql: function(){
        if(this.isWebSqlCompatible == null){   
            this.isWebSqlCompatible = (typeof window.openDatabase != "undefined") ? true : false ;            
        }
        return this.isWebSqlCompatible;  
    },
    
    
    supportsIndexedDB: function(){
        if(this.isIndexedDbCompatible == null){   
            this.isIndexedDbCompatible = ((window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB) != 'undefined') ? true : false ;            
        }
        return this.isIndexedDbCompatible;  
    },
    
    
    supportsLocalStorage: function(){
        if(this.isLocalStorageCompatible == null){   
            this.isLocalStorageCompatible = (typeof localStorage != "undefined" ) ? true : false ;            
        }
        return this.isLocalStorageCompatible;  
    },
    
    
    supportsWebSockets: function(){
        if(this.isWebSocketCompatible == null){   
            this.isWebSocketCompatible = (typeof WebSocket == "function" || "WebSocket" in window ) ? true : false ;            
        }
        return this.isWebSocketCompatible;  
    },
    
    
    supportsWebAppCache: function(){
        if(this.isWebAppCacheCompatible == null){   
            this.isWebAppCacheCompatible = (typeof applicationCache == "object" || "applicationCache" in window ) ? true : false ;            
        }
        return this.isWebAppCacheCompatible;  
    },
    
    
    supportsHtml5GeoLocation: function(){
         if(this.isGeoLocationCompatible == null){   
            this.isGeoLocationCompatible = (navigator.geolocation) ? true : false ;            
        }
        return this.isGeoLocationCompatible;      
    },
    
    
    supportsFileSystemApi: function(){
         if(this.isFileSystemApiCompatible == null){   
            this.isFileSystemApiCompatible = (window.webkitRequestFileSystemSync || window.requestFileSystemSync) ? true : false ;            
        }
        return this.isFileSystemApiCompatible;      
    },
    
    
    supportsNotifications: function(){
         if(this.isNotificationsCompatible == null){   
            this.isNotificationsCompatible = (window.webkitNotifications) ? true : false ;            
        }
        return this.isNotificationsCompatible;      
    },
    
    
    supportsHtmlFileUpload: function(){
         if(this.isHtmlFileUploadCompatible == null){ 
            var elem = document.createElement("input");
            elem.setAttribute("type", "file");
            elem.setAttribute("id", "fileupload");
            document.body.appendChild(elem);
            this.isHtmlFileUploadCompatible = (typeof elem.files !== 'object' ? false : true );    
            document.body.removeChild(elem);               
        }
        return this.isHtmlFileUploadCompatible;      
        
    },
    
    
    supportsHtml5History: function(){
         if(this.isHtml5HistoryEnabled == null){ 
            this.isHtml5HistoryEnabled = (window.history ? false : true );                 
        }
        return this.isHtml5HistoryEnabled;      
        
    },
    
    
    supportsDomPerformanceStats: function(){
         if(this.isDomPerformanceStatsCompatible == null){   
            this.isDomPerformanceStatsCompatible = (window.performance || "performance" in window) ? true : false ;            
        }
        return this.isDomPerformanceStatsCompatible;      
    },
    
    
    supportsWebGL: function(){
         if(this.isWebGlCompatible == null){  
            var gl = null; 
            var contextNames = ["webgl","experimental-webgl","moz-webgl","webkit-3d"];
            var canvas = document.createElement('canvas');
            canvas.setAttribute('id','cv');
            document.body.appendChild(canvas);
            for(var i = 0; i < 4; i++){
                try{ 
                    if(canvas.getContext(contextNames[i], { antialias:true })){
                        this.isWebGlCompatible = true;
                        break;
                    }
                }catch(e){
                    this.isWebGlCompatible = false;
                }
            }
            document.body.removeChild(canvas);       
            if(this.isWebGlCompatible === undefined || this.isWebGlCompatible == null || this.isWebGlCompatible == '')
                this.isWebGlCompatible = false;            
        }
        return this.isWebGlCompatible;      
    },
    
    
    setIdentCookie: function (device_type) {
        if(this.getIdentCookie())
            return true;  
        return this.setCookie('device_type', device_type, 31);
    },
    
    
    getIdentCookie: function (){
        return this.getCookie('device_type');
    },
    
    
    setCookie: function(name, value, expiry_days){
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + expiry_days); // set the cookie for 31 days
        var value = escape(value)+"; expires="+exdate.toUTCString();
        document.cookie= name+"="+value;       
    },
    
    
    getCookie: function (name){
        var i,x,y,deviceCookies = document.cookie.split(";");
        for (i=0; i<deviceCookies.length; i++) {
              x = deviceCookies[i].substr(0,deviceCookies[i].indexOf("="));
              y = deviceCookies[i].substr(deviceCookies[i].indexOf("=")+1);
              x = x.replace(/^\s+|\s+$/g,"");
              return (x == name) ? unescape(y) : false;
        }
    },
    
    
    removeCookie: function(name,path){
        if (this.getCookie(name)) 
            document.cookie = name + "=" + ( ( path ) ? ";path=" + path : "") + ( ( domain ) ? ";domain=" + domain : "" ) + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
    },

    
    getUDID: function(){
        
        if(this.udid != null)
            return this.udid;

        // Attempt to get the UDID from local storage
        if(this.supportsLocalStorage()){
            var udid = localStorage.getItem('udid');
            if(udid != null && udid.length > 5){ 
                this.udid = udid;
                return this.udid;   
            }
        } else { // Only supports cookies
            var cookied_udid = this.getCookie('udid');
            if(cookied_udid != null && cookied_udid.length > 5) {
                this.udid = udid;
                return this.udid;       
            }
        }
        
        // At this point, no UDID was found, so generate one
        this.udid = '';   
        var chars = "0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ";
        for(var i = 0; i < 32; i++)
            this.udid += chars.substr( Math.floor(Math.random() * 62), 1 );

        if(this.supportsLocalStorage()){ 
            localStorage.removeItem('udid');
            localStorage.setItem('udid',this.udid);
        } else {
            this.removeCookie('udid','/','www.whatsmydevice.mobi');
            this.setCookie('udid', this.udid);         
        }
        
        return this.udid;    

    },
    

   
    track: function(){
     
        var tp = document.querySelector('#dr_tracking');
        if(tp == null || !tp){
            var img = document.createElement('img');
            img.id = 'dr_tracking';
            //var src = 'http://quantum.detectright.com/track.php?udid='+this.getUDID();
            var src = 'http://quantum.detectright.com/track.php?drid='+this.drid;  
            src += '&udid='+this.getUDID();       
            src += '&ua='+this.getUserAgent() + '&screenx='+ this.display.getWidth() + '&screeny=' + this.display.getHeight();
            src += '&referrer='+document.referrer;
            
            src += '&dpi='+this.getDPI() + '&websql='+(this.supportsWebSql() ? 1 : 0) + '&indexedDb='+(this.supportsIndexedDB() ? 1 : 0); 
            src += '&localstorage='+(this.supportsLocalStorage() ? 1 : 0) + '&hastouch='+(this.display.hasTouchSupport() ? 1 : 0); 
            src += '&websockets='+(this.supportsWebSockets() ? 1 : 0) + '&geolocation='+(this.supportsHtml5GeoLocation() ? 1 : 0);  
            src += '&latlon='+ this.getLatitude()+','+this.getLongitude();  
             
            src += '&conntype='+ this.getConnectionType() + '&htmlfileupload='+(this.supportsHtmlFileUpload() ? 1 : 0);  
            src += '&filesysapi='+(this.supportsFileSystemApi() ? 1 : 0) + '&browsernotifications='+(this.supportsNotifications() ? 1 : 0);        

            src += '&iswebkit='+(this.getIsWebkit() ? 1 : 0) + '&webGL='+(this.supportsWebGL() ? 1 : 0) + '&hashtml5video='+(this.supportsHtml5Video() ? 1 : 0);  
            src += '&isknownpcbrowser='+(this.getIsKnownPcBrowser() ? 1 : 0 );           
              
            src += '&r='+Math.floor(Math.random()*1000000);
            
            img.src = src; 
            console.log(src);
            document.querySelector('body').appendChild(img);
        }
        
    } 
    
       
}

//alert(DetectRight.android.isAppInstalled('com.zzforplay'));
