﻿/**
* A browser-side widget for displaying a Google Map overlayed with markers
* which when clicked, display a traffic camera with options for users
* to add cameras to favourites (cookie based storage).
* 
* @constructor
* @author Craig Nagy (craig dot nagy AT rci dot rogers dot com)
* @version 1.0
*/

if (typeof (com) == 'undefined') com = {};
if (typeof (com.rogers) == 'undefined') com.rogers = {};
if (typeof (com.rogers.traffic) == 'undefined') com.rogers.traffic = {};

com.rogers.traffic.Cameras = function (camera_markers, options) {
    var config = jQuery.extend({

        rotatorTarget: "",
        rotatorRefreshSpeed: 180000, // refresh speed in milliseconds (3min = 180000)
        rotatorSpeed: 5000, 	      // rotation speed in milliseconds

        dashboardTarget: "",
        dashboardCameras: "<ul id='cam-dashboard'></ul>",
        dashboardTitle: "<h2 style='clear:both;padding-top:1em;'>Favourite Cameras</h2>",
        dashboardMessage: "<p id='cam-dashboard-msg'></p>",
        dashboardRefreshSpeed: 180000,  // (3min = 180000)
        dashboardRefreshCookie: "dashboardRefresh",

        mapTarget: "#cam-map",
        mapPreviewClass: "cam-preview",
        mapCenterX: 43.741169984847446,
        mapCenterY: -79.42590809499603,

        favsCookie: "camCookie",
        favsCookieParams: { expires: 365 },
        favsDefault: [190], // array of IDs of default favourites


        // Images
        img: {
            rotatorLoading: "http://tools.citytv.com/traffic/images/camera-loading.gif",
            rotatorNotFound: "http://tools.citytv.com/traffic/images/camera-not-found.gif",
            rotatorNone: "http://tools.citytv.com/traffic/images/camera-none.gif",
            dashboardLoading: "http://tools.citytv.com/traffic/images/camera-loading-s.gif",
            dashboardNotFound: "http://tools.citytv.com/traffic/images/camera-not-found.gif",
            mapIcon: "http://tools.citytv.com/traffic/images/cameraIcon-bluedot.png"
        },

        // Language
        lang: {
            camLoading: "Loading...",
            favTitle: "Favourite Cameras",
            favAdd: "Add to Favourite Cameras",
            favDel: "Remove",
            favEdit: "Edit Cameras",
            btnStop: "stop",
            btnPlay: "play",
            btnNext: "next &raquo;",
            btnPrev: "&laquo; prev",
            msgIncompat: "<p>Sorry, the Google Maps API is not compatible with this browser</p>",
            msgCookies: "You must <a href='http://www.google.com/cookies.html'>enable cookies</a> to save your favourite cameras.",
            msgNoFavs: "Use the map to choose your favourite traffic cameras!"
        },

        styles: {
            dashCameraCSS: { 'width': '45%', 'float': 'left', 'padding-right': '3%', 'padding-top': '10px' },
            dashCameraImageCSS: { 'width': '100%', 'height': '225px' },
            mapContainerCSS: { 'float': 'left', 'width': '375px', 'height': '300px' },
            mapPreviewCSS: { 'width': '250px', 'height': '300px', 'float': 'right' },
            mapPreviewImageCSS: { 'width': '100%' },
            rotatorImageCSS: { 'width': '280px' },
            rotatorLabel: { 'clear': 'left', 'display': 'block' }
        },

        debug: true

    }, options);

    // DATA
    var cameras = []; // array of active camera IDs
    var data = camera_markers;

    // MODES
    var useDashboard = true;
    var useRotator = true;
    var useGMapInfoWindow = false;

    // SINGLE CAMERA
    var camIdx = 0; // index into the array of cameras being displayed
    var camRefreshTimer; // timed interval for refreshing the next camera
    var camRotateTimer; // timed interval for moving to the next camera
    var isCamRotating = true;

    // JQUERY REFERENCES
    var $map;
    var $dash;
    var $dash_msg;
    var $dash_controls;
    var $dash_refresh;
    var $dash_clear;

    var $rotator;
    var $rotator_img;
    var $rotator_controls;
    var $rotator_label;

    // GOOGLE MAP
    var gMapIcon;
    var gMap;

    var self = this;

    /***************************************************************
    CAMERA ROTATOR (FOR SIDEBAR)
    ***************************************************************/

    /**
    * Initialization function for traffic cameras displayed
    * in a user configurable rotation.
    * Only call this function once!
    */
    this.initRotator = function () {

        self.log("initRotator():");

        $rotator = $(config.rotatorTarget);
        $rotator_image = $(['<img src="', config.img.rotatorLoading, '"/>'].join(''))
							.appendTo(config.rotatorTarget)
							.css(config.styles.rotatorImageCSS);
        $rotator_label = $(['<label>', config.lang.camLoading, '</label>'].join(''))
							.appendTo(config.rotatorTarget)
							.css(config.styles.rotatorLabel);
        $rotator_controls = $(['<div id="rot-nav">',
									'<a id="rot-prev" href="#">', config.lang.btnPrev, '</a> ',
									'<a id="rot-playstop" href="#">', config.lang.btnStop, '</a> ',
									'<a id="rot-next" href="#">', config.lang.btnNext, '</a> ',
								'</div>'].join('')).appendTo(config.rotatorTarget);


        // Bind click events to the camera controls/buttons
        $("#rot-prev").click(function () { self.prevCamera(); return false; });
        $("#rot-next").click(function () { self.setCameraTimers(false); self.nextCamera(); return false; });
        $("#rot-playstop").click(function () {
            self.setCameraTimers(!isCamRotating);
            if (isCamRotating) {
                self.nextCamera();
            }
            return false;
        });

        self.loadCameraFavouites();
        self.updateCameraControls(); 	// set the state of the buttons
        self.updateCameraSingle(); 		// display the first camera immediately	
    };

    /**
    * Update the current camera image displayed. Call this function after
    * changing the camIdx value. The src attribute of the image (homeImgCamera) 
    * is updated to reflect the new image URL.
    */
    this.updateCameraSingle = function () {
        self.log("updateCameraSingle()", cameras, camIdx);
        if (cameras[camIdx]) {
            var src = data[cameras[camIdx]].img;
            var label = data[cameras[camIdx]].label;

            // temporarily stop rotation until the next camera loads
            self.rotateTimer(false);

            // Display a loading placeholder
            if (cameras.length > 1) {
                self.cameraLabel(config.lang.camLoading);
                self.cameraImage(config.img.rotatorLoading);
            }
            self.cameraLabel(label);
            self.cameraImage(src);
            self.rotateTimer(isCamRotating); // continue rotating
        }
        else {
            // The camera was removed. The existing timed intervals
            // will move to the next one. If no cameras exist, we should
            // display a special graphic until one does.
            if (cameras.length < 1) {
                self.cameraImage(config.img.rotatorNone);
                self.cameraLabel('');
            }
        }
    };

    /**
    * Turns the rotation interval on or off.
    */
    this.rotateTimer = function (on) {
        if (on) {
            camRotateTimer = setInterval(self.nextCamera, config.rotatorSpeed);
        } else {
            clearInterval(camRotateTimer); // stops the interval	
        }
    };

    /**
    * Turns the refreshing interval on or off.
    */
    this.refreshTimer = function (on) {
        if (on) {
            camRefreshTimer = setInterval(self.updateCameraSingle, config.rotatorRefreshSpeed);
        } else {
            clearInterval(camRefreshTimer); // stops the interval	
        }
    };

    /**
    * Sets the camera timers:
    *  - If rotation is on, set a timer to go to the next camera
    *  - If rotation is off, set a timer to refresh the camera
    */
    this.setCameraTimers = function (rotate) {
        isCamRotating = rotate;
        clearInterval(camRotateTimer);
        clearInterval(camRefreshTimer);

        if (isCamRotating) {
            self.rotateTimer(true); // stops the interval
        } else {
            self.refreshTimer(true);
        }

        self.updateCameraControls();
    };

    /**
    * Display the next traffic camera in the home Camera Array
    */
    this.nextCamera = function () {
        camIdx = self.getNextcamIdx();
        self.updateCameraSingle(); // calls function to switch camera passing in new ID
    };

    /**
    * Returns the index for the next camera in the cameras.
    * This implementation supports wrapping around to the first camera.
    */
    this.getNextcamIdx = function () {
        if (cameras[camIdx + 1]) {
            return camIdx + 1;
        } else {
            return 0;
        }
    };

    /**
    * Display the previous traffic camera in the cameras.
    */
    this.prevCamera = function () {
        self.setCameraTimers(false); // if we are going backwards, we automatically stop the rotation
        camIdx = self.getPrevcamIdx();
        self.updateCameraSingle(); // calls function to switch camera passing in new ID
    };

    /**
    * Returns the index for the previous camera in the cameras.
    * This implementation supports wrapping around to the last camera if
    * the current display is the first camera.
    */
    this.getPrevcamIdx = function () {
        if (camIdx == 1) {
            return cameras.length - 1;
        } else {
            return camIdx - 1;
        }
    };

    /**
    * Sets the state of the camera navigation buttons
    * depending on the current settings.
    */
    this.updateCameraControls = function () {
        if (isCamRotating) {
            $("#rot-playstop").text(config.lang.btnStop);
        } else {
            $("#rot-playstop").text(config.lang.btnPlay);
        }
    };

    /***************************************************************
    DASHBOARD FUNCTIONS
    ***************************************************************/

    /**
    * Initialize the display of the visitors favourite traffic cameras
    * (dashboard) as stored in a cookie.
    */
    this.initDashboard = function () {
        self.log("initDashboard()");

        $(config.dashboardTitle).appendTo(config.dashboardTarget);
        $dash_msg = $(config.dashboardMessage).appendTo(config.dashboardTarget);
        $dash = $(config.dashboardCameras).appendTo(config.dashboardTarget);
        $dash.before('<div id="dashboard-ctrls">' +
					'<input type="checkbox" id="dash-refresh"/> ' +
					'<label for="dash-refresh">Auto Refresh</label> ' +
					' | <a href="#" id="dash-clear">Remove All</a> ' +
					'</div>');
        $dash_controls = $('#dashboard-ctrls');
        $dash_refresh = $('#dash-refresh');
        $dash_clear = $('#dash-clear');

        if ($.isCookiesOn()) {
            // if there are no favourites don't show the default cameras.
            if (!self.loadCameraFavouites()) {
                //	cameras = [];
            }
            if (cameras.length > 0) self.previewCamera(cameras[0]);

            self.bindDashboardControls();
            self.updateCameraDashboard();

            $dash_refresh.get(0).checked = $.cookie(config.dashboardRefreshCookie) == null;
            self.dashboardRefresh();

        }
        else {
            self.dashboardMsg(config.lang.msgCookies);
        }

    };

    /**
    * Update all cameras in the dashboard with the latest camera image.
    */
    this.updateCameraDashboard = function () {
        self.log("updateCameraDashboard");
        if (cameras.length > 0) {
            $dash_msg.hide();
            $dash_controls.show();
            // show all favourite cameras
            for (var i = 0; i < cameras.length; i++) {
                self.showCamera(cameras[i]);
            }
        }
        else {
            self.dashboardMsg(config.lang.msgNoFavs);
        }
    };

    /**
    * Binds click events to the dashboard controls (refresh, remove all)
    */
    this.bindDashboardControls = function () {
        self.log('bindDashboardControls', $dash_clear);
        $dash_clear.click(function () {
            self.removeCameraFavs();
            self.updateCameraDashboard();
            return false;
        });
        $dash_refresh.click(function () { self.toggleDashboardRefresh(); });
    };


    /**
    * Adds a given camera (ID) to the user's list of favourites.
    * Updates the camera array and saves it to a cookie.
    */
    this.addCameraFav = function (id) {
        self.log("addCameraFav()", id);
        if (self.indexOfCamFav(id) == -1) {
            cameras.push(id);
            self.saveCameras();
            self.bindPreviewAction(id);
            self.updateCameraDashboard();
        }
        gMap.closeInfoWindow();
    };

    /**
    * Removes a given camera (ID) from the user's list of favourites.
    * Updates the camera array and saves it to a cookie.
    */
    this.removeCameraFav = function (id) {
        self.log("removeCameraFav()", id);
        var removeID = self.indexOfCamFav(id);
        if (removeID > -1) {
            cameras.remove(removeID);
            self.saveCameras();
            self.bindPreviewAction(id);
            $("#camera" + id).fadeOut("slow"); // hides the camera from the dashboard
            self.updateCameraDashboard();

        }
        gMap.closeInfoWindow();
    };

    /**
    * Removes ALL camera favourites
    */
    this.removeCameraFavs = function () {
        self.log('removeCameraFavs');
        // hide the cameras from the dashboard
        for (var i = 0; i <= cameras.length; i++) {
            $("#camera" + cameras[i]).fadeOut("slow");
        }
        cameras = []; // empty the array
        self.saveCameras();
    };

    /**
    * Shows a camera (by ID) in the favourites dashboard. The generated DOM 
    * chunk is a new list item.
    */
    this.showCamera = function (id) {
        self.log("showCamera", id);
        var camID = "camera" + id;
        var imgID = "img" + id;

        // checks if camera exists as it could have been
        // added and hidden when removed
        if ($("#" + camID).length) {
            // reshows the hidden camera
            $("#" + camID).show();
        }
        else {
            // add the html to the dashboard
            var cam = [
				"<li id='", camID, "' class='camera'>",
				"<label>", data[id].label, "</label>",
				"<img id='", imgID, "' src='", config.img.dashboardLoading, "'>",
				"<a href='#'>", config.lang.favDel, "</a></li>"
			];

            $dash.append(cam.join(''));

            $("#" + camID).css(config.styles.dashCameraCSS);
            $("#" + camID).find('img').css(config.styles.dashCameraImageCSS);
            $("#" + camID).find('a').click(function () {
                self.removeCameraFav(id);
                return false;
            });
        }
        var imgSrc = data[id].img + self.cacheKill();
        self.cameraImage(imgSrc, id);
    };

    /**
    * Returns a query parameter to kill any caching that
    * might occur with the traffic camera image.
    */
    this.cacheKill = function () {
        return "?ck=" + new Date().getTime();
    };

    /**
    * Turns dashboard refreshing on or off by setting
    * a preference cookie.
    */
    this.toggleDashboardRefresh = function () {
        self.log("toggleDashboardRefresh()");
        if (!$dash_refresh.get(0).checked) {
            $.cookie(config.dashboardRefreshCookie, "off", config.favsCookieParams);
        }
        else {
            $.cookie(config.dashboardRefreshCookie, null);
        }
    };

    /**
    * Refreshes all camera images in the dashboard by looping
    * through the cameras and setting their source to the same
    * source, prompting the browser to get the latest version.
    */
    this.dashboardRefresh = function () {
        if ($.cookie(config.dashboardRefreshCookie) == null) {
            self.log("dashboardRefresh()", cameras);
            for (var i = 0; i < cameras.length; i++) {
                var src = data[self.indexOfCamFav(cameras[i])].img + self.cacheKill();
                $("#camera" + cameras[i] + " img").attr("src", src);
            }
        }
        setTimeout(self.dashboardRefresh, config.dashboardRefreshSpeed);
    };

    /**
    * Saves the current array of cameras to a
    * cookie for loading later (favourites).
    */
    this.dashboardMsg = function (msg) {
        $dash_controls.hide();
        $dash_msg.text(msg).show();
    };

    /**
    * Saves the current array of cameras to a
    * cookie for loading later (favourites).
    */
    this.saveCameras = function () {
        self.log("saveCameras()", cameras);
        if (cameras.length) {
            $.cookie(config.favsCookie, cameras.join('|'), config.favsCookieParams);
            self.log("saved!");
        }
        else {
            $.cookie(config.favsCookie, null);
        }
    };

    /***************************************************************
    MAP FUNCTIONS
    ***************************************************************/

    /**
    * Initialize the Google Map and adds all of the camera Map Markers
    */
    this.initMap = function () {
        self.log("initMap()");
        $map = $(['<div id="', config.mapTarget.replace('#', ''), '"></div>'].join(''))
					.appendTo(config.dashboardTarget)
					.css(config.styles.mapContainerCSS);
        if (GBrowserIsCompatible()) {
            gMapIcon = new GIcon();
            gMapIcon.image = config.img.mapIcon;
            gMapIcon.iconSize = new GSize(8, 8);
            gMapIcon.iconAnchor = new GPoint(4, 4);
            gMapIcon.infoWindowAnchor = new GPoint(4, 4);
            gMap = new GMap2($map.get(0));
            gMap.addControl(new GSmallMapControl());
            gMap.addControl(new GMapTypeControl());
            gMap.setCenter(new GLatLng(config.mapCenterX, config.mapCenterY), 11);

            // Add a map marker for each camera
            for (var id = 0; id < data.length; id++) {
                if (data[id].lat && data[id].lng) {
                    self.addCameraMarker(id);
                }
            }

            $(window).unload(function () { GUnload(); });

        } else {
            $map.html(config.lang.msgIncompat);
        }
    };

    /**
    * Creates a Google Map Marker (GMarker), attaches click events to the marker
    * for displaying the informatino window, and adds the marker to the map.
    */
    this.addCameraMarker = function (id) {
        var point = new GLatLng(data[id].lat, data[id].lng);
        var marker = new GMarker(point, gMapIcon);
        gMap.addOverlay(marker);
        GEvent.addListener(marker, "click", function () { self.previewCamera(id); });
        return true;
    };

    /**
    * Displays a camera for further user interaction. This is generally
    * called when a marker is clicked on the map.
    */
    this.previewCamera = function (id) {
        $('.' + config.mapPreviewClass).remove();
        $(self.previewHtml(id)).insertAfter(config.mapTarget)
				.css(config.styles.mapPreviewCSS);
        self.bindPreviewAction(id);
        $('#' + config.mapPreviewClass + id).find('img')
				.attr("src", data[id].img)
				.css(config.styles.mapPreviewImageCSS);
    };

    /**
    * Helper to setup the links (actions) for the camera preview
    */
    this.bindPreviewAction = function (id) {
        if ($.isCookiesOn()) {
            var $cam_link = $('#' + config.mapPreviewClass + id + " a");
            if (self.indexOfCamFav(id) > -1) {
                // is a favourite, so it can be removed
                $cam_link.unbind("click")
						 .text(config.lang.favDel)
						 .click(function () {
						     self.removeCameraFav(id);
						     return false;
						 });
            } else {
                // not a favourite, can be added
                $cam_link.unbind("click")
						 .text(config.lang.favAdd)
						 .click(function () {
						     self.addCameraFav(id);
						     return false;
						 });
            }
        }
    };

    /**
    * Generates and returns the HTML for previewing a camera
    */
    this.previewHtml = function (id) {
        return [
		"<div class='", config.mapPreviewClass, "' id='", config.mapPreviewClass, id, "'>",
		"<label id='label", id, "'>", data[id].label, "</label><br/>",
		"<img src='", config.img.dashboardLoading, "'><br/>",
		"<a href='#'></a>",
		"</div>"
		].join('');
    };

    /***************************************************************
    GENERIC FUNCTIONS
    ***************************************************************/

    /**
    * Checks if a camera is a favouirte by searching for
    * the existence of the given id in the array
    * @return index of the favourite.
    */
    this.indexOfCamFav = function (id) {
        for (var i = 0; i <= cameras.length; i++) {
            if (parseInt(cameras[i], 10) === parseInt(id, 10)) return i;
        }
        return -1;
    };

    /**
    * Load any favouite camera IDs into the cameras array. If no
    * favourite are saved, load the default cameras.
    * @return true Returns true if there are saved favouites, false otherwise
    */
    this.loadCameraFavouites = function () {
        var tmpCookie = $.cookie(config.favsCookie);

        if (tmpCookie) {
            cameras = tmpCookie.split("|");
        }
        self.log("loadCameraFavouites()", tmpCookie, cameras);

        if (cameras.length > 0) {
            return true;
        } else {
            cameras = config.favsDefault;
            return false;
        }
    };

    /**
    * A debugging function for the traffic cameras (requires Firebug).
    */
    this.log = function () {
        if (config.debug) {
            if (window.console) {
                //console.debug.apply(console, arguments);
            } else if ($("#cameraDebug").length) {
                var out = [];
                out.push("<p>");
                for (var i = 0; i < arguments.length; i++) {
                    out.push(arguments[i].toString());
                    out.push(", ");
                }
                out.push("</p>");
                $("#cameraDebug").prepend(out.join(''));
            }
        }
    };

    /**
    * Sets the text of the label for the current camera
    * or a specific camera id.
    */
    this.cameraLabel = function (text, id) {
        if (arguments.length == 1) {
            if (useRotator) $rotator.find("label").text(text);
        } else {
            $("#camera" + id + " label").text(text);
        }
    };

    /**
    * Sets the image for the current camera or
    * for a specific camera id.
    */
    this.cameraImage = function (url, id) {
        if (arguments.length == 1) {
            if (useRotator) {
                $rotator_image.attr("src", url);
            }
        }
        else {
            $("#camera" + id + " img").attr("src", url);
        }
    };

    /**
    * Initializes the widget for display
    */
    this.init = function () {
        // after the page has finished loading...
        $(function () {
            self.log("init");

            useDashboard = config.dashboardTarget.length > 1 && $(config.dashboardTarget).length == 1;
            useRotator = config.rotatorTarget.length > 1 && $(config.rotatorTarget).length == 1;

            if (!useDashboard && !useRotator) {
                //alert("No target IDs are set or exist in the document. You must supply the dashboardTarget and/or rotatorTarget");
                return false;
            }
            else {
                if (useDashboard) {
                    self.initMap();
                    self.initDashboard();
                }

                if (useRotator) {
                    self.initRotator();
                }
            }
        });
    };
    this.init();

};

/***************************************************************
UTILS
***************************************************************/

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function (from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};

/**
* Create a cookie with the given name and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
*       used when the cookie was set.
*
* @param String name The name of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
*                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
*                             If set to null or omitted, the cookie will be a session cookie and will not be retained
*                             when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
*                        require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/

/**
* Get the value of a cookie with the given name.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String name The name of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function (name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

jQuery.isCookiesOn = function () {
    var tmp = "TESTCOOKIE";
    $.cookie(tmp, tmp);
    if ($.cookie(tmp)) {
        $.cookie(tmp, null);
        return true;
    }
    return false;
};


