// JavaScript Document
$.fn.copyTo = function(to) {
   var to = $(to);
   for ( var i = 1; i < arguments.length; i++ )
      to.set( arguments[i], this.get(0)[ arguments[i] ] );
   return this;
};

new function() {
   $.fn.validateX = {
      init: function(o) {
         if(o.name == 'name') {
            this.email(o)
         }
         if(o.name == 'pass') {
            this.password(o)
         }
      },
      username: function(o) {
         var user = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
         if (!o.value.match(user)) {
            //doValidate(o);
            doSuccess(o,'username format valid')
         } else {
            doError(o,'no special characters allowed');
         }
      },
      password: function(o) {
         var pass = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
         if (!o.value.match(pass) && o.value.length > 5) {
            doSuccess(o, 'password format valid');
         } else {
            if( o.value.length < 6 )
               doError( o, 'must be greater 5 characters')
            else
               doError(o,'no special characters allowed');
         }
      },
      email: function(o) {
         var email  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
         if (o.value.match(email)) {
            doSuccess(o,'valid email address');
         } else {
            doError(o,'not a valid email');
         }
      }
   };

   function doSuccess(o,m) {
      $('#' + o.id + '_img').html('<img src="images/accept.gif" title="' + m + '" style="float: left;"/>');
      $('#' + o.id + '_li').removeClass("error");
      $('#' + o.id + '_msg').html("");
      $('#' + o.id + '_li').addClass("success");
   }

   function doError(o,m) {
      $('#' + o.id + '_img').html('<img src="images/exclamation.gif" style="float: left;"/>');
      $('#' + o.id + '_li').addClass("error");
      $('#' + o.id + '_msg').html(m);
      $('#' + o.id + '_li').removeClass("success");
      var element = $('#' + o.id);

      setTimeout( function() {
         element.focus();
         element.select();
      } , 10);

   }
   //private helper, validates each type after check
   function doValidate(o) {
      // $('#' + o.id + '_img').html('<img src="images/loading.gif" border="0" style="float:left;" />');
      $.post('ajax.php', {
         id: o.id,
         value: o.value
      }, function(json) {
         eval("var args = " + json);
         if (args.success == true)
         {
            doSuccess(args);
         }
         else
         {
            doError(args,args.msg);
            return false;
         }
      });
   }

};

$.fn.extend({
   insertAtCaret: function(myValue){
      if (document.selection) {
         this.focus();
         sel = document.selection.createRange();
         sel.text = myValue;
         this.focus();
      }
      else if (this.selectionStart || this.selectionStart == '0') {
         var startPos = this.selectionStart;
         var endPos = this.selectionEnd;
         var scrollTop = this.scrollTop;
         this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
         this.focus();
         this.selectionStart = startPos + myValue.length;
         this.selectionEnd = startPos + myValue.length;
         this.scrollTop = scrollTop;
      } else {
         this.value += myValue;
         this.focus();
      }
   }
});

$.extend({
   getUrlVars: function(){
      var vars = [], hash;
      var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
      for(var i = 0; i < hashes.length; i++)
      {
         hash = hashes[i].split('=');
         vars.push(hash[0]);
         vars[hash[0]] = hash[1];
      }
      return vars;
   },
   getUrlVar: function(name){
      return $.getUrlVars()[name];
   }
});

$.fn.match = function(m) {
   $('#' + this.get(0).id + '_img').html('<img src="images/loading.gif" border="0" style="float:left;" />');
   if ($(this).get(0).val() == $(m.match).val()) {
      $('#' + this.get(0).id + '_img').html('<img src="images/accept.gif" border="0" style="float:left;" />');
      $(m.error).removeClass("error");
      $(m.error).addClass("success");
      $('#' + this.get(0).id + '_msg').html("");
   } else {
      $('#' + this.get(0).id + '_img').html('<img src="images/exclamation.gif" border="0" style="float:left;" />');
      $(m.error).addClass("error");
      $(m.error).removeClass("success");
      $('#' + this.get(0).id + '_msg').html("The passwords don't match, please try again");
   }
};

// jQuery script to initiate the menu
var popupStatus = 0;

$(document).ready(function() {
   $('#globalnav ul').superfish();

   var lgnWidth = $('#loginform').width();
   var lgnPos   = $('#loginbutton').offset();

   $("input[class=validated]").blur(function() {
      $(this).validateX.init(this);
   });

   // This Used To Be HOVER, But I.E. Didnt Like It
   //$(".form li").hover(function(){$(this).addClass("selected");},function(){$(this).removeClass("selected");});
   $("#loginForm li").mouseover(function() {
      $(this).addClass("selected");
   });

   $("#loginForm li").mouseout(function() {
      $(this).removeClass("selected");
   });

   $(document).keyup(function(e) {
      if (e.keyCode == 27 && popupStatus == 1) {
         $('#logincancel').click();
      }
   });

   $('input').keydown(function(e){ // Allow IE to submit with enter key
      if (e.keyCode == 13) {
         $(this).parents('form').submit();
         return false;
      }
   });

   // Support "placeholder" attr in all browsers
   $('body').find('input[type=password][name=pass]').each( function(){
      $(this).hide();
      size = $(this).attr('size');
      id = $(this).attr('id');
      $(this).after('<input type="text" id="'+id+'-pseudo" size="'+size+'" class="pseudo-password" title="password" />');
   });

   $('body').find('input[type=text]').each( function(){
      if( $(this).val().length == 0 ){
         $(this).val( $(this).attr('title') );
         $(this).addClass('watermark');
      }
   });


   $('input[type=text]').focus(function(){
      // Handle pseudo-password field
      if( $(this).hasClass('pseudo-password') ){
         $(this).hide();
         $(this).prev('input[type=password]').show();
         $(this).prev('input[type=password]').focus();
      }else if( $(this).attr('type')!='password' ){
         if( $(this).val() == $(this).attr('title') )
         {
            $(this).val('').removeClass('watermark');
         }
      }
   });

   $('input[type=password]').blur(function(){
      if($(this).val() == '' && $(this).attr('title').length > 0)
      {
         $(this).hide();
         $(this).next('input[type=text]').show();
      }
   });

   $('input[type=text]').blur(function(){
      if($(this).val() == '' && $(this).attr('title').length > 0 )
      {
         $(this).val( $(this).attr('title') ).addClass('watermark');
      }
   });


   $("#loginform").hide();
   $("#loginform #edit-submit").hide();
   if( $('.loginerror').length ){
      $('#mainContent .error').hide();
      $("#loginform").show();
   }

   jQuery.fn.fadeToggle = function(speed, easing, callback) {
      return this.animate({
         opacity: 'toggle',
         height: 'toggle'
      }, speed, easing, callback);
   };

   function meDone() {
      /* Fixes an issue in IE where it's doesn't hide on finish of the toggle. */
      $('#loginform').hide();
      /* Remove mask from screen */
      $('#loginbutton').removeAttr( "disabled" );
      $('#mask, .window').hide();
      popupStatus = 0;
   }


   $('#logintab').click(function(e) {
      $("#loginform").fadeToggle('normal', 'swing', meDone);
   });

   $("#loginbutton").click(function(e){
      var btnWidth = $('#loginbutton').width();
      var btnHeight = $('#loginbutton').height();
      var maskHeight = $(document).height();
      var maskWidth = $(document).width();

      e.preventDefault();

      // Set the mask height and width.
      $('#mask').css({
         'width': maskWidth,
         'height': maskHeight
      });

      // Transition mask in.
      $('#mask').fadeTo("normal", 0.5);

      // Calculate the popup position.
      $('#logintab').css( {
         'left': (lgnPos.left - 8 /* for padding */ ) + "px",
         'top': (lgnPos.top - 3) + "px"
      });
      $('#loginform form').css( {
         'left': lgnPos.left - (btnWidth * 2)- lgnWidth - 15 + "px",
         'top':lgnPos.top + btnHeight + "px"
      } );

      $('#loginbutton').attr( "disabled", "disabled" );
      $("#loginform").fadeToggle('normal');
      popupStatus = 1;
      return false;
   });

   $('#user-loginform').submit( function(event) {
      // We are going to check the validatity of the user response
      var returnVal = false;
      if( $('#emailaddr_img').hasClass('error') ||
         $('#password_img').hasClass('error') ) {
         event.preventDefault();
         return returnVal;
      }
      var userName = $('#emailaddr').val();
      var password = $('#password').val();

      var JSONObject = new Object;
      JSONObject.action = 'login';
      JSONObject.username = userName;
      JSONObject.password = password;

      $.ajax( {
         type: 'POST',
         url: 'include/signin-out.php',
         data: JSONObject,
         cache: false,
         async: false,
         dataType: 'json',
         success: function ajaxSuccess( data ) {
            if( data.status != true ) {
               $('#password_img').html('<img src="images/exclamation.gif" style="float: left;"/>');
               $('#password_li').addClass("error");
               $('#password_msg').html(data.error);
               $('#password_li').removeClass("success");
            }
            else {
               event.preventDefault();
               var curdate = new Date();
               var expires = new Date();
               expires.setTime( curdate.getTime() + 3600000*24*360);
               // Must set before change window content.
               if( $('#rememberMe').is( ':checked' ) ) {
                  document.cookie = 'CNTIT_USERNAME' + '=' +
                  escape( userName ) +
                  ";expires=" + expires.toGMTString();
               }
               window.location = data.page + "?" + Math.floor(Math.random()*11);
               returnVal = true;
            }
         },
         error: function(data) {
            alert( data );
         }
      });
      if( !returnVal ) {
         event.preventDefault();
      }
      return returnVal;

   });

   $('#logincancel').click(function() {
      $("#loginform").fadeToggle('normal', 'swing', meDone);
   });

   $('#loginsubmit').click(function(event) {
      $('#user-loginform').submit();
      var submitStatus = event.isDefaultPrevented();

      if( submitStatus != false ) {
         /* Remove mask from screen */
         $("#loginform").fadeToggle('normal', 'swing', meDone);
         return false;
      }
      else {
         return false;
      }
   });
/*
   $("#dialog").dialog({
      modal: true ,
      disabled: true,
      resizable: false,
      draggable: false,
      dialogClass: 'alert',
      autoOpen: false,
      buttons: {
         "Ok": function() {
            $(this).dialog("close");
         }
      }
   });
*/
});

