// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function setSection() {
  $('.section').hide().css('visibility','visible').fadeIn(1000);
  return false
  
  if($('.section') == undefined) return
  
  var w = 0;
  $('.section .images dd').each(function() {
    w += $(this).width();
  });
  
  var h = Math.floor(($('.section').height() * $(window).width())/w);
  var offset = $(window).height() - h - 55;
  $('.section .images').width($(window).width()+20).height(h);
  $('.section .images').css({
    'position':'absolute',
    'top':offset,
    'left':-20
  });
  
  
  

}

function setCollection() {
  if($('.collection').length == 0) {return false};


  var w = 0;
  
  // $('.collection .images').height($('.collection').innerHeight());
  $('.collection').data('ranges',[])
  $('.collection .images dd').each(function(i) {
    if($(this).find('img').length > 0) {
      $(this).width($(this).find('img').width());
    }
    
    w += $(this).width();
    $('.collection').data('ranges').push(w - ($(window).width()/2));
    
    
  });
  
  
  $('dl.images').width(w+500)
  
  
  
  $('.collection .images dd.image').click(function(e) {
    e.preventDefault();
    selectImage($(this));
  });

  $('.arrows').css('visibility', 'visible')

  

}

function selectImage(img) {
  
  closeBag();
  // $(this).siblings().toggleClass('concealed');
  $('.collection .images dd').removeClass('selected');
  img.css({'opacity':1})
  if(img.hasClass('image')) {
    img.addClass('selected');
    if(img.hasClass('selected')) {

      img.siblings().css({'opacity':.2})
      // $('#details .options').html(img.find('.content').html())
      $('#details').css({'left':img.position().left + img.width()}).fadeIn(1000);
      scrollCollectionTo(img);

    } else {
      img.siblings().css({'opacity':1});
      $('#details').hide();
    }
  } else {
    img.siblings().css({'opacity':1});
    scrollCollectionTo(img);
    $('#details').hide();
  }
  

  
  
}

function scrollCollectionTo(obj) {
  var offset = ($(window).width() - obj.width())/2
  $('.collection').stop().scrollTo(obj, {axis:'x',duration:1500, offset:-offset});
  $('#scroller').slider('option', 'value', obj.position().left);
  updateArrows(obj.position().left);
}

function updateArrows(pos) {
  if(pos > 0) {
    $('a.go-left').css('visibility','visible');
  } else {
    $('a.go-left').css('visibility','hidden');
  }
  var max = $('.collection').data('ranges')[$('.collection').data('ranges').length - 1]

  if(pos <= $('.collection').data('ranges')[$('.collection').data('ranges').length - 1]) {
    $('a.go-right').css('visibility','visible');
  } else {
    $('a.go-right').css('visibility','hidden');
  }
}

function updateScroll(ev, ui) {
  var maxScroll = $(".collection").attr("scrollWidth") - $(".collection").width();
  if($('.collection .images dd.selected').length > 0) {
    $('.collection .images dd.selected').removeClass('selected');
    $('#details').hide();
    $('.collection .images dd').css({'opacity':1})
  }
  
  
  // var slideScroll = $('.collection').animate({scrollLeft: ui.value * (maxScroll / 100) }, 20);
  
}


function slideScroll(ev, ui) {
  var maxScroll = $(".collection").attr("scrollWidth") - $(".collection").width();
  var slideScroll = $('.collection').animate({scrollLeft: ui.value}, 0);
  if($('.collection .images dd.selected').length > 0) {
    $('.collection .images dd.selected').removeClass('selected');
    $('#details').hide();
    $('.collection .images dd').css({'opacity':1})
  }
  updateArrows(ui.value);
}

function closeBag() {
  if($('#cart').hasClass('expanded')) {
    $('#cart').hide().removeClass('expanded');
    $('#bag').animate({'top': "+=28px"}, 'fast');
  }

}

function openBag() {
  if(!$('#cart').hasClass('expanded')) {
    $('#cart').fadeIn(500).addClass('expanded');
    $('#bag').animate({'top': "-=28px"}, 'fast'); 
  }
}

$(window).resize(function() {
  $('body').height($(window).height());
  setCollection();
})

$(window).load(function() {
  
  
  $('#mailing-list').submit(function(e){
    e.preventDefault();
    e.stopPropagation();
    $.post($(this).attr('action'), $(this).serialize(), null, 'script' );
    
  })
  
  $('body').height($(window).height());
  setSection();
  
  $('dl.images').height($(window).height())
  
  setCollection();

  $('.collection .images').hide().css('top','0').fadeIn(500,function() {
    
    var w = $('.images').width() - $('.collection').innerWidth() ;
    
    $('#scroller').slider({
      animate:true,
      min:0,
      max:w,
      change:updateScroll,
      slide:slideScroll
    });
  
  });
  
});

$(document).ready(function() {

  setForms();
  // setCollection();


  $('#images dl').sortable({
    update:function(e, ui) {
 
      $.post("/resort/"+ui.item.attr('image_id'), {pos:(ui.item.prevAll('dd').size() )}, null, "script")
    }
  });
  
  $('#details .back-lnk').click(function(e) {
    e.preventDefault();
    // $('.images dd.concealed').removeClass('concealed').hide().fadeIn(1000);
    $('.images dd').css({'opacity':1})
    $('.images dd.selected').removeClass('selected');
    $('#details').hide();
    
    
  });
  

  $("#lnk-"+$('#selected').text()).addClass('selected');
  
  
  $('#image_section_id').change(function(ev) {
    $.post("/new-image", $(this).serialize(), null, "script");
  });
  
  $('#image_collection_id').change(function(ev) {
    $.post("/collection-images", $(this).serialize(), null, "script");
  });

  $('a.thumb').click(function(ev) {
    ev.preventDefault();
    $.scrollTo($(this).attr('href'), {axis:'x', target:'.collections', duration:1000, offset:-400});
  });
  
  $('.add-to-bag').live('click', function(e) {
    e.preventDefault();
    openBag();
     $.post($(this).attr('href'), $(this).serialize(), null, "script");
  });
  
  $('.action').live('click',function(ev) {
    ev.preventDefault();
    $.post($(this).attr('href'),$(this).serialize(), null, "script");
  });
  
  $('#add_new_item').click(function(ev) {
    ev.preventDefault();
    $('#new_item_form').toggle();
  });
  
  $('#cart select').change(function(e) {
    e.preventDefault();
    $.post($(this).parents('form').attr('action'), $(this).serialize(), null, "script");
  })
  
  $('#cart .quantity').focus(function(e) {
    this.select();
  });
  
  $('#cart .quantity').keypress(function(e) {
    
    var charCode = (e.which) ? e.which : e.keyCode

    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
      this.select();
      return false; 
    } 
  })
  
  $('#cart .quantity').keyup(function(e) {

    if($(this).val() <= 0) {
      $(this).val(1)
    } 
    var charCode = (e.which) ? e.which : e.keyCode
    
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
      return false
    } else {
      $.post($(this).parents('form').attr('action'), $(this).serialize(), null, "script");
    }
    
     
  })
  
  
  // $('#images dd').sortable()
  

 $('dl h3').click(function(e) {
   e.preventDefault();
   $(this).parent('dl').toggleClass('expanded');
 });
 
 $('#cart .close').click(function(e) {
   e.preventDefault();
   closeBag();
 })

 $('#bag').click(function(e) {
   e.preventDefault();
   e.stopPropagation();
   
   if($('#cart').hasClass('expanded')) {
     closeBag();
   } else
   {
     openBag();
   }
 
   
 });
 
 $('.item_select').live('submit',function(e) {
   e.preventDefault();
   $.post($(this).attr('action'), $(this).serialize(), null, "script");
 });


 $('#item-admin input').change(function(e) {
   var form = $(this).parent('form');
   form.submit()
 })
 
 $('.qt input').change(function(e) {
   $.post($(this).attr('src'), $(this).serialize(), null, "script")
 })
 
 
 $('.arrows a').mouseup(function(e) {
   clearInterval($('.arrows').data("timer"));
 }).mousedown(function(e) {
   var sc = $('.collection').scrollLeft();
   if($(this).hasClass('go-left')) {
     // fnc = "scrollCollectionLeft()"
     x = -800;
     if($('.collection .images dd.selected').length > 0) {
       var p = $('.collection .images dd.selected').prev();
       
      selectImage( $(p))
     } else {
       for(var i = $('.collection .images dd.image').length-1; i >= 0; i--) {

         var cx = $($('.collection .images dd.image')[i]).position().left

         if(cx < sc) {
           // x = cx;
           selectImage( $($('.collection .images dd')[i]))
           break;
         }
       };
     }

     
   } else {
      if($('.collection .images dd.selected').length > 0) {
        var p = $('.collection .images dd.selected').next()[0];
       
       selectImage( $(p))
      } else {
         for(var i = 1; i <= $('.collection').data('ranges').length; i++) {
           var cx = $('.collection').data('ranges')[i]
           if(cx > sc) {
             // x = cx;
             // img = $('.collection .images dd')[i]
             //          scrollCollectionTo(img);
             selectImage( $($('.collection .images dd')[i]))
             break;
           }
         };
      }
     // fnc = "scrollCollectionRight()"
     // x = 800;
     // x = sc + 300;
     // 
    
   }
   // scrollCollection(x);
   // var timer = setInterval("scrollCollection("+x+")", 2000);
   // 
   // $('.arrows').data("timer", timer);
   

   
 }).click(function(e) {
    e.preventDefault();
 });

});

function scrollCollection(x) {
  var x = $('.collection').scrollLeft() + x;

  x = (x > 0) ? x : 0
  

  $('.collection').stop().scrollTo(x, {axis:'x',duration:1000, offset:-300});
  $('#scroller').slider('option', 'value', x);
}

function updateCart(size, total) {

  $('#cart .total .price').html(total);
  $('#bag .counter').html(size);
  if(size == 0) {
    $('#cart').addClass('empty');
    $('#bag').addClass('empty');
  } else {
    $('#cart').removeClass('empty');
    $('#bag').removeClass('empty');
  }

}

function setForms() {
  // Make input have default text that toggles upon focus
  $('.inputable').each(function(i) {
    var input = $(this).find('input:first');
    var label = $(this).find('label');
    input.focus(function(e) {
      label.hide();
    })
    input.blur(function(e) {
      if(input.val().length == 0) {
        label.show();
      }
        
    })
    label.click(function(e) {
      input.focus();
    });
    
    if(input.val().length > 0) {
      label.hide();
    }
  })
  
  
}

jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} 
});