
//CONTENT FUNCTION - calls to this function come from db loaded content and not code within the codebase
function run_vds_demo (){
    MM_openBrWindow('http://corporate.trafficland.com/demo/','','width=770,height=450');
}
//CONTENT FUNCTION - calls to this function come from db loaded content and not code within the codebase
function load_intro_slideshow (){
    AC_FL_RunContent( 'codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0','width','350','height','263','src','promo_slides','quality','high','pluginspage','http://www.macromedia.com/go/getflashplayer','movie','promo_slides' ); //end AC code
}

/***********************************
 Basic Utility Functions
 *************************************/

var js_version = "3.2.7";
var map_bookmark_link;
function getJSVersion() {
    return js_version;
}
function fadeIn(element) {
  //  setOpacity(element, 0);
    element.setOpacity(0);
    activate(element, 'block');
    for (var i = 0; i <= 100; i += 5) {
        (function() {
            setTimeout(function() {
                element.setOpacity(i);
            }, (i + 1) * 10);
        })();
    }
}
Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};
 
function appendAll() {
    var target = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
        target.appendChild(arguments[i]);
    }
};
function createTextElement(text, element) {
    var targetText = document.createTextNode(text);
    var targetElement = document.createElement(element);
    targetElement.appendChild(targetText);
    return targetElement;
};

function toggle(element) {
    if (document.getElementById(element).style.display != 'block') {
        document.getElementById(element).style.display = 'block';
    } else {
        document.getElementById(element).style.display = 'none';
    }
};
function activate(element, mode) {//element= target , mode= block,none,inline etc.
    if (typeof element == 'string')
        element = document.getElementById(element);
    element.style.display = mode;
};

function removeFrom(element) {
    element.parentNode.removeChild(element);
};
function clearTextBox(textBox) {
    textBox.value = '';
    textBox.style.color = 'black';
}
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}
function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft,curtop];
}
function arraySearch(searchItem, arrayname) {
    var searchResults = false;
    for (var i = 0; i < arrayname.length; i++) {
        if (arrayname[i] == searchItem) {
            searchResults = true;
            break;
        }
    }
    return searchResults;
}

function showHelper() {
    var helper = document.getElementById('helper');
    var text ;
    if (arguments.length < 2)
        text = document.createTextNode(this.desctxt);
    else
        text = document.createTextNode(arguments[0] + ': ' + arguments[1]);
    
    helper.innerHTML = '';
    helper.setOpacity(0.8);
    var helperText = $('helpertxt');
    activate(helper, 'block');
    helper.appendChild(text);
}

function hideHelper() {
    var helper = document.getElementById('helper');
    helper.innerHTML = '';
    activate(helper, 'none');
}

function getMousePos(e) {
    var posx = 0;
    var posy = 0;
    if (!e) var e = window.event;
    if (e.pageX || e.pageY) {
        posx = e.pageX;
        posy = e.pageY;
    }else if (e.clientX || e.clientY) {
        posx = e.clientX + document.body.scrollLeft
                + document.documentElement.scrollLeft;
        posy = e.clientY + document.body.scrollTop
                + document.documentElement.scrollTop;
    }
    if ($('helper')) {
        var widowWidth = document.documentElement.clientWidth || document.body.clientWidth;
        var widowHeight = document.documentElement.clientHeight || document.body.clientHeight;
        var helperPosX = posx + ($('helper').offsetWidth);
        var helperPosY = posy + ($('helper').offsetHeight);
        $('helper').style.left = posx + "px";
        $('helper').style.top = posy + 30 + "px";

        if (helperPosX > widowWidth) {
            $('helper').style.left = posx - ($('helper').offsetWidth) + "px";
        }

        if (helperPosY > widowHeight) {
            $('helper').style.top = posy - (10 + ($('helper').offsetHeight)) + "px";
        }
    }
}

function updateTitle(desc) {
    document.title = "TrafficLand.com -- " + desc;
}
/* End of utility functions  */
var tl_alert = {
    area: "alerts",
    make: function(message) {
        if (message == '') {
            var a = document.getElementById("alerts");
            a.style.display = "none";
            return;
        }
        $('alertcontent').innerHTML = '';
        var area = this.area;
        this.insertMessage(message);
        activate($(area), "block");
        fadeIn($(area));
    },
    insertMessage: function(message) {
        var area = $(this.area);
        var content = $('alertcontent');
        message = createTextElement(message + "  ", 'p');
        var close = new Element('a',{"class":"closealert",href:"javascript:void(tl_alert.close())"}).update("Hide this Alert");
        message.appendChild(close);
        appendAll(content, message);
    },
    close: function() {
        var a = $("alerts");
        a.style.display = "none";
    }
}

function loadArea() {
    if (arraySearch("city", urlArray)) {
        var url = "/data/city.xml?system=pub&pubtoken="+ token;
        var data = "";
        var countries;
        countries = new Ajax.Request(url, {method: 'get', parameters: data, onComplete: goToArea });
    }
};
function rsidCheck() {
    var url = window.location.toString();
    var fullRsid = url.substring((url.indexOf('?') ), url.length);
    var rsid = '';
    var rsidArray = new Array;
    rsidArray = fullRsid.split('=');
    if (rsidArray[0] == '?rsid') {
        rsid = fullRsid;
    }
    return rsid;
};
function getPartner() {
    var n = '';
    if (rsidCheck() != '') {
        p = rsidCheck();
        p = p.split('=');
        return "partner=" + p[1] + ";";
    } else {
        return n;
    }
};
function esidCheck() {
    var url = window.location.toString();
    var fullEsid = url.substring((url.indexOf('?') ), url.length);
    var esid = '';
    var esidArray = new Array;
    esidArray = fullEsid.split('=');
    if (esidArray[0] == '?esid') {
        esid = fullEsid;
    }
    return esid;
};
function pageCounter(location) {
    var url2 = '';
    var data2 = "";
    var cameras;
    var rsid = rsidCheck();
    var esid = esidCheck();
    if (tluser.status == 'inactive') {
        url2 = location + "standard" + rsid + esid;
    } else if (tluser.isPremium) {
        url2 = location + "premium" + rsid + esid;
    } else {
        url2 = location + "registered" + rsid + esid;
    }
    cameras = new Ajax.Request(url2, {method: 'get', parameters: data2 });
}


function gaPageCounter(pageName, contentCategory) {
    if (tlHBXCobrandContent != 'null') contentCategory += "/cobrand/" + tlHBXCobrandContent;
    var GA_content = contentCategory.replace(/\//g,".");
    _gaq.push(['_trackPageview',contentCategory],['_setCustomVar',1, 'tltitle', GA_content ],['_setDomainName', 'none'],['_setAllowLinker', true]);

 }
function loadMultiCameras(lat,lng){
    var html ="<h3 class='map_multilist_header'>multiple camera location:</h3><ul id='map_multilist'>",infoBoxOptions,mInfo="";
    var  action = function(c){
        var xml = c.responseXML;
        var cameras = xml.getElementsByTagName('camera');
        for (var i = 0; i < cameras.length; i++) {
            var multimarker = {};
            var webid = cameras[i].getAttribute('webid');
            var desc = cameras[i].getAttribute('desc');
            var orientation = cameras[i].getAttribute('orientation');
            var provider = cameras[i].getAttribute('provider');
            var rate = cameras[i].getAttribute('refreshRate');
            var zip = cameras[i].getAttribute('zipCode');
            var citycode  = cameras[i].getAttribute('cityCode');

            mInfo = "'"+webid+"','"+desc+"','"+orientation+"','"+provider+"','"+rate+"','"+zip+"','"+citycode+"'";
            html +="<li><a onclick=\"showMulti("+mInfo+")\"  >"+ desc+"</a></li>";
        }

        html +="</ul>";
        var target = new GLatLng(lat, lng);
        map.openInfoWindow(target,html);
    }

    var url = "/data/data.xml?swlat=" + lat + "&swlng=" + lng + "&nelat=" + lat + "&nelng=" + lng + "&system=pub&pubtoken=" + token;
    var data = "";
    var cams;
    cams = new Ajax.Request(url, {method: 'get', parameters: data, onComplete: action });

};
function showMulti(webid,desc,orientation,provider,rate,zipcode,citycode){
     var videoImage = document.getElementById("videoImage");
    if (video._id != '') {
        video.clear_vars();
        video.clear_metadata();
        videoImage.style.display = 'none';
        clearInterval(ourInterval);
    }
    // load_weather(this.zipcode, this.citycode);
    // Log AJAX page view on camera click
    pageCounter("/city/" + citycode + "/camera/" + webid + "/");
    gaPageCounter("TrafficLand.com -- " +desc, "/city/" + citycode + "/camera/" + webid);
    showImage(webid, desc, orientation, provider, rate, zipcode, citycode, true);
}
function loadCamera(load) {
    var xml = load.responseXML;
    var cameras = xml.getElementsByTagName('camera');
    var videoImage = document.getElementById("videoImage");
    for (var i = 0; i < cameras.length; i++) {
        if (cameras[i].getAttribute('webid') == urlArray[3]) {
            if ((video._id != '') && (recentViews.list.length != 0)) {
                video.clear_vars();
                video.clear_metadata();
                videoImage.style.display = 'none';
            }
            var webid = cameras[i].getAttribute('webid');
            var desc = cameras[i].getAttribute('desc');
            var orientation = cameras[i].getAttribute('orientation');
            var provider = cameras[i].getAttribute('provider');
            var rate = cameras[i].getAttribute('refreshRate');
            var zip = cameras[i].getAttribute('zipCode');

            showImage(webid, desc, orientation, provider, rate, zip, cameras[i].getAttribute('cityCode'), true);

        }
    }
};
function updateCityBookmarkLink (relative){
    //you cant be nowhere
    //check for ? rsid - split (?) &
    var root = self.location.protocol + '//' + self.location.hostname + '/' + relative ;
    var queryString = '';
    if (self.location.href.indexOf('?',0) > 0)
        queryString = self.location.href.substring(self.location.href.indexOf('?',0), self.location.href.length);
     map_bookmark_link = root + queryString ;
};
function initCamera(webid, desc, orientation, provider, rate, zipCode, cityCode) {
    var videoImage = document.getElementById("videoImage");
    if ((video._id != '') && (recentViews.list.length != 0)) {
        video.clear_vars();
        video.clear_metadata();
        videoImage.style.display = 'none';
    }
    showImage(webid, desc, orientation, provider, rate, zipCode, cityCode, false);
};

function goToArea(load) {
    var xml = load.responseXML;
    var area = xml.getElementsByTagName('city');
    var locationMenu = new Array;
    var cityname = document.getElementById('cityname').getElementsByTagName("h5")[0];
    activate('menu_instruct', 'none');
    activate(cityname.parentNode, 'inline');
    while (document.getElementById("world").nextSibling) {
        cityname.removeChild(cityname.lastChild);
    }
    for (var i = 0; i < area.length; i++) {
        if (area[i].getAttribute('code') == urlArray[1]) {
            var message = area[i].getAttribute('alert');
            tl_alert.make(message);
            var map_start = $('map_start');
            map_start.style.display = 'none';
            var mapArea = $('map');
            mapArea.style.display = "block";
            loadGmap(area[i].getAttribute('lat'), area[i].getAttribute('lon'), area[i].getAttribute('zoomLevel'));
            locationMenu.push(area[i].getAttribute('name'));
            locationMenu.push(area[i].parentNode.getAttribute('name'));
            if (area[i].parentNode.parentNode.tagName != 'countries') {
                locationMenu.push(area[i].parentNode.parentNode.getAttribute('name'));
            }
            if (!arraySearch('camera', urlArray)) {
                updateTitle(area[i].getAttribute('name'));
            }
            break;
        }

    }
    locationMenu.reverse();
    var lastNodeIsCity = 0 ;
    for (var j = 0; j < locationMenu.length; j++) {
        var areaLink = new Element('a').update(locationMenu[j]);
        var type = '';
        if (locationMenu.length < 3) {
            if (j == 0) {
                type = 'city';
                areaLink.id = 'citylink';
                areaLink.href = "javascript: load_map_menu('" + locationMenu[j] + "','" + type + "')";
            }
            if (j == 1) {
                areaLink.id = 'citytitle';
                lastNodeIsCity = 1;
            }
        } else {
            if (j == 0) {
                type = 'state';
                areaLink.id = 'statelink';
                areaLink.href = "javascript: load_map_menu('" + locationMenu[j] + "','" + type + "')";
            } else if (j == 1) {
                type = 'city';
                areaLink.id = 'citylink';
                areaLink.href = "javascript: load_map_menu('" + locationMenu[j] + "','" + type + "')";
            } else {
                areaLink.id = 'citytitle';
                lastNodeIsCity = 1;
            }
        }
        cityname.appendChild(areaLink);
    }
};

function estArea(area, type) {
    var area;
    var type;
    this.getArea = function() {
        if (area == '') {
            area = null;
        }
        return  area;
    }
    this.getType = function() {
        return  type;
    }
};

function attach_map_function() {
    var map_start = document.getElementById('map_start');
    var mapElement = map_start.getElementsByTagName('li');
    for (var i = 0; i < mapElement.length; i++) {
        mapElement[i].onclick = load_map_menu;
        mapElement[i].onmouseover = changeBkgnd;
        mapElement[i].onmouseout = changeBkgnd2;
    }
}
var type = "";
var area = "";
function load_map_menu() {
    if (arguments.length > 1) {
        area = arguments[0];
        type = arguments[1];
    } else {
        area = this.id;
        type = this.className;
    }
    if (area == "" && type == "country"){
        city = "" ;
    }
    var cityname = document.getElementById('cityname').getElementsByTagName("h5")[0];
    if (type != 'country') {
        activate('menu_instruct', 'none');
        activate(cityname.parentNode, 'inline');
    }
    var linkId = type + "link";
    var areaLink = new Element('a',{id:linkId,href:"javascript: load_map_menu('" + area + "','" + type + "');"}).update(area);

    var oldChild = document.getElementById(linkId);
    if (area == '') {
        linkId = 'world'
    }
    if (document.getElementById(linkId)) {
        while (document.getElementById(linkId).nextSibling) {
            cityname.removeChild(cityname.lastChild);
        }
        if (linkId != 'world') {
            cityname.replaceChild(areaLink, oldChild);
        }
    } else {
        cityname.appendChild(areaLink);
    }
    var map_start = document.getElementById('map_start');
    map_start.innerHTML = '';

    window.currentArea = new estArea(area, type);
    var url = "/data/city.xml?system=pub&pubtoken=" + token;
    var data = "";
    var countries;
    countries = new Ajax.Request(url, {method: 'get', parameters: data, onComplete:  build_map_menu });
}
 
function menu_over(){
    this.style.textDecoration =  "underline";
    this.style.backgroundPosition = "2px 50%" ;
}
function menu_out(){
    this.style.backgroundPosition = "100% -700%" ;
    this.style.textDecoration =  "none";
}

function build_map_menu(load) {
    var menu_width = 620;
    var menu_rows = 0;
    var menu_columns = 0;
    var xml = load.responseXML;
    var areaType = xml.getElementsByTagName(currentArea.getType());
    var map_start = document.getElementById('map_start');
    var addList = new Element('ul',{id:"list 1",'class':"map_menu_list"});
    var addList2 = new Element('ul',{id:"list 2",'class':"map_menu_list"});
    var addList3 = new Element('ul',{id:"list 3",'class':"map_menu_list"});
    if (map_start.style.display == "none"){
        showMapMenu();
    }
    for (var i = 0; i < areaType.length; i++) {
        var parent = areaType[i].parentNode;
        if (parent.getAttribute('name') == currentArea.getArea() && areaType[i].getAttribute('name') != "N/A") {
            menu_rows++;
            var name = areaType[i].getAttribute('name');
            var type = '';
            if (areaType[i].getElementsByTagName('state')[0]) {
                type = 'state';
            } else {
                type = 'city';
            }
            var point = areaType[i].getAttribute('lat') + ", " + areaType[i].getAttribute('lon');
            var zoomLevel = areaType[i].getAttribute('zoomLevel');
            var li = new Element('li');
            var txt = document.createTextNode(name) ;
            li.onmouseover =  menu_over;
            li.onmouseout =  menu_out;
            li.style.backgroundColor = i % 2? "#efefef" :"transparent";
            if (areaType[i].hasChildNodes()) {
                li.className = type;
                li.onclick = load_map_menu;
            } else {
                li.className = areaType[i].getAttribute('zip');
                li.citycode = areaType[i].getAttribute('code');
                li.alert = areaType[i].getAttribute('alert');
                li.onclick = showGmap;
            }
            li.id = name;
            li.appendChild(txt);
            li.title = "Go to: "+name;
            li.latLng = point;
            li.zoomLevel = zoomLevel;
            var menu_one = 12;
            var menu_two =  menu_one + menu_one ;
            if(menu_rows <= menu_one ){
                addList.appendChild(li);
            }else  if(menu_rows >  menu_one &&  menu_rows <=  menu_two ) {
                addList2.appendChild(li);
            }else{
                addList3.appendChild(li);
            }
            if (li.citycode == 'WAS') {
                updateCityBookmarkLink("city/" + li.citycode + "/index.html");
                showGmap.call(li);
                return;
            }

        }
    }
    if(menu_rows < menu_one ){
        addList.style.width =  menu_width+"px";
        map_start.appendChild(addList);
        menu_rows = 0;
    }else  if(menu_rows > menu_one &&  menu_rows < menu_two ) {
        addList.style.width =  (menu_width/2)+"px";
        addList2.style.width =  (menu_width/2)+"px";
        map_start.appendChild(addList);
        map_start.appendChild(addList2);
        menu_rows = 0;
    }else{
        addList.style.width =  (menu_width/3)+"px";
        addList2.style.width =  (menu_width/3)+"px";
        addList3.style.width =  (menu_width/3)+"px";
        map_start.appendChild(addList);
        map_start.appendChild(addList2);
        map_start.appendChild(addList3);
        menu_rows = 0;
    }
    if (document.getElementById('United States') && document.getElementById('United States') != addList.getElementsByTagName('div')[0]) {
        var usa = document.getElementById('United States') ;
        addList.removeChild(usa);
        addList.insertBefore(usa, addList.firstChild);
    }
}
var cameraMarkers = [];
function addCameraIconsToMap() {   //todo finish
       var web_number;
     for (var i = 0; i < markers.length; i++) {
        point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
        web_number  = markers[i].getAttribute("webid");
        if (markers[i].getAttribute("tempdis") == 'true'){
            window["cameraGMarker_"+web_number] = new GMarker(point, {icon:deadCameraIcon,title:'Camera temporarily unavailable : ' + markers[i].getAttribute("desc")});
            window["cameraGMarker_"+web_number].tempdis = markers[i].getAttribute("tempdis");
        }else{
            window["cameraGMarker_"+web_number] = new GMarker(point, {icon:normalCameraIcon,title:markers[i].getAttribute("desc")});
            window["cameraGMarker_"+web_number].webid = markers[i].getAttribute("webid");
            window["cameraGMarker_"+web_number].desc = markers[i].getAttribute("desc");
            window["cameraGMarker_"+web_number].multicam = eval(markers[i].getAttribute("multiCamLocation"));
            window["cameraGMarker_"+web_number].orientation = markers[i].getAttribute("orientation");
            window["cameraGMarker_"+web_number].provider = markers[i].getAttribute("provider");
            window["cameraGMarker_"+web_number].zipcode = markers[i].getAttribute("zipCode");
            window["cameraGMarker_"+web_number].citycode = markers[i].getAttribute("cityCode");
            window["cameraGMarker_"+web_number].rate = markers[i].getAttribute("refreshRate");
            window["cameraGMarker_"+web_number].lat = markers[i].getAttribute("lat");
            window["cameraGMarker_"+web_number].lng = markers[i].getAttribute("lng");
            window["cameraGMarker_"+web_number].tempdis = markers[i].getAttribute("tempdis");
            window["cameraGMarker_"+web_number].id = i;
            /*Add Listener--------------------------------------- */
            GEvent.addListener(window["cameraGMarker_"+web_number], "click", iconVideo);
        }
            /* End Listener ---------------------------------------*/
            cameraMarkers.push(window["cameraGMarker_"+web_number]);
            map.addOverlay(window["cameraGMarker_"+web_number]);

        }
         if(video._id != ""){
             addActiveIcon(video._id);
         }
};
function addActiveIcon(webid){
    /*  Check for existing icon & remove if nessasary */
    if(window.activeIcon){ map.removeOverlay(window.activeIcon) };
    /*   Add icon as needed    */
    if(window["cameraGMarker_"+webid] && window["cameraGMarker_"+webid].tempdis == "false"){
         var point = new GLatLng(parseFloat(window["cameraGMarker_"+webid].lat), parseFloat(window["cameraGMarker_"+webid].lng));
        window.activeIcon = new GMarker(point, {icon: selectedCameraIcon ,title:'Active Camera'});
        map.addOverlay(window.activeIcon);
    }
}
function iconVideo() {
    clearInterval(ourInterval);
    var preroll = $("preroll");
    var videoImage = $("videoImage");
    if(window["cameraGMarker_"+this.webid].multicam){
        loadMultiCameras(window["cameraGMarker_"+this.webid].lat,window["cameraGMarker_"+this.webid].lng);
    }else{
        if (video._id != '') {
            video.clear_vars();
            video.clear_metadata();
            videoImage.style.display = 'none';
            clearInterval(ourInterval);
        }
        // load_weather(this.zipcode, this.citycode);
        // Log AJAX page view on camera click
        pageCounter("/city/" + this.citycode + "/camera/" + this.webid + "/");
        gaPageCounter("TrafficLand.com -- " + this.desc, "/city/" + this.citycode + "/camera/" + this.webid)
        showImage(this.webid, this.desc, this.orientation, this.provider, this.rate, this.zipcode, this.citycode, true);
    }
}

// A Rectangle is a simple overlay that outlines a lat/lng bounds on the
// map. It has a border of the given weight and color and can optionally
// have a semi-transparent background color.
function Rectangle(bounds, opt_weight, opt_color) {
    this.bounds_ = bounds;
    this.weight_ = opt_weight || 2;
    this.color_ = opt_color || "#888888";
}
// Creates the DIV representing this rectangle.
Rectangle.prototype.initialize = function(map) {
    if(!$("maploader")){
        // Create the DIV representing our rectangle
        var div = document.createElement("div");
        div.id = "maploader";
        var iloading = document.createElement("img");
        var loadTxt = createTextElement("Loading Map", "span");
        iloading.style.float = "left";
        iloading.id = "loadingImage";
        iloading.alt = "Loading Map";
        iloading.src = "/images/loading.gif"
        appendAll(div, iloading, loadTxt);
        div.style.background = '#000';
        div.style.position = "relative";
        div.style.zIndex = 1;
        // Our rectangle is flat against the map, so we add our selves to the
        // MAP_PANE pane, which is at the same z-index as the map itself (i.e.,
        // below the marker shadows)
        map.getPane(G_MAP_MAP_PANE).appendChild(div);
        this.map_ = map;
        this.div_ = div;
    }
}

// Remove the main DIV from the map pane
Rectangle.prototype.remove = function() {
    this.div_.parentNode.removeChild(this.div_);
}
Rectangle.prototype.redraw = function(force) {
    // We only need to redraw if the coordinate system has changed
    if (!force) return;
    // Calculate the DIV coordinates of two opposite corners of our bounds to
    // get the size and position of our rectangle
    var c1 = this.map_.fromLatLngToDivPixel(this.bounds_.getSouthWest());
    var c2 = this.map_.fromLatLngToDivPixel(this.bounds_.getNorthEast());
    this.div_.id = "maploader";
    // Now position our DIV based on the DIV coordinates of our bounds
    this.div_.style.width = Math.abs(c2.x - c1.x) + "px";
    //this.div_.style.height = (Math.abs(c2.y - c1.y) - 100) + "px";
    this.div_.style.height = (Math.abs(c2.y - c1.y)) + "px";

    this.div_.style.left = (Math.min(c2.x, c1.x) - this.weight_) + "px";
    //this.div_.style.top = ((Math.min(c2.y, c1.y) - this.weight_) + 50) + "px";
    this.div_.style.top = ((Math.min(c2.y, c1.y) - this.weight_)) + "px";
    //this.div_.style.opacity = 1/10;
}
var mapcount = 0;
var mapLoading;


/* Trafficflowtoggle function */

// TrafficFlowToggle is a GControl that controls the display of the traffic flow layer
//
//

var trafficInfo;
var toggleState = 1;
var trafficToggle = false;
function TrafficFlowToggle() {
}

if(!!GControl)
    TrafficFlowToggle.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.


TrafficFlowToggle.prototype.initialize = function(map) {
  var container = document.createElement("div");
  var zoomInDiv = document.createElement("div");
  this.setButtonStyle_(zoomInDiv);
  container.appendChild(zoomInDiv);
  zoomInDiv.appendChild(document.createTextNode("Traffic Speed On/Off"));
  GEvent.addDomListener(zoomInDiv, "click", function() {
      trafficToggle = true;
       if (toggleState == 1) {
               trafficInfo.hide();
               toggleState = 0;
             } else {
                trafficInfo.show();
               toggleState = 1;
              }
    });
  map.getContainer().appendChild(container);
  return container;
}

// By default, the control will appear in the top left corner of the
// map with 6 pixels of padding.
TrafficFlowToggle.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(6, 6));
}

// Sets the proper CSS for the given button element.
TrafficFlowToggle.prototype.setButtonStyle_ = function(button) {
  button.style.textDecoration = "none";
  button.style.color = "#000";
  button.style.backgroundColor = "white";
  button.style.font = "small Arial";
  button.style.border = "2px solid black";
  button.style.padding = "1px";
  button.style.marginBottom = "3px";
  button.style.marginRight = "7%"
  button.style.textAlign = "center";
  button.style.width = "10em";
  button.style.cursor = "pointer";
  button.style.fontSize = "11px";
}

/*Traffic flow toggle */








function loadGmap(lat, lon, zoomLevel) {
    mapcount = 0;
    if (GBrowserIsCompatible()) {
        initialZoomLevel = new Number(zoomLevel);
        if (map == null) {
            initializeBaseIcon();
            initializeNormalCameraIcon();
            initializeDeadCameraIcon();
            initializeActiveCameraIcon();

            mapDiv = document.getElementById("map");
            map = new GMap2(mapDiv);
            if (geocoder == null) {
                geocoder = new GClientGeocoder();
            }
            map.addControl(new GLargeMapControl());
           // map.addControl(new GMapTypeControl());
            map.addControl(new GOverviewMapControl());
            map.addControl(new GScaleControl());
            var trafficOptions = {incidents:false};
            trafficInfo = new GTrafficOverlay(trafficOptions);

            map.addControl(new TrafficFlowToggle());
            //map.addControl(new ExtMapTypeControl({showTraffic: true, showTrafficKey: true}));            
            map.enableContinuousZoom();

            GEvent.addListener(map, "moveend", function() {
                if (mapcount != 0) {
                    if (!tluser.isPremium && !trafficToggle) {
                        var a = Math.random() + "";
                        var ord = a * 1000000000000000000;
                        $('cds2').src = "http://ad.doubleclick.net/adi/site208.tmus/homepage;tile=2;" + window.rsidStringr + "dcopt=ist;abr=!webtv;sz=300x250;ord=" + ord;
                        $('cds1').src = "http://ad.doubleclick.net/adi/site208.tmus/homepage;tile=1;" + window.rsidString +"dcopt=ist;abr=!webtv;sz=728x90;ord=" + ord;
                    }
                    pageCounter("/city/" + urlArray[1] + "/mapmove_" + mapcount + "/");
                    gaPageCounter("TrafficLand.com -- " + urlArray[1], "/city/" + urlArray[1] + "/mapmove");
                }
                if(window.cameraMarkers.length > 0){
                    var tlMarker;
                    for(tlMarker in cameraMarkers){map.removeOverlay(cameraMarkers[tlMarker])};
                    cameraMarkers = [];
                    map.removeOverlay(mapLoading);
                }

               //if (mapcount == 0) {
                    var bounds = map.getBounds();
                    var southWest = bounds.getSouthWest();
                    var northEast = bounds.getNorthEast();
                    swlat = southWest.lat();
                    swlng = southWest.lng();
                    nelat = northEast.lat();
                    nelng = northEast.lng();
                    //////////////////////////////////////////
                    var lngDelta = (northEast.lng() - southWest.lng()) / 4;
                    var latDelta = (northEast.lat() - southWest.lat()) / 4;
                    var rectBounds = new GLatLngBounds(
                            new GLatLng(southWest.lat() + latDelta, southWest.lng() + lngDelta),
                            new GLatLng(northEast.lat() - latDelta, northEast.lng() - lngDelta));
                   mapLoading = new Rectangle(rectBounds);
                   // map.addOverlay(mapLoading);
                //}
               mapcount += 1;
                /////////////////////////////////////////////
                var url_tl = "/data/data.xml?swlat=" + swlat + "&swlng=" + swlng + "&nelat=" + nelat + "&nelng=" + nelng + "&system=pub&pubtoken=" + token;
                var request = GXmlHttp.create();
                request.open("GET", url_tl, true);
                request.onreadystatechange = function() {
                    if (request.readyState == 4) {
                         // doesn't work in IE
                        cameraXML = GXml.parse(request.responseText);
                        markers = cameraXML.documentElement.getElementsByTagName("camera");
                        addCameraIconsToMap();
                       // $("maploader").style.display = 'none';
                    }
                }
                 request.send(null);
            });
            map.setCenter(new GLatLng(lat, lon), initialZoomLevel.valueOf());
            map.addOverlay(trafficInfo);

        } else {
            map.checkResize();
            map.setCenter(new GLatLng(lat, lon), initialZoomLevel.valueOf());
        }
    } else {

        alert("Your browser is not compatible with Google Maps. Please try Internet Explorer 7 or Mozilla FireFox.");
        throw error('Your browser is not compatible with Google Maps. Please try Internet Explorer 7 or Mozilla FireFox.');
    }
}

function initializeBaseIcon() {
    // Create a base icon for all of our markers that specifies the
    // shadow, icon dimensions, etc.
    baseIcon = new GIcon();
    baseIcon.iconSize = new GSize(10, 10);
    baseIcon.shadowSize = new GSize(22, 20);
    baseIcon.iconAnchor = new GPoint(5, 5);
    baseIcon.infoWindowAnchor = new GPoint(5, 1);
    largeIcon = new GIcon();
    largeIcon.iconSize = new GSize(14, 14);
    largeIcon.shadowSize = new GSize(22, 20);
    largeIcon.iconAnchor = new GPoint(7, 7);
    largeIcon.infoWindowAnchor = new GPoint(5, 1);
}
function initializeNormalCameraIcon() {
    normalCameraIcon = new GIcon(baseIcon);
    normalCameraIcon.image = "/images/icon.png";
    normalCameraIcon.shadow = "";
}
function initializeDeadCameraIcon() {
    deadCameraIcon = new GIcon(baseIcon);
    deadCameraIcon.image = "/images/disabled.png";
    deadCameraIcon.shadow = "";
}
function initializeActiveCameraIcon(){    
    selectedCameraIcon= new GIcon(largeIcon );
    selectedCameraIcon.image = "/images/activeicon.png";
    selectedCameraIcon.shadow = "";
}
function showImage(webid, desc, orientation, provider, rate, zip, citycode, isNotInitialLoad) {

    var video_holder = $('video_holder');
    var videoImage = $("videoImage");
    videoImage.onclick = '';
    videoImage.style.cursor = 'default';
    video_holder.style.background = "#000 url( '/images/loading.gif' ) 50% 50% no-repeat";

    if (video_holder.style.display != 'block') {
        activate(video_holder, 'block');
    }

    // page view for camera

    updateTitle(desc);
    recentViews.Add( webid + "," + desc.replace(/,/gi,' ') + "," + orientation + "," + provider + "," + rate + "," + zip + "," + citycode);
    video._id = webid;
    video._name = desc;
    video._zip = zip;
    video._city = citycode;
    video._orientation_simple = orientation;

    if (orientation == '' || orientation == 'unknown') {
        video._orientation = '';
    } else if (orientation == 'East' || orientation == 'West' || orientation == 'North' || orientation == 'South'
            || orientation == 'Northeast' || orientation == 'Northwest' || orientation == 'Southeast' || orientation == 'Southwest') {
        video._orientation = 'Traffic closest to camera is traveling ' + orientation;
    } else {
        video._orientation = 'Camera located ' + orientation;
    }
    //    video._orientation = orientation;
    video._provider = provider;
    if (rate < 2000) rate = 2000;
    video._rate = rate;

    //TODO FIX ERROR HERE
    video.display_metadata();
    var timeoutSecs = 60;
    if (tluser.isPremium) timeoutSecs = 300;
    doOnLoad(timeoutSecs);
    if(isNotInitialLoad){
         video.updateFeedBookmarkLink("city/" + citycode + "/camera/" + webid + "/index.html");
        load_weather(zip, citycode);
    }
    _gaq.push(['_trackEvent', 'MSA',  citycode]);
}
 

function showGmap() {
    tl_alert.make(this.alert);
    var mapArea = document.getElementById('map');
    mapArea.style.display = "block";
    var areaLink = new Element('a').update(this.id);
    var cityname = $('cityname').getElementsByTagName("h5")[0];
    if (cityname.lastChild.id != 'citylink' && cityname.lastChild.id != 'countrylink') {
        cityname.replaceChild(areaLink, cityname.lastChild);
        areaLink.id = 'citytitle';
    } else {
        areaLink.id = 'citytitle';
        cityname.appendChild(areaLink);
    }
    updateTitle($('citytitle').innerHTML);
    var map_start = document.getElementById('map_start');
    map_start.style.display = 'none';

    var LatLng = this.latLng;
    var LatLng_array = new Array;
    LatLng_array = LatLng.split(",");

    var lat = LatLng_array[0];
    var lon = LatLng_array[1];
    loadGmap(lat, lon, this.zoomLevel);
    loadTopCams(this.citycode);
     updateCityBookmarkLink("city/" + this.citycode + "/index.html");
    load_weather(this.className, this.citycode);
    //    pageCounter("/city/" + this.citycode + "/");
    pageCounter("/city/" + this.citycode + "/mapmove_0/");
    gaPageCounter("TrafficLand.com -- " + this.citycode, "/city/" + this.citycode);
    city = this.citycode;
    urlArray[1] = this.citycode;
};
function loadTopCams(citycode) {
     if (!$('citytitle')) {
        load_camDock('topcams');
        return;
    }
    tl_tab('topcams');
    var areaname = $('citytitle').innerHTML;
    var mod_title = document.getElementById('citycam_name').getElementsByTagName('h5')[0];
    mod_title.innerHTML = "Top " + areaname + " Cameras";
    var help = createTextElement("[?]", 'span');
    help.desctxt = "Top " + areaname + " Cameras shown are currently the most viewed cameras in this region.";
    help.onmouseover=showHelper;
    help.onmouseout = hideHelper;
    help.id = 'help';
    mod_title.appendChild(help);

    var camDock = $('cam_dock');
    var cams = $('cams');
    cams.innerHTML = '';
    camDock.className = type;
    var url = "/data/topcams.xml?system=pub&city=" + citycode + "&pubtoken=" + token;
    var data = "";
    var cameras;
    cameras = new Ajax.Request(url, {method: 'get', parameters: data, onComplete: build_camDock});
};

function showMapMenu() {
    $('map_start').style.display = 'block';
    $('map').style.display = 'none';
}

function catalogNameCheck(name) {
    var check = false;
    name = stripInput(name);
    name = name.toUpperCase();
    var nameArray = new Array;
    tluser._catalogs.each(function(i){nameArray.push(i._name.toUpperCase())});
    check = nameArray.inArray(name);
    return check;
}

function Tl_user() {
    this._id = '';
    this.status = '';

}


   

function doOnLoad(timeoutSecs) {
    bRunUpdate = false;
    var timeoutMilliseconds = timeoutSecs * 1000;
    updateThisVideo(timeoutSecs);
}

function timeoutLoop(timeoutSecs) {
    //        alert("timeoutSecs : " + timeoutSecs + " iTimeout : " + iTimeout + " bRunUpdate : " + bRunUpdate);
    if (bRunUpdate && iTimeout <= timeoutSecs) {
        iTimeout++;
        setTimeout('timeoutLoop(' + timeoutSecs + ')', 1000);
    } else if (bRunUpdate && iTimeout > timeoutSecs) {
        showTimeoutImage();
        bRunUpdate = false;
    }
}

function camLoadedOnce() {
    if (dTimeout == "0") {
        var videoImage = $("videoImage");
        fadeIn(videoImage);
        dTimeout = "1";
    }
}

function updateThisVideo(timeoutSecs) {
    iTimeout = "0";
    dTimeout = "0";
    iTimeoutTotal = Math.round((timeoutSecs * 1000) / video._rate);
    if (iTimeoutTotal == 0) {
        iTimeoutTotal = 1;
    }
    bRunUpdate = true;
    iClickLog++;
    bLoadDone = true;
    var videoImage = document.getElementById("videoImage");
    videoImage.onload = camLoaded;
    timerLoop(iClickLog);
}

function camLoaded() {
    bLoadDone = true;
    if (dTimeout == "0") {
        var videoImage = document.getElementById("videoImage");
            if(videoImage.style.display=="none")
            fadeIn(videoImage);
        dTimeout = "1";
    }
    updateCam();
};

function timerLoop(iClickNum) {
    if (bRunUpdate && iTimeout <= iTimeoutTotal && iClickNum == iClickLog) {
        bTimeDone = true;
        iTimeout++;
        timerRef = setTimeout('timerLoop(' + iClickNum + ')', video._rate);
        updateCam();
    } else if (iTimeout > iTimeoutTotal) {
        bRunUpdate = false;
        showTimeoutImage();
    }
};
function showTimeoutImage() {
    if (!bRunUpdate) {
        var videoImage = document.getElementById("videoImage");
        videoImage.style.cursor = 'pointer';
        var videoHolder = document.getElementById("video_holder");
        var oldImg = videoImage.src;
        videoHolder.style.background = "#000 url( '" + oldImg + "' ) 50% 50% no-repeat";
        videoImage.src = '/images/replay_camera.gif';
        var videoInfo = [video._id,video._name,video._orientation_simple,video._provider,video._rate,video._zip,video._city];
        videoImage.onclick = function() {
            videoHolder.style.background = "#000 url( '/images/loading.gif' ) 50% 50% no-repeat";
            videoImage.style.cursor = 'default';
            pageCounter("/city/" + videoInfo[6] + "/camera/" + videoInfo[0] + "/");
            gaPageCounter("TrafficLand.com -- " + video._name, "/city/" + videoInfo[6] + "/camera/" + videoInfo[0])
            showImage(videoInfo[0], videoInfo[1], videoInfo[2], videoInfo[3], videoInfo[4], videoInfo[5], videoInfo[6], true);
        };
        video.clear_metadata();
        video.clear_vars();
    }
}

function updateCam() {
    if (bTimeDone && bLoadDone) {
        bTimeDone = false;
        bLoadDone = false;
        LoadImage();
    }
}

function LoadImage() {
    var videoImage = $("videoImage");
    videoImage.src = "http://pub2.camera.trafficland.com/image/live.jpg?system=pub&webid=" + video._id + "&pubtoken=" + token + "&" + Math.random(); //TODO this is an issue for putting in enhanced token
    frame_count ++ ;
}
/* End Imported Video stream*/
function Tl_video() {
    this._id = '';
    this._name = '';
    this._orientation = '';
    this._provider = '';
    this._rate = '';
    this._zip = '';
    this._city = '';
    this._orientation_simple = '';
    this._video_bookmark_link = self.location;

    if (arguments.length == 8){
        this._id = arguments[0];
        this._name = arguments[1];
        this._orientation = arguments[2];
        this._provider = arguments[3];
        this._rate = arguments[4];
        this._zip = arguments[5];
        this._city = arguments[6];
        this._orientation_simple = arguments[7];
    }

    this.updateFeedBookmarkLink = function (relative) {
        //check for ? rsid - split (?) &
        var root = self.location.protocol + '//' + self.location.hostname + '/' + relative ;
        var queryString = '';
        if (self.location.href.indexOf('?',0) > 0)
            queryString = self.location.href.substring(self.location.href.indexOf('?',0), self.location.href.length);
        this._video_bookmark_link = root + queryString ;
    }
    this.getFeedBookmark = function() {
        return  this._video_bookmark_link;
    }


    this.clear_vars = function() {
        this._id = '';
        this._name = '';
        this._orientation = '';
        this._provider = '';
        this._rate = '';
        this._zip = '';
        this._city = '';
        this._orientation_simple = '';
    }
    this.getId = function() {
        return  this._id;
    }
    this.display_metadata = function () {
        if ($("initial_camera")) {
            var preview = $("initial_camera");
            preview.parentNode.removeChild(preview);
        }
        var video = document.getElementById('video_holder');
        if (!$('videoinfo')) {
            var insertBefore = video.parentNode.removeChild($('catalogconfig'));
            var videoInfo = new Element('div',{id:'videoinfo'});
            video.parentNode.appendChild(videoInfo);
            video.parentNode.appendChild(insertBefore);
        } else {
            $('videoinfo').style.display = 'block';
        }
        var vtools = new Element('div',{id:'vtools'});
        var metadata = new Element('span',{id:'metadata'});
        /*Metadata Targets*/
        var videoName = new Element("div",{id:'videoname','class':'metadata'}).update(this._name);
        var orientation  = new Element("div",{id:'orientation','class':'metadata'}).update(this._orientation);
        var providerLink = new Element('a',{id:'partnerLink', href:'http://corporate.trafficland.com/partners.html'} );
        if (this._provider == 'Montgomery') {
            providerLink.update('MCDPWT');
        } else {
            providerLink.update(this._provider);
        }
        var provider = new Element("div",{id:'provider','class':'metadata'});
        var rate = new Element("div",{id:'rate','class':'metadata'}).update(this._rate);

        /*Metadata */
        var name = document.createTextNode(this._name);
        var orientationInfo = document.createTextNode(this._orientation);

        var providerLabel = document.createTextNode("Source : ");
        var providerInfo = document.createTextNode(" Updates: " + this._rate / 1000 + " seconds");
        //var rateInfo = document.createTextNode();

  
        var bookmarkImg = new Element('img',{title: "Bookmark this camera",src:"/images/vid_win_tools_bookmark.gif"});
        var bookmark = new Element('a',{id :"bkmarkcam",href:"javascript:bookmarkCamera()"}).update(bookmarkImg);

        var shareWithFriendImage =  new Element('img',{id:"share",title: "Share this camera",src:"/images/vid_win_tools_share.gif"});
        var shareWithFriend = new Element('a',{id:'sharelink',href: '/shareVideo.jsp?webid=' + this._id}).update(shareWithFriendImage);

        var addWidgetImage = new Element('img',{id:"widget",title: "Add this camera to your site",src:"/images/vid_win_tools_widget.gif"});
        var addWidget = new Element('a',{id:'add_widget',href: '/widget_signup.jsp?webid=' + this._id}).update(addWidgetImage);

        var feedbackImg =  new Element('img',{title: "Report this camera",src:"/images/vid_win_tools_feedback.gif"});
        var feedback = new Element('a',{id:'feedbackcam',href: '/feedback.jsp?webid=' + this._id}).update(feedbackImg);

        /*Show Metadata*/
        if (!$('videoname') || !$('orientation') || !$('provider') || !$('rate')) {
            var videoInfo = $('videoinfo');
            provider.appendChild(providerLabel);
            provider.appendChild(providerLink);
            provider.appendChild(providerInfo);
            videoInfo.appendChild(provider);
            appendAll(vtools,  bookmark, shareWithFriend, addWidget, feedback);
            appendAll(videoInfo, vtools, videoName, orientation, provider);
            //with video tools
        }
       /* display camera location */
        addActiveIcon(this._id);
    };

    this.clear_metadata = function () {
         var videoinfo = $('videoinfo');
         /*Metadata Targets*/
        var videoname = document.getElementById('videoname');
        var orientation = document.getElementById('orientation');
        var provider = document.getElementById('provider');
        var vtools = document.getElementById('vtools');

        /*Clear Metadata*/
        videoinfo.removeChild(videoname);
        videoinfo.removeChild(orientation);
        videoinfo.removeChild(provider);
        videoinfo.removeChild(vtools);
    };

}

function tl_tab(element) {
    var activeTab = document.getElementById(element);
    var mod_title = document.getElementById('citycam_name').getElementsByTagName('h5')[0];
    mod_title.innerHTML = '';
    var help = createTextElement("[?]", 'span');
    help.id = 'help';
    switch (element) {
        case "topcams":
            if (firstLoad == 1) {
                if (firstLoad_isCity == true) {
                    var areaname = firstLoad_City;
                    var title = document.createTextNode("Top " + areaname + " Cameras");
                    help.desctxt = "Top " + areaname + " Cameras shown are currently the most viewed cameras in this region.";
                    help.onmouseover = showHelper;
                    help.onmouseout = hideHelper;
                } else {
                    var title = document.createTextNode("Top Cameras Worldwide");
                    help.desctxt = "Top Cameras shown are currently the most viewed cameras on our network.";
                    help.onmouseover = showHelper;
                    help.onmouseout = hideHelper;
                }
                firstLoad = 0;
            }else{
                if ($('citytitle')) {
                    var areaname = $('citytitle').innerHTML;
                    var title = document.createTextNode("Top " + areaname + " Cameras");
                    help.desctxt = "Top " + areaname + " Cameras shown are currently the most viewed cameras in this region.";
                    help.onmouseover = showHelper;
                    help.onmouseout = hideHelper;
                } else {
                    var title = document.createTextNode("Top Cameras Worldwide");
                    help.desctxt = "Top Cameras shown are currently the most viewed cameras on our network.";
                    help.onmouseover = showHelper;
                    help.onmouseout = hideHelper;
                }
            }
            break;
        case "recentViewTab":
            var title = document.createTextNode(activeTab.innerHTML);
            help.desctxt = "The last 10 cameras you view will be automatically saved as Recently Viewed cameras for this browser. You can delete these cameras from this feature by clicking Clear Recent";
            help.onmouseover = showHelper;
            help.onmouseout = hideHelper;
            break;
        case "favorites":
            var title = document.createTextNode(activeTab.innerHTML);
            help.desctxt = "";
            help.onmouseover = showHelper;
            help.onmouseout = hideHelper;
            var cams = document.getElementById('cams');
            cams.innerHTML = '';
           var notCreatedMessage = createTextElement('Favorites Removed', 'h1');
           notCreatedMessage.margin = "5px 5px ";
           notCreatedMessage.color = "#ccc";
           var notCreatedText = createTextElement('Registered User features, including "Favorites," have been removed from TrafficLand.com ', 'p');
         
           appendAll(cams, notCreatedMessage, notCreatedText);
            break;
     case "worldwide":
            var title = document.createTextNode("Top Cameras Worldwide");
            help.desctxt = "Top Cameras shown are currently the most viewed cameras on our network.";
            help.onmouseover = showHelper;
            help.onmouseout = hideHelper;
            break;
    }
    appendAll(mod_title, title, help);
    var tl_menu = activeTab.parentNode;
    var menuItems = tl_menu.childNodes;

    for (var i = 0; i < menuItems.length; i++) {
        if (menuItems[i].id == element) {
            menuItems[i].className = 'active';
        } else {
            menuItems[i].className = 'nonactive';
        }
    }
};

function load_weather(zip1, cityCode) {
    var weatherArea = document.getElementById("weather");
    weatherArea.innerHTML = '';
    if (zip1 == undefined) {
        zip1 = "22030";
    }

    if (!tluser.isPremium) {
        var data;
        var url = "/data/weather.xml?cityCode=" + cityCode + "&zip=" + zip1 + "&system=pub&pubtoken=" + token;
        var weatherFeed;
        if (zip1 == 0) {
            weatherFeed = new Ajax.Request(url, {method: 'get', onComplete: build_InternationalWeather});
        } else {
            weatherFeed = new Ajax.Request(url, {method: 'get',  onComplete: build_weather});
        }
        var a = Math.random() + "";
        var ord = a * 1000000000000000000;
        if (zip1 == 0) {
            $('cds2').src = "http://ad.doubleclick.net/adi/site208.tmus/homepage;tile=2;" + window.rsidString + "dcopt=ist;abr=!webtv;sz=300x250;ord=" + ord;
            $('cds1').src = "http://ad.doubleclick.net/adi/site208.tmus/homepage;tile=1;" + window.rsidString + "dcopt=ist;abr=!webtv;sz=728x90;ord=" + ord;
        } else {
            $('cds2').src = "http://ad.doubleclick.net/adi/site208.tmus/homepage;tile=2;" + window.rsidString + "dcopt=ist;abr=!webtv;sz=300x250;ord=" + ord;
            $('cds1').src = "http://ad.doubleclick.net/adi/site208.tmus/homepage;tile=1;" + window.rsidString + "dcopt=ist;abr=!webtv;sz=728x90;ord=" + ord;
        }
    }
};

function initAds() {
    if (!tluser.isPremium) {
        var a = Math.random() + "";
        var ord = a * 1000000000000000000;
        $('cds2').src = "http://ad.doubleclick.net/adi/site208.tmus/homepage;tile=2;" + window.rsidString + "dcopt=ist;abr=!webtv;sz=300x250;ord=" + ord;
        $('cds1').src = "http://ad.doubleclick.net/adi/site208.tmus/homepage;tile=1;" + window.rsidString +  spSelectId+"dcopt=ist;abr=!webtv;sz=728x90;ord=" + ord;
    }
};


function build_InternationalWeather(weather) {
    var weatherXML = weather.responseXML;
    var weatherArea = document.getElementById("weather");
    var location = weatherXML.getElementsByTagName("city");
    var locationInfo = document.createTextNode("Forecast for " + location[0].childNodes[0].nodeValue);
    var weatherTop = document.createElement("div");
    weatherTop.id = "weatherinfo";

    var weatherHolder = document.createElement("div");
    weatherHolder.id = "weatherholder";


    var weatherHdr = document.createElement("div");
    weatherHdr.id = "weatherhdr";
    weatherHolder.appendChild(weatherHdr);


    var wbLogo = document.createElement('img');
    wbLogo.src = "/images/powerd_by_wb.gif";
    var wbLogoLink = document.createElement('a');
    wbLogoLink.id = 'poweredbywb';
    wbLogoLink.href = "http://weather.weatherbug.com?zcode=z5636";
    wbLogoLink.appendChild(wbLogo);

    weatherTop.appendChild(locationInfo);
    weatherHdr.appendChild(weatherTop);

    weatherArea.appendChild(weatherHolder);

    var forecasts = weatherXML.getElementsByTagName("forecast");
    for (var i = 0; i < 2; i++) {
        //    for (var i = 0; i < forecasts.length; i++) {

        var area = document.createElement("div");
        area.id = "forecast" + i;
        area.className = "forecastareas";

        var img = document.createElement("img");
        img.src = forecasts[i].getElementsByTagName("image")[0].childNodes[0].nodeValue;
        area.appendChild(img);

        var titleTxt = forecasts[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
        var title = document.createTextNode(titleTxt);
        var titleHolder = document.createElement('h5');
        titleHolder.appendChild(title);
        area.appendChild(titleHolder);

        var high = forecasts[i].getElementsByTagName("high")[0].childNodes[0].nodeValue;
        var highUnits = forecasts[i].getElementsByTagName("high")[0].getAttribute("units");
        var hightTxt = createTextElement(high + " " + highUnits.unescapeHTML(), "span");
        hightTxt.className = "high";
        var divide = document.createTextNode("/");
        var low = forecasts[i].getElementsByTagName("low")[0].childNodes[0].nodeValue;
        var lowUnits = forecasts[i].getElementsByTagName("low")[0].getAttribute("units");
        var lowTxt = createTextElement(low + " " + lowUnits.unescapeHTML(), "span");
        lowTxt.className = "low";

        var lowDiv = document.createElement('div');
        lowDiv.appendChild(hightTxt);
        lowDiv.appendChild(divide);
        lowDiv.appendChild(lowTxt);
        lowDiv.className = "temp";
        area.appendChild(lowDiv);
        weatherHdr.appendChild(area);

    }
    var linkList = document.createElement('ul');
    var links = document.createElement("div");
    links.id = "weatherlinks";
    var worldWeather = document.createElement("a");
    var worldWeatherItem = document.createElement('li');
    var worldWeatherTxt = document.createTextNode("World Weather");
    worldWeather.appendChild(worldWeatherTxt);
    worldWeather.href = "http://weather.weatherbug.com/world-weather.html?zcode=z5602";
    worldWeatherItem.appendChild(worldWeather);

    var weatherNews = document.createElement("a");
    var weatherNewsTxt = document.createTextNode("Weather News");
    var weatherNewsItem = document.createElement('li');
    weatherNews.appendChild(weatherNewsTxt);
    weatherNews.href = "http://weather.weatherbug.com/weather-reports.html?zcode=z5602";
    weatherNewsItem.appendChild(weatherNews);

    appendAll(linkList, worldWeatherItem, weatherNewsItem);
    weatherTop.appendChild(linkList);
    weatherTop.appendChild(wbLogoLink);
}

function build_weather(weather) {

    var weatherXML = weather.responseXML;
    var weatherArea = document.getElementById("weather");
    var location = weatherXML.getElementsByTagName("location");
    var city = location[0].getElementsByTagName("city")[0].childNodes[0].nodeValue;
    var state = location[0].getElementsByTagName("state")[0].childNodes[0].nodeValue;
    var zip = location[0].getElementsByTagName("zip")[0].childNodes[0].nodeValue;

    for (var i = 0; i < location.length; i++) {
        var locationInfo = document.createTextNode("Forecast for " + city + ", " + state + "  " + zip + " ");
        var weatherTop = document.createElement("div");
        var weatherHolder = document.createElement("div");

        weatherHolder.id = "weatherholder";
        weatherTop.id = 'weatherinfo';
        var weatherHdr = document.createElement("div");
        weatherHdr.id = "weatherhdr";
        var wbLogo = document.createElement('img');
        wbLogo.src = "/images/powerd_by_wb.gif";
        var wbLogoLink = document.createElement('a');
        wbLogoLink.href = "http://weather.weatherbug.com?zcode=z5636";
        wbLogoLink.appendChild(wbLogo);
        wbLogoLink.id = 'poweredbywb';
        weatherHdr.appendChild(weatherTop);
        weatherHolder.appendChild(weatherHdr);
        weatherArea.appendChild(weatherHolder);
    }
    var forecasts = weatherXML.getElementsByTagName("forecast");

    for (var i = 0; i < forecasts.length; i++) {

        var area = document.createElement("div");
        area.id = "forecast" + i;
        area.className = "forecastareas";


        var img = document.createElement("img");
        img.src = forecasts[i].getElementsByTagName("image")[0].childNodes[0].nodeValue;
        area.appendChild(img);

        var titleTxt = forecasts[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
        var title = document.createTextNode(titleTxt);
        var titleHolder = document.createElement('h5');
        titleHolder.appendChild(title);
        area.appendChild(titleHolder);
        var high = forecasts[i].getElementsByTagName("high")[0].childNodes[0].nodeValue;
        var highUnits = forecasts[i].getElementsByTagName("high")[0].getAttribute("unit");
        var hightTxt = createTextElement(high + " " + highUnits.unescapeHTML(), "span");
        hightTxt.className = "high";
        var divide = document.createTextNode("/");
        var low = forecasts[i].getElementsByTagName("low")[0].childNodes[0].nodeValue;
        var lowUnits = forecasts[i].getElementsByTagName("low")[0].getAttribute("unit");
        var lowTxt = createTextElement(low + " " + lowUnits.unescapeHTML(), "span");
        lowTxt.className = "low";
        var lowDiv = document.createElement('div');
        lowDiv.appendChild(hightTxt);
        lowDiv.appendChild(divide);
        lowDiv.appendChild(lowTxt);
        lowDiv.className = "temp";
        area.appendChild(lowDiv);

        var desc = createTextElement(forecasts[i].getElementsByTagName("description")[0].childNodes[0].nodeValue, 'a');
        desc.href = "http://weather.weatherbug.com/" + state + "/" + city + "-weather.html?zcode=z5636";
        var descDiv = document.createElement('div');
        descDiv.className = "weatherdesc";
        descDiv.appendChild(desc);
        lowDiv.appendChild(descDiv);
        $('weatherhdr').appendChild(area);
    }
    var links = document.createElement("div");
    links.id = "weatherlinks";
    var SevenDay = document.createElement("a");
    var sevenTxt = document.createTextNode("7-Day Forecast");
    SevenDay.appendChild(sevenTxt);
    SevenDay.href = "http://weather.weatherbug.com/" + state + "/" + city + "-weather/local-forecast/7-day-forecast.html?zcode=z5636";

    var Weekend = document.createElement("a");
    var WeekendTxt = document.createTextNode("Doppler Radar");
    Weekend.appendChild(WeekendTxt);
    Weekend.href = "http://weather.weatherbug.com/" + state + "/" + city + "-weather/local-radar/doppler-radar.html?zcode=z5636";
    var SevenDayItem = document.createElement('li');
    SevenDayItem.appendChild(SevenDay);
    var WeekendItem = document.createElement('li');
    WeekendItem.appendChild(Weekend);
    var linkList = document.createElement('ul');
    appendAll(linkList, SevenDayItem, WeekendItem);
    appendAll(weatherTop, locationInfo,linkList, wbLogoLink);
}


function initBuildWeather(city, state, zip, image1, image2, high1, high2, low1, low2, title1, title2, desc1, desc2, units) {

    var weatherArea = document.getElementById("weather");
    weatherArea.innerHTML = '';

    var locationText = "Forecast for " + city;
    if(state != '') locationText += ", " + state + "  " + zip;
    var locationInfo = document.createTextNode(locationText);

    var weatherTop = document.createElement("div");
    weatherTop.id = 'weatherinfo';
    var weatherHolder = document.createElement("div");
    weatherHolder.id = "weatherholder";
    var weatherHdr = document.createElement("div");
    weatherHdr.id = "weatherhdr";
    var wbLogo = document.createElement('img');
    wbLogo.src = "/images/powerd_by_wb.gif";
    var wbLogoLink = document.createElement('a');
    wbLogoLink.id = 'poweredbywb';
    wbLogoLink.href = "http://weather.weatherbug.com?zcode=z5636";
    wbLogoLink.appendChild(wbLogo);
    appendAll(weatherTop, locationInfo, wbLogoLink);
    weatherHdr.appendChild(weatherTop);
    weatherHolder.appendChild(weatherHdr);
    weatherArea.appendChild(weatherHolder);

    var area = document.createElement("div");
    area.id = "forecast0";
    area.className = "forecastareas";

    var img = document.createElement("img");
    img.src = image1;
    area.appendChild(img);

    var title = document.createTextNode(title1);
    var titleHolder = document.createElement('h5');
    titleHolder.appendChild(title);
    area.appendChild(titleHolder);
    var hightTxt = createTextElement(high1 + " " + units.unescapeHTML(), "span");
    hightTxt.className = "high";
    var divide = document.createTextNode("/");
    var lowTxt = createTextElement(low1 + " " + units.unescapeHTML(), "span");
    lowTxt.className = "low";
    var lowDiv = document.createElement('div');
    lowDiv.appendChild(hightTxt);
    lowDiv.appendChild(divide);
    lowDiv.appendChild(lowTxt);
    lowDiv.className = "temp";
    area.appendChild(lowDiv);

    var desc = createTextElement(desc1, 'a');
    desc.href = "http://weather.weatherbug.com/" + state + "/" + city + "-weather.html?zcode=z5636";
    var descDiv = document.createElement('div');
    descDiv.className = "weatherdesc";
    descDiv.appendChild(desc);
    lowDiv.appendChild(descDiv);
    $('weatherhdr').appendChild(area);

    var areab = document.createElement("div");
    areab.id = "forecast1";
    areab.className = "forecastareas";


    var imgb = document.createElement("img");
    imgb.src = image2;
    areab.appendChild(imgb);

    var titleb = document.createTextNode(title2);
    var titleHolderb = document.createElement('h5');
    titleHolderb.appendChild(titleb);
    areab.appendChild(titleHolderb);
    var hightTxtb = createTextElement(high2 + " " + units.unescapeHTML(), "span");
    hightTxtb.className = "high";
    var divideb = document.createTextNode("/");
    var lowTxtb = createTextElement(low2 + " " + units.unescapeHTML(), "span");
    lowTxtb.className = "low";
    var lowDivb = document.createElement('div');
    lowDivb.appendChild(hightTxtb);
    lowDivb.appendChild(divideb);
    lowDivb.appendChild(lowTxtb);
    lowDivb.className = "temp";
    areab.appendChild(lowDivb);

    var descb = createTextElement(desc2, 'a');
    descb.href = "http://weather.weatherbug.com/" + state + "/" + city + "-weather.html?zcode=z5636";
    var descDivb = document.createElement('div');
    descDivb.className = "weatherdesc";
    descDivb.appendChild(descb);
    lowDivb.appendChild(descDivb);
    $('weatherhdr').appendChild(areab);
    var links = document.createElement("div");
    links.id = "weatherlinks";
    var SevenDay = document.createElement("a");
    var sevenTxt = document.createTextNode("7-Day Forecast");
    SevenDay.appendChild(sevenTxt);
    SevenDay.href = "http://weather.weatherbug.com/" + state + "/" + city + "-weather/local-forecast/7-day-forecast.html?zcode=z5636";

    var Weekend = document.createElement("a");
    var WeekendTxt = document.createTextNode("Doppler Radar");
    Weekend.appendChild(WeekendTxt);
    Weekend.href = "http://weather.weatherbug.com/" + state + "/" + city + "-weather/local-radar/doppler-radar.html?zcode=z5636";
    var SevenDayItem = document.createElement('li');
    SevenDayItem.appendChild(SevenDay);
    var WeekendItem = document.createElement('li');
    WeekendItem.appendChild(Weekend);
    var linkList = document.createElement('ul');
    appendAll(linkList, SevenDayItem, WeekendItem);
    appendAll(weatherTop, linkList, wbLogoLink);
}



function changeBkgnd() {
    this.parentNode.style.background = "#f3f324";
}

function changeBkgnd2() {
    this.parentNode.style.background = "#fff";
}

function viewTopTen() {
     if (typeof video == 'undefined' || typeof video.clear_vars == 'undefined' ){
        return ;
    }
    var videoData ;
    var camId ;
    if (arguments.length < 2){
        videoData = new Array();
        videoData = this.tl_meta.split(",");
        camId = this.id;
    } else{
        videoData = arguments ;
        camId = arguments[6] ;
    }
    if ($('video_holder').style.display != 'block') {
        activate('video_holder', 'block');
    }
    var preroll = document.getElementById("preroll");
    var videoImage = document.getElementById("videoImage");
    //TODO fix error here
    if (video._id != '') {
        video.clear_vars();
        video.clear_metadata();
         videoImage.style.display = 'none';
        clearInterval(ourInterval);
        video.updateFeedBookmarkLink("city/" + videoData[0] + "/camera/" + camId + "/index.html");
    }
    showImage(camId, videoData[1], videoData[2], videoData[3], videoData[4], videoData[5], videoData[0], true);
    pageCounter("/city/" + videoData[0] + "/camera/" + camId + "/");
    gaPageCounter("TrafficLand.com -- " + videoData[1], "/city/" + videoData[0] + "/camera/" + camId)

}

/* Cookie code */
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

function delete_cookie ( cookie_name ){
     var exdate = new Date();
     var expiredays = 60;
     exdate.setDate(exdate.getDate() - expiredays);
    document.cookie = "recentItems=" +  recentViews.list.join("|") + ((expiredays == null) ? "" : "; expires=" + exdate.toGMTString())+" ; path=/";
}

 
/* End of Cookie code */
function oc(a){
  var o = {};
  for(var i=0;i<a.length;i++){
    o[a[i]]='';
   }
  return o;
}
function escapeAll(str){
    var list = str.split(',');
    for (var i = 0; i <  list.length; i++) {
        list[i] = escape(list[i]);
    }
    return list.toString();
}
var recentViews = {
    list : new Array(),
    save : function() {
        if (this.list.length > 0    ) {
            var exdate = new Date();
            var expiredays = 60;
            exdate.setDate(exdate.getDate() + expiredays);
            //recentViews.list.reverse();
            document.cookie = "recentItems=" +  recentViews.list.join("|") + ((expiredays == null) ? "" : "; expires=" + exdate.toGMTString())+" ; path=/";
         }
    },
    Add : function(webid){
        var recentItems = getCookie('recentItems');
        if ( (recentItems != "" || recentItems != null) && recentItems.split("|").length > 0){
            this.list =   recentItems.split("|") ;
        }
        if (webid in oc(recentViews.list)){
            return;
        }
        if (this.list.length > 9) {
            this.list.reverse();
            this.list.shift();
            this.list.push(webid);
            this.list.reverse();
            recentViews.save();
            if ($("recentViewTab").className == "active") {
                this.build();
            }
        } else {
            this.list.reverse();
            this.list.push(webid);
            this.list.reverse();
            recentViews.save();
            if ($("recentViewTab").className == "active") {
                this.build();
            }
        }
    },
    clear: function() {
        delete_cookie('recentItems');
        recentViews.list = [];
        recentViews.build();
    },
    build: function() {
        var recentItems = getCookie('recentItems');
        if (  (recentItems != "" || recentItems != null) && recentViews.list.length == 0 ){
            var list =   recentItems.split("|") ;
            for (var j = 0; j <  list.length; j++) {
                if(list[j] != ""){
                    recentViews.list.push(list[j]);
                }
            }
           //recentViews.list.reverse();
        }
        var camDock = document.getElementById('cams');
        camDock.innerHTML = '';
        if (this.list.length == 0) {
            var notCreatedMessage = createTextElement('No Cameras Viewed', 'h1');
            camDock.appendChild(notCreatedMessage);
            var notCreatedText = createTextElement('The last 10 cameras you viewed will be displayed here for repeat viewing. ', 'p');

            appendAll(camDock, notCreatedText);
            return;
        }


        var recentViewCatalogCreate = document.createElement('div');
        recentViewCatalogCreate.id = 'recent_create';

        var clearRecent = document.createElement('a');
        clearRecent.id = "clearbutton";
        var clearImg = document.createElement('img');
        clearImg.src = "/images/clear_recent.gif";
        clearRecent.appendChild(clearImg);
        clearRecent.onclick = this.clear;
        clearRecent.href = "javascript:void(0);";

        appendAll(recentViewCatalogCreate, clearRecent);
        camDock.appendChild(recentViewCatalogCreate);
 
        for (var i = 0; i < this.list.length; i++) {
            if(this.list[i] != ""){
             var Attributes = this.list[i].split(",");
            var webid =  Attributes[0] ;
            var desc =  Attributes[1] ;
            var ori =  Attributes[2] ;
            var provider =  Attributes[3] ;
            var refresh =  Attributes[4] ;
            var zipCode =  Attributes[5] ;
            var cityCode =  Attributes[6] ;
            var div = document.createElement('div');

            /*Create Image*/
        
            var img = document.createElement('img');
            img.src = "http://pub2.camera.trafficland.com/image/live.jpg?webid=" + webid + "&system=topcams&size=half&docksrc=recent&pubtoken=" + token;          //TODO this is an issue for enhanced token
            img.tl_meta = cityCode + "," + desc + "," + ori + "," + provider + "," + refresh + "," + zipCode;
            img.desctxt = desc;
            img.onmouseover = showHelper;
            img.onmouseout = hideHelper;
            img.width = 115;
            img.height = 78;
            img.onclick = viewTopTen;
            img.id = webid;

              /*Create Description*/
            j = i + 1;
            var text = document.createTextNode(desc);

            /*Append to container*/
            div.appendChild(img);
            div.appendChild(text);
            camDock.insertBefore(div, recentViewCatalogCreate);
            }
        }
    }
};

function load_camDock(type) {
    if ( type == "topcams" && city && city.length > 0){
        loadTopCams(city);
    }else {
        var camDock = document.getElementById('cam_dock');
        var cams = document.getElementById('cams');
        cams.innerHTML = '';
        camDock.className = type;
        var url = "/data/topcams.xml?system=pub&pubtoken=" + token;
        var data = "";
        var cameras;
        cameras = new Ajax.Request(url, {method: 'get', parameters: data, onComplete: build_camDock});
    }
};

function updateCatalog(action) {


}

function stripInput(input) {
    var r = /[!"#$%&'()*+,-./:;?@[\\\]_`{|}~]/g;
    input = input.replace(r, '');
    return input;
}




function _myFormSubmit() {

}
 /*   Loads Favorites Message   */
function buildFavorites() {

    var cams = document.getElementById('cams');
       cams.innerHTML = '';
           var notCreatedMessage = createTextElement('No Favorites Created', 'h1');
           notCreatedMessage.margin = "5px 5px ";
           notCreatedMessage.color = "#ccc";
           var notCreatedText = createTextElement('As a Registered User at TrafficLand, you can organize groups of your favorite cameras. Each group may contain up to 10 cameras. Your favorites will then be visible on this tab for quick navigation and selection to view the video. ', 'p');
           if (tluser.status == 'inactive') {
               var link = createTextElement('Become a registered user', 'a');
               link.href = '/registration.jsp';
               notCreatedText.appendChild(link);
           }
           appendAll(cams, notCreatedMessage, notCreatedText);
};                  
function build_camDock(load) {
    var camDock = document.getElementById('cams');
    var xmlLoad = load.responseXML;
    var cams = xmlLoad.getElementsByTagName("camera");
 

    if (video._id == '' && $("initial_camera")) {
        var initial_camera = $("initial_camera");
        initial_camera.style.background = "#000 url('http://pub2.camera.trafficland.com/image/live.jpg?webid=" + cams[0].getAttribute('webid') + "&system=topcams&size=full&pubtoken=" + token + "') no-repeat 50% 50%";   //TODO this is an issue for enhanced token

        if( $('playbutton')){
            var play = $('playbutton');
            play.title = "View :" + cams[0].getAttribute('desc');
            play.onclick = function() {
                // Log PageView because the ad changes
                pageCounter("/city/" + cams[0].getAttribute('cityCode') + "/camera/" + cams[0].getAttribute('webid') + "/");
                gaPageCounter("TrafficLand.com -- " + cams[0].getAttribute('desc'), "/city/" + cams[0].getAttribute('cityCode') + "/camera/" + cams[0].getAttribute('webid'))
                showImage(cams[0].getAttribute('webid'), cams[0].getAttribute('desc'), cams[0].getAttribute('orientation'), cams[0].getAttribute('provider'), cams[0].getAttribute('refreshRate'), cams[0].getAttribute('zipCode'), cams[0].getAttribute('cityCode'), true);
            }
        }
        if (!$('citylink')) {
            load_weather(cams[0].getAttribute('zipCode'), cams[0].getAttribute('cityCode'));
        }

    }
    var j;
    for (var i = 0; i < cams.length; i++) {
        var desc = cams[i].getAttribute('desc');
        var ori = cams[i].getAttribute('orientation');
        var provider = cams[i].getAttribute('provider');
        var refresh = cams[i].getAttribute('refreshRate');
        var cityCode = cams[i].getAttribute('cityCode');
        var zipCode = cams[i].getAttribute('zipCode');
        var cityName = cams[i].getAttribute('cityName');
        /*Create Div Container*/
        var div = document.createElement('div');

        /*Create Image*/
        var img = document.createElement('img');
        img.src = "http://pub2.camera.trafficland.com/image/live.jpg?webid=" + cams[i].getAttribute('webid') + "&system=topcams&size=half&pubtoken=" + token;             //TODO this is an issue for enhanced token
        img.tl_meta = cityCode + "," + desc + "," + ori + "," + provider + "," + refresh + "," + zipCode;
        img.width = 115;
        img.height = 78;
        img.desctxt = cams[i].getAttribute('cityName') + ": " + cams[i].getAttribute('desc');
        img.onmouseover = showHelper;

        ///changeBkgnd;
        img.onmouseout = hideHelper;
        img.onclick = viewTopTen;
        img.id = cams[i].getAttribute('webid');

        /*Create Description*/
        j = i + 1;
        var text = document.createTextNode(j + ". " + desc);

        /*Append to container*/
        div.appendChild(img);
        div.appendChild(text);
        camDock.appendChild(div);
    }
}

function showHideToggle(element, mode) {
     $(element).toggle();
}

function attachShowHide() {
    var moduleBtnSearch = document.getElementsByTagName('*');
    for (var i = 0; i < moduleBtnSearch.length; i++) {
        if (moduleBtnSearch[i].className == 'moduleBtn') {
            moduleBtnSearch[i].onclick = show_hide_module;

        }
    }
}

function show_hide_module() {
    var container = this.parentNode.parentNode;
      var moduleSearch = container.childNodes;

      for (var i = 0; i < moduleSearch.length; i++) {
          if (moduleSearch[i].className == 'module') {
              if (moduleSearch[i].style.display != 'none') {
                  this.src = "/images/mod_show.gif";
                  moduleSearch[i].style.display = 'none';
              } else {
                  moduleSearch[i].style.display = 'block';
                  this.src = "/images/mod_hide.gif";
              }
          }
      }
   
};

 
/****************************
 Cookie Functions
 ****************************/
function tl_createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function tl_readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function tl_eraseCookie(name) {
    createCookie(name, "", -1);
}
// =Bookmark
function bookmarkCamera(){
    var title = document.getElementById("videoname").innerHTML + ' -- powered by TrafficLand.com';
    var url = '';
    if (!!video) {
         url = video.getFeedBookmark();
    } else {
        alert ("Please click on a camera to bookmark it. Cameras are available through the map, by choosing your area in the 'Choose Cameras by Location' component. Cameras are also available through the 'Favorites', 'Top Cameras' and 'Recently Viewed' sections.") ;
    }
    if (window.sidebar){    // firefox
        window.sidebar.addPanel(title, url, "");
    }else if(window.opera && window.print){ // opera
        var elem = document.createElement('a');
        elem.setAttribute('href',url);
        elem.setAttribute('title',title);
        elem.setAttribute('rel','sidebar');
        elem.click();
    }else if(document.all){  // ie
        window.external.AddFavorite(url, title);
    }
}

// =Bookmark
function bookmarkCity(){
    var title = $('citytitle').innerHTML + ' -- powered by TrafficLand.com';
    var url = map_bookmark_link;
    if (window.sidebar){
        // firefox
        window.sidebar.addPanel(title, url, "");
    } else if(window.opera && window.print){
        // opera
        var elem = document.createElement('a');
        elem.setAttribute('href',url);
        elem.setAttribute('title',title);
        elem.setAttribute('rel','sidebar');
        elem.click();
    }else if(document.all){
        // ie
        window.external.AddFavorite(url, title);
    }
}

function getEventTarget(e) {
    var e = e || window.event;
    var targ = e.target || e.srcElement;
    if (targ.nodeType == 3) {
        targ = targ.parentNode;
    }
    return targ;
}

