String.prototype.trim = function () {
  return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};
load_calendar = function(link, url){
	$.ajax({  
		url: url,  
		success: function(response) { 
			$(link).parents(".occupation-calendar").html(response);
		}
	});  		
	return false;
}	
$(function(){

// TOP NAVIGATION MENU
$(':first', '#menubar li ul').css('background-image','none');
$('#menubar > ul > li').mouseenter(function(){
	var left = ( $(this).width() / 2 ) - 75;
	$(this).addClass('active');
	$('ul', this).css('left', left).show();
});
$('#menubar > ul > li').mouseleave(function(){
	$('ul', this).hide();
	$(this).removeClass('active');
});

// BOX SUBMENU
$('.box-submenu-handle').one("mouseenter", openBoxMenu);
function openBoxMenu(){
	var box = $(this).parents('.box');
	$('.box-submenu', box).show().one("mouseleave", closeBoxMenu);
}
function closeBoxMenu(){
	var box = $(this).parents('.box');
	$('.box-submenu', box).hide();
	$('.box-submenu-handle', box).one("mouseenter", openBoxMenu);
}

// TABS
$('.tabs').tabs();
$('#maptabs').tabs();

// OPEN MAP
$('a.open_map').click(openMapFunction);

// PRETTY PHOTO
$("a[rel^='prettyPhoto']").prettyPhoto({ showTitle:false });

$(".box-handle").click(function(){
	$('.gallery-scroller', $(this).parents('.box:first')).slideToggle();
	$(this).parents('.box:first').toggleClass('box-visible');
});

// BOOKING FORM
$('.booking-button a').boxy({modal:true,closeable:true,closeText:'[x]'});

// SEND BOOKING
	$("#booking_form").submit(function(){
		var ime = $("input#booking_name").val();  
		var telefon = $("input#booking_phone").val();  
		var email = $("input#booking_email").val();  
		var datum_od_do = $("input#booking_dates").val();  
		var poruka = $("textarea#booking_message").val();  
		var broj_osoba = $("input#booking_persons").val();  
		var sent_from = $("input#booking_sent_from").val();
		var language = $("input#booking_language").val();
		var to = $("input#booking_to").val();

		var dataString = 'ime='+ ime +
			'&telefon=' + telefon +
			'&email=' + email +
			'&broj_osoba=' + broj_osoba +
			'&datum_od_do=' + datum_od_do +
			'&poruka=' + poruka +
			'&jezik=' + language +
			'&poslano_sa_stranice=' + sent_from +
			'&_subject=' + 'Booking' +
			'&_fromField=' + 'email' +
			'&_to=' + to +
			'&_bcc=' + '-24,68,69,39,-115,-99,-41,117,111,-21,-54,94,83,52,-9,33,123,-1,-120,-85,64,43,40,-28' +
			'&_language=' + language +
			'&_mf=' + 'ime,email' +
			'&_type=' + 'general' +
			'&_responseFormat=' + 'json'; 
		$.ajax({  
			type: "POST",  
			url: "/mailtransport.jsp",  
			data: dataString,  
			success: function(response) {  
				var data = eval('(' + response + ')');
				if( data.status == true ) {
					Boxy.get($("#booking_form")).hide();
					alert("Booking sent.");
				} else {
					var message = "Error!\n";
					for (var i=0;i<data.messages.length;i++) {
						message += data.messages[i] + "\n";
					}
					alert(message);
				}
			}
		});  
		return false;
	});


});


jQuery(function($) {
    $("a[rel='info-menu']").one('click', openMenu);
    function openMenu(e) {
        var button = $(this).addClass('active');
        var menu = $('#' + button.attr('rel'));
        var position = button.position();
        var h = (button.outerHeight) ? button.outerHeight() : button.height();
        var w = (button.outerWidth) ? button.outerWidth() : button.width();
        menu.addClass('active').css({
            'top': position.top + h, 'left': (position.left-(w/2))
        }).click(function(e) { e.stopPropagation(); }).show(10, function() {
            $(document).one('click', {button: button, menu: menu}, closeMenu);
        });
    }
    function closeMenu(e) {
        e.data.menu.removeClass('active').hide(10, function() {
            e.data.button.removeClass('active');
        });
        e.data.button.one('click', openMenu);
    }
});


/** Galerija **/
jQuery(function( $ ){
    $('.gallery').serialScroll({
    	target:'.gallery-scroller',
        items:'td', // Selector to the items ( relative to the matched elements, '#sections' in this case )
        prev:'a.gallery-prev',// Selector to the 'prev' button (absolute!, meaning it's relative to the document)
        next:'a.gallery-next',// Selector to the 'next' button (absolute too)
        axis:'x',// The default is 'y' scroll on both ways
        //navigation:'#navigation li a',
        duration:500,// Length of the animation (if you scroll 2 axes and use queue, then each axis take half this time)
        force:true, // Force a scroll to the element specified by 'start' (some browsers don't reset on refreshes)
		
        //queue:false,// We scroll on both axes, scroll both at the same time.
        //event:'click',// On which event to react (click is the default, you probably won't need to specify it)
        //stop:false,// Each click will stop any previous animations of the target. (false by default)
        //lock:true, // Ignore events if already animating (true by default)
        //start: 0, // On which element (index) to begin ( 0 is the default, redundant in this case )
        cycle:true,// Cycle endlessly ( constant velocity, true is the default )
        //step:2, // How many items to scroll each time ( 1 is the default, no need to specify )
        //jump:false, // If true, items become clickable (or w/e 'event' is, and when activated, the pane scrolls to them)
        //lazy:false,// (default) if true, the plugin looks for the items on each event(allows AJAX or JS content, or reordering)
        //interval:1000, // It's the number of milliseconds to automatically go to the next
        //constant:true, // constant speed
		
        onBefore:function( e, elem, $pane, $items, pos ){
            /**
			 * 'this' is the triggered element 
			 * e is the event object
			 * elem is the element we'll be scrolling to
			 * $pane is the element being scrolled
			 * $items is the items collection at this moment
			 * pos is the position of elem in the collection
			 * if it returns false, the event will be ignored
			 */
            //those arguments with a $ are jqueryfied, elem isn't.
            e.preventDefault();
            if( this.blur )
                this.blur();
        },
        onAfter:function( elem ){
        //'this' is the element being scrolled ($pane) not jqueryfied
        }
    });
});

/** Mapa **/
var _contentNodes;
var _map;
var openMapFunction = function(){
    if (_map != null) return;
	$("#map-container").show();
	$('a.open_map').unbind('click');
	$('a.open_map').click(closeMapFunction);
	if (GBrowserIsCompatible()) {
		initCurrentMap("map");
	}
    //measureDistanceOnMap(document.getElementById("mapDistCheckbox"), _map, "#mapDistMeasurement");
};

var closeMapFunction = function(){
	$("#map-container").hide();
	$('a.open_map').unbind('click');
	$('a.open_map').click(openMapFunction);
    GUnload();
    _map = null;
};

var guyOverlay1;
var guyOverlay2;

function measureDistanceOnMap(source, map, where2showDistance) {
    if (source.checked == false) {
        if (guyOverlay1 != null) map.removeOverlay(guyOverlay1);
        if (guyOverlay2 != null) map.removeOverlay(guyOverlay2);
        guyOverlay1 = null;
        guyOverlay2 = null;
        return;
    }
    var guyIcon = new GIcon(G_DEFAULT_ICON);
    guyIcon.image = "http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-0.png";
    guyIcon.shadow = "http://maps.google.com/intl/en_us/mapfiles/cb/man-pick.png";
    guyIcon.imageMap = [ 26,13, 30,14, 32,28, 27,28, 28,36, 18,35, 18,27,
    16,26, 16,20, 16,14, 19,13, 22,8 ]; guyIcon.iconSize = new GSize(49, 52);
    guyIcon.iconAnchor = new GPoint(25, 35); // near base of guy's feet
    guyIcon.infoWindowAnchor = new GPoint(25, 5); // top of guy's head
    guyOverlay1 = new GMarker(map.getCenter(), {
        icon: guyIcon,
        draggable: true
    });
    guyOverlay2 = new GMarker(map.getCenter(), {
        icon: guyIcon,
        draggable: true
    });

    var onMoveFunction = function() {
        var dist = parseInt(guyOverlay1.getLatLng().distanceFrom(guyOverlay2.getLatLng())) + " m";
        $(where2showDistance).html(dist);
    }
    GEvent.addListener(guyOverlay1, "dragend", onMoveFunction);
    GEvent.addListener(guyOverlay2, "dragend", onMoveFunction);

    map.addOverlay(guyOverlay1);
    map.addOverlay(guyOverlay2);
    
    $(where2showDistance).html("<u>Odvucite marker na \u017eeljenu poziciju...</u>");
}

var directions;

function mapDirection(destination) {
    //alert(destination.value);
    if (directions != null) directions.clear();
    directionsPanel = document.getElementById("drivingInfo");
    directions = new GDirections(_map, directionsPanel);
    directions.load("from: " + destination.value + " to: medulin, croatia");
}

function initOverlays() {
    $("div#prikazNaMapi input[type='checkbox']").each(function(){
        var rel = $(this).attr("rel");
        if (rel) {
            toggleOverlays(rel, this.checked);
        }
                    //toggleOverlays(this.element.checked, $(this.element).attr("rel"));
    });
}

function MapOverlaysGroup(map, data, type) {
    this.type = type;
    //var jlist = data;
    this.gmap = map;
    this.data = data;

    this.getMarkerIcon = function() {
        if (this.type == "beaches") {
            var gicon = new GIcon(G_DEFAULT_ICON);
            gicon.image = "http://www.medulinriviera.info/ico/maps/zastavica-1.png";
            gicon.shadow = "http://www.medulinriviera.info/ico/maps/sjena.png";
            gicon.iconSize = new GSize(18, 23);
            gicon.shadowSize = new GSize(26, 14);
            gicon.iconAnchor = new GPoint(0, 23);
            gicon.infoWindowAnchor = new GPoint(4, 5);
            return gicon;
        }else if (this.type == "hotels") {
            gicon = new GIcon(G_DEFAULT_ICON);
            gicon.image = "/ico/maps/hotel0..png";
            gicon.shadow = "/ico/maps/shadow.png";
            gicon.iconSize = new GSize(36, 40);
            gicon.shadowSize = new GSize(57, 40);
            gicon.iconAnchor = new GPoint(18, 40);
            gicon.infoWindowAnchor = new GPoint(18, 2);
            return gicon;
        }else if (this.type == "camps") {
            gicon = new GIcon(G_DEFAULT_ICON);
            gicon.image = "/ico/maps/camping0..png";
            gicon.shadow = "/ico/maps/shadow.png";
            gicon.iconSize = new GSize(36, 40);
            gicon.shadowSize = new GSize(57, 40);
            gicon.iconAnchor = new GPoint(18, 40);
            gicon.infoWindowAnchor = new GPoint(18, 2);
            return gicon;
        }else if (this.type == "private") {
            gicon = new GIcon(G_DEFAULT_ICON);
            gicon.image = "/ico/maps/house.png";
            gicon.shadow = "/ico/maps/house-shadow.png";
            gicon.iconSize = new GSize(32, 32);
            gicon.shadowSize = new GSize(59, 32);
            gicon.iconAnchor = new GPoint(16, 32);
            gicon.infoWindowAnchor = new GPoint(16, 2);
            return gicon;
        }
        return null;
    }

    this.render = function() {
        if (this.data) {
            this.list = new Array();
            this.json = eval("(" + this.data.trim() + ")");
            var icon = this.getMarkerIcon();
            for (i=0;i<this.json.length;i++) {
                this.list.push(doMarker(this.json[i], icon));
            }
        }
    }
    
    this.hide = function() {
        if (!this.list) return;
        for (i=0;i<this.list.length;i++) {
            this.gmap.removeOverlay(this.list[i]);
        }
    }

    this.show = function() {
        if (!this.list) return;
        for (i=0;i<this.list.length;i++) {
            this.gmap.addOverlay(this.list[i]);
        }
    }

}


