/* 

#####################################

		PARALLAX SCROLLING 

#####################################


//////////Stamppotje Instinct///////////


(c) Milan Jansen, Gradient Media 2011 

*/

function init(){
	if(browser == 'desktop'){
		pxs_init();
	}
	else{
		$('#static_bgs').css('height',$('body').height()+'px');
	}
	$('#logo').mouseenter(function(){
		$(this).fadeTo(200,0.8);
	})
	$('#logo').mouseleave(function(){
		$(this).fadeTo(200,1);
	})
	$('#cart-trigger').mouseenter(function(){
		$('#add-product-popup').hide(); 
		$('#header-fill').fadeOut(200);	
		$('#cart-list').fadeIn(200);
	})
	
	$('#cart-list').mouseleave(function(){
		$('#header-fill').fadeIn(200);	
		$('#cart-list').fadeOut(200);
	})
	var maxProduct = 0;
	$.ajax({
        url: '../shop/index.php?route=checkout/cart/update',
        dataType: 'json',
        success: function(json) {
            updateCart(json)
        }
    })
    ajaxForm();
	doValTag();
}

$(window).resize(function(){
    Wheight = $(window).height();
})

function pxs_init(){
    $('.speed1, .speed2, .content-scroll').each(function(){
        this.initialTop  = parseInt($(this).css('top'));
    });
    speed2Obj = $('.speed2');
    speed1Obj = $('.speed1');
    Wheight = $(window).height();
    $(window).scroll(function(e){
        scrollTop = $(window).scrollTop()
        fixScroll($('.content-scroll')[0],1);
        speed2Obj.each(function(){
            fixScroll(this,1.308);      
        })
	    speed1Obj.each(function(){
	        fixScroll(this,2);
	    })
	    $('#cart').css('bottom', - ($('body').height() - (scrollTop+Wheight)) / 1.4 + 'px');
	    $('#madeby').css('bottom', - ($('body').height() - (scrollTop+Wheight)) / 1.4 + 'px');
	    //}
    });
}

function fixScroll(obj, speed){
    if(speed == 1){
        topVal = Wheight - (scrollTop+Wheight - obj.initialTop);
        $(obj).css('top',topVal + 'px');
    }
    else{   
        theval = Wheight - (scrollTop+Wheight - obj.initialTop)
        theTop = theval - ((theval - obj.initialTop)/speed);
        $(obj).css('top',theTop+'px'); 
    }
}

function setY(obj,yval){
    if($.browser.msie){
        $(obj).css('background-position-y',yval+'px');
    }else{
        pos = $(obj).css('background-position');
        xVal = pos.substr(0,pos.indexOf(' '));
        $(obj).css('background-position',xVal+' '+yval);
    }
}

 
// Copied from opencarts common.js
function addToCart(product_id, max) {

	if( maxProduct >= maxProducts && max == 1 ){
		openPopup('max-product-popup');
	} else {
		$.ajax({
			url: '../shop/index.php?route=checkout/cart/update',
			type: 'post',
			data: $('#product-'+product_id+' input[type=\'checkbox\']:checked, #product-'+product_id+' input[type=\'hidden\']'),
			dataType: 'json',
			success: function(json) {
				updateCart(json);
			$('#add-product-popup').stop();
			$('#add-product-popup').fadeIn();
			$('#add-product-popup').delay(5000).fadeOut('slow'); 
			}
		});
	}
}


function QuickAddToCart(product_id) {
	$.ajax({
		url: '../shop/index.php?route=checkout/cart/update',
		type: 'post',
        data: 'product_id=' + product_id,
		dataType: 'json',
		success: function(json) {
            updateCart(json);
			$('#add-product-popup').stop();
			$('#add-product-popup').show();
			$('#add-product-popup').delay(5000).fadeOut('slow');    
		}
	});
}

function removeCart(key) {
    $.ajax({
        url: '../shop/index.php?route=checkout/cart/update',
        type: 'post',
        data: 'remove=' + key,
        dataType: 'json',
        success: function(json) {      
            updateCart(json)       
        }
    });
}

function updateCart(json){

	if (json['output']) {
	    $('#cart-list')[0].innerHTML = json['output'].replace(/catalog\/view\/theme\/default\/image\/close.png/g,'img/remove.png');
	    $('#cart-list').find('.name').find('a').each(function(){
	    	this.setAttribute('href','javascript:void(0)');
	    });
	    $('.cart').wrap("<div class='overflow'></div>");
	    $('#cart-overview')[0].innerHTML = json['output'].replace(/catalog\/view\/theme\/default\/image\/close.png/g,'img/remove.png');
	    $('#cart-overview').find('.name').find('a').each(function(){
	    	this.setAttribute('href','javascript:void(0)');
	    });
		$('#cart-overview').find('table.cart').prepend('<tr><th>mijn bestelling</th><th>hoeveelheid</th><th>per stuk</th><th>totaal</th><th>verwijder</td></tr>');
	    $('#cart-overview').find('.image').remove();		    		
		$('#cart-overview').find('td.total').each(function(){
			$(this).before($(this).clone())
			$(this).prev().removeClass('total').addClass('perpiece');
			PerPiece = (parseFloat($(this).parent().find('.perpiece').html().replace(',','.').substr(1)) / $(this).parent().find('.quantity').html().replace('&nbsp;','').substr(1));
			
			PerPiece = '&euro;'+PerPiece;
			PerPiece = PerPiece.replace('.',',');
			
			if(PerPiece.indexOf(',') == -1){
				PerPiece = PerPiece+',00';
			}
			else if(PerPiece.substr(PerPiece.indexOf(',')).length == 2){
				PerPiece = PerPiece+'0';
			}
			
			$(this).parent().find('.perpiece').html(PerPiece);
		})
	}

	count = parseInt(json['total'].substr(0,2));
	$('.cart .count').html(count);

	if(count > 0){
		$('.cart').removeClass('empty');
		$('.no-items').hide();
		if(json['total_price'] >= minPrice){
			$(".checkout").show();
			$(".cart-less").hide();
		} else {
			$('#cart-list').append('<div class="cart-less">de minimale besteding is &euro; 10,-.</div> ');
			$(".checkout").hide();
			$(".cart-less").show();
		}
	} else {
		$('.cart').addClass('empty');	
		$('.no-items').show();
		$('#cart-overview')[0].innerHTML = '';	
	}

	// set maxProduct
	maxProduct = json['products_with_options'];
	//maxProduct = 0;
	
	
}

function openPopup(id){

	$('body').append('<div id="overlay" onclick="closePopup(\'' + id + '\')"></div>');
	$('body').append('<div id="popup"></div>');
	
	$('#popup').append($('#'+id));
	$('#popup').append("<a href='javascript:void(0)' id='popupclose' onclick=\"closePopup('"+id+"')\"><img src='"+source+"img/close.png' /></a>");
	
	$('#popup').css('width',$('#'+id).width());
	$('#popup').css('height',$('#'+id).height());

	$('#popup').css('margin-top', -(($('#popup').height()+40)/2)+'px');
	$('#popup').css('margin-left', -(($('#popup').width()+40)/2)+'px');
	
	$('#'+id).show();
	
	$('#popup').find('iframe').each(function(){
		this.src = this.src;
	})

}

function closePopup(id){
	$('body').append($('#'+id));
	$('#'+id).hide();
	$('#overlay').remove();
	$('#popup').remove();
}

function ajaxForm(){
    $('form').each(function(){
        if(this.getAttribute('action') == '#ajax'){
                       
            $(this).submit(function(event){
                error = false;
                radioError = false;
                    
                $(this).find('input[type=text],textarea').each(function(){
                    if(this.value == '' && $(this).hasClass('required')){
                        error = true;
                        $(this).addClass('error');
                        $(this).focus(function(){
                            $(this).removeClass('error');
                        })
                    }                
                });

				if( $("#general").attr('checked') == 'checked' || $("#deliver").attr('checked') == 'checked' ){
					$("#radio_error").hide();
				} else {
					$("#radio_error").show();
				}

                if(!error){
                    jQuery.post(source+'ajax/mail_form.php', $(this).find('input,textarea').serializeArray(),(function(form){
                        return function(data){
                            if(data == 'succes'){
                                $(form).find('.form_entry').hide();
                                $(form).find('.succes').show();
                            }
                        }
                    }(this)))
                }  
                event.preventDefault();
            })           
        }else{
            
            
            $(this).submit(function(event){
                error = false;
                    
                $(this).find('input,textarea').each(function(){
                    if(this.value == '' && $(this).hasClass('required')){
                        error = true;
                        $(this).addClass('error');
                        $(this).focus(function(){
                            $(this).removeClass('error');
                        })
                    }                
                })
                if(!error){
                    this.submit();
                }  
                event.preventDefault();
            })
            
        }      
    })    
}

function checkZipcode(){

	var zip = $('#zip-code').val();
	
    $.ajax({
        url: '../shop/zipcode.php',
        type: 'post',
        data: 'mode=check&zipcode=' + zip,
        dataType: 'json',
        success: function(json) {      
            if(json.result.code == '1' ){
				openPopup('zipcode-popup-true');
			} else {
				openPopup('zipcode-popup-false');
			}
        }
    });

}

function doValTag(){
    origvalue = new Array
    onch = $('.valuetag')
    onch.each(function(){
        if(this.tagName == 'INPUT' || this.tagName == 'TEXTAREA'){
            this.origval = this.value;
            this.onfocus = function(){
                if(this.value == this.origval){
                    this.value = '';
                    $(this).addClass('active')
                }
            }
            this.onblur = function(){
                if(this.value == ''){
                    this.value = this.origval;
                    $(this).removeClass('active')
                }
            }
        }
    })
}

	
function initialize() {
  var myOptions = {
    zoom: 12,
    center: new google.maps.LatLng(52.361083,4.864883),
    //center: new google.maps.LatLng(52.371125,4.870425),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

  setMarkers(map, stores);
}

/**
 * Data for the markers consisting of a name, a LatLng and a zIndex for
 * the order in which these markers should display on top of each
 * other.
 */
var stores = [
	['<strong>Stamppotje</strong><br />Amstelveenseweg 218', 52.3512337, 4.8562523, 6],
	['<strong>Stamppotje</strong><br />Bilderdijkstraat 46', 52.3711246, 4.8704251, 4],
    ['<strong>Stamppotje</strong><br />Eerste van der helstraat 27', 52.3558715, 4.8930452, 3],
	['<strong>Stamppotje</strong><br />Prinsengracht 292', 52.3704126, 4.8824358, 5],
    ['<strong>Stamppotje</strong><br />Buitenveldertselaan 84', 52.3269741, 4.8685623, 2],
    ['<strong>Stamppotje</strong><br />Haarlemmerdijk 14', 52.381849, 4.888736, 1],
    ['<strong>Stamppotje</strong><br />Kleine houtstraat 5 Zwart', 52.3794651, 4.6370451, 7]
];

function setMarkers(map, locations) {
	var image = new google.maps.MarkerImage('img/marker.png',
	// This marker is 20 pixels wide by 32 pixels tall.
	new google.maps.Size(40, 65),
	// The origin for this image is 0,0.
	new google.maps.Point(0,0),
	// The anchor for this image is the base of the flagpole at 0,32.
	new google.maps.Point(20, 52));

	var infowindow = null;
	/* now inside your initialise function */
	infowindow = new google.maps.InfoWindow({
	content: "Laden..."
	});


	for (var i = 0; i < locations.length; i++) {
		var store = locations[i];
		var myLatLng = new google.maps.LatLng(store[1], store[2]);

		var marker = new google.maps.Marker({
			position: myLatLng,
			map: map,
			icon: image,
			zIndex: store[3],
			html: store[0]
		});		

		google.maps.event.addListener(marker, 'click', function () {
			// where I have added .html to the marker object.
			infowindow.setContent('<div style="height: 60px">' + this.html + '</div>');
			infowindow.open(map, this);
		});
	}
}
