﻿if (typeof window.xcore == 'undefined') {
   window.xcore = {};
}

// banner slider
window.xcore.fader = {

   init: function (els, delay, slide_transition_speed) {
      if (!els) {
         alert('No elements to be "faded"...');
         return;
      }

      var size = els.length,
      curr_index = 0,
      delay = delay != null ? delay : 5000,
      slidespeed = slide_transition_speed <= 1000 ? 1000 : slide_transition_speed,
      interval = null;

      var toggleanimation = function (pause) {
         if (pause)
            clearInterval(interval);
         else
            interval = setInterval(slideNext, delay);
      }

      var slide = function (speedoverride) {
         var speed = speedoverride ? speedoverride : slidespeed;

         $(els).stop(false, true).fadeOut(speed / 1.2);
         $(els[curr_index]).stop(false, true).fadeIn(speed);
      }

      var slideNext = function (speedoverride) {
         if (curr_index < size - 1) curr_index++;
         else curr_index = 0;
         slide(speedoverride);
      }

      var slidePrevious = function (speedoverride) {
         if (curr_index < 1) curr_index = size - 1;
         else curr_index--;
         slide(speedoverride);
      }

      slide();
      interval = setInterval(slideNext, delay);

      var container = $(els[0]).parent();
      $(container).children('span.forward').click(function () { clearInterval(interval); slideNext(300); });
      $(container).children('span.backward').click(function () { clearInterval(interval); slidePrevious(300); }); //.mouseleave(function () { interval = setInterval(slideNext, delay); })

      for (i = 0; i <= els.length - 1; i++) {
         $(els[i]).hover(function () {
            toggleanimation(true);
         }, function () {
            toggleanimation(false);
         });
      }
   }
};

window.xcore.windowState = (function () {
   var readScroll = {
      scrollLeft: 0,
      scrollTop: 0
   },
    readSize = {
       clientWidth: 0,
       clientHeight: 0
    },
    readScrollX = 'scrollLeft',
    readScrollY = 'scrollTop',
    readWidth = 'clientWidth',
    readHeight = 'clientHeight';

   function otherWindowTest(obj) {
      if ((document.compatMode) && (document.compatMode == 'CSS1Compat') && (document.documentElement)) {
         return document.documentElement;
      } else if (document.body) {
         return document.body;
      } else {
         return obj;
      }
   };

   if ((typeof this.innerHeight == 'number') && (typeof this.innerWidth == 'number')) {
      readSize = this;
      readWidth = 'innerWidth';
      readHeight = 'innerHeight';
   } else {
      readSize = otherWindowTest(readSize);
   }
   if ((typeof this.pageYOffset == 'number') && (typeof this.pageXOffset == 'number')) {
      readScroll = this;
      readScrollY = 'pageYOffset';
      readScrollX = 'pageXOffset';
   } else {
      readScroll = otherWindowTest(readScroll);
   }

   return {
      getScrollX: function () {
         return (readScroll[readScrollX] || 0);
      },
      getScrollY: function () {
         return (readScroll[readScrollY] || 0);
      },
      getWidth: function () {
         return (readSize[readWidth] || 0);
      },
      getHeight: function () {
         return (readSize[readHeight] || 0);
      }
   };

})();

window.xcore.PageFader = function (options) {
   $(window).resize(function () {
      var $el = $('#obscurer');

      if (typeof $el != 'undefined') {
         $el.css('height', document.body.offsetHeight);
         $el.css('width', document.body.offsetWidth);
      }
   });

   return new function (options) {
      var that = this;

      options = options || {};

      this.isOn = true;

      if (typeof options.waitImage !== 'undefined') {
         this.waitImage = options.waitImage;
      }

      this.toggle = function () {
         var $el = $(document.createElement('div')),
			$img,
         horizontalScroll,
         verticalScroll,
         viewPortHeight,
         viewPortWidth;

         if (that.isOn) {
            $el.attr('id', 'obscurer');
            $el.css('background-color', '#000');
            $el.css('height', document.body.offsetHeight);
            $el.css('width', document.body.offsetWidth);
            $el.css('position', 'absolute');
            $el.css('z-index', '400000');
            $el.css('top', '0');
            $el.hide();

            if (typeof that.waitImage !== 'undefined') {
               $img = $(document.createElement('img'));
               $img.attr('src', that.options.waitImage);
               $img.attr('id', 'wait-image');

               viewPortHeight = xcore.windowState.getHeight();
               viewPortWidth = xcore.windowState.getWidth();
               horizontalScroll = xcore.windowState.getScrollX();
               verticalScroll = xcore.windowState.getScrollY();

               var left = Math.round(horizontalScroll + ((viewPortWidth - $img.width) / 2));
               var top = Math.round(verticalScroll + ((viewPortHeight - $img.height) / 2));

               $img.attr('style', 'position:absolute; left:' + left + '; top: ' + top + '; z-index:2000000');

               $el.append($img[0]);
            }
            else {
               if ($el.children().size() > 0) {
                  $el.children().remove();
               }
            }

            document.body.appendChild($el[0]);

            $el.fadeTo('slow', 0.8);
         }
         else {
            that.$el = $('#obscurer');

            that.$el.fadeOut('slow', function () { that.$el.remove(); });
         }

         that.isOn = !that.isOn;
      }
   }
};

window.xcore.FormFields = function () {
   if (typeof this === window) {
      return new xcore.FormFields();
   }

   return new function () {
      var that = this
		  , regEmail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/
		  , regUrl = /^(((ftp|http|https):\/\/)|(www\.))(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/
		  , regPhone = /^(\+\d)*\s*(\d{3}\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/;

      this.options = {};
      this.isJQuery = false;
      this.notificationareas = [];

      this.init = function (options) {
         var fields;

         if (options !== 'undefined') {
            that.options = options;
         }
         that.isJQuery = typeof $ !== 'undefined';

         if (that.isJQuery) {
            fields = $('input[type=text].[class*=validate-], textarea.[class*=validate-], select.[class*=validate-]');

            fields.blur(that.validate);    // attach blur validation for each input text and textarea
            that._augmentFields(fields);   // augment input fields attributes
         }
      };

      this._augmentFields = function (els) {
         var props,
             i,
             valSummaryIdx,
             notifications = $('[class*=validateNotification]');

         for (i = 0; i < els.length; i++) {
            els[i].validate = that.validate;

            props = that._getValidationProperties(els[i]);

            $.each(notifications, function (i) {
               valSummaryIdx = this.className.split('-');

               if (valSummaryIdx[1] === 'undefined') {
                  console.log('no group defined on notification area!');
               }
               that.notificationareas[valSummaryIdx[1]] = {};
               that.notificationareas[valSummaryIdx[1]].element = this;
               that.notificationareas[valSummaryIdx[1]].isposted = false;
            });

            els[i].errormessage = props.errormessage;
            els[i].valtype = props.valtype;
            els[i].valgroup = props.valgroup;

            // labelize fields
            if (that.options.labelize) {
               that._labelize(els[i]);
            }
         }
      };

      this.isValidForm = function (group) {
         var $inputs,
         selector,
			isvalid = true,
         i;

         if (group !== 'undefined') {
            selector = 'input[type=text].[class*=validate-' + group + '], textarea.[class*=validate-' + group + '], select.[class*=validate-' + group + ']';
            that.notificationareas[group].isposted = true;
         }
         else {
            selector = 'input[type=text].[class*=validate-], textarea.[class*=validate-], select.[class*=validate-]';
            that.notificationareas[0].isposted = true;
         }

         $inputs = $(selector);

         for (i = 0; i < $inputs.length; i++) {
            if (!$inputs[i].validate()) {
               isvalid = false;
            }
         }

         return isvalid;
      };

      this.validate = function () {
         var isvalid = true;

         if (typeof this !== 'undefined' && that.notificationareas[this.valgroup].isposted) {
            if (this.nodeName === 'INPUT') {
               isvalid = that._validateInputText(this);
            }
            if (this.nodeName === 'TEXTAREA') {
               isvalid = that._validateInputText(this);
            }
            if (this.nodeName === 'SELECT') {
               isvalid = that._validateSelectField(this);
            }

            if (!isvalid) {
               that._addMessage(this);
               $(this).addClass('error');
            }
            else {
               that._removeMessage(this);
               $(this).removeClass('error');
            }
         }
         return isvalid;
      };

      this._addMessage = function (el) {
         if (el.valgroup === 'undefined') return;
         var ul = that.notificationareas[el.valgroup].element,
             ulChildren = $(ul).children(),
             li,
             i;

         if (typeof ul === 'undefined') return;

         for (i = 0; i < ulChildren.length; i++) {
            if (ulChildren[i].className.indexOf(el.id) > -1)
               return;
         }

         li = document.createElement('li');
         $(li).addClass(el.id);
         $(li).addClass('error');
         li.innerHTML = el.errormessage;

         ul.appendChild(li);
      };

      this._removeMessage = function (el) {
         if (el.valgroup === 'undefined') return;
         var group = that.notificationareas[el.valgroup].element,
             selector = '.' + el.id;

         if (typeof group === 'undefined') return;

         $(group).children().remove(selector);
      };

      this._labelize = function (el) {
         el.value = el.title;

         if (that.isJQuery) {
            $(el).click(function () {
               if (this.value === this.title) { this.value = ''; }
            });
            $(el).focus(function () {
               if (this.value === this.title) { this.value = ''; }
            });
            $(el).blur(function () {
               if (this.value === '') { this.value = this.title; }
            });
         }
         // else {
         // handle non-jquery
         // }
      };

      this._validateInputText = function (el) {

         if (el.title === el.value) {
            return false;
         }

         switch (el.valtype) {
            case 'notempty':
               if (el.value === '') {
                  return false;
               }
               return true;
            case 'url':
               if (!regUrl.test(el.value)) {
                  return false;
               }
               return true;
            case 'email':
               if (!regEmail.test(el.value)) {
                  return false;
               }
               return true;
            case 'phone':
               if (!regPhone.test(el.value)) {
                  return false;
               }
               return true;
            default:
               return true;
         }
      };

      this._validateSelectField = function (el) {
         switch (el.valtype) {
            case 'notempty':
               if ($(el).val() === '') {
                  return false;
               }
               return true;
            default:
               return true;
         }
      };

      this._getValidationProperties = function (el) {
         var startIdx = el.className.indexOf('validate-'),
				 descriptor = el.className.substring(startIdx),
				 fragments;

         // if descriptor is not the last class
         if (el.className.indexOf(' ', startIdx) > 0) {
            descriptor = el.className.substring(startIdx, el.className.indexOf(' ', startIdx) - 1);
         }

         fragments = descriptor.split('-');

         return {
            valgroup: fragments[1],
            valtype: fragments[2],
            errormessage: fragments[3].split('_').join(' ')
         };
      };
   };
};
