/* ---------------------------------------------------
Title: effectcontroller.js
Copyright: (c) 2010
Author: Joe Simper - joes@rhinointernet.com
Company: Rhino Internet
Description: Visual effects of DOOOOOM!
--------------------------------------------------- */

jQuery.fn.random = function() {
   var index = Math.floor(Math.random() * this.length);
   return jQuery(this[index]);
};


$(document).ready(function() {
   prepareinputs();
   if ($('#hero').length){
      slider();
   }; //if hero
   
   browserversions();
   clientlogin.initialize();
   collapsables.initialize();
   selectquote();
   makeEnterSubmitForms();
   amiloggedin();
   
   // there is a conflict with DOTNETNUKE
   // JS that blocks external.js from firing properly
   $('a[rel=external]').attr('target', '_blank');
});


function makeEnterSubmitForms() {
   // This fixes DNN (H20?) forms not submitting on hitting Return in a field.
   // At this time this may only work for H20 forms, not sure.
   $('div[id$=_pnlControls]').each(function(){
      var saveID = $(this).attr('id').replace('pnlControls', 'btnSave');
      $(this).find('input').keypress(function(event){
         if (event.which == 13) {
            event.preventDefault();
            var hrefJS= $('#' + saveID).attr('href')
               .replace('javascript:', '');
            eval(hrefJS);
         }
      }); // keypress
   });
} // fixEnterSubmitForms()


function prepareinputs()
{
   $('#login input[type=text]').each(function() {
      $(this).data('defaultValue', $(this).val());
   });

   $('#login input[type=text]').focus(function() {
      $(this).css({ 'color': '#000' });
      if ($(this).data('defaultValue') == $(this).val()) {
         $(this).val('');
      }
   }).blur(function() {
      if ($(this).val() == '') {
         $(this).css({ 'color': '#9d9894' });
         $(this).val($(this).data('defaultValue'));
      }
   });

   $('#login #password').focus(function() {
      $(this).css({ 'color': '#000' });
   });

   passwordMask();
   $('#login #passwordHidden').blur(function() {
      if ($(this).val() == '') {
         passwordMask();
      }
   });
}


function passwordMask()
{
   $('#password').hide();
   var oldID = $('#password').attr('id');
   $('#password').attr('id', 'passwordHidden');

   var newInput = document.createElement('input');
   newInput.setAttribute('id', oldID);
   newInput.setAttribute('type', 'text');
   newInput.value = 'Password';
   $('#passwordHidden').after(newInput);

   $(newInput).focus(function() {
      $('#passwordHidden').attr('id', 'password').show();
      $('#password').focus();
      $(this).remove();
   });
}


function selectquote()
{
   $('.quotecontainer > li').hide();
   $('.quotecontainer > li').random().show();
}




/*==( Homepage Animated Slider )======================================================*/

function slider() {
   $('#hero').append('<div class="panelnav"></div>');
   $('.panelnav').append('<a href="#" class="goleft">Previous</a><a href="#" class="goright">Next</a>');
   $('.panelcontainer').children('li:first-child').addClass('active');

   looper = setInterval (function(){
      $('.goright').click();
   }, 7500); //bigpromotionloop

   $('.goright').click(function(){

      if ($('.panelcontainer').children('li:last-child').is('.active')) {
         $('.panelcontainer').children('.active').removeClass('active').parent('.panelcontainer').children('li:first-child').addClass('active');
      } else {
         $('.panelcontainer').children('.active').removeClass('active').next('li').addClass('active');
      }; //if
      clearInterval(looper);
      looper = setInterval(function() {
         $('a.goright').click();
      }, 10000);

      $('.panelcontainer').animate({'left': -$('.panelcontainer').children('li.active').position().left}, {duration: 2000, easing: 'expoinout'});

      return false;
   }); //click
}; //slider



function browserversions() {
   jQuery.each(jQuery.browser, function(i, val) {
   if(i=="mozilla" && jQuery.browser.version.substr(0,5)=="1.9.0") {
      $('body').addClass('ff3');
   };
   if(i=="opera") {
      $('body').addClass('opera');
   };
   });
}; //browserversions


/*==( Collapsables )=========================================================*/

var collapsables = {
   items:   null,
   headers: null,

   initialize: function() {
      var _this    = this;
      this.items   = $('.collapsable');
      this.headers = this.items.children('.header');
      
      // setup
      this.items.children(':not(.header)').hide();
      this.headers.css('cursor', 'pointer');

      // add hover effect
      this.headers.hover(
         function() { // mouseover
            $(this).css('color', '#A38661');
         },
         function() { // mouseout
            $(this).css('color', '#4A3B14');
         }
      );
      
      // toggle contents on header click
      this.headers.click(function(){
         var contents = $(this).parent().children(':not(.header)');
         var visible  = contents.filter(':visible');
         if (visible.length > 0) {
            // we need to hide things
            contents.slideUp();
         } else {
            // we need to show things
            // hide content from any other sections
            visible = _this.items.children(':not(.header):visible');
            if (visible.length > 0) {
               visible.slideUp(500);
               var delay = 600;
            } else {
               var delay = 0;
            }
         
            // show this section's content
            setTimeout(function(){
               contents.slideDown();
            }, delay);
         } // if
      }); // headers.click

      // check URL hash for initial content to display
      if (window.location.hash.length > 1) {
         setTimeout(function(){
            _this.items.filter(window.location.hash).children().slideDown();
         }, 300); // delay animation for a nicer feel
      }
   } // initialize()
}; // collapsable{}



/*==( Client Login Form )====================================================*/

var clientlogin = {
   wrap: '#login',
   usernameField:  null,
   passwordField:  null,
   submittingform: null,
   popupName:      'extUCPM',
   blockNextSubmitClick: false,
   
   initialize: function() {
      _this = this;
      
      this.wrap = $(this.wrap);
      this.usernameField = $('#username');
      this.passwordField = $('#passwordHidden');
      this.createSubmitForm();
      
      this.wrap.find('.submitbutton, input[type=text], input[type=password]')
         .keypress(function(event){
            if (event.which == 13) {
               _this.processForm(event);
            }
      });
      
      /* Problem: We need to capture the click event of the submit button for this form but that event is fired when hitting 'Enter' in fields in other forms since DotNetNuke has a single form over everything.
      
         Solution: We trigger the form processing event on mousedown. That works except the click event will still be fired on the submit button if the user releases their mouse button over the submit button causing the form's action to fire. So we block the next click event on the submit button if the mouseup event is called since mousedown + mouseup = click.
      */
      this.wrap.find('.submitbutton')
         .mousedown(function(event){
            _this.processForm(event);
         })
         .mouseup(function() {
            _this.blockNextSubmitClick = true;
         })
         .click(function(event) {
            if (_this.blockNextSubmitClick) {
               event.preventDefault();
               _this.blockNextSubmitClick = false;
            }
         } // click
      );
   }, // initialize()
   
   processForm: function(event) {
      event.preventDefault();
      
      var values = _this.check();
      if (values != false) {
         this.launchPopup();
         this.submitForm(values.username, values.password);
      }
   }, // processForm()
   
   createSubmitForm: function() {
      this.submittingform = $('<form>')
         .attr({ name:   'ClientLoginSubmitForm',
                 action: 'https://ext.ucpm.com/v1/login.asp?pid=&style=UCPM&b=&d=',
                 method: 'post',
                 target: this.popupName
         })
         .append('<input type="hidden" name="txtLoginHash" />'
               + '<input type="hidden" name="txtUserName" />'
               + '<input type="hidden" name="txtPassword" />'
               + '<input type="hidden" name="txtBrowserID" />'
               + '<input type="hidden" name="txtRefer" />'
               + '<input type="hidden" name="txtIP" />'
         )
         .hide();
      
      $('body').append(this.submittingform);
   }, // createSubmitForm()
   
   check: function() {
      var username = this.usernameField.val();
      var password = this.passwordField.val();
      
      // check for default values
      if (username == this.usernameField.data('defaultValue')) {
         username = '';
      }
      if (password == 'Password') {
         password = '';
      }
      
      username = jQuery.trim(username);
      if (username.length <= 0) {
         alert("Please enter your username.");
         return false;
      } // else
      
      password = jQuery.trim(password);
      if (password.length <= 0) {
         alert("Please enter your password.");
         return false;
      } // else
      
      return {username: username, password: password}
   }, // check()
   
   launchPopup: function() {
      window.open('https://ext.ucpm.com/v1/login.asp?style=UCPM&b=&d=', this.popupName,
         'width=800, height=600, location=no, menubar=no, status=no, titlebar=no, scrollbars=yes'
      );
   }, // launchPopup()
   
   submitForm: function(username, password) {	  
	  var _this = this;
	  
      var fields = {
         txtLoginHash: this.makeLoginHash(username, password),
         txtUserName:  username,
         txtPassword:  password,
         txtBrowserID: Math.floor(Math.random() * 10000000),
         txtIP:        ''
      };
      
      for (name in fields) {
         this.submittingform.find('input[name=' + name + ']').val(fields[name]);
      }
      
      setTimeout(function() { _this.submittingform.submit(); }, 100);
   }, // submitForm()
   
   makeLoginHash: function(username, password) {
      return this.hasher.splitEncode(this.hasher.encodeStr(username, password));
   }, // makeLoginHash()   
   
   hasher: {
      encodeStr: function(sU, sP) {
          var arrUser = new Array(32)
          var arrPass = new Array(32)
          var arrOut = new Array(32)
      
          var sUser = sU.toLowerCase()
          var sPass = sP.toLowerCase()
      
          var j = 31, k, t
          for (var i = 0; i < 32; i += 2) {
              t = (i < sUser.length)
                  ? (sUser.charCodeAt(i) + 5)
                  : (arrUser[i - 2] + 13);
             
              arrUser[i] = parseInt(t * 5 / 6);
      
              t = ((i + 1) < sUser.length)
                  ? (sUser.charCodeAt(i + 1) + 35)
                  : (arrUser[i] + 91);
      
              arrUser[i + 1] = parseInt(t * 5 / 3);
      
              t = (i < sPass.length)
                  ? (sPass.charCodeAt(i) + 5)
                  : (arrPass[i - 2] + 65);
      
              arrPass[i] = parseInt(t * 5 / 8);
      
              t = ((i + 1) < sPass.length)
                  ? (sPass.charCodeAt(i + 1) + 35)
                  : (arrPass[j + 2] + 132);
      
              arrPass[j] = parseInt(t * 2 / 3);
      
              j -= 2;
          }
      
          var s
          for (var i = 0; i < 32; i++) {
              j = (arrUser[i] + arrPass[31 - i]);
      
              while (j > 255) { j -= 256 };
              s = " 00" + j.toString(16);
              arrOut[i] = s.substring(s.length - 2, s.length);        
          }
          return arrOut.join("").toLowerCase();
      }, // encodeStr()
      
      splitString: function(s) {
          arrTemp = new Array(32)
          var j = 0
          for (var i = 0; i < s.length; i += 2) {
              arrTemp[j] = String.fromCharCode(parseInt(s.substring(i, i + 2), 16));
              j++;
          }
          var s1 = "", s2 = ""
          for (var i = 0; i < arrTemp.length; i += 2) {
              s1 += arrTemp[i]
              s2 += arrTemp[i + 1]
          }
          arrTemp[0] = s1
          arrTemp[1] = s2
          return arrTemp;
      }, // splitString()
      
      splitEncode: function(s) {
          var sRet, arrTemp
          sRet = "" + s
      
          for (var x = 0; x < 5; x++) {
              arrTemp = this.splitString(sRet)
              sRet = this.encodeStr(arrTemp[0], arrTemp[1])
          }
          return sRet
      } // splitEncode()
   } // hasher
}; // var clientlogin{}



/*==( Check to see if user is logged in )====================================================*/


function amiloggedin() {
   if ($('.ControlPanel').length) {
      $('body').addClass('loggedin');
   }; //totally logged in.
}; //amiloggedin









