var cycleseconds = 7, cycler;

// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function(){
  var cache = {};

  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :

      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +

        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +

        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");

    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();

function carouselNext() {
  var onn = $('.carousel a.on');
  var nex = onn.next();
  if(nex.size()===0) { nex = onn.siblings('a:first-child'); }
  nex.click();
}

$(document).ready(function() {
  // if (js_vars.live_domain === true) {
  // We are now replacing phone numbers server side (AppController::afterFilter())
  //replace_phone_numbers();
  // }

//Scroll to top of page
  $('.back-to-top').click(function(e){
    $('html, body').animate({scrollTop:0}, 'slow');
    e.preventDefault();
  });

  $('.carousel').each(function() {
   $(this).append('<div class="slides" />');
   $(this).children('.slide').each(function(i) {
    $(this).siblings('.slides').append('<a href="#'+i+'"'+(i===0 ? ' class="on"' : '')+'></a>').children('a:eq('+i+')').click(function() {
      $(this).addClass('on').siblings('.on').removeClass();
      $(this).parent().parent().children('.slide:eq('+i+')').css('z-index',1).addClass('on').show()
      .siblings('.slide.on').fadeOut('slow',function() {
        $(this).removeClass('on').siblings('.on').css('z-index',2);
      });
      clearTimeout(cycler);
      cycler = setTimeout(carouselNext,cycleseconds*1000);
      //e.preventDefault();
    });
   });
   cycler = setTimeout(carouselNext,cycleseconds*1000);
  });

  if($('#testimonial-thumbs').size() > 0) {
    $('#testimonial-thumbs a:gt(4)').hide();
    $('#testimonial-thumbs').append('<a href="#prev" class="ar p off" /><a href="#next" class="ar n" />');
    $('#testimonial-thumbs a.thumb').click(function(e) {
     if($(this).hasClass('on')===false) {
      var yt = $(this).attr('href');
      yt = yt.substr(31);
      $(this).addClass('on').siblings('a.thumb.on').removeClass('on');
      $('#testimonial-video').html('<object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/'+yt+'?fs=1&amp;hl=en_US&amp;rel=0&amp;title=&amp;autoplay=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'+yt+'?fs=1&amp;hl=en_US&amp;rel=0&amp;title=&amp;autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed></object>');
     }
     e.preventDefault();
    });
    $('#testimonial-thumbs a.ar').click(function(e) {
     if($(this).hasClass('off')===false) {
       $(this).siblings('a.ar.off').removeClass('off');
       if($(this).hasClass('p')) {
         $('#testimonial-thumbs a.thumb:visible:first').prev().show().nextAll('a.thumb:visible:last').hide();
         if($('#testimonial-thumbs a.thumb:eq(0)').is(':visible')) { $(this).addClass('off'); }
       } else {
         $('#testimonial-thumbs a.thumb:visible:first').hide().nextAll('a.thumb:visible:last').next().show();
         if($('#testimonial-thumbs a.thumb:visible:last').next().hasClass('ar')) { $(this).addClass('off'); }
       }
     }
     e.preventDefault();
    });
  }

  if ($('#verisign-logo').size() > 0) {
    $('#verisign-logo').click(function(e) {
      var src = $('#verisign-logo').attr("href");
      v_window = window.open(src, "verisign_window", "location=1,status=1,scrollbars=1,width=520,height=520");
      v_window.moveTo(0, 0);
      e.preventDefault();
    });
  }

  $("#resources-link").click(function(e) {
    $("#footer-resources").toggle();
    $('html, body').animate({ 
         scrollTop: $('#footer-resources-bottom').offset().top 
     }, 200);
    e.preventDefault();
  });

  // Round some corners using jquery.corners.js
  // IE8 hack
  var ua = $.browser;
  if (ua.msie && (parseInt(ua.version, 10) === '8' || parseInt(ua.version, 10) === '7')) {
    // Get started box
    $('#get_started').corner();
    $("#get_started h3.rounded-corners-top").corner("top");
    // Primary nav
    $("#nav").css("background-color", "transparent");
    $("#nav li.rounded-corners-left").corner("bl cc:#1688ad");
    $("#nav li.rounded-corners-left").corner("tl cc:#42a6c8");
    $("#nav li.rounded-corners-right").corner("br cc:#1378a4");
    $("#nav li.rounded-corners-right").corner("tr cc:#3a97c0");
    // $("#dentists_dentist_profile #content #join div.results-header").corner("top"); // Can't do this... it removes the border
  }
  

  /*
   * Function replace newdental phone numbers
   * 
   * For now we are not using this function and replacement is done server side
   */
  function replace_phone_numbers() {
    //Replacing newdental phone number
    var agent_phone_number = js_vars.agent_phone.replace(/\(?([0-9]{3})\)?[\-. ]?([0-9]{3})[\-. ]?([0-9]{4})/g,"($1) $2-$3");
    var default_phone_number = js_vars.default_phone_numbers[0].replace(/\(?([0-9]{3})\)?[\-. ]?([0-9]{3})[\-. ]?([0-9]{4})/g,"$1$2$3");
    var default_area_code = default_phone_number.substring(0,3);
    var default_prefix = default_phone_number.substring(3,6);
    var default_postfix = default_phone_number.substring(6,10);
    
    // An alternate selector to consider. This select all elements which have no children and are not in table.results-content
    //$("body *:not(:has(*), table.results-content *)")
    
    // FIXME: Had to create a hack for the Savings Results page... otherwise IE freaks out about a script taking too long to run.
    // Either optimize what gets looked at (ie, the "each" criteria) or the matching
    // agent_phone_number = '999-111-2222';
    if ($("body").attr("id") !== "savings_results") {
      $("body *:not(:has(*))").each(function () {
        var text = $(this).text();
        var re = new RegExp('\\(?('+default_area_code+')\\)?[-. ]?('+default_prefix+')[-. ]?('+default_postfix+')', "g");
        if (text.match(re)) {
          var replacement = text.replace(text.match(re), agent_phone_number);
          $(this).text(replacement);
        }
      });
    } else {
      // FIXME: Hack for the Savings Results page
      $("#call-us > p > span, .help .module-content > p > span").each(function () {
        var text = $(this).text();
        var re = new RegExp('\\(?('+default_area_code+')\\)?[-. ]?('+default_prefix+')[-. ]?('+default_postfix+')', "g");
        if (text.match(re)) {
          var replacement = text.replace(text.match(re), agent_phone_number);
          $(this).text(replacement);
        }
      });
    }
  }
});


/**
 * Function to format number.
 */
function number_format (number, decimals, dec_point, thousands_sep) {
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}


