function makeUrl(params) {
    var moduleName  = params.module ? params.module : '',
        managerName = params.manager ? params.manager : moduleName,
        rslt        = location.protocol + '//' + location.host + '/' + encodeURIComponent(moduleName) + '/' + encodeURIComponent(managerName) + '/';

    for (x in params) {
        if (x == 'module' || x =='manager') continue;
        rslt += encodeURIComponent(x) + '/' + encodeURIComponent(params[x]) + '/';
    }

    return rslt;
}

function getCurrentUrl(withoutAnchor) {
    var url = document.location.href.toLowerCase();

    if (withoutAnchor) {

        var anchor_index = url.indexOf('#');

        if (anchor_index != -1)
            url = url.substring(0, anchor_index);

        if (url.lastIndexOf('/') + 1 != url.length)
            url += '/';
    }

    return url;
}

var FormUtil = {

    createHiddenValueQuick: function(form, element, reload) {
        this.createHiddenValue(form, element.name, element.value);
        if (reload)
            this.reload(form);
    },

    createHiddenValue: function(form, name, value) {
        form.append($('<input type="hidden"/>').attr('name', name).val(value));
    },

    setHiddenValueByRadioGroupValue: function(name, formName, radioGroupName) {
        $('#' + name).val($('#' + formName + ' input[name=' + radioGroupName + ']:checked').val());
    },

    reload: function(form) {
        $('#action').val($('#reloadAction').val());

        form.submit();
    },

    getForm: function(childId) {
        return $(childId).closest('form');
    },

    submitForm: function(childId) {
        this.getForm(childId).submit();
    },

    load: function(elementName, newUrl, showLoader) {
        if (showLoader)
            Loader.create();

        if (!newUrl)
            newUrl = getCurrentUrl();

        if ($('#' + elementName).length) {
            var elementValue = $('#' + elementName).val();

            if (elementValue) {
              if (newUrl.lastIndexOf('/') + 1 != newUrl.length)
                newUrl += '/';

              newUrl += elementName + '/' + elementValue + '/';
            }
        }

        document.location.href = newUrl;

        return true;
    },

    cancelForm: function(form) {
        this.createHiddenValue(form, 'cancel', 1);
        form.submit();
    },

    applyForm: function(form) {
        this.createHiddenValue(form, 'apply', 1);
        form.submit();
    },

    getFirstLabel: function(element) {
        return $(element).find('label:first');
    },

    getRequiredNote: function() {
        return ' <span class="reqSymbol">*</span>';
    },

    eatEnter: function(event, callback) {
        if (event.keyCode == 13) {
            event.preventDefault();

            if (callback)
                callback();
        }
    }
};

var ErrorHandler = {
    alert: function(html) {
        Loader.createOverlay();
        $('body').append($('<div id="jsError">' + html + '</div>'));

        $('#overlay').click(function() {
          $('#jsError').remove();
          Loader.hide();
        });
    }
};

var Loader = {
    create: function (innerHTML) {
        this.createOverlay();

        var loader = $('#loader');

        if (loader.length)
            loader.show();
        else {
            if (!innerHTML)
                innerHTML = SGL_LOADING;

            $('body').append($('<div id="loader">' + innerHTML + '</div>'));
        }
    },

    createOverlay: function() {
        var opacityLimit = .87,
            fade         = true,
            overlay      = $('#overlay');

        if (overlay.length) {
            if (overlay.css('opacity') >= opacityLimit && overlay.is(':visible'))
                fade = false;
        } else {
            overlay = $('<div id="overlay"></div>').css('opacity', '0');

            $('body').append(overlay);
        }

        if (fade)
            overlay.fadeTo(300, opacityLimit);

        return overlay;
    },

    hide: function(hideOverlay) {
        if (hideOverlay === undefined)
            hideOverlay = true;

        $('#loader').hide();

        if (hideOverlay && $('#overlay').length) $('#overlay').fadeOut(100);
    },

    waitAndGo: function(text, url) {
        this.create(text);
        setTimeout(function() {
            document.location.href = url;
            return true;
        }, 400);
    },

    confirmAndGo: function(text, url) {
        if (this.confirm(text)) {
            document.location.href = url;
            return true;
        }

        return false;
    },

    confirm: function(question) {
        var result = confirm(question);

        if (!result)
            return false;

        this.createOverlay();
        return result;
    }
};

var AjaxUtil = {

    startRequest: function(module,
                           manager,
                           action,
                           parameters,
                           successCallback,
                           disableLoader,
                           hideAjaxError,
                           completeCallback) {
        return this.startRequestByUrl(
            makeUrl({'module' : module, 'manager' : manager, 'action'  : action}),
            parameters,
            successCallback,
            'post',
            disableLoader,
            hideAjaxError,
            completeCallback
        );
    },

    startRequestByUrl: function(url,
                                parameters,
                                successCallback,
                                method,
                                disableLoader,
                                hideAjaxError,
                                completeCallback) {
        if (method === undefined)
            method = 'post';

        if (disableLoader === undefined)
            disableLoader = false;

        if (!disableLoader)
            Loader.create();

        if (completeCallback === undefined)
            completeCallback = Loader.hide;

        var settings = {
          url:      url,
          type:     method,
          data:     parameters,
          success:  successCallback,
          complete: completeCallback,
          dataType: 'json'
        };

        if (!hideAjaxError)
          settings['error'] = this.showAjaxError;

        $.ajax(settings);

        return false;
    },

    showAjaxError: function(request, textStatus) {
        ErrorHandler.alert('<h1>AJAX ' + textStatus + ' (transport ' + request.statusText + ')</h1>' + request.responseText);
    }
};

var FixTranslations = {

    get: function(key) {
        var value = false;

        if (aWords && aWords[key])
            value = aWords[key];

        if (!value)
            value = key;

        return value;
    }
};

var CookieUtil = {
    createCookie: function(name, value, days) {
        var expires = "";

        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + days * 86400000);
            expires = "; expires=" + date.toGMTString();
        }

        document.cookie = name + "=" + value + expires + "; path=/";
    },

    readCookie: function(name) {
        var nameEQ = name + "=";
        var ca     = document.cookie.split(';');
        var i      = ca.length;

        while (i--) {
            var c = ca[i];

            while (c.charAt(0) == ' ')
                c = c.substring(1, c.length);

            if (c.indexOf(nameEQ) == 0)
                return c.substring(nameEQ.length, c.length);
        }

        return null;
    },

    eraseCookie: function(name) {
        this.createCookie(name, '', -1);
    }
};

var Uploader = {

        doAttach: function(id, required) {
            var fileInputValue = false;
            var valid          = false;

            if (id)
                fileInputValue = $('#' + id).val();

            if (id && !fileInputValue){
                if (required) {
                    $('#' + id + 'Field').addClass('warning');

                    //  set focus to it
                    $('#' + id).focus();
                    translate('Please enter a file!', $('#' + id + 'Label'), true);
                } else
                    valid = true;
            } else {
                Loader.create();
                valid = true;
            }

            return valid;
        },

        doAttachAndSetHiddenValue: function(formName, name, value) {
            FormUtil.createHiddenValue($('#' + formName), name, value);
            Uploader.doAttach();
        }
    };
function doResize(textarea, defaultRows) {
    var lines   = textarea.val().split('\n'),
        newRows = lines.length,
        oldRows = textarea.attr('rows'),
        cols    = textarea.attr('cols');

    if (cols > 0) {
        for (var i = 0; i < lines.length; i++)
            if (lines[i].length >= cols)
                newRows += Math.floor(lines[i].length / cols);
    }

    if (newRows > oldRows)
        textarea.attr('rows', newRows);
    else if (newRows < oldRows)
        textarea.attr('rows', Math.max(defaultRows, newRows));
}

$(function() {
    $.fn.makeResizable = function() {
        return this.each(function() {
            var defaultRows = Math.max(this.rows, 3);

            doResize($(this), defaultRows);
            $(this).keyup(function() {
                doResize($(this), defaultRows);
            });

            if ($(this).hasClass('maxLength')) {
                $(this).attr('class').match(/max_([0-9]+)/);

                var maxVal     = RegExp.$1,
                    difference = maxVal - $(this).val().length;

                if (difference > 0)
                    $('#' + this.id + 'LengthCount').text(difference);

                $(this).keyup(function() {
                    if ($(this).val().length > maxVal) $(this).val($(this).val().substring(0, maxVal));
                    $('#' + this.id + 'LengthCount').text(maxVal - $(this).val().length);
                });
            }
        });
    };
});
var effectLoader = {

    duration: 250,

    initialize: function() {

        $('form').each(function() {

            $(this).find('p.req').each(function() {
                FormUtil.getFirstLabel(this).append(FormUtil.getRequiredNote());
            });

            if ($(this).parents().is('#page')) {

                $(this).find('#checkAll').click(function() {
                    var doCheck = this.checked;

                    $(this).closest('form').find('input:checkbox').each(function() {
                        this.checked = doCheck;
                    });
                });

                $(this).find('.cancel').click(function() {
                    FormUtil.cancelForm($(this).closest('form'));
                });

                $(this).find('.apply').click(function() {
                    FormUtil.applyForm($(this).closest('form'));
                });

                $(this).find('textarea:not(.disabled)').each(function() {
                    $(this).makeResizable();
                });
            }
        });

        if (typeof elementId2Focus != 'undefined' && elementId2Focus !== false)
            $('#' + elementId2Focus).focus();

        $('#sidebarToggle').click(function() {
            effectLoader.onSidebarToggleClick();
        });

        this.initializeTogglers();
    },

    initializeTogglers: function() {
        $('.toggle').each(function() {
            effectLoader.validateToggler($(this));

            $(this).click(function() {
                effectLoader.toggle($(this));
            });
        });
    },

    validateToggler: function(toggle) {
        var toggleTarget = this.getToggleTarget(toggle);

        if (toggleTarget.length) {
            var name  = this.getToggleCookieName(toggleTarget),
                value = CookieUtil.readCookie(name);

            if (value) {
                var open = toggleTarget.is(':visible');

                if (!open && value == 'open' ||
                     open && value == 'close')
                       this.toggle(toggle);
                else {
                   if (open)
                       toggle.removeClass('closed');
                   else
                       toggle.addClass('closed');
               }
            } else
                if (toggle.hasClass('closed'))
                    toggleTarget.hide();
        }
    },

    getToggleTarget: function (toggle) {

        var toggleTarget = $(toggle).next('.toggleTarget');

        if (!toggleTarget.length)
            toggleTarget = $(toggle).siblings('.toggleTarget:first');

        if (!toggleTarget.length)
            toggleTarget = $(toggle).parent().siblings('.toggleTarget:first');

        return toggleTarget;
    },

    getToggleCookieName: function(toggleTarget) {
        return jQuery.trim(
                   toggleTarget[0].baseURI + ' ' +
                   toggleTarget.attr('class') + ' ' +
                   toggleTarget.attr('id')
               );
    },

    toggle: function(toggle) {
        var toggleTarget = this.getToggleTarget(toggle);

        if (toggleTarget && toggleTarget.length) {

            var fast = toggleTarget.html().length > 15000,
                opened;

            if (toggleTarget.is(':visible')) {
                if (fast)
                    toggleTarget.hide();
                else
                    toggleTarget.toggle('blind', {}, this.duration);

                opened = false;

                $(toggle).addClass('closed');
            } else {
                if (fast)
                    toggleTarget.show();
                else
                    toggleTarget.toggle('blind', {}, this.duration);

                opened = true;

                $(toggle).removeClass('closed');
            }

            var value = opened ? 'open' : 'close';

            CookieUtil.createCookie(this.getToggleCookieName(toggleTarget), value, 1);
        }
    },

    onSidebarToggleClick: function()
    {
        var sidebar = $('#sidebar'),
            opened,
            sidebarClass = sidebar.attr('class');

        if (sidebarClass.length < 1 || sidebarClass == 'open') {
            opened = false;

            $('#page').removeClass('collapsed').addClass('expanded');
            sidebar.removeClass('open').addClass('closed');
        } else {
            opened = true;

            $('#page').removeClass('expanded').addClass('collapsed');
            sidebar.removeClass('closed').addClass('open');
        }

        CookieUtil.createCookie('sidebar', opened ? 'open' : 'closed', 1);
    }
};

$(function() {
    effectLoader.initialize();
});
var externalLinks =  {
    rebuild: function() {
        $('a[rel*=external]').click(function() {
            return !window.open($(this).attr('href'));
        });
    }
};

$(function() {
    externalLinks.rebuild();
});
var customEffectLoader = {

    jumpMargin: 40,
    sloganCounter: 0,

    initialize: function() {
      if ($('#scenePlayer').length) {
        this.initializeScenePlayer();
      } else {
        this.initializeJumpBox();
        this.initializeVideoPopups();
        this.initializeTabbing();
        this.initializeFaqLink();
        this.initializeNewsButton();

        if (typeof aSlogans !== "undefined") {
          this.loopSlogans();
        }

        if ($('#slidesWrapper').length) {
          this.initVideoSlider();
        }
      }
    },

    initVideoSlider: function() {
      $("#slidesWrapper").slides({
          container: 'slidesContainer',
          next: 'slide-right',
          prev: 'slide-left',
          pagination: true,
          fadeSpeed: effectLoader.duration
      });
    },

    loopSlogans: function() {
        setTimeout(customEffectLoader.nextSlogan, 4500);
    },

    nextSlogan: function() {
      $('#slogan').fadeOut(effectLoader.duration, function() {
        customEffectLoader.sloganCounter++;

        if (customEffectLoader.sloganCounter >= aSlogans.length)
          customEffectLoader.sloganCounter = 0;

        $('#slogan').text(aSlogans[customEffectLoader.sloganCounter]).fadeIn(effectLoader.duration, customEffectLoader.loopSlogans);
      });
    },

    initializeJumpBox: function(selector) {
      if (typeof selector === undefined)
        selector = '.secondCol ol.jump:visible';

      $(selector).each(function() {
        var jump = $(this).attr('data-defaultOffsetTop', $(this).offset().top);
        $(window).scroll(function() {
          var o1     = jump.offset().top - customEffectLoader.jumpMargin;
          var offset = $(window).scrollTop() - o1;

          if (offset > 0)
            jump.stop().animate({top: '+=' + parseInt(offset)}, effectLoader.duration, 'swing');
          else {
            offset = Math.abs(parseInt(offset));

            if (o1 - offset < jump.attr('data-defaultOffsetTop'))
              offset = 0;
            else
              offset = '-=' + offset;

            jump.stop().animate({top: offset}, effectLoader.duration, 'swing');
          }
        });
      });
    },

    initializeTabbing: function() {
      var tabs = $('#jTabs').tabs();

      $('#jTabs div button').each(function() {
        $(this).click(function() {
          tabs.tabs('select', tabs.tabs('option', 'selected') + 1);
        });
      });
    },

    initializeFaqLink: function() {
      var that = this;

      $('a.faqLink').each(function(){
        $(this).click(function() {
          var index = $(this).data('faq');
          if (!index) index = 1;

          var id = '#faq' + index;

          $('div.faq:not(' + id + ')').hide();

          $('#footer').css({
            'position':   'relative',
            'max-height': 'none'
          });

          $('.main').css({
            'padding-bottom': '1.4em'
          });

          $(id).show();

          that.initializeJumpBox(id + ' .secondCol ol.jump');
        });
      });

      $('a.closeFAQ').each(function(){
        $(this).click(function() {
          $('div.faq').hide();

          $('#footer').removeAttr('style');
          $('.main').removeAttr('style');
        });
      });
    },

    initializeVideoPopups: function() {
      $('.videoPopup').fancybox({
        'scrolling': 'no',
        'padding':   10,
        'type':      'ajax',
        'afterShow': function() {
          customEffectLoader.initializeScenePlayer();
        }
      });
    },

    initializeScenePlayer: function() {
      $f(
        'scenePlayer',
        fSrc,
        {
          key:     fConf.key,
          plugins: fConf.plugins,
          play:    fConf.play,
          clip: {
            autoBuffering: fConf.clip.autoBuffering,
            bufferLength:  fConf.clip.bufferLength,
            url:           $('scenePlayer').attr('href')
          }
        }
      ).ipad();
    },

    initializeNewsButton: function() {
      $('#newsButton').hover(
          function() {
              $('#newsButton .slideout').stop().animate({width: '54px'}, 150);
          },
          function() {
            $('#newsButton .slideout').stop().animate({width: '0'}, 150);
          }
      );
    }
};

var fSrc = '/r/f/flowplayer/flowplayer.commercial-3.2.16.swf';

var fConf = {
  key: '#$7106dbc8a792a155907',
  clip: {
    autoBuffering: true,
    bufferLength: '3'
  },
  plugins: {
    controls: {
      volume: false,
      mute:   false
    },
  },
  logo: {
    url:            '/r/i/themes/standard/logo_transparent_small.png',
    fullscreenOnly: false,
    displayTime:    0
  },
  play: {
    url:    '/r/i/themes/standard/play.png',
    width:  96,
    height: 96
  }
};

$(function() {
  customEffectLoader.initialize();
});
$ = jQuery;
$.fn.extend({
  defaultValue: function(callback) {

    var nativePlaceholderSupport = function() {
      var i = document.createElement('input');
      return 'placeholder' in i;
    }();

    // Default Value will halt here if the browser
    // has native support for the placeholder attribute
    if (nativePlaceholderSupport) return false;

    return this.each(function(index, element) {

      // Executing Default Value twice on an element will lead to trouble
      if ($(this).data('defaultValued')) return false;

      var $input        = $(this),
          defaultValue  = $input.attr('placeholder');

      var callbackArguments = {'input':$input};

      // Mark as defaultvalued
      $input.data('defaultValued', true);

      // Create clone and switch
      var $clone = createClone();

      // Add clone to callback arguments
      callbackArguments.clone = $clone;

      $clone.insertAfter($input);

      var setState = function() {
        if ($input.val().length <= 0) {
          $clone.show();
          $input.hide();
        } else {
          $clone.hide();
          $input.show().trigger('click');
        }
      };

      // Events for password fields
      $input.bind('blur', setState);

      // Create a input element clone
      function createClone() {

        var $el;

        if ($input.context.nodeName.toLowerCase() == 'input') {
          $el = $("<input/>").attr({
            'type': 'text'
          });
        } else if ($input.context.nodeName.toLowerCase() == 'textarea') {
          $el = $("<textarea/>");
        } else
          throw 'DefaultValue only works with input and textareas';

        $el.attr({
          'value'   : defaultValue,
          'class'   : $input.attr('class')+' empty',
          'size'    : $input.attr('size'),
          'style'   : $input.attr('style'),
          'tabindex': $input.attr('tabindex'),
          'rows'    : $input.attr('rows'),
          'cols'    : $input.attr('cols'),
          'name'    : 'defaultvalue-clone-' + ((1+Math.random())*0x10000|0).toString(16).substring(1)
        });

        $el.focus(function() {

          // Hide text clone and show real password field
          $el.hide();
          $input.show();

          // Webkit and Moz need some extra time
          // BTW $input.show(0,function(){$input.focus();}); doesn't work.
          setTimeout(function () {
            $input.focus();
          }, 1);
        });

        return $el;
      }

      setState();

      if (callback)callback(callbackArguments);
    });
  }
});

$(function() {
  $('form.smartForm [placeholder]').defaultValue();
});
$ = jQuery;

$.fn.extend({
  smartForm: function() {
    var smartForm = $(this);

    smartForm.submit(function(e) {
      e.preventDefault();

      var aSmartFormData = smartForm.serializeArray();

      AjaxUtil.startRequestByUrl(
          getCurrentUrl(),
          aSmartFormData,
          function(aResults) {
            if (aResults && aResults['htmlId'])
              $('html').attr('id', aResults['htmlId']);

            if (aResults && aResults['aErrors']) {
              var aErrors = aResults['aErrors'];

              $('span.errorBubble').remove();
              smartForm.find('p.warning').each(function() {
                $(this).removeClass('warning');
              });

              for (var id in aErrors) {
                var input = $('#' + id);

                if (input.length) {
                  $(input).parent('p').addClass('warning');
                  var bubble = '<span class="errorBubble">' + aErrors[id] + '</span>';

                  if ($(input).next('span.help').length)
                    $(input).next('span.help').before(bubble);
                  else if ($(input).next('label').length)
                    $(input).next('label').after(bubble);
                  else
                    $(input).after(bubble);
                }
              }
            } else if (aResults && aResults['aContents']) {
              for (var element in aResults['aContents']) {
                $('#' + element).html(aResults['aContents'][element]);
                $('#' + element + ' form.smartForm').smartForm();
              }
              $('form.smartForm [placeholder]').defaultValue();
            } else {
              if (aResults && aResults['action']) {
                $('#action').val(aResults['action']);
              }

              smartForm.unbind('submit').submit();
            }
          },
          'post',
          true,
          true
      );
    });
  }
});

$(function() {
  $('form.smartForm').smartForm();
});