$('document').ready( function () {
	/* INIT */
	var cartSliding = false;
		
	$('.payment_options').click(function() {
		
		if($(this).val() == 'PAYMENT_INSTALLMENT') {
			if(!$('.installment_options').is(':visible')) {
				$('.installment_options').slideToggle('slow');
			}
		} else {
			if($('.installment_options').is(':visible')) {
				$('.installment_options').slideToggle('slow');
			}
		}
    });
    
	$('form.productForm, form#productForm').submit( addToCart);

	$('input.amount').change( function() {
		var row = $(this).attr('id');

		var amount = $(this).val();

		var totalt = parseInt(amount) * parseInt($('.prodPrice_'+row).val());

		$('.totalt_'+row).html(totalt+':-');

	});

	$('.productbuyantal').keyup( function() {
		var amount = $(this).val();

		var name = $(this).attr('name');

		var list = name.split('_');

		var sectionID = list[1];
		var productID = $('#prodID_'+sectionID).val();

		if(parseInt(amount) > 0){
			$.get('xmlhttp/getPropID.php', { amount: amount, productID: productID, sectionID: sectionID }, function(data){
				var list = data.split('|');

				var propID = parseInt(list[0]);

				$('#prodSection_'+sectionID).attr('value', propID);
				$('#propID_'+sectionID).attr('value', propID);
				$('#price_'+sectionID).html(list[1]+':-');
			});
		}
	});


	$('.prodSections select').change( function() {

		var data = $('#productForm').formSerialize();

		$.post('xmlhttp/getProductPropertyPrice.php', data, function(data) {

			values = data.split('|');

			if(values[1] != 0){
				$('td#t_'+values[1]+' a').click();
			}

			$('.price-body').html(values[0]);
		});
	});


	$('#lev_same').click(function() {

		$('tr.shipping').toggle();

		if($('input.shipping').val() == 1){
			$('input.shipping').attr('value', 0);
		}else{
			$('input.shipping').attr('value', 1);
		}
	});

	
	$('[name=pernum]').change(function() {
		$.get('xmlhttp/checkorgnr.php', {regnr: $(this).val()}, function(data) {
			
			if ( data == 'ERROR' ) {
				alert('Numret är felaktigt, försök gärna igen.');
			} else if ( data == 'COMPANY' ) {
				$('#companyRow').show();
			} else {
				$('[name=company]').val('');
				$('#companyRow').hide();
			}
			
		});
		
	});
	

	$('#newsletteradd').submit( function() {
		
		var data = $('#newsletteradd').formSerialize();

		$.post('handlers/newsletter.handler.php', data, function(data) {
			var list = data.split('||');

			if(list[0] == 1){
				$('.newsletter .msg').html(list[1]);
				$('#newsletteradd').hide();
			}else{
				$('.newsletter .msg').html(list[1]);
			}
		});

		return false;
	});


	//Visa kundvagn vid hover
	$('div#top .cart').hover( function(){
		if(!cartSliding){
			cartSliding = true;
			$('div#top .cart .cart_items').slideDown('fast', function() { cartSliding = false; });
		}
	}, function(){
		$('div#top .cart .cart_items').slideUp('fast', function() {
			$('div#top .cart .cart_items').clearQueue();
			cartSliding = false;
		});
	});

	$('.popup .close').click(function() {
		$(this).parent().hide();
		$('#lightbox-shadow').hide();
	});
	
	$('.popup.models .close').click(function() {
			$('.popup.models').hide();
			$('#lightbox-shadow').hide();
		})
	$('#left .margin .from-list').click(function() {
			$('.popup.models').center();
			$('.popup.models').show();
			$('#lightbox-shadow').show();
			fetchMakes("#car_select_form .make");
		});
	
	var sliding = false;
	
	$('.product_box .more').click(function() {
		if(!sliding) {
			if($(this).parent().find('.products').css('top') == '-10px') {
				sliding = true;
				$(this).parent().find('.products').animate({'top':'-=217'}, 'slow', function() { sliding = false; });
			} else {
				sliding = true;
				$(this).parent().find('.products').animate({'top':'+=217'}, 'slow', function() { sliding = false; });
			}
		}
		});
	
	$('#regnr_form').submit(function() {
		getCarInfo($('#regnr_form_regnr').val());
		return false;
	});
	
	$('#clear_regnr').submit(function() {
		clearCarInfo();
		return false;
	});
	
	$('#regnr_show_information').click(function() {
		$('.popup.carinfo').show();	
	});
	
	$('.popup.carinfo .close a').click(function() {
		$('.popup.carinfo').hide();	
	});
	
	$('#car_select_form input').click(function() {
		setCar();
		return false;
	});
	
	$('#confirm_cart .continue').click(function() {
		$('#confirm_cart').fadeOut('fast');
	});
	
	$('.quantity-buy').keydown(function(e) {
		if(!((e.which >= 48 && e.which <= 57) || //0-9 Top of keyboard
		     (e.which >= 35 && e.which <= 40) || //Arrow keys, Home and End
		     (e.which >= 45 && e.which <= 46) || //Insert delete
		     (e.which >= 96 && e.which <= 105) || //0-9 Keypad
		     (e.which == 8) ||  		 // Backspace
		     (e.which == 116))) {		//F5
			e.preventDefault();
		}
	});
	
	$('#webshop-article .share .taf').click(function() { showPopup('tellafriend'); });
	
	$('.tellafriend form').submit(function() {
		sendTellAFriend();
		return false;
	});
	
	if (! ("placeholder" in document.createElement("input"))) {
        $('*[placeholder]').each(function() {
            $this = $(this);
            var placeholder = $(this).attr('placeholder');
            if ($(this).val() === '') {
                $this.val(placeholder);
            }
            $this.bind('focus',
            function() {
                if ($(this).val() === placeholder) {
                    this.plchldr = placeholder;
                    $(this).val('');
                }
            });
            $this.bind('blur',
            function() {
                if ($(this).val() === '' && $(this).val() !== this.plchldr) {
                    $(this).val(this.plchldr);
                }
            });
        });
 
	}
	
	$('#lightbox-close').click( function() {
	$('#lightbox').hide();
	$('#lightbox-shadow').hide();
	});
    
	setLightboxPosition();
	$(window).resize(setLightboxPosition);
	
	$('#lightbox .lightbox-right').click(getNext);
	$('#lightbox .lightbox-left').click(getPrev);
	
	$('.product_installment_price').hover(function() { $('.product_installment_options').show(); }, function() { $('.product_installment_options').hide(); });
	
	setZoom();
	
	$('.extra_service, .payment_options').change(function() {
		var serviceID = 0;
		var $extraService = $('.extra_service');
		var paymentOption = $('.payment_options:checked').val();
		
		if($('.extra_service:checked').length > 0){
		    serviceID = $('.extra_service:checked').attr('id').split('_')[1];
		    $extraService.not('.extra_service:checked').attr('disabled', 'disabled');
		    $extraService.not('.extra_service:checked').parent().find('span.label').addClass('disabled');
		} else {
		    $extraService.removeAttr('disabled');
		    $extraService.parent().find('span.label').removeClass('disabled');
		}
		
		    
		$.getJSON('xmlhttp/setExtraService.php', {'service' : serviceID, 'po' : paymentOption}, function(data) {
		    $('#webshop-cart .total .e .tot').html(data.newOrderPrice);
		    $('#webshop-cart .extra_price').html(data.newExtraServicePrice);
		});
	});
	
	$('.payment_options, .klarna_payment').change(function() {
		var paymentOption = $('.payment_options:checked').val();
		$.getJSON('xmlhttp/setPaymentMethod.php', {'0' : paymentOption, '1' : $('.klarna_payment:checked').val()});
	});
    
	$("#car_select_form .make").change(function() {
		var $make = $("#car_select_form .make");
		var $model = $("#car_select_form .model");
		
		if( $make.val() == '' ) {
			$model.attr('disabled', 'disabled');
		} else {
			$model.removeAttr('disabled');
			fetchModels($make.val(), "#car_select_form .model");
		}
	});
	
	$("#car_select_form .model").change(function() {
		var $make = $("#car_select_form .make");
		var $model = $("#car_select_form .model");
		var $year_model = $("#car_select_form .year_model");
		
		
		if( $model.val() == '' ) {
			$year_model.attr('disabled', 'disabled');
		} else {
			$year_model.removeAttr('disabled');
			fetchYears($make.val(), $model.val(), "#car_select_form .year_model");
		}
	});
	
	$(".quantity-buy").change(function() {
		if( $(this).val() == 0 ) {
			$(this).val(1);
		}	
	});
	
	$(".quantity-buy").keyup(function() {
		if( $(this).val() === '0' ) {
			$(this).val(1);
		}	
	});
}); 

function manualCheckoutUpdate() {
	var serviceID = 0;
	var $extraService = $('.extra_service');
	var paymentOption = $('.payment_options:checked').val();
	
	if($('.extra_service:checked').length > 0){
	    serviceID = $('.extra_service:checked').attr('id').split('_')[1];
	    $extraService.not('.extra_service:checked').attr('disabled', 'disabled');
	    $extraService.not('.extra_service:checked').parent().find('span.label').addClass('disabled');
	} else {
	    $extraService.removeAttr('disabled');
	    $extraService.parent().find('span.label').removeClass('disabled');
	}
	
	    
	$.getJSON('xmlhttp/setExtraService.php', {'service' : serviceID, 'po' : paymentOption}, function(data) {
	    $('#webshop-cart .total .e .tot').html(data.newOrderPrice);
	    $('#webshop-cart .extra_price').html(data.newExtraServicePrice);
	});
}

function fetchModels(make, target) {
	$.post('xmlhttp/getModels.php', {'make' : make}, function(data) { $(target).html(data); });
}

function fetchMakes(target) {
	$.post('xmlhttp/getMakes.php', {}, function(data) { $(target).append(data); });
}

function fetchYears(make, model, target) {
	$.post('xmlhttp/getYears.php', {'make' : make, 'model' : model}, function(data) { $(target).html(data); });
}

function sendTellAFriend() {
	
	$('div.tellafriend .form').hide();
	$('div.tellafriend .ajax-loader-big').show();
	
	//$('div.tellafriend').animate({height: '-=100px'}, 1000);
	var post_data = $('div.tellafriend .form form').serialize();
	$.post('xmlhttp/taf.php', post_data, function(data) {
		$('div.tellafriend .ajax-loader-big').hide().delay(1000);

		switch(data){
			case "0":
				$('div.tellafriend .error.not-sent').show();
				break;
			case "1":
				$('div.tellafriend .error.not-valid').show();
				break;
			case "10":
				$('div.tellafriend .confirmation').show();
				break;
		}
		
		
		$('div.tellafriend').delay(1500).fadeOut(0, function() {
			$('div.tellafriend .confirmation').hide();
			$('div.tellafriend .error').hide();
			$('div.tellafriend .form').show();
			$('#lightbox-shadow').hide();
		});
	});
		
}


function showPopup(popup_class) {
	
	$('.popup.' + popup_class).center().show();
	$('#lightbox-shadow').show();
	
}


function setCar() {
	
	var post = $('#car_select_form').serialize();
	
	$.post('xmlhttp/getCarInfo.php', post, function(data) {
		location.reload();
	});
	
}

function setCarInfo(type, value) {
	$.post('xmlhttp/setCarInfo.php', {'action':type, 'data':value}, function(data) {
		location.reload();
	});
}


function setZoom() {
	$('#productImageLargeTD img').mousemove(imageZoom);
	$('#productImageLargeTD img').mouseenter(function() { $('.zoom').show(); });
	$('#productImageLargeTD img').mouseout(function() { $('.zoom').hide(); });
}


function imageZoom(e) {
	var x = e.pageX - $(this).offset().left;
	var y = e.pageY - $(this).offset().top;
	
	var w = $(this).width();
	var h = $(this).height();
	
	var target_w = $('.zoom .image img:visible').width();
	var target_h = $('.zoom .image img:visible').height();
	
	var target_left = (x * (target_w/w));
	var target_top = (y * (target_h/h));
	
	if(target_left >= (target_w - $('.zoom .image').width())) {
		target_left = target_w - $('.zoom .image').width();
	}
	
	if(target_top >= (target_h - $('.zoom .image').height())) {
		target_top = target_h - $('.zoom .image').height();
	}
	
	$('.zoom .image img:visible').css('top', '-' + target_top + 'px');
	$('.zoom .image img:visible').css('left', '-' + target_left  + 'px');
}

function nemo(namn,foretag){
	location.href= 'mailto:'+namn+'@'+foretag;
	return false;
}


function changeProductMainPicture(img, imageID, productID, orgImg){
	$('.thumb').removeClass('active');

	$('#t_'+imageID).addClass('active');


	if(img.length > 5){
		$('#productImageLargeTD').html('<a href="javascript:;" onClick="showLightbox(\'' + imageID + '\')"> <img src="'+ img +'" /></a>')
		$('.zoom .image img').not('.hidden').addClass('hidden');
		$('#zoom_' + imageID).removeClass('hidden');
		setZoom();
		
		//for lightbox
		$('#lightbox-active').val(imageID);
	}
}

/************** WEBSHOP BUY **************/

function addToCart(){
	
	var data = $(this).formSerialize();

	var error = 0;
	//Check if size or color is as demand
	$('.prodSections select').each( function() {
		var value = $(this).val();

		if(value == 0){
			error = 1;
			$(this).addClass('error');
		}
	});

	$('.cart_message').center();

	// Inga fel, lägg i kundvagnen
	if(error == 0){

		$.post('xmlhttp/cartaction.php', data, function (data) {

			if (data != 'ERROR') {

				$('#confirm_cart').fadeIn("slow");
				$('.cart:eq(0)').html(data);
				$('.cart:eq(1) .basket').html($('.cart:eq(0) .basket').html());
				reload();

				setTimeout('$(\'#confirm_cart\').fadeOut("slow");', 8000);
			}
			else {	
				$('#confirm_cart_error').fadeIn("slow");
				setTimeout('$(\'#confirm_cart_error\').fadeOut("slow");', 8000);
			}
		});

	}else{
		$('#confirm_cart_error').fadeIn("slow");
		setTimeout('$(\'#confirm_cart_error\').fadeOut("slow");', 2000);
	}

	return false;
}


/************** WEBSHOP SETTINGS ***************/

function webshopView(viewType, catID) {
	$('#webshop-content').html('');
	$('#webshop-loader').show();
	if(viewType == "cols") {
		$('#list_icon img').show();
		$('#cols_icon img').hide();
	}

	if(viewType == "list") {
		$('#list_icon img').hide();
		$('#cols_icon img').show();
	}

	$.post('xmlhttp/webshopSettings.php', { view: viewType, category: catID }, function(data){
		$('#webshop-loader').hide();
		$('#webshop-content').html(data);
		reload();
	});
}

function webshopShowAll(catID) {
	$.post('xmlhttp/webshopSettings.php', {
		showAll: 1,
		category: catID
	}, function(data){
		$('#webshop-content').html(data);
		reload();
		
		$('#webshop-list .pagination .all .showAll').hide();
		$('#webshop-list .pagination .pages').hide();
		$('#webshop-list .pagination .prev').hide();
		$('#webshop-list .pagination .next').hide();
		$('#webshop-list .pagination .more_pages').hide();
		
		$('#webshop-list .pagination .showPerPage').show();
	});
}


function webshopShowPages(catID) {
	$.post('xmlhttp/webshopSettings.php', {
		category: catID
	}, function(data){
		$('#webshop-content').html(data);
		reload();
		
		$('#webshop-list .pagination .all .showAll').show();
		$('#webshop-list .pagination .pages').show();
		$('#webshop-list .pagination .prev').show();
		$('#webshop-list .pagination .next').show();
		$('#webshop-list .pagination .more_pages').show();
		
		$('#webshop-list .pagination .showPerPage').hide();
	});
}


function reload(){
	Cufon.refresh();
}

function clearCarInfo() {
	$.post('xmlhttp/getCarInfo.php', {'action':'del'}, function() {
		location.reload();	
	});
}

function getCarInfo(regnr) {

	$('div#left .regnr_info .space img.load_carinfo').show();
	$('div#left .regnr_info .space input[name="submit"]').hide();

	$.post('xmlhttp/getCarInfo.php', {'action':'add', 'regnr' : regnr}, function(data) {
		if(data != 'OK') {
			$('.regnr_error .space').html(data);
			$('.regnr_error').show().delay(2000).fadeOut('slow');

			$('div#left .regnr_info .space img.load_carinfo').hide();
			$('div#left .regnr_info .space input[name="submit"]').show();
		} else {
			location.reload();
		}
	});
}


function popup (url, name, width, height, status, menu, resizable) {
	var prop = 'toolbar=no,location=no,directories=no,scrollbars=yes,copyhistory=no,';
	prop += 'status='+ (status ? 'yes' : 'no') +',';
	prop += 'resizable='+ (resizable ? resizable : 'yes') +',';
	prop += 'menu='+ (menu ? 'yes' : 'no') +',';
	prop += 'width='+ (width ? width : 500) +',';
	prop += 'height='+ (height ? height : 400);

	var win = window.open(typeof(url) == 'string' ? url : url.href, name, prop);

	win.focus();
	
	return false;
}




//
//
//   Lightbox
//
////////////////////
function showLightbox(id) {
    var active = $('#lightbox-active').val();
    $('.lightbox_image').hide();
    $('#lightbox_image_'+active).show();
    
    $('#lightbox-shadow').height($(document).height()).show();
    
    
    $('#lightbox').show();
    setLightboxPosition();

    
}

function getNext() {
    var active = $('#lightbox-active').val();
    var list = $('#lightbox-image-list').val().split(',');
    var position = $.inArray(active, list);
    var next = ((position + 1) >= (list.length)) ? list[0] : list[position + 1];
    
    $('#lightbox_image_'+active).hide();
    $('#lightbox_image_'+next).show();
    
    $('#lightbox-active').val(next);    
    setLightboxPosition();
}

function getPrev() {
    var active = $('#lightbox-active').val();
    var list = $('#lightbox-image-list').val().split(',');
    var position = $.inArray(active, list);
    var prev = ((position - 1) == -1) ? list[list.length - 1] : list[position - 1];
    
    
    $('#lightbox_image_'+active).hide();
    $('#lightbox_image_'+prev).show();
    
    $('#lightbox-active').val(prev);    
    setLightboxPosition();
}

function setLightboxPosition() {
	//position lightbox
	var height = $(window).height();
	var width = $(window).width();
	
	var w = parseInt($('#lightbox').width()) - parseInt($('#lightbox .lightbox-left').width()) - parseInt($('#lightbox .lightbox-right').width());
	var h = parseInt($('#lightbox').height()) - parseInt($('#lightbox .upper').height());
	
	var min_height = 150;
	var min_width = 100;
	
	if(height - 80 > min_height && width - 80 > min_width) {
		$('#lightbox').css('width', width - 80);
		$('#lightbox').css('height', height - 80);
	}
	
	//check image resize
	img_original_w = $('#lightbox .image-holder img:visible').attr('w');
	img_original_h = $('#lightbox .image-holder img:visible').attr('h');
	
		
	if(w <= $('#lightbox .image-holder img:visible').width() || h <= $('#lightbox .image-holder img:visible').height()) {
		setByRatio(w, h, $('#lightbox .image-holder img:visible').width(), $('#lightbox .image-holder img:visible').height());
	} else {
		setByRatio(w, h, img_original_w, img_original_h);
	}
	
	$('#lightbox .lightbox-left').css('top', (parseInt($('#lightbox').height()) / 2)-($('#lightbox .lightbox-left').height() / 2));
	$('#lightbox .lightbox-right').css('top', (parseInt($('#lightbox').height()) / 2)-($('#lightbox .lightbox-right').height() / 2));
	$('#lightbox .lightbox-right').css('left', $('#lightbox').width() - $('#lightbox .lightbox-right').width());
	
	$('#lightbox .image-holder').css('top', ((h / 2)-($('#lightbox .image-holder').height() / 2)) + $('#lightbox .upper').height())
	$('#lightbox .image-holder').css('left', (w / 2)-(($('#lightbox .image-holder').width() / 2)) + $('#lightbox .lightbox-left').width())
}

function setByRatio(ow, oh, w, h) {
	var maxWidth = ow; // Max width for the image
        var maxHeight = oh;    // Max height for the image
        var ratio = 1;  // Used for aspect ratio
        var width = w;    // Current image width
        var height = h;  // Current image height

        // Check if the current width is larger than the max
        if(width > maxWidth){
            ratio = maxWidth / width;   // get ratio for scaling image
            $('#lightbox .image-holder img:visible').css("width", maxWidth); // Set new width
            $('#lightbox .image-holder img:visible').css("height", height * ratio);  // Scale height based on ratio
            height = height * ratio;    // Reset height to match scaled image
            width = width * ratio;    // Reset width to match scaled image
        }

        // Check if current height is larger than max
        if(height > maxHeight){
            ratio = maxHeight / height; // get ratio for scaling image
            $('#lightbox .image-holder img:visible').css("height", maxHeight);   // Set new height
            $('#lightbox .image-holder img:visible').css("width", width * ratio);    // Scale width based on ratio
            width = width * ratio;    // Reset width to match scaled image
        }

}
