/**
**	some of the code here is dependant on the markup
*/

jQuery.noConflict();
$j = jQuery;
$j().ready(function(){
  doCorners();
  window.onresize = fixPos;
  fixPos();
  // remove the dotted top border from the first item. bleh!
  $j('.accordion_toggle:first').css({border:0});  
}); 

__listen__ = true;


function doCorners(){
  $j('.cats,.cart,.auth,#genres,.skinned-mod-search').each( function(i){
    var str = '<em class="ctl"><b>&bull;</b></em><em class="cbl"><b>&bull;</b></em><em class="ctr"><b>&bull;</b></em><em class="cbr"><b>&bull;</b></em>';
    $j(this).prepend(str);
    $j(this).find('.wrapper').css({position:'relative',zIndex:100});
  });
}

function hijackMenu(){
  $j('#categories li a').click( function(e){
    var str = this.href.split('menu/');
    var sid = str[1].split('/')[1];
    $j.ajax({
      type: "GET",
      url: "/_cfc/services/order.cfc?method=displayMenuItems&sid="+sid,
      success: function(data){
        $j('.items').html( data );
      }
    });
    return false;
  })
}

function loadAccordions() {
  $j('div.accordion_content').hide();
  $j('h1.accordion_toggle').toggle(
    function(e){  // e is the event in case we need it
      var $this = $j(this);
      if( !$this.next().find('div.group').size() ) return false;   // make sure a modifiers group is present before opening
      $this.addClass('accordion_toggle_active');
      $this.next().slideDown(400);
    },
    function(e){
      var $this = $j(this);
      $this.removeClass('accordion_toggle_active');
      $this.next().slideUp(400);
    }
  )
}


function hijackCart() {
  
  // update the item count for cart by counting the children li's for #cart
  $j('#cartcount').html( $j('#cart > li').size() +' items');
  
  $j('.frm-addToCart')
    .livequery('submit', function(event) { 
      $this = $j(this);
      alert( 'skinning.js' );
      var par = $this.parents('.accordion_content');
      $j.ajax({
        type: "POST",
        data: $this.serialize(),
        url: this.action,
        success: function(data){
          alert('done');
          $j('#cart-wrapper').html( data );
          fixPos();
          if( par.is(':visible') ){
            par.prev().trigger('click');
          }
          clearMods( $this );
        }
      });
      return false;
    });
  
}


function prepCart() {
  
  // update the item count for cart by counting the children li's for #cart
  $j('#cartcount').html( $j('#cart > li').size() +' items');
  
  $j('.close-option').click( function(){
    $this = $j(this);
    var par = $this.parents('.accordion_content');
    par.prev().trigger('click');
  });
  
  $j('#submit-cart').hover( 
    function(){
      $j(this).addClass('hover');
      //$j(this).attr('src','/_imgs/_global/btn_review_order_on.png');
    },
    function(){
      $j(this).removeClass('hover');
      //$j(this).attr('src','/_imgs/_global/btn_review_order_off.png');
    }
  );  
  $j('#submit-cart').click( function(){
    //$j(this).parent().trigger('click');
    /*
    // start checkout process
    $j.ajax({
      type: "GET",
      url: "/_cart_checkout.cfm",
      success: function(data){
        $j('#ctr-column').html(data);
      }
    });
    */
    //return false;
  });
  
  $j('li.option input[type="checkbox"]').click( function(){
    return handleModOption(this);
  });
  
  $j('.btn-addToCart').hover( 
    function(){
      $j(this).addClass('btn-addToCart-hover');
      //$j(this).attr('src','/_imgs/_global/btn_add_to_cart_on.png');
    },
    function(){
      $j(this).removeClass('btn-addToCart-hover');
      //$j(this).attr('src','/_imgs/_global/btn_add_to_cart_off.png');
    }
  );
  
  $j('.btn-addToCart')
    .livequery('click', function(event) { 
        //alert('clicked'); 
        $j(this).parents('.frm-addToCart').submit();
        return false; 
    }); 
    
  
  
  $j('.frm-addToCart')
    .livequery('submit', function(event) { 
      $this = $j(this);
      var ret = true;
      // find the mod_min value if present and make sure at least that many options are selected
      $this.find('.group').each( function(){
        var $grp = $j(this);
        var $mod_min = $j(this).find('.options-instructions .mod_min');
        if( $mod_min.size() > 0 ){   // if there's a .mod_min element
          var mod_min = $mod_min.text();
          // count the number of selected elements in the group
          if( $this.find('input[type="checkbox"]:checked').size() < mod_min ){
            var grp = $grp.find('h2').eq(0).html();
            //tooltip('You must select at least '+mod_min+' modifier from the '+grp+' group.', $grp);
            alert('You must select at least '+mod_min+' modifier from the '+grp+' group.');
            ret = false;
          }
        }
      });
      if(!ret) return false;
      
      var par = $this.parents('.accordion_content');
      $j.ajax({
        type: "POST",
        data: $this.serialize(),
        url: this.action,
        success: function(data){
          $j('#cart-wrapper').html( data );
          fixPos();
          if( par.is(':visible') ){
            par.prev().trigger('click');
          }
          clearMods( $this );
        }
      });
      return false;
    });
    
    
  
  $j('.btn-smlAddToCart').click( function(){
    var par = $j(this).parents('.accordion_toggle');
    var c_div = par.next();
    if( c_div.find('input[type="checkbox"]').size() == 0 ){    // options are not available trigger the add to cart and return false
      c_div.find('form').submit();
      return false;
    }
  });
}

function handleModOption( el ){
  var $el = $j(el);
  
  // first we can determine if this click can be allowed
  // we're not concerned with them removing any options so...
  if( !el.checked ) {
    // we actually need to check for a price if we're removing an option in order to decrease the price hidden field
    var price_adj = $el.attr('price');    // find it in the DOM (or return false?)
    if( price_adj != undefined){
      var cur_price = $el.parents('.frm-addToCart').find('input[name="price"]').val();
      var parsed_price = parseFloat(cur_price.replace('$',''));
      var new_price = parsed_price - parseFloat(price_adj);
      $el.parents('.frm-addToCart').find('input[name="price"]').val( '$'+new_price.toFixed(2) );
    }
    return true
  }
  
  var total_opt_sels = $el.parents('.options').find('input[type="checkbox"]:checked').size();
  var mod_max = undefined;
  var mod_min = undefined;
  $el
    .parents('.options')
    .prev()
    .find('.mod_max')   // there should be one 
    .each( function(){
      mod_max = $j(this).html();
    });
  if (total_opt_sels > mod_max) {
    // we need the group name
    var $grp = $el.parents('.group');
    var grp = $el.parents('.group').find('h2').eq(0).html();
    //tooltip('You can only select '+mod_max+' modifier(s) from the '+grp+' group.', $grp);
    alert('You can only select '+mod_max+' modifier(s) from the '+grp+' group.');
    return false;
  }
  
  // now let's get a price adjustment if there is one
  // if we've gotten here the option is being added and the price needs to update
  var price_adj = $el.attr('price');     
  if( price_adj != undefined){
    var cur_price = $el.parents('.frm-addToCart').find('input[name="price"]').val();   // fetch it from the DOM
    var parsed_price = parseFloat(cur_price.replace('$',''));
    var new_price = parsed_price + parseFloat(price_adj);   // make sure we're working with a float
    $el.parents('.frm-addToCart').find('input[name="price"]').val( '$'+new_price.toFixed(2) );   // update the DOM
  }
  
  return true;
}

function tooltip( msg, $grp ){
  //console.log('tooltip:');
  //console.log($grp);
  //console.log($grp.position());
  $j("body").append("<p id='tooltip'>"+ msg +"</p>");
  var instr = $grp.find('.options-instructions');
  $j("#tooltip")
    .css("top",(instr.position().top) + "px")
    .css("left",(instr.position().left) + "px")
    .fadeIn("fast");
  window.setTimeout("fadeTooltip()",4000);
}
function fadeTooltip(){
  $j('#tooltip').fadeOut("fast", function(){$j('#tooltip').remove()});
  $j('#pg').unbind('mousemove');
}


function clearMods( $el ){
  // called when an item is added to the cart in order to clear all user selections
  $el.find('input[type="checkbox"]:checked').each( function(){
    this.checked = false;
  });
}
  
 
function fixPos(){
  var h = ($j(window).height() > 600 ? $j(window).height() : 600);
  //alert('h: '+h);
  $j('.cats').height(h - 120);
  $j('#cart').height(h - 320);
  $j('#cart').jScrollPane();
  $j('.items').height(h - 120);
  return false;
  
  if(! $j.browser.msie){
    var h = ($j(window).height() > 600 ? $j(window).height() : 600);
    //var neg = $j('#banner').height() +40;
    //    h = h - neg;
    //    h = h - 120;
    //$j('#rt-column').height(h);
    $j('.cats').height(h - 120);
    //$j('#categories').jScrollPane();
    $j('#cart').height(h - 320);
    $j('#cart').jScrollPane();
    $j('.items').height(h - 160);
  } else {
    $j('.cats').height(500);
    //$j('#categories').jScrollPane();
    $j('#cart').height(500);
    //$j('#cart').jScrollPane();
    $j('.items').height(500);
  }
}

function fixMods(){
  // fix the position of the banner and two side panels
  // first get their current position
  $j('.cats, #rt-column')
    .each( function(i,e){
      var $this = $j(this);
      var _y = $this.offset().top;
      $this.css({position:'fixed',top:_y+'px'});
    });
  $j('#banner').css({position:'fixed'});
  $j('#container').css({top:'90px'});
  
}