jQuery.fn.exists = function() {
	return jQuery(this).length > 0;
}

$(document).ready(function() {
	$("#qsearch").focus(function() {
		$(this).val('');
	});

    $("#nav ul li").hoverIntent({
        sensitivity: 3,  
        over: function(){
            $(this).children(".submenu").css({
                left: $(this).position().left + 8
            }).slideDown(350);
        },
        out: function(){
            $(this).children(".submenu").slideUp(350);
        }
    });

	/**********************************
	 ** begin google map functionality
	 **/
	if ($("#map").exists()) {//Checks to see that the page element exists and to prevent conflict with other maps
		
		$.ajax({
			type: "POST",
			url: _base_url + "/el/api/duty/oncoming",
			data: "days=2",
			dataType: "json",
			success: function(data){
				if (data.success) {
					if(data.data.length){
						var html='';
						$(data.data).each(function(i, duty){
							html += '<div class="map-location" data="{id: ' + duty.phone + ', point: {lat: ' + duty.latitude + ', lng: ' + duty.longitude + '}, category:\'health\'}">'+
								    '<a href="#" class="map-link">'+ duty.name + '</a><br/>'+
								    '<span class="map-link-address"> (από: '+ duty.start_at + ' έως: ' + duty.end_at + ')</span><br/>'+
								    '<span class="map-link-address">'+ duty.address + ', ' + duty.phone + '</span>'+
								    '<div class="info-box">'+
								      '<span>'+duty.name+'</span><br/>'+
								      '<span>'+duty.address+'</span><br/>'+
								      '<span>'+duty.phone+'</span>'+
								    '</div></div>';
							$('#map-side-bar').html(html);
		    				$('#map').jMapping({
								category_icon_options: {
							      'health': {primaryColor: '#65A93B', cornerColor: '#EBEBEB'},
							      'default': {primaryColor: '#65A93B'}
							    },
						    	map_config: function(map){
									map.addControl(new GMapTypeControl());
							      	map.addControl(new GLargeMapControl3D());
							      	map.addControl(new GScaleControl());
							      	map.enableScrollWheelZoom();
						    	}
							});
		    				$('#map').jMapping('update');
							$(".map-link").click(function(){
							 	$('html, body').animate({scrollTop:0}, 'slow');
                                return false;
							});
						});
					} else {
						$('#map').html('Δεν υπάρχουν διαθέσιμα φαρμακεία για το χάρτη.');
						$('#map-side-bar').html('Δεν υπάρχουν διαθέσιμες υπηρεσίες φαρμακείων.');
					}
				} else {
					$('#map').html('Δεν υπάρχουν διαθέσιμα φαρμακεία για το χάρτη.');
					$('#map-side-bar').html('Δεν υπάρχουν διαθέσιμες υπηρεσίες φαρμακείων.');
				}	
			}
		 });
	}
		
	/**
	 ** end google map functionality
	 ********************************/
	
	// We only want these styles applied when javascript is enabled
	$('div.content').css('display', 'block');
	if ($('#featured').exists()) {
		// Initially set opacity on thumbs and add
		// additional styling for hover effect on thumbs
		var onMouseOutOpacity = 0.3;
		$('#thumbs ul.thumbs li, div.navigation a.pageLink').opacityrollover({
			mouseOutOpacity:   onMouseOutOpacity,
			mouseOverOpacity:  1.0,
			fadeSpeed:         'slow',
			exemptionSelector: '.selected'
		});
		
		// Initialize Galleriffic Gallery
		var gallery = $('#thumbs').galleriffic({
			delay:                     12000,
			numThumbs:                 12,
			preloadAhead:              12,
			enableTopPager:            false,
			enableBottomPager:         false,
			imageContainerSel:         '#slideshow',
			controlsContainerSel:      '#controls',
			captionContainerSel:       '#caption',
			loadingContainerSel:       '#loading',
			renderSSControls:          true,
			renderNavControls:         true,
			playLinkText:              'Play',
			pauseLinkText:             'Pause',
			prevLinkText:              '&lsaquo; Previous',
			nextLinkText:              'Next &rsaquo;',
			nextPageLinkText:          'Next &rsaquo;',
			prevPageLinkText:          '&lsaquo; Prev',
			enableHistory:             true,
			autoStart:                 true,
			syncTransitions:           true,
			defaultTransitionDuration: 1000,
			onSlideChange:             function(prevIndex, nextIndex) {
				// 'this' refers to the gallery, which is an extension of $('#thumbs')
				this.find('ul.thumbs').children()
					.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
					.eq(nextIndex).fadeTo('fast', 1.0);
	
				// Update the photo index display
				this.$captionContainer.find('div.photo-index')
					.html((nextIndex+1) +' of '+ this.data.length);
			},
			onPageTransitionOut:       function(callback) {
				this.fadeTo('fast', 0.0, callback);
			},
			onPageTransitionIn:        function() {
				var prevPageLink = this.find('a.prev').css('visibility', 'hidden');
				var nextPageLink = this.find('a.next').css('visibility', 'hidden');
				
				// Show appropriate next / prev page links
				if (this.displayedPage > 0)
					prevPageLink.css('visibility', 'visible');
	
				var lastPage = this.getNumPages() - 1;
				if (this.displayedPage < lastPage)
					nextPageLink.css('visibility', 'visible');
	
				this.fadeTo('fast', 0.8);
			}
		});
	
		/**************** Event handlers for custom next / prev page links **********************/
	
		gallery.find('a.prev').click(function(e) {
			e.preventDefault();
			gallery.previousPage();
		});
	
		gallery.find('a.next').click(function(e) {
			e.preventDefault();
			gallery.nextPage();
		});
	
		/****************************************************************************************/
	
		/**** Functions to support integration of galleriffic with the jquery.history plugin ****/
	
		// PageLoad function
		// This function is called when:
		// 1. after calling $.historyInit();
		// 2. after calling $.historyLoad();
		// 3. after pushing "Go Back" button of a browser
		function pageload(hash) {
			// alert("pageload: " + hash);
			// hash doesn't contain the first # character.
			if(hash) {
				$.galleriffic.gotoImage(hash);
			} else {
				gallery.gotoIndex(0);
			}
		}
	
		// Initialize history plugin.
		// The callback is called at once by present location.hash. 
		$.historyInit(pageload);
	
		// set onlick event for buttons using the jQuery 1.3 live method
		$("a[rel='history']").live('click', function(e) {
			if (e.button != 0) return true;
	
			var hash = this.href;
			hash = hash.replace(/^.*#/, '');
	
			// moves to a new page. 
			// pageload is called at once. 
			// hash don't contain "#", "?"
			$.historyLoad(hash);
	
			return false;
		});
	}
	/****************************************************************************************/
	
	/************************************
     ** begin the lightbox functionality
     **/
    $("a.lightbox").lightBox({
        imageLoading: _base_url + '/scripts/jquery/lightbox/images/lightbox-ico-loading.gif',
        imageBtnPrev: _base_url + '/scripts/jquery/lightbox/images/lightbox-btn-prev.gif',
        imageBtnNext: _base_url + '/scripts/jquery/lightbox/images/lightbox-btn-next.gif',
        imageBtnClose: _base_url + '/scripts/jquery/lightbox/images/lightbox-btn-close.gif',
        imageBlank: _base_url + '/scripts/jquery/lightbox/images/lightbox-blank.gif',
        txtImage: 'Εικόνα',
        txtOf: 'από'
    });
    /**
     ** end the lightbox functionality
     **********************************/
	
	$('#back_to_top').click(function(){
		$('html, body').animate({scrollTop:0}, 'slow');
        return false;
	});
	
	$('#pharmacies_popup').popupWindow({ 
		centerBrowser: true,
		height: 600,
		menubar: 0,
		resizable: 0,
		scrollbars: 1, 
		width: 900
	});
	
});