// --------------------------------------------------------------------------------
// DOM READY STUFF: Set up the map controls and dialog windows...
// --------------------------------------------------------------------------------
$(document).ready(function () {

    var mapMenuWidth;

    // set alert scroller width
    var scrollerWidth = $(window).width();
    $('.scrollingtext').width(scrollerWidth);


    // alert scroller stuff
    $('#emergenciesBanner div.scrollingtext, #amberAlertsBanner div.scrollingtext').marquee('emergencybanner').mouseover(function () {
        $(this).trigger('stop').css('cursor', 'pointer');
    }).mouseout(function () {
        $(this).trigger('start').css('cursor', 'default');
    }).mousemove(function (event) {
        if ($(this).data('drag') == true) {
            this.scrollLeft = $(this).data('scrollX') + ($(this).data('x') - event.clientX);
        }
    }).mousedown(function (event) {
        $(this).data('drag', true).data('x', event.clientX).data('scrollX', this.scrollLeft).css('cursor', 'move');
    }).mouseup(function () {
        $(this).data('drag', false).css('cursor', 'default');
    });

    // make controls resizeable
    $('#map-menu-accordion').resizable({ handles: 'e' });

    // toggle map controls
    $('#mapMenuShowHide a').toggle(function () {
        var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
        if (!is_chrome) //don't slide for chrome, box model issue 
        {
            //alert("sliding in"); 
            mapMenuWidth = $('#map-menu-accordion').width() + 6;
            mapMenuShowHideWidth = $('#mapMenuShowHide').width();
            $('#map-container').animate({ paddingLeft: '31px' }, { queue: false, duration: 200 });
            $('#map-menu-accordion').animate({ left: '-' + mapMenuWidth + 'px' },
        { queue: false, duration: 500,
            complete: function () {
                // map.checkResize(); 
                // alert("done" );
            }
        });

        } // end if chrome 
    }, function () {
        var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
        if (!is_chrome) //don't slide for chrome 
        {
            //alert("sliding out"); 
            mapMenuWidth = $('#map-menu-accordion').width() + parseInt($('#map-menu-accordion').css('padding-left').replace('px', ''));
           $('#map-menu-accordion').animate({ left: '0' },
         { queue: false, duration: 500,

             complete: function () {
                 $("#map-container").css({ "padding-left": mapMenuWidth + "px" });
             }
         });

          }// end if chrome 
    });
  
    // show/hide accordion panels within map controls
    $('#map-menu-accordion h3 a').click(function () {
        //$(this).toggleClass('show');
        var anchorID = $(this).attr('href');
        if (anchorID == '#message-signs') {
            document.getElementById('ifrmMsgSigns').src = "listView_msgBoards.aspx";
        }
        if (anchorID == '#cameras-list') {
            document.getElementById('ifrmCameraList').src = "listView_cameraSites.aspx";
        }
        if (anchorID == '#alerts-list') {
            document.getElementById('ifrmAlerts').src = "listView_alerts.aspx";
        }
        if (anchorID == '#favorites-list') {
            
            document.getElementById('ifrmFavorites').src = "listView_favorites.aspx";
        }
        if ($(anchorID).is(':visible')) {

            $(anchorID).slideUp();
            $(this).removeClass('show');
        }
        else {

            $('div.accordion-item').slideUp();
            $('#map-menu-accordion h3 a').removeClass('show');
            $(anchorID).slideDown();
            $(this).addClass('show');
        }
        return false;
    });

    // control checkboxes
    $('#map-controls input[type=checkbox]').click(function () {
        var isChecked = $(this).parent().hasClass('selected');
        if (isChecked == 0) {
            $(this).parent().addClass('selected');
        } else {
            $(this).parent().removeClass('selected');
        }
    });

    // upon page refresh, see if checkboxes are checked
    $('#map-controls input[type=checkbox]:checked').each(function () {
        $(this).parent().addClass('selected');
    });

   


    $('#openSignIn a').click(function () {
        // alert($('#map-container').width); 
        closeAllDialogs();
        $(this).parent().append($('#loginWrapper'));
        //$('#openSignIn').append($('#loginWrapper'));
        $('#registerWrapper').slideUp();
        $('#loginWrapper').slideToggle();
        return false;
    });
   
    $('#createAccount a').click(function () {
        closeAllDialogs();
        $(this).parent().append($('#registerWrapper'));
        // $('#createAccount').append($('#registerWrapper'));
        $('#loginWrapper').slideUp();
        $('#registerWrapper').slideToggle();
        return false;
    });

    /*****************************
    // all the dialog boxes here 
    ***************************/
    $('#dialog:ui-dialog').dialog('destroy');
    $('#divContactUs, #divContributors,#divFaq').dialog({
        width: 800,
        height: 400,
        autoOpen: false
    });
    $('#divMyCommutes, #divAccountInfo').dialog({
        width: 900,
        height: 640,
        modal: true,
        autoOpen: false
    });
    $('#divFavoritesConsole').dialog({
        width: 900,
        height: 724,
        modal: true,
        autoOpen: false
    });
    $('#divPasswordRecovery').dialog({
        width: 500,
        height: 540,
        modal: true,
        draggable: false,
        resizable: false,
        autoOpen: false
    });
    $('#divUnregister').dialog({
        width: 800,
        height: 640,
        modal: true,
        draggable: false,
        resizable: false,
        autoOpen: false,
        open: function (type, data) { $(this).parent().appendTo("form"); }
    });

    $('#divEmergenciesContainer').dialog({
        width: 800,
        height: 500,
        modal: false,
        draggable: true,
        resizable: false,
        autoOpen: false
    });
    $('#divAmberContainer').dialog({
        width: 800,
        height: 500,
        modal: false,
        draggable: true,
        resizable: false,
        autoOpen: false
    });


    /*****************************
    end dialog boxes 
    start click functions 
    ********************************/


    $('#emergenciesBanner').click(function () {
        document.getElementById('ifrmEmergencies').src = "emergencyConditions3.aspx";
        $('#divEmergenciesContainer').dialog('open');
        return false;
    });

    $('#amberAlertsBanner').click(function () {
        document.getElementById('ifrmAmberAlerts').src = "amberAlerts.aspx";
        $('#divAmberContainer').dialog('open');
        return false;
    });

    $('#menu-contact-us a').click(function () {
        closeAllDialogs();
        document.getElementById('ifrmContactUs').src = "contact.htm";
        $('#divContactUs').dialog('open');
        return false;
    });

    $('#menu-contributors a').click(function () {
        closeAllDialogs();
        document.getElementById('ifrmContributors').src = "contributors.htm";
        $('#divContributors').dialog('open');
        return false;
    });

    $('#menu-faq a').click(function () {
        closeAllDialogs();
        document.getElementById('ifrmFAQ').src = "faq.htm";
        $('#divFaq').dialog('open');
        return false;
    });



    $('#user-nav-commutes a').click(function () {
        document.getElementById('ifrmCommutes').src = "myDriveMain.aspx";
        $('#divMyCommutes').dialog('open');
        return false;
    });

    $('#user-nav-favorites a').click(function () {
        showMenuFavorites();
        viewFavsConsole();
        return false;
    });

    $('#user-nav-accounts a').click(function () {
        document.getElementById('ifrmAccountInfo').src = "myDriveEditUserPass.aspx";
        $('#divAccountInfo').dialog('open');
        return false;
    });


});            //end ready function 




function forgotPasswordClick() {

    closeAllDialogs();
    $('#loginWrapper').hide();
    document.getElementById('ifrmPasswordRecovery').src = "myDrivePasswordRecovery.aspx";
    $('#divPasswordRecovery').dialog('open');
    return false;

}

function onRegisterSuccess() {

    $('#registerWrapper').hide();
    document.getElementById('ifrmCommutes').src = "myDriveCommutes.aspx";
    $('#divMyCommutes').dialog('open');
    return false;

}


function showMap(lat, lon, zoom) {
   
    if (map.getExtInfoWindow() != null) {
        map.closeExtInfoWindow();
    }
    closeAllDialogs();
    map.setCenter(new GLatLng(lat, lon), zoom);

}

function mapit_click(markerToClick) {
    // alert(markerToClick);
      if (map.getExtInfoWindow() != null) {
          map.closeExtInfoWindow();
      }
      closeAllDialogs(); 
    var thismarker;
    thismarker = markersALL[markerToClick];
    if (map.getZoom() < 10) {//if the map is too far out then zoom it in, otherwise, don't because it is confusing 
        map.setCenter(thismarker.getLatLng(), 12);
    }
    google.maps.Event.trigger(markersALL[markerToClick], 'click');
    
}

function mapit_mouseover(markerToClick) {
    google.maps.Event.trigger(markersALL[markerToClick], 'mouseover');
}

function mapit_mouseout(markerToClick) {   
    google.maps.Event.trigger(markersALL[markerToClick], 'mouseout');
}


function closeAllDialogs() {

    $(' #divContactUs, #divContributors,#divFaq , #divMyCommutes, #divAccountInfo, #divPasswordRecovery, #divCreateAccount').dialog('close');

    $('#dialog:ui-dialog').dialog('destroy');
    if ($('#loginWrapper').is(':visible')) {
        $('#loginWrapper').slideUp();
    }
    if ($('#registerWrapper').is(':visible')) {
        $('#registerWrapper').slideUp();
    }
    
}



function mapit_click_cam(markerToClick, siteid, cameraid) {
    if (map.getExtInfoWindow() != null) {
        map.closeExtInfoWindow();
    }
    var thismarker;
    thismarker = markersALL[markerToClick];
     if (map.getZoom() < 10)
    {//if the map is too far out then zoom it in, otherwise, don't because it is confusing 
      map.setCenter(thismarker.getLatLng() , 12); 
    }
    google.maps.Event.trigger(markersALL[markerToClick], 'click');
    document.getElementById("ifrmMapBubble").src = "mapbubbles/camerasite.aspx?site=" + siteid + "&camid=" + cameraid;
    closeAllDialogs();
}



function whichAlertIcon(emergency, transaction_type, impact, alert_type) {

    var thisIcon;
    if (transaction_type == "C") {
        thisIcon = "cancelled-alerts";
    }
    else if (impact == "Closed") {
    thisIcon = "closed-roads"; 
    }
    else if (alert_type == "Construction") {
        thisIcon = "construction" ;
    }
    else if (alert_type == "Maintenance") {
        thisIcon = "construction";
    }
    else //emergency, weather, incident (red icon)
    {
        thisIcon = "incident-alerts";
    }

    return thisIcon;
}

function whichAlertMarker(emergency, transaction_type, impact, alert_type) {
    var thisMarkerStr;
    if (transaction_type == "C") {
        thisMarkerStr = "map-cancelled-alerts";

    }
    else if (impact == "Closed") {
        thisMarkerStr = "map-closed-roads";

    }
    else if (alert_type == "Construction") {
        thisMarkerStr = "map-construction";

    }
    else if (alert_type == "Maintenance") {
        thisMarkerStr = "map-construction";

    }
    else {
        thisMarkerStr = "map-incident-alerts";
    }
    /* not distinguishing emergency now
    if (emergency != "") 
    {
    thisMarkerStr = emergencyIcon; 
    return thisMarkerStr; 
    }
    */
    //default

    return thisMarkerStr;
}

function signInOrOut(inOrOut, first_name, is_firstresponder, is_admin, numscreens) {
    if (inOrOut == 'in') {
        if (map.getExtInfoWindow() != null) {
            map.closeExtInfoWindow();
        }
        document.getElementById('lblWelcome').innerHTML = "Welcome, " + first_name
        $('body').removeClass('loggedinfalse');
        $('body').addClass('loggedintrue');
        $('#li-hot-spots').addClass('selected');
        $("#li-hot-spots input:checkbox").attr("disabled", false);
        userSignedInOrOut = 'in';
        //if the sign in box is open, hide it 
        $('#loginWrapper').hide();
        if (is_firstresponder == 'true') {
            $('#user-nav-firstresponders').show();
            document.getElementById('lnkOpenVWall').href = "javascript:openVideoWall(" +  numscreens  + ");"
        }
        else {
            $('#user-nav-firstresponders').hide();
        }
        if (is_admin == 'true') {
            $('#menu-admin').show();
        }
        else {
            $('#menu-admin').hide();
        }
    }
    else if (inOrOut == 'out') {
        $('body').removeClass('loggedintrue');
        $('body').addClass('loggedinfalse');
        resetCommutePolys();
        $('#li-hot-spots').removeClass('selected');
        $("#li-hot-spots input:checkbox").attr("disabled", true);
        userSignedInOrOut = 'out';
        closeAllDialogs(); 
    }
    else {
        alert("incorrect parameter sent to signInOrOut function"); 
    }
}

function loadUserCommute(pt_list, tooltip, type) {
    //create a global var for extents 
    //add markergroup toggle later 
    var i, j;
    var splitPointColon, splitPointComma;
    splitPointColon = pt_list.split(";");
    // alert(splitPointColon.length); //num points 
    var latlons;
    latlons = new Array();
    for (i = 0; i < splitPointColon.length; i++) {
        splitPointComma = splitPointColon[i].split(",");
        latlons.push(new GLatLng(splitPointComma[0], splitPointComma[1]));
    } //end for 

    latlons.push(latlons[0]);
    poly2 = new GPolygon(latlons, '#0000af', 3, .8, '#335599', .2);
    map.addOverlay(poly2);
    markerGroups[type].push(poly2);

    return;
} //end load commute

function resetCommutePolys() {
    //delete all polys from commutepoly group
    for (var i = 0; i < markerGroups['map-hot-spots'].length; i++) {
        var marker = markerGroups['map-hot-spots'][i];
        map.removeOverlay(marker);

    } //end for  
    markerGroups['map-hot-spots'].length = 0;
} // end resetCommutePolys


function growWindow(thisframe, regularHeight) {
  
    try {
   
    var f, scrollHt, scrollW;
    f = frames[thisframe];
    if (document.getElementById(thisframe).contentdocument != null) {//this works in firefox, in IE contentdocument doesn't exist 
        //have to reset it first to normal height, else after expand once, scrollheight will always stay at larger number 
        f.frameElement.style.height = regularHeight + 'px';
       // f.frameElement.style.width = regularWidth + 'px';
        scrollHt = document.getElementById(thisframe).contentdocument.documentElement.scrollHeight;
       // scrollW = document.getElementById(thisframe).contentdocument.documentElement.scrollWidth;

    }
    else { //this works in IE, in firefox will return the set height of frame, no scroll height    
        f.frameElement.style.height = regularHeight + 'px';
        scrollHt = frames[thisframe].document.body.scrollHeight;
        //f.frameElement.style.width= regularWidth + 'px';
        //scrollW = frames[thisframe].document.body.scrollWidth;
    }

   // alert(scrollW + " " + regularWidth);
    if (scrollHt > regularHeight) {
        //add for padding
        var scrollHtPlus;
        scrollHtPlus = scrollHt + 15;
        f.frameElement.style.height = scrollHtPlus + 'px';
    }
    else {
        f.frameElement.style.height = regularHeight + 'px';
    }
  }
catch (err) {
   // alert(thisframe + "error in growwindow.  err.message " + err.description);
  }
}


function openCommutesWindow() {
    //used when user clicks my commutes link from a dialog box, like unregister
    closeAllDialogs();

    $("#user-nav-commutes a").click();
    $('#divUnregister').dialog('close'); 
}

function openSigninPanelFromForgotPassword() {
   //super problematic to call button click directly 
    $('#divPasswordRecovery').dialog('close');
    $('#loginWrapper').slideToggle();
}

function openSigninPanelFromUnregister() {
    $('#divUnregister').dialog('close');
    $('#loginWrapper').slideToggle();
}

function openSigninPanelOnLoad() {
    $('#loginWrapper').slideToggle();
}


function openCreateAccountPanel() {
    //used when user clicks create account link from a dialog box 
    closeAllDialogs();
    $("#createAccount a").click();
}

function openEditAccountPanel() {
    //used when user clicks edit my account from email  
    //closeAllDialogs();
    $("#user-nav-accounts a").click();
}

function openUnregister() {
    $('#divAccountInfo').dialog('close');
    $('#divUnregister').dialog('open');
}

function ismaxlength(obj) {
    var mlength = obj.getAttribute ? parseInt(obj.getAttribute("maxlength")) : ""
    if (obj.getAttribute && obj.value.length > mlength) {
        alert("I'm sorry, this field accepts a maximum of 300 chars");
        obj.value = obj.value.substring(0, mlength);
    }
}

function viewFavsConsole() {

    document.getElementById('ifrmFavoritesConsole').src = "favoritesConsole.aspx";
    $('#divFavoritesConsole').dialog('open');
}

function showMenuFavorites() {

    if ($('#favorites-list').is(':visible')) {
        // alert("is visible");
        document.getElementById('ifrmFavorites').src = "listView_favorites.aspx";
    }
    else
        
    $("#menu-favorites-list").trigger("click");
}
function openVideoWall(numscreens) {
  
    if (numscreens == 4) {
        pagename = "vwall/vwall4.aspx";
    }
    else if (numscreens == 6) {
        pagename = "vwall/vwall6.aspx";
    }
    else if (numscreens == 8) {
        pagename = "vwall/vwall8.aspx";
    }
    else{
        pagename = "vwall/vwall6.aspx";
    }

    var OpenWindow;
    OpenWindow = (window.open(pagename, 'VideoWall', 'top=0,left=0,width=' + (screen.width) + ',height=' + (screen.height) + ',resizable=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,copyhistory=yes', 'false'));
    if (!OpenWindow) {
        alert("You must have popup boxes enabled to view video wall");
    }
    else {
        OpenWindow.focus();
    }

}
