// Common JavaScript code across your application goes here.


// Breadcrumb behavior
var breadcrumb = new Array();
breadcrumb.active = false;
breadcrumb.timer = false;

breadcrumb.off = function() {
  if(breadcrumb.timer) {
    window.clearTimeout(breadcrumb.timer);
    breadcrumb.timer = false;
  }
  if(breadcrumb.active) {
    breadcrumb.active.css('display', 'none');
    breadcrumb.active = false;
  }
}

breadcrumb.over = function( whichlist ) {
  if (whichlist == breadcrumb.active) {
  } else {
    breadcrumb.off();
  }
  whichlist.css('display', 'block');
  breadcrumb.active = whichlist;
}
breadcrumb.out = function() {
  breadcrumb.timer = window.setTimeout(breadcrumb.off, 300);
}

$(document).ready(function() {
  $('#breadcrumb a.crumb').mouseover(function(){
    breadcrumb.over( $(this).siblings('div.quick-list').children('ul.altcrumbs') );
  });
  $('#breadcrumb .quick-list ul.altcrumbs').mouseover(function(){
    breadcrumb.over( $(this) );
  });
  $('#breadcrumb .quick-list ul.altcrumbs').mouseout(function(){
    breadcrumb.out();
  });
});


// Form JS Ready-State Checker
formReadyCheck = function ( whichForm ) {
  var tehReturn = true;

  $( '#'+whichForm.id+' input.required').each( function(i) {
    if( $(this).val() == '' ){
      alert( $(this).attr('title') );
      $(this).focus();
      tehReturn = false;
      if (!tehReturn) return false;
    }
  });

  if (!tehReturn) return false;
  
  $( '#'+whichForm.id+' input.validate').each( function(i) {
    if( $(this).val() != '' ){
      //alert('validating ' + $(this).attr('name'));
      if($(this).hasClass('email')) {
        var exp = /^.*@.*\..*$/i;
        if( !exp.test( $(this).val() ) ){         
          alert ( $(this).attr('title') );
          $(this).focus();
          tehReturn = false;
          if (!tehReturn) return false;
        }
      } else if($(this).hasClass('phone')) {
        var tehValue = $(this).val();
        tehValue = tehValue.replace(/[^0-9]+/g, '');
        if(( tehValue.length < 10 ) || ( tehValue.length > 11 )){
          alert ( $(this).attr('title') );
          $(this).focus();
          tehReturn = false;
          if (!tehReturn) return false;
        }
      } else if($(this).hasClass('number')) {
        var tehValue = $(this).val();
        if( isNaN( tehValue ) ){
          alert ( $(this).attr('title') );
          $(this).focus();
          tehReturn = false;
          if (!tehReturn) return false;
        }
      } else if( $(this).hasClass('url') ) {
        /*
        // TODO: Make this accept "http://" at the beginning
        var exp = /^[A-Za-z0-9\-_]+\.[~A-Za-z0-9-_%&\\\?\/.=]+$/i;
        if( !exp.test( $(this).val() ) ){         
          alert ( $(this).attr('title') );
          $(this).focus();
          tehReturn = false;
          if (!tehReturn) return false;
        }
        */
      }
    }
  });
  return tehReturn;
}

$(document).ready(function() {
  $('.oddeven').children().each( function(oddevenenum){
    if (isOddNum(oddevenenum)) $(this).addClass('odd');
  });
});

var isOddNum = function (value) {
  var binvalue = value.toString(2);
  return (binvalue.charAt(binvalue.length-1) != "1");
}


var getFriendlyDate = function() {
  var today = new Date();
  var day_names = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
  var month_names = ["January","February","March","April","May","June","July","August","September","October","November","December"];
  return day_names[today.getDay()]+', '+month_names[today.getMonth()]+' '+today.getDate()+', '+(today.getFullYear());
}

var isIe6 = ((navigator.userAgent.indexOf("MSIE 6") != -1) && (navigator.userAgent.indexOf("Opera") == -1));



jQuery.fn.defuscate = function( settings ) {
  settings = jQuery.extend({
    link: true,
    find: /\b([A-Z0-9._%-]+)\([^)]+\)((?:[A-Z0-9-]+\.)+[A-Z]{2,6})\b/gi,
    replace: '$1@$2'
  }, settings);
  return this.each(function() {
    if ( $(this).is('a[@href]') ) {
      $(this).attr('href', $(this).attr('href').replace(settings.find, settings.replace));
      var is_link = true;
    }
    $(this).html($(this).html().replace(settings.find, (settings.link && !is_link ? '<a href="mailto:' + settings.replace + '">' + settings.replace + '</a>' : settings.replace)));
  });
};



// GP Ad Builder and JSON parser
placeGPAd = function(objectid, category_id, ad_type, region_id){
  var gpad_feed = window.path_prefix + '/feeds/gpad.js?category_id='+category_id+'&ad_type='+ad_type+'&region_id='+region_id+'&jsoncallback=?';

  $.getJSON(gpad_feed, function(json){
    if (json.url && json.image) {
      var gpad_link = document.createElement("a");
      gpad_link.target = '_new'
      gpad_link.href = json.url
      
      var gpad_image = document.createElement("img");
      gpad_image.src = json.image;
      
      $( gpad_link ).append( gpad_image );
      $('#'+objectid).append( gpad_link );
    }
  });
}

// VC Ad Builder and XML parser
placeAdFeed = function(adobject_array, xurl) {
  // TODO: unH4X this
  xurl = window.path_prefix + xurl;
  if ((window.path_prefix=='') && (window.location.href.indexOf('batonrouge.gopickle.com')>=0)) xurl = '/directory'+xurl;
  
  var adFeed = [];
  adFeed.listing = [];
  $.ajax({
    url: xurl,
    type: 'GET',
    dataType: 'xml',
    timeout: 12000,
    error: function(){
      return false;
    },
    success: function(xml){
      // do something with xml
      // put the XML into a usable array of strings
      $(xml).find('LISTING').each(function( i ){
        adFeed.listing[ i ] = [];
        $(this).find('RANK').each(function(){ adFeed.listing[ i ].rank = $(this).text(); });
        $(this).find('TITLE').each(function(){ adFeed.listing[ i ].title = $(this).text(); });
        $(this).find('DESCRIPTION').each(function(){ adFeed.listing[ i ].description = $(this).text(); });
        $(this).find('SITEHOST').each(function(){ adFeed.listing[ i ].sitehost = $(this).text(); });
        $(this).find('LINK').each(function(){ adFeed.listing[ i ].link = $(this).text(); });
      });
      
      adobject_array.each(function( i ){
        if (i == 0){
          ads_sponsornote = document.createElement('p');
          ads_sponsornote.className = 'listheader';
          $( ads_sponsornote ).html('Sponsored listings:');
          $(this).append( ads_sponsornote );
        }
        
        newad = document.createElement('a');
        newad.target = '_blank';
        newad.href = unescape(adFeed.listing[i].link);
        $(newad).click(function(){
          // if it's running in a development environment, don't allow the click-through.
          try { console.log('.ad click, Title: ' + $(this).children('.name').text()); }catch(err){}
          try {
            if (window.merb_env == 'development') {
              alert("Ad clicks and Analytics tracking disabled in development environment.\n\nSee JS console for log.");
              return false;
            }
          } catch (err) {}
          try {
            if (pageTracker._trackEvent('ValidClick', 'click', $(this).children('.name').text()))
              console.log('.ad click pageTracker._trackEvent( callback=>true )');
          } catch (err) { }
        });
        $(newad).mouseover(function(e){
          try { console.log('.ad mouseover, Title: ' + $(this).children('.name').text()); } catch (err) { }
        });
        
        newad_name = document.createElement('span');
        newad_name.className = 'name';
        $( newad_name ).html( adFeed.listing[i].title );
        $( newad ).append( newad_name );
        
        newad_description = document.createElement('span');
        newad_description.className = 'description';
        $( newad_description ).html( adFeed.listing[i].description );
        $( newad ).append( newad_description );
        
        newad_sponsornote = document.createElement('span');
        newad_sponsornote.className = 'sponsornote';
        $( newad_sponsornote ).html( 'sponsor link' );
        $( newad ).append( newad_sponsornote );

        newad_url = document.createElement('span');
        newad_url.className = 'url';
        $( newad_url ).html( adFeed.listing[i].sitehost );
        $( newad ).append( newad_url );

        $(this).append( newad );
        try {console.log('.ad appended, Title: ' + adFeed.listing[i].title);} catch (err) {}
      });
    },
    complete: function( response ){
      $.getScript('http://feed.validclick.com/check.php?affid='+window.vc_affid);
    }
  });
}