

var $j = jQuery.noConflict();


// php's equivalent
function urlencode(str)
{
  return encodeURIComponent((str + '').toString()).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}
function urldecode(str) 
{
  return decodeURIComponent((str + '').replace(/\+/g, '%20'));
}

function explode (delimiter, string, limit) 
{
    var emptyArray = { 0 : ''};
 
    // third argument is not required
    if ( arguments.length < 2 || typeof arguments[0] == 'undefined' || typeof arguments[1] == 'undefined' ) 
    {
        return null;
    }
 
    if ( delimiter === '' || delimiter === false || delimiter === null ) 
    {
        return false;
    }
 
    if ( typeof delimiter == 'function' || typeof delimiter == 'object' || typeof string == 'function' || typeof string == 'object' ) 
    {
        return emptyArray;
    }
 
    if ( delimiter === true ) 
    {
        delimiter = '1';
    }
 
    if ( !limit ) 
    {
        return string.toString().split(delimiter.toString());
    } 
    else 
    {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}

//On Hover Over
function megaHoverOver()
{
  $j(this).find(".sub").stop().fadeTo('fast', 1).show(); //Find sub and fade it in
  (function($j) 
  {
    //Function to calculate total width of all ul's
    jQuery.fn.calcSubWidth = function() 
    {
      var rowWidth = 0;
      //Calculate row
      $j(this).find("ul").each(function() 
      { //for each ul...
        rowWidth += $j(this).width(); //Add each ul's width together
        rowWidth += parseInt($j(this).css("padding-left"), 10) + parseInt($j(this).css("padding-right"), 10); //Total Padding Width
        rowWidth += parseInt($j(this).css("margin-left"), 10) + parseInt($j(this).css("margin-right"), 10); //Total Margin Width
      });
      return rowWidth + 10;
    };
  })(jQuery);
  
  if ( $j(this).closest('ul.supreme').length == 0 )
  {
    if ( $j(this).find(".row").length > 0 ) 
    { 
      //If row exists...
      
      var biggestRow = 0;

      $j(this).find(".row").each(function() 
      {	
        //for each row...
        var rowWidth = $j(this).calcSubWidth(); //Call function to calculate width of all ul's
        //Find biggest row
        if(rowWidth > biggestRow) 
        {
          biggestRow = rowWidth;
        }
      });
      $j(this).find(".sub").css({'width' :biggestRow}); //Set width
      $j(this).find(".row:last").css({'margin':'0'});  //Kill last row's margin
    } 
    else 
    { 
      //If row does not exist...

      var rowWidth = $j(this).calcSubWidth();  //Call function to calculate width of all ul's
      $j(this).find(".sub").css({'width' : rowWidth}); //Set Width
      var offsets = $j(this).find(".sub").offset();
      if ( offsets != null )
      {
        var calcover = offsets.left + $j(this).find(".sub").width();
        if ( calcover != null && calcover > $j(window).width() )
        {
          $j(this).find(".sub").css({'left' : -(calcover-$j(window).width()+50)}); //Set Width
        }
      }
    } // end else
  }
  else
  {
    // load the images and put them into place
    $j(this).find('div.subContent div[class*="category_"]:first input[type="hidden"]').each(function(i)
    {
      if ( !$j(this).closest('div.info').find('img').data('loaded') )
      {
        $j(this).closest('div.info').find('img').attr('src', this.value).load(function()
        {
          $j(this).css({ width : 'auto', height : 'auto', backgroundImage : 'none' }).data('loaded', true);
        })
      }
    });
    
    $j(this).find('div.subContentInfo').hide().eq(0).show();
    
    var offset = $j(this).find('.sub').offset() || {};
    var calcover = (offset.left || 0) + $j(this).find('.sub').width();
    if ( calcover > $j(window).width() )
    {
      $j(this).find('.sub').css({'left' : -(calcover - $j(window).width() + 50)}); // set width
    }
  }

  if($j(this).hasClass("megafirst"))
  {
    $j(this).addClass('megaActive');
  }
}
//On Hover Out
function megaHoverOut(){
  if($j(this).hasClass("megafirst"))
  {
    $j(this).removeClass("megaActive");
  }

  $j(this).find(".sub").stop().fadeTo('fast', 0, function() 
  { 
    //Fade to 0 opacity
    $j(this).hide();  //after fading, hide it
  });
}

Function.prototype.debounce = function (threshold, execAsap)
{
  var func = this, // reference to original function
      timeout; // handle to setTimeout async task (detection period)
      //
  // return the new debounced function which executes the original function only once
  // until the detection period expires
  return function debounced ()
  {
      var obj = this, // reference to original context object
          args = arguments; // arguments at execution time
      // this is the detection function. it will be executed if/when the threshold expires
      function delayed ()
      {
        // if we're executing at the end of the detection period
        if (!execAsap)
        {
          func.apply(obj, args); // execute now
        }
        // clear timeout handle
        timeout = null;
      }
      // stop any current detection period
      if (timeout)
      {
        clearTimeout(timeout);
      }
      // otherwise, if we're not already waiting and we're executing at the beginning of the waiting period
      else if (execAsap)
      {
        func.apply(obj, args); // execute now
      }

      // reset the waiting period
      timeout = setTimeout(delayed, threshold || 100);
  };
}

String.prototype.escapeHtml = function()
{
  return this.replace(/"/g, '\"').replace(/</g, '\<').replace(/>/g, '\>').replace(/&/g,'\&');
}


function limitChars(textid, limit, infodiv)
 {
  var text = $j('#'+textid).val();
  var textlength = text.length;
  if(textlength > limit)
  {
  $j('#' + infodiv).html('You cannot write more then '+limit+' characters!');
  $j('#'+textid).val(text.substr(0,limit));
  return false;
  }
  else
  {
  $j('#' + infodiv).html('You have '+ (limit - textlength) +' characters left.');
  return true;
  }
 }

//  check for valid numeric strings
function isNumeric(strString)
{
  var strValidChars = '0123456789',
      strChar,
      i = 0,
      blnResult = true;

  if (strString.length == 0)
  {
    return false;
  }

  //  test strString consists of valid characters listed above
  for ( ; i < strString.length && blnResult == true; i++)
  {
    strChar = strString.charAt(i);

    if (strValidChars.indexOf(strChar) == -1)
    {
      blnResult = false;
    }
  }

  return blnResult;
}

/*
 * Natural Sort algorithm for Javascript
 *  Version 0.2
 * Author: Jim Palmer (based on chunking idea from Dave Koelle)
 * Released under MIT license.
 */
function naturalSort (a, b)
{
  // setup temp-scope variables for comparison evauluation
  var x = a.toString().toLowerCase() || '', y = b.toString().toLowerCase() || '',
          nC = String.fromCharCode(0),
          xN = x.replace(/([-]{0,1}[0-9.]{1,})/g, nC + '$1' + nC).split(nC),
          yN = y.replace(/([-]{0,1}[0-9.]{1,})/g, nC + '$1' + nC).split(nC),
          xD = (new Date(x)).getTime(), yD = (new Date(y)).getTime();
  // natural sorting of dates
  if ( xD && yD && xD < yD )
  {
    return -1;
  }
  else if ( xD && yD && xD > yD )
  {
    return 1;
  }
  // natural sorting through split numeric strings and default strings
  for ( var cLoc=0, numS = Math.max( xN.length, yN.length ); cLoc < numS; cLoc++ )
  {
    if ( ( parseFloat( xN[cLoc] ) || xN[cLoc] ) < ( parseFloat( yN[cLoc] ) || yN[cLoc] ) )
    {
      return -1;
    }
    else if ( ( parseFloat( xN[cLoc] ) || xN[cLoc] ) > ( parseFloat( yN[cLoc] ) || yN[cLoc] ) )
    {
      return 1;
    }
  }
  return 0;
}

function popupwin(thehref, win, xwidth, yheight, attrib )
{
  // figure out the center position
  var scrW = screen.availWidth;
  var scrH = screen.availHeight;
  if (xwidth > scrW)
  {
    pW = scrW - 10;
  }
  else
  {
  pW = xwidth;
  }
  if (yheight > scrH)
  {
    pH = scrH - 40;
  }
  else
  {
    pH = yheight;
  }
  scrX = (scrW - pW - 10) * .5;
  scrY = (scrH - pH - 30) * .5;

  var windowatts = "width=" + xwidth + ",height=" + yheight + ",left=" + scrX + ",top=" + scrY + ",screenX=" + scrX + ",screenY=" + scrY;
  windowatts += "," + attrib;
  window.open( thehref, win, windowatts);

  return false;
}

function setupPopup()
{
	$j('a.popup').unbind('click').bind('click', function(event)
	{
		//var url_address = this.href; // wrong place!
		popupwin(this.href, '', 900, 700, 'statusbar=1,status=1,toolbar=1,scrollbars=1,resizable=1,location=1,address=1,directories=1,menubar=1');
		event.preventDefault();
	});

  // Pretty Photo
  $j("a[rel^='wmiBox']").prettyPhoto(
  {
     theme: 'facebook'
  });
}

function unHideComments(id1,id2,id3,id4,focusid)
{
  $j("#"+id1).show();
  $j("#"+id2).show();
  $j("#"+id3).hide();
  $j("#"+id4).hide();
  $j("#"+focusid).focus();
}

$j(function()
{
  // popup
  setupPopup();

  // popup
  $j('a.cleanPopup').each(function()
  {
    //var url_address = this.href; // wrong place
    $j(this).click(function(event)
    {
      popupwin(this.href, '', 500, 400, 'statusbar=0,status=0,toolbar=0,scrollbars=1,resizable=1,location=0,address=0,directories=0,menubar=0');
      event.preventDefault();
    });
  });

  // bookmark
  $j('a.bookmark').each(function()
  {
    $j(this).click(function(event)
    {
      // bookmark the page
      if(window.all) {
         window.external.AddFavorite(this.href, this.title);
      }
      else if(window.external)
      {
         window.sidebar.addPanel(this.title,this.href,'');
      }
      else
      {
         alert('Your browser does not support automatic Bookmarks. You will have to do it manually.');
      }

      // prevent the action
      event.preventDefault();
    });
  });

});

/* Makes all the special javascript work */

$j(function()
{
  // jQuery Cycle Hero
  $j("div#hero-image").cycle(
  {
    speed:  800,
    pause: 1,
    pager: '#hero-nav'
  });
  // jQuery Cycle Side Image
  $j("div#rotate-image").cycle(
  {
    speed:  800,
    pause: 1
  });
  // jQuery Cycle Special Static Pager
  $j("div#imageSet").cycle(
  {
    timeout:  0,
    pager: '#imageSet-nav',
    pagerAnchorBuilder: function(idx, slide)
    {
      return '<li><a href="#">' + $j(slide).attr("rel") + '</a></li>';
    }
  });
  // jQuery Cycle Image Alt Pager
  $j("div#hero-image-alt").cycle(
  {
    speed: 800,
    pause: 1,
    pager: '#hero-nav',
    pagerEvent: 'mouseover',
    allowPagerClickBubble: true,
    pagerAnchorBuilder: function(idx, slide)
    {
      return '<a href="'+ $j(slide).find("a").attr("href") +'">' + $j(slide).find("img").attr("alt") + '</a>';
    }
  });
  // jQuery Cycle No-Text Pager
  $j("div#hero-image-notext").cycle(
  {
    speed: 800,
    pause:  1,
    pager: '#hero-nav',
    pagerAnchorBuilder: function(idx, slide)
    {
      return '<a href="#">&nbsp;</a>';
    }
  });
  // jQuery Cycle Non-Text Pager with arrows
  $j("div#hero-image-nontext").cycle(
  {
    speed: 800,
    pause:  1,
    pager: '#hero-nav',
    pagerAnchorBuilder: function(idx, slide)
    {
      return '<a href="#">&nbsp;</a>';
    },
    next:   '#hero-next',
    prev:   '#hero-prev',
    fit : true,
    height : $j('#hero-image-nontext').height(),
    slider: '.hero-slider',
    slider_down: false
  });

  // Star Ratings
  $j(':radio.star').rating();

  // Phone Field Mask
  $j(".phonemask").mask("(999) 999-9999");


  // jQuery superfish
  $j("ul.sf-menu").superfish({
   pathClass: 'current',
   delay: 800,
   speed: 50
  });
  
  //Set custom configurations
  var config = 
  {
    sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
    interval: 100, // number = milliseconds for onMouseOver polling interval
    over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
    timeout: 500, // number = milliseconds delay before onMouseOut
    out: megaHoverOut // function = onMouseOut callback (REQUIRED)
  };
  
  $j("ul.megamenu li div.sub").css({'opacity':'0'}); //Fade sub nav to 0 opacity on default
  $j("ul.megamenu li").hoverIntent(config); //Trigger Hover intent with custom configuration
  
  var cancelDebounce = false;
  
  $j('ul.megamenu.supreme div.subContent').delegate('div.subContentInfo', 'mouseover', function()
  {
    cancelDebounce = true;
  })
  .delegate('div.subContentInfo', 'mouseout', function()
  {
    cancelDebounce = false;
  });
  
  $j('ul.megamenu.supreme div.subList').delegate('a', 'mouseover', function()
  {
    var className = this.className;
    
    // load the images and put them into place
    $j('ul.megamenu.supreme div.subContent div[class*="category_' + className + '"] input[type="hidden"]').each(function(i)
    {
      if ( !$j(this).closest('div.info').find('img').data('loaded') )
      {
        $j(this).closest('div.info').find('img').attr('src', this.value).load(function()
        {
          $j(this).css({ width : 'auto', height : 'auto', backgroundImage : 'none' }).data('loaded', true);
        })
      }
    });
    
    // show the div
    (function()
    {
      if ( !cancelDebounce )
      {
        $j('ul.megamenu.supreme div.subContent div[class*="category_"]').hide().filter('[class*="category_' + className + '"]').show();
        cancelDebounce = false;
      }
    }).debounce(500)();
  }.debounce(250));
  
});
