// custom js code for Riebeek Cellars 
//    (C) www.pa-ket.com -- 2011/oct
//    -- last update: 2011/oct/20
/////////////////////////////////////////////
jQuery(document).ready(function($) {

  // add open in new window to all pdf links
  $('a.pdfr, a.pdf').attr('target', '_blank');
  $('.literature-container > span.icon img[src$="pdf.png"]').each(function() { 
    $(this).parent().parent().find('.name > a').attr('target', '_blank'); }
  );  


  // disable newsscroller on home to speed things up
  $('body.home header').addClass('disabled').find('.scroll li:gt(0)').remove();
  
  // top right scrolling banner -- turned off while dev to save cpu
  if($('header:not(.disabled) #newsscroller').length == 1 ) {
    $('header #newsscroller .scroll').scrollable(
      { easing:'linear', keyboard:false, circular:true, speed:7000 }
    ).autoscroll({interval:0 });  
  }


  // webapp brand landing page
  if($('ul#winebrand').length == 1) {
    $('ul#winebrand').jcarousel({ wrap: 'circular', scroll: 3, easing: 'swing', animation: 500, auto: 0});
  }
  // webapp brand landing -- if max 6 wines, then remove prev/next btn...
  if($('ul#winebrand li').length < 7) {
    $('.jcarousel-next-horizontal, .jcarousel-prev-horizontal').addClass('disabled');
  }
  // ... and center items
  var len = $('ul#winebrand li:not(.jcarousel-item-placeholder)').length;
  if(len < 6) {
    $('.jcarousel-clip-horizontal').css('margin-left', Math.floor(18 + (6-len)*105/2) + 'px');
  } 
  // then for fun lets scroll on hover -- yeeeah
  if(len > 6) {
    var api = $('ul#winebrand').data('jcarousel');  
    $('.jcarousel-container').mouseover(function(e) {
      var x = e.pageX;
      var w = $(window).width();
      if(w > 1026)
        x = Math.floor(e.pageX - (w-1025)/2); // page width center aligned
      if(x < 230) { // moved left 
        api.prev();
      } else if(x > 470) { // move right
        api.next();
      }
    });
  }

  
  // webapp main landing page
  if($('ul#winemainland').length == 1) {
    $('ul#winemainland').roundabout( { clickToFocus: true, minOpacity: 0.5, minScale: 0.6, maxScale: 1, 
      duration: 700, tilt: -2.5, /*btnNext: '#winemain-right', btnPrev: '#winemain-left'*/ } );
  }  
  
  // webapp wine webapp pages sidebar menu pick selections based on URL
  // webapp main cat. prefix is 'wines-'
  if($('#wineslist').length == 1) {
    var url = document.location.pathname;
    // look for whole url match then select its parent as well if it has one
    // use css to show / hide selection
    $('#wineslist ul li > a[href="'+url+'"]').parent().addClass('selected')
      .parent().parent('li').addClass('selected');
  }
  


  // check newsletter form and submit using ajax / check errors
  $('#newsletter form').submit(function() {
    $('#newsletter #errordesc').hide();        
    var oks = true;          
    $('#newsletter :input[type=text]').each(function() {
      $this = $(this);
      if($this.val() == '' /* || $this.val() == $this.attr('title') */ ) {
        oks = false;
      }
    });
    if(!oks) {
      $('#newsletter #errordesc').fadeIn().delay(1000).fadeOut();    
    } else { // send it
      var f = $('#newsletter form');
      $.post(f.attr('action'), f.serialize(), function(data) {
        $('#newsletter #submitokdesc').fadeIn().delay(1500).fadeOut();
        $('#newsletter :input[type=text]').val('');
      }, 'html');
    }
    return false; // always submit via ajax
  });




  EmailUnobfuscate(); // replace dot and (at) with proper values, compose href
	// $("img.reflect").reflect({/* Put custom options here */});
	
});






//http://www.sitepoint.com/stop-spam-harvesting-email-obfuscation/
function EmailUnobfuscate() {  
    // find all links in HTML  
    var link = document.getElementsByTagName && document.getElementsByTagName("a");  
    var email, e;  
    // examine all links  
    for (e = 0; link && e < link.length; e++) {  
        // does the link have use a class named "email"  
        if ((" "+link[e].className+" ").indexOf(" email ") >= 0) {  
            // get the obfuscated email address  
            email = link[e].firstChild.nodeValue.toLowerCase() || "";  
            // transform into real email address  
            email = email.replace(/dot/ig, ".");  
            email = email.replace(/\(at\)/ig, "@");  
            email = email.replace(/\s/g, "");  
            // is email valid?  
            if (/^[^@]+@[a-z0-9]+([_\.\-]{0,1}[a-z0-9]+)*([\.]{1}[a-z0-9]+)+$/.test(email)) {  
                // change into a real mailto link  
                link[e].href = "mailto:" + email;  
                link[e].firstChild.nodeValue = email;  
            }  
        }  
    }  
}  





/*!
	reflection.js for jQuery v1.1
	(c) 2006-2011 Christophe Beyls <http://www.digitalia.be>
	MIT-style license.
*/
(function(a){a.fn.extend({reflect:function(b){b=a.extend({height:1/3,opacity:0.5},b);return this.unreflect().each(function(){var c=this;if(/^img$/i.test(c.tagName)){function d(){var g=c.width,f=c.height,l,i,m,h,k;i=Math.floor((b.height>1)?Math.min(f,b.height):f*b.height);l=a("<canvas />")[0];if(l.getContext){h=l.getContext("2d");try{a(l).attr({width:g,height:i});h.save();h.translate(0,f-1);h.scale(1,-1);h.drawImage(c,0,0,g,f);h.restore();h.globalCompositeOperation="destination-out";k=h.createLinearGradient(0,0,0,i);k.addColorStop(0,"rgba(255, 255, 255, "+(1-b.opacity)+")");k.addColorStop(1,"rgba(255, 255, 255, 1.0)");h.fillStyle=k;h.rect(0,0,g,i);h.fill()}catch(j){return}}else{if(!a.browser.msie){return}l=a("<img />").attr("src",c.src).css({width:g,height:f,marginBottom:i-f,filter:"FlipV progid:DXImageTransform.Microsoft.Alpha(Opacity="+(b.opacity*100)+", FinishOpacity=0, Style=1, StartX=0, StartY=0, FinishX=0, FinishY="+(i/f*100)+")"})[0]}a(l).css({display:"block",border:0});m=a(/^a$/i.test(c.parentNode.tagName)?"<span />":"<div />").insertAfter(c).append([c,l])[0];m.className=c.className;a.data(c,"reflected",m.style.cssText=c.style.cssText);a(m).css({width:g,height:f+i,overflow:"hidden"});c.style.cssText="display: block; border: 0px";c.className="reflected"}if(c.complete){d()}else{a(c).load(d)}}})},unreflect:function(){return this.unbind("load").each(function(){var c=this,b=a.data(this,"reflected"),d;if(b!==undefined){d=c.parentNode;c.className=d.className;c.style.cssText=b;a.removeData(c,"reflected");d.parentNode.replaceChild(c,d)}})}})})(jQuery);


/*
 * jQuery throttle / debounce - v1.1 - 3/7/2010
 * http://benalman.com/projects/jquery-throttle-debounce-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function(b,c){var $=b.jQuery||b.Cowboy||(b.Cowboy={}),a;$.throttle=a=function(e,f,j,i){var h,d=0;if(typeof f!=="boolean"){i=j;j=f;f=c}function g(){var o=this,m=+new Date()-d,n=arguments;function l(){d=+new Date();j.apply(o,n)}function k(){h=c}if(i&&!h){l()}h&&clearTimeout(h);if(i===c&&m>e){l()}else{if(f!==true){h=setTimeout(i?k:l,i===c?e-m:e)}}}if($.guid){g.guid=j.guid=j.guid||$.guid++}return g};$.debounce=function(d,e,f){return f===c?a(d,e,false):a(d,f,e!==false)}})(this);


/* Modernizr 2.0.6 (Custom Build) | MIT & BSD
 * Build: http://www.modernizr.com/download/#-backgroundsize-borderimage-borderradius-boxshadow-multiplebgs-textshadow-generatedcontent-canvas-iepp-cssclasses-teststyles-testprop-testallprops-domprefixes
 */
;window.Modernizr=function(a,b,c){function C(a,b){var c=a.charAt(0).toUpperCase()+a.substr(1),d=(a+" "+o.join(c+" ")+c).split(" ");return B(d,b)}function B(a,b){for(var d in a)if(k[a[d]]!==c)return b=="pfx"?a[d]:!0;return!1}function A(a,b){return!!~(""+a).indexOf(b)}function z(a,b){return typeof a===b}function y(a,b){return x(prefixes.join(a+";")+(b||""))}function x(a){k.cssText=a}var d="2.0.6",e={},f=!0,g=b.documentElement,h=b.head||b.getElementsByTagName("head")[0],i="modernizr",j=b.createElement(i),k=j.style,l,m=":)",n=Object.prototype.toString,o="Webkit Moz O ms Khtml".split(" "),p={},q={},r={},s=[],t=function(a,c,d,e){var f,h,j,k=b.createElement("div");if(parseInt(d,10))while(d--)j=b.createElement("div"),j.id=e?e[d]:i+(d+1),k.appendChild(j);f=["&shy;","<style>",a,"</style>"].join(""),k.id=i,k.innerHTML+=f,g.appendChild(k),h=c(k,a),k.parentNode.removeChild(k);return!!h},u,v={}.hasOwnProperty,w;!z(v,c)&&!z(v.call,c)?w=function(a,b){return v.call(a,b)}:w=function(a,b){return b in a&&z(a.constructor.prototype[b],c)};var D=function(a,c){var d=a.join(""),f=c.length;t(d,function(a,c){var d=b.styleSheets[b.styleSheets.length-1],g=d.cssRules&&d.cssRules[0]?d.cssRules[0].cssText:d.cssText||"",h=a.childNodes,i={};while(f--)i[h[f].id]=h[f];e.generatedcontent=i.generatedcontent.offsetHeight>=1},f,c)}([,['#generatedcontent:after{content:"',m,'";visibility:hidden}'].join("")],[,"generatedcontent"]);p.canvas=function(){var a=b.createElement("canvas");return!!a.getContext&&!!a.getContext("2d")},p.multiplebgs=function(){x("background:url(https://),url(https://),red url(https://)");return/(url\s*\(.*?){3}/.test(k.background)},p.backgroundsize=function(){return C("backgroundSize")},p.borderimage=function(){return C("borderImage")},p.borderradius=function(){return C("borderRadius")},p.boxshadow=function(){return C("boxShadow")},p.textshadow=function(){return b.createElement("div").style.textShadow===""},p.generatedcontent=function(){return e.generatedcontent};for(var E in p)w(p,E)&&(u=E.toLowerCase(),e[u]=p[E](),s.push((e[u]?"":"no-")+u));x(""),j=l=null,a.attachEvent&&function(){var a=b.createElement("div");a.innerHTML="<elem></elem>";return a.childNodes.length!==1}()&&function(a,b){function s(a){var b=-1;while(++b<g)a.createElement(f[b])}a.iepp=a.iepp||{};var d=a.iepp,e=d.html5elements||"abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",f=e.split("|"),g=f.length,h=new RegExp("(^|\\s)("+e+")","gi"),i=new RegExp("<(/*)("+e+")","gi"),j=/^\s*[\{\}]\s*$/,k=new RegExp("(^|[^\\n]*?\\s)("+e+")([^\\n]*)({[\\n\\w\\W]*?})","gi"),l=b.createDocumentFragment(),m=b.documentElement,n=m.firstChild,o=b.createElement("body"),p=b.createElement("style"),q=/print|all/,r;d.getCSS=function(a,b){if(a+""===c)return"";var e=-1,f=a.length,g,h=[];while(++e<f){g=a[e];if(g.disabled)continue;b=g.media||b,q.test(b)&&h.push(d.getCSS(g.imports,b),g.cssText),b="all"}return h.join("")},d.parseCSS=function(a){var b=[],c;while((c=k.exec(a))!=null)b.push(((j.exec(c[1])?"\n":c[1])+c[2]+c[3]).replace(h,"$1.iepp_$2")+c[4]);return b.join("\n")},d.writeHTML=function(){var a=-1;r=r||b.body;while(++a<g){var c=b.getElementsByTagName(f[a]),d=c.length,e=-1;while(++e<d)c[e].className.indexOf("iepp_")<0&&(c[e].className+=" iepp_"+f[a])}l.appendChild(r),m.appendChild(o),o.className=r.className,o.id=r.id,o.innerHTML=r.innerHTML.replace(i,"<$1font")},d._beforePrint=function(){p.styleSheet.cssText=d.parseCSS(d.getCSS(b.styleSheets,"all")),d.writeHTML()},d.restoreHTML=function(){o.innerHTML="",m.removeChild(o),m.appendChild(r)},d._afterPrint=function(){d.restoreHTML(),p.styleSheet.cssText=""},s(b),s(l);d.disablePP||(n.insertBefore(p,n.firstChild),p.media="print",p.className="iepp-printshim",a.attachEvent("onbeforeprint",d._beforePrint),a.attachEvent("onafterprint",d._afterPrint))}(a,b),e._version=d,e._domPrefixes=o,e.testProp=function(a){return B([a])},e.testAllProps=C,e.testStyles=t,g.className=g.className.replace(/\bno-js\b/,"")+(f?" js "+s.join(" "):"");return e}(this,this.document);
