/*
 * Project: Generic reusable functions for Adnet websites
 * Author: Rudy Affandi
 * Created: 03/19/2011
 * Revision: 10/13/2011
 * File name: masterfunctions.js
 */

/*
 * Suckerfish drop down navigation initialization (Will deprecate soon)
 * Usage: id: 'nav' for main level
 */

   if ( $('ul#nav').length > 0 ) // Check if DOM element exist
   {
      sfHover = function() {
         var sfEls = document.getElementById('nav').getElementsByTagName('li');
         for (var i=0; i<sfEls.length; i++) {
            sfEls[i].onmouseover=function() {
               this.className+=' sfhover';
            }
            sfEls[i].onmouseout=function() {
               this.className=this.className.replace(new RegExp(' sfhover\\b'), '');
            }
         }
      }
      if (window.attachEvent) window.attachEvent('onload', sfHover);
   }

// jQuery initialization and CSS settings, waiting for DOM tree to initialize
$(document).ready(function(){

   /*
    * jQuery-based drop down navigation
    * Dependency: jQuery
    * Usage: classname: 'dropdown' for main level
    */

   if($('ul.dropdown').length) {// Check if DOM exist
      $('ul.dropdown li').each(function() {

      /* Bind version, need to work on sensitivity handling a'la hoverIntent */
         $(this).bind({
            mouseenter: function()
            {
               $(this).addClass('hover');
               $('ul:first',this).css('visibility', 'visible');
               if (cufon_nav == 'yes')
               { Cufon.refresh(); }
            },
            mouseleave: function()
            {
               $(this).removeClass('hover');
               $('ul:first',this).css('visibility', 'hidden');
               if (cufon_nav == 'yes')
               { Cufon.refresh(); }
            }
         });
      });

      // Mark sub navs
      //$('ul.dropdown li ul li:has(ul)').find('a:first').append(' &raquo; ');
      if (allow_main_3rd_level == 'yes'){
         $('ul.dropdown li ul li:has(ul)').find('a:first').addClass('has_sub');
        }
      // Add incremental id number for each a tag
      $('.dropdown > li a').not('.dropdown li ul li a').each(function(index, element){
         $(element).attr('id', 'n'+index);
      });

   }

   // Add ID for each of the main navigation
   $('#nav > li a').not('#nav li ul li a').each(function(index, element){
      $(element).attr('id', 'n'+index);
   });

   // Main navigation 3rd level settings, please set trigger from local functions.js
   if (allow_main_3rd_level == 'yes'){
      $('#nav li ul li ul').each(function(index, element){
         $(element).attr('id', 's'+index).prev().addClass('has_sub');
      });
      $('.dropdown li ul li ul').each(function(index, element){
         $(element).attr('id', 's'+index).prev().addClass('has_sub');
      });
   } else {
      $('#nav li ul li ul').each(function(index, element){
         $(element).css('display', 'none');
      });
      $('.dropdown li ul li ul').each(function(index, element){
         $(element).css('display', 'none');
      });
   }

   // Side navigation 3rd level settings, please set trigger from local functions.js
   if (allow_side_3rd_level == 'yes'){
      $('.content_side ul li ul').each(function(index, element){
         $(element).attr('id', 's'+index).prev().addClass('has_sub');
      });
   } else {
      $('.content_side ul li ul').each(function(index, element){
         $(element).attr('id', 's'+index);
      });
   }

   // Activate "class='active'" on current URL
   var host = location.host;
   if (jQuery().url){// Check if plugin loaded
      var script_path_length = (jQuery.url.segment(0).length + 2);
   } else {// if no plugin
      var script_path_length = 3;
   }
   var path = location.pathname.substring(script_path_length);
   var jpath = $(location).attr('href');
   var param_path = location.search;
   var complete_path = (path.toLowerCase() + param_path);
   if ( complete_path )
   {
     $('a[href$="' + complete_path + '"]').each(function(){
         $(this).addClass('active');
      });
   };

   // Add ID for each of the sub navigation and marked with 'has_sub' class
   // Show side navigation with children
   $('a.has_sub.active').each(function(){
      $(this).next().show();
   });

   // Also expand tree for all parents
   $('.content_side li a.active').parents().show();

   $('.content_side ul ul li a.active').parent().parent().show();
   $('.content_side ul ul ul li a.active').parent().parent().parent().show();
   $('.content_side ul ul:visible').prev().addClass('active');
   $('.content_side ul ul ul:visible').prev().prev().addClass('active');

   // Style default RFI form (Experimental)
   // First we clean up the mess from original table formatting
   // jQuery Uniform plugin required

   if ($('div.form_wrapper').length > 0){
      $.getScript('/cc/lib/jquery/plugins/uniform/jquery.uniform.min.js', function(){
         $('div.form_wrapper table').addClass('ui-helper-reset').removeAttr('background').removeAttr('border');
         $('div.form_wrapper td').removeAttr('background');
         // and then we apply modifier to form elements
         $('div.form_wrapper table input[type=text], div.form_wrapper table td').addClass('ui-corner-all');
         $('div.form_wrapper table input[type=submit], div.form_wrapper table input[type=reset]').button();
         $('div.form_wrapper table textarea').addClass('ui-corner-all');
         $('select, input:checkbox, input:radio, input:file').uniform({resetSelector: 'input[type="reset"]'});
      });
   }

   // Corporate Directory formatting, hide empty fields
   $('.colon').append(':');
   $('.comma').append(',');
   $('div.address div:has(span.value:empty)').hide();
   $('div.address div:has([href]:empty)').hide();
   $('div.address div:has(a.url:empty)').hide();

   // Media Coverage formatting, hide empty fields
   $('div.media_format div:has(span.value:empty)').hide();
   $('div.media_format div:has(span.img:empty)').hide();
   $('div.media_format div:has([href]:empty)').hide();
   $('div.media_format div:has(a.url:empty)').hide();

   // jQuerize Buttons
   //$('button').button();

   // Initiate shadowbox
   //   Shadowbox.init();

   // Convert email href to mailto
   $('a.email').each(function(){
      var email = $(this).html().replace(/\s*\(.+\)\s*/, "@");
      $(this).before('<a href="mailto:' + email + '" rel="nofollow" title="Email ' + email + '">' + email + '</a>').remove();
   });

   // External link warning dialog
   $('a.ext_link').live('click', function(){
      var link = $(this).attr('href');
      $('<div>You are leaving ' + companyName + ' site. Do you want to proceed?</div>').dialog({
         title: "External Link",
         width: 400,
         modal : true,
         overlay: {
            backgroundColor: '#000',
            opacity: 0.5
         },
         buttons: {
            'Proceed': function() {
               $(this).dialog('close').remove();
               window.open(link);
            },
           'Cancel': function() {
              $(this).dialog('close').remove();
              return false;
            }
         }
      });
      return false;
   });

   // Image thumbnail processing
   $('ul.image_grid_format li').each(function(){
      var _this = $(this);
      $(this).find('img').load(function(){
         _this.css('width', $(this).width() + 'px');
         //_this.css('height', $(this).height() + 'px');
      });
   });

   $('.img_thumb').each(function(){
      var _this = $(this);
      $(this).find('img').load(function(){
         _this.css('width', $(this).width() + 'px');
         //_this.css('height', $(this).outerHeight() + 'px');
      });
   });

/*
   // Image thumbnail processing
   $('img').load(function(){
       var $this = $(this),
           img_width = $this.outerWidth();
           img_height = $this.outerHeight();
       $this.closest('.img_thumb').css('width', img_width + 'px');
       $this.closest('ul.image_grid_format li').css('width', img_width + 'px');
   });
*/

   // Add zoom icon
   $('.img_thumb a, ul.image_grid_format li a').append('<div class="zoom">');

   // Increase image rendering quality
   //$('img').css({'image-rendering': 'optimizeQuality', '-ms-interpolation-mode': 'bicubic'});

});

// Deprecated since ...
// External link warning dialog
function extLink(link) {
   var answer = confirm('You are leaving ' + companyName + ' Website')
   if (answer){
      window.open(link);
   }
   else {
      return false;
   }
};

// External link warning dialog - Spanish
function extLinkEsp(link) {
   var answer = confirm('Est‡s abandonando el sitio web de ' + companyName)
   if (answer){
      window.open(link);
   }
   else {
      return false;
   }
};


$(window).unload(function() {
   if (jQuery().qtip){// Check if plugin loaded
      $('area').qtip("destroy");
   }
});

// jQuery REGEX filter
jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ?
                        matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels,'')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}
