// Don't add the toggle value text if the field has a value, but instead add it on change
function applyToggleValue($field, populateFrom) {
  if ($field.val() == '') {
    $field.toggleVal({
      populateFrom: populateFrom
    });
  }
  else {
    $field.change(function(){
      if ($(this).val() == "") {
        $field.toggleVal({
          populateFrom: populateFrom
        });
      }
    });
  }
}

function isEmptyOrDefaultValue(field) {
  return $(field).val() == "" || $(field).val() == $(field).data("defText");
}

// FIXME: Ignores DST
Date.prototype.addDays = function(count) {
  return new Date(this.valueOf() + 86400000 * count);
}

// derived from http://delete.me.uk/2005/03/iso8601.html
Date.parseISO8601 = function(s, ignoreTimezone) {
  var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
  "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
  "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
  var d = s.match(new RegExp(regexp));
  if (!d) return null;
  var offset = 0;
  var date = new Date(d[1], 0, 1);
  if (d[3]) {
    date.setMonth(d[3] - 1);
  }
  if (d[5]) {
    date.setDate(d[5]);
  }
  if (d[7]) {
    date.setHours(d[7]);
  }
  if (d[8]) {
    date.setMinutes(d[8]);
  }
  if (d[10]) {
    date.setSeconds(d[10]);
  }
  if (d[12]) {
    date.setMilliseconds(Number("0." + d[12]) * 1000);
  }
  if (!ignoreTimezone) {
    if (d[14]) {
      offset = (Number(d[16]) * 60) + Number(d[17]);
      offset *= ((d[15] == '-') ? 1 : -1);
    }
    offset -= date.getTimezoneOffset();
  }
  return new Date(Number(date) + (offset * 60 * 1000));
}

//http://jacwright.com/projects/javascript/date_format
Date.prototype.format=function(format){var returnStr='';var replace=Date.replaceChars;for(var i=0;i<format.length;i++){var curChar=format.charAt(i);if(replace[curChar]){returnStr+=replace[curChar].call(this);}else{returnStr+=curChar;}}return returnStr;};Date.replaceChars={shortMonths:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],longMonths:['January','February','March','April','May','June','July','August','September','October','November','December'],shortDays:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],longDays:['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],d:function(){return(this.getDate()<10?'0':'')+this.getDate();},D:function(){return Date.replaceChars.shortDays[this.getDay()];},j:function(){return this.getDate();},l:function(){return Date.replaceChars.longDays[this.getDay()];},N:function(){return this.getDay()+1;},S:function(){return(this.getDate()%10==1&&this.getDate()!=11?'st':(this.getDate()%10==2&&this.getDate()!=12?'nd':(this.getDate()%10==3&&this.getDate()!=13?'rd':'th')));},w:function(){return this.getDay();},z:function(){return"Not Yet Supported";},W:function(){return"Not Yet Supported";},F:function(){return Date.replaceChars.longMonths[this.getMonth()];},m:function(){return(this.getMonth()<9?'0':'')+(this.getMonth()+1);},M:function(){return Date.replaceChars.shortMonths[this.getMonth()];},n:function(){return this.getMonth()+1;},t:function(){return"Not Yet Supported";},L:function(){return(((this.getFullYear()%4==0)&&(this.getFullYear()%100!=0))||(this.getFullYear()%400==0))?'1':'0';},o:function(){return"Not Supported";},Y:function(){return this.getFullYear();},y:function(){return(''+this.getFullYear()).substr(2);},a:function(){return this.getHours()<12?'am':'pm';},A:function(){return this.getHours()<12?'AM':'PM';},B:function(){return"Not Yet Supported";},g:function(){return this.getHours()%12||12;},G:function(){return this.getHours();},h:function(){return((this.getHours()%12||12)<10?'0':'')+(this.getHours()%12||12);},H:function(){return(this.getHours()<10?'0':'')+this.getHours();},i:function(){return(this.getMinutes()<10?'0':'')+this.getMinutes();},s:function(){return(this.getSeconds()<10?'0':'')+this.getSeconds();},e:function(){return"Not Yet Supported";},I:function(){return"Not Supported";},O:function(){return(-this.getTimezoneOffset()<0?'-':'+')+(Math.abs(this.getTimezoneOffset()/60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()/60))+'00';},P:function(){return(-this.getTimezoneOffset()<0?'-':'+')+(Math.abs(this.getTimezoneOffset()/60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()/60))+':'+(Math.abs(this.getTimezoneOffset()%60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()%60));},T:function(){var m=this.getMonth();this.setMonth(0);var result=this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/,'$1');this.setMonth(m);return result;},Z:function(){return-this.getTimezoneOffset()*60;},c:function(){return this.format("Y-m-d")+"T"+this.format("H:i:sP");},r:function(){return this.toString();},U:function(){return this.getTime()/1000;}};

function getCookie(check_name){var a_all_cookies=document.cookie.split(';');var a_temp_cookie='';var cookie_name='';var cookie_value='';var b_cookie_found=false;for(i=0;i<a_all_cookies.length;i++)
{a_temp_cookie=a_all_cookies[i].split('=');cookie_name=a_temp_cookie[0].replace(/^\s+|\s+$/g,'');if(cookie_name==check_name)
{b_cookie_found=true;if(a_temp_cookie.length>1)
{cookie_value=unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g,''));}
return cookie_value;break;}
a_temp_cookie=null;cookie_name='';}
if(!b_cookie_found)
{return null;}}


(function($) {
  $.fn.appointmentList = function(options) {
    if($.appointmentList.options === undefined)
      $.appointmentList.options = options
    else {
      options = $.extend($.appointmentList.options, options)
    }

    return this.each(function(){

      function dates() {
        return $headerDiv.find('li div').map( function() {
          return $.datepicker.parseDate('D mm/dd/y', $(this).text())
        })
      };

      function start() {
        return dates()[0];
      };

      options.nextButton.click(function() {
        setStart(start().addDays(7));
        return false
      })

      options.prevButton.click(function() {
        setStart(start().addDays(-7));
        return false
      })

      var $headerDiv = $( this );

      function setStart(date) {
        $.getJSON( options.url,
        {
          start: date,
          appointment_type: options.appointment_type.val() == undefined ? '' : options.appointment_type.val()
        },
        function(data) {
          $headerDiv.find('li div').each( function(index) {
            $(this).html($.datepicker.formatDate('D mm/dd/y', date.addDays(index)));
          });
          $('div.days').each(function() {
            $(this).replaceWith(data[this.id.match(/\d+$/)[0]])
          })
          if(options.afterLoad)
            options.afterLoad.call(this);
        }
        )
        return null;
      };

      if( options['start'] )
        setStart(options['start'])
    })
  };

  $.appointmentList = { }

})(jQuery);