﻿/*jslint browser: true, maxerr: 50, indent: 2 */
/*jslint Typekit: false, $: false */

// Typekit inclusion, during load
try { Typekit.load(); } catch (e) {}

// jQuery Log (http://plugins.jquery.com/project/jQueryLog)
(function(a){a.log=function(){if(window.console&&window.console.log){console.log.apply(window.console,arguments)}};a.fn.log=function(){a.log(this);return this}})(jQuery);

// jQuery dateFormat (http://plugins.jquery.com/project/jquery-dateFormat)
(function($){$.format=(function(){function strMonth(value){switch(parseInt(value)){case 1:return"Jan";case 2:return"Feb";case 3:return"Mar";case 4:return"Apr";case 5:return"May";case 6:return"Jun";case 7:return"Jul";case 8:return"Aug";case 9:return"Sep";case 10:return"Oct";case 11:return"Nov";case 12:return"Dec";default:return value;}} var parseMonth=function(value){switch(value){case"Jan":return"01";case"Feb":return"02";case"Mar":return"03";case"Apr":return"04";case"May":return"05";case"Jun":return"06";case"Jul":return"07";case"Aug":return"08";case"Sep":return"09";case"Oct":return"10";case"Nov":return"11";case"Dec":return"12";default:return value;}};var parseTime=function(value){var retValue=value;if(retValue.indexOf(".")!==-1){retValue=retValue.substring(0,retValue.indexOf("."));} var values3=retValue.split(":");if(values3.length===3){hour=values3[0];minute=values3[1];second=values3[2];return{time:retValue,hour:hour,minute:minute,second:second};}else{return{time:"",hour:"",minute:"",second:""};}};return{date:function(value,format){try{var year=null;var month=null;var dayOfMonth=null;var time=null;if(typeof value.getFullYear==="function"){year=value.getFullYear();month=value.getMonth()+1;dayOfMonth=value.getDate();time=parseTime(value.toTimeString());}else if(value.search(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.?\d{0,3}\+\d{2}:\d{2}/)!=-1){var values=value.split(/[T\+-]/);year=values[0];month=values[1];dayOfMonth=values[2];time=parseTime(values[3].split(".")[0]);}else{var values=value.split(" ");switch(values.length){case 6:year=values[5];month=parseMonth(values[1]);dayOfMonth=values[2];time=parseTime(values[3]);break;case 2:var values2=values[0].split("-");year=values2[0];month=values2[1];dayOfMonth=values2[2];time=parseTime(values[1]);break;case 7:year=values[3];month=parseMonth(values[1]);dayOfMonth=values[2];time=parseTime(values[4]);break;default:return value;}} var pattern="";var retValue="";for(var i=0;i<format.length;i++){var currentPattern=format.charAt(i);pattern+=currentPattern;switch(pattern){case"dd":retValue+=dayOfMonth;pattern="";break;case"MMM":retValue+=strMonth(month);pattern="";break;case"MM":if(format.charAt(i+1)=="M"){break;} retValue+=month;pattern="";break;case"yyyy":retValue+=year;pattern="";break;case"HH":retValue+=time.hour;pattern="";break;case"hh":retValue+=(time.hour==0?12:time.hour<13?time.hour:time.hour-12);pattern="";break;case"mm":retValue+=time.minute;pattern="";break;case"ss":retValue+=time.second.substring(0,2);pattern="";break;case"a":retValue+=time.hour>=12?"PM":"AM";pattern="";break;case" ":retValue+=currentPattern;pattern="";break;case"/":retValue+=currentPattern;pattern="";break;case":":retValue+=currentPattern;pattern="";break;default:if(pattern.length===2&&pattern.indexOf("y")!==0){retValue+=pattern.substring(0,1);pattern=pattern.substring(1,2);}else if((pattern.length===3&&pattern.indexOf("yyy")===-1)){pattern="";}}} return retValue;}catch(e){console.log(e);return value;}}};}());}(jQuery));

// Object Overrides/Extensions
Date.prototype.addDays = function (Days) { return new Date(this.getTime()+(1000 * 60 * 60 * 24 * Days)); };
Date.prototype.diffDays = function (Date2) { return (this - Date2) / (1000 * 60 * 60 * 24); };
Date.prototype.dateOnly = function () { return new Date(this.getYear() + 1900, this.getMonth(), this.getDate()); };

// External JS files
function IncludeJS(file) { document.write('<script type="text/javascript" src="/_scripts/'+ file + '"></scr' + 'ipt>'); }
IncludeJS("jquery.fancybox.js");
IncludeJS("jquery.watermark.min.js");

// Kingsway object  ========================================================================================
var KWD=new (function() {this.QueryString=(function(a){if(a=="")return{};var b={};for(var i=0;i<a.length;++i)
{var p=a[i].split('=');if(p.length!=2)continue;b[p[0]]=decodeURIComponent(p[1].replace(/\+/g," "));}
return b;})(window.location.search.substr(1).split('&'));})();

// Application JS object  ==================================================================================
var Junk777 = new (function ()
{
  // Properties
  this.CurrentGuid = null;
  this.ServiceNotAvailableTitle = "Service not available!";
  this.ServiceNotAvailableMessage = "The zip code that you entered is currently not included in our service area. If you feel this is an error, please enter your 5-digit zip code again. Thank you!";
  this.ServiceAvailableTitle = "Congratulations!";
  this.ServiceAvailableMessage = "We service your zip code. Please schedule your day and time next.";

  // Methods
  this.FindServiceAreas = function (ZipCode, cb)
  {
    $.ajax({
      type: "POST",
      url: "/webapp/Appointment.svc/FindServiceAreas",
      data: '{"ZipCode" : "' + ZipCode + '", "CurrentGuid" : "' + this.CurrentGuid + '"}',
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      processdata: true,
      success: function (msg)
      {
        if (cb != null && typeof cb == 'function')
        { cb(true, msg.FindServiceAreasResult); }
      },
      error: function (msg)
      {
        if (cb != null && typeof cb == 'function')
        { cb(false, msg); }
        else
        { Junk777.Alert(null, "Unable to perform a zip code search at this time. Please contact customer service."); }
      }
    });
  };

  this.InitLoadingModal = function ()
  {
    var img = new Image();
    img.src = "/_images/icon_spinnybar.gif";
  };

  var ModalLoadingHandle = null;
  this.ShowLoadingModal = function ()
  {
    this.CloseLoadingModal();

    ModalLoadingHandle = $("<div class='loadingmodal'><img src='/_images/icon_spinnybar.gif' alt='Loading Icon' /></div>").dialog(
    {
      modal: true,
      draggable: false,
      resizable: false,
      height: 75,
      width: 260
    })
    .siblings(".ui-dialog-titlebar")
      .hide()
    .end();
  };

  this.CloseLoadingModal = function ()
  {
    if (ModalLoadingHandle !== null)
    { try { ModalLoadingHandle.dialog("close"); } catch (e) { } }
  };

  this.Alert = function (title, message)
  {
    var m = $("<div>" + message + "</div>").dialog(
      {
        modal: true,
        draggable: false,
        resizable: false,
        title: title
      });
    if (title === null)
    { m.siblings(".ui-dialog-titlebar").hide(); }
  };

  this.Confirm = function (title, message, OKText, CancelText, OKCallback)
  {
    var buttons = new Object();
    buttons[OKText] = function ()
    {
      $(this).dialog("close");
      OKCallback();
    };
    buttons[CancelText] = function () { $(this).dialog("close"); };

    var m = $("<div>" + message + "</div>").dialog(
      {
        modal: true,
        draggable: false,
        resizable: false,
        title: title,
        buttons: buttons
      });

    if (title === null)
    { m.siblings(".ui-dialog-titlebar").hide(); }
  };

  this.Notice = function (title, message)
  {
    var dlg = $("<div>" + message + "</div>").dialog(
      {
        draggable: false,
        resizable: false,
        title: title,
        position: ['right', 'top'],
        show: 'blind',
        hide: 'blind'
      });
    if (title === null)
    { dlg.siblings(".ui-dialog-titlebar").hide(); }
    setTimeout(function () { dlg.dialog("close"); }, 3000);
  };

  this.TimePickerOptions = {
    showPeriod: true,
    showLeadingZero: false,
    onSelect: function (time, ctl)
    {
      var matches = time.match(/(\d+):(\d+)\s+(..)/);
      var h = (matches[1] - 0) + (matches[3].search(/pm/i) !== -1 ? 12 : 0);
      if (+matches[1] === 12) { h -= 12; }
      $(ctl.input).val(h + ":" + matches[2] + ":00")
    }
  };

  // TODO: Move this to use Date's expanded methods
  this.AddDays = function (dt, Days)
  {
    if (dt == null) { return null; }
    return new Date(dt.getTime() + (1000 * 60 * 60 * 24 * Days));
  };

  this.InitTimeSelector = function (slotWidth, scrollAnimationTiming)
  {
    if (typeof slotWidth === 'undefined' || slotWidth == null) { slotWidth = 147; }
    if (typeof scrollAnimationTiming === 'undefined' || scrollAnimationTiming == null) { scrollAnimationTiming = 500; }

    // Fix to repeater headers (AM or PM appear without any times underneath)
    $(".times-dayperiod").each(function ()
    {
      var t = $(this);
      if (t.next(".times-dayperiod").length > 0 || t.next().length === 0)
      { t.hide(); }
    });

    // Fix floated day containers (bottom of boxes are jagged, so set height to tallest box)
    $(".times-day").height($("#timeslotselector").height());

    // When the time is changed, update the hidden field
    $(".timeslotselector :radio").change(function ()
    {
      var checked = $(".timeslotselector :radio:checked");
      if (checked.length === 1) { $("#hfSelectedAppointmentSlotId").val(checked.val()); }
    });

    // Refresh the navigation bar
    var RefreshSlotNavigation = function (ixSlot)
    {
      if (typeof ixSlot == 'undefined') { ixSlot = +$("#timeslotselector").data("StartDateIndexOffset"); }

      var slotCount = $("#timeslotselector .times-day-container").length;
      var ixLast = slotCount - 5;

      $("#lnkPreviousWeek").toggle(ixSlot > 0);
      $("#lnkNextWeek").toggle(ixSlot < ixLast);
      $("#noPreviousWeek").toggle(!(ixSlot > 0));
      $("#noNextWeek").toggle(!(ixSlot < ixLast));

      var ixEnd = (ixSlot + 4 > slotCount - 1) ? (slotCount - 1) : (ixSlot + 4);
      var startText = $("#timeslotselector .times-day-container:eq(" + ixSlot + ") .times-dayheader span").text();
      var endText = $("#timeslotselector .times-day-container:eq(" + ixEnd + ") .times-dayheader span").text();
      $("#lblDisplayStartDay").text(startText);
      $("#lblDisplayEndDay").text(endText);
    };

    // Initial setup of the timeslot navigation bar
    if ($("#hfSelectedAppointmentSlotId").val() === "")
    {
      $("#timeslotselector").data("StartDateIndexOffset", 0)
      RefreshSlotNavigation(0);
    }
    else
    {
      var ixSlot = 0;
      var apptSlotId = $("#hfSelectedAppointmentSlotId").val();
      var apptSlot = $(".timeslotselector :radio[value=" + apptSlotId + "]");
      if (apptSlot.length) // Slot is available
      {
        var m = apptSlotId.match(/(\d{8})/)
        var cssClass = ".d" + m[1];
        ixSlot = $("#timeslotselector " + cssClass).index();
        ixSlot = ixSlot - (ixSlot % 5);
        $("#timeslotselector").css('margin-left', (ixSlot * slotWidth * -1));
        apptSlot.click();
      }
      else // Slot no longer available
      {
        $("#hfSelectedAppointmentSlotId").val("");
        ixSlot = 0;
      }

      $("#timeslotselector").data("StartDateIndexOffset", ixSlot)
      RefreshSlotNavigation(ixSlot);
    }

    $("a#lnkPreviousWeek").click(function (evt)
    {
      evt.preventDefault();

      var ixSlot = +$("#timeslotselector").data("StartDateIndexOffset");
      if (ixSlot <= 0) { return; }
      ixSlot -= 5;
      if (ixSlot < 0) { ixSlot = 0; }
      var slotOffset = ixSlot * slotWidth * -1;

      $("#timeslotselector").clearQueue().animate({ 'margin-left': slotOffset }, scrollAnimationTiming);
      $("#timeslotselector").data("StartDateIndexOffset", ixSlot);

      RefreshSlotNavigation(ixSlot);
    });

    $("a#lnkNextWeek").click(function (evt)
    {
      evt.preventDefault();
      var ixSlot = +$("#timeslotselector").data("StartDateIndexOffset");
      var ixEnd = $("#timeslotselector .times-day-container").length - 5;
      if (ixSlot >= ixEnd) { return; }
      ixSlot += 5;
      if (ixSlot > ixEnd) { ixSlot = ixEnd; }
      var slotOffset = ixSlot * slotWidth * -1;

      $("#timeslotselector").clearQueue().animate({ 'margin-left': slotOffset }, scrollAnimationTiming);
      $("#timeslotselector").data("StartDateIndexOffset", ixSlot);

      RefreshSlotNavigation(ixSlot);
    });

  };
})();

// Startup jQuery  =========================================================================================
$(function ()
{
  // Navigation wireup: show chevron under hovered menu parent while hovering in submenu
  var fn = function (e) { $(e.currentTarget).closest('li').children('a:first').toggleClass('hover'); };
  $("nav li ul").hover(fn, fn);

  // Apply jQuery UI Button theming
  $(".button-container a.btn, a.btn-jq").button();

  // Activate collapsible fields
  $("fieldset.collapsible legend")
    .css({ cursor: 'pointer' })
    .click(function ()
    {
      $(this)
        .closest("fieldset")
        .toggleClass("closed")
        .children(".collapsible-content")
        .slideToggle();
    });

  // Activate Date Pickers
  try { $(".datepicker").datepicker(); } catch (e) { }

  // Activate known watermarks
  $("#txtZipCode:not(.nowatermark)").watermark("Zip Code");
  $("aside .widget_search #s").watermark("Search");

  // Activate videos
  $(".video").click(function (evt)
  {
    evt.preventDefault();
    var $this = $(this);
    var url = this.href.replace(new RegExp("watch\\?v=", "i"), 'v/');
    if ($this.attr("href").indexOf("#") === 0)
    { url = "http://www.youtube.com/v/" + $this.attr("href").substring(1) + "?fs=1&amp;autoplay=1"; }

    $.fancybox({
      'padding': 0,
      'autoScale': false,
      'transitionIn': 'none',
      'transitionOut': 'none',
      'title': this.title,
      'width': 560,
      'height': 344,
      'href': url,
      'type': 'swf',
      'swf':
      {
        'wmode': 'transparent',
        'allowfullscreen': 'true'
      }
    });
  });

  // Activate enter-key-to-submit ====================
  $(".enterKeySubmits").keypress(function (evt)
  {
    if (evt.which == 13)
    {
      evt.preventDefault();
      var btn = $("#" + $(this).attr('rel'));
      if (btn.attr('href').indexOf("javascript:") === 0)
      { eval(btn.attr('href')); }
      else
      { btn.click(); }
    }
  });

  // Activate any zip code search on the page ====================
  if ($(".zipsearch-activate").length !== 0) // prevents flicker
  { $("<img src='/_images/icon_spinnybar.gif' alt='Loading Icon' class='hid' />").appendTo("body"); }
  $($(".zipsearch-activate").attr("href")).keypress(function (evt)
  {
    if (evt.which == 13)
    {
      evt.preventDefault();
      $(".zipsearch-activate[href=#" + this.id + "]").first().click();
    }
  });
  $(".zipsearch-activate").click(function (evt)
  {
    evt.preventDefault();
    var zipCode = $($(this).attr("href")).first().val();
    if (zipCode === null || zipCode === "") { return; }
    if (zipCode.search(/^\d+$/))
    {
      Junk777.Alert("Zip Code", "To search for service, please enter the 5-digit zip code.");
      $($(this).attr("href")).first().val("");
      return;
    }

    // Tracking variables
    var minTimeComplete = false, callComplete = false, callResults = null;

    // Show the loading modal
    Junk777.ShowLoadingModal();

    // Callback after the service call is completed
    var cbCompleted = function ()
    {
      Junk777.CloseLoadingModal();
      if (callResults === null || callResults === "")
      {
        Junk777.Alert(Junk777.ServiceNotAvailableTitle, Junk777.ServiceNotAvailableMessage);
      }
      else
      {
        Junk777.Alert(Junk777.ServiceAvailableTitle, Junk777.ServiceAvailableMessage);
        window.location.replace("/step2time.aspx?zip=" + zipCode);
      }
    };

    // Make the service call and manage the spinny
    setTimeout(function ()
    {
      minTimeComplete = true;
      if (callComplete) { cbCompleted(); }
    }, 500);

    Junk777.FindServiceAreas(zipCode, function (success, r)
    {
      if (!success)
      {
        Junk777.CloseLoadingModal();
        Junk777.Alert("Error while searching", "An error was encountered while searching. Please contact customer service.");
        $.log("ERROR: %s %s (%s)", r.status, r.statusText, r.responseText);
        return;
      }
      callResults = r;
      callComplete = true;
      if (minTimeComplete) { cbCompleted(); }
    });
  });
});



