﻿//---------------------------------------------------------------------
// SCRIPT FOR InfoEnvoy
//---------------------------------------------------------------------
// ORDER OF EVENTS
//-----------------------
// NOT POSTBACK
//-----------------------
// 1. pageLoad
// 2. document.ready()

//-----------------------
// POSTBACK
//-----------------------
// 1. InitializeRequest
// 2. BeginRequest
// 4. pageLoad
// 5. EndRequest

var objEmail;
var objPassword;
var objPasswordPlaceholder;
var objEmailDefault;
var activePanels;
var postBackElement;

var pnlSearchResults = 0;
var pnlAcctInfo = 1;
var pnlStreetMap = 2;
var pnlGISMap = 3;
var pnlSales = 4;
var pnlOtherSales = 5;
var pnlTaxableValues = 6;
var pnlPropDetails = 7;
var pnlPropImages = 8;

// Use the prm reference, hook _initializeRequest and _endRequest
// so this code is executed at the begin & end of all async postbacks that occur.
// prm is a reference to the Microsoft AJAX PageRequestManager.
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_beginRequest(BeginRequest);
prm.add_pageLoading(PageLoading);
prm.add_endRequest(EndRequest);

//------------------------------------------------------------------------------------------------------------------------------------------------------
// INITIALIZE REQUEST - Raised before the request is initialized for an asynchronous postback. Occurs for all asynchronous postback
//------------------------------------------------------------------------------------------------------------------------------------------------------
function InitializeRequest(sender, args) {
  postBackElement = args.get_postBackElement();

  // If this postback was initiated by any control EXCEPT the Model Occurrence Attributes Panel, disable that control to prevent double postback
  if (jQuery.inArray("dalmodeloccurrence", new Array(postBackElement.id.toLowerCase())) <= -1) {
    // Get a reference to the element that raised the postback and disable it.
    postBackElement.disabled = true;
  }

  document.body.style.cursor = "wait";
}

//------------------------------------------------------------------------------------------------------------------------------------------------------
// BEGIN REQUEST - Raised just before the asynchronous postback is sent to the server
//------------------------------------------------------------------------------------------------------------------------------------------------------
function BeginRequest(sender, args) {
}

//------------------------------------------------------------------------------------------------------------------------------------------------------
// PAGE LOADING - Raised after the response to the most recent asynchronous postback has been received but before any updates to the page have been made
//------------------------------------------------------------------------------------------------------------------------------------------------------
function PageLoading(sender, args) {
}

//------------------------------------------------------------------------------------------------------------------------------------------------------
// PROCESS GIS - Used to load iFrame src for 3rd party GIS
//------------------------------------------------------------------------------------------------------------------------------------------------------
function panelClicked(ui, blnClosing) {
  switch (ui.tab[0].id) {
    case 'divGISPanel': break;
    default:
  }
}

//------------------------------------------------------------------------------------------------------------------------------------------------------
// PAGE LOAD - Raised after page regions are updated after the most recent postback. Makes available information about what panels were created or updated
//------------------------------------------------------------------------------------------------------------------------------------------------------
function pageLoad(sender, args) {
  activePanels = $('input[name=hidActivePanels]');
  objEmail = $('input[name=txtEmail]');
  objEmail.val('Email');
  objEmailDefault = objEmail.val();
  objPassword = $('input[name=txtPassword]');

  $('#optSearchButtons').buttonset();
  $("#cmdLogin").button();
  $('#pnlInside').addClass("ui-corner-all");

  if (args.get_isPartialLoad()) {
    // ASYNC POSTBACK
    //$('#multiOpenAccordion').multiOpenAccordion({ active: activePanels.val(), tabShown: function (event, ui) { panelClicked(ui, false); }, tabHidden: function (event, ui) { panelClicked(ui, true); } });
    $('#multiOpenAccordion').multiOpenAccordion({ active: activePanels.val() });
        
    // set selected UI status as jQuery UI not correctly reflecting seleted status after postback
    $("input[name='optSearchButtons']")[$("#hidSearchTypeSelectedIndex").val()].checked = true;
    $("input[name='optSearchButtons']").button("refresh");

    // Initiated by Search Button
    if (postBackElement.id == "cmdSearch") {
      // Store last search criteria
      $('#hidLastSearchString').val($("input[name='optSearchButtons']:checked").val() + $("#txtSearch").val());

      if ($get("hidSearchResultsRowCount").value > 0) {
        // Open first panel
        $('#multiOpenAccordion').multiOpenAccordion({ active: 0 });
      }

      $get("hidSearchResultsScrollPos").value = "0"
      $get("hidPropertyDetailsLeftScrollPos").value = "0"

      $get('hidLatitude').value = ""
      $get('hidLongitude').value = ""
    }

    $get("divSearchResultsContent").scrollTop = $get("hidSearchResultsScrollPos").value;
    $get("divPropertyDetailsLeft").scrollTop = $get("hidPropertyDetailsLeftScrollPos").value;

    // Initiated by link in grid
    if (jQuery.inArray("grdaccountlist", new Array(postBackElement.id.toLowerCase())) > -1) {
      // reset the scroll positions of all panels that need to maintain vert scroll position
      $get("divSearchResultsContent").scrollTop = $get("hidSearchResultsScrollPos").value;

      // Open other necessary panels
      if ($get("hidAccountInfoRowCount").value > 0) {
        
        var pnlList = new Array();
        var blnOpenStreetMap = jQuery.inArray(pnlStreetMap, $('#multiOpenAccordion').multiOpenAccordion('getActiveTabs')) >= 0;
        var blnOpenGISMap = jQuery.inArray(pnlGISMap, $('#multiOpenAccordion').multiOpenAccordion('getActiveTabs')) >= 0;
        var blnOpenSales = jQuery.inArray(pnlSales, $('#multiOpenAccordion').multiOpenAccordion('getActiveTabs')) >= 0;
        var blnOpenPropDetails = jQuery.inArray(pnlPropDetails, $('#multiOpenAccordion').multiOpenAccordion('getActiveTabs')) >= 0;

        // always open by default
        pnlList.push(pnlSearchResults);
        pnlList.push(pnlAcctInfo);

        // open to previous state
        if (blnOpenStreetMap) { pnlList.push(pnlStreetMap) };
        if (blnOpenGISMap) { pnlList.push(pnlGISMap) };
        if (blnOpenSales) { pnlList.push(pnlSales) };
        if (blnOpenPropDetails) { pnlList.push(pnlPropDetails) };

        // open by default only if rows exist
        if ($get("hidSalesRowCount").value > 0) {pnlList.push(pnlSales)}; 
        if ($get("hidTaxableValuesRowCount").value > 0) { pnlList.push(pnlTaxableValues) };
        if ($get("hidPropDetailsRowCount").value > 0) { pnlList.push(pnlPropDetails) };

        // apply changes
        $('#multiOpenAccordion').multiOpenAccordion({ active: pnlList });
      }
    }
  }
  else {
    // NOT ASYNC POSTBACK
    $("#txtSearch").css("color", "#777");

    // initially set activePanels.val() to first panel (0)
    //$('#multiOpenAccordion').multiOpenAccordion({ active: 0, tabShown: function (event, ui) { panelClicked(ui, false); }, tabHidden: function (event, ui) { panelClicked(ui, true) } });
    $('#multiOpenAccordion').multiOpenAccordion({ active: 0 });
    activePanels.val($('#multiOpenAccordion').multiOpenAccordion('getActiveTabs'));

    $('#txtSearch').val('Enter Address');

    $("input[name='optSearchButtons']")[0].checked = true;
    $("input[name='optSearchButtons']").button("refresh");
  }

  // see if it exists...don't want to create a dup on postback
  if ($('#objPasswordPlaceholder').length == 0) {
    objPassword.after('<input id="objPasswordPlaceholder" type="text" class="input_login text ui-widget-content ui-corner-all" style="font-size: 11px;" value="Password" autocomplete="off" />');
    objPasswordPlaceholder = $('#objPasswordPlaceholder');
  }
  objPasswordPlaceholder.show();
  objPassword.hide();

  $(function () {
    $('#multiOpenAccordion').click(function (event, ui) {
      activePanels.val($('#multiOpenAccordion').multiOpenAccordion('getActiveTabs'));
    });
  });

  $(function () {
    $('#txtSearch').blur(function (e) {
      var indexSelected = $("input[name='optSearchButtons']:checked").val();
      if (indexSelected) {
        if ($('#txtSearch').val() == '') {
          switch (indexSelected) {
            case '0': $('#txtSearch').val('Enter Address'); $("#txtSearch").css("color", "#777"); break;
            case '1': $('#txtSearch').val('Enter Owner Name'); $("#txtSearch").css("color", "#777"); break;
            case '2': $('#txtSearch').val('Enter Account Number'); $("#txtSearch").css("color", "#777"); break;
            case '3': $('#txtSearch').val('Enter Parcel Number'); $("#txtSearch").css("color", "#777"); break;
            default:
          }
        }
      }
    });
  });

  $(function () {
    $('#txtSearch').focus(function (e) {
      $("#txtSearch").css("color", "windowtext");
      $('#txtSearch').val('');
    });
  });
  
  $(function () {
    $('#txtSearch').keypress(function (e) {
      if (e.which == 13) {
        $('#cmdSearch').click();
        return false;
      }
      else {
        //SetInputSearchDefaults('keypress');
        return true;
      }
    });
  });

  $(function () {
    $("#cmdSearch").click(function () {
    });
  });

  $(function () {
    $('#optSearchButtons').change(function (e) {
      var indexSelected = $("input[name='optSearchButtons']:checked").val();

      if (indexSelected) {
        //store index/value of option selected for code behind use
        $('#hidSearchTypeSelectedIndex').val(indexSelected);

        switch (indexSelected) {
          case '0': $('#txtSearch').val('Enter Address'); $("#txtSearch").css("color", "#777"); break;
          case '1': $('#txtSearch').val('Enter Owner Name'); $("#txtSearch").css("color", "#777"); break;
          case '2': $('#txtSearch').val('Enter Account Number'); $("#txtSearch").css("color", "#777"); break;
          case '3': $('#txtSearch').val('Enter Parcel Number'); $("#txtSearch").css("color", "#777"); break;
          default:
        }
      }

      $find("txtSearchAutoComplete").set_contextKey($("#hidCnum").val() + ',' + indexSelected);
    });
  });

  objPasswordPlaceholder.focus(function () {
    objPasswordPlaceholder.hide();
    objPassword.show();
    objPassword.focus();
  });

  objPassword.focus(function () {
    selectedInput = objPassword;
  });

  objPassword.blur(function () {
    if (objPassword.val() == '') {
      objPasswordPlaceholder.show();
      objPassword.hide();
    }
  });

  objEmail.focus(function () {
    selectedInput = objEmail;
    if (objEmail.val() == objEmailDefault) {
      objEmail.val('');
    }
  });

  objEmail.blur(function () {
    if (objEmail.val() == '') {
      objEmail.val(objEmailDefault);
    }
  });

  //  $('input#chkOutputToEmail').change(function() {
  //    if ($(this).checked) {
  //      //checked
  //      return;
  //    }
  //  });

  // to initially set autocomplete criteria on all page loads
  $find("txtSearchAutoComplete").set_contextKey($("#hidCnum").val() + ',' + $("#hidSearchTypeSelectedIndex").val());
}

//------------------------------------------------------------------------------------------------------------------------------------------------------
// END REQUEST - Raised when request processing is finished. Executed when the async postback completes. Object makes available information about errors
//------------------------------------------------------------------------------------------------------------------------------------------------------
function EndRequest(sender, args) {
  //if (sender._postBackSettings.sourceElement.id != '<CONTROL ID>') {
    // Get a reference to the element that raised the postback and disables it.
    // sender._postBackSettings.sourceElement.disabled = false;
  //}

  // notify user that email was delivered
  var blnMenuAccountsServerSel = jQuery.inArray("mnuaccountsserver", new Array(postBackElement.id.toLowerCase())) > -1;
  var blnNoEmailErr = $('#lblOutputToEmailError').text() == "";
  if (blnMenuAccountsServerSel && blnNoEmailErr) {
    alert("The report has been delivered to the provided email address.");
  }

  ShowStreetMap();
  //ShowGISMap();
                               
  document.body.style.cursor = "auto";
}

//---------------------------------------------------------------------
// DOCUMENT READY - 
//---------------------------------------------------------------------
$(document).ready(function () {
});

//---------------------------------------------------------------------
// AUTOCOMPLETE
//---------------------------------------------------------------------
function autocompletePopulated(sender, e) {
  var elementPos = $("#txtSearch").offset();

  if ($.browser.msie && $.browser.version <= 7) {
    sender._popupBehavior._x = -40;
    sender._popupBehavior._y = 0;
  }
  else {
    sender._popupBehavior._x = 0;
    sender._popupBehavior._y = -10;
  }
  //alert(elementPos.left + " " + elementPos.top);
}

function autocompleteItemSelected(sender, e) {
  // e.get_text(); e.get_value()
  $('#txtSearch').val(e.get_value());
  $('#cmdSearch').click();
}

//---------------------------------------------------------------------
// SHOW STREET MAP
//---------------------------------------------------------------------
function ShowStreetMap() {
  var pinPoint = null;
  var pinPixel = null;
  var ParcelMap = null;
  var pnlObject = $get('divMapContent');

  if (pnlObject) {
    if ($get('hidLongitude').value != '' && $get('hidLatitude').value != '') {
      ParcelMap = new VEMap('divMap');
      // location, zoom level, initial map style, map locked, map mode, show map mode switch, tile buffer width (border around map)
      ParcelMap.LoadMap(new VELatLong($get('hidLatitude').value, $get('hidLongitude').value), 17, VEMapStyle.Hybrid, false, VEMapMode.Mode2D, true, 1);

      // Add a new pushpin to the center of the map.
      pinPoint = ParcelMap.GetCenter();
      pinPixel = ParcelMap.LatLongToPixel(pinPoint);
      ParcelMap.AddPushpin(pinPoint);
      ParcelMap.Resize(766, 298);
    }
    else {
      if (ParcelMap) {
        ParcelMap.Clear;
        ParcelMap.Dispose;
      }
    }
  }
}

//---------------------------------------------------------------------
// SHOW GIS MAP
//---------------------------------------------------------------------
//function ShowGISMap() {
//  var doc;
//  var iFrameObject = $get('iFrameGIS');
//  var pnlObject = $get('divGISPanel');

//  if (postBackElement.id == 'grdAccountList' || postBackElement.id == 'dalModelOccurrence') {
//    if (pnlObject) {
//      if (iFrameObject) {
//        if ($('#hidGISUrl').val != '') {
//          frames['iFrameGIS'].location.href = $('#hidGISUrl').val(); // "gispage.aspx?url=" + $('#hidGISUrl').val();

//          $('#divGISPanel').show();
//          if (iFrameObject.contentDocument) { // DOM
//            doc = iFrameObject.contentDocument;
//          }
//          else {
//            if ($get('iFrameGIS').contentWindow.document) { // IE Win
//              doc = iFrameObject.contentWindow.document;
//            }
//          }
//          if (doc) {
//            $('#divGISPanel').show();
//            //doc.location = $('#hidGISUrl').val();
//            //doc.location.reload();
//          }
//        }
//        else {
//          //doc.location = '';
//          $('#divGISPanel').hide();
//        }
//      }
//    }
//  }
//}

//---------------------------------------------------------------------
// STORE SCROLL POSITION
//---------------------------------------------------------------------
function setScroll(val, hiddenFieldName) {
  var hiddenField;
  hiddenField = document.getElementById(hiddenFieldName);
  hiddenField.value = val.scrollTop;
}

//---------------------------------------------------------------------
// HANDLE PROTEST WINDOW
//---------------------------------------------------------------------      
function SelectAndCloseProtest(value) {
  dlgProtestClient.Hide();
  if (value == '1') {
    // hide protest menu
    mnuAccountsClient.GetItem(2).SetVisible(false);
  }
}

function SelectAndCloseProtestDisclaimer(value) {
  dlgProtestDisclaimerClient.Hide();
  if (value == 'agree') {
    // show protest form
    dlgProtestClient.Show();
  }
}

//---------------------------------------------------------------------
// CENTER WINDOW
//---------------------------------------------------------------------
function f_clientWidth() {
  return f_filterResults(window.innerWidth ? window.innerWidth : 0, document.documentElement ? document.documentElement.clientWidth : 0, document.body ? document.body.clientWidth : 0);
}

function f_clientHeight() {
  return f_filterResults(window.innerHeight ? window.innerHeight : 0, document.documentElement ? document.documentElement.clientHeight : 0, document.body ? document.body.clientHeight : 0);
}

function f_filterResults(n_win, n_docel, n_body) {
  var n_result = n_win ? n_win : 0;
  if (n_docel && (!n_result || (n_result > n_docel)))
    n_result = n_docel;
  return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

window.size = function() {
  var w = 0;
  var h = 0;

  //IE
  if (!window.innerWidth) {
    //strict mode
    if (!(document.documentElement.clientWidth == 0)) {
      w = document.documentElement.clientWidth;
      h = document.documentElement.clientHeight;
    }
    //quirks mode
    else {
      w = document.body.clientWidth;
      h = document.body.clientHeight;
    }
  }
  //w3c
  else {
    w = window.innerWidth;
    h = window.innerHeight;
  }
  return { width: w, height: h };
}

window.center = function() {
  var hWnd = (arguments[0] != null) ? arguments[0] : { width: 0, height: 0 };

  var _x = 0;
  var _y = 0;
  var offsetX = 0;
  var offsetY = 0;

  //IE
  if (!window.pageYOffset) {
    //strict mode
    if (!(document.documentElement.scrollTop == 0)) {
      offsetY = document.documentElement.scrollTop;
      offsetX = document.documentElement.scrollLeft;
    }
    //quirks mode
    else {
      offsetY = document.body.scrollTop;
      offsetX = document.body.scrollLeft;
    }
  }
  //w3c
  else {
    offsetX = window.pageXOffset;
    offsetY = window.pageYOffset;
  }

  _x = ((this.size().width - hWnd.width) / 2) + offsetX;
  _y = ((this.size().height - hWnd.height) / 2) + offsetY;

  return { x: _x, y: _y };
}

function showCenter(point, url) {
  var target = "_blank";
  var top = point.y + "px";
  var left = point.x + "px";
  // var win = window.open(url, target, "width=800, height=600, left=" + left + ", top=" + top + ", " + "location=no, menubar=yes, status=no, toolbar=no, scrollbars=yes, resizable=yes");
  var win = window.open(url, target, "width=800, height=600, left=" + left + ", top=100, " + "location=no, menubar=yes, status=no, toolbar=no, scrollbars=yes, resizable=yes");
  win.focus;
}
