jQuery(document).ready(function(){
  subscribtionForm();
  initCarousels();
  vacatureForm();
  validateForms();
  displayForm();
  roiQuestions();
  countRoiValues();
  saveAllFormsData();
});

function subscribtionForm() {
  $("#subscribe-show-more").click(function(){
    $("#subscribe-more").fadeToggle(300);
    return false;
  });
}

function initCarousels(){
  jQuery('.gallery').slides({
    effect: 'fade',
    paginationClass: 'switcher',
    generateNextPrev: true,
    next: 'btn-next',
    prev: 'btn-prev',
    play: 5000,
    slideSpeed: 500,
    hoverPause: true
  });
  /*jQuery('div.gallery').gallery({
    duration: jQuery.browser.msie && jQuery.browser.version < 9?0:500,
    autoRotation: 5000,
    listOfSlides: '> ul > li',
    switcher: '.switcher li',
    effect:true
  });*/
  initSlideShow();
}
function displayForm(){
	$('#brochure-href').click(function(e){
		e.preventDefault();
		$('#brochure-form-container').slideToggle('fast');
	});
	$('#whitepaper-href').click(function(e){
		e.preventDefault();
		$('#whitepaper-form-container').slideToggle('fast');
	});
}
// slideshow init
function initSlideShow() {
  jQuery('div.news').fadeGallery({
    slideElements:'ul > li',
    pagerLinks:'div.pager a',
    btnNext:'a.next',
    btnPrev:'a.prev',
    btnPlayPause:'a.play-pause',
    pausedClass:'paused',
    playClass:'playing',
    activeClass:'active',
    pauseOnHover:true,
    autoRotation:true,
    autoHeight:false,
    switchTime:5000,
    duration:500,
    event:'click'
  });
}

function validateForms(){
	$.validator.addMethod("phone",function(value,element)
	{
		return this.optional(element) || /^[0-9\ \-\+]{1,20}$/i.test(value); 
	},"Bijvoorbeeld: 0123456789");
  // aanmelden nieuwsbrief
  jQuery("#aanmelden-nieuwsbrief").validate();
  jQuery("#contact-form, #roi-form").validate({
    rules: {
      name: 'required',
      email: {
        required: true,
        email: true
      },
      phone: {
        required: true,
        phone: true
      },
      message: 'required'
    },
    messages: {
      name: 'Bijvoorbeeld: Janssen',
      email: {
        required: 'E-mail adres mag niet leeg zijn',
        email: 'Bijvoorbeeld: jan@janssen.nl'
      },
      phone: 'Bijvoorbeeld: 0123456789',
      message: 'Bericht mag niet leeg zijn'
    }
  });
  
  jQuery("#contact-form, #roi-form").submit(function(){
    var form    = jQuery(this),
        errors  = form.find('.errors'),
        name    = form.find('input[name="name"]'),
        email   = form.find('input[name="email"]'),
        phone   = form.find('input[name="phone"]'),
        message = form.find('textarea[name="message"]');
    
    errors.remove();
    
    if (name.val() == '' || email.val() == '' || phone.val() == '' || message.val() == '') {
      form.find('.btn-hold button')
          .before('<div class="row errors"><p>De volgende velden zijn nog niet (correct) ingevuld:</p></div>');
      
      errors = form.find('.errors');
      
      if (name.val() == '')
        errors.append('<p>Naam</p>');
      
      if (email.val() == '')
        errors.append('<p>E-mailadres</p>');
      
      if (phone.val() == '')
        errors.append('<p>Telefoonnnummer</p>');
      
      if (message.val() == '')
        errors.append('<p>Uw bericht</p>');
    }
  });
  jQuery("#widget-form").validate({
    rules: {
      name: 'required',
      phone: {
        required: true,
        phone: true
      }
    },
    messages: {
      name: 'Bijvoorbeeld: Janssen',
      phone: 'Bijvoorbeeld: 0123456789'
    }
  });
  
  jQuery("#whitepaper-form").validate({
    rules: {
	    gender1: 'required',
      name1: 'required',
      email1: {
        required: true,
        email: true
      }
    },
    messages: {
      name1: 'Bijvoorbeeld: Janssen',
      email1: {
        required: 'E-mail adres mag niet leeg zijn',
        email: 'Bijvoorbeeld: jan@janssen.nl'
      }
    }
  });
  
  jQuery("#brochure-form").validate({
    rules: {
	    gender2: 'required',
      name2: 'required',
      email2: {
        required: true,
        email: true
      }
    },
    messages: {
      name2: 'Bijvoorbeeld: Janssen',
      email2: {
        required: 'E-mail adres mag niet leeg zijn',
        email: 'Bijvoorbeeld: jan@janssen.nl'
      }
    }
  });
  
  jQuery("#service-form").validate({
    rules: {
      naam2: 'required',
      email: {
        required: true,
        email: true
      },
	  bedrijfsnaam: 'required',
	  telefoonnummer: {
        required: true,
        phone: true
      },
      bericht: 'required'
    },
    messages: {
      name: 'Bijvoorbeeld: Janssen',
      email: {
        required: 'E-mail adres mag niet leeg zijn',
        email: 'Bijvoorbeeld: jan@janssen.nl'
      },
	  bedrijfsnaam: 'Bijvoorbeeld: DDInformatica',
      telefoonnummer: 'Bijvoorbeeld: 0123456789',
      bericht: 'Bericht mag niet leeg zijn'
    }
  });
}
 
// slideshow plugin
jQuery.fn.fadeGallery = function(_options){
  var _options = jQuery.extend({
    slideElements:'div.slideset > div',
    pagerLinks:'div.pager a',
    btnNext:'a.next',
    btnPrev:'a.prev',
    btnPlayPause:'a.play-pause',
    btnPlay:'a.play',
    btnPause:'a.pause',
    pausedClass:'paused',
    disabledClass: 'disabled',
    playClass:'playing',
    activeClass:'active',
    loadingClass:'ajax-loading',
    loadedClass:'slide-loaded',
    dynamicImageLoad:false,
    dynamicImageLoadAttr:'alt',
    currentNum:false,
    allNum:false,
    startSlide:null,
    noCircle:false,
    pauseOnHover:true,
    autoRotation:false,
    autoHeight:false,
    onBeforeFade:false,
    onAfterFade:false,
    onChange:false,
    disableWhileAnimating:false,
    switchTime:3000,
    duration:650,
    event:'click'
  },_options);

  return this.each(function(){
    // gallery options
    if(this.slideshowInit) return; else this.slideshowInit;
    var _this = jQuery(this);
    var _slides = jQuery(_options.slideElements, _this);
    var _pagerLinks = jQuery(_options.pagerLinks, _this);
    var _btnPrev = jQuery(_options.btnPrev, _this);
    var _btnNext = jQuery(_options.btnNext, _this);
    var _btnPlayPause = jQuery(_options.btnPlayPause, _this);
    var _btnPause = jQuery(_options.btnPause, _this);
    var _btnPlay = jQuery(_options.btnPlay, _this);
    var _pauseOnHover = _options.pauseOnHover;
    var _dynamicImageLoad = _options.dynamicImageLoad;
    var _dynamicImageLoadAttr = _options.dynamicImageLoadAttr;
    var _autoRotation = _options.autoRotation;
    var _activeClass = _options.activeClass;
    var _loadingClass = _options.loadingClass;
    var _loadedClass = _options.loadedClass;
    var _disabledClass = _options.disabledClass;
    var _pausedClass = _options.pausedClass;
    var _playClass = _options.playClass;
    var _autoHeight = _options.autoHeight;
    var _duration = _options.duration;
    var _switchTime = _options.switchTime;
    var _controlEvent = _options.event;
    var _currentNum = (_options.currentNum ? jQuery(_options.currentNum, _this) : false);
    var _allNum = (_options.allNum ? jQuery(_options.allNum, _this) : false);
    var _startSlide = _options.startSlide;
    var _noCycle = _options.noCircle;
    var _onChange = _options.onChange;
    var _onBeforeFade = _options.onBeforeFade;
    var _onAfterFade = _options.onAfterFade;
    var _disableWhileAnimating = _options.disableWhileAnimating;
    
    // gallery init
    var _anim = false;
    var _hover = false;
    var _prevIndex = 0;
    var _currentIndex = 0;
    var _slideCount = _slides.length;
    var _timer;
    if(_slideCount < 2) return;

    _prevIndex = _slides.index(_slides.filter('.'+_activeClass));
    if(_prevIndex < 0) _prevIndex = _currentIndex = 0;
    else _currentIndex = _prevIndex;
    if(_startSlide != null) {
      if(_startSlide == 'random') _prevIndex = _currentIndex = Math.floor(Math.random()*_slideCount);
      else _prevIndex = _currentIndex = parseInt(_startSlide);
    }
    _slides.hide().eq(_currentIndex).show();
    if(_autoRotation) _this.removeClass(_pausedClass).addClass(_playClass);
    else _this.removeClass(_playClass).addClass(_pausedClass);

    // gallery control
    if(_btnPrev.length) {
      _btnPrev.bind(_controlEvent,function(){
        prevSlide();
        return false;
      });
    }
    if(_btnNext.length) {
      _btnNext.bind(_controlEvent,function(){
        nextSlide();
        return false;
      });
    }
    if(_pagerLinks.length) {
      _pagerLinks.each(function(_ind){
        jQuery(this).bind(_controlEvent,function(){
          if(_currentIndex != _ind) {
            if(_disableWhileAnimating && _anim) return;
            _prevIndex = _currentIndex;
            _currentIndex = _ind;
            switchSlide();
          }
          return false;
        });
      });
    }

    // play pause section
    if(_btnPlayPause.length) {
      _btnPlayPause.bind(_controlEvent,function(){
        if(_this.hasClass(_pausedClass)) {
          _this.removeClass(_pausedClass).addClass(_playClass);
          _autoRotation = true;
          autoSlide();
        } else {
          _autoRotation = false;
          if(_timer) clearTimeout(_timer);
          _this.removeClass(_playClass).addClass(_pausedClass);
        }
        return false;
      });
    }
    if(_btnPlay.length) {
      _btnPlay.bind(_controlEvent,function(){
        _this.removeClass(_pausedClass).addClass(_playClass);
        _autoRotation = true;
        autoSlide();
        return false;
      });
    }
    if(_btnPause.length) {
      _btnPause.bind(_controlEvent,function(){
        _autoRotation = false;
        if(_timer) clearTimeout(_timer);
        _this.removeClass(_playClass).addClass(_pausedClass);
        return false;
      });
    }

    // dynamic image loading (swap from ATTRIBUTE)
    function loadSlide(slide) {
      if(!slide.hasClass(_loadingClass) && !slide.hasClass(_loadedClass)) {
        var images = slide.find(_dynamicImageLoad) // pass selector here
        var imagesCount = images.length;
        if(imagesCount) {
          slide.addClass(_loadingClass);
          images.each(function(){
            var img = this;
            img.onload = function(){
              img.loaded = true;
              img.onload = null;
              setTimeout(reCalc,_duration);
            }
            img.setAttribute('src', img.getAttribute(_dynamicImageLoadAttr));
            img.setAttribute(_dynamicImageLoadAttr,'');
          }).css({opacity:0});

          function reCalc() {
            var cnt = 0;
            images.each(function(){
              if(this.loaded) cnt++;
            });
            if(cnt == imagesCount) {
              slide.removeClass(_loadingClass);
              images.animate({opacity:1},{duration:_duration,complete:function(){
                if(jQuery.browser.msie && jQuery.browser.version < 9) jQuery(this).css({opacity:'auto'})
              }});
              slide.addClass(_loadedClass)
            }
          }
        }
      }
    }

    // gallery animation
    function prevSlide() {
      if(_disableWhileAnimating && _anim) return;
      _prevIndex = _currentIndex;
      if(_currentIndex > 0) _currentIndex--;
      else {
        if(_noCycle) return;
        else _currentIndex = _slideCount-1;
      }
      switchSlide();
    }
    function nextSlide() {
      if(_disableWhileAnimating && _anim) return;
      _prevIndex = _currentIndex;
      if(_currentIndex < _slideCount-1) _currentIndex++;
      else {
        if(_noCycle) return;
        else _currentIndex = 0;
      }
      switchSlide();
    }
    function refreshStatus() {
      if(_dynamicImageLoad) loadSlide(_slides.eq(_currentIndex));
      if(_pagerLinks.length) _pagerLinks.removeClass(_activeClass).eq(_currentIndex).addClass(_activeClass);
      if(_currentNum) _currentNum.text(_currentIndex+1);
      if(_allNum) _allNum.text(_slideCount);
      _slides.eq(_prevIndex).removeClass(_activeClass);
      _slides.eq(_currentIndex).addClass(_activeClass);
      if(_noCycle) {
        if(_btnPrev.length) {
          if(_currentIndex == 0) _btnPrev.addClass(_disabledClass);
          else _btnPrev.removeClass(_disabledClass);
        }
        if(_btnNext.length) {
          if(_currentIndex == _slideCount-1) _btnNext.addClass(_disabledClass);
          else _btnNext.removeClass(_disabledClass);
        }
      }
      if(typeof _onChange === 'function') {
        _onChange(_this, _slides, _prevIndex, _currentIndex);
      }
    }
    function switchSlide() {
      _anim = true;
      if(typeof _onBeforeFade === 'function') _onBeforeFade(_this, _slides, _prevIndex, _currentIndex);
      _slides.eq(_prevIndex).fadeOut(_duration,function(){
        _anim = false;
      });
      _slides.eq(_currentIndex).fadeIn(_duration,function(){
        if(typeof _onAfterFade === 'function') _onAfterFade(_this, _slides, _prevIndex, _currentIndex);
      });
      if(_autoHeight) _slides.eq(_currentIndex).parent().animate({height:_slides.eq(_currentIndex).outerHeight(true)},{duration:_duration,queue:false});
      refreshStatus();
      autoSlide();
    }

    // autoslide function
    function autoSlide() {
      if(!_autoRotation || _hover) return;
      if(_timer) clearTimeout(_timer);
      _timer = setTimeout(nextSlide,_switchTime+_duration);
    }
    if(_pauseOnHover) {
      _this.hover(function(){
        _hover = true;
        if(_timer) clearTimeout(_timer);
      },function(){
        _hover = false;
        autoSlide();
      });
    }
    jQuery(window).focus(function(){
      autoSlide();
    }).blur(function(){
      clearTimeout(_timer);
      _slides.stop();
    });
    refreshStatus();
    autoSlide();
  });
}
;(function($) {
  $.fn.gallery = function(options) {
    var args = Array.prototype.slice.call(arguments);
    args.shift();
    this.each(function(){
      if(this.galControl && typeof options === 'string') {
        if(typeof this.galControl[options] === 'function') {
          this.galControl[options].apply(this.galControl, args);
        }
      } else {
        this.galControl = new Gallery(this, options);
      }
    });
    return this;
  };
  function Gallery(context, options) { this.init(context, options); };
  Gallery.prototype = {
    options:{},
    init: function (context, options){
      this.options = $.extend({
        duration: 700,
        slideElement:1,
        autoRotation: false,
        effect: false,
        listOfSlides: '.list > li',
        switcher: false,
        autoSwitcher: false,
        disableBtn: false,
        nextBtn: 'a.link-next, a.btn-next, a.next',
        prevBtn: 'a.link-prev, a.btn-prev, a.prev',
        circle: true,
        clone: false,
        direction: false,
        event: 'click',
        IE: false
      }, options || {});
      var self = this;
      this.context = $(context);
      this.els = this.context.find(this.options.listOfSlides);
      this.list = this.els.parent();
      this.count = this.els.length;
      this.autoRotation = this.options.autoRotation;
      this.direction = this.options.direction;
      this.duration = this.options.duration;
      if (this.options.clone) {
        this.list.append(this.els.clone());
        this.list.prepend(this.els.clone());
        this.els = this.context.find(this.options.listOfSlides);
      }
      this.wrap = this.list.parent();
      if (this.options.nextBtn) this.nextBtn = this.context.find(this.options.nextBtn);
      if (this.options.prevBtn) this.prevBtn = this.context.find(this.options.prevBtn);

      this.calcParams(this);
      
      if (this.options.autoSwitcher) {
        this.switcherHolder = this.context.find(this.options.switcher).empty();
        this.switchPattern = $('<ul class="'+ (this.options.autoSwitcher == true ? '' : this.options.autoSwitcher) +'"></ul>');
        for (var i=0;i<this.max+1;i++){
          $('<li><a href="#">'+i+'</a></li>').appendTo(this.switchPattern);
        }
        this.switchPattern.appendTo(this.switcherHolder);
        this.switcher = this.context.find(this.options.switcher).find('li');
        this.active = 0;
      } else {
        if (this.options.switcher) {
          this.switcher = this.context.find(this.options.switcher);
          this.active = this.switcher.index(this.switcher.filter('.active:eq(0)'));
        }
        else this.active = this.els.index(this.els.filter('.active:eq(0)'));
      }
      if (this.active < 0) this.active = 0;
      this.last = this.active;
      if (this.options.switcher) this.switcher.removeClass('active').eq(this.active).addClass('active');
      if (this.options.clone) this.active += this.count;
      
      if (this.options.effect) this.els.css({opacity: 0}).removeClass('active').eq(this.active).addClass('active').css({opacity: 1}).css('opacity', 'auto');
      else {
        if (this.direction) this.list.css({marginTop: -(this.mas[this.active])});
        else this.list.css({marginLeft: -(this.mas[this.active])});
      }
      
      
      if (this.options.nextBtn) this.initEvent(this, this.nextBtn,true);
      if (this.options.prevBtn) this.initEvent(this, this.prevBtn,false);
      
      this.initWindow(this,$(window));
      
      if (this.autoRotation) this.runTimer(this);
      
      if (this.options.switcher) this.initEventSwitcher(this, this.switcher);
      if (this.options.disableBtn && !this.options.circle && !this.options.clone) this.disableControls();
    },
    calcParams: function(self){
      this.mas = [];
      this.sum = 0;
      this.max = this.count-1;
      this.width = 0;
      this.els.each(function(){self.mas.push(self.width);self.width += self.direction?$(this).outerHeight(true):$(this).outerWidth(true);self.sum+=self.direction?$(this).outerHeight(true):$(this).outerWidth(true);});
      this.finish = this.direction?this.sum-this.wrap.outerHeight():this.sum-this.wrap.outerWidth();
      for (var i=0;i<this.count;i++){
        if (this.mas[i]>=this.finish) {
          this.max = i;
          break;
        }
      }
    },
    changeSettings: function(set,val){
      this[set] = val;
    },
    fadeElement: function(){
      this.els.eq(this.last).animate({opacity:0}, {queue:false, duration: this.duration});
      this.els.removeClass('active').eq(this.active).addClass('active').animate({
        opacity:1
      }, {queue:false, duration: this.duration, complete: function(){
        $(this).css('opacity','auto');
      }});
      if (this.options.switcher) this.switcher.removeClass('active').eq(this.active).addClass('active');
      this.last = this.active;
    },
    scrollElement: function(f){
      if (this.direction) this.list.animate({marginTop: f ? -this.finish : -(this.mas[this.active])}, {queue:false, duration: this.duration});
      else this.list.animate({marginLeft: f ? -this.finish : -(this.mas[this.active])}, {queue:false, duration: this.duration});
      if (this.options.switcher) this.switcher.removeClass('active').eq(this.options.clone ? this.active < this.count ? this.active/this.options.slideElement : this.active >= this.count*2 ? (this.active - this.count*2)/this.options.slideElement : (this.active - this.count)/this.options.slideElement : this.active/this.options.slideElement).addClass('active');
    },
    runTimer: function($this){
      if($this._t) clearTimeout($this._t);
      $this._t = setInterval(function(){
        $this.nextStep();
      }, this.autoRotation);
    },
    initEventSwitcher: function($this, el){
      el.bind($this.options.event, function(){
        if (!$(this).hasClass('active')){
          $this.active = $this.switcher.index($(this)) * $this.options.slideElement;
          if ($this.options.clone) $this.active += $this.count;
          $this.initMove();
        }
        return false;
      });
    },
    initEvent: function($this, addEventEl, dir){
      addEventEl.bind($this.options.event, function(){
        if (dir) $this.nextStep();
        else $this.prevStep();
        if($this._t) clearTimeout($this._t);
        if ($this.autoRotation) $this.runTimer($this);
        return false;
      });
    },
    disableControls: function(){
      this.prevBtn.removeClass(this.options.disableBtn);
      this.nextBtn.removeClass(this.options.disableBtn);
      if (this.active>=this.max) this.nextBtn.addClass(this.options.disableBtn);
      if (this.active<=0) this.prevBtn.addClass(this.options.disableBtn);
    },
    initMove: function(){
      var f = false;
      if (this.active >= this.max && !this.options.clone) {
        f = true;
        this.active = this.max;
      }
      if(this._t) clearTimeout(this._t);
      if (!this.options.effect) this.scrollElement(f);
      else this.fadeElement();
      if (this.autoRotation) this.runTimer(this);
      if (this.options.disableBtn && !this.options.circle && !this.options.clone) this.disableControls();
    },
    nextStep:function(){
      var f = false;
      this.active = this.active + this.options.slideElement;
      if (this.options.disableBtn && !this.options.circle && !this.options.clone) this.disableControls();
      if (this.options.clone){
        if (this.active > this.count*2) {
          if (this.direction) this.list.css({marginTop:-this.mas[this.count]});
          else this.list.css({marginLeft:-this.mas[this.count]});
          this.active = this.count+this.options.slideElement;
        }
      } else {
        if (this.active >= this.max) {
          if (this.options.circle) {
            if (this.active > this.max) this.active = 0;
            else {
              this.active = this.max;
              f = true
            }
          }
          else {
            this.active = this.max;
            f = true;
          }
        }
      }
      if (!this.options.effect) this.scrollElement(f);
      else this.fadeElement();
    },
    prevStep: function(){
      var f = false;
      this.active = this.active - this.options.slideElement;
      if (this.options.disableBtn && !this.options.circle && !this.options.clone) this.disableControls();
      if (this.options.clone){
        if (this.active < 0) {
          if (this.direction) this.list.css({marginTop:-this.mas[this.count]});
          else this.list.css({marginLeft:-this.mas[this.count]});
          this.active = this.count-1;
        }
      } else {
        if (this.active < 0) {
          if (this.options.circle) {
            this.active = this.max;
            f = true;
          }
          else this.active = 0;
        }
      }
      if (!this.options.effect) this.scrollElement(f);
      else this.fadeElement();
    },
    initWindow: function($this,$window){
      $window.focus($.proxy(this.play,this));
      $window.blur($.proxy(this.stop,this));
    },
    stop: function(){
      if (this._t) clearTimeout(this._t);
    },
    play: function(){
      if (this._t) clearTimeout(this._t);
      if (this.autoRotation) this.runTimer(this);
    }
  }
}(jQuery));
function initPage()
{
  clearFormFields({
    clearInputs: false,
    clearTextareas: false,
    passwordFieldText: true,
    addClassFocus: "focus",
    filterClass: "default"
  });
}
  function vacatureForm() {
    $('#content .vacature-form span.after').click(function(){
      $(this).next('input[type="file"]').click();
    });
  
    $("#content .vacature-form input[type='file']").change(function(){
      //$(this).prev().attr("rel", $(this).val().split('\\').pop());
      $(this).prev('span.after').find('span').text($(this).val().split('\\').pop());
    });
    
    $("#application-form").submit(function(e){
      var toReturn = true;
      
      if ($("#application-form .errors")) {
        $("#application-form .errors").remove();
      }
      
      $("#application-form .btn-hold").before('<div class="errors" />');
      
      var err = $("#application-form .errors");
      
      if ($("#letter").val() == '') {
        $(err).append('<p>Kies een te uploaden bestand: sollicitatiebrief.</p>');
        toReturn = false;
      }

      if ($("#cv").val() == '') {
        $(err).append('<p>Kies een te uploaden bestand: curriculum vitae.</p>');
        toReturn = false;
      }
      
      if(toReturn == false) {
        e.preventDefault();
      }
      return toReturn;
    });
  }

function clearFormFields(o)
{
  if (o.clearInputs == null) o.clearInputs = true;
  if (o.clearTextareas == null) o.clearTextareas = true;
  if (o.passwordFieldText == null) o.passwordFieldText = false;
  if (o.addClassFocus == null) o.addClassFocus = false;
  if (!o.filterClass) o.filterClass = "default";
  if(o.clearInputs) {
    var inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++ ) {
      if((inputs[i].type == "text" || inputs[i].type == "password") && inputs[i].className.indexOf(o.filterClass) == -1) {
        inputs[i].valueHtml = inputs[i].value;
        inputs[i].onfocus = function ()  {
          if(this.valueHtml == this.value) this.value = "";
          if(this.fake) {
            inputsSwap(this, this.previousSibling);
            this.previousSibling.focus();
          }
          if(o.addClassFocus && !this.fake) {
            this.className += " " + o.addClassFocus;
            this.parentNode.className += " parent-" + o.addClassFocus;
          }
        }
        inputs[i].onblur = function () {
          if(this.value == "") {
            this.value = this.valueHtml;
            if(o.passwordFieldText && this.type == "password") inputsSwap(this, this.nextSibling);
          }
          if(o.addClassFocus) {
            this.className = this.className.replace(o.addClassFocus, "");
            this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
          }
        }
        if(o.passwordFieldText && inputs[i].type == "password") {
          var fakeInput = document.createElement("input");
          fakeInput.type = "text";
          fakeInput.value = inputs[i].value;
          fakeInput.className = inputs[i].className;
          fakeInput.fake = true;
          inputs[i].parentNode.insertBefore(fakeInput, inputs[i].nextSibling);
          inputsSwap(inputs[i], null);
        }
      }
    }
  }
  if(o.clearTextareas) {
    var textareas = document.getElementsByTagName("textarea");
    for(var i=0; i<textareas.length; i++) {
      if(textareas[i].className.indexOf(o.filterClass) == -1) {
        textareas[i].valueHtml = textareas[i].value;
        textareas[i].onfocus = function() {
          if(this.value == this.valueHtml) this.value = "";
          if(o.addClassFocus) {
            this.className += " " + o.addClassFocus;
            this.parentNode.className += " parent-" + o.addClassFocus;
          }
        }
        textareas[i].onblur = function() {
          if(this.value == "") this.value = this.valueHtml;
          if(o.addClassFocus) {
            this.className = this.className.replace(o.addClassFocus, "");
            this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
          }
        }
      }
    }
  }
  function inputsSwap(el, el2) {
    if(el) el.style.display = "none";
    if(el2) el2.style.display = "inline";
  }
}
if (window.addEventListener)
  window.addEventListener("load", initPage, false);
else if (window.attachEvent)
  window.attachEvent("onload", initPage);

function addCommas(nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + '.' + '$2');
    }
    return x1 + x2;
}

function roiQuestions() {
  var sliders = $("#roi-box .slider");
	
  sliders.each(function() {
    var attrs = $(this).attr("rel").split(",");
    $(this).slider({
      range: "min",
      min: parseInt(attrs[0]),
      max: parseInt(attrs[1]),
      value: parseInt(attrs[2]),
	  step: parseInt(attrs[3]),
      slide: function(event, ui) {
        $(ui.handle)
          .parent()
          .next()
          .val(ui.value)
            .next()
            .find("span")
            .text(addCommas(ui.value));
      },
	  stop: function(event, ui){
		  countRoiValues();
	  }
    });
  });

}

function countRoiValues() {
  var sliders		= $("#roi-box .slider"),
	  categoryId	= $('#div-roi-questions input[name="categoryId"]').val(),
	  urlParams		= 'categoryId=' + categoryId;
  
  sliders.each(function(){
    var field      = $(this).parent().find('input[type=hidden]'),
        fieldName  = field.attr('name'),
        fieldValue = field.val();
	
    urlParams += '&' + fieldName + '=' + fieldValue;
  });
  
  var url = '/json_getprice?' + urlParams;
 
  $.getJSON(url, function(data){
	$('#roi-amount span').text(data.price);
	$('.amount span').text(data.price);
	$('#div-roi-questions input[name="_totalPrice"]').val(data.price);
  });
}

function saveAllFormsData(){
  $("input[type=text]").change(function(){
      var fn = $(this).parents("form").attr("id");
      var fd = $(this).val();
      var inID = $(this).attr("id");
      var urlWS = 'http://' + document.domain + '/WebService/4A951B52-F960-404B-B5E9-953E30DFEF10.asmx/SaveFormsData';
      var parameters = "{'formName':'" + fn + "','inputName':'" + inID + "','inputData':'" + fd + "'}";
      var t = $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: urlWS,
        data: parameters,	        
        success: function(msg) {    
            //alert('ok');
        },
        error: function(e){
            //alert('no');
        }
      });    
  });
}
