﻿'use strict';
var $j = jQuery.noConflict(),
    $ = $j;

// Extensions
$j.fn.setFocus = function () {
  var $this = $j(this),
        $inputToFocus;

  if ($this.is(':input')) {
    $inputToFocus = $this;
  } else {
    $inputToFocus = $this.find(':input:visible:enabled:first');
  }

  if (!$inputToFocus.is(':radio') && !$inputToFocus.is(':checkbox') && !$inputToFocus.is('select')) {
    $inputToFocus.select();
  } else {
    $inputToFocus.focus();
  }
}

// End of Extensions
var site = (function ($) {

  var groupVirtualName = 'dhcc';

  function _log(message) {
    if (typeof console !== 'undefined' && console.log) {
      console.log(message);
    }
  }

  function _invoke(params, confirmation, callback) {
    if (typeof confirmation === 'function') {
      callback = confirmation;
    }
    if (typeof confirmation === 'string') {
      if (!confirm(confirmation)) {
        return false;
      }
    }
    $j.post(params.InvokeUrl ? params.InvokeUrl : window.location.pathname, params, function (data, textStatus) {
      if (typeof callback === 'function') {
        callback(data, textStatus);
      }
    });
    return true;
  }

  return {
    invoke: _invoke,
    log: _log,
    configuration: {
      maximumPictureSize: 4 * 1024 * 1024,
      picturePaths: {
        fullUserProfile: 'http:\/\/dpg-storage.s3.amazonaws.com\/' + groupVirtualName + '\/images\/fullprofilepage\/'
      }
    },
    currentUser: {
      token: ''
    }
  };
})();

$j(function () {
  var currentClass = 'current';

  $j('.expandable-section .title').live('click', function () {
    var $title = $j(this),
            $section = $title.closest('.expandable-section'),
            $sectionBody = $section.find('.body'),
            $expandableGroup = $section.closest('.expandable-group');

    if ($sectionBody.is(':hidden')) {
      $expandableGroup.find('.expandable-section').removeClass(currentClass).find('.body').slideUp();
      $sectionBody.slideDown();
      $section.addClass(currentClass);
    }
  });

  $j('.expandable-section .body').slideUp();
});


//function Invoke(params, confirmation, callback) {
//  params.InvokeUrl = '\/cms\/controler.aspx';
//  site.invoke(params, confirmation, callback);
//}
$j(function () {
  $j('input[type="text"],input[type="password"]').each(SetupDefaultText);
});

/* Setting up default text */
/* better use placeholder instead of this */
/* ex.: <input type="text" placeholder="Search" /> */

function SetupDefaultText() {
  var q = jQuery(this);
  var txt = q.attr('title');
  if (!txt) {
    return;
  }
  var onFocus = function () {
    if (q.val() == txt) {
      q.val('').removeClass('inactive');
    }
  };
  var onBlur = function () {
    if (q.val() == '' || q.val() == txt) {
      q.val(txt).addClass('inactive');
    }
  };
  q.focus(onFocus).blur(onBlur);
  onBlur();
}

site.randomString = function (stringLength) {
  var randomString = '';

  for (var i = 0; i < stringLength; i++) {
    randomString += Math.floor(Math.random() * 10); ;
  }

  return randomString;
}

/* Notification */

function getHostFullName() {
  return window.location.protocol + '//' + window.location.host + '/';
}

function pngFixUpdateIfAny() {
  if (typeof (IEPNGFix) != 'undefined') IEPNGFix.update();
}

var Notification = {
  initialize: function () { /* Notification initialization */
    var zindex = 1000;
    var body = $j('body');

    var screenlock = $j('<div id="screenlock" style="display:none; z-index:' + zindex + ';"></div>');
    screenlock.css('opacity', '0.3');
    screenlock.click(function () {
      Notification.UnlockScreen();
    });
    body.append(screenlock);

    var alertBox = ['<div id="alert-box" style="display:none; z-index:' + (++zindex) + ';">', '<div id="alert-head">', '<a id="alert-close" title="Close" onclick="Notification.UnlockScreen();"></a>', '<div id="alert-title"></div>', '</div>', '<div id="alert-content"></div>', '<div id="alert-footer"></div>', '</div>'];
    body.append($j(alertBox.join('')));

    /* do not add classes to "popup", because they are dinamically cleared by display* functions */
    var popup = ['<div id="popup" style="display:none;z-index:' + (++zindex) + ';">', '<a id="popup-close" class="pngfix" title="Close" onclick="Notification.UnlockScreen();"></a>', '<div id="popup-title"></div>', '<div id="popup-content"></div>', '</div>'];
    body.append(popup.join('')); /***/

  },

  showBrochureFlv: function (mediaId, duration, title, productId) {
    Notification.showFlv(mediaId, duration, title, productId);
  },

  showUserMediaFlv: function (mediaId, duration, title) {
    Notification.showFlvVideo(mediaId, duration, title);
  },

  showFlv: function (mediaId, duration, title, productId) {
    var html = [];
    var trackerStr = ''

    var so = new SWFObject('/local/flash/player.swf', 'mpl', '480', '270', '9');
    so.addParam('allowscriptaccess', 'always');
    so.addParam('allowfullscreen', 'true');
    so.addParam('wmode', 'transparent');


    var productIdStr = '';
    if (typeof (productId) != 'undefined') {
      productIdStr = '%3FproductId%3D' + productId;
      so.addParam('flashvars', 'streamer=' + mediaId + '/' + productIdStr + '&amp;file=x.flv&amp;type=http&amp;backcolor=FFFFFF&amp;frontcolor=5E95C6&amp;lightcolor=2583bf&amp;screencolor=FFFFFF&amp;controlbar=over&amp;autostart=true');
    } else {
      so.addParam('flashvars', 'streamer=' + mediaId + '&amp;file=x.flv&amp;type=http&amp;backcolor=FFFFFF&amp;frontcolor=5E95C6&amp;lightcolor=2583bf&amp;screencolor=FFFFFF&amp;controlbar=over&amp;autostart=true');

    }
    //TODO: add duration!!

    trackerStr = title;
    html.push('<div id="VideoPlayerContainer"></div>');
    Notification.displayVideo(title, html.join(''));
    //if (pageTracker != null) pageTracker._trackEvent('Video', 'Play', trackerStr);
    so.write('VideoPlayerContainer');
  },

  showFlvVideo: function (fileUrl, duration, title) {
    var html = [];
    var trackerStr = ''
    var so = new SWFObject('/local/flash/player.swf', 'mpl', '480', '270', '9');
    so.addParam('allowscriptaccess', 'always');
    so.addParam('allowfullscreen', 'true');
    so.addParam('wmode', 'transparent');
    // so.addParam('flashvars', 'streamer=' + stream + '&amp;file=webinar.flv&amp;type=http&amp;backcolor=FFFFFF&amp;frontcolor=5E95C6&amp;lightcolor=2583bf&amp;screencolor=FFFFFF&amp;controlbar=over&amp;autostart=true');
    so.addParam('flashvars', '&amp;duration=' + duration + '&amp;file=' + fileUrl + '&amp;type=http&amp;backcolor=FFFFFF&amp;frontcolor=5E95C6&amp;lightcolor=2583bf&amp;screencolor=FFFFFF&amp;controlbar=over&amp;autostart=true');

    trackerStr = title;
    html.push('<div id="VideoPlayerContainer"></div>');
    Notification.displayVideo(title, html.join(''));
    //if (pageTracker != null) pageTracker._trackEvent('Video', 'Play', trackerStr);
    so.write('VideoPlayerContainer');
  },

  showVideo: function (fileUrl, duration, title) {
    var html = [];
    var trackerStr = ''

    var so = new SWFObject('/local/flash/player.swf', 'mpl', '480', '270', '9');
    so.addParam('allowscriptaccess', 'always');
    so.addParam('allowfullscreen', 'true');
    so.addParam('wmode', 'transparent');
    //fileUrl ex.: http://devbridge.s3.amazonaws.com/video/aircycle/AtoZ_Recycling.flv
    so.addParam('flashvars', '&duration=' + duration + '&file=' + fileUrl + '&backcolor=FFFFFF&frontcolor=5E95C6&lightcolor=2583bf&screencolor=FFFFFF&controlbar=over&autostart=true');
    trackerStr = title;
    html.push('<div id="VideoPlayerContainer"></div>');
    Notification.displayVideo(title, html.join(''));
    //if (pageTracker != null) pageTracker._trackEvent('Video', 'Play', trackerStr);
    so.write('VideoPlayerContainer');
  },

  displayVideo: function (title, content) {
    $j('#popup').removeAttr('class');
    $j('#popup').addClass('popup-video');
    Notification.Popup(title, content);
  },

  displayInformationPopup: function (title, content) {
    $j('#popup').removeAttr('class');
    $j('#popup').addClass('popup-information');
    Notification.Popup(title, '<div class="pictured ico-24x24 ico-error-24x24 no-padding-top">' + content + '</div>');
  },

  displayDefaultPopup: function (title, content) {
    $j('#popup').removeAttr('class');
    $j('#popup').addClass('popup-default');
    Notification.Popup(title, content);
  },

  OnUnlockScreen: function () { },

  Alert: function (title, content) {
    Notification.LockScreen();
    Notification.OnUnlockScreen = function () {
      $j('#alert-box').hide();
    };
    $j('#alert-title').html(title ? title : '');
    $j('#alert-content').html(content ? content : '');
    $j('#alert-box,#screenlock').show();
  },

  Popup: function (title, content) {
    Notification.LockScreen();
    Notification.OnUnlockScreen = function () {
      $j('#popup').hide();
    };
    $j('#popup').css({
      top: ($j(window).scrollTop() + 100) + 'px'
    });
    $j('#popup-title').html(title ? title : '');
    $j('#popup-content').html(content ? content : '');
    $j('#popup,#screenlock').show();
  },

  LockScreen: function () {
    $j('#screenlock').show();
  },

  UnlockScreen: function () {
    $j('#screenlock').hide();
    $j('#popup-content').html('');
    $j('#alert-content').html('');
    Notification.OnUnlockScreen();
    Notification.OnUnlockScreen = function () { };
  }
}

/* Link Spinning */

function AjaxRequestByLink(link, params, customMessage) {

  var l = $j(link);

  if (l.hasClass('in-progress')) return;
  var linkClass = 'link' + site.randomString(8);
  l.addClass(linkClass);

  LinkStartSpinning(linkClass, link, customMessage);

  params.InvokeUrl = params.InvokeUrl ? params.InvokeUrl : window.location.pathname;

  site.invoke(params, function () { LinkStopSpinning(linkClass); });
}


function LinkStartSpinning(linkClass, control, customMessage) {
  var DEFAULT_MARGIN_LEFT = 5;
  var DEFAULT_MARGIN_TOP = 4;

  if (customMessage) {
    if (customMessage == 'no-text') customMessage = '';
  } else {
    customMessage = 'In Progress...';
  }

  var attrStyles = $j(control).attr('styles');
  $j(control).after('<div class="progress-spinner ' + linkClass + '-progress-spinner" styles="' + attrStyles + '"><img src="/local/css/images/ico-loading-16x16.gif" style="vertical-align: middle;"/> ' + customMessage + '</div>');
  var marginLeft = $j("." + linkClass + "-progress-spinner").css('margin-left');
  var marginTop = $j("." + linkClass + "-progress-spinner").css('margin-top');

  if (marginLeft == DEFAULT_MARGIN_LEFT + 'px' && marginTop == DEFAULT_MARGIN_TOP + 'px') {
    var sumbitBtnMarginLeft = $j(control).css('margin-left');
    var sumbitBtnMarginTop = $j(control).css('margin-top');

    sumbitBtnMarginLeft = sumbitBtnMarginLeft.substring(0, sumbitBtnMarginLeft.indexOf('px'))
    sumbitBtnMarginTop = sumbitBtnMarginTop.substring(0, sumbitBtnMarginTop.indexOf('px'))

    if (sumbitBtnMarginLeft == '') { sumbitBtnMarginLeft = '0'; }
    if (sumbitBtnMarginTop == '') { sumbitBtnMarginTop = '0'; }

    $j("." + linkClass + "-progress-spinner").css('margin-left', (parseInt(DEFAULT_MARGIN_LEFT) + parseInt(sumbitBtnMarginLeft)) + 'px');
    $j("." + linkClass + "-progress-spinner").css('margin-top', (parseInt(DEFAULT_MARGIN_TOP) + parseInt(sumbitBtnMarginTop)) + 'px');
  }

  $j(control).hide().addClass('in-progress');
}

function LinkStopSpinning(linkClass) {
  $j('.' + linkClass).removeClass('in-progress');
  $j('.' + linkClass).show()
  $j('.' + linkClass + '-progress-spinner').remove();
  $j('.' + linkClass).removeClass(linkClass);
}

/***/

function ApplyFlowPlayer() {
    var items = $j('a.flv-player');
    if (items.length > 0) Notification.initialize();

    items.click(function (event) {
        var element = $j(event.target);
        if (element.parent().hasClass('flv-player')) element = element.parent();
        var title = '<h1>' + element.attr('title') + '</h1>';
        var content = '<a href="' + element.attr('href') + '" ' +
									' id="playing-video">' +
									'</a>';
        Notification.displayDefaultPopup(title, content);
        flowplayer('playing-video', '/local/flash/flowplayer-3.2.7.swf');
        event.preventDefault();
    });
}
