// DocShop.com Core JS Library
// Copyright (c) 2007, Einstein Industries, Inc. All rights reserved.
// 
// Requires: ei.js, prototype.js (v1.6.0)
//

EI.namespace("DocShop");

// Form validation
//

EI.namespace("DocShop.Forms");

EI.DocShop.Forms = function() {
  
  // private functions and properties
  var _private = {
    elemsToValidate       : ['input','select'],   // form elements to validate
    classReqPrefix        : 'req_',               // class prefix used for validation type, e.g. req_email
    classToValidate       : 'validate',           // class signaling 'validate me!'
    classInvalid          : 'validate-error',
    classValid            : 'validate-ok',
    errorMessage          : 'Please complete all required fields.',

    getElementsToValidate : function(formElt) {
      var elements = new Array();
      // for each tag element type
      for (var i = 0; i < this.elemsToValidate.length; i++) {
        // get all elements with specified className
        elements = elements.concat(
          formElt.select(this.elemsToValidate[i] + '.' + this.classToValidate)
        );
      }
      return elements;
    }
  }

  // public functions and properties
  var _public = {

    init : function() {
      var objForm = $$('form');
      for (var i = 0; i < objForm.length; i++) {
        var obj = _private.getElementsToValidate(objForm[i]);
        // attach onchange validation to each element
        for (var j = 0; j < obj.length; j++)
          obj[j].observe('change', function(){ return EI.DocShop.Forms.test(this); })
        // attach validate() to the form
        if (obj.length > 0)
          objForm[i].observe('submit', function(e){ return EI.DocShop.Forms.validate(this, e) });
      }
    },

    test : function(elem) {
      var classNames = elem.className.split(' ');
      for (var i=0; i<classNames.length; i++) {
        // only check fields prefixed correctly that aren't already flagged as invalid
        if (classNames[i].indexOf(_private.classReqPrefix) >= 0 && classNames[i].indexOf(_private.classInvalid) < 0 && !elem.disabled) {
          // do validation checks & flag invalid
          switch (classNames[i]) {
            case _private.classReqPrefix + 'email':
              var isValid = _public.validEmail(elem);
              _public.updateValidState(elem,isValid);
            break;
            case _private.classReqPrefix + 'post_code_US':
              var isValid = _public.validZip(elem);
              _public.updateValidState(elem,isValid);
            break;
            case _private.classReqPrefix + 'not_empty':
              var isValid = _public.validNotEmpty(elem);
              _public.updateValidState(elem,isValid);
            break;
            case _private.classReqPrefix + 'not_default_select':
              var isValid = _public.validNotDefaultSelect(elem);
              _public.updateValidState(elem,isValid);
            break;
            case _private.classReqPrefix + 'has_value':
              var isValid = _public.validHasValue(elem);
              _public.updateValidState(elem,isValid);
            break;
          }
        }
      }
    },

    validate : function(f, e) {
      // do one final validation fly-over
      var elems = _private.getElementsToValidate(f);
      for (var i = 0; i < elems.length; i++)
        _public.test(elems[i]);
      var elems_invalid = f.select('.' + _private.classInvalid + ':not([disabled~=disabled])');
      // are any required inputs flagged as invalid?
      if ( elems_invalid.length ) {
        alert(_private.errorMessage);
        elems_invalid[0].focus();
        e.stop(); return false;
      }
    },

    updateValidState : function(elem,isValid) {
      if (isValid) {
        // flag as valid
        elem.removeClassName(_private.classInvalid);
        elem.addClassName(_private.classValid);
      } else {
        // flag as invalid
        elem.addClassName(_private.classInvalid);
        elem.removeClassName(_private.classValid);
      }
    },

    // validation routines
    validEmail : function(elem) {
      // email regular expression (http://www.regexlib.com)
      var regex = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
      return regex.test(elem.value)
    },
    
    validZip : function(elem) {
      // checks for 5-digit zip code
      var regex = /^\d{5}$/;
      return regex.test(elem.value);
    },

    validNotEmpty : function(elem) {
      // checks for empty or only whitespace
      var regex = /\S/;
      return (regex.test(elem.value) && elem.value != elem.defaultValue);
    },

    validNotDefaultSelect : function(elem) {
      // checks if default option is selected
      return (elem.value != elem.options[0].value);
    },

    validHasValue : function(elem) {
      // checks for empty or only whitespace
      var regex = /\S/;
      return (regex.test(elem.value));
    }
  }
  return _public;
}();

document.observe('dom:loaded', EI.DocShop.Forms.init);

// Outgoing link click tracking
// 

EI.namespace("DocShop.ClickTracks");

EI.DocShop.ClickTracks = function() {

  var _targetClassName = 'ga_target';
  var _clickPause = 1500;

  return {

    init : function() {
      var targets = $$('a.' + _targetClassName);
      // Attach event for all targeted links
      for (var i = 0; i < targets.length; i++){
        targets[i].observe('click', EI.DocShop.ClickTracks.recordClick)
      }
    },

    recordClick : function(e) {
      var eTarget = e.target || e.srcElement;

      // Prevent recording double clicks twice
      if (e.timeStamp-eTarget.lastClick > _clickPause || eTarget.lastClick==null) {

        // Extract URL & remove any path and "http://www."
        var url = this.href;
        var domain = url.replace(/http(s)?:\/\/|www\./gi,'').split('/')[0];

        // Record event
        if (domain) {
          try {
            _gaq.push(['_trackEvent', 'External Link', 'click', domain.toLowerCase()]);
          }
          catch (err) {}
        }

        // Reset timestamp
        eTarget.lastClick = e.timeStamp;
      }
    }
  }
}();

document.observe('dom:loaded', EI.DocShop.ClickTracks.init);

// The PhoneClickTracks constructor attaches a click tracking behavior to links
//
// Requires: Prototype 1.6+
//
// Parameters:
//
//   click_elem_classname:  Classname of link elements to which we will attach click tracking
//   options:               Hash of paramters to pass to tracking script, i.e. profile_id, site_id, nav
//
// Additional notes:
//
//  PhoneClickTracks looks for the first <span> following the click element and toggles visibility of both.
//  Also hits tracking script, as well as Google Analytics.
// 
EI.namespace('EI.DocShop.PhoneClickTracks');

EI.DocShop.PhoneClickTracks = function(click_elem_classname, options) {

  var self   = this;

  var loadPhoneClickBehavior = function() {
    $$('.' + click_elem_classname).each(function(elem){
      elem.observe('click', function(e){

        var phone_number = elem.next('span');
        if (phone_number) {

          // Toggle visibility of elements
          elem.hide();
          phone_number.show();

          // Hit tracking script
          new Ajax.Request('/cgi-opt/stats_track.cgi', {
            method: 'get',
            parameters: options
          });

          // Record event
          if (options.domain) {
            try {
              _gaq.push(['_trackEvent', 'Phone Number', 'click', options.domain.toLowerCase()]);
            }
            catch (err) {}
          }
        }

        Event.stop(e);
      });
    });
  }

  // Initializes slide show
  // 
  var initialize = function() {
    document.observe('dom:loaded', function() {
      loadPhoneClickBehavior();
    });
  }();

}


// Automatic pullquotes for articles
// adapted from http://www.456bereastreet.com/js/pullquote.js
//

EI.namespace("DocShop.PullQuotes");

EI.DocShop.PullQuotes = function () {

  var _el, _pullquote, _pullquote_p;
  var _classname = 'pullquote';
  var _regex = new RegExp("(^|\\s)" + _classname + "(\\s|$)");

  // -- Public --
  return {
    
    init: function() {

      // Check browser support
      if (!document.getElementById || !document.createElement || !document.appendChild) return false;

      // Find all span elements
      var arrElements = $$('span');

      for (i = 0; i < arrElements.length; i++) {

        _el = arrElements[i];

        // Check classname for a match
        if (_regex.test(_el.className)) {

          // Create the blockquote and p elements
          _pullquote = document.createElement('blockquote');
          _pullquote.className = _el.className
          _pullquote_p = document.createElement('p');

          // Insert the pullquote text
          for(j = 0; j < _el.childNodes.length; j++) {
            _pullquote_p.appendChild(_el.childNodes[j].cloneNode(true));
          }
          _pullquote.appendChild(_pullquote_p);

          // Insert the blockquote element before the span element's parent element
          _el.parentNode.parentNode.insertBefore(_pullquote,_el.parentNode);
        }
      }
    } 
  };
}();

document.observe('dom:loaded', EI.DocShop.PullQuotes.init);


// Automatic addition of link to *Shop directory page based on specialty ID
//
// Requires: Prototype 1.6.x

EI.namespace("DocShop.DirectoryAutoLink");

EI.DocShop.DirectoryAutoLink = function() {

  var _element, _html;
  var _elementId = 'content';
  var _className = 'directory_autolink info';
  var _language = document.location.pathname.split('/').indexOf('es') == true ? 'es' : 'en';

  var _specialtyList = {
    5:  { text: { 'en' : 'a dentist', 'es' : 'un dentista' },                                      url: '/dentists/subspec.html' },
    6:  { text: { 'en' : 'a cosmetic dermatologist', 'es' : 'un dermatólogo' },                    url: '/dermatology_procedures/states.html' },
    7:  { text: { 'en' : 'a facial plastic surgeon', 'es' : 'un cirujano plástica facial' },       url: '/facial_plastic_surgeons/states.html' },
    12: { text: { 'en' : 'an oncologist', 'es' : 'un oncologista' },                               url: '/oncologists/states.html' },
    13: { text: { 'en' : 'an eye care specialist', 'es' : 'un oftalmólogo' },                      url: '/eye_care_specialists/subspec.html' },
    18: { text: { 'en' : 'a cosmetic surgeon', 'es' : 'un cirujano estético' },                    url: '/plastic_cosmetic_surgeons/states.html' },
    23: { text: { 'en' : 'a fertility specialist', 'es' : 'un especialista en reproducción' },     url: '/infertility_reproductive_specialists/states.html' },
    25: { text: { 'en' : 'a bariatric surgeon', 'es' : 'un cirujano bariátrico' },                 url: '/bariatric_weight_loss_surgeons/states.html' },
    26: { text: { 'en' : 'a hair loss specialist', 'es' : 'un especialista en pérdida de pelo' },  url: '/hair_loss_specialists/states.html' },
    32: { text: { 'en' : 'a day spa', 'es' : 'un spa' },                                           url: '/day_spas/states.html' },
    34: { text: { 'en' : 'a radiologist', 'es' : 'un radiologista' },                              url: '/radiologists/states.html' },
    41: { text: { 'en' : 'a hearing loss specialist', 'es' : 'un especialista en audición' },      url: '/hearing_loss_specialists/states.html' }
  }

  // -- Public --
  return {
    
    init: function(options) {

      if (typeof(options) != 'object') return;

      var paragraphOffset = options.paragraphOffset;
      var specialtyId = options.specialtyId;

      _element = $(_elementId)

      if (_element && _specialtyList[specialtyId]) {

        // Create the p element
        _html = new Element('p', { 'class': _className });
        _html.update( _language == 'en' ? 
          'DocShop can help you <a href="/zipsearch?specialty_id=' + specialtyId + '">find ' + _specialtyList[specialtyId].text[_language] + '</a> in your area today.' : 
          'DocShop puede ayudarlo a <a href="/zipsearch?specialty_id=' + specialtyId + '">buscar ' + _specialtyList[specialtyId].text[_language] + '</a> en su región.'
        );

        // Insert the link below third paragraph
        _element.down('p', paragraphOffset).insert({ after: _html });
      }

    }
  };
}();


// Functionality for DocShop Search
// Author: Adam Patten apatten@einsteinindustries.com
// 

EI.namespace("DocShop.Search");

EI.DocShop.Search = function() {

  // private functions and properties
  var _private = {
    specialtyZipSearch_class : 'specialtyZipSearch',
    specialtyZipSearch_specialtyClass : 'specialty'
  }

  // public functions and properties
  var _public = {

    init : function() {
      var objForm = $$('form');
      for (var i = 0; i < objForm.length; i++) {
        if (objForm[i].hasClassName(_private.specialtyZipSearch_class)) {
          objForm[i].observe('submit', function(e){ if (!e.stopped) return EI.DocShop.Search.specialtyZipSearch_concat(this, e); })
        }
      }
    },

    specialtyZipSearch_concat : function(obj, event) {
      var specialtySelect;
      var specialty = '';
      var zip = obj.query.value;

      specialtySelect = obj.select('select.' + _private.specialtyZipSearch_specialtyClass);
      
      if(specialtySelect && 0 != specialtySelect[0].selectedIndex) {
        specialty = specialtySelect[0].value + '+';
        document.location = 'http://' + document.domain + '/search/?query=' + specialty + zip;
        event.stop();
      }
    }
  }
  return _public;
}();

document.observe('dom:loaded', EI.DocShop.Search.init);


// Prevents button mashing clicky-clicky
//
EI.ButtonMash = function() {
  var _class_name = '.no-mash';
  var _click_pause = 1500;

  return {
    prevent: function(event) {
      var target = event.findElement();
      if (target.lastClick && (event.timeStamp - target.lastClick) < _click_pause) {
        Event.stop(event);
      }
      target.lastClick = event.timeStamp;
    },
    init: function() {
      $$(_class_name).each(function(element){
        element.observe('click', function(e){ EI.ButtonMash.prevent(e) });
      })
    }
  }
}();

document.observe('dom:loaded', EI.ButtonMash.init);
