$(document).ready(function(){

  /*
  ** Populates Text Field
  */
  if($('.structure').length > 0) {
    $('.structure').each(function(){
      var field_val = $(this).text();
      $(this).next().val(field_val);

      $(this).next().focus(function(){
        $(this).val('');
      }).blur(function(){
        $(this).val(field_val);
      });

    });
  }

  /*
  ** Hover Table Rows
  */
  if($('.table-grouping').length > 0) {
    $('.table-grouping tr').each(function(){
      $(this).mouseover(function(){
        $(this).addClass('active-hover');
      }).mouseout(function(){
        $(this).removeClass('active-hover');
      });
    });
  }

  /*
  ** Initialize Scroller
  */

  if($('#caousel').length > 0) {
    $('#carousel').jcarousel({
      vertical:false,
      scroll: 3
    });
  }

  if($('.overlay-toggle').length > 0) {

    //Create overlay divs
    $('body').append('<div class="inactive overlay"></div>');
    $('body').append('<div class="inactive overlay-wrap"></div>');
    $('ul.overlay-menu').append('<span class="overlay-option">[X]</span>');
    $('.overlay').css({opacity:.7});

    $('li.overlay-toggle').click(function(){

      //Make overlay divs visible
      $('.overlay').removeClass('inactive');
      $('.overlay-wrap').removeClass('inactive');

      //Show and append selected area
      var dd_display = $(this).find('ul').css('display') == 'none' ? 'block' : 'none';
      $(this).find('ul.overlay-menu').css({display:dd_display});
      $('.overlay-wrap').append($(this).find('ul.overlay-menu'));
      $(this).addClass('active-toggle');

      var current_url = window.location.toString();
      var url = current_url.split('#');
      var message = '<div class="messages reload rounded">*<strong>HEY YOU!!</strong> In order to view these changes, <a href="' + url[0] + '">reload the page</a></div>';
      $('.overlay-wrap ul li:first').append(message);

      //Hide div when clicked off
      $('html').click(function(){

        $('ul.overlay-menu').css({display:'none'});
        $('div.overlay').addClass('inactive');
        $('div.overlay-wrap').addClass('inactive');

        $('li.active-toggle').append($('div.overlay-wrap > *'));
        $('li.active-toggle').removeClass('active-toggle');

        //Remove cloned elements admin area
        $('.simple-admin .group-wrap').remove();
        $('.product-type .product-type').remove();
        $('.overlay-wrap').fadeOut('slow');
     });

      return false;

    });

    //For reordering option
    $('a.nodehierarchy_action').click(function(){
      $('.reload').css({display:'block'});
      $(this).parent().parent().parent().addClass('selected');
    });

  }

  /* Pop Up*/
  popUp('a.pop', 500, 570);
  popUp('a.lg-pop', 700, 700);

  /* Form Validation */
  (function(){
  //Attaching the onSubmit event to the login form
    var errors = "";
    var loginForm = document.getElementById('movieform');
    if (!loginForm){ return false; }
    loginForm.onsubmit = function () {
      return canSubmit(this);
    }


    function canSubmit(form) {
      var errors = "";
      //Hide error messeges if any are present
      var errorBefore = document.getElementById('movieform');
      var parentDiv = errorBefore.parentNode;
      var errorPlist = parentDiv.getElementsByTagName("p");
      for (i = 0; i < errorPlist.length; i++){
          if (errorPlist[i].className == "showError"){
            errorPlist[i].className = "hideError";
          }
        }       

      
      //count all form elements
      var elCount = document.movieform.elements.length;
      //all text elements are filled? 
      for (i=0;i<elCount;i++) {
        var formEl = document.movieform.elements[i];
        var type = formEl.type;
        var fieldName = formEl.name;

        // all text fields are filled
        if (type=="text" && !formEl.value) {
          var errors = "empty_txt";
        }
        var illegalChars = /^[\w ]*$/;
        // allow only letters, numbers, and underscores
        if (fieldName=="name" && !formEl.value.match(illegalChars)) {
          var errors = "illegal_namechar";
        } 
        var emailFilter=/^.+@.+\..{2,3}$/;
        if (fieldName=="email" && !(emailFilter.test(formEl.value))) { 
          var errors = "valid_email";
        }
        var illegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/;
        if (fieldName=="email" && formEl.value.match(illegalChars)) {
          var errors = "illegal_email";
        }
      }

      // email and verify email addy are the same
      if (document.movieform.email.value != document.movieform.email2.value) {
        var errors = "nomatch";
      }

      //terms are checked
      if (!document.movieform.terms.checked) {
        var errors = "terms";
      } 

      if (errors){
        showError();
        return false;
      }
      else{
        return true;
      }

      function showError() {
        //error arrays
        var errorMess = [];
        errorMess['empty_txt'] = 'Please provide your Name, Email and verify Email.';
        errorMess['terms'] = 'Please Accept the Terms and Agreements of this contest.';
        errorMess['nomatch'] = 'The email addresses do not match.';
        errorMess['illegal_namechar'] = 'Something seems to be wrong with your Name.';
        errorMess['illegal_email'] = 'Your email address contains illegal characters.';
        errorMess['valid_email'] = 'Pleae enter a valid email address.';


      var errorP = document.createElement("p");
      errorP.setAttribute("class", "showError");
      errorP.className = "showError";
      var errorPcontent = document.createTextNode(errorMess[errors]);
      errorP.appendChild(errorPcontent);

      var errorBefore = document.getElementById("movieform");
      var parentDiv = errorBefore.parentNode;
      
       parentDiv.insertBefore(errorP, errorBefore);

      }
    }
  })();
});

function popUp(el,h,w) {
  if($(el).length > 0) {
    $(el).bind('click', function(e){
      window.open($(this).attr('href'), 'popup', 'status=0, toolbar=0, location=0, menubar=0, directories=0,' + 
                                                 'resizeable=1, scrollbars=1, height='+ h +', width='+ w);
      return false;
    });
  }
}

function nh_nid(nid, pid) {
  var menu  = '<div class="nodehierarchy_actions">';
  menu += '<a title="up" class="nodehierarchy_action nodehierarchy_action_up" href="/hierarchy/' + nid + '/up?destination=node%2F' + pid + '">';
  menu += '<span class="nodehierarchy_icon"><img height="16" width="16" src="/sites/all/themes/zeta/images/icons/up.gif"/></span></a>';
  menu += '<a title="down" class="nodehierarchy_action nodehierarchy_action_down" href="/hierarchy/' + nid + '/down?destination=node%2F' + pid + '">';
  menu += '<span class="nodehierarchy_icon"><img height="16" width="16" src="/sites/all/themes/zeta/images/icons/down.gif"/></span></a>';
  menu += '</div>';
  return menu;
}
