
var Local = {

    onCommentReply: function(id) {
		Comments.openReply(id);
	},

    onCancelReply: function(id) {
		Comments.closeReply();
	}

};

(function(){
	var j=jQuery;
	
	var alerting=false;
	var oh={};
	
	oh.items=[];
	oh.add_item=function(el){
		id=el.attr('id');
		
		// Number of item to add
		no=parseInt(el.find('.qty input').val().replace(/[^\d]/,''),10);
		
		el.find('.qty input').val(0);
		
		// If they've already got some
		if(j('#order-'+id).length>0){
			// add number in the box
			j('#order-no-'+id).html(parseInt(j('#order-no-'+id).html()) + no, 10)
			
		// If they haven't bought any yet, add them
		}else{
			
			// Add new row
			j('#wholesale-form').append("<tr id=\"order-" + id + "\" class=\"order_item\"><td class=\"order_no\"><input type=\"hidden\" id=\"order-input-"+id+"\" name=\""+id+"\" value=\"\" /><a class=\"dec\" id=\"dec-"+id+"\" href=\"#\">&ndash;</a><a class=\"inc\" id=\"inc-"+id+"\"  href=\"#\">+</a><span class=\"qty\" id=\"order-no-"+id+"\">"+no+"</span></td><td class=\"title\">"+el.find('.title').html()+"</td><td class=\"price\">$10.28</td><td class=\"item_remove\"><a href=\"#\" id=\"remove-"+id+"\">&times;</a></td></tr>");
      // oh.row_total(id);
			
			// Give new row increase and decrease and remove
			j('#inc-'+id).click(function(e){
				e.preventDefault();
				val=parseInt(j(this).next().html(),10)+1;
				j(this).next().html(val);
				oh.total();
			});
			j('#dec-'+id).click(function(e){
				e.preventDefault();
				val=parseInt(j(this).next().next().html(),10)-1;
				if(val <= 0) {
					j(this).parent().parent().remove();
				} else {
					j(this).next().next().html(val);
				}
				oh.total();
			});
			
			j('#remove-'+id).click(function(e){
				e.preventDefault();
				j(this).parent().parent().remove();
				oh.total();
			});
		}
		oh.total();
	}
    oh.lightboxy = function() {
        // lightbox functionality
        j('body').append(
            j(jQuery('<div />'))
            .attr({id: 'overlay'})
            .click(
                function() {
                j('#lightbox').hide()
                setTimeout(function() {
                    j('#lightbox').removeClass('cake_lightbox').removeClass('video_lightbox')
                }, 501)
                j('#overlay').css({display: 'none'})
                j('.youtube_videos').css({display: 'block'});
            })
            .hide()
        )
        j('body').append(
            j(jQuery('<div />'))
            .attr({id: 'lightbox'})
            .click(
                function() {
                j('#overlay, #lightbox').stop()
            })
            .css({display: 'none'})
        )
        j('body').append(j(jQuery('<div />')).attr({id: 'preload'}).css({position: 'absolute', top: -10000, left: -10000}))
        if(jQuery.browser.safari) {
            j('#overlay, #lightbox').css({display: 'none'})
            j('.youtube_videos').css({display: 'block'});
        } else if(jQuery.browser.msie && jQuery.browser.version < 7) {
            j('#overlay').height(j('body').height())
            j('.youtube_videos').css({display: 'block'});
        }

        j('a[rel*=lightbox]').each(
            function() {
            j(this).attr({src: j(this).attr('href'), href: 'javascript:void(0)'})
            j(this).click(
                function() {
                j(this).blur()
                var large = j(jQuery('<img />'))
                large.attr({src: j(this).attr('src'), alt: j(this).attr('title')})
                j('#preload').html(large)
                var dimensions = {x: large.width(), y: large.height()}
                if(large.attr('src').match(/\.png/i) && jQuery.browser.msie && jQuery.browser.version < 7) {
                    large.css({background: 'none', filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + large.attr('src') + "', sizingMethod='scale')"}).attr({src: '/images/clear.gif', width: dimensions.x, height: dimensions.y })
                }
                if(j(this).next('a[href*=pdf]').length > 0) {
                    var pdf = j(this).next('a[href*=pdf]').attr('href')
                } else {
                    pdf = false
                }
                if(pdf) {
                    j('#lightbox').html(large)
                    .append(
                        j(jQuery('<div />'))
                        .addClass('close')
                        .click(
                            function() {
                            setTimeout(
                                function() {
                                j('#lightbox').hide()
                                setTimeout(function() {
                                    j('#lightbox').removeClass('cake_lightbox').removeClass('video_lightbox')
                                }, 510)
                                j('#overlay').css({display: 'none'})
                                j('.youtube_videos').css({display: 'block'});
                            }, 5)
                        })
                    )
                    .append(
                        j(jQuery('<a />'))
                        .addClass('pdf')
                        .attr({href: pdf, title: 'Download PDF'})
                    )
                } else {
                    j('#lightbox').html(large)
                    .append(
                        j(jQuery('<div />'))
                        .addClass('close')
                        .click(
                            function() {
                            setTimeout(
                                function() {
                                j('#lightbox').hide()
                                setTimeout(function() {
                                    j('#lightbox').removeClass('cake_lightbox').removeClass('video_lightbox')
                                }, 510)
                                j('#overlay').css({display: 'none'})
                                j('.youtube_videos').css({display: 'block'});
                            }, 5)
                        })
                    )

                }
                j('#overlay').css({display: 'block'});
                j('.youtube_videos').css({display: 'none'});
                j('#lightbox').css({height: ''})
                j('#lightbox').fadeIn(500)
                if(jQuery.browser.msie && jQuery.browser.version < 7) {
                    window.scrollTo(0,0)
                }
            })
        });
        j('div#video_sidebar a').each(
            function() {
                if(j(this).attr('href') == 'javascript:void(0)') {
                    return false;
            }
            var url = j(this).attr('href')
            j(this).attr({href: 'javascript:void(0)'})
            j(this).click(
                function() {
                    j('#lightbox')
                    .load(url + ' embed')
                    .addClass('video_lightbox')
                    j('#overlay').css({display: 'block'});
                    j('#lightbox').fadeIn(500)
                    if(jQuery.browser.msie && jQuery.browser.version < 7) {
                        window.scrollTo(0,0)
                    }
                })
        })
    }
	
  // oh.row_total=function(id){
  //  el=j('#order-'+id);
  //  no=parseInt(j('#order-no-'+id).html().replace(/[^\d]/,''),10);
  //  
  //  // figure out which price to use
  //  price = (no<50)? parseFloat(j('#'+id+' .price1').html().replace(/[^\d\.]/,'')) : parseFloat(j('#'+id+' .price2').html().replace(/[^\d\.]/,''));
  //  
  //  
  //  // fix the hidden input
  //  input_id=j('#'+id+' .qty input').attr('part');
  //  j('#order-input-'+id).attr('value',input_id+'|'+no+'|'+price);
  //  j('#order-input-'+id).attr('name','order-products[]');
  //  
  //  // total it and update span and input
  //  var tot=no*price;
  //  j('#order-'+id+' .price').html('$'+tot.toFixed(2));
  //  return tot;
  // }
  //      
  // oh.total=function(){
  //  items=j.find("#wholesale-form tr");
  //  var qty=0;
  //  var tot=0;
  //  for(i=0;i<items.length;i++){
  //    tot+=oh.row_total(items[i].id.substr(6));
  //    // Add 'em to the total quantity unless it's the case
  //    if(items[i].id!='part-d41d8cd98f00b204e9800998ecf8427e')        
  //      qty+=parseInt(j('#order-no-'+items[i].id.substr(6)).html().replace(/[^\d]/,''),10);
  //  }
  //  
  //  // If they want cases give them some for free maybe
  //  if(j('#order-part-d41d8cd98f00b204e9800998ecf8427e').length>0){
  //    num_cases=parseInt(j('#order-no-part-d41d8cd98f00b204e9800998ecf8427e').html().replace(/[^\d]/,''),10);
  //    free=Math.floor(qty/24);
  //    num_cases-=free;
  //    if(num_cases<1) num_cases=0;
  //    console.log(num_cases);
  //    j('#order-part-d41d8cd98f00b204e9800998ecf8427e .price').html('$'+(num_cases*17).toFixed(2));
  //    tot-=free*17;
  //  }
  // 
  //  tot = tot.toFixed(2);
  //  j("input[@name=order-total]").val(tot);
  //  j("#order-total .total").html(tot);
  // }
  
  oh.total = function(){
    var items = j.find("#wholesale-form tr")
    var case_id = 'part-d41d8cd98f00b204e9800998ecf8427e'
    var total = 0
    var qty = 0
    
    for(i=0; i<items.length; i++){
      var line = j(items[i])
      var id = line.attr('id').replace('order-','')
      var item_qty = parseInt(line.find('.qty').html())
      var price = parseFloat(j('#'+id).find('.price1').html().gsub(/[^\d.]/,''))
      // alert('id:'+id+' / pr:'+price+' / qty:'+item_qty)
      qty += item_qty
      total += price*item_qty
      line.find('.price').html('$'+(price*item_qty).toFixed(2))
		   // fix the hidden input
			var input = j('#order-input-'+id);
		  input_id=j('#wholesale-items #'+id).find('.qty input').attr('part');
		  input.attr('value',input_id+'|'+item_qty+'|'+price);
 		  input.attr('name','order-products[]');
    }
    
    j('#order-total .total').text(total.toFixed(2));
		
      if(qty>50) {
       j('#order-total input').val((total-qty).toFixed(2));
       } else {
          j('#order-total input').val((total).toFixed(2));
       }
    
    if(qty > 50)
      oh.$_discount(items)
    
    if(qty > 12)
      j('form#wholesale-order-form_form input.input-submit').show();

    if(qty < 13)
      j('form#wholesale-order-form_form input.input-submit').hide();

  }
  
  oh.$_discount = function(items){
    var total_discount = 0
    for(i=0; i<items.length; i++){
      var line = j(items[i])
	  var id = line.attr('id').replace('order-', '')
      var item_qty = parseFloat(line.find('.qty').html())
      var price2 = parseFloat(j('#'+id).find('.price2').html().gsub(/[^\d.]/,''))
      var discount = parseFloat(j('#'+id).find('.price1').html().gsub(/[^\d.]/,'')) - price2
      line.find('.price').html('$'+(price2 * item_qty).toFixed(2))
      total_discount += item_qty * discount
			var input = line.find('input');
		  input_id=j('#wholesale-items #'+id).find('.qty input').attr('part');
		  input.attr('value',input_id+'|'+item_qty+'|'+price2);
    }
    var total = j('#order-total .total')
    total.html((parseFloat(total.html().gsub(/[^\d.]/,'')) - total_discount).toFixed(2))
  }
	
	j(document).ready(function(){
        oh.lightboxy();

		j('#wholesale-items tr .add a').click(function(e){
			e.preventDefault();
			oh.add_item(j(this).parent().parent());
		});
		
		j('#wholesale-items tr .qty input').keyup(function(e){
			e.preventDefault();
			if((e.which==13) && (!alerting))
				oh.add_item(j(this).parent().parent());
		});
		
		j('#wholesale-items .qty input').val(0);
		
		j('form#wholesale-order-form_form input.input-submit').hide();
		
		
		
		j('a').click(function() { j(this).blur(); });
	});
	
	j(window).load(function() { // These functions get called when everything has loaded
		j('#sidebar').height((j('#sidebar').height() < 600 ? 600 : ''))
		j('#main').height((j('#main').height() < j('#sidebar').height() ? j('#sidebar').height() : ''))
		
		
	});
	
	
})();

