jQuery(document).ready(function($) {

  // if in blog and showing a category - get the category name from the list of cats from ul/li sidebar
  if(window.location.search.indexOf('BlogID=419') != -1) {
    $('#sidemenu-content .blogpostcategories ul li a').each(function() {
      var lnk = $(this).attr('href');
      var lnk = lnk.substr(lnk.indexOf('?')); 
      if(window.location.search == lnk) {
        var z = $(this).text();
        z = z.substr(0, z.lastIndexOf('(')-1); // cut (..) from end
        $('#content #blog-category').text('- '+z);
        Cufon.refresh('h1');
      }
    });
  }



  // scroll for announcements -- replaced with jquery tools scroller
  // $('#menu-top ul#announcements-list').liScroll({travelocity: 0.035});
  $('#announcements-list').scrollable(
    { easing:'linear', keyboard:false, circular:true, speed:7000 }
  ).autoscroll({interval:0 });        


  // fix shop addto cart input boxes replaced with specific option boxes
  // + see addtocart function on bottom of this file - overides original fn.
  $('#content .price .addcart input.productTextInput').each(function() {
    $this = $(this);
    $this.replaceWith(['<select name="AddToCart_Amount" id=', $this.attr('id'), '>',
    '<option value="0">QTY</option>', '<option value="1">1</option><option value="2">2</option><option value="3">3</option>',
    '<option value="4">4</option><option value="5">5</option><option value="6">6</option>',    
    '<option value="7">7</option><option value="8">8</option><option value="9">9</option>',        
    '<option value="10">10</option><option value="11">11</option><option value="12">12</option>',
    '<option value="18">18</option><option value="24">24</option><option value="30">30</option>',         
    '</select>'].join(''));
  });
  
  // refresh cart when using back button (template change also needed!)
  // http://securesyd.worldsecuresystems.com/Utilities/SupportCentral.aspx?gcs=Partner.html?page=654:bc_654:html&keyword=0_quantity
  var r = $('#refresh');
  if(r.length == 1) {
    if(r.val() == 0) r.val(1);
    else if(typeof RefreshCart == 'function') RefreshCart();
  }
  
  

  // fix home blog datums + if cut long text
  $('.box.blog li').each(function() {
    $this = $(this);
    var a = $this.find('span.date');
    var x = a.text().split('-');
    // fix if date is not in format dd-mmm-yyyy then simply print 'today' - as it was posted today
    if(x.length == 1)
      a.replaceWith('<span class="date"><div class="day" style="margin-top:8px;">today</div><div class="month"></div></span>');
    else
      a.replaceWith('<span class="date"><div class="day">'+x[0]+'</div><div class="month">'+x[1]+'</div></span>');

    var a = $this.find('a');
    if(a.text().length > 18) {
      a.text(a.text().substr(0,17) + '...');
		  Cufon.refresh('#boxes .blog li');		  		  		    		  
		}      
  });


  // hover effect for wines. filenames must be ending with _sml and _lrg for this to work
  $('#wines a').each(function() { // copy img src to a background
    $this = $(this);
    var src = $this.find('img').css('visibility', 'hidden').attr('src');
    $this.attr('data-src', src);
    $this.css('background', 'url('+src+') no-repeat center');
    // preload
    var x = new Image();
    x.src = src.replace('_sml', '_lrg');
  });
  
  $('#wines a').hover(function() {
    var src = $(this).attr('data-src');
    var newsrc = src.replace('_sml', '_lrg');
    $(this).css('background', 'url('+newsrc+') no-repeat center');
  }, function() {
    var src = $(this).attr('data-src');
    $(this).css('background', 'url('+src+') no-repeat center');          
  });        


  // use title as value when entering data to newsletter - makes form compact
  $('#newsletter :input[type=text][title]').each(function() {
    var $this = $(this);
    if($this.val() === '') {
      $this.val($this.attr('title'));
    }
    $this.focus(function() {
      if($this.val() === $this.attr('title')) {
        $this.val('');
      }
    });
    $this.blur(function() {
      if($this.val() === '') {
        $this.val($this.attr('title'));
      }
    });
  });

  // check newsletter form and submit using ajax / check errors
  $('#newsletter form').submit(function() {
    $('#newsletter #errordesc').hide();        
    var oks = true;          
    $('#newsletter :input[type=text][title]').each(function() {
      $this = $(this);
      if($this.val() == '' || $this.val() == $this.attr('title')) {
        $('#newsletter #errordesc').show();
        oks = false;
      }
    });
    if(oks) { // send it
      var f = $('#newsletter form');
      $.post(f.attr('action'), f.serialize(), function(data) {
        $('#newsletter #submitokdesc').show();
      }, 'html');
    }
    return false; // always submit via ajax
  });



  // team pages tip on images
  if($('div.team-image .rollovertext').length > 0) {
    $('div.team-image .rollovertext').hide();
    $('div.team-image img').each(function() {
      // I love closures!
      $this = $(this);
      $this.qtip({
        content: $this.parent().find('.rollovertext').html(),
        position: { corner: { target: 'rightTop'} },
        style: { width: 250, name: 'cream'}      
      });
    });
  }
// tip: 'leftTop',
 // team pages tip on images -left
  if($('div.team-imagel .rollovertextl').length > 0) {
    $('div.team-imagel .rollovertextl').hide();
    $('div.team-imagel img').each(function() {
      // I love closures!
      $this = $(this);
      $this.qtip({
        content: $this.parent().find('.rollovertextl').html(),
        position: {  corner: {target: 'topLeft', tooltip: 'topRight'} }, 
        style: { width: 250, name: 'cream'}      
      });
    });
  }

  // WINE WEBAPP LOGICS
  ////////////////////////

  // cut 2(+space) chars from app-title as well as title is used for ordering items
  // see n.substr(3) also below in .each()
  if($('#content h1.app-title').length == 1) {
    $('#content h1.app-title').text($('#content h1.app-title').text().substr(3));
    Cufon.refresh('h1');
    document.title = document.title.substr(3);
  }
  

  //hide buy now link if not available for buying
  var z = $('#content #available_for_buying');
  if(z.length == 1 && z.val()==0)
    $('#content #buynow').hide();


  // pedigree tip -- fucking IE js error if not checked!!!!
  if($('#pedigree img').length==1) {
    $('#pedigree img').qtip({
      content: $('#pedigreetxt').html(),
      position: { corner: {target: 'bottomLeft', tooltip: 'topRight'} },
      style: { tip: 'topRight', width: 450, name: 'cream'}
    });        
  }
    
  // pdf / buynow text replacement as BC cant emit only plain text links grrrr
  $('#content #factsheet a').html('PDF FACTSHEET');        
  //$('#content #buynow a').html('BUY NOW');                
  Cufon.replace('#content #factsheet, #content #buynow', {fontFamily:'TradeGothic', hover: true });
  
  // organize and build up wines categorized by name (years under each one)
  var w = [];
  //var wi = {'name':'', 'elems':{}}; // elem: {year:4444, url:''}

  //var curr = window.location.hash.replace(/\s+/g,'-').replace(/[^a-zA-Z0-9\-]/g,'');
  var nprev = '';
  $('#content #allwines li').each(function() { // get all
    var $t = $(this);
    var n = $t.find('a').text().replace(/\s+/g,' ');
    var n = n.substr(3); // cut 2 chars (+space) prefix used for ordering..
    var url = $t.find('a').attr('href');
    var nbase = n.substr(0, n.length-5);
    var nyear = n.substr(n.length-4);
    if(nprev != nbase) { // new group
      nprev = nbase;
      w.push({'name': nbase, 'elems': [{'year': nyear, 'url': url}] });
    } else {
      w[w.length-1].elems.push({'year': nyear, 'url': url}); // add it to last group always
    }
  });
  var current_url = window.location.pathname;
  //current_url = '/_webapp_203518/Calligraphy_2000';
  var html = '';
  for(var i=0; i<w.length; i++) { // sort desc by year and build html
    w[i].elems.sort(function(a,b){ return b.year - a.year; });
    // check if child element is selected - mark if yes 'selected'
    var selected_child = false;
    for(var z in w[i].elems) {
      if(w[i].elems[z].url == current_url) selected_child = true;
    }
    html = [html, '<li', (selected_child?' class="selected"':''), '><a href="javascript:void(0);">',
           w[i].name, '</a><ul>'].join('');
    for(var z in w[i].elems) {
      var el = w[i].elems[z];
      html = [html, '<li', ((el.url==current_url)?' class="selected"':''),
             '><a href="', el.url, '">', w[i].name, ' ', el.year,'</a></li>'].join('');
    }
    html = [html, '</ul></li>'].join('');
    $('#sidebar #sidemenu.wines #sidemenu-content ul').html(html);
    //console.log(html); 
  }
  // fix up showing submenus stuff (clicking)
  $('#sidebar #sidemenu.wines #sidemenu-content > ul > li > a').click(function() {
    $this = $(this);
    if($this.parent().hasClass('enabled')) {
      $this.parent().removeClass('enabled');
    } else {
      $this.parent().parent().find('li').removeClass('enabled');
      $this.parent().addClass('enabled');
    }
  });
  
  
});

function flashFix(o){document.write(o)}
////////////////////////////////////////////////////////////
// MODIFICATIONS TO the stock /CatalystScripts/Java_Onlineshopping.js scripts add to cart function
// to allow using dropdown select list boxes for quantity (otherwise it would just write them back as input=text boxes)
// fcuk..

function AddToCart(j, w, t, B, l) {
   var h = w; 
   var q = ""; 
   var f = document.getElementById("Units_" + w); 
   var A = readCookie("CartID"); 
   var v = document.getElementById("Grouping_" + w); 
   var F = document.getElementById("Related_" + w); 
   var e = document.getElementById("catProdTd_" + w); 
   var n = document.getElementById("catProdAttributes_" + w); 
   var u = document.getElementById("catProdAttributes2_" + w); 
   var s = document.getElementById("catProdInstructions_" + w); 
   var c = ""; 
   var p = new Array(); 
   var C = false; 
   var a = false; 
   var m; 
   var g = 0; 
   var E; 
   var d = true; 
   if(f) {
      m = f.value; 
      if(m < 0) {
         alert(OshopLang.RemoveError); 
         return false}
      }
   else {
      m = 1}
   if(A == null || A == "") {
      A =- 1}
   E = document.getElementById("catCartSummary"); 
   if(v) {
      if(v.nodeName == "SELECT") {
         h = v.value}
      else {
         var r = v.getElementsByTagName("input"); 
         for(var z = 0; z < r.length; z++) {
            if(r[z].checked) {
               h = r[z].value; 
               break}
            }
         }
      }
   if(F) {
      q = GetCheckListValue(F); 
      if(q.length > 0) {
         g = q.split(",").length}
      }
   if(s) {
      c = s.value}
   if(n) {
      var o = n.getElementsByTagName("select"); 
      if(o) {
         if(c.length > 0) {
            c += ";"}
         for(var z = 0; z < o.length; z++) {
            if(o[z].value.length > 0) {
               c += o[z].value + ";"}
            }
         }
      }
   if(u) {
      var D = 0; 
      var o = u.getElementsByTagName("select"); 
      var y; 
      var x; 
      var k = ""; 
      if(o) {
         for(var z = 0; z < o.length; z++) {
            if(o[z].value.length > 0) {
               p[D] = o[z].value + "|1"; 
               D++}
            else {
               if(o[z].getAttribute("mandatory")) {
                  alert(Oshoplang.ChooseAttribute); 
                  return}
               }
            }
         }
      var o = u.getElementsByTagName("input"); 
      if(o) {
         for(var z = 0; z < o.length; z++) {
            if(o[z].type == "checkbox" || o[z].type == "radio") {
               if(k != o[z].getAttribute("name")) {
                  if(z > 0 &&!x && o[z - 1].getAttribute("mandatory")) {
                     alert(Oshoplang.ChooseAttribute); 
                     return}
                  x = false}
               if(o[z].checked) {
                  p[D] = o[z].id + "|1"; 
                  D++; 
                  x = true}
               k = o[z].getAttribute("name")}
            else {
               if(o[z].value.length > 0) {
                  p[D] = o[z].id + "|" + o[z].value; 
                  D++; 
                  x = true}
               else {
                  if(o[z].getAttribute("mandatory")) {
                     alert(Oshoplang.ChooseAttribute); 
                     return}
                  }
               }
            }
         if(o.length > 0 && (o[o.length - 1].type == "checkbox" || o[o.length - 1].type == "radio")) {
            if(!x && o[z - 1].getAttribute("mandatory")) {
               alert(Oshoplang.ChooseAttribute); 
               return}
            }
         }
      }
   if(E) {
      if(E.getAttribute("Vertical") == "True") {
         C = true}
      if(E.getAttribute("Quote") == "True") {
         a = true}
      }
   var b = CMS.CatalogueRetrieve.ServerSideAddItemToOrder(A, j, h, m, q, p, c, C, B, a, t, d); 
   if(b.value[4]) {
      g = b.value[4]}
   createCookie("CartID", b.value[0], 2); 
   if(E) {
      E.innerHTML = b.value[2]}
   switch(b.value[1]) {
      case 0 : if(!l) {
         if(e) {
            //e.innerHTML = b.value[3]; // <<< THIS ONE LINE ONLY (ehhhh)
            ProcessJS(e)}
         alert(g + Oshoplang.Added)}
      else {
         document.location = "/OrderRetrievev2.aspx?CatalogueID=" + j}
      break; 
      case 1 : alert(Oshoplang.OutOfStock); 
      break; 
      case 2 : if(!l) {
         if(e) {
            e.innerHTML = b.value[3]; 
            ProcessJS(e)}
         alert(g + Oshoplang.PreOrder)}
      else {
         document.location = "/OrderRetrievev2.aspx?CatalogueID=" + j}
      break; 
      case 3 : alert(Oshoplang.MinLimit); 
      break; 
      case 4 : alert(Oshoplang.MaxLimit); 
      break}
   if(typeof AddProductExtras == "function") {
      AddProductExtras(j, h, b.value[1])
  }
}


