// Initialize plugins
$(document).ready(function() {
	$("#video-container").css("height",0);
	
	/*$("#video-container a").click(function(){
		$("#video-holder").replaceWith('<div id="video-holder"></div>');
		$("#video-container").animate({height:"0px"},"slow",function(){
			$("#video-container").hide();
		});
		return false;
	});
	
	$("#audio-player a#youtube_video_link").click(function(){
		$("#jquery_jplayer").jPlayer("pause");
		$("#video-container").animate({height: "485px"},"slow",function(){
			var flashvars = {"config":"{'clip':'"+video_path+"','autoPlay':false}"};
			var params = {};
			var attributes = {};
			swfobject.embedSWF(assets+"media/flvPlayer/flowplayer-3.2.2.swf", "video-holder", "720", "485", "7.0.0","", flashvars, params, attributes);
		});
		return false;
	});*/
	$("#video-container a").click(function(){
		$("#video-holder iframe").attr('src', '');
		$("#video-container").animate({height:"0px"},"slow",function(){
			$("#video-container").hide();
		});
		return false;
	});
	
	$("#audio-player a#youtube_video_link").click(function(){
		$("#jquery_jplayer").jPlayer("pause");
		$("#video-container").animate({height: "485px"},"slow",function(){
			$("#video-holder iframe").attr('src', 'http://www.youtube.com/embed/tGT8ZzPT5Pk');
		});
		return false;
	});
        
    // Open external links in a new window.    
    $("a[href^='http:']").not($("a.same")).attr('target','_blank');
    
    // Hide and show text input value on email sign up.
    $(".default-value").each(function() {
        var defaultValue = this.value;
        $(this).focus(function() {
            if(this.value == defaultValue) {
                this.value = '';
            }
        });
        $(this).blur(function() {
            if(this.value == '') {
                this.value = defaultValue;
            }
        });
    });
    
    // Set default class on content
    $("#sections").addClass("closed");
    $("#sections").one("click", openContent);
    $("#sections .close").live("click", closeContent);
    closeContent();
    
    // Close email box.
    $("#email").one("click", openEmail);
    $("#email .close").live("click", function() {
        $("#email").removeClass("open");
        $("#email").stop().animate({
            "height": 32
        });
        $("#email").one("click", openEmail);
        $("#email .box").css("display", "none");
        $(this).remove();
    });    
        
    // Close reservations.
    $("#check-available").one("click", openEmail);
    $("#check-available .close").live("click", function(){
        $("#check-available").removeClass("open");
        $("#check-available").stop().animate({
            "height": 32
        });
        $("#check-available").one("click", openEmail);
        $("#check-available .box").css("display", "none");
        $(this).remove();
    })  
    
    // Spicy select.
    $("#arrival-dd, #arrival-m-y, #nights, #adults").spicyselect();
    
    // Slides
    $("#slides").cycle({
        prev:   "#prev",
        next:   "#next",
        timeout: 6000,
        speed: 1100
    });
	
    
    // Slide nav.
    $("#slide-container").live("mouseenter",function(){
    	if( $("#slides img").size() > 1 )
    		$("#prev, #next").show();
    });
    $("#slide-container").live("mouseleave",function(){
    	$("#prev, #next").hide();
    });    
    
    var uri = window.location.href.substr(window.location.href.lastIndexOf("/"));
	if ( uri != "/" && uri != "/es")
    	ajaxifyIt();
    
    // Slide sections in
	$("#sub-nav a, #content .section-one h3 a").live("click", function(){
		var url = this.href;
		
		$("#sub-nav li a.active").removeClass("active");
		$("#sub-nav li a[href$='"+url.substr(url.lastIndexOf("/"))+"']").addClass("active");
		
		if ($(this).attr("target")=="_blank")
		{
		    return true;
		}
		else 
		{
		window.location.href="#"+url.replace("http://"+window.location.host+"/","");
		
		$.ajax({
            cache: false,
            url: url,
            dataType: 'html',
            beforeSend: function(){
    			closeSection();
    		},
    		complete: function(data) {
    		    $("#sections").animate({
                    "width": 557
                }, function(){
					$("#slide-container").html($("#slide-container",data.responseText).html());
        	    	$("#slides").cycle({
    	                prev:   "#prev",
    	                next:   "#next",
    	                timeout: 8000,
    	                speed:   1100
    	            });

        	    	if(!$("#sections").hasClass("photo-gallery"))
        	    		$("#sections").append('<div class="close">');
                    
        	    	$(".section-one").html($(".section-one",data.responseText).html());
                    $(".section-two").html($(".section-two",data.responseText).html());

                	$(".section-two").show()
                	$(".content-area div", "#sections").css("display", "block");
                    iniScroll();
                    
                    if($("#map").size()>0)
                		iniMap();
                	
                	$("a.lightbox").prettyPhoto({
						theme: 'light_square'
					});
					$("#list-navigator").css("display", "none");
					$("#gallery").cycle({
						fx: 'scrollHorz',
					    timeout: 0,
					    speed: 'fast',
					    pager: $("#list-navigator .pager"),
						prev:   '#list-navigator .prev',
						next:   '#list-navigator .next',
						pagerAnchorBuilder: function(idx) {
						  return '&nbsp;<a href="#">' + (idx+1) + '</a>&nbsp;';
						}
					});
					if($("#list-navigator .pager a").size()>0)
						$("#list-navigator").fadeIn();
						
					$(".virtual-tour").click(function(e){
						var tour = this.href;
						e.preventDefault();
						$("#video-container").animate({height: "485px"},"slow",function(){
							$("#video-holder").html("<iframe src='"+tour+"' width='100%' height='485' scrolling='no' frameborder='0' marginheight='0' marginwidth='0' style='z-index:0'>");
						});

						return false;
					});
                });
    		}
        });
    	
		return false;
	}
    });
        
    $("#header h1 a, #content .section-two a:not(.view,.sitemap,.embeddedImageButton,.virtual-tour,[href^='http:']),#main-nav a.content, #top-nav a.content, #footer-links a, #privacy a, #audio-player a").live('click',function(event){
	if($(this).attr("id")!='youtube_video_link'){    	
    	var url = this.href;

		if(!$(this).hasClass('ajax'))
		{
			$(this).addClass('ajax');
			if(url.match("#")){
				var anchor = url.substr(url.lastIndexOf("#"));
				$pane = $(".scrollpane");
				$pane[0].scrollTo(anchor);
	    	}else{
	        	window.location.href="#"+url.replace("http://"+window.location.host+"/","");
	        	ajaxifyIt();
	    	}
		}

    	return false;
	}
    });
    
	// Audio player
	$("#jquery_jplayer").jPlayer({
		swfPath: assets+"media/",
		ready: function () {
			this.element.jPlayer("setFile", assets+"media/streamSound.mp3");//.jPlayer("play");
		},
		volume: 50,
		oggSupport: false
	}).jPlayer("onSoundComplete", function() {
		this.element.jPlayer("play");
	});
		
	$("#jplayer_play").click(function(){
	    $(".jp-controls").css("background-image", "url("+assets+"images/bg-audio-player.png)");
	});
	
	$("#jplayer_pause").click(function(){
	    $(".jp-controls").css("background-image", "url("+assets+"images/bg-audio-player-off.png)");
	});
	    
	// Slide out audio player.
	$(".jp-controls").hover(function() {
	    $("#audio-player").css("width", "127px")
	    $(this).stop().animate({
	        "right": 0
	    });
	},  function() {
	    $(this).stop().animate({
	        "right": -83
	    }, function(){
	        $("#audio-player").css("width", "38px")
	    });
	});
    

	// Reservations
	$('select[name="arrival-m-y"]').change( function() {
		var resdate = $(this).val().split('-');
		$('input[name="fmonth"]').val(resdate[0]);
		$('input[name="fyear"]').val(resdate[1]);
	});
    
});

//Initialize jScrollPane
function iniScroll(){
    $(".scrollpane").jScrollPane({scrollbarWidth: 5, dragMaxHeight: 80});
    $(".scrollpane").css({"top": "0"});
}

//Open content areas.
function openContent(event) {
	//Prevents clicking of Google Map and/or Anchor links from propagating
	//up to the $("#sections") click event handler, not really sure how else to stop it
	//so just checked to see if openContent is being passed an event, if it is
	//it's being called by a click handler that's been binded to an element
	if((event && $(event.currentTarget).is("div#sections.closed")) || !event){
		$(".content-area div", "#sections").css("display", "block");
		
		if(!$("#sections").hasClass("photo-gallery"))
			$("#sections").append('<div class="close">');
		
		$("#sections").removeClass("closed").addClass("open");
		
		$("#sections").animate({
			"height": 402
		}, 500, function(){
			iniScroll();
		});
		
		if($("#map").size()>0)
			iniMap();
		
		$("a.lightbox").prettyPhoto({
				theme: 'light_square'
		});
		$("#slides").cycle('pause');
		$("a.ajax").removeClass("ajax");
		$("#list-navigator").css("display", "none");
		$("#gallery").cycle({
			fx: 'scrollHorz',
		    timeout: 0,
		    speed: 'fast',
		    pager: $("#list-navigator .pager"),
			prev:   '#list-navigator .prev',
			next:   '#list-navigator .next',
			pagerAnchorBuilder: function(idx) {
			  return '&nbsp;<a href="#">' + (idx+1) + '</a>&nbsp;';
			}
		});
		if($("#list-navigator .pager a").size()>0)
			$("#list-navigator").fadeIn();
		$(".virtual-tour").click(function(e){
			var tour = this.href;
			e.preventDefault();
			$("#video-container").animate({height: "485px"},"slow",function(){
				$("#video-holder").html("<iframe src='"+tour+"' width='100%' height='485' scrolling='no' frameborder='0' marginheight='0' marginwidth='0' style='z-index:0'>");
			});
			
			return false;
		});
	}
}

//Close content areas.
function closeContent() {
    $(".content-area div").css("display", "none");
	$("#sections").removeClass("open").addClass("closed");
    $("#sections").stop().animate({
        "height": 32
    });
    $("#sections").one("click", openContent);
    $("#sections .close").remove(); 
    $("#slides").cycle('resume');
}

function closeSection() {
    if ( $("#sections").hasClass("open") ) {
        $(".section-two").hide()
        $("#sections .close").remove();
        $("#sections").stop().animate({
            "width": 164
        });
    }
}

//Open email
function openEmail() {
    $(this).stop().animate({
        "height": 135
    })
    $(this).addClass("open");
    $(".box", this).css("display", "block");
    $(this).append('<div class="close">');
}

//Open reservations
function openReservations() {
    $(this).stop().animate({
        "height": 135
    })
    $(this).addClass("open");
    $(".box", this).css("display", "block");
    $(this).append('<div class="close">');
}

function iniMap(){
	var map = new GMap2(document.getElementById("map"));
	map.setMapType(G_NORMAL_MAP);		
	map.addControl(new GLargeMapControl());
   	//map.addControl(new GMapTypeControl());
   	map.setCenter(new GLatLng(36.253405, -5.963827), 13);

	var text="<div><b>Hotel Address</b></div><div>Hotel V Vejer<br />CALLE ROSARIO 11-13, VEJER DE LA FRONTERA<br />11150 - SPAIN</div><br>";
	var text1="<div>Enter Starting Address:</div><form target='_blank' method='get' action='http://maps.google.com/maps'><div><input type='hidden' name='daddr' value='CALLE ROSARIO 11-13, VEJER DE LA FRONTERA, 11150 - SPAIN' /><div><input id='saddr' type='text' size='35' name='saddr' /></div><div><input type='submit' name='btnG' value='Get Directions' /></div>";
	
	var infoTabs = [
 		new GInfoWindowTab("Address", text),
 		new GInfoWindowTab("Directions", text1)
	];
    
	var marker = new GMarker(new GLatLng(36.253405, -5.963827));
	GEvent.addListener(marker, "click", function() {     		
		marker.openInfoWindowTabsHtml(infoTabs);
	});
	map.addOverlay(marker);
	marker.openInfoWindowTabsHtml(infoTabs);
}


function ajaxifyIt(){
	var url = window.location.href.substr(window.location.href.lastIndexOf("#")+1);
    	
	if(url.substr(0,4) != "http")
	{
		$("#main-nav li a.active").removeClass("active");
	}
	$("#main-nav li a[href$='"+url+"']").addClass("active").addClass("ajax");
    
	$.ajax({
	    cache: false,
		url: url,
		dataType: 'html',
		beforeSend: function(){
			$("#slides").cycle("destroy");
			$(".content-area div").css("display", "none");
			if($("#sections").hasClass("open")){
    			$("#sections").animate({
    				"height": 32
    			});
			}
		},
		complete: function(data) {
		    
		    // if open, slide down, load content, slide up
			if ( $("#sections").hasClass("open") ) {
			    $("#sections").animate({
        	        "height": 32
        	    }, "fast", function(){
        	    	$("#slide-container").html($("#slide-container",data.responseText).html());
        	    	
        	    	$("#slides").cycle({
    	                prev:   "#prev",
    	                next:   "#next",
    	                timeout: 8000,
    	                speed:   1100
    	            });
        	    		
    	    		$("#sections .close").remove();
        	    	$("#sections").removeClass("closed photo-gallery").addClass("open");
        	    	
        	    	$(".section-one").html($(".section-one",data.responseText).html());
        	    	$(".section-two").html($(".section-two",data.responseText).html());
        	    
        	    	// unless they want the front page then just slide down
        	    	if ( url == "http://"+window.location.host+"/" || url == "#" || url == "" || url == "es")  {
        	    	    $("#sections").removeClass("open photo-gallery").addClass("closed");
        	    	    $("#sections").one("click", openContent);
        	    	// or they want the photo page
        	    	} else if ( url == "http://"+window.location.host+"/" + "photo-gallery" || url.indexOf("photo-gallery") != -1 || url == "http://www.hotelv-vejer.es/galeria-de-fotos" || url.indexOf("galeria-de-fotos") != -1 ){
        	    		$("#sections .close").remove();
        	    	    $("#sections").addClass("photo-gallery");
        	    	    openContent();
						/*$("#gallery").cycle({
							fx: 'scrollHorz',
						    timeout: 0,
						    speed: 'fast',
						    pager: $("#list-navigator .pager"),
							prev:   '#list-navigator .prev',
							next:   '#list-navigator .next',
							pagerAnchorBuilder: function(idx) {
							  return '&nbsp;<a href="#">' + (idx+1) + '</a>&nbsp;';
							}
						});*/
        	    	// every other request
        	    	} else {
        	    		openContent();
        	    	}
        	    		
    	    	});
			
			// if we're on the front page AND it's closed and they hit photo gallery first
			} else if ( $("#sections").hasClass("closed")  && ( url == "http://"+window.location.host+"/" + "photo-gallery" || url.indexOf("photo-gallery") != -1 || url == "http://www.hotelv-vejer.es/galeria-de-fotos" || url.indexOf("galeria-de-fotos") != -1 ) ) {
				$("#slide-container").html($("#slide-container",data.responseText).html());
                $("#slides").cycle({ 
                	fx:     "scrollHorz",
                    prev:   "#prev",
                    next:   "#next",
                    timeout: 6000,
                    speed:   1100
                });       	    	

    	    	$(".section-one").html($(".section-one",data.responseText).html());
    	    	$(".section-two").html($(".section-two",data.responseText).html());

    	    	$("#sections .close").remove();
    	    	$("#sections").addClass("photo-gallery");        	    	
    	    	openContent();
				/*$("#gallery").cycle({
					fx: 'scrollHorz',
				    timeout: 0,
				    speed: 'fast',
				    pager: $("#list-navigator .pager"),
					prev:   '#list-navigator .prev',
					next:   '#list-navigator .next',
					pagerAnchorBuilder: function(idx) {
					  return '&nbsp;<a href="#">' + (idx+1) + '</a>&nbsp;';
					}
				});*/
			} else if ( url.indexOf("content/action") != -1 ) {
				openContent();
			} else {
				$("#slide-container").html($("#slide-container",data.responseText).html());
    	    	$("#slides").cycle({
	                prev:   "#prev",
	                next:   "#next",
	                timeout: 6000,
	                speed:   1100
	            });

				$("#sections .close").remove();
    	    	$("#sections").removeClass("closed photo-gallery").addClass("open");

    	    	$(".section-one").html($(".section-one",data.responseText).html());
    	    	$(".section-two").html($(".section-two",data.responseText).html());
    	    	
    	    	openContent();
        	}
	    }
	});
}



