// Put all global "onload" scripts here
var blank = new Image();
blank.src = '/images/blank.gif';

$(document).ready(function () {
  /*$("a#new-user").colorbox({ width:"490px", height:"700px", iframe:true, close:'stäng' });
  $("a#new-user").colorbox({onLoad: function() {
    $('#cboxClose').remove();
  }});*/
  $("a#login-user").colorbox({ inline:true, href:"#login-box", close:'stäng', scrolling:false });
  $("a#login-user").colorbox({onLoad: function() {
    $('#cboxClose').remove();
  }});
  $('#sf_guard_user_same_delivery_address').click(function() {
    $('#delivery-address').slideToggle('slow')
  });
	$('#delivery-toggle').click(function() {
    $('#delivery-address').slideToggle('slow')
  });
  $('#login-toggle').click(function() {
    $('#login-box').slideToggle('slow');
    return false;
  });
  // This needs to be fixed for IE6
  /*message = $('#flash-message p:first').html();
  if(!message){ 
    $('#flash-message').hide();
  }*/
	$("#area-select").fixSelect();
	$('select', '#search-box').fixSelect('no');
	$('#sortBy').fixSelect();
	
// Login ajaxing

$("form#login-form").submit(function() {
  $.ajax({
    url: $(this).attr('action'),
    type: 'POST',
    data: $(this).serialize(),
    dataType: 'json',
    success: function(response) {
      if(response.loggedIn) {
        window.location.reload();
      } else {
        $("form#login-form #message").html("Användarnamnet eller lösenordet som du angav är felaktigt.")
        $('#login-box').colorbox.resize();
      }
    }
  });
  return false;
});

	pub.setupCarousel();
	
  $('.read-more').show();
  $('.read-more').click(function() {
    window.location = $(this).attr('id');
  });
});


$.fn.fixSelect = function(search) {
	$(this).bind('change',function() {
		$(this).next().text(this.options[this.selectedIndex].text);
		if(search != 'no') $(this).parents('form').submit();
	}).bind('name', function() {
		$(this).next().text(this.options[this.selectedIndex].text);
	});
	$(this).trigger('name');
};

function openExtSearch(elm) {
	$('#ext-search').slideToggle('medium');
	($(elm).html() == 'Stäng utökad sök')? $(elm).html('Utökad sök') : $(elm).html('Stäng utökad sök');
	$('#ext-open').val(Math.abs($('#ext-open').val() - 1));
}


// The global js object. Add all your scripts to this one
var pub = {};

// Create a private namespace to avoid polluting the global namespace
(function() {

	// Runs onload to setup the carousel, if present
	pub.setupCarousel = function() {
		if (!$('#carousel').length) return;
		$("#carousel").jcarousel({
	        scroll: 1,
	        wrap: 'both',
	        initCallback: _carouselInitCallback,
	        itemFirstInCallback: _carouselOnChangeCallback,
	        buttonNextHTML: null,
	        buttonPrevHTML: null
	    });
	};

	// Used internally by carousel to setup custom navigation
	_carouselInitCallback = function (carousel) {
	    $('.jcarousel-control a').click(function() {
	        if ($(this).attr('id').substr(0,2) == 'jc')
	        	carousel.scroll($.jcarousel.intval($(this).text()));
	        return false;
	    });
	    $('#carousel-next').click(function() {
	        carousel.next();
	        return false;
	    });
	    $('#carousel-prev').click(function() {
	        carousel.prev();
	        return false;
	    });
	};
	
	// Used internally by carousel to activate current item in nav
	_carouselOnChangeCallback = function (carousel, li, idx) {
		$('.jcarousel-control a').css('text-decoration', 'none');
		$('a#jc' + idx).css('text-decoration', 'underline');
	};

// The cart functions object
  pub.cart = {
    add: function(url) {
      $('#cart').slideToggle('medium');
      $.ajax({
        cache: false,
        url: url,
        success: function(response) {
          $('#orderSummary').load($('#refreshUrl').val() + '?' + Math.round(Math.random()*1000));
          $('#cart').html(response);
        },
        complete: function(response) {
          $('#cart').slideToggle('medium', function() {
          });
          $.ajax({
            cache: false,
            url: '/main/flash',
            dataType: "json",
            success: function(response) {
              $('#flash-message').show();
              $('#flash-message p').html(response.message);
              $('#flash-message').delay(2000).fadeOut('slow');
            }
          });
        }
      });
      return false;
    },
    update: function(url, qty) {
      $('#cart').slideToggle('medium');
      $.ajax({
        cache: false,
        url: url + '?qty=' + qty,
        success: function(response) {
          $('#orderSummary').load($('#refreshUrl').val() + '?' + Math.round(Math.random()*1000));
          $('#cart').html(response);
        },
        complete: function(response) {
          $('#cart').slideToggle('medium', function() {
          });
          $.ajax({
            cache: false,
            url: '/main/flash',
            dataType: "json",
            success: function(response) {
              $('#flash-message').show();
              $('#flash-message p').html(response.message);
              $('#flash-message').delay(2000).fadeOut('slow');
            }
          });
        }
      });
      return false;
    }
  };
})(); // (function() {

//jQuery funtion för att fixa PNGs i IE6, http://allinthehead.com/retro/338/supersleight-jquery-plugin hämtad 2009-04-19
jQuery.fn.supersleight = function(settings) {
	settings = jQuery.extend({
		imgs: true,
		backgrounds: true,
		shim: '/css/images/x.gif',
		apply_positioning: true
	}, settings);
	
	return this.each(function(){
		if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 7 && parseInt(jQuery.browser.version) > 4) {
			jQuery(this).find('*').each(function(i,obj) {
				var self = jQuery(obj);
				// background pngs
				if (settings.backgrounds && self.css('background-image').match(/\.png/i) !== null) {
					var bg = self.css('background-image');
					var src = bg.substring(5,bg.length-2);
					var mode = (self.css('background-repeat') == 'no-repeat' ? 'crop' : 'scale');
					var styles = {
						'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + mode + "')",
						'background-image': 'url('+settings.shim+')'
					};
					self.css(styles);
				};
				// image elements
				if (settings.imgs && self.is('img[src$=png]')){
					var styles = {
						'width': self.width() + 'px',
						'height': self.height() + 'px',
						'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + self.attr('src') + "', sizingMethod='scale')"
					};
					self.css(styles).attr('src', settings.shim);
				};
				// apply position to 'active' elements
				if (settings.applyPositioning && self.is('a, input') && self.css('position') === ''){
					self.css('position', 'relative');
				};
			});
		};
	});
};
