String.prototype.trim = function () {
  return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};

function openBoxyFrame(url, width, height) {
	new Boxy("<iframe src='" + url + "' width='" + width + "' height='" + height + "'></iframe>",
                {title: "Map", closeable: true});
}

$(function(){
	load_calendar = function(link, url){
		$.ajax({  
			url: url,  
			success: function(response) {  
				$(link).parents(".occupation-calendar").html(response);
			}
		});  		
		return false;
	}	
	/**
	* PrettyPhoto
	*/
	
	$("a[rel^='prettyPhoto']").prettyPhoto({
		showTitle:false
	});

	/**
	* Photo gallery
	*/
	
	$("a.gallery_link").click(function(){
		loadGallery($(this).attr("href"));
		return false;
	});
	
	/**
	* Boxy
	*/
	
	$(function(){
		$('.boxy').boxy({
			modal: true,
			closeText: '[x]'
		});
	});
	
    /**
	* Submenu
	*/
	
    // calculate submenu positions
    $('#topnav td a').each(
        function(){
            var current_link = $(this);
            var submenu = $('#' + $(this).parent().attr('id') + '_submenu');
            var position = parseInt(($(current_link).position().left + ($(current_link).outerWidth()/2)) - ($(submenu).outerWidth()/2));
            if( position < 0 ) {
                position = 0;
            }
            else if( position > ( $('#topnav').outerWidth() - $(submenu).outerWidth() ) ) {
                position = $('#topnav').outerWidth() - $(submenu).outerWidth();
            }
            $(submenu).css('left',position+'px');
			
        }
        );
    // show/hide sumbenu
    $('#topnav td a').mouseenter(
        function(){
            $('#' + $(this).parent().attr('id') + '_submenu').css('display','block');
            if( $('#' + $(this).parent().attr('id') + '_submenu').attr('id') ) {
                $(this).addClass('selected');
            }
        }
        ).mouseleave(
        function(){
            var current_link = $(this);
            $('#' + $(this).parent().attr('id') + '_submenu').mouseenter(
                function(){
                    $(this).css('display','block');
                    $(current_link).addClass('selected');
                }
                ).mouseleave(
                function(){
                    $(this).animate({
                        opacity: 1.0
                    }, 3000).css('display','none');
                    $(current_link).removeClass('selected');
                }
                )
            $('#' + $(this).parent().attr('id') + '_submenu').css('display','none');
            $(this).removeClass('selected');
        }
        );

    /**
	* ACCORDION
	*/
	if( $("#content_area").css('background-image') != 'none' ) {
	    acc_height = $('#content_area').outerHeight();
	    $('#accordion_wrapper').siblings().each(function(){
	        acc_height -= $(this).outerHeight();
	    });
		if( acc_height < 400 ) acc_height = 400;
	    $('#accordion_wrapper').height(acc_height);
	    var acc = $('#accordion').accordion({
	    autoHeight: true,
	    fillSpace: true,
		header: 'a.panel-header',
		active: '#default-acc-panel'
	});
	} else {
		// collapsible panels
		$('#collapsible-panels .panel-header').click(function() {
			$(this).next().slideToggle('slow');
			$(this).toggleClass('ui-state-active');
			return false;
		}).prepend('<span class="ui-icon"></span>').next().hide();
		$('#collapsible-panels .active-panel').toggleClass('ui-state-active').next().show();

	    /*var acc = $('#accordion').accordion({
	    	fillSpace: true,
			header: 'a.panel-header'
		});*/
	}	
    /*acc.bind('accordionchange', function(event, ui) {
      //alert(ui.newHeader); // jQuery object, activated header
      //ui.oldHeader // jQuery object, previous header
      //ui.newContent // jQuery object, activated content
      //ui.oldContent // jQuery object, previous content
    });*/
	
	
	
    /**
	* MAP
	*/
    // map close handle
    $('.close_map_handle').click(closeMapFunction);
    
    $('.open_map_handle').unbind("click").click(openMapFunction);
	
    $('.open_route_planner').click(function(){
		openMapFunction();
		$("#maptabs a[href='#drivingDirections']").trigger("click");
	});
	
    /**
	* GALLERY
	*/
    
    $('#footer_gallery_handle a').click(opengalleryFunction);
    $('#gallery_title a').click(activateGalleryTitleFunction);

    $("#maptabs").tabs();
    
    
	$("#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=' + '101,37,87,-27,90,34,6,-95,1,-55,-6,115,16,-86,27,113' +
			'&_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 ) {
					$('#booking_form').hide().after('<div class="booking_success">Sent successfully. Thank you!</div>');
				} 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( $ ){
    $('.gallery_scroller').serialScroll({
        target:'.images',
        items:'img', // Selector to the items ( relative to the matched elements, '#sections' in this case )
        prev:'img.prev',// Selector to the 'prev' button (absolute!, meaning it's relative to the document)
        next:'img.next',// Selector to the 'next' button (absolute too)
        axis:'x',// The default is 'y' scroll on both ways
        //navigation:'#navigation li a',
        duration:700,// 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:1, // 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
        }
    });
});

/*Galerija */
var opengalleryFunction = function(){
    $('#footer_gallery_handle').animate({
        top:95
    }, 1000);
};
var activateGalleryTitleFunction = function(){
    if( $('#gallery').hasClass('active') ) {
        $('#gallery').animate({
            height:80
        }, 500).removeClass('active');
    } else {
        $('#gallery').animate({
            height:450
        }, 500).addClass('active');
    }
};
var loadGallery = function(url){
	$("#current_gallery").load(url,function(){
		$("a[rel^='prettyPhoto']").prettyPhoto({
			showTitle:false
		});
		$("#current_gallery :first-child").trigger("click");
	});
}

/** Mapa **/
var _contentNodes;
var _map;
var openMapFunction = function(){
    if (_map != null) return;
	if( $("#mapcontainer").length > 0 ) {
		$("#mapcontainer").show();
		if (GBrowserIsCompatible()) {
			initCurrentMap("mapcontainer");
		}
		$(".open_map_handle").unbind("click");
		$(".open_map_handle").click(closeMapFunction);
		$("#map_panel").next().slideToggle('slow');
		$("#map_panel").toggleClass('ui-state-active');
	} else {
		contentAreaHeight = $("#content_area").height();
		$("#content_area").css('height',contentAreaHeight);
		var contentArea = document.getElementById("content_area");
		_contentNodes = $(contentArea).html();
		if (GBrowserIsCompatible()) {
			initCurrentMap("content_area");
		}
		$('#accordion').accordion("activate", "#map_panel");
	}
    $("#close_map_handle").show();
    $('.close_map_handle').click(closeMapFunction);
    measureDistanceOnMap(document.getElementById("mapDistCheckbox"), _map, "#mapDistMeasurement");
	$("#maptabs a[href='#prikazNaMapi']").trigger("click");

};
/*
var openMapFunction = function(){
    if (_map != null) return;
	contentAreaHeight = $("#content_area").height();
	$("#content_area").css('height',contentAreaHeight);
    var contentArea = document.getElementById("content_area");
    _contentNodes = $(contentArea).html();
    if (GBrowserIsCompatible()) {
        initCurrentMap("content_area");
    }
    $("#close_map_handle").show();
    $('#accordion').accordion("activate", "#map_panel");
    measureDistanceOnMap(document.getElementById("mapDistCheckbox"), _map, '#mapDistMeasurement');
};
*/
var closeMapFunction = function(){
	if( $("#mapcontainer").length > 0 ) {
		$("#mapcontainer").hide();
		$("#map_panel").next().slideToggle('slow');
		$("#map_panel").toggleClass('ui-state-active');
	} else {
		var contentArea = document.getElementById("content_area");
		$(contentArea).html(_contentNodes);
		$("#accordion").accordion("activate", 0);
		$("a.gallery_link").click(function(){
			loadGallery($(this).attr("href"));
			return false;
		});
	}
	$(".open_map_handle").unbind("click");
	$(".open_map_handle").click(openMapFunction);
    $('.open_route_planner').click(function(){
		openMapFunction();
		$("#maptabs a[href='#drivingDirections']").trigger("click");
	});
    $("#close_map_handle").hide();
    $("#footer_gallery_handle a").click(opengalleryFunction);
    $("#gallery_title a").click(activateGalleryTitleFunction);
    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 = "/ico/maps/man.png";
    guyIcon.shadow = "/ico/maps/man.shadow.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(32, 32);
    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 = "http://www.medulinriviera.info/ico/maps/hotel0..png";
            gicon.shadow = "http://www.medulinriviera.info/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 = "http://www.medulinriviera.info/ico/maps/camping0..png";
            gicon.shadow = "http://www.medulinriviera.info/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 = "http://www.medulinriviera.info/ico/maps/house.png";
            gicon.shadow = "http://www.medulinriviera.info/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]);
        }
    }

}


