var googleMap = {
	map: null,
	gdir: null,
	geocoder: null,

    init: function(){
        if($("#gmap").length == 0) return;
        
        if (GBrowserIsCompatible()) {
			// init map
			googleMap.map = new GMap2(document.getElementById("gmap"));
			googleMap.map.addControl( new GSmallMapControl());
            googleMap.map.addControl( new GMapTypeControl());


			// get coordinates of location
			googleMap.geocoder = new GClientGeocoder();

			googleMap.geocoder.getLatLng('Markt 7b Veenendaal Netherlands', function(point) { googleMap.setOnMarker(point) });

			// init directions
			googleMap.gdir = new GDirections(googleMap.map, document.getElementById("directions"));
			GEvent.addListener(googleMap.gdir, "load", googleMap.onGDirectionsLoad);
			GEvent.addListener(googleMap.gdir, "error", googleMap.handleErrors);
		}
    },
    setOnMarker: function(){
        if(!point) {
			// backup if geocoder fails
			var point = new GLatLng(52.024508,5.557022);
		}
		googleMap.map.setCenter(point, 15);
		
		var marker = new GMarker(point);
        googleMap.map.addOverlay(marker);

        var contents = "<div class='map-address'>Dames & Heren<br />Markt 7b<br />3901 DM Veenendaal<br />Telefoon: 0318-517875</div>";
        marker.openInfoWindowHtml(contents);
        
        GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml(contents);
        });
    }
}

var ajaxForm = {
    form : null,
    data : null,

    init : function(form){
        ajaxForm.form = form;
        ajaxForm.data = $(form).serialize();
    },
    sendForm : function(){
        $.ajax({
            type:   "post",
            data:   ajaxForm.data,  // Form variables
            dataType: "json",       // Expected response type
            url: "/quotes/add",
            success: function(response, status) {
                ajaxForm.handleCallback(response, status);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                ajaxForm.handleError(XMLHttpRequest, textStatus, errorThrown);
            }
        });
    },
    handleCallback : function(response, status){
        if (response.success === true){
            // Response was a success
            $("#responseSuccess").html(response.message).slideDown();
            $(ajaxForm.form).hide();
        }else{
             // Response contains errors
            $("#responseError").html(response.message).slideDown();
        }
        return false;
    },
    handleError : function(XMLHttpRequest, textStatus, errorThrown){
        var error = "<li>Er ging iets fout. Probeer het later nog eens!</li>";
        $("#responseError").html(error).slideDown();
    }
}

var orderList = {
    init: function(){
        /*$("#QuotePersonen").bind("change", function(e){
            $("#prices .personen span").html($(this).val());
            orderList.updatePrice();
            return false;
        });

        $("input[type='checkbox']").bind("change", function(e){
            var parent = $(this).parent();
            var price = $("h2 span", parent).html();
            price = price.replace("p.p.", "");
            price = price.replace("+", "");
            price = price.replace(",", ".");
            price = jQuery.trim(price);

            var text = $("h2", parent).text();
            text = text.split("+");
            text = jQuery.trim(text[0]);
            var pid = text.replace(/ /gi, "_");

            if($(this).attr('checked')){
                orderList.addProduct(pid, text, price);
            }else{
                orderList.removeProduct(pid);
            }
            return false;
        });*/
    },
    addProduct: function(pid, text, price){
        $("#prices li.standard").after("<li id='"+pid+"'>"+text+"<span>"+price+"</span></li>");
        orderList.updatePrice();
    },
    removeProduct: function(pid){
        $("#"+pid).remove();
        orderList.updatePrice();
    },
    updatePrice: function(){
        var start_tarief = $("#prices li.standard span").text();
        start_tarief = start_tarief.replace("€", "");
        start_tarief = parseFloat(start_tarief);

        var total_persons = parseFloat($("#prices li.personen span").text());
        var prices = 0;
        var total_price = 0;
        
        jQuery.each($("#prices li"), function(i, val) {
            if(!$(this).hasClass("personen") && !$(this).hasClass("standard")){
                var price = $("span", this).html();
                price = price.replace("€", "");
                prices += parseFloat(price);
            }
        });

        total_price = (prices * total_persons) + (start_tarief * total_persons);
        $("#total li span").html("€"+total_price);
    }
}

var gallery = {
   active: 1,
   init: function(){
      if($("#gallery-images").length == 0) return;
      
      gallery.buildPaging();
      $("#gallery-paging li:first").addClass('active');

      $("#gallery-paging li").click(function(ev){
         var newActive = $(this).attr('id').split('_');
         gallery.showPhoto(newActive[1]);
         gallery.updatePaging();
         ev.preventDefault();
      })
   },
   buildPaging: function(){
      $("#gallery-images").after("<ul id=\"gallery-paging\"></ul>");

      jQuery.each($("#gallery-images li"), function(i, val) {
         $("#gallery-paging").append("<li id='img_"+(i+1)+"'><a href='#'>"+(i+1)+"</a></li>")
      });
   },
   showPhoto: function(newActive){
      $("#gallery-images li#image_"+newActive).show();
      $("#gallery-images li#image_"+gallery.active).hide();
      gallery.active = newActive;
   },
   updatePaging: function(){
      $("#gallery-paging li").removeClass('active');
      $("#gallery-paging li#img_"+gallery.active).addClass('active');
   }
}

$(document).ready(function(){
    $("li.sub ul").hide();

    //expandables.init(".expandable");
    googleMap.init();
    gallery.init();
    
    if($("#QuoteAddForm").length > 0){
        orderList.init();
    }

    if($("body#particulieren").length == 1){
        $("body#particulieren li.particulieren ul").show();
    }
    if($("body#bedrijven").length == 1){
        $("body#bedrijven li.bedrijven ul").show();
    }
    
    $(".particulieren a:first").click(function(){
            $("li.particulieren ul").slideDown();
            $("li.bedrijven ul").slideUp();
            return false;
        });

    $(".bedrijven a:first").click(function(){
        $("li.bedrijven ul").slideDown();
        $("li.particulieren ul").slideUp();
        return false;
    });

    var quoteAddForm = $("#QuoteAddForm").validate({
		rules: {
			'data[Quote][naam]' : "required",
            'data[Quote][telefoon]' : "required",
            'data[Quote][email]': {
                required: true,
                email: true
            }
		},
		messages: {
			'data[Quote][naam]' : "Verplicht veld!",
            'data[Quote][telefoon]' : "Verplicht veld!",
            'data[Quote][email]' : {
                required: "Verplicht veld!",
                email: "Ongeldige email!"
            }
		}
    });

    if($(".datepick").length > 0){
        $(".datepick").datepicker({
            showOn: "both",
            buttonImage: "/img/calender_icon_large.gif",
            buttonImageOnly: true,
            dateFormat: 'dd-mm-yy'
        });
    }

    if($("#tabs").length > 0){
        var $tabs = $("#tabs").tabs();
        $('.submit-order').hide();

        $('#btn_stap2').click(function(e) {
            if($("#QuoteAddForm").valid()){
                $tabs.tabs('select', 1);
            }else{
                $tabs.tabs('select', 0);
            }
            e.preventDefault();
        });

        $('#btn_stap3').click(function(e) {
            if($("#QuoteAddForm").valid()){
                $tabs.tabs('select', 2);
            }else{
                $tabs.tabs('select', 0);
            }
            e.preventDefault();
        });

        $('#btn_stap4').click(function(e) {
            if($("#QuoteAddForm").valid()){
                $("#QuoteAddForm").submit();
                $tabs.tabs('select', 0);
            }else{
                $tabs.tabs('select', 0);
            }
            e.preventDefault();
        });
    }
});
