/* creates expandables */
var expandables = {
    current: null,
    
	init: function(container){
		if($(container).length == 0) return;

        $(container+' h3').addClass('closed');
        $(container+' h3').next().hide();

        expandables.current = $(container+' h3:first');
        $(container+' h3:first').removeClass('closed');
        $(container+' h3:first').next().show();

        $(container+' h3').click(
            function() {
                $(expandables.current).toggleClass("closed");
                $(expandables.current).next().slideToggle('medium');

                $(this).toggleClass("closed");
                $(this).next().slideToggle('medium');

                expandables.current = $(this);
            }
        );
	}
}

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());

			// get coordinates of location
			googleMap.geocoder = new GClientGeocoder();

			googleMap.geocoder.getLatLng('Veenslag 5 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.0285216, 5.5326812);
		}
		googleMap.map.setCenter(point, 15);
		
		var marker = new GMarker(point);
        googleMap.map.addOverlay(marker);
        var contents = "<div class='map-address'>Keurslagerij Harzevoort<br />Veenslag 5<br />3905 SK Veenendaal<br />0318-506033</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 printObj = {
	addPrint: function(targetElm){
		var targetURL = $(targetElm).attr("href");
		$(targetElm).click(function(){
			printObj.printWindow(targetURL, 500, 700);
			return false;
		});
	},

	printWindow: function(targetURL, w, h, pagetitle, pType) {
		printDocContents='<HTML>\n';
		printDocContents+='<HEAD>\n';
		printDocContents+='<TITLE>New Document</TITLE>\n';

        printDocContents+='<link rel="stylesheet" type="text/css" href="/css/reset.css" />\n';
		printDocContents+='<link rel="stylesheet" type="text/css" href="/css/sIFR-print.css" />\n';
        printDocContents+='<link rel="stylesheet" type="text/css" href="/css/styles.css" />\n';
        printDocContents+='<link rel="stylesheet" type="text/css" href="/css/print.css" />\n';

		printDocContents+='</HEAD>\n';
		printDocContents+='<BODY>\n';
		printDocContents+=$("#content").html()+'\n';
		printDocContents+='</BODY>\n';
		printDocContents+='</HTML>';

		newwindow=window.open(null, '' ,'height=' + w + ',width=' + h + ',toolbar=no,scrollbars=yes');
		newdocument=newwindow.document;
		newdocument.write(printDocContents);
		newdocument.close();

		newwindow.focus();
		newwindow.print();
	}
}

$(document).ready(function(){
    expandables.init(".expandable");
    googleMap.init();
    printObj.addPrint(".print");

    var QuoteQuickAddForm = $("#QuoteQuickAddForm").validate({
		rules: {
			'data[Quote][naam]' : "required",
            'data[Quote][personen]' : "required",
            'data[Quote][aanvraag]' : "required",
            'data[Quote][datum]' : "required",
            'data[Quote][email]': {
                required: true,
                email: true
            }
		},
		messages: {
			'data[Quote][naam]' : "Verplicht veld!",
            'data[Quote][personen]' : "Verplicht veld!",
            'data[Quote][aanvraag]' : "Verplicht veld!",
            'data[Quote][datum]' : "Verplicht veld!",
            'data[Quote][email]' : {
                required: "Verplicht veld!",
                email: "Ongeldige email!"
            }
		},
        submitHandler: function() {
            ajaxForm.init("#QuoteQuickAddForm");
            ajaxForm.sendForm();
        }
    });

    var quoteAddForm = $("#QuoteAddForm").validate({
		rules: {
			'data[Quote][naam]' : "required",
            'data[Quote][personen]' : "required",
            'data[Quote][datum]' : "required",
            'data[Quote][email]': {
                required: true,
                email: true
            }
		},
		messages: {
			'data[Quote][naam]' : "Verplicht veld!",
            'data[Quote][personen]' : "Verplicht veld!",
            'data[Quote][datum]' : "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();
        $('#volgende-stap').click(function() {
            $("#QuoteAddForm").submit();
            if(quoteAddForm.element($("#QuotePersonen")) == true && quoteAddForm.element($("#QuoteDatum")) == true){
                $tabs.tabs('select', 1);
            }
            return false;
        });
    }

    $(function() {
		$('a.lightbox').lightBox({
			overlayBgColor:'#fff',
			containerBorderSize:0
		});
	});

    $("#price-slider").slider({
        orientation: 'horizontal',
        min: 10,
        max: 250,
        step: 1,
        value: 1,
        slide: function(event, ui) {
            $("#price").html(ui.value);
            $("#QuoteBudget").val(ui.value);
        }
    });
   
    $('.js-dependent').removeClass('js-dependent');
});
